repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/TransactionsActivityTest.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.test.ui;
import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.rule.GrantPermissionRule;
import android.support.test.runner.AndroidJUnit4;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.model.TransactionType;
import org.gnucash.android.receivers.TransactionRecorder;
import org.gnucash.android.test.ui.util.DisableAnimationsRule;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.gnucash.android.ui.transaction.TransactionFormFragment;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.isChecked;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
@RunWith(AndroidJUnit4.class)
public class TransactionsActivityTest {
private static final String TRANSACTION_AMOUNT = "9.99";
private static final String TRANSACTION_NAME = "Pizza";
private static final String TRANSACTIONS_ACCOUNT_UID = "transactions-account";
private static final String TRANSACTIONS_ACCOUNT_NAME = "Transactions Account";
private static final String TRANSFER_ACCOUNT_NAME = "Transfer account";
private static final String TRANSFER_ACCOUNT_UID = "transfer_account";
public static final String CURRENCY_CODE = "USD";
public static Commodity COMMODITY = Commodity.DEFAULT_COMMODITY;
private Transaction mTransaction;
private long mTransactionTimeMillis;
private static AccountsDbAdapter mAccountsDbAdapter;
private static TransactionsDbAdapter mTransactionsDbAdapter;
private static SplitsDbAdapter mSplitsDbAdapter;
private TransactionsActivity mTransactionsActivity;
@Rule public GrantPermissionRule animationPermissionsRule = GrantPermissionRule.grant(Manifest.permission.SET_ANIMATION_SCALE);
@ClassRule
public static DisableAnimationsRule disableAnimationsRule = new DisableAnimationsRule();
@Rule
public ActivityTestRule<TransactionsActivity> mActivityRule =
new ActivityTestRule<>(TransactionsActivity.class, true, false);
private Account mBaseAccount;
private Account mTransferAccount;
public TransactionsActivityTest() {
mBaseAccount = new Account(TRANSACTIONS_ACCOUNT_NAME, COMMODITY);
mBaseAccount.setUID(TRANSACTIONS_ACCOUNT_UID);
mTransferAccount = new Account(TRANSFER_ACCOUNT_NAME, COMMODITY);
mTransferAccount.setUID(TRANSFER_ACCOUNT_UID);
mTransactionTimeMillis = System.currentTimeMillis();
mTransaction = new Transaction(TRANSACTION_NAME);
mTransaction.setCommodity(COMMODITY);
mTransaction.setNote("What up?");
mTransaction.setTime(mTransactionTimeMillis);
Split split = new Split(new Money(TRANSACTION_AMOUNT, CURRENCY_CODE), TRANSACTIONS_ACCOUNT_UID);
split.setType(TransactionType.DEBIT);
mTransaction.addSplit(split);
mTransaction.addSplit(split.createPair(TRANSFER_ACCOUNT_UID));
mBaseAccount.addTransaction(mTransaction);
}
@BeforeClass
public static void prepareTestCase(){
Context context = GnuCashApplication.getAppContext();
AccountsActivityTest.preventFirstRunDialogs(context);
mSplitsDbAdapter = SplitsDbAdapter.getInstance();
mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
COMMODITY = CommoditiesDbAdapter.getInstance().getCommodity(CURRENCY_CODE);
// PreferenceActivity.getActiveBookSharedPreferences(context)
// .edit().putBoolean(context.getString(R.string.key_use_compact_list), false)
// .apply();
}
@Before
public void setUp() throws Exception {
mAccountsDbAdapter.deleteAllRecords();
mAccountsDbAdapter.addRecord(mBaseAccount, DatabaseAdapter.UpdateMethod.insert);
mAccountsDbAdapter.addRecord(mTransferAccount, DatabaseAdapter.UpdateMethod.insert);
mTransactionsDbAdapter.addRecord(mTransaction, DatabaseAdapter.UpdateMethod.insert);
assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(3); //including ROOT account
assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, TRANSACTIONS_ACCOUNT_UID);
mTransactionsActivity = mActivityRule.launchActivity(intent);
//refreshTransactionsList();
}
private void validateTransactionListDisplayed(){
onView(withId(R.id.transaction_recycler_view)).check(matches(isDisplayed()));
}
private int getTransactionCount(){
return mTransactionsDbAdapter.getAllTransactionsForAccount(TRANSACTIONS_ACCOUNT_UID).size();
}
private void validateTimeInput(long timeMillis){
String expectedValue = TransactionFormFragment.DATE_FORMATTER.format(new Date(timeMillis));
onView(withId(R.id.input_date)).check(matches(withText(expectedValue)));
expectedValue = TransactionFormFragment.TIME_FORMATTER.format(new Date(timeMillis));
onView(withId(R.id.input_time)).check(matches(withText(expectedValue)));
}
@Test
public void testAddTransactionShouldRequireAmount(){
validateTransactionListDisplayed();
int beforeCount = mTransactionsDbAdapter.getTransactionsCount(TRANSACTIONS_ACCOUNT_UID);
onView(withId(R.id.fab_create_transaction)).perform(click());
onView(withId(R.id.input_transaction_name))
.check(matches(isDisplayed()))
.perform(typeText("Lunch"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.menu_save))
.check(matches(isDisplayed()))
.perform(click());
onView(withText(R.string.title_add_transaction)).check(matches(isDisplayed()));
sleep(1000);
assertToastDisplayed(R.string.toast_transanction_amount_required);
int afterCount = mTransactionsDbAdapter.getTransactionsCount(TRANSACTIONS_ACCOUNT_UID);
assertThat(afterCount).isEqualTo(beforeCount);
}
/**
* Sleep the thread for a specified period
* @param millis Duration to sleep in milliseconds
*/
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Checks that a specific toast message is displayed
* @param toastString String that should be displayed
*/
private void assertToastDisplayed(int toastString) {
onView(withText(toastString))
.inRoot(withDecorView(not(mTransactionsActivity.getWindow().getDecorView())))
.check(matches(isDisplayed()));
}
private void validateEditTransactionFields(Transaction transaction){
onView(withId(R.id.input_transaction_name)).check(matches(withText(transaction.getDescription())));
Money balance = transaction.getBalance(TRANSACTIONS_ACCOUNT_UID);
NumberFormat formatter = NumberFormat.getInstance(Locale.getDefault());
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
onView(withId(R.id.input_transaction_amount)).check(matches(withText(formatter.format(balance.asDouble()))));
onView(withId(R.id.input_date)).check(matches(withText(TransactionFormFragment.DATE_FORMATTER.format(transaction.getTimeMillis()))));
onView(withId(R.id.input_time)).check(matches(withText(TransactionFormFragment.TIME_FORMATTER.format(transaction.getTimeMillis()))));
onView(withId(R.id.input_description)).check(matches(withText(transaction.getNote())));
validateTimeInput(transaction.getTimeMillis());
}
//TODO: Add test for only one account but with double-entry enabled
@Test
public void testAddTransaction(){
setDoubleEntryEnabled(true);
setDefaultTransactionType(TransactionType.DEBIT);
validateTransactionListDisplayed();
onView(withId(R.id.fab_create_transaction)).perform(click());
onView(withId(R.id.input_transaction_name)).perform(typeText("Lunch"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.input_transaction_amount)).perform(typeText("899"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.input_transaction_type))
.check(matches(allOf(isDisplayed(), withText(R.string.label_receive))))
.perform(click())
.check(matches(withText(R.string.label_spend)));
String expectedValue = NumberFormat.getInstance().format(-899);
onView(withId(R.id.input_transaction_amount)).check(matches(withText(expectedValue)));
int transactionsCount = getTransactionCount();
onView(withId(R.id.menu_save)).perform(click());
validateTransactionListDisplayed();
List<Transaction> transactions = mTransactionsDbAdapter.getAllTransactionsForAccount(TRANSACTIONS_ACCOUNT_UID);
assertThat(transactions).hasSize(2);
Transaction transaction = transactions.get(0);
assertThat(transaction.getSplits()).hasSize(2);
assertThat(getTransactionCount()).isEqualTo(transactionsCount + 1);
}
@Test
public void testAddMultiCurrencyTransaction(){
Commodity euro = Commodity.getInstance("EUR");
Account euroAccount = new Account("Euro Konto", euro);
mAccountsDbAdapter.addRecord(euroAccount);
int transactionCount = mTransactionsDbAdapter.getTransactionsCount(TRANSACTIONS_ACCOUNT_UID);
setDoubleEntryEnabled(true);
setDefaultTransactionType(TransactionType.DEBIT);
validateTransactionListDisplayed();
onView(withId(R.id.fab_create_transaction)).perform(click());
String transactionName = "Multicurrency lunch";
onView(withId(R.id.input_transaction_name)).perform(typeText(transactionName));
onView(withId(R.id.input_transaction_amount)).perform(typeText("10"));
Espresso.pressBack(); //close calculator keyboard
onView(withId(R.id.input_transfer_account_spinner)).perform(click());
onView(withText(euroAccount.getFullName()))
.check(matches(isDisplayed()))
.perform(click());
onView(withId(R.id.menu_save)).perform(click());
onView(withText(R.string.msg_provide_exchange_rate)).check(matches(isDisplayed()));
onView(withId(R.id.radio_converted_amount)).perform(click());
onView(withId(R.id.input_converted_amount)).perform(typeText("5"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.btn_save)).perform(click());
List<Transaction> allTransactions = mTransactionsDbAdapter.getAllTransactionsForAccount(TRANSACTIONS_ACCOUNT_UID);
assertThat(allTransactions).hasSize(transactionCount+1);
Transaction multiTrans = allTransactions.get(0);
assertThat(multiTrans.getSplits()).hasSize(2);
assertThat(multiTrans.getSplits()).extracting("mAccountUID")
.contains(TRANSACTIONS_ACCOUNT_UID)
.contains(euroAccount.getUID());
Split euroSplit = multiTrans.getSplits(euroAccount.getUID()).get(0);
Money expectedQty = new Money("5", euro.getCurrencyCode());
Money expectedValue = new Money(BigDecimal.TEN, COMMODITY);
assertThat(euroSplit.getQuantity()).isEqualTo(expectedQty);
assertThat(euroSplit.getValue()).isEqualTo(expectedValue);
Split usdSplit = multiTrans.getSplits(TRANSACTIONS_ACCOUNT_UID).get(0);
assertThat(usdSplit.getQuantity()).isEqualTo(expectedValue);
assertThat(usdSplit.getValue()).isEqualTo(expectedValue);
}
@Test
public void testEditTransaction(){
validateTransactionListDisplayed();
onView(withId(R.id.edit_transaction)).perform(click());
validateEditTransactionFields(mTransaction);
String trnName = "Pasta";
onView(withId(R.id.input_transaction_name)).perform(clearText(), typeText(trnName));
onView(withId(R.id.menu_save)).perform(click());
Transaction editedTransaction = mTransactionsDbAdapter.getRecord(mTransaction.getUID());
assertThat(editedTransaction.getDescription()).isEqualTo(trnName);
assertThat(editedTransaction.getSplits()).hasSize(2);
Split split = mTransaction.getSplits(TRANSACTIONS_ACCOUNT_UID).get(0);
Split editedSplit = editedTransaction.getSplits(TRANSACTIONS_ACCOUNT_UID).get(0);
assertThat(split.isEquivalentTo(editedSplit)).isTrue();
split = mTransaction.getSplits(TRANSFER_ACCOUNT_UID).get(0);
editedSplit = editedTransaction.getSplits(TRANSFER_ACCOUNT_UID).get(0);
assertThat(split.isEquivalentTo(editedSplit)).isTrue();
}
/**
* Tests that transactions splits are automatically balanced and an imbalance account will be created
* This test case assumes that single entry is used
*/
//TODO: move this to the unit tests
public void testAutoBalanceTransactions(){
setDoubleEntryEnabled(false);
mTransactionsDbAdapter.deleteAllRecords();
assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(0);
String imbalanceAcctUID = mAccountsDbAdapter.getImbalanceAccountUID(Commodity.getInstance(CURRENCY_CODE));
assertThat(imbalanceAcctUID).isNull();
validateTransactionListDisplayed();
onView(withId(R.id.fab_create_transaction)).perform(click());
onView(withId(R.id.fragment_transaction_form)).check(matches(isDisplayed()));
onView(withId(R.id.input_transaction_name)).perform(typeText("Autobalance"));
onView(withId(R.id.input_transaction_amount)).perform(typeText("499"));
//no double entry so no split editor
//TODO: check that the split drawable is not displayed
onView(withId(R.id.menu_save)).perform(click());
assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1);
Transaction transaction = mTransactionsDbAdapter.getAllTransactions().get(0);
assertThat(transaction.getSplits()).hasSize(2);
imbalanceAcctUID = mAccountsDbAdapter.getImbalanceAccountUID(Commodity.getInstance(CURRENCY_CODE));
assertThat(imbalanceAcctUID).isNotNull();
assertThat(imbalanceAcctUID).isNotEmpty();
assertThat(mAccountsDbAdapter.isHiddenAccount(imbalanceAcctUID)).isTrue(); //imbalance account should be hidden in single entry mode
assertThat(transaction.getSplits()).extracting("mAccountUID").contains(imbalanceAcctUID);
}
/**
* Tests input of transaction splits using the split editor.
* Also validates that the imbalance from the split editor will be automatically added as a split
* //FIXME: find a more reliable way to test opening of the split editor
*/
@Test
public void testSplitEditor(){
setDoubleEntryEnabled(true);
setDefaultTransactionType(TransactionType.DEBIT);
mTransactionsDbAdapter.deleteAllRecords();
//when we start there should be no imbalance account in the system
String imbalanceAcctUID = mAccountsDbAdapter.getImbalanceAccountUID(Commodity.getInstance(CURRENCY_CODE));
assertThat(imbalanceAcctUID).isNull();
validateTransactionListDisplayed();
onView(withId(R.id.fab_create_transaction)).perform(click());
onView(withId(R.id.input_transaction_name)).perform(typeText("Autobalance"));
onView(withId(R.id.input_transaction_amount)).perform(typeText("499"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.btn_split_editor)).perform(click());
onView(withId(R.id.split_list_layout)).check(matches(allOf(isDisplayed(), hasDescendant(withId(R.id.input_split_amount)))));
onView(allOf(withId(R.id.input_split_amount), withText("-499"))).perform(clearText());
onView(allOf(withId(R.id.input_split_amount), withText(""))).perform(typeText("400"));
onView(withId(R.id.menu_save)).perform(click());
//after we use split editor, we should not be able to toggle the transaction type
onView(withId(R.id.input_transaction_type)).check(matches(not(isDisplayed())));
onView(withId(R.id.menu_save)).perform(click());
List<Transaction> transactions = mTransactionsDbAdapter.getAllTransactions();
assertThat(transactions).hasSize(1);
Transaction transaction = transactions.get(0);
assertThat(transaction.getSplits()).hasSize(3); //auto-balanced
imbalanceAcctUID = mAccountsDbAdapter.getImbalanceAccountUID(Commodity.getInstance(CURRENCY_CODE));
assertThat(imbalanceAcctUID).isNotNull();
assertThat(imbalanceAcctUID).isNotEmpty();
assertThat(mAccountsDbAdapter.isHiddenAccount(imbalanceAcctUID)).isFalse();
//at least one split will belong to the imbalance account
assertThat(transaction.getSplits()).extracting("mAccountUID").contains(imbalanceAcctUID);
List<Split> imbalanceSplits = mSplitsDbAdapter.getSplitsForTransactionInAccount(transaction.getUID(), imbalanceAcctUID);
assertThat(imbalanceSplits).hasSize(1);
Split split = imbalanceSplits.get(0);
assertThat(split.getValue().asBigDecimal()).isEqualTo(new BigDecimal("99.00"));
assertThat(split.getType()).isEqualTo(TransactionType.CREDIT);
}
private void setDoubleEntryEnabled(boolean enabled){
SharedPreferences prefs = PreferenceActivity.getActiveBookSharedPreferences();
Editor editor = prefs.edit();
editor.putBoolean(mTransactionsActivity.getString(R.string.key_use_double_entry), enabled);
editor.apply();
}
@Test
public void testDefaultTransactionType(){
setDefaultTransactionType(TransactionType.CREDIT);
onView(withId(R.id.fab_create_transaction)).perform(click());
onView(withId(R.id.input_transaction_type)).check(matches(allOf(isChecked(), withText(R.string.label_spend))));
}
private void setDefaultTransactionType(TransactionType type) {
SharedPreferences prefs = PreferenceActivity.getActiveBookSharedPreferences();
Editor editor = prefs.edit();
editor.putString(mTransactionsActivity.getString(R.string.key_default_transaction_type), type.name());
editor.commit();
}
//FIXME: Improve on this test
public void childAccountsShouldUseParentTransferAccountSetting(){
Account transferAccount = new Account("New Transfer Acct");
mAccountsDbAdapter.addRecord(transferAccount, DatabaseAdapter.UpdateMethod.insert);
mAccountsDbAdapter.addRecord(new Account("Higher account"), DatabaseAdapter.UpdateMethod.insert);
Account childAccount = new Account("Child Account");
childAccount.setParentUID(TRANSACTIONS_ACCOUNT_UID);
mAccountsDbAdapter.addRecord(childAccount, DatabaseAdapter.UpdateMethod.insert);
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseSchema.AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID, transferAccount.getUID());
mAccountsDbAdapter.updateRecord(TRANSACTIONS_ACCOUNT_UID, contentValues);
Intent intent = new Intent(mTransactionsActivity, TransactionsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, childAccount.getUID());
mTransactionsActivity.startActivity(intent);
onView(withId(R.id.input_transaction_amount)).perform(typeText("1299"));
clickOnView(R.id.menu_save);
//if our transfer account has a transaction then the right transfer account was used
List<Transaction> transactions = mTransactionsDbAdapter.getAllTransactionsForAccount(transferAccount.getUID());
assertThat(transactions).hasSize(1);
}
@Test
public void testToggleTransactionType(){
validateTransactionListDisplayed();
onView(withId(R.id.edit_transaction)).perform(click());
validateEditTransactionFields(mTransaction);
onView(withId(R.id.input_transaction_type)).check(matches(
allOf(isDisplayed(), withText(R.string.label_receive))
)).perform(click()).check(matches(withText(R.string.label_spend)));
onView(withId(R.id.input_transaction_amount)).check(matches(withText("-9.99")));
onView(withId(R.id.menu_save)).perform(click());
List<Transaction> transactions = mTransactionsDbAdapter.getAllTransactionsForAccount(TRANSACTIONS_ACCOUNT_UID);
assertThat(transactions).hasSize(1);
Transaction trx = transactions.get(0);
assertThat(trx.getSplits()).hasSize(2); //auto-balancing of splits
assertThat(trx.getBalance(TRANSACTIONS_ACCOUNT_UID).isNegative()).isTrue();
}
@Test
public void testOpenTransactionEditShouldNotModifyTransaction(){
validateTransactionListDisplayed();
onView(withId(R.id.edit_transaction)).perform(click());
validateTimeInput(mTransactionTimeMillis);
clickOnView(R.id.menu_save);
List<Transaction> transactions = mTransactionsDbAdapter.getAllTransactionsForAccount(TRANSACTIONS_ACCOUNT_UID);
assertThat(transactions).hasSize(1);
Transaction transaction = transactions.get(0);
assertThat(TRANSACTION_NAME).isEqualTo(transaction.getDescription());
Date expectedDate = new Date(mTransactionTimeMillis);
Date trxDate = new Date(transaction.getTimeMillis());
assertThat(TransactionFormFragment.DATE_FORMATTER.format(expectedDate))
.isEqualTo(TransactionFormFragment.DATE_FORMATTER.format(trxDate));
assertThat(TransactionFormFragment.TIME_FORMATTER.format(expectedDate))
.isEqualTo(TransactionFormFragment.TIME_FORMATTER.format(trxDate));
Split baseSplit = transaction.getSplits(TRANSACTIONS_ACCOUNT_UID).get(0);
Money expectedAmount = new Money(TRANSACTION_AMOUNT, CURRENCY_CODE);
assertThat(baseSplit.getValue()).isEqualTo(expectedAmount);
assertThat(baseSplit.getQuantity()).isEqualTo(expectedAmount);
assertThat(baseSplit.getType()).isEqualTo(TransactionType.DEBIT);
Split transferSplit = transaction.getSplits(TRANSFER_ACCOUNT_UID).get(0);
assertThat(transferSplit.getValue()).isEqualTo(expectedAmount);
assertThat(transferSplit.getQuantity()).isEqualTo(expectedAmount);
assertThat(transferSplit.getType()).isEqualTo(TransactionType.CREDIT);
}
@Test
public void testDeleteTransaction(){
onView(withId(R.id.options_menu)).perform(click());
onView(withText(R.string.menu_delete)).perform(click());
assertThat(0).isEqualTo(mTransactionsDbAdapter.getTransactionsCount(TRANSACTIONS_ACCOUNT_UID));
}
@Test
public void testMoveTransaction(){
Account account = new Account("Move account");
account.setCommodity(Commodity.getInstance(CURRENCY_CODE));
mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
assertThat(mTransactionsDbAdapter.getAllTransactionsForAccount(account.getUID())).hasSize(0);
onView(withId(R.id.options_menu)).perform(click());
onView(withText(R.string.menu_move_transaction)).perform(click());
onView(withId(R.id.btn_save)).perform(click());
assertThat(mTransactionsDbAdapter.getAllTransactionsForAccount(TRANSACTIONS_ACCOUNT_UID)).hasSize(0);
assertThat(mTransactionsDbAdapter.getAllTransactionsForAccount(account.getUID())).hasSize(1);
}
/**
* This test edits a transaction from within an account and removes the split belonging to that account.
* The account should then have a balance of 0 and the transaction has "moved" to another account
*/
@Test
public void editingSplit_shouldNotSetAmountToZero(){
setDoubleEntryEnabled(true);
setDefaultTransactionType(TransactionType.DEBIT);
mTransactionsDbAdapter.deleteAllRecords();
Account account = new Account("Z Account", Commodity.getInstance(CURRENCY_CODE));
mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
//create new transaction "Transaction Acct" --> "Transfer Account"
onView(withId(R.id.fab_create_transaction)).perform(click());
onView(withId(R.id.input_transaction_name)).perform(typeText("Test Split"));
onView(withId(R.id.input_transaction_amount)).perform(typeText("1024"));
onView(withId(R.id.menu_save)).perform(click());
assertThat(mTransactionsDbAdapter.getTransactionsCount(TRANSACTIONS_ACCOUNT_UID)).isEqualTo(1);
sleep(500);
onView(withText("Test Split")).perform(click());
onView(withId(R.id.fab_edit_transaction)).perform(click());
onView(withId(R.id.btn_split_editor)).perform(click());
onView(withText(TRANSACTIONS_ACCOUNT_NAME)).perform(click());
onView(withText(account.getFullName())).perform(click());
onView(withId(R.id.menu_save)).perform(click());
onView(withId(R.id.menu_save)).perform(click());
assertThat(mTransactionsDbAdapter.getTransactionsCount(TRANSACTIONS_ACCOUNT_UID)).isZero();
assertThat(mAccountsDbAdapter.getAccountBalance(account.getUID()))
.isEqualTo(new Money("1024", CURRENCY_CODE));
}
@Test
public void testDuplicateTransaction(){
assertThat(mTransactionsDbAdapter.getAllTransactionsForAccount(TRANSACTIONS_ACCOUNT_UID)).hasSize(1);
onView(withId(R.id.options_menu)).perform(click());
onView(withText(R.string.menu_duplicate_transaction)).perform(click());
List<Transaction> dummyAccountTrns = mTransactionsDbAdapter.getAllTransactionsForAccount(TRANSACTIONS_ACCOUNT_UID);
assertThat(dummyAccountTrns).hasSize(2);
assertThat(dummyAccountTrns.get(0).getDescription()).isEqualTo(dummyAccountTrns.get(1).getDescription());
assertThat(dummyAccountTrns.get(0).getTimeMillis()).isNotEqualTo(dummyAccountTrns.get(1).getTimeMillis());
}
//TODO: add normal transaction recording
@Test
public void testLegacyIntentTransactionRecording(){
int beforeCount = mTransactionsDbAdapter.getTransactionsCount(TRANSACTIONS_ACCOUNT_UID);
Intent transactionIntent = new Intent(Intent.ACTION_INSERT);
transactionIntent.setType(Transaction.MIME_TYPE);
transactionIntent.putExtra(Intent.EXTRA_TITLE, "Power intents");
transactionIntent.putExtra(Intent.EXTRA_TEXT, "Intents for sale");
transactionIntent.putExtra(Transaction.EXTRA_AMOUNT, new BigDecimal(4.99));
transactionIntent.putExtra(Transaction.EXTRA_ACCOUNT_UID, TRANSACTIONS_ACCOUNT_UID);
transactionIntent.putExtra(Transaction.EXTRA_TRANSACTION_TYPE, TransactionType.DEBIT.name());
transactionIntent.putExtra(Account.EXTRA_CURRENCY_CODE, "USD");
new TransactionRecorder().onReceive(mTransactionsActivity, transactionIntent);
int afterCount = mTransactionsDbAdapter.getTransactionsCount(TRANSACTIONS_ACCOUNT_UID);
assertThat(beforeCount + 1).isEqualTo(afterCount);
List<Transaction> transactions = mTransactionsDbAdapter.getAllTransactionsForAccount(TRANSACTIONS_ACCOUNT_UID);
for (Transaction transaction : transactions) {
if (transaction.getDescription().equals("Power intents")){
assertThat("Intents for sale").isEqualTo(transaction.getNote());
assertThat(4.99).isEqualTo(transaction.getBalance(TRANSACTIONS_ACCOUNT_UID).asDouble());
}
}
}
/**
* Opening a transactions and then hitting save button without changing anything should have no side-effects
* This is similar to the test @{@link #testOpenTransactionEditShouldNotModifyTransaction()}
* with the difference that this test checks multi-currency transactions
*/
@Test
public void openingAndSavingMultiCurrencyTransaction_shouldNotModifyTheSplits(){
Commodity bgnCommodity = CommoditiesDbAdapter.getInstance().getCommodity("BGN");
Account account = new Account("Zen Account", bgnCommodity);
mAccountsDbAdapter.addRecord(account);
onView(withId(R.id.fab_create_transaction)).perform(click());
String trnDescription = "Multi-currency trn";
onView(withId(R.id.input_transaction_name)).perform(typeText(trnDescription));
onView(withId(R.id.input_transaction_amount)).perform(typeText("10"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.input_transfer_account_spinner)).perform(click());
onView(withText(account.getFullName())).perform(click());
//at this point, the transfer funds dialog should be shown
onView(withText(R.string.msg_provide_exchange_rate)).check(matches(isDisplayed()));
onView(withId(R.id.radio_converted_amount)).perform(click());
onView(withId(R.id.input_converted_amount)).perform(typeText("5"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.btn_save)).perform(click()); //close currency exchange dialog
onView(withId(R.id.menu_save)).perform(click()); //save transaction
List<Transaction> transactions = mTransactionsDbAdapter.getAllTransactionsForAccount(account.getUID());
assertThat(transactions).hasSize(1);
Transaction transaction = transactions.get(0);
assertThat(transaction.getSplits()).hasSize(2);
assertThat(transaction.getSplits()).extracting("mAccountUID")
.contains(account.getUID()).contains(mBaseAccount.getUID());
onView(allOf(withParent(hasDescendant(withText(trnDescription))),
withId(R.id.edit_transaction))).perform(click());
//do nothing to the transaction, just save it
onView(withId(R.id.menu_save)).perform(click());
transaction = mTransactionsDbAdapter.getRecord(transaction.getUID());
Split baseSplit = transaction.getSplits(mBaseAccount.getUID()).get(0);
Money expectedValueAmount = new Money(BigDecimal.TEN, COMMODITY);
assertThat(baseSplit.getValue()).isEqualTo(expectedValueAmount);
assertThat(baseSplit.getQuantity()).isEqualTo(expectedValueAmount);
Split transferSplit = transaction.getSplits(account.getUID()).get(0);
Money convertedQuantity = new Money("5", "BGN");
assertThat(transferSplit.getValue()).isEqualTo(expectedValueAmount);
assertThat(transferSplit.getQuantity()).isEqualTo(convertedQuantity);
}
/**
* If a multi-currency transaction is edited so that it is no longer multicurrency, then the
* values for split and quantity should be adjusted accordingly so that they are consistent
* <p>
* Basically the test works like this:
* <ol>
* <li>Create a multicurrency transaction</li>
* <li>Change the transfer account so that both splits are of the same currency</li>
* <li>We now expect both the values and quantities of the splits to be the same</li>
* </ol>
* </p>
*/
@Test
public void testEditingTransferAccountOfMultiCurrencyTransaction(){
mTransactionsDbAdapter.deleteAllRecords(); //clean slate
Commodity euroCommodity = CommoditiesDbAdapter.getInstance().getCommodity("EUR");
Account euroAccount = new Account("Euro Account", euroCommodity);
mAccountsDbAdapter.addRecord(euroAccount);
Money expectedValue = new Money(BigDecimal.TEN, COMMODITY);
Money expectedQty = new Money("5", "EUR");
String trnDescription = "Multicurrency Test Trn";
Transaction multiTransaction = new Transaction(trnDescription);
Split split1 = new Split(expectedValue, TRANSACTIONS_ACCOUNT_UID);
split1.setType(TransactionType.DEBIT);
Split split2 = new Split(expectedValue, expectedQty, euroAccount.getUID());
split2.setType(TransactionType.CREDIT);
multiTransaction.addSplit(split1);
multiTransaction.addSplit(split2);
multiTransaction.setCommodity(COMMODITY);
mTransactionsDbAdapter.addRecord(multiTransaction);
Transaction savedTransaction = mTransactionsDbAdapter.getRecord(multiTransaction.getUID());
assertThat(savedTransaction.getSplits()).extracting("mQuantity").contains(expectedQty);
assertThat(savedTransaction.getSplits()).extracting("mValue").contains(expectedValue);
refreshTransactionsList();
onView(withText(trnDescription)).check(matches(isDisplayed())); //transaction was added
onView(allOf(withParent(hasDescendant(withText(trnDescription))),
withId(R.id.edit_transaction))).perform(click());
//now change the transfer account to be no longer multi-currency
onView(withId(R.id.input_transfer_account_spinner)).perform(click());
onView(withText(mTransferAccount.getFullName())).perform(click());
onView(withId(R.id.menu_save)).perform(click());
//no splits should be in the euro account anymore
List<Transaction> euroTransxns = mTransactionsDbAdapter.getAllTransactionsForAccount(euroAccount.getUID());
assertThat(euroTransxns).hasSize(0);
List<Transaction> transferAcctTrns = mTransactionsDbAdapter.getAllTransactionsForAccount(mTransferAccount.getUID());
assertThat(transferAcctTrns).hasSize(1);
Transaction singleCurrencyTrn = transferAcctTrns.get(0);
assertThat(singleCurrencyTrn.getUID()).isEqualTo(multiTransaction.getUID()); //should be the same one, just different splits
//the crux of the test. All splits should now have value and quantity of USD $10
List<Split> allSplits = singleCurrencyTrn.getSplits();
assertThat(allSplits).extracting("mAccountUID")
.contains(mTransferAccount.getUID())
.doesNotContain(euroAccount.getUID());
assertThat(allSplits).extracting("mValue").contains(expectedValue).doesNotContain(expectedQty);
assertThat(allSplits).extracting("mQuantity").contains(expectedValue).doesNotContain(expectedQty);
}
/**
* In this test we check that editing a transaction and switching the transfer account to one
* which is of a different currency and then back again should not have side-effects.
* The split value and quantity should remain consistent.
*/
@Test
public void editingTransferAccount_shouldKeepSplitAmountsConsistent() {
mTransactionsDbAdapter.deleteAllRecords(); //clean slate
Commodity euroCommodity = CommoditiesDbAdapter.getInstance().getCommodity("EUR");
Account euroAccount = new Account("Euro Account", euroCommodity);
mAccountsDbAdapter.addRecord(euroAccount);
Money expectedValue = new Money(BigDecimal.TEN, COMMODITY);
Money expectedQty = new Money("5", "EUR");
String trnDescription = "Multicurrency Test Trn";
Transaction multiTransaction = new Transaction(trnDescription);
Split split1 = new Split(expectedValue, TRANSACTIONS_ACCOUNT_UID);
split1.setType(TransactionType.CREDIT);
Split split2 = new Split(expectedValue, expectedQty, euroAccount.getUID());
split2.setType(TransactionType.DEBIT);
multiTransaction.addSplit(split1);
multiTransaction.addSplit(split2);
multiTransaction.setCommodity(COMMODITY);
mTransactionsDbAdapter.addRecord(multiTransaction);
Transaction savedTransaction = mTransactionsDbAdapter.getRecord(multiTransaction.getUID());
assertThat(savedTransaction.getSplits()).extracting("mQuantity").contains(expectedQty);
assertThat(savedTransaction.getSplits()).extracting("mValue").contains(expectedValue);
assertThat(savedTransaction.getSplits(TRANSACTIONS_ACCOUNT_UID).get(0)
.isEquivalentTo(multiTransaction.getSplits(TRANSACTIONS_ACCOUNT_UID).get(0)))
.isTrue();
refreshTransactionsList();
//open transaction for editing
onView(withText(trnDescription)).check(matches(isDisplayed())); //transaction was added
onView(allOf(withParent(hasDescendant(withText(trnDescription))),
withId(R.id.edit_transaction))).perform(click());
onView(withId(R.id.input_transfer_account_spinner)).perform(click());
onView(withText(TRANSFER_ACCOUNT_NAME)).perform(click());
onView(withId(R.id.input_transfer_account_spinner)).perform(click());
onView(withText(euroAccount.getFullName())).perform(click());
onView(withId(R.id.input_converted_amount)).perform(typeText("5"));
Espresso.closeSoftKeyboard();
onView(withId(R.id.btn_save)).perform(click());
onView(withId(R.id.input_transfer_account_spinner)).perform(click());
onView(withText(TRANSFER_ACCOUNT_NAME)).perform(click());
onView(withId(R.id.menu_save)).perform(click());
Transaction editedTransaction = mTransactionsDbAdapter.getRecord(multiTransaction.getUID());
assertThat(editedTransaction.getSplits(TRANSACTIONS_ACCOUNT_UID).get(0)
.isEquivalentTo(savedTransaction.getSplits(TRANSACTIONS_ACCOUNT_UID).get(0)))
.isTrue();
Money firstAcctBalance = mAccountsDbAdapter.getAccountBalance(TRANSACTIONS_ACCOUNT_UID);
assertThat(firstAcctBalance).isEqualTo(editedTransaction.getBalance(TRANSACTIONS_ACCOUNT_UID));
Money transferBalance = mAccountsDbAdapter.getAccountBalance(TRANSFER_ACCOUNT_UID);
assertThat(transferBalance).isEqualTo(editedTransaction.getBalance(TRANSFER_ACCOUNT_UID));
assertThat(editedTransaction.getBalance(TRANSFER_ACCOUNT_UID)).isEqualTo(expectedValue);
Split transferAcctSplit = editedTransaction.getSplits(TRANSFER_ACCOUNT_UID).get(0);
assertThat(transferAcctSplit.getQuantity()).isEqualTo(expectedValue);
assertThat(transferAcctSplit.getValue()).isEqualTo(expectedValue);
}
/**
* Simple wrapper for clicking on views with espresso
* @param viewId View resource ID
*/
private void clickOnView(int viewId){
onView(withId(viewId)).perform(click());
}
/**
* Refresh the account list fragment
*/
private void refreshTransactionsList(){
try {
mActivityRule.runOnUiThread(new Runnable() {
@Override
public void run() {
mTransactionsActivity.refresh();
}
});
} catch (Throwable throwable) {
System.err.println("Failed to refresh fragment");
}
}
@After
public void tearDown() throws Exception {
if (mTransactionsActivity != null)
mTransactionsActivity.finish();
}
}
| 38,432 | 41.561462 | 135 |
java
|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/util/DisableAnimationsRule.java
|
package org.gnucash.android.test.ui.util;
import android.os.IBinder;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Created by Ngewi on 19.04.2016.
* Credit: https://product.reverb.com/2015/06/06/disabling-animations-in-espresso-for-android-testing/
*/
public class DisableAnimationsRule implements TestRule {
private Method mSetAnimationScalesMethod;
private Method mGetAnimationScalesMethod;
private Object mWindowManagerObject;
public DisableAnimationsRule() {
try {
Class<?> windowManagerStubClazz = Class.forName("android.view.IWindowManager$Stub");
Method asInterface = windowManagerStubClazz.getDeclaredMethod("asInterface", IBinder.class);
Class<?> serviceManagerClazz = Class.forName("android.os.ServiceManager");
Method getService = serviceManagerClazz.getDeclaredMethod("getService", String.class);
Class<?> windowManagerClazz = Class.forName("android.view.IWindowManager");
mSetAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("setAnimationScales", float[].class);
mGetAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("getAnimationScales");
IBinder windowManagerBinder = (IBinder) getService.invoke(null, "window");
mWindowManagerObject = asInterface.invoke(null, windowManagerBinder);
}
catch (Exception e) {
throw new RuntimeException("Failed to access animation methods", e);
}
}
@Override
public Statement apply(final Statement statement, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
setAnimationScaleFactors(0.0f);
try { statement.evaluate(); }
finally { setAnimationScaleFactors(1.0f); }
}
};
}
private void setAnimationScaleFactors(float scaleFactor) throws Exception {
float[] scaleFactors = (float[]) mGetAnimationScalesMethod.invoke(mWindowManagerObject);
Arrays.fill(scaleFactors, scaleFactor);
mSetAnimationScalesMethod.invoke(mWindowManagerObject, scaleFactors);
}
}
| 2,333 | 38.559322 | 114 |
java
|
gnucash-android
|
gnucash-android-master/app/src/androidTest/java/org/gnucash/android/test/ui/util/GnucashAndroidTestRunner.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.test.ui.util;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.multidex.MultiDex;
import android.support.test.runner.AndroidJUnitRunner;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Custom test runner
*/
public class GnucashAndroidTestRunner extends AndroidJUnitRunner{
private static final String TAG = "GncAndroidTestRunner";
private static final String ANIMATION_PERMISSION = "android.permission.SET_ANIMATION_SCALE";
private static final float DISABLED = 0.0f;
private static final float DEFAULT = 1.0f;
@Override
public void onCreate(Bundle args) {
super.onCreate(args);
// as time goes on we may actually need to process our arguments.
disableAnimation();
}
@Override
public void onDestroy() {
enableAnimation();
super.onDestroy();
}
private void disableAnimation() {
int permStatus = getContext().checkCallingOrSelfPermission(ANIMATION_PERMISSION);
if (permStatus == PackageManager.PERMISSION_GRANTED) {
if (reflectivelyDisableAnimation(DISABLED)) {
Log.i(TAG, "All animations disabled.");
} else {
Log.i(TAG, "Could not disable animations.");
}
} else {
Log.i(TAG, "Cannot disable animations due to lack of permission.");
}
}
private void enableAnimation(){
int permStatus = getContext().checkCallingOrSelfPermission(ANIMATION_PERMISSION);
if (permStatus == PackageManager.PERMISSION_GRANTED) {
if (reflectivelyDisableAnimation(DEFAULT)) {
Log.i(TAG, "All animations enabled.");
} else {
Log.i(TAG, "Could not enable animations.");
}
} else {
Log.i(TAG, "Cannot disable animations due to lack of permission.");
}
}
private boolean reflectivelyDisableAnimation(float animationScale) {
try {
Class<?> windowManagerStubClazz = Class.forName("android.view.IWindowManager$Stub");
Method asInterface = windowManagerStubClazz.getDeclaredMethod("asInterface", IBinder.class);
Class<?> serviceManagerClazz = Class.forName("android.os.ServiceManager");
Method getService = serviceManagerClazz.getDeclaredMethod("getService", String.class);
Class<?> windowManagerClazz = Class.forName("android.view.IWindowManager");
Method setAnimationScales = windowManagerClazz.getDeclaredMethod("setAnimationScales",
float[].class);
Method getAnimationScales = windowManagerClazz.getDeclaredMethod("getAnimationScales");
IBinder windowManagerBinder = (IBinder) getService.invoke(null, "window");
Object windowManagerObj = asInterface.invoke(null, windowManagerBinder);
float[] currentScales = (float[]) getAnimationScales.invoke(windowManagerObj);
for (int i = 0; i < currentScales.length; i++) {
currentScales[i] = animationScale;
}
setAnimationScales.invoke(windowManagerObj, currentScales);
return true;
} catch (ClassNotFoundException cnfe) {
Log.w(TAG, "Cannot disable animations reflectively.", cnfe);
} catch (NoSuchMethodException mnfe) {
Log.w(TAG, "Cannot disable animations reflectively.", mnfe);
} catch (SecurityException se) {
Log.w(TAG, "Cannot disable animations reflectively.", se);
} catch (InvocationTargetException ite) {
Log.w(TAG, "Cannot disable animations reflectively.", ite);
} catch (IllegalAccessException iae) {
Log.w(TAG, "Cannot disable animations reflectively.", iae);
} catch (RuntimeException re) {
Log.w(TAG, "Cannot disable animations reflectively.", re);
}
return false;
}
}
| 4,669 | 40.327434 | 104 |
java
|
gnucash-android
|
gnucash-android-master/app/src/debug/java/org/gnucash/android/app/StethoUtils.java
|
package org.gnucash.android.app;
import android.app.Application;
import android.os.Build;
import com.facebook.stetho.Stetho;
import org.gnucash.android.BuildConfig;
/**
* Utility class for initializing Stetho in debug builds
*/
public class StethoUtils {
/**
* Sets up Stetho to enable remote debugging from Chrome developer tools.
*
* <p>Among other things, allows access to the database and preferences.
* See http://facebook.github.io/stetho/#features</p>
*/
public static void install(Application application){
//don't initialize stetho during tests
if (!BuildConfig.DEBUG || isRoboUnitTest())
return;
Stetho.initialize(Stetho.newInitializerBuilder(application)
.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(application))
.build());
}
/**
* Returns {@code true} if the app is being run by robolectric
* @return {@code true} if in unit testing, {@code false} otherwise
*/
private static boolean isRoboUnitTest(){
return "robolectric".equals(Build.FINGERPRINT);
}
}
| 1,150 | 27.775 | 99 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/app/GnuCashApplication.java
|
/*
* Copyright (c) 2013 - 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.app;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDexApplication;
import android.support.v7.preference.PreferenceManager;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.core.CrashlyticsCore;
import com.uservoice.uservoicesdk.Config;
import com.uservoice.uservoicesdk.UserVoice;
import org.gnucash.android.BuildConfig;
import org.gnucash.android.R;
import org.gnucash.android.db.BookDbHelper;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.BudgetAmountsDbAdapter;
import org.gnucash.android.db.adapter.BudgetsDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.PricesDbAdapter;
import org.gnucash.android.db.adapter.RecurrenceDbAdapter;
import org.gnucash.android.db.adapter.ScheduledActionDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.receivers.PeriodicJobReceiver;
import org.gnucash.android.service.ScheduledActionService;
import org.gnucash.android.ui.settings.PreferenceActivity;
import java.util.Currency;
import java.util.Locale;
import io.fabric.sdk.android.Fabric;
/**
* An {@link Application} subclass for retrieving static context
* @author Ngewi Fet <[email protected]>
*
*/
public class GnuCashApplication extends MultiDexApplication {
/**
* Authority (domain) for the file provider. Also used in the app manifest
*/
public static final String FILE_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID + ".fileprovider";
/**
* Lifetime of passcode session
*/
public static final long SESSION_TIMEOUT = 5 * 1000;
/**
* Init time of passcode session
*/
public static long PASSCODE_SESSION_INIT_TIME = 0L;
private static Context context;
private static AccountsDbAdapter mAccountsDbAdapter;
private static TransactionsDbAdapter mTransactionsDbAdapter;
private static SplitsDbAdapter mSplitsDbAdapter;
private static ScheduledActionDbAdapter mScheduledActionDbAdapter;
private static CommoditiesDbAdapter mCommoditiesDbAdapter;
private static PricesDbAdapter mPricesDbAdapter;
private static BudgetsDbAdapter mBudgetsDbAdapter;
private static BudgetAmountsDbAdapter mBudgetAmountsDbAdapter;
private static RecurrenceDbAdapter mRecurrenceDbAdapter;
private static BooksDbAdapter mBooksDbAdapter;
private static DatabaseHelper mDbHelper;
/**
* Returns darker version of specified <code>color</code>.
* Use for theming the status bar color when setting the color of the actionBar
*/
public static int darken(int color) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f; // value component
return Color.HSVToColor(hsv);
}
@Override
public void onCreate(){
super.onCreate();
GnuCashApplication.context = getApplicationContext();
Fabric.with(this, new Crashlytics.Builder().core(
new CrashlyticsCore.Builder().disabled(!isCrashlyticsEnabled()).build())
.build());
setUpUserVoice();
BookDbHelper bookDbHelper = new BookDbHelper(getApplicationContext());
mBooksDbAdapter = new BooksDbAdapter(bookDbHelper.getWritableDatabase());
initializeDatabaseAdapters();
setDefaultCurrencyCode(getDefaultCurrencyCode());
StethoUtils.install(this);
}
/**
* Initialize database adapter singletons for use in the application
* This method should be called every time a new book is opened
*/
public static void initializeDatabaseAdapters() {
if (mDbHelper != null){ //close if open
mDbHelper.getReadableDatabase().close();
}
try {
mDbHelper = new DatabaseHelper(getAppContext(),
mBooksDbAdapter.getActiveBookUID());
} catch (BooksDbAdapter.NoActiveBookFoundException e) {
mBooksDbAdapter.fixBooksDatabase();
mDbHelper = new DatabaseHelper(getAppContext(),
mBooksDbAdapter.getActiveBookUID());
}
SQLiteDatabase mainDb;
try {
mainDb = mDbHelper.getWritableDatabase();
} catch (SQLException e) {
Crashlytics.logException(e);
Log.e("GnuCashApplication", "Error getting database: " + e.getMessage());
mainDb = mDbHelper.getReadableDatabase();
}
mSplitsDbAdapter = new SplitsDbAdapter(mainDb);
mTransactionsDbAdapter = new TransactionsDbAdapter(mainDb, mSplitsDbAdapter);
mAccountsDbAdapter = new AccountsDbAdapter(mainDb, mTransactionsDbAdapter);
mRecurrenceDbAdapter = new RecurrenceDbAdapter(mainDb);
mScheduledActionDbAdapter = new ScheduledActionDbAdapter(mainDb, mRecurrenceDbAdapter);
mPricesDbAdapter = new PricesDbAdapter(mainDb);
mCommoditiesDbAdapter = new CommoditiesDbAdapter(mainDb);
mBudgetAmountsDbAdapter = new BudgetAmountsDbAdapter(mainDb);
mBudgetsDbAdapter = new BudgetsDbAdapter(mainDb, mBudgetAmountsDbAdapter, mRecurrenceDbAdapter);
}
public static AccountsDbAdapter getAccountsDbAdapter() {
return mAccountsDbAdapter;
}
public static TransactionsDbAdapter getTransactionDbAdapter() {
return mTransactionsDbAdapter;
}
public static SplitsDbAdapter getSplitsDbAdapter() {
return mSplitsDbAdapter;
}
public static ScheduledActionDbAdapter getScheduledEventDbAdapter(){
return mScheduledActionDbAdapter;
}
public static CommoditiesDbAdapter getCommoditiesDbAdapter(){
return mCommoditiesDbAdapter;
}
public static PricesDbAdapter getPricesDbAdapter(){
return mPricesDbAdapter;
}
public static BudgetsDbAdapter getBudgetDbAdapter() {
return mBudgetsDbAdapter;
}
public static RecurrenceDbAdapter getRecurrenceDbAdapter() {
return mRecurrenceDbAdapter;
}
public static BudgetAmountsDbAdapter getBudgetAmountsDbAdapter(){
return mBudgetAmountsDbAdapter;
}
public static BooksDbAdapter getBooksDbAdapter(){
return mBooksDbAdapter;
}
/**
* Returns the currently active database in the application
* @return Currently active {@link SQLiteDatabase}
*/
public static SQLiteDatabase getActiveDb(){
return mDbHelper.getWritableDatabase();
}
/**
* Returns the application context
* @return Application {@link Context} object
*/
public static Context getAppContext() {
return GnuCashApplication.context;
}
/**
* Checks if crashlytics is enabled
* @return {@code true} if crashlytics is enabled, {@code false} otherwise
*/
public static boolean isCrashlyticsEnabled(){
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.key_enable_crashlytics), false);
}
/**
* Returns <code>true</code> if double entry is enabled in the app settings, <code>false</code> otherwise.
* If the value is not set, the default value can be specified in the parameters.
* @return <code>true</code> if double entry is enabled, <code>false</code> otherwise
*/
public static boolean isDoubleEntryEnabled(){
SharedPreferences sharedPrefs = PreferenceActivity.getActiveBookSharedPreferences();
return sharedPrefs.getBoolean(context.getString(R.string.key_use_double_entry), true);
}
/**
* Returns <code>true</code> if setting is enabled to save opening balances after deleting transactions,
* <code>false</code> otherwise.
* @param defaultValue Default value to return if double entry is not explicitly set
* @return <code>true</code> if opening balances should be saved, <code>false</code> otherwise
*/
public static boolean shouldSaveOpeningBalances(boolean defaultValue){
SharedPreferences sharedPrefs = PreferenceActivity.getActiveBookSharedPreferences();
return sharedPrefs.getBoolean(context.getString(R.string.key_save_opening_balances), defaultValue);
}
/**
* Returns the default currency code for the application. <br/>
* What value is actually returned is determined in this order of priority:<ul>
* <li>User currency preference (manually set be user in the app)</li>
* <li>Default currency for the device locale</li>
* <li>United States Dollars</li>
* </ul>
*
* @return Default currency code string for the application
*/
public static String getDefaultCurrencyCode(){
Locale locale = getDefaultLocale();
String currencyCode = "USD"; //start with USD as the default
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
try { //there are some strange locales out there
currencyCode = Currency.getInstance(locale).getCurrencyCode();
} catch (Throwable e) {
Crashlytics.logException(e);
Log.e(context.getString(R.string.app_name), "" + e.getMessage());
} finally {
currencyCode = prefs.getString(context.getString(R.string.key_default_currency), currencyCode);
}
return currencyCode;
}
/**
* Sets the default currency for the application in all relevant places:
* <ul>
* <li>Shared preferences</li>
* <li>{@link Money#DEFAULT_CURRENCY_CODE}</li>
* <li>{@link Commodity#DEFAULT_COMMODITY}</li>
* </ul>
* @param currencyCode ISO 4217 currency code
* @see #getDefaultCurrencyCode()
*/
public static void setDefaultCurrencyCode(@NonNull String currencyCode){
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putString(getAppContext().getString(R.string.key_default_currency), currencyCode)
.apply();
Money.DEFAULT_CURRENCY_CODE = currencyCode;
Commodity.DEFAULT_COMMODITY = mCommoditiesDbAdapter.getCommodity(currencyCode);
}
/**
* Returns the default locale which is used for currencies, while handling special cases for
* locales which are not supported for currency such as en_GB
* @return The default locale for this device
*/
public static Locale getDefaultLocale() {
Locale locale = Locale.getDefault();
//sometimes the locale en_UK is returned which causes a crash with Currency
if (locale.getCountry().equals("UK")) {
locale = new Locale(locale.getLanguage(), "GB");
}
//for unsupported locale es_LG
if (locale.getCountry().equals("LG")){
locale = new Locale(locale.getLanguage(), "ES");
}
if (locale.getCountry().equals("en")){
locale = Locale.US;
}
return locale;
}
/**
* Starts the service for scheduled events and schedules an alarm to call the service twice daily.
* <p>If the alarm already exists, this method does nothing. If not, the alarm will be created
* Hence, there is no harm in calling the method repeatedly</p>
* @param context Application context
*/
public static void startScheduledActionExecutionService(Context context){
Intent alarmIntent = new Intent(context, PeriodicJobReceiver.class);
alarmIntent.setAction(PeriodicJobReceiver.ACTION_SCHEDULED_ACTIONS);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0, alarmIntent,
PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) //if service is already scheduled, just return
return;
else
pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES,
AlarmManager.INTERVAL_HOUR, pendingIntent);
ScheduledActionService.enqueueWork(context);
}
/**
* Sets up UserVoice.
*
* <p>Allows users to contact with us and access help topics.</p>
*/
private void setUpUserVoice() {
// Set this up once when your application launches
Config config = new Config("gnucash.uservoice.com");
config.setTopicId(107400);
config.setForumId(320493);
config.putUserTrait("app_version_name", BuildConfig.VERSION_NAME);
config.putUserTrait("app_version_code", BuildConfig.VERSION_CODE);
config.putUserTrait("android_version", Build.VERSION.RELEASE);
// config.identifyUser("USER_ID", "User Name", "[email protected]");
UserVoice.init(config, this);
}
}
| 14,353 | 37.690027 | 140 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/BookDbHelper.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema.BookEntry;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.model.Book;
import org.gnucash.android.util.RecursiveMoveFiles;
import java.io.File;
import java.io.IOException;
/**
* Database helper for managing database which stores information about the books in the application
* This is a different database from the one which contains the accounts and transaction data because
* there are multiple accounts/transactions databases in the system and this one will be used to
* switch between them.
*/
public class BookDbHelper extends SQLiteOpenHelper {
public static final String LOG_TAG = "BookDbHelper";
private Context mContext;
/**
* Create the books table
*/
private static final String BOOKS_TABLE_CREATE = "CREATE TABLE " + BookEntry.TABLE_NAME + " ("
+ BookEntry._ID + " integer primary key autoincrement, "
+ BookEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ BookEntry.COLUMN_DISPLAY_NAME + " varchar(255) not null, "
+ BookEntry.COLUMN_ROOT_GUID + " varchar(255) not null, "
+ BookEntry.COLUMN_TEMPLATE_GUID + " varchar(255), "
+ BookEntry.COLUMN_ACTIVE + " tinyint default 0, "
+ BookEntry.COLUMN_SOURCE_URI + " varchar(255), "
+ BookEntry.COLUMN_LAST_SYNC + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ BookEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ BookEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(BookEntry.TABLE_NAME);
public BookDbHelper(Context context) {
super(context, DatabaseSchema.BOOK_DATABASE_NAME, null, DatabaseSchema.BOOK_DATABASE_VERSION);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(BOOKS_TABLE_CREATE);
if (mContext.getDatabasePath(DatabaseSchema.LEGACY_DATABASE_NAME).exists()){
Log.d(LOG_TAG, "Legacy database found. Migrating to multibook format");
DatabaseHelper helper = new DatabaseHelper(GnuCashApplication.getAppContext(),
DatabaseSchema.LEGACY_DATABASE_NAME);
SQLiteDatabase mainDb = helper.getWritableDatabase();
AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(mainDb,
new TransactionsDbAdapter(mainDb, new SplitsDbAdapter(mainDb)));
String rootAccountUID = accountsDbAdapter.getOrCreateGnuCashRootAccountUID();
Book book = new Book(rootAccountUID);
book.setActive(true);
insertBook(db, book);
String mainDbPath = mainDb.getPath();
helper.close();
File src = new File(mainDbPath);
File dst = new File(src.getParent(), book.getUID());
try {
MigrationHelper.moveFile(src, dst);
} catch (IOException e) {
String err_msg = "Error renaming database file";
Crashlytics.log(err_msg);
Log.e(LOG_TAG, err_msg, e);
}
migrateBackupFiles(book.getUID());
}
String sql = "SELECT COUNT(*) FROM " + BookEntry.TABLE_NAME;
SQLiteStatement statement = db.compileStatement(sql);
long count = statement.simpleQueryForLong();
if (count == 0) { //no book in the database, create a default one
Log.i(LOG_TAG, "No books found in database, creating default book");
Book book = new Book();
DatabaseHelper helper = new DatabaseHelper(GnuCashApplication.getAppContext(), book.getUID());
SQLiteDatabase mainDb = helper.getWritableDatabase(); //actually create the db
AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(mainDb,
new TransactionsDbAdapter(mainDb, new SplitsDbAdapter(mainDb)));
String rootAccountUID = accountsDbAdapter.getOrCreateGnuCashRootAccountUID();
book.setRootAccountUID(rootAccountUID);
book.setActive(true);
insertBook(db, book);
}
}
/**
* Returns the database for the book
* @param bookUID GUID of the book
* @return SQLiteDatabase of the book
*/
public static SQLiteDatabase getDatabase(String bookUID){
DatabaseHelper dbHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), bookUID);
return dbHelper.getWritableDatabase();
}
/**
* Inserts the book into the database
* @param db Book database
* @param book Book to insert
*/
private void insertBook(SQLiteDatabase db, Book book) {
ContentValues contentValues = new ContentValues();
contentValues.put(BookEntry.COLUMN_UID, book.getUID());
contentValues.put(BookEntry.COLUMN_ROOT_GUID, book.getRootAccountUID());
contentValues.put(BookEntry.COLUMN_TEMPLATE_GUID, Book.generateUID());
contentValues.put(BookEntry.COLUMN_DISPLAY_NAME, new BooksDbAdapter(db).generateDefaultBookName());
contentValues.put(BookEntry.COLUMN_ACTIVE, book.isActive() ? 1 : 0);
db.insert(BookEntry.TABLE_NAME, null, contentValues);
}
/**
* Move the backup and export files from the old location (single-book) to the new multi-book
* backup folder structure. Each book has its own directory as well as backups and exports.
* <p>This method should be called only once during the initial migration to multi-book support</p>
* @param activeBookUID GUID of the book for which to migrate the files
*/
private void migrateBackupFiles(String activeBookUID){
Log.d(LOG_TAG, "Moving export and backup files to book-specific folders");
File newBasePath = new File(Exporter.LEGACY_BASE_FOLDER_PATH + "/" + activeBookUID);
newBasePath.mkdirs();
File src = new File(Exporter.LEGACY_BASE_FOLDER_PATH + "/backups/");
File dst = new File(Exporter.LEGACY_BASE_FOLDER_PATH + "/" + activeBookUID + "/backups/");
new Thread(new RecursiveMoveFiles(src, dst)).start();
src = new File(Exporter.LEGACY_BASE_FOLDER_PATH + "/exports/");
dst = new File(Exporter.LEGACY_BASE_FOLDER_PATH + "/" + activeBookUID + "/exports/");
new Thread(new RecursiveMoveFiles(src, dst)).start();
File nameFile = new File(newBasePath, "Book 1");
try {
nameFile.createNewFile();
} catch (IOException e) {
Log.e(LOG_TAG, "Error creating name file for the database: " + nameFile.getName());
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//nothing to see here yet, move along
}
}
| 8,119 | 42.42246 | 107 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/DatabaseCursorLoader.java
|
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import org.gnucash.android.db.adapter.DatabaseAdapter;
/**
* Abstract base class for asynchronously loads records from a database and manages the cursor.
* In order to use this class, you must subclass it and implement the
* {@link #loadInBackground()} method to load the particular records from the database.
* Ideally, the database has {@link DatabaseAdapter} which is used for managing access to the
* records from the database
* @author Ngewi Fet <[email protected]>
* @see DatabaseAdapter
*/
public abstract class DatabaseCursorLoader extends AsyncTaskLoader<Cursor> {
/**
* Cursor which will hold the loaded data set.
* The cursor will be returned from the {@link #loadInBackground()} method
*/
private Cursor mCursor = null;
/**
* {@link DatabaseAdapter} which will be used to load the records from the database
*/
protected DatabaseAdapter mDatabaseAdapter = null;
/**
* A content observer which monitors the cursor and provides notifications when
* the dataset backing the cursor changes. You need to register the oberserver on
* your cursor using {@link #registerContentObserver(Cursor)}
*/
protected final Loader.ForceLoadContentObserver mObserver;
/**
* Constructor
* Initializes the content observer
* @param context Application context
*/
public DatabaseCursorLoader(Context context) {
super(context);
mObserver = new ForceLoadContentObserver();
}
/**
* Asynchronously loads the results from the database.
*/
public abstract Cursor loadInBackground();
/**
* Registers the content observer for the cursor.
* @param cursor {@link Cursor} whose content is to be observed for changes
*/
protected void registerContentObserver(Cursor cursor){
cursor.registerContentObserver(mObserver);
}
@Override
public void deliverResult(Cursor data) {
if (isReset()) {
if (data != null) {
onReleaseResources(data);
}
return;
}
Cursor oldCursor = mCursor;
mCursor = data;
if (isStarted()) {
super.deliverResult(data);
}
if (oldCursor != null && oldCursor != data && !oldCursor.isClosed()) {
onReleaseResources(oldCursor);
}
}
@Override
protected void onStartLoading() {
if (mCursor != null){
deliverResult(mCursor);
}
if (takeContentChanged() || mCursor == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
@Override
protected void onStopLoading() {
cancelLoad();
}
@Override
public void onCanceled(Cursor data) {
super.onCanceled(data);
onReleaseResources(data);
}
/**
* Handles a request to completely reset the Loader.
*/
@Override
protected void onReset() {
super.onReset();
onStopLoading();
// At this point we can release the resources associated with 'mCursor'
// if needed.
if (mCursor != null && !mCursor.isClosed()) {
onReleaseResources(mCursor);
}
mCursor = null;
}
/**
* Helper function to take care of releasing resources associated
* with an actively loaded data set.
* @param c {@link Cursor} to be released
*/
protected void onReleaseResources(Cursor c) {
if (c != null)
c.close();
}
}
| 4,119 | 26.651007 | 95 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/DatabaseHelper.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.model.Commodity;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.xml.parsers.ParserConfigurationException;
import static org.gnucash.android.db.DatabaseSchema.AccountEntry;
import static org.gnucash.android.db.DatabaseSchema.BudgetAmountEntry;
import static org.gnucash.android.db.DatabaseSchema.BudgetEntry;
import static org.gnucash.android.db.DatabaseSchema.CommodityEntry;
import static org.gnucash.android.db.DatabaseSchema.CommonColumns;
import static org.gnucash.android.db.DatabaseSchema.PriceEntry;
import static org.gnucash.android.db.DatabaseSchema.RecurrenceEntry;
import static org.gnucash.android.db.DatabaseSchema.ScheduledActionEntry;
import static org.gnucash.android.db.DatabaseSchema.SplitEntry;
import static org.gnucash.android.db.DatabaseSchema.TransactionEntry;
/**
* Helper class for managing the SQLite database.
* Creates the database and handles upgrades
* @author Ngewi Fet <[email protected]>
*
*/
public class DatabaseHelper extends SQLiteOpenHelper {
/**
* Tag for logging
*/
public static final String LOG_TAG = DatabaseHelper.class.getName();
/**
* SQL statement to create the accounts table in the database
*/
private static final String ACCOUNTS_TABLE_CREATE = "create table " + AccountEntry.TABLE_NAME + " ("
+ AccountEntry._ID + " integer primary key autoincrement, "
+ AccountEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ AccountEntry.COLUMN_NAME + " varchar(255) not null, "
+ AccountEntry.COLUMN_TYPE + " varchar(255) not null, "
+ AccountEntry.COLUMN_CURRENCY + " varchar(255) not null, "
+ AccountEntry.COLUMN_COMMODITY_UID + " varchar(255) not null, "
+ AccountEntry.COLUMN_DESCRIPTION + " varchar(255), "
+ AccountEntry.COLUMN_COLOR_CODE + " varchar(255), "
+ AccountEntry.COLUMN_FAVORITE + " tinyint default 0, "
+ AccountEntry.COLUMN_HIDDEN + " tinyint default 0, "
+ AccountEntry.COLUMN_FULL_NAME + " varchar(255), "
+ AccountEntry.COLUMN_PLACEHOLDER + " tinyint default 0, "
+ AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " varchar(255), "
+ AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID + " varchar(255), "
+ AccountEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ AccountEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
// + "FOREIGN KEY (" + AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID + ") REFERENCES " + AccountEntry.TABLE_NAME + " (" + AccountEntry.COLUMN_UID + ") ON DELETE SET NULL, "
+ "FOREIGN KEY (" + AccountEntry.COLUMN_COMMODITY_UID + ") REFERENCES " + CommodityEntry.TABLE_NAME + " (" + CommodityEntry.COLUMN_UID + ") "
+ ");" + createUpdatedAtTrigger(AccountEntry.TABLE_NAME);
/**
* SQL statement to create the transactions table in the database
*/
private static final String TRANSACTIONS_TABLE_CREATE = "create table " + TransactionEntry.TABLE_NAME + " ("
+ TransactionEntry._ID + " integer primary key autoincrement, "
+ TransactionEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ TransactionEntry.COLUMN_DESCRIPTION + " varchar(255), "
+ TransactionEntry.COLUMN_NOTES + " text, "
+ TransactionEntry.COLUMN_TIMESTAMP + " integer not null, "
+ TransactionEntry.COLUMN_EXPORTED + " tinyint default 0, "
+ TransactionEntry.COLUMN_TEMPLATE + " tinyint default 0, "
+ TransactionEntry.COLUMN_CURRENCY + " varchar(255) not null, "
+ TransactionEntry.COLUMN_COMMODITY_UID + " varchar(255) not null, "
+ TransactionEntry.COLUMN_SCHEDX_ACTION_UID + " varchar(255), "
+ TransactionEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ TransactionEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + TransactionEntry.COLUMN_SCHEDX_ACTION_UID + ") REFERENCES " + ScheduledActionEntry.TABLE_NAME + " (" + ScheduledActionEntry.COLUMN_UID + ") ON DELETE SET NULL, "
+ "FOREIGN KEY (" + TransactionEntry.COLUMN_COMMODITY_UID + ") REFERENCES " + CommodityEntry.TABLE_NAME + " (" + CommodityEntry.COLUMN_UID + ") "
+ ");" + createUpdatedAtTrigger(TransactionEntry.TABLE_NAME);
/**
* SQL statement to create the transaction splits table
*/
private static final String SPLITS_TABLE_CREATE = "CREATE TABLE " + SplitEntry.TABLE_NAME + " ("
+ SplitEntry._ID + " integer primary key autoincrement, "
+ SplitEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ SplitEntry.COLUMN_MEMO + " text, "
+ SplitEntry.COLUMN_TYPE + " varchar(255) not null, "
+ SplitEntry.COLUMN_VALUE_NUM + " integer not null, "
+ SplitEntry.COLUMN_VALUE_DENOM + " integer not null, "
+ SplitEntry.COLUMN_QUANTITY_NUM + " integer not null, "
+ SplitEntry.COLUMN_QUANTITY_DENOM + " integer not null, "
+ SplitEntry.COLUMN_ACCOUNT_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_TRANSACTION_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_RECONCILE_STATE + " varchar(1) not null default 'n', "
+ SplitEntry.COLUMN_RECONCILE_DATE + " timestamp not null default current_timestamp, "
+ SplitEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ SplitEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_ACCOUNT_UID + ") REFERENCES " + AccountEntry.TABLE_NAME + " (" + AccountEntry.COLUMN_UID + ") ON DELETE CASCADE, "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_TRANSACTION_UID + ") REFERENCES " + TransactionEntry.TABLE_NAME + " (" + TransactionEntry.COLUMN_UID + ") ON DELETE CASCADE "
+ ");" + createUpdatedAtTrigger(SplitEntry.TABLE_NAME);
public static final String SCHEDULED_ACTIONS_TABLE_CREATE = "CREATE TABLE " + ScheduledActionEntry.TABLE_NAME + " ("
+ ScheduledActionEntry._ID + " integer primary key autoincrement, "
+ ScheduledActionEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ ScheduledActionEntry.COLUMN_ACTION_UID + " varchar(255) not null, "
+ ScheduledActionEntry.COLUMN_TYPE + " varchar(255) not null, "
+ ScheduledActionEntry.COLUMN_RECURRENCE_UID + " varchar(255) not null, "
+ ScheduledActionEntry.COLUMN_TEMPLATE_ACCT_UID + " varchar(255) not null, "
+ ScheduledActionEntry.COLUMN_LAST_RUN + " integer default 0, "
+ ScheduledActionEntry.COLUMN_START_TIME + " integer not null, "
+ ScheduledActionEntry.COLUMN_END_TIME + " integer default 0, "
+ ScheduledActionEntry.COLUMN_TAG + " text, "
+ ScheduledActionEntry.COLUMN_ENABLED + " tinyint default 1, " //enabled by default
+ ScheduledActionEntry.COLUMN_AUTO_CREATE + " tinyint default 1, "
+ ScheduledActionEntry.COLUMN_AUTO_NOTIFY + " tinyint default 0, "
+ ScheduledActionEntry.COLUMN_ADVANCE_CREATION + " integer default 0, "
+ ScheduledActionEntry.COLUMN_ADVANCE_NOTIFY + " integer default 0, "
+ ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY + " integer default 0, "
+ ScheduledActionEntry.COLUMN_EXECUTION_COUNT + " integer default 0, "
+ ScheduledActionEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ ScheduledActionEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + ScheduledActionEntry.COLUMN_RECURRENCE_UID + ") REFERENCES " + RecurrenceEntry.TABLE_NAME + " (" + RecurrenceEntry.COLUMN_UID + ") "
+ ");" + createUpdatedAtTrigger(ScheduledActionEntry.TABLE_NAME);
public static final String COMMODITIES_TABLE_CREATE = "CREATE TABLE " + DatabaseSchema.CommodityEntry.TABLE_NAME + " ("
+ CommodityEntry._ID + " integer primary key autoincrement, "
+ CommodityEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ CommodityEntry.COLUMN_NAMESPACE + " varchar(255) not null default " + Commodity.Namespace.ISO4217.name() + ", "
+ CommodityEntry.COLUMN_FULLNAME + " varchar(255) not null, "
+ CommodityEntry.COLUMN_MNEMONIC + " varchar(255) not null, "
+ CommodityEntry.COLUMN_LOCAL_SYMBOL+ " varchar(255) not null default '', "
+ CommodityEntry.COLUMN_CUSIP + " varchar(255), "
+ CommodityEntry.COLUMN_SMALLEST_FRACTION + " integer not null, "
+ CommodityEntry.COLUMN_QUOTE_FLAG + " integer not null, "
+ CommodityEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ CommodityEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP "
+ ");" + createUpdatedAtTrigger(CommodityEntry.TABLE_NAME);
/**
* SQL statement to create the commodity prices table
*/
private static final String PRICES_TABLE_CREATE = "CREATE TABLE " + PriceEntry.TABLE_NAME + " ("
+ PriceEntry._ID + " integer primary key autoincrement, "
+ PriceEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ PriceEntry.COLUMN_COMMODITY_UID + " varchar(255) not null, "
+ PriceEntry.COLUMN_CURRENCY_UID + " varchar(255) not null, "
+ PriceEntry.COLUMN_TYPE + " varchar(255), "
+ PriceEntry.COLUMN_DATE + " TIMESTAMP not null, "
+ PriceEntry.COLUMN_SOURCE + " text, "
+ PriceEntry.COLUMN_VALUE_NUM + " integer not null, "
+ PriceEntry.COLUMN_VALUE_DENOM + " integer not null, "
+ PriceEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ PriceEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "UNIQUE (" + PriceEntry.COLUMN_COMMODITY_UID + ", " + PriceEntry.COLUMN_CURRENCY_UID + ") ON CONFLICT REPLACE, "
+ "FOREIGN KEY (" + PriceEntry.COLUMN_COMMODITY_UID + ") REFERENCES " + CommodityEntry.TABLE_NAME + " (" + CommodityEntry.COLUMN_UID + ") ON DELETE CASCADE, "
+ "FOREIGN KEY (" + PriceEntry.COLUMN_CURRENCY_UID + ") REFERENCES " + CommodityEntry.TABLE_NAME + " (" + CommodityEntry.COLUMN_UID + ") ON DELETE CASCADE "
+ ");" + createUpdatedAtTrigger(PriceEntry.TABLE_NAME);
private static final String BUDGETS_TABLE_CREATE = "CREATE TABLE " + BudgetEntry.TABLE_NAME + " ("
+ BudgetEntry._ID + " integer primary key autoincrement, "
+ BudgetEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ BudgetEntry.COLUMN_NAME + " varchar(255) not null, "
+ BudgetEntry.COLUMN_DESCRIPTION + " varchar(255), "
+ BudgetEntry.COLUMN_RECURRENCE_UID + " varchar(255) not null, "
+ BudgetEntry.COLUMN_NUM_PERIODS + " integer, "
+ BudgetEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ BudgetEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + BudgetEntry.COLUMN_RECURRENCE_UID + ") REFERENCES " + RecurrenceEntry.TABLE_NAME + " (" + RecurrenceEntry.COLUMN_UID + ") "
+ ");" + createUpdatedAtTrigger(BudgetEntry.TABLE_NAME);
private static final String BUDGET_AMOUNTS_TABLE_CREATE = "CREATE TABLE " + BudgetAmountEntry.TABLE_NAME + " ("
+ BudgetAmountEntry._ID + " integer primary key autoincrement, "
+ BudgetAmountEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ BudgetAmountEntry.COLUMN_BUDGET_UID + " varchar(255) not null, "
+ BudgetAmountEntry.COLUMN_ACCOUNT_UID + " varchar(255) not null, "
+ BudgetAmountEntry.COLUMN_AMOUNT_NUM + " integer not null, "
+ BudgetAmountEntry.COLUMN_AMOUNT_DENOM + " integer not null, "
+ BudgetAmountEntry.COLUMN_PERIOD_NUM + " integer not null, "
+ BudgetAmountEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ BudgetAmountEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + BudgetAmountEntry.COLUMN_ACCOUNT_UID + ") REFERENCES " + AccountEntry.TABLE_NAME + " (" + AccountEntry.COLUMN_UID + ") ON DELETE CASCADE, "
+ "FOREIGN KEY (" + BudgetAmountEntry.COLUMN_BUDGET_UID + ") REFERENCES " + BudgetEntry.TABLE_NAME + " (" + BudgetEntry.COLUMN_UID + ") ON DELETE CASCADE "
+ ");" + createUpdatedAtTrigger(BudgetAmountEntry.TABLE_NAME);
private static final String RECURRENCE_TABLE_CREATE = "CREATE TABLE " + RecurrenceEntry.TABLE_NAME + " ("
+ RecurrenceEntry._ID + " integer primary key autoincrement, "
+ RecurrenceEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ RecurrenceEntry.COLUMN_MULTIPLIER + " integer not null default 1, "
+ RecurrenceEntry.COLUMN_PERIOD_TYPE + " varchar(255) not null, "
+ RecurrenceEntry.COLUMN_BYDAY + " varchar(255), "
+ RecurrenceEntry.COLUMN_PERIOD_START + " timestamp not null, "
+ RecurrenceEntry.COLUMN_PERIOD_END + " timestamp, "
+ RecurrenceEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ RecurrenceEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP); "
+ createUpdatedAtTrigger(RecurrenceEntry.TABLE_NAME);
/**
* Constructor
* @param context Application context
* @param databaseName Name of the database
*/
public DatabaseHelper(Context context, String databaseName){
super(context, databaseName, null, DatabaseSchema.DATABASE_VERSION);
}
/**
* Creates an update trigger to update the updated_at column for all records in the database.
* This has to be run per table, and is currently appended to the create table statement.
* @param tableName Name of table on which to create trigger
* @return SQL statement for creating trigger
*/
static String createUpdatedAtTrigger(String tableName){
return "CREATE TRIGGER update_time_trigger "
+ " AFTER UPDATE ON " + tableName + " FOR EACH ROW"
+ " BEGIN " + "UPDATE " + tableName
+ " SET " + CommonColumns.COLUMN_MODIFIED_AT + " = CURRENT_TIMESTAMP"
+ " WHERE OLD." + CommonColumns.COLUMN_UID + " = NEW." + CommonColumns.COLUMN_UID + ";"
+ " END;";
}
@Override
public void onCreate(SQLiteDatabase db) {
createDatabaseTables(db);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
db.execSQL("PRAGMA foreign_keys=ON");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
Log.i(LOG_TAG, "Upgrading database from version "
+ oldVersion + " to " + newVersion);
Toast.makeText(GnuCashApplication.getAppContext(), "Upgrading GnuCash database", Toast.LENGTH_SHORT).show();
/*
* NOTE: In order to modify the database, create a new static method in the MigrationHelper class
* called upgradeDbToVersion<#>, e.g. int upgradeDbToVersion10(SQLiteDatabase) in order to upgrade to version 10.
* The upgrade method should return the new (upgraded) database version as the return value.
* Then all you need to do is increment the DatabaseSchema.DATABASE_VERSION to the appropriate number to trigger an upgrade.
*/
if (oldVersion > newVersion) {
throw new IllegalArgumentException("Database downgrades are not supported at the moment");
}
while(oldVersion < newVersion){
try {
Method method = MigrationHelper.class.getDeclaredMethod("upgradeDbToVersion" + (oldVersion+1), SQLiteDatabase.class);
Object result = method.invoke(null, db);
oldVersion = Integer.parseInt(result.toString());
} catch (NoSuchMethodException e) {
String msg = String.format("Database upgrade method upgradeToVersion%d(SQLiteDatabase) definition not found ", newVersion);
Log.e(LOG_TAG, msg, e);
Crashlytics.log(msg);
Crashlytics.logException(e);
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
String msg = String.format("Database upgrade to version %d failed. The upgrade method is inaccessible ", newVersion);
Log.e(LOG_TAG, msg, e);
Crashlytics.log(msg);
Crashlytics.logException(e);
throw new RuntimeException(e);
} catch (InvocationTargetException e){
Crashlytics.logException(e.getTargetException());
throw new RuntimeException(e.getTargetException());
}
}
}
/**
* Creates the tables in the database and import default commodities into the database
* @param db Database instance
*/
private void createDatabaseTables(SQLiteDatabase db) {
Log.i(LOG_TAG, "Creating database tables");
db.execSQL(ACCOUNTS_TABLE_CREATE);
db.execSQL(TRANSACTIONS_TABLE_CREATE);
db.execSQL(SPLITS_TABLE_CREATE);
db.execSQL(SCHEDULED_ACTIONS_TABLE_CREATE);
db.execSQL(COMMODITIES_TABLE_CREATE);
db.execSQL(PRICES_TABLE_CREATE);
db.execSQL(RECURRENCE_TABLE_CREATE);
db.execSQL(BUDGETS_TABLE_CREATE);
db.execSQL(BUDGET_AMOUNTS_TABLE_CREATE);
String createAccountUidIndex = "CREATE UNIQUE INDEX '" + AccountEntry.INDEX_UID + "' ON "
+ AccountEntry.TABLE_NAME + "(" + AccountEntry.COLUMN_UID + ")";
String createTransactionUidIndex = "CREATE UNIQUE INDEX '" + TransactionEntry.INDEX_UID + "' ON "
+ TransactionEntry.TABLE_NAME + "(" + TransactionEntry.COLUMN_UID + ")";
String createSplitUidIndex = "CREATE UNIQUE INDEX '" + SplitEntry.INDEX_UID + "' ON "
+ SplitEntry.TABLE_NAME + "(" + SplitEntry.COLUMN_UID + ")";
String createScheduledEventUidIndex = "CREATE UNIQUE INDEX '" + ScheduledActionEntry.INDEX_UID
+ "' ON " + ScheduledActionEntry.TABLE_NAME + "(" + ScheduledActionEntry.COLUMN_UID + ")";
String createCommodityUidIndex = "CREATE UNIQUE INDEX '" + CommodityEntry.INDEX_UID
+ "' ON " + CommodityEntry.TABLE_NAME + "(" + CommodityEntry.COLUMN_UID + ")";
String createPriceUidIndex = "CREATE UNIQUE INDEX '" + PriceEntry.INDEX_UID
+ "' ON " + PriceEntry.TABLE_NAME + "(" + PriceEntry.COLUMN_UID + ")";
String createBudgetUidIndex = "CREATE UNIQUE INDEX '" + BudgetEntry.INDEX_UID
+ "' ON " + BudgetEntry.TABLE_NAME + "(" + BudgetEntry.COLUMN_UID + ")";
String createBudgetAmountUidIndex = "CREATE UNIQUE INDEX '" + BudgetAmountEntry.INDEX_UID
+ "' ON " + BudgetAmountEntry.TABLE_NAME + "(" + BudgetAmountEntry.COLUMN_UID + ")";
String createRecurrenceUidIndex = "CREATE UNIQUE INDEX '" + RecurrenceEntry.INDEX_UID
+ "' ON " + RecurrenceEntry.TABLE_NAME + "(" + RecurrenceEntry.COLUMN_UID + ")";
db.execSQL(createAccountUidIndex);
db.execSQL(createTransactionUidIndex);
db.execSQL(createSplitUidIndex);
db.execSQL(createScheduledEventUidIndex);
db.execSQL(createCommodityUidIndex);
db.execSQL(createPriceUidIndex);
db.execSQL(createBudgetUidIndex);
db.execSQL(createRecurrenceUidIndex);
db.execSQL(createBudgetAmountUidIndex);
try {
MigrationHelper.importCommodities(db);
} catch (SAXException | ParserConfigurationException | IOException e) {
Log.e(LOG_TAG, "Error loading currencies into the database");
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
| 21,870 | 58.594005 | 194 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/DatabaseSchema.java
|
/*
* Copyright (c) 2014 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db;
import android.provider.BaseColumns;
/**
* Holds the database schema
*
* @author Ngewi Fet <[email protected]>
*/
public class DatabaseSchema {
/**
* Name of database storing information about the books in the application
*/
public static final String BOOK_DATABASE_NAME = "gnucash_books.db";
/**
* Version number of database containing information about the books in the application
*/
public static final int BOOK_DATABASE_VERSION = 1;
/**
* Version number of database containing accounts and transactions info.
* With any change to the database schema, this number must increase
*/
public static final int DATABASE_VERSION = 15;
/**
* Name of the database
* <p>This was used when the application had only one database per instance.
* Now there can be multiple databases for each book imported
* </p>
* @deprecated Each database uses the GUID of the root account as name
*/
@Deprecated
public static final String LEGACY_DATABASE_NAME = "gnucash_db";
//no instances are to be instantiated
private DatabaseSchema(){}
public interface CommonColumns extends BaseColumns {
public static final String COLUMN_UID = "uid";
public static final String COLUMN_CREATED_AT = "created_at";
public static final String COLUMN_MODIFIED_AT = "modified_at";
}
public static abstract class BookEntry implements CommonColumns {
public static final String TABLE_NAME = "books";
public static final String COLUMN_DISPLAY_NAME = "name";
public static final String COLUMN_SOURCE_URI = "uri";
public static final String COLUMN_ROOT_GUID = "root_account_guid";
public static final String COLUMN_TEMPLATE_GUID = "root_template_guid";
public static final String COLUMN_ACTIVE = "is_active";
public static final String COLUMN_LAST_SYNC = "last_export_time";
}
/**
* Columns for the account tables
*/
public static abstract class AccountEntry implements CommonColumns {
public static final String TABLE_NAME = "accounts";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_CURRENCY = "currency_code";
public static final String COLUMN_COMMODITY_UID = "commodity_uid";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_PARENT_ACCOUNT_UID = "parent_account_uid";
public static final String COLUMN_PLACEHOLDER = "is_placeholder";
public static final String COLUMN_COLOR_CODE = "color_code";
public static final String COLUMN_FAVORITE = "favorite";
public static final String COLUMN_FULL_NAME = "full_name";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_HIDDEN = "is_hidden";
public static final String COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID = "default_transfer_account_uid";
public static final String INDEX_UID = "account_uid_index";
}
/**
* Column schema for the transaction table in the database
*/
public static abstract class TransactionEntry implements CommonColumns {
public static final String TABLE_NAME = "transactions";
//The actual names of columns for description and notes are unlike the variable names because of legacy
//We will not change them now for backwards compatibility reasons. But the variable names make sense
public static final String COLUMN_DESCRIPTION = "name";
public static final String COLUMN_NOTES = "description";
public static final String COLUMN_CURRENCY = "currency_code";
public static final String COLUMN_COMMODITY_UID = "commodity_uid";
public static final String COLUMN_TIMESTAMP = "timestamp";
/**
* Flag for marking transactions which have been exported
* @deprecated Transactions are exported based on last modified timestamp
*/
@Deprecated
public static final String COLUMN_EXPORTED = "is_exported";
public static final String COLUMN_TEMPLATE = "is_template";
public static final String COLUMN_SCHEDX_ACTION_UID = "scheduled_action_uid";
public static final String INDEX_UID = "transaction_uid_index";
}
/**
* Column schema for the splits table in the database
*/
public static abstract class SplitEntry implements CommonColumns {
public static final String TABLE_NAME = "splits";
public static final String COLUMN_TYPE = "type";
/**
* The value columns are in the currency of the transaction containing the split
*/
public static final String COLUMN_VALUE_NUM = "value_num";
public static final String COLUMN_VALUE_DENOM = "value_denom";
/**
* The quantity columns are in the currency of the account to which the split belongs
*/
public static final String COLUMN_QUANTITY_NUM = "quantity_num";
public static final String COLUMN_QUANTITY_DENOM = "quantity_denom";
public static final String COLUMN_MEMO = "memo";
public static final String COLUMN_ACCOUNT_UID = "account_uid";
public static final String COLUMN_TRANSACTION_UID = "transaction_uid";
public static final String COLUMN_RECONCILE_STATE = "reconcile_state";
public static final String COLUMN_RECONCILE_DATE = "reconcile_date";
public static final String INDEX_UID = "split_uid_index";
}
public static abstract class ScheduledActionEntry implements CommonColumns {
public static final String TABLE_NAME = "scheduled_actions";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_ACTION_UID = "action_uid";
public static final String COLUMN_START_TIME = "start_time";
public static final String COLUMN_END_TIME = "end_time";
public static final String COLUMN_LAST_RUN = "last_run";
/**
* Tag for scheduledAction-specific information e.g. backup parameters for backup
*/
public static final String COLUMN_TAG = "tag";
public static final String COLUMN_ENABLED = "is_enabled";
public static final String COLUMN_TOTAL_FREQUENCY = "total_frequency";
/**
* Number of times this scheduledAction has been run. Analogous to instance_count in GnuCash desktop SQL
*/
public static final String COLUMN_EXECUTION_COUNT = "execution_count";
public static final String COLUMN_RECURRENCE_UID = "recurrence_uid";
public static final String COLUMN_AUTO_CREATE = "auto_create";
public static final String COLUMN_AUTO_NOTIFY = "auto_notify";
public static final String COLUMN_ADVANCE_CREATION = "adv_creation";
public static final String COLUMN_ADVANCE_NOTIFY = "adv_notify";
public static final String COLUMN_TEMPLATE_ACCT_UID = "template_act_uid";
public static final String INDEX_UID = "scheduled_action_uid_index";
}
public static abstract class CommodityEntry implements CommonColumns {
public static final String TABLE_NAME = "commodities";
/**
* The namespace field denotes the namespace for this commodity,
* either a currency or symbol from a quote source
*/
public static final String COLUMN_NAMESPACE = "namespace";
/**
* The fullname is the official full name of the currency
*/
public static final String COLUMN_FULLNAME = "fullname";
/**
* The mnemonic is the official abbreviated designation for the currency
*/
public static final String COLUMN_MNEMONIC = "mnemonic";
public static final String COLUMN_LOCAL_SYMBOL = "local_symbol";
/**
* The fraction is the number of sub-units that the basic commodity can be divided into
*/
public static final String COLUMN_SMALLEST_FRACTION = "fraction";
/**
* A CUSIP is a nine-character alphanumeric code that identifies a North American financial security
* for the purposes of facilitating clearing and settlement of trades
*/
public static final String COLUMN_CUSIP = "cusip";
/**
* TRUE if prices are to be downloaded for this commodity from a quote source
*/
public static final String COLUMN_QUOTE_FLAG = "quote_flag";
public static final String INDEX_UID = "commodities_uid_index";
}
public static abstract class PriceEntry implements CommonColumns {
public static final String TABLE_NAME = "prices";
public static final String COLUMN_COMMODITY_UID = "commodity_guid";
public static final String COLUMN_CURRENCY_UID = "currency_guid";
public static final String COLUMN_DATE = "date";
public static final String COLUMN_SOURCE = "source";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_VALUE_NUM = "value_num";
public static final String COLUMN_VALUE_DENOM = "value_denom";
public static final String INDEX_UID = "prices_uid_index";
}
public static abstract class BudgetEntry implements CommonColumns {
public static final String TABLE_NAME = "budgets";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_NUM_PERIODS = "num_periods";
public static final String COLUMN_RECURRENCE_UID = "recurrence_uid";
public static final String INDEX_UID = "budgets_uid_index";
}
public static abstract class BudgetAmountEntry implements CommonColumns {
public static final String TABLE_NAME = "budget_amounts";
public static final String COLUMN_BUDGET_UID = "budget_uid";
public static final String COLUMN_ACCOUNT_UID = "account_uid";
public static final String COLUMN_PERIOD_NUM = "period_num";
public static final String COLUMN_AMOUNT_NUM = "amount_num";
public static final String COLUMN_AMOUNT_DENOM = "amount_denom";
public static final String INDEX_UID = "budget_amounts_uid_index";
}
public static abstract class RecurrenceEntry implements CommonColumns {
public static final String TABLE_NAME = "recurrences";
public static final String COLUMN_MULTIPLIER = "recurrence_mult";
public static final String COLUMN_PERIOD_TYPE = "recurrence_period_type";
public static final String COLUMN_PERIOD_START = "recurrence_period_start";
public static final String COLUMN_PERIOD_END = "recurrence_period_end";
public static final String COLUMN_BYDAY = "recurrence_byday";
public static final String INDEX_UID = "recurrence_uid_index";
}
}
| 12,342 | 43.399281 | 112 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/MigrationHelper.java
|
/*
* Copyright (c) 2014 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.support.v7.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.export.ExportFormat;
import org.gnucash.android.export.ExportParams;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.importer.CommoditiesXmlHandler;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.BaseModel;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Recurrence;
import org.gnucash.android.model.ScheduledAction;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.service.ScheduledActionService;
import org.gnucash.android.util.PreferencesHelper;
import org.gnucash.android.util.TimestampHelper;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.channels.FileChannel;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import static org.gnucash.android.db.DatabaseSchema.AccountEntry;
import static org.gnucash.android.db.DatabaseSchema.BudgetAmountEntry;
import static org.gnucash.android.db.DatabaseSchema.BudgetEntry;
import static org.gnucash.android.db.DatabaseSchema.CommodityEntry;
import static org.gnucash.android.db.DatabaseSchema.CommonColumns;
import static org.gnucash.android.db.DatabaseSchema.PriceEntry;
import static org.gnucash.android.db.DatabaseSchema.RecurrenceEntry;
import static org.gnucash.android.db.DatabaseSchema.ScheduledActionEntry;
import static org.gnucash.android.db.DatabaseSchema.SplitEntry;
import static org.gnucash.android.db.DatabaseSchema.TransactionEntry;
/**
* Collection of helper methods which are used during database migrations
*
* @author Ngewi Fet <[email protected]>
*/
@SuppressWarnings("unused")
public class MigrationHelper {
public static final String LOG_TAG = "MigrationHelper";
/**
* Performs same function as {@link AccountsDbAdapter#getFullyQualifiedAccountName(String)}
* <p>This method is only necessary because we cannot open the database again (by instantiating {@link AccountsDbAdapter}
* while it is locked for upgrades. So we re-implement the method here.</p>
* @param db SQLite database
* @param accountUID Unique ID of account whose fully qualified name is to be determined
* @return Fully qualified (colon-separated) account name
* @see AccountsDbAdapter#getFullyQualifiedAccountName(String)
*/
static String getFullyQualifiedAccountName(SQLiteDatabase db, String accountUID){
//get the parent account UID of the account
Cursor cursor = db.query(AccountEntry.TABLE_NAME,
new String[] {AccountEntry.COLUMN_PARENT_ACCOUNT_UID},
AccountEntry.COLUMN_UID + " = ?",
new String[]{accountUID},
null, null, null, null);
String parentAccountUID = null;
if (cursor != null && cursor.moveToFirst()){
parentAccountUID = cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_PARENT_ACCOUNT_UID));
cursor.close();
}
//get the name of the account
cursor = db.query(AccountEntry.TABLE_NAME,
new String[]{AccountEntry.COLUMN_NAME},
AccountEntry.COLUMN_UID + " = ?",
new String[]{accountUID}, null, null, null);
String accountName = null;
if (cursor != null && cursor.moveToFirst()){
accountName = cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_NAME));
cursor.close();
}
String gnucashRootAccountUID = getGnuCashRootAccountUID(db);
if (parentAccountUID == null || accountName == null
|| parentAccountUID.equalsIgnoreCase(gnucashRootAccountUID)){
return accountName;
}
String parentAccountName = getFullyQualifiedAccountName(db, parentAccountUID);
return parentAccountName + AccountsDbAdapter.ACCOUNT_NAME_SEPARATOR + accountName;
}
/**
* Returns the GnuCash ROOT account UID.
* <p>In GnuCash desktop account structure, there is a root account (which is not visible in the UI) from which
* other top level accounts derive. GnuCash Android does not have this ROOT account by default unless the account
* structure was imported from GnuCash for desktop. Hence this method also returns <code>null</code> as an
* acceptable result.</p>
* <p><b>Note:</b> NULL is an acceptable response, be sure to check for it</p>
* @return Unique ID of the GnuCash root account.
*/
private static String getGnuCashRootAccountUID(SQLiteDatabase db){
String condition = AccountEntry.COLUMN_TYPE + "= '" + AccountType.ROOT.name() + "'";
Cursor cursor = db.query(AccountEntry.TABLE_NAME,
null, condition, null, null, null,
AccountEntry.COLUMN_NAME + " ASC");
String rootUID = null;
if (cursor != null && cursor.moveToFirst()){
rootUID = cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_UID));
cursor.close();
}
return rootUID;
}
/**
* Copies the contents of the file in {@code src} to {@code dst} and then deletes the {@code src} if copy was successful.
* If the file copy was unsuccessful, the src file will not be deleted.
* @param src Source file
* @param dst Destination file
* @throws IOException if an error occurred during the file copy
*/
static void moveFile(File src, File dst) throws IOException {
Log.d(LOG_TAG, String.format(Locale.US, "Moving %s from %s to %s",
src.getName(), src.getParent(), dst.getParent()));
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
long bytesCopied = inChannel.transferTo(0, inChannel.size(), outChannel);
if(bytesCopied >= src.length()) {
boolean result = src.delete();
String msg = result ? "Deleted src file: " : "Could not delete src: ";
Log.d(LOG_TAG, msg + src.getPath());
}
} finally {
if (inChannel != null)
inChannel.close();
outChannel.close();
}
}
/**
* Runnable which moves all exported files (exports and backups) from the old SD card location which
* was generic to the new folder structure which uses the application ID as folder name.
* <p>The new folder structure also futher enables parallel installation of multiple flavours of
* the program (like development and production) on the same device.</p>
*/
static final Runnable moveExportedFilesToNewDefaultLocation = new Runnable() {
@Override
public void run() {
File oldExportFolder = new File(Environment.getExternalStorageDirectory() + "/gnucash");
if (oldExportFolder.exists()){
for (File src : oldExportFolder.listFiles()) {
if (src.isDirectory())
continue;
File dst = new File(Exporter.LEGACY_BASE_FOLDER_PATH + "/exports/" + src.getName());
try {
MigrationHelper.moveFile(src, dst);
} catch (IOException e) {
Log.e(LOG_TAG, "Error migrating " + src.getName());
Crashlytics.logException(e);
}
}
} else {
//if the base folder does not exist, no point going one level deeper
return;
}
File oldBackupFolder = new File(oldExportFolder, "backup");
if (oldBackupFolder.exists()){
for (File src : new File(oldExportFolder, "backup").listFiles()) {
File dst = new File(Exporter.LEGACY_BASE_FOLDER_PATH + "/backups/" + src.getName());
try {
MigrationHelper.moveFile(src, dst);
} catch (IOException e) {
Log.e(LOG_TAG, "Error migrating backup: " + src.getName());
Crashlytics.logException(e);
}
}
}
if (oldBackupFolder.delete())
oldExportFolder.delete();
}
};
/**
* Imports commodities into the database from XML resource file
*/
static void importCommodities(SQLiteDatabase db) throws SAXException, ParserConfigurationException, IOException {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
InputStream commoditiesInputStream = GnuCashApplication.getAppContext().getResources()
.openRawResource(R.raw.iso_4217_currencies);
BufferedInputStream bos = new BufferedInputStream(commoditiesInputStream);
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
CommoditiesXmlHandler handler = new CommoditiesXmlHandler(db);
xr.setContentHandler(handler);
xr.parse(new InputSource(bos));
}
/**
* Upgrades the database from version 1 to 2
* @param db SQLiteDatabase
* @return Version number: 2 if upgrade successful, 1 otherwise
*/
public static int upgradeDbToVersion2(SQLiteDatabase db) {
int oldVersion;
String addColumnSql = "ALTER TABLE " + TransactionEntry.TABLE_NAME +
" ADD COLUMN double_account_uid varchar(255)";
//introducing sub accounts
Log.i(DatabaseHelper.LOG_TAG, "Adding column for parent accounts");
String addParentAccountSql = "ALTER TABLE " + AccountEntry.TABLE_NAME +
" ADD COLUMN " + AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " varchar(255)";
db.execSQL(addColumnSql);
db.execSQL(addParentAccountSql);
//update account types to GnuCash account types
//since all were previously CHECKING, now all will be CASH
Log.i(DatabaseHelper.LOG_TAG, "Converting account types to GnuCash compatible types");
ContentValues cv = new ContentValues();
cv.put(SplitEntry.COLUMN_TYPE, AccountType.CASH.toString());
db.update(AccountEntry.TABLE_NAME, cv, null, null);
oldVersion = 2;
return oldVersion;
}
/**
* Upgrades the database from version 2 to 3
* @param db SQLiteDatabase to upgrade
* @return Version number: 3 if upgrade successful, 2 otherwise
*/
static int upgradeDbToVersion3(SQLiteDatabase db) {
int oldVersion;
String addPlaceHolderAccountFlagSql = "ALTER TABLE " + AccountEntry.TABLE_NAME +
" ADD COLUMN " + AccountEntry.COLUMN_PLACEHOLDER + " tinyint default 0";
db.execSQL(addPlaceHolderAccountFlagSql);
oldVersion = 3;
return oldVersion;
}
/**
* Upgrades the database from version 3 to 4
* @param db SQLiteDatabase
* @return Version number: 4 if upgrade successful, 3 otherwise
*/
static int upgradeDbToVersion4(SQLiteDatabase db) {
int oldVersion;
String addRecurrencePeriod = "ALTER TABLE " + TransactionEntry.TABLE_NAME +
" ADD COLUMN recurrence_period integer default 0";
String addDefaultTransferAccount = "ALTER TABLE " + AccountEntry.TABLE_NAME
+ " ADD COLUMN " + AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID + " varchar(255)";
String addAccountColor = " ALTER TABLE " + AccountEntry.TABLE_NAME
+ " ADD COLUMN " + AccountEntry.COLUMN_COLOR_CODE + " varchar(255)";
db.execSQL(addRecurrencePeriod);
db.execSQL(addDefaultTransferAccount);
db.execSQL(addAccountColor);
oldVersion = 4;
return oldVersion;
}
/**
* Upgrades the database from version 4 to 5
* <p>Adds favorites column to accounts</p>
* @param db SQLiteDatabase
* @return Version number: 5 if upgrade successful, 4 otherwise
*/
static int upgradeDbToVersion5(SQLiteDatabase db) {
int oldVersion;
String addAccountFavorite = " ALTER TABLE " + AccountEntry.TABLE_NAME
+ " ADD COLUMN " + AccountEntry.COLUMN_FAVORITE + " tinyint default 0";
db.execSQL(addAccountFavorite);
oldVersion = 5;
return oldVersion;
}
/**
* Upgrades the database from version 5 to version 6.<br>
* This migration adds support for fully qualified account names and updates existing accounts.
* @param db SQLite Database to be upgraded
* @return New database version (6) if upgrade successful, old version (5) if unsuccessful
*/
static int upgradeDbToVersion6(SQLiteDatabase db) {
int oldVersion = 5;
String addFullAccountNameQuery = " ALTER TABLE " + AccountEntry.TABLE_NAME
+ " ADD COLUMN " + AccountEntry.COLUMN_FULL_NAME + " varchar(255) ";
db.execSQL(addFullAccountNameQuery);
//update all existing accounts with their fully qualified name
Cursor cursor = db.query(AccountEntry.TABLE_NAME,
new String[]{AccountEntry._ID, AccountEntry.COLUMN_UID},
null, null, null, null, null);
while(cursor != null && cursor.moveToNext()){
String uid = cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_UID));
String fullName = getFullyQualifiedAccountName(db, uid);
if (fullName == null)
continue;
ContentValues contentValues = new ContentValues();
contentValues.put(AccountEntry.COLUMN_FULL_NAME, fullName);
long id = cursor.getLong(cursor.getColumnIndexOrThrow(AccountEntry._ID));
db.update(AccountEntry.TABLE_NAME, contentValues, AccountEntry._ID + " = " + id, null);
}
if (cursor != null) {
cursor.close();
}
oldVersion = 6;
return oldVersion;
}
/**
* Code for upgrading the database to version 7 from version 6.<br>
* Tasks accomplished in migration:
* <ul>
* <li>Added new splits table for transaction splits</li>
* <li>Extract existing info from transactions table to populate split table</li>
* </ul>
* @param db SQLite Database
* @return The new database version if upgrade was successful, or the old db version if it failed
*/
static int upgradeDbToVersion7(SQLiteDatabase db) {
int oldVersion = 6;
db.beginTransaction();
try {
// backup transaction table
db.execSQL("ALTER TABLE " + TransactionEntry.TABLE_NAME + " RENAME TO " + TransactionEntry.TABLE_NAME + "_bak");
// create new transaction table
db.execSQL("create table " + TransactionEntry.TABLE_NAME + " ("
+ TransactionEntry._ID + " integer primary key autoincrement, "
+ TransactionEntry.COLUMN_UID + " varchar(255) not null, "
+ TransactionEntry.COLUMN_DESCRIPTION + " varchar(255), "
+ TransactionEntry.COLUMN_NOTES + " text, "
+ TransactionEntry.COLUMN_TIMESTAMP + " integer not null, "
+ TransactionEntry.COLUMN_EXPORTED + " tinyint default 0, "
+ TransactionEntry.COLUMN_CURRENCY + " varchar(255) not null, "
+ "recurrence_period integer default 0, "
+ "UNIQUE (" + TransactionEntry.COLUMN_UID + ") "
+ ");");
// initialize new transaction table wiht data from old table
db.execSQL("INSERT INTO " + TransactionEntry.TABLE_NAME + " ( "
+ TransactionEntry._ID + " , "
+ TransactionEntry.COLUMN_UID + " , "
+ TransactionEntry.COLUMN_DESCRIPTION + " , "
+ TransactionEntry.COLUMN_NOTES + " , "
+ TransactionEntry.COLUMN_TIMESTAMP + " , "
+ TransactionEntry.COLUMN_EXPORTED + " , "
+ TransactionEntry.COLUMN_CURRENCY + " , "
+ "recurrence_period ) SELECT "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry._ID + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_UID + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_DESCRIPTION + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_NOTES + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_TIMESTAMP + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_EXPORTED + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_CURRENCY + " , "
+ TransactionEntry.TABLE_NAME + "_bak.recurrence_period"
+ " FROM " + TransactionEntry.TABLE_NAME + "_bak , " + AccountEntry.TABLE_NAME
+ " ON " + TransactionEntry.TABLE_NAME + "_bak.account_uid == " + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_UID
);
// create split table
db.execSQL("CREATE TABLE " + SplitEntry.TABLE_NAME + " ("
+ SplitEntry._ID + " integer primary key autoincrement, "
+ SplitEntry.COLUMN_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_MEMO + " text, "
+ SplitEntry.COLUMN_TYPE + " varchar(255) not null, "
+ "amount" + " varchar(255) not null, "
+ SplitEntry.COLUMN_ACCOUNT_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_TRANSACTION_UID + " varchar(255) not null, "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_ACCOUNT_UID + ") REFERENCES " + AccountEntry.TABLE_NAME + " (" + AccountEntry.COLUMN_UID + "), "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_TRANSACTION_UID + ") REFERENCES " + TransactionEntry.TABLE_NAME + " (" + TransactionEntry.COLUMN_UID + "), "
+ "UNIQUE (" + SplitEntry.COLUMN_UID + ") "
+ ");");
// Initialize split table with data from backup transaction table
// New split table is initialized after the new transaction table as the
// foreign key constraint will stop any data from being inserted
// If new split table is created before the backup is made, the foreign key
// constraint will be rewritten to refer to the backup transaction table
db.execSQL("INSERT INTO " + SplitEntry.TABLE_NAME + " ( "
+ SplitEntry.COLUMN_UID + " , "
+ SplitEntry.COLUMN_TYPE + " , "
+ "amount" + " , "
+ SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.COLUMN_TRANSACTION_UID + " ) SELECT "
+ "LOWER(HEX(RANDOMBLOB(16))) , "
+ "CASE WHEN " + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_TYPE + " IN ( 'CASH' , 'BANK', 'ASSET', 'EXPENSE', 'RECEIVABLE', 'STOCK', 'MUTUAL' ) THEN CASE WHEN "
+ "amount" + " < 0 THEN 'CREDIT' ELSE 'DEBIT' END ELSE CASE WHEN "
+ "amount" + " < 0 THEN 'DEBIT' ELSE 'CREDIT' END END , "
+ "ABS ( " + TransactionEntry.TABLE_NAME + "_bak.amount ) , "
+ TransactionEntry.TABLE_NAME + "_bak.account_uid , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_UID
+ " FROM " + TransactionEntry.TABLE_NAME + "_bak , " + AccountEntry.TABLE_NAME
+ " ON " + TransactionEntry.TABLE_NAME + "_bak.account_uid = " + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_UID
+ " UNION SELECT "
+ "LOWER(HEX(RANDOMBLOB(16))) AS " + SplitEntry.COLUMN_UID + " , "
+ "CASE WHEN " + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_TYPE + " IN ( 'CASH' , 'BANK', 'ASSET', 'EXPENSE', 'RECEIVABLE', 'STOCK', 'MUTUAL' ) THEN CASE WHEN "
+ "amount" + " < 0 THEN 'DEBIT' ELSE 'CREDIT' END ELSE CASE WHEN "
+ "amount" + " < 0 THEN 'CREDIT' ELSE 'DEBIT' END END , "
+ "ABS ( " + TransactionEntry.TABLE_NAME + "_bak.amount ) , "
+ TransactionEntry.TABLE_NAME + "_bak.double_account_uid , "
+ TransactionEntry.TABLE_NAME + "_baK." + TransactionEntry.COLUMN_UID
+ " FROM " + TransactionEntry.TABLE_NAME + "_bak , " + AccountEntry.TABLE_NAME
+ " ON " + TransactionEntry.TABLE_NAME + "_bak.account_uid = " + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_UID
+ " WHERE " + TransactionEntry.TABLE_NAME + "_bak.double_account_uid IS NOT NULL"
);
// drop backup transaction table
db.execSQL("DROP TABLE " + TransactionEntry.TABLE_NAME + "_bak");
db.setTransactionSuccessful();
oldVersion = 7;
} finally {
db.endTransaction();
}
return oldVersion;
}
/**
* Upgrades the database from version 7 to version 8.
* <p>This migration accomplishes the following:
* <ul>
* <li>Added created_at and modified_at columns to all tables (including triggers for updating the columns).</li>
* <li>New table for scheduled actions and migrate all existing recurring transactions</li>
* <li>Auto-balancing of all existing splits</li>
* <li>Added "hidden" flag to accounts table</li>
* <li>Add flag for transaction templates</li>
* </ul>
* </p>
* @param db SQLite Database to be upgraded
* @return New database version (8) if upgrade successful, old version (7) if unsuccessful
*/
static int upgradeDbToVersion8(SQLiteDatabase db) {
Log.i(DatabaseHelper.LOG_TAG, "Upgrading database to version 8");
int oldVersion = 7;
new File(Exporter.LEGACY_BASE_FOLDER_PATH + "/backups/").mkdirs();
new File(Exporter.LEGACY_BASE_FOLDER_PATH + "/exports/").mkdirs();
//start moving the files in background thread before we do the database stuff
new Thread(moveExportedFilesToNewDefaultLocation).start();
db.beginTransaction();
try {
Log.i(DatabaseHelper.LOG_TAG, "Creating scheduled actions table");
db.execSQL("CREATE TABLE " + ScheduledActionEntry.TABLE_NAME + " ("
+ ScheduledActionEntry._ID + " integer primary key autoincrement, "
+ ScheduledActionEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ ScheduledActionEntry.COLUMN_ACTION_UID + " varchar(255) not null, "
+ ScheduledActionEntry.COLUMN_TYPE + " varchar(255) not null, "
+ "period " + " integer not null, "
+ ScheduledActionEntry.COLUMN_LAST_RUN + " integer default 0, "
+ ScheduledActionEntry.COLUMN_START_TIME + " integer not null, "
+ ScheduledActionEntry.COLUMN_END_TIME + " integer default 0, "
+ ScheduledActionEntry.COLUMN_TAG + " text, "
+ ScheduledActionEntry.COLUMN_ENABLED + " tinyint default 1, " //enabled by default
+ ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY + " integer default 0, "
+ ScheduledActionEntry.COLUMN_EXECUTION_COUNT+ " integer default 0, "
+ ScheduledActionEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ ScheduledActionEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(ScheduledActionEntry.TABLE_NAME));
//==============================BEGIN TABLE MIGRATIONS ========================================
Log.i(DatabaseHelper.LOG_TAG, "Migrating accounts table");
// backup transaction table
db.execSQL("ALTER TABLE " + AccountEntry.TABLE_NAME + " RENAME TO " + AccountEntry.TABLE_NAME + "_bak");
// create new transaction table
db.execSQL("CREATE TABLE " + AccountEntry.TABLE_NAME + " ("
+ AccountEntry._ID + " integer primary key autoincrement, "
+ AccountEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ AccountEntry.COLUMN_NAME + " varchar(255) not null, "
+ AccountEntry.COLUMN_TYPE + " varchar(255) not null, "
+ AccountEntry.COLUMN_CURRENCY + " varchar(255) not null, "
+ AccountEntry.COLUMN_DESCRIPTION + " varchar(255), "
+ AccountEntry.COLUMN_COLOR_CODE + " varchar(255), "
+ AccountEntry.COLUMN_FAVORITE + " tinyint default 0, "
+ AccountEntry.COLUMN_HIDDEN + " tinyint default 0, "
+ AccountEntry.COLUMN_FULL_NAME + " varchar(255), "
+ AccountEntry.COLUMN_PLACEHOLDER + " tinyint default 0, "
+ AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " varchar(255), "
+ AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID + " varchar(255), "
+ AccountEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ AccountEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(AccountEntry.TABLE_NAME));
// initialize new account table with data from old table
db.execSQL("INSERT INTO " + AccountEntry.TABLE_NAME + " ( "
+ AccountEntry._ID + ","
+ AccountEntry.COLUMN_UID + " , "
+ AccountEntry.COLUMN_NAME + " , "
+ AccountEntry.COLUMN_TYPE + " , "
+ AccountEntry.COLUMN_CURRENCY + " , "
+ AccountEntry.COLUMN_COLOR_CODE + " , "
+ AccountEntry.COLUMN_FAVORITE + " , "
+ AccountEntry.COLUMN_FULL_NAME + " , "
+ AccountEntry.COLUMN_PLACEHOLDER + " , "
+ AccountEntry.COLUMN_HIDDEN + " , "
+ AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " , "
+ AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID
+ ") SELECT "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry._ID + " , "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_UID + " , "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_NAME + " , "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_TYPE + " , "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_CURRENCY + " , "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_COLOR_CODE + " , "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_FAVORITE + " , "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_FULL_NAME + " , "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_PLACEHOLDER + " , "
+ " CASE WHEN " + AccountEntry.TABLE_NAME + "_bak.type = 'ROOT' THEN 1 ELSE 0 END, "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " , "
+ AccountEntry.TABLE_NAME + "_bak." + AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID
+ " FROM " + AccountEntry.TABLE_NAME + "_bak;"
);
Log.i(DatabaseHelper.LOG_TAG, "Migrating transactions table");
// backup transaction table
db.execSQL("ALTER TABLE " + TransactionEntry.TABLE_NAME + " RENAME TO " + TransactionEntry.TABLE_NAME + "_bak");
// create new transaction table
db.execSQL("CREATE TABLE " + TransactionEntry.TABLE_NAME + " ("
+ TransactionEntry._ID + " integer primary key autoincrement, "
+ TransactionEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ TransactionEntry.COLUMN_DESCRIPTION + " varchar(255), "
+ TransactionEntry.COLUMN_NOTES + " text, "
+ TransactionEntry.COLUMN_TIMESTAMP + " integer not null, "
+ TransactionEntry.COLUMN_EXPORTED + " tinyint default 0, "
+ TransactionEntry.COLUMN_TEMPLATE + " tinyint default 0, "
+ TransactionEntry.COLUMN_CURRENCY + " varchar(255) not null, "
+ TransactionEntry.COLUMN_SCHEDX_ACTION_UID + " varchar(255), "
+ TransactionEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ TransactionEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + TransactionEntry.COLUMN_SCHEDX_ACTION_UID + ") REFERENCES " + ScheduledActionEntry.TABLE_NAME + " (" + ScheduledActionEntry.COLUMN_UID + ") ON DELETE SET NULL "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(TransactionEntry.TABLE_NAME));
// initialize new transaction table with data from old table
db.execSQL("INSERT INTO " + TransactionEntry.TABLE_NAME + " ( "
+ TransactionEntry._ID + " , "
+ TransactionEntry.COLUMN_UID + " , "
+ TransactionEntry.COLUMN_DESCRIPTION + " , "
+ TransactionEntry.COLUMN_NOTES + " , "
+ TransactionEntry.COLUMN_TIMESTAMP + " , "
+ TransactionEntry.COLUMN_EXPORTED + " , "
+ TransactionEntry.COLUMN_CURRENCY + " , "
+ TransactionEntry.COLUMN_TEMPLATE
+ ") SELECT "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry._ID + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_UID + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_DESCRIPTION + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_NOTES + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_TIMESTAMP + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_EXPORTED + " , "
+ TransactionEntry.TABLE_NAME + "_bak." + TransactionEntry.COLUMN_CURRENCY + " , "
+ " CASE WHEN " + TransactionEntry.TABLE_NAME + "_bak.recurrence_period > 0 THEN 1 ELSE 0 END "
+ " FROM " + TransactionEntry.TABLE_NAME + "_bak;"
);
Log.i(DatabaseHelper.LOG_TAG, "Migrating splits table");
// backup split table
db.execSQL("ALTER TABLE " + SplitEntry.TABLE_NAME + " RENAME TO " + SplitEntry.TABLE_NAME + "_bak");
// create new split table
db.execSQL("CREATE TABLE " + SplitEntry.TABLE_NAME + " ("
+ SplitEntry._ID + " integer primary key autoincrement, "
+ SplitEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ SplitEntry.COLUMN_MEMO + " text, "
+ SplitEntry.COLUMN_TYPE + " varchar(255) not null, "
+ "amount" + " varchar(255) not null, "
+ SplitEntry.COLUMN_ACCOUNT_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_TRANSACTION_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ SplitEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_ACCOUNT_UID + ") REFERENCES " + AccountEntry.TABLE_NAME + " (" + AccountEntry.COLUMN_UID + ") ON DELETE CASCADE, "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_TRANSACTION_UID + ") REFERENCES " + TransactionEntry.TABLE_NAME + " (" + TransactionEntry.COLUMN_UID + ") ON DELETE CASCADE "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(SplitEntry.TABLE_NAME));
// initialize new split table with data from old table
db.execSQL("INSERT INTO " + SplitEntry.TABLE_NAME + " ( "
+ SplitEntry._ID + " , "
+ SplitEntry.COLUMN_UID + " , "
+ SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.COLUMN_TYPE + " , "
+ "amount" + " , "
+ SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.COLUMN_TRANSACTION_UID
+ ") SELECT "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry._ID + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_UID + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.TABLE_NAME + "_bak." + "amount" + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_TRANSACTION_UID
+ " FROM " + SplitEntry.TABLE_NAME + "_bak;"
);
//================================ END TABLE MIGRATIONS ================================
// String timestamp to be used for all new created entities in migration
String timestamp = TimestampHelper.getUtcStringFromTimestamp(TimestampHelper.getTimestampFromNow());
//ScheduledActionDbAdapter scheduledActionDbAdapter = new ScheduledActionDbAdapter(db);
//SplitsDbAdapter splitsDbAdapter = new SplitsDbAdapter(db);
//TransactionsDbAdapter transactionsDbAdapter = new TransactionsDbAdapter(db, splitsDbAdapter);
//AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(db,transactionsDbAdapter);
Log.i(DatabaseHelper.LOG_TAG, "Creating default root account if none exists");
ContentValues contentValues = new ContentValues();
//assign a root account to all accounts which had null as parent except ROOT (top-level accounts)
String rootAccountUID;
Cursor cursor = db.query(AccountEntry.TABLE_NAME,
new String[]{AccountEntry.COLUMN_UID},
AccountEntry.COLUMN_TYPE + "= ?",
new String[]{AccountType.ROOT.name()}, null, null, null);
try {
if (cursor.moveToFirst()) {
rootAccountUID = cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_UID));
}
else
{
rootAccountUID = BaseModel.generateUID();
contentValues.clear();
contentValues.put(CommonColumns.COLUMN_UID, rootAccountUID);
contentValues.put(CommonColumns.COLUMN_CREATED_AT, timestamp);
contentValues.put(AccountEntry.COLUMN_NAME, "ROOT");
contentValues.put(AccountEntry.COLUMN_TYPE, "ROOT");
contentValues.put(AccountEntry.COLUMN_CURRENCY, Money.DEFAULT_CURRENCY_CODE);
contentValues.put(AccountEntry.COLUMN_PLACEHOLDER, 0);
contentValues.put(AccountEntry.COLUMN_HIDDEN, 1);
contentValues.putNull(AccountEntry.COLUMN_COLOR_CODE);
contentValues.put(AccountEntry.COLUMN_FAVORITE, 0);
contentValues.put(AccountEntry.COLUMN_FULL_NAME, " ");
contentValues.putNull(AccountEntry.COLUMN_PARENT_ACCOUNT_UID);
contentValues.putNull(AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID);
db.insert(AccountEntry.TABLE_NAME, null, contentValues);
}
} finally {
cursor.close();
}
//String rootAccountUID = accountsDbAdapter.getOrCreateGnuCashRootAccountUID();
contentValues.clear();
contentValues.put(AccountEntry.COLUMN_PARENT_ACCOUNT_UID, rootAccountUID);
db.update(AccountEntry.TABLE_NAME, contentValues, AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " IS NULL AND " + AccountEntry.COLUMN_TYPE + " != ?", new String[]{"ROOT"});
Log.i(DatabaseHelper.LOG_TAG, "Migrating existing recurring transactions");
cursor = db.query(TransactionEntry.TABLE_NAME + "_bak", null, "recurrence_period > 0", null, null, null, null);
long lastRun = System.currentTimeMillis();
while (cursor.moveToNext()){
contentValues.clear();
Timestamp timestampT = new Timestamp(cursor.getLong(cursor.getColumnIndexOrThrow(TransactionEntry.COLUMN_TIMESTAMP)));
contentValues.put(TransactionEntry.COLUMN_CREATED_AT, TimestampHelper.getUtcStringFromTimestamp(timestampT));
long transactionId = cursor.getLong(cursor.getColumnIndexOrThrow(TransactionEntry._ID));
db.update(TransactionEntry.TABLE_NAME, contentValues, TransactionEntry._ID + "=" + transactionId, null);
//ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION);
//scheduledAction.setActionUID(cursor.getString(cursor.getColumnIndexOrThrow(TransactionEntry.COLUMN_UID)));
//long period = cursor.getLong(cursor.getColumnIndexOrThrow("recurrence_period"));
//scheduledAction.setPeriod(period);
//scheduledAction.setStartTime(timestampT.getTime()); //the start time is when the transaction was created
//scheduledAction.setLastRun(System.currentTimeMillis()); //prevent this from being executed at the end of migration
contentValues.clear();
contentValues.put(CommonColumns.COLUMN_UID, BaseModel.generateUID());
contentValues.put(CommonColumns.COLUMN_CREATED_AT, timestamp);
contentValues.put(ScheduledActionEntry.COLUMN_ACTION_UID, cursor.getString(cursor.getColumnIndexOrThrow(TransactionEntry.COLUMN_UID)));
contentValues.put("period", cursor.getLong(cursor.getColumnIndexOrThrow("recurrence_period")));
contentValues.put(ScheduledActionEntry.COLUMN_START_TIME, timestampT.getTime());
contentValues.put(ScheduledActionEntry.COLUMN_END_TIME, 0);
contentValues.put(ScheduledActionEntry.COLUMN_LAST_RUN, lastRun);
contentValues.put(ScheduledActionEntry.COLUMN_TYPE, "TRANSACTION");
contentValues.put(ScheduledActionEntry.COLUMN_TAG, "");
contentValues.put(ScheduledActionEntry.COLUMN_ENABLED, 1);
contentValues.put(ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY, 0);
contentValues.put(ScheduledActionEntry.COLUMN_EXECUTION_COUNT, 0);
//scheduledActionDbAdapter.addRecord(scheduledAction);
db.insert(ScheduledActionEntry.TABLE_NAME, null, contentValues);
//build intent for recurring transactions in the database
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType(Transaction.MIME_TYPE);
//cancel existing pending intent
Context context = GnuCashApplication.getAppContext();
PendingIntent recurringPendingIntent = PendingIntent.getBroadcast(context,
(int)transactionId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(recurringPendingIntent);
}
cursor.close();
//auto-balance existing splits
Log.i(DatabaseHelper.LOG_TAG, "Auto-balancing existing transaction splits");
cursor = db.query(
TransactionEntry.TABLE_NAME + " , " + SplitEntry.TABLE_NAME + " ON "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + "=" + SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID
+ " , " + AccountEntry.TABLE_NAME + " ON "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_ACCOUNT_UID + "=" + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_UID,
new String[]{
TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " AS trans_uid",
TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_CURRENCY + " AS trans_currency",
"TOTAL ( CASE WHEN " +
SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TYPE + " = 'DEBIT' THEN " +
SplitEntry.TABLE_NAME + "." + "amount" + " ELSE - " +
SplitEntry.TABLE_NAME + "." + "amount" + " END ) AS trans_acct_balance",
"COUNT ( DISTINCT " +
AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_CURRENCY +
" ) AS trans_currency_count"
},
TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TEMPLATE + " == 0",
null,
TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID,
"trans_acct_balance != 0 AND trans_currency_count = 1",
null);
try {
while (cursor.moveToNext()){
double imbalance = cursor.getDouble(cursor.getColumnIndexOrThrow("trans_acct_balance"));
BigDecimal decimalImbalance = BigDecimal.valueOf(imbalance).setScale(2, BigDecimal.ROUND_HALF_UP);
if (decimalImbalance.compareTo(BigDecimal.ZERO) != 0) {
String currencyCode = cursor.getString(cursor.getColumnIndexOrThrow("trans_currency"));
String imbalanceAccountName = GnuCashApplication.getAppContext().getString(R.string.imbalance_account_name) + "-" + currencyCode;
String imbalanceAccountUID;
Cursor c = db.query(AccountEntry.TABLE_NAME, new String[]{AccountEntry.COLUMN_UID},
AccountEntry.COLUMN_FULL_NAME + "= ?", new String[]{imbalanceAccountName},
null, null, null);
try {
if (c.moveToFirst()) {
imbalanceAccountUID = c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_UID));
}
else {
imbalanceAccountUID = BaseModel.generateUID();
contentValues.clear();
contentValues.put(CommonColumns.COLUMN_UID, imbalanceAccountUID);
contentValues.put(CommonColumns.COLUMN_CREATED_AT, timestamp);
contentValues.put(AccountEntry.COLUMN_NAME, imbalanceAccountName);
contentValues.put(AccountEntry.COLUMN_TYPE, "BANK");
contentValues.put(AccountEntry.COLUMN_CURRENCY, currencyCode);
contentValues.put(AccountEntry.COLUMN_PLACEHOLDER, 0);
contentValues.put(AccountEntry.COLUMN_HIDDEN, GnuCashApplication.isDoubleEntryEnabled() ? 0 : 1);
contentValues.putNull(AccountEntry.COLUMN_COLOR_CODE);
contentValues.put(AccountEntry.COLUMN_FAVORITE, 0);
contentValues.put(AccountEntry.COLUMN_FULL_NAME, imbalanceAccountName);
contentValues.put(AccountEntry.COLUMN_PARENT_ACCOUNT_UID, rootAccountUID);
contentValues.putNull(AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID);
db.insert(AccountEntry.TABLE_NAME, null, contentValues);
}
} finally {
c.close();
}
String TransactionUID = cursor.getString(cursor.getColumnIndexOrThrow("trans_uid"));
contentValues.clear();
contentValues.put(CommonColumns.COLUMN_UID, BaseModel.generateUID());
contentValues.put(CommonColumns.COLUMN_CREATED_AT, timestamp);
contentValues.put("amount", decimalImbalance.abs().toPlainString());
contentValues.put(SplitEntry.COLUMN_TYPE, decimalImbalance.compareTo(BigDecimal.ZERO) < 0 ? "DEBIT" : "CREDIT");
contentValues.put(SplitEntry.COLUMN_MEMO, "");
contentValues.put(SplitEntry.COLUMN_ACCOUNT_UID, imbalanceAccountUID);
contentValues.put(SplitEntry.COLUMN_TRANSACTION_UID, TransactionUID);
db.insert(SplitEntry.TABLE_NAME, null, contentValues);
contentValues.clear();
contentValues.put(TransactionEntry.COLUMN_MODIFIED_AT, timestamp);
db.update(TransactionEntry.TABLE_NAME, contentValues, TransactionEntry.COLUMN_UID + " == ?",
new String[]{TransactionUID});
}
}
} finally {
cursor.close();
}
Log.i(DatabaseHelper.LOG_TAG, "Dropping temporary migration tables");
db.execSQL("DROP TABLE " + SplitEntry.TABLE_NAME + "_bak");
db.execSQL("DROP TABLE " + AccountEntry.TABLE_NAME + "_bak");
db.execSQL("DROP TABLE " + TransactionEntry.TABLE_NAME + "_bak");
db.setTransactionSuccessful();
oldVersion = 8;
} finally {
db.endTransaction();
}
GnuCashApplication.startScheduledActionExecutionService(GnuCashApplication.getAppContext());
return oldVersion;
}
/**
* Upgrades the database from version 8 to version 9.
* <p>This migration accomplishes the following:
* <ul>
* <li>Adds a commodities table to the database</li>
* <li>Adds prices table to the database</li>
* <li>Add separate columns for split value and quantity</li>
* <li>Migrate amounts to use the correct denominations for the currency</li>
* </ul>
* </p>
* @param db SQLite Database to be upgraded
* @return New database version (9) if upgrade successful, old version (8) if unsuccessful
* @throws RuntimeException if the default commodities could not be imported
*/
static int upgradeDbToVersion9(SQLiteDatabase db){
Log.i(DatabaseHelper.LOG_TAG, "Upgrading database to version 9");
int oldVersion = 8;
db.beginTransaction();
try {
db.execSQL("CREATE TABLE " + CommodityEntry.TABLE_NAME + " ("
+ CommodityEntry._ID + " integer primary key autoincrement, "
+ CommodityEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ CommodityEntry.COLUMN_NAMESPACE + " varchar(255) not null default " + Commodity.Namespace.ISO4217.name() + ", "
+ CommodityEntry.COLUMN_FULLNAME + " varchar(255) not null, "
+ CommodityEntry.COLUMN_MNEMONIC + " varchar(255) not null, "
+ CommodityEntry.COLUMN_LOCAL_SYMBOL+ " varchar(255) not null default '', "
+ CommodityEntry.COLUMN_CUSIP + " varchar(255), "
+ CommodityEntry.COLUMN_SMALLEST_FRACTION + " integer not null, "
+ CommodityEntry.COLUMN_QUOTE_FLAG + " integer not null, "
+ CommodityEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ CommodityEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(CommodityEntry.TABLE_NAME));
db.execSQL("CREATE UNIQUE INDEX '" + CommodityEntry.INDEX_UID
+ "' ON " + CommodityEntry.TABLE_NAME + "(" + CommodityEntry.COLUMN_UID + ")");
try {
importCommodities(db);
} catch (SAXException | ParserConfigurationException | IOException e) {
Log.e(DatabaseHelper.LOG_TAG, "Error loading currencies into the database", e);
Crashlytics.logException(e);
throw new RuntimeException(e);
}
db.execSQL(" ALTER TABLE " + AccountEntry.TABLE_NAME
+ " ADD COLUMN " + AccountEntry.COLUMN_COMMODITY_UID + " varchar(255) "
+ " REFERENCES " + CommodityEntry.TABLE_NAME + " (" + CommodityEntry.COLUMN_UID + ") ");
db.execSQL(" ALTER TABLE " + TransactionEntry.TABLE_NAME
+ " ADD COLUMN " + TransactionEntry.COLUMN_COMMODITY_UID + " varchar(255) "
+ " REFERENCES " + CommodityEntry.TABLE_NAME + " (" + CommodityEntry.COLUMN_UID + ") ");
db.execSQL("UPDATE " + AccountEntry.TABLE_NAME + " SET " + AccountEntry.COLUMN_COMMODITY_UID + " = "
+ " (SELECT " + CommodityEntry.COLUMN_UID
+ " FROM " + CommodityEntry.TABLE_NAME
+ " WHERE " + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_COMMODITY_UID + " = " + CommodityEntry.TABLE_NAME + "." + CommodityEntry.COLUMN_UID
+ ")");
db.execSQL("UPDATE " + TransactionEntry.TABLE_NAME + " SET " + TransactionEntry.COLUMN_COMMODITY_UID + " = "
+ " (SELECT " + CommodityEntry.COLUMN_UID
+ " FROM " + CommodityEntry.TABLE_NAME
+ " WHERE " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_COMMODITY_UID + " = " + CommodityEntry.TABLE_NAME + "." + CommodityEntry.COLUMN_UID
+ ")");
db.execSQL("CREATE TABLE " + PriceEntry.TABLE_NAME + " ("
+ PriceEntry._ID + " integer primary key autoincrement, "
+ PriceEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ PriceEntry.COLUMN_COMMODITY_UID + " varchar(255) not null, "
+ PriceEntry.COLUMN_CURRENCY_UID + " varchar(255) not null, "
+ PriceEntry.COLUMN_TYPE + " varchar(255), "
+ PriceEntry.COLUMN_DATE + " TIMESTAMP not null, "
+ PriceEntry.COLUMN_SOURCE + " text, "
+ PriceEntry.COLUMN_VALUE_NUM + " integer not null, "
+ PriceEntry.COLUMN_VALUE_DENOM + " integer not null, "
+ PriceEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ PriceEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "UNIQUE (" + PriceEntry.COLUMN_COMMODITY_UID + ", " + PriceEntry.COLUMN_CURRENCY_UID + ") ON CONFLICT REPLACE, "
+ "FOREIGN KEY (" + PriceEntry.COLUMN_COMMODITY_UID + ") REFERENCES " + CommodityEntry.TABLE_NAME + " (" + CommodityEntry.COLUMN_UID + ") ON DELETE CASCADE, "
+ "FOREIGN KEY (" + PriceEntry.COLUMN_CURRENCY_UID + ") REFERENCES " + CommodityEntry.TABLE_NAME + " (" + CommodityEntry.COLUMN_UID + ") ON DELETE CASCADE "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(PriceEntry.TABLE_NAME));
db.execSQL("CREATE UNIQUE INDEX '" + PriceEntry.INDEX_UID
+ "' ON " + PriceEntry.TABLE_NAME + "(" + PriceEntry.COLUMN_UID + ")");
//store split amounts as integer components numerator and denominator
db.execSQL("ALTER TABLE " + SplitEntry.TABLE_NAME + " RENAME TO " + SplitEntry.TABLE_NAME + "_bak");
// create new split table
db.execSQL("CREATE TABLE " + SplitEntry.TABLE_NAME + " ("
+ SplitEntry._ID + " integer primary key autoincrement, "
+ SplitEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ SplitEntry.COLUMN_MEMO + " text, "
+ SplitEntry.COLUMN_TYPE + " varchar(255) not null, "
+ SplitEntry.COLUMN_VALUE_NUM + " integer not null, "
+ SplitEntry.COLUMN_VALUE_DENOM + " integer not null, "
+ SplitEntry.COLUMN_QUANTITY_NUM + " integer not null, "
+ SplitEntry.COLUMN_QUANTITY_DENOM + " integer not null, "
+ SplitEntry.COLUMN_ACCOUNT_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_TRANSACTION_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ SplitEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_ACCOUNT_UID + ") REFERENCES " + AccountEntry.TABLE_NAME + " (" + AccountEntry.COLUMN_UID + ") ON DELETE CASCADE, "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_TRANSACTION_UID + ") REFERENCES " + TransactionEntry.TABLE_NAME + " (" + TransactionEntry.COLUMN_UID + ") ON DELETE CASCADE "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(SplitEntry.TABLE_NAME));
// initialize new split table with data from old table
db.execSQL("INSERT INTO " + SplitEntry.TABLE_NAME + " ( "
+ SplitEntry._ID + " , "
+ SplitEntry.COLUMN_UID + " , "
+ SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.COLUMN_VALUE_NUM + " , "
+ SplitEntry.COLUMN_VALUE_DENOM + " , "
+ SplitEntry.COLUMN_QUANTITY_NUM + " , "
+ SplitEntry.COLUMN_QUANTITY_DENOM + " , "
+ SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.COLUMN_TRANSACTION_UID
+ ") SELECT "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry._ID + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_UID + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.TABLE_NAME + "_bak.amount * 100, " //we will update this value in the next steps
+ "100, "
+ SplitEntry.TABLE_NAME + "_bak.amount * 100, " //default units of 2 decimal places were assumed until now
+ "100, "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_TRANSACTION_UID
+ " FROM " + SplitEntry.TABLE_NAME + "_bak;");
//************** UPDATE SPLITS WHOSE CURRENCIES HAVE NO DECIMAL PLACES *****************
//get all account UIDs which have currencies with fraction digits of 0
String query = "SELECT " + "A." + AccountEntry.COLUMN_UID + " AS account_uid "
+ " FROM " + AccountEntry.TABLE_NAME + " AS A, " + CommodityEntry.TABLE_NAME + " AS C "
+ " WHERE A." + AccountEntry.COLUMN_CURRENCY + " = C." + CommodityEntry.COLUMN_MNEMONIC
+ " AND C." + CommodityEntry.COLUMN_SMALLEST_FRACTION + "= 1";
Cursor cursor = db.rawQuery(query, null);
List<String> accountUIDs = new ArrayList<>();
try {
while (cursor.moveToNext()) {
String accountUID = cursor.getString(cursor.getColumnIndexOrThrow("account_uid"));
accountUIDs.add(accountUID);
}
} finally {
cursor.close();
}
String accounts = TextUtils.join("' , '", accountUIDs);
db.execSQL("REPLACE INTO " + SplitEntry.TABLE_NAME + " ( "
+ SplitEntry.COLUMN_UID + " , "
+ SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.COLUMN_TRANSACTION_UID + " , "
+ SplitEntry.COLUMN_CREATED_AT + " , "
+ SplitEntry.COLUMN_MODIFIED_AT + " , "
+ SplitEntry.COLUMN_VALUE_NUM + " , "
+ SplitEntry.COLUMN_VALUE_DENOM + " , "
+ SplitEntry.COLUMN_QUANTITY_NUM + " , "
+ SplitEntry.COLUMN_QUANTITY_DENOM
+ ") SELECT "
+ SplitEntry.COLUMN_UID + " , "
+ SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.COLUMN_TRANSACTION_UID + " , "
+ SplitEntry.COLUMN_CREATED_AT + " , "
+ SplitEntry.COLUMN_MODIFIED_AT + " , "
+ " ROUND (" + SplitEntry.COLUMN_VALUE_NUM + "/ 100), "
+ "1, "
+ " ROUND (" + SplitEntry.COLUMN_QUANTITY_NUM + "/ 100), "
+ "1 "
+ " FROM " + SplitEntry.TABLE_NAME
+ " WHERE " + SplitEntry.COLUMN_ACCOUNT_UID + " IN ('" + accounts + "')"
+ ";");
//************ UPDATE SPLITS WITH CURRENCIES HAVING 3 DECIMAL PLACES *******************
query = "SELECT " + "A." + AccountEntry.COLUMN_UID + " AS account_uid "
+ " FROM " + AccountEntry.TABLE_NAME + " AS A, " + CommodityEntry.TABLE_NAME + " AS C "
+ " WHERE A." + AccountEntry.COLUMN_CURRENCY + " = C." + CommodityEntry.COLUMN_MNEMONIC
+ " AND C." + CommodityEntry.COLUMN_SMALLEST_FRACTION + "= 1000";
cursor = db.rawQuery(query, null);
accountUIDs.clear();
try {
while (cursor.moveToNext()) {
String accountUID = cursor.getString(cursor.getColumnIndexOrThrow("account_uid"));
accountUIDs.add(accountUID);
}
} finally {
cursor.close();
}
accounts = TextUtils.join("' , '", accountUIDs);
db.execSQL("REPLACE INTO " + SplitEntry.TABLE_NAME + " ( "
+ SplitEntry.COLUMN_UID + " , "
+ SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.COLUMN_TRANSACTION_UID + " , "
+ SplitEntry.COLUMN_CREATED_AT + " , "
+ SplitEntry.COLUMN_MODIFIED_AT + " , "
+ SplitEntry.COLUMN_VALUE_NUM + " , "
+ SplitEntry.COLUMN_VALUE_DENOM + " , "
+ SplitEntry.COLUMN_QUANTITY_NUM + " , "
+ SplitEntry.COLUMN_QUANTITY_DENOM
+ ") SELECT "
+ SplitEntry.COLUMN_UID + " , "
+ SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.COLUMN_TRANSACTION_UID + " , "
+ SplitEntry.COLUMN_CREATED_AT + " , "
+ SplitEntry.COLUMN_MODIFIED_AT + " , "
+ SplitEntry.COLUMN_VALUE_NUM + "* 10, " //add an extra zero because we used only 2 digits before
+ "1000, "
+ SplitEntry.COLUMN_QUANTITY_NUM + "* 10, "
+ "1000 "
+ " FROM " + SplitEntry.TABLE_NAME
+ " WHERE " + SplitEntry.COLUMN_ACCOUNT_UID + " IN ('" + accounts + "')"
+ ";");
db.execSQL("DROP TABLE " + SplitEntry.TABLE_NAME + "_bak");
db.setTransactionSuccessful();
oldVersion = 9;
} finally {
db.endTransaction();
}
return oldVersion;
}
/**
* Upgrades the database to version 10
* <p>This method converts all saved scheduled export parameters to the new format using the
* timestamp of last export</p>
* @param db SQLite database
* @return 10 if upgrade was successful, 9 otherwise
*/
static int upgradeDbToVersion10(SQLiteDatabase db){
Log.i(DatabaseHelper.LOG_TAG, "Upgrading database to version 9");
int oldVersion = 9;
db.beginTransaction();
try {
Cursor cursor = db.query(ScheduledActionEntry.TABLE_NAME,
new String[]{ScheduledActionEntry.COLUMN_UID, ScheduledActionEntry.COLUMN_TAG},
ScheduledActionEntry.COLUMN_TYPE + " = ?",
new String[]{ScheduledAction.ActionType.BACKUP.name()},
null, null, null);
ContentValues contentValues = new ContentValues();
while (cursor.moveToNext()){
String paramString = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_TAG));
String[] tokens = paramString.split(";");
ExportParams params = new ExportParams(ExportFormat.valueOf(tokens[0]));
params.setExportTarget(ExportParams.ExportTarget.valueOf(tokens[1]));
params.setDeleteTransactionsAfterExport(Boolean.parseBoolean(tokens[3]));
boolean exportAll = Boolean.parseBoolean(tokens[2]);
if (exportAll){
params.setExportStartTime(TimestampHelper.getTimestampFromEpochZero());
} else {
Timestamp timestamp = PreferencesHelper.getLastExportTime();
params.setExportStartTime(timestamp);
}
String uid = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_UID));
contentValues.clear();
contentValues.put(ScheduledActionEntry.COLUMN_UID, uid);
contentValues.put(ScheduledActionEntry.COLUMN_TAG, params.toCsv());
db.insert(ScheduledActionEntry.TABLE_NAME, null, contentValues);
}
cursor.close();
db.setTransactionSuccessful();
oldVersion = 10;
} finally {
db.endTransaction();
}
return oldVersion;
}
/**
* Upgrade database to version 11
* <p>
* Migrate scheduled backups and update export parameters to the new format
* </p>
* @param db SQLite database
* @return 11 if upgrade was successful, 10 otherwise
*/
static int upgradeDbToVersion11(SQLiteDatabase db){
Log.i(DatabaseHelper.LOG_TAG, "Upgrading database to version 9");
int oldVersion = 10;
db.beginTransaction();
try {
Cursor cursor = db.query(ScheduledActionEntry.TABLE_NAME, null,
ScheduledActionEntry.COLUMN_TYPE + "= ?",
new String[]{ScheduledAction.ActionType.BACKUP.name()}, null, null, null);
Map<String, String> uidToTagMap = new HashMap<>();
while (cursor.moveToNext()) {
String uid = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_UID));
String tag = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_TAG));
String[] tokens = tag.split(";");
try {
Timestamp timestamp = TimestampHelper.getTimestampFromUtcString(tokens[2]);
} catch (IllegalArgumentException ex) {
tokens[2] = TimestampHelper.getUtcStringFromTimestamp(PreferencesHelper.getLastExportTime());
} finally {
tag = TextUtils.join(";", tokens);
}
uidToTagMap.put(uid, tag);
}
cursor.close();
ContentValues contentValues = new ContentValues();
for (Map.Entry<String, String> entry : uidToTagMap.entrySet()) {
contentValues.clear();
contentValues.put(ScheduledActionEntry.COLUMN_TAG, entry.getValue());
db.update(ScheduledActionEntry.TABLE_NAME, contentValues,
ScheduledActionEntry.COLUMN_UID + " = ?", new String[]{entry.getKey()});
}
db.setTransactionSuccessful();
oldVersion = 11;
} finally {
db.endTransaction();
}
return oldVersion;
}
public static Timestamp subtractTimeZoneOffset(Timestamp timestamp, TimeZone timeZone) {
final long millisecondsToSubtract = Math.abs(timeZone.getOffset(timestamp.getTime()));
return new Timestamp(timestamp.getTime() - millisecondsToSubtract);
}
/**
* Upgrade database to version 12
* <p>
* Change last_export_time Android preference to current value - N
* where N is the absolute timezone offset for current user time zone.
* For details see #467.
* </p>
* @param db SQLite database
* @return 12 if upgrade was successful, 11 otherwise
*/
static int upgradeDbToVersion12(SQLiteDatabase db){
Log.i(MigrationHelper.LOG_TAG, "Upgrading database to version 12");
int oldVersion = 11;
try {
final Timestamp currentLastExportTime = PreferencesHelper.getLastExportTime();
final Timestamp updatedLastExportTime = subtractTimeZoneOffset(
currentLastExportTime, TimeZone.getDefault());
PreferencesHelper.setLastExportTime(updatedLastExportTime);
oldVersion = 12;
} catch (Exception ignored){
// Do nothing: here oldVersion = 11.
}
return oldVersion;
}
/**
* Upgrades the database to version 13.
* <p>This migration makes the following changes to the database:
* <ul>
* <li>Adds support for multiple database for different books and one extra database for storing book info</li>
* <li>Adds a table for budgets</li>
* <li>Adds an extra table for recurrences</li>
* <li>Migrate scheduled transaction recurrences to own table</li>
* <li>Adds flags for reconciled status to split table</li>
* <li>Add flags for auto-/advance- create and notification to scheduled actions</li>
* <li>Migrate old shared preferences into new book-specific preferences</li>
* </ul>
* </p>
* @param db SQlite database to be upgraded
* @return New database version, 13 if migration succeeds, 11 otherwise
*/
static int upgradeDbToVersion13(SQLiteDatabase db){
Log.i(DatabaseHelper.LOG_TAG, "Upgrading database to version 13");
int oldVersion = 12;
db.beginTransaction();
try {
db.execSQL("CREATE TABLE " + RecurrenceEntry.TABLE_NAME + " ("
+ RecurrenceEntry._ID + " integer primary key autoincrement, "
+ RecurrenceEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ RecurrenceEntry.COLUMN_MULTIPLIER + " integer not null default 1, "
+ RecurrenceEntry.COLUMN_PERIOD_TYPE + " varchar(255) not null, "
+ RecurrenceEntry.COLUMN_BYDAY + " varchar(255), "
+ RecurrenceEntry.COLUMN_PERIOD_START + " timestamp not null, "
+ RecurrenceEntry.COLUMN_PERIOD_END + " timestamp, "
+ RecurrenceEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ RecurrenceEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP); "
+ DatabaseHelper.createUpdatedAtTrigger(RecurrenceEntry.TABLE_NAME));
db.execSQL("CREATE TABLE " + BudgetEntry.TABLE_NAME + " ("
+ BudgetEntry._ID + " integer primary key autoincrement, "
+ BudgetEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ BudgetEntry.COLUMN_NAME + " varchar(255) not null, "
+ BudgetEntry.COLUMN_DESCRIPTION + " varchar(255), "
+ BudgetEntry.COLUMN_RECURRENCE_UID + " varchar(255) not null, "
+ BudgetEntry.COLUMN_NUM_PERIODS + " integer, "
+ BudgetEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ BudgetEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + BudgetEntry.COLUMN_RECURRENCE_UID + ") REFERENCES " + RecurrenceEntry.TABLE_NAME + " (" + RecurrenceEntry.COLUMN_UID + ") "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(BudgetEntry.TABLE_NAME));
db.execSQL("CREATE UNIQUE INDEX '" + BudgetEntry.INDEX_UID
+ "' ON " + BudgetEntry.TABLE_NAME + "(" + BudgetEntry.COLUMN_UID + ")");
db.execSQL("CREATE TABLE " + BudgetAmountEntry.TABLE_NAME + " ("
+ BudgetAmountEntry._ID + " integer primary key autoincrement, "
+ BudgetAmountEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ BudgetAmountEntry.COLUMN_BUDGET_UID + " varchar(255) not null, "
+ BudgetAmountEntry.COLUMN_ACCOUNT_UID + " varchar(255) not null, "
+ BudgetAmountEntry.COLUMN_AMOUNT_NUM + " integer not null, "
+ BudgetAmountEntry.COLUMN_AMOUNT_DENOM + " integer not null, "
+ BudgetAmountEntry.COLUMN_PERIOD_NUM + " integer not null, "
+ BudgetAmountEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ BudgetAmountEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + BudgetAmountEntry.COLUMN_ACCOUNT_UID + ") REFERENCES " + AccountEntry.TABLE_NAME + " (" + AccountEntry.COLUMN_UID + ") ON DELETE CASCADE, "
+ "FOREIGN KEY (" + BudgetAmountEntry.COLUMN_BUDGET_UID + ") REFERENCES " + BudgetEntry.TABLE_NAME + " (" + BudgetEntry.COLUMN_UID + ") ON DELETE CASCADE "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(BudgetAmountEntry.TABLE_NAME));
db.execSQL("CREATE UNIQUE INDEX '" + BudgetAmountEntry.INDEX_UID
+ "' ON " + BudgetAmountEntry.TABLE_NAME + "(" + BudgetAmountEntry.COLUMN_UID + ")");
//extract recurrences from scheduled actions table and put in the recurrence table
db.execSQL("ALTER TABLE " + ScheduledActionEntry.TABLE_NAME + " RENAME TO " + ScheduledActionEntry.TABLE_NAME + "_bak");
db.execSQL("CREATE TABLE " + ScheduledActionEntry.TABLE_NAME + " ("
+ ScheduledActionEntry._ID + " integer primary key autoincrement, "
+ ScheduledActionEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ ScheduledActionEntry.COLUMN_ACTION_UID + " varchar(255) not null, "
+ ScheduledActionEntry.COLUMN_TYPE + " varchar(255) not null, "
+ ScheduledActionEntry.COLUMN_RECURRENCE_UID + " varchar(255) not null, "
+ ScheduledActionEntry.COLUMN_TEMPLATE_ACCT_UID + " varchar(255) not null, "
+ ScheduledActionEntry.COLUMN_LAST_RUN + " integer default 0, "
+ ScheduledActionEntry.COLUMN_START_TIME + " integer not null, "
+ ScheduledActionEntry.COLUMN_END_TIME + " integer default 0, "
+ ScheduledActionEntry.COLUMN_TAG + " text, "
+ ScheduledActionEntry.COLUMN_ENABLED + " tinyint default 1, " //enabled by default
+ ScheduledActionEntry.COLUMN_AUTO_CREATE + " tinyint default 1, "
+ ScheduledActionEntry.COLUMN_AUTO_NOTIFY + " tinyint default 0, "
+ ScheduledActionEntry.COLUMN_ADVANCE_CREATION + " integer default 0, "
+ ScheduledActionEntry.COLUMN_ADVANCE_NOTIFY + " integer default 0, "
+ ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY + " integer default 0, "
+ ScheduledActionEntry.COLUMN_EXECUTION_COUNT + " integer default 0, "
+ ScheduledActionEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ ScheduledActionEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + ScheduledActionEntry.COLUMN_RECURRENCE_UID + ") REFERENCES " + RecurrenceEntry.TABLE_NAME + " (" + RecurrenceEntry.COLUMN_UID + ") "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(ScheduledActionEntry.TABLE_NAME));
// initialize new transaction table with data from old table
db.execSQL("INSERT INTO " + ScheduledActionEntry.TABLE_NAME + " ( "
+ ScheduledActionEntry._ID + " , "
+ ScheduledActionEntry.COLUMN_UID + " , "
+ ScheduledActionEntry.COLUMN_ACTION_UID + " , "
+ ScheduledActionEntry.COLUMN_TYPE + " , "
+ ScheduledActionEntry.COLUMN_LAST_RUN + " , "
+ ScheduledActionEntry.COLUMN_START_TIME + " , "
+ ScheduledActionEntry.COLUMN_END_TIME + " , "
+ ScheduledActionEntry.COLUMN_ENABLED + " , "
+ ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY + " , "
+ ScheduledActionEntry.COLUMN_EXECUTION_COUNT + " , "
+ ScheduledActionEntry.COLUMN_CREATED_AT + " , "
+ ScheduledActionEntry.COLUMN_MODIFIED_AT + " , "
+ ScheduledActionEntry.COLUMN_RECURRENCE_UID + " , "
+ ScheduledActionEntry.COLUMN_TEMPLATE_ACCT_UID + " , "
+ ScheduledActionEntry.COLUMN_TAG
+ ") SELECT "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry._ID + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_UID + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_ACTION_UID + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_TYPE + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_LAST_RUN + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_START_TIME + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_END_TIME + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_ENABLED + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_EXECUTION_COUNT + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_CREATED_AT + " , "
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_MODIFIED_AT + " , "
+ " 'dummy-string' ," //will be updated in next steps
+ " 'dummy-string' ,"
+ ScheduledActionEntry.TABLE_NAME + "_bak." + ScheduledActionEntry.COLUMN_TAG
+ " FROM " + ScheduledActionEntry.TABLE_NAME + "_bak;");
//update the template-account-guid and the recurrence guid for all scheduled actions
Cursor cursor = db.query(ScheduledActionEntry.TABLE_NAME + "_bak",
new String[]{ScheduledActionEntry.COLUMN_UID,
"period",
ScheduledActionEntry.COLUMN_START_TIME
},
null, null, null, null, null);
ContentValues contentValues = new ContentValues();
while (cursor.moveToNext()){
String uid = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_UID));
long period = cursor.getLong(cursor.getColumnIndexOrThrow("period"));
long startTime = cursor.getLong(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_START_TIME));
Recurrence recurrence = Recurrence.fromLegacyPeriod(period);
recurrence.setPeriodStart(new Timestamp(startTime));
contentValues.clear();
contentValues.put(RecurrenceEntry.COLUMN_UID, recurrence.getUID());
contentValues.put(RecurrenceEntry.COLUMN_MULTIPLIER, recurrence.getMultiplier());
contentValues.put(RecurrenceEntry.COLUMN_PERIOD_TYPE, recurrence.getPeriodType().name());
contentValues.put(RecurrenceEntry.COLUMN_PERIOD_START, recurrence.getPeriodStart().toString());
db.insert(RecurrenceEntry.TABLE_NAME, null, contentValues);
contentValues.clear();
contentValues.put(ScheduledActionEntry.COLUMN_RECURRENCE_UID, recurrence.getUID());
contentValues.put(ScheduledActionEntry.COLUMN_TEMPLATE_ACCT_UID, BaseModel.generateUID());
db.update(ScheduledActionEntry.TABLE_NAME, contentValues,
ScheduledActionEntry.COLUMN_UID + " = ?", new String[]{uid});
}
cursor.close();
db.execSQL("DROP TABLE " + ScheduledActionEntry.TABLE_NAME + "_bak");
//============== Add RECONCILE_STATE and RECONCILE_DATE to the splits table ==========
//We migrate the whole table because we want those columns to have default values
db.execSQL("ALTER TABLE " + SplitEntry.TABLE_NAME + " RENAME TO " + SplitEntry.TABLE_NAME + "_bak");
db.execSQL("CREATE TABLE " + SplitEntry.TABLE_NAME + " ("
+ SplitEntry._ID + " integer primary key autoincrement, "
+ SplitEntry.COLUMN_UID + " varchar(255) not null UNIQUE, "
+ SplitEntry.COLUMN_MEMO + " text, "
+ SplitEntry.COLUMN_TYPE + " varchar(255) not null, "
+ SplitEntry.COLUMN_VALUE_NUM + " integer not null, "
+ SplitEntry.COLUMN_VALUE_DENOM + " integer not null, "
+ SplitEntry.COLUMN_QUANTITY_NUM + " integer not null, "
+ SplitEntry.COLUMN_QUANTITY_DENOM + " integer not null, "
+ SplitEntry.COLUMN_ACCOUNT_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_TRANSACTION_UID + " varchar(255) not null, "
+ SplitEntry.COLUMN_RECONCILE_STATE + " varchar(1) not null default 'n', "
+ SplitEntry.COLUMN_RECONCILE_DATE + " timestamp not null default current_timestamp, "
+ SplitEntry.COLUMN_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ SplitEntry.COLUMN_MODIFIED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_ACCOUNT_UID + ") REFERENCES " + AccountEntry.TABLE_NAME + " (" + AccountEntry.COLUMN_UID + ") ON DELETE CASCADE, "
+ "FOREIGN KEY (" + SplitEntry.COLUMN_TRANSACTION_UID + ") REFERENCES " + TransactionEntry.TABLE_NAME + " (" + TransactionEntry.COLUMN_UID + ") ON DELETE CASCADE "
+ ");" + DatabaseHelper.createUpdatedAtTrigger(SplitEntry.TABLE_NAME));
db.execSQL("INSERT INTO " + SplitEntry.TABLE_NAME + " ( "
+ SplitEntry._ID + " , "
+ SplitEntry.COLUMN_UID + " , "
+ SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.COLUMN_VALUE_NUM + " , "
+ SplitEntry.COLUMN_VALUE_DENOM + " , "
+ SplitEntry.COLUMN_QUANTITY_NUM + " , "
+ SplitEntry.COLUMN_QUANTITY_DENOM + " , "
+ SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.COLUMN_TRANSACTION_UID
+ ") SELECT "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry._ID + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_UID + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_MEMO + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_VALUE_NUM + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_VALUE_DENOM + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_QUANTITY_NUM + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_QUANTITY_DENOM + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_ACCOUNT_UID + " , "
+ SplitEntry.TABLE_NAME + "_bak." + SplitEntry.COLUMN_TRANSACTION_UID
+ " FROM " + SplitEntry.TABLE_NAME + "_bak;");
db.execSQL("DROP TABLE " + SplitEntry.TABLE_NAME + "_bak");
db.setTransactionSuccessful();
oldVersion = 13;
} finally {
db.endTransaction();
}
//Migrate book-specific preferences away from shared preferences
Log.d(LOG_TAG, "Migrating shared preferences into book preferences");
Context context = GnuCashApplication.getAppContext();
String keyUseDoubleEntry = context.getString(R.string.key_use_double_entry);
String keySaveOpeningBalance = context.getString(R.string.key_save_opening_balances);
String keyLastExportTime = PreferencesHelper.PREFERENCE_LAST_EXPORT_TIME_KEY;
String keyUseCompactView = context.getString(R.string.key_use_compact_list);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String lastExportTime = sharedPrefs.getString(keyLastExportTime, TimestampHelper.getTimestampFromEpochZero().toString());
boolean useDoubleEntry = sharedPrefs.getBoolean(keyUseDoubleEntry, true);
boolean saveOpeningBalance = sharedPrefs.getBoolean(keySaveOpeningBalance, false);
boolean useCompactTrnView = PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(context.getString(R.string.key_use_double_entry), !useDoubleEntry);
String rootAccountUID = getGnuCashRootAccountUID(db);
SharedPreferences bookPrefs = context.getSharedPreferences(rootAccountUID, Context.MODE_PRIVATE);
bookPrefs.edit()
.putString(keyLastExportTime, lastExportTime)
.putBoolean(keyUseDoubleEntry, useDoubleEntry)
.putBoolean(keySaveOpeningBalance, saveOpeningBalance)
.putBoolean(keyUseCompactView, useCompactTrnView)
.apply();
rescheduleServiceAlarm();
return oldVersion;
}
/**
* Cancel the existing alarm for the scheduled service and restarts/reschedules the service
*/
private static void rescheduleServiceAlarm() {
Context context = GnuCashApplication.getAppContext();
//cancel the existing pending intent so that the alarm can be rescheduled
Intent alarmIntent = new Intent(context, ScheduledActionService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, alarmIntent, PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
GnuCashApplication.startScheduledActionExecutionService(context);
}
/**
* Move files from {@code srcDir} to {@code dstDir}
* Subdirectories will be created in the target as necessary
* @param srcDir Source directory which should already exist
* @param dstDir Destination directory which should already exist
* @see #moveFile(File, File)
* @throws IOException if the {@code srcDir} does not exist or {@code dstDir} could not be created
* @throws IllegalArgumentException if {@code srcDir} is not a directory
*/
private static void moveDirectory(File srcDir, File dstDir) throws IOException {
if (!srcDir.isDirectory()){
throw new IllegalArgumentException("Source is not a directory: " + srcDir.getPath());
}
if (!srcDir.exists()){
String msg = String.format(Locale.US, "Source directory %s does not exist", srcDir.getPath());
Log.e(LOG_TAG, msg);
throw new IOException(msg);
}
if (!dstDir.exists() || !dstDir.isDirectory()){
Log.w(LOG_TAG, "Target directory does not exist. Attempting to create..." + dstDir.getPath());
if (!dstDir.mkdirs()){
throw new IOException(String.format("Target directory %s does not exist and could not be created", dstDir.getPath()));
}
}
if (srcDir.listFiles() == null) //nothing to see here, move along
return;
for (File src : srcDir.listFiles()){
if (src.isDirectory()){
File dst = new File(dstDir, src.getName());
dst.mkdir();
moveDirectory(src, dst);
if (!src.delete())
Log.i(LOG_TAG, "Failed to delete directory: " + src.getPath());
continue;
}
try {
File dst = new File(dstDir, src.getName());
MigrationHelper.moveFile(src, dst);
} catch (IOException e) {
Log.e(LOG_TAG, "Error moving file " + src.getPath());
Crashlytics.logException(e);
}
}
}
/**
* Upgrade the database to version 14
* <p>
* This migration actually does not change anything in the database
* It moves the backup files to a new backup location which does not require SD CARD write permission
* </p>
* @param db SQLite database to be upgraded
* @return New database version
*/
public static int upgradeDbToVersion14(SQLiteDatabase db){
Log.i(DatabaseHelper.LOG_TAG, "Upgrading database to version 14");
int oldDbVersion = 13;
File backupFolder = new File(Exporter.BASE_FOLDER_PATH);
backupFolder.mkdir();
new Thread(new Runnable() {
@Override
public void run() {
File srcDir = new File(Exporter.LEGACY_BASE_FOLDER_PATH);
File dstDir = new File(Exporter.BASE_FOLDER_PATH);
try {
moveDirectory(srcDir, dstDir);
File readmeFile = new File(Exporter.LEGACY_BASE_FOLDER_PATH, "README.txt");
FileWriter writer = null;
writer = new FileWriter(readmeFile);
writer.write("Backup files have been moved to " + dstDir.getPath() +
"\nYou can now delete this folder");
writer.flush();
} catch (IOException | IllegalArgumentException ex) {
ex.printStackTrace();
String msg = String.format("Error moving files from %s to %s", srcDir.getPath(), dstDir.getPath());
Log.e(LOG_TAG, msg);
Crashlytics.log(msg);
Crashlytics.logException(ex);
}
}
}).start();
return 14;
}
/**
* Upgrades the database to version 14.
* <p>This migration makes the following changes to the database:
* <ul>
* <li>Fixes accounts referencing a default transfer account that no longer
* exists (see #654)</li>
* </ul>
* </p>
* @param db SQLite database to be upgraded
* @return New database version, 14 if migration succeeds, 13 otherwise
*/
static int upgradeDbToVersion15(SQLiteDatabase db) {
Log.i(DatabaseHelper.LOG_TAG, "Upgrading database to version 15");
int dbVersion = 14;
db.beginTransaction();
try {
ContentValues contentValues = new ContentValues();
contentValues.putNull(AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID);
db.update(
AccountEntry.TABLE_NAME,
contentValues,
AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID
+ " NOT IN (SELECT " + AccountEntry.COLUMN_UID
+ " FROM " + AccountEntry.TABLE_NAME + ")",
null);
db.setTransactionSuccessful();
dbVersion = 15;
} finally {
db.endTransaction();
}
//remove previously saved export destination index because the number of destinations has changed
//an invalid value would lead to crash on start
Context context = GnuCashApplication.getAppContext();
android.preference.PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.remove(context.getString(R.string.key_last_export_destination))
.apply();
//the default interval has been changed from daily to hourly with this release. So reschedule alarm
rescheduleServiceAlarm();
return dbVersion;
}
}
| 94,867 | 57.129902 | 200 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/AccountsDbAdapter.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db.adapter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.model.TransactionType;
import org.gnucash.android.util.TimestampHelper;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import static org.gnucash.android.db.DatabaseSchema.AccountEntry;
import static org.gnucash.android.db.DatabaseSchema.SplitEntry;
import static org.gnucash.android.db.DatabaseSchema.TransactionEntry;
/**
* Manages persistence of {@link Account}s in the database
* Handles adding, modifying and deleting of account records.
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
* @author Oleksandr Tyshkovets <[email protected]>
*/
public class AccountsDbAdapter extends DatabaseAdapter<Account> {
/**
* Separator used for account name hierarchies between parent and child accounts
*/
public static final String ACCOUNT_NAME_SEPARATOR = ":";
/**
* ROOT account full name.
* should ensure the ROOT account's full name will always sort before any other
* account's full name.
*/
public static final String ROOT_ACCOUNT_FULL_NAME = " ";
/**
* Transactions database adapter for manipulating transactions associated with accounts
*/
private final TransactionsDbAdapter mTransactionsAdapter;
/**
* Commodities database adapter for commodity manipulation
*/
private final CommoditiesDbAdapter mCommoditiesDbAdapter;
/**
* Overloaded constructor. Creates an adapter for an already open database
* @param db SQliteDatabase instance
*/
public AccountsDbAdapter(SQLiteDatabase db, TransactionsDbAdapter transactionsDbAdapter) {
super(db, AccountEntry.TABLE_NAME, new String[]{
AccountEntry.COLUMN_NAME ,
AccountEntry.COLUMN_DESCRIPTION ,
AccountEntry.COLUMN_TYPE ,
AccountEntry.COLUMN_CURRENCY ,
AccountEntry.COLUMN_COLOR_CODE ,
AccountEntry.COLUMN_FAVORITE ,
AccountEntry.COLUMN_FULL_NAME ,
AccountEntry.COLUMN_PLACEHOLDER ,
AccountEntry.COLUMN_CREATED_AT ,
AccountEntry.COLUMN_HIDDEN ,
AccountEntry.COLUMN_COMMODITY_UID,
AccountEntry.COLUMN_PARENT_ACCOUNT_UID,
AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID
});
mTransactionsAdapter = transactionsDbAdapter;
mCommoditiesDbAdapter = new CommoditiesDbAdapter(db);
}
/**
* Convenience overloaded constructor.
* This is used when an AccountsDbAdapter object is needed quickly. Otherwise, the other
* constructor {@link #AccountsDbAdapter(SQLiteDatabase, TransactionsDbAdapter)}
* should be used whenever possible
* @param db Database to create an adapter for
*/
public AccountsDbAdapter(SQLiteDatabase db){
super(db, AccountEntry.TABLE_NAME, new String[]{
AccountEntry.COLUMN_NAME ,
AccountEntry.COLUMN_DESCRIPTION ,
AccountEntry.COLUMN_TYPE ,
AccountEntry.COLUMN_CURRENCY ,
AccountEntry.COLUMN_COLOR_CODE ,
AccountEntry.COLUMN_FAVORITE ,
AccountEntry.COLUMN_FULL_NAME ,
AccountEntry.COLUMN_PLACEHOLDER ,
AccountEntry.COLUMN_CREATED_AT ,
AccountEntry.COLUMN_HIDDEN ,
AccountEntry.COLUMN_COMMODITY_UID,
AccountEntry.COLUMN_PARENT_ACCOUNT_UID,
AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID
});
mTransactionsAdapter = new TransactionsDbAdapter(db, new SplitsDbAdapter(db));
mCommoditiesDbAdapter = new CommoditiesDbAdapter(db);
}
/**
* Returns an application-wide instance of this database adapter
* @return Instance of Accounts db adapter
*/
public static AccountsDbAdapter getInstance(){
return GnuCashApplication.getAccountsDbAdapter();
}
/**
* Adds an account to the database.
* If an account already exists in the database with the same GUID, it is replaced.
* @param account {@link Account} to be inserted to database
*/
@Override
public void addRecord(@NonNull Account account, UpdateMethod updateMethod){
Log.d(LOG_TAG, "Replace account to db");
//in-case the account already existed, we want to update the templates based on it as well
List<Transaction> templateTransactions = mTransactionsAdapter.getScheduledTransactionsForAccount(account.getUID());
super.addRecord(account, updateMethod);
String accountUID = account.getUID();
//now add transactions if there are any
if (account.getAccountType() != AccountType.ROOT){
//update the fully qualified account name
updateRecord(accountUID, AccountEntry.COLUMN_FULL_NAME, getFullyQualifiedAccountName(accountUID));
for (Transaction t : account.getTransactions()) {
t.setCommodity(account.getCommodity());
mTransactionsAdapter.addRecord(t, updateMethod);
}
for (Transaction transaction : templateTransactions) {
mTransactionsAdapter.addRecord(transaction, UpdateMethod.update);
}
}
}
/**
* Adds some accounts and their transactions to the database in bulk.
* <p>If an account already exists in the database with the same GUID, it is replaced.
* This function will NOT try to determine the full name
* of the accounts inserted, full names should be generated prior to the insert.
* <br>All or none of the accounts will be inserted;</p>
* @param accountList {@link Account} to be inserted to database
* @return number of rows inserted
*/
@Override
public long bulkAddRecords(@NonNull List<Account> accountList, UpdateMethod updateMethod){
//scheduled transactions are not fetched from the database when getting account transactions
//so we retrieve those which affect this account and then re-save them later
//this is necessary because the database has ON DELETE CASCADE between accounts and splits
//and all accounts are editing via SQL REPLACE
//// TODO: 20.04.2016 Investigate if we can safely remove updating the transactions when bulk updating accounts
List<Transaction> transactionList = new ArrayList<>(accountList.size()*2);
for (Account account : accountList) {
transactionList.addAll(account.getTransactions());
transactionList.addAll(mTransactionsAdapter.getScheduledTransactionsForAccount(account.getUID()));
}
long nRow = super.bulkAddRecords(accountList, updateMethod);
if (nRow > 0 && !transactionList.isEmpty()){
mTransactionsAdapter.bulkAddRecords(transactionList, updateMethod);
}
return nRow;
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final Account account) {
stmt.clearBindings();
stmt.bindString(1, account.getName());
if (account.getDescription() != null)
stmt.bindString(2, account.getDescription());
stmt.bindString(3, account.getAccountType().name());
stmt.bindString(4, account.getCommodity().getCurrencyCode());
if (account.getColor() != Account.DEFAULT_COLOR) {
stmt.bindString(5, account.getColorHexString());
}
stmt.bindLong(6, account.isFavorite() ? 1 : 0);
stmt.bindString(7, account.getFullName());
stmt.bindLong(8, account.isPlaceholderAccount() ? 1 : 0);
stmt.bindString(9, TimestampHelper.getUtcStringFromTimestamp(account.getCreatedTimestamp()));
stmt.bindLong(10, account.isHidden() ? 1 : 0);
stmt.bindString(11, account.getCommodity().getUID());
String parentAccountUID = account.getParentUID();
if (parentAccountUID == null && account.getAccountType() != AccountType.ROOT) {
parentAccountUID = getOrCreateGnuCashRootAccountUID();
}
if (parentAccountUID != null) {
stmt.bindString(12, parentAccountUID);
}
if (account.getDefaultTransferAccountUID() != null) {
stmt.bindString(13, account.getDefaultTransferAccountUID());
}
stmt.bindString(14, account.getUID());
return stmt;
}
/**
* Marks all transactions for a given account as exported
* @param accountUID Unique ID of the record to be marked as exported
* @return Number of records marked as exported
*/
public int markAsExported(String accountUID){
ContentValues contentValues = new ContentValues();
contentValues.put(TransactionEntry.COLUMN_EXPORTED, 1);
return mDb.update(
TransactionEntry.TABLE_NAME,
contentValues,
TransactionEntry.COLUMN_UID + " IN ( " +
"SELECT DISTINCT " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID +
" FROM " + TransactionEntry.TABLE_NAME + " , " + SplitEntry.TABLE_NAME + " ON " +
TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " = " +
SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID + " , " +
AccountEntry.TABLE_NAME + " ON " + SplitEntry.TABLE_NAME + "." +
SplitEntry.COLUMN_ACCOUNT_UID + " = " + AccountEntry.TABLE_NAME + "." +
AccountEntry.COLUMN_UID + " WHERE " + AccountEntry.TABLE_NAME + "." +
AccountEntry.COLUMN_UID + " = ? "
+ " ) ",
new String[]{accountUID}
);
}
/**
* This feature goes through all the rows in the accounts and changes value for <code>columnKey</code> to <code>newValue</code><br/>
* The <code>newValue</code> parameter is taken as string since SQLite typically stores everything as text.
* <p><b>This method affects all rows, exercise caution when using it</b></p>
* @param columnKey Name of column to be updated
* @param newValue New value to be assigned to the columnKey
* @return Number of records affected
*/
public int updateAllAccounts(String columnKey, String newValue){
ContentValues contentValues = new ContentValues();
if (newValue == null) {
contentValues.putNull(columnKey);
} else {
contentValues.put(columnKey, newValue);
}
return mDb.update(AccountEntry.TABLE_NAME, contentValues, null, null);
}
/**
* Updates a specific entry of an account
* @param accountId Database record ID of the account to be updated
* @param columnKey Name of column to be updated
* @param newValue New value to be assigned to the columnKey
* @return Number of records affected
*/
public int updateAccount(long accountId, String columnKey, String newValue){
return updateRecord(AccountEntry.TABLE_NAME, accountId, columnKey, newValue);
}
/**
* This method goes through all the children of {@code accountUID} and updates the parent account
* to {@code newParentAccountUID}. The fully qualified account names for all descendant accounts will also be updated.
* @param accountUID GUID of the account
* @param newParentAccountUID GUID of the new parent account
*/
public void reassignDescendantAccounts(@NonNull String accountUID, @NonNull String newParentAccountUID) {
List<String> descendantAccountUIDs = getDescendantAccountUIDs(accountUID, null, null);
if (descendantAccountUIDs.size() > 0) {
List<Account> descendantAccounts = getSimpleAccountList(
AccountEntry.COLUMN_UID + " IN ('" + TextUtils.join("','", descendantAccountUIDs) + "')",
null,
null
);
HashMap<String, Account> mapAccounts = new HashMap<>();
for (Account account : descendantAccounts)
mapAccounts.put(account.getUID(), account);
String parentAccountFullName;
if (getAccountType(newParentAccountUID) == AccountType.ROOT) {
parentAccountFullName = "";
} else {
parentAccountFullName = getAccountFullName(newParentAccountUID);
}
ContentValues contentValues = new ContentValues();
for (String acctUID : descendantAccountUIDs) {
Account acct = mapAccounts.get(acctUID);
if (accountUID.equals(acct.getParentUID())) {
// direct descendant
acct.setParentUID(newParentAccountUID);
if (parentAccountFullName == null || parentAccountFullName.isEmpty()) {
acct.setFullName(acct.getName());
} else {
acct.setFullName(parentAccountFullName + ACCOUNT_NAME_SEPARATOR + acct.getName());
}
// update DB
contentValues.clear();
contentValues.put(AccountEntry.COLUMN_PARENT_ACCOUNT_UID, newParentAccountUID);
contentValues.put(AccountEntry.COLUMN_FULL_NAME, acct.getFullName());
mDb.update(
AccountEntry.TABLE_NAME, contentValues,
AccountEntry.COLUMN_UID + " = ?",
new String[]{acct.getUID()}
);
} else {
// indirect descendant
acct.setFullName(
mapAccounts.get(acct.getParentUID()).getFullName() +
ACCOUNT_NAME_SEPARATOR + acct.getName()
);
// update DB
contentValues.clear();
contentValues.put(AccountEntry.COLUMN_FULL_NAME, acct.getFullName());
mDb.update(
AccountEntry.TABLE_NAME, contentValues,
AccountEntry.COLUMN_UID + " = ?",
new String[]{acct.getUID()}
);
}
}
}
}
/**
* Deletes an account and its transactions, and all its sub-accounts and their transactions.
* <p>Not only the splits belonging to the account and its descendants will be deleted, rather,
* the complete transactions associated with this account and its descendants
* (i.e. as long as the transaction has at least one split belonging to one of the accounts).
* This prevents an split imbalance from being caused.</p>
* <p>If you want to preserve transactions, make sure to first reassign the children accounts (see {@link #reassignDescendantAccounts(String, String)}
* before calling this method. This method will however not delete a root account. </p>
* <p><b>This method does a thorough delete, use with caution!!!</b></p>
* @param accountId Database record ID of account
* @return <code>true</code> if the account and subaccounts were all successfully deleted, <code>false</code> if
* even one was not deleted
* @see #reassignDescendantAccounts(String, String)
*/
public boolean recursiveDeleteAccount(long accountId){
String accountUID = getUID(accountId);
if (getAccountType(accountUID) == AccountType.ROOT) {
// refuse to delete ROOT
return false;
}
Log.d(LOG_TAG, "Delete account with rowId with its transactions and sub-accounts: " + accountId);
List<String> descendantAccountUIDs = getDescendantAccountUIDs(accountUID, null, null);
mDb.beginTransaction();
try {
descendantAccountUIDs.add(accountUID); //add account to descendants list just for convenience
for (String descendantAccountUID : descendantAccountUIDs) {
mTransactionsAdapter.deleteTransactionsForAccount(descendantAccountUID);
}
String accountUIDList = "'" + TextUtils.join("','", descendantAccountUIDs) + "'";
// delete accounts
long deletedCount = mDb.delete(
AccountEntry.TABLE_NAME,
AccountEntry.COLUMN_UID + " IN (" + accountUIDList + ")",
null
);
//if we delete some accounts, reset the default transfer account to NULL
//there is also a database trigger from db version > 12
if (deletedCount > 0){
ContentValues contentValues = new ContentValues();
contentValues.putNull(AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID);
mDb.update(mTableName, contentValues,
AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID + " IN (" + accountUIDList + ")",
null);
}
mDb.setTransactionSuccessful();
return true;
}
finally {
mDb.endTransaction();
}
}
/**
* Builds an account instance with the provided cursor and loads its corresponding transactions.
*
* @param c Cursor pointing to account record in database
* @return {@link Account} object constructed from database record
*/
@Override
public Account buildModelInstance(@NonNull final Cursor c){
Account account = buildSimpleAccountInstance(c);
account.setTransactions(mTransactionsAdapter.getAllTransactionsForAccount(account.getUID()));
return account;
}
/**
* Builds an account instance with the provided cursor and loads its corresponding transactions.
* <p>The method will not move the cursor position, so the cursor should already be pointing
* to the account record in the database<br/>
* <b>Note</b> Unlike {@link #buildModelInstance(android.database.Cursor)} this method will not load transactions</p>
*
* @param c Cursor pointing to account record in database
* @return {@link Account} object constructed from database record
*/
private Account buildSimpleAccountInstance(Cursor c) {
Account account = new Account(c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_NAME)));
populateBaseModelAttributes(c, account);
String description = c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_DESCRIPTION));
account.setDescription(description == null ? "" : description);
account.setParentUID(c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_PARENT_ACCOUNT_UID)));
account.setAccountType(AccountType.valueOf(c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_TYPE))));
String currencyCode = c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_CURRENCY));
account.setCommodity(mCommoditiesDbAdapter.getCommodity(currencyCode));
account.setPlaceHolderFlag(c.getInt(c.getColumnIndexOrThrow(AccountEntry.COLUMN_PLACEHOLDER)) == 1);
account.setDefaultTransferAccountUID(c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID)));
String color = c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_COLOR_CODE));
if (color != null)
account.setColor(color);
account.setFavorite(c.getInt(c.getColumnIndexOrThrow(AccountEntry.COLUMN_FAVORITE)) == 1);
account.setFullName(c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_FULL_NAME)));
account.setHidden(c.getInt(c.getColumnIndexOrThrow(AccountEntry.COLUMN_HIDDEN)) == 1);
return account;
}
/**
* Returns the unique ID of the parent account of the account with unique ID <code>uid</code>
* If the account has no parent, null is returned
* @param uid Unique Identifier of account whose parent is to be returned. Should not be null
* @return DB record UID of the parent account, null if the account has no parent
*/
public String getParentAccountUID(@NonNull String uid){
Cursor cursor = mDb.query(AccountEntry.TABLE_NAME,
new String[]{AccountEntry.COLUMN_PARENT_ACCOUNT_UID},
AccountEntry.COLUMN_UID + " = ?",
new String[]{uid},
null, null, null, null);
try {
if (cursor.moveToFirst()) {
Log.d(LOG_TAG, "Found parent account UID, returning value");
return cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_PARENT_ACCOUNT_UID));
} else {
return null;
}
} finally {
cursor.close();
}
}
/**
* Returns the color code for the account in format #rrggbb
* @param accountId Database row ID of the account
* @return String color code of account or null if none
*/
public String getAccountColorCode(long accountId){
Cursor c = mDb.query(AccountEntry.TABLE_NAME,
new String[]{AccountEntry._ID, AccountEntry.COLUMN_COLOR_CODE},
AccountEntry._ID + "=" + accountId,
null, null, null, null);
try {
if (c.moveToFirst()) {
return c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_COLOR_CODE));
}
else {
return null;
}
} finally {
c.close();
}
}
/**
* Overloaded method. Resolves the account unique ID from the row ID and makes a call to {@link #getAccountType(String)}
* @param accountId Database row ID of the account
* @return {@link AccountType} of the account
*/
public AccountType getAccountType(long accountId){
return getAccountType(getUID(accountId));
}
/**
* Returns a list of all account entries in the system (includes root account)
* No transactions are loaded, just the accounts
* @return List of {@link Account}s in the database
*/
public List<Account> getSimpleAccountList(){
LinkedList<Account> accounts = new LinkedList<>();
Cursor c = fetchAccounts(null, null, AccountEntry.COLUMN_FULL_NAME + " ASC");
try {
while (c.moveToNext()) {
accounts.add(buildSimpleAccountInstance(c));
}
}
finally {
c.close();
}
return accounts;
}
/**
* Returns a list of all account entries in the system (includes root account)
* No transactions are loaded, just the accounts
* @return List of {@link Account}s in the database
*/
public List<Account> getSimpleAccountList(String where, String[] whereArgs, String orderBy){
LinkedList<Account> accounts = new LinkedList<>();
Cursor c = fetchAccounts(where, whereArgs, orderBy);
try {
while (c.moveToNext()) {
accounts.add(buildSimpleAccountInstance(c));
}
}
finally {
c.close();
}
return accounts;
}
/**
* Returns a list of accounts which have transactions that have not been exported yet
* @param lastExportTimeStamp Timestamp after which to any transactions created/modified should be exported
* @return List of {@link Account}s with unexported transactions
*/
public List<Account> getExportableAccounts(Timestamp lastExportTimeStamp){
LinkedList<Account> accountsList = new LinkedList<>();
Cursor cursor = mDb.query(
TransactionEntry.TABLE_NAME + " , " + SplitEntry.TABLE_NAME +
" ON " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " = " +
SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID + " , " +
AccountEntry.TABLE_NAME + " ON " + AccountEntry.TABLE_NAME + "." +
AccountEntry.COLUMN_UID + " = " + SplitEntry.TABLE_NAME + "." +
SplitEntry.COLUMN_ACCOUNT_UID,
new String[]{AccountEntry.TABLE_NAME + ".*"},
TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_MODIFIED_AT + " > ?",
new String[]{TimestampHelper.getUtcStringFromTimestamp(lastExportTimeStamp)},
AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_UID,
null,
null
);
try {
while (cursor.moveToNext()) {
accountsList.add(buildModelInstance(cursor));
}
}
finally {
cursor.close();
}
return accountsList;
}
/**
* Retrieves the unique ID of the imbalance account for a particular currency (creates the imbalance account
* on demand if necessary)
* @param commodity Commodity for the imbalance account
* @return String unique ID of the account
*/
public String getOrCreateImbalanceAccountUID(Commodity commodity){
String imbalanceAccountName = getImbalanceAccountName(commodity);
String uid = findAccountUidByFullName(imbalanceAccountName);
if (uid == null){
Account account = new Account(imbalanceAccountName, commodity);
account.setAccountType(AccountType.BANK);
account.setParentUID(getOrCreateGnuCashRootAccountUID());
account.setHidden(!GnuCashApplication.isDoubleEntryEnabled());
account.setColor("#964B00");
addRecord(account, UpdateMethod.insert);
uid = account.getUID();
}
return uid;
}
/**
* Returns the GUID of the imbalance account for the commodity
*
* <p>This method will not create the imbalance account if it doesn't exist</p>
*
* @param commodity Commodity for the imbalance account
* @return GUID of the account or null if the account doesn't exist yet
* @see #getOrCreateImbalanceAccountUID(Commodity)
*/
public String getImbalanceAccountUID(Commodity commodity){
String imbalanceAccountName = getImbalanceAccountName(commodity);
return findAccountUidByFullName(imbalanceAccountName);
}
/**
* Creates the account with the specified name and returns its unique identifier.
* <p>If a full hierarchical account name is provided, then the whole hierarchy is created and the
* unique ID of the last account (at bottom) of the hierarchy is returned</p>
* @param fullName Fully qualified name of the account
* @param accountType Type to assign to all accounts created
* @return String unique ID of the account at bottom of hierarchy
*/
public String createAccountHierarchy(String fullName, AccountType accountType) {
if ("".equals(fullName)) {
throw new IllegalArgumentException("fullName cannot be empty");
}
String[] tokens = fullName.trim().split(ACCOUNT_NAME_SEPARATOR);
String uid = getOrCreateGnuCashRootAccountUID();
String parentName = "";
ArrayList<Account> accountsList = new ArrayList<>();
for (String token : tokens) {
parentName += token;
String parentUID = findAccountUidByFullName(parentName);
if (parentUID != null) { //the parent account exists, don't recreate
uid = parentUID;
} else {
Account account = new Account(token);
account.setAccountType(accountType);
account.setParentUID(uid); //set its parent
account.setFullName(parentName);
accountsList.add(account);
uid = account.getUID();
}
parentName += ACCOUNT_NAME_SEPARATOR;
}
if (accountsList.size() > 0) {
bulkAddRecords(accountsList, UpdateMethod.insert);
}
// if fullName is not empty, loop will be entered and then uid will never be null
//noinspection ConstantConditions
return uid;
}
/**
* Returns the unique ID of the opening balance account or creates one if necessary
* @return String unique ID of the opening balance account
*/
public String getOrCreateOpeningBalanceAccountUID() {
String openingBalanceAccountName = getOpeningBalanceAccountFullName();
String uid = findAccountUidByFullName(openingBalanceAccountName);
if (uid == null) {
uid = createAccountHierarchy(openingBalanceAccountName, AccountType.EQUITY);
}
return uid;
}
/**
* Finds an account unique ID by its full name
* @param fullName Fully qualified name of the account
* @return String unique ID of the account or null if no match is found
*/
public String findAccountUidByFullName(String fullName){
Cursor c = mDb.query(AccountEntry.TABLE_NAME, new String[]{AccountEntry.COLUMN_UID},
AccountEntry.COLUMN_FULL_NAME + "= ?", new String[]{fullName},
null, null, null, "1");
try {
if (c.moveToNext()) {
return c.getString(c.getColumnIndexOrThrow(AccountEntry.COLUMN_UID));
} else {
return null;
}
} finally {
c.close();
}
}
/**
* Returns a cursor to all account records in the database.
* GnuCash ROOT accounts and hidden accounts will <b>not</b> be included in the result set
* @return {@link Cursor} to all account records
*/
@Override
public Cursor fetchAllRecords(){
Log.v(LOG_TAG, "Fetching all accounts from db");
String selection = AccountEntry.COLUMN_HIDDEN + " = 0 AND " + AccountEntry.COLUMN_TYPE + " != ?" ;
return mDb.query(AccountEntry.TABLE_NAME,
null,
selection,
new String[]{AccountType.ROOT.name()},
null, null,
AccountEntry.COLUMN_NAME + " ASC");
}
/**
* Returns a cursor to all account records in the database ordered by full name.
* GnuCash ROOT accounts and hidden accounts will not be included in the result set.
* @return {@link Cursor} to all account records
*/
public Cursor fetchAllRecordsOrderedByFullName(){
Log.v(LOG_TAG, "Fetching all accounts from db");
String selection = AccountEntry.COLUMN_HIDDEN + " = 0 AND " + AccountEntry.COLUMN_TYPE + " != ?" ;
return mDb.query(AccountEntry.TABLE_NAME,
null,
selection,
new String[]{AccountType.ROOT.name()},
null, null,
AccountEntry.COLUMN_FULL_NAME + " ASC");
}
/**
* Returns a Cursor set of accounts which fulfill <code>where</code>
* and ordered by <code>orderBy</code>
* @param where SQL WHERE statement without the 'WHERE' itself
* @param whereArgs args to where clause
* @param orderBy orderBy clause
* @return Cursor set of accounts which fulfill <code>where</code>
*/
public Cursor fetchAccounts(@Nullable String where, @Nullable String[] whereArgs, @Nullable String orderBy){
if (orderBy == null){
orderBy = AccountEntry.COLUMN_NAME + " ASC";
}
Log.v(LOG_TAG, "Fetching all accounts from db where " + where + " order by " + orderBy);
return mDb.query(AccountEntry.TABLE_NAME,
null, where, whereArgs, null, null,
orderBy);
}
/**
* Returns a Cursor set of accounts which fulfill <code>where</code>
* <p>This method returns the accounts list sorted by the full account name</p>
* @param where SQL WHERE statement without the 'WHERE' itself
* @param whereArgs where args
* @return Cursor set of accounts which fulfill <code>where</code>
*/
public Cursor fetchAccountsOrderedByFullName(String where, String[] whereArgs) {
Log.v(LOG_TAG, "Fetching all accounts from db where " + where);
return mDb.query(AccountEntry.TABLE_NAME,
null, where, whereArgs, null, null,
AccountEntry.COLUMN_FULL_NAME + " ASC");
}
/**
* Returns a Cursor set of accounts which fulfill <code>where</code>
* <p>This method returns the favorite accounts first, sorted by name, and then the other accounts,
* sorted by name.</p>
* @param where SQL WHERE statement without the 'WHERE' itself
* @param whereArgs where args
* @return Cursor set of accounts which fulfill <code>where</code>
*/
public Cursor fetchAccountsOrderedByFavoriteAndFullName(String where, String[] whereArgs) {
Log.v(LOG_TAG, "Fetching all accounts from db where " + where + " order by Favorite then Name");
return mDb.query(AccountEntry.TABLE_NAME,
null, where, whereArgs, null, null,
AccountEntry.COLUMN_FAVORITE + " DESC, " + AccountEntry.COLUMN_FULL_NAME + " ASC");
}
/**
* Returns the balance of an account while taking sub-accounts into consideration
* @return Account Balance of an account including sub-accounts
*/
public Money getAccountBalance(String accountUID){
return computeBalance(accountUID, -1, -1);
}
/**
* Returns the balance of an account within the specified time range while taking sub-accounts into consideration
* @param accountUID the account's UUID
* @param startTimestamp the start timestamp of the time range
* @param endTimestamp the end timestamp of the time range
* @return the balance of an account within the specified range including sub-accounts
*/
public Money getAccountBalance(String accountUID, long startTimestamp, long endTimestamp) {
return computeBalance(accountUID, startTimestamp, endTimestamp);
}
/**
* Compute the account balance for all accounts with the specified type within a specific duration
* @param accountType Account Type for which to compute balance
* @param startTimestamp Begin time for the duration in milliseconds
* @param endTimestamp End time for duration in milliseconds
* @return Account balance
*/
public Money getAccountBalance(AccountType accountType, long startTimestamp, long endTimestamp){
Cursor cursor = fetchAccounts(AccountEntry.COLUMN_TYPE + "= ?",
new String[]{accountType.name()}, null);
List<String> accountUidList = new ArrayList<>();
while (cursor.moveToNext()){
String accountUID = cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_UID));
accountUidList.add(accountUID);
}
cursor.close();
boolean hasDebitNormalBalance = accountType.hasDebitNormalBalance();
String currencyCode = GnuCashApplication.getDefaultCurrencyCode();
Log.d(LOG_TAG, "all account list : " + accountUidList.size());
SplitsDbAdapter splitsDbAdapter = mTransactionsAdapter.getSplitDbAdapter();
return (startTimestamp == -1 && endTimestamp == -1)
? splitsDbAdapter.computeSplitBalance(accountUidList, currencyCode, hasDebitNormalBalance)
: splitsDbAdapter.computeSplitBalance(accountUidList, currencyCode, hasDebitNormalBalance, startTimestamp, endTimestamp);
}
/**
* Returns the account balance for all accounts types specified
* @param accountTypes List of account types
* @param start Begin timestamp for transactions
* @param end End timestamp of transactions
* @return Money balance of the account types
*/
public Money getAccountBalance(List<AccountType> accountTypes, long start, long end){
Money balance = Money.createZeroInstance(GnuCashApplication.getDefaultCurrencyCode());
for (AccountType accountType : accountTypes) {
balance = balance.add(getAccountBalance(accountType, start, end));
}
return balance;
}
private Money computeBalance(String accountUID, long startTimestamp, long endTimestamp) {
Log.d(LOG_TAG, "Computing account balance for account ID " + accountUID);
String currencyCode = mTransactionsAdapter.getAccountCurrencyCode(accountUID);
boolean hasDebitNormalBalance = getAccountType(accountUID).hasDebitNormalBalance();
List<String> accountsList = getDescendantAccountUIDs(accountUID,
null, null);
accountsList.add(0, accountUID);
Log.d(LOG_TAG, "all account list : " + accountsList.size());
SplitsDbAdapter splitsDbAdapter = mTransactionsAdapter.getSplitDbAdapter();
return (startTimestamp == -1 && endTimestamp == -1)
? splitsDbAdapter.computeSplitBalance(accountsList, currencyCode, hasDebitNormalBalance)
: splitsDbAdapter.computeSplitBalance(accountsList, currencyCode, hasDebitNormalBalance, startTimestamp, endTimestamp);
}
/**
* Returns the balance of account list within the specified time range. The default currency
* takes as base currency.
* @param accountUIDList list of account UIDs
* @param startTimestamp the start timestamp of the time range
* @param endTimestamp the end timestamp of the time range
* @return Money balance of account list
*/
public Money getAccountsBalance(@NonNull List<String> accountUIDList, long startTimestamp, long endTimestamp) {
String currencyCode = GnuCashApplication.getDefaultCurrencyCode();
Money balance = Money.createZeroInstance(currencyCode);
if (accountUIDList.isEmpty())
return balance;
boolean hasDebitNormalBalance = getAccountType(accountUIDList.get(0)).hasDebitNormalBalance();
SplitsDbAdapter splitsDbAdapter = mTransactionsAdapter.getSplitDbAdapter();
Money splitSum = (startTimestamp == -1 && endTimestamp == -1)
? splitsDbAdapter.computeSplitBalance(accountUIDList, currencyCode, hasDebitNormalBalance)
: splitsDbAdapter.computeSplitBalance(accountUIDList, currencyCode, hasDebitNormalBalance, startTimestamp, endTimestamp);
return balance.add(splitSum);
}
/**
* Retrieve all descendant accounts of an account
* Note, in filtering, once an account is filtered out, all its descendants
* will also be filtered out, even they don't meet the filter where
* @param accountUID The account to retrieve descendant accounts
* @param where Condition to filter accounts
* @param whereArgs Condition args to filter accounts
* @return The descendant accounts list.
*/
public List<String> getDescendantAccountUIDs(String accountUID, String where, String[] whereArgs) {
// accountsList will hold accountUID with all descendant accounts.
// accountsListLevel will hold descendant accounts of the same level
ArrayList<String> accountsList = new ArrayList<>();
ArrayList<String> accountsListLevel = new ArrayList<>();
accountsListLevel.add(accountUID);
for (;;) {
Cursor cursor = mDb.query(AccountEntry.TABLE_NAME,
new String[]{AccountEntry.COLUMN_UID},
AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " IN ( '" + TextUtils.join("' , '", accountsListLevel) + "' )" +
(where == null ? "" : " AND " + where),
whereArgs, null, null, null);
accountsListLevel.clear();
if (cursor != null) {
try {
int columnIndex = cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_UID);
while (cursor.moveToNext()) {
accountsListLevel.add(cursor.getString(columnIndex));
}
} finally {
cursor.close();
}
}
if (accountsListLevel.size() > 0) {
accountsList.addAll(accountsListLevel);
}
else {
break;
}
}
return accountsList;
}
/**
* Returns a cursor to the dataset containing sub-accounts of the account with record ID <code>accoundId</code>
* @param accountUID GUID of the parent account
* @return {@link Cursor} to the sub accounts data set
*/
public Cursor fetchSubAccounts(String accountUID) {
Log.v(LOG_TAG, "Fetching sub accounts for account id " + accountUID);
String selection = AccountEntry.COLUMN_HIDDEN + " = 0 AND "
+ AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " = ?";
return mDb.query(AccountEntry.TABLE_NAME,
null,
selection,
new String[]{accountUID}, null, null, AccountEntry.COLUMN_NAME + " ASC");
}
/**
* Returns the top level accounts i.e. accounts with no parent or with the GnuCash ROOT account as parent
* @return Cursor to the top level accounts
*/
public Cursor fetchTopLevelAccounts() {
//condition which selects accounts with no parent, whose UID is not ROOT and whose type is not ROOT
return fetchAccounts("(" + AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " IS NULL OR "
+ AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " = ?) AND "
+ AccountEntry.COLUMN_HIDDEN + " = 0 AND "
+ AccountEntry.COLUMN_TYPE + " != ?",
new String[]{getOrCreateGnuCashRootAccountUID(), AccountType.ROOT.name()},
AccountEntry.COLUMN_NAME + " ASC");
}
/**
* Returns a cursor to accounts which have recently had transactions added to them
* @return Cursor to recently used accounts
*/
public Cursor fetchRecentAccounts(int numberOfRecent) {
return mDb.query(TransactionEntry.TABLE_NAME
+ " LEFT OUTER JOIN " + SplitEntry.TABLE_NAME + " ON "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " = "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID
+ " , " + AccountEntry.TABLE_NAME + " ON " + SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_ACCOUNT_UID
+ " = " + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_UID,
new String[]{AccountEntry.TABLE_NAME + ".*"},
AccountEntry.COLUMN_HIDDEN + " = 0",
null,
SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_ACCOUNT_UID, //groupby
null, //haveing
"MAX ( " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TIMESTAMP + " ) DESC", // order
Integer.toString(numberOfRecent) // limit;
);
}
/**
* Fetches favorite accounts from the database
* @return Cursor holding set of favorite accounts
*/
public Cursor fetchFavoriteAccounts(){
Log.v(LOG_TAG, "Fetching favorite accounts from db");
String condition = AccountEntry.COLUMN_FAVORITE + " = 1";
return mDb.query(AccountEntry.TABLE_NAME,
null, condition, null, null, null,
AccountEntry.COLUMN_NAME + " ASC");
}
/**
* Returns the GnuCash ROOT account UID if one exists (or creates one if necessary).
* <p>In GnuCash desktop account structure, there is a root account (which is not visible in the UI) from which
* other top level accounts derive. GnuCash Android also enforces a ROOT account now</p>
* @return Unique ID of the GnuCash root account.
*/
public String getOrCreateGnuCashRootAccountUID() {
Cursor cursor = fetchAccounts(AccountEntry.COLUMN_TYPE + "= ?",
new String[]{AccountType.ROOT.name()}, null);
try {
if (cursor.moveToFirst()) {
return cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_UID));
}
} finally {
cursor.close();
}
// No ROOT exits, create a new one
Account rootAccount = new Account("ROOT Account", new CommoditiesDbAdapter(mDb).getCommodity("USD"));
rootAccount.setAccountType(AccountType.ROOT);
rootAccount.setFullName(ROOT_ACCOUNT_FULL_NAME);
rootAccount.setHidden(true);
rootAccount.setPlaceHolderFlag(true);
ContentValues contentValues = new ContentValues();
contentValues.put(AccountEntry.COLUMN_UID, rootAccount.getUID());
contentValues.put(AccountEntry.COLUMN_NAME, rootAccount.getName());
contentValues.put(AccountEntry.COLUMN_FULL_NAME, rootAccount.getFullName());
contentValues.put(AccountEntry.COLUMN_TYPE, rootAccount.getAccountType().name());
contentValues.put(AccountEntry.COLUMN_HIDDEN, rootAccount.isHidden() ? 1 : 0);
String defaultCurrencyCode = GnuCashApplication.getDefaultCurrencyCode();
contentValues.put(AccountEntry.COLUMN_CURRENCY, defaultCurrencyCode);
contentValues.put(AccountEntry.COLUMN_COMMODITY_UID, getCommodityUID(defaultCurrencyCode));
Log.i(LOG_TAG, "Creating ROOT account");
mDb.insert(AccountEntry.TABLE_NAME, null, contentValues);
return rootAccount.getUID();
}
/**
* Returns the number of accounts for which the account with ID <code>accoundId</code> is a first level parent
* @param accountUID String Unique ID (GUID) of the account
* @return Number of sub accounts
*/
public int getSubAccountCount(String accountUID){
//TODO: at some point when API level 11 and above only is supported, use DatabaseUtils.queryNumEntries
String queryCount = "SELECT COUNT(*) FROM " + AccountEntry.TABLE_NAME + " WHERE "
+ AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " = ?";
Cursor cursor = mDb.rawQuery(queryCount, new String[]{accountUID});
cursor.moveToFirst();
int count = cursor.getInt(0);
cursor.close();
return count;
}
/**
* Returns currency code of account with database ID <code>id</code>
* @param uid GUID of the account
* @return Currency code of the account
*/
public String getCurrencyCode(String uid){
return getAccountCurrencyCode(uid);
}
/**
* Returns the simple name of the account with unique ID <code>accountUID</code>.
* @param accountUID Unique identifier of the account
* @return Name of the account as String
* @throws java.lang.IllegalArgumentException if accountUID does not exist
* @see #getFullyQualifiedAccountName(String)
*/
public String getAccountName(String accountUID){
return getAttribute(accountUID, AccountEntry.COLUMN_NAME);
}
/**
* Returns the default transfer account record ID for the account with UID <code>accountUID</code>
* @param accountID Database ID of the account record
* @return Record ID of default transfer account
*/
public long getDefaultTransferAccountID(long accountID){
Cursor cursor = mDb.query(AccountEntry.TABLE_NAME,
new String[]{AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID},
AccountEntry._ID + " = " + accountID,
null, null, null, null);
try {
if (cursor.moveToNext()) {
String uid = cursor.getString(
cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID));
if (uid == null)
return 0;
else
return getID(uid);
} else {
return 0;
}
} finally {
cursor.close();
}
}
/**
* Returns the full account name including the account hierarchy (parent accounts)
* @param accountUID Unique ID of account
* @return Fully qualified (with parent hierarchy) account name
*/
public String getFullyQualifiedAccountName(String accountUID){
String accountName = getAccountName(accountUID);
String parentAccountUID = getParentAccountUID(accountUID);
if (parentAccountUID == null || parentAccountUID.equalsIgnoreCase(getOrCreateGnuCashRootAccountUID())){
return accountName;
}
String parentAccountName = getFullyQualifiedAccountName(parentAccountUID);
return parentAccountName + ACCOUNT_NAME_SEPARATOR + accountName;
}
/**
* get account's full name directly from DB
* @param accountUID the account to retrieve full name
* @return full name registered in DB
*/
public String getAccountFullName(String accountUID) {
Cursor cursor = mDb.query(AccountEntry.TABLE_NAME, new String[]{AccountEntry.COLUMN_FULL_NAME},
AccountEntry.COLUMN_UID + " = ?", new String[]{accountUID},
null, null, null);
try {
if (cursor.moveToFirst()) {
return cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_FULL_NAME));
}
}
finally {
cursor.close();
}
throw new IllegalArgumentException("account UID: " + accountUID + " does not exist");
}
/**
* Returns <code>true</code> if the account with unique ID <code>accountUID</code> is a placeholder account.
* @param accountUID Unique identifier of the account
* @return <code>true</code> if the account is a placeholder account, <code>false</code> otherwise
*/
public boolean isPlaceholderAccount(String accountUID) {
String isPlaceholder = getAttribute(accountUID, AccountEntry.COLUMN_PLACEHOLDER);
return Integer.parseInt(isPlaceholder) == 1;
}
/**
* Convenience method, resolves the account unique ID and calls {@link #isPlaceholderAccount(String)}
* @param accountUID GUID of the account
* @return <code>true</code> if the account is hidden, <code>false</code> otherwise
*/
public boolean isHiddenAccount(String accountUID){
String isHidden = getAttribute(accountUID, AccountEntry.COLUMN_HIDDEN);
return Integer.parseInt(isHidden) == 1;
}
/**
* Returns true if the account is a favorite account, false otherwise
* @param accountUID GUID of the account
* @return <code>true</code> if the account is a favorite account, <code>false</code> otherwise
*/
public boolean isFavoriteAccount(String accountUID){
String isFavorite = getAttribute(accountUID, AccountEntry.COLUMN_FAVORITE);
return Integer.parseInt(isFavorite) == 1;
}
/**
* Updates all opening balances to the current account balances
*/
public List<Transaction> getAllOpeningBalanceTransactions(){
Cursor cursor = fetchAccounts(null, null, null);
List<Transaction> openingTransactions = new ArrayList<>();
try {
SplitsDbAdapter splitsDbAdapter = mTransactionsAdapter.getSplitDbAdapter();
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(AccountEntry._ID));
String accountUID = getUID(id);
String currencyCode = getCurrencyCode(accountUID);
ArrayList<String> accountList = new ArrayList<>();
accountList.add(accountUID);
Money balance = splitsDbAdapter.computeSplitBalance(accountList,
currencyCode, getAccountType(accountUID).hasDebitNormalBalance());
if (balance.asBigDecimal().compareTo(new BigDecimal(0)) == 0)
continue;
Transaction transaction = new Transaction(GnuCashApplication.getAppContext().getString(R.string.account_name_opening_balances));
transaction.setNote(getAccountName(accountUID));
transaction.setCommodity(Commodity.getInstance(currencyCode));
TransactionType transactionType = Transaction.getTypeForBalance(getAccountType(accountUID),
balance.isNegative());
Split split = new Split(balance, accountUID);
split.setType(transactionType);
transaction.addSplit(split);
transaction.addSplit(split.createPair(getOrCreateOpeningBalanceAccountUID()));
transaction.setExported(true);
openingTransactions.add(transaction);
}
} finally {
cursor.close();
}
return openingTransactions;
}
public static String getImbalanceAccountPrefix() {
return GnuCashApplication.getAppContext().getString(R.string.imbalance_account_name) + "-";
}
/**
* Returns the imbalance account where to store transactions which are not double entry.
*
* @param commodity Commodity of the transaction
* @return Imbalance account name
*/
public static String getImbalanceAccountName(Commodity commodity){
return getImbalanceAccountPrefix() + commodity.getCurrencyCode();
}
/**
* Get the name of the default account for opening balances for the current locale.
* For the English locale, it will be "Equity:Opening Balances"
* @return Fully qualified account name of the opening balances account
*/
public static String getOpeningBalanceAccountFullName(){
Context context = GnuCashApplication.getAppContext();
String parentEquity = context.getString(R.string.account_name_equity).trim();
//German locale has no parent Equity account
if (parentEquity.length() > 0) {
return parentEquity + ACCOUNT_NAME_SEPARATOR
+ context.getString(R.string.account_name_opening_balances);
} else
return context.getString(R.string.account_name_opening_balances);
}
/**
* Returns the account color for the active account as an Android resource ID.
* <p>
* 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
* </p>
* @param accountUID GUID of the account
* @return Android resource ID representing the color which can be directly set to a view
*/
public static int getActiveAccountColorResource(@NonNull String accountUID) {
AccountsDbAdapter accountsDbAdapter = getInstance();
String colorCode = null;
int iColor = -1;
String parentAccountUID = accountUID;
while (parentAccountUID != null ) {
colorCode = accountsDbAdapter.getAccountColorCode(accountsDbAdapter.getID(parentAccountUID));
if (colorCode != null) {
iColor = Color.parseColor(colorCode);
break;
}
parentAccountUID = accountsDbAdapter.getParentAccountUID(parentAccountUID);
}
if (colorCode == null) {
iColor = GnuCashApplication.getAppContext().getResources().getColor(R.color.theme_primary);
}
return iColor;
}
/**
* Returns the list of commodities in use in the database.
*
* <p>This is not the same as the list of all available commodities.</p>
*
* @return List of commodities in use
*/
public List<Commodity> getCommoditiesInUse() {
Cursor cursor = mDb.query(true, AccountEntry.TABLE_NAME, new String[]{AccountEntry.COLUMN_CURRENCY},
null, null, null, null, null, null);
List<Commodity> commodityList = new ArrayList<>();
try {
while (cursor.moveToNext()) {
String currencyCode =
cursor.getString(cursor.getColumnIndexOrThrow(AccountEntry.COLUMN_CURRENCY));
commodityList.add(mCommoditiesDbAdapter.getCommodity(currencyCode));
}
} finally {
cursor.close();
}
return commodityList;
}
/**
* Deletes all accounts, transactions (and their splits) from the database.
* Basically empties all 3 tables, so use with care ;)
*/
@Override
public int deleteAllRecords() {
// Relies "ON DELETE CASCADE" takes too much time
// It take more than 300s to complete the deletion on my dataset without
// clearing the split table first, but only needs a little more that 1s
// if the split table is cleared first.
mDb.delete(DatabaseSchema.PriceEntry.TABLE_NAME, null, null);
mDb.delete(SplitEntry.TABLE_NAME, null, null);
mDb.delete(TransactionEntry.TABLE_NAME, null, null);
mDb.delete(DatabaseSchema.ScheduledActionEntry.TABLE_NAME, null, null);
mDb.delete(DatabaseSchema.BudgetAmountEntry.TABLE_NAME, null, null);
mDb.delete(DatabaseSchema.BudgetEntry.TABLE_NAME, null, null);
mDb.delete(DatabaseSchema.RecurrenceEntry.TABLE_NAME, null, null);
return mDb.delete(AccountEntry.TABLE_NAME, null, null);
}
@Override
public boolean deleteRecord(@NonNull String uid) {
boolean result = super.deleteRecord(uid);
if (result){
ContentValues contentValues = new ContentValues();
contentValues.putNull(AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID);
mDb.update(mTableName, contentValues,
AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID + "=?",
new String[]{uid});
}
return result;
}
public int getTransactionMaxSplitNum(@NonNull String accountUID) {
Cursor cursor = mDb.query("trans_extra_info",
new String[]{"MAX(trans_split_count)"},
"trans_acct_t_uid IN ( SELECT DISTINCT " + TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_UID +
" FROM trans_split_acct WHERE " + AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_UID +
" = ? )",
new String[]{accountUID},
null,
null,
null
);
try {
if (cursor.moveToFirst()) {
return (int)cursor.getLong(0);
} else {
return 0;
}
}
finally {
cursor.close();
}
}
}
| 59,837 | 44.400607 | 154 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/BooksDbAdapter.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db.adapter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.DatabaseSchema.BookEntry;
import org.gnucash.android.model.Book;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.gnucash.android.util.TimestampHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Database adapter for creating/modifying book entries
*/
public class BooksDbAdapter extends DatabaseAdapter<Book> {
/**
* Opens the database adapter with an existing database
* @param db SQLiteDatabase object
*/
public BooksDbAdapter(SQLiteDatabase db) {
super(db, BookEntry.TABLE_NAME, new String[] {
BookEntry.COLUMN_DISPLAY_NAME,
BookEntry.COLUMN_ROOT_GUID,
BookEntry.COLUMN_TEMPLATE_GUID,
BookEntry.COLUMN_SOURCE_URI,
BookEntry.COLUMN_ACTIVE,
BookEntry.COLUMN_UID,
BookEntry.COLUMN_LAST_SYNC
});
}
/**
* Return the application instance of the books database adapter
* @return Books database adapter
*/
public static BooksDbAdapter getInstance(){
return GnuCashApplication.getBooksDbAdapter();
}
@Override
public Book buildModelInstance(@NonNull Cursor cursor) {
String rootAccountGUID = cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_ROOT_GUID));
String rootTemplateGUID = cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_TEMPLATE_GUID));
String uriString = cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_SOURCE_URI));
String displayName = cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_DISPLAY_NAME));
int active = cursor.getInt(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_ACTIVE));
String lastSync = cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_LAST_SYNC));
Book book = new Book(rootAccountGUID);
book.setDisplayName(displayName);
book.setRootTemplateUID(rootTemplateGUID);
book.setSourceUri(uriString == null ? null : Uri.parse(uriString));
book.setActive(active > 0);
book.setLastSync(TimestampHelper.getTimestampFromUtcString(lastSync));
populateBaseModelAttributes(cursor, book);
return book;
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final Book book) {
stmt.clearBindings();
String displayName = book.getDisplayName() == null ? generateDefaultBookName() : book.getDisplayName();
stmt.bindString(1, displayName);
stmt.bindString(2, book.getRootAccountUID());
stmt.bindString(3, book.getRootTemplateUID());
if (book.getSourceUri() != null)
stmt.bindString(4, book.getSourceUri().toString());
stmt.bindLong(5, book.isActive() ? 1L : 0L);
stmt.bindString(6, book.getUID());
stmt.bindString(7, TimestampHelper.getUtcStringFromTimestamp(book.getLastSync()));
return stmt;
}
/**
* Deletes a book - removes the book record from the database and deletes the database file from the disk
* @param bookUID GUID of the book
* @return <code>true</code> if deletion was successful, <code>false</code> otherwise
* @see #deleteRecord(String)
*/
public boolean deleteBook(@NonNull String bookUID){
Context context = GnuCashApplication.getAppContext();
boolean result = context.deleteDatabase(bookUID);
if (result) //delete the db entry only if the file deletion was successful
result &= deleteRecord(bookUID);
PreferenceActivity.getBookSharedPreferences(bookUID).edit().clear().apply();
return result;
}
/**
* Sets the book with unique identifier {@code uid} as active and all others as inactive
* <p>If the parameter is null, then the currently active book is not changed</p>
* @param bookUID Unique identifier of the book
* @return GUID of the currently active book
*/
public String setActive(@NonNull String bookUID){
if (bookUID == null)
return getActiveBookUID();
ContentValues contentValues = new ContentValues();
contentValues.put(BookEntry.COLUMN_ACTIVE, 0);
mDb.update(mTableName, contentValues, null, null); //disable all
contentValues.clear();
contentValues.put(BookEntry.COLUMN_ACTIVE, 1);
mDb.update(mTableName, contentValues, BookEntry.COLUMN_UID + " = ?", new String[]{bookUID});
return bookUID;
}
/**
* Checks if the book is active or not
* @param bookUID GUID of the book
* @return {@code true} if the book is active, {@code false} otherwise
*/
public boolean isActive(String bookUID){
String isActive = getAttribute(bookUID, BookEntry.COLUMN_ACTIVE);
return Integer.parseInt(isActive) > 0;
}
/**
* Returns the GUID of the current active book
* @return GUID of the active book
*/
public @NonNull String getActiveBookUID(){
try (Cursor cursor = mDb.query(mTableName,
new String[]{BookEntry.COLUMN_UID},
BookEntry.COLUMN_ACTIVE + "= 1",
null,
null,
null,
null,
"1")) {
if (cursor.getCount() == 0) {
NoActiveBookFoundException e = new NoActiveBookFoundException(
"There is no active book in the app."
+ "This should NEVER happen, fix your bugs!\n"
+ getNoActiveBookFoundExceptionInfo());
e.printStackTrace();
throw e;
}
cursor.moveToFirst();
return cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_UID));
}
}
private String getNoActiveBookFoundExceptionInfo() {
StringBuilder info = new StringBuilder("UID, created, source\n");
for (Book book : getAllRecords()) {
info.append(String.format("%s, %s, %s\n",
book.getUID(),
book.getCreatedTimestamp(),
book.getSourceUri()));
}
return info.toString();
}
public class NoActiveBookFoundException extends RuntimeException {
public NoActiveBookFoundException(String message) {
super(message);
}
}
/** Tries to fix the books database. */
public void fixBooksDatabase() {
Log.w(LOG_TAG, "Looking for books to set as active...");
if (getRecordsCount() <= 0) {
Log.w(LOG_TAG, "No books found in the database. Recovering books records...");
recoverBookRecords();
}
setFirstBookAsActive();
}
/**
* Restores the records in the book database.
*
* Does so by looking for database files from books.
*/
private void recoverBookRecords() {
for (String dbName : getBookDatabases()) {
Book book = new Book(getRootAccountUID(dbName));
book.setUID(dbName);
book.setDisplayName(generateDefaultBookName());
addRecord(book);
Log.w(LOG_TAG, "Recovered book record: " + book.getUID());
}
}
/**
* Returns the root account UID from the database with name dbName.
*/
private String getRootAccountUID(String dbName) {
Context context = GnuCashApplication.getAppContext();
DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName);
SQLiteDatabase db = databaseHelper.getReadableDatabase();
AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(db,
new TransactionsDbAdapter(db, new SplitsDbAdapter(db)));
String uid = accountsDbAdapter.getOrCreateGnuCashRootAccountUID();
db.close();
return uid;
}
/**
* Sets the first book in the database as active.
*/
private void setFirstBookAsActive() {
Book firstBook = getAllRecords().get(0);
firstBook.setActive(true);
addRecord(firstBook);
Log.w(LOG_TAG, "Book " + firstBook.getUID() + " set as active.");
}
/**
* Returns a list of database names corresponding to book databases.
*/
private List<String> getBookDatabases() {
List<String> bookDatabases = new ArrayList<>();
for (String database : GnuCashApplication.getAppContext().databaseList()) {
if (isBookDatabase(database)) {
bookDatabases.add(database);
}
}
return bookDatabases;
}
private boolean isBookDatabase(String databaseName) {
return databaseName.matches("[a-z0-9]{32}"); // UID regex
}
public @NonNull List<String> getAllBookUIDs(){
List<String> bookUIDs = new ArrayList<>();
try (Cursor cursor = mDb.query(true, mTableName, new String[]{BookEntry.COLUMN_UID},
null, null, null, null, null, null)) {
while (cursor.moveToNext()) {
bookUIDs.add(cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_UID)));
}
}
return bookUIDs;
}
/**
* Return the name of the currently active book.
* Or a generic name if there is no active book (should never happen)
* @return Display name of the book
*/
public @NonNull String getActiveBookDisplayName(){
Cursor cursor = mDb.query(mTableName,
new String[]{BookEntry.COLUMN_DISPLAY_NAME}, BookEntry.COLUMN_ACTIVE + " = 1",
null, null, null, null);
try {
if (cursor.moveToFirst()){
return cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_DISPLAY_NAME));
}
} finally {
cursor.close();
}
return "Book1";
}
/**
* Generates a new default name for a new book
* @return String with default name
*/
public @NonNull String generateDefaultBookName() {
long bookCount = getRecordsCount() + 1;
String sql = "SELECT COUNT(*) FROM " + mTableName + " WHERE " + BookEntry.COLUMN_DISPLAY_NAME + " = ?";
SQLiteStatement statement = mDb.compileStatement(sql);
while (true) {
Context context = GnuCashApplication.getAppContext();
String name = context.getString(R.string.book_default_name, bookCount);
//String name = "Book" + " " + bookCount;
statement.clearBindings();
statement.bindString(1, name);
long nameCount = statement.simpleQueryForLong();
if (nameCount == 0) {
return name;
}
bookCount++;
}
}
}
| 12,057 | 36.331269 | 114 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/BudgetAmountsDbAdapter.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db.adapter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.model.BudgetAmount;
import org.gnucash.android.model.Money;
import java.util.ArrayList;
import java.util.List;
import static org.gnucash.android.db.DatabaseSchema.BudgetAmountEntry;
/**
* Database adapter for {@link BudgetAmount}s
*/
public class BudgetAmountsDbAdapter extends DatabaseAdapter<BudgetAmount> {
/**
* Opens the database adapter with an existing database
*
* @param db SQLiteDatabase object
*/
public BudgetAmountsDbAdapter(SQLiteDatabase db) {
super(db, BudgetAmountEntry.TABLE_NAME, new String[] {
BudgetAmountEntry.COLUMN_BUDGET_UID ,
BudgetAmountEntry.COLUMN_ACCOUNT_UID ,
BudgetAmountEntry.COLUMN_AMOUNT_NUM ,
BudgetAmountEntry.COLUMN_AMOUNT_DENOM ,
BudgetAmountEntry.COLUMN_PERIOD_NUM
});
}
public static BudgetAmountsDbAdapter getInstance(){
return GnuCashApplication.getBudgetAmountsDbAdapter();
}
@Override
public BudgetAmount buildModelInstance(@NonNull Cursor cursor) {
String budgetUID = cursor.getString(cursor.getColumnIndexOrThrow(BudgetAmountEntry.COLUMN_BUDGET_UID));
String accountUID = cursor.getString(cursor.getColumnIndexOrThrow(BudgetAmountEntry.COLUMN_ACCOUNT_UID));
long amountNum = cursor.getLong(cursor.getColumnIndexOrThrow(BudgetAmountEntry.COLUMN_AMOUNT_NUM));
long amountDenom = cursor.getLong(cursor.getColumnIndexOrThrow(BudgetAmountEntry.COLUMN_AMOUNT_DENOM));
long periodNum = cursor.getLong(cursor.getColumnIndexOrThrow(BudgetAmountEntry.COLUMN_PERIOD_NUM));
BudgetAmount budgetAmount = new BudgetAmount(budgetUID, accountUID);
budgetAmount.setAmount(new Money(amountNum, amountDenom, getAccountCurrencyCode(accountUID)));
budgetAmount.setPeriodNum(periodNum);
populateBaseModelAttributes(cursor, budgetAmount);
return budgetAmount;
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final BudgetAmount budgetAmount) {
stmt.clearBindings();
stmt.bindString(1, budgetAmount.getBudgetUID());
stmt.bindString(2, budgetAmount.getAccountUID());
stmt.bindLong(3, budgetAmount.getAmount().getNumerator());
stmt.bindLong(4, budgetAmount.getAmount().getDenominator());
stmt.bindLong(5, budgetAmount.getPeriodNum());
stmt.bindString(6, budgetAmount.getUID());
return stmt;
}
/**
* Return budget amounts for the specific budget
* @param budgetUID GUID of the budget
* @return List of budget amounts
*/
public List<BudgetAmount> getBudgetAmountsForBudget(String budgetUID){
Cursor cursor = fetchAllRecords(BudgetAmountEntry.COLUMN_BUDGET_UID + "=?",
new String[]{budgetUID}, null);
List<BudgetAmount> budgetAmounts = new ArrayList<>();
while (cursor.moveToNext()){
budgetAmounts.add(buildModelInstance(cursor));
}
cursor.close();
return budgetAmounts;
}
/**
* Delete all the budget amounts for a budget
* @param budgetUID GUID of the budget
* @return Number of records deleted
*/
public int deleteBudgetAmountsForBudget(String budgetUID){
return mDb.delete(mTableName, BudgetAmountEntry.COLUMN_BUDGET_UID + "=?",
new String[]{budgetUID});
}
/**
* Returns the budgets associated with a specific account
* @param accountUID GUID of the account
* @return List of {@link BudgetAmount}s for the account
*/
public List<BudgetAmount> getBudgetAmounts(String accountUID) {
Cursor cursor = fetchAllRecords(BudgetAmountEntry.COLUMN_ACCOUNT_UID + " = ?", new String[]{accountUID}, null);
List<BudgetAmount> budgetAmounts = new ArrayList<>();
while(cursor.moveToNext()){
budgetAmounts.add(buildModelInstance(cursor));
}
cursor.close();
return budgetAmounts;
}
/**
* Returns the sum of the budget amounts for a particular account
* @param accountUID GUID of the account
* @return Sum of the budget amounts
*/
public Money getBudgetAmountSum(String accountUID){
List<BudgetAmount> budgetAmounts = getBudgetAmounts(accountUID);
Money sum = Money.createZeroInstance(getAccountCurrencyCode(accountUID));
for (BudgetAmount budgetAmount : budgetAmounts) {
sum = sum.add(budgetAmount.getAmount());
}
return sum;
}
}
| 5,472 | 37.542254 | 125 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/BudgetsDbAdapter.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db.adapter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema.BudgetAmountEntry;
import org.gnucash.android.db.DatabaseSchema.BudgetEntry;
import org.gnucash.android.model.Budget;
import org.gnucash.android.model.BudgetAmount;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Recurrence;
import java.util.ArrayList;
import java.util.List;
/**
* Database adapter for accessing {@link org.gnucash.android.model.Budget} records
*/
public class BudgetsDbAdapter extends DatabaseAdapter<Budget>{
private RecurrenceDbAdapter mRecurrenceDbAdapter;
private BudgetAmountsDbAdapter mBudgetAmountsDbAdapter;
/**
* Opens the database adapter with an existing database
*
* @param db SQLiteDatabase object
*/
public BudgetsDbAdapter(SQLiteDatabase db, BudgetAmountsDbAdapter budgetAmountsDbAdapter,
RecurrenceDbAdapter recurrenceDbAdapter) {
super(db, BudgetEntry.TABLE_NAME, new String[]{
BudgetEntry.COLUMN_NAME,
BudgetEntry.COLUMN_DESCRIPTION,
BudgetEntry.COLUMN_RECURRENCE_UID,
BudgetEntry.COLUMN_NUM_PERIODS
});
mRecurrenceDbAdapter = recurrenceDbAdapter;
mBudgetAmountsDbAdapter = budgetAmountsDbAdapter;
}
/**
* Returns an instance of the budget database adapter
* @return BudgetsDbAdapter instance
*/
public static BudgetsDbAdapter getInstance(){
return GnuCashApplication.getBudgetDbAdapter();
}
@Override
public void addRecord(@NonNull Budget budget, UpdateMethod updateMethod) {
if (budget.getBudgetAmounts().size() == 0)
throw new IllegalArgumentException("Budgets must have budget amounts");
mRecurrenceDbAdapter.addRecord(budget.getRecurrence(), updateMethod);
super.addRecord(budget, updateMethod);
mBudgetAmountsDbAdapter.deleteBudgetAmountsForBudget(budget.getUID());
for (BudgetAmount budgetAmount : budget.getBudgetAmounts()) {
mBudgetAmountsDbAdapter.addRecord(budgetAmount, updateMethod);
}
}
@Override
public long bulkAddRecords(@NonNull List<Budget> budgetList, UpdateMethod updateMethod) {
List<BudgetAmount> budgetAmountList = new ArrayList<>(budgetList.size()*2);
for (Budget budget : budgetList) {
budgetAmountList.addAll(budget.getBudgetAmounts());
}
//first add the recurrences, they have no dependencies (foreign key constraints)
List<Recurrence> recurrenceList = new ArrayList<>(budgetList.size());
for (Budget budget : budgetList) {
recurrenceList.add(budget.getRecurrence());
}
mRecurrenceDbAdapter.bulkAddRecords(recurrenceList, updateMethod);
//now add the budgets themselves
long nRow = super.bulkAddRecords(budgetList, updateMethod);
//then add the budget amounts, they require the budgets to exist
if (nRow > 0 && !budgetAmountList.isEmpty()){
mBudgetAmountsDbAdapter.bulkAddRecords(budgetAmountList, updateMethod);
}
return nRow;
}
@Override
public Budget buildModelInstance(@NonNull Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndexOrThrow(BudgetEntry.COLUMN_NAME));
String description = cursor.getString(cursor.getColumnIndexOrThrow(BudgetEntry.COLUMN_DESCRIPTION));
String recurrenceUID = cursor.getString(cursor.getColumnIndexOrThrow(BudgetEntry.COLUMN_RECURRENCE_UID));
long numPeriods = cursor.getLong(cursor.getColumnIndexOrThrow(BudgetEntry.COLUMN_NUM_PERIODS));
Budget budget = new Budget(name);
budget.setDescription(description);
budget.setRecurrence(mRecurrenceDbAdapter.getRecord(recurrenceUID));
budget.setNumberOfPeriods(numPeriods);
populateBaseModelAttributes(cursor, budget);
budget.setBudgetAmounts(mBudgetAmountsDbAdapter.getBudgetAmountsForBudget(budget.getUID()));
return budget;
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final Budget budget) {
stmt.clearBindings();
stmt.bindString(1, budget.getName());
if (budget.getDescription() != null)
stmt.bindString(2, budget.getDescription());
stmt.bindString(3, budget.getRecurrence().getUID());
stmt.bindLong(4, budget.getNumberOfPeriods());
stmt.bindString(5, budget.getUID());
return stmt;
}
/**
* Fetch all budgets which have an amount specified for the account
* @param accountUID GUID of account
* @return Cursor with budgets data
*/
public Cursor fetchBudgetsForAccount(String accountUID){
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(BudgetEntry.TABLE_NAME + "," + BudgetAmountEntry.TABLE_NAME
+ " ON " + BudgetEntry.TABLE_NAME + "." + BudgetEntry.COLUMN_UID + " = "
+ BudgetAmountEntry.TABLE_NAME + "." + BudgetAmountEntry.COLUMN_BUDGET_UID);
queryBuilder.setDistinct(true);
String[] projectionIn = new String[]{BudgetEntry.TABLE_NAME + ".*"};
String selection = BudgetAmountEntry.TABLE_NAME + "." + BudgetAmountEntry.COLUMN_ACCOUNT_UID + " = ?";
String[] selectionArgs = new String[]{accountUID};
String sortOrder = BudgetEntry.TABLE_NAME + "." + BudgetEntry.COLUMN_NAME + " ASC";
return queryBuilder.query(mDb, projectionIn, selection, selectionArgs, null, null, sortOrder);
}
/**
* Returns the budgets associated with a specific account
* @param accountUID GUID of the account
* @return List of budgets for the account
*/
public List<Budget> getAccountBudgets(String accountUID) {
Cursor cursor = fetchBudgetsForAccount(accountUID);
List<Budget> budgets = new ArrayList<>();
while(cursor.moveToNext()){
budgets.add(buildModelInstance(cursor));
}
cursor.close();
return budgets;
}
/**
* Returns the sum of the account balances for all accounts in a budget for a specified time period
* <p>This represents the total amount spent within the account of this budget in a given period</p>
* @param budgetUID GUID of budget
* @param periodStart Start of the budgeting period in millis
* @param periodEnd End of the budgeting period in millis
* @return Balance of all the accounts
*/
public Money getAccountSum(String budgetUID, long periodStart, long periodEnd){
List<BudgetAmount> budgetAmounts = mBudgetAmountsDbAdapter.getBudgetAmountsForBudget(budgetUID);
List<String> accountUIDs = new ArrayList<>();
for (BudgetAmount budgetAmount : budgetAmounts) {
accountUIDs.add(budgetAmount.getAccountUID());
}
return new AccountsDbAdapter(mDb).getAccountsBalance(accountUIDs, periodStart, periodEnd);
}
}
| 7,925 | 40.28125 | 113 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/CommoditiesDbAdapter.java
|
package org.gnucash.android.db.adapter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.model.Commodity;
import static org.gnucash.android.db.DatabaseSchema.CommodityEntry;
/**
* Database adapter for {@link org.gnucash.android.model.Commodity}
*/
public class CommoditiesDbAdapter extends DatabaseAdapter<Commodity> {
/**
* Opens the database adapter with an existing database
*
* @param db SQLiteDatabase object
*/
public CommoditiesDbAdapter(SQLiteDatabase db) {
super(db, CommodityEntry.TABLE_NAME, new String[]{
CommodityEntry.COLUMN_FULLNAME,
CommodityEntry.COLUMN_NAMESPACE,
CommodityEntry.COLUMN_MNEMONIC,
CommodityEntry.COLUMN_LOCAL_SYMBOL,
CommodityEntry.COLUMN_CUSIP,
CommodityEntry.COLUMN_SMALLEST_FRACTION,
CommodityEntry.COLUMN_QUOTE_FLAG
});
/**
* initialize commonly used commodities
*/
Commodity.USD = getCommodity("USD");
Commodity.EUR = getCommodity("EUR");
Commodity.GBP = getCommodity("GBP");
Commodity.CHF = getCommodity("CHF");
Commodity.CAD = getCommodity("CAD");
Commodity.JPY = getCommodity("JPY");
Commodity.AUD = getCommodity("AUD");
Commodity.DEFAULT_COMMODITY = getCommodity(GnuCashApplication.getDefaultCurrencyCode());
}
public static CommoditiesDbAdapter getInstance(){
return GnuCashApplication.getCommoditiesDbAdapter();
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final Commodity commodity) {
stmt.clearBindings();
stmt.bindString(1, commodity.getFullname());
stmt.bindString(2, commodity.getNamespace().name());
stmt.bindString(3, commodity.getMnemonic());
stmt.bindString(4, commodity.getLocalSymbol());
stmt.bindString(5, commodity.getCusip());
stmt.bindLong(6, commodity.getSmallestFraction());
stmt.bindLong(7, commodity.getQuoteFlag());
stmt.bindString(8, commodity.getUID());
return stmt;
}
@Override
public Commodity buildModelInstance(@NonNull final Cursor cursor) {
String fullname = cursor.getString(cursor.getColumnIndexOrThrow(CommodityEntry.COLUMN_FULLNAME));
String mnemonic = cursor.getString(cursor.getColumnIndexOrThrow(CommodityEntry.COLUMN_MNEMONIC));
String namespace = cursor.getString(cursor.getColumnIndexOrThrow(CommodityEntry.COLUMN_NAMESPACE));
String cusip = cursor.getString(cursor.getColumnIndexOrThrow(CommodityEntry.COLUMN_CUSIP));
String localSymbol = cursor.getString(cursor.getColumnIndexOrThrow(CommodityEntry.COLUMN_LOCAL_SYMBOL));
int fraction = cursor.getInt(cursor.getColumnIndexOrThrow(CommodityEntry.COLUMN_SMALLEST_FRACTION));
int quoteFlag = cursor.getInt(cursor.getColumnIndexOrThrow(CommodityEntry.COLUMN_QUOTE_FLAG));
Commodity commodity = new Commodity(fullname, mnemonic, fraction);
commodity.setNamespace(Commodity.Namespace.valueOf(namespace));
commodity.setCusip(cusip);
commodity.setQuoteFlag(quoteFlag);
commodity.setLocalSymbol(localSymbol);
populateBaseModelAttributes(cursor, commodity);
return commodity;
}
@Override
public Cursor fetchAllRecords() {
return mDb.query(mTableName, null, null, null, null, null,
CommodityEntry.COLUMN_FULLNAME + " ASC");
}
/**
* Fetches all commodities in the database sorted in the specified order
* @param orderBy SQL statement for orderBy without the ORDER_BY itself
* @return Cursor holding all commodity records
*/
public Cursor fetchAllRecords(String orderBy) {
return mDb.query(mTableName, null, null, null, null, null,
orderBy);
}
/**
* Returns the commodity associated with the ISO4217 currency code
* @param currencyCode 3-letter currency code
* @return Commodity associated with code or null if none is found
*/
public Commodity getCommodity(String currencyCode){
Cursor cursor = fetchAllRecords(CommodityEntry.COLUMN_MNEMONIC + "=?", new String[]{currencyCode}, null);
Commodity commodity = null;
if (cursor.moveToNext()){
commodity = buildModelInstance(cursor);
} else {
String msg = "Commodity not found in the database: " + currencyCode;
Log.e(LOG_TAG, msg);
Crashlytics.log(msg);
}
cursor.close();
return commodity;
}
public String getCurrencyCode(@NonNull String guid) {
Cursor cursor = mDb.query(mTableName, new String[]{CommodityEntry.COLUMN_MNEMONIC},
DatabaseSchema.CommonColumns.COLUMN_UID + " = ?", new String[]{guid},
null, null, null);
try {
if (cursor.moveToNext()) {
return cursor.getString(cursor.getColumnIndexOrThrow(CommodityEntry.COLUMN_MNEMONIC));
} else {
throw new IllegalArgumentException("guid " + guid + " not exits in commodity db");
}
} finally {
cursor.close();
}
}
}
| 5,591 | 38.942857 | 119 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/DatabaseAdapter.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db.adapter;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.DatabaseSchema.AccountEntry;
import org.gnucash.android.db.DatabaseSchema.CommonColumns;
import org.gnucash.android.db.DatabaseSchema.SplitEntry;
import org.gnucash.android.db.DatabaseSchema.TransactionEntry;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.BaseModel;
import org.gnucash.android.util.TimestampHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Adapter to be used for creating and opening the database for read/write operations.
* The adapter abstracts several methods for database access and should be subclassed
* by any other adapters to database-backed data models.
* @author Ngewi Fet <[email protected]>
*
*/
public abstract class DatabaseAdapter<Model extends BaseModel> {
/**
* Tag for logging
*/
protected String LOG_TAG = "DatabaseAdapter";
/**
* SQLite database
*/
protected final SQLiteDatabase mDb;
protected final String mTableName;
protected final String[] mColumns;
protected volatile SQLiteStatement mReplaceStatement;
protected volatile SQLiteStatement mUpdateStatement;
protected volatile SQLiteStatement mInsertStatement;
public enum UpdateMethod {
insert, update, replace
};
/**
* Opens the database adapter with an existing database
* @param db SQLiteDatabase object
*/
public DatabaseAdapter(SQLiteDatabase db, @NonNull String tableName, @NonNull String[] columns) {
this.mTableName = tableName;
this.mDb = db;
this.mColumns = columns;
if (!db.isOpen() || db.isReadOnly())
throw new IllegalArgumentException("Database not open or is read-only. Require writeable database");
if (mDb.getVersion() >= 9) {
createTempView();
}
LOG_TAG = getClass().getSimpleName();
}
private void createTempView() {
//the multiplication by 1.0 is to cause sqlite to handle the value as REAL and not to round off
// Create some temporary views. Temporary views only exists in one DB session, and will not
// be saved in the DB
//
// TODO: Useful views should be add to the DB
//
// create a temporary view, combining accounts, transactions and splits, as this is often used
// in the queries
//todo: would it be useful to add the split reconciled_state and reconciled_date to this view?
mDb.execSQL("CREATE TEMP VIEW IF NOT EXISTS trans_split_acct AS SELECT "
+ TransactionEntry.TABLE_NAME + "." + CommonColumns.COLUMN_MODIFIED_AT + " AS "
+ TransactionEntry.TABLE_NAME + "_" + CommonColumns.COLUMN_MODIFIED_AT + " , "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " AS "
+ TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_UID + " , "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_DESCRIPTION + " AS "
+ TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_DESCRIPTION + " , "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_NOTES + " AS "
+ TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_NOTES + " , "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_CURRENCY + " AS "
+ TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_CURRENCY + " , "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TIMESTAMP + " AS "
+ TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_TIMESTAMP + " , "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_EXPORTED + " AS "
+ TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_EXPORTED + " , "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TEMPLATE + " AS "
+ TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_TEMPLATE + " , "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_UID + " AS "
+ SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_UID + " , "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TYPE + " AS "
+ SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_TYPE + " , "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_VALUE_NUM + " AS "
+ SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_VALUE_NUM + " , "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_VALUE_DENOM + " AS "
+ SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_VALUE_DENOM + " , "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_QUANTITY_NUM + " AS "
+ SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_QUANTITY_NUM + " , "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_QUANTITY_DENOM + " AS "
+ SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_QUANTITY_DENOM + " , "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_MEMO + " AS "
+ SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_MEMO + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_UID + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_UID + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_NAME + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_NAME + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_CURRENCY + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_CURRENCY + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_PARENT_ACCOUNT_UID + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_PLACEHOLDER + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_PLACEHOLDER + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_COLOR_CODE + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_COLOR_CODE + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_FAVORITE + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_FAVORITE + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_FULL_NAME + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_FULL_NAME + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_TYPE + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_TYPE + " , "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID + " AS "
+ AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID
+ " FROM " + TransactionEntry.TABLE_NAME + " , " + SplitEntry.TABLE_NAME + " ON "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + "=" + SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID
+ " , " + AccountEntry.TABLE_NAME + " ON "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_ACCOUNT_UID + "=" + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_UID
);
// SELECT transactions_uid AS trans_acct_t_uid ,
// SUBSTR (
// MIN (
// ( CASE WHEN IFNULL ( splits_memo , '' ) == '' THEN 'a' ELSE 'b' END ) || accounts_uid
// ) ,
// 2
// ) AS trans_acct_a_uid ,
// TOTAL ( CASE WHEN splits_type = 'DEBIT' THEN splits_value_num
// ELSE - splits_value_num END ) * 1.0 / splits_value_denom AS trans_acct_balance ,
// COUNT ( DISTINCT accounts_currency_code ) AS trans_currency_count ,
// COUNT (*) AS trans_split_count
// FROM trans_split_acct GROUP BY transactions_uid
//
// This temporary view would pick one Account_UID for each
// Transaction, which can be used to order all transactions. If possible, account_uid of a split whose
// memo is null is select.
//
// Transaction balance is also picked out by this view
//
// a split without split memo is chosen if possible, in the following manner:
// if the splits memo is null or empty string, attach an 'a' in front of the split account uid,
// if not, attach a 'b' to the split account uid
// pick the minimal value of the modified account uid (one of the ones begins with 'a', if exists)
// use substr to get account uid
mDb.execSQL("CREATE TEMP VIEW IF NOT EXISTS trans_extra_info AS SELECT " + TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_UID +
" AS trans_acct_t_uid , SUBSTR ( MIN ( ( CASE WHEN IFNULL ( " + SplitEntry.TABLE_NAME + "_" +
SplitEntry.COLUMN_MEMO + " , '' ) == '' THEN 'a' ELSE 'b' END ) || " +
AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_UID +
" ) , 2 ) AS trans_acct_a_uid , TOTAL ( CASE WHEN " + SplitEntry.TABLE_NAME + "_" +
SplitEntry.COLUMN_TYPE + " = 'DEBIT' THEN "+ SplitEntry.TABLE_NAME + "_" +
SplitEntry.COLUMN_VALUE_NUM + " ELSE - " + SplitEntry.TABLE_NAME + "_" +
SplitEntry.COLUMN_VALUE_NUM + " END ) * 1.0 / " + SplitEntry.TABLE_NAME + "_" +
SplitEntry.COLUMN_VALUE_DENOM + " AS trans_acct_balance , COUNT ( DISTINCT " +
AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_CURRENCY +
" ) AS trans_currency_count , COUNT (*) AS trans_split_count FROM trans_split_acct " +
" GROUP BY " + TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_UID
);
}
/**
* Checks if the database is open
* @return <code>true</code> if the database is open, <code>false</code> otherwise
*/
public boolean isOpen(){
return mDb.isOpen();
}
/**
* Adds a record to the database with the data contained in the model.
* <p>This method uses the SQL REPLACE instructions to replace any record with a matching GUID.
* So beware of any foreign keys with cascade dependencies which might need to be re-added</p>
* @param model Model to be saved to the database
*/
public void addRecord(@NonNull final Model model){
addRecord(model, UpdateMethod.replace);
}
/**
* Add a model record to the database.
* <p>If unsure about which {@code updateMethod} to use, use {@link UpdateMethod#replace}</p>
* @param model Subclass of {@link BaseModel} to be added
* @param updateMethod Method to use for adding the record
*/
public void addRecord(@NonNull final Model model, UpdateMethod updateMethod){
Log.d(LOG_TAG, String.format("Adding %s record to database: ", model.getClass().getSimpleName()));
switch(updateMethod){
case insert:
synchronized(getInsertStatement()) {
setBindings(getInsertStatement(), model).execute();
}
break;
case update:
synchronized(getUpdateStatement()) {
setBindings(getUpdateStatement(), model).execute();
}
break;
default:
synchronized(getReplaceStatement()) {
setBindings(getReplaceStatement(), model).execute();
}
break;
}
}
/**
* Persist the model object to the database as records using the {@code updateMethod}
* @param modelList List of records
* @param updateMethod Method to use when persisting them
* @return Number of rows affected in the database
*/
private long doAddModels(@NonNull final List<Model> modelList, UpdateMethod updateMethod) {
long nRow = 0;
switch (updateMethod) {
case update:
synchronized(getUpdateStatement()) {
for (Model model : modelList) {
setBindings(getUpdateStatement(), model).execute();
nRow++;
}
}
break;
case insert:
synchronized(getInsertStatement()) {
for (Model model : modelList) {
setBindings(getInsertStatement(), model).execute();
nRow++;
}
}
break;
default:
synchronized(getReplaceStatement()) {
for (Model model : modelList) {
setBindings(getReplaceStatement(), model).execute();
nRow++;
}
}
break;
}
return nRow;
}
/**
* Add multiple records to the database at once
* <p>Either all or none of the records will be inserted/updated into the database.</p>
* @param modelList List of model records
* @return Number of rows inserted
*/
public long bulkAddRecords(@NonNull List<Model> modelList){
return bulkAddRecords(modelList, UpdateMethod.replace);
}
public long bulkAddRecords(@NonNull List<Model> modelList, UpdateMethod updateMethod) {
if (modelList.isEmpty()) {
Log.d(LOG_TAG, "Empty model list. Cannot bulk add records, returning 0");
return 0;
}
Log.i(LOG_TAG, String.format("Bulk adding %d %s records to the database", modelList.size(),
modelList.size() == 0 ? "null": modelList.get(0).getClass().getSimpleName()));
long nRow = 0;
try {
mDb.beginTransaction();
nRow = doAddModels(modelList, updateMethod);
mDb.setTransactionSuccessful();
}
finally {
mDb.endTransaction();
}
return nRow;
}
/**
* Builds an instance of the model from the database record entry
* <p>When implementing this method, remember to call {@link #populateBaseModelAttributes(Cursor, BaseModel)}</p>
* @param cursor Cursor pointing to the record
* @return New instance of the model from database record
*/
public abstract Model buildModelInstance(@NonNull final Cursor cursor);
/**
* Generates an {@link SQLiteStatement} with values from the {@code model}.
* This statement can be executed to replace a record in the database.
* <p>If the {@link #mReplaceStatement} is null, subclasses should create a new statement and return.<br/>
* If it is not null, the previous bindings will be cleared and replaced with those from the model</p>
* @return SQLiteStatement for replacing a record in the database
*/
protected final @NonNull SQLiteStatement getReplaceStatement() {
SQLiteStatement stmt = mReplaceStatement;
if (stmt == null) {
synchronized (this) {
stmt = mReplaceStatement;
if (stmt == null) {
mReplaceStatement = stmt
= mDb.compileStatement("REPLACE INTO " + mTableName + " ( "
+ TextUtils.join(" , ", mColumns) + " , "
+ CommonColumns.COLUMN_UID
+ " ) VALUES ( "
+ (new String(new char[mColumns.length]).replace("\0", "? , "))
+ "?)");
}
}
}
return stmt;
}
protected final @NonNull SQLiteStatement getUpdateStatement() {
SQLiteStatement stmt = mUpdateStatement;
if (stmt == null) {
synchronized (this) {
stmt = mUpdateStatement;
if (stmt == null) {
mUpdateStatement = stmt
= mDb.compileStatement("UPDATE " + mTableName + " SET "
+ TextUtils.join(" = ? , ", mColumns) + " = ? WHERE "
+ CommonColumns.COLUMN_UID
+ " = ?");
}
}
}
return stmt;
}
protected final @NonNull SQLiteStatement getInsertStatement() {
SQLiteStatement stmt = mInsertStatement;
if (stmt == null) {
synchronized (this) {
stmt = mInsertStatement;
if (stmt == null) {
mInsertStatement = stmt
= mDb.compileStatement("INSERT INTO " + mTableName + " ( "
+ TextUtils.join(" , ", mColumns) + " , "
+ CommonColumns.COLUMN_UID
+ " ) VALUES ( "
+ (new String(new char[mColumns.length]).replace("\0", "? , "))
+ "?)");
}
}
}
return stmt;
}
/**
* Binds the values from the model the the SQL statement
* @param stmt SQL statement with placeholders
* @param model Model from which to read bind attributes
* @return SQL statement ready for execution
*/
protected abstract @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final Model model);
/**
* Returns a model instance populated with data from the record with GUID {@code uid}
* <p>Sub-classes which require special handling should override this method</p>
* @param uid GUID of the record
* @return BaseModel instance of the record
* @throws IllegalArgumentException if the record UID does not exist in thd database
*/
public Model getRecord(@NonNull String uid){
Log.v(LOG_TAG, "Fetching record with GUID " + uid);
Cursor cursor = fetchRecord(uid);
try {
if (cursor.moveToFirst()) {
return buildModelInstance(cursor);
}
else {
throw new IllegalArgumentException(LOG_TAG + ": Record with " + uid + " does not exist");
}
} finally {
cursor.close();
}
}
/**
* Overload of {@link #getRecord(String)}
* Simply converts the record ID to a GUID and calls {@link #getRecord(String)}
* @param id Database record ID
* @return Subclass of {@link BaseModel} containing record info
*/
public Model getRecord(long id){
return getRecord(getUID(id));
}
/**
* Returns all the records in the database
* @return List of records in the database
*/
public List<Model> getAllRecords(){
List<Model> modelRecords = new ArrayList<>();
Cursor c = fetchAllRecords();
try {
while (c.moveToNext()) {
modelRecords.add(buildModelInstance(c));
}
} finally {
c.close();
}
return modelRecords;
}
/**
* Extracts the attributes of the base model and adds them to the ContentValues object provided
* @param contentValues Content values to which to add attributes
* @param model {@link org.gnucash.android.model.BaseModel} from which to extract values
* @return {@link android.content.ContentValues} with the data to be inserted into the db
*/
protected ContentValues extractBaseModelAttributes(@NonNull ContentValues contentValues, @NonNull Model model){
contentValues.put(CommonColumns.COLUMN_UID, model.getUID());
contentValues.put(CommonColumns.COLUMN_CREATED_AT, TimestampHelper.getUtcStringFromTimestamp(model.getCreatedTimestamp()));
//there is a trigger in the database for updated the modified_at column
/* Due to the use of SQL REPLACE syntax, we insert the created_at values each time
* (maintain the original creation time and not the time of creation of the replacement)
* The updated_at column has a trigger in the database which will update the column
*/
return contentValues;
}
/**
* Initializes the model with values from the database record common to all models (i.e. in the BaseModel)
* @param cursor Cursor pointing to database record
* @param model Model instance to be initialized
*/
protected void populateBaseModelAttributes(Cursor cursor, BaseModel model){
String uid = cursor.getString(cursor.getColumnIndexOrThrow(CommonColumns.COLUMN_UID));
String created = cursor.getString(cursor.getColumnIndexOrThrow(CommonColumns.COLUMN_CREATED_AT));
String modified= cursor.getString(cursor.getColumnIndexOrThrow(CommonColumns.COLUMN_MODIFIED_AT));
model.setUID(uid);
model.setCreatedTimestamp(TimestampHelper.getTimestampFromUtcString(created));
model.setModifiedTimestamp(TimestampHelper.getTimestampFromUtcString(modified));
}
/**
* Retrieves record with id <code>rowId</code> from database table
* @param rowId ID of record to be retrieved
* @return {@link Cursor} to record retrieved
*/
public Cursor fetchRecord(long rowId){
return mDb.query(mTableName, null, DatabaseSchema.CommonColumns._ID + "=" + rowId,
null, null, null, null);
}
/**
* Retrieves record with GUID {@code uid} from database table
* @param uid GUID of record to be retrieved
* @return {@link Cursor} to record retrieved
*/
public Cursor fetchRecord(@NonNull String uid){
return mDb.query(mTableName, null, CommonColumns.COLUMN_UID + "=?" ,
new String[]{uid}, null, null, null);
}
/**
* Retrieves all records from database table
* @return {@link Cursor} to all records in table <code>tableName</code>
*/
public Cursor fetchAllRecords(){
return fetchAllRecords(null, null, null);
}
/**
* Fetch all records from database matching conditions
* @param where SQL where clause
* @param whereArgs String arguments for where clause
* @param orderBy SQL orderby clause
* @return Cursor to records matching conditions
*/
public Cursor fetchAllRecords(String where, String[] whereArgs, String orderBy){
return mDb.query(mTableName, null, where, whereArgs, null, null, orderBy);
}
/**
* Deletes record with ID <code>rowID</code> from database table.
* @param rowId ID of record to be deleted
* @return <code>true</code> if deletion was successful, <code>false</code> otherwise
*/
public boolean deleteRecord(long rowId){
Log.d(LOG_TAG, "Deleting record with id " + rowId + " from " + mTableName);
return mDb.delete(mTableName, DatabaseSchema.CommonColumns._ID + "=" + rowId, null) > 0;
}
/**
* Deletes all records in the database
* @return Number of deleted records
*/
public int deleteAllRecords(){
return mDb.delete(mTableName, null, null);
}
/**
* Returns the string unique ID (GUID) of a record in the database
* @param uid GUID of the record
* @return Long record ID
* @throws IllegalArgumentException if the GUID does not exist in the database
*/
public long getID(@NonNull String uid){
Cursor cursor = mDb.query(mTableName,
new String[] {DatabaseSchema.CommonColumns._ID},
DatabaseSchema.CommonColumns.COLUMN_UID + " = ?",
new String[]{uid},
null, null, null);
long result = -1;
try{
if (cursor.moveToFirst()) {
result = cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseSchema.CommonColumns._ID));
} else {
throw new IllegalArgumentException(mTableName + " with GUID " + uid + " does not exist in the db");
}
} finally {
cursor.close();
}
return result;
}
/**
* Returns the string unique ID (GUID) of a record in the database
* @param id long database record ID
* @return GUID of the record
* @throws IllegalArgumentException if the record ID does not exist in the database
*/
public String getUID(long id){
Cursor cursor = mDb.query(mTableName,
new String[]{DatabaseSchema.CommonColumns.COLUMN_UID},
DatabaseSchema.CommonColumns._ID + " = " + id,
null, null, null, null);
String uid = null;
try {
if (cursor.moveToFirst()) {
uid = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.CommonColumns.COLUMN_UID));
} else {
throw new IllegalArgumentException(mTableName + " Record ID " + id + " does not exist in the db");
}
} finally {
cursor.close();
}
return uid;
}
/**
* Returns the currency code (according to the ISO 4217 standard) of the account
* with unique Identifier <code>accountUID</code>
* @param accountUID Unique Identifier of the account
* @return Currency code of the account. "" if accountUID
* does not exist in DB
*/
public String getAccountCurrencyCode(@NonNull String accountUID) {
Cursor cursor = mDb.query(DatabaseSchema.AccountEntry.TABLE_NAME,
new String[] {DatabaseSchema.AccountEntry.COLUMN_CURRENCY},
DatabaseSchema.AccountEntry.COLUMN_UID + "= ?",
new String[]{accountUID}, null, null, null);
try {
if (cursor.moveToFirst()) {
return cursor.getString(0);
} else {
throw new IllegalArgumentException("Account " + accountUID + " does not exist");
}
} finally {
cursor.close();
}
}
/**
* Returns the commodity GUID for the given ISO 4217 currency code
* @param currencyCode ISO 4217 currency code
* @return GUID of commodity
*/
public String getCommodityUID(String currencyCode){
String where = DatabaseSchema.CommodityEntry.COLUMN_MNEMONIC + "= ?";
String[] whereArgs = new String[]{currencyCode};
Cursor cursor = mDb.query(DatabaseSchema.CommodityEntry.TABLE_NAME,
new String[]{DatabaseSchema.CommodityEntry.COLUMN_UID},
where, whereArgs, null, null, null);
try {
if (cursor.moveToNext()) {
return cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.CommodityEntry.COLUMN_UID));
} else {
throw new IllegalArgumentException("Currency code not found in commodities");
}
} finally {
cursor.close();
}
}
/**
* Returns the {@link org.gnucash.android.model.AccountType} of the account with unique ID <code>uid</code>
* @param accountUID Unique ID of the account
* @return {@link org.gnucash.android.model.AccountType} of the account.
* @throws java.lang.IllegalArgumentException if accountUID does not exist in DB,
*/
public AccountType getAccountType(@NonNull String accountUID){
String type = "";
Cursor c = mDb.query(DatabaseSchema.AccountEntry.TABLE_NAME,
new String[]{DatabaseSchema.AccountEntry.COLUMN_TYPE},
DatabaseSchema.AccountEntry.COLUMN_UID + "=?",
new String[]{accountUID}, null, null, null);
try {
if (c.moveToFirst()) {
type = c.getString(c.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_TYPE));
} else {
throw new IllegalArgumentException("account " + accountUID + " does not exist in DB");
}
} finally {
c.close();
}
return AccountType.valueOf(type);
}
/**
* Updates a record in the table
* @param recordId Database ID of the record to be updated
* @param columnKey Name of column to be updated
* @param newValue New value to be assigned to the columnKey
* @return Number of records affected
*/
protected int updateRecord(String tableName, long recordId, String columnKey, String newValue) {
ContentValues contentValues = new ContentValues();
if (newValue == null) {
contentValues.putNull(columnKey);
} else {
contentValues.put(columnKey, newValue);
}
return mDb.update(tableName, contentValues,
DatabaseSchema.CommonColumns._ID + "=" + recordId, null);
}
/**
* Updates a record in the table
* @param uid GUID of the record
* @param columnKey Name of column to be updated
* @param newValue New value to be assigned to the columnKey
* @return Number of records affected
*/
public int updateRecord(@NonNull String uid, @NonNull String columnKey, String newValue) {
return updateRecords(CommonColumns.COLUMN_UID + "= ?", new String[]{uid}, columnKey, newValue);
}
/**
* Overloaded method. Updates the record with GUID {@code uid} with the content values
* @param uid GUID of the record
* @param contentValues Content values to update
* @return Number of records updated
*/
public int updateRecord(@NonNull String uid, @NonNull ContentValues contentValues){
return mDb.update(mTableName, contentValues, CommonColumns.COLUMN_UID + "=?", new String[]{uid});
}
/**
* Updates all records which match the {@code where} clause with the {@code newValue} for the column
* @param where SQL where clause
* @param whereArgs String arguments for where clause
* @param columnKey Name of column to be updated
* @param newValue New value to be assigned to the columnKey
* @return Number of records affected
*/
public int updateRecords(String where, String[] whereArgs, @NonNull String columnKey, String newValue){
ContentValues contentValues = new ContentValues();
if (newValue == null) {
contentValues.putNull(columnKey);
} else {
contentValues.put(columnKey, newValue);
}
return mDb.update(mTableName, contentValues, where, whereArgs);
}
/**
* Deletes a record from the database given its unique identifier.
* <p>Overload of the method {@link #deleteRecord(long)}</p>
* @param uid GUID of the record
* @return <code>true</code> if deletion was successful, <code>false</code> otherwise
* @see #deleteRecord(long)
*/
public boolean deleteRecord(@NonNull String uid){
return deleteRecord(getID(uid));
}
/**
* Returns an attribute from a specific column in the database for a specific record.
* <p>The attribute is returned as a string which can then be converted to another type if
* the caller was expecting something other type </p>
* @param recordUID GUID of the record
* @param columnName Name of the column to be retrieved
* @return String value of the column entry
* @throws IllegalArgumentException if either the {@code recordUID} or {@code columnName} do not exist in the database
*/
public String getAttribute(@NonNull String recordUID, @NonNull String columnName){
return getAttribute(mTableName, recordUID, columnName);
}
/**
* Returns an attribute from a specific column in the database for a specific record and specific table.
* <p>The attribute is returned as a string which can then be converted to another type if
* the caller was expecting something other type </p>
* <p>This method is an override of {@link #getAttribute(String, String)} which allows to select a value from a
* different table than the one of current adapter instance
* </p>
* @param tableName Database table name. See {@link DatabaseSchema}
* @param recordUID GUID of the record
* @param columnName Name of the column to be retrieved
* @return String value of the column entry
* @throws IllegalArgumentException if either the {@code recordUID} or {@code columnName} do not exist in the database
*/
protected String getAttribute(@NonNull String tableName, @NonNull String recordUID, @NonNull String columnName){
Cursor cursor = mDb.query(tableName,
new String[]{columnName},
AccountEntry.COLUMN_UID + " = ?",
new String[]{recordUID}, null, null, null);
try {
if (cursor.moveToFirst())
return cursor.getString(cursor.getColumnIndexOrThrow(columnName));
else {
throw new IllegalArgumentException(String.format("Record with GUID %s does not exist in the db", recordUID));
}
} finally {
cursor.close();
}
}
/**
* Returns the number of records in the database table backed by this adapter
* @return Total number of records in the database
*/
public long getRecordsCount(){
String sql = "SELECT COUNT(*) FROM " + mTableName;
SQLiteStatement statement = mDb.compileStatement(sql);
return statement.simpleQueryForLong();
}
/**
* Expose mDb.beginTransaction()
*/
public void beginTransaction() {
mDb.beginTransaction();
}
/**
* Expose mDb.setTransactionSuccessful()
*/
public void setTransactionSuccessful() {
mDb.setTransactionSuccessful();
}
/// Foreign key constraits should be enabled in general.
/// But if it affects speed (check constraints takes time)
/// and the constrained can be assured by the program,
/// or if some SQL exec will cause deletion of records
/// (like use replace in accounts update will delete all transactions)
/// that need not be deleted, then it can be disabled temporarily
public void enableForeignKey(boolean enable) {
if (enable){
mDb.execSQL("PRAGMA foreign_keys=ON;");
} else {
mDb.execSQL("PRAGMA foreign_keys=OFF;");
}
}
/**
* Expose mDb.endTransaction()
*/
public void endTransaction() {
mDb.endTransaction();
}
}
| 35,733 | 43.445274 | 161 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/PricesDbAdapter.java
|
package org.gnucash.android.db.adapter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.util.Pair;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.model.Price;
import org.gnucash.android.util.TimestampHelper;
import static org.gnucash.android.db.DatabaseSchema.PriceEntry;
/**
* Database adapter for prices
*/
public class PricesDbAdapter extends DatabaseAdapter<Price> {
/**
* Opens the database adapter with an existing database
* @param db SQLiteDatabase object
*/
public PricesDbAdapter(SQLiteDatabase db) {
super(db, PriceEntry.TABLE_NAME, new String[]{
PriceEntry.COLUMN_COMMODITY_UID,
PriceEntry.COLUMN_CURRENCY_UID,
PriceEntry.COLUMN_DATE,
PriceEntry.COLUMN_SOURCE,
PriceEntry.COLUMN_TYPE,
PriceEntry.COLUMN_VALUE_NUM,
PriceEntry.COLUMN_VALUE_DENOM
});
}
public static PricesDbAdapter getInstance(){
return GnuCashApplication.getPricesDbAdapter();
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final Price price) {
stmt.clearBindings();
stmt.bindString(1, price.getCommodityUID());
stmt.bindString(2, price.getCurrencyUID());
stmt.bindString(3, price.getDate().toString());
if (price.getSource() != null) {
stmt.bindString(4, price.getSource());
}
if (price.getType() != null) {
stmt.bindString(5, price.getType());
}
stmt.bindLong(6, price.getValueNum());
stmt.bindLong(7, price.getValueDenom());
stmt.bindString(8, price.getUID());
return stmt;
}
@Override
public Price buildModelInstance(@NonNull final Cursor cursor) {
String commodityUID = cursor.getString(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_COMMODITY_UID));
String currencyUID = cursor.getString(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_CURRENCY_UID));
String dateString = cursor.getString(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_DATE));
String source = cursor.getString(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_SOURCE));
String type = cursor.getString(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_TYPE));
long valueNum = cursor.getLong(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_VALUE_NUM));
long valueDenom = cursor.getLong(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_VALUE_DENOM));
Price price = new Price(commodityUID, currencyUID);
price.setDate(TimestampHelper.getTimestampFromUtcString(dateString));
price.setSource(source);
price.setType(type);
price.setValueNum(valueNum);
price.setValueDenom(valueDenom);
populateBaseModelAttributes(cursor, price);
return price;
}
/**
* Get the price for commodity / currency pair.
* The price can be used to convert from one commodity to another. The 'commodity' is the origin and the 'currency' is the target for the conversion.
*
* <p>Pair is used instead of Price object because we must sometimes invert the commodity/currency in DB,
* rendering the Price UID invalid.</p>
*
* @param commodityUID GUID of the commodity which is starting point for conversion
* @param currencyUID GUID of target commodity for the conversion
*
* @return The numerator/denominator pair for commodity / currency pair
*/
public Pair<Long, Long> getPrice(@NonNull String commodityUID, @NonNull String currencyUID) {
Pair<Long, Long> pairZero = new Pair<>(0L, 0L);
if (commodityUID.equals(currencyUID))
{
return new Pair<Long, Long>(1L, 1L);
}
Cursor cursor = mDb.query(PriceEntry.TABLE_NAME, null,
// the commodity and currency can be swapped
"( " + PriceEntry.COLUMN_COMMODITY_UID + " = ? AND " + PriceEntry.COLUMN_CURRENCY_UID + " = ? ) OR ( "
+ PriceEntry.COLUMN_COMMODITY_UID + " = ? AND " + PriceEntry.COLUMN_CURRENCY_UID + " = ? )",
new String[]{commodityUID, currencyUID, currencyUID, commodityUID}, null, null,
// only get the latest price
PriceEntry.COLUMN_DATE + " DESC", "1");
try {
if (cursor.moveToNext()) {
String commodityUIDdb = cursor.getString(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_COMMODITY_UID));
long valueNum = cursor.getLong(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_VALUE_NUM));
long valueDenom = cursor.getLong(cursor.getColumnIndexOrThrow(PriceEntry.COLUMN_VALUE_DENOM));
if (valueNum < 0 || valueDenom < 0) {
// this should not happen
return pairZero;
}
if (!commodityUIDdb.equals(commodityUID)) {
// swap Num and denom
long t = valueNum;
valueNum = valueDenom;
valueDenom = t;
}
return new Pair<Long, Long>(valueNum, valueDenom);
} else {
return pairZero;
}
} finally {
cursor.close();
}
}
}
| 5,511 | 42.0625 | 153 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/RecurrenceDbAdapter.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db.adapter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.model.PeriodType;
import org.gnucash.android.model.Recurrence;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import static org.gnucash.android.db.DatabaseSchema.RecurrenceEntry;
/**
* Database adapter for {@link Recurrence} entries
*/
public class RecurrenceDbAdapter extends DatabaseAdapter<Recurrence> {
/**
* Opens the database adapter with an existing database
*
* @param db SQLiteDatabase object
*/
public RecurrenceDbAdapter(SQLiteDatabase db) {
super(db, RecurrenceEntry.TABLE_NAME, new String[]{
RecurrenceEntry.COLUMN_MULTIPLIER,
RecurrenceEntry.COLUMN_PERIOD_TYPE,
RecurrenceEntry.COLUMN_BYDAY,
RecurrenceEntry.COLUMN_PERIOD_START,
RecurrenceEntry.COLUMN_PERIOD_END
});
}
public static RecurrenceDbAdapter getInstance(){
return GnuCashApplication.getRecurrenceDbAdapter();
}
@Override
public Recurrence buildModelInstance(@NonNull Cursor cursor) {
String type = cursor.getString(cursor.getColumnIndexOrThrow(RecurrenceEntry.COLUMN_PERIOD_TYPE));
long multiplier = cursor.getLong(cursor.getColumnIndexOrThrow(RecurrenceEntry.COLUMN_MULTIPLIER));
String periodStart = cursor.getString(cursor.getColumnIndexOrThrow(RecurrenceEntry.COLUMN_PERIOD_START));
String periodEnd = cursor.getString(cursor.getColumnIndexOrThrow(RecurrenceEntry.COLUMN_PERIOD_END));
String byDays = cursor.getString(cursor.getColumnIndexOrThrow(RecurrenceEntry.COLUMN_BYDAY));
PeriodType periodType = PeriodType.valueOf(type);
Recurrence recurrence = new Recurrence(periodType);
recurrence.setMultiplier((int) multiplier);
recurrence.setPeriodStart(Timestamp.valueOf(periodStart));
if (periodEnd != null)
recurrence.setPeriodEnd(Timestamp.valueOf(periodEnd));
recurrence.setByDays(stringToByDays(byDays));
populateBaseModelAttributes(cursor, recurrence);
return recurrence;
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final Recurrence recurrence) {
stmt.clearBindings();
stmt.bindLong(1, recurrence.getMultiplier());
stmt.bindString(2, recurrence.getPeriodType().name());
if (!recurrence.getByDays().isEmpty())
stmt.bindString(3, byDaysToString(recurrence.getByDays()));
//recurrence should always have a start date
stmt.bindString(4, recurrence.getPeriodStart().toString());
if (recurrence.getPeriodEnd() != null)
stmt.bindString(5, recurrence.getPeriodEnd().toString());
stmt.bindString(6, recurrence.getUID());
return stmt;
}
/**
* Converts a list of days of week as Calendar constants to an String for
* storing in the database.
*
* @param byDays list of days of week constants from Calendar
* @return String of days of the week or null if {@code byDays} was empty
*/
private static @NonNull String byDaysToString(@NonNull List<Integer> byDays) {
StringBuilder builder = new StringBuilder();
for (int day : byDays) {
switch (day) {
case Calendar.MONDAY:
builder.append("MO");
break;
case Calendar.TUESDAY:
builder.append("TU");
break;
case Calendar.WEDNESDAY:
builder.append("WE");
break;
case Calendar.THURSDAY:
builder.append("TH");
break;
case Calendar.FRIDAY:
builder.append("FR");
break;
case Calendar.SATURDAY:
builder.append("SA");
break;
case Calendar.SUNDAY:
builder.append("SU");
break;
default:
throw new RuntimeException("bad day of week: " + day);
}
builder.append(",");
}
builder.deleteCharAt(builder.length()-1);
return builder.toString();
}
/**
* Converts a String with the comma-separated days of the week into a
* list of Calendar constants.
*
* @param byDaysString String with comma-separated days fo the week
* @return list of days of the week as Calendar constants.
*/
private static @NonNull List<Integer> stringToByDays(@Nullable String byDaysString) {
if (byDaysString == null)
return Collections.emptyList();
List<Integer> byDaysList = new ArrayList<>();
for (String day : byDaysString.split(",")) {
switch (day) {
case "MO":
byDaysList.add(Calendar.MONDAY);
break;
case "TU":
byDaysList.add(Calendar.TUESDAY);
break;
case "WE":
byDaysList.add(Calendar.WEDNESDAY);
break;
case "TH":
byDaysList.add(Calendar.THURSDAY);
break;
case "FR":
byDaysList.add(Calendar.FRIDAY);
break;
case "SA":
byDaysList.add(Calendar.SATURDAY);
break;
case "SU":
byDaysList.add(Calendar.SUNDAY);
break;
default:
throw new RuntimeException("bad day of week: " + day);
}
}
return byDaysList;
}
}
| 6,771 | 36.208791 | 121 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/ScheduledActionDbAdapter.java
|
/*
* Copyright (c) 2014 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db.adapter;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.util.Log;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.model.Recurrence;
import org.gnucash.android.model.ScheduledAction;
import java.util.ArrayList;
import java.util.List;
import static org.gnucash.android.db.DatabaseSchema.ScheduledActionEntry;
/**
* Database adapter for fetching/saving/modifying scheduled events
*
* @author Ngewi Fet <[email protected]>
*/
public class ScheduledActionDbAdapter extends DatabaseAdapter<ScheduledAction> {
private RecurrenceDbAdapter mRecurrenceDbAdapter;
public ScheduledActionDbAdapter(SQLiteDatabase db, RecurrenceDbAdapter recurrenceDbAdapter){
super(db, ScheduledActionEntry.TABLE_NAME, new String[]{
ScheduledActionEntry.COLUMN_ACTION_UID ,
ScheduledActionEntry.COLUMN_TYPE ,
ScheduledActionEntry.COLUMN_START_TIME ,
ScheduledActionEntry.COLUMN_END_TIME ,
ScheduledActionEntry.COLUMN_LAST_RUN ,
ScheduledActionEntry.COLUMN_ENABLED ,
ScheduledActionEntry.COLUMN_CREATED_AT ,
ScheduledActionEntry.COLUMN_TAG ,
ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY ,
ScheduledActionEntry.COLUMN_RECURRENCE_UID ,
ScheduledActionEntry.COLUMN_AUTO_CREATE ,
ScheduledActionEntry.COLUMN_AUTO_NOTIFY ,
ScheduledActionEntry.COLUMN_ADVANCE_CREATION ,
ScheduledActionEntry.COLUMN_ADVANCE_NOTIFY ,
ScheduledActionEntry.COLUMN_TEMPLATE_ACCT_UID ,
ScheduledActionEntry.COLUMN_EXECUTION_COUNT
});
mRecurrenceDbAdapter = recurrenceDbAdapter;
LOG_TAG = "ScheduledActionDbAdapter";
}
/**
* Returns application-wide instance of database adapter
* @return ScheduledEventDbAdapter instance
*/
public static ScheduledActionDbAdapter getInstance(){
return GnuCashApplication.getScheduledEventDbAdapter();
}
@Override
public void addRecord(@NonNull ScheduledAction scheduledAction, UpdateMethod updateMethod) {
mRecurrenceDbAdapter.addRecord(scheduledAction.getRecurrence(), updateMethod);
super.addRecord(scheduledAction, updateMethod);
}
@Override
public long bulkAddRecords(@NonNull List<ScheduledAction> scheduledActions, UpdateMethod updateMethod) {
List<Recurrence> recurrenceList = new ArrayList<>(scheduledActions.size());
for (ScheduledAction scheduledAction : scheduledActions) {
recurrenceList.add(scheduledAction.getRecurrence());
}
//first add the recurrences, they have no dependencies (foreign key constraints)
long nRecurrences = mRecurrenceDbAdapter.bulkAddRecords(recurrenceList, updateMethod);
Log.d(LOG_TAG, String.format("Added %d recurrences for scheduled actions", nRecurrences));
return super.bulkAddRecords(scheduledActions, updateMethod);
}
/**
* Updates only the recurrence attributes of the scheduled action.
* The recurrence attributes are the period, start time, end time and/or total frequency.
* All other properties of a scheduled event are only used for internal database tracking and are
* not central to the recurrence schedule.
* <p><b>The GUID of the scheduled action should already exist in the database</b></p>
* @param scheduledAction Scheduled action
* @return Database record ID of the edited scheduled action
*/
public long updateRecurrenceAttributes(ScheduledAction scheduledAction){
//since we are updating, first fetch the existing recurrence UID and set it to the object
//so that it will be updated and not a new one created
RecurrenceDbAdapter recurrenceDbAdapter = new RecurrenceDbAdapter(mDb);
String recurrenceUID = recurrenceDbAdapter.getAttribute(scheduledAction.getUID(), ScheduledActionEntry.COLUMN_RECURRENCE_UID);
Recurrence recurrence = scheduledAction.getRecurrence();
recurrence.setUID(recurrenceUID);
recurrenceDbAdapter.addRecord(recurrence, UpdateMethod.update);
ContentValues contentValues = new ContentValues();
extractBaseModelAttributes(contentValues, scheduledAction);
contentValues.put(ScheduledActionEntry.COLUMN_START_TIME, scheduledAction.getStartTime());
contentValues.put(ScheduledActionEntry.COLUMN_END_TIME, scheduledAction.getEndTime());
contentValues.put(ScheduledActionEntry.COLUMN_TAG, scheduledAction.getTag());
contentValues.put(ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY, scheduledAction.getTotalPlannedExecutionCount());
Log.d(LOG_TAG, "Updating scheduled event recurrence attributes");
String where = ScheduledActionEntry.COLUMN_UID + "=?";
String[] whereArgs = new String[]{scheduledAction.getUID()};
return mDb.update(ScheduledActionEntry.TABLE_NAME, contentValues, where, whereArgs);
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final ScheduledAction schedxAction) {
stmt.clearBindings();
stmt.bindString(1, schedxAction.getActionUID());
stmt.bindString(2, schedxAction.getActionType().name());
stmt.bindLong(3, schedxAction.getStartTime());
stmt.bindLong(4, schedxAction.getEndTime());
stmt.bindLong(5, schedxAction.getLastRunTime());
stmt.bindLong(6, schedxAction.isEnabled() ? 1 : 0);
stmt.bindString(7, schedxAction.getCreatedTimestamp().toString());
if (schedxAction.getTag() == null)
stmt.bindNull(8);
else
stmt.bindString(8, schedxAction.getTag());
stmt.bindString(9, Integer.toString(schedxAction.getTotalPlannedExecutionCount()));
stmt.bindString(10, schedxAction.getRecurrence().getUID());
stmt.bindLong(11, schedxAction.shouldAutoCreate() ? 1 : 0);
stmt.bindLong(12, schedxAction.shouldAutoNotify() ? 1 : 0);
stmt.bindLong(13, schedxAction.getAdvanceCreateDays());
stmt.bindLong(14, schedxAction.getAdvanceNotifyDays());
stmt.bindString(15, schedxAction.getTemplateAccountUID());
stmt.bindString(16, Integer.toString(schedxAction.getExecutionCount()));
stmt.bindString(17, schedxAction.getUID());
return stmt;
}
/**
* Builds a {@link org.gnucash.android.model.ScheduledAction} instance from a row to cursor in the database.
* The cursor should be already pointing to the right entry in the data set. It will not be modified in any way
* @param cursor Cursor pointing to data set
* @return ScheduledEvent object instance
*/
@Override
public ScheduledAction buildModelInstance(@NonNull final Cursor cursor){
String actionUid = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_ACTION_UID));
long startTime = cursor.getLong(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_START_TIME));
long endTime = cursor.getLong(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_END_TIME));
long lastRun = cursor.getLong(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_LAST_RUN));
String typeString = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_TYPE));
String tag = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_TAG));
boolean enabled = cursor.getInt(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_ENABLED)) > 0;
int numOccurrences = cursor.getInt(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY));
int execCount = cursor.getInt(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_EXECUTION_COUNT));
int autoCreate = cursor.getInt(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_AUTO_CREATE));
int autoNotify = cursor.getInt(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_AUTO_NOTIFY));
int advanceCreate = cursor.getInt(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_ADVANCE_CREATION));
int advanceNotify = cursor.getInt(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_ADVANCE_NOTIFY));
String recurrenceUID = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_RECURRENCE_UID));
String templateActUID = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_TEMPLATE_ACCT_UID));
ScheduledAction event = new ScheduledAction(ScheduledAction.ActionType.valueOf(typeString));
populateBaseModelAttributes(cursor, event);
event.setStartTime(startTime);
event.setEndTime(endTime);
event.setActionUID(actionUid);
event.setLastRun(lastRun);
event.setTag(tag);
event.setEnabled(enabled);
event.setTotalPlannedExecutionCount(numOccurrences);
event.setExecutionCount(execCount);
event.setAutoCreate(autoCreate == 1);
event.setAutoNotify(autoNotify == 1);
event.setAdvanceCreateDays(advanceCreate);
event.setAdvanceNotifyDays(advanceNotify);
//TODO: optimize by doing overriding fetchRecord(String) and join the two tables
event.setRecurrence(mRecurrenceDbAdapter.getRecord(recurrenceUID));
event.setTemplateAccountUID(templateActUID);
return event;
}
/**
* Returns all {@link org.gnucash.android.model.ScheduledAction}s from the database with the specified action UID.
* Note that the parameter is not of the the scheduled action record, but from the action table
* @param actionUID GUID of the event itself
* @return List of ScheduledEvents
*/
public List<ScheduledAction> getScheduledActionsWithUID(@NonNull String actionUID){
Cursor cursor = mDb.query(ScheduledActionEntry.TABLE_NAME, null,
ScheduledActionEntry.COLUMN_ACTION_UID + "= ?",
new String[]{actionUID}, null, null, null);
List<ScheduledAction> scheduledActions = new ArrayList<>();
try {
while (cursor.moveToNext()) {
scheduledActions.add(buildModelInstance(cursor));
}
} finally {
cursor.close();
}
return scheduledActions;
}
/**
* Returns all enabled scheduled actions in the database
* @return List of enabled scheduled actions
*/
public List<ScheduledAction> getAllEnabledScheduledActions(){
Cursor cursor = mDb.query(mTableName,
null, ScheduledActionEntry.COLUMN_ENABLED + "=1", null, null, null, null);
List<ScheduledAction> scheduledActions = new ArrayList<>();
while (cursor.moveToNext()){
scheduledActions.add(buildModelInstance(cursor));
}
return scheduledActions;
}
/**
* Returns the number of instances of the action which have been created from this scheduled action
* @param scheduledActionUID GUID of scheduled action
* @return Number of transactions created from scheduled action
*/
public long getActionInstanceCount(String scheduledActionUID) {
String sql = "SELECT COUNT(*) FROM " + DatabaseSchema.TransactionEntry.TABLE_NAME
+ " WHERE " + DatabaseSchema.TransactionEntry.COLUMN_SCHEDX_ACTION_UID + "=?";
SQLiteStatement statement = mDb.compileStatement(sql);
statement.bindString(1, scheduledActionUID);
return statement.simpleQueryForLong();
}
}
| 12,586 | 49.959514 | 134 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/SplitsDbAdapter.java
|
/*
* Copyright (c) 2014 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db.adapter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.TransactionType;
import org.gnucash.android.util.TimestampHelper;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import static org.gnucash.android.db.DatabaseSchema.SplitEntry;
import static org.gnucash.android.db.DatabaseSchema.TransactionEntry;
/**
* Database adapter for managing transaction splits in the database
*
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
* @author Oleksandr Tyshkovets <[email protected]>
*/
public class SplitsDbAdapter extends DatabaseAdapter<Split> {
public SplitsDbAdapter(SQLiteDatabase db) {
super(db, SplitEntry.TABLE_NAME, new String[]{
SplitEntry.COLUMN_MEMO,
SplitEntry.COLUMN_TYPE,
SplitEntry.COLUMN_VALUE_NUM,
SplitEntry.COLUMN_VALUE_DENOM,
SplitEntry.COLUMN_QUANTITY_NUM,
SplitEntry.COLUMN_QUANTITY_DENOM,
SplitEntry.COLUMN_CREATED_AT,
SplitEntry.COLUMN_RECONCILE_STATE,
SplitEntry.COLUMN_RECONCILE_DATE,
SplitEntry.COLUMN_ACCOUNT_UID,
SplitEntry.COLUMN_TRANSACTION_UID
});
}
/**
* Returns application-wide instance of the database adapter
* @return SplitsDbAdapter instance
*/
public static SplitsDbAdapter getInstance(){
return GnuCashApplication.getSplitsDbAdapter();
}
/**
* Adds a split to the database.
* The transactions belonging to the split are marked as exported
* @param split {@link org.gnucash.android.model.Split} to be recorded in DB
*/
public void addRecord(@NonNull final Split split, UpdateMethod updateMethod){
Log.d(LOG_TAG, "Replace transaction split in db");
super.addRecord(split, updateMethod);
long transactionId = getTransactionID(split.getTransactionUID());
//when a split is updated, we want mark the transaction as not exported
updateRecord(TransactionEntry.TABLE_NAME, transactionId,
TransactionEntry.COLUMN_EXPORTED, String.valueOf(0));
//modifying a split means modifying the accompanying transaction as well
updateRecord(TransactionEntry.TABLE_NAME, transactionId,
TransactionEntry.COLUMN_MODIFIED_AT, TimestampHelper.getUtcStringFromTimestamp(TimestampHelper.getTimestampFromNow()));
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull final Split split) {
stmt.clearBindings();
if (split.getMemo() != null) {
stmt.bindString(1, split.getMemo());
}
stmt.bindString(2, split.getType().name());
stmt.bindLong(3, split.getValue().getNumerator());
stmt.bindLong(4, split.getValue().getDenominator());
stmt.bindLong(5, split.getQuantity().getNumerator());
stmt.bindLong(6, split.getQuantity().getDenominator());
stmt.bindString(7, split.getCreatedTimestamp().toString());
stmt.bindString(8, String.valueOf(split.getReconcileState()));
stmt.bindString(9, split.getReconcileDate().toString());
stmt.bindString(10, split.getAccountUID());
stmt.bindString(11, split.getTransactionUID());
stmt.bindString(12, split.getUID());
return stmt;
}
/**
* Builds a split instance from the data pointed to by the cursor provided
* <p>This method will not move the cursor in any way. So the cursor should already by pointing to the correct entry</p>
* @param cursor Cursor pointing to transaction record in database
* @return {@link org.gnucash.android.model.Split} instance
*/
public Split buildModelInstance(@NonNull final Cursor cursor){
long valueNum = cursor.getLong(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_VALUE_NUM));
long valueDenom = cursor.getLong(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_VALUE_DENOM));
long quantityNum = cursor.getLong(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_QUANTITY_NUM));
long quantityDenom = cursor.getLong(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_QUANTITY_DENOM));
String typeName = cursor.getString(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_TYPE));
String accountUID = cursor.getString(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_ACCOUNT_UID));
String transxUID = cursor.getString(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_TRANSACTION_UID));
String memo = cursor.getString(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_MEMO));
String reconcileState = cursor.getString(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_RECONCILE_STATE));
String reconcileDate = cursor.getString(cursor.getColumnIndexOrThrow(SplitEntry.COLUMN_RECONCILE_DATE));
String transactionCurrency = getAttribute(TransactionEntry.TABLE_NAME, transxUID, TransactionEntry.COLUMN_CURRENCY);
Money value = new Money(valueNum, valueDenom, transactionCurrency);
String currencyCode = getAccountCurrencyCode(accountUID);
Money quantity = new Money(quantityNum, quantityDenom, currencyCode);
Split split = new Split(value, accountUID);
split.setQuantity(quantity);
populateBaseModelAttributes(cursor, split);
split.setTransactionUID(transxUID);
split.setType(TransactionType.valueOf(typeName));
split.setMemo(memo);
split.setReconcileState(reconcileState.charAt(0));
if (reconcileDate != null && !reconcileDate.isEmpty())
split.setReconcileDate(TimestampHelper.getTimestampFromUtcString(reconcileDate));
return split;
}
/**
* Returns the sum of the splits for given set of accounts.
* This takes into account the kind of movement caused by the split in the account (which also depends on account type)
* The Caller must make sure all accounts have the currency, which is passed in as currencyCode
* @param accountUIDList List of String unique IDs of given set of accounts
* @param currencyCode currencyCode for all the accounts in the list
* @param hasDebitNormalBalance Does the final balance has normal debit credit meaning
* @return Balance of the splits for this account
*/
public Money computeSplitBalance(List<String> accountUIDList, String currencyCode, boolean hasDebitNormalBalance){
return calculateSplitBalance(accountUIDList, currencyCode, hasDebitNormalBalance, -1, -1);
}
/**
* Returns the sum of the splits for given set of accounts within the specified time range.
* This takes into account the kind of movement caused by the split in the account (which also depends on account type)
* The Caller must make sure all accounts have the currency, which is passed in as currencyCode
* @param accountUIDList List of String unique IDs of given set of accounts
* @param currencyCode currencyCode for all the accounts in the list
* @param hasDebitNormalBalance Does the final balance has normal debit credit meaning
* @param startTimestamp the start timestamp of the time range
* @param endTimestamp the end timestamp of the time range
* @return Balance of the splits for this account within the specified time range
*/
public Money computeSplitBalance(List<String> accountUIDList, String currencyCode, boolean hasDebitNormalBalance,
long startTimestamp, long endTimestamp){
return calculateSplitBalance(accountUIDList, currencyCode, hasDebitNormalBalance, startTimestamp, endTimestamp);
}
private Money calculateSplitBalance(List<String> accountUIDList, String currencyCode, boolean hasDebitNormalBalance,
long startTimestamp, long endTimestamp){
if (accountUIDList.size() == 0){
return new Money("0", currencyCode);
}
Cursor cursor;
String[] selectionArgs = null;
String selection = DatabaseSchema.AccountEntry.TABLE_NAME + "_" + DatabaseSchema.CommonColumns.COLUMN_UID + " in ( '" + TextUtils.join("' , '", accountUIDList) + "' ) AND " +
TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_TEMPLATE + " = 0";
if (startTimestamp != -1 && endTimestamp != -1) {
selection += " AND " + TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_TIMESTAMP + " BETWEEN ? AND ? ";
selectionArgs = new String[]{String.valueOf(startTimestamp), String.valueOf(endTimestamp)};
} else if (startTimestamp == -1 && endTimestamp != -1) {
selection += " AND " + TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_TIMESTAMP + " <= ?";
selectionArgs = new String[]{String.valueOf(endTimestamp)};
} else if (startTimestamp != -1/* && endTimestamp == -1*/) {
selection += " AND " + TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_TIMESTAMP + " >= ?";
selectionArgs = new String[]{String.valueOf(startTimestamp)};
}
cursor = mDb.query("trans_split_acct",
new String[]{"TOTAL ( CASE WHEN " + SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_TYPE + " = 'DEBIT' THEN " +
SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_QUANTITY_NUM + " ELSE - " +
SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_QUANTITY_NUM + " END )",
SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_QUANTITY_DENOM,
DatabaseSchema.AccountEntry.TABLE_NAME + "_" + DatabaseSchema.AccountEntry.COLUMN_CURRENCY},
selection, selectionArgs, DatabaseSchema.AccountEntry.TABLE_NAME + "_" + DatabaseSchema.AccountEntry.COLUMN_CURRENCY, null, null);
try {
Money total = Money.createZeroInstance(currencyCode);
CommoditiesDbAdapter commoditiesDbAdapter = null;
PricesDbAdapter pricesDbAdapter = null;
Commodity commodity = null;
String currencyUID = null;
while (cursor.moveToNext()) {
long amount_num = cursor.getLong(0);
long amount_denom = cursor.getLong(1);
String commodityCode = cursor.getString(2);
//Log.d(getClass().getName(), commodity + " " + amount_num + "/" + amount_denom);
if (commodityCode.equals("XXX") || amount_num == 0) {
// ignore custom currency
continue;
}
if (!hasDebitNormalBalance) {
amount_num = -amount_num;
}
if (commodityCode.equals(currencyCode)) {
// currency matches
total = total.add(new Money(amount_num, amount_denom, currencyCode));
//Log.d(getClass().getName(), "currency " + commodity + " sub - total " + total);
} else {
// there is a second currency involved
if (commoditiesDbAdapter == null) {
commoditiesDbAdapter = new CommoditiesDbAdapter(mDb);
pricesDbAdapter = new PricesDbAdapter(mDb);
commodity = commoditiesDbAdapter.getCommodity(currencyCode);
currencyUID = commoditiesDbAdapter.getCommodityUID(currencyCode);
}
// get price
String commodityUID = commoditiesDbAdapter.getCommodityUID(commodityCode);
Pair<Long, Long> price = pricesDbAdapter.getPrice(commodityUID, currencyUID);
if (price.first <= 0 || price.second <= 0) {
// no price exists, just ignore it
continue;
}
BigDecimal amount = Money.getBigDecimal(amount_num, amount_denom);
BigDecimal amountConverted = amount.multiply(new BigDecimal(price.first))
.divide(new BigDecimal(price.second), commodity.getSmallestFractionDigits(), BigDecimal.ROUND_HALF_EVEN);
total = total.add(new Money(amountConverted, commodity));
//Log.d(getClass().getName(), "currency " + commodity + " sub - total " + total);
}
}
return total;
} finally {
cursor.close();
}
}
/**
* Returns the list of splits for a transaction
* @param transactionUID String unique ID of transaction
* @return List of {@link org.gnucash.android.model.Split}s
*/
public List<Split> getSplitsForTransaction(String transactionUID){
Cursor cursor = fetchSplitsForTransaction(transactionUID);
List<Split> splitList = new ArrayList<Split>();
try {
while (cursor.moveToNext()) {
splitList.add(buildModelInstance(cursor));
}
} finally {
cursor.close();
}
return splitList;
}
/**
* Returns the list of splits for a transaction
* @param transactionID DB record ID of the transaction
* @return List of {@link org.gnucash.android.model.Split}s
* @see #getSplitsForTransaction(String)
* @see #getTransactionUID(long)
*/
public List<Split> getSplitsForTransaction(long transactionID){
return getSplitsForTransaction(getTransactionUID(transactionID));
}
/**
* Fetch splits for a given transaction within a specific account
* @param transactionUID String unique ID of transaction
* @param accountUID String unique ID of account
* @return List of splits
*/
public List<Split> getSplitsForTransactionInAccount(String transactionUID, String accountUID){
Cursor cursor = fetchSplitsForTransactionAndAccount(transactionUID, accountUID);
List<Split> splitList = new ArrayList<Split>();
if (cursor != null){
while (cursor.moveToNext()){
splitList.add(buildModelInstance(cursor));
}
cursor.close();
}
return splitList;
}
/**
* Fetches a collection of splits for a given condition and sorted by <code>sortOrder</code>
* @param where String condition, formatted as SQL WHERE clause
* @param whereArgs where args
* @param sortOrder Sort order for the returned records
* @return Cursor to split records
*/
public Cursor fetchSplits(String where, String[] whereArgs, String sortOrder){
return mDb.query(SplitEntry.TABLE_NAME,
null, where, whereArgs, null, null, sortOrder);
}
/**
* Returns a Cursor to a dataset of splits belonging to a specific transaction
* @param transactionUID Unique idendtifier of the transaction
* @return Cursor to splits
*/
public Cursor fetchSplitsForTransaction(String transactionUID){
Log.v(LOG_TAG, "Fetching all splits for transaction UID " + transactionUID);
return mDb.query(SplitEntry.TABLE_NAME,
null, SplitEntry.COLUMN_TRANSACTION_UID + " = ?",
new String[]{transactionUID},
null, null, null);
}
/**
* Fetches splits for a given account
* @param accountUID String unique ID of account
* @return Cursor containing splits dataset
*/
public Cursor fetchSplitsForAccount(String accountUID){
Log.d(LOG_TAG, "Fetching all splits for account UID " + accountUID);
//This is more complicated than a simple "where account_uid=?" query because
// we need to *not* return any splits which belong to recurring transactions
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TransactionEntry.TABLE_NAME
+ " INNER JOIN " + SplitEntry.TABLE_NAME + " ON "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " = "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID);
queryBuilder.setDistinct(true);
String[] projectionIn = new String[]{SplitEntry.TABLE_NAME + ".*"};
String selection = SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_ACCOUNT_UID + " = ?"
+ " AND " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TEMPLATE + " = 0";
String[] selectionArgs = new String[]{accountUID};
String sortOrder = TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TIMESTAMP + " DESC";
return queryBuilder.query(mDb, projectionIn, selection, selectionArgs, null, null, sortOrder);
}
/**
* Returns a cursor to splits for a given transaction and account
* @param transactionUID Unique idendtifier of the transaction
* @param accountUID String unique ID of account
* @return Cursor to splits data set
*/
public Cursor fetchSplitsForTransactionAndAccount(String transactionUID, String accountUID){
if (transactionUID == null || accountUID == null)
return null;
Log.v(LOG_TAG, "Fetching all splits for transaction ID " + transactionUID
+ "and account ID " + accountUID);
return mDb.query(SplitEntry.TABLE_NAME,
null, SplitEntry.COLUMN_TRANSACTION_UID + " = ? AND "
+ SplitEntry.COLUMN_ACCOUNT_UID + " = ?",
new String[]{transactionUID, accountUID},
null, null, SplitEntry.COLUMN_VALUE_NUM + " ASC");
}
/**
* Returns the unique ID of a transaction given the database record ID of same
* @param transactionId Database record ID of the transaction
* @return String unique ID of the transaction or null if transaction with the ID cannot be found.
*/
public String getTransactionUID(long transactionId){
Cursor cursor = mDb.query(TransactionEntry.TABLE_NAME,
new String[]{TransactionEntry.COLUMN_UID},
TransactionEntry._ID + " = " + transactionId,
null, null, null, null);
try {
if (cursor.moveToFirst()) {
return cursor.getString(cursor.getColumnIndexOrThrow(TransactionEntry.COLUMN_UID));
} else {
throw new IllegalArgumentException("transaction " + transactionId + " does not exist");
}
} finally {
cursor.close();
}
}
@Override
public boolean deleteRecord(long rowId) {
Split split = getRecord(rowId);
String transactionUID = split.getTransactionUID();
boolean result = mDb.delete(SplitEntry.TABLE_NAME, SplitEntry._ID + "=" + rowId, null) > 0;
if (!result) //we didn't delete for whatever reason, invalid rowId etc
return false;
//if we just deleted the last split, then remove the transaction from db
Cursor cursor = fetchSplitsForTransaction(transactionUID);
try {
if (cursor.getCount() > 0) {
long transactionID = getTransactionID(transactionUID);
result = mDb.delete(TransactionEntry.TABLE_NAME,
TransactionEntry._ID + "=" + transactionID, null) > 0;
}
} finally {
cursor.close();
}
return result;
}
/**
* Returns the database record ID for the specified transaction UID
* @param transactionUID Unique idendtifier of the transaction
* @return Database record ID for the transaction
*/
public long getTransactionID(String transactionUID) {
Cursor c = mDb.query(TransactionEntry.TABLE_NAME,
new String[]{TransactionEntry._ID},
TransactionEntry.COLUMN_UID + "=?",
new String[]{transactionUID}, null, null, null);
try {
if (c.moveToFirst()) {
return c.getLong(0);
} else {
throw new IllegalArgumentException("transaction " + transactionUID + " does not exist");
}
} finally {
c.close();
}
}
}
| 21,438 | 47.069507 | 182 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/db/adapter/TransactionsDbAdapter.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.db.adapter;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.util.TimestampHelper;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import static org.gnucash.android.db.DatabaseSchema.AccountEntry;
import static org.gnucash.android.db.DatabaseSchema.ScheduledActionEntry;
import static org.gnucash.android.db.DatabaseSchema.SplitEntry;
import static org.gnucash.android.db.DatabaseSchema.TransactionEntry;
/**
* Manages persistence of {@link Transaction}s in the database
* Handles adding, modifying and deleting of transaction records.
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
* @author Oleksandr Tyshkovets <[email protected]>
*/
public class TransactionsDbAdapter extends DatabaseAdapter<Transaction> {
private final SplitsDbAdapter mSplitsDbAdapter;
private final CommoditiesDbAdapter mCommoditiesDbAdapter;
/**
* Overloaded constructor. Creates adapter for already open db
* @param db SQlite db instance
*/
public TransactionsDbAdapter(SQLiteDatabase db, SplitsDbAdapter splitsDbAdapter) {
super(db, TransactionEntry.TABLE_NAME, new String[]{
TransactionEntry.COLUMN_DESCRIPTION,
TransactionEntry.COLUMN_NOTES,
TransactionEntry.COLUMN_TIMESTAMP,
TransactionEntry.COLUMN_EXPORTED,
TransactionEntry.COLUMN_CURRENCY,
TransactionEntry.COLUMN_COMMODITY_UID,
TransactionEntry.COLUMN_CREATED_AT,
TransactionEntry.COLUMN_SCHEDX_ACTION_UID,
TransactionEntry.COLUMN_TEMPLATE
});
mSplitsDbAdapter = splitsDbAdapter;
mCommoditiesDbAdapter = new CommoditiesDbAdapter(db);
}
/**
* Returns an application-wide instance of the database adapter
* @return Transaction database adapter
*/
public static TransactionsDbAdapter getInstance(){
return GnuCashApplication.getTransactionDbAdapter();
}
public SplitsDbAdapter getSplitDbAdapter() {
return mSplitsDbAdapter;
}
/**
* Adds an transaction to the database.
* If a transaction already exists in the database with the same unique ID,
* then the record will just be updated instead
* @param transaction {@link Transaction} to be inserted to database
*/
@Override
public void addRecord(@NonNull Transaction transaction, UpdateMethod updateMethod){
Log.d(LOG_TAG, "Adding transaction to the db via " + updateMethod.name());
mDb.beginTransaction();
try {
Split imbalanceSplit = transaction.createAutoBalanceSplit();
if (imbalanceSplit != null){
String imbalanceAccountUID = new AccountsDbAdapter(mDb, this)
.getOrCreateImbalanceAccountUID(transaction.getCommodity());
imbalanceSplit.setAccountUID(imbalanceAccountUID);
}
super.addRecord(transaction, updateMethod);
Log.d(LOG_TAG, "Adding splits for transaction");
ArrayList<String> splitUIDs = new ArrayList<>(transaction.getSplits().size());
for (Split split : transaction.getSplits()) {
Log.d(LOG_TAG, "Replace transaction split in db");
if (imbalanceSplit == split) {
mSplitsDbAdapter.addRecord(split, UpdateMethod.insert);
} else {
mSplitsDbAdapter.addRecord(split, updateMethod);
}
splitUIDs.add(split.getUID());
}
Log.d(LOG_TAG, transaction.getSplits().size() + " splits added");
long deleted = mDb.delete(SplitEntry.TABLE_NAME,
SplitEntry.COLUMN_TRANSACTION_UID + " = ? AND "
+ SplitEntry.COLUMN_UID + " NOT IN ('" + TextUtils.join("' , '", splitUIDs) + "')",
new String[]{transaction.getUID()});
Log.d(LOG_TAG, deleted + " splits deleted");
mDb.setTransactionSuccessful();
} catch (SQLException sqlEx) {
Log.e(LOG_TAG, sqlEx.getMessage());
Crashlytics.logException(sqlEx);
} finally {
mDb.endTransaction();
}
}
/**
* Adds an several transactions to the database.
* If a transaction already exists in the database with the same unique ID,
* then the record will just be updated instead. Recurrence Transactions will not
* be inserted, instead schedule Transaction would be called. If an exception
* occurs, no transaction would be inserted.
* @param transactionList {@link Transaction} transactions to be inserted to database
* @return Number of transactions inserted
*/
@Override
public long bulkAddRecords(@NonNull List<Transaction> transactionList, UpdateMethod updateMethod){
long start = System.nanoTime();
long rowInserted = super.bulkAddRecords(transactionList, updateMethod);
long end = System.nanoTime();
Log.d(getClass().getSimpleName(), String.format("bulk add transaction time %d ", end - start));
List<Split> splitList = new ArrayList<>(transactionList.size()*3);
for (Transaction transaction : transactionList) {
splitList.addAll(transaction.getSplits());
}
if (rowInserted != 0 && !splitList.isEmpty()) {
try {
start = System.nanoTime();
long nSplits = mSplitsDbAdapter.bulkAddRecords(splitList, updateMethod);
Log.d(LOG_TAG, String.format("%d splits inserted in %d ns", nSplits, System.nanoTime()-start));
}
finally {
SQLiteStatement deleteEmptyTransaction = mDb.compileStatement("DELETE FROM " +
TransactionEntry.TABLE_NAME + " WHERE NOT EXISTS ( SELECT * FROM " +
SplitEntry.TABLE_NAME +
" WHERE " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID +
" = " + SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID + " ) ");
deleteEmptyTransaction.execute();
}
}
return rowInserted;
}
@Override
protected @NonNull SQLiteStatement setBindings(@NonNull SQLiteStatement stmt, @NonNull Transaction transaction) {
stmt.clearBindings();
stmt.bindString(1, transaction.getDescription());
stmt.bindString(2, transaction.getNote());
stmt.bindLong(3, transaction.getTimeMillis());
stmt.bindLong(4, transaction.isExported() ? 1 : 0);
stmt.bindString(5, transaction.getCurrencyCode());
stmt.bindString(6, transaction.getCommodity().getUID());
stmt.bindString(7, TimestampHelper.getUtcStringFromTimestamp(transaction.getCreatedTimestamp()));
if (transaction.getScheduledActionUID() == null)
stmt.bindNull(8);
else
stmt.bindString(8, transaction.getScheduledActionUID());
stmt.bindLong(9, transaction.isTemplate() ? 1 : 0);
stmt.bindString(10, transaction.getUID());
return stmt;
}
/**
* Returns a cursor to a set of all transactions which have a split belonging to the accound with unique ID
* <code>accountUID</code>.
* @param accountUID UID of the account whose transactions are to be retrieved
* @return Cursor holding set of transactions for particular account
* @throws java.lang.IllegalArgumentException if the accountUID is null
*/
public Cursor fetchAllTransactionsForAccount(String accountUID){
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TransactionEntry.TABLE_NAME
+ " INNER JOIN " + SplitEntry.TABLE_NAME + " ON "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " = "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID);
queryBuilder.setDistinct(true);
String[] projectionIn = new String[]{TransactionEntry.TABLE_NAME + ".*"};
String selection = SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_ACCOUNT_UID + " = ?"
+ " AND " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TEMPLATE + " = 0";
String[] selectionArgs = new String[]{accountUID};
String sortOrder = TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TIMESTAMP + " DESC";
return queryBuilder.query(mDb, projectionIn, selection, selectionArgs, null, null, sortOrder);
}
/**
* Returns a cursor to all scheduled transactions which have at least one split in the account
* <p>This is basically a set of all template transactions for this account</p>
* @param accountUID GUID of account
* @return Cursor with set of transactions
*/
public Cursor fetchScheduledTransactionsForAccount(String accountUID){
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TransactionEntry.TABLE_NAME
+ " INNER JOIN " + SplitEntry.TABLE_NAME + " ON "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " = "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID);
queryBuilder.setDistinct(true);
String[] projectionIn = new String[]{TransactionEntry.TABLE_NAME + ".*"};
String selection = SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_ACCOUNT_UID + " = ?"
+ " AND " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TEMPLATE + " = 1";
String[] selectionArgs = new String[]{accountUID};
String sortOrder = TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TIMESTAMP + " DESC";
return queryBuilder.query(mDb, projectionIn, selection, selectionArgs, null, null, sortOrder);
}
/**
* Deletes all transactions which contain a split in the account.
* <p><b>Note:</b>As long as the transaction has one split which belongs to the account {@code accountUID},
* it will be deleted. The other splits belonging to the transaction will also go away</p>
* @param accountUID GUID of the account
*/
public void deleteTransactionsForAccount(String accountUID){
String rawDeleteQuery = "DELETE FROM " + TransactionEntry.TABLE_NAME + " WHERE " + TransactionEntry.COLUMN_UID + " IN "
+ " (SELECT " + SplitEntry.COLUMN_TRANSACTION_UID + " FROM " + SplitEntry.TABLE_NAME + " WHERE "
+ SplitEntry.COLUMN_ACCOUNT_UID + " = ?)";
mDb.execSQL(rawDeleteQuery, new String[]{accountUID});
}
/**
* Deletes all transactions which have no splits associated with them
* @return Number of records deleted
*/
public int deleteTransactionsWithNoSplits(){
return mDb.delete(
TransactionEntry.TABLE_NAME,
"NOT EXISTS ( SELECT * FROM " + SplitEntry.TABLE_NAME +
" WHERE " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID +
" = " + SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID + " ) ",
null
);
}
/**
* Fetches all recurring transactions from the database.
* <p>Recurring transactions are the transaction templates which have an entry in the scheduled events table</p>
* @return Cursor holding set of all recurring transactions
*/
public Cursor fetchAllScheduledTransactions(){
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TransactionEntry.TABLE_NAME + " INNER JOIN " + ScheduledActionEntry.TABLE_NAME + " ON "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " = "
+ ScheduledActionEntry.TABLE_NAME + "." + ScheduledActionEntry.COLUMN_ACTION_UID);
String[] projectionIn = new String[]{TransactionEntry.TABLE_NAME + ".*",
ScheduledActionEntry.TABLE_NAME+"."+ScheduledActionEntry.COLUMN_UID + " AS " + "origin_scheduled_action_uid"};
String sortOrder = TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_DESCRIPTION + " ASC";
// queryBuilder.setDistinct(true);
return queryBuilder.query(mDb, projectionIn, null, null, null, null, sortOrder);
}
/**
* Returns list of all transactions for account with UID <code>accountUID</code>
* @param accountUID UID of account whose transactions are to be retrieved
* @return List of {@link Transaction}s for account with UID <code>accountUID</code>
*/
public List<Transaction> getAllTransactionsForAccount(String accountUID){
Cursor c = fetchAllTransactionsForAccount(accountUID);
ArrayList<Transaction> transactionsList = new ArrayList<>();
try {
while (c.moveToNext()) {
transactionsList.add(buildModelInstance(c));
}
} finally {
c.close();
}
return transactionsList;
}
/**
* Returns all transaction instances in the database.
* @return List of all transactions
*/
public List<Transaction> getAllTransactions(){
Cursor cursor = fetchAllRecords();
List<Transaction> transactions = new ArrayList<Transaction>();
try {
while (cursor.moveToNext()) {
transactions.add(buildModelInstance(cursor));
}
} finally {
cursor.close();
}
return transactions;
}
public Cursor fetchTransactionsWithSplits(String [] columns, @Nullable String where, @Nullable String[] whereArgs, @Nullable String orderBy) {
return mDb.query(TransactionEntry.TABLE_NAME + " , " + SplitEntry.TABLE_NAME +
" ON " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID +
" = " + SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID +
" , trans_extra_info ON trans_extra_info.trans_acct_t_uid = " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID ,
columns, where, whereArgs, null, null,
orderBy);
}
/**
* Fetch all transactions modified since a given timestamp
* @param timestamp Timestamp in milliseconds (since Epoch)
* @return Cursor to the results
*/
public Cursor fetchTransactionsModifiedSince(Timestamp timestamp){
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TransactionEntry.TABLE_NAME);
String startTimeString = TimestampHelper.getUtcStringFromTimestamp(timestamp);
return queryBuilder.query(mDb, null, TransactionEntry.COLUMN_MODIFIED_AT + " >= \"" + startTimeString + "\"",
null, null, null, TransactionEntry.COLUMN_TIMESTAMP + " ASC", null);
}
public Cursor fetchTransactionsWithSplitsWithTransactionAccount(String [] columns, String where, String[] whereArgs, String orderBy) {
// table is :
// trans_split_acct , trans_extra_info ON trans_extra_info.trans_acct_t_uid = transactions_uid ,
// accounts AS account1 ON account1.uid = trans_extra_info.trans_acct_a_uid
//
// views effectively simplified this query
//
// account1 provides information for the grouped account. Splits from the grouped account
// can be eliminated with a WHERE clause. Transactions in QIF can be auto balanced.
//
// Account, transaction and split Information can be retrieve in a single query.
return mDb.query(
"trans_split_acct , trans_extra_info ON trans_extra_info.trans_acct_t_uid = trans_split_acct." +
TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_UID + " , " +
AccountEntry.TABLE_NAME + " AS account1 ON account1." + AccountEntry.COLUMN_UID +
" = trans_extra_info.trans_acct_a_uid",
columns, where, whereArgs, null, null , orderBy);
}
/**
* Return number of transactions in the database (excluding templates)
* @return Number of transactions
*/
public long getRecordsCount() {
String queryCount = "SELECT COUNT(*) FROM " + TransactionEntry.TABLE_NAME +
" WHERE " + TransactionEntry.COLUMN_TEMPLATE + " =0";
Cursor cursor = mDb.rawQuery(queryCount, null);
try {
cursor.moveToFirst();
return cursor.getLong(0);
} finally {
cursor.close();
}
}
/**
* Returns the number of transactions in the database which fulfill the conditions
* @param where SQL WHERE clause without the "WHERE" itself
* @param whereArgs Arguments to substitute question marks for
* @return Number of records in the databases
*/
public long getRecordsCount(@Nullable String where, @Nullable String[] whereArgs) {
Cursor cursor = mDb.query(true, TransactionEntry.TABLE_NAME + " , trans_extra_info ON "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID
+ " = trans_extra_info.trans_acct_t_uid",
new String[]{"COUNT(*)"},
where,
whereArgs,
null,
null,
null,
null);
try{
cursor.moveToFirst();
return cursor.getLong(0);
} finally {
cursor.close();
}
}
/**
* Builds a transaction instance with the provided cursor.
* The cursor should already be pointing to the transaction record in the database
* @param c Cursor pointing to transaction record in database
* @return {@link Transaction} object constructed from database record
*/
@Override
public Transaction buildModelInstance(@NonNull final Cursor c){
String name = c.getString(c.getColumnIndexOrThrow(TransactionEntry.COLUMN_DESCRIPTION));
Transaction transaction = new Transaction(name);
populateBaseModelAttributes(c, transaction);
transaction.setTime(c.getLong(c.getColumnIndexOrThrow(TransactionEntry.COLUMN_TIMESTAMP)));
transaction.setNote(c.getString(c.getColumnIndexOrThrow(TransactionEntry.COLUMN_NOTES)));
transaction.setExported(c.getInt(c.getColumnIndexOrThrow(TransactionEntry.COLUMN_EXPORTED)) == 1);
transaction.setTemplate(c.getInt(c.getColumnIndexOrThrow(TransactionEntry.COLUMN_TEMPLATE)) == 1);
String currencyCode = c.getString(c.getColumnIndexOrThrow(TransactionEntry.COLUMN_CURRENCY));
transaction.setCommodity(mCommoditiesDbAdapter.getCommodity(currencyCode));
transaction.setScheduledActionUID(c.getString(c.getColumnIndexOrThrow(TransactionEntry.COLUMN_SCHEDX_ACTION_UID)));
long transactionID = c.getLong(c.getColumnIndexOrThrow(TransactionEntry._ID));
transaction.setSplits(mSplitsDbAdapter.getSplitsForTransaction(transactionID));
return transaction;
}
/**
* Returns the transaction balance for the transaction for the specified account.
* <p>We consider only those splits which belong to this account</p>
* @param transactionUID GUID of the transaction
* @param accountUID GUID of the account
* @return {@link org.gnucash.android.model.Money} balance of the transaction for that account
*/
public Money getBalance(String transactionUID, String accountUID){
List<Split> splitList = mSplitsDbAdapter.getSplitsForTransactionInAccount(
transactionUID, accountUID);
return Transaction.computeBalance(accountUID, splitList);
}
/**
* Assigns transaction with id <code>rowId</code> to account with id <code>accountId</code>
* @param transactionUID GUID of the transaction
* @param srcAccountUID GUID of the account from which the transaction is to be moved
* @param dstAccountUID GUID of the account to which the transaction will be assigned
* @return Number of transactions splits affected
*/
public int moveTransaction(String transactionUID, String srcAccountUID, String dstAccountUID){
Log.i(LOG_TAG, "Moving transaction ID " + transactionUID
+ " splits from " + srcAccountUID + " to account " + dstAccountUID);
List<Split> splits = mSplitsDbAdapter.getSplitsForTransactionInAccount(transactionUID, srcAccountUID);
for (Split split : splits) {
split.setAccountUID(dstAccountUID);
}
mSplitsDbAdapter.bulkAddRecords(splits, UpdateMethod.update);
return splits.size();
}
/**
* Returns the number of transactions belonging to an account
* @param accountUID GUID of the account
* @return Number of transactions with splits in the account
*/
public int getTransactionsCount(String accountUID){
Cursor cursor = fetchAllTransactionsForAccount(accountUID);
int count = 0;
if (cursor == null)
return count;
else {
count = cursor.getCount();
cursor.close();
}
return count;
}
/**
* Returns the number of template transactions in the database
* @return Number of template transactions
*/
public long getTemplateTransactionsCount(){
String sql = "SELECT COUNT(*) FROM " + TransactionEntry.TABLE_NAME
+ " WHERE " + TransactionEntry.COLUMN_TEMPLATE + "=1";
SQLiteStatement statement = mDb.compileStatement(sql);
return statement.simpleQueryForLong();
}
/**
* Returns a list of all scheduled transactions in the database
* @return List of all scheduled transactions
*/
public List<Transaction> getScheduledTransactionsForAccount(String accountUID){
Cursor cursor = fetchScheduledTransactionsForAccount(accountUID);
List<Transaction> scheduledTransactions = new ArrayList<>();
try {
while (cursor.moveToNext()) {
scheduledTransactions.add(buildModelInstance(cursor));
}
return scheduledTransactions;
} finally {
cursor.close();
}
}
/**
* Returns the number of splits for the transaction in the database
* @param transactionUID GUID of the transaction
* @return Number of splits belonging to the transaction
*/
public long getSplitCount(@NonNull String transactionUID){
if (transactionUID == null)
return 0;
String sql = "SELECT COUNT(*) FROM " + SplitEntry.TABLE_NAME
+ " WHERE " + SplitEntry.COLUMN_TRANSACTION_UID + "= '" + transactionUID + "'";
SQLiteStatement statement = mDb.compileStatement(sql);
return statement.simpleQueryForLong();
}
/**
* Returns a cursor to transactions whose name (UI: description) start with the <code>prefix</code>
* <p>This method is used for autocomplete suggestions when creating new transactions. <br/>
* The suggestions are either transactions which have at least one split with {@code accountUID} or templates.</p>
* @param prefix Starting characters of the transaction name
* @param accountUID GUID of account within which to search for transactions
* @return Cursor to the data set containing all matching transactions
*/
public Cursor fetchTransactionSuggestions(String prefix, String accountUID){
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TransactionEntry.TABLE_NAME
+ " INNER JOIN " + SplitEntry.TABLE_NAME + " ON "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " = "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID);
queryBuilder.setDistinct(true);
String[] projectionIn = new String[]{TransactionEntry.TABLE_NAME + ".*"};
String selection = "(" + SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_ACCOUNT_UID + " = ?"
+ " OR " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TEMPLATE + "=1 )"
+ " AND " + TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_DESCRIPTION + " LIKE '" + prefix + "%'";
String[] selectionArgs = new String[]{accountUID};
String sortOrder = TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TIMESTAMP + " DESC";
String groupBy = TransactionEntry.COLUMN_DESCRIPTION;
String limit = Integer.toString(5);
return queryBuilder.query(mDb, projectionIn, selection, selectionArgs, groupBy, null, sortOrder, limit);
}
/**
* Updates a specific entry of an transaction
* @param contentValues Values with which to update the record
* @param whereClause Conditions for updating formatted as SQL where statement
* @param whereArgs Arguments for the SQL wehere statement
* @return Number of records affected
*/
public int updateTransaction(ContentValues contentValues, String whereClause, String[] whereArgs){
return mDb.update(TransactionEntry.TABLE_NAME, contentValues, whereClause, whereArgs);
}
/**
* Return the number of currencies used in the transaction.
* For example if there are different splits with different currencies
* @param transactionUID GUID of the transaction
* @return Number of currencies within the transaction
*/
public int getNumCurrencies(String transactionUID) {
Cursor cursor = mDb.query("trans_extra_info",
new String[]{"trans_currency_count"},
"trans_acct_t_uid=?",
new String[]{transactionUID},
null, null, null);
int numCurrencies = 0;
try {
if (cursor.moveToFirst()) {
numCurrencies = cursor.getInt(0);
}
}
finally {
cursor.close();
}
return numCurrencies;
}
/**
* Deletes all transactions except those which are marked as templates.
* <p>If you want to delete really all transaction records, use {@link #deleteAllRecords()}</p>
* @return Number of records deleted
*/
public int deleteAllNonTemplateTransactions(){
String where = TransactionEntry.COLUMN_TEMPLATE + "=0";
return mDb.delete(mTableName, where, null);
}
/**
* Returns a timestamp of the earliest transaction for a specified account type and currency
* @param type the account type
* @param currencyCode the currency code
* @return the earliest transaction's timestamp. Returns 1970-01-01 00:00:00.000 if no transaction found
*/
public long getTimestampOfEarliestTransaction(AccountType type, String currencyCode) {
return getTimestamp("MIN", type, currencyCode);
}
/**
* Returns a timestamp of the latest transaction for a specified account type and currency
* @param type the account type
* @param currencyCode the currency code
* @return the latest transaction's timestamp. Returns 1970-01-01 00:00:00.000 if no transaction found
*/
public long getTimestampOfLatestTransaction(AccountType type, String currencyCode) {
return getTimestamp("MAX", type, currencyCode);
}
/**
* Returns the most recent `modified_at` timestamp of non-template transactions in the database
* @return Last moodified time in milliseconds or current time if there is none in the database
*/
public Timestamp getTimestampOfLastModification(){
Cursor cursor = mDb.query(TransactionEntry.TABLE_NAME,
new String[]{"MAX(" + TransactionEntry.COLUMN_MODIFIED_AT + ")"},
null, null, null, null, null);
Timestamp timestamp = TimestampHelper.getTimestampFromNow();
if (cursor.moveToFirst()){
String timeString = cursor.getString(0);
if (timeString != null){ //in case there were no transactions in the XML file (account structure only)
timestamp = TimestampHelper.getTimestampFromUtcString(timeString);
}
}
cursor.close();
return timestamp;
}
/**
* Returns the earliest or latest timestamp of transactions for a specific account type and currency
* @param mod Mode (either MAX or MIN)
* @param type AccountType
* @param currencyCode the currency code
* @return earliest or latest timestamp of transactions
* @see #getTimestampOfLatestTransaction(AccountType, String)
* @see #getTimestampOfEarliestTransaction(AccountType, String)
*/
private long getTimestamp(String mod, AccountType type, String currencyCode) {
String sql = "SELECT " + mod + "(" + TransactionEntry.COLUMN_TIMESTAMP + ")"
+ " FROM " + TransactionEntry.TABLE_NAME
+ " INNER JOIN " + SplitEntry.TABLE_NAME + " ON "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_TRANSACTION_UID + " = "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID
+ " INNER JOIN " + AccountEntry.TABLE_NAME + " ON "
+ AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_UID + " = "
+ SplitEntry.TABLE_NAME + "." + SplitEntry.COLUMN_ACCOUNT_UID
+ " WHERE " + AccountEntry.TABLE_NAME + "." + AccountEntry.COLUMN_TYPE + " = ? AND "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_CURRENCY + " = ? AND "
+ TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TEMPLATE + " = 0";
Cursor cursor = mDb.rawQuery(sql, new String[]{ type.name(), currencyCode });
long timestamp= 0;
if (cursor != null) {
if (cursor.moveToFirst()) {
timestamp = cursor.getLong(0);
}
cursor.close();
}
return timestamp;
}
}
| 31,278 | 45.754858 | 153 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/DropboxHelper.java
|
/*
* Copyright (c) 2016 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.preference.PreferenceManager;
import com.dropbox.core.DbxRequestConfig;
import com.dropbox.core.android.Auth;
import com.dropbox.core.v2.DbxClientV2;
import org.gnucash.android.BuildConfig;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
/**
* Helper class for commonly used DropBox methods
*/
public class DropboxHelper {
/**
* DropBox API v2 client for making requests to DropBox
*/
private static DbxClientV2 sDbxClient;
/**
* Retrieves the access token after DropBox OAuth authentication and saves it to preferences file
* <p>This method should typically by called in the {@link Activity#onResume()} method of the
* Activity or Fragment which called {@link Auth#startOAuth2Authentication(Context, String)}
* </p>
* @return Retrieved access token. Could be null if authentication failed or was canceled.
*/
public static String retrieveAndSaveToken(){
Context context = GnuCashApplication.getAppContext();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String keyAccessToken = context.getString(R.string.key_dropbox_access_token);
String accessToken = sharedPrefs.getString(keyAccessToken, null);
if (accessToken != null)
return accessToken;
accessToken = Auth.getOAuth2Token();
sharedPrefs.edit()
.putString(keyAccessToken, accessToken)
.apply();
return accessToken;
}
/**
* Return a DropBox client for making requests
* @return DropBox client for API v2
*/
public static DbxClientV2 getClient(){
if (sDbxClient != null)
return sDbxClient;
Context context = GnuCashApplication.getAppContext();
String accessToken = PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.key_dropbox_access_token), null);
if (accessToken == null)
accessToken = Auth.getOAuth2Token();
DbxRequestConfig config = new DbxRequestConfig(BuildConfig.APPLICATION_ID);
sDbxClient = new DbxClientV2(config, accessToken);
return sDbxClient;
}
/**
* Checks if the app holds an access token for dropbox
* @return {@code true} if token exists, {@code false} otherwise
*/
public static boolean hasToken(){
Context context = GnuCashApplication.getAppContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String accessToken = prefs.getString(context.getString(R.string.key_dropbox_access_token), null);
return accessToken != null;
}
}
| 3,501 | 36.255319 | 105 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/ExportAsyncTask.java
|
/*
* Copyright (c) 2013 - 2015 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.v2.files.FileMetadata;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.MetadataChangeSet;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.CreateRemoteFolderOperation;
import com.owncloud.android.lib.resources.files.FileUtils;
import com.owncloud.android.lib.resources.files.UploadRemoteFileOperation;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.export.csv.CsvAccountExporter;
import org.gnucash.android.export.csv.CsvTransactionsExporter;
import org.gnucash.android.export.ofx.OfxExporter;
import org.gnucash.android.export.qif.QifExporter;
import org.gnucash.android.export.xml.GncXmlExporter;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.account.AccountsListFragment;
import org.gnucash.android.ui.settings.BackupPreferenceFragment;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import org.gnucash.android.util.BackupManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Asynchronous task for exporting transactions.
*
* @author Ngewi Fet <[email protected]>
*/
public class ExportAsyncTask extends AsyncTask<ExportParams, Void, Boolean> {
/**
* App context
*/
private final Context mContext;
private ProgressDialog mProgressDialog;
private SQLiteDatabase mDb;
/**
* Log tag
*/
public static final String TAG = "ExportAsyncTask";
/**
* Export parameters
*/
private ExportParams mExportParams;
// File paths generated by the exporter
private List<String> mExportedFiles = Collections.emptyList();
private Exporter mExporter;
public ExportAsyncTask(Context context, SQLiteDatabase db){
this.mContext = context;
this.mDb = db;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mContext instanceof Activity) {
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle(R.string.title_progress_exporting_transactions);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setProgressNumberFormat(null);
mProgressDialog.setProgressPercentFormat(null);
mProgressDialog.show();
}
}
/**
* Generates the appropriate exported transactions file for the given parameters
* @param params Export parameters
* @return <code>true</code> if export was successful, <code>false</code> otherwise
*/
@Override
protected Boolean doInBackground(ExportParams... params) {
mExportParams = params[0];
mExporter = getExporter();
try {
mExportedFiles = mExporter.generateExport();
} catch (final Exception e) {
Log.e(TAG, "Error exporting: " + e.getMessage());
Crashlytics.logException(e);
e.printStackTrace();
if (mContext instanceof Activity) {
((Activity)mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext,
mContext.getString(R.string.toast_export_error, mExportParams.getExportFormat().name())
+ "\n" + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
if (mExportedFiles.isEmpty())
return false;
try {
moveToTarget();
} catch (Exporter.ExporterException e) {
Crashlytics.log(Log.ERROR, TAG, "Error sending exported files to target: " + e.getMessage());
return false;
}
return true;
}
/**
* Transmits the exported transactions to the designated location, either SD card or third-party application
* Finishes the activity if the export was starting in the context of an activity
* @param exportSuccessful Result of background export execution
*/
@Override
protected void onPostExecute(Boolean exportSuccessful) {
if (exportSuccessful) {
if (mContext instanceof Activity)
reportSuccess();
if (mExportParams.shouldDeleteTransactionsAfterExport()) {
backupAndDeleteTransactions();
refreshViews();
}
} else {
if (mContext instanceof Activity) {
dismissProgressDialog();
if (mExportedFiles.isEmpty()) {
Toast.makeText(mContext,
R.string.toast_no_transactions_to_export,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext,
mContext.getString(R.string.toast_export_error, mExportParams.getExportFormat().name()),
Toast.LENGTH_LONG).show();
}
}
}
dismissProgressDialog();
}
private void dismissProgressDialog() {
if (mContext instanceof Activity) {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
((Activity) mContext).finish();
}
}
/**
* Returns an exporter corresponding to the user settings.
* @return Object of one of {@link QifExporter}, {@link OfxExporter} or {@link GncXmlExporter}, {@Link CsvAccountExporter} or {@Link CsvTransactionsExporter}
*/
private Exporter getExporter() {
switch (mExportParams.getExportFormat()) {
case QIF:
return new QifExporter(mExportParams, mDb);
case OFX:
return new OfxExporter(mExportParams, mDb);
case CSVA:
return new CsvAccountExporter(mExportParams, mDb);
case CSVT:
return new CsvTransactionsExporter(mExportParams, mDb);
case XML:
default:
return new GncXmlExporter(mExportParams, mDb);
}
}
/**
* Moves the generated export files to the target specified by the user
* @throws Exporter.ExporterException if the move fails
*/
private void moveToTarget() throws Exporter.ExporterException {
switch (mExportParams.getExportTarget()) {
case SHARING:
shareFiles(mExportedFiles);
break;
case DROPBOX:
moveExportToDropbox();
break;
case GOOGLE_DRIVE:
moveExportToGoogleDrive();
break;
case OWNCLOUD:
moveExportToOwnCloud();
break;
case SD_CARD:
moveExportToSDCard();
break;
case URI:
moveExportToUri();
break;
default:
throw new Exporter.ExporterException(mExportParams, "Invalid target");
}
}
/**
* Move the exported files to a specified URI.
* This URI could be a Storage Access Framework file
* @throws Exporter.ExporterException if something failed while moving the exported file
*/
private void moveExportToUri() throws Exporter.ExporterException {
Uri exportUri = Uri.parse(mExportParams.getExportLocation());
if (exportUri == null){
Log.w(TAG, "No URI found for export destination");
return;
}
if (mExportedFiles.size() > 0){
try {
OutputStream outputStream = mContext.getContentResolver().openOutputStream(exportUri);
// Now we always get just one file exported (multi-currency QIFs are zipped)
org.gnucash.android.util.FileUtils.moveFile(mExportedFiles.get(0), outputStream);
} catch (IOException ex) {
throw new Exporter.ExporterException(mExportParams, "Error when moving file to URI");
}
}
}
/**
* Move the exported files to a GnuCash folder on Google Drive
* @throws Exporter.ExporterException if something failed while moving the exported file
* @deprecated Explicit Google Drive integration is deprecated, use Storage Access Framework. See {@link #moveExportToUri()}
*/
@Deprecated
private void moveExportToGoogleDrive() throws Exporter.ExporterException {
Log.i(TAG, "Moving exported file to Google Drive");
final GoogleApiClient googleApiClient = BackupPreferenceFragment.getGoogleApiClient(GnuCashApplication.getAppContext());
googleApiClient.blockingConnect();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
String folderId = sharedPreferences.getString(mContext.getString(R.string.key_google_drive_app_folder_id), "");
DriveFolder folder = DriveId.decodeFromString(folderId).asDriveFolder();
try {
for (String exportedFilePath : mExportedFiles) {
DriveApi.DriveContentsResult driveContentsResult =
Drive.DriveApi.newDriveContents(googleApiClient).await(1, TimeUnit.MINUTES);
if (!driveContentsResult.getStatus().isSuccess()) {
throw new Exporter.ExporterException(mExportParams,
"Error while trying to create new file contents");
}
final DriveContents driveContents = driveContentsResult.getDriveContents();
OutputStream outputStream = driveContents.getOutputStream();
File exportedFile = new File(exportedFilePath);
FileInputStream fileInputStream = new FileInputStream(exportedFile);
byte[] buffer = new byte[1024];
int count;
while ((count = fileInputStream.read(buffer)) >= 0) {
outputStream.write(buffer, 0, count);
}
fileInputStream.close();
outputStream.flush();
exportedFile.delete();
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(exportedFile.getName())
.setMimeType(mExporter.getExportMimeType())
.build();
// create a file on root folder
DriveFolder.DriveFileResult driveFileResult =
folder.createFile(googleApiClient, changeSet, driveContents)
.await(1, TimeUnit.MINUTES);
if (!driveFileResult.getStatus().isSuccess())
throw new Exporter.ExporterException(mExportParams, "Error creating file in Google Drive");
Log.i(TAG, "Created file with id: " + driveFileResult.getDriveFile().getDriveId());
}
} catch (IOException e) {
throw new Exporter.ExporterException(mExportParams, e);
}
}
/**
* Move the exported files (in the cache directory) to Dropbox
*/
private void moveExportToDropbox() {
Log.i(TAG, "Uploading exported files to DropBox");
DbxClientV2 dbxClient = DropboxHelper.getClient();
for (String exportedFilePath : mExportedFiles) {
File exportedFile = new File(exportedFilePath);
try {
FileInputStream inputStream = new FileInputStream(exportedFile);
FileMetadata metadata = dbxClient.files()
.uploadBuilder("/" + exportedFile.getName())
.uploadAndFinish(inputStream);
Log.i(TAG, "Successfully uploaded file " + metadata.getName() + " to DropBox");
inputStream.close();
exportedFile.delete(); //delete file to prevent cache accumulation
} catch (IOException e) {
Crashlytics.logException(e);
Log.e(TAG, e.getMessage());
} catch (com.dropbox.core.DbxException e) {
e.printStackTrace();
}
}
}
private void moveExportToOwnCloud() throws Exporter.ExporterException {
Log.i(TAG, "Copying exported file to ownCloud");
SharedPreferences mPrefs = mContext.getSharedPreferences(mContext.getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
Boolean mOC_sync = mPrefs.getBoolean(mContext.getString(R.string.owncloud_sync), false);
if (!mOC_sync) {
throw new Exporter.ExporterException(mExportParams, "ownCloud not enabled.");
}
String mOC_server = mPrefs.getString(mContext.getString(R.string.key_owncloud_server), null);
String mOC_username = mPrefs.getString(mContext.getString(R.string.key_owncloud_username), null);
String mOC_password = mPrefs.getString(mContext.getString(R.string.key_owncloud_password), null);
String mOC_dir = mPrefs.getString(mContext.getString(R.string.key_owncloud_dir), null);
Uri serverUri = Uri.parse(mOC_server);
OwnCloudClient mClient = OwnCloudClientFactory.createOwnCloudClient(serverUri, this.mContext, true);
mClient.setCredentials(
OwnCloudCredentialsFactory.newBasicCredentials(mOC_username, mOC_password)
);
if (mOC_dir.length() != 0) {
RemoteOperationResult dirResult = new CreateRemoteFolderOperation(
mOC_dir, true).execute(mClient);
if (!dirResult.isSuccess()) {
Log.w(TAG, "Error creating folder (it may happen if it already exists): "
+ dirResult.getLogMessage());
}
}
for (String exportedFilePath : mExportedFiles) {
String remotePath = mOC_dir + FileUtils.PATH_SEPARATOR + stripPathPart(exportedFilePath);
String mimeType = mExporter.getExportMimeType();
RemoteOperationResult result = new UploadRemoteFileOperation(
exportedFilePath, remotePath, mimeType,
getFileLastModifiedTimestamp(exportedFilePath))
.execute(mClient);
if (!result.isSuccess())
throw new Exporter.ExporterException(mExportParams, result.getLogMessage());
new File(exportedFilePath).delete();
}
}
private static String getFileLastModifiedTimestamp(String path) {
Long timeStampLong = new File(path).lastModified() / 1000;
return timeStampLong.toString();
}
/**
* Moves the exported files from the internal storage where they are generated to
* external storage, which is accessible to the user.
* @return The list of files moved to the SD card.
* @deprecated Use the Storage Access Framework to save to SD card. See {@link #moveExportToUri()}
*/
@Deprecated
private List<String> moveExportToSDCard() throws Exporter.ExporterException {
Log.i(TAG, "Moving exported file to external storage");
new File(Exporter.getExportFolderPath(mExporter.mBookUID));
List<String> dstFiles = new ArrayList<>();
for (String src: mExportedFiles) {
String dst = Exporter.getExportFolderPath(mExporter.mBookUID) + stripPathPart(src);
try {
org.gnucash.android.util.FileUtils.moveFile(src, dst);
dstFiles.add(dst);
} catch (IOException e) {
throw new Exporter.ExporterException(mExportParams, e);
}
}
return dstFiles;
}
// "/some/path/filename.ext" -> "filename.ext"
private String stripPathPart(String fullPathName) {
return (new File(fullPathName)).getName();
}
/**
* Backups of the database, saves opening balances (if necessary)
* and deletes all non-template transactions in the database.
*/
private void backupAndDeleteTransactions(){
Log.i(TAG, "Backup and deleting transactions after export");
BackupManager.backupActiveBook(); //create backup before deleting everything
List<Transaction> openingBalances = new ArrayList<>();
boolean preserveOpeningBalances = GnuCashApplication.shouldSaveOpeningBalances(false);
TransactionsDbAdapter transactionsDbAdapter = new TransactionsDbAdapter(mDb, new SplitsDbAdapter(mDb));
if (preserveOpeningBalances) {
openingBalances = new AccountsDbAdapter(mDb, transactionsDbAdapter).getAllOpeningBalanceTransactions();
}
transactionsDbAdapter.deleteAllNonTemplateTransactions();
if (preserveOpeningBalances) {
transactionsDbAdapter.bulkAddRecords(openingBalances, DatabaseAdapter.UpdateMethod.insert);
}
}
/**
* Starts an intent chooser to allow the user to select an activity to receive
* the exported files.
* @param paths list of full paths of the files to send to the activity.
*/
private void shareFiles(List<String> paths) {
Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
shareIntent.setType("text/xml");
ArrayList<Uri> exportFiles = convertFilePathsToUris(paths);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, exportFiles);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, mContext.getString(R.string.title_export_email,
mExportParams.getExportFormat().name()));
String defaultEmail = PreferenceManager.getDefaultSharedPreferences(mContext)
.getString(mContext.getString(R.string.key_default_export_email), null);
if (defaultEmail != null && defaultEmail.trim().length() > 0)
shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{defaultEmail});
SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance();
String extraText = mContext.getString(R.string.description_export_email)
+ " " + formatter.format(new Date(System.currentTimeMillis()));
shareIntent.putExtra(Intent.EXTRA_TEXT, extraText);
if (mContext instanceof Activity) {
List<ResolveInfo> activities = mContext.getPackageManager().queryIntentActivities(shareIntent, 0);
if (activities != null && !activities.isEmpty()) {
mContext.startActivity(Intent.createChooser(shareIntent,
mContext.getString(R.string.title_select_export_destination)));
} else {
Toast.makeText(mContext, R.string.toast_no_compatible_apps_to_receive_export,
Toast.LENGTH_LONG).show();
}
}
}
/**
* Convert file paths to URIs by adding the file// prefix
* <p>e.g. /some/path/file.ext --> file:///some/path/file.ext</p>
* @param paths List of file paths to convert
* @return List of file URIs
*/
@NonNull
private ArrayList<Uri> convertFilePathsToUris(List<String> paths) {
ArrayList<Uri> exportFiles = new ArrayList<>();
for (String path : paths) {
File file = new File(path);
Uri contentUri = FileProvider.getUriForFile(GnuCashApplication.getAppContext(), GnuCashApplication.FILE_PROVIDER_AUTHORITY, file);
exportFiles.add(contentUri);
}
return exportFiles;
}
private void reportSuccess() {
String targetLocation;
switch (mExportParams.getExportTarget()){
case SD_CARD:
targetLocation = "SD card";
break;
case DROPBOX:
targetLocation = "DropBox -> Apps -> GnuCash";
break;
case GOOGLE_DRIVE:
targetLocation = "Google Drive -> " + mContext.getString(R.string.app_name);
break;
case OWNCLOUD:
targetLocation = mContext.getSharedPreferences(
mContext.getString(R.string.owncloud_pref),
Context.MODE_PRIVATE).getBoolean(
mContext.getString(R.string.owncloud_sync), false) ?
"ownCloud -> " +
mContext.getSharedPreferences(
mContext.getString(R.string.owncloud_pref),
Context.MODE_PRIVATE).getString(
mContext.getString(R.string.key_owncloud_dir), null) :
"ownCloud sync not enabled";
break;
default:
targetLocation = mContext.getString(R.string.label_export_target_external_service);
}
Toast.makeText(mContext,
String.format(mContext.getString(R.string.toast_exported_to), targetLocation),
Toast.LENGTH_LONG).show();
}
private void refreshViews() {
if (mContext instanceof AccountsActivity){
AccountsListFragment fragment =
((AccountsActivity) mContext).getCurrentAccountListFragment();
if (fragment != null)
fragment.refresh();
}
if (mContext instanceof TransactionsActivity){
((TransactionsActivity) mContext).refresh();
}
}
}
| 23,863 | 40.287197 | 161 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/ExportFormat.java
|
/*
* Copyright (c) 2013 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export;
/**
* Enumeration of the different export formats supported by the application
* @author Ngewi Fet <[email protected]>
*/
public enum ExportFormat {
QIF("Quicken Interchange Format"),
OFX("Open Financial eXchange"),
XML("GnuCash XML"),
CSVA("GnuCash accounts CSV"),
CSVT("GnuCash transactions CSV");
/**
* Full name of the export format acronym
*/
private String mDescription;
ExportFormat(String description) {
this.mDescription = description;
}
/**
* Returns the file extension for this export format including the period e.g. ".qif"
* @return String file extension for the export format
*/
public String getExtension(){
switch (this) {
case QIF:
return ".qif";
case OFX:
return ".ofx";
case XML:
return ".gnca";
case CSVA:
case CSVT:
return ".csv";
default:
return ".txt";
}
}
@Override
public String toString() {
return mDescription;
}
}
| 1,768 | 27.079365 | 89 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/ExportParams.java
|
/*
* Copyright (c) 2013 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export;
import android.net.Uri;
import org.gnucash.android.ui.export.ExportFormFragment;
import org.gnucash.android.util.TimestampHelper;
import java.sql.Timestamp;
/**
* Encapsulation of the parameters used for exporting transactions.
* The parameters are determined by the user in the export dialog and are then transmitted to the asynchronous task which
* actually performs the export.
* @see ExportFormFragment
* @see ExportAsyncTask
*
* @author Ngewi Fet <[email protected]>
*/
public class ExportParams {
/**
* Options for the destination of the exported transctions file.
* It could be stored on the {@link #SD_CARD} or exported through another program via {@link #SHARING}
*/
public enum ExportTarget {SD_CARD("SD Card"), SHARING("External Service"),
DROPBOX("Dropbox"), GOOGLE_DRIVE("Google Drive"), OWNCLOUD("ownCloud"),
URI("Sync Service");
private String mDescription;
ExportTarget(String description){
mDescription = description;
}
public String getDescription(){
return mDescription;
}
}
/**
* Format to use for the exported transactions
* By default, the {@link ExportFormat#QIF} format is used
*/
private ExportFormat mExportFormat = ExportFormat.QIF;
/**
* All transactions created after this date will be exported
*/
private Timestamp mExportStartTime = TimestampHelper.getTimestampFromEpochZero();
/**
* Flag to determine if all transactions should be deleted after exporting is complete
* By default no transactions are deleted
*/
private boolean mDeleteTransactionsAfterExport = false;
/**
* Destination for the exported transactions
*/
private ExportTarget mExportTarget = ExportTarget.SHARING;
/**
* Location to save the file name being exported.
* This is typically a Uri and used for {@link ExportTarget#URI} target
*/
private String mExportLocation;
/**
* CSV-separator char
*/
private char mCsvSeparator = ',';
/**
* Creates a new set of paramters and specifies the export format
* @param format Format to use when exporting the transactions
*/
public ExportParams(ExportFormat format){
setExportFormat(format);
}
/**
* Return the format used for exporting
* @return {@link ExportFormat}
*/
public ExportFormat getExportFormat() {
return mExportFormat;
}
/**
* Set the export format
* @param exportFormat {@link ExportFormat}
*/
public void setExportFormat(ExportFormat exportFormat) {
this.mExportFormat = exportFormat;
}
/**
* Return date from which to start exporting transactions
* <p>Transactions created or modified after this timestamp will be exported</p>
* @return Timestamp from which to export
*/
public Timestamp getExportStartTime(){
return mExportStartTime;
}
/**
* Set the timestamp after which all transactions created/modified will be exported
* @param exportStartTime Timestamp
*/
public void setExportStartTime(Timestamp exportStartTime){
this.mExportStartTime = exportStartTime;
}
/**
* Returns flag whether transactions should be deleted after export
* @return <code>true</code> if all transactions will be deleted, <code>false</code> otherwise
*/
public boolean shouldDeleteTransactionsAfterExport() {
return mDeleteTransactionsAfterExport;
}
/**
* Set flag to delete transactions after exporting is complete
* @param deleteTransactions SEt to <code>true</code> if transactions should be deleted, false if not
*/
public void setDeleteTransactionsAfterExport(boolean deleteTransactions) {
this.mDeleteTransactionsAfterExport = deleteTransactions;
}
/**
* Get the target for the exported file
* @return {@link org.gnucash.android.export.ExportParams.ExportTarget}
*/
public ExportTarget getExportTarget() {
return mExportTarget;
}
/**
* Set the target for the exported transactions
* @param mExportTarget Target for exported transactions
*/
public void setExportTarget(ExportTarget mExportTarget) {
this.mExportTarget = mExportTarget;
}
/**
* Return the location where the file should be exported to.
* When used with {@link ExportTarget#URI}, the returned value will be a URI which can be parsed
* with {@link Uri#parse(String)}
* @return String representing export file destination.
*/
public String getExportLocation(){
return mExportLocation;
}
/**
* Set the location where to export the file
* @param exportLocation Destination of the export
*/
public void setExportLocation(String exportLocation){
mExportLocation = exportLocation;
}
/**
* Get the CSV-separator char
* @return CSV-separator char
*/
public char getCsvSeparator(){
return mCsvSeparator;
}
/**
* Set the CSV-separator char
* @param separator CSV-separator char
*/
public void setCsvSeparator(char separator) {
mCsvSeparator = separator;
}
@Override
public String toString() {
return "Export all transactions created since " + TimestampHelper.getUtcStringFromTimestamp(mExportStartTime) + " UTC"
+ " as "+ mExportFormat.name() + " to " + mExportTarget.name() + (mExportLocation != null ? " (" + mExportLocation +")" : "");
}
/**
* Returns the export parameters formatted as CSV.
* <p>The CSV format is: exportformat;exportTarget;shouldExportAllTransactions;shouldDeleteAllTransactions</p>
* @return String containing CSV format of ExportParams
*/
public String toCsv(){
String separator = ";";
return mExportFormat.name() + separator
+ mExportTarget.name() + separator
+ TimestampHelper.getUtcStringFromTimestamp(mExportStartTime) + separator
+ Boolean.toString(mDeleteTransactionsAfterExport) + separator
+ (mExportLocation != null ? mExportLocation : "");
}
/**
* Parses csv generated by {@link #toCsv()} to create
* @param csvParams String containing csv of params
* @return ExportParams from the csv
*/
public static ExportParams parseCsv(String csvParams){
String[] tokens = csvParams.split(";");
ExportParams params = new ExportParams(ExportFormat.valueOf(tokens[0]));
params.setExportTarget(ExportTarget.valueOf(tokens[1]));
params.setExportStartTime(TimestampHelper.getTimestampFromUtcString(tokens[2]));
params.setDeleteTransactionsAfterExport(Boolean.parseBoolean(tokens[3]));
if (tokens.length == 5){
params.setExportLocation(tokens[4]);
}
return params;
}
}
| 7,639 | 32.073593 | 142 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/Exporter.java
|
/*
* Copyright (c) 2014 - 2015 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.BuildConfig;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.BudgetAmountsDbAdapter;
import org.gnucash.android.db.adapter.BudgetsDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.PricesDbAdapter;
import org.gnucash.android.db.adapter.RecurrenceDbAdapter;
import org.gnucash.android.db.adapter.ScheduledActionDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Base class for the different exporters
*
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
*/
public abstract class Exporter {
/**
* Tag for logging
*/
protected static String LOG_TAG = "Exporter";
/**
* Application folder on external storage
* @deprecated Use {@link #BASE_FOLDER_PATH} instead
*/
@Deprecated
public static final String LEGACY_BASE_FOLDER_PATH = Environment.getExternalStorageDirectory() + "/" + BuildConfig.APPLICATION_ID;
/**
* Application folder on external storage
*/
public static final String BASE_FOLDER_PATH = GnuCashApplication.getAppContext().getExternalFilesDir(null).getAbsolutePath();
/**
* Export options
*/
protected final ExportParams mExportParams;
/**
* Cache directory to which files will be first exported before moved to final destination.
* <p>There is a different cache dir per export format, which has the name of the export format.<br/>
* The cache dir is cleared every time a new {@link Exporter} is instantiated.
* The files created here are only accessible within this application, and should be copied to SD card before they can be shared
* </p>
*/
private final File mCacheDir;
private static final SimpleDateFormat EXPORT_FILENAME_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
/**
* Adapter for retrieving accounts to export
* Subclasses should close this object when they are done with exporting
*/
protected final AccountsDbAdapter mAccountsDbAdapter;
protected final TransactionsDbAdapter mTransactionsDbAdapter;
protected final SplitsDbAdapter mSplitsDbAdapter;
protected final ScheduledActionDbAdapter mScheduledActionDbAdapter;
protected final PricesDbAdapter mPricesDbAdapter;
protected final CommoditiesDbAdapter mCommoditiesDbAdapter;
protected final BudgetsDbAdapter mBudgetsDbAdapter;
protected final Context mContext;
private String mExportCacheFilePath;
/**
* Database being currently exported
*/
protected final SQLiteDatabase mDb;
/**
* GUID of the book being exported
*/
protected String mBookUID;
public Exporter(ExportParams params, SQLiteDatabase db) {
this.mExportParams = params;
mContext = GnuCashApplication.getAppContext();
if (db == null) {
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
mSplitsDbAdapter = SplitsDbAdapter.getInstance();
mPricesDbAdapter = PricesDbAdapter.getInstance();
mCommoditiesDbAdapter = CommoditiesDbAdapter.getInstance();
mBudgetsDbAdapter = BudgetsDbAdapter.getInstance();
mScheduledActionDbAdapter = ScheduledActionDbAdapter.getInstance();
mDb = GnuCashApplication.getActiveDb();
} else {
mDb = db;
mSplitsDbAdapter = new SplitsDbAdapter(db);
mTransactionsDbAdapter = new TransactionsDbAdapter(db, mSplitsDbAdapter);
mAccountsDbAdapter = new AccountsDbAdapter(db, mTransactionsDbAdapter);
mPricesDbAdapter = new PricesDbAdapter(db);
mCommoditiesDbAdapter = new CommoditiesDbAdapter(db);
RecurrenceDbAdapter recurrenceDbAdapter = new RecurrenceDbAdapter(db);
mBudgetsDbAdapter = new BudgetsDbAdapter(db, new BudgetAmountsDbAdapter(db), recurrenceDbAdapter);
mScheduledActionDbAdapter = new ScheduledActionDbAdapter(db, recurrenceDbAdapter);
}
mBookUID = new File(mDb.getPath()).getName(); //this depends on the database file always having the name of the book GUID
mExportCacheFilePath = null;
mCacheDir = new File(mContext.getCacheDir(), params.getExportFormat().name());
mCacheDir.mkdir();
purgeDirectory(mCacheDir);
}
/**
* Strings a string of any characters not allowed in a file name.
* All unallowed characters are replaced with an underscore
* @param inputName Raw file name input
* @return Sanitized file name
*/
public static String sanitizeFilename(String inputName) {
return inputName.replaceAll("[^a-zA-Z0-9-_\\.]", "_");
}
/**
* Builds a file name based on the current time stamp for the exported file
* @param format Format to use when exporting
* @param bookName Name of the book being exported. This name will be included in the generated file name
* @return String containing the file name
*/
public static String buildExportFilename(ExportFormat format, String bookName) {
return EXPORT_FILENAME_DATE_FORMAT.format(new Date(System.currentTimeMillis()))
+ "_gnucash_export_" + sanitizeFilename(bookName) +
(format == ExportFormat.CSVA ? "_accounts" : "") +
(format == ExportFormat.CSVT ? "_transactions" : "") +
format.getExtension();
}
/**
* Parses the name of an export file and returns the date of export
* @param filename Export file name generated by {@link #buildExportFilename(ExportFormat,String)}
* @return Date in milliseconds
*/
public static long getExportTime(String filename){
String[] tokens = filename.split("_");
long timeMillis = 0;
if (tokens.length < 2){
return timeMillis;
}
try {
Date date = EXPORT_FILENAME_DATE_FORMAT.parse(tokens[0] + "_" + tokens[1]);
timeMillis = date.getTime();
} catch (ParseException e) {
Log.e("Exporter", "Error parsing time from file name: " + e.getMessage());
Crashlytics.logException(e);
}
return timeMillis;
}
/**
* Generates the export output
* @throws ExporterException if an error occurs during export
*/
public abstract List<String> generateExport() throws ExporterException;
/**
* Recursively delete all files in a directory
* @param directory File descriptor for directory
*/
private void purgeDirectory(File directory){
for (File file : directory.listFiles()) {
if (file.isDirectory())
purgeDirectory(file);
else
file.delete();
}
}
/**
* Returns the path to the file where the exporter should save the export during generation
* <p>This path is a temporary cache file whose file extension matches the export format.<br>
* This file is deleted every time a new export is started</p>
* @return Absolute path to file
*/
protected String getExportCacheFilePath(){
// The file name contains a timestamp, so ensure it doesn't change with multiple calls to
// avoid issues like #448
if (mExportCacheFilePath == null) {
String cachePath = mCacheDir.getAbsolutePath();
if (!cachePath.endsWith("/"))
cachePath += "/";
String bookName = BooksDbAdapter.getInstance().getAttribute(mBookUID, DatabaseSchema.BookEntry.COLUMN_DISPLAY_NAME);
mExportCacheFilePath = cachePath + buildExportFilename(mExportParams.getExportFormat(), bookName);
}
return mExportCacheFilePath;
}
/**
* Returns that path to the export folder for the book with GUID {@code bookUID}.
* This is the folder where exports like QIF and OFX will be saved for access by external programs
* @param bookUID GUID of the book being exported. Each book has its own export path
* @return Absolute path to export folder for active book
*/
public static String getExportFolderPath(String bookUID){
String path = BASE_FOLDER_PATH + "/" + bookUID + "/exports/";
File file = new File(path);
if (!file.exists())
file.mkdirs();
return path;
}
/**
* Returns the MIME type for this exporter.
* @return MIME type as string
*/
public String getExportMimeType(){
return "text/plain";
}
public static class ExporterException extends RuntimeException{
public ExporterException(ExportParams params){
super("Failed to generate export with parameters: " + params.toString());
}
public ExporterException(@NonNull ExportParams params, @NonNull String msg) {
super("Failed to generate export with parameters: " + params.toString() + " - " + msg);
}
public ExporterException(ExportParams params, Throwable throwable){
super("Failed to generate " + params.getExportFormat().toString() +"-"+ throwable.getMessage(),
throwable);
}
}
}
| 10,686 | 38.876866 | 135 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/csv/CsvAccountExporter.java
|
/*
* Copyright (c) 2018 Semyannikov Gleb <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export.csv;
import android.database.sqlite.SQLiteDatabase;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.R;
import org.gnucash.android.export.ExportParams;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.model.Account;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Creates a GnuCash CSV account representation of the accounts and transactions
*
* @author Semyannikov Gleb <[email protected]>
*/
public class CsvAccountExporter extends Exporter{
private char mCsvSeparator;
/**
* Construct a new exporter with export parameters
* @param params Parameters for the export
*/
public CsvAccountExporter(ExportParams params) {
super(params, null);
mCsvSeparator = params.getCsvSeparator();
LOG_TAG = "GncXmlExporter";
}
/**
* Overloaded constructor.
* Creates an exporter with an already open database instance.
* @param params Parameters for the export
* @param db SQLite database
*/
public CsvAccountExporter(ExportParams params, SQLiteDatabase db) {
super(params, db);
mCsvSeparator = params.getCsvSeparator();
LOG_TAG = "GncXmlExporter";
}
@Override
public List<String> generateExport() throws ExporterException {
String outputFile = getExportCacheFilePath();
try (CsvWriter writer = new CsvWriter(new FileWriter(outputFile), mCsvSeparator + "")) {
generateExport(writer);
} catch (IOException ex){
Crashlytics.log("Error exporting CSV");
Crashlytics.logException(ex);
throw new ExporterException(mExportParams, ex);
}
return Arrays.asList(outputFile);
}
/**
* Writes out all the accounts in the system as CSV to the provided writer
* @param csvWriter Destination for the CSV export
* @throws ExporterException if an error occurred while writing to the stream
*/
public void generateExport(final CsvWriter csvWriter) throws ExporterException {
try {
List<String> names = Arrays.asList(mContext.getResources().getStringArray(R.array.csv_account_headers));
List<Account> accounts = mAccountsDbAdapter.getAllRecords();
for(int i = 0; i < names.size(); i++) {
csvWriter.writeToken(names.get(i));
}
csvWriter.newLine();
for (Account account : accounts) {
csvWriter.writeToken(account.getAccountType().toString());
csvWriter.writeToken(account.getFullName());
csvWriter.writeToken(account.getName());
csvWriter.writeToken(null); //Account code
csvWriter.writeToken(account.getDescription());
csvWriter.writeToken(account.getColorHexString());
csvWriter.writeToken(null); //Account notes
csvWriter.writeToken(account.getCommodity().getCurrencyCode());
csvWriter.writeToken("CURRENCY");
csvWriter.writeToken(account.isHidden() ? "T" : "F");
csvWriter.writeToken("F"); //Tax
csvWriter.writeEndToken(account.isPlaceholderAccount() ? "T": "F");
}
} catch (IOException e) {
Crashlytics.logException(e);
throw new ExporterException(mExportParams, e);
}
}
}
| 4,123 | 34.86087 | 116 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/csv/CsvTransactionsExporter.java
|
/*
* Copyright (c) 2018 Semyannikov Gleb <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export.csv;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.R;
import org.gnucash.android.export.ExportParams;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.model.TransactionType;
import org.gnucash.android.util.PreferencesHelper;
import org.gnucash.android.util.TimestampHelper;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Creates a GnuCash CSV transactions representation of the accounts and transactions
*
* @author Semyannikov Gleb <[email protected]>
*/
public class CsvTransactionsExporter extends Exporter{
private char mCsvSeparator;
private DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd", Locale.US);
/**
* Construct a new exporter with export parameters
* @param params Parameters for the export
*/
public CsvTransactionsExporter(ExportParams params) {
super(params, null);
mCsvSeparator = params.getCsvSeparator();
LOG_TAG = "GncXmlExporter";
}
/**
* Overloaded constructor.
* Creates an exporter with an already open database instance.
* @param params Parameters for the export
* @param db SQLite database
*/
public CsvTransactionsExporter(ExportParams params, SQLiteDatabase db) {
super(params, db);
mCsvSeparator = params.getCsvSeparator();
LOG_TAG = "GncXmlExporter";
}
@Override
public List<String> generateExport() throws ExporterException {
String outputFile = getExportCacheFilePath();
try (CsvWriter csvWriter = new CsvWriter(new FileWriter(outputFile), "" + mCsvSeparator)){
generateExport(csvWriter);
} catch (IOException ex){
Crashlytics.log("Error exporting CSV");
Crashlytics.logException(ex);
throw new ExporterException(mExportParams, ex);
}
return Arrays.asList(outputFile);
}
/**
* Write splits to CSV format
* @param splits Splits to be written
*/
private void writeSplitsToCsv(@NonNull List<Split> splits, @NonNull CsvWriter writer) throws IOException {
int index = 0;
Map<String, Account> uidAccountMap = new HashMap<>();
for (Split split : splits) {
if (index++ > 0){ // the first split is on the same line as the transactions. But after that, we
writer.write("" + mCsvSeparator + mCsvSeparator + mCsvSeparator + mCsvSeparator
+ mCsvSeparator + mCsvSeparator + mCsvSeparator + mCsvSeparator);
}
writer.writeToken(split.getMemo());
//cache accounts so that we do not have to go to the DB each time
String accountUID = split.getAccountUID();
Account account;
if (uidAccountMap.containsKey(accountUID)) {
account = uidAccountMap.get(accountUID);
} else {
account = mAccountsDbAdapter.getRecord(accountUID);
uidAccountMap.put(accountUID, account);
}
writer.writeToken(account.getFullName());
writer.writeToken(account.getName());
String sign = split.getType() == TransactionType.CREDIT ? "-" : "";
writer.writeToken(sign + split.getQuantity().formattedString());
writer.writeToken(sign + split.getQuantity().toLocaleString());
writer.writeToken("" + split.getReconcileState());
if (split.getReconcileState() == Split.FLAG_RECONCILED) {
String recDateString = dateFormat.format(new Date(split.getReconcileDate().getTime()));
writer.writeToken(recDateString);
} else {
writer.writeToken(null);
}
writer.writeEndToken(split.getQuantity().divide(split.getValue()).toLocaleString());
}
}
private void generateExport(final CsvWriter csvWriter) throws ExporterException {
try {
List<String> names = Arrays.asList(mContext.getResources().getStringArray(R.array.csv_transaction_headers));
for(int i = 0; i < names.size(); i++) {
csvWriter.writeToken(names.get(i));
}
csvWriter.newLine();
Cursor cursor = mTransactionsDbAdapter.fetchTransactionsModifiedSince(mExportParams.getExportStartTime());
Log.d(LOG_TAG, String.format("Exporting %d transactions to CSV", cursor.getCount()));
while (cursor.moveToNext()){
Transaction transaction = mTransactionsDbAdapter.buildModelInstance(cursor);
Date date = new Date(transaction.getTimeMillis());
csvWriter.writeToken(dateFormat.format(date));
csvWriter.writeToken(transaction.getUID());
csvWriter.writeToken(null); //Transaction number
csvWriter.writeToken(transaction.getDescription());
csvWriter.writeToken(transaction.getNote());
csvWriter.writeToken("CURRENCY::" + transaction.getCurrencyCode());
csvWriter.writeToken(null); // Void Reason
csvWriter.writeToken(null); // Action
writeSplitsToCsv(transaction.getSplits(), csvWriter);
}
PreferencesHelper.setLastExportTime(TimestampHelper.getTimestampFromNow());
} catch (IOException e) {
Crashlytics.logException(e);
throw new ExporterException(mExportParams, e);
}
}
}
| 6,634 | 37.575581 | 120 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/csv/CsvWriter.java
|
/*
* Copyright (c) 2018 Semyannikov Gleb <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export.csv;
import android.support.annotation.NonNull;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
/**
* Format data to be CSV-compatible
*
* @author Semyannikov Gleb <[email protected]>
* @author Ngewi Fet <[email protected]>
*/
public class CsvWriter extends BufferedWriter {
private String separator = ",";
public CsvWriter(Writer writer){
super(writer);
}
public CsvWriter(Writer writer, String separator){
super(writer);
this.separator = separator;
}
@Override
public void write(@NonNull String str) throws IOException {
this.write(str, 0, str.length());
}
/**
* Writes a CSV token and the separator to the underlying output stream.
*
* The token **MUST NOT** not contain the CSV separator. If the separator is found in the token, then
* the token will be escaped as specified by RFC 4180
* @param token Token to be written to file
* @throws IOException if the token could not be written to the underlying stream
*/
public void writeToken(String token) throws IOException {
if (token == null || token.isEmpty()){
write(separator);
} else {
token = escape(token);
write(token + separator);
}
}
/**
* Escape any CSV separators by surrounding the token in double quotes
* @param token String token to be written to CSV
* @return Escaped CSV token
*/
@NonNull
private String escape(@NonNull String token) {
if (token.contains(separator)){
return "\"" + token + "\"";
}
return token;
}
/**
* Writes a token to the CSV file and appends end of line to it.
*
* The token **MUST NOT** not contain the CSV separator. If the separator is found in the token, then
* the token will be escaped as specified by RFC 4180
* @param token The token to be written to the file
* @throws IOException if token could not be written to underlying writer
*/
public void writeEndToken(String token) throws IOException {
if (token != null && !token.isEmpty()) {
write(escape(token));
}
this.newLine();
}
}
| 2,925 | 29.8 | 105 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/ofx/OfxExporter.java
|
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export.ofx;
import android.database.sqlite.SQLiteDatabase;
import android.preference.PreferenceManager;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.export.ExportParams;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.util.PreferencesHelper;
import org.gnucash.android.util.TimestampHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.ProcessingInstruction;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
/**
* Exports the data in the database in OFX format
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
*/
public class OfxExporter extends Exporter{
/**
* List of accounts in the expense report
*/
private List<Account> mAccountsList;
/**
* Builds an XML representation of the {@link Account}s and {@link Transaction}s in the database
*/
public OfxExporter(ExportParams params) {
super(params, null);
LOG_TAG = "OfxExporter";
}
/**
* Overloaded constructor. Initializes the export parameters and the database to export
* @param params Export options
* @param db SQLiteDatabase to export
*/
public OfxExporter(ExportParams params, SQLiteDatabase db){
super(params, db);
LOG_TAG = "OfxExporter";
}
/**
* Converts all expenses into OFX XML format and adds them to the XML document
* @param doc DOM document of the OFX expenses.
* @param parent Parent node for all expenses in report
*/
private void generateOfx(Document doc, Element parent){
Element transactionUid = doc.createElement(OfxHelper.TAG_TRANSACTION_UID);
//unsolicited because the data exported is not as a result of a request
transactionUid.appendChild(doc.createTextNode(OfxHelper.UNSOLICITED_TRANSACTION_ID));
Element statementTransactionResponse = doc.createElement(OfxHelper.TAG_STATEMENT_TRANSACTION_RESPONSE);
statementTransactionResponse.appendChild(transactionUid);
Element bankmsgs = doc.createElement(OfxHelper.TAG_BANK_MESSAGES_V1);
bankmsgs.appendChild(statementTransactionResponse);
parent.appendChild(bankmsgs);
AccountsDbAdapter accountsDbAdapter = mAccountsDbAdapter;
for (Account account : mAccountsList) {
if (account.getTransactionCount() == 0)
continue;
//do not export imbalance accounts for OFX transactions and double-entry disabled
if (!GnuCashApplication.isDoubleEntryEnabled() && account.getName().contains(mContext.getString(R.string.imbalance_account_name)))
continue;
//add account details (transactions) to the XML document
account.toOfx(doc, statementTransactionResponse, mExportParams.getExportStartTime());
//mark as exported
accountsDbAdapter.markAsExported(account.getUID());
}
}
/**
* Generate OFX export file from the transactions in the database
* @return String containing OFX export
* @throws ExporterException
*/
private String generateOfxExport() throws ExporterException {
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new ExporterException(mExportParams, e);
}
Document document = docBuilder.newDocument();
Element root = document.createElement("OFX");
ProcessingInstruction pi = document.createProcessingInstruction("OFX", OfxHelper.OFX_HEADER);
document.appendChild(pi);
document.appendChild(root);
generateOfx(document, root);
boolean useXmlHeader = PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(mContext.getString(R.string.key_xml_ofx_header), false);
PreferencesHelper.setLastExportTime(TimestampHelper.getTimestampFromNow());
StringWriter stringWriter = new StringWriter();
//if we want SGML OFX headers, write first to string and then prepend header
if (useXmlHeader){
write(document, stringWriter, false);
return stringWriter.toString();
} else {
Node ofxNode = document.getElementsByTagName("OFX").item(0);
write(ofxNode, stringWriter, true);
return OfxHelper.OFX_SGML_HEADER + '\n' + stringWriter.toString();
}
}
@Override
public List<String> generateExport() throws ExporterException {
mAccountsList = mAccountsDbAdapter.getExportableAccounts(mExportParams.getExportStartTime());
if (mAccountsList.isEmpty())
return new ArrayList<>(); // Nothing to export, so no files generated
BufferedWriter writer = null;
try {
File file = new File(getExportCacheFilePath());
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
writer.write(generateOfxExport());
} catch (IOException e) {
throw new ExporterException(mExportParams, e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
throw new ExporterException(mExportParams, e);
}
}
}
List<String> exportedFiles = new ArrayList<>();
exportedFiles.add(getExportCacheFilePath());
return exportedFiles;
}
/**
* Writes out the document held in <code>node</code> to <code>outputWriter</code>
* @param node {@link Node} containing the OFX document structure. Usually the parent node
* @param outputWriter {@link java.io.Writer} to use in writing the file to stream
* @param omitXmlDeclaration Flag which causes the XML declaration to be omitted
*/
private void write(Node node, Writer outputWriter, boolean omitXmlDeclaration){
try {
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(node);
StreamResult result = new StreamResult(outputWriter);
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
if (omitXmlDeclaration) {
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
}
transformer.transform(source, result);
} catch (TransformerException tfException) {
Log.e(LOG_TAG, tfException.getMessage());
Crashlytics.logException(tfException);
}
}
/**
* Returns the MIME type for this exporter.
* @return MIME type as string
*/
public String getExportMimeType(){
return "text/xml";
}
}
| 8,587 | 35.858369 | 142 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/ofx/OfxHelper.java
|
/*
* Copyright (c) 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export.ofx;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Helper class with collection of useful method and constants for the OFX export
*
* @author Ngewi Fet <[email protected]>
*/
public class OfxHelper {
/**
* A date formatter used when creating file names for the exported data
*/
public final static SimpleDateFormat OFX_DATE_FORMATTER = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
/**
* The Transaction ID is usually the client ID sent in a request.
* Since the data exported is not as a result of a request, we use 0
*/
public static final String UNSOLICITED_TRANSACTION_ID = "0";
/**
* Header for OFX documents
*/
public static final String OFX_HEADER = "OFXHEADER=\"200\" VERSION=\"211\" SECURITY=\"NONE\" OLDFILEUID=\"NONE\" NEWFILEUID=\"NONE\"";
/**
* SGML header for OFX. Used for compatibility with desktop GnuCash
*/
public static final String OFX_SGML_HEADER = "ENCODING:UTF-8\nOFXHEADER:100\nDATA:OFXSGML\nVERSION:211\nSECURITY:NONE\nCHARSET:UTF-8\nCOMPRESSION:NONE\nOLDFILEUID:NONE\nNEWFILEUID:NONE";
/*
* XML tag name constants for the OFX file
*/
public static final String TAG_TRANSACTION_UID = "TRNUID";
public static final String TAG_BANK_MESSAGES_V1 = "BANKMSGSRSV1";
public static final String TAG_CURRENCY_DEF = "CURDEF";
public static final String TAG_BANK_ID = "BANKID";
public static final String TAG_ACCOUNT_ID = "ACCTID";
public static final String TAG_ACCOUNT_TYPE = "ACCTTYPE";
public static final String TAG_BANK_ACCOUNT_FROM = "BANKACCTFROM";
public static final String TAG_BALANCE_AMOUNT = "BALAMT";
public static final String TAG_DATE_AS_OF = "DTASOF";
public static final String TAG_LEDGER_BALANCE = "LEDGERBAL";
public static final String TAG_DATE_START = "DTSTART";
public static final String TAG_DATE_END = "DTEND";
public static final String TAG_TRANSACTION_TYPE = "TRNTYPE";
public static final String TAG_DATE_POSTED = "DTPOSTED";
public static final String TAG_DATE_USER = "DTUSER";
public static final String TAG_TRANSACTION_AMOUNT = "TRNAMT";
public static final String TAG_TRANSACTION_FITID = "FITID";
public static final String TAG_NAME = "NAME";
public static final String TAG_MEMO = "MEMO";
public static final String TAG_BANK_ACCOUNT_TO = "BANKACCTTO";
public static final String TAG_BANK_TRANSACTION_LIST = "BANKTRANLIST";
public static final String TAG_STATEMENT_TRANSACTIONS = "STMTRS";
public static final String TAG_STATEMENT_TRANSACTION = "STMTTRN";
public static final String TAG_STATEMENT_TRANSACTION_RESPONSE = "STMTTRNRS";
/**
* ID which will be used as the bank ID for OFX from this app
*/
public static String APP_ID = "org.gnucash.android";
/**
* Returns the current time formatted using the pattern in {@link #OFX_DATE_FORMATTER}
* @return Current time as a formatted string
* @see #getOfxFormattedTime(long)
*/
public static String getFormattedCurrentTime(){
return getOfxFormattedTime(System.currentTimeMillis());
}
/**
* Returns a formatted string representation of time in <code>milliseconds</code>
* @param milliseconds Long value representing the time to be formatted
* @return Formatted string representation of time in <code>milliseconds</code>
*/
public static String getOfxFormattedTime(long milliseconds){
Date date = new Date(milliseconds);
String dateString = OFX_DATE_FORMATTER.format(date);
TimeZone tz = Calendar.getInstance().getTimeZone();
int offset = tz.getRawOffset();
int hours = (int) (( offset / (1000*60*60)) % 24);
String sign = offset > 0 ? "+" : "";
return dateString + "[" + sign + hours + ":" + tz.getDisplayName(false, TimeZone.SHORT, Locale.getDefault()) + "]";
}
}
| 4,828 | 43.302752 | 190 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/qif/QifExporter.java
|
/*
* Copyright (c) 2013 - 2014 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export.qif;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.export.ExportParams;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.util.FileUtils;
import org.gnucash.android.util.PreferencesHelper;
import org.gnucash.android.util.TimestampHelper;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static org.gnucash.android.db.DatabaseSchema.AccountEntry;
import static org.gnucash.android.db.DatabaseSchema.SplitEntry;
import static org.gnucash.android.db.DatabaseSchema.TransactionEntry;
/**
* Exports the accounts and transactions in the database to the QIF format
*
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
*/
public class QifExporter extends Exporter{
/**
* Initialize the exporter
* @param params Export options
*/
public QifExporter(ExportParams params){
super(params, null);
LOG_TAG = "QifExporter";
}
/**
* Initialize the exporter
* @param params Options for export
* @param db SQLiteDatabase to export
*/
public QifExporter(ExportParams params, SQLiteDatabase db){
super(params, db);
LOG_TAG = "QifExporter";
}
@Override
public List<String> generateExport() throws ExporterException {
final String newLine = "\n";
TransactionsDbAdapter transactionsDbAdapter = mTransactionsDbAdapter;
try {
String lastExportTimeStamp = TimestampHelper.getUtcStringFromTimestamp(mExportParams.getExportStartTime());
Cursor cursor = transactionsDbAdapter.fetchTransactionsWithSplitsWithTransactionAccount(
new String[]{
TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_UID + " AS trans_uid",
TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_TIMESTAMP + " AS trans_time",
TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_DESCRIPTION + " AS trans_desc",
TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_NOTES + " AS trans_notes",
SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_QUANTITY_NUM + " AS split_quantity_num",
SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_QUANTITY_DENOM + " AS split_quantity_denom",
SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_TYPE + " AS split_type",
SplitEntry.TABLE_NAME + "_" + SplitEntry.COLUMN_MEMO + " AS split_memo",
"trans_extra_info.trans_acct_balance AS trans_acct_balance",
"trans_extra_info.trans_split_count AS trans_split_count",
"account1." + AccountEntry.COLUMN_UID + " AS acct1_uid",
"account1." + AccountEntry.COLUMN_FULL_NAME + " AS acct1_full_name",
"account1." + AccountEntry.COLUMN_CURRENCY + " AS acct1_currency",
"account1." + AccountEntry.COLUMN_TYPE + " AS acct1_type",
AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_FULL_NAME + " AS acct2_full_name"
},
// no recurrence transactions
TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_TEMPLATE + " == 0 AND " +
// in qif, split from the one account entry is not recorded (will be auto balanced)
"( " + AccountEntry.TABLE_NAME + "_" + AccountEntry.COLUMN_UID + " != account1." + AccountEntry.COLUMN_UID + " OR " +
// or if the transaction has only one split (the whole transaction would be lost if it is not selected)
"trans_split_count == 1 )" +
(
" AND " + TransactionEntry.TABLE_NAME + "_" + TransactionEntry.COLUMN_MODIFIED_AT + " > \"" + lastExportTimeStamp + "\""
),
null,
// trans_time ASC : put transactions in time order
// trans_uid ASC : put splits from the same transaction together
"acct1_currency ASC, trans_time ASC, trans_uid ASC"
);
File file = new File(getExportCacheFilePath());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
try {
String currentCurrencyCode = "";
String currentAccountUID = "";
String currentTransactionUID = "";
while (cursor.moveToNext()) {
String currencyCode = cursor.getString(cursor.getColumnIndexOrThrow("acct1_currency"));
String accountUID = cursor.getString(cursor.getColumnIndexOrThrow("acct1_uid"));
String transactionUID = cursor.getString(cursor.getColumnIndexOrThrow("trans_uid"));
if (!transactionUID.equals(currentTransactionUID)) {
if (!currentTransactionUID.equals("")) {
writer.append(QifHelper.ENTRY_TERMINATOR).append(newLine);
// end last transaction
}
if (!accountUID.equals(currentAccountUID)) {
// no need to end account
//if (!currentAccountUID.equals("")) {
// // end last account
//}
if (!currencyCode.equals(currentCurrencyCode)) {
currentCurrencyCode = currencyCode;
writer.append(QifHelper.INTERNAL_CURRENCY_PREFIX)
.append(currencyCode)
.append(newLine);
}
// start new account
currentAccountUID = accountUID;
writer.append(QifHelper.ACCOUNT_HEADER).append(newLine);
writer.append(QifHelper.ACCOUNT_NAME_PREFIX)
.append(cursor.getString(cursor.getColumnIndexOrThrow("acct1_full_name")))
.append(newLine);
writer.append(QifHelper.ENTRY_TERMINATOR).append(newLine);
writer.append(QifHelper.getQifHeader(cursor.getString(cursor.getColumnIndexOrThrow("acct1_type"))))
.append(newLine);
}
// start new transaction
currentTransactionUID = transactionUID;
writer.append(QifHelper.DATE_PREFIX)
.append(QifHelper.formatDate(cursor.getLong(cursor.getColumnIndexOrThrow("trans_time"))))
.append(newLine);
// Payee / description
writer.append(QifHelper.PAYEE_PREFIX)
.append(cursor.getString(cursor.getColumnIndexOrThrow("trans_desc")))
.append(newLine);
// Notes, memo
writer.append(QifHelper.MEMO_PREFIX)
.append(cursor.getString(cursor.getColumnIndexOrThrow("trans_notes")))
.append(newLine);
// deal with imbalance first
double imbalance = cursor.getDouble(cursor.getColumnIndexOrThrow("trans_acct_balance"));
BigDecimal decimalImbalance = BigDecimal.valueOf(imbalance).setScale(2, BigDecimal.ROUND_HALF_UP);
if (decimalImbalance.compareTo(BigDecimal.ZERO) != 0) {
writer.append(QifHelper.SPLIT_CATEGORY_PREFIX)
.append(AccountsDbAdapter.getImbalanceAccountName(
Commodity.getInstance(cursor.getString(cursor.getColumnIndexOrThrow("acct1_currency")))
))
.append(newLine);
writer.append(QifHelper.SPLIT_AMOUNT_PREFIX)
.append(decimalImbalance.toPlainString())
.append(newLine);
}
}
if (cursor.getInt(cursor.getColumnIndexOrThrow("trans_split_count")) == 1) {
// No other splits should be recorded if this is the only split.
continue;
}
// all splits
// amount associated with the header account will not be exported.
// It can be auto balanced when importing to GnuCash
writer.append(QifHelper.SPLIT_CATEGORY_PREFIX)
.append(cursor.getString(cursor.getColumnIndexOrThrow("acct2_full_name")))
.append(newLine);
String splitMemo = cursor.getString(cursor.getColumnIndexOrThrow("split_memo"));
if (splitMemo != null && splitMemo.length() > 0) {
writer.append(QifHelper.SPLIT_MEMO_PREFIX)
.append(splitMemo)
.append(newLine);
}
String splitType = cursor.getString(cursor.getColumnIndexOrThrow("split_type"));
Double quantity_num = cursor.getDouble(cursor.getColumnIndexOrThrow("split_quantity_num"));
int quantity_denom = cursor.getInt(cursor.getColumnIndexOrThrow("split_quantity_denom"));
int precision = 0;
switch (quantity_denom) {
case 0: // will sometimes happen for zero values
break;
case 1:
precision = 0;
break;
case 10:
precision = 1;
break;
case 100:
precision = 2;
break;
case 1000:
precision = 3;
break;
case 10000:
precision = 4;
break;
case 100000:
precision = 5;
break;
case 1000000:
precision = 6;
break;
default:
throw new ExporterException(mExportParams, "split quantity has illegal denominator: "+ quantity_denom);
}
Double quantity = 0.0;
if (quantity_denom != 0) {
quantity = quantity_num / quantity_denom;
}
final Locale noLocale = null;
writer.append(QifHelper.SPLIT_AMOUNT_PREFIX)
.append(splitType.equals("DEBIT") ? "-" : "")
.append(String.format(noLocale, "%." + precision + "f", quantity))
.append(newLine);
}
if (!currentTransactionUID.equals("")) {
// end last transaction
writer.append(QifHelper.ENTRY_TERMINATOR).append(newLine);
}
writer.flush();
} finally {
cursor.close();
writer.close();
}
ContentValues contentValues = new ContentValues();
contentValues.put(TransactionEntry.COLUMN_EXPORTED, 1);
transactionsDbAdapter.updateTransaction(contentValues, null, null);
/// export successful
PreferencesHelper.setLastExportTime(TimestampHelper.getTimestampFromNow());
List<String> exportedFiles = splitQIF(file);
if (exportedFiles.isEmpty())
return Collections.emptyList();
else if (exportedFiles.size() > 1)
return zipQifs(exportedFiles);
else
return exportedFiles;
} catch (IOException e) {
throw new ExporterException(mExportParams, e);
}
}
@NonNull
private List<String> zipQifs(List<String> exportedFiles) throws IOException {
String zipFileName = getExportCacheFilePath() + ".zip";
FileUtils.zipFiles(exportedFiles, zipFileName);
return Collections.singletonList(zipFileName);
}
/**
* Splits a Qif file into several ones for each currency.
*
* @param file File object of the Qif file to split.
* @return a list of paths of the newly created Qif files.
* @throws IOException if something went wrong while splitting the file.
*/
private List<String> splitQIF(File file) throws IOException {
// split only at the last dot
String[] pathParts = file.getPath().split("(?=\\.[^\\.]+$)");
ArrayList<String> splitFiles = new ArrayList<>();
String line;
BufferedReader in = new BufferedReader(new FileReader(file));
BufferedWriter out = null;
try {
while ((line = in.readLine()) != null) {
if (line.startsWith(QifHelper.INTERNAL_CURRENCY_PREFIX)) {
String currencyCode = line.substring(1);
if (out != null) {
out.close();
}
String newFileName = pathParts[0] + "_" + currencyCode + pathParts[1];
splitFiles.add(newFileName);
out = new BufferedWriter(new FileWriter(newFileName));
} else {
if (out == null) {
throw new IllegalArgumentException(file.getPath() + " format is not correct");
}
out.append(line).append('\n');
}
}
} finally {
in.close();
if (out != null) {
out.close();
}
}
return splitFiles;
}
/**
* Returns the mime type for this Exporter.
* @return MIME type as string
*/
public String getExportMimeType(){
return "text/plain";
}
}
| 16,071 | 48.913043 | 156 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/qif/QifHelper.java
|
/*
* Copyright (c) 2013 - 2014 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export.qif;
import org.gnucash.android.model.AccountType;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author Ngewi Fet <[email protected]>
*/
public class QifHelper {
/*
Prefixes for the QIF file
*/
public static final String PAYEE_PREFIX = "P";
public static final String DATE_PREFIX = "D";
public static final String AMOUNT_PREFIX = "T";
public static final String MEMO_PREFIX = "M";
public static final String CATEGORY_PREFIX = "L";
public static final String SPLIT_MEMO_PREFIX = "E";
public static final String SPLIT_AMOUNT_PREFIX = "$";
public static final String SPLIT_CATEGORY_PREFIX = "S";
public static final String SPLIT_PERCENTAGE_PREFIX = "%";
public static final String ACCOUNT_HEADER = "!Account";
public static final String ACCOUNT_NAME_PREFIX = "N";
public static final String INTERNAL_CURRENCY_PREFIX = "*";
public static final String ENTRY_TERMINATOR = "^";
private static final SimpleDateFormat QIF_DATE_FORMATTER = new SimpleDateFormat("yyyy/M/d");
/**
* Formats the date for QIF in the form d MMMM YYYY.
* For example 25 January 2013
* @param timeMillis Time in milliseconds since epoch
* @return Formatted date from the time
*/
public static final String formatDate(long timeMillis){
Date date = new Date(timeMillis);
return QIF_DATE_FORMATTER.format(date);
}
/**
* Returns the QIF header for the transaction based on the account type.
* By default, the QIF cash header is used
* @param accountType AccountType of account
* @return QIF header for the transactions
*/
public static String getQifHeader(AccountType accountType){
switch (accountType) {
case CASH:
return "!Type:Cash";
case BANK:
return "!Type:Bank";
case CREDIT:
return "!Type:CCard";
case ASSET:
return "!Type:Oth A";
case LIABILITY:
return "!Type:Oth L";
default:
return "!Type:Cash";
}
}
public static String getQifHeader(String accountType) {
return getQifHeader(AccountType.valueOf(accountType));
}
}
| 3,050 | 34.068966 | 96 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/xml/GncXmlExporter.java
|
/*
* Copyright (c) 2014 - 2015 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export.xml;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.RecurrenceDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.export.ExportFormat;
import org.gnucash.android.export.ExportParams;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.BaseModel;
import org.gnucash.android.model.Book;
import org.gnucash.android.model.Budget;
import org.gnucash.android.model.BudgetAmount;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.PeriodType;
import org.gnucash.android.model.Recurrence;
import org.gnucash.android.model.ScheduledAction;
import org.gnucash.android.model.TransactionType;
import org.gnucash.android.util.BookUtils;
import org.gnucash.android.util.TimestampHelper;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.zip.GZIPOutputStream;
import static org.gnucash.android.db.DatabaseSchema.ScheduledActionEntry;
import static org.gnucash.android.db.DatabaseSchema.SplitEntry;
import static org.gnucash.android.db.DatabaseSchema.TransactionEntry;
/**
* Creates a GnuCash XML representation of the accounts and transactions
*
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
*/
public class GncXmlExporter extends Exporter{
/**
* Root account for template accounts
*/
private Account mRootTemplateAccount;
private Map<String, Account> mTransactionToTemplateAccountMap = new TreeMap<>();
/**
* Construct a new exporter with export parameters
* @param params Parameters for the export
*/
public GncXmlExporter(ExportParams params) {
super(params, null);
LOG_TAG = "GncXmlExporter";
}
/**
* Overloaded constructor.
* Creates an exporter with an already open database instance.
* @param params Parameters for the export
* @param db SQLite database
*/
public GncXmlExporter(ExportParams params, SQLiteDatabase db) {
super(params, db);
LOG_TAG = "GncXmlExporter";
}
private void exportSlots(XmlSerializer xmlSerializer,
List<String> slotKey,
List<String> slotType,
List<String> slotValue) throws IOException {
if (slotKey == null || slotType == null || slotValue == null ||
slotKey.size() == 0 || slotType.size() != slotKey.size() || slotValue.size() != slotKey.size()) {
return;
}
for (int i = 0; i < slotKey.size(); i++) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT_KEY);
xmlSerializer.text(slotKey.get(i));
xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT_KEY);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT_VALUE);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, slotType.get(i));
xmlSerializer.text(slotValue.get(i));
xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT_VALUE);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT);
}
}
private void exportAccounts(XmlSerializer xmlSerializer) throws IOException {
// gnucash desktop requires that parent account appears before its descendants.
// sort by full-name to fulfill the request
Cursor cursor = mAccountsDbAdapter.fetchAccounts(null, null, DatabaseSchema.AccountEntry.COLUMN_FULL_NAME + " ASC");
while (cursor.moveToNext()) {
// write account
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCOUNT);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, GncXmlHelper.BOOK_VERSION);
// account name
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_NAME);
xmlSerializer.text(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_NAME)));
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_NAME);
// account guid
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_ID);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_UID)));
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_ID);
// account type
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_TYPE);
String acct_type = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_TYPE));
xmlSerializer.text(acct_type);
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_TYPE);
// commodity
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_COMMODITY);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.text("ISO4217");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_ID);
String acctCurrencyCode = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_CURRENCY));
xmlSerializer.text(acctCurrencyCode);
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_COMMODITY);
// commodity scu
Commodity commodity = CommoditiesDbAdapter.getInstance().getCommodity(acctCurrencyCode);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SCU);
xmlSerializer.text(Integer.toString(commodity.getSmallestFraction()));
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SCU);
// account description
String description = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_DESCRIPTION));
if (description != null && !description.equals("")) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_DESCRIPTION);
xmlSerializer.text(description);
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_DESCRIPTION);
}
// account slots, color, placeholder, default transfer account, favorite
ArrayList<String> slotKey = new ArrayList<>();
ArrayList<String> slotType = new ArrayList<>();
ArrayList<String> slotValue = new ArrayList<>();
slotKey.add(GncXmlHelper.KEY_PLACEHOLDER);
slotType.add(GncXmlHelper.ATTR_VALUE_STRING);
slotValue.add(Boolean.toString(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_PLACEHOLDER)) != 0));
String color = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_COLOR_CODE));
if (color != null && color.length() > 0) {
slotKey.add(GncXmlHelper.KEY_COLOR);
slotType.add(GncXmlHelper.ATTR_VALUE_STRING);
slotValue.add(color);
}
String defaultTransferAcctUID = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_DEFAULT_TRANSFER_ACCOUNT_UID));
if (defaultTransferAcctUID != null && defaultTransferAcctUID.length() > 0) {
slotKey.add(GncXmlHelper.KEY_DEFAULT_TRANSFER_ACCOUNT);
slotType.add(GncXmlHelper.ATTR_VALUE_STRING);
slotValue.add(defaultTransferAcctUID);
}
slotKey.add(GncXmlHelper.KEY_FAVORITE);
slotType.add(GncXmlHelper.ATTR_VALUE_STRING);
slotValue.add(Boolean.toString(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_FAVORITE)) != 0));
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_SLOTS);
exportSlots(xmlSerializer, slotKey, slotType, slotValue);
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_SLOTS);
// parent uid
String parentUID = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_PARENT_ACCOUNT_UID));
if (!acct_type.equals("ROOT") && parentUID != null && parentUID.length() > 0) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_PARENT_UID);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(parentUID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_PARENT_UID);
} else {
Log.d("export", "root account : " + cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_UID)));
}
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCOUNT);
}
cursor.close();
}
/**
* Exports template accounts
* <p>Template accounts are just dummy accounts created for use with template transactions</p>
* @param xmlSerializer XML serializer
* @param accountList List of template accounts
* @throws IOException if could not write XML to output stream
*/
private void exportTemplateAccounts(XmlSerializer xmlSerializer, Collection<Account> accountList) throws IOException {
for (Account account : accountList) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCOUNT);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, GncXmlHelper.BOOK_VERSION);
// account name
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_NAME);
xmlSerializer.text(account.getName());
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_NAME);
// account guid
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_ID);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(account.getUID());
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_ID);
// account type
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_TYPE);
xmlSerializer.text(account.getAccountType().name());
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_TYPE);
// commodity
xmlSerializer.startTag(null, GncXmlHelper.TAG_ACCT_COMMODITY);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.text("template");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_ID);
String acctCurrencyCode = "template";
xmlSerializer.text(acctCurrencyCode);
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCT_COMMODITY);
// commodity scu
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SCU);
xmlSerializer.text("1");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SCU);
if (account.getAccountType() != AccountType.ROOT && mRootTemplateAccount != null) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_PARENT_UID);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(mRootTemplateAccount.getUID());
xmlSerializer.endTag(null, GncXmlHelper.TAG_PARENT_UID);
}
xmlSerializer.endTag(null, GncXmlHelper.TAG_ACCOUNT);
}
}
/**
* Serializes transactions from the database to XML
* @param xmlSerializer XML serializer
* @param exportTemplates Flag whether to export templates or normal transactions
* @throws IOException if the XML serializer cannot be written to
*/
private void exportTransactions(XmlSerializer xmlSerializer, boolean exportTemplates) throws IOException {
String where = TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TEMPLATE + "=0";
if (exportTemplates) {
where = TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TEMPLATE + "=1";
}
Cursor cursor = mTransactionsDbAdapter.fetchTransactionsWithSplits(
new String[]{
TransactionEntry.TABLE_NAME+"."+ TransactionEntry.COLUMN_UID + " AS trans_uid",
TransactionEntry.TABLE_NAME+"."+ TransactionEntry.COLUMN_DESCRIPTION + " AS trans_desc",
TransactionEntry.TABLE_NAME+"."+ TransactionEntry.COLUMN_NOTES + " AS trans_notes",
TransactionEntry.TABLE_NAME+"."+ TransactionEntry.COLUMN_TIMESTAMP + " AS trans_time",
TransactionEntry.TABLE_NAME+"."+ TransactionEntry.COLUMN_EXPORTED + " AS trans_exported",
TransactionEntry.TABLE_NAME+"."+ TransactionEntry.COLUMN_CURRENCY + " AS trans_currency",
TransactionEntry.TABLE_NAME+"."+ TransactionEntry.COLUMN_CREATED_AT + " AS trans_date_posted",
TransactionEntry.TABLE_NAME+"."+ TransactionEntry.COLUMN_SCHEDX_ACTION_UID + " AS trans_from_sched_action",
SplitEntry.TABLE_NAME+"."+ SplitEntry.COLUMN_UID + " AS split_uid",
SplitEntry.TABLE_NAME+"."+ SplitEntry.COLUMN_MEMO + " AS split_memo",
SplitEntry.TABLE_NAME+"."+ SplitEntry.COLUMN_TYPE + " AS split_type",
SplitEntry.TABLE_NAME+"."+ SplitEntry.COLUMN_VALUE_NUM + " AS split_value_num",
SplitEntry.TABLE_NAME+"."+ SplitEntry.COLUMN_VALUE_DENOM + " AS split_value_denom",
SplitEntry.TABLE_NAME+"."+ SplitEntry.COLUMN_QUANTITY_NUM + " AS split_quantity_num",
SplitEntry.TABLE_NAME+"."+ SplitEntry.COLUMN_QUANTITY_DENOM + " AS split_quantity_denom", SplitEntry.TABLE_NAME+"."+ SplitEntry.COLUMN_ACCOUNT_UID + " AS split_acct_uid"},
where, null,
TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_TIMESTAMP + " ASC , " +
TransactionEntry.TABLE_NAME + "." + TransactionEntry.COLUMN_UID + " ASC ");
String lastTrxUID = "";
Commodity trnCommodity = null;
String denomString = "100";
if (exportTemplates) {
mRootTemplateAccount = new Account("Template Root");
mRootTemplateAccount.setAccountType(AccountType.ROOT);
mTransactionToTemplateAccountMap.put(" ", mRootTemplateAccount);
//FIXME: Retrieve the template account GUIDs from the scheduled action table and create accounts with that
//this will allow use to maintain the template account GUID when we import from the desktop and also use the same for the splits
while (cursor.moveToNext()) {
Account account = new Account(BaseModel.generateUID());
account.setAccountType(AccountType.BANK);
String trnUID = cursor.getString(cursor.getColumnIndexOrThrow("trans_uid"));
mTransactionToTemplateAccountMap.put(trnUID, account);
}
exportTemplateAccounts(xmlSerializer, mTransactionToTemplateAccountMap.values());
//push cursor back to before the beginning
cursor.moveToFirst();
cursor.moveToPrevious();
}
//// FIXME: 12.10.2015 export split reconciled_state and reconciled_date to the export
while (cursor.moveToNext()){
String curTrxUID = cursor.getString(cursor.getColumnIndexOrThrow("trans_uid"));
if (!lastTrxUID.equals(curTrxUID)) { // new transaction starts
if (!lastTrxUID.equals("")) { // there's an old transaction, close it
xmlSerializer.endTag(null, GncXmlHelper.TAG_TRN_SPLITS);
xmlSerializer.endTag(null, GncXmlHelper.TAG_TRANSACTION);
}
// new transaction
xmlSerializer.startTag(null, GncXmlHelper.TAG_TRANSACTION);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, GncXmlHelper.BOOK_VERSION);
// transaction id
xmlSerializer.startTag(null, GncXmlHelper.TAG_TRX_ID);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(curTrxUID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_TRX_ID);
// currency
String currencyCode = cursor.getString(cursor.getColumnIndexOrThrow("trans_currency"));
trnCommodity = CommoditiesDbAdapter.getInstance().getCommodity(currencyCode);//Currency.getInstance(currencyCode);
xmlSerializer.startTag(null, GncXmlHelper.TAG_TRX_CURRENCY);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.text("ISO4217");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.text(currencyCode);
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_TRX_CURRENCY);
// date posted, time which user put on the transaction
String strDate = GncXmlHelper.formatDate(cursor.getLong(cursor.getColumnIndexOrThrow("trans_time")));
xmlSerializer.startTag(null, GncXmlHelper.TAG_DATE_POSTED);
xmlSerializer.startTag(null, GncXmlHelper.TAG_TS_DATE);
xmlSerializer.text(strDate);
xmlSerializer.endTag(null, GncXmlHelper.TAG_TS_DATE);
xmlSerializer.endTag(null, GncXmlHelper.TAG_DATE_POSTED);
// date entered, time when the transaction was actually created
Timestamp timeEntered = TimestampHelper.getTimestampFromUtcString(cursor.getString(cursor.getColumnIndexOrThrow("trans_date_posted")));
String dateEntered = GncXmlHelper.formatDate(timeEntered.getTime());
xmlSerializer.startTag(null, GncXmlHelper.TAG_DATE_ENTERED);
xmlSerializer.startTag(null, GncXmlHelper.TAG_TS_DATE);
xmlSerializer.text(dateEntered);
xmlSerializer.endTag(null, GncXmlHelper.TAG_TS_DATE);
xmlSerializer.endTag(null, GncXmlHelper.TAG_DATE_ENTERED);
// description
xmlSerializer.startTag(null, GncXmlHelper.TAG_TRN_DESCRIPTION);
xmlSerializer.text(cursor.getString(cursor.getColumnIndexOrThrow("trans_desc")));
xmlSerializer.endTag(null, GncXmlHelper.TAG_TRN_DESCRIPTION);
lastTrxUID = curTrxUID;
// slots
ArrayList<String> slotKey = new ArrayList<>();
ArrayList<String> slotType = new ArrayList<>();
ArrayList<String> slotValue = new ArrayList<>();
String notes = cursor.getString(cursor.getColumnIndexOrThrow("trans_notes"));
if (notes != null && notes.length() > 0) {
slotKey.add(GncXmlHelper.KEY_NOTES);
slotType.add(GncXmlHelper.ATTR_VALUE_STRING);
slotValue.add(notes);
}
String scheduledActionUID = cursor.getString(cursor.getColumnIndexOrThrow("trans_from_sched_action"));
if (scheduledActionUID != null && !scheduledActionUID.isEmpty()){
slotKey.add(GncXmlHelper.KEY_FROM_SCHED_ACTION);
slotType.add(GncXmlHelper.ATTR_VALUE_GUID);
slotValue.add(scheduledActionUID);
}
xmlSerializer.startTag(null, GncXmlHelper.TAG_TRN_SLOTS);
exportSlots(xmlSerializer, slotKey, slotType, slotValue);
xmlSerializer.endTag(null, GncXmlHelper.TAG_TRN_SLOTS);
// splits start
xmlSerializer.startTag(null, GncXmlHelper.TAG_TRN_SPLITS);
}
xmlSerializer.startTag(null, GncXmlHelper.TAG_TRN_SPLIT);
// split id
xmlSerializer.startTag(null, GncXmlHelper.TAG_SPLIT_ID);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(cursor.getString(cursor.getColumnIndexOrThrow("split_uid")));
xmlSerializer.endTag(null, GncXmlHelper.TAG_SPLIT_ID);
// memo
String memo = cursor.getString(cursor.getColumnIndexOrThrow("split_memo"));
if (memo != null && memo.length() > 0){
xmlSerializer.startTag(null, GncXmlHelper.TAG_SPLIT_MEMO);
xmlSerializer.text(memo);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SPLIT_MEMO);
}
// reconciled
xmlSerializer.startTag(null, GncXmlHelper.TAG_RECONCILED_STATE);
xmlSerializer.text("n"); //fixme: retrieve reconciled state from the split in the db
xmlSerializer.endTag(null, GncXmlHelper.TAG_RECONCILED_STATE);
//todo: if split is reconciled, add reconciled date
// value, in the transaction's currency
String trxType = cursor.getString(cursor.getColumnIndexOrThrow("split_type"));
int splitValueNum = cursor.getInt(cursor.getColumnIndexOrThrow("split_value_num"));
int splitValueDenom = cursor.getInt(cursor.getColumnIndexOrThrow("split_value_denom"));
BigDecimal splitAmount = Money.getBigDecimal(splitValueNum, splitValueDenom);
String strValue = "0/" + denomString;
if (!exportTemplates) { //when doing normal transaction export
strValue = (trxType.equals("CREDIT") ? "-" : "") + splitValueNum + "/" + splitValueDenom;
}
xmlSerializer.startTag(null, GncXmlHelper.TAG_SPLIT_VALUE);
xmlSerializer.text(strValue);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SPLIT_VALUE);
// quantity, in the split account's currency
String splitQuantityNum = cursor.getString(cursor.getColumnIndexOrThrow("split_quantity_num"));
String splitQuantityDenom = cursor.getString(cursor.getColumnIndexOrThrow("split_quantity_denom"));
if (!exportTemplates) {
strValue = (trxType.equals("CREDIT") ? "-" : "") + splitQuantityNum + "/" + splitQuantityDenom;
}
xmlSerializer.startTag(null, GncXmlHelper.TAG_SPLIT_QUANTITY);
xmlSerializer.text(strValue);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SPLIT_QUANTITY);
// account guid
xmlSerializer.startTag(null, GncXmlHelper.TAG_SPLIT_ACCOUNT);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
String splitAccountUID;
if (exportTemplates){
//get the UID of the template account
splitAccountUID = mTransactionToTemplateAccountMap.get(curTrxUID).getUID();
} else {
splitAccountUID = cursor.getString(cursor.getColumnIndexOrThrow("split_acct_uid"));
}
xmlSerializer.text(splitAccountUID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SPLIT_ACCOUNT);
//if we are exporting a template transaction, then we need to add some extra slots
if (exportTemplates){
xmlSerializer.startTag(null, GncXmlHelper.TAG_SPLIT_SLOTS);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT_KEY);
xmlSerializer.text(GncXmlHelper.KEY_SCHEDX_ACTION); //FIXME: not all templates may be scheduled actions
xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT_KEY);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT_VALUE);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, "frame");
List<String> slotKeys = new ArrayList<>();
List<String> slotTypes = new ArrayList<>();
List<String> slotValues = new ArrayList<>();
slotKeys.add(GncXmlHelper.KEY_SPLIT_ACCOUNT_SLOT);
slotTypes.add(GncXmlHelper.ATTR_VALUE_GUID);
slotValues.add(cursor.getString(cursor.getColumnIndexOrThrow("split_acct_uid")));
TransactionType type = TransactionType.valueOf(trxType);
if (type == TransactionType.CREDIT){
slotKeys.add(GncXmlHelper.KEY_CREDIT_FORMULA);
slotTypes.add(GncXmlHelper.ATTR_VALUE_STRING);
slotValues.add(GncXmlHelper.formatTemplateSplitAmount(splitAmount));
slotKeys.add(GncXmlHelper.KEY_CREDIT_NUMERIC);
slotTypes.add(GncXmlHelper.ATTR_VALUE_NUMERIC);
slotValues.add(GncXmlHelper.formatSplitAmount(splitAmount, trnCommodity));
} else {
slotKeys.add(GncXmlHelper.KEY_DEBIT_FORMULA);
slotTypes.add(GncXmlHelper.ATTR_VALUE_STRING);
slotValues.add(GncXmlHelper.formatTemplateSplitAmount(splitAmount));
slotKeys.add(GncXmlHelper.KEY_DEBIT_NUMERIC);
slotTypes.add(GncXmlHelper.ATTR_VALUE_NUMERIC);
slotValues.add(GncXmlHelper.formatSplitAmount(splitAmount, trnCommodity));
}
exportSlots(xmlSerializer, slotKeys, slotTypes, slotValues);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT_VALUE);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SPLIT_SLOTS);
}
xmlSerializer.endTag(null, GncXmlHelper.TAG_TRN_SPLIT);
}
if (!lastTrxUID.equals("")){ // there's an unfinished transaction, close it
xmlSerializer.endTag(null,GncXmlHelper.TAG_TRN_SPLITS);
xmlSerializer.endTag(null, GncXmlHelper.TAG_TRANSACTION);
}
cursor.close();
}
/**
* Serializes {@link ScheduledAction}s from the database to XML
* @param xmlSerializer XML serializer
* @throws IOException
*/
private void exportScheduledTransactions(XmlSerializer xmlSerializer) throws IOException{
//for now we will export only scheduled transactions to XML
Cursor cursor = mScheduledActionDbAdapter.fetchAllRecords(
ScheduledActionEntry.COLUMN_TYPE + "=?", new String[]{ScheduledAction.ActionType.TRANSACTION.name()}, null);
while (cursor.moveToNext()) {
ScheduledAction scheduledAction = mScheduledActionDbAdapter.buildModelInstance(cursor);
String actionUID = scheduledAction.getActionUID();
Account accountUID = mTransactionToTemplateAccountMap.get(actionUID);
if (accountUID == null) //if the action UID does not belong to a transaction we've seen before, skip it
continue;
xmlSerializer.startTag(null, GncXmlHelper.TAG_SCHEDULED_ACTION);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, GncXmlHelper.BOOK_VERSION);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_ID);
String nameUID = accountUID.getName();
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(nameUID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_ID);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_NAME);
ScheduledAction.ActionType actionType = scheduledAction.getActionType();
if (actionType == ScheduledAction.ActionType.TRANSACTION) {
String description = TransactionsDbAdapter.getInstance().getAttribute(actionUID, TransactionEntry.COLUMN_DESCRIPTION);
xmlSerializer.text(description);
} else {
xmlSerializer.text(actionType.name());
}
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_NAME);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_ENABLED);
xmlSerializer.text(scheduledAction.isEnabled() ? "y" : "n");
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_ENABLED);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_AUTO_CREATE);
xmlSerializer.text(scheduledAction.shouldAutoCreate() ? "y" : "n");
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_AUTO_CREATE);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_AUTO_CREATE_NOTIFY);
xmlSerializer.text(scheduledAction.shouldAutoNotify() ? "y" : "n");
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_AUTO_CREATE_NOTIFY);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_ADVANCE_CREATE_DAYS);
xmlSerializer.text(Integer.toString(scheduledAction.getAdvanceCreateDays()));
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_ADVANCE_CREATE_DAYS);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_ADVANCE_REMIND_DAYS);
xmlSerializer.text(Integer.toString(scheduledAction.getAdvanceNotifyDays()));
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_ADVANCE_REMIND_DAYS);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_INSTANCE_COUNT);
String scheduledActionUID = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_UID));
long instanceCount = mScheduledActionDbAdapter.getActionInstanceCount(scheduledActionUID);
xmlSerializer.text(Long.toString(instanceCount));
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_INSTANCE_COUNT);
//start date
String createdTimestamp = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_CREATED_AT));
long scheduleStartTime = TimestampHelper.getTimestampFromUtcString(createdTimestamp).getTime();
serializeDate(xmlSerializer, GncXmlHelper.TAG_SX_START, scheduleStartTime);
long lastRunTime = cursor.getLong(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_LAST_RUN));
if (lastRunTime > 0){
serializeDate(xmlSerializer, GncXmlHelper.TAG_SX_LAST, lastRunTime);
}
long endTime = cursor.getLong(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_END_TIME));
if (endTime > 0) {
//end date
serializeDate(xmlSerializer, GncXmlHelper.TAG_SX_END, endTime);
} else { //add number of occurrences
int totalFrequency = cursor.getInt(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_TOTAL_FREQUENCY));
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_NUM_OCCUR);
xmlSerializer.text(Integer.toString(totalFrequency));
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_NUM_OCCUR);
//remaining occurrences
int executionCount = cursor.getInt(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_EXECUTION_COUNT));
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_REM_OCCUR);
xmlSerializer.text(Integer.toString(totalFrequency - executionCount));
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_REM_OCCUR);
}
String tag = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_TAG));
if (tag != null && !tag.isEmpty()){
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_TAG);
xmlSerializer.text(tag);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_TAG);
}
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_TEMPL_ACCOUNT);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(accountUID.getUID());
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_TEMPL_ACCOUNT);
//// FIXME: 11.10.2015 Retrieve the information for this section from the recurrence table
xmlSerializer.startTag(null, GncXmlHelper.TAG_SX_SCHEDULE);
xmlSerializer.startTag(null, GncXmlHelper.TAG_GNC_RECURRENCE);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, GncXmlHelper.RECURRENCE_VERSION);
String recurrenceUID = cursor.getString(cursor.getColumnIndexOrThrow(ScheduledActionEntry.COLUMN_RECURRENCE_UID));
Recurrence recurrence = RecurrenceDbAdapter.getInstance().getRecord(recurrenceUID);
exportRecurrence(xmlSerializer, recurrence);
xmlSerializer.endTag(null, GncXmlHelper.TAG_GNC_RECURRENCE);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SX_SCHEDULE);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SCHEDULED_ACTION);
}
}
/**
* Serializes a date as a {@code tag} which has a nested {@link GncXmlHelper#TAG_GDATE} which
* has the date as a text element formatted using {@link GncXmlHelper#DATE_FORMATTER}
* @param xmlSerializer XML serializer
* @param tag Enclosing tag
* @param timeMillis Date to be formatted and output
* @throws IOException
*/
private void serializeDate(XmlSerializer xmlSerializer, String tag, long timeMillis) throws IOException {
xmlSerializer.startTag(null, tag);
xmlSerializer.startTag(null, GncXmlHelper.TAG_GDATE);
xmlSerializer.text(GncXmlHelper.DATE_FORMATTER.format(timeMillis));
xmlSerializer.endTag(null, GncXmlHelper.TAG_GDATE);
xmlSerializer.endTag(null, tag);
}
private void exportCommodities(XmlSerializer xmlSerializer, List<Commodity> commodities) throws IOException {
for (Commodity commodity : commodities) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, GncXmlHelper.BOOK_VERSION);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.text("ISO4217");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.text(commodity.getCurrencyCode());
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY);
}
}
private void exportPrices(XmlSerializer xmlSerializer) throws IOException {
xmlSerializer.startTag(null, GncXmlHelper.TAG_PRICEDB);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, "1");
Cursor cursor = mPricesDbAdapter.fetchAllRecords();
try {
while(cursor.moveToNext()) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_PRICE);
// GUID
xmlSerializer.startTag(null, GncXmlHelper.TAG_PRICE_ID);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.CommonColumns.COLUMN_UID)));
xmlSerializer.endTag(null, GncXmlHelper.TAG_PRICE_ID);
// commodity
xmlSerializer.startTag(null, GncXmlHelper.TAG_PRICE_COMMODITY);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.text("ISO4217");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.text(mCommoditiesDbAdapter.getCurrencyCode(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.PriceEntry.COLUMN_COMMODITY_UID))));
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_PRICE_COMMODITY);
// currency
xmlSerializer.startTag(null, GncXmlHelper.TAG_PRICE_CURRENCY);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.text("ISO4217");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.text(mCommoditiesDbAdapter.getCurrencyCode(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.PriceEntry.COLUMN_CURRENCY_UID))));
xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_ID);
xmlSerializer.endTag(null, GncXmlHelper.TAG_PRICE_CURRENCY);
// time
String strDate = GncXmlHelper.formatDate(TimestampHelper.getTimestampFromUtcString(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.PriceEntry.COLUMN_DATE))).getTime());
xmlSerializer.startTag(null, GncXmlHelper.TAG_PRICE_TIME);
xmlSerializer.startTag(null, GncXmlHelper.TAG_TS_DATE);
xmlSerializer.text(strDate);
xmlSerializer.endTag(null, GncXmlHelper.TAG_TS_DATE);
xmlSerializer.endTag(null, GncXmlHelper.TAG_PRICE_TIME);
// source
xmlSerializer.startTag(null, GncXmlHelper.TAG_PRICE_SOURCE);
xmlSerializer.text(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.PriceEntry.COLUMN_SOURCE)));
xmlSerializer.endTag(null, GncXmlHelper.TAG_PRICE_SOURCE);
// type, optional
String type = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.PriceEntry.COLUMN_TYPE));
if (type != null && !type.equals("")) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_PRICE_TYPE);
xmlSerializer.text(type);
xmlSerializer.endTag(null, GncXmlHelper.TAG_PRICE_TYPE);
}
// value
xmlSerializer.startTag(null, GncXmlHelper.TAG_PRICE_VALUE);
xmlSerializer.text(cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseSchema.PriceEntry.COLUMN_VALUE_NUM))
+ "/" + cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseSchema.PriceEntry.COLUMN_VALUE_DENOM)));
xmlSerializer.endTag(null, GncXmlHelper.TAG_PRICE_VALUE);
xmlSerializer.endTag(null, GncXmlHelper.TAG_PRICE);
}
} finally {
cursor.close();
}
xmlSerializer.endTag(null, GncXmlHelper.TAG_PRICEDB);
}
/**
* Exports the recurrence to GnuCash XML, except the recurrence tags itself i.e. the actual recurrence attributes only
* <p>This is because there are different recurrence start tags for transactions and budgets.<br>
* So make sure to write the recurrence start/closing tags before/after calling this method.</p>
* @param xmlSerializer XML serializer
* @param recurrence Recurrence object
*/
private void exportRecurrence(XmlSerializer xmlSerializer, Recurrence recurrence) throws IOException{
PeriodType periodType = recurrence.getPeriodType();
xmlSerializer.startTag(null, GncXmlHelper.TAG_RX_MULT);
xmlSerializer.text(String.valueOf(recurrence.getMultiplier()));
xmlSerializer.endTag(null, GncXmlHelper.TAG_RX_MULT);
xmlSerializer.startTag(null, GncXmlHelper.TAG_RX_PERIOD_TYPE);
xmlSerializer.text(periodType.name().toLowerCase());
xmlSerializer.endTag(null, GncXmlHelper.TAG_RX_PERIOD_TYPE);
long recurrenceStartTime = recurrence.getPeriodStart().getTime();
serializeDate(xmlSerializer, GncXmlHelper.TAG_RX_START, recurrenceStartTime);
}
private void exportBudgets(XmlSerializer xmlSerializer) throws IOException {
Cursor cursor = mBudgetsDbAdapter.fetchAllRecords();
while(cursor.moveToNext()) {
Budget budget = mBudgetsDbAdapter.buildModelInstance(cursor);
xmlSerializer.startTag(null, GncXmlHelper.TAG_BUDGET);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, GncXmlHelper.BOOK_VERSION);
xmlSerializer.startTag(null, GncXmlHelper.TAG_BUDGET_ID);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(budget.getUID());
xmlSerializer.endTag(null, GncXmlHelper.TAG_BUDGET_ID);
xmlSerializer.startTag(null, GncXmlHelper.TAG_BUDGET_NAME);
xmlSerializer.text(budget.getName());
xmlSerializer.endTag(null, GncXmlHelper.TAG_BUDGET_NAME);
xmlSerializer.startTag(null, GncXmlHelper.TAG_BUDGET_DESCRIPTION);
xmlSerializer.text(budget.getDescription() == null ? "" : budget.getDescription());
xmlSerializer.endTag(null, GncXmlHelper.TAG_BUDGET_DESCRIPTION);
xmlSerializer.startTag(null, GncXmlHelper.TAG_BUDGET_NUM_PERIODS);
xmlSerializer.text(Long.toString(budget.getNumberOfPeriods()));
xmlSerializer.endTag(null, GncXmlHelper.TAG_BUDGET_NUM_PERIODS);
xmlSerializer.startTag(null, GncXmlHelper.TAG_BUDGET_RECURRENCE);
exportRecurrence(xmlSerializer, budget.getRecurrence());
xmlSerializer.endTag(null, GncXmlHelper.TAG_BUDGET_RECURRENCE);
//export budget slots
ArrayList<String> slotKey = new ArrayList<>();
ArrayList<String> slotType = new ArrayList<>();
ArrayList<String> slotValue = new ArrayList<>();
xmlSerializer.startTag(null, GncXmlHelper.TAG_BUDGET_SLOTS);
for (BudgetAmount budgetAmount : budget.getExpandedBudgetAmounts()) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT);
xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT_KEY);
xmlSerializer.text(budgetAmount.getAccountUID());
xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT_KEY);
Money amount = budgetAmount.getAmount();
slotKey.clear();
slotType.clear();
slotValue.clear();
for (int period = 0; period < budget.getNumberOfPeriods(); period++) {
slotKey.add(String.valueOf(period));
slotType.add(GncXmlHelper.ATTR_VALUE_NUMERIC);
slotValue.add(amount.getNumerator() + "/" + amount.getDenominator());
}
//budget slots
xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT_VALUE);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_FRAME);
exportSlots(xmlSerializer, slotKey, slotType, slotValue);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT_VALUE);
xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT);
}
xmlSerializer.endTag(null, GncXmlHelper.TAG_BUDGET_SLOTS);
xmlSerializer.endTag(null, GncXmlHelper.TAG_BUDGET);
}
cursor.close();
}
@Override
public List<String> generateExport() throws ExporterException {
OutputStreamWriter writer = null;
String outputFile = getExportCacheFilePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
writer = new OutputStreamWriter(bufferedOutputStream);
generateExport(writer);
} catch (IOException ex){
Crashlytics.log("Error exporting XML");
Crashlytics.logException(ex);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
throw new ExporterException(mExportParams, e);
}
}
}
List<String> exportedFiles = new ArrayList<>();
exportedFiles.add(outputFile);
return exportedFiles;
}
/**
* Generates an XML export of the database and writes it to the {@code writer} output stream
* @param writer Output stream
* @throws ExporterException
*/
public void generateExport(Writer writer) throws ExporterException {
try {
String[] namespaces = new String[]{"gnc", "act", "book", "cd", "cmdty", "price", "slot",
"split", "trn", "ts", "sx", "bgt", "recurrence"};
XmlSerializer xmlSerializer = XmlPullParserFactory.newInstance().newSerializer();
try {
xmlSerializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
} catch (IllegalStateException e) {
// Feature not supported. No problem
}
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("utf-8", true);
// root tag
xmlSerializer.startTag(null, GncXmlHelper.TAG_ROOT);
for (String ns : namespaces) {
xmlSerializer.attribute(null, "xmlns:" + ns, "http://www.gnucash.org/XML/" + ns);
}
// book count
xmlSerializer.startTag(null, GncXmlHelper.TAG_COUNT_DATA);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_CD_TYPE, GncXmlHelper.ATTR_VALUE_BOOK);
xmlSerializer.text("1");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COUNT_DATA);
// book
xmlSerializer.startTag(null, GncXmlHelper.TAG_BOOK);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, GncXmlHelper.BOOK_VERSION);
// book_id
xmlSerializer.startTag(null, GncXmlHelper.TAG_BOOK_ID);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, GncXmlHelper.ATTR_VALUE_GUID);
xmlSerializer.text(BaseModel.generateUID());
xmlSerializer.endTag(null, GncXmlHelper.TAG_BOOK_ID);
//commodity count
List<Commodity> commodities = mAccountsDbAdapter.getCommoditiesInUse();
for (int i = 0; i < commodities.size(); i++) {
if (commodities.get(i).getCurrencyCode().equals("XXX")) {
commodities.remove(i);
}
}
xmlSerializer.startTag(null, GncXmlHelper.TAG_COUNT_DATA);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_CD_TYPE, "commodity");
xmlSerializer.text(commodities.size() + "");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COUNT_DATA);
//account count
xmlSerializer.startTag(null, GncXmlHelper.TAG_COUNT_DATA);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_CD_TYPE, "account");
xmlSerializer.text(mAccountsDbAdapter.getRecordsCount() + "");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COUNT_DATA);
//transaction count
xmlSerializer.startTag(null, GncXmlHelper.TAG_COUNT_DATA);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_CD_TYPE, "transaction");
xmlSerializer.text(mTransactionsDbAdapter.getRecordsCount() + "");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COUNT_DATA);
//price count
long priceCount = mPricesDbAdapter.getRecordsCount();
if (priceCount > 0) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_COUNT_DATA);
xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_CD_TYPE, "price");
xmlSerializer.text(priceCount + "");
xmlSerializer.endTag(null, GncXmlHelper.TAG_COUNT_DATA);
}
// export the commodities used in the DB
exportCommodities(xmlSerializer, commodities);
// prices
if (priceCount > 0) {
exportPrices(xmlSerializer);
}
// accounts.
exportAccounts(xmlSerializer);
// transactions.
exportTransactions(xmlSerializer, false);
//transaction templates
if (mTransactionsDbAdapter.getTemplateTransactionsCount() > 0) {
xmlSerializer.startTag(null, GncXmlHelper.TAG_TEMPLATE_TRANSACTIONS);
exportTransactions(xmlSerializer, true);
xmlSerializer.endTag(null, GncXmlHelper.TAG_TEMPLATE_TRANSACTIONS);
}
//scheduled actions
exportScheduledTransactions(xmlSerializer);
//budgets
exportBudgets(xmlSerializer);
xmlSerializer.endTag(null, GncXmlHelper.TAG_BOOK);
xmlSerializer.endTag(null, GncXmlHelper.TAG_ROOT);
xmlSerializer.endDocument();
xmlSerializer.flush();
} catch (Exception e) {
Crashlytics.logException(e);
throw new ExporterException(mExportParams, e);
}
}
/**
* Returns the MIME type for this exporter.
* @return MIME type as string
*/
public String getExportMimeType(){
return "text/xml";
}
}
| 51,153 | 55.089912 | 218 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/export/xml/GncXmlHelper.java
|
/*
* Copyright (c) 2014 - 2015 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.export.xml;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.ui.transaction.TransactionFormFragment;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Collection of helper tags and methods for Gnc XML export
*
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
*/
public abstract class GncXmlHelper {
public static final String TAG_GNC_PREFIX = "gnc:";
public static final String ATTR_KEY_CD_TYPE = "cd:type";
public static final String ATTR_KEY_TYPE = "type";
public static final String ATTR_KEY_VERSION = "version";
public static final String ATTR_VALUE_STRING = "string";
public static final String ATTR_VALUE_NUMERIC = "numeric";
public static final String ATTR_VALUE_GUID = "guid";
public static final String ATTR_VALUE_BOOK = "book";
public static final String ATTR_VALUE_FRAME = "frame";
public static final String TAG_GDATE = "gdate";
/*
Qualified GnuCash XML tag names
*/
public static final String TAG_ROOT = "gnc-v2";
public static final String TAG_BOOK = "gnc:book";
public static final String TAG_BOOK_ID = "book:id";
public static final String TAG_COUNT_DATA = "gnc:count-data";
public static final String TAG_COMMODITY = "gnc:commodity";
public static final String TAG_COMMODITY_ID = "cmdty:id";
public static final String TAG_COMMODITY_SPACE = "cmdty:space";
public static final String TAG_ACCOUNT = "gnc:account";
public static final String TAG_ACCT_NAME = "act:name";
public static final String TAG_ACCT_ID = "act:id";
public static final String TAG_ACCT_TYPE = "act:type";
public static final String TAG_ACCT_COMMODITY = "act:commodity";
public static final String TAG_COMMODITY_SCU = "act:commodity-scu";
public static final String TAG_PARENT_UID = "act:parent";
public static final String TAG_SLOT_KEY = "slot:key";
public static final String TAG_SLOT_VALUE = "slot:value";
public static final String TAG_ACCT_SLOTS = "act:slots";
public static final String TAG_SLOT = "slot";
public static final String TAG_ACCT_DESCRIPTION = "act:description";
public static final String TAG_TRANSACTION = "gnc:transaction";
public static final String TAG_TRX_ID = "trn:id";
public static final String TAG_TRX_CURRENCY = "trn:currency";
public static final String TAG_DATE_POSTED = "trn:date-posted";
public static final String TAG_TS_DATE = "ts:date";
public static final String TAG_DATE_ENTERED = "trn:date-entered";
public static final String TAG_TRN_DESCRIPTION = "trn:description";
public static final String TAG_TRN_SPLITS = "trn:splits";
public static final String TAG_TRN_SPLIT = "trn:split";
public static final String TAG_TRN_SLOTS = "trn:slots";
public static final String TAG_TEMPLATE_TRANSACTIONS = "gnc:template-transactions";
public static final String TAG_SPLIT_ID = "split:id";
public static final String TAG_SPLIT_MEMO = "split:memo";
public static final String TAG_RECONCILED_STATE = "split:reconciled-state";
public static final String TAG_RECONCILED_DATE = "split:recondiled-date";
public static final String TAG_SPLIT_ACCOUNT = "split:account";
public static final String TAG_SPLIT_VALUE = "split:value";
public static final String TAG_SPLIT_QUANTITY = "split:quantity";
public static final String TAG_SPLIT_SLOTS = "split:slots";
public static final String TAG_PRICEDB = "gnc:pricedb";
public static final String TAG_PRICE = "price";
public static final String TAG_PRICE_ID = "price:id";
public static final String TAG_PRICE_COMMODITY = "price:commodity";
public static final String TAG_PRICE_CURRENCY = "price:currency";
public static final String TAG_PRICE_TIME = "price:time";
public static final String TAG_PRICE_SOURCE = "price:source";
public static final String TAG_PRICE_TYPE = "price:type";
public static final String TAG_PRICE_VALUE = "price:value";
/**
* Periodicity of the recurrence.
* <p>Only currently used for reading old backup files. May be removed in the future. </p>
* @deprecated Use {@link #TAG_GNC_RECURRENCE} instead
*/
@Deprecated
public static final String TAG_RECURRENCE_PERIOD = "trn:recurrence_period";
public static final String TAG_SCHEDULED_ACTION = "gnc:schedxaction";
public static final String TAG_SX_ID = "sx:id";
public static final String TAG_SX_NAME = "sx:name";
public static final String TAG_SX_ENABLED = "sx:enabled";
public static final String TAG_SX_AUTO_CREATE = "sx:autoCreate";
public static final String TAG_SX_AUTO_CREATE_NOTIFY = "sx:autoCreateNotify";
public static final String TAG_SX_ADVANCE_CREATE_DAYS = "sx:advanceCreateDays";
public static final String TAG_SX_ADVANCE_REMIND_DAYS = "sx:advanceRemindDays";
public static final String TAG_SX_INSTANCE_COUNT = "sx:instanceCount";
public static final String TAG_SX_START = "sx:start";
public static final String TAG_SX_LAST = "sx:last";
public static final String TAG_SX_END = "sx:end";
public static final String TAG_SX_NUM_OCCUR = "sx:num-occur";
public static final String TAG_SX_REM_OCCUR = "sx:rem-occur";
public static final String TAG_SX_TAG = "sx:tag";
public static final String TAG_SX_TEMPL_ACCOUNT = "sx:templ-acct";
public static final String TAG_SX_SCHEDULE = "sx:schedule";
public static final String TAG_GNC_RECURRENCE = "gnc:recurrence";
public static final String TAG_RX_MULT = "recurrence:mult";
public static final String TAG_RX_PERIOD_TYPE = "recurrence:period_type";
public static final String TAG_RX_START = "recurrence:start";
public static final String TAG_BUDGET = "gnc:budget";
public static final String TAG_BUDGET_ID = "bgt:id";
public static final String TAG_BUDGET_NAME = "bgt:name";
public static final String TAG_BUDGET_DESCRIPTION = "bgt:description";
public static final String TAG_BUDGET_NUM_PERIODS = "bgt:num-periods";
public static final String TAG_BUDGET_RECURRENCE = "bgt:recurrence";
public static final String TAG_BUDGET_SLOTS = "bgt:slots";
public static final String RECURRENCE_VERSION = "1.0.0";
public static final String BOOK_VERSION = "2.0.0";
public static final SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.US);
public static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
public static final String KEY_PLACEHOLDER = "placeholder";
public static final String KEY_COLOR = "color";
public static final String KEY_FAVORITE = "favorite";
public static final String KEY_NOTES = "notes";
public static final String KEY_EXPORTED = "exported";
public static final String KEY_SCHEDX_ACTION = "sched-xaction";
public static final String KEY_SPLIT_ACCOUNT_SLOT = "account";
public static final String KEY_DEBIT_FORMULA = "debit-formula";
public static final String KEY_CREDIT_FORMULA = "credit-formula";
public static final String KEY_DEBIT_NUMERIC = "debit-numeric";
public static final String KEY_CREDIT_NUMERIC = "credit-numeric";
public static final String KEY_FROM_SCHED_ACTION = "from-sched-xaction";
public static final String KEY_DEFAULT_TRANSFER_ACCOUNT = "default_transfer_account";
/**
* Formats dates for the GnuCash XML format
* @param milliseconds Milliseconds since epoch
*/
public static String formatDate(long milliseconds){
return TIME_FORMATTER.format(new Date(milliseconds));
}
/**
* Parses a date string formatted in the format "yyyy-MM-dd HH:mm:ss Z"
* @param dateString String date representation
* @return Time in milliseconds since epoch
* @throws ParseException if the date string could not be parsed e.g. because of different format
*/
public static long parseDate(String dateString) throws ParseException {
Date date = TIME_FORMATTER.parse(dateString);
return date.getTime();
}
/**
* Parses amount strings from GnuCash XML into {@link java.math.BigDecimal}s.
* The amounts are formatted as 12345/100
* @param amountString String containing the amount
* @return BigDecimal with numerical value
* @throws ParseException if the amount could not be parsed
*/
public static BigDecimal parseSplitAmount(String amountString) throws ParseException {
int pos = amountString.indexOf("/");
if (pos < 0)
{
throw new ParseException("Cannot parse money string : " + amountString, 0);
}
int scale = amountString.length() - pos - 2; //do this before, because we could modify the string
//String numerator = TransactionFormFragment.stripCurrencyFormatting(amountString.substring(0, pos));
String numerator = amountString.substring(0,pos);
numerator = TransactionFormFragment.stripCurrencyFormatting(numerator);
BigInteger numeratorInt = new BigInteger(numerator);
return new BigDecimal(numeratorInt, scale);
}
/**
* Formats money amounts for splits in the format 2550/100
* @param amount Split amount as BigDecimal
* @param commodity Commodity of the transaction
* @return Formatted split amount
* @deprecated Just use the values for numerator and denominator which are saved in the database
*/
public static String formatSplitAmount(BigDecimal amount, Commodity commodity){
int denomInt = commodity.getSmallestFraction();
BigDecimal denom = new BigDecimal(denomInt);
String denomString = Integer.toString(denomInt);
String numerator = TransactionFormFragment.stripCurrencyFormatting(amount.multiply(denom).stripTrailingZeros().toPlainString());
return numerator + "/" + denomString;
}
/**
* Format the amount in template transaction splits.
* <p>GnuCash desktop always formats with a locale dependent format, and that varies per user.<br>
* So we will use the device locale here and hope that the user has the same locale on the desktop GnuCash</p>
* @param amount Amount to be formatted
* @return String representation of amount
*/
public static String formatTemplateSplitAmount(BigDecimal amount){
//TODO: If we ever implement an application-specific locale setting, use it here as well
return NumberFormat.getNumberInstance().format(amount);
}
}
| 12,211 | 50.527426 | 136 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/importer/CommoditiesXmlHandler.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.importer;
import android.database.sqlite.SQLiteDatabase;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.model.Commodity;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
/**
* XML stream handler for parsing currencies to add to the database
*/
public class CommoditiesXmlHandler extends DefaultHandler {
public static final String TAG_CURRENCY = "currency";
public static final String ATTR_ISO_CODE = "isocode";
public static final String ATTR_FULL_NAME = "fullname";
public static final String ATTR_NAMESPACE = "namespace";
public static final String ATTR_EXCHANGE_CODE = "exchange-code";
public static final String ATTR_SMALLEST_FRACTION = "smallest-fraction";
public static final String ATTR_LOCAL_SYMBOL = "local-symbol";
/**
* List of commodities parsed from the XML file.
* They will be all added to db at once at the end of the document
*/
private List<Commodity> mCommodities;
private CommoditiesDbAdapter mCommoditiesDbAdapter;
public CommoditiesXmlHandler(SQLiteDatabase db){
if (db == null){
mCommoditiesDbAdapter = GnuCashApplication.getCommoditiesDbAdapter();
} else {
mCommoditiesDbAdapter = new CommoditiesDbAdapter(db);
}
mCommodities = new ArrayList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals(TAG_CURRENCY)) {
String isoCode = attributes.getValue(ATTR_ISO_CODE);
String fullname = attributes.getValue(ATTR_FULL_NAME);
String namespace = attributes.getValue(ATTR_NAMESPACE);
String cusip = attributes.getValue(ATTR_EXCHANGE_CODE);
//TODO: investigate how up-to-date the currency XML list is and use of parts-per-unit vs smallest-fraction.
//some currencies like XAF have smallest fraction 100, but parts-per-unit of 1.
// However java.util.Currency agrees only with the parts-per-unit although we use smallest-fraction in the app
// This could lead to inconsistencies over time
String smallestFraction = attributes.getValue(ATTR_SMALLEST_FRACTION);
String localSymbol = attributes.getValue(ATTR_LOCAL_SYMBOL);
Commodity commodity = new Commodity(fullname, isoCode, Integer.parseInt(smallestFraction));
commodity.setNamespace(Commodity.Namespace.valueOf(namespace));
commodity.setCusip(cusip);
commodity.setLocalSymbol(localSymbol);
mCommodities.add(commodity);
}
}
@Override
public void endDocument() throws SAXException {
mCommoditiesDbAdapter.bulkAddRecords(mCommodities, DatabaseAdapter.UpdateMethod.insert);
}
}
| 3,725 | 41.340909 | 122 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/importer/GncXmlHandler.java
|
/*
* Copyright (c) 2013 - 2015 Ngewi Fet <[email protected]>
* Copyright (c) 2014 - 2015 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.importer;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.BudgetAmountsDbAdapter;
import org.gnucash.android.db.adapter.BudgetsDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.PricesDbAdapter;
import org.gnucash.android.db.adapter.RecurrenceDbAdapter;
import org.gnucash.android.db.adapter.ScheduledActionDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.export.xml.GncXmlHelper;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.BaseModel;
import org.gnucash.android.model.Book;
import org.gnucash.android.model.Budget;
import org.gnucash.android.model.BudgetAmount;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.PeriodType;
import org.gnucash.android.model.Price;
import org.gnucash.android.model.Recurrence;
import org.gnucash.android.model.ScheduledAction;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.model.TransactionType;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.regex.Pattern;
/**
* Handler for parsing the GnuCash XML file.
* The discovered accounts and transactions are automatically added to the database
*
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
*/
public class GncXmlHandler extends DefaultHandler {
/**
* ISO 4217 currency code for "No Currency"
*/
private static final String NO_CURRENCY_CODE = "XXX";
/**
* Tag for logging
*/
private static final String LOG_TAG = "GnuCashAccountImporter";
/*
^ anchor for start of string
# the literal #
( start of group
?: indicate a non-capturing group that doesn't generate back-references
[0-9a-fA-F] hexadecimal digit
{3} three times
) end of group
{2} repeat twice
$ anchor for end of string
*/
/**
* Regular expression for validating color code strings.
* Accepts #rgb and #rrggbb
*/
//TODO: Allow use of #aarrggbb format as well
public static final String ACCOUNT_COLOR_HEX_REGEX = "^#(?:[0-9a-fA-F]{3}){2}$";
/**
* Adapter for saving the imported accounts
*/
AccountsDbAdapter mAccountsDbAdapter;
/**
* StringBuilder for accumulating characters between XML tags
*/
StringBuilder mContent;
/**
* Reference to account which is built when each account tag is parsed in the XML file
*/
Account mAccount;
/**
* All the accounts found in a file to be imported, used for bulk import mode
*/
List<Account> mAccountList;
/**
* List of all the template accounts found
*/
List<Account> mTemplatAccountList;
/**
* Map of the tempate accounts to the template transactions UIDs
*/
Map<String, String> mTemplateAccountToTransactionMap;
/**
* Account map for quick referencing from UID
*/
HashMap<String, Account> mAccountMap;
/**
* ROOT account of the imported book
*/
Account mRootAccount;
/**
* Transaction instance which will be built for each transaction found
*/
Transaction mTransaction;
/**
* All the transaction instances found in a file to be inserted, used in bulk mode
*/
List<Transaction> mTransactionList;
/**
* All the template transactions found during parsing of the XML
*/
List<Transaction> mTemplateTransactions;
/**
* Accumulate attributes of splits found in this object
*/
Split mSplit;
/**
* (Absolute) quantity of the split, which uses split account currency
*/
BigDecimal mQuantity;
/**
* (Absolute) value of the split, which uses transaction currency
*/
BigDecimal mValue;
/**
* price table entry
*/
Price mPrice;
boolean mPriceCommodity;
boolean mPriceCurrency;
List<Price> mPriceList;
/**
* Whether the quantity is negative
*/
boolean mNegativeQuantity;
/**
* The list for all added split for autobalancing
*/
List<Split> mAutoBalanceSplits;
/**
* Ignore certain elements in GnuCash XML file, such as "<gnc:template-transactions>"
*/
String mIgnoreElement = null;
/**
* {@link ScheduledAction} instance for each scheduled action parsed
*/
ScheduledAction mScheduledAction;
/**
* List of scheduled actions to be bulk inserted
*/
List<ScheduledAction> mScheduledActionsList;
/**
* List of budgets which have been parsed from XML
*/
List<Budget> mBudgetList;
Budget mBudget;
Recurrence mRecurrence;
BudgetAmount mBudgetAmount;
boolean mInColorSlot = false;
boolean mInPlaceHolderSlot = false;
boolean mInFavoriteSlot = false;
boolean mISO4217Currency = false;
boolean mIsDatePosted = false;
boolean mIsDateEntered = false;
boolean mIsNote = false;
boolean mInDefaultTransferAccount = false;
boolean mInExported = false;
boolean mInTemplates = false;
boolean mInSplitAccountSlot = false;
boolean mInCreditNumericSlot = false;
boolean mInDebitNumericSlot = false;
boolean mIsScheduledStart = false;
boolean mIsScheduledEnd = false;
boolean mIsLastRun = false;
boolean mIsRecurrenceStart = false;
boolean mInBudgetSlot = false;
/**
* Saves the attribute of the slot tag
* Used for determining where we are in the budget amounts
*/
String mSlotTagAttribute = null;
String mBudgetAmountAccountUID = null;
/**
* Multiplier for the recurrence period type. e.g. period type of week and multiplier of 2 means bi-weekly
*/
int mRecurrenceMultiplier = 1;
/**
* Flag which says to ignore template transactions until we successfully parse a split amount
* Is updated for each transaction template split parsed
*/
boolean mIgnoreTemplateTransaction = true;
/**
* Flag which notifies the handler to ignore a scheduled action because some error occurred during parsing
*/
boolean mIgnoreScheduledAction = false;
/**
* Used for parsing old backup files where recurrence was saved inside the transaction.
* Newer backup files will not require this
* @deprecated Use the new scheduled action elements instead
*/
@Deprecated
private long mRecurrencePeriod = 0;
private TransactionsDbAdapter mTransactionsDbAdapter;
private ScheduledActionDbAdapter mScheduledActionsDbAdapter;
private CommoditiesDbAdapter mCommoditiesDbAdapter;
private PricesDbAdapter mPricesDbAdapter;
private Map<String, Integer> mCurrencyCount;
private BudgetsDbAdapter mBudgetsDbAdapter;
private Book mBook;
private SQLiteDatabase mainDb;
/**
* Creates a handler for handling XML stream events when parsing the XML backup file
*/
public GncXmlHandler() {
init();
}
/**
* Initialize the GnuCash XML handler
*/
private void init() {
mBook = new Book();
DatabaseHelper databaseHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), mBook.getUID());
mainDb = databaseHelper.getWritableDatabase();
mTransactionsDbAdapter = new TransactionsDbAdapter(mainDb, new SplitsDbAdapter(mainDb));
mAccountsDbAdapter = new AccountsDbAdapter(mainDb, mTransactionsDbAdapter);
RecurrenceDbAdapter recurrenceDbAdapter = new RecurrenceDbAdapter(mainDb);
mScheduledActionsDbAdapter = new ScheduledActionDbAdapter(mainDb, recurrenceDbAdapter);
mCommoditiesDbAdapter = new CommoditiesDbAdapter(mainDb);
mPricesDbAdapter = new PricesDbAdapter(mainDb);
mBudgetsDbAdapter = new BudgetsDbAdapter(mainDb, new BudgetAmountsDbAdapter(mainDb), recurrenceDbAdapter);
mContent = new StringBuilder();
mAccountList = new ArrayList<>();
mAccountMap = new HashMap<>();
mTransactionList = new ArrayList<>();
mScheduledActionsList = new ArrayList<>();
mBudgetList = new ArrayList<>();
mTemplatAccountList = new ArrayList<>();
mTemplateTransactions = new ArrayList<>();
mTemplateAccountToTransactionMap = new HashMap<>();
mAutoBalanceSplits = new ArrayList<>();
mPriceList = new ArrayList<>();
mCurrencyCount = new HashMap<>();
}
@Override
public void startElement(String uri, String localName,
String qualifiedName, Attributes attributes) throws SAXException {
switch (qualifiedName){
case GncXmlHelper.TAG_ACCOUNT:
mAccount = new Account(""); // dummy name, will be replaced when we find name tag
mISO4217Currency = false;
break;
case GncXmlHelper.TAG_TRANSACTION:
mTransaction = new Transaction(""); // dummy name will be replaced
mTransaction.setExported(true); // default to exported when import transactions
mISO4217Currency = false;
break;
case GncXmlHelper.TAG_TRN_SPLIT:
mSplit = new Split(Money.getZeroInstance(), "");
break;
case GncXmlHelper.TAG_DATE_POSTED:
mIsDatePosted = true;
break;
case GncXmlHelper.TAG_DATE_ENTERED:
mIsDateEntered = true;
break;
case GncXmlHelper.TAG_TEMPLATE_TRANSACTIONS:
mInTemplates = true;
break;
case GncXmlHelper.TAG_SCHEDULED_ACTION:
//default to transaction type, will be changed during parsing
mScheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION);
break;
case GncXmlHelper.TAG_SX_START:
mIsScheduledStart = true;
break;
case GncXmlHelper.TAG_SX_END:
mIsScheduledEnd = true;
break;
case GncXmlHelper.TAG_SX_LAST:
mIsLastRun = true;
break;
case GncXmlHelper.TAG_RX_START:
mIsRecurrenceStart = true;
break;
case GncXmlHelper.TAG_PRICE:
mPrice = new Price();
break;
case GncXmlHelper.TAG_PRICE_CURRENCY:
mPriceCurrency = true;
mPriceCommodity = false;
mISO4217Currency = false;
break;
case GncXmlHelper.TAG_PRICE_COMMODITY:
mPriceCurrency = false;
mPriceCommodity = true;
mISO4217Currency = false;
break;
case GncXmlHelper.TAG_BUDGET:
mBudget = new Budget();
break;
case GncXmlHelper.TAG_GNC_RECURRENCE:
case GncXmlHelper.TAG_BUDGET_RECURRENCE:
mRecurrenceMultiplier = 1;
mRecurrence = new Recurrence(PeriodType.MONTH);
break;
case GncXmlHelper.TAG_BUDGET_SLOTS:
mInBudgetSlot = true;
break;
case GncXmlHelper.TAG_SLOT:
if (mInBudgetSlot){
mBudgetAmount = new BudgetAmount(mBudget.getUID(), mBudgetAmountAccountUID);
}
break;
case GncXmlHelper.TAG_SLOT_VALUE:
mSlotTagAttribute = attributes.getValue(GncXmlHelper.ATTR_KEY_TYPE);
break;
}
}
@Override
public void endElement(String uri, String localName, String qualifiedName) throws SAXException {
// FIXME: 22.10.2015 First parse the number of accounts/transactions and use the numer to init the array lists
String characterString = mContent.toString().trim();
if (mIgnoreElement != null) {
// Ignore everything inside
if (qualifiedName.equals(mIgnoreElement)) {
mIgnoreElement = null;
}
mContent.setLength(0);
return;
}
switch (qualifiedName) {
case GncXmlHelper.TAG_ACCT_NAME:
mAccount.setName(characterString);
mAccount.setFullName(characterString);
break;
case GncXmlHelper.TAG_ACCT_ID:
mAccount.setUID(characterString);
break;
case GncXmlHelper.TAG_ACCT_TYPE:
AccountType accountType = AccountType.valueOf(characterString);
mAccount.setAccountType(accountType);
mAccount.setHidden(accountType == AccountType.ROOT); //flag root account as hidden
break;
case GncXmlHelper.TAG_COMMODITY_SPACE:
if (characterString.equals("ISO4217") || characterString.equals("CURRENCY") ) {
mISO4217Currency = true;
} else {
// price of non-ISO4217 commodities cannot be handled
mPrice = null;
}
break;
case GncXmlHelper.TAG_COMMODITY_ID:
String currencyCode = mISO4217Currency ? characterString : NO_CURRENCY_CODE;
Commodity commodity = mCommoditiesDbAdapter.getCommodity(currencyCode);
if (mAccount != null) {
if (commodity != null) {
mAccount.setCommodity(commodity);
} else {
throw new SAXException("Commodity with '" + currencyCode
+ "' currency code not found in the database");
}
if (mCurrencyCount.containsKey(currencyCode)) {
mCurrencyCount.put(currencyCode, mCurrencyCount.get(currencyCode) + 1);
} else {
mCurrencyCount.put(currencyCode, 1);
}
}
if (mTransaction != null) {
mTransaction.setCommodity(commodity);
}
if (mPrice != null) {
if (mPriceCommodity) {
mPrice.setCommodityUID(mCommoditiesDbAdapter.getCommodityUID(currencyCode));
mPriceCommodity = false;
}
if (mPriceCurrency) {
mPrice.setCurrencyUID(mCommoditiesDbAdapter.getCommodityUID(currencyCode));
mPriceCurrency = false;
}
}
break;
case GncXmlHelper.TAG_ACCT_DESCRIPTION:
mAccount.setDescription(characterString);
break;
case GncXmlHelper.TAG_PARENT_UID:
mAccount.setParentUID(characterString);
break;
case GncXmlHelper.TAG_ACCOUNT:
if (!mInTemplates) { //we ignore template accounts, we have no use for them. FIXME someday and import the templates too
mAccountList.add(mAccount);
mAccountMap.put(mAccount.getUID(), mAccount);
// check ROOT account
if (mAccount.getAccountType() == AccountType.ROOT) {
if (mRootAccount == null) {
mRootAccount = mAccount;
} else {
throw new SAXException("Multiple ROOT accounts exist in book");
}
}
// prepare for next input
mAccount = null;
//reset ISO 4217 flag for next account
mISO4217Currency = false;
}
break;
case GncXmlHelper.TAG_SLOT:
break;
case GncXmlHelper.TAG_SLOT_KEY:
switch (characterString) {
case GncXmlHelper.KEY_PLACEHOLDER:
mInPlaceHolderSlot = true;
break;
case GncXmlHelper.KEY_COLOR:
mInColorSlot = true;
break;
case GncXmlHelper.KEY_FAVORITE:
mInFavoriteSlot = true;
break;
case GncXmlHelper.KEY_NOTES:
mIsNote = true;
break;
case GncXmlHelper.KEY_DEFAULT_TRANSFER_ACCOUNT:
mInDefaultTransferAccount = true;
break;
case GncXmlHelper.KEY_EXPORTED:
mInExported = true;
break;
case GncXmlHelper.KEY_SPLIT_ACCOUNT_SLOT:
mInSplitAccountSlot = true;
break;
case GncXmlHelper.KEY_CREDIT_NUMERIC:
mInCreditNumericSlot = true;
break;
case GncXmlHelper.KEY_DEBIT_NUMERIC:
mInDebitNumericSlot = true;
break;
}
if (mInBudgetSlot && mBudgetAmountAccountUID == null){
mBudgetAmountAccountUID = characterString;
mBudgetAmount.setAccountUID(characterString);
} else if (mInBudgetSlot){
mBudgetAmount.setPeriodNum(Long.parseLong(characterString));
}
break;
case GncXmlHelper.TAG_SLOT_VALUE:
if (mInPlaceHolderSlot) {
//Log.v(LOG_TAG, "Setting account placeholder flag");
mAccount.setPlaceHolderFlag(Boolean.parseBoolean(characterString));
mInPlaceHolderSlot = false;
} else if (mInColorSlot) {
//Log.d(LOG_TAG, "Parsing color code: " + characterString);
String color = characterString.trim();
//Gnucash exports the account color in format #rrrgggbbb, but we need only #rrggbb.
//so we trim the last digit in each block, doesn't affect the color much
if (!color.equals("Not Set")) {
// avoid known exception, printStackTrace is very time consuming
if (!Pattern.matches(ACCOUNT_COLOR_HEX_REGEX, color))
color = "#" + color.replaceAll(".(.)?", "$1").replace("null", "");
try {
if (mAccount != null)
mAccount.setColor(color);
} catch (IllegalArgumentException ex) {
//sometimes the color entry in the account file is "Not set" instead of just blank. So catch!
Log.e(LOG_TAG, "Invalid color code '" + color + "' for account " + mAccount.getName());
Crashlytics.logException(ex);
}
}
mInColorSlot = false;
} else if (mInFavoriteSlot) {
mAccount.setFavorite(Boolean.parseBoolean(characterString));
mInFavoriteSlot = false;
} else if (mIsNote) {
if (mTransaction != null) {
mTransaction.setNote(characterString);
mIsNote = false;
}
} else if (mInDefaultTransferAccount) {
mAccount.setDefaultTransferAccountUID(characterString);
mInDefaultTransferAccount = false;
} else if (mInExported) {
if (mTransaction != null) {
mTransaction.setExported(Boolean.parseBoolean(characterString));
mInExported = false;
}
} else if (mInTemplates && mInSplitAccountSlot) {
mSplit.setAccountUID(characterString);
mInSplitAccountSlot = false;
} else if (mInTemplates && mInCreditNumericSlot) {
handleEndOfTemplateNumericSlot(characterString, TransactionType.CREDIT);
} else if (mInTemplates && mInDebitNumericSlot) {
handleEndOfTemplateNumericSlot(characterString, TransactionType.DEBIT);
} else if (mInBudgetSlot){
if (mSlotTagAttribute.equals(GncXmlHelper.ATTR_VALUE_NUMERIC)) {
try {
BigDecimal bigDecimal = GncXmlHelper.parseSplitAmount(characterString);
//currency doesn't matter since we don't persist it in the budgets table
mBudgetAmount.setAmount(new Money(bigDecimal, Commodity.DEFAULT_COMMODITY));
} catch (ParseException e) {
mBudgetAmount.setAmount(Money.getZeroInstance()); //just put zero, in case it was a formula we couldnt parse
e.printStackTrace();
} finally {
mBudget.addBudgetAmount(mBudgetAmount);
}
mSlotTagAttribute = GncXmlHelper.ATTR_VALUE_FRAME;
} else {
mBudgetAmountAccountUID = null;
}
}
break;
case GncXmlHelper.TAG_BUDGET_SLOTS:
mInBudgetSlot = false;
break;
//================ PROCESSING OF TRANSACTION TAGS =====================================
case GncXmlHelper.TAG_TRX_ID:
mTransaction.setUID(characterString);
break;
case GncXmlHelper.TAG_TRN_DESCRIPTION:
mTransaction.setDescription(characterString);
break;
case GncXmlHelper.TAG_TS_DATE:
try {
if (mIsDatePosted && mTransaction != null) {
mTransaction.setTime(GncXmlHelper.parseDate(characterString));
mIsDatePosted = false;
}
if (mIsDateEntered && mTransaction != null) {
Timestamp timestamp = new Timestamp(GncXmlHelper.parseDate(characterString));
mTransaction.setCreatedTimestamp(timestamp);
mIsDateEntered = false;
}
if (mPrice != null) {
mPrice.setDate(new Timestamp(GncXmlHelper.parseDate(characterString)));
}
} catch (ParseException e) {
Crashlytics.logException(e);
String message = "Unable to parse transaction time - " + characterString;
Log.e(LOG_TAG, message + "\n" + e.getMessage());
Crashlytics.log(message);
throw new SAXException(message, e);
}
break;
case GncXmlHelper.TAG_RECURRENCE_PERIOD: //for parsing of old backup files
mRecurrencePeriod = Long.parseLong(characterString);
mTransaction.setTemplate(mRecurrencePeriod > 0);
break;
case GncXmlHelper.TAG_SPLIT_ID:
mSplit.setUID(characterString);
break;
case GncXmlHelper.TAG_SPLIT_MEMO:
mSplit.setMemo(characterString);
break;
case GncXmlHelper.TAG_SPLIT_VALUE:
try {
// The value and quantity can have different sign for custom currency(stock).
// Use the sign of value for split, as it would not be custom currency
String q = characterString;
if (q.charAt(0) == '-') {
mNegativeQuantity = true;
q = q.substring(1);
} else {
mNegativeQuantity = false;
}
mValue = GncXmlHelper.parseSplitAmount(characterString).abs(); // use sign from quantity
} catch (ParseException e) {
String msg = "Error parsing split quantity - " + characterString;
Crashlytics.log(msg);
Crashlytics.logException(e);
throw new SAXException(msg, e);
}
break;
case GncXmlHelper.TAG_SPLIT_QUANTITY:
// delay the assignment of currency when the split account is seen
try {
mQuantity = GncXmlHelper.parseSplitAmount(characterString).abs();
} catch (ParseException e) {
String msg = "Error parsing split quantity - " + characterString;
Crashlytics.log(msg);
Crashlytics.logException(e);
throw new SAXException(msg, e);
}
break;
case GncXmlHelper.TAG_SPLIT_ACCOUNT:
if (!mInTemplates) {
//this is intentional: GnuCash XML formats split amounts, credits are negative, debits are positive.
mSplit.setType(mNegativeQuantity ? TransactionType.CREDIT : TransactionType.DEBIT);
//the split amount uses the account currency
mSplit.setQuantity(new Money(mQuantity, getCommodityForAccount(characterString)));
//the split value uses the transaction currency
mSplit.setValue(new Money(mValue, mTransaction.getCommodity()));
mSplit.setAccountUID(characterString);
} else {
if (!mIgnoreTemplateTransaction)
mTemplateAccountToTransactionMap.put(characterString, mTransaction.getUID());
}
break;
//todo: import split reconciled state and date
case GncXmlHelper.TAG_TRN_SPLIT:
mTransaction.addSplit(mSplit);
break;
case GncXmlHelper.TAG_TRANSACTION:
mTransaction.setTemplate(mInTemplates);
Split imbSplit = mTransaction.createAutoBalanceSplit();
if (imbSplit != null) {
mAutoBalanceSplits.add(imbSplit);
}
if (mInTemplates){
if (!mIgnoreTemplateTransaction)
mTemplateTransactions.add(mTransaction);
} else {
mTransactionList.add(mTransaction);
}
if (mRecurrencePeriod > 0) { //if we find an old format recurrence period, parse it
mTransaction.setTemplate(true);
ScheduledAction scheduledAction = ScheduledAction.parseScheduledAction(mTransaction, mRecurrencePeriod);
mScheduledActionsList.add(scheduledAction);
}
mRecurrencePeriod = 0;
mIgnoreTemplateTransaction = true;
mTransaction = null;
break;
case GncXmlHelper.TAG_TEMPLATE_TRANSACTIONS:
mInTemplates = false;
break;
// ========================= PROCESSING SCHEDULED ACTIONS ==================================
case GncXmlHelper.TAG_SX_ID:
mScheduledAction.setUID(characterString);
break;
case GncXmlHelper.TAG_SX_NAME:
if (characterString.equals(ScheduledAction.ActionType.BACKUP.name()))
mScheduledAction.setActionType(ScheduledAction.ActionType.BACKUP);
else
mScheduledAction.setActionType(ScheduledAction.ActionType.TRANSACTION);
break;
case GncXmlHelper.TAG_SX_ENABLED:
mScheduledAction.setEnabled(characterString.equals("y"));
break;
case GncXmlHelper.TAG_SX_AUTO_CREATE:
mScheduledAction.setAutoCreate(characterString.equals("y"));
break;
//todo: export auto_notify, advance_create, advance_notify
case GncXmlHelper.TAG_SX_NUM_OCCUR:
mScheduledAction.setTotalPlannedExecutionCount(Integer.parseInt(characterString));
break;
case GncXmlHelper.TAG_RX_MULT:
mRecurrenceMultiplier = Integer.parseInt(characterString);
break;
case GncXmlHelper.TAG_RX_PERIOD_TYPE:
try {
PeriodType periodType = PeriodType.valueOf(characterString.toUpperCase());
mRecurrence.setPeriodType(periodType);
mRecurrence.setMultiplier(mRecurrenceMultiplier);
} catch (IllegalArgumentException ex){ //the period type constant is not supported
String msg = "Unsupported period constant: " + characterString;
Log.e(LOG_TAG, msg);
Crashlytics.logException(ex);
mIgnoreScheduledAction = true;
}
break;
case GncXmlHelper.TAG_GDATE:
try {
long date = GncXmlHelper.DATE_FORMATTER.parse(characterString).getTime();
if (mIsScheduledStart && mScheduledAction != null) {
mScheduledAction.setCreatedTimestamp(new Timestamp(date));
mIsScheduledStart = false;
}
if (mIsScheduledEnd && mScheduledAction != null) {
mScheduledAction.setEndTime(date);
mIsScheduledEnd = false;
}
if (mIsLastRun && mScheduledAction != null) {
mScheduledAction.setLastRun(date);
mIsLastRun = false;
}
if (mIsRecurrenceStart && mScheduledAction != null){
mRecurrence.setPeriodStart(new Timestamp(date));
mIsRecurrenceStart = false;
}
} catch (ParseException e) {
String msg = "Error parsing scheduled action date " + characterString;
Log.e(LOG_TAG, msg + e.getMessage());
Crashlytics.log(msg);
Crashlytics.logException(e);
throw new SAXException(msg, e);
}
break;
case GncXmlHelper.TAG_SX_TEMPL_ACCOUNT:
if (mScheduledAction.getActionType() == ScheduledAction.ActionType.TRANSACTION) {
mScheduledAction.setActionUID(mTemplateAccountToTransactionMap.get(characterString));
} else {
mScheduledAction.setActionUID(BaseModel.generateUID());
}
break;
case GncXmlHelper.TAG_GNC_RECURRENCE:
if (mScheduledAction != null){
mScheduledAction.setRecurrence(mRecurrence);
}
break;
case GncXmlHelper.TAG_SCHEDULED_ACTION:
if (mScheduledAction.getActionUID() != null && !mIgnoreScheduledAction) {
if (mScheduledAction.getRecurrence().getPeriodType() == PeriodType.WEEK) {
// TODO: implement parsing of by days for scheduled actions
setMinimalScheduledActionByDays();
}
mScheduledActionsList.add(mScheduledAction);
int count = generateMissedScheduledTransactions(mScheduledAction);
Log.i(LOG_TAG, String.format("Generated %d transactions from scheduled action", count));
}
mIgnoreScheduledAction = false;
break;
// price table
case GncXmlHelper.TAG_PRICE_ID:
mPrice.setUID(characterString);
break;
case GncXmlHelper.TAG_PRICE_SOURCE:
if (mPrice != null) {
mPrice.setSource(characterString);
}
break;
case GncXmlHelper.TAG_PRICE_VALUE:
if (mPrice != null) {
String[] parts = characterString.split("/");
if (parts.length != 2) {
String message = "Illegal price - " + characterString;
Log.e(LOG_TAG, message);
Crashlytics.log(message);
throw new SAXException(message);
} else {
mPrice.setValueNum(Long.valueOf(parts[0]));
mPrice.setValueDenom(Long.valueOf(parts[1]));
Log.d(getClass().getName(), "price " + characterString +
" .. " + mPrice.getValueNum() + "/" + mPrice.getValueDenom());
}
}
break;
case GncXmlHelper.TAG_PRICE_TYPE:
if (mPrice != null) {
mPrice.setType(characterString);
}
break;
case GncXmlHelper.TAG_PRICE:
if (mPrice != null) {
mPriceList.add(mPrice);
mPrice = null;
}
break;
case GncXmlHelper.TAG_BUDGET:
if (mBudget.getBudgetAmounts().size() > 0) //ignore if no budget amounts exist for the budget
mBudgetList.add(mBudget);
break;
case GncXmlHelper.TAG_BUDGET_NAME:
mBudget.setName(characterString);
break;
case GncXmlHelper.TAG_BUDGET_DESCRIPTION:
mBudget.setDescription(characterString);
break;
case GncXmlHelper.TAG_BUDGET_NUM_PERIODS:
mBudget.setNumberOfPeriods(Long.parseLong(characterString));
break;
case GncXmlHelper.TAG_BUDGET_RECURRENCE:
mBudget.setRecurrence(mRecurrence);
break;
}
//reset the accumulated characters
mContent.setLength(0);
}
@Override
public void characters(char[] chars, int start, int length) throws SAXException {
mContent.append(chars, start, length);
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
HashMap<String, String> mapFullName = new HashMap<>(mAccountList.size());
HashMap<String, Account> mapImbalanceAccount = new HashMap<>();
// The XML has no ROOT, create one
if (mRootAccount == null) {
mRootAccount = new Account("ROOT");
mRootAccount.setAccountType(AccountType.ROOT);
mAccountList.add(mRootAccount);
mAccountMap.put(mRootAccount.getUID(), mRootAccount);
}
String imbalancePrefix = AccountsDbAdapter.getImbalanceAccountPrefix();
// Add all account without a parent to ROOT, and collect top level imbalance accounts
for(Account account:mAccountList) {
mapFullName.put(account.getUID(), null);
boolean topLevel = false;
if (account.getParentUID() == null && account.getAccountType() != AccountType.ROOT) {
account.setParentUID(mRootAccount.getUID());
topLevel = true;
}
if (topLevel || (mRootAccount.getUID().equals(account.getParentUID()))) {
if (account.getName().startsWith(imbalancePrefix)) {
mapImbalanceAccount.put(account.getName().substring(imbalancePrefix.length()), account);
}
}
}
// Set the account for created balancing splits to correct imbalance accounts
for (Split split: mAutoBalanceSplits) {
// XXX: yes, getAccountUID() returns a currency code in this case (see Transaction.createAutoBalanceSplit())
String currencyCode = split.getAccountUID();
Account imbAccount = mapImbalanceAccount.get(currencyCode);
if (imbAccount == null) {
imbAccount = new Account(imbalancePrefix + currencyCode, mCommoditiesDbAdapter.getCommodity(currencyCode));
imbAccount.setParentUID(mRootAccount.getUID());
imbAccount.setAccountType(AccountType.BANK);
mapImbalanceAccount.put(currencyCode, imbAccount);
mAccountList.add(imbAccount);
}
split.setAccountUID(imbAccount.getUID());
}
java.util.Stack<Account> stack = new Stack<>();
for (Account account:mAccountList){
if (mapFullName.get(account.getUID()) != null) {
continue;
}
stack.push(account);
String parentAccountFullName;
while (!stack.isEmpty()) {
Account acc = stack.peek();
if (acc.getAccountType() == AccountType.ROOT) {
// ROOT_ACCOUNT_FULL_NAME should ensure ROOT always sorts first
mapFullName.put(acc.getUID(), AccountsDbAdapter.ROOT_ACCOUNT_FULL_NAME);
stack.pop();
continue;
}
String parentUID = acc.getParentUID();
Account parentAccount = mAccountMap.get(parentUID);
// ROOT account will be added if not exist, so now anly ROOT
// has an empty parent
if (parentAccount.getAccountType() == AccountType.ROOT) {
// top level account, full name is the same as its name
mapFullName.put(acc.getUID(), acc.getName());
stack.pop();
continue;
}
parentAccountFullName = mapFullName.get(parentUID);
if (parentAccountFullName == null) {
// non-top-level account, parent full name still unknown
stack.push(parentAccount);
continue;
}
mapFullName.put(acc.getUID(), parentAccountFullName +
AccountsDbAdapter.ACCOUNT_NAME_SEPARATOR + acc.getName());
stack.pop();
}
}
for (Account account:mAccountList){
account.setFullName(mapFullName.get(account.getUID()));
}
String mostAppearedCurrency = "";
int mostCurrencyAppearance = 0;
for (Map.Entry<String, Integer> entry : mCurrencyCount.entrySet()) {
if (entry.getValue() > mostCurrencyAppearance) {
mostCurrencyAppearance = entry.getValue();
mostAppearedCurrency = entry.getKey();
}
}
if (mostCurrencyAppearance > 0) {
GnuCashApplication.setDefaultCurrencyCode(mostAppearedCurrency);
}
saveToDatabase();
}
/**
* Saves the imported data to the database
* @return GUID of the newly created book, or null if not successful
*/
private void saveToDatabase() {
BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance();
mBook.setRootAccountUID(mRootAccount.getUID());
mBook.setDisplayName(booksDbAdapter.generateDefaultBookName());
//we on purpose do not set the book active. Only import. Caller should handle activation
long startTime = System.nanoTime();
mAccountsDbAdapter.beginTransaction();
Log.d(getClass().getSimpleName(), "bulk insert starts");
try {
// disable foreign key. The database structure should be ensured by the data inserted.
// it will make insertion much faster.
mAccountsDbAdapter.enableForeignKey(false);
Log.d(getClass().getSimpleName(), "before clean up db");
mAccountsDbAdapter.deleteAllRecords();
Log.d(getClass().getSimpleName(), String.format("deb clean up done %d ns", System.nanoTime()-startTime));
long nAccounts = mAccountsDbAdapter.bulkAddRecords(mAccountList, DatabaseAdapter.UpdateMethod.insert);
Log.d("Handler:", String.format("%d accounts inserted", nAccounts));
//We need to add scheduled actions first because there is a foreign key constraint on transactions
//which are generated from scheduled actions (we do auto-create some transactions during import)
long nSchedActions = mScheduledActionsDbAdapter.bulkAddRecords(mScheduledActionsList, DatabaseAdapter.UpdateMethod.insert);
Log.d("Handler:", String.format("%d scheduled actions inserted", nSchedActions));
long nTempTransactions = mTransactionsDbAdapter.bulkAddRecords(mTemplateTransactions, DatabaseAdapter.UpdateMethod.insert);
Log.d("Handler:", String.format("%d template transactions inserted", nTempTransactions));
long nTransactions = mTransactionsDbAdapter.bulkAddRecords(mTransactionList, DatabaseAdapter.UpdateMethod.insert);
Log.d("Handler:", String.format("%d transactions inserted", nTransactions));
long nPrices = mPricesDbAdapter.bulkAddRecords(mPriceList, DatabaseAdapter.UpdateMethod.insert);
Log.d(getClass().getSimpleName(), String.format("%d prices inserted", nPrices));
//// TODO: 01.06.2016 Re-enable import of Budget stuff when the UI is complete
// long nBudgets = mBudgetsDbAdapter.bulkAddRecords(mBudgetList, DatabaseAdapter.UpdateMethod.insert);
// Log.d(getClass().getSimpleName(), String.format("%d budgets inserted", nBudgets));
long endTime = System.nanoTime();
Log.d(getClass().getSimpleName(), String.format("bulk insert time: %d", endTime - startTime));
//if all of the import went smoothly, then add the book to the book db
booksDbAdapter.addRecord(mBook, DatabaseAdapter.UpdateMethod.insert);
mAccountsDbAdapter.setTransactionSuccessful();
} finally {
mAccountsDbAdapter.enableForeignKey(true);
mAccountsDbAdapter.endTransaction();
mainDb.close(); //close it after import
}
}
/**
* Returns the unique identifier of the just-imported book
* @return GUID of the newly imported book
*/
public @NonNull String getBookUID(){
return mBook.getUID();
}
/**
* Returns the currency for an account which has been parsed (but not yet saved to the db)
* <p>This is used when parsing splits to assign the right currencies to the splits</p>
* @param accountUID GUID of the account
* @return Commodity of the account
*/
private Commodity getCommodityForAccount(String accountUID){
try {
return mAccountMap.get(accountUID).getCommodity();
} catch (Exception e) {
Crashlytics.logException(e);
return Commodity.DEFAULT_COMMODITY;
}
}
/**
* Handles the case when we reach the end of the template numeric slot
* @param characterString Parsed characters containing split amount
*/
private void handleEndOfTemplateNumericSlot(String characterString, TransactionType splitType) {
try {
// HACK: Check for bug #562. If a value has already been set, ignore the one just read
if (mSplit.getValue().equals(
new Money(BigDecimal.ZERO, mSplit.getValue().getCommodity()))) {
BigDecimal amountBigD = GncXmlHelper.parseSplitAmount(characterString);
Money amount = new Money(amountBigD, getCommodityForAccount(mSplit.getAccountUID()));
mSplit.setValue(amount);
mSplit.setType(splitType);
mIgnoreTemplateTransaction = false; //we have successfully parsed an amount
}
} catch (NumberFormatException | ParseException e) {
String msg = "Error parsing template credit split amount " + characterString;
Log.e(LOG_TAG, msg + "\n" + e.getMessage());
Crashlytics.log(msg);
Crashlytics.logException(e);
} finally {
if (splitType == TransactionType.CREDIT)
mInCreditNumericSlot = false;
else
mInDebitNumericSlot = false;
}
}
/**
* Generates the runs of the scheduled action which have been missed since the file was last opened.
* @param scheduledAction Scheduled action for transaction
* @return Number of transaction instances generated
*/
private int generateMissedScheduledTransactions(ScheduledAction scheduledAction){
//if this scheduled action should not be run for any reason, return immediately
if (scheduledAction.getActionType() != ScheduledAction.ActionType.TRANSACTION
|| !scheduledAction.isEnabled() || !scheduledAction.shouldAutoCreate()
|| (scheduledAction.getEndTime() > 0 && scheduledAction.getEndTime() > System.currentTimeMillis())
|| (scheduledAction.getTotalPlannedExecutionCount() > 0 && scheduledAction.getExecutionCount() >= scheduledAction.getTotalPlannedExecutionCount())){
return 0;
}
long lastRuntime = scheduledAction.getStartTime();
if (scheduledAction.getLastRunTime() > 0){
lastRuntime = scheduledAction.getLastRunTime();
}
int generatedTransactionCount = 0;
long period = scheduledAction.getPeriod();
final String actionUID = scheduledAction.getActionUID();
while ((lastRuntime = lastRuntime + period) <= System.currentTimeMillis()){
for (Transaction templateTransaction : mTemplateTransactions) {
if (templateTransaction.getUID().equals(actionUID)){
Transaction transaction = new Transaction(templateTransaction, true);
transaction.setTime(lastRuntime);
transaction.setScheduledActionUID(scheduledAction.getUID());
mTransactionList.add(transaction);
//autobalance splits are generated with the currency of the transactions as the GUID
//so we add them to the mAutoBalanceSplits which will be updated to real GUIDs before saving
List<Split> autoBalanceSplits = transaction.getSplits(transaction.getCurrencyCode());
mAutoBalanceSplits.addAll(autoBalanceSplits);
scheduledAction.setExecutionCount(scheduledAction.getExecutionCount() + 1);
++generatedTransactionCount;
break;
}
}
}
scheduledAction.setLastRun(lastRuntime);
return generatedTransactionCount;
}
/**
* Sets the by days of the scheduled action to the day of the week of the start time.
*
* <p>Until we implement parsing of days of the week for scheduled actions,
* this ensures they are executed at least once per week.</p>
*/
private void setMinimalScheduledActionByDays() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(mScheduledAction.getStartTime()));
mScheduledAction.getRecurrence().setByDays(
Collections.singletonList(calendar.get(Calendar.DAY_OF_WEEK)));
}
}
| 49,457 | 42.4223 | 164 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/importer/GncXmlImporter.java
|
/*
* Copyright (c) 2014 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.importer;
import android.util.Log;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.util.PreferencesHelper;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.zip.GZIPInputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
/**
* Importer for Gnucash XML files and GNCA (GnuCash Android) XML files
*
* @author Ngewi Fet <[email protected]>
*/
public class GncXmlImporter {
/**
* Parse GnuCash XML input and populates the database
* @param gncXmlInputStream InputStream source of the GnuCash XML file
* @return GUID of the book into which the XML was imported
*/
public static String parse(InputStream gncXmlInputStream) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
BufferedInputStream bos;
PushbackInputStream pb = new PushbackInputStream( gncXmlInputStream, 2 ); //we need a pushbackstream to look ahead
byte [] signature = new byte[2];
pb.read( signature ); //read the signature
pb.unread( signature ); //push back the signature to the stream
if( signature[ 0 ] == (byte) 0x1f && signature[ 1 ] == (byte) 0x8b ) //check if matches standard gzip magic number
bos = new BufferedInputStream(new GZIPInputStream(pb));
else
bos = new BufferedInputStream(pb);
//TODO: Set an error handler which can log errors
Log.d(GncXmlImporter.class.getSimpleName(), "Start import");
GncXmlHandler handler = new GncXmlHandler();
xr.setContentHandler(handler);
long startTime = System.nanoTime();
xr.parse(new InputSource(bos));
long endTime = System.nanoTime();
Log.d(GncXmlImporter.class.getSimpleName(), String.format("%d ns spent on importing the file", endTime-startTime));
String bookUID = handler.getBookUID();
PreferencesHelper.setLastExportTime(
TransactionsDbAdapter.getInstance().getTimestampOfLastModification(),
bookUID
);
return bookUID;
}
}
| 3,177 | 37.756098 | 126 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/importer/ImportAsyncTask.java
|
/*
* Copyright (c) 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.importer;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.OpenableColumns;
import android.util.Log;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.R;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.ui.util.TaskDelegate;
import org.gnucash.android.util.BookUtils;
import java.io.InputStream;
/**
* Imports a GnuCash (desktop) account file and displays a progress dialog.
* The AccountsActivity is opened when importing is done.
*/
public class ImportAsyncTask extends AsyncTask<Uri, Void, Boolean> {
private final Activity mContext;
private TaskDelegate mDelegate;
private ProgressDialog mProgressDialog;
private String mImportedBookUID;
public ImportAsyncTask(Activity context){
this.mContext = context;
}
public ImportAsyncTask(Activity context, TaskDelegate delegate){
this.mContext = context;
this.mDelegate = delegate;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle(R.string.title_progress_importing_accounts);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
//these methods must be called after progressDialog.show()
mProgressDialog.setProgressNumberFormat(null);
mProgressDialog.setProgressPercentFormat(null);
}
@Override
protected Boolean doInBackground(Uri... uris) {
try {
InputStream accountInputStream = mContext.getContentResolver().openInputStream(uris[0]);
mImportedBookUID = GncXmlImporter.parse(accountInputStream);
} catch (Exception exception){
Log.e(ImportAsyncTask.class.getName(), "" + exception.getMessage());
Crashlytics.log("Could not open: " + uris[0].toString());
Crashlytics.logException(exception);
exception.printStackTrace();
final String err_msg = exception.getLocalizedMessage();
Crashlytics.log(err_msg);
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext,
mContext.getString(R.string.toast_error_importing_accounts) + "\n" + err_msg,
Toast.LENGTH_LONG).show();
}
});
return false;
}
Cursor cursor = mContext.getContentResolver().query(uris[0], null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
String displayName = cursor.getString(nameIndex);
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseSchema.BookEntry.COLUMN_DISPLAY_NAME, displayName);
contentValues.put(DatabaseSchema.BookEntry.COLUMN_SOURCE_URI, uris[0].toString());
BooksDbAdapter.getInstance().updateRecord(mImportedBookUID, contentValues);
cursor.close();
}
//set the preferences to their default values
mContext.getSharedPreferences(mImportedBookUID, Context.MODE_PRIVATE)
.edit()
.putBoolean(mContext.getString(R.string.key_use_double_entry), true)
.apply();
return true;
}
@Override
protected void onPostExecute(Boolean importSuccess) {
try {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
} catch (IllegalArgumentException ex){
//TODO: This is a hack to catch "View not attached to window" exceptions
//FIXME by moving the creation and display of the progress dialog to the Fragment
} finally {
mProgressDialog = null;
}
int message = importSuccess ? R.string.toast_success_importing_accounts : R.string.toast_error_importing_accounts;
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
if (mImportedBookUID != null)
BookUtils.loadBook(mImportedBookUID);
if (mDelegate != null)
mDelegate.onTaskComplete();
}
}
| 5,336 | 35.554795 | 122 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/Account.java
|
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import android.graphics.Color;
import android.support.annotation.NonNull;
import org.gnucash.android.BuildConfig;
import org.gnucash.android.export.ofx.OfxHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
/**
* An account represents a transaction account in with {@link Transaction}s may be recorded
* Accounts have different types as specified by {@link AccountType} and also a currency with
* which transactions may be recorded in the account
* By default, an account is made an {@link AccountType#CASH} and the default currency is
* the currency of the Locale of the device on which the software is running. US Dollars is used
* if the platform locale cannot be determined.
*
* @author Ngewi Fet <[email protected]>
* @see AccountType
*/
public class Account extends BaseModel {
/**
* The MIME type for accounts in GnucashMobile
* This is used when sending intents from third-party applications
*/
public static final String MIME_TYPE = "vnd.android.cursor.item/vnd." + BuildConfig.APPLICATION_ID + ".account";
/**
* Default color, if not set explicitly through {@link #setColor(String)}.
*/
// TODO: get it from a theme value?
public static final int DEFAULT_COLOR = Color.LTGRAY;
/**
* Accounts types which are used by the OFX standard
*/
public enum OfxAccountType {
CHECKING, SAVINGS, MONEYMRKT, CREDITLINE
}
/**
* Name of this account
*/
private String mName;
/**
* Fully qualified name of this account including the parent hierarchy.
* On instantiation of an account, the full name is set to the name by default
*/
private String mFullName;
/**
* Account description
*/
private String mDescription = "";
/**
* Commodity used by this account
*/
private Commodity mCommodity;
/**
* Type of account
* Defaults to {@link AccountType#CASH}
*/
private AccountType mAccountType = AccountType.CASH;
/**
* List of transactions in this account
*/
private List<Transaction> mTransactionsList = new ArrayList<>();
/**
* Account UID of the parent account. Can be null
*/
private String mParentAccountUID;
/**
* Save UID of a default account for transfers.
* All transactions in this account will by default be transfers to the other account
*/
private String mDefaultTransferAccountUID;
/**
* Flag for placeholder accounts.
* These accounts cannot have transactions
*/
private boolean mIsPlaceholderAccount;
/**
* Account color field in hex format #rrggbb
*/
private int mColor = DEFAULT_COLOR;
/**
* Flag which marks this account as a favorite account
*/
private boolean mIsFavorite;
/**
* Flag which indicates if this account is a hidden account or not
*/
private boolean mIsHidden;
/**
* An extra key for passing the currency code (according ISO 4217) in an intent
*/
public static final String EXTRA_CURRENCY_CODE = "org.gnucash.android.extra.currency_code";
/**
* Extra key for passing the unique ID of the parent account when creating a
* new account using Intents
*/
public static final String EXTRA_PARENT_UID = "org.gnucash.android.extra.parent_uid";
/**
* Constructor
* Creates a new account with the default currency and a generated unique ID
* @param name Name of the account
*/
public Account(String name) {
setName(name);
this.mFullName = mName;
setCommodity(Commodity.DEFAULT_COMMODITY);
}
/**
* Overloaded constructor
* @param name Name of the account
* @param commodity {@link Commodity} to be used by transactions in this account
*/
public Account(String name, @NonNull Commodity commodity) {
setName(name);
this.mFullName = mName;
setCommodity(commodity);
}
/**
* Sets the name of the account
* @param name String name of the account
*/
public void setName(String name) {
this.mName = name.trim();
}
/**
* Returns the name of the account
* @return String containing name of the account
*/
public String getName() {
return mName;
}
/**
* Returns the full name of this account.
* The full name is the full account hierarchy name
* @return Fully qualified name of the account
*/
public String getFullName() {
return mFullName;
}
/**
* Sets the fully qualified name of the account
* @param fullName Fully qualified account name
*/
public void setFullName(String fullName) {
this.mFullName = fullName;
}
/**
* Returns the account description
* @return String with description
*/
public String getDescription() {
return mDescription;
}
/**
* Sets the account description
* @param description Account description
*/
public void setDescription(@NonNull String description) {
this.mDescription = description;
}
/**
* Get the type of account
* @return {@link AccountType} type of account
*/
public AccountType getAccountType() {
return mAccountType;
}
/**
* Sets the type of account
* @param mAccountType Type of account
* @see AccountType
*/
public void setAccountType(AccountType mAccountType) {
this.mAccountType = mAccountType;
}
/**
* Adds a transaction to this account
* @param transaction {@link Transaction} to be added to the account
*/
public void addTransaction(Transaction transaction) {
transaction.setCommodity(mCommodity);
mTransactionsList.add(transaction);
}
/**
* Sets a list of transactions for this account.
* Overrides any previous transactions with those in the list.
* The account UID and currency of the transactions will be set to the unique ID
* and currency of the account respectively
* @param transactionsList List of {@link Transaction}s to be set.
*/
public void setTransactions(List<Transaction> transactionsList) {
this.mTransactionsList = transactionsList;
}
/**
* Returns a list of transactions for this account
* @return Array list of transactions for the account
*/
public List<Transaction> getTransactions() {
return mTransactionsList;
}
/**
* Returns the number of transactions in this account
* @return Number transactions in account
*/
public int getTransactionCount() {
return mTransactionsList.size();
}
/**
* Returns the aggregate of all transactions in this account.
* It takes into account debit and credit amounts, it does not however consider sub-accounts
* @return {@link Money} aggregate amount of all transactions in account.
*/
public Money getBalance() {
Money balance = Money.createZeroInstance(mCommodity.getCurrencyCode());
for (Transaction transaction : mTransactionsList) {
balance = balance.add(transaction.getBalance(getUID()));
}
return balance;
}
/**
* Returns the color of the account.
* @return Color of the account as an int as returned by {@link Color}.
*/
public int getColor() {
return mColor;
}
/**
* Returns the account color as an RGB hex string
* @return Hex color of the account
*/
public String getColorHexString(){
return String.format("#%06X", (0xFFFFFF & mColor));
}
/**
* Sets the color of the account.
* @param color Color as an int as returned by {@link Color}.
* @throws java.lang.IllegalArgumentException if the color is transparent,
* which is not supported.
*/
public void setColor(int color) {
if (Color.alpha(color) < 255)
throw new IllegalArgumentException("Transparent colors are not supported: " + color);
mColor = color;
}
/**
* Sets the color of the account.
* @param colorCode Color code to be set in the format #rrggbb
* @throws java.lang.IllegalArgumentException if the color code is not properly formatted or
* the color is transparent.
*/
//TODO: Allow use of #aarrggbb format as well
public void setColor(@NonNull String colorCode) {
setColor(Color.parseColor(colorCode));
}
/**
* Tests if this account is a favorite account or not
* @return <code>true</code> if account is flagged as favorite, <code>false</code> otherwise
*/
public boolean isFavorite() {
return mIsFavorite;
}
/**
* Toggles the favorite flag on this account on or off
* @param isFavorite <code>true</code> if account should be flagged as favorite, <code>false</code> otherwise
*/
public void setFavorite(boolean isFavorite) {
this.mIsFavorite = isFavorite;
}
/**
* Return the commodity for this account
*/
@NonNull
public Commodity getCommodity() {
return mCommodity;
}
/**
* Sets the commodity of this account
* @param commodity Commodity of the account
*/
public void setCommodity(@NonNull Commodity commodity) {
this.mCommodity = commodity;
//todo: should we also change commodity of transactions? Transactions can have splits from different accounts
}
/**
* Sets the Unique Account Identifier of the parent account
* @param parentUID String Unique ID of parent account
*/
public void setParentUID(String parentUID) {
mParentAccountUID = parentUID;
}
/**
* Returns the Unique Account Identifier of the parent account
* @return String Unique ID of parent account
*/
public String getParentUID() {
return mParentAccountUID;
}
/**
* Returns <code>true</code> if this account is a placeholder account, <code>false</code> otherwise.
* @return <code>true</code> if this account is a placeholder account, <code>false</code> otherwise
*/
public boolean isPlaceholderAccount() {
return mIsPlaceholderAccount;
}
/**
* Returns the hidden property of this account.
* <p>Hidden accounts are not visible in the UI</p>
* @return <code>true</code> if the account is hidden, <code>false</code> otherwise.
*/
public boolean isHidden() {
return mIsHidden;
}
/**
* Toggles the hidden property of the account.
* <p>Hidden accounts are not visible in the UI</p>
* @param hidden boolean specifying is hidden or not
*/
public void setHidden(boolean hidden) {
this.mIsHidden = hidden;
}
/**
* Sets the placeholder flag for this account.
* Placeholder accounts cannot have transactions
* @param isPlaceholder Boolean flag indicating if the account is a placeholder account or not
*/
public void setPlaceHolderFlag(boolean isPlaceholder) {
mIsPlaceholderAccount = isPlaceholder;
}
/**
* Return the unique ID of accounts to which to default transfer transactions to
* @return Unique ID string of default transfer account
*/
public String getDefaultTransferAccountUID() {
return mDefaultTransferAccountUID;
}
/**
* Set the unique ID of account which is the default transfer target
* @param defaultTransferAccountUID Unique ID string of default transfer account
*/
public void setDefaultTransferAccountUID(String defaultTransferAccountUID) {
this.mDefaultTransferAccountUID = defaultTransferAccountUID;
}
/**
* Maps the <code>accountType</code> to the corresponding account type.
* <code>accountType</code> have corresponding values to GnuCash desktop
* @param accountType {@link AccountType} of an account
* @return Corresponding {@link OfxAccountType} for the <code>accountType</code>
* @see AccountType
* @see OfxAccountType
*/
public static OfxAccountType convertToOfxAccountType(AccountType accountType) {
switch (accountType) {
case CREDIT:
case LIABILITY:
return OfxAccountType.CREDITLINE;
case CASH:
case INCOME:
case EXPENSE:
case PAYABLE:
case RECEIVABLE:
return OfxAccountType.CHECKING;
case BANK:
case ASSET:
return OfxAccountType.SAVINGS;
case MUTUAL:
case STOCK:
case EQUITY:
case CURRENCY:
return OfxAccountType.MONEYMRKT;
default:
return OfxAccountType.CHECKING;
}
}
/**
* Converts this account's transactions into XML and adds them to the DOM document
* @param doc XML DOM document for the OFX data
* @param parent Parent node to which to add this account's transactions in XML
* @param exportStartTime Time from which to export transactions which are created/modified after
*/
public void toOfx(Document doc, Element parent, Timestamp exportStartTime) {
Element currency = doc.createElement(OfxHelper.TAG_CURRENCY_DEF);
currency.appendChild(doc.createTextNode(mCommodity.getCurrencyCode()));
//================= BEGIN BANK ACCOUNT INFO (BANKACCTFROM) =================================
Element bankId = doc.createElement(OfxHelper.TAG_BANK_ID);
bankId.appendChild(doc.createTextNode(OfxHelper.APP_ID));
Element acctId = doc.createElement(OfxHelper.TAG_ACCOUNT_ID);
acctId.appendChild(doc.createTextNode(getUID()));
Element accttype = doc.createElement(OfxHelper.TAG_ACCOUNT_TYPE);
String ofxAccountType = convertToOfxAccountType(mAccountType).toString();
accttype.appendChild(doc.createTextNode(ofxAccountType));
Element bankFrom = doc.createElement(OfxHelper.TAG_BANK_ACCOUNT_FROM);
bankFrom.appendChild(bankId);
bankFrom.appendChild(acctId);
bankFrom.appendChild(accttype);
//================= END BANK ACCOUNT INFO ============================================
//================= BEGIN ACCOUNT BALANCE INFO =================================
String balance = getBalance().toPlainString();
String formattedCurrentTimeString = OfxHelper.getFormattedCurrentTime();
Element balanceAmount = doc.createElement(OfxHelper.TAG_BALANCE_AMOUNT);
balanceAmount.appendChild(doc.createTextNode(balance));
Element dtasof = doc.createElement(OfxHelper.TAG_DATE_AS_OF);
dtasof.appendChild(doc.createTextNode(formattedCurrentTimeString));
Element ledgerBalance = doc.createElement(OfxHelper.TAG_LEDGER_BALANCE);
ledgerBalance.appendChild(balanceAmount);
ledgerBalance.appendChild(dtasof);
//================= END ACCOUNT BALANCE INFO =================================
//================= BEGIN TIME PERIOD INFO =================================
Element dtstart = doc.createElement(OfxHelper.TAG_DATE_START);
dtstart.appendChild(doc.createTextNode(formattedCurrentTimeString));
Element dtend = doc.createElement(OfxHelper.TAG_DATE_END);
dtend.appendChild(doc.createTextNode(formattedCurrentTimeString));
//================= END TIME PERIOD INFO =================================
//================= BEGIN TRANSACTIONS LIST =================================
Element bankTransactionsList = doc.createElement(OfxHelper.TAG_BANK_TRANSACTION_LIST);
bankTransactionsList.appendChild(dtstart);
bankTransactionsList.appendChild(dtend);
for (Transaction transaction : mTransactionsList) {
if (transaction.getModifiedTimestamp().before(exportStartTime))
continue;
bankTransactionsList.appendChild(transaction.toOFX(doc, getUID()));
}
//================= END TRANSACTIONS LIST =================================
Element statementTransactions = doc.createElement(OfxHelper.TAG_STATEMENT_TRANSACTIONS);
statementTransactions.appendChild(currency);
statementTransactions.appendChild(bankFrom);
statementTransactions.appendChild(bankTransactionsList);
statementTransactions.appendChild(ledgerBalance);
parent.appendChild(statementTransactions);
}
}
| 17,315 | 31.548872 | 117 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/AccountType.java
|
package org.gnucash.android.model;
/**
* The type of account
* This are the different types specified by the OFX format and
* they are currently not used except for exporting
*/
public enum AccountType {
CASH(TransactionType.DEBIT), BANK(TransactionType.DEBIT), CREDIT, ASSET(TransactionType.DEBIT), LIABILITY,
INCOME, EXPENSE(TransactionType.DEBIT), PAYABLE, RECEIVABLE(TransactionType.DEBIT), EQUITY, CURRENCY,
STOCK(TransactionType.DEBIT), MUTUAL(TransactionType.DEBIT), TRADING, ROOT;
/**
* Indicates that this type of normal balance the account type has
* <p>To increase the value of an account with normal balance of credit, one would credit the account.
* To increase the value of an account with normal balance of debit, one would likewise debit the account.</p>
*/
private TransactionType mNormalBalance = TransactionType.CREDIT;
AccountType(TransactionType normalBalance){
this.mNormalBalance = normalBalance;
}
AccountType() {
//nothing to see here, move along
}
public boolean hasDebitNormalBalance(){
return mNormalBalance == TransactionType.DEBIT;
}
/**
* Returns the type of normal balance this account possesses
* @return TransactionType balance of the account type
*/
public TransactionType getNormalBalanceType(){
return mNormalBalance;
}
}
| 1,392 | 33.825 | 114 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/BaseModel.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import org.gnucash.android.util.TimestampHelper;
import java.sql.Timestamp;
import java.util.UUID;
/**
* Abstract class representing the base data model which is persisted to the database.
* All other models should extend this base model.
*/
public abstract class BaseModel {
/**
* Unique identifier of this model instance.
* <p>It is declared private because it is generated only on-demand. Sub-classes should use the accessor methods to read and write this value</p>
* @see #getUID()
* @see #setUID(String)
*/
private String mUID;
protected Timestamp mCreatedTimestamp;
protected Timestamp mModifiedTimestamp;
/**
* Initializes the model attributes.
* <p>A GUID for this model is not generated in the constructor.
* A unique ID will be generated on demand with a call to {@link #getUID()}</p>
*/
public BaseModel(){
mCreatedTimestamp = TimestampHelper.getTimestampFromNow();
mModifiedTimestamp = TimestampHelper.getTimestampFromNow();
}
/**
* Method for generating the Global Unique ID for the model object
* @return Random GUID for the model object
*/
public static String generateUID(){
return UUID.randomUUID().toString().replaceAll("-", "");
}
/**
* Returns a unique string identifier for this model instance
* @return GUID for this model
*/
public String getUID() {
if (mUID == null)
{
mUID = generateUID();
}
return mUID;
}
/**
* Sets the GUID of the model.
* <p>A new GUID can be generated with a call to {@link #generateUID()}</p>
* @param uid String unique ID
*/
public void setUID(String uid) {
this.mUID = uid;
}
/**8
* Returns the timestamp when this model entry was created in the database
* @return Timestamp of creation of model
*/
public Timestamp getCreatedTimestamp() {
return mCreatedTimestamp;
}
/**
* Sets the timestamp when the model was created
* @param createdTimestamp Timestamp of model creation
*/
public void setCreatedTimestamp(Timestamp createdTimestamp) {
this.mCreatedTimestamp = createdTimestamp;
}
/**
* Returns the timestamp when the model record in the database was last modified.
* @return Timestamp of last modification
*/
public Timestamp getModifiedTimestamp() {
return mModifiedTimestamp;
}
/**
* Sets the timestamp when the model was last modified in the database
* <p>Although the database automatically has triggers for entering the timestamp,
* when SQL INSERT OR REPLACE syntax is used, it is possible to override the modified timestamp.
* <br/>In that case, it has to be explicitly set in the SQL statement.</p>
* @param modifiedTimestamp Timestamp of last modification
*/
public void setModifiedTimestamp(Timestamp modifiedTimestamp) {
this.mModifiedTimestamp = modifiedTimestamp;
}
/**
* Two instances are considered equal if their GUID's are the same
* @param o BaseModel instance to compare
* @return {@code true} if both instances are equal, {@code false} otherwise
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BaseModel)) return false;
BaseModel baseModel = (BaseModel) o;
return getUID().equals(baseModel.getUID());
}
@Override
public int hashCode() {
return getUID().hashCode();
}
}
| 4,238 | 30.634328 | 149 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/Book.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import android.net.Uri;
import java.sql.Timestamp;
/**
* Represents a GnuCash book which is made up of accounts and transactions
* @author Ngewi Fet <[email protected]>
*/
public class Book extends BaseModel {
private Uri mSourceUri;
private String mDisplayName;
private String mRootAccountUID;
private String mRootTemplateUID;
private boolean mActive;
private Timestamp mLastSync;
/**
* Default constructor
*/
public Book(){
init();
}
/**
* Create a new book instance
* @param rootAccountUID GUID of root account
*/
public Book(String rootAccountUID){
this.mRootAccountUID = rootAccountUID;
init();
}
/**
* Initialize default values for the book
*/
private void init(){
this.mRootTemplateUID = generateUID();
mLastSync = new Timestamp(System.currentTimeMillis());
}
/**
* Return the root account GUID of this book
* @return GUID of the book root account
*/
public String getRootAccountUID() {
return mRootAccountUID;
}
/**
* Sets the GUID of the root account of this book.
* <p>Each book has only one root account</p>
* @param rootAccountUID GUID of the book root account
*/
public void setRootAccountUID(String rootAccountUID) {
mRootAccountUID = rootAccountUID;
}
/**
* Return GUID of the template root account
* @return GUID of template root acount
*/
public String getRootTemplateUID() {
return mRootTemplateUID;
}
/**
* Set the GUID of the root template account
* @param rootTemplateUID GUID of the root template account
*/
public void setRootTemplateUID(String rootTemplateUID) {
mRootTemplateUID = rootTemplateUID;
}
/**
* Check if this book is the currently active book in the app
* <p>An active book is one whose data is currently displayed in the UI</p>
* @return {@code true} if this is the currently active book, {@code false} otherwise
*/
public boolean isActive() {
return mActive;
}
/**
* Sets this book as the currently active one in the application
* @param active Flag for activating/deactivating the book
*/
public void setActive(boolean active) {
mActive = active;
}
/**
* Return the Uri of the XML file from which the book was imported.
* <p>In API level 16 and above, this is the Uri from the storage access framework which will
* be used for synchronization of the book</p>
* @return Uri of the book source XML
*/
public Uri getSourceUri() {
return mSourceUri;
}
/**
* Set the Uri of the XML source for the book
* <p>This Uri will be used for sync where applicable</p>
* @param uri Uri of the GnuCash XML source file
*/
public void setSourceUri(Uri uri) {
this.mSourceUri = uri;
}
/**
* Returns a name for the book
* <p>This is the user readable string which is used in UI unlike the root account GUID which
* is used for uniquely identifying each book</p>
* @return Name of the book
*/
public String getDisplayName() {
return mDisplayName;
}
/**
* Set a name for the book
* @param name Name of the book
*/
public void setDisplayName(String name) {
this.mDisplayName = name;
}
/**
* Get the time of last synchronization of the book
* @return Timestamp of last synchronization
*/
public Timestamp getLastSync() {
return mLastSync;
}
/**
* Set the time of last synchronization of the book
* @param lastSync Timestamp of last synchronization
*/
public void setLastSync(Timestamp lastSync) {
this.mLastSync = lastSync;
}
}
| 4,507 | 26.487805 | 97 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/Budget.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import android.support.annotation.NonNull;
import android.util.Log;
import org.joda.time.LocalDateTime;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Budgets model
* @author Ngewi Fet <[email protected]>
*/
public class Budget extends BaseModel {
private String mName;
private String mDescription;
private Recurrence mRecurrence;
private List<BudgetAmount> mBudgetAmounts = new ArrayList<>();
private long mNumberOfPeriods = 12; //default to 12 periods per year
/**
* Default constructor
*/
public Budget(){
//nothing to see here, move along
}
/**
* Overloaded constructor.
* Initializes the name and amount of this budget
* @param name String name of the budget
*/
public Budget(@NonNull String name){
this.mName = name;
}
public Budget(@NonNull String name, @NonNull Recurrence recurrence){
this.mName = name;
this.mRecurrence = recurrence;
}
/**
* Returns the name of the budget
* @return name of the budget
*/
public String getName() {
return mName;
}
/**
* Sets the name of the budget
* @param name String name of budget
*/
public void setName(@NonNull String name) {
this.mName = name;
}
/**
* Returns the description of the budget
* @return String description of budget
*/
public String getDescription() {
return mDescription;
}
/**
* Sets the description of the budget
* @param description String description
*/
public void setDescription(String description) {
this.mDescription = description;
}
/**
* Returns the recurrence for this budget
* @return Recurrence object for this budget
*/
public Recurrence getRecurrence() {
return mRecurrence;
}
/**
* Set the recurrence pattern for this budget
* @param recurrence Recurrence object
*/
public void setRecurrence(@NonNull Recurrence recurrence) {
this.mRecurrence = recurrence;
}
/**
* Return list of budget amounts associated with this budget
* @return List of budget amounts
*/
public List<BudgetAmount> getBudgetAmounts() {
return mBudgetAmounts;
}
/**
* Set the list of budget amounts
* @param budgetAmounts List of budget amounts
*/
public void setBudgetAmounts(List<BudgetAmount> budgetAmounts) {
this.mBudgetAmounts = budgetAmounts;
for (BudgetAmount budgetAmount : mBudgetAmounts) {
budgetAmount.setBudgetUID(getUID());
}
}
/**
* Adds a BudgetAmount to this budget
* @param budgetAmount Budget amount
*/
public void addBudgetAmount(BudgetAmount budgetAmount){
budgetAmount.setBudgetUID(getUID());
mBudgetAmounts.add(budgetAmount);
}
/**
* Returns the budget amount for a specific account
* @param accountUID GUID of the account
* @return Money amount of the budget or null if the budget has no amount for the account
*/
public Money getAmount(@NonNull String accountUID){
for (BudgetAmount budgetAmount : mBudgetAmounts) {
if (budgetAmount.getAccountUID().equals(accountUID))
return budgetAmount.getAmount();
}
return null;
}
/**
* Returns the budget amount for a specific account and period
* @param accountUID GUID of the account
* @param periodNum Budgeting period, zero-based index
* @return Money amount or zero if no matching {@link BudgetAmount} is found for the period
*/
public Money getAmount(@NonNull String accountUID, int periodNum){
for (BudgetAmount budgetAmount : mBudgetAmounts) {
if (budgetAmount.getAccountUID().equals(accountUID)
&& (budgetAmount.getPeriodNum() == periodNum || budgetAmount.getPeriodNum() == -1)){
return budgetAmount.getAmount();
}
}
return Money.getZeroInstance();
}
/**
* Returns the sum of all budget amounts in this budget
* <p><b>NOTE:</b> This method ignores budgets of accounts which are in different currencies</p>
* @return Money sum of all amounts
*/
public Money getAmountSum(){
Money sum = null; //we explicitly allow this null instead of a money instance, because this method should never return null for a budget
for (BudgetAmount budgetAmount : mBudgetAmounts) {
if (sum == null){
sum = budgetAmount.getAmount();
} else {
try {
sum = sum.add(budgetAmount.getAmount().abs());
} catch (Money.CurrencyMismatchException ex){
Log.i(getClass().getSimpleName(), "Skip some budget amounts with different currency");
}
}
}
return sum;
}
/**
* Returns the number of periods covered by this budget
* @return Number of periods
*/
public long getNumberOfPeriods() {
return mNumberOfPeriods;
}
/**
* Returns the timestamp of the start of current period of the budget
* @return Start timestamp in milliseconds
*/
public long getStartofCurrentPeriod(){
LocalDateTime localDate = new LocalDateTime();
int interval = mRecurrence.getMultiplier();
switch (mRecurrence.getPeriodType()){
case HOUR:
localDate = localDate.millisOfDay().withMinimumValue().plusHours(interval);
break;
case DAY:
localDate = localDate.millisOfDay().withMinimumValue().plusDays(interval);
break;
case WEEK:
localDate = localDate.dayOfWeek().withMinimumValue().minusDays(interval);
break;
case MONTH:
localDate = localDate.dayOfMonth().withMinimumValue().minusMonths(interval);
break;
case YEAR:
localDate = localDate.dayOfYear().withMinimumValue().minusYears(interval);
break;
}
return localDate.toDate().getTime();
}
/**
* Returns the end timestamp of the current period
* @return End timestamp in milliseconds
*/
public long getEndOfCurrentPeriod(){
LocalDateTime localDate = new LocalDateTime();
int interval = mRecurrence.getMultiplier();
switch (mRecurrence.getPeriodType()){
case HOUR:
localDate = localDate.millisOfDay().withMaximumValue().plusHours(interval);
break;
case DAY:
localDate = localDate.millisOfDay().withMaximumValue().plusDays(interval);
break;
case WEEK:
localDate = localDate.dayOfWeek().withMaximumValue().plusWeeks(interval);
break;
case MONTH:
localDate = localDate.dayOfMonth().withMaximumValue().plusMonths(interval);
break;
case YEAR:
localDate = localDate.dayOfYear().withMaximumValue().plusYears(interval);
break;
}
return localDate.toDate().getTime();
}
public long getStartOfPeriod(int periodNum){
LocalDateTime localDate = new LocalDateTime(mRecurrence.getPeriodStart().getTime());
int interval = mRecurrence.getMultiplier() * periodNum;
switch (mRecurrence.getPeriodType()){
case HOUR:
localDate = localDate.millisOfDay().withMinimumValue().plusHours(interval);
break;
case DAY:
localDate = localDate.millisOfDay().withMinimumValue().plusDays(interval);
break;
case WEEK:
localDate = localDate.dayOfWeek().withMinimumValue().minusDays(interval);
break;
case MONTH:
localDate = localDate.dayOfMonth().withMinimumValue().minusMonths(interval);
break;
case YEAR:
localDate = localDate.dayOfYear().withMinimumValue().minusYears(interval);
break;
}
return localDate.toDate().getTime();
}
/**
* Returns the end timestamp of the period
* @param periodNum Number of the period
* @return End timestamp in milliseconds of the period
*/
public long getEndOfPeriod(int periodNum){
LocalDateTime localDate = new LocalDateTime();
int interval = mRecurrence.getMultiplier() * periodNum;
switch (mRecurrence.getPeriodType()){
case HOUR:
localDate = localDate.plusHours(interval);
break;
case DAY:
localDate = localDate.millisOfDay().withMaximumValue().plusDays(interval);
break;
case WEEK:
localDate = localDate.dayOfWeek().withMaximumValue().plusWeeks(interval);
break;
case MONTH:
localDate = localDate.dayOfMonth().withMaximumValue().plusMonths(interval);
break;
case YEAR:
localDate = localDate.dayOfYear().withMaximumValue().plusYears(interval);
break;
}
return localDate.toDate().getTime();
}
/**
* Sets the number of periods for the budget
* @param numberOfPeriods Number of periods as long
*/
public void setNumberOfPeriods(long numberOfPeriods) {
this.mNumberOfPeriods = numberOfPeriods;
}
/**
* Returns the number of accounts in this budget
* @return Number of budgeted accounts
*/
public int getNumberOfAccounts(){
Set<String> accountSet = new HashSet<>();
for (BudgetAmount budgetAmount : mBudgetAmounts) {
accountSet.add(budgetAmount.getAccountUID());
}
return accountSet.size();
}
/**
* Returns the list of budget amounts where only one BudgetAmount is present if the amount of the budget amount
* is the same for all periods in the budget.
* BudgetAmounts with different amounts per period are still return separately
* <p>
* This method is used during import because GnuCash desktop saves one BudgetAmount per period for the whole budgeting period.
* While this can be easily displayed in a table form on the desktop, it is not feasible in the Android app.
* So we display only one BudgetAmount if it covers all periods in the budgeting period
* </p>
* @return List of {@link BudgetAmount}s
*/
public List<BudgetAmount> getCompactedBudgetAmounts(){
Map<String, List<BigDecimal>> accountAmountMap = new HashMap<>();
for (BudgetAmount budgetAmount : mBudgetAmounts) {
String accountUID = budgetAmount.getAccountUID();
BigDecimal amount = budgetAmount.getAmount().asBigDecimal();
if (accountAmountMap.containsKey(accountUID)){
accountAmountMap.get(accountUID).add(amount);
} else {
List<BigDecimal> amounts = new ArrayList<>();
amounts.add(amount);
accountAmountMap.put(accountUID, amounts);
}
}
List<BudgetAmount> compactBudgetAmounts = new ArrayList<>();
for (Map.Entry<String, List<BigDecimal>> entry : accountAmountMap.entrySet()) {
List<BigDecimal> amounts = entry.getValue();
BigDecimal first = amounts.get(0);
boolean allSame = true;
for (BigDecimal bigDecimal : amounts) {
allSame &= bigDecimal.equals(first);
}
if (allSame){
if (amounts.size() == 1) {
for (BudgetAmount bgtAmount : mBudgetAmounts) {
if (bgtAmount.getAccountUID().equals(entry.getKey())) {
compactBudgetAmounts.add(bgtAmount);
break;
}
}
} else {
BudgetAmount bgtAmount = new BudgetAmount(getUID(), entry.getKey());
bgtAmount.setAmount(new Money(first, Commodity.DEFAULT_COMMODITY));
bgtAmount.setPeriodNum(-1);
compactBudgetAmounts.add(bgtAmount);
}
} else {
//if not all amounts are the same, then just add them as we read them
for (BudgetAmount bgtAmount : mBudgetAmounts) {
if (bgtAmount.getAccountUID().equals(entry.getKey())){
compactBudgetAmounts.add(bgtAmount);
}
}
}
}
return compactBudgetAmounts;
}
/**
* Returns a list of budget amounts where each period has it's own budget amount
* <p>Any budget amounts in the database with a period number of -1 are expanded to individual budget amounts for all periods</p>
* <p>This method is useful with exporting budget amounts to XML</p>
* @return List of expande
*/
public List<BudgetAmount> getExpandedBudgetAmounts(){
List<BudgetAmount> amountsToAdd = new ArrayList<>();
List<BudgetAmount> amountsToRemove = new ArrayList<>();
for (BudgetAmount budgetAmount : mBudgetAmounts) {
if (budgetAmount.getPeriodNum() == -1){
amountsToRemove.add(budgetAmount);
String accountUID = budgetAmount.getAccountUID();
for (int period = 0; period < mNumberOfPeriods; period++) {
BudgetAmount bgtAmount = new BudgetAmount(getUID(), accountUID);
bgtAmount.setAmount(budgetAmount.getAmount());
bgtAmount.setPeriodNum(period);
amountsToAdd.add(bgtAmount);
}
}
}
List<BudgetAmount> expandedBudgetAmounts = new ArrayList<>(mBudgetAmounts);
for (BudgetAmount bgtAmount : amountsToRemove) {
expandedBudgetAmounts.remove(bgtAmount);
}
for (BudgetAmount bgtAmount : amountsToAdd) {
expandedBudgetAmounts.add(bgtAmount);
}
return expandedBudgetAmounts;
}
}
| 15,100 | 35.040573 | 144 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/BudgetAmount.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import android.os.Parcel;
import android.os.Parcelable;
import java.math.BigDecimal;
/**
* Budget amounts for the different accounts.
* The {@link Money} amounts are absolute values
* @see Budget
*/
public class BudgetAmount extends BaseModel implements Parcelable {
private String mBudgetUID;
private String mAccountUID;
/**
* Period number for this budget amount
* A value of -1 indicates that this budget amount applies to all periods
*/
private long mPeriodNum;
private Money mAmount;
/**
* Create a new budget amount
* @param budgetUID GUID of the budget
* @param accountUID GUID of the account
*/
public BudgetAmount(String budgetUID, String accountUID){
this.mBudgetUID = budgetUID;
this.mAccountUID = accountUID;
}
/**
* Creates a new budget amount with the absolute value of {@code amount}
* @param amount Money amount of the budget
* @param accountUID GUID of the account
*/
public BudgetAmount(Money amount, String accountUID){
this.mAmount = amount.abs();
this.mAccountUID = accountUID;
}
public String getBudgetUID() {
return mBudgetUID;
}
public void setBudgetUID(String budgetUID) {
this.mBudgetUID = budgetUID;
}
public String getAccountUID() {
return mAccountUID;
}
public void setAccountUID(String accountUID) {
this.mAccountUID = accountUID;
}
/**
* Returns the period number of this budget amount
* <p>The period is zero-based index, and a value of -1 indicates that this budget amount is applicable to all budgeting periods</p>
* @return Period number
*/
public long getPeriodNum() {
return mPeriodNum;
}
/**
* Set the period number for this budget amount
* <p>A value of -1 indicates that this BudgetAmount is for all periods</p>
* @param periodNum Zero-based period number of the budget amount
*/
public void setPeriodNum(long periodNum) {
this.mPeriodNum = periodNum;
}
/**
* Returns the Money amount of this budget amount
* @return Money amount
*/
public Money getAmount() {
return mAmount;
}
/**
* Sets the amount for the budget
* <p>The absolute value of the amount is used</p>
* @param amount Money amount
*/
public void setAmount(Money amount) {
this.mAmount = amount.abs();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getUID());
dest.writeString(mBudgetUID);
dest.writeString(mAccountUID);
dest.writeString(mAmount.toPlainString());
dest.writeLong(mPeriodNum);
}
public static final Parcelable.Creator<BudgetAmount> CREATOR = new Parcelable.Creator<BudgetAmount>(){
@Override
public BudgetAmount createFromParcel(Parcel source) {
return new BudgetAmount(source);
}
@Override
public BudgetAmount[] newArray(int size) {
return new BudgetAmount[size];
}
};
/**
* Private constructor for creating new BudgetAmounts from a Parcel
* @param source Parcel
*/
private BudgetAmount(Parcel source){
setUID(source.readString());
mBudgetUID = source.readString();
mAccountUID = source.readString();
mAmount = new Money(new BigDecimal(source.readString()), Commodity.DEFAULT_COMMODITY);
mPeriodNum = source.readLong();
}
}
| 4,280 | 27.350993 | 136 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/Commodity.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
/**
* Commodities are the currencies used in the application.
* At the moment only ISO4217 currencies are supported
*/
public class Commodity extends BaseModel {
public enum Namespace { ISO4217 } //Namespace for commodities
private Namespace mNamespace = Namespace.ISO4217;
/**
* Default commodity for device locale
* <p>This value is set when a new application instance is created in {@link GnuCashApplication#onCreate()}.
* The value initialized here is just a placeholder for unit tests</p>
*/
public static Commodity DEFAULT_COMMODITY = new Commodity("US Dollars", "USD", 100); //this value is a stub. Will be overwritten when the app is launched
public static Commodity USD = new Commodity("", "USD", 100);
public static Commodity EUR = new Commodity("", "EUR", 100);
public static Commodity GBP = new Commodity("", "GBP", 100);
public static Commodity CHF = new Commodity("", "CHF", 100);
public static Commodity CAD = new Commodity("", "CAD", 100);
public static Commodity JPY = new Commodity("", "JPY", 1);
public static Commodity AUD = new Commodity("", "AUD", 100);
/**
* This is the currency code for ISO4217 currencies
*/
private String mMnemonic;
private String mFullname;
private String mCusip;
private String mLocalSymbol = "";
private int mSmallestFraction;
private int mQuoteFlag;
/**
* Create a new commodity
* @param fullname Official full name of the currency
* @param mnemonic Official abbreviated designation for the currency
* @param smallestFraction Number of sub-units that the basic commodity can be divided into, as power of 10. e.g. 10^<number_of_fraction_digits>
*/
public Commodity(String fullname, String mnemonic, int smallestFraction){
this.mFullname = fullname;
this.mMnemonic = mnemonic;
setSmallestFraction(smallestFraction);
}
/**
* Returns an instance of commodity for the specified currencyCode
* @param currencyCode ISO 4217 currency code (3-letter)
*/
public static Commodity getInstance(String currencyCode){
switch (currencyCode){ //save time for database trip
case "USD": return USD;
case "EUR": return EUR;
case "GBP": return GBP;
case "CHF": return CHF;
case "JPY": return JPY;
case "AUD": return AUD;
case "CAD": return CAD;
default: return CommoditiesDbAdapter.getInstance().getCommodity(currencyCode);
}
}
public Namespace getNamespace() {
return mNamespace;
}
public void setNamespace(Namespace namespace) {
this.mNamespace = namespace;
}
/**
* Returns the mnemonic, or currency code for ISO4217 currencies
* @return Mnemonic of the commodity
*/
public String getMnemonic() {
return mMnemonic;
}
/**
* Alias for {@link #getMnemonic()}
* @return ISO 4217 code for this commodity
*/
public String getCurrencyCode(){
return getMnemonic();
}
public void setMnemonic(String mMnemonic) {
this.mMnemonic = mMnemonic;
}
public String getFullname() {
return mFullname;
}
public void setFullname(String mFullname) {
this.mFullname = mFullname;
}
public String getCusip() {
return mCusip;
}
public void setCusip(String mCusip) {
this.mCusip = mCusip;
}
public String getLocalSymbol() {
return mLocalSymbol;
}
/**
* Returns the symbol for this commodity.
* <p>Normally this would be the local symbol, but in it's absence, the mnemonic (currency code)
* is returned.</p>
* @return
*/
public String getSymbol(){
if (mLocalSymbol == null || mLocalSymbol.isEmpty()){
return mMnemonic;
}
return mLocalSymbol;
}
public void setLocalSymbol(String localSymbol) {
this.mLocalSymbol = localSymbol;
}
/**
* Returns the smallest fraction supported by the commodity as a power of 10.
* <p>i.e. for commodities with no fractions, 1 is returned, for commodities with 2 fractions, 100 is returned</p>
* @return Smallest fraction as power of 10
*/
public int getSmallestFraction() {
return mSmallestFraction;
}
/**
* Returns the (minimum) number of digits that this commodity supports in its fractional part
* <p>For any unsupported values for the smallest fraction, a default value of 2 is returned.
* Supported values for the smallest fraction are powers of 10 i.e. 1, 10, 100 etc</p>
* @return Number of digits in fraction
* @see #getSmallestFraction()
*/
public int getSmallestFractionDigits(){
if (mSmallestFraction == 0){
return 0;
} else {
return Integer.numberOfTrailingZeros(mSmallestFraction);
}
}
/**
* Sets the smallest fraction for the commodity.
* <p>The fraction is a power of 10. So commodities with 2 fraction digits, have fraction of 10^2 = 100.<br>
* If the parameter is any other value, a default fraction of 100 will be set</p>
* @param smallestFraction Smallest fraction as power of ten
* @throws IllegalArgumentException if the smallest fraction is not a power of 10
*/
public void setSmallestFraction(int smallestFraction) {
this.mSmallestFraction = smallestFraction;
}
public int getQuoteFlag() {
return mQuoteFlag;
}
public void setQuoteFlag(int quoteFlag) {
this.mQuoteFlag = quoteFlag;
}
@Override
/**
* Returns the full name of the currency, or the currency code if there is no full name
* @return String representation of the commodity
*/
public String toString() {
return mFullname == null || mFullname.isEmpty() ? mMnemonic : mFullname;
}
/**
* Overrides {@link BaseModel#equals(Object)} to compare only the currency codes of the commodity.
* <p>Two commodities are considered equal if they have the same currency code</p>
* @param o Commodity instance to compare
* @return {@code true} if both instances have same currency code, {@code false} otherwise
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Commodity commodity = (Commodity) o;
return mMnemonic.equals(commodity.mMnemonic);
}
@Override
public int hashCode() {
return mMnemonic.hashCode();
}
}
| 7,433 | 32.1875 | 157 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/Money.java
|
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import android.support.annotation.NonNull;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
/**
* Money represents a money amount and a corresponding currency.
* Money internally uses {@link BigDecimal} to represent the amounts, which enables it
* to maintain high precision afforded by BigDecimal. Money objects are immutable and
* most operations return new Money objects.
* Money String constructors should not be passed any locale-formatted numbers. Only
* {@link Locale#US} is supported e.g. "2.45" will be parsed as 2.45 meanwhile
* "2,45" will be parsed to 245 although that could be a decimal in {@link Locale#GERMAN}
*
* @author Ngewi Fet<[email protected]>
*
*/
public final class Money implements Comparable<Money>{
/**
* Currency of the account
*/
private Commodity mCommodity;
/**
* Amount value held by this object
*/
private BigDecimal mAmount;
/**
* Rounding mode to be applied when performing operations
* Defaults to {@link RoundingMode#HALF_EVEN}
*/
protected RoundingMode ROUNDING_MODE = RoundingMode.HALF_EVEN;
/**
* Default currency code (according ISO 4217)
* This is typically initialized to the currency of the device default locale,
* otherwise US dollars are used
*/
public static String DEFAULT_CURRENCY_CODE = "USD";
/**
* A zero instance with the currency of the default locale.
* This can be used anywhere where a starting amount is required without having to create a new object
*/
private static Money sDefaultZero;
/**
* Returns a Money instance initialized to the local currency and value 0
* @return Money instance of value 0 in locale currency
*/
public static Money getZeroInstance(){
if (sDefaultZero == null) {
sDefaultZero = new Money(BigDecimal.ZERO, Commodity.DEFAULT_COMMODITY);
}
return sDefaultZero;
}
/**
* Returns the {@link BigDecimal} from the {@code numerator} and {@code denominator}
* @param numerator Number of the fraction
* @param denominator Denominator of the fraction
* @return BigDecimal representation of the number
*/
public static BigDecimal getBigDecimal(long numerator, long denominator) {
int scale;
if (numerator == 0 && denominator == 0) {
denominator = 1;
}
scale = Integer.numberOfTrailingZeros((int)denominator);
return new BigDecimal(BigInteger.valueOf(numerator), scale);
}
/**
* Creates a new money amount
* @param amount Value of the amount
* @param commodity Commodity of the money
*/
public Money(BigDecimal amount, Commodity commodity){
this.mCommodity = commodity;
setAmount(amount); //commodity has to be set first. Because we use it's scale
}
/**
* Overloaded constructor.
* Accepts strings as arguments and parses them to create the Money object
* @param amount Numerical value of the Money
* @param currencyCode Currency code as specified by ISO 4217
*/
public Money(String amount, String currencyCode){
//commodity has to be set first
mCommodity = Commodity.getInstance(currencyCode);
setAmount(new BigDecimal(amount));
}
/**
* Constructs a new money amount given the numerator and denominator of the amount.
* The rounding mode used for the division is {@link BigDecimal#ROUND_HALF_EVEN}
* @param numerator Numerator as integer
* @param denominator Denominator as integer
* @param currencyCode 3-character currency code string
*/
public Money(long numerator, long denominator, String currencyCode){
mAmount = getBigDecimal(numerator, denominator);
setCommodity(currencyCode);
}
/**
* Copy constructor.
* Creates a new Money object which is a clone of <code>money</code>
* @param money Money instance to be cloned
*/
public Money(Money money){
setCommodity(money.getCommodity());
setAmount(money.asBigDecimal());
}
/**
* Creates a new Money instance with 0 amount and the <code>currencyCode</code>
* @param currencyCode Currency to use for this money instance
* @return Money object with value 0 and currency <code>currencyCode</code>
*/
public static Money createZeroInstance(@NonNull String currencyCode){
Commodity commodity = Commodity.getInstance(currencyCode);
return new Money(BigDecimal.ZERO, commodity);
}
/**
* Returns the commodity used by the Money
* @return Instance of commodity
*/
public Commodity getCommodity(){
return mCommodity;
}
/**
* Returns a new <code>Money</code> object the currency specified by <code>currency</code>
* and the same value as this one. No value exchange between the currencies is performed.
* @param commodity {@link Commodity} to assign to new <code>Money</code> object
* @return {@link Money} object with same value as current object, but with new <code>currency</code>
*/
public Money withCurrency(@NonNull Commodity commodity){
return new Money(mAmount, commodity);
}
/**
* Sets the commodity for the Money
* <p>No currency conversion is performed</p>
* @param commodity Commodity instance
*/
private void setCommodity(@NonNull Commodity commodity){
this.mCommodity = commodity;
}
/**
* Sets the commodity for the Money
* @param currencyCode ISO 4217 currency code
*/
private void setCommodity(@NonNull String currencyCode){
mCommodity = Commodity.getInstance(currencyCode);
}
/**
* Returns the GnuCash format numerator for this amount.
* <p>Example: Given an amount 32.50$, the numerator will be 3250</p>
* @return GnuCash numerator for this amount
*/
public long getNumerator() {
try {
return mAmount.scaleByPowerOfTen(getScale()).longValueExact();
} catch (ArithmeticException e) {
String msg = "Currency " + mCommodity.getCurrencyCode() +
" with scale " + getScale() +
" has amount " + mAmount.toString();
Crashlytics.log(msg);
Log.e(getClass().getName(), msg);
throw e;
}
}
/**
* Returns the GnuCash amount format denominator for this amount
* <p>The denominator is 10 raised to the power of number of fractional digits in the currency</p>
* @return GnuCash format denominator
*/
public long getDenominator() {
int scale = getScale();
return BigDecimal.ONE.scaleByPowerOfTen(scale).longValueExact();
}
/**
* Returns the scale (precision) used for the decimal places of this amount.
* <p>The scale used depends on the commodity</p>
* @return Scale of amount as integer
*/
private int getScale() {
int scale = mCommodity.getSmallestFractionDigits();
if (scale < 0) {
scale = mAmount.scale();
}
if (scale < 0) {
scale = 0;
}
return scale;
}
/**
* Returns the amount represented by this Money object
* <p>The scale and rounding mode of the returned value are set to that of this Money object</p>
* @return {@link BigDecimal} valure of amount in object
*/
public BigDecimal asBigDecimal() {
return mAmount.setScale(mCommodity.getSmallestFractionDigits(), RoundingMode.HALF_EVEN);
}
/**
* Returns the amount this object
* @return Double value of the amount in the object
*/
public double asDouble(){
return mAmount.doubleValue();
}
/**
* An alias for {@link #toPlainString()}
* @return Money formatted as a string (excludes the currency)
*/
public String asString(){
return toPlainString();
}
/**
* Returns a string representation of the Money object formatted according to
* the <code>locale</code> and includes the currency symbol.
* The output precision is limited to the number of fractional digits supported by the currency
* @param locale Locale to use when formatting the object
* @return String containing formatted Money representation
*/
public String formattedString(Locale locale){
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);
String symbol;
//if we want to show US Dollars for locales which also use Dollars, for example, Canada
if (mCommodity.equals(Commodity.USD) && !locale.equals(Locale.US)) {
symbol = "US$";
} else {
symbol = mCommodity.getSymbol();
}
DecimalFormatSymbols decimalFormatSymbols = ((DecimalFormat)currencyFormat).getDecimalFormatSymbols();
decimalFormatSymbols.setCurrencySymbol(symbol);
((DecimalFormat)currencyFormat).setDecimalFormatSymbols(decimalFormatSymbols);
currencyFormat.setMinimumFractionDigits(mCommodity.getSmallestFractionDigits());
currencyFormat.setMaximumFractionDigits(mCommodity.getSmallestFractionDigits());
return currencyFormat.format(asDouble());
/*
// old currency formatting code
NumberFormat formatter = NumberFormat.getInstance(locale);
formatter.setMinimumFractionDigits(mCommodity.getSmallestFractionDigits());
formatter.setMaximumFractionDigits(mCommodity.getSmallestFractionDigits());
Currency currency = Currency.getInstance(mCommodity.getCurrencyCode());
return formatter.format(asDouble()) + " " + currency.getSymbol(locale);
*/
}
/**
* Equivalent to calling formattedString(Locale.getDefault())
* @return String formatted Money representation in default locale
*/
public String formattedString(){
return formattedString(Locale.getDefault());
}
/**
* Returns a new Money object whose amount is the negated value of this object amount.
* The original <code>Money</code> object remains unchanged.
* @return Negated <code>Money</code> object
*/
public Money negate(){
return new Money(mAmount.negate(), mCommodity);
}
/**
* Sets the amount value of this <code>Money</code> object
* @param amount {@link BigDecimal} amount to be set
*/
private void setAmount(@NonNull BigDecimal amount) {
mAmount = amount.setScale(mCommodity.getSmallestFractionDigits(), ROUNDING_MODE);
}
/**
* Returns a new <code>Money</code> object whose value is the sum of the values of
* this object and <code>addend</code>.
*
* @param addend Second operand in the addition.
* @return Money object whose value is the sum of this object and <code>money</code>
* @throws CurrencyMismatchException if the <code>Money</code> objects to be added have different Currencies
*/
public Money add(Money addend){
if (!mCommodity.equals(addend.mCommodity))
throw new CurrencyMismatchException();
BigDecimal bigD = mAmount.add(addend.mAmount);
return new Money(bigD, mCommodity);
}
/**
* Returns a new <code>Money</code> object whose value is the difference of the values of
* this object and <code>subtrahend</code>.
* This object is the minuend and the parameter is the subtrahend
* @param subtrahend Second operand in the subtraction.
* @return Money object whose value is the difference of this object and <code>subtrahend</code>
* @throws CurrencyMismatchException if the <code>Money</code> objects to be added have different Currencies
*/
public Money subtract(Money subtrahend){
if (!mCommodity.equals(subtrahend.mCommodity))
throw new CurrencyMismatchException();
BigDecimal bigD = mAmount.subtract(subtrahend.mAmount);
return new Money(bigD, mCommodity);
}
/**
* Returns a new <code>Money</code> object whose value is the quotient of the values of
* this object and <code>divisor</code>.
* This object is the dividend and <code>divisor</code> is the divisor
* <p>This method uses the rounding mode {@link BigDecimal#ROUND_HALF_EVEN}</p>
* @param divisor Second operand in the division.
* @return Money object whose value is the quotient of this object and <code>divisor</code>
* @throws CurrencyMismatchException if the <code>Money</code> objects to be added have different Currencies
*/
public Money divide(Money divisor){
if (!mCommodity.equals(divisor.mCommodity))
throw new CurrencyMismatchException();
BigDecimal bigD = mAmount.divide(divisor.mAmount, mCommodity.getSmallestFractionDigits(), ROUNDING_MODE);
return new Money(bigD, mCommodity);
}
/**
* Returns a new <code>Money</code> object whose value is the quotient of the division of this objects
* value by the factor <code>divisor</code>
* @param divisor Second operand in the addition.
* @return Money object whose value is the quotient of this object and <code>divisor</code>
*/
public Money divide(int divisor){
Money moneyDiv = new Money(new BigDecimal(divisor), mCommodity);
return divide(moneyDiv);
}
/**
* Returns a new <code>Money</code> object whose value is the product of the values of
* this object and <code>money</code>.
*
* @param money Second operand in the multiplication.
* @return Money object whose value is the product of this object and <code>money</code>
* @throws CurrencyMismatchException if the <code>Money</code> objects to be added have different Currencies
*/
public Money multiply(Money money){
if (!mCommodity.equals(money.mCommodity))
throw new CurrencyMismatchException();
BigDecimal bigD = mAmount.multiply(money.mAmount);
return new Money(bigD, mCommodity);
}
/**
* Returns a new <code>Money</code> object whose value is the product of this object
* and the factor <code>multiplier</code>
* <p>The currency of the returned object is the same as the current object</p>
* @param multiplier Factor to multiply the amount by.
* @return Money object whose value is the product of this objects values and <code>multiplier</code>
*/
public Money multiply(int multiplier){
Money moneyFactor = new Money(new BigDecimal(multiplier), mCommodity);
return multiply(moneyFactor);
}
/**
* Returns a new <code>Money</code> object whose value is the product of this object
* and the factor <code>multiplier</code>
* @param multiplier Factor to multiply the amount by.
* @return Money object whose value is the product of this objects values and <code>multiplier</code>
*/
public Money multiply(@NonNull BigDecimal multiplier){
return new Money(mAmount.multiply(multiplier), mCommodity);
}
/**
* Returns true if the amount held by this Money object is negative
* @return <code>true</code> if the amount is negative, <code>false</code> otherwise.
*/
public boolean isNegative(){
return mAmount.compareTo(BigDecimal.ZERO) == -1;
}
/**
* Returns the string representation of the amount (without currency) of the Money object.
*
* <p>This string is not locale-formatted. The decimal operator is a period (.)
* For a locale-formatted version, see the method overload {@link #toLocaleString(Locale)}</p>
* @return String representation of the amount (without currency) of the Money object
*/
public String toPlainString(){
return mAmount.setScale(mCommodity.getSmallestFractionDigits(), ROUNDING_MODE).toPlainString();
}
/**
* Returns a locale-specific representation of the amount of the Money object (excluding the currency)
*
* @return String representation of the amount (without currency) of the Money object
*/
public String toLocaleString(){
return String.format(Locale.getDefault(), "%.2f", asDouble());
}
/**
* Returns the string representation of the Money object (value + currency) formatted according
* to the default locale
* @return String representation of the amount formatted with default locale
*/
@Override
public String toString() {
return formattedString(Locale.getDefault());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (mAmount.hashCode());
result = prime * result + (mCommodity.hashCode());
return result;
}
/** //FIXME: equality failing for money objects
* Two Money objects are only equal if their amount (value) and currencies are equal
* @param obj Object to compare with
* @return <code>true</code> if the objects are equal, <code>false</code> otherwise
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Money other = (Money) obj;
if (!mAmount.equals(other.mAmount))
return false;
if (!mCommodity.equals(other.mCommodity))
return false;
return true;
}
@Override
public int compareTo(@NonNull Money another) {
if (!mCommodity.equals(another.mCommodity))
throw new CurrencyMismatchException();
return mAmount.compareTo(another.mAmount);
}
/**
* Returns a new instance of {@link Money} object with the absolute value of the current object
* @return Money object with absolute value of this instance
*/
public Money abs() {
return new Money(mAmount.abs(), mCommodity);
}
/**
* Checks if the value of this amount is exactly equal to zero.
* @return {@code true} if this money amount is zero, {@code false} otherwise
*/
public boolean isAmountZero() {
return mAmount.compareTo(BigDecimal.ZERO) == 0;
}
public class CurrencyMismatchException extends IllegalArgumentException{
@Override
public String getMessage() {
return "Cannot perform operation on Money instances with different currencies";
}
}
}
| 17,846 | 33.520309 | 109 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/PeriodType.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Represents a type of period which can be associated with a recurring event
* @author Ngewi Fet <[email protected]>
* @see org.gnucash.android.model.ScheduledAction
*/
public enum PeriodType {
HOUR, DAY, WEEK, MONTH, YEAR;
/**
* Returns the frequency description of this period type.
* This is used mostly for generating the recurrence rule.
* @return Frequency description
*/
public String getFrequencyDescription() {
switch (this) {
case HOUR:
return "HOURLY";
case DAY:
return "DAILY";
case WEEK:
return "WEEKLY";
case MONTH:
return "MONTHLY";
case YEAR:
return "YEARLY";
default:
return "";
}
}
/**
* Returns the parts of the recurrence rule which describe the day or month on which to run the
* scheduled transaction. These parts are the BYxxx
* @param startTime Start time of transaction used to determine the start day of execution
* @return String describing the BYxxx parts of the recurrence rule
*/
public String getByParts(long startTime){
String partString = "";
if (this == WEEK){
String dayOfWeek = new SimpleDateFormat("E", Locale.US).format(new Date(startTime));
//our parser only supports two-letter day names
partString = "BYDAY=" + dayOfWeek.substring(0, dayOfWeek.length()-1).toUpperCase();
}
return partString;
}
}
| 2,307 | 31.971429 | 99 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/Price.java
|
package org.gnucash.android.model;
import org.gnucash.android.util.TimestampHelper;
import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Model for commodity prices
*/
public class Price extends BaseModel {
private String mCommodityUID;
private String mCurrencyUID;
private Timestamp mDate;
private String mSource;
private String mType;
private long mValueNum;
private long mValueDenom;
/**
* String indicating that the price was provided by the user
*/
public static final String SOURCE_USER = "user:xfer-dialog";
public Price(){
mDate = TimestampHelper.getTimestampFromNow();
}
/**
* Create new instance with the GUIDs of the commodities
* @param commodityUID GUID of the origin commodity
* @param currencyUID GUID of the target commodity
*/
public Price(String commodityUID, String currencyUID){
this.mCommodityUID = commodityUID;
this.mCurrencyUID = currencyUID;
mDate = TimestampHelper.getTimestampFromNow();
}
/**
* Create new instance with the GUIDs of the commodities and the specified exchange rate.
* @param commodity1UID GUID of the origin commodity
* @param commodity2UID GUID of the target commodity
* @param exchangeRate exchange rate between the commodities
*/
public Price(String commodity1UID, String commodity2UID, BigDecimal exchangeRate) {
this(commodity1UID, commodity2UID);
// Store 0.1234 as 1234/10000
setValueNum(exchangeRate.unscaledValue().longValue());
setValueDenom(BigDecimal.ONE.scaleByPowerOfTen(exchangeRate.scale()).longValue());
}
public String getCommodityUID() {
return mCommodityUID;
}
public void setCommodityUID(String mCommodityUID) {
this.mCommodityUID = mCommodityUID;
}
public String getCurrencyUID() {
return mCurrencyUID;
}
public void setCurrencyUID(String currencyUID) {
this.mCurrencyUID = currencyUID;
}
public Timestamp getDate() {
return mDate;
}
public void setDate(Timestamp date) {
this.mDate = date;
}
public String getSource() {
return mSource;
}
public void setSource(String source) {
this.mSource = source;
}
public String getType() {
return mType;
}
public void setType(String type) {
this.mType = type;
}
public long getValueNum() {
reduce();
return mValueNum;
}
public void setValueNum(long valueNum) {
this.mValueNum = valueNum;
}
public long getValueDenom() {
reduce();
return mValueDenom;
}
public void setValueDenom(long valueDenom) {
this.mValueDenom = valueDenom;
}
private void reduce() {
if (mValueDenom < 0) {
mValueDenom = -mValueDenom;
mValueNum = -mValueNum;
}
if (mValueDenom != 0 && mValueNum != 0) {
long num1 = mValueNum;
if (num1 < 0) {
num1 = -num1;
}
long num2 = mValueDenom;
long commonDivisor = 1;
for(;;) {
long r = num1 % num2;
if (r == 0) {
commonDivisor = num2;
break;
}
num1 = r;
r = num2 % num1;
if (r == 0) {
commonDivisor = num1;
break;
}
num2 = r;
}
mValueNum /= commonDivisor;
mValueDenom /= commonDivisor;
}
}
/**
* Returns the exchange rate as a string formatted with the default locale.
*
* <p>It will have up to 6 decimal places.
*
* <p>Example: "0.123456"
*/
@Override
public String toString() {
BigDecimal numerator = new BigDecimal(mValueNum);
BigDecimal denominator = new BigDecimal(mValueDenom);
DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance();
formatter.setMaximumFractionDigits(6);
return formatter.format(numerator.divide(denominator, MathContext.DECIMAL32));
}
}
| 4,332 | 25.746914 | 93 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/Recurrence.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.ui.util.RecurrenceParser;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.Months;
import org.joda.time.ReadablePeriod;
import org.joda.time.Weeks;
import org.joda.time.Years;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* Model for recurrences in the database
* <p>Basically a wrapper around {@link PeriodType}</p>
*/
public class Recurrence extends BaseModel {
private PeriodType mPeriodType;
/**
* Start time of the recurrence
*/
private Timestamp mPeriodStart;
/**
* End time of this recurrence
* <p>This value is not persisted to the database</p>
*/
private Timestamp mPeriodEnd;
/**
* Days of week on which to run the recurrence
*/
private List<Integer> mByDays = Collections.emptyList();
private int mMultiplier = 1; //multiplier for the period type
public Recurrence(@NonNull PeriodType periodType){
setPeriodType(periodType);
mPeriodStart = new Timestamp(System.currentTimeMillis());
}
/**
* Return the PeriodType for this recurrence
* @return PeriodType for the recurrence
*/
public PeriodType getPeriodType() {
return mPeriodType;
}
/**
* Sets the period type for the recurrence
* @param periodType PeriodType
*/
public void setPeriodType(PeriodType periodType) {
this.mPeriodType = periodType;
}
/**
* Return the start time for this recurrence
* @return Timestamp of start of recurrence
*/
public Timestamp getPeriodStart() {
return mPeriodStart;
}
/**
* Set the start time of this recurrence
* @param periodStart {@link Timestamp} of recurrence
*/
public void setPeriodStart(Timestamp periodStart) {
this.mPeriodStart = periodStart;
}
/**
* Returns an approximate period for this recurrence
* <p>The period is approximate because months do not all have the same number of days,
* but that is assumed</p>
* @return Milliseconds since Epoch representing the period
* @deprecated Do not use in new code. Uses fixed period values for months and years (which have variable units of time)
*/
public long getPeriod(){
long baseMillis = 0;
switch (mPeriodType){
case HOUR:
baseMillis = RecurrenceParser.HOUR_MILLIS;
break;
case DAY:
baseMillis = RecurrenceParser.DAY_MILLIS;
break;
case WEEK:
baseMillis = RecurrenceParser.WEEK_MILLIS;
break;
case MONTH:
baseMillis = RecurrenceParser.MONTH_MILLIS;
break;
case YEAR:
baseMillis = RecurrenceParser.YEAR_MILLIS;
break;
}
return mMultiplier * baseMillis;
}
/**
* Returns the event schedule (start, end and recurrence)
* @return String description of repeat schedule
*/
public String getRepeatString(){
StringBuilder repeatBuilder = new StringBuilder(getFrequencyRepeatString());
Context context = GnuCashApplication.getAppContext();
String dayOfWeek = new SimpleDateFormat("EEEE", GnuCashApplication.getDefaultLocale())
.format(new Date(mPeriodStart.getTime()));
if (mPeriodType == PeriodType.WEEK) {
repeatBuilder.append(" ").
append(context.getString(R.string.repeat_on_weekday, dayOfWeek));
}
if (mPeriodEnd != null){
String endDateString = SimpleDateFormat.getDateInstance().format(new Date(mPeriodEnd.getTime()));
repeatBuilder.append(", ").append(context.getString(R.string.repeat_until_date, endDateString));
}
return repeatBuilder.toString();
}
/**
* Creates an RFC 2445 string which describes this recurring event.
* <p>See http://recurrance.sourceforge.net/</p>
* <p>The output of this method is not meant for human consumption</p>
* @return String describing event
*/
public String getRuleString(){
String separator = ";";
StringBuilder ruleBuilder = new StringBuilder();
// =======================================================================
//This section complies with the formal rules, but the betterpickers library doesn't like/need it
// SimpleDateFormat startDateFormat = new SimpleDateFormat("'TZID'=zzzz':'yyyyMMdd'T'HHmmss", Locale.US);
// ruleBuilder.append("DTSTART;");
// ruleBuilder.append(startDateFormat.format(new Date(mStartDate)));
// ruleBuilder.append("\n");
// ruleBuilder.append("RRULE:");
// ========================================================================
ruleBuilder.append("FREQ=").append(mPeriodType.getFrequencyDescription()).append(separator);
ruleBuilder.append("INTERVAL=").append(mMultiplier).append(separator);
if (getCount() > 0)
ruleBuilder.append("COUNT=").append(getCount()).append(separator);
ruleBuilder.append(mPeriodType.getByParts(mPeriodStart.getTime())).append(separator);
return ruleBuilder.toString();
}
/**
* Return the number of days left in this period
* @return Number of days left in period
*/
public int getDaysLeftInCurrentPeriod(){
LocalDateTime startDate = new LocalDateTime(System.currentTimeMillis());
int interval = mMultiplier - 1;
LocalDateTime endDate = null;
switch (mPeriodType){
case HOUR:
endDate = new LocalDateTime(System.currentTimeMillis()).plusHours(interval);
break;
case DAY:
endDate = new LocalDateTime(System.currentTimeMillis()).plusDays(interval);
break;
case WEEK:
endDate = startDate.dayOfWeek().withMaximumValue().plusWeeks(interval);
break;
case MONTH:
endDate = startDate.dayOfMonth().withMaximumValue().plusMonths(interval);
break;
case YEAR:
endDate = startDate.dayOfYear().withMaximumValue().plusYears(interval);
break;
}
return Days.daysBetween(startDate, endDate).getDays();
}
/**
* Returns the number of periods from the start date of this recurrence until the end of the
* interval multiplier specified in the {@link PeriodType}
* //fixme: Improve the documentation
* @return Number of periods in this recurrence
*/
public int getNumberOfPeriods(int numberOfPeriods) {
LocalDateTime startDate = new LocalDateTime(mPeriodStart.getTime());
LocalDateTime endDate;
int interval = mMultiplier;
//// TODO: 15.08.2016 Why do we add the number of periods. maybe rename method or param
switch (mPeriodType){
case HOUR: //this is not the droid you are looking for
endDate = startDate.plusHours(numberOfPeriods);
return Hours.hoursBetween(startDate, endDate).getHours();
case DAY:
endDate = startDate.plusDays(numberOfPeriods);
return Days.daysBetween(startDate, endDate).getDays();
case WEEK:
endDate = startDate.dayOfWeek().withMaximumValue().plusWeeks(numberOfPeriods);
return Weeks.weeksBetween(startDate, endDate).getWeeks() / interval;
case MONTH:
endDate = startDate.dayOfMonth().withMaximumValue().plusMonths(numberOfPeriods);
return Months.monthsBetween(startDate, endDate).getMonths() / interval;
case YEAR:
endDate = startDate.dayOfYear().withMaximumValue().plusYears(numberOfPeriods);
return Years.yearsBetween(startDate, endDate).getYears() / interval;
}
return 0;
}
/**
* Return the name of the current period
* @return String of current period
*/
public String getTextOfCurrentPeriod(int periodNum){
LocalDate startDate = new LocalDate(mPeriodStart.getTime());
switch (mPeriodType){
case HOUR:
//nothing to see here. Just use default period designation
break;
case DAY:
return startDate.dayOfWeek().getAsText();
case WEEK:
return startDate.weekOfWeekyear().getAsText();
case MONTH:
return startDate.monthOfYear().getAsText();
case YEAR:
return startDate.year().getAsText();
}
return "Period " + periodNum;
}
/**
* Return the days of week on which to run the recurrence.
*
* <p>Days are expressed as defined in {@link java.util.Calendar}.
* For example, Calendar.MONDAY</p>
*
* @return list of days of week on which to run the recurrence.
*/
public @NonNull List<Integer> getByDays(){
return Collections.unmodifiableList(mByDays);
}
/**
* Sets the days on which to run the recurrence.
*
* <p>Days must be expressed as defined in {@link java.util.Calendar}.
* For example, Calendar.MONDAY</p>
*
* @param byDays list of days of week on which to run the recurrence.
*/
public void setByDays(@NonNull List<Integer> byDays){
mByDays = new ArrayList<>(byDays);
}
/**
* Computes the number of occurrences of this recurrences between start and end date
* <p>If there is no end date or the PeriodType is unknown, it returns -1</p>
* @return Number of occurrences, or -1 if there is no end date
*/
public int getCount(){
if (mPeriodEnd == null)
return -1;
int multiple = mMultiplier;
ReadablePeriod jodaPeriod;
switch (mPeriodType){
case HOUR:
jodaPeriod = Hours.hours(multiple);
break;
case DAY:
jodaPeriod = Days.days(multiple);
break;
case WEEK:
jodaPeriod = Weeks.weeks(multiple);
break;
case MONTH:
jodaPeriod = Months.months(multiple);
break;
case YEAR:
jodaPeriod = Years.years(multiple);
break;
default:
jodaPeriod = Months.months(multiple);
}
int count = 0;
LocalDateTime startTime = new LocalDateTime(mPeriodStart.getTime());
while (startTime.toDateTime().getMillis() < mPeriodEnd.getTime()){
++count;
startTime = startTime.plus(jodaPeriod);
}
return count;
/*
//this solution does not use looping, but is not very accurate
int multiplier = mMultiplier;
LocalDateTime startDate = new LocalDateTime(mPeriodStart.getTime());
LocalDateTime endDate = new LocalDateTime(mPeriodEnd.getTime());
switch (mPeriodType){
case DAY:
return Days.daysBetween(startDate, endDate).dividedBy(multiplier).getDays();
case WEEK:
return Weeks.weeksBetween(startDate, endDate).dividedBy(multiplier).getWeeks();
case MONTH:
return Months.monthsBetween(startDate, endDate).dividedBy(multiplier).getMonths();
case YEAR:
return Years.yearsBetween(startDate, endDate).dividedBy(multiplier).getYears();
default:
return -1;
}
*/
}
/**
* Sets the end time of this recurrence by specifying the number of occurences
* @param numberOfOccurences Number of occurences from the start time
*/
public void setPeriodEnd(int numberOfOccurences){
LocalDateTime localDate = new LocalDateTime(mPeriodStart.getTime());
LocalDateTime endDate;
int occurrenceDuration = numberOfOccurences * mMultiplier;
switch (mPeriodType){
case HOUR:
endDate = localDate.plusHours(occurrenceDuration);
break;
case DAY:
endDate = localDate.plusDays(occurrenceDuration);
break;
case WEEK:
endDate = localDate.plusWeeks(occurrenceDuration);
break;
default:
case MONTH:
endDate = localDate.plusMonths(occurrenceDuration);
break;
case YEAR:
endDate = localDate.plusYears(occurrenceDuration);
break;
}
mPeriodEnd = new Timestamp(endDate.toDateTime().getMillis());
}
/**
* Return the end date of the period in milliseconds
* @return End date of the recurrence period
*/
public Timestamp getPeriodEnd(){
return mPeriodEnd;
}
/**
* Set period end date
* @param endTimestamp End time in milliseconds
*/
public void setPeriodEnd(Timestamp endTimestamp){
mPeriodEnd = endTimestamp;
}
/**
* Returns the multiplier for the period type. The default multiplier is 1.
* e.g. bi-weekly actions have period type {@link PeriodType#WEEK} and multiplier 2.
*
* @return Multiplier for the period type
*/
public int getMultiplier(){
return mMultiplier;
}
/**
* Sets the multiplier for the period type.
* e.g. bi-weekly actions have period type {@link PeriodType#WEEK} and multiplier 2.
*
* @param multiplier Multiplier for the period type
*/
public void setMultiplier(int multiplier){
mMultiplier = multiplier;
}
/**
* Returns a localized string describing the period type's frequency.
*
* @return String describing the period type
*/
private String getFrequencyRepeatString(){
Resources res = GnuCashApplication.getAppContext().getResources();
switch (mPeriodType) {
case HOUR:
return res.getQuantityString(R.plurals.label_every_x_hours, mMultiplier, mMultiplier);
case DAY:
return res.getQuantityString(R.plurals.label_every_x_days, mMultiplier, mMultiplier);
case WEEK:
return res.getQuantityString(R.plurals.label_every_x_weeks, mMultiplier, mMultiplier);
case MONTH:
return res.getQuantityString(R.plurals.label_every_x_months, mMultiplier, mMultiplier);
case YEAR:
return res.getQuantityString(R.plurals.label_every_x_years, mMultiplier, mMultiplier);
default:
return "";
}
}
/**
* Returns a new {@link Recurrence} with the {@link PeriodType} specified in the old format.
*
* @param period Period in milliseconds since Epoch (old format to define a period)
* @return Recurrence with the specified period.
*/
public static Recurrence fromLegacyPeriod(long period) {
int result = (int) (period/RecurrenceParser.YEAR_MILLIS);
if (result > 0) {
Recurrence recurrence = new Recurrence(PeriodType.YEAR);
recurrence.setMultiplier(result);
return recurrence;
}
result = (int) (period/RecurrenceParser.MONTH_MILLIS);
if (result > 0) {
Recurrence recurrence = new Recurrence(PeriodType.MONTH);
recurrence.setMultiplier(result);
return recurrence;
}
result = (int) (period/RecurrenceParser.WEEK_MILLIS);
if (result > 0) {
Recurrence recurrence = new Recurrence(PeriodType.WEEK);
recurrence.setMultiplier(result);
return recurrence;
}
result = (int) (period/RecurrenceParser.DAY_MILLIS);
if (result > 0) {
Recurrence recurrence = new Recurrence(PeriodType.DAY);
recurrence.setMultiplier(result);
return recurrence;
}
result = (int) (period/RecurrenceParser.HOUR_MILLIS);
if (result > 0) {
Recurrence recurrence = new Recurrence(PeriodType.HOUR);
recurrence.setMultiplier(result);
return recurrence;
}
return new Recurrence(PeriodType.DAY);
}
}
| 17,429 | 34.571429 | 124 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/ScheduledAction.java
|
/*
* Copyright (c) 2014 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import android.content.Context;
import android.support.annotation.NonNull;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.joda.time.LocalDateTime;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Represents a scheduled event which is stored in the database and run at regular mPeriod
*
* @author Ngewi Fet <[email protected]>
*/
public class ScheduledAction extends BaseModel{
private long mStartDate;
private long mEndDate;
private String mTag;
/**
* Recurrence of this scheduled action
*/
private Recurrence mRecurrence;
/**
* Types of events which can be scheduled
*/
public enum ActionType {TRANSACTION, BACKUP}
/**
* Next scheduled run of Event
*/
private long mLastRun = 0;
/**
* Unique ID of the template from which the recurring event will be executed.
* For example, transaction UID
*/
private String mActionUID;
/**
* Flag indicating if this event is enabled or not
*/
private boolean mIsEnabled;
/**
* Type of event being scheduled
*/
private ActionType mActionType;
/**
* Number of times this event is planned to be executed
*/
private int mTotalFrequency = 0;
/**
* How many times this action has already been executed
*/
private int mExecutionCount = 0;
/**
* Flag for whether the scheduled transaction should be auto-created
*/
private boolean mAutoCreate = true;
private boolean mAutoNotify = false;
private int mAdvanceCreateDays = 0;
private int mAdvanceNotifyDays = 0;
private String mTemplateAccountUID;
public ScheduledAction(ActionType actionType){
mActionType = actionType;
mEndDate = 0;
mIsEnabled = true; //all actions are enabled by default
}
/**
* Returns the type of action to be performed by this scheduled action
* @return ActionType of the scheduled action
*/
public ActionType getActionType() {
return mActionType;
}
/**
* Sets the {@link ActionType}
* @param actionType Type of action
*/
public void setActionType(ActionType actionType) {
this.mActionType = actionType;
}
/**
* Returns the GUID of the action covered by this scheduled action
* @return GUID of action
*/
public String getActionUID() {
return mActionUID;
}
/**
* Sets the GUID of the action being scheduled
* @param actionUID GUID of the action
*/
public void setActionUID(String actionUID) {
this.mActionUID = actionUID;
}
/**
* Returns the timestamp of the last execution of this scheduled action
* <p>This is not necessarily the time when the scheduled action was due, only when it was actually last executed.</p>
* @return Timestamp in milliseconds since Epoch
*/
public long getLastRunTime() {
return mLastRun;
}
/**
* Returns the time when the last schedule in the sequence of planned executions was executed.
* This relies on the number of executions of the scheduled action
* <p>This is different from {@link #getLastRunTime()} which returns the date when the system last
* run the scheduled action.</p>
* @return Time of last schedule, or -1 if the scheduled action has never been run
*/
public long getTimeOfLastSchedule(){
if (mExecutionCount == 0)
return -1;
LocalDateTime startTime = LocalDateTime.fromDateFields(new Date(mStartDate));
int multiplier = mRecurrence.getMultiplier();
int factor = (mExecutionCount-1) * multiplier;
switch (mRecurrence.getPeriodType()){
case HOUR:
startTime = startTime.plusHours(factor);
break;
case DAY:
startTime = startTime.plusDays(factor);
break;
case WEEK:
startTime = startTime.plusWeeks(factor);
break;
case MONTH:
startTime = startTime.plusMonths(factor);
break;
case YEAR:
startTime = startTime.plusYears(factor);
break;
}
return startTime.toDate().getTime();
}
/**
* Computes the next time that this scheduled action is supposed to be
* executed based on the execution count.
*
* <p>This method does not consider the end time, or number of times it should be run.
* It only considers when the next execution would theoretically be due.</p>
*
* @return Next run time in milliseconds
*/
public long computeNextCountBasedScheduledExecutionTime(){
return computeNextScheduledExecutionTimeStartingAt(getTimeOfLastSchedule());
}
/**
* Computes the next time that this scheduled action is supposed to be
* executed based on the time of the last run.
*
* <p>This method does not consider the end time, or number of times it should be run.
* It only considers when the next execution would theoretically be due.</p>
*
* @return Next run time in milliseconds
*/
public long computeNextTimeBasedScheduledExecutionTime() {
return computeNextScheduledExecutionTimeStartingAt(getLastRunTime());
}
/**
* Computes the next time that this scheduled action is supposed to be
* executed starting at startTime.
*
* <p>This method does not consider the end time, or number of times it should be run.
* It only considers when the next execution would theoretically be due.</p>
*
* @param startTime time in milliseconds to use as start to compute the next schedule.
*
* @return Next run time in milliseconds
*/
private long computeNextScheduledExecutionTimeStartingAt(long startTime) {
if (startTime <= 0){ // has never been run
return mStartDate;
}
int multiplier = mRecurrence.getMultiplier();
LocalDateTime nextScheduledExecution = LocalDateTime.fromDateFields(new Date(startTime));
switch (mRecurrence.getPeriodType()) {
case HOUR:
nextScheduledExecution = nextScheduledExecution.plusHours(multiplier);
break;
case DAY:
nextScheduledExecution = nextScheduledExecution.plusDays(multiplier);
break;
case WEEK:
nextScheduledExecution = computeNextWeeklyExecutionStartingAt(nextScheduledExecution);
break;
case MONTH:
nextScheduledExecution = nextScheduledExecution.plusMonths(multiplier);
break;
case YEAR:
nextScheduledExecution = nextScheduledExecution.plusYears(multiplier);
break;
}
return nextScheduledExecution.toDate().getTime();
}
/**
* Computes the next time that this weekly scheduled action is supposed to be
* executed starting at startTime.
*
* If no days of the week have been set (GnuCash desktop allows it), it will return a
* date in the future to ensure ScheduledActionService doesn't execute it.
*
* @param startTime LocalDateTime to use as start to compute the next schedule.
*
* @return Next run time as a LocalDateTime. A date in the future, if no days of the week
* were set in the Recurrence.
*/
@NonNull
private LocalDateTime computeNextWeeklyExecutionStartingAt(LocalDateTime startTime) {
if (mRecurrence.getByDays().isEmpty())
return LocalDateTime.now().plusDays(1); // Just a date in the future
// Look into the week of startTime for another scheduled day of the week
for (int dayOfWeek : mRecurrence.getByDays() ) {
int jodaDayOfWeek = convertCalendarDayOfWeekToJoda(dayOfWeek);
LocalDateTime candidateNextDueTime = startTime.withDayOfWeek(jodaDayOfWeek);
if (candidateNextDueTime.isAfter(startTime))
return candidateNextDueTime;
}
// Return the first scheduled day of the week from the next due week
int firstScheduledDayOfWeek = convertCalendarDayOfWeekToJoda(mRecurrence.getByDays().get(0));
return startTime.plusWeeks(mRecurrence.getMultiplier())
.withDayOfWeek(firstScheduledDayOfWeek);
}
/**
* Converts a java.util.Calendar day of the week constant to the
* org.joda.time.DateTimeConstants equivalent.
*
* @param calendarDayOfWeek day of the week constant from java.util.Calendar
* @return day of the week constant equivalent from org.joda.time.DateTimeConstants
*/
private int convertCalendarDayOfWeekToJoda(int calendarDayOfWeek) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, calendarDayOfWeek);
return LocalDateTime.fromCalendarFields(cal).getDayOfWeek();
}
/**
* Set time of last execution of the scheduled action
* @param nextRun Timestamp in milliseconds since Epoch
*/
public void setLastRun(long nextRun) {
this.mLastRun = nextRun;
}
/**
* Returns the period of this scheduled action in milliseconds.
* @return Period in milliseconds since Epoch
* @deprecated Uses fixed values for time of months and years (which actually vary depending on number of days in month or leap year)
*/
public long getPeriod() {
return mRecurrence.getPeriod();
}
/**
* Returns the time of first execution of the scheduled action
* @return Start time of scheduled action in milliseconds since Epoch
*/
public long getStartTime() {
return mStartDate;
}
/**
* Sets the time of first execution of the scheduled action
* @param startDate Timestamp in milliseconds since Epoch
*/
public void setStartTime(long startDate) {
this.mStartDate = startDate;
if (mRecurrence != null) {
mRecurrence.setPeriodStart(new Timestamp(startDate));
}
}
/**
* Returns the time of last execution of the scheduled action
* @return Timestamp in milliseconds since Epoch
*/
public long getEndTime() {
return mEndDate;
}
/**
* Sets the end time of the scheduled action
* @param endDate Timestamp in milliseconds since Epoch
*/
public void setEndTime(long endDate) {
this.mEndDate = endDate;
if (mRecurrence != null){
mRecurrence.setPeriodEnd(new Timestamp(mEndDate));
}
}
/**
* Returns the tag of this scheduled action
* <p>The tag saves additional information about the scheduled action,
* e.g. such as export parameters for scheduled backups</p>
* @return Tag of scheduled action
*/
public String getTag() {
return mTag;
}
/**
* Sets the tag of the schedules action.
* <p>The tag saves additional information about the scheduled action,
* e.g. such as export parameters for scheduled backups</p>
* @param tag Tag of scheduled action
*/
public void setTag(String tag) {
this.mTag = tag;
}
/**
* Returns {@code true} if the scheduled action is enabled, {@code false} otherwise
* @return {@code true} if the scheduled action is enabled, {@code false} otherwise
*/
public boolean isEnabled(){
return mIsEnabled;
}
/**
* Toggles the enabled state of the scheduled action
* Disabled scheduled actions will not be executed
* @param enabled Flag if the scheduled action is enabled or not
*/
public void setEnabled(boolean enabled){
this.mIsEnabled = enabled;
}
/**
* Returns the total number of planned occurrences of this scheduled action.
* @return Total number of planned occurrences of this action
*/
public int getTotalPlannedExecutionCount(){
return mTotalFrequency;
}
/**
* Sets the number of occurences of this action
* @param plannedExecutions Number of occurences
*/
public void setTotalPlannedExecutionCount(int plannedExecutions){
this.mTotalFrequency = plannedExecutions;
}
/**
* Returns how many times this scheduled action has already been executed
* @return Number of times this action has been executed
*/
public int getExecutionCount(){
return mExecutionCount;
}
/**
* Sets the number of times this scheduled action has been executed
* @param executionCount Number of executions
*/
public void setExecutionCount(int executionCount){
mExecutionCount = executionCount;
}
/**
* Returns flag if transactions should be automatically created or not
* <p>This flag is currently unused in the app. It is only included here for compatibility with GnuCash desktop XML</p>
* @return {@code true} if the transaction should be auto-created, {@code false} otherwise
*/
public boolean shouldAutoCreate() {
return mAutoCreate;
}
/**
* Set flag for automatically creating transaction based on this scheduled action
* <p>This flag is currently unused in the app. It is only included here for compatibility with GnuCash desktop XML</p>
* @param autoCreate Flag for auto creating transactions
*/
public void setAutoCreate(boolean autoCreate) {
this.mAutoCreate = autoCreate;
}
/**
* Check if user will be notified of creation of scheduled transactions
* <p>This flag is currently unused in the app. It is only included here for compatibility with GnuCash desktop XML</p>
* @return {@code true} if user will be notified, {@code false} otherwise
*/
public boolean shouldAutoNotify() {
return mAutoNotify;
}
/**
* Sets whether to notify the user that scheduled transactions have been created
* <p>This flag is currently unused in the app. It is only included here for compatibility with GnuCash desktop XML</p>
* @param autoNotify Boolean flag
*/
public void setAutoNotify(boolean autoNotify) {
this.mAutoNotify = autoNotify;
}
/**
* Returns number of days in advance to create the transaction
* <p>This flag is currently unused in the app. It is only included here for compatibility with GnuCash desktop XML</p>
* @return Number of days in advance to create transaction
*/
public int getAdvanceCreateDays() {
return mAdvanceCreateDays;
}
/**
* Set number of days in advance to create the transaction
* <p>This flag is currently unused in the app. It is only included here for compatibility with GnuCash desktop XML</p>
* @param advanceCreateDays Number of days
*/
public void setAdvanceCreateDays(int advanceCreateDays) {
this.mAdvanceCreateDays = advanceCreateDays;
}
/**
* Returns the number of days in advance to notify of scheduled transactions
* <p>This flag is currently unused in the app. It is only included here for compatibility with GnuCash desktop XML</p>
* @return {@code true} if user will be notified, {@code false} otherwise
*/
public int getAdvanceNotifyDays() {
return mAdvanceNotifyDays;
}
/**
* Set number of days in advance to notify of scheduled transactions
* <p>This flag is currently unused in the app. It is only included here for compatibility with GnuCash desktop XML</p>
* @param advanceNotifyDays Number of days
*/
public void setAdvanceNotifyDays(int advanceNotifyDays) {
this.mAdvanceNotifyDays = advanceNotifyDays;
}
/**
* Return the template account GUID for this scheduled action
* <p>This method generates one if none was set</p>
* @return String GUID of template account
*/
public String getTemplateAccountUID() {
if (mTemplateAccountUID == null)
return mTemplateAccountUID = generateUID();
else
return mTemplateAccountUID;
}
/**
* Set the template account GUID
* @param templateAccountUID String GUID of template account
*/
public void setTemplateAccountUID(String templateAccountUID) {
this.mTemplateAccountUID = templateAccountUID;
}
/**
* Returns the event schedule (start, end and recurrence)
* @return String description of repeat schedule
*/
public String getRepeatString(){
StringBuilder ruleBuilder = new StringBuilder(mRecurrence.getRepeatString());
Context context = GnuCashApplication.getAppContext();
if (mEndDate <= 0 && mTotalFrequency > 0){
ruleBuilder.append(", ").append(context.getString(R.string.repeat_x_times, mTotalFrequency));
}
return ruleBuilder.toString();
}
/**
* Creates an RFC 2445 string which describes this recurring event
* <p>See http://recurrance.sourceforge.net/</p>
* @return String describing event
*/
public String getRuleString(){
String separator = ";";
StringBuilder ruleBuilder = new StringBuilder(mRecurrence.getRuleString());
if (mEndDate > 0){
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.US);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
ruleBuilder.append("UNTIL=").append(df.format(new Date(mEndDate))).append(separator);
} else if (mTotalFrequency > 0){
ruleBuilder.append("COUNT=").append(mTotalFrequency).append(separator);
}
return ruleBuilder.toString();
}
/**
* Return GUID of recurrence pattern for this scheduled action
* @return {@link Recurrence} object
*/
public Recurrence getRecurrence() {
return mRecurrence;
}
/**
* Overloaded method for setting the recurrence of the scheduled action.
* <p>This method allows you to specify the periodicity and the ordinal of it. For example,
* a recurrence every fortnight would give parameters: {@link PeriodType#WEEK}, ordinal:2</p>
* @param periodType Periodicity of the scheduled action
* @param ordinal Ordinal of the periodicity. If unsure, specify 1
* @see #setRecurrence(Recurrence)
*/
public void setRecurrence(PeriodType periodType, int ordinal){
Recurrence recurrence = new Recurrence(periodType);
recurrence.setMultiplier(ordinal);
setRecurrence(recurrence);
}
/**
* Sets the recurrence pattern of this scheduled action
* <p>This also sets the start period of the recurrence object, if there is one</p>
* @param recurrence {@link Recurrence} object
*/
public void setRecurrence(@NonNull Recurrence recurrence) {
this.mRecurrence = recurrence;
//if we were parsing XML and parsed the start and end date from the scheduled action first,
//then use those over the values which might be gotten from the recurrence
if (mStartDate > 0){
mRecurrence.setPeriodStart(new Timestamp(mStartDate));
} else {
mStartDate = mRecurrence.getPeriodStart().getTime();
}
if (mEndDate > 0){
mRecurrence.setPeriodEnd(new Timestamp(mEndDate));
} else if (mRecurrence.getPeriodEnd() != null){
mEndDate = mRecurrence.getPeriodEnd().getTime();
}
}
/**
* Creates a ScheduledAction from a Transaction and a period
* @param transaction Transaction to be scheduled
* @param period Period in milliseconds since Epoch
* @return Scheduled Action
* @deprecated Used for parsing legacy backup files. Use {@link Recurrence} instead
*/
@Deprecated
public static ScheduledAction parseScheduledAction(Transaction transaction, long period){
ScheduledAction scheduledAction = new ScheduledAction(ActionType.TRANSACTION);
scheduledAction.mActionUID = transaction.getUID();
Recurrence recurrence = Recurrence.fromLegacyPeriod(period);
scheduledAction.setRecurrence(recurrence);
return scheduledAction;
}
@Override
public String toString() {
return mActionType.name() + " - " + getRepeatString();
}
}
| 21,133 | 34.223333 | 137 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/Split.java
|
package org.gnucash.android.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import java.sql.Timestamp;
/**
* A split amount in a transaction.
*
* <p>Every transaction is made up of at least two splits (representing a double
* entry transaction)</p>
*
* <p>Amounts are always stored unsigned. This is independent of the negative values
* which are shown in the UI (for user convenience). The actual movement of the
* balance in the account depends on the type of normal balance of the account
* and the transaction type of the split (CREDIT/DEBIT).</p>
*
* @author Ngewi Fet <[email protected]>
*/
public class Split extends BaseModel implements Parcelable{
/**
* Flag indicating that the split has been reconciled
*/
public static final char FLAG_RECONCILED = 'y';
/**
* Flag indicating that the split has not been reconciled
*/
public static final char FLAG_NOT_RECONCILED = 'n';
/**
* Flag indicating that the split has been cleared, but not reconciled
*/
public static final char FLAG_CLEARED = 'c';
/**
* Amount value of this split which is in the currency of the transaction
*/
private Money mValue;
/**
* Amount of the split in the currency of the account to which the split belongs
*/
private Money mQuantity;
/**
* Transaction UID which this split belongs to
*/
private String mTransactionUID = "";
/**
* Account UID which this split belongs to
*/
private String mAccountUID;
/**
* The type of this transaction, credit or debit
*/
private TransactionType mSplitType = TransactionType.CREDIT;
/**
* Memo associated with this split
*/
private String mMemo;
private char mReconcileState = FLAG_NOT_RECONCILED;
/**
* Database required non-null field
*/
private Timestamp mReconcileDate = new Timestamp(System.currentTimeMillis());
/**
* Initialize split with a value and quantity amounts and the owning account
*
* <p>The transaction type is set to CREDIT. The amounts are stored unsigned.</p>
*
* @param value Money value amount of this split in the currency of the transaction.
* @param quantity Money value amount of this split in the currency of the
* owning account.
* @param accountUID String UID of transfer account
*/
public Split(@NonNull Money value, @NonNull Money quantity, String accountUID){
setQuantity(quantity);
setValue(value);
setAccountUID(accountUID);
}
/**
* Initialize split with a value amount and the owning account
*
* <p>The transaction type is set to CREDIT. The amount is stored unsigned.</p>
*
* @param amount Money value amount of this split. Value is always in the
* currency the owning transaction. This amount will be assigned
* as both the value and the quantity of this split.
* @param accountUID String UID of owning account
*/
public Split(@NonNull Money amount, String accountUID){
this(amount, new Money(amount), accountUID);
}
/**
* Clones the <code>sourceSplit</code> to create a new instance with same fields
* @param sourceSplit Split to be cloned
* @param generateUID Determines if the clone should have a new UID or should
* maintain the one from source
*/
public Split(Split sourceSplit, boolean generateUID){
this.mMemo = sourceSplit.mMemo;
this.mAccountUID = sourceSplit.mAccountUID;
this.mSplitType = sourceSplit.mSplitType;
this.mTransactionUID = sourceSplit.mTransactionUID;
this.mValue = new Money(sourceSplit.mValue);
this.mQuantity = new Money(sourceSplit.mQuantity);
//todo: clone reconciled status
if (generateUID){
generateUID();
} else {
setUID(sourceSplit.getUID());
}
}
/**
* Returns the value amount of the split
* @return Money amount of the split with the currency of the transaction
* @see #getQuantity()
*/
public Money getValue() {
return mValue;
}
/**
* Sets the value amount of the split.
*
* <p>The value is in the currency of the containing transaction.
* It's stored unsigned.</p>
*
* @param value Money value of this split
* @see #setQuantity(Money)
*/
public void setValue(Money value) {
mValue = value.abs();
}
/**
* Returns the quantity amount of the split.
* <p>The quantity is in the currency of the account to which the split is associated</p>
* @return Money quantity amount
* @see #getValue()
*/
public Money getQuantity() {
return mQuantity;
}
/**
* Sets the quantity value of the split.
*
* <p>The quantity is in the currency of the owning account.
* It will be stored unsigned.</p>
*
* @param quantity Money quantity amount
* @see #setValue(Money)
*/
public void setQuantity(Money quantity) {
this.mQuantity = quantity.abs();
}
/**
* Returns transaction GUID to which the split belongs
* @return String GUID of the transaction
*/
public String getTransactionUID() {
return mTransactionUID;
}
/**
* Sets the transaction to which the split belongs
* @param transactionUID GUID of transaction
*/
public void setTransactionUID(String transactionUID) {
this.mTransactionUID = transactionUID;
}
/**
* Returns the account GUID of this split
* @return GUID of the account
*/
public String getAccountUID() {
return mAccountUID;
}
/**
* Sets the GUID of the account of this split
* @param accountUID GUID of account
*/
public void setAccountUID(String accountUID) {
this.mAccountUID = accountUID;
}
/**
* Returns the type of the split
* @return {@link TransactionType} of the split
*/
public TransactionType getType() {
return mSplitType;
}
/**
* Sets the type of this split
* @param splitType Type of the split
*/
public void setType(TransactionType splitType) {
this.mSplitType = splitType;
}
/**
* Returns the memo of this split
* @return String memo of this split
*/
public String getMemo() {
return mMemo;
}
/**
* Sets this split memo
* @param memo String memo of this split
*/
public void setMemo(String memo) {
this.mMemo = memo;
}
/**
* Creates a split which is a pair of this instance.
* A pair split has all the same attributes except that the SplitType is inverted and it belongs
* to another account.
* @param accountUID GUID of account
* @return New split pair of current split
* @see TransactionType#invert()
*/
public Split createPair(String accountUID){
Split pair = new Split(mValue, accountUID);
pair.setType(mSplitType.invert());
pair.setMemo(mMemo);
pair.setTransactionUID(mTransactionUID);
pair.setQuantity(mQuantity);
return pair;
}
/**
* Clones this split and returns an exact copy.
* @return New instance of a split which is a copy of the current one
*/
protected Split clone() throws CloneNotSupportedException {
super.clone();
Split split = new Split(mValue, mAccountUID);
split.setUID(getUID());
split.setType(mSplitType);
split.setMemo(mMemo);
split.setTransactionUID(mTransactionUID);
split.setQuantity(mQuantity);
return split;
}
/**
* Checks is this <code>other</code> is a pair split of this.
* <p>Two splits are considered a pair if they have the same amount and
* opposite split types</p>
* @param other the other split of the pair to be tested
* @return whether the two splits are a pair
*/
public boolean isPairOf(Split other) {
return mValue.equals(other.mValue)
&& mSplitType.invert().equals(other.mSplitType);
}
/**
* Returns the formatted amount (with or without negation sign) for the split value
* @return Money amount of value
* @see #getFormattedAmount(Money, String, TransactionType)
*/
public Money getFormattedValue(){
return getFormattedAmount(mValue, mAccountUID, mSplitType);
}
/**
* Returns the formatted amount (with or without negation sign) for the quantity
* @return Money amount of quantity
* @see #getFormattedAmount(Money, String, TransactionType)
*/
public Money getFormattedQuantity(){
return getFormattedAmount(mQuantity, mAccountUID, mSplitType);
}
/**
* Splits are saved as absolute values to the database, with no negative numbers.
* The type of movement the split causes to the balance of an account determines
* its sign, and that depends on the split type and the account type
* @param amount Money amount to format
* @param accountUID GUID of the account
* @param splitType Transaction type of the split
* @return -{@code amount} if the amount would reduce the balance of
* {@code account}, otherwise +{@code amount}
*/
private static Money getFormattedAmount(Money amount, String accountUID, TransactionType
splitType){
boolean isDebitAccount = AccountsDbAdapter.getInstance().getAccountType(accountUID).hasDebitNormalBalance();
Money absAmount = amount.abs();
boolean isDebitSplit = splitType == TransactionType.DEBIT;
if (isDebitAccount) {
if (isDebitSplit) {
return absAmount;
} else {
return absAmount.negate();
}
} else {
if (isDebitSplit) {
return absAmount.negate();
} else {
return absAmount;
}
}
}
/**
* Return the reconciled state of this split
* <p>
* The reconciled state is one of the following values:
* <ul>
* <li><b>y</b>: means this split has been reconciled</li>
* <li><b>n</b>: means this split is not reconciled</li>
* <li><b>c</b>: means split has been cleared, but not reconciled</li>
* </ul>
* </p>
* <p>You can check the return value against the reconciled flags
* {@link #FLAG_RECONCILED}, {@link #FLAG_NOT_RECONCILED}, {@link #FLAG_CLEARED}</p>
*
* @return Character showing reconciled state
*/
public char getReconcileState() {
return mReconcileState;
}
/**
* Check if this split is reconciled
* @return {@code true} if the split is reconciled, {@code false} otherwise
*/
public boolean isReconciled(){
return mReconcileState == FLAG_RECONCILED;
}
/**
* Set reconciled state of this split.
* <p>
* The reconciled state is one of the following values:
* <ul>
* <li><b>y</b>: means this split has been reconciled</li>
* <li><b>n</b>: means this split is not reconciled</li>
* <li><b>c</b>: means split has been cleared, but not reconciled</li>
* </ul>
* </p>
* @param reconcileState One of the following flags {@link #FLAG_RECONCILED},
* {@link #FLAG_NOT_RECONCILED}, {@link #FLAG_CLEARED}
*/
public void setReconcileState(char reconcileState) {
this.mReconcileState = reconcileState;
}
/**
* Return the date of reconciliation
* @return Timestamp
*/
public Timestamp getReconcileDate() {
return mReconcileDate;
}
/**
* Set reconciliation date for this split
* @param reconcileDate Timestamp of reconciliation
*/
public void setReconcileDate(Timestamp reconcileDate) {
this.mReconcileDate = reconcileDate;
}
@Override
public String toString() {
return mSplitType.name() + " of " + mValue.toString() + " in account: " + mAccountUID;
}
/**
* Returns a string representation of the split which can be parsed again
* using {@link org.gnucash.android.model.Split#parseSplit(String)}
*
* <p>The string is formatted as:<br/>
* "<uid>;<valueNum>;<valueDenom>;<valueCurrencyCode>;<quantityNum>;<quantityDenom>;<quantityCurrencyCode>;<transaction_uid>;<account_uid>;<type>;<memo>"
* </p>
*
* <p><b>Only the memo field is allowed to be null</b></p>
*
* @return the converted CSV string of this split
*/
public String toCsv(){
String sep = ";";
//TODO: add reconciled state and date
String splitString = getUID() + sep + mValue.getNumerator() + sep + mValue.getDenominator()
+ sep + mValue.getCommodity().getCurrencyCode() + sep + mQuantity.getNumerator()
+ sep + mQuantity.getDenominator() + sep + mQuantity.getCommodity().getCurrencyCode()
+ sep + mTransactionUID + sep + mAccountUID + sep + mSplitType.name();
if (mMemo != null){
splitString = splitString + sep + mMemo;
}
return splitString;
}
/**
* Parses a split which is in the format:<br/>
* "<uid>;<valueNum>;<valueDenom>;<currency_code>;<quantityNum>;<quantityDenom>;<currency_code>;<transaction_uid>;<account_uid>;<type>;<memo>".
*
* <p>Also supports parsing of the deprecated format
* "<amount>;<currency_code>;<transaction_uid>;<account_uid>;<type>;<memo>".
* The split input string is the same produced by the {@link Split#toCsv()} method.</p>
*
* @param splitCsvString String containing formatted split
* @return Split instance parsed from the string
*/
public static Split parseSplit(String splitCsvString) {
//TODO: parse reconciled state and date
String[] tokens = splitCsvString.split(";");
if (tokens.length < 8) { //old format splits
Money amount = new Money(tokens[0], tokens[1]);
Split split = new Split(amount, tokens[2]);
split.setTransactionUID(tokens[3]);
split.setType(TransactionType.valueOf(tokens[4]));
if (tokens.length == 6) {
split.setMemo(tokens[5]);
}
return split;
} else {
long valueNum = Long.parseLong(tokens[1]);
long valueDenom = Long.parseLong(tokens[2]);
String valueCurrencyCode = tokens[3];
long quantityNum = Long.parseLong(tokens[4]);
long quantityDenom = Long.parseLong(tokens[5]);
String qtyCurrencyCode = tokens[6];
Money value = new Money(valueNum, valueDenom, valueCurrencyCode);
Money quantity = new Money(quantityNum, quantityDenom, qtyCurrencyCode);
Split split = new Split(value, tokens[8]);
split.setUID(tokens[0]);
split.setQuantity(quantity);
split.setTransactionUID(tokens[7]);
split.setType(TransactionType.valueOf(tokens[9]));
if (tokens.length == 11) {
split.setMemo(tokens[10]);
}
return split;
}
}
/**
* Two splits are considered equivalent if all the fields (excluding GUID
* and timestamps - created, modified, reconciled) are equal.
*
* <p>Any two splits which are equal are also equivalent, but the reverse
* is not true</p>
*
* <p>The difference with to {@link #equals(Object)} is that the GUID of
* the split is not considered. This is useful in cases where a new split
* is generated for a transaction with the same properties, but a new GUID
* is generated e.g. when editing a transaction and modifying the splits</p>
*
* @param split Other split for which to test equivalence
* @return {@code true} if both splits are equivalent, {@code false} otherwise
*/
@SuppressWarnings("SimplifiableIfStatement")
public boolean isEquivalentTo(Split split){
if (this == split) return true;
if (super.equals(split)) return true;
if (mReconcileState != split.mReconcileState) return false;
if (!mValue.equals(split.mValue)) return false;
if (!mQuantity.equals(split.mQuantity)) return false;
if (!mTransactionUID.equals(split.mTransactionUID)) return false;
if (!mAccountUID.equals(split.mAccountUID)) return false;
if (mSplitType != split.mSplitType) return false;
return mMemo != null ? mMemo.equals(split.mMemo) : split.mMemo == null;
}
/**
* Two splits are considered equal if all their properties excluding
* timestamps (created, modified, reconciled) are equal.
*
* @param o Other split to compare for equality
* @return {@code true} if this split is equal to {@code o}, {@code false} otherwise
*/
@SuppressWarnings("SimplifiableIfStatement")
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Split split = (Split) o;
if (mReconcileState != split.mReconcileState) return false;
if (!mValue.equals(split.mValue)) return false;
if (!mQuantity.equals(split.mQuantity)) return false;
if (!mTransactionUID.equals(split.mTransactionUID)) return false;
if (!mAccountUID.equals(split.mAccountUID)) return false;
if (mSplitType != split.mSplitType) return false;
return mMemo != null ? mMemo.equals(split.mMemo) : split.mMemo == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + mValue.hashCode();
result = 31 * result + mQuantity.hashCode();
result = 31 * result + mTransactionUID.hashCode();
result = 31 * result + mAccountUID.hashCode();
result = 31 * result + mSplitType.hashCode();
result = 31 * result + (mMemo != null ? mMemo.hashCode() : 0);
result = 31 * result + (int) mReconcileState;
return result;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getUID());
dest.writeString(mAccountUID);
dest.writeString(mTransactionUID);
dest.writeString(mSplitType.name());
dest.writeLong(mValue.getNumerator());
dest.writeLong(mValue.getDenominator());
dest.writeString(mValue.getCommodity().getCurrencyCode());
dest.writeLong(mQuantity.getNumerator());
dest.writeLong(mQuantity.getDenominator());
dest.writeString(mQuantity.getCommodity().getCurrencyCode());
dest.writeString(mMemo == null ? "" : mMemo);
dest.writeString(String.valueOf(mReconcileState));
dest.writeString(mReconcileDate.toString());
}
/**
* Constructor for creating a Split object from a Parcel
* @param source Source parcel containing the split
* @see #CREATOR
*/
private Split(Parcel source){
setUID(source.readString());
mAccountUID = source.readString();
mTransactionUID = source.readString();
mSplitType = TransactionType.valueOf(source.readString());
long valueNum = source.readLong();
long valueDenom = source.readLong();
String valueCurrency = source.readString();
mValue = new Money(valueNum, valueDenom, valueCurrency).abs();
long qtyNum = source.readLong();
long qtyDenom = source.readLong();
String qtyCurrency = source.readString();
mQuantity = new Money(qtyNum, qtyDenom, qtyCurrency).abs();
String memo = source.readString();
mMemo = memo.isEmpty() ? null : memo;
mReconcileState = source.readString().charAt(0);
mReconcileDate = Timestamp.valueOf(source.readString());
}
/**
* Creates new Parcels containing the information in this split during serialization
*/
public static final Parcelable.Creator<Split> CREATOR
= new Parcelable.Creator<Split>() {
@Override
public Split createFromParcel(Parcel source) {
return new Split(source);
}
@Override
public Split[] newArray(int size) {
return new Split[size];
}
};
}
| 20,868 | 33.324013 | 223 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/Transaction.java
|
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import android.content.Intent;
import android.support.annotation.NonNull;
import org.gnucash.android.BuildConfig;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.export.ofx.OfxHelper;
import org.gnucash.android.model.Account.OfxAccountType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Represents a financial transaction, either credit or debit.
* Transactions belong to accounts and each have the unique identifier of the account to which they belong.
* The default type is a debit, unless otherwise specified.
* @author Ngewi Fet <[email protected]>
*/
public class Transaction extends BaseModel{
/**
* Mime type for transactions in Gnucash.
* Used for recording transactions through intents
*/
public static final String MIME_TYPE = "vnd.android.cursor.item/vnd." + BuildConfig.APPLICATION_ID + ".transaction";
/**
* Key for passing the account unique Identifier as an argument through an {@link Intent}
* @deprecated use {@link Split}s instead
*/
@Deprecated
public static final String EXTRA_ACCOUNT_UID = "org.gnucash.android.extra.account_uid";
/**
* Key for specifying the double entry account
* @deprecated use {@link Split}s instead
*/
@Deprecated
public static final String EXTRA_DOUBLE_ACCOUNT_UID = "org.gnucash.android.extra.double_account_uid";
/**
* Key for identifying the amount of the transaction through an Intent
* @deprecated use {@link Split}s instead
*/
@Deprecated
public static final String EXTRA_AMOUNT = "org.gnucash.android.extra.amount";
/**
* Extra key for the transaction type.
* This value should typically be set by calling {@link TransactionType#name()}
* @deprecated use {@link Split}s instead
*/
@Deprecated
public static final String EXTRA_TRANSACTION_TYPE = "org.gnucash.android.extra.transaction_type";
/**
* Argument key for passing splits as comma-separated multi-line list and each line is a split.
* The line format is: <type>;<amount>;<account_uid>
* The amount should be formatted in the US Locale
*/
public static final String EXTRA_SPLITS = "org.gnucash.android.extra.transaction.splits";
/**
* GUID of commodity associated with this transaction
*/
private Commodity mCommodity;
/**
* The splits making up this transaction
*/
private List<Split> mSplitList = new ArrayList<>();
/**
* Name describing the transaction
*/
private String mDescription;
/**
* An extra note giving details about the transaction
*/
private String mNotes = "";
/**
* Flag indicating if this transaction has been exported before or not
* The transactions are typically exported as bank statement in the OFX format
*/
private boolean mIsExported = false;
/**
* Timestamp when this transaction occurred
*/
private long mTimestamp;
/**
* Flag indicating that this transaction is a template
*/
private boolean mIsTemplate = false;
/**
* GUID of ScheduledAction which created this transaction
*/
private String mScheduledActionUID = null;
/**
* Overloaded constructor. Creates a new transaction instance with the
* provided data and initializes the rest to default values.
* @param name Name of the transaction
*/
public Transaction(String name) {
initDefaults();
setDescription(name);
}
/**
* Copy constructor.
* Creates a new transaction object which is a clone of the parameter.
* <p><b>Note:</b> The unique ID of the transaction is not cloned if the parameter <code>generateNewUID</code>,
* is set to false. Otherwise, a new one is generated.<br/>
* The export flag and the template flag are not copied from the old transaction to the new.</p>
* @param transaction Transaction to be cloned
* @param generateNewUID Flag to determine if new UID should be assigned or not
*/
public Transaction(Transaction transaction, boolean generateNewUID){
initDefaults();
setDescription(transaction.getDescription());
setNote(transaction.getNote());
setTime(transaction.getTimeMillis());
setCommodity(transaction.getCommodity());
//exported flag is left at default value of false
for (Split split : transaction.mSplitList) {
addSplit(new Split(split, generateNewUID));
}
if (!generateNewUID){
setUID(transaction.getUID());
}
}
/**
* Initializes the different fields to their default values.
*/
private void initDefaults(){
setCommodity(Commodity.DEFAULT_COMMODITY);
this.mTimestamp = System.currentTimeMillis();
}
/**
* Creates a split which will balance the transaction, in value.
* <p><b>Note:</b>If a transaction has splits with different currencies, no auto-balancing will be performed.</p>
*
* <p>The added split will not use any account in db, but will use currency code as account UID.
* The added split will be returned, to be filled with proper account UID later.</p>
* @return Split whose amount is the imbalance of this transaction
*/
public Split createAutoBalanceSplit(){
Money imbalance = getImbalance(); //returns imbalance of 0 for multicurrency transactions
if (!imbalance.isAmountZero()){
// yes, this is on purpose the account UID is set to the currency.
// This should be overridden before saving to db
Split split = new Split(imbalance, mCommodity.getCurrencyCode());
split.setType(imbalance.isNegative() ? TransactionType.CREDIT : TransactionType.DEBIT);
addSplit(split);
return split;
}
return null;
}
/**
* Set the GUID of the transaction
* If the transaction has Splits, their transactionGUID will be updated as well
* @param uid String unique ID
*/
@Override
public void setUID(String uid) {
super.setUID(uid);
for (Split split : mSplitList) {
split.setTransactionUID(uid);
}
}
/**
* Returns list of splits for this transaction
* @return {@link java.util.List} of splits in the transaction
*/
public List<Split> getSplits(){
return mSplitList;
}
/**
* Returns the list of splits belonging to a specific account
* @param accountUID Unique Identifier of the account
* @return List of {@link org.gnucash.android.model.Split}s
*/
public List<Split> getSplits(String accountUID){
List<Split> splits = new ArrayList<>();
for (Split split : mSplitList) {
if (split.getAccountUID().equals(accountUID)){
splits.add(split);
}
}
return splits;
}
/**
* Sets the splits for this transaction
* <p>All the splits in the list will have their transaction UID set to this transaction</p>
* @param splitList List of splits for this transaction
*/
public void setSplits(List<Split> splitList){
mSplitList = splitList;
for (Split split : splitList) {
split.setTransactionUID(getUID());
}
}
/**
* Add a split to the transaction.
* <p>Sets the split UID and currency to that of this transaction</p>
* @param split Split for this transaction
*/
public void addSplit(Split split){
//sets the currency of the split to the currency of the transaction
split.setTransactionUID(getUID());
mSplitList.add(split);
}
/**
* Returns the balance of this transaction for only those splits which relate to the account.
* <p>Uses a call to {@link #getBalance(String)} with the appropriate parameters</p>
* @param accountUID Unique Identifier of the account
* @return Money balance of the transaction for the specified account
* @see #computeBalance(String, java.util.List)
*/
public Money getBalance(String accountUID){
return computeBalance(accountUID, mSplitList);
}
/**
* Computes the imbalance amount for the given transaction.
* In double entry, all transactions should resolve to zero. But imbalance occurs when there are unresolved splits.
* <p><b>Note:</b> If this is a multi-currency transaction, an imbalance of zero will be returned</p>
* @return Money imbalance of the transaction or zero if it is a multi-currency transaction
*/
private Money getImbalance(){
Money imbalance = Money.createZeroInstance(mCommodity.getCurrencyCode());
for (Split split : mSplitList) {
if (!split.getQuantity().getCommodity().equals(mCommodity)) {
// this may happen when importing XML exported from GNCA before 2.0.0
// these transactions should only be imported from XML exported from GNC desktop
// so imbalance split should not be generated for them
return Money.createZeroInstance(mCommodity.getCurrencyCode());
}
Money amount = split.getValue();
if (split.getType() == TransactionType.DEBIT)
imbalance = imbalance.subtract(amount);
else
imbalance = imbalance.add(amount);
}
return imbalance;
}
/**
* Computes the balance of the splits belonging to a particular account.
* <p>Only those splits which belong to the account will be considered.
* If the {@code accountUID} is null, then the imbalance of the transaction is computed. This means that either
* zero is returned (for balanced transactions) or the imbalance amount will be returned.</p>
* @param accountUID Unique Identifier of the account
* @param splitList List of splits
* @return Money list of splits
*/
public static Money computeBalance(String accountUID, List<Split> splitList) {
AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance();
AccountType accountType = accountsDbAdapter.getAccountType(accountUID);
String accountCurrencyCode = accountsDbAdapter.getAccountCurrencyCode(accountUID);
boolean isDebitAccount = accountType.hasDebitNormalBalance();
Money balance = Money.createZeroInstance(accountCurrencyCode);
for (Split split : splitList) {
if (!split.getAccountUID().equals(accountUID))
continue;
Money amount;
if (split.getValue().getCommodity().getCurrencyCode().equals(accountCurrencyCode)){
amount = split.getValue();
} else { //if this split belongs to the account, then either its value or quantity is in the account currency
amount = split.getQuantity();
}
boolean isDebitSplit = split.getType() == TransactionType.DEBIT;
if (isDebitAccount) {
if (isDebitSplit) {
balance = balance.add(amount);
} else {
balance = balance.subtract(amount);
}
} else {
if (isDebitSplit) {
balance = balance.subtract(amount);
} else {
balance = balance.add(amount);
}
}
}
return balance;
}
/**
* Returns the currency code of this transaction.
* @return ISO 4217 currency code string
*/
public String getCurrencyCode() {
return mCommodity.getCurrencyCode();
}
/**
* Returns the commodity for this transaction
* @return Commodity of the transaction
*/
public @NonNull Commodity getCommodity() {
return mCommodity;
}
/**
* Sets the commodity for this transaction
* @param commodity Commodity instance
*/
public void setCommodity(@NonNull Commodity commodity) {
this.mCommodity = commodity;
}
/**
* Returns the description of the transaction
* @return Transaction description
*/
public String getDescription() {
return mDescription;
}
/**
* Sets the transaction description
* @param description String description
*/
public void setDescription(String description) {
this.mDescription = description.trim();
}
/**
* Add notes to the transaction
* @param notes String containing notes for the transaction
*/
public void setNote(String notes) {
this.mNotes = notes;
}
/**
* Returns the transaction notes
* @return String notes of transaction
*/
public String getNote() {
return mNotes;
}
/**
* Set the time of the transaction
* @param timestamp Time when transaction occurred as {@link Date}
*/
public void setTime(Date timestamp){
this.mTimestamp = timestamp.getTime();
}
/**
* Sets the time when the transaction occurred
* @param timeInMillis Time in milliseconds
*/
public void setTime(long timeInMillis) {
this.mTimestamp = timeInMillis;
}
/**
* Returns the time of transaction in milliseconds
* @return Time when transaction occurred in milliseconds
*/
public long getTimeMillis(){
return mTimestamp;
}
/**
* Returns the corresponding {@link TransactionType} given the accounttype and the effect which the transaction
* type should have on the account balance
* @param accountType Type of account
* @param shouldReduceBalance <code>true</code> if type should reduce balance, <code>false</code> otherwise
* @return TransactionType for the account
*/
public static TransactionType getTypeForBalance(AccountType accountType, boolean shouldReduceBalance){
TransactionType type;
if (accountType.hasDebitNormalBalance()) {
type = shouldReduceBalance ? TransactionType.CREDIT : TransactionType.DEBIT;
} else {
type = shouldReduceBalance ? TransactionType.DEBIT : TransactionType.CREDIT;
}
return type;
}
/**
* Returns true if the transaction type represents a decrease for the account balance for the <code>accountType</code>, false otherwise
* @return true if the amount represents a decrease in the account balance, false otherwise
* @see #getTypeForBalance(AccountType, boolean)
*/
public static boolean shouldDecreaseBalance(AccountType accountType, TransactionType transactionType) {
if (accountType.hasDebitNormalBalance()) {
return transactionType == TransactionType.CREDIT;
} else
return transactionType == TransactionType.DEBIT;
}
/**
* Sets the exported flag on the transaction
* @param isExported <code>true</code> if the transaction has been exported, <code>false</code> otherwise
*/
public void setExported(boolean isExported){
mIsExported = isExported;
}
/**
* Returns <code>true</code> if the transaction has been exported, <code>false</code> otherwise
* @return <code>true</code> if the transaction has been exported, <code>false</code> otherwise
*/
public boolean isExported(){
return mIsExported;
}
/**
* Returns {@code true} if this transaction is a template, {@code false} otherwise
* @return {@code true} if this transaction is a template, {@code false} otherwise
*/
public boolean isTemplate(){
return mIsTemplate;
}
/**
* Sets flag indicating whether this transaction is a template or not
* @param isTemplate Flag indicating if transaction is a template or not
*/
public void setTemplate(boolean isTemplate){
mIsTemplate = isTemplate;
}
/**
* 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){
Money balance = getBalance(accountUID);
TransactionType transactionType = balance.isNegative() ? TransactionType.DEBIT : TransactionType.CREDIT;
Element transactionNode = doc.createElement(OfxHelper.TAG_STATEMENT_TRANSACTION);
Element typeNode = doc.createElement(OfxHelper.TAG_TRANSACTION_TYPE);
typeNode.appendChild(doc.createTextNode(transactionType.toString()));
transactionNode.appendChild(typeNode);
Element datePosted = doc.createElement(OfxHelper.TAG_DATE_POSTED);
datePosted.appendChild(doc.createTextNode(OfxHelper.getOfxFormattedTime(mTimestamp)));
transactionNode.appendChild(datePosted);
Element dateUser = doc.createElement(OfxHelper.TAG_DATE_USER);
dateUser.appendChild(doc.createTextNode(
OfxHelper.getOfxFormattedTime(mTimestamp)));
transactionNode.appendChild(dateUser);
Element amount = doc.createElement(OfxHelper.TAG_TRANSACTION_AMOUNT);
amount.appendChild(doc.createTextNode(balance.toPlainString()));
transactionNode.appendChild(amount);
Element transID = doc.createElement(OfxHelper.TAG_TRANSACTION_FITID);
transID.appendChild(doc.createTextNode(getUID()));
transactionNode.appendChild(transID);
Element name = doc.createElement(OfxHelper.TAG_NAME);
name.appendChild(doc.createTextNode(mDescription));
transactionNode.appendChild(name);
if (mNotes != null && mNotes.length() > 0){
Element memo = doc.createElement(OfxHelper.TAG_MEMO);
memo.appendChild(doc.createTextNode(mNotes));
transactionNode.appendChild(memo);
}
if (mSplitList.size() == 2){ //if we have exactly one other split, then treat it like a transfer
String transferAccountUID = accountUID;
for (Split split : mSplitList) {
if (!split.getAccountUID().equals(accountUID)){
transferAccountUID = split.getAccountUID();
break;
}
}
Element bankId = doc.createElement(OfxHelper.TAG_BANK_ID);
bankId.appendChild(doc.createTextNode(OfxHelper.APP_ID));
Element acctId = doc.createElement(OfxHelper.TAG_ACCOUNT_ID);
acctId.appendChild(doc.createTextNode(transferAccountUID));
Element accttype = doc.createElement(OfxHelper.TAG_ACCOUNT_TYPE);
AccountsDbAdapter acctDbAdapter = AccountsDbAdapter.getInstance();
OfxAccountType ofxAccountType = Account.convertToOfxAccountType(acctDbAdapter.getAccountType(transferAccountUID));
accttype.appendChild(doc.createTextNode(ofxAccountType.toString()));
Element bankAccountTo = doc.createElement(OfxHelper.TAG_BANK_ACCOUNT_TO);
bankAccountTo.appendChild(bankId);
bankAccountTo.appendChild(acctId);
bankAccountTo.appendChild(accttype);
transactionNode.appendChild(bankAccountTo);
}
return transactionNode;
}
/**
* Returns the GUID of the {@link org.gnucash.android.model.ScheduledAction} which created this transaction
* @return GUID of scheduled action
*/
public String getScheduledActionUID() {
return mScheduledActionUID;
}
/**
* Sets the GUID of the {@link org.gnucash.android.model.ScheduledAction} which created this transaction
* @param scheduledActionUID GUID of the scheduled action
*/
public void setScheduledActionUID(String scheduledActionUID) {
mScheduledActionUID = scheduledActionUID;
}
/**
* Creates an Intent with arguments from the <code>transaction</code>.
* This intent can be broadcast to create a new transaction
* @param transaction Transaction used to create intent
* @return Intent with transaction details as extras
*/
public static Intent createIntent(Transaction transaction){
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType(Transaction.MIME_TYPE);
intent.putExtra(Intent.EXTRA_TITLE, transaction.getDescription());
intent.putExtra(Intent.EXTRA_TEXT, transaction.getNote());
intent.putExtra(Account.EXTRA_CURRENCY_CODE, transaction.getCurrencyCode());
StringBuilder stringBuilder = new StringBuilder();
for (Split split : transaction.getSplits()) {
stringBuilder.append(split.toCsv()).append("\n");
}
intent.putExtra(Transaction.EXTRA_SPLITS, stringBuilder.toString());
return intent;
}
}
| 21,430 | 36.206597 | 139 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/model/TransactionType.java
|
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
/**
* Type of transaction, a credit or a debit
*
* @author Ngewi Fet <[email protected]>
* @author Jesse Shieh <[email protected]>
*/
public enum TransactionType {
DEBIT, CREDIT;
private TransactionType opposite;
static {
DEBIT.opposite = CREDIT;
CREDIT.opposite = DEBIT;
}
/**
* Inverts the transaction type.
* <p>{@link TransactionType#CREDIT} becomes {@link TransactionType#DEBIT} and vice versa</p>
* @return Inverted transaction type
*/
public TransactionType invert() {
return opposite;
}
}
| 1,245 | 26.688889 | 97 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/receivers/AccountCreator.java
|
/*
* Copyright (c) 2012 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Commodity;
/**
* Broadcast receiver responsible for creating {@link Account}s received through intents.
* In order to create an <code>Account</code>, you need to broadcast an {@link Intent} with arguments
* for the name, currency and optionally, a unique identifier for the account (which should be unique to Gnucash)
* of the Account to be created. Also remember to set the right mime type so that Android can properly route the Intent
* <b>Note</b> This Broadcast receiver requires the permission "org.gnucash.android.permission.CREATE_ACCOUNT"
* in order to be able to use Intents to create accounts. So remember to declare it in your manifest
*
* @author Ngewi Fet <[email protected]>
* @see {@link Account#EXTRA_CURRENCY_CODE}, {@link Account#MIME_TYPE} {@link Intent#EXTRA_TITLE}, {@link Intent#EXTRA_UID}
*/
public class AccountCreator extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Gnucash", "Received account creation intent");
Bundle args = intent.getExtras();
Account account = new Account(args.getString(Intent.EXTRA_TITLE));
account.setParentUID(args.getString(Account.EXTRA_PARENT_UID));
String currencyCode = args.getString(Account.EXTRA_CURRENCY_CODE);
if (currencyCode != null) {
Commodity commodity = Commodity.getInstance(currencyCode);
if (commodity != null) {
account.setCommodity(commodity);
} else {
throw new IllegalArgumentException("Commodity with '" + currencyCode
+ "' currency code not found in the database");
}
}
String uid = args.getString(Intent.EXTRA_UID);
if (uid != null)
account.setUID(uid);
AccountsDbAdapter.getInstance().addRecord(account, DatabaseAdapter.UpdateMethod.insert);
}
}
| 2,917 | 40.685714 | 123 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/receivers/BootReceiver.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.util.BackupManager;
/**
* Receiver which is called when the device finishes booting.
* It schedules periodic jobs.
* @author Ngewi Fet <[email protected]>
*/
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
GnuCashApplication.startScheduledActionExecutionService(context);
BackupManager.schedulePeriodicBackups(context);
}
}
| 1,270 | 31.589744 | 75 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/receivers/PeriodicJobReceiver.java
|
/* Copyright (c) 2018 Àlex Magaz Graça <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.gnucash.android.service.ScheduledActionService;
import org.gnucash.android.util.BackupJob;
/**
* Receiver to run periodic jobs.
*
* <p>For now, backups and scheduled actions.</p>
*
* @author Àlex Magaz Graça <[email protected]>
*/
public class PeriodicJobReceiver extends BroadcastReceiver {
private static final String LOG_TAG = "PeriodicJobReceiver";
public static final String ACTION_BACKUP = "org.gnucash.android.action_backup";
public static final String ACTION_SCHEDULED_ACTIONS = "org.gnucash.android.action_scheduled_actions";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == null) {
Log.w(LOG_TAG, "No action was set in the intent. Ignoring...");
return;
}
if (intent.getAction().equals(ACTION_BACKUP)) {
BackupJob.enqueueWork(context);
} else if (intent.getAction().equals(ACTION_SCHEDULED_ACTIONS)) {
ScheduledActionService.enqueueWork(context);
}
}
}
| 1,848 | 33.886792 | 105 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/receivers/TransactionAppWidgetProvider.java
|
/*
* Copyright (c) 2012 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.receivers;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.homescreen.WidgetConfigurationActivity;
import org.gnucash.android.ui.settings.PreferenceActivity;
/**
* {@link AppWidgetProvider} which is responsible for managing widgets on the homescreen
* It receives broadcasts related to updating and deleting widgets
* Widgets can also be updated manually by calling {@link WidgetConfigurationActivity#updateAllWidgets(Context)}
* @author Ngewi Fet <[email protected]>
*
*/
public class TransactionAppWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int appWidgetId : appWidgetIds) {
WidgetConfigurationActivity.updateWidget(context, appWidgetId);
}
}
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
WidgetConfigurationActivity.updateAllWidgets(context);
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
for (int appWidgetId : appWidgetIds) {
WidgetConfigurationActivity.removeWidgetConfiguration(context, appWidgetId);
}
}
}
| 2,187 | 34.868852 | 112 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/receivers/TransactionRecorder.java
|
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.model.TransactionType;
import org.gnucash.android.ui.homescreen.WidgetConfigurationActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.MathContext;
/**
* Broadcast receiver responsible for creating transactions received through {@link Intent}s
* In order to create a transaction through Intents, broadcast an intent with the arguments needed to
* create the transaction. Transactions are strongly bound to {@link Account}s and it is recommended to
* create an Account for your transaction splits.
* <p>Remember to declare the appropriate permissions in order to create transactions with Intents.
* The required permission is "org.gnucash.android.permission.RECORD_TRANSACTION"</p>
* @author Ngewi Fet <[email protected]>
* @see AccountCreator
* @see org.gnucash.android.model.Transaction#createIntent(org.gnucash.android.model.Transaction)
*/
public class TransactionRecorder extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(this.getClass().getName(), "Received transaction recording intent");
Bundle args = intent.getExtras();
String name = args.getString(Intent.EXTRA_TITLE);
String note = args.getString(Intent.EXTRA_TEXT);
String currencyCode = args.getString(Account.EXTRA_CURRENCY_CODE);
if (currencyCode == null)
currencyCode = Money.DEFAULT_CURRENCY_CODE;
Transaction transaction = new Transaction(name);
transaction.setTime(System.currentTimeMillis());
transaction.setNote(note);
transaction.setCommodity(Commodity.getInstance(currencyCode));
//Parse deprecated args for compatibility. Transactions were bound to accounts, now only splits are
String accountUID = args.getString(Transaction.EXTRA_ACCOUNT_UID);
if (accountUID != null) {
TransactionType type = TransactionType.valueOf(args.getString(Transaction.EXTRA_TRANSACTION_TYPE));
BigDecimal amountBigDecimal = (BigDecimal) args.getSerializable(Transaction.EXTRA_AMOUNT);
Commodity commodity = CommoditiesDbAdapter.getInstance().getCommodity(currencyCode);
amountBigDecimal = amountBigDecimal.setScale(commodity.getSmallestFractionDigits(), BigDecimal.ROUND_HALF_EVEN).round(MathContext.DECIMAL128);
Money amount = new Money(amountBigDecimal, Commodity.getInstance(currencyCode));
Split split = new Split(amount, accountUID);
split.setType(type);
transaction.addSplit(split);
String transferAccountUID = args.getString(Transaction.EXTRA_DOUBLE_ACCOUNT_UID);
if (transferAccountUID != null) {
transaction.addSplit(split.createPair(transferAccountUID));
}
}
String splits = args.getString(Transaction.EXTRA_SPLITS);
if (splits != null) {
StringReader stringReader = new StringReader(splits);
BufferedReader bufferedReader = new BufferedReader(stringReader);
String line = null;
try {
while ((line = bufferedReader.readLine()) != null){
Split split = Split.parseSplit(line);
transaction.addSplit(split);
}
} catch (IOException e) {
Crashlytics.logException(e);
}
}
TransactionsDbAdapter.getInstance().addRecord(transaction, DatabaseAdapter.UpdateMethod.insert);
WidgetConfigurationActivity.updateAllWidgets(context);
}
}
| 4,843 | 42.25 | 154 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/service/ScheduledActionService.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.support.v4.app.JobIntentService;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.RecurrenceDbAdapter;
import org.gnucash.android.db.adapter.ScheduledActionDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.export.ExportAsyncTask;
import org.gnucash.android.export.ExportParams;
import org.gnucash.android.model.Book;
import org.gnucash.android.model.ScheduledAction;
import org.gnucash.android.model.Transaction;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* Service for running scheduled events.
*
* <p>It's run every time the <code>enqueueWork</code> is called. It goes
* through all scheduled event entries in the the database and executes them.</p>
*
* <p>Scheduled runs of the service should be achieved using an
* {@link android.app.AlarmManager}, with
* {@link org.gnucash.android.receivers.PeriodicJobReceiver} as an intermediary.</p>
*
* @author Ngewi Fet <[email protected]>
*/
public class ScheduledActionService extends JobIntentService {
private static final String LOG_TAG = "ScheduledActionService";
private static final int JOB_ID = 1001;
public static void enqueueWork(Context context) {
Intent intent = new Intent(context, ScheduledActionService.class);
enqueueWork(context, ScheduledActionService.class, JOB_ID, intent);
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
Log.i(LOG_TAG, "Starting scheduled action service");
BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance();
List<Book> books = booksDbAdapter.getAllRecords();
for (Book book : books) { //// TODO: 20.04.2017 Retrieve only the book UIDs with new method
DatabaseHelper dbHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), book.getUID());
SQLiteDatabase db = dbHelper.getWritableDatabase();
RecurrenceDbAdapter recurrenceDbAdapter = new RecurrenceDbAdapter(db);
ScheduledActionDbAdapter scheduledActionDbAdapter = new ScheduledActionDbAdapter(db, recurrenceDbAdapter);
List<ScheduledAction> scheduledActions = scheduledActionDbAdapter.getAllEnabledScheduledActions();
Log.i(LOG_TAG, String.format("Processing %d total scheduled actions for Book: %s",
scheduledActions.size(), book.getDisplayName()));
processScheduledActions(scheduledActions, db);
//close all databases except the currently active database
if (!db.getPath().equals(GnuCashApplication.getActiveDb().getPath()))
db.close();
}
Log.i(LOG_TAG, "Completed service @ " + java.text.DateFormat.getDateTimeInstance().format(new Date()));
}
/**
* Process scheduled actions and execute any pending actions
* @param scheduledActions List of scheduled actions
*/
//made public static for testing. Do not call these methods directly
@VisibleForTesting
public static void processScheduledActions(List<ScheduledAction> scheduledActions, SQLiteDatabase db) {
for (ScheduledAction scheduledAction : scheduledActions) {
long now = System.currentTimeMillis();
int totalPlannedExecutions = scheduledAction.getTotalPlannedExecutionCount();
int executionCount = scheduledAction.getExecutionCount();
//the end time of the ScheduledAction is not handled here because
//it is handled differently for transactions and backups. See the individual methods.
if (scheduledAction.getStartTime() > now //if schedule begins in the future
|| !scheduledAction.isEnabled() // of if schedule is disabled
|| (totalPlannedExecutions > 0 && executionCount >= totalPlannedExecutions)) { //limit was set and we reached or exceeded it
Log.i(LOG_TAG, "Skipping scheduled action: " + scheduledAction.toString());
continue;
}
executeScheduledEvent(scheduledAction, db);
}
}
/**
* Executes a scheduled event according to the specified parameters
* @param scheduledAction ScheduledEvent to be executed
*/
private static void executeScheduledEvent(ScheduledAction scheduledAction, SQLiteDatabase db){
Log.i(LOG_TAG, "Executing scheduled action: " + scheduledAction.toString());
int executionCount = 0;
switch (scheduledAction.getActionType()){
case TRANSACTION:
executionCount += executeTransactions(scheduledAction, db);
break;
case BACKUP:
executionCount += executeBackup(scheduledAction, db);
break;
}
if (executionCount > 0) {
scheduledAction.setLastRun(System.currentTimeMillis());
// Set the execution count in the object because it will be checked
// for the next iteration in the calling loop.
// This call is important, do not remove!!
scheduledAction.setExecutionCount(scheduledAction.getExecutionCount() + executionCount);
// Update the last run time and execution count
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseSchema.ScheduledActionEntry.COLUMN_LAST_RUN,
scheduledAction.getLastRunTime());
contentValues.put(DatabaseSchema.ScheduledActionEntry.COLUMN_EXECUTION_COUNT,
scheduledAction.getExecutionCount());
db.update(DatabaseSchema.ScheduledActionEntry.TABLE_NAME, contentValues,
DatabaseSchema.ScheduledActionEntry.COLUMN_UID + "=?", new String[]{scheduledAction.getUID()});
}
}
/**
* Executes scheduled backups for a given scheduled action.
* The backup will be executed only once, even if multiple schedules were missed
* @param scheduledAction Scheduled action referencing the backup
* @param db SQLiteDatabase to backup
* @return Number of times backup is executed. This should either be 1 or 0
*/
private static int executeBackup(ScheduledAction scheduledAction, SQLiteDatabase db) {
if (!shouldExecuteScheduledBackup(scheduledAction))
return 0;
ExportParams params = ExportParams.parseCsv(scheduledAction.getTag());
// HACK: the tag isn't updated with the new date, so set the correct by hand
params.setExportStartTime(new Timestamp(scheduledAction.getLastRunTime()));
Boolean result = false;
try {
//wait for async task to finish before we proceed (we are holding a wake lock)
result = new ExportAsyncTask(GnuCashApplication.getAppContext(), db).execute(params).get();
} catch (InterruptedException | ExecutionException e) {
Crashlytics.logException(e);
Log.e(LOG_TAG, e.getMessage());
}
if (!result) {
Log.i(LOG_TAG, "Backup/export did not occur. There might have been no"
+ " new transactions to export or it might have crashed");
// We don't know if something failed or there weren't transactions to export,
// so fall on the safe side and return as if something had failed.
// FIXME: Change ExportAsyncTask to distinguish between the two cases
return 0;
}
return 1;
}
/**
* Check if a scheduled action is due for execution
* @param scheduledAction Scheduled action
* @return {@code true} if execution is due, {@code false} otherwise
*/
@SuppressWarnings("RedundantIfStatement")
private static boolean shouldExecuteScheduledBackup(ScheduledAction scheduledAction) {
long now = System.currentTimeMillis();
long endTime = scheduledAction.getEndTime();
if (endTime > 0 && endTime < now)
return false;
if (scheduledAction.computeNextTimeBasedScheduledExecutionTime() > now)
return false;
return true;
}
/**
* Executes scheduled transactions which are to be added to the database.
* <p>If a schedule was missed, all the intervening transactions will be generated, even if
* the end time of the transaction was already reached</p>
* @param scheduledAction Scheduled action which references the transaction
* @param db SQLiteDatabase where the transactions are to be executed
* @return Number of transactions created as a result of this action
*/
private static int executeTransactions(ScheduledAction scheduledAction, SQLiteDatabase db) {
int executionCount = 0;
String actionUID = scheduledAction.getActionUID();
TransactionsDbAdapter transactionsDbAdapter = new TransactionsDbAdapter(db, new SplitsDbAdapter(db));
Transaction trxnTemplate;
try {
trxnTemplate = transactionsDbAdapter.getRecord(actionUID);
} catch (IllegalArgumentException ex){ //if the record could not be found, abort
Log.e(LOG_TAG, "Scheduled transaction with UID " + actionUID + " could not be found in the db with path " + db.getPath());
return executionCount;
}
long now = System.currentTimeMillis();
//if there is an end time in the past, we execute all schedules up to the end time.
//if the end time is in the future, we execute all schedules until now (current time)
//if there is no end time, we execute all schedules until now
long endTime = scheduledAction.getEndTime() > 0 ? Math.min(scheduledAction.getEndTime(), now) : now;
int totalPlannedExecutions = scheduledAction.getTotalPlannedExecutionCount();
List<Transaction> transactions = new ArrayList<>();
int previousExecutionCount = scheduledAction.getExecutionCount(); // We'll modify it
//we may be executing scheduled action significantly after scheduled time (depending on when Android fires the alarm)
//so compute the actual transaction time from pre-known values
long transactionTime = scheduledAction.computeNextCountBasedScheduledExecutionTime();
while (transactionTime <= endTime) {
Transaction recurringTrxn = new Transaction(trxnTemplate, true);
recurringTrxn.setTime(transactionTime);
transactions.add(recurringTrxn);
recurringTrxn.setScheduledActionUID(scheduledAction.getUID());
scheduledAction.setExecutionCount(++executionCount); //required for computingNextScheduledExecutionTime
if (totalPlannedExecutions > 0 && executionCount >= totalPlannedExecutions)
break; //if we hit the total planned executions set, then abort
transactionTime = scheduledAction.computeNextCountBasedScheduledExecutionTime();
}
transactionsDbAdapter.bulkAddRecords(transactions, DatabaseAdapter.UpdateMethod.insert);
// Be nice and restore the parameter's original state to avoid confusing the callers
scheduledAction.setExecutionCount(previousExecutionCount);
return executionCount;
}
}
| 12,542 | 46.692015 | 144 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/account/AccountFormFragment.java
|
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.account;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import org.gnucash.android.R;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.colorpicker.ColorPickerDialog;
import org.gnucash.android.ui.colorpicker.ColorPickerSwatch;
import org.gnucash.android.ui.colorpicker.ColorSquare;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.gnucash.android.util.CommoditiesCursorAdapter;
import org.gnucash.android.util.QualifiedAccountNameCursorAdapter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Fragment used for creating and editing accounts
* @author Ngewi Fet <[email protected]>
* @author Yongxin Wang <[email protected]>
*/
public class AccountFormFragment extends Fragment {
/**
* Tag for the color picker dialog fragment
*/
private static final String COLOR_PICKER_DIALOG_TAG = "color_picker_dialog";
/**
* EditText for the name of the account to be created/edited
*/
@BindView(R.id.input_account_name) EditText mNameEditText;
@BindView(R.id.name_text_input_layout) TextInputLayout mTextInputLayout;
/**
* Spinner for selecting the currency of the account
* Currencies listed are those specified by ISO 4217
*/
@BindView(R.id.input_currency_spinner) Spinner mCurrencySpinner;
/**
* Accounts database adapter
*/
private AccountsDbAdapter mAccountsDbAdapter;
/**
* GUID of the parent account
* This value is set to the parent account of the transaction being edited or
* the account in which a new sub-account is being created
*/
private String mParentAccountUID = null;
/**
* Account ID of the root account
*/
private long mRootAccountId = -1;
/**
* Account UID of the root account
*/
private String mRootAccountUID = null;
/**
* Reference to account object which will be created at end of dialog
*/
private Account mAccount = null;
/**
* Unique ID string of account being edited
*/
private String mAccountUID = null;
/**
* Cursor which will hold set of eligible parent accounts
*/
private Cursor mParentAccountCursor;
/**
* List of all descendant Account UIDs, if we are modifying an account
* null if creating a new account
*/
private List<String> mDescendantAccountUIDs;
/**
* SimpleCursorAdapter for the parent account spinner
* @see QualifiedAccountNameCursorAdapter
*/
private SimpleCursorAdapter mParentAccountCursorAdapter;
/**
* Spinner for parent account list
*/
@BindView(R.id.input_parent_account) Spinner mParentAccountSpinner;
/**
* Checkbox which activates the parent account spinner when selected
* Leaving this unchecked means it is a top-level root account
*/
@BindView(R.id.checkbox_parent_account) CheckBox mParentCheckBox;
/**
* Spinner for the account type
* @see org.gnucash.android.model.AccountType
*/
@BindView(R.id.input_account_type_spinner) Spinner mAccountTypeSpinner;
/**
* Checkbox for activating the default transfer account spinner
*/
@BindView(R.id.checkbox_default_transfer_account) CheckBox mDefaultTransferAccountCheckBox;
/**
* Spinner for selecting the default transfer account
*/
@BindView(R.id.input_default_transfer_account) Spinner mDefaultTransferAccountSpinner;
/**
* Account description input text view
*/
@BindView(R.id.input_account_description) EditText mDescriptionEditText;
/**
* Checkbox indicating if account is a placeholder account
*/
@BindView(R.id.checkbox_placeholder_account) CheckBox mPlaceholderCheckBox;
/**
* Cursor adapter which binds to the spinner for default transfer account
*/
private SimpleCursorAdapter mDefaultTransferAccountCursorAdapter;
/**
* Flag indicating if double entry transactions are enabled
*/
private boolean mUseDoubleEntry;
private int mSelectedColor = Account.DEFAULT_COLOR;
/**
* Trigger for color picker dialog
*/
@BindView(R.id.input_color_picker) ColorSquare mColorSquare;
private final ColorPickerSwatch.OnColorSelectedListener mColorSelectedListener =
new ColorPickerSwatch.OnColorSelectedListener() {
@Override
public void onColorSelected(int color) {
mColorSquare.setBackgroundColor(color);
mSelectedColor = color;
}
};
/**
* Default constructor
* Required, else the app crashes on screen rotation
*/
public AccountFormFragment() {
//nothing to see here, move along
}
/**
* Construct a new instance of the dialog
* @return New instance of the dialog fragment
*/
static public AccountFormFragment newInstance() {
AccountFormFragment f = new AccountFormFragment();
f.mAccountsDbAdapter = AccountsDbAdapter.getInstance();
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
SharedPreferences sharedPrefs = PreferenceActivity.getActiveBookSharedPreferences();
mUseDoubleEntry = sharedPrefs.getBoolean(getString(R.string.key_use_double_entry), true);
}
/**
* Inflates the dialog view and retrieves references to the dialog elements
*/
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_account_form, container, false);
ButterKnife.bind(this, view);
mNameEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//nothing to see here, move along
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//nothing to see here, move along
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().length() > 0) {
mTextInputLayout.setErrorEnabled(false);
}
}
});
mAccountTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
loadParentAccountList(getSelectedAccountType());
if (mParentAccountUID != null)
setParentAccountSelection(mAccountsDbAdapter.getID(mParentAccountUID));
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
//nothing to see here, move along
}
});
mParentAccountSpinner.setEnabled(false);
mParentCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mParentAccountSpinner.setEnabled(isChecked);
}
});
mDefaultTransferAccountSpinner.setEnabled(false);
mDefaultTransferAccountCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mDefaultTransferAccountSpinner.setEnabled(isChecked);
}
});
mColorSquare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showColorPickerDialog();
}
});
return view;
}
/**
* Initializes the values of the views in the dialog
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
CommoditiesCursorAdapter commoditiesAdapter = new CommoditiesCursorAdapter(
getActivity(), android.R.layout.simple_spinner_item);
commoditiesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mCurrencySpinner.setAdapter(commoditiesAdapter);
mAccountUID = getArguments().getString(UxArgument.SELECTED_ACCOUNT_UID);
ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (mAccountUID != null) {
mAccount = mAccountsDbAdapter.getRecord(mAccountUID);
supportActionBar.setTitle(R.string.title_edit_account);
} else {
supportActionBar.setTitle(R.string.title_create_account);
}
mRootAccountUID = mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID();
if (mRootAccountUID != null)
mRootAccountId = mAccountsDbAdapter.getID(mRootAccountUID);
//need to load the cursor adapters for the spinners before initializing the views
loadAccountTypesList();
loadDefaultTransferAccountList();
setDefaultTransferAccountInputsVisible(mUseDoubleEntry);
if (mAccount != null){
initializeViewsWithAccount(mAccount);
//do not immediately open the keyboard when editing an account
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
} else {
initializeViews();
}
}
/**
* Initialize view with the properties of <code>account</code>.
* This is applicable when editing an account
* @param account Account whose fields are used to populate the form
*/
private void initializeViewsWithAccount(Account account){
if (account == null)
throw new IllegalArgumentException("Account cannot be null");
loadParentAccountList(account.getAccountType());
mParentAccountUID = account.getParentUID();
if (mParentAccountUID == null) {
// null parent, set Parent as root
mParentAccountUID = mRootAccountUID;
}
if (mParentAccountUID != null) {
setParentAccountSelection(mAccountsDbAdapter.getID(mParentAccountUID));
}
String currencyCode = account.getCommodity().getCurrencyCode();
setSelectedCurrency(currencyCode);
if (mAccountsDbAdapter.getTransactionMaxSplitNum(mAccount.getUID()) > 1)
{
//TODO: Allow changing the currency and effecting the change for all transactions without any currency exchange (purely cosmetic change)
mCurrencySpinner.setEnabled(false);
}
mNameEditText.setText(account.getName());
mNameEditText.setSelection(mNameEditText.getText().length());
mDescriptionEditText.setText(account.getDescription());
if (mUseDoubleEntry) {
if (account.getDefaultTransferAccountUID() != null) {
long doubleDefaultAccountId = mAccountsDbAdapter.getID(account.getDefaultTransferAccountUID());
setDefaultTransferAccountSelection(doubleDefaultAccountId, true);
} else {
String currentAccountUID = account.getParentUID();
String rootAccountUID = mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID();
while (!currentAccountUID.equals(rootAccountUID)) {
long defaultTransferAccountID = mAccountsDbAdapter.getDefaultTransferAccountID(mAccountsDbAdapter.getID(currentAccountUID));
if (defaultTransferAccountID > 0) {
setDefaultTransferAccountSelection(defaultTransferAccountID, false);
break; //we found a parent with default transfer setting
}
currentAccountUID = mAccountsDbAdapter.getParentAccountUID(currentAccountUID);
}
}
}
mPlaceholderCheckBox.setChecked(account.isPlaceholderAccount());
mSelectedColor = account.getColor();
mColorSquare.setBackgroundColor(account.getColor());
setAccountTypeSelection(account.getAccountType());
}
/**
* Initialize views with defaults for new account
*/
private void initializeViews(){
setSelectedCurrency(Money.DEFAULT_CURRENCY_CODE);
mColorSquare.setBackgroundColor(Color.LTGRAY);
mParentAccountUID = getArguments().getString(UxArgument.PARENT_ACCOUNT_UID);
if (mParentAccountUID != null) {
AccountType parentAccountType = mAccountsDbAdapter.getAccountType(mParentAccountUID);
setAccountTypeSelection(parentAccountType);
loadParentAccountList(parentAccountType);
setParentAccountSelection(mAccountsDbAdapter.getID(mParentAccountUID));
}
}
/**
* Selects the corresponding account type in the spinner
* @param accountType AccountType to be set
*/
private void setAccountTypeSelection(AccountType accountType){
String[] accountTypeEntries = getResources().getStringArray(R.array.key_account_type_entries);
int accountTypeIndex = Arrays.asList(accountTypeEntries).indexOf(accountType.name());
mAccountTypeSpinner.setSelection(accountTypeIndex);
}
/**
* Toggles the visibility of the default transfer account input fields.
* This field is irrelevant for users who do not use double accounting
*/
private void setDefaultTransferAccountInputsVisible(boolean visible) {
final int visibility = visible ? View.VISIBLE : View.GONE;
final View view = getView();
assert view != null;
view.findViewById(R.id.layout_default_transfer_account).setVisibility(visibility);
view.findViewById(R.id.label_default_transfer_account).setVisibility(visibility);
}
/**
* Selects the currency with code <code>currencyCode</code> in the spinner
* @param currencyCode ISO 4217 currency code to be selected
*/
private void setSelectedCurrency(String currencyCode){
CommoditiesDbAdapter commodityDbAdapter = CommoditiesDbAdapter.getInstance();
long commodityId = commodityDbAdapter.getID(commodityDbAdapter.getCommodityUID(currencyCode));
int position = 0;
for (int i = 0; i < mCurrencySpinner.getCount(); i++) {
if (commodityId == mCurrencySpinner.getItemIdAtPosition(i)) {
position = i;
}
}
mCurrencySpinner.setSelection(position);
}
/**
* Selects the account with ID <code>parentAccountId</code> in the parent accounts spinner
* @param parentAccountId Record ID of parent account to be selected
*/
private void setParentAccountSelection(long parentAccountId){
if (parentAccountId <= 0 || parentAccountId == mRootAccountId) {
return;
}
for (int pos = 0; pos < mParentAccountCursorAdapter.getCount(); pos++) {
if (mParentAccountCursorAdapter.getItemId(pos) == parentAccountId){
mParentCheckBox.setChecked(true);
mParentAccountSpinner.setEnabled(true);
mParentAccountSpinner.setSelection(pos, true);
break;
}
}
}
/**
* Selects the account with ID <code>parentAccountId</code> in the default transfer account spinner
* @param defaultTransferAccountId Record ID of parent account to be selected
*/
private void setDefaultTransferAccountSelection(long defaultTransferAccountId, boolean enableTransferAccount) {
if (defaultTransferAccountId > 0) {
mDefaultTransferAccountCheckBox.setChecked(enableTransferAccount);
mDefaultTransferAccountSpinner.setEnabled(enableTransferAccount);
} else
return;
for (int pos = 0; pos < mDefaultTransferAccountCursorAdapter.getCount(); pos++) {
if (mDefaultTransferAccountCursorAdapter.getItemId(pos) == defaultTransferAccountId) {
mDefaultTransferAccountSpinner.setSelection(pos);
break;
}
}
}
/**
* Returns an array of colors used for accounts.
* The array returned has the actual color values and not the resource ID.
* @return Integer array of colors used for accounts
*/
private int[] getAccountColorOptions(){
Resources res = getResources();
TypedArray colorTypedArray = res.obtainTypedArray(R.array.account_colors);
int[] colorOptions = new int[colorTypedArray.length()];
for (int i = 0; i < colorTypedArray.length(); i++) {
int color = colorTypedArray.getColor(i, ContextCompat.getColor(getContext(),
R.color.title_green));
colorOptions[i] = color;
}
colorTypedArray.recycle();
return colorOptions;
}
/**
* Shows the color picker dialog
*/
private void showColorPickerDialog(){
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
int currentColor = Color.LTGRAY;
if (mAccount != null){
currentColor = mAccount.getColor();
}
ColorPickerDialog colorPickerDialogFragment = ColorPickerDialog.newInstance(
R.string.color_picker_default_title,
getAccountColorOptions(),
currentColor, 4, 12);
colorPickerDialogFragment.setOnColorSelectedListener(mColorSelectedListener);
colorPickerDialogFragment.show(fragmentManager, COLOR_PICKER_DIALOG_TAG);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.default_save_actions, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
saveAccount();
return true;
case android.R.id.home:
finishFragment();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Initializes the default transfer account spinner with eligible accounts
*/
private void loadDefaultTransferAccountList(){
String condition = DatabaseSchema.AccountEntry.COLUMN_UID + " != '" + mAccountUID + "' " //when creating a new account mAccountUID is null, so don't use whereArgs
+ " AND " + DatabaseSchema.AccountEntry.COLUMN_PLACEHOLDER + "=0"
+ " AND " + DatabaseSchema.AccountEntry.COLUMN_HIDDEN + "=0"
+ " AND " + DatabaseSchema.AccountEntry.COLUMN_TYPE + " != ?";
Cursor defaultTransferAccountCursor = mAccountsDbAdapter.fetchAccountsOrderedByFullName(condition,
new String[]{AccountType.ROOT.name()});
if (mDefaultTransferAccountSpinner.getCount() <= 0) {
setDefaultTransferAccountInputsVisible(false);
}
mDefaultTransferAccountCursorAdapter = new QualifiedAccountNameCursorAdapter(getActivity(),
defaultTransferAccountCursor);
mDefaultTransferAccountSpinner.setAdapter(mDefaultTransferAccountCursorAdapter);
}
/**
* Loads the list of possible accounts which can be set as a parent account and initializes the spinner.
* The allowed parent accounts depends on the account type
* @param accountType AccountType of account whose allowed parent list is to be loaded
*/
private void loadParentAccountList(AccountType accountType){
String condition = DatabaseSchema.SplitEntry.COLUMN_TYPE + " IN ("
+ getAllowedParentAccountTypes(accountType) + ") AND " + DatabaseSchema.AccountEntry.COLUMN_HIDDEN + "!=1 ";
if (mAccount != null){ //if editing an account
mDescendantAccountUIDs = mAccountsDbAdapter.getDescendantAccountUIDs(mAccount.getUID(), null, null);
String rootAccountUID = mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID();
List<String> descendantAccountUIDs = new ArrayList<>(mDescendantAccountUIDs);
if (rootAccountUID != null)
descendantAccountUIDs.add(rootAccountUID);
// limit cyclic account hierarchies.
condition += " AND (" + DatabaseSchema.AccountEntry.COLUMN_UID + " NOT IN ( '"
+ TextUtils.join("','", descendantAccountUIDs) + "','" + mAccountUID + "' ) )";
}
//if we are reloading the list, close the previous cursor first
if (mParentAccountCursor != null)
mParentAccountCursor.close();
mParentAccountCursor = mAccountsDbAdapter.fetchAccountsOrderedByFullName(condition, null);
final View view = getView();
assert view != null;
if (mParentAccountCursor.getCount() <= 0){
mParentCheckBox.setChecked(false); //disable before hiding, else we can still read it when saving
view.findViewById(R.id.layout_parent_account).setVisibility(View.GONE);
view.findViewById(R.id.label_parent_account).setVisibility(View.GONE);
} else {
view.findViewById(R.id.layout_parent_account).setVisibility(View.VISIBLE);
view.findViewById(R.id.label_parent_account).setVisibility(View.VISIBLE);
}
mParentAccountCursorAdapter = new QualifiedAccountNameCursorAdapter(
getActivity(), mParentAccountCursor);
mParentAccountSpinner.setAdapter(mParentAccountCursorAdapter);
}
/**
* Returns a comma separated list of account types which can be parent accounts for the specified <code>type</code>.
* The strings in the list are the {@link org.gnucash.android.model.AccountType#name()}s of the different types.
* @param type {@link org.gnucash.android.model.AccountType}
* @return String comma separated list of account types
*/
private String getAllowedParentAccountTypes(AccountType type) {
switch (type) {
case EQUITY:
return "'" + AccountType.EQUITY.name() + "'";
case INCOME:
case EXPENSE:
return "'" + AccountType.EXPENSE.name() + "', '" + AccountType.INCOME.name() + "'";
case CASH:
case BANK:
case CREDIT:
case ASSET:
case LIABILITY:
case PAYABLE:
case RECEIVABLE:
case CURRENCY:
case STOCK:
case MUTUAL: {
List<String> accountTypeStrings = getAccountTypeStringList();
accountTypeStrings.remove(AccountType.EQUITY.name());
accountTypeStrings.remove(AccountType.EXPENSE.name());
accountTypeStrings.remove(AccountType.INCOME.name());
accountTypeStrings.remove(AccountType.ROOT.name());
return "'" + TextUtils.join("','", accountTypeStrings) + "'";
}
case TRADING:
return "'" + AccountType.TRADING.name() + "'";
case ROOT:
default:
return Arrays.toString(AccountType.values()).replaceAll("\\[|]", "");
}
}
/**
* Returns a list of all the available {@link org.gnucash.android.model.AccountType}s as strings
* @return String list of all account types
*/
private List<String> getAccountTypeStringList(){
String[] accountTypes = Arrays.toString(AccountType.values()).replaceAll("\\[|]", "").split(",");
List<String> accountTypesList = new ArrayList<>();
for (String accountType : accountTypes) {
accountTypesList.add(accountType.trim());
}
return accountTypesList;
}
/**
* Loads the list of account types into the account type selector spinner
*/
private void loadAccountTypesList(){
String[] accountTypes = getResources().getStringArray(R.array.account_type_entry_values);
ArrayAdapter<String> accountTypesAdapter = new ArrayAdapter<>(
getActivity(), android.R.layout.simple_list_item_1, accountTypes);
accountTypesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mAccountTypeSpinner.setAdapter(accountTypesAdapter);
}
/**
* Finishes the fragment appropriately.
* Depends on how the fragment was loaded, it might have a backstack or not
*/
private void finishFragment() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mNameEditText.getWindowToken(), 0);
final String action = getActivity().getIntent().getAction();
if (action != null && action.equals(Intent.ACTION_INSERT_OR_EDIT)){
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
} else {
getActivity().getSupportFragmentManager().popBackStack();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mParentAccountCursor != null)
mParentAccountCursor.close();
if (mDefaultTransferAccountCursorAdapter != null) {
mDefaultTransferAccountCursorAdapter.getCursor().close();
}
}
/**
* Reads the fields from the account form and saves as a new account
*/
private void saveAccount() {
Log.i("AccountFormFragment", "Saving account");
if (mAccountsDbAdapter == null)
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
// accounts to update, in case we're updating full names of a sub account tree
ArrayList<Account> accountsToUpdate = new ArrayList<>();
boolean nameChanged = false;
if (mAccount == null){
String name = getEnteredName();
if (name.length() == 0){
mTextInputLayout.setErrorEnabled(true);
mTextInputLayout.setError(getString(R.string.toast_no_account_name_entered));
return;
}
mAccount = new Account(getEnteredName());
mAccountsDbAdapter.addRecord(mAccount, DatabaseAdapter.UpdateMethod.insert); //new account, insert it
}
else {
nameChanged = !mAccount.getName().equals(getEnteredName());
mAccount.setName(getEnteredName());
}
long commodityId = mCurrencySpinner.getSelectedItemId();
Commodity commodity = CommoditiesDbAdapter.getInstance().getRecord(commodityId);
mAccount.setCommodity(commodity);
AccountType selectedAccountType = getSelectedAccountType();
mAccount.setAccountType(selectedAccountType);
mAccount.setDescription(mDescriptionEditText.getText().toString());
mAccount.setPlaceHolderFlag(mPlaceholderCheckBox.isChecked());
mAccount.setColor(mSelectedColor);
long newParentAccountId;
String newParentAccountUID;
if (mParentCheckBox.isChecked()) {
newParentAccountId = mParentAccountSpinner.getSelectedItemId();
newParentAccountUID = mAccountsDbAdapter.getUID(newParentAccountId);
mAccount.setParentUID(newParentAccountUID);
} else {
//need to do this explicitly in case user removes parent account
newParentAccountUID = mRootAccountUID;
newParentAccountId = mRootAccountId;
}
mAccount.setParentUID(newParentAccountUID);
if (mDefaultTransferAccountCheckBox.isChecked()
&& mDefaultTransferAccountSpinner.getSelectedItemId() != Spinner.INVALID_ROW_ID){
long id = mDefaultTransferAccountSpinner.getSelectedItemId();
mAccount.setDefaultTransferAccountUID(mAccountsDbAdapter.getUID(id));
} else {
//explicitly set in case of removal of default account
mAccount.setDefaultTransferAccountUID(null);
}
long parentAccountId = mParentAccountUID == null ? -1 : mAccountsDbAdapter.getID(mParentAccountUID);
// update full names
if (nameChanged || mDescendantAccountUIDs == null || newParentAccountId != parentAccountId) {
// current account name changed or new Account or parent account changed
String newAccountFullName;
if (newParentAccountId == mRootAccountId){
newAccountFullName = mAccount.getName();
}
else {
newAccountFullName = mAccountsDbAdapter.getAccountFullName(newParentAccountUID) +
AccountsDbAdapter.ACCOUNT_NAME_SEPARATOR + mAccount.getName();
}
mAccount.setFullName(newAccountFullName);
if (mDescendantAccountUIDs != null) {
// modifying existing account, e.t. name changed and/or parent changed
if ((nameChanged || parentAccountId != newParentAccountId) && mDescendantAccountUIDs.size() > 0) {
// parent change, update all full names of descent accounts
accountsToUpdate.addAll(mAccountsDbAdapter.getSimpleAccountList(
DatabaseSchema.AccountEntry.COLUMN_UID + " IN ('" +
TextUtils.join("','", mDescendantAccountUIDs) + "')", null, null
));
}
HashMap<String, Account> mapAccount = new HashMap<>();
for (Account acct : accountsToUpdate) mapAccount.put(acct.getUID(), acct);
for (String uid: mDescendantAccountUIDs) {
// mAccountsDbAdapter.getDescendantAccountUIDs() will ensure a parent-child order
Account acct = mapAccount.get(uid);
// mAccount cannot be root, so acct here cannot be top level account.
if (mAccount.getUID().equals(acct.getParentUID())) {
acct.setFullName(mAccount.getFullName() + AccountsDbAdapter.ACCOUNT_NAME_SEPARATOR + acct.getName());
}
else {
acct.setFullName(
mapAccount.get(acct.getParentUID()).getFullName() +
AccountsDbAdapter.ACCOUNT_NAME_SEPARATOR +
acct.getName()
);
}
}
}
}
accountsToUpdate.add(mAccount);
// bulk update, will not update transactions
mAccountsDbAdapter.bulkAddRecords(accountsToUpdate, DatabaseAdapter.UpdateMethod.update);
finishFragment();
}
/**
* Returns the currently selected account type in the spinner
* @return {@link org.gnucash.android.model.AccountType} currently selected
*/
private AccountType getSelectedAccountType() {
int selectedAccountTypeIndex = mAccountTypeSpinner.getSelectedItemPosition();
String[] accountTypeEntries = getResources().getStringArray(R.array.key_account_type_entries);
return AccountType.valueOf(accountTypeEntries[selectedAccountTypeIndex]);
}
/**
* Retrieves the name of the account which has been entered in the EditText
* @return Name of the account which has been entered in the EditText
*/
private String getEnteredName(){
return mNameEditText.getText().toString().trim();
}
}
| 33,696 | 38.457845 | 170 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/account/AccountsActivity.java
|
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.account;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.PreferenceManager;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.kobakei.ratethisapp.RateThisApp;
import org.gnucash.android.BuildConfig;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.importer.ImportAsyncTask;
import org.gnucash.android.ui.common.BaseDrawerActivity;
import org.gnucash.android.ui.common.FormActivity;
import org.gnucash.android.ui.common.Refreshable;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import org.gnucash.android.ui.util.TaskDelegate;
import org.gnucash.android.ui.wizard.FirstRunWizardActivity;
import org.gnucash.android.util.BackupManager;
import butterknife.BindView;
/**
* Manages actions related to accounts, displaying, exporting and creating new accounts
* The various actions are implemented as Fragments which are then added to this activity
*
* @author Ngewi Fet <[email protected]>
* @author Oleksandr Tyshkovets <[email protected]>
*/
public class AccountsActivity extends BaseDrawerActivity implements OnAccountClickedListener {
/**
* Request code for GnuCash account structure file to import
*/
public static final int REQUEST_PICK_ACCOUNTS_FILE = 0x1;
/**
* Request code for opening the account to edit
*/
public static final int REQUEST_EDIT_ACCOUNT = 0x10;
/**
* Logging tag
*/
protected static final String LOG_TAG = "AccountsActivity";
/**
* Number of pages to show
*/
private static final int DEFAULT_NUM_PAGES = 3;
/**
* Index for the recent accounts tab
*/
public static final int INDEX_RECENT_ACCOUNTS_FRAGMENT = 0;
/**
* Index of the top level (all) accounts tab
*/
public static final int INDEX_TOP_LEVEL_ACCOUNTS_FRAGMENT = 1;
/**
* Index of the favorite accounts tab
*/
public static final int INDEX_FAVORITE_ACCOUNTS_FRAGMENT = 2;
/**
* Used to save the index of the last open tab and restore the pager to that index
*/
public static final String LAST_OPEN_TAB_INDEX = "last_open_tab";
/**
* Key for putting argument for tab into bundle arguments
*/
public static final String EXTRA_TAB_INDEX = "org.gnucash.android.extra.TAB_INDEX";
/**
* Map containing fragments for the different tabs
*/
private SparseArray<Refreshable> mFragmentPageReferenceMap = new SparseArray<>();
/**
* ViewPager which manages the different tabs
*/
@BindView(R.id.pager) ViewPager mViewPager;
@BindView(R.id.fab_create_account) FloatingActionButton mFloatingActionButton;
@BindView(R.id.coordinatorLayout) CoordinatorLayout mCoordinatorLayout;
/**
* Configuration for rating the app
*/
public static RateThisApp.Config rateAppConfig = new RateThisApp.Config(14, 100);
private AccountViewPagerAdapter mPagerAdapter;
/**
* Adapter for managing the sub-account and transaction fragment pages in the accounts view
*/
private class AccountViewPagerAdapter extends FragmentPagerAdapter {
public AccountViewPagerAdapter(FragmentManager fm){
super(fm);
}
@Override
public Fragment getItem(int i) {
AccountsListFragment currentFragment = (AccountsListFragment) mFragmentPageReferenceMap.get(i);
if (currentFragment == null) {
switch (i) {
case INDEX_RECENT_ACCOUNTS_FRAGMENT:
currentFragment = AccountsListFragment.newInstance(AccountsListFragment.DisplayMode.RECENT);
break;
case INDEX_FAVORITE_ACCOUNTS_FRAGMENT:
currentFragment = AccountsListFragment.newInstance(AccountsListFragment.DisplayMode.FAVORITES);
break;
case INDEX_TOP_LEVEL_ACCOUNTS_FRAGMENT:
default:
currentFragment = AccountsListFragment.newInstance(AccountsListFragment.DisplayMode.TOP_LEVEL);
break;
}
mFragmentPageReferenceMap.put(i, currentFragment);
}
return currentFragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mFragmentPageReferenceMap.remove(position);
}
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case INDEX_RECENT_ACCOUNTS_FRAGMENT:
return getString(R.string.title_recent_accounts);
case INDEX_FAVORITE_ACCOUNTS_FRAGMENT:
return getString(R.string.title_favorite_accounts);
case INDEX_TOP_LEVEL_ACCOUNTS_FRAGMENT:
default:
return getString(R.string.title_all_accounts);
}
}
@Override
public int getCount() {
return DEFAULT_NUM_PAGES;
}
}
public AccountsListFragment getCurrentAccountListFragment(){
int index = mViewPager.getCurrentItem();
Fragment fragment = (Fragment) mFragmentPageReferenceMap.get(index);
if (fragment == null)
fragment = mPagerAdapter.getItem(index);
return (AccountsListFragment) fragment;
}
@Override
public int getContentView() {
return R.layout.activity_accounts;
}
@Override
public int getTitleRes() {
return R.string.title_accounts;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
handleOpenFileIntent(intent);
init();
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText(R.string.title_recent_accounts));
tabLayout.addTab(tabLayout.newTab().setText(R.string.title_all_accounts));
tabLayout.addTab(tabLayout.newTab().setText(R.string.title_favorite_accounts));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//show the simple accounts list
mPagerAdapter = new AccountViewPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
//nothing to see here, move along
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
//nothing to see here, move along
}
});
setCurrentTab();
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent addAccountIntent = new Intent(AccountsActivity.this, FormActivity.class);
addAccountIntent.setAction(Intent.ACTION_INSERT_OR_EDIT);
addAccountIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.ACCOUNT.name());
startActivityForResult(addAccountIntent, AccountsActivity.REQUEST_EDIT_ACCOUNT);
}
});
}
@Override
protected void onStart() {
super.onStart();
if (BuildConfig.CAN_REQUEST_RATING) {
RateThisApp.init(rateAppConfig);
RateThisApp.onStart(this);
RateThisApp.showRateDialogIfNeeded(this);
}
}
/**
* Handles the case where another application has selected to open a (.gnucash or .gnca) file with this app
* @param intent Intent containing the data to be imported
*/
private void handleOpenFileIntent(Intent intent) {
//when someone launches the app to view a (.gnucash or .gnca) file
Uri data = intent.getData();
if (data != null){
BackupManager.backupActiveBook();
intent.setData(null);
new ImportAsyncTask(this).execute(data);
removeFirstRunFlag();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
setCurrentTab();
int index = mViewPager.getCurrentItem();
Fragment fragment = (Fragment) mFragmentPageReferenceMap.get(index);
if (fragment != null)
((Refreshable)fragment).refresh();
handleOpenFileIntent(intent);
}
/**
* Sets the current tab in the ViewPager
*/
public void setCurrentTab(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int lastTabIndex = preferences.getInt(LAST_OPEN_TAB_INDEX, INDEX_TOP_LEVEL_ACCOUNTS_FRAGMENT);
int index = getIntent().getIntExtra(EXTRA_TAB_INDEX, lastTabIndex);
mViewPager.setCurrentItem(index);
}
/**
* Loads default setting for currency and performs app first-run initialization.
* <p>Also handles displaying the What's New dialog</p>
*/
private void init() {
PreferenceManager.setDefaultValues(this, BooksDbAdapter.getInstance().getActiveBookUID(),
Context.MODE_PRIVATE, R.xml.fragment_transaction_preferences, true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean firstRun = prefs.getBoolean(getString(R.string.key_first_run), true);
if (firstRun){
startActivity(new Intent(GnuCashApplication.getAppContext(), FirstRunWizardActivity.class));
//default to using double entry and save the preference explicitly
prefs.edit().putBoolean(getString(R.string.key_use_double_entry), true).apply();
finish();
return;
}
if (hasNewFeatures()){
showWhatsNewDialog(this);
}
GnuCashApplication.startScheduledActionExecutionService(this);
BackupManager.schedulePeriodicBackups(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().putInt(LAST_OPEN_TAB_INDEX, mViewPager.getCurrentItem()).apply();
}
/**
* Checks if the minor version has been increased and displays the What's New dialog box.
* This is the minor version as per semantic versioning.
* @return <code>true</code> if the minor version has been increased, <code>false</code> otherwise.
*/
private boolean hasNewFeatures(){
String minorVersion = getResources().getString(R.string.app_minor_version);
int currentMinor = Integer.parseInt(minorVersion);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int previousMinor = prefs.getInt(getString(R.string.key_previous_minor_version), 0);
if (currentMinor > previousMinor){
Editor editor = prefs.edit();
editor.putInt(getString(R.string.key_previous_minor_version), currentMinor);
editor.apply();
return true;
}
return false;
}
/**
* Show dialog with new features for this version
*/
public static AlertDialog showWhatsNewDialog(Context context){
Resources resources = context.getResources();
StringBuilder releaseTitle = new StringBuilder(resources.getString(R.string.title_whats_new));
PackageInfo packageInfo;
try {
packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
releaseTitle.append(" - v").append(packageInfo.versionName);
} catch (NameNotFoundException e) {
Crashlytics.logException(e);
Log.e(LOG_TAG, "Error displaying 'Whats new' dialog");
}
return new AlertDialog.Builder(context)
.setTitle(releaseTitle.toString())
.setMessage(R.string.whats_new)
.setPositiveButton(R.string.label_dismiss, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
/**
* Displays the dialog for exporting transactions
*/
public static void openExportFragment(AppCompatActivity activity) {
Intent intent = new Intent(activity, FormActivity.class);
intent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.EXPORT.name());
activity.startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.global_actions, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
return super.onOptionsItemSelected(item);
default:
return false;
}
}
/**
* Creates default accounts with the specified currency code.
* If the currency parameter is null, then locale currency will be used if available
*
* @param currencyCode Currency code to assign to the imported accounts
* @param activity Activity for providing context and displaying dialogs
*/
public static void createDefaultAccounts(final String currencyCode, final Activity activity) {
TaskDelegate delegate = null;
if (currencyCode != null) {
delegate = new TaskDelegate() {
@Override
public void onTaskComplete() {
AccountsDbAdapter.getInstance().updateAllAccounts(DatabaseSchema.AccountEntry.COLUMN_CURRENCY, currencyCode);
GnuCashApplication.setDefaultCurrencyCode(currencyCode);
}
};
}
Uri uri = Uri.parse("android.resource://" + BuildConfig.APPLICATION_ID + "/" + R.raw.default_accounts);
new ImportAsyncTask(activity, delegate).execute(uri);
}
/**
* Starts Intent chooser for selecting a GnuCash accounts file to import.
* <p>The {@code activity} is responsible for the actual import of the file and can do so by calling {@link #importXmlFileFromIntent(Activity, Intent, TaskDelegate)}<br>
* The calling class should respond to the request code {@link AccountsActivity#REQUEST_PICK_ACCOUNTS_FILE} in its {@link #onActivityResult(int, int, Intent)} method</p>
* @param activity Activity starting the request and will also handle the response
* @see #importXmlFileFromIntent(Activity, Intent, TaskDelegate)
*/
public static void startXmlFileChooser(Activity activity) {
Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickIntent.setType("*/*");
Intent chooser = Intent.createChooser(pickIntent, "Select GnuCash account file"); //todo internationalize string
try {
activity.startActivityForResult(chooser, REQUEST_PICK_ACCOUNTS_FILE);
} catch (ActivityNotFoundException ex){
Crashlytics.log("No file manager for selecting files available");
Crashlytics.logException(ex);
Toast.makeText(activity, R.string.toast_install_file_manager, Toast.LENGTH_LONG).show();
}
}
/**
* Overloaded method.
* Starts chooser for selecting a GnuCash account file to import
* @param fragment Fragment creating the chooser and which will also handle the result
* @see #startXmlFileChooser(Activity)
*/
public static void startXmlFileChooser(Fragment fragment) {
Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickIntent.setType("*/*");
Intent chooser = Intent.createChooser(pickIntent, "Select GnuCash account file"); //todo internationalize string
try {
fragment.startActivityForResult(chooser, REQUEST_PICK_ACCOUNTS_FILE);
} catch (ActivityNotFoundException ex){
Crashlytics.log("No file manager for selecting files available");
Crashlytics.logException(ex);
Toast.makeText(fragment.getActivity(), R.string.toast_install_file_manager, Toast.LENGTH_LONG).show();
}
}
/**
* Reads and XML file from an intent and imports it into the database
* <p>This method is usually called in response to {@link AccountsActivity#startXmlFileChooser(Activity)}</p>
* @param context Activity context
* @param data Intent data containing the XML uri
* @param onFinishTask Task to be executed when import is complete
*/
public static void importXmlFileFromIntent(Activity context, Intent data, TaskDelegate onFinishTask) {
BackupManager.backupActiveBook();
new ImportAsyncTask(context, onFinishTask).execute(data.getData());
}
/**
* Starts the AccountsActivity and clears the activity stack
* @param context Application context
*/
public static void start(Context context){
Intent accountsActivityIntent = new Intent(context, AccountsActivity.class);
accountsActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
accountsActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(accountsActivityIntent);
}
@Override
public void accountSelected(String accountUID) {
Intent intent = new Intent(this, TransactionsActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID);
startActivity(intent);
}
/**
* Removes the flag indicating that the app is being run for the first time.
* This is called every time the app is started because the next time won't be the first time
*/
public static void removeFirstRunFlag(){
Context context = GnuCashApplication.getAppContext();
Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean(context.getString(R.string.key_first_run), false);
editor.commit();
}
}
| 20,503 | 37.111524 | 173 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/account/AccountsListFragment.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.account;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseCursorLoader;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BudgetsDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Budget;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.common.FormActivity;
import org.gnucash.android.ui.common.Refreshable;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.util.AccountBalanceTask;
import org.gnucash.android.ui.util.CursorRecyclerAdapter;
import org.gnucash.android.ui.util.widget.EmptyRecyclerView;
import org.gnucash.android.util.BackupManager;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Fragment for displaying the list of accounts in the database
*
* @author Ngewi Fet <[email protected]>
*/
public class AccountsListFragment extends Fragment implements
Refreshable,
LoaderCallbacks<Cursor>,
android.support.v7.widget.SearchView.OnQueryTextListener,
android.support.v7.widget.SearchView.OnCloseListener {
AccountRecyclerAdapter mAccountRecyclerAdapter;
@BindView(R.id.account_recycler_view) EmptyRecyclerView mRecyclerView;
@BindView(R.id.empty_view) TextView mEmptyTextView;
/**
* Describes the kinds of accounts that should be loaded in the accounts list.
* This enhances reuse of the accounts list fragment
*/
public enum DisplayMode {
TOP_LEVEL, RECENT, FAVORITES
}
/**
* Field indicating which kind of accounts to load.
* Default value is {@link DisplayMode#TOP_LEVEL}
*/
private DisplayMode mDisplayMode = DisplayMode.TOP_LEVEL;
/**
* Logging tag
*/
protected static final String TAG = "AccountsListFragment";
/**
* Tag to save {@link AccountsListFragment#mDisplayMode} to fragment state
*/
private static final String STATE_DISPLAY_MODE = "mDisplayMode";
/**
* Database adapter for loading Account records from the database
*/
private AccountsDbAdapter mAccountsDbAdapter;
/**
* Listener to be notified when an account is clicked
*/
private OnAccountClickedListener mAccountSelectedListener;
/**
* GUID of the account whose children will be loaded in the list fragment.
* If no parent account is specified, then all top-level accounts are loaded.
*/
private String mParentAccountUID = null;
/**
* Filter for which accounts should be displayed. Used by search interface
*/
private String mCurrentFilter;
/**
* Search view for searching accounts
*/
private android.support.v7.widget.SearchView mSearchView;
public static AccountsListFragment newInstance(DisplayMode displayMode){
AccountsListFragment fragment = new AccountsListFragment();
fragment.mDisplayMode = displayMode;
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_accounts_list, container,
false);
ButterKnife.bind(this, v);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setEmptyView(mEmptyTextView);
switch (mDisplayMode){
case TOP_LEVEL:
mEmptyTextView.setText(R.string.label_no_accounts);
break;
case RECENT:
mEmptyTextView.setText(R.string.label_no_recent_accounts);
break;
case FAVORITES:
mEmptyTextView.setText(R.string.label_no_favorite_accounts);
break;
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
} else {
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
}
return v;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null)
mParentAccountUID = args.getString(UxArgument.PARENT_ACCOUNT_UID);
if (savedInstanceState != null)
mDisplayMode = (DisplayMode) savedInstanceState.getSerializable(STATE_DISPLAY_MODE);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBar actionbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
actionbar.setTitle(R.string.title_accounts);
actionbar.setDisplayHomeAsUpEnabled(true);
setHasOptionsMenu(true);
// specify an adapter (see also next example)
mAccountRecyclerAdapter = new AccountRecyclerAdapter(null);
mRecyclerView.setAdapter(mAccountRecyclerAdapter);
}
@Override
public void onStart() {
super.onStart();
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
}
@Override
public void onResume() {
super.onResume();
refresh();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mAccountSelectedListener = (OnAccountClickedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnAccountSelectedListener");
}
}
public void onListItemClick(String accountUID) {
mAccountSelectedListener.accountSelected(accountUID);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED)
return;
refresh();
}
/**
* Delete the account with record ID <code>rowId</code>
* It shows the delete confirmation dialog if the account has transactions,
* else deletes the account immediately
*
* @param rowId The record ID of the account
*/
public void tryDeleteAccount(long rowId) {
Account acc = mAccountsDbAdapter.getRecord(rowId);
if (acc.getTransactionCount() > 0 || mAccountsDbAdapter.getSubAccountCount(acc.getUID()) > 0) {
showConfirmationDialog(rowId);
} else {
BackupManager.backupActiveBook();
// Avoid calling AccountsDbAdapter.deleteRecord(long). See #654
String uid = mAccountsDbAdapter.getUID(rowId);
mAccountsDbAdapter.deleteRecord(uid);
refresh();
}
}
/**
* Shows the delete confirmation dialog
*
* @param id Record ID of account to be deleted after confirmation
*/
public void showConfirmationDialog(long id) {
DeleteAccountDialogFragment alertFragment =
DeleteAccountDialogFragment.newInstance(mAccountsDbAdapter.getUID(id));
alertFragment.setTargetFragment(this, 0);
alertFragment.show(getActivity().getSupportFragmentManager(), "delete_confirmation_dialog");
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (mParentAccountUID != null)
inflater.inflate(R.menu.sub_account_actions, menu);
else {
inflater.inflate(R.menu.account_actions, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) GnuCashApplication.getAppContext().getSystemService(Context.SEARCH_SERVICE);
mSearchView = (android.support.v7.widget.SearchView)
MenuItemCompat.getActionView(menu.findItem(R.id.menu_search));
if (mSearchView == null)
return;
mSearchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnCloseListener(this);
}
}
@Override
/**
* Refresh the account list as a sublist of another account
* @param parentAccountUID GUID of the parent account
*/
public void refresh(String parentAccountUID) {
getArguments().putString(UxArgument.PARENT_ACCOUNT_UID, parentAccountUID);
refresh();
}
/**
* Refreshes the list by restarting the {@link DatabaseCursorLoader} associated
* with the ListView
*/
@Override
public void refresh() {
getLoaderManager().restartLoader(0, null, this);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_DISPLAY_MODE, mDisplayMode);
}
/**
* Closes any open database adapters used by the list
*/
@Override
public void onDestroy() {
super.onDestroy();
if (mAccountRecyclerAdapter != null)
mAccountRecyclerAdapter.swapCursor(null);
}
/**
* Opens a new activity for creating or editing an account.
* If the <code>accountId</code> < 1, then create else edit the account.
* @param accountId Long record ID of account to be edited. Pass 0 to create a new account.
*/
public void openCreateOrEditActivity(long accountId){
Intent editAccountIntent = new Intent(AccountsListFragment.this.getActivity(), FormActivity.class);
editAccountIntent.setAction(Intent.ACTION_INSERT_OR_EDIT);
editAccountIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, mAccountsDbAdapter.getUID(accountId));
editAccountIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.ACCOUNT.name());
startActivityForResult(editAccountIntent, AccountsActivity.REQUEST_EDIT_ACCOUNT);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "Creating the accounts loader");
Bundle arguments = getArguments();
String accountUID = arguments == null ? null : arguments.getString(UxArgument.PARENT_ACCOUNT_UID);
if (mCurrentFilter != null){
return new AccountsCursorLoader(getActivity(), mCurrentFilter);
} else {
return new AccountsCursorLoader(this.getActivity(), accountUID, mDisplayMode);
}
}
@Override
public void onLoadFinished(Loader<Cursor> loaderCursor, Cursor cursor) {
Log.d(TAG, "Accounts loader finished. Swapping in cursor");
mAccountRecyclerAdapter.swapCursor(cursor);
mAccountRecyclerAdapter.notifyDataSetChanged();
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
Log.d(TAG, "Resetting the accounts loader");
mAccountRecyclerAdapter.swapCursor(null);
}
@Override
public boolean onQueryTextSubmit(String query) {
//nothing to see here, move along
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
if (mCurrentFilter == null && newFilter == null) {
return true;
}
if (mCurrentFilter != null && mCurrentFilter.equals(newFilter)) {
return true;
}
mCurrentFilter = newFilter;
getLoaderManager().restartLoader(0, null, this);
return true;
}
@Override
public boolean onClose() {
if (!TextUtils.isEmpty(mSearchView.getQuery())) {
mSearchView.setQuery(null, true);
}
return true;
}
/**
* Extends {@link DatabaseCursorLoader} for loading of {@link Account} from the
* database asynchronously.
* <p>By default it loads only top-level accounts (accounts which have no parent or have GnuCash ROOT account as parent.
* By submitting a parent account ID in the constructor parameter, it will load child accounts of that parent.</p>
* <p>Class must be static because the Android loader framework requires it to be so</p>
* @author Ngewi Fet <[email protected]>
*/
private static final class AccountsCursorLoader extends DatabaseCursorLoader {
private String mParentAccountUID = null;
private String mFilter;
private DisplayMode mDisplayMode = DisplayMode.TOP_LEVEL;
/**
* Initializes the loader to load accounts from the database.
* If the <code>parentAccountId <= 0</code> then only top-level accounts are loaded.
* Else only the child accounts of the <code>parentAccountId</code> will be loaded
* @param context Application context
* @param parentAccountUID GUID of the parent account
*/
public AccountsCursorLoader(Context context, String parentAccountUID, DisplayMode displayMode) {
super(context);
this.mParentAccountUID = parentAccountUID;
this.mDisplayMode = displayMode;
}
/**
* Initializes the loader with a filter for account names.
* Only accounts whose name match the filter will be loaded.
* @param context Application context
* @param filter Account name filter string
*/
public AccountsCursorLoader(Context context, String filter){
super(context);
mFilter = filter;
}
@Override
public Cursor loadInBackground() {
mDatabaseAdapter = AccountsDbAdapter.getInstance();
Cursor cursor;
if (mFilter != null){
cursor = ((AccountsDbAdapter)mDatabaseAdapter)
.fetchAccounts(DatabaseSchema.AccountEntry.COLUMN_HIDDEN + "= 0 AND "
+ DatabaseSchema.AccountEntry.COLUMN_NAME + " LIKE '%" + mFilter + "%'",
null, null);
} else {
if (mParentAccountUID != null && mParentAccountUID.length() > 0)
cursor = ((AccountsDbAdapter) mDatabaseAdapter).fetchSubAccounts(mParentAccountUID);
else {
switch (this.mDisplayMode){
case RECENT:
cursor = ((AccountsDbAdapter) mDatabaseAdapter).fetchRecentAccounts(10);
break;
case FAVORITES:
cursor = ((AccountsDbAdapter) mDatabaseAdapter).fetchFavoriteAccounts();
break;
case TOP_LEVEL:
default:
cursor = ((AccountsDbAdapter) mDatabaseAdapter).fetchTopLevelAccounts();
break;
}
}
}
if (cursor != null)
registerContentObserver(cursor);
return cursor;
}
}
class AccountRecyclerAdapter extends CursorRecyclerAdapter<AccountRecyclerAdapter.AccountViewHolder> {
public AccountRecyclerAdapter(Cursor cursor){
super(cursor);
}
@Override
public AccountViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_account, parent, false);
return new AccountViewHolder(v);
}
@Override
public void onBindViewHolderCursor(final AccountViewHolder holder, final Cursor cursor) {
final String accountUID = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_UID));
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
holder.accoundId = mAccountsDbAdapter.getID(accountUID);
holder.accountName.setText(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_NAME)));
int subAccountCount = mAccountsDbAdapter.getSubAccountCount(accountUID);
if (subAccountCount > 0) {
holder.description.setVisibility(View.VISIBLE);
String text = getResources().getQuantityString(R.plurals.label_sub_accounts, subAccountCount, subAccountCount);
holder.description.setText(text);
} else
holder.description.setVisibility(View.GONE);
// add a summary of transactions to the account view
// Make sure the balance task is truly multithread
new AccountBalanceTask(holder.accountBalance).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, accountUID);
String accountColor = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_COLOR_CODE));
int colorCode = accountColor == null ? Color.TRANSPARENT : Color.parseColor(accountColor);
holder.colorStripView.setBackgroundColor(colorCode);
boolean isPlaceholderAccount = mAccountsDbAdapter.isPlaceholderAccount(accountUID);
if (isPlaceholderAccount) {
holder.createTransaction.setVisibility(View.GONE);
} else {
holder.createTransaction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), FormActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID);
intent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.TRANSACTION.name());
getActivity().startActivity(intent);
}
});
}
List<Budget> budgets = BudgetsDbAdapter.getInstance().getAccountBudgets(accountUID);
//TODO: include fetch only active budgets
if (budgets.size() == 1){
Budget budget = budgets.get(0);
Money balance = mAccountsDbAdapter.getAccountBalance(accountUID, budget.getStartofCurrentPeriod(), budget.getEndOfCurrentPeriod());
double budgetProgress = balance.divide(budget.getAmount(accountUID)).asBigDecimal().doubleValue() * 100;
holder.budgetIndicator.setVisibility(View.VISIBLE);
holder.budgetIndicator.setProgress((int) budgetProgress);
} else {
holder.budgetIndicator.setVisibility(View.GONE);
}
if (mAccountsDbAdapter.isFavoriteAccount(accountUID)){
holder.favoriteStatus.setImageResource(R.drawable.ic_star_black_24dp);
} else {
holder.favoriteStatus.setImageResource(R.drawable.ic_star_border_black_24dp);
}
holder.favoriteStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isFavoriteAccount = mAccountsDbAdapter.isFavoriteAccount(accountUID);
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseSchema.AccountEntry.COLUMN_FAVORITE, !isFavoriteAccount);
mAccountsDbAdapter.updateRecord(accountUID, contentValues);
int drawableResource = !isFavoriteAccount ?
R.drawable.ic_star_black_24dp : R.drawable.ic_star_border_black_24dp;
holder.favoriteStatus.setImageResource(drawableResource);
if (mDisplayMode == DisplayMode.FAVORITES)
refresh();
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onListItemClick(accountUID);
}
});
}
class AccountViewHolder extends RecyclerView.ViewHolder implements PopupMenu.OnMenuItemClickListener{
@BindView(R.id.primary_text) TextView accountName;
@BindView(R.id.secondary_text) TextView description;
@BindView(R.id.account_balance) TextView accountBalance;
@BindView(R.id.create_transaction) ImageView createTransaction;
@BindView(R.id.favorite_status) ImageView favoriteStatus;
@BindView(R.id.options_menu) ImageView optionsMenu;
@BindView(R.id.account_color_strip) View colorStripView;
@BindView(R.id.budget_indicator) ProgressBar budgetIndicator;
long accoundId;
public AccountViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
optionsMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(getActivity(), v);
popup.setOnMenuItemClickListener(AccountViewHolder.this);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.account_context_menu, popup.getMenu());
popup.show();
}
});
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.context_menu_edit_accounts:
openCreateOrEditActivity(accoundId);
return true;
case R.id.context_menu_delete:
tryDeleteAccount(accoundId);
return true;
default:
return false;
}
}
}
}
}
| 24,012 | 37.793215 | 147 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/account/DeleteAccountDialogFragment.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.account;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.ui.common.Refreshable;
import org.gnucash.android.ui.homescreen.WidgetConfigurationActivity;
import org.gnucash.android.util.BackupManager;
import org.gnucash.android.util.QualifiedAccountNameCursorAdapter;
import java.util.List;
/**
* Delete confirmation dialog for accounts.
* It is displayed when deleting an account which has transactions or sub-accounts, and the user
* has the option to either move the transactions/sub-accounts, or delete them.
* If an account has no transactions, it is deleted immediately with no confirmation required
*
* @author Ngewi Fet <[email protected]>
*/
public class DeleteAccountDialogFragment extends DialogFragment {
/**
* Spinner for selecting the account to move the transactions to
*/
private Spinner mTransactionsDestinationAccountSpinner;
private Spinner mAccountsDestinationAccountSpinner;
/**
* Dialog positive button. Ok to moving the transactions
*/
private Button mOkButton;
/**
* Cancel button
*/
private Button mCancelButton;
/**
* GUID of account from which to move the transactions
*/
private String mOriginAccountUID = null;
private RadioButton mMoveAccountsRadioButton;
private RadioButton mMoveTransactionsRadioButton;
private RadioButton mDeleteAccountsRadioButton;
private RadioButton mDeleteTransactionsRadioButton;
private int mTransactionCount;
private int mSubAccountCount;
/**
* Creates new instance of the delete confirmation dialog and provides parameters for it
* @param accountUID GUID of the account to be deleted
* @return New instance of the delete confirmation dialog
*/
public static DeleteAccountDialogFragment newInstance(String accountUID) {
DeleteAccountDialogFragment fragment = new DeleteAccountDialogFragment();
fragment.mOriginAccountUID = accountUID;
fragment.mSubAccountCount = AccountsDbAdapter.getInstance().getSubAccountCount(accountUID);
fragment.mTransactionCount = TransactionsDbAdapter.getInstance().getTransactionsCount(accountUID);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_account_delete, container, false);
View transactionOptionsView = view.findViewById(R.id.transactions_options);
((TextView) transactionOptionsView.findViewById(R.id.title_content)).setText(R.string.section_header_transactions);
((TextView) transactionOptionsView.findViewById(R.id.description)).setText(R.string.label_delete_account_transactions_description);
mDeleteTransactionsRadioButton = (RadioButton) transactionOptionsView.findViewById(R.id.radio_delete);
mDeleteTransactionsRadioButton.setText(R.string.label_delete_transactions);
mMoveTransactionsRadioButton = (RadioButton) transactionOptionsView.findViewById(R.id.radio_move);
mTransactionsDestinationAccountSpinner = (Spinner) transactionOptionsView.findViewById(R.id.target_accounts_spinner);
View accountOptionsView = view.findViewById(R.id.accounts_options);
((TextView) accountOptionsView.findViewById(R.id.title_content)).setText(R.string.section_header_subaccounts);
((TextView) accountOptionsView.findViewById(R.id.description)).setText(R.string.label_delete_account_subaccounts_description);
mDeleteAccountsRadioButton = (RadioButton) accountOptionsView.findViewById(R.id.radio_delete);
mDeleteAccountsRadioButton.setText(R.string.label_delete_sub_accounts);
mMoveAccountsRadioButton = (RadioButton) accountOptionsView.findViewById(R.id.radio_move);
mAccountsDestinationAccountSpinner = (Spinner) accountOptionsView.findViewById(R.id.target_accounts_spinner);
transactionOptionsView.setVisibility(mTransactionCount > 0 ? View.VISIBLE : View.GONE);
accountOptionsView.setVisibility(mSubAccountCount > 0 ? View.VISIBLE : View.GONE);
mCancelButton = (Button) view.findViewById(R.id.btn_cancel);
mOkButton = (Button) view.findViewById(R.id.btn_save);
mOkButton.setText(R.string.alert_dialog_ok_delete);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String accountName = AccountsDbAdapter.getInstance().getAccountName(mOriginAccountUID);
getDialog().setTitle(getString(R.string.alert_dialog_ok_delete) + ": " + accountName);
AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance();
List<String> descendantAccountUIDs = accountsDbAdapter.getDescendantAccountUIDs(mOriginAccountUID, null, null);
String currencyCode = accountsDbAdapter.getCurrencyCode(mOriginAccountUID);
AccountType accountType = accountsDbAdapter.getAccountType(mOriginAccountUID);
String transactionDeleteConditions = "(" + DatabaseSchema.AccountEntry.COLUMN_UID + " != ? AND "
+ DatabaseSchema.AccountEntry.COLUMN_CURRENCY + " = ? AND "
+ DatabaseSchema.AccountEntry.COLUMN_TYPE + " = ? AND "
+ DatabaseSchema.AccountEntry.COLUMN_PLACEHOLDER + " = 0 AND "
+ DatabaseSchema.AccountEntry.COLUMN_UID + " NOT IN ('" + TextUtils.join("','", descendantAccountUIDs) + "')"
+ ")";
Cursor cursor = accountsDbAdapter.fetchAccountsOrderedByFullName(transactionDeleteConditions,
new String[]{mOriginAccountUID, currencyCode, accountType.name()});
SimpleCursorAdapter mCursorAdapter = new QualifiedAccountNameCursorAdapter(getActivity(), cursor);
mTransactionsDestinationAccountSpinner.setAdapter(mCursorAdapter);
//target accounts for transactions and accounts have different conditions
String accountMoveConditions = "(" + DatabaseSchema.AccountEntry.COLUMN_UID + " != ? AND "
+ DatabaseSchema.AccountEntry.COLUMN_CURRENCY + " = ? AND "
+ DatabaseSchema.AccountEntry.COLUMN_TYPE + " = ? AND "
+ DatabaseSchema.AccountEntry.COLUMN_UID + " NOT IN ('" + TextUtils.join("','", descendantAccountUIDs) + "')"
+ ")";
cursor = accountsDbAdapter.fetchAccountsOrderedByFullName(accountMoveConditions,
new String[]{mOriginAccountUID, currencyCode, accountType.name()});
mCursorAdapter = new QualifiedAccountNameCursorAdapter(getActivity(), cursor);
mAccountsDestinationAccountSpinner.setAdapter(mCursorAdapter);
setListeners();
//this comes after the listeners because of some useful bindings done there
if (cursor.getCount() == 0){
mMoveAccountsRadioButton.setEnabled(false);
mMoveAccountsRadioButton.setChecked(false);
mDeleteAccountsRadioButton.setChecked(true);
mMoveTransactionsRadioButton.setEnabled(false);
mMoveTransactionsRadioButton.setChecked(false);
mDeleteTransactionsRadioButton.setChecked(true);
mAccountsDestinationAccountSpinner.setVisibility(View.GONE);
mTransactionsDestinationAccountSpinner.setVisibility(View.GONE);
}
}
/**
* Binds click listeners for the dialog buttons
*/
protected void setListeners(){
mMoveAccountsRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mAccountsDestinationAccountSpinner.setEnabled(isChecked);
}
});
mMoveTransactionsRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mTransactionsDestinationAccountSpinner.setEnabled(isChecked);
}
});
mCancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
mOkButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BackupManager.backupActiveBook();
AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance();
if ((mTransactionCount > 0) && mMoveTransactionsRadioButton.isChecked()){
long targetAccountId = mTransactionsDestinationAccountSpinner.getSelectedItemId();
//move all the splits
SplitsDbAdapter.getInstance().updateRecords(DatabaseSchema.SplitEntry.COLUMN_ACCOUNT_UID + " = ?",
new String[]{mOriginAccountUID}, DatabaseSchema.SplitEntry.COLUMN_ACCOUNT_UID, accountsDbAdapter.getUID(targetAccountId));
}
if ((mSubAccountCount > 0) && mMoveAccountsRadioButton.isChecked()){
long targetAccountId = mAccountsDestinationAccountSpinner.getSelectedItemId();
AccountsDbAdapter.getInstance().reassignDescendantAccounts(mOriginAccountUID, accountsDbAdapter.getUID(targetAccountId));
}
if (GnuCashApplication.isDoubleEntryEnabled()){ //reassign splits to imbalance
TransactionsDbAdapter.getInstance().deleteTransactionsForAccount(mOriginAccountUID);
}
//now kill them all!!
accountsDbAdapter.recursiveDeleteAccount(accountsDbAdapter.getID(mOriginAccountUID));
WidgetConfigurationActivity.updateAllWidgets(getActivity());
((Refreshable)getTargetFragment()).refresh();
dismiss();
}
});
}
}
| 11,693 | 46.92623 | 150 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/account/OnAccountClickedListener.java
|
/*
* Copyright (c) 2012 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.account;
/**
* Interface for implemented by activities which wish to be notified when
* an action on account has been requested
* This is typically used for Fragment-to-Activity communication
*
* @author Ngewi Fet <[email protected]>
*/
public interface OnAccountClickedListener {
/**
* Callback when an account is selected (clicked) from in a list of accounts
* @param accountUID GUID of the selected account
*/
public void accountSelected(String accountUID);
}
| 1,129 | 31.285714 | 77 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/budget/BudgetAmountEditorFragment.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.budget;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.gnucash.android.R;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.model.BudgetAmount;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.util.widget.CalculatorEditText;
import org.gnucash.android.util.QualifiedAccountNameCursorAdapter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Fragment for editing budgeting amounts
*/
public class BudgetAmountEditorFragment extends Fragment {
private Cursor mAccountCursor;
private QualifiedAccountNameCursorAdapter mAccountCursorAdapter;
private List<View> mBudgetAmountViews = new ArrayList<>();
private AccountsDbAdapter mAccountsDbAdapter;
@BindView(R.id.budget_amount_layout) LinearLayout mBudgetAmountTableLayout;
@BindView(R.id.calculator_keyboard) KeyboardView mKeyboardView;
public static BudgetAmountEditorFragment newInstance(Bundle args){
BudgetAmountEditorFragment fragment = new BudgetAmountEditorFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_budget_amount_editor, container, false);
ButterKnife.bind(this, view);
setupAccountSpinnerAdapter();
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
assert actionBar != null;
actionBar.setTitle("Edit Budget Amounts");
setHasOptionsMenu(true);
ArrayList<BudgetAmount> budgetAmounts = getArguments().getParcelableArrayList(UxArgument.BUDGET_AMOUNT_LIST);
if (budgetAmounts != null) {
if (budgetAmounts.isEmpty()){
BudgetAmountViewHolder viewHolder = (BudgetAmountViewHolder) addBudgetAmountView(null).getTag();
viewHolder.removeItemBtn.setVisibility(View.GONE); //there should always be at least one
} else {
loadBudgetAmountViews(budgetAmounts);
}
} else {
BudgetAmountViewHolder viewHolder = (BudgetAmountViewHolder) addBudgetAmountView(null).getTag();
viewHolder.removeItemBtn.setVisibility(View.GONE); //there should always be at least one
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.budget_amount_editor_actions, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_add_budget_amount:
addBudgetAmountView(null);
return true;
case R.id.menu_save:
saveBudgetAmounts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Checks if the budget amounts can be saved
* @return {@code true} if all amounts a properly entered, {@code false} otherwise
*/
private boolean canSave(){
for (View budgetAmountView : mBudgetAmountViews) {
BudgetAmountViewHolder viewHolder = (BudgetAmountViewHolder) budgetAmountView.getTag();
viewHolder.amountEditText.evaluate();
if (viewHolder.amountEditText.getError() != null){
return false;
}
//at least one account should be loaded (don't create budget with empty account tree
if (viewHolder.budgetAccountSpinner.getCount() == 0){
Toast.makeText(getActivity(), "You need an account hierarchy to create a budget!",
Toast.LENGTH_SHORT).show();
return false;
}
}
return true;
}
private void saveBudgetAmounts() {
if (canSave()){
ArrayList<BudgetAmount> budgetAmounts = (ArrayList<BudgetAmount>) extractBudgetAmounts();
Intent data = new Intent();
data.putParcelableArrayListExtra(UxArgument.BUDGET_AMOUNT_LIST, budgetAmounts);
getActivity().setResult(Activity.RESULT_OK, data);
getActivity().finish();
}
}
/**
* Load views for the budget amounts
* @param budgetAmounts List of {@link BudgetAmount}s
*/
private void loadBudgetAmountViews(List<BudgetAmount> budgetAmounts){
for (BudgetAmount budgetAmount : budgetAmounts) {
addBudgetAmountView(budgetAmount);
}
}
/**
* Inflates a new BudgetAmount item view and adds it to the UI.
* <p>If the {@code budgetAmount} is not null, then it is used to initialize the view</p>
* @param budgetAmount Budget amount
*/
private View addBudgetAmountView(BudgetAmount budgetAmount){
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View budgetAmountView = layoutInflater.inflate(R.layout.item_budget_amount,
mBudgetAmountTableLayout, false);
BudgetAmountViewHolder viewHolder = new BudgetAmountViewHolder(budgetAmountView);
if (budgetAmount != null){
viewHolder.bindViews(budgetAmount);
}
mBudgetAmountTableLayout.addView(budgetAmountView, 0);
mBudgetAmountViews.add(budgetAmountView);
// mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
return budgetAmountView;
}
/**
* Loads the accounts in the spinner
*/
private void setupAccountSpinnerAdapter(){
String conditions = "(" + DatabaseSchema.AccountEntry.COLUMN_HIDDEN + " = 0 )";
if (mAccountCursor != null) {
mAccountCursor.close();
}
mAccountCursor = mAccountsDbAdapter.fetchAccountsOrderedByFavoriteAndFullName(conditions, null);
mAccountCursorAdapter = new QualifiedAccountNameCursorAdapter(getActivity(), mAccountCursor);
}
/**
* Extract {@link BudgetAmount}s from the views
* @return List of budget amounts
*/
private List<BudgetAmount> extractBudgetAmounts(){
List<BudgetAmount> budgetAmounts = new ArrayList<>();
for (View view : mBudgetAmountViews) {
BudgetAmountViewHolder viewHolder = (BudgetAmountViewHolder) view.getTag();
BigDecimal amountValue = viewHolder.amountEditText.getValue();
if (amountValue == null)
continue;
Money amount = new Money(amountValue, Commodity.DEFAULT_COMMODITY);
String accountUID = mAccountsDbAdapter.getUID(viewHolder.budgetAccountSpinner.getSelectedItemId());
BudgetAmount budgetAmount = new BudgetAmount(amount, accountUID);
budgetAmounts.add(budgetAmount);
}
return budgetAmounts;
}
/**
* View holder for budget amounts
*/
class BudgetAmountViewHolder{
@BindView(R.id.currency_symbol) TextView currencySymbolTextView;
@BindView(R.id.input_budget_amount) CalculatorEditText amountEditText;
@BindView(R.id.btn_remove_item) ImageView removeItemBtn;
@BindView(R.id.input_budget_account_spinner) Spinner budgetAccountSpinner;
View itemView;
public BudgetAmountViewHolder(View view){
itemView = view;
ButterKnife.bind(this, view);
itemView.setTag(this);
amountEditText.bindListeners(mKeyboardView);
budgetAccountSpinner.setAdapter(mAccountCursorAdapter);
budgetAccountSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String currencyCode = mAccountsDbAdapter.getCurrencyCode(mAccountsDbAdapter.getUID(id));
Commodity commodity = Commodity.getInstance(currencyCode);
currencySymbolTextView.setText(commodity.getSymbol());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//nothing to see here, move along
}
});
removeItemBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBudgetAmountTableLayout.removeView(itemView);
mBudgetAmountViews.remove(itemView);
}
});
}
public void bindViews(BudgetAmount budgetAmount){
amountEditText.setValue(budgetAmount.getAmount().asBigDecimal());
budgetAccountSpinner.setSelection(mAccountCursorAdapter.getPosition(budgetAmount.getAccountUID()));
}
}
}
| 10,756 | 37.833935 | 117 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/budget/BudgetDetailFragment.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.budget;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import org.gnucash.android.R;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BudgetsDbAdapter;
import org.gnucash.android.model.Budget;
import org.gnucash.android.model.BudgetAmount;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.common.FormActivity;
import org.gnucash.android.ui.common.Refreshable;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import org.gnucash.android.ui.util.widget.EmptyRecyclerView;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Fragment for displaying budget details
*/
public class BudgetDetailFragment extends Fragment implements Refreshable {
@BindView(R.id.primary_text) TextView mBudgetNameTextView;
@BindView(R.id.secondary_text) TextView mBudgetDescriptionTextView;
@BindView(R.id.budget_recurrence) TextView mBudgetRecurrence;
@BindView(R.id.budget_amount_recycler) EmptyRecyclerView mRecyclerView;
private String mBudgetUID;
private BudgetsDbAdapter mBudgetsDbAdapter;
public static BudgetDetailFragment newInstance(String budgetUID){
BudgetDetailFragment fragment = new BudgetDetailFragment();
Bundle args = new Bundle();
args.putString(UxArgument.BUDGET_UID, budgetUID);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_budget_detail, container, false);
ButterKnife.bind(this, view);
mBudgetDescriptionTextView.setMaxLines(3);
mRecyclerView.setHasFixedSize(true);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
} else {
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
}
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mBudgetsDbAdapter = BudgetsDbAdapter.getInstance();
mBudgetUID = getArguments().getString(UxArgument.BUDGET_UID);
bindViews();
setHasOptionsMenu(true);
}
private void bindViews(){
Budget budget = mBudgetsDbAdapter.getRecord(mBudgetUID);
mBudgetNameTextView.setText(budget.getName());
String description = budget.getDescription();
if (description != null && !description.isEmpty())
mBudgetDescriptionTextView.setText(description);
else {
mBudgetDescriptionTextView.setVisibility(View.GONE);
}
mBudgetRecurrence.setText(budget.getRecurrence().getRepeatString());
mRecyclerView.setAdapter(new BudgetAmountAdapter());
}
@Override
public void onResume() {
super.onResume();
refresh();
View view = getActivity().findViewById(R.id.fab_create_budget);
if (view != null){
view.setVisibility(View.GONE);
}
}
@Override
public void refresh() {
bindViews();
String budgetName = mBudgetsDbAdapter.getAttribute(mBudgetUID, DatabaseSchema.BudgetEntry.COLUMN_NAME);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
assert actionBar != null;
actionBar.setTitle("Budget: " + budgetName);
}
@Override
public void refresh(String budgetUID) {
mBudgetUID = budgetUID;
refresh();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.budget_actions, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_edit_budget:
Intent addAccountIntent = new Intent(getActivity(), FormActivity.class);
addAccountIntent.setAction(Intent.ACTION_INSERT_OR_EDIT);
addAccountIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.BUDGET.name());
addAccountIntent.putExtra(UxArgument.BUDGET_UID, mBudgetUID);
startActivityForResult(addAccountIntent, 0x11);
return true;
default:
return false;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK){
refresh();
}
}
public class BudgetAmountAdapter extends RecyclerView.Adapter<BudgetAmountAdapter.BudgetAmountViewHolder>{
private List<BudgetAmount> mBudgetAmounts;
private Budget mBudget;
public BudgetAmountAdapter(){
mBudget = mBudgetsDbAdapter.getRecord(mBudgetUID);
mBudgetAmounts = mBudget.getCompactedBudgetAmounts();
}
@Override
public BudgetAmountViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.cardview_budget_amount, parent, false);
return new BudgetAmountViewHolder(view);
}
@Override
public void onBindViewHolder(BudgetAmountViewHolder holder, final int position) {
BudgetAmount budgetAmount = mBudgetAmounts.get(position);
Money projectedAmount = budgetAmount.getAmount();
AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance();
holder.budgetAccount.setText(accountsDbAdapter.getAccountFullName(budgetAmount.getAccountUID()));
holder.budgetAmount.setText(projectedAmount.formattedString());
Money spentAmount = accountsDbAdapter.getAccountBalance(budgetAmount.getAccountUID(),
mBudget.getStartofCurrentPeriod(), mBudget.getEndOfCurrentPeriod());
holder.budgetSpent.setText(spentAmount.abs().formattedString());
holder.budgetLeft.setText(projectedAmount.subtract(spentAmount.abs()).formattedString());
double budgetProgress = 0;
if (projectedAmount.asDouble() != 0){
budgetProgress = spentAmount.asBigDecimal().divide(projectedAmount.asBigDecimal(),
spentAmount.getCommodity().getSmallestFractionDigits(),
RoundingMode.HALF_EVEN).doubleValue();
}
holder.budgetIndicator.setProgress((int) (budgetProgress * 100));
holder.budgetSpent.setTextColor(BudgetsActivity.getBudgetProgressColor(1 - budgetProgress));
holder.budgetLeft.setTextColor(BudgetsActivity.getBudgetProgressColor(1 - budgetProgress));
generateChartData(holder.budgetChart, budgetAmount);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), TransactionsActivity.class);
intent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, mBudgetAmounts.get(position).getAccountUID());
startActivityForResult(intent, 0x10);
}
});
}
/**
* Generate the chart data for the chart
* @param barChart View where to display the chart
* @param budgetAmount BudgetAmount to visualize
*/
public void generateChartData(BarChart barChart, BudgetAmount budgetAmount) {
// FIXME: 25.10.15 chart is broken
AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance();
List<BarEntry> barEntries = new ArrayList<>();
List<String> xVals = new ArrayList<>();
//todo: refactor getNumberOfPeriods into budget
int budgetPeriods = (int) mBudget.getNumberOfPeriods();
budgetPeriods = budgetPeriods == 0 ? 12 : budgetPeriods;
int periods = mBudget.getRecurrence().getNumberOfPeriods(budgetPeriods); //// FIXME: 15.08.2016 why do we need number of periods
for (int periodNum = 1; periodNum <= periods; periodNum++) {
BigDecimal amount = accountsDbAdapter.getAccountBalance(budgetAmount.getAccountUID(),
mBudget.getStartOfPeriod(periodNum), mBudget.getEndOfPeriod(periodNum))
.asBigDecimal();
if (amount.equals(BigDecimal.ZERO))
continue;
barEntries.add(new BarEntry(amount.floatValue(), periodNum));
xVals.add(mBudget.getRecurrence().getTextOfCurrentPeriod(periodNum));
}
String label = accountsDbAdapter.getAccountName(budgetAmount.getAccountUID());
BarDataSet barDataSet = new BarDataSet(barEntries, label);
BarData barData = new BarData(xVals, barDataSet);
LimitLine limitLine = new LimitLine(budgetAmount.getAmount().asBigDecimal().floatValue());
limitLine.setLineWidth(2f);
limitLine.setLineColor(Color.RED);
barChart.setData(barData);
barChart.getAxisLeft().addLimitLine(limitLine);
BigDecimal maxValue = budgetAmount.getAmount().add(budgetAmount.getAmount().multiply(new BigDecimal("0.2"))).asBigDecimal();
barChart.getAxisLeft().setAxisMaxValue(maxValue.floatValue());
barChart.animateX(1000);
barChart.setAutoScaleMinMaxEnabled(true);
barChart.setDrawValueAboveBar(true);
barChart.invalidate();
}
@Override
public int getItemCount() {
return mBudgetAmounts.size();
}
class BudgetAmountViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.budget_account) TextView budgetAccount;
@BindView(R.id.budget_amount) TextView budgetAmount;
@BindView(R.id.budget_spent) TextView budgetSpent;
@BindView(R.id.budget_left) TextView budgetLeft;
@BindView(R.id.budget_indicator) ProgressBar budgetIndicator;
@BindView(R.id.budget_chart) BarChart budgetChart;
public BudgetAmountViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
}
| 12,470 | 39.099678 | 140 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/budget/BudgetFormFragment.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.budget;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.codetroopers.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment;
import com.codetroopers.betterpickers.recurrencepicker.EventRecurrence;
import com.codetroopers.betterpickers.recurrencepicker.EventRecurrenceFormatter;
import com.codetroopers.betterpickers.recurrencepicker.RecurrencePickerDialogFragment;
import org.gnucash.android.R;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BudgetsDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.model.Budget;
import org.gnucash.android.model.BudgetAmount;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Recurrence;
import org.gnucash.android.ui.common.FormActivity;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.transaction.TransactionFormFragment;
import org.gnucash.android.ui.util.RecurrenceParser;
import org.gnucash.android.ui.util.RecurrenceViewClickListener;
import org.gnucash.android.ui.util.widget.CalculatorEditText;
import org.gnucash.android.util.QualifiedAccountNameCursorAdapter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Fragment for creating or editing Budgets
*/
public class BudgetFormFragment extends Fragment implements RecurrencePickerDialogFragment.OnRecurrenceSetListener, CalendarDatePickerDialogFragment.OnDateSetListener {
public static final int REQUEST_EDIT_BUDGET_AMOUNTS = 0xBA;
@BindView(R.id.input_budget_name) EditText mBudgetNameInput;
@BindView(R.id.input_description) EditText mDescriptionInput;
@BindView(R.id.input_recurrence) TextView mRecurrenceInput;
@BindView(R.id.name_text_input_layout) TextInputLayout mNameTextInputLayout;
@BindView(R.id.calculator_keyboard) KeyboardView mKeyboardView;
@BindView(R.id.input_budget_amount) CalculatorEditText mBudgetAmountInput;
@BindView(R.id.input_budget_account_spinner) Spinner mBudgetAccountSpinner;
@BindView(R.id.btn_add_budget_amount) Button mAddBudgetAmount;
@BindView(R.id.input_start_date) TextView mStartDateInput;
@BindView(R.id.budget_amount_layout) View mBudgetAmountLayout;
EventRecurrence mEventRecurrence = new EventRecurrence();
String mRecurrenceRule;
private BudgetsDbAdapter mBudgetsDbAdapter;
private Budget mBudget;
private Calendar mStartDate;
private ArrayList<BudgetAmount> mBudgetAmounts;
private AccountsDbAdapter mAccountsDbAdapter;
private QualifiedAccountNameCursorAdapter mAccountsCursorAdapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_budget_form, container, false);
ButterKnife.bind(this, view);
view.findViewById(R.id.btn_remove_item).setVisibility(View.GONE);
mBudgetAmountInput.bindListeners(mKeyboardView);
mStartDateInput.setText(TransactionFormFragment.DATE_FORMATTER.format(mStartDate.getTime()));
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBudgetsDbAdapter = BudgetsDbAdapter.getInstance();
mStartDate = Calendar.getInstance();
mBudgetAmounts = new ArrayList<>();
String conditions = "(" + DatabaseSchema.AccountEntry.COLUMN_HIDDEN + " = 0 )";
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
Cursor accountCursor = mAccountsDbAdapter.fetchAccountsOrderedByFavoriteAndFullName(conditions, null);
mAccountsCursorAdapter = new QualifiedAccountNameCursorAdapter(getActivity(), accountCursor);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mBudgetAccountSpinner.setAdapter(mAccountsCursorAdapter);
String budgetUID = getArguments().getString(UxArgument.BUDGET_UID);
if (budgetUID != null){ //if we are editing the budget
initViews(mBudget = mBudgetsDbAdapter.getRecord(budgetUID));
}
ActionBar actionbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
assert actionbar != null;
if (mBudget == null)
actionbar.setTitle("Create Budget");
else
actionbar.setTitle("Edit Budget");
mRecurrenceInput.setOnClickListener(
new RecurrenceViewClickListener((AppCompatActivity) getActivity(), mRecurrenceRule, this));
}
/**
* Initialize views when editing an existing budget
* @param budget Budget to use to initialize the views
*/
private void initViews(Budget budget){
mBudgetNameInput.setText(budget.getName());
mDescriptionInput.setText(budget.getDescription());
String recurrenceRuleString = budget.getRecurrence().getRuleString();
mRecurrenceRule = recurrenceRuleString;
mEventRecurrence.parse(recurrenceRuleString);
mRecurrenceInput.setText(budget.getRecurrence().getRepeatString());
mBudgetAmounts = (ArrayList<BudgetAmount>) budget.getCompactedBudgetAmounts();
toggleAmountInputVisibility();
}
/**
* Extracts the budget amounts from the form
* <p>If the budget amount was input using the simple form, then read the values.<br>
* Else return the values gotten from the BudgetAmountEditor</p>
* @return List of budget amounts
*/
private ArrayList<BudgetAmount> extractBudgetAmounts(){
BigDecimal value = mBudgetAmountInput.getValue();
if (value == null)
return mBudgetAmounts;
if (mBudgetAmounts.isEmpty()){ //has not been set in budget amounts editor
ArrayList<BudgetAmount> budgetAmounts = new ArrayList<>();
Money amount = new Money(value, Commodity.DEFAULT_COMMODITY);
String accountUID = mAccountsDbAdapter.getUID(mBudgetAccountSpinner.getSelectedItemId());
BudgetAmount budgetAmount = new BudgetAmount(amount, accountUID);
budgetAmounts.add(budgetAmount);
return budgetAmounts;
} else {
return mBudgetAmounts;
}
}
/**
* Checks that this budget can be saved
* Also sets the appropriate error messages on the relevant views
* <p>For a budget to be saved, it needs to have a name, an amount and a schedule</p>
* @return {@code true} if the budget can be saved, {@code false} otherwise
*/
private boolean canSave(){
if (mEventRecurrence.until != null && mEventRecurrence.until.length() > 0
|| mEventRecurrence.count <= 0){
Toast.makeText(getActivity(),
"Set a number periods in the recurrence dialog to save the budget",
Toast.LENGTH_SHORT).show();
return false;
}
mBudgetAmounts = extractBudgetAmounts();
String budgetName = mBudgetNameInput.getText().toString();
boolean canSave = mRecurrenceRule != null
&& !budgetName.isEmpty()
&& !mBudgetAmounts.isEmpty();
if (!canSave){
if (budgetName.isEmpty()){
mNameTextInputLayout.setError("A name is required");
mNameTextInputLayout.setErrorEnabled(true);
} else {
mNameTextInputLayout.setErrorEnabled(false);
}
if (mBudgetAmounts.isEmpty()){
mBudgetAmountInput.setError("Enter an amount for the budget");
Toast.makeText(getActivity(), "Add budget amounts in order to save the budget",
Toast.LENGTH_SHORT).show();
}
if (mRecurrenceRule == null){
Toast.makeText(getActivity(), "Set a repeat pattern to create a budget!",
Toast.LENGTH_SHORT).show();
}
}
return canSave;
}
/**
* Extracts the information from the form and saves the budget
*/
private void saveBudget(){
if (!canSave())
return;
String name = mBudgetNameInput.getText().toString().trim();
if (mBudget == null){
mBudget = new Budget(name);
} else {
mBudget.setName(name);
}
// TODO: 22.10.2015 set the period num of the budget amount
extractBudgetAmounts();
mBudget.setBudgetAmounts(mBudgetAmounts);
mBudget.setDescription(mDescriptionInput.getText().toString().trim());
Recurrence recurrence = RecurrenceParser.parse(mEventRecurrence);
recurrence.setPeriodStart(new Timestamp(mStartDate.getTimeInMillis()));
mBudget.setRecurrence(recurrence);
mBudgetsDbAdapter.addRecord(mBudget, DatabaseAdapter.UpdateMethod.insert);
getActivity().finish();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.default_save_actions, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_save:
saveBudget();
return true;
}
return false;
}
@OnClick(R.id.input_start_date)
public void onClickBudgetStartDate(View v) {
long dateMillis = 0;
try {
Date date = TransactionFormFragment.DATE_FORMATTER.parse(((TextView) v).getText().toString());
dateMillis = date.getTime();
} catch (ParseException e) {
Log.e(getTag(), "Error converting input time to Date object");
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(dateMillis);
int year = calendar.get(Calendar.YEAR);
int monthOfYear = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
CalendarDatePickerDialogFragment datePickerDialog = new CalendarDatePickerDialogFragment();
datePickerDialog.setOnDateSetListener(BudgetFormFragment.this);
datePickerDialog.setPreselectedDate(year, monthOfYear, dayOfMonth);
datePickerDialog.show(getFragmentManager(), "date_picker_fragment");
}
@OnClick(R.id.btn_add_budget_amount)
public void onOpenBudgetAmountEditor(View v){
Intent intent = new Intent(getActivity(), FormActivity.class);
intent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.BUDGET_AMOUNT_EDITOR.name());
mBudgetAmounts = extractBudgetAmounts();
intent.putParcelableArrayListExtra(UxArgument.BUDGET_AMOUNT_LIST, mBudgetAmounts);
startActivityForResult(intent, REQUEST_EDIT_BUDGET_AMOUNTS);
}
@Override
public void onRecurrenceSet(String rrule) {
mRecurrenceRule = rrule;
String repeatString = getString(R.string.label_tap_to_create_schedule);
if (mRecurrenceRule != null){
mEventRecurrence.parse(mRecurrenceRule);
repeatString = EventRecurrenceFormatter.getRepeatString(getActivity(), getResources(), mEventRecurrence, true);
}
mRecurrenceInput.setText(repeatString);
}
@Override
public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {
Calendar cal = new GregorianCalendar(year, monthOfYear, dayOfMonth);
mStartDateInput.setText(TransactionFormFragment.DATE_FORMATTER.format(cal.getTime()));
mStartDate.set(Calendar.YEAR, year);
mStartDate.set(Calendar.MONTH, monthOfYear);
mStartDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EDIT_BUDGET_AMOUNTS){
if (resultCode == Activity.RESULT_OK){
ArrayList<BudgetAmount> budgetAmounts = data.getParcelableArrayListExtra(UxArgument.BUDGET_AMOUNT_LIST);
if (budgetAmounts != null){
mBudgetAmounts = budgetAmounts;
toggleAmountInputVisibility();
}
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Toggles the visibility of the amount input based on {@link #mBudgetAmounts}
*/
private void toggleAmountInputVisibility() {
if (mBudgetAmounts.size() > 1){
mBudgetAmountLayout.setVisibility(View.GONE);
mAddBudgetAmount.setText("Edit Budget Amounts");
} else {
mAddBudgetAmount.setText("Add Budget Amounts");
mBudgetAmountLayout.setVisibility(View.VISIBLE);
if (!mBudgetAmounts.isEmpty()) {
BudgetAmount budgetAmount = mBudgetAmounts.get(0);
mBudgetAmountInput.setValue(budgetAmount.getAmount().asBigDecimal());
mBudgetAccountSpinner.setSelection(mAccountsCursorAdapter.getPosition(budgetAmount.getAccountUID()));
}
}
}
}
| 14,867 | 39.958678 | 168 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/budget/BudgetListFragment.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.budget;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.gnucash.android.R;
import org.gnucash.android.db.DatabaseCursorLoader;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BudgetsDbAdapter;
import org.gnucash.android.model.Budget;
import org.gnucash.android.model.BudgetAmount;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.common.FormActivity;
import org.gnucash.android.ui.common.Refreshable;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.util.CursorRecyclerAdapter;
import org.gnucash.android.ui.util.widget.EmptyRecyclerView;
import java.math.BigDecimal;
import java.math.RoundingMode;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Budget list fragment
*/
public class BudgetListFragment extends Fragment implements Refreshable,
LoaderManager.LoaderCallbacks<Cursor> {
private static final String LOG_TAG = "BudgetListFragment";
private static final int REQUEST_EDIT_BUDGET = 0xB;
private static final int REQUEST_OPEN_ACCOUNT = 0xC;
private BudgetRecyclerAdapter mBudgetRecyclerAdapter;
private BudgetsDbAdapter mBudgetsDbAdapter;
@BindView(R.id.budget_recycler_view) EmptyRecyclerView mRecyclerView;
@BindView(R.id.empty_view) Button mProposeBudgets;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_budget_list, container, false);
ButterKnife.bind(this, view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setEmptyView(mProposeBudgets);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
} else {
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
}
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mBudgetsDbAdapter = BudgetsDbAdapter.getInstance();
mBudgetRecyclerAdapter = new BudgetRecyclerAdapter(null);
mRecyclerView.setAdapter(mBudgetRecyclerAdapter);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(LOG_TAG, "Creating the accounts loader");
return new BudgetsCursorLoader(getActivity());
}
@Override
public void onLoadFinished(Loader<Cursor> loaderCursor, Cursor cursor) {
Log.d(LOG_TAG, "Budget loader finished. Swapping in cursor");
mBudgetRecyclerAdapter.swapCursor(cursor);
mBudgetRecyclerAdapter.notifyDataSetChanged();
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
Log.d(LOG_TAG, "Resetting the accounts loader");
mBudgetRecyclerAdapter.swapCursor(null);
}
@Override
public void onResume() {
super.onResume();
refresh();
getActivity().findViewById(R.id.fab_create_budget).setVisibility(View.VISIBLE);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Budgets");
}
@Override
public void refresh() {
getLoaderManager().restartLoader(0, null, this);
}
/**
* This method does nothing with the GUID.
* Is equivalent to calling {@link #refresh()}
* @param uid GUID of relevant item to be refreshed
*/
@Override
public void refresh(String uid) {
refresh();
}
/**
* Opens the budget detail fragment
* @param budgetUID GUID of budget
*/
public void onClickBudget(String budgetUID){
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, BudgetDetailFragment.newInstance(budgetUID));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
/**
* Launches the FormActivity for editing the budget
* @param budgetId Db record Id of the budget
*/
private void editBudget(long budgetId){
Intent addAccountIntent = new Intent(getActivity(), FormActivity.class);
addAccountIntent.setAction(Intent.ACTION_INSERT_OR_EDIT);
addAccountIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.BUDGET.name());
addAccountIntent.putExtra(UxArgument.BUDGET_UID, mBudgetsDbAdapter.getUID(budgetId));
startActivityForResult(addAccountIntent, REQUEST_EDIT_BUDGET);
}
/**
* Delete the budget from the database
* @param budgetId Database record ID
*/
private void deleteBudget(long budgetId){
BudgetsDbAdapter.getInstance().deleteRecord(budgetId);
refresh();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK){
refresh();
}
}
class BudgetRecyclerAdapter extends CursorRecyclerAdapter<BudgetRecyclerAdapter.BudgetViewHolder>{
public BudgetRecyclerAdapter(Cursor cursor) {
super(cursor);
}
@Override
public void onBindViewHolderCursor(BudgetViewHolder holder, Cursor cursor) {
final Budget budget = mBudgetsDbAdapter.buildModelInstance(cursor);
holder.budgetId = mBudgetsDbAdapter.getID(budget.getUID());
holder.budgetName.setText(budget.getName());
AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance();
String accountString;
int numberOfAccounts = budget.getNumberOfAccounts();
if (numberOfAccounts == 1){
accountString = accountsDbAdapter.getAccountFullName(budget.getBudgetAmounts().get(0).getAccountUID());
} else {
accountString = numberOfAccounts + " budgeted accounts";
}
holder.accountName.setText(accountString);
holder.budgetRecurrence.setText(budget.getRecurrence().getRepeatString() + " - "
+ budget.getRecurrence().getDaysLeftInCurrentPeriod() + " days left");
BigDecimal spentAmountValue = BigDecimal.ZERO;
for (BudgetAmount budgetAmount : budget.getCompactedBudgetAmounts()) {
Money balance = accountsDbAdapter.getAccountBalance(budgetAmount.getAccountUID(),
budget.getStartofCurrentPeriod(), budget.getEndOfCurrentPeriod());
spentAmountValue = spentAmountValue.add(balance.asBigDecimal());
}
Money budgetTotal = budget.getAmountSum();
Commodity commodity = budgetTotal.getCommodity();
String usedAmount = commodity.getSymbol() + spentAmountValue + " of "
+ budgetTotal.formattedString();
holder.budgetAmount.setText(usedAmount);
double budgetProgress = spentAmountValue.divide(budgetTotal.asBigDecimal(),
commodity.getSmallestFractionDigits(), RoundingMode.HALF_EVEN)
.doubleValue();
holder.budgetIndicator.setProgress((int) (budgetProgress * 100));
holder.budgetAmount.setTextColor(BudgetsActivity.getBudgetProgressColor(1 - budgetProgress));
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickBudget(budget.getUID());
}
});
}
@Override
public BudgetViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_budget, parent, false);
return new BudgetViewHolder(v);
}
class BudgetViewHolder extends RecyclerView.ViewHolder implements PopupMenu.OnMenuItemClickListener{
@BindView(R.id.primary_text) TextView budgetName;
@BindView(R.id.secondary_text) TextView accountName;
@BindView(R.id.budget_amount) TextView budgetAmount;
@BindView(R.id.options_menu) ImageView optionsMenu;
@BindView(R.id.budget_indicator) ProgressBar budgetIndicator;
@BindView(R.id.budget_recurrence) TextView budgetRecurrence;
long budgetId;
public BudgetViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
optionsMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
android.support.v7.widget.PopupMenu popup = new android.support.v7.widget.PopupMenu(getActivity(), v);
popup.setOnMenuItemClickListener(BudgetViewHolder.this);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.budget_context_menu, popup.getMenu());
popup.show();
}
});
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.context_menu_edit_budget:
editBudget(budgetId);
return true;
case R.id.context_menu_delete:
deleteBudget(budgetId);
return true;
default:
return false;
}
}
}
}
/**
* Loads Budgets asynchronously from the database
*/
private static class BudgetsCursorLoader extends DatabaseCursorLoader {
/**
* Constructor
* Initializes the content observer
*
* @param context Application context
*/
public BudgetsCursorLoader(Context context) {
super(context);
}
@Override
public Cursor loadInBackground() {
mDatabaseAdapter = BudgetsDbAdapter.getInstance();
return mDatabaseAdapter.fetchAllRecords(null, null, DatabaseSchema.BudgetEntry.COLUMN_NAME + " ASC");
}
}
}
| 12,404 | 36.820122 | 126 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/budget/BudgetsActivity.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.budget;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.ui.common.BaseDrawerActivity;
import org.gnucash.android.ui.common.FormActivity;
import org.gnucash.android.ui.common.UxArgument;
/**
* Activity for managing display and editing of budgets
*/
public class BudgetsActivity extends BaseDrawerActivity {
public static final int REQUEST_CREATE_BUDGET = 0xA;
@Override
public int getContentView() {
return R.layout.activity_budgets;
}
@Override
public int getTitleRes() {
return R.string.title_budgets;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new BudgetListFragment());
fragmentTransaction.commit();
}
}
/**
* Callback when create budget floating action button is clicked
* @param view View which was clicked
*/
public void onCreateBudgetClick(View view){
Intent addAccountIntent = new Intent(BudgetsActivity.this, FormActivity.class);
addAccountIntent.setAction(Intent.ACTION_INSERT_OR_EDIT);
addAccountIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.BUDGET.name());
startActivityForResult(addAccountIntent, REQUEST_CREATE_BUDGET);
}
/**
* Returns a color between red and green depending on the value parameter
* @param value Value between 0 and 1 indicating the red to green ratio
* @return Color between red and green
*/
public static int getBudgetProgressColor(double value){
return GnuCashApplication.darken(android.graphics.Color.HSVToColor(new float[]{(float)value*120f,1f,1f}));
}
}
| 2,841 | 34.08642 | 114 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/colorpicker/ColorPickerDialog.java
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.colorpicker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import org.gnucash.android.R;
import org.gnucash.android.ui.colorpicker.ColorPickerSwatch.OnColorSelectedListener;
/**
* A dialog which takes in as input an array of colors and creates a palette allowing the user to
* select a specific color swatch, which invokes a listener.
*/
public class ColorPickerDialog extends DialogFragment implements OnColorSelectedListener {
public static final int SIZE_LARGE = 1;
public static final int SIZE_SMALL = 2;
protected AlertDialog mAlertDialog;
protected static final String KEY_TITLE_ID = "title_id";
protected static final String KEY_COLORS = "colors";
protected static final String KEY_SELECTED_COLOR = "selected_color";
protected static final String KEY_COLUMNS = "columns";
protected static final String KEY_SIZE = "size";
protected int mTitleResId = R.string.color_picker_default_title;
protected int[] mColors = null;
protected int mSelectedColor;
protected int mColumns;
protected int mSize;
private ColorPickerPalette mPalette;
private ProgressBar mProgress;
protected OnColorSelectedListener mListener;
public ColorPickerDialog() {
// Empty constructor required for dialog fragments.
}
public static ColorPickerDialog newInstance(int titleResId, int[] colors, int selectedColor,
int columns, int size) {
ColorPickerDialog ret = new ColorPickerDialog();
ret.initialize(titleResId, colors, selectedColor, columns, size);
return ret;
}
public void initialize(int titleResId, int[] colors, int selectedColor, int columns, int size) {
setArguments(titleResId, columns, size);
setColors(colors, selectedColor);
}
public void setArguments(int titleResId, int columns, int size) {
Bundle bundle = new Bundle();
bundle.putInt(KEY_TITLE_ID, titleResId);
bundle.putInt(KEY_COLUMNS, columns);
bundle.putInt(KEY_SIZE, size);
setArguments(bundle);
}
public void setOnColorSelectedListener(OnColorSelectedListener listener) {
mListener = listener;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitleResId = getArguments().getInt(KEY_TITLE_ID);
mColumns = getArguments().getInt(KEY_COLUMNS);
mSize = getArguments().getInt(KEY_SIZE);
}
if (savedInstanceState != null) {
mColors = savedInstanceState.getIntArray(KEY_COLORS);
mSelectedColor = (Integer) savedInstanceState.getSerializable(KEY_SELECTED_COLOR);
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Activity activity = getActivity();
View view = LayoutInflater.from(getActivity()).inflate(R.layout.color_picker_dialog, null);
mProgress = (ProgressBar) view.findViewById(android.R.id.progress);
mPalette = (ColorPickerPalette) view.findViewById(R.id.color_picker);
mPalette.init(mSize, mColumns, this);
if (mColors != null) {
showPaletteView();
}
mAlertDialog = new AlertDialog.Builder(activity)
.setTitle(mTitleResId)
.setView(view)
.create();
return mAlertDialog;
}
@Override
public void onColorSelected(int color) {
if (mListener != null) {
mListener.onColorSelected(color);
}
if (getTargetFragment() instanceof OnColorSelectedListener) {
final OnColorSelectedListener listener =
(OnColorSelectedListener) getTargetFragment();
listener.onColorSelected(color);
}
if (color != mSelectedColor) {
mSelectedColor = color;
// Redraw palette to show checkmark on newly selected color before dismissing.
mPalette.drawPalette(mColors, mSelectedColor);
}
dismiss();
}
public void showPaletteView() {
if (mProgress != null && mPalette != null) {
mProgress.setVisibility(View.GONE);
refreshPalette();
mPalette.setVisibility(View.VISIBLE);
}
}
public void showProgressBarView() {
if (mProgress != null && mPalette != null) {
mProgress.setVisibility(View.VISIBLE);
mPalette.setVisibility(View.GONE);
}
}
public void setColors(int[] colors, int selectedColor) {
if (mColors != colors || mSelectedColor != selectedColor) {
mColors = colors;
mSelectedColor = selectedColor;
refreshPalette();
}
}
public void setColors(int[] colors) {
if (mColors != colors) {
mColors = colors;
refreshPalette();
}
}
public void setSelectedColor(int color) {
if (mSelectedColor != color) {
mSelectedColor = color;
refreshPalette();
}
}
private void refreshPalette() {
if (mPalette != null && mColors != null) {
mPalette.drawPalette(mColors, mSelectedColor);
}
}
public int[] getColors() {
return mColors;
}
public int getSelectedColor() {
return mSelectedColor;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putIntArray(KEY_COLORS, mColors);
outState.putSerializable(KEY_SELECTED_COLOR, mSelectedColor);
}
}
| 6,532 | 31.341584 | 100 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/colorpicker/ColorPickerPalette.java
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.colorpicker;
import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import org.gnucash.android.R;
import org.gnucash.android.ui.colorpicker.ColorPickerSwatch.OnColorSelectedListener;
/**
* A color picker custom view which creates an grid of color squares. The number of squares per
* row (and the padding between the squares) is determined by the user.
*/
public class ColorPickerPalette extends TableLayout {
public OnColorSelectedListener mOnColorSelectedListener;
private String mDescription;
private String mDescriptionSelected;
private int mSwatchLength;
private int mMarginSize;
private int mNumColumns;
public ColorPickerPalette(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ColorPickerPalette(Context context) {
super(context);
}
/**
* Initialize the size, columns, and listener. Size should be a pre-defined size (SIZE_LARGE
* or SIZE_SMALL) from ColorPickerDialogFragment.
*/
public void init(int size, int columns, OnColorSelectedListener listener) {
mNumColumns = columns;
Resources res = getResources();
if (size == ColorPickerDialog.SIZE_LARGE) {
mSwatchLength = res.getDimensionPixelSize(R.dimen.color_swatch_large);
mMarginSize = res.getDimensionPixelSize(R.dimen.color_swatch_margins_large);
} else {
mSwatchLength = res.getDimensionPixelSize(R.dimen.color_swatch_small);
mMarginSize = res.getDimensionPixelSize(R.dimen.color_swatch_margins_small);
}
mOnColorSelectedListener = listener;
mDescription = res.getString(R.string.color_swatch_description);
mDescriptionSelected = res.getString(R.string.color_swatch_description_selected);
}
private TableRow createTableRow() {
TableRow row = new TableRow(getContext());
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
return row;
}
/**
* Adds swatches to table in a serpentine format.
*/
public void drawPalette(int[] colors, int selectedColor) {
if (colors == null) {
return;
}
this.removeAllViews();
int tableElements = 0;
int rowElements = 0;
int rowNumber = 0;
// Fills the table with swatches based on the array of colors.
TableRow row = createTableRow();
for (int color : colors) {
tableElements++;
View colorSwatch = createColorSwatch(color, selectedColor);
setSwatchDescription(rowNumber, tableElements, rowElements, color == selectedColor,
colorSwatch);
addSwatchToRow(row, colorSwatch, rowNumber);
rowElements++;
if (rowElements == mNumColumns) {
addView(row);
row = createTableRow();
rowElements = 0;
rowNumber++;
}
}
// Create blank views to fill the row if the last row has not been filled.
if (rowElements > 0) {
while (rowElements != mNumColumns) {
addSwatchToRow(row, createBlankSpace(), rowNumber);
rowElements++;
}
addView(row);
}
}
/**
* Appends a swatch to the end of the row for even-numbered rows (starting with row 0),
* to the beginning of a row for odd-numbered rows.
*/
private void addSwatchToRow(TableRow row, View swatch, int rowNumber) {
if (rowNumber % 2 == 0) {
row.addView(swatch);
} else {
row.addView(swatch, 0);
}
}
/**
* Add a content description to the specified swatch view. Because the colors get added in a
* snaking form, every other row will need to compensate for the fact that the colors are added
* in an opposite direction from their left->right/top->bottom order, which is how the system
* will arrange them for accessibility purposes.
*/
private void setSwatchDescription(int rowNumber, int index, int rowElements, boolean selected,
View swatch) {
int accessibilityIndex;
if (rowNumber % 2 == 0) {
// We're in a regular-ordered row
accessibilityIndex = index;
} else {
// We're in a backwards-ordered row.
int rowMax = (rowNumber + 1) * mNumColumns;
accessibilityIndex = rowMax - rowElements;
}
String description;
if (selected) {
description = String.format(mDescriptionSelected, accessibilityIndex);
} else {
description = String.format(mDescription, accessibilityIndex);
}
swatch.setContentDescription(description);
}
/**
* Creates a blank space to fill the row.
*/
private ImageView createBlankSpace() {
ImageView view = new ImageView(getContext());
TableRow.LayoutParams params = new TableRow.LayoutParams(mSwatchLength, mSwatchLength);
params.setMargins(mMarginSize, mMarginSize, mMarginSize, mMarginSize);
view.setLayoutParams(params);
return view;
}
/**
* Creates a color swatch.
*/
private ColorPickerSwatch createColorSwatch(int color, int selectedColor) {
ColorPickerSwatch view = new ColorPickerSwatch(getContext(), color,
color == selectedColor, mOnColorSelectedListener);
TableRow.LayoutParams params = new TableRow.LayoutParams(mSwatchLength, mSwatchLength);
params.setMargins(mMarginSize, mMarginSize, mMarginSize, mMarginSize);
view.setLayoutParams(params);
return view;
}
}
| 6,680 | 34.919355 | 99 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/colorpicker/ColorPickerSwatch.java
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.colorpicker;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import org.gnucash.android.R;
/**
* Creates a circular swatch of a specified color. Adds a checkmark if marked as checked.
*/
public class ColorPickerSwatch extends FrameLayout implements View.OnClickListener {
private int mColor;
private ImageView mSwatchImage;
private ImageView mCheckmarkImage;
private OnColorSelectedListener mOnColorSelectedListener;
/**
* Interface for a callback when a color square is selected.
*/
public interface OnColorSelectedListener {
/**
* Called when a specific color square has been selected.
*/
public void onColorSelected(int color);
}
public ColorPickerSwatch(Context context, int color, boolean checked,
OnColorSelectedListener listener) {
super(context);
mColor = color;
mOnColorSelectedListener = listener;
LayoutInflater.from(context).inflate(R.layout.color_picker_swatch, this);
mSwatchImage = (ImageView) findViewById(R.id.color_picker_swatch);
mCheckmarkImage = (ImageView) findViewById(R.id.color_picker_checkmark);
setColor(color);
setChecked(checked);
setOnClickListener(this);
}
protected void setColor(int color) {
Drawable[] colorDrawable = new Drawable[]
{getContext().getResources().getDrawable(R.drawable.color_picker_swatch)};
mSwatchImage.setImageDrawable(new ColorStateDrawable(colorDrawable, color));
}
private void setChecked(boolean checked) {
if (checked) {
mCheckmarkImage.setVisibility(View.VISIBLE);
} else {
mCheckmarkImage.setVisibility(View.GONE);
}
}
@Override
public void onClick(View v) {
if (mOnColorSelectedListener != null) {
mOnColorSelectedListener.onColorSelected(mColor);
}
}
}
| 2,754 | 32.192771 | 90 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/colorpicker/ColorSquare.java
|
package org.gnucash.android.ui.colorpicker;
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.QuickContactBadge;
import org.gnucash.android.R;
/**
* The color square used as an entry point to launching the {@link ColorPickerDialog}.
*/
public class ColorSquare extends QuickContactBadge {
public ColorSquare(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ColorSquare(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setBackgroundColor(int color) {
Drawable[] colorDrawable = new Drawable[] {
getContext().getResources().getDrawable(R.drawable.color_square) };
setImageDrawable(new ColorStateDrawable(colorDrawable, color));
}
}
| 1,499 | 31.608696 | 86 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/colorpicker/ColorStateDrawable.java
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.colorpicker;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
/**
* A drawable which sets its color filter to a color specified by the user, and changes to a
* slightly darker color when pressed or focused.
*/
public class ColorStateDrawable extends LayerDrawable {
private static final float PRESSED_STATE_MULTIPLIER = 0.70f;
private int mColor;
public ColorStateDrawable(Drawable[] layers, int color) {
super(layers);
mColor = color;
}
@Override
protected boolean onStateChange(int[] states) {
boolean pressedOrFocused = false;
for (int state : states) {
if (state == android.R.attr.state_pressed || state == android.R.attr.state_focused) {
pressedOrFocused = true;
break;
}
}
if (pressedOrFocused) {
super.setColorFilter(getPressedColor(mColor), PorterDuff.Mode.SRC_ATOP);
} else {
super.setColorFilter(mColor, PorterDuff.Mode.SRC_ATOP);
}
return super.onStateChange(states);
}
/**
* Given a particular color, adjusts its value by a multiplier.
*/
private int getPressedColor(int color) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] = hsv[2] * PRESSED_STATE_MULTIPLIER;
return Color.HSVToColor(hsv);
}
@Override
public boolean isStateful() {
return true;
}
}
| 2,211 | 29.30137 | 97 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/colorpicker/HsvColorComparator.java
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.colorpicker;
import android.graphics.Color;
import java.util.Comparator;
/**
* A color comparator which compares based on hue, saturation, and value.
*/
public class HsvColorComparator implements Comparator<Integer> {
@Override
public int compare(Integer lhs, Integer rhs) {
float[] hsv = new float[3];
Color.colorToHSV(lhs, hsv);
float hue1 = hsv[0];
float sat1 = hsv[1];
float val1 = hsv[2];
float[] hsv2 = new float[3];
Color.colorToHSV(rhs, hsv2);
float hue2 = hsv2[0];
float sat2 = hsv2[1];
float val2 = hsv2[2];
if (hue1 < hue2) {
return 1;
} else if (hue1 > hue2) {
return -1;
} else {
if (sat1 < sat2) {
return 1;
} else if (sat1 > sat2) {
return -1;
} else {
if (val1 < val2) {
return 1;
} else if (val1 > val2) {
return -1;
}
}
}
return 0;
}
}
| 1,737 | 27.491803 | 75 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/common/BaseDrawerActivity.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.common;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.LayoutRes;
import android.support.annotation.StringRes;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.uservoice.uservoicesdk.UserVoice;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.passcode.PasscodeLockActivity;
import org.gnucash.android.ui.report.ReportsActivity;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.gnucash.android.ui.transaction.ScheduledActionsActivity;
import org.gnucash.android.util.BookUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Base activity implementing the navigation drawer, to be extended by all activities requiring one.
* <p>
* Each activity inheriting from this class has an indeterminate progress bar at the top,
* (above the action bar) which can be used to display busy operations. See {@link #getProgressBar()}
* </p>
*
* <p>Sub-classes should simply provide their layout using {@link #getContentView()} and then annotate
* any variables they wish to use with {@link ButterKnife#bind(Activity)} annotations. The view
* binding will be done in this base abstract class.<br>
* The activity layout of the subclass is expected to contain {@code DrawerLayout} and
* a {@code NavigationView}.<br>
* Sub-class should also consider using the {@code toolbar.xml} or {@code toolbar_with_spinner.xml}
* for the action bar in their XML layout. Otherwise provide another which contains widgets for the
* toolbar and progress indicator with the IDs {@code R.id.toolbar} and {@code R.id.progress_indicator} respectively.
* </p>
* @author Ngewi Fet <[email protected]>
*/
public abstract class BaseDrawerActivity extends PasscodeLockActivity implements
PopupMenu.OnMenuItemClickListener {
public static final int ID_MANAGE_BOOKS = 0xB00C;
@BindView(R.id.drawer_layout) DrawerLayout mDrawerLayout;
@BindView(R.id.nav_view) NavigationView mNavigationView;
@BindView(R.id.toolbar) Toolbar mToolbar;
@BindView(R.id.toolbar_progress) ProgressBar mToolbarProgress;
protected TextView mBookNameTextView;
protected ActionBarDrawerToggle mDrawerToggle;
public static final int REQUEST_OPEN_DOCUMENT = 0x20;
private class DrawerItemClickListener implements NavigationView.OnNavigationItemSelectedListener {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
onDrawerMenuItemClicked(menuItem.getItemId());
return true;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentView());
//if a parameter was passed to open an account within a specific book, then switch
String bookUID = getIntent().getStringExtra(UxArgument.BOOK_UID);
if (bookUID != null && !bookUID.equals(BooksDbAdapter.getInstance().getActiveBookUID())){
BookUtils.activateBook(bookUID);
}
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(getTitleRes());
}
mToolbarProgress.getIndeterminateDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
View headerView = mNavigationView.getHeaderView(0);
headerView.findViewById(R.id.drawer_title).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickAppTitle(v);
}
});
mBookNameTextView = (TextView) headerView.findViewById(R.id.book_name);
mBookNameTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickBook(v);
}
});
updateActiveBookName();
setUpNavigationDrawer();
}
@Override
protected void onResume() {
super.onResume();
updateActiveBookName();
}
/**
* Return the layout to inflate for this activity
* @return Layout resource identifier
*/
public abstract @LayoutRes int getContentView();
/**
* Return the title for this activity.
* This will be displayed in the action bar
* @return String resource identifier
*/
public abstract @StringRes int getTitleRes();
/**
* Returns the progress bar for the activity.
* <p>This progress bar is displayed above the toolbar and should be used to show busy status
* for long operations.<br/>
* The progress bar visibility is set to {@link View#GONE} by default. Make visible to use </p>
* @return Indeterminate progress bar.
*/
public ProgressBar getProgressBar(){
return mToolbarProgress;
}
/**
* Sets up the navigation drawer for this activity.
*/
private void setUpNavigationDrawer() {
mNavigationView.setNavigationItemSelectedListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
if (!mDrawerLayout.isDrawerOpen(mNavigationView))
mDrawerLayout.openDrawer(mNavigationView);
else
mDrawerLayout.closeDrawer(mNavigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Update the display name of the currently active book
*/
protected void updateActiveBookName(){
mBookNameTextView.setText(BooksDbAdapter.getInstance().getActiveBookDisplayName());
}
/**
* Handler for the navigation drawer items
* */
protected void onDrawerMenuItemClicked(int itemId) {
switch (itemId){
case R.id.nav_item_open: { //Open... files
//use the storage access framework
Intent openDocument = new Intent(Intent.ACTION_OPEN_DOCUMENT);
openDocument.addCategory(Intent.CATEGORY_OPENABLE);
openDocument.setType("text/*|application/*");
String[] mimeTypes = {"text/*", "application/*"};
openDocument.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
startActivityForResult(openDocument, REQUEST_OPEN_DOCUMENT);
}
break;
case R.id.nav_item_favorites: { //favorite accounts
Intent intent = new Intent(this, AccountsActivity.class);
intent.putExtra(AccountsActivity.EXTRA_TAB_INDEX,
AccountsActivity.INDEX_FAVORITE_ACCOUNTS_FRAGMENT);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
break;
case R.id.nav_item_reports: {
Intent intent = new Intent(this, ReportsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
break;
/*
//todo: Re-enable this when Budget UI is complete
case R.id.nav_item_budgets:
startActivity(new Intent(this, BudgetsActivity.class));
break;
*/
case R.id.nav_item_scheduled_actions: { //show scheduled transactions
Intent intent = new Intent(this, ScheduledActionsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
break;
case R.id.nav_item_export:
AccountsActivity.openExportFragment(this);
break;
case R.id.nav_item_settings: //Settings activity
startActivity(new Intent(this, PreferenceActivity.class));
break;
case R.id.nav_item_help:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean(UxArgument.SKIP_PASSCODE_SCREEN, true).apply();
UserVoice.launchUserVoice(this);
break;
}
mDrawerLayout.closeDrawer(mNavigationView);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
switch (requestCode) {
case AccountsActivity.REQUEST_PICK_ACCOUNTS_FILE:
AccountsActivity.importXmlFileFromIntent(this, data, null);
break;
case BaseDrawerActivity.REQUEST_OPEN_DOCUMENT: //this uses the Storage Access Framework
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
AccountsActivity.importXmlFileFromIntent(this, data, null);
getContentResolver().takePersistableUriPermission(data.getData(), takeFlags);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
long id = item.getItemId();
if (id == ID_MANAGE_BOOKS){
Intent intent = new Intent(this, PreferenceActivity.class);
intent.setAction(PreferenceActivity.ACTION_MANAGE_BOOKS);
startActivity(intent);
mDrawerLayout.closeDrawer(mNavigationView);
return true;
}
BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance();
String bookUID = booksDbAdapter.getUID(id);
if (!bookUID.equals(booksDbAdapter.getActiveBookUID())){
BookUtils.loadBook(bookUID);
finish();
}
AccountsActivity.start(GnuCashApplication.getAppContext());
return true;
}
public void onClickAppTitle(View view){
mDrawerLayout.closeDrawer(mNavigationView);
AccountsActivity.start(this);
}
public void onClickBook(View view){
PopupMenu popup = new PopupMenu(this, view);
popup.setOnMenuItemClickListener(this);
Menu menu = popup.getMenu();
int maxRecent = 0;
Cursor cursor = BooksDbAdapter.getInstance().fetchAllRecords(null, null,
DatabaseSchema.BookEntry.COLUMN_MODIFIED_AT + " DESC");
while (cursor.moveToNext() && maxRecent++ < 5) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseSchema.BookEntry._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.BookEntry.COLUMN_DISPLAY_NAME));
menu.add(0, (int)id, maxRecent, name);
}
menu.add(0, ID_MANAGE_BOOKS, maxRecent, R.string.menu_manage_books);
popup.show();
}
}
| 13,868 | 37.740223 | 119 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/common/FormActivity.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.common;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.ui.account.AccountFormFragment;
import org.gnucash.android.ui.budget.BudgetAmountEditorFragment;
import org.gnucash.android.ui.budget.BudgetFormFragment;
import org.gnucash.android.ui.export.ExportFormFragment;
import org.gnucash.android.ui.passcode.PasscodeLockActivity;
import org.gnucash.android.ui.transaction.SplitEditorFragment;
import org.gnucash.android.ui.transaction.TransactionFormFragment;
import org.gnucash.android.ui.util.widget.CalculatorKeyboard;
import org.gnucash.android.util.BookUtils;
/**
* Activity for displaying forms in the application.
* The activity provides the standard close button, but it is up to the form fragments to display
* menu options (e.g. for saving etc)
* @author Ngewi Fet <[email protected]>
*/
public class FormActivity extends PasscodeLockActivity {
private String mAccountUID;
private CalculatorKeyboard mOnBackListener;
public enum FormType {ACCOUNT, TRANSACTION, EXPORT, SPLIT_EDITOR, BUDGET, BUDGET_AMOUNT_EDITOR}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
//if a parameter was passed to open an account within a specific book, then switch
String bookUID = getIntent().getStringExtra(UxArgument.BOOK_UID);
if (bookUID != null && !bookUID.equals(BooksDbAdapter.getInstance().getActiveBookUID())){
BookUtils.activateBook(bookUID);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
assert(actionBar != null);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp);
final Intent intent = getIntent();
String formtypeString = intent.getStringExtra(UxArgument.FORM_TYPE);
FormType formType = FormType.valueOf(formtypeString);
mAccountUID = intent.getStringExtra(UxArgument.SELECTED_ACCOUNT_UID);
if (mAccountUID == null){
mAccountUID = intent.getStringExtra(UxArgument.PARENT_ACCOUNT_UID);
}
if (mAccountUID != null) {
int colorCode = AccountsDbAdapter.getActiveAccountColorResource(mAccountUID);
actionBar.setBackgroundDrawable(new ColorDrawable(colorCode));
if (Build.VERSION.SDK_INT > 20)
getWindow().setStatusBarColor(GnuCashApplication.darken(colorCode));
}
switch (formType){
case ACCOUNT:
showAccountFormFragment(intent.getExtras());
break;
case TRANSACTION:
showTransactionFormFragment(intent.getExtras());
break;
case EXPORT:
showExportFormFragment(null);
break;
case SPLIT_EDITOR:
showSplitEditorFragment(intent.getExtras());
break;
case BUDGET:
showBudgetFormFragment(intent.getExtras());
break;
case BUDGET_AMOUNT_EDITOR:
showBudgetAmountEditorFragment(intent.getExtras());
break;
default:
throw new IllegalArgumentException("No form display type specified");
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
setResult(RESULT_CANCELED);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Return the GUID of the account for which the form is displayed.
* If the form is a transaction form, the transaction is created within that account. If it is
* an account form, then the GUID is the parent account
* @return GUID of account
*/
public String getCurrentAccountUID() {
return mAccountUID;
}
/**
* Shows the form for creating/editing accounts
* @param args Arguments to use for initializing the form.
* This could be an account to edit or a preset for the parent account
*/
private void showAccountFormFragment(Bundle args){
AccountFormFragment accountFormFragment = AccountFormFragment.newInstance();
accountFormFragment.setArguments(args);
showFormFragment(accountFormFragment);
}
/**
* Loads the transaction insert/edit fragment and passes the arguments
* @param args Bundle arguments to be passed to the fragment
*/
private void showTransactionFormFragment(Bundle args){
TransactionFormFragment transactionFormFragment = new TransactionFormFragment();
transactionFormFragment.setArguments(args);
showFormFragment(transactionFormFragment);
}
/**
* Loads the export form fragment and passes the arguments
* @param args Bundle arguments
*/
private void showExportFormFragment(Bundle args){
ExportFormFragment exportFragment = new ExportFormFragment();
exportFragment.setArguments(args);
showFormFragment(exportFragment);
}
/**
* Load the split editor fragment
* @param args View arguments
*/
private void showSplitEditorFragment(Bundle args){
SplitEditorFragment splitEditor = SplitEditorFragment.newInstance(args);
showFormFragment(splitEditor);
}
/**
* Load the budget form
* @param args View arguments
*/
private void showBudgetFormFragment(Bundle args){
BudgetFormFragment budgetFormFragment = new BudgetFormFragment();
budgetFormFragment.setArguments(args);
showFormFragment(budgetFormFragment);
}
/**
* Load the budget amount editor fragment
* @param args Arguments
*/
private void showBudgetAmountEditorFragment(Bundle args){
BudgetAmountEditorFragment fragment = BudgetAmountEditorFragment.newInstance(args);
showFormFragment(fragment);
}
/**
* Loads the fragment into the fragment container, replacing whatever was there before
* @param fragment Fragment to be displayed
*/
private void showFormFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
public void setOnBackListener(CalculatorKeyboard keyboard) {
mOnBackListener = keyboard;
}
@Override
public void onBackPressed() {
boolean eventProcessed = false;
if (mOnBackListener != null)
eventProcessed = mOnBackListener.onBackPressed();
if (!eventProcessed)
super.onBackPressed();
}
}
| 8,230 | 34.175214 | 99 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/common/Refreshable.java
|
/*
* Copyright (c) 2013 - 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.common;
/**
* Interface for fragments which are refreshable
* @author Ngewi Fet <[email protected]>
*/
public interface Refreshable {
/**
* Refresh the list, typically be restarting the loader
*/
public void refresh();
/**
* Refresh the list with modified parameters
* @param uid GUID of relevant item to be refreshed
*/
public void refresh(String uid);
}
| 1,056 | 29.2 | 75 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/common/UxArgument.java
|
/*
* Copyright (c) 2014 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.common;
/**
* Collection of constants which are passed across multiple pieces of the UI (fragments, activities, dialogs)
*
* @author Ngewi Fet <[email protected]>
*/
public final class UxArgument {
/**
* Key for passing the transaction GUID as parameter in a bundle
*/
public static final String SELECTED_TRANSACTION_UID = "selected_transaction_uid";
/**
* Key for passing list of IDs selected transactions as an argument in a bundle or intent
*/
public static final String SELECTED_TRANSACTION_IDS = "selected_transactions";
/**
* Key for the origin account as argument when moving accounts
*/
public static final String ORIGIN_ACCOUNT_UID = "origin_acccount_uid";
/**
* Key for checking whether the passcode is enabled or not
*/
public static final String ENABLED_PASSCODE = "enabled_passcode";
/**
* Key for disabling the passcode
*/
public static final String DISABLE_PASSCODE = "disable_passcode";
/**
* Key for storing the passcode
*/
public static final String PASSCODE = "passcode";
/**
* Key for skipping the passcode screen. Use this only when there is no other choice.
*/
public static final String SKIP_PASSCODE_SCREEN = "skip_passcode_screen";
/**
* Amount passed as a string
*/
public static final String AMOUNT_STRING = "starting_amount";
/**
* Class caller, which will be launched after the unlocking
*/
public static final String PASSCODE_CLASS_CALLER = "passcode_class_caller";
/**
* Key for passing the account unique ID as argument to UI
*/
public static final String SELECTED_ACCOUNT_UID = "account_uid";
/**
* Key for passing whether a widget should hide the account balance or not
*/
public static final String HIDE_ACCOUNT_BALANCE_IN_WIDGET = "hide_account_balance";
/**
* Key for passing argument for the parent account GUID.
*/
public static final String PARENT_ACCOUNT_UID = "parent_account_uid";
/**
* Key for passing the scheduled action UID to the transactions editor
*/
public static final String SCHEDULED_ACTION_UID = "scheduled_action_uid";
/**
* Type of form displayed in the {@link FormActivity}
*/
public static final String FORM_TYPE = "form_type";
/**
* List of splits which have been created using the split editor
*/
public static final String SPLIT_LIST = "split_list";
/**
* GUID of a budget
*/
public static final String BUDGET_UID = "budget_uid";
/**
* List of budget amounts (as csv)
*/
public static final String BUDGET_AMOUNT_LIST = "budget_amount_list";
/**
* GUID of a book which is relevant for a specific action
*/
public static final String BOOK_UID = "book_uid";
//prevent initialization of instances of this class
private UxArgument(){
//prevent even the native class from calling the ctor
throw new AssertionError();
}
}
| 3,718 | 29.735537 | 109 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/export/ExportFormFragment.java
|
/*
* Copyright (c) 2012-2013 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.export;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import com.codetroopers.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment;
import com.codetroopers.betterpickers.radialtimepicker.RadialTimePickerDialogFragment;
import com.codetroopers.betterpickers.recurrencepicker.EventRecurrence;
import com.codetroopers.betterpickers.recurrencepicker.EventRecurrenceFormatter;
import com.codetroopers.betterpickers.recurrencepicker.RecurrencePickerDialogFragment;
import com.dropbox.core.android.Auth;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.ScheduledActionDbAdapter;
import org.gnucash.android.export.DropboxHelper;
import org.gnucash.android.export.ExportAsyncTask;
import org.gnucash.android.export.ExportFormat;
import org.gnucash.android.export.ExportParams;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.model.BaseModel;
import org.gnucash.android.model.ScheduledAction;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.settings.BackupPreferenceFragment;
import org.gnucash.android.ui.settings.dialog.OwnCloudDialogFragment;
import org.gnucash.android.ui.transaction.TransactionFormFragment;
import org.gnucash.android.ui.util.RecurrenceParser;
import org.gnucash.android.ui.util.RecurrenceViewClickListener;
import org.gnucash.android.util.PreferencesHelper;
import org.gnucash.android.util.TimestampHelper;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Dialog fragment for exporting accounts and transactions in various formats
* <p>The dialog is used for collecting information on the export options and then passing them
* to the {@link org.gnucash.android.export.Exporter} responsible for exporting</p>
* @author Ngewi Fet <[email protected]>
*/
public class ExportFormFragment extends Fragment implements
RecurrencePickerDialogFragment.OnRecurrenceSetListener,
CalendarDatePickerDialogFragment.OnDateSetListener,
RadialTimePickerDialogFragment.OnTimeSetListener {
/**
* Request code for intent to pick export file destination
*/
private static final int REQUEST_EXPORT_FILE = 0x14;
/**
* Spinner for selecting destination for the exported file.
* The destination could either be SD card, or another application which
* accepts files, like Google Drive.
*/
@BindView(R.id.spinner_export_destination) Spinner mDestinationSpinner;
/**
* Checkbox for deleting all transactions after exporting them
*/
@BindView(R.id.checkbox_post_export_delete) CheckBox mDeleteAllCheckBox;
/**
* Text view for showing warnings based on chosen export format
*/
@BindView(R.id.export_warning) TextView mExportWarningTextView;
@BindView(R.id.target_uri) TextView mTargetUriTextView;
/**
* Recurrence text view
*/
@BindView(R.id.input_recurrence) TextView mRecurrenceTextView;
/**
* Text view displaying start date to export from
*/
@BindView(R.id.export_start_date) TextView mExportStartDate;
@BindView(R.id.export_start_time) TextView mExportStartTime;
/**
* Switch toggling whether to export all transactions or not
*/
@BindView(R.id.switch_export_all) SwitchCompat mExportAllSwitch;
@BindView(R.id.export_date_layout) LinearLayout mExportDateLayout;
@BindView(R.id.radio_ofx_format) RadioButton mOfxRadioButton;
@BindView(R.id.radio_qif_format) RadioButton mQifRadioButton;
@BindView(R.id.radio_xml_format) RadioButton mXmlRadioButton;
@BindView(R.id.radio_csv_transactions_format) RadioButton mCsvTransactionsRadioButton;
@BindView(R.id.radio_separator_comma_format) RadioButton mSeparatorCommaButton;
@BindView(R.id.radio_separator_colon_format) RadioButton mSeparatorColonButton;
@BindView(R.id.radio_separator_semicolon_format) RadioButton mSeparatorSemicolonButton;
@BindView(R.id.layout_csv_options) LinearLayout mCsvOptionsLayout;
@BindView(R.id.recurrence_options) View mRecurrenceOptionsView;
/**
* Event recurrence options
*/
private EventRecurrence mEventRecurrence = new EventRecurrence();
/**
* Recurrence rule
*/
private String mRecurrenceRule;
private Calendar mExportStartCalendar = Calendar.getInstance();
/**
* Tag for logging
*/
private static final String TAG = "ExportFormFragment";
/**
* Export format
*/
private ExportFormat mExportFormat = ExportFormat.QIF;
private ExportParams.ExportTarget mExportTarget = ExportParams.ExportTarget.SD_CARD;
/**
* The Uri target for the export
*/
private Uri mExportUri;
private char mExportCsvSeparator = ',';
/**
* Flag to determine if export has been started.
* Used to continue export after user has picked a destination file
*/
private boolean mExportStarted = false;
private void onRadioButtonClicked(View view){
switch (view.getId()){
case R.id.radio_ofx_format:
mExportFormat = ExportFormat.OFX;
if (GnuCashApplication.isDoubleEntryEnabled()){
mExportWarningTextView.setText(getActivity().getString(R.string.export_warning_ofx));
mExportWarningTextView.setVisibility(View.VISIBLE);
} else {
mExportWarningTextView.setVisibility(View.GONE);
}
OptionsViewAnimationUtils.expand(mExportDateLayout);
OptionsViewAnimationUtils.collapse(mCsvOptionsLayout);
break;
case R.id.radio_qif_format:
mExportFormat = ExportFormat.QIF;
//TODO: Also check that there exist transactions with multiple currencies before displaying warning
if (GnuCashApplication.isDoubleEntryEnabled()) {
mExportWarningTextView.setText(getActivity().getString(R.string.export_warning_qif));
mExportWarningTextView.setVisibility(View.VISIBLE);
} else {
mExportWarningTextView.setVisibility(View.GONE);
}
OptionsViewAnimationUtils.expand(mExportDateLayout);
OptionsViewAnimationUtils.collapse(mCsvOptionsLayout);
break;
case R.id.radio_xml_format:
mExportFormat = ExportFormat.XML;
mExportWarningTextView.setText(R.string.export_warning_xml);
OptionsViewAnimationUtils.collapse(mExportDateLayout);
OptionsViewAnimationUtils.collapse(mCsvOptionsLayout);
break;
case R.id.radio_csv_transactions_format:
mExportFormat = ExportFormat.CSVT;
mExportWarningTextView.setText(R.string.export_notice_csv);
OptionsViewAnimationUtils.expand(mExportDateLayout);
OptionsViewAnimationUtils.expand(mCsvOptionsLayout);
break;
case R.id.radio_separator_comma_format:
mExportCsvSeparator = ',';
break;
case R.id.radio_separator_colon_format:
mExportCsvSeparator = ':';
break;
case R.id.radio_separator_semicolon_format:
mExportCsvSeparator = ';';
break;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_export_form, container, false);
ButterKnife.bind(this, view);
bindViewListeners();
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.default_save_actions, menu);
MenuItem menuItem = menu.findItem(R.id.menu_save);
menuItem.setTitle(R.string.btn_export);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_save:
startExport();
return true;
case android.R.id.home:
getActivity().finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
assert supportActionBar != null;
supportActionBar.setTitle(R.string.title_export_dialog);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
DropboxHelper.retrieveAndSaveToken();
}
@Override
public void onPause() {
super.onPause();
// When the user try to export sharing to 3rd party service like DropBox
// then pausing all activities. That cause passcode screen appearing happened.
// We use a disposable flag to skip this unnecessary passcode screen.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs.edit().putBoolean(UxArgument.SKIP_PASSCODE_SCREEN, true).apply();
}
/**
* Starts the export of transactions with the specified parameters
*/
private void startExport(){
if (mExportTarget == ExportParams.ExportTarget.URI && mExportUri == null){
mExportStarted = true;
selectExportFile();
return;
}
ExportParams exportParameters = new ExportParams(mExportFormat);
if (mExportAllSwitch.isChecked()){
exportParameters.setExportStartTime(TimestampHelper.getTimestampFromEpochZero());
} else {
exportParameters.setExportStartTime(new Timestamp(mExportStartCalendar.getTimeInMillis()));
}
exportParameters.setExportTarget(mExportTarget);
exportParameters.setExportLocation(mExportUri != null ? mExportUri.toString() : null);
exportParameters.setDeleteTransactionsAfterExport(mDeleteAllCheckBox.isChecked());
exportParameters.setCsvSeparator(mExportCsvSeparator);
Log.i(TAG, "Commencing async export of transactions");
new ExportAsyncTask(getActivity(), GnuCashApplication.getActiveDb()).execute(exportParameters);
if (mRecurrenceRule != null) {
ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP);
scheduledAction.setRecurrence(RecurrenceParser.parse(mEventRecurrence));
scheduledAction.setTag(exportParameters.toCsv());
scheduledAction.setActionUID(BaseModel.generateUID());
ScheduledActionDbAdapter.getInstance().addRecord(scheduledAction, DatabaseAdapter.UpdateMethod.insert);
}
int position = mDestinationSpinner.getSelectedItemPosition();
PreferenceManager.getDefaultSharedPreferences(getActivity())
.edit().putInt(getString(R.string.key_last_export_destination), position)
.apply();
// finish the activity will cause the progress dialog to be leaked
// which would throw an exception
//getActivity().finish();
}
/**
* Bind views to actions when initializing the export form
*/
private void bindViewListeners(){
// export destination bindings
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.export_destinations, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDestinationSpinner.setAdapter(adapter);
mDestinationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (view == null) //the item selection is fired twice by the Android framework. Ignore the first one
return;
switch (position) {
case 0: //Save As..
mExportTarget = ExportParams.ExportTarget.URI;
mRecurrenceOptionsView.setVisibility(View.VISIBLE);
if (mExportUri != null)
setExportUriText(mExportUri.toString());
break;
case 1: //DROPBOX
setExportUriText(getString(R.string.label_dropbox_export_destination));
mRecurrenceOptionsView.setVisibility(View.VISIBLE);
mExportTarget = ExportParams.ExportTarget.DROPBOX;
String dropboxAppKey = getString(R.string.dropbox_app_key, BackupPreferenceFragment.DROPBOX_APP_KEY);
String dropboxAppSecret = getString(R.string.dropbox_app_secret, BackupPreferenceFragment.DROPBOX_APP_SECRET);
if (!DropboxHelper.hasToken()) {
Auth.startOAuth2Authentication(getActivity(), dropboxAppKey);
}
break;
case 2: //OwnCloud
setExportUriText(null);
mRecurrenceOptionsView.setVisibility(View.VISIBLE);
mExportTarget = ExportParams.ExportTarget.OWNCLOUD;
if(!(PreferenceManager.getDefaultSharedPreferences(getActivity())
.getBoolean(getString(R.string.key_owncloud_sync), false))) {
OwnCloudDialogFragment ocDialog = OwnCloudDialogFragment.newInstance(null);
ocDialog.show(getActivity().getSupportFragmentManager(), "ownCloud dialog");
}
break;
case 3: //Share File
setExportUriText(getString(R.string.label_select_destination_after_export));
mExportTarget = ExportParams.ExportTarget.SHARING;
mRecurrenceOptionsView.setVisibility(View.GONE);
break;
default:
mExportTarget = ExportParams.ExportTarget.SD_CARD;
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//nothing to see here, move along
}
});
int position = PreferenceManager.getDefaultSharedPreferences(getActivity())
.getInt(getString(R.string.key_last_export_destination), 0);
mDestinationSpinner.setSelection(position);
//**************** export start time bindings ******************
Timestamp timestamp = PreferencesHelper.getLastExportTime();
mExportStartCalendar.setTimeInMillis(timestamp.getTime());
final Date date = new Date(timestamp.getTime());
mExportStartDate.setText(TransactionFormFragment.DATE_FORMATTER.format(date));
mExportStartTime.setText(TransactionFormFragment.TIME_FORMATTER.format(date));
mExportStartDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
long dateMillis = 0;
try {
Date date = TransactionFormFragment.DATE_FORMATTER.parse(mExportStartDate.getText().toString());
dateMillis = date.getTime();
} catch (ParseException e) {
Log.e(getTag(), "Error converting input time to Date object");
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(dateMillis);
int year = calendar.get(Calendar.YEAR);
int monthOfYear = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
CalendarDatePickerDialogFragment datePickerDialog = new CalendarDatePickerDialogFragment();
datePickerDialog.setOnDateSetListener(ExportFormFragment.this);
datePickerDialog.setPreselectedDate(year, monthOfYear, dayOfMonth);
datePickerDialog.show(getFragmentManager(), "date_picker_fragment");
}
});
mExportStartTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
long timeMillis = 0;
try {
Date date = TransactionFormFragment.TIME_FORMATTER.parse(mExportStartTime.getText().toString());
timeMillis = date.getTime();
} catch (ParseException e) {
Log.e(getTag(), "Error converting input time to Date object");
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeMillis);
RadialTimePickerDialogFragment timePickerDialog = new RadialTimePickerDialogFragment();
timePickerDialog.setOnTimeSetListener(ExportFormFragment.this);
timePickerDialog.setStartTime(calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE));
timePickerDialog.show(getFragmentManager(), "time_picker_dialog_fragment");
}
});
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
mExportAllSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mExportStartDate.setEnabled(!isChecked);
mExportStartTime.setEnabled(!isChecked);
int color = isChecked ? android.R.color.darker_gray : android.R.color.black;
mExportStartDate.setTextColor(ContextCompat.getColor(getContext(), color));
mExportStartTime.setTextColor(ContextCompat.getColor(getContext(), color));
}
});
mExportAllSwitch.setChecked(sharedPrefs.getBoolean(getString(R.string.key_export_all_transactions), false));
mDeleteAllCheckBox.setChecked(sharedPrefs.getBoolean(getString(R.string.key_delete_transactions_after_export), false));
mRecurrenceTextView.setOnClickListener(new RecurrenceViewClickListener((AppCompatActivity) getActivity(), mRecurrenceRule, this));
//this part (setting the export format) must come after the recurrence view bindings above
String defaultExportFormat = sharedPrefs.getString(getString(R.string.key_default_export_format), ExportFormat.CSVT.name());
mExportFormat = ExportFormat.valueOf(defaultExportFormat);
View.OnClickListener radioClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
onRadioButtonClicked(view);
}
};
View v = getView();
assert v != null;
mOfxRadioButton.setOnClickListener(radioClickListener);
mQifRadioButton.setOnClickListener(radioClickListener);
mXmlRadioButton.setOnClickListener(radioClickListener);
mCsvTransactionsRadioButton.setOnClickListener(radioClickListener);
mSeparatorCommaButton.setOnClickListener(radioClickListener);
mSeparatorColonButton.setOnClickListener(radioClickListener);
mSeparatorSemicolonButton.setOnClickListener(radioClickListener);
ExportFormat defaultFormat = ExportFormat.valueOf(defaultExportFormat.toUpperCase());
switch (defaultFormat){
case QIF: mQifRadioButton.performClick(); break;
case OFX: mOfxRadioButton.performClick(); break;
case XML: mXmlRadioButton.performClick(); break;
case CSVT: mCsvTransactionsRadioButton.performClick(); break;
}
if (GnuCashApplication.isDoubleEntryEnabled()){
mOfxRadioButton.setVisibility(View.GONE);
} else {
mXmlRadioButton.setVisibility(View.GONE);
}
}
/**
* Display the file path of the file where the export will be saved
* @param filepath Path to export file. If {@code null}, the view will be hidden and nothing displayed
*/
private void setExportUriText(String filepath){
if (filepath == null){
mTargetUriTextView.setVisibility(View.GONE);
mTargetUriTextView.setText("");
} else {
mTargetUriTextView.setText(filepath);
mTargetUriTextView.setVisibility(View.VISIBLE);
}
}
/**
* Open a chooser for user to pick a file to export to
*/
private void selectExportFile() {
Intent createIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
createIntent.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
String bookName = BooksDbAdapter.getInstance().getActiveBookDisplayName();
String filename = Exporter.buildExportFilename(mExportFormat, bookName);
createIntent.putExtra(Intent.EXTRA_TITLE, filename);
startActivityForResult(createIntent, REQUEST_EXPORT_FILE);
}
@Override
public void onRecurrenceSet(String rrule) {
mRecurrenceRule = rrule;
String repeatString = getString(R.string.label_tap_to_create_schedule);
if (mRecurrenceRule != null){
mEventRecurrence.parse(mRecurrenceRule);
repeatString = EventRecurrenceFormatter.getRepeatString(getActivity(), getResources(),
mEventRecurrence, true);
}
mRecurrenceTextView.setText(repeatString);
}
/**
* Callback for when the activity chooser dialog is completed
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case BackupPreferenceFragment.REQUEST_RESOLVE_CONNECTION:
if (resultCode == Activity.RESULT_OK) {
BackupPreferenceFragment.mGoogleApiClient.connect();
}
break;
case REQUEST_EXPORT_FILE:
if (resultCode == Activity.RESULT_OK){
if (data != null){
mExportUri = data.getData();
}
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getActivity().getContentResolver().takePersistableUriPermission(mExportUri, takeFlags);
mTargetUriTextView.setText(mExportUri.toString());
if (mExportStarted)
startExport();
}
break;
}
}
@Override
public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {
Calendar cal = new GregorianCalendar(year, monthOfYear, dayOfMonth);
mExportStartDate.setText(TransactionFormFragment.DATE_FORMATTER.format(cal.getTime()));
mExportStartCalendar.set(Calendar.YEAR, year);
mExportStartCalendar.set(Calendar.MONTH, monthOfYear);
mExportStartCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
@Override
public void onTimeSet(RadialTimePickerDialogFragment dialog, int hourOfDay, int minute) {
Calendar cal = new GregorianCalendar(0, 0, 0, hourOfDay, minute);
mExportStartTime.setText(TransactionFormFragment.TIME_FORMATTER.format(cal.getTime()));
mExportStartCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
mExportStartCalendar.set(Calendar.MINUTE, minute);
}
}
// Gotten from: https://stackoverflow.com/a/31720191
class OptionsViewAnimationUtils {
public static void expand(final View v) {
v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final int targetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? ViewGroup.LayoutParams.WRAP_CONTENT
: (int)(targetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int)(3 * targetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if(interpolatedTime == 1){
v.setVisibility(View.GONE);
}else{
v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int)(3 * initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
}
| 24,222 | 35.370871 | 132 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/homescreen/WidgetConfigurationActivity.java
|
/*
* Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.homescreen;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.Toast;
import org.gnucash.android.R;
import org.gnucash.android.db.BookDbHelper;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Book;
import org.gnucash.android.model.Money;
import org.gnucash.android.receivers.TransactionAppWidgetProvider;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.common.FormActivity;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import org.gnucash.android.util.QualifiedAccountNameCursorAdapter;
import java.util.Locale;
import java.util.prefs.Preferences;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Activity for configuration which account to display on a widget.
* The activity is opened each time a widget is added to the homescreen
* @author Ngewi Fet <[email protected]>
*/
public class WidgetConfigurationActivity extends Activity {
private AccountsDbAdapter mAccountsDbAdapter;
private int mAppWidgetId;
@BindView(R.id.input_accounts_spinner) Spinner mAccountsSpinner;
@BindView(R.id.input_books_spinner) Spinner mBooksSpinner;
@BindView(R.id.input_hide_account_balance) CheckBox mHideAccountBalance;
@BindView(R.id.btn_save) Button mOkButton;
@BindView(R.id.btn_cancel) Button mCancelButton;
private SimpleCursorAdapter mAccountsCursorAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.widget_configuration);
setResult(RESULT_CANCELED);
ButterKnife.bind(this);
BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance();
Cursor booksCursor = booksDbAdapter.fetchAllRecords();
String currentBookUID = booksDbAdapter.getActiveBookUID();
//determine the position of the currently active book in the cursor
int position = 0;
while (booksCursor.moveToNext()){
String bookUID = booksCursor.getString(booksCursor.getColumnIndexOrThrow(DatabaseSchema.BookEntry.COLUMN_UID));
if (bookUID.equals(currentBookUID))
break;
++position;
}
SimpleCursorAdapter booksCursorAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, booksCursor,
new String[]{DatabaseSchema.BookEntry.COLUMN_DISPLAY_NAME},
new int[]{android.R.id.text1}, 0);
booksCursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mBooksSpinner.setAdapter(booksCursorAdapter);
mBooksSpinner.setSelection(position);
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
Cursor cursor = mAccountsDbAdapter.fetchAllRecordsOrderedByFullName();
if (cursor.getCount() <= 0){
Toast.makeText(this, R.string.error_no_accounts, Toast.LENGTH_LONG).show();
finish();
}
mAccountsCursorAdapter = new QualifiedAccountNameCursorAdapter(this, cursor);
//without this line, the app crashes when a user tries to select an account
mAccountsCursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mAccountsSpinner.setAdapter(mAccountsCursorAdapter);
boolean passcodeEnabled = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getBoolean(UxArgument.ENABLED_PASSCODE, false);
mHideAccountBalance.setChecked(passcodeEnabled);
bindListeners();
}
/**
* Sets click listeners for the buttons in the dialog
*/
private void bindListeners() {
mBooksSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Book book = BooksDbAdapter.getInstance().getRecord(id);
SQLiteDatabase db = new DatabaseHelper(WidgetConfigurationActivity.this, book.getUID()).getWritableDatabase();
mAccountsDbAdapter = new AccountsDbAdapter(db);
Cursor cursor = mAccountsDbAdapter.fetchAllRecordsOrderedByFullName();
mAccountsCursorAdapter.swapCursor(cursor);
mAccountsCursorAdapter.notifyDataSetChanged();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//nothing to see here, move along
}
});
mOkButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID){
finish();
return;
}
String bookUID = BooksDbAdapter.getInstance().getUID(mBooksSpinner.getSelectedItemId());
String accountUID = mAccountsDbAdapter.getUID(mAccountsSpinner.getSelectedItemId());
boolean hideAccountBalance = mHideAccountBalance.isChecked();
configureWidget(WidgetConfigurationActivity.this, mAppWidgetId, bookUID, accountUID, hideAccountBalance);
updateWidget(WidgetConfigurationActivity.this, mAppWidgetId);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
});
mCancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
/**
* Configure a given widget with the given parameters.
* @param context The current context
* @param appWidgetId ID of the widget to configure
* @param bookUID UID of the book for this widget
* @param accountUID UID of the account for this widget
* @param hideAccountBalance <code>true</code> if the account balance should be hidden,
* <code>false</code> otherwise
*/
public static void configureWidget(final Context context, int appWidgetId, String bookUID, String accountUID, boolean hideAccountBalance) {
context.getSharedPreferences("widget:" + appWidgetId, MODE_PRIVATE).edit()
.putString(UxArgument.BOOK_UID, bookUID)
.putString(UxArgument.SELECTED_ACCOUNT_UID, accountUID)
.putBoolean(UxArgument.HIDE_ACCOUNT_BALANCE_IN_WIDGET, hideAccountBalance)
.apply();
}
/**
* Remove the configuration for a widget. Primarily this should be called when a widget is
* destroyed.
* @param context The current context
* @param appWidgetId ID of the widget whose configuration should be removed
*/
public static void removeWidgetConfiguration(final Context context, int appWidgetId) {
context.getSharedPreferences("widget:" + appWidgetId, MODE_PRIVATE).edit()
.clear()
.apply();
}
/**
* Load obsolete preferences for a widget, if they exist, and save them using the new widget
* configuration format.
* @param context The current context
* @param appWidgetId ID of the widget whose configuration to load/save
*/
private static void loadOldPreferences(Context context, int appWidgetId) {
SharedPreferences preferences = PreferenceActivity.getActiveBookSharedPreferences();
String accountUID = preferences.getString(UxArgument.SELECTED_ACCOUNT_UID + appWidgetId, null);
if (accountUID != null) {
String bookUID = BooksDbAdapter.getInstance().getActiveBookUID();
boolean hideAccountBalance = preferences.getBoolean(UxArgument.HIDE_ACCOUNT_BALANCE_IN_WIDGET + appWidgetId, false);
configureWidget(context, appWidgetId, bookUID, accountUID, hideAccountBalance);
preferences.edit()
.remove(UxArgument.SELECTED_ACCOUNT_UID + appWidgetId)
.remove(UxArgument.HIDE_ACCOUNT_BALANCE_IN_WIDGET + appWidgetId)
.apply();
}
}
/**
* Updates the widget with id <code>appWidgetId</code> with information from the
* account with record ID <code>accountId</code>
* If the account has been deleted, then a notice is posted in the widget
* @param appWidgetId ID of the widget to be updated
*/
public static void updateWidget(final Context context, int appWidgetId) {
Log.i("WidgetConfiguration", "Updating widget: " + appWidgetId);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
loadOldPreferences(context, appWidgetId);
SharedPreferences preferences = context.getSharedPreferences("widget:" + appWidgetId, MODE_PRIVATE);
String bookUID = preferences.getString(UxArgument.BOOK_UID, null);
String accountUID = preferences.getString(UxArgument.SELECTED_ACCOUNT_UID, null);
boolean hideAccountBalance = preferences.getBoolean(UxArgument.HIDE_ACCOUNT_BALANCE_IN_WIDGET, false);
if (bookUID == null || accountUID == null) {
return;
}
AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(BookDbHelper.getDatabase(bookUID));
final Account account;
try {
account = accountsDbAdapter.getRecord(accountUID);
} catch (IllegalArgumentException e) {
Log.i("WidgetConfiguration", "Account not found, resetting widget " + appWidgetId);
//if account has been deleted, let the user know
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_4x1);
views.setTextViewText(R.id.account_name, context.getString(R.string.toast_account_deleted));
views.setTextViewText(R.id.transactions_summary, "");
//set it to simply open the app
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
new Intent(context, AccountsActivity.class), 0);
views.setOnClickPendingIntent(R.id.widget_layout, pendingIntent);
views.setOnClickPendingIntent(R.id.btn_new_transaction, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
Editor editor = PreferenceActivity.getActiveBookSharedPreferences().edit(); //PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.remove(UxArgument.SELECTED_ACCOUNT_UID + appWidgetId);
editor.apply();
return;
}
final RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_4x1);
views.setTextViewText(R.id.account_name, account.getName());
Money accountBalance = accountsDbAdapter.getAccountBalance(accountUID, -1, System.currentTimeMillis());
if (hideAccountBalance) {
views.setViewVisibility(R.id.transactions_summary, View.GONE);
} else {
views.setTextViewText(R.id.transactions_summary,
accountBalance.formattedString(Locale.getDefault()));
int color = accountBalance.isNegative() ? R.color.debit_red : R.color.credit_green;
views.setTextColor(R.id.transactions_summary, ContextCompat.getColor(context, color));
}
Intent accountViewIntent = new Intent(context, TransactionsActivity.class);
accountViewIntent.setAction(Intent.ACTION_VIEW);
accountViewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
accountViewIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID);
accountViewIntent.putExtra(UxArgument.BOOK_UID, bookUID);
PendingIntent accountPendingIntent = PendingIntent
.getActivity(context, appWidgetId, accountViewIntent, 0);
views.setOnClickPendingIntent(R.id.widget_layout, accountPendingIntent);
if (accountsDbAdapter.isPlaceholderAccount(accountUID)) {
views.setOnClickPendingIntent(R.id.btn_view_account, accountPendingIntent);
views.setViewVisibility(R.id.btn_new_transaction, View.GONE);
} else {
Intent newTransactionIntent = new Intent(context, FormActivity.class);
newTransactionIntent.setAction(Intent.ACTION_INSERT_OR_EDIT);
newTransactionIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newTransactionIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.TRANSACTION.name());
newTransactionIntent.putExtra(UxArgument.BOOK_UID, bookUID);
newTransactionIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID);
PendingIntent pendingIntent = PendingIntent
.getActivity(context, appWidgetId, newTransactionIntent, 0);
views.setOnClickPendingIntent(R.id.btn_new_transaction, pendingIntent);
views.setViewVisibility(R.id.btn_view_account, View.GONE);
}
appWidgetManager.updateAppWidget(appWidgetId, views);
}
/**
* Updates all widgets belonging to the application
* @param context Application context
*/
public static void updateAllWidgets(final Context context){
Log.i("WidgetConfiguration", "Updating all widgets");
AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
ComponentName componentName = new ComponentName(context, TransactionAppWidgetProvider.class);
final int[] appWidgetIds = widgetManager.getAppWidgetIds(componentName);
//update widgets asynchronously so as not to block method which called the update
//inside the computation of the account balance
new Thread(new Runnable() {
@Override
public void run() {
for (final int widgetId : appWidgetIds) {
updateWidget(context, widgetId);
}
}
}).start();
}
}
| 14,542 | 39.851124 | 143 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/passcode/KeyboardFragment.java
|
/*
* Copyright (c) 2014 Oleksandr Tyshkovets <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.passcode;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.gnucash.android.R;
/**
* Soft numeric keyboard for lock screen and passcode preference.
* @author Oleksandr Tyshkovets <[email protected]>
*/
public class KeyboardFragment extends Fragment {
private static final int DELAY = 500;
private TextView pass1;
private TextView pass2;
private TextView pass3;
private TextView pass4;
private int length = 0;
public interface OnPasscodeEnteredListener {
void onPasscodeEntered(String pass);
}
private OnPasscodeEnteredListener listener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_numeric_keyboard, container, false);
pass1 = (TextView) rootView.findViewById(R.id.passcode1);
pass2 = (TextView) rootView.findViewById(R.id.passcode2);
pass3 = (TextView) rootView.findViewById(R.id.passcode3);
pass4 = (TextView) rootView.findViewById(R.id.passcode4);
rootView.findViewById(R.id.one_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("1");
}
});
rootView.findViewById(R.id.two_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("2");
}
});
rootView.findViewById(R.id.three_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("3");
}
});
rootView.findViewById(R.id.four_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("4");
}
});
rootView.findViewById(R.id.five_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("5");
}
});
rootView.findViewById(R.id.six_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("6");
}
});
rootView.findViewById(R.id.seven_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("7");
}
});
rootView.findViewById(R.id.eight_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("8");
}
});
rootView.findViewById(R.id.nine_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("9");
}
});
rootView.findViewById(R.id.zero_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add("0");
}
});
rootView.findViewById(R.id.delete_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (length) {
case 1:
pass1.setText(null);
length--;
break;
case 2:
pass2.setText(null);
length--;
break;
case 3:
pass3.setText(null);
length--;
break;
case 4:
pass4.setText(null);
length--;
}
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (OnPasscodeEnteredListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement "
+ KeyboardFragment.OnPasscodeEnteredListener.class);
}
}
private void add(String num) {
switch (length + 1) {
case 1:
pass1.setText(num);
length++;
break;
case 2:
pass2.setText(num);
length++;
break;
case 3:
pass3.setText(num);
length++;
break;
case 4:
pass4.setText(num);
length++;
new Handler().postDelayed(new Runnable() {
public void run() {
listener.onPasscodeEntered(pass1.getText().toString() + pass2.getText()
+ pass3.getText() + pass4.getText());
pass1.setText(null);
pass2.setText(null);
pass3.setText(null);
pass4.setText(null);
length = 0;
}
}, DELAY);
}
}
}
| 6,241 | 31.680628 | 103 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/passcode/PasscodeLockActivity.java
|
/*
* Copyright (c) 2014-2015 Oleksandr Tyshkovets <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.passcode;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager.LayoutParams;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.ui.common.UxArgument;
/**
* This activity used as the parent class for enabling passcode lock
*
* @author Oleksandr Tyshkovets <[email protected]>
* @see org.gnucash.android.ui.account.AccountsActivity
* @see org.gnucash.android.ui.transaction.TransactionsActivity
*/
public class PasscodeLockActivity extends AppCompatActivity {
private static final String TAG = "PasscodeLockActivity";
@Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean isPassEnabled = prefs.getBoolean(UxArgument.ENABLED_PASSCODE, false);
if (isPassEnabled) {
getWindow().addFlags(LayoutParams.FLAG_SECURE);
} else {
getWindow().clearFlags(LayoutParams.FLAG_SECURE);
}
// Only for Android Lollipop that brings a few changes to the recent apps feature
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
GnuCashApplication.PASSCODE_SESSION_INIT_TIME = 0;
}
// see ExportFormFragment.onPause()
boolean skipPasscode = prefs.getBoolean(UxArgument.SKIP_PASSCODE_SCREEN, false);
prefs.edit().remove(UxArgument.SKIP_PASSCODE_SCREEN).apply();
String passCode = prefs.getString(UxArgument.PASSCODE, "");
if (isPassEnabled && !isSessionActive() && !passCode.trim().isEmpty() && !skipPasscode) {
Log.v(TAG, "Show passcode screen");
Intent intent = new Intent(this, PasscodeLockScreenActivity.class)
.setAction(getIntent().getAction())
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)
.putExtra(UxArgument.PASSCODE_CLASS_CALLER, this.getClass().getName());
if (getIntent().getExtras() != null)
intent.putExtras(getIntent().getExtras());
startActivity(intent);
}
}
@Override
protected void onPause() {
super.onPause();
GnuCashApplication.PASSCODE_SESSION_INIT_TIME = System.currentTimeMillis();
}
/**
* @return {@code true} if passcode session is active, and {@code false} otherwise
*/
private boolean isSessionActive() {
return System.currentTimeMillis() - GnuCashApplication.PASSCODE_SESSION_INIT_TIME
< GnuCashApplication.SESSION_TIMEOUT;
}
}
| 3,475 | 38.05618 | 105 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/passcode/PasscodeLockScreenActivity.java
|
/*
* Copyright (c) 2014 - 2015 Oleksandr Tyshkovets <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.passcode;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.ui.common.UxArgument;
/**
* Activity for displaying and managing the passcode lock screen.
* @author Oleksandr Tyshkovets <[email protected]>
*/
public class PasscodeLockScreenActivity extends AppCompatActivity
implements KeyboardFragment.OnPasscodeEnteredListener {
private static final String TAG = "PassLockScreenActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.passcode_lockscreen);
}
@Override
public void onPasscodeEntered(String pass) {
String passcode = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getString(UxArgument.PASSCODE, "");
Log.d(TAG, "Passcode: " + passcode);
if (pass.equals(passcode)) {
if (UxArgument.DISABLE_PASSCODE.equals(getIntent().getStringExtra(UxArgument.DISABLE_PASSCODE))) {
setResult(RESULT_OK);
finish();
return;
}
GnuCashApplication.PASSCODE_SESSION_INIT_TIME = System.currentTimeMillis();
startActivity(new Intent()
.setClassName(this, getIntent().getStringExtra(UxArgument.PASSCODE_CLASS_CALLER))
.setAction(getIntent().getAction())
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)
.putExtras(getIntent().getExtras())
);
} else {
Toast.makeText(this, R.string.toast_wrong_passcode, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onBackPressed() {
setResult(RESULT_CANCELED);
if (UxArgument.DISABLE_PASSCODE.equals(getIntent().getStringExtra(UxArgument.DISABLE_PASSCODE))) {
finish();
return;
}
GnuCashApplication.PASSCODE_SESSION_INIT_TIME = System.currentTimeMillis() - GnuCashApplication.SESSION_TIMEOUT;
startActivity(new Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_HOME)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
);
}
}
| 3,203 | 36.255814 | 127 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/passcode/PasscodePreferenceActivity.java
|
/*
* Copyright (c) 2014 - 2015 Oleksandr Tyshkovets <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.passcode;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import org.gnucash.android.R;
import org.gnucash.android.ui.common.UxArgument;
/**
* Activity for entering and confirming passcode
* @author Oleksandr Tyshkovets <[email protected]>
*/
public class PasscodePreferenceActivity extends AppCompatActivity
implements KeyboardFragment.OnPasscodeEnteredListener {
private boolean mIsPassEnabled;
private boolean mReenter = false;
private String mPasscode;
private TextView mPassTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.passcode_lockscreen);
mPassTextView = (TextView) findViewById(R.id.passcode_label);
mIsPassEnabled = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getBoolean(UxArgument.ENABLED_PASSCODE, false);
if (mIsPassEnabled) {
mPassTextView.setText(R.string.label_old_passcode);
}
}
@Override
public void onPasscodeEntered(String pass) {
String passCode = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getString(UxArgument.PASSCODE, "");
if (mIsPassEnabled) {
if (pass.equals(passCode)) {
mIsPassEnabled = false;
mPassTextView.setText(R.string.label_new_passcode);
} else {
Toast.makeText(this, R.string.toast_wrong_passcode, Toast.LENGTH_SHORT).show();
}
return;
}
if (mReenter) {
if (mPasscode.equals(pass)) {
setResult(RESULT_OK, new Intent().putExtra(UxArgument.PASSCODE, pass));
finish();
} else {
Toast.makeText(this, R.string.toast_invalid_passcode_confirmation, Toast.LENGTH_LONG).show();
}
} else {
mPasscode = pass;
mReenter = true;
mPassTextView.setText(R.string.label_confirm_passcode);
}
}
}
| 2,934 | 32.735632 | 109 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/report/BaseReportFragment.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.report;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.ui.common.Refreshable;
import org.joda.time.LocalDateTime;
import org.joda.time.Months;
import org.joda.time.Years;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Base class for report fragments.
* <p>All report fragments should extend this class. At the minimum, reports must implement
* {@link #getLayoutResource()}, {@link #getReportType()}, {@link #generateReport()}, {@link #displayReport()} and {@link #getTitle()}</p>
* <p>Implementing classes should create their own XML layouts and provide it in {@link #getLayoutResource()}.
* Then annotate any views in the resource using {@code @Bind} annotation from ButterKnife library.
* This base activity will automatically call {@link ButterKnife#bind(View)} for the layout.
* </p>
* <p>Any custom information to be initialized for the report should be done in {@link #onActivityCreated(Bundle)} in implementing classes.
* The report is then generated in {@link #onStart()}
* </p>
* @author Ngewi Fet <[email protected]>
*/
public abstract class BaseReportFragment extends Fragment implements
OnChartValueSelectedListener, ReportOptionsListener, Refreshable {
/**
* Color for chart with no data
*/
public static final int NO_DATA_COLOR = Color.LTGRAY;
protected static String TAG = "BaseReportFragment";
/**
* Reporting period start time
*/
protected long mReportPeriodStart = -1;
/**
* Reporting period end time
*/
protected long mReportPeriodEnd = -1;
/**
* Account type for which to display reports
*/
protected AccountType mAccountType;
/**
* Commodity for which to display reports
*/
protected Commodity mCommodity;
/**
* Intervals in which to group reports
*/
protected ReportsActivity.GroupInterval mGroupInterval = ReportsActivity.GroupInterval.MONTH;
/**
* Pattern to use to display selected chart values
*/
public static final String SELECTED_VALUE_PATTERN = "%s - %.2f (%.2f %%)";
protected ReportsActivity mReportsActivity;
@Nullable @BindView(R.id.selected_chart_slice) protected TextView mSelectedValueTextView;
private AsyncTask<Void, Void, Void> mReportGenerator;
/**
* Return the title of this report
* @return Title string identifier
*/
public abstract @StringRes int getTitle();
/**
* Returns the layout resource to use for this report
* @return Layout resource identifier
*/
public abstract @LayoutRes int getLayoutResource();
/**
* Returns what kind of report this is
* @return Type of report
*/
public abstract ReportType getReportType();
/**
* Return {@code true} if this report fragment requires account type options.
* <p>Sub-classes should implement this method. The base implementation returns {@code true}</p>
* @return {@code true} if the fragment makes use of account type options, {@code false} otherwise
*/
public boolean requiresAccountTypeOptions(){
return true;
}
/**
* Return {@code true} if this report fragment requires time range options.
* <p>Base implementation returns true</p>
* @return {@code true} if the report fragment requires time range options, {@code false} otherwise
*/
public boolean requiresTimeRangeOptions(){
return true;
}
/**
* Generates the data for the report
* <p>This method should not call any methods which modify the UI as it will be run in a background thread
* <br>Put any code to update the UI in {@link #displayReport()}
* </p>
*/
protected abstract void generateReport();
/**
* Update the view after the report chart has been generated <br/>
* Sub-classes should call to the base method
*/
protected abstract void displayReport();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TAG = this.getClass().getSimpleName();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(getLayoutResource(), container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
assert actionBar != null;
actionBar.setTitle(getTitle());
setHasOptionsMenu(true);
mCommodity = CommoditiesDbAdapter.getInstance()
.getCommodity(GnuCashApplication.getDefaultCurrencyCode());
ReportsActivity reportsActivity = (ReportsActivity) getActivity();
mReportPeriodStart = reportsActivity.getReportPeriodStart();
mReportPeriodEnd = reportsActivity.getReportPeriodEnd();
mAccountType = reportsActivity.getAccountType();
}
@Override
public void onStart() {
super.onStart();
refresh();
}
@Override
public void onResume() {
super.onResume();
mReportsActivity.setAppBarColor(getReportType().getTitleColor());
mReportsActivity.toggleToolbarTitleVisibility();
toggleBaseReportingOptionsVisibility();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (!(getActivity() instanceof ReportsActivity))
throw new RuntimeException("Report fragments can only be used with the ReportsActivity");
else
mReportsActivity = (ReportsActivity) getActivity();
}
@Override
public void onDetach() {
super.onDetach();
if (mReportGenerator != null)
mReportGenerator.cancel(true);
}
private void toggleBaseReportingOptionsVisibility() {
View timeRangeLayout = mReportsActivity.findViewById(R.id.time_range_layout);
View dateRangeDivider = mReportsActivity.findViewById(R.id.date_range_divider);
if (timeRangeLayout != null && dateRangeDivider != null) {
int visibility = requiresTimeRangeOptions() ? View.VISIBLE : View.GONE;
timeRangeLayout.setVisibility(visibility);
dateRangeDivider.setVisibility(visibility);
}
View accountTypeSpinner = mReportsActivity.findViewById(R.id.report_account_type_spinner);
int visibility = requiresAccountTypeOptions() ? View.VISIBLE : View.GONE;
accountTypeSpinner.setVisibility(visibility);
}
/**
* Calculates difference between two date values accordingly to {@code mGroupInterval}
* @param start start date
* @param end end date
* @return difference between two dates or {@code -1}
*/
protected int getDateDiff(LocalDateTime start, LocalDateTime end) {
switch (mGroupInterval) {
case QUARTER:
int y = Years.yearsBetween(start.withDayOfYear(1).withMillisOfDay(0), end.withDayOfYear(1).withMillisOfDay(0)).getYears();
return getQuarter(end) - getQuarter(start) + y * 4;
case MONTH:
return Months.monthsBetween(start.withDayOfMonth(1).withMillisOfDay(0), end.withDayOfMonth(1).withMillisOfDay(0)).getMonths();
case YEAR:
return Years.yearsBetween(start.withDayOfYear(1).withMillisOfDay(0), end.withDayOfYear(1).withMillisOfDay(0)).getYears();
default:
return -1;
}
}
/**
* Returns a quarter of the specified date
* @param date date
* @return a quarter
*/
protected int getQuarter(LocalDateTime date) {
return (date.getMonthOfYear() - 1) / 3 + 1;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.chart_actions, menu);
}
@Override
public void refresh() {
if (mReportGenerator != null)
mReportGenerator.cancel(true);
mReportGenerator = new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
mReportsActivity.getProgressBar().setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... params) {
generateReport();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
displayReport();
mReportsActivity.getProgressBar().setVisibility(View.GONE);
}
};
mReportGenerator.execute();
}
/**
* Charts do not support account specific refreshes in general.
* So we provide a base implementation which just calls {@link #refresh()}
*
* @param uid GUID of relevant item to be refreshed
*/
@Override
public void refresh(String uid) {
refresh();
}
@Override
public void onGroupingUpdated(ReportsActivity.GroupInterval groupInterval) {
if (mGroupInterval != groupInterval) {
mGroupInterval = groupInterval;
refresh();
}
}
@Override
public void onTimeRangeUpdated(long start, long end) {
if (mReportPeriodStart != start || mReportPeriodEnd != end) {
mReportPeriodStart = start;
mReportPeriodEnd = end;
refresh();
}
}
@Override
public void onAccountTypeUpdated(AccountType accountType) {
if (mAccountType != accountType) {
mAccountType = accountType;
refresh();
}
}
@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
//nothing to see here, move along
}
@Override
public void onNothingSelected() {
if (mSelectedValueTextView != null)
mSelectedValueTextView.setText(R.string.select_chart_to_view_details);
}
}
| 11,708 | 32.743516 | 142 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/report/ReportOptionsListener.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.report;
import org.gnucash.android.model.AccountType;
/**
* Listener interface for passing reporting options from activity to the report fragments
*/
public interface ReportOptionsListener {
/**
* Notify the implementing class of the selected date range
* @param start Start date in milliseconds since epoch
* @param end End date in milliseconds since epoch
*/
void onTimeRangeUpdated(long start, long end);
/**
* Updates the listener on a change of the grouping for the report
* @param groupInterval Group interval
*/
void onGroupingUpdated(ReportsActivity.GroupInterval groupInterval);
/**
* Update to the account type for the report
* @param accountType Account type
*/
void onAccountTypeUpdated(AccountType accountType);
}
| 1,455 | 32.090909 | 89 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/report/ReportType.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.report;
import android.content.Context;
import android.support.annotation.ColorRes;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.ui.report.barchart.StackedBarChartFragment;
import org.gnucash.android.ui.report.linechart.CashFlowLineChartFragment;
import org.gnucash.android.ui.report.piechart.PieChartFragment;
import org.gnucash.android.ui.report.sheet.BalanceSheetFragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Different types of reports
* <p>This class also contains mappings for the reports of the different types which are available
* in the system. When adding a new report, make sure to add a mapping in the constructor</p>
*/
public enum ReportType {
PIE_CHART(0), BAR_CHART(1), LINE_CHART(2), TEXT(3), NONE(4);
Map<String, Class> mReportTypeMap = new HashMap<>();
int mValue = 4;
ReportType(int index){
mValue = index;
Context context = GnuCashApplication.getAppContext();
switch (index){
case 0:
mReportTypeMap.put(context.getString(R.string.title_pie_chart), PieChartFragment.class);
break;
case 1:
mReportTypeMap.put(context.getString(R.string.title_bar_chart), StackedBarChartFragment.class);
break;
case 2:
mReportTypeMap.put(context.getString(R.string.title_cash_flow_report), CashFlowLineChartFragment.class);
break;
case 3:
mReportTypeMap.put(context.getString(R.string.title_balance_sheet_report), BalanceSheetFragment.class);
break;
case 4:
break;
}
}
/**
* Returns the toolbar color to be used for this report type
* @return Color resource
*/
public @ColorRes int getTitleColor(){
switch (mValue){
case 0:
return R.color.account_green;
case 1:
return R.color.account_red;
case 2:
return R.color.account_blue;
case 3:
return R.color.account_purple;
case 4:
default:
return R.color.theme_primary;
}
}
public List<String> getReportNames(){
return new ArrayList<>(mReportTypeMap.keySet());
}
public BaseReportFragment getFragment(String name){
BaseReportFragment fragment = null;
try {
fragment = (BaseReportFragment) mReportTypeMap.get(name).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return fragment;
}
}
| 3,464 | 32.970588 | 120 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/report/ReportsActivity.java
|
/*
* Copyright (c) 2015 Oleksandr Tyshkovets <[email protected]>
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.report;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.Spinner;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.ui.common.BaseDrawerActivity;
import org.gnucash.android.ui.common.Refreshable;
import org.gnucash.android.ui.util.dialog.DateRangePickerDialogFragment;
import org.joda.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
/**
* Activity for displaying report fragments (which must implement {@link BaseReportFragment})
* <p>In order to add new reports, extend the {@link BaseReportFragment} class to provide the view
* for the report. Then add the report mapping in {@link ReportType} constructor depending on what
* kind of report it is. The report will be dynamically included at runtime.</p>
*
* @author Oleksandr Tyshkovets <[email protected]>
* @author Ngewi Fet <[email protected]>
*/
public class ReportsActivity extends BaseDrawerActivity implements AdapterView.OnItemSelectedListener,
DatePickerDialog.OnDateSetListener, DateRangePickerDialogFragment.OnDateRangeSetListener,
Refreshable{
public static final int[] COLORS = {
Color.parseColor("#17ee4e"), Color.parseColor("#cc1f09"), Color.parseColor("#3940f7"),
Color.parseColor("#f9cd04"), Color.parseColor("#5f33a8"), Color.parseColor("#e005b6"),
Color.parseColor("#17d6ed"), Color.parseColor("#e4a9a2"), Color.parseColor("#8fe6cd"),
Color.parseColor("#8b48fb"), Color.parseColor("#343a36"), Color.parseColor("#6decb1"),
Color.parseColor("#f0f8ff"), Color.parseColor("#5c3378"), Color.parseColor("#a6dcfd"),
Color.parseColor("#ba037c"), Color.parseColor("#708809"), Color.parseColor("#32072c"),
Color.parseColor("#fddef8"), Color.parseColor("#fa0e6e"), Color.parseColor("#d9e7b5")
};
private static final String STATE_REPORT_TYPE = "STATE_REPORT_TYPE";
@BindView(R.id.time_range_spinner) Spinner mTimeRangeSpinner;
@BindView(R.id.report_account_type_spinner) Spinner mAccountTypeSpinner;
@BindView(R.id.toolbar_spinner) Spinner mReportTypeSpinner;
private TransactionsDbAdapter mTransactionsDbAdapter;
private AccountType mAccountType = AccountType.EXPENSE;
private ReportType mReportType = ReportType.NONE;
private ReportsOverviewFragment mReportsOverviewFragment;
public enum GroupInterval {WEEK, MONTH, QUARTER, YEAR, ALL}
// default time range is the last 3 months
private long mReportPeriodStart = new LocalDate().minusMonths(2).dayOfMonth().withMinimumValue().toDate().getTime();
private long mReportPeriodEnd = new LocalDate().plusDays(1).toDate().getTime();
private GroupInterval mReportGroupInterval = GroupInterval.MONTH;
private boolean mSkipNextReportTypeSelectedRun = false;
AdapterView.OnItemSelectedListener mReportTypeSelectedListener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mSkipNextReportTypeSelectedRun){
mSkipNextReportTypeSelectedRun = false;
} else {
String reportName = parent.getItemAtPosition(position).toString();
loadFragment(mReportType.getFragment(reportName));
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//nothing to see here, move along
}
};
@Override
public int getContentView() {
return R.layout.activity_reports;
}
@Override
public int getTitleRes() {
return R.string.title_reports;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mReportType = (ReportType) savedInstanceState.getSerializable(STATE_REPORT_TYPE);
}
super.onCreate(savedInstanceState);
mTransactionsDbAdapter = TransactionsDbAdapter.getInstance();
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.report_time_range,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mTimeRangeSpinner.setAdapter(adapter);
mTimeRangeSpinner.setOnItemSelectedListener(this);
mTimeRangeSpinner.setSelection(1);
ArrayAdapter<CharSequence> dataAdapter = ArrayAdapter.createFromResource(this,
R.array.report_account_types, android.R.layout.simple_spinner_item);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mAccountTypeSpinner.setAdapter(dataAdapter);
mAccountTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
switch(position) {
default:
case 0:
mAccountType = AccountType.EXPENSE;
break;
case 1:
mAccountType = AccountType.INCOME;
}
updateAccountTypeOnFragments();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
//nothing to see here, move along
}
});
mReportsOverviewFragment = new ReportsOverviewFragment();
if (savedInstanceState == null) {
loadFragment(mReportsOverviewFragment);
}
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
if (fragment instanceof BaseReportFragment) {
BaseReportFragment reportFragment = (BaseReportFragment)fragment;
updateReportTypeSpinner(reportFragment.getReportType(), getString(reportFragment.getTitle()));
}
}
/**
* Load the provided fragment into the view replacing the previous one
* @param fragment BaseReportFragment instance
*/
private void loadFragment(BaseReportFragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
/**
* Update the report type spinner
*/
public void updateReportTypeSpinner(ReportType reportType, String reportName) {
if (reportType == mReportType)//if it is the same report type, don't change anything
return;
mReportType = reportType;
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(actionBar.getThemedContext(),
android.R.layout.simple_list_item_1,
mReportType.getReportNames());
mSkipNextReportTypeSelectedRun = true; //selection event will be fired again
mReportTypeSpinner.setAdapter(arrayAdapter);
mReportTypeSpinner.setSelection(arrayAdapter.getPosition(reportName));
mReportTypeSpinner.setOnItemSelectedListener(mReportTypeSelectedListener);
toggleToolbarTitleVisibility();
}
public void toggleToolbarTitleVisibility() {
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
if (mReportType == ReportType.NONE){
mReportTypeSpinner.setVisibility(View.GONE);
} else {
mReportTypeSpinner.setVisibility(View.VISIBLE);
}
actionBar.setDisplayShowTitleEnabled(mReportType == ReportType.NONE);
}
/**
* Sets the color Action Bar and Status bar (where applicable)
*/
public void setAppBarColor(int color) {
int resolvedColor = ContextCompat.getColor(this, color);
if (getSupportActionBar() != null)
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(resolvedColor));
if (Build.VERSION.SDK_INT > 20)
getWindow().setStatusBarColor(GnuCashApplication.darken(resolvedColor));
}
/**
* Updates the reporting time range for all listening fragments
*/
private void updateDateRangeOnFragment(){
List<Fragment> fragments = getSupportFragmentManager().getFragments();
for (Fragment fragment : fragments) {
if (fragment instanceof ReportOptionsListener){
((ReportOptionsListener) fragment).onTimeRangeUpdated(mReportPeriodStart, mReportPeriodEnd);
}
}
}
/**
* Updates the account type for all attached fragments which are listening
*/
private void updateAccountTypeOnFragments(){
List<Fragment> fragments = getSupportFragmentManager().getFragments();
for (Fragment fragment : fragments) {
if (fragment instanceof ReportOptionsListener){
((ReportOptionsListener) fragment).onAccountTypeUpdated(mAccountType);
}
}
}
/**
* Updates the report grouping interval on all attached fragments which are listening
*/
private void updateGroupingOnFragments(){
List<Fragment> fragments = getSupportFragmentManager().getFragments();
for (Fragment fragment : fragments) {
if (fragment instanceof ReportOptionsListener){
((ReportOptionsListener) fragment).onGroupingUpdated(mReportGroupInterval);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.report_actions, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_group_reports_by:
return true;
case R.id.group_by_month:
item.setChecked(true);
mReportGroupInterval = GroupInterval.MONTH;
updateGroupingOnFragments();
return true;
case R.id.group_by_quarter:
item.setChecked(true);
mReportGroupInterval = GroupInterval.QUARTER;
updateGroupingOnFragments();
return true;
case R.id.group_by_year:
item.setChecked(true);
mReportGroupInterval = GroupInterval.YEAR;
updateGroupingOnFragments();
return true;
case android.R.id.home:
super.onOptionsItemSelected(item);
default:
return false;
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mReportPeriodEnd = new LocalDate().plusDays(1).toDate().getTime();
switch (position){
case 0: //current month
mReportPeriodStart = new LocalDate().dayOfMonth().withMinimumValue().toDate().getTime();
break;
case 1: // last 3 months. x-2, x-1, x
mReportPeriodStart = new LocalDate().minusMonths(2).dayOfMonth().withMinimumValue().toDate().getTime();
break;
case 2:
mReportPeriodStart = new LocalDate().minusMonths(5).dayOfMonth().withMinimumValue().toDate().getTime();
break;
case 3:
mReportPeriodStart = new LocalDate().minusMonths(11).dayOfMonth().withMinimumValue().toDate().getTime();
break;
case 4: //ALL TIME
mReportPeriodStart = -1;
mReportPeriodEnd = -1;
break;
case 5:
String mCurrencyCode = GnuCashApplication.getDefaultCurrencyCode();
long earliestTransactionTime = mTransactionsDbAdapter.getTimestampOfEarliestTransaction(mAccountType, mCurrencyCode);
DialogFragment rangeFragment = DateRangePickerDialogFragment.newInstance(
earliestTransactionTime,
new LocalDate().plusDays(1).toDate().getTime(),
this);
rangeFragment.show(getSupportFragmentManager(), "range_dialog");
break;
}
if (position != 5){ //the date picker will trigger the update itself
updateDateRangeOnFragment();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//nothing to see here, move along
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, monthOfYear, dayOfMonth);
mReportPeriodStart = calendar.getTimeInMillis();
updateDateRangeOnFragment();
}
@Override
public void onDateRangeSet(Date startDate, Date endDate) {
mReportPeriodStart = startDate.getTime();
mReportPeriodEnd = endDate.getTime();
updateDateRangeOnFragment();
}
public AccountType getAccountType(){
return mAccountType;
}
/**
* Return the end time of the reporting period
* @return Time in millis
*/
public long getReportPeriodEnd() {
return mReportPeriodEnd;
}
/**
* Return the start time of the reporting period
* @return Time in millis
*/
public long getReportPeriodStart() {
return mReportPeriodStart;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
if (mReportType != ReportType.NONE){
loadFragment(mReportsOverviewFragment);
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
public void refresh() {
List<Fragment> fragments = getSupportFragmentManager().getFragments();
for (Fragment fragment : fragments) {
if (fragment instanceof Refreshable){
((Refreshable) fragment).refresh();
}
}
}
@Override
/**
* Just another call to refresh
*/
public void refresh(String uid) {
refresh();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_REPORT_TYPE, mReportType);
}
}
| 16,111 | 36.55711 | 133 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/report/ReportsOverviewFragment.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.report;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.AppCompatButton;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import org.gnucash.android.R;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.report.barchart.StackedBarChartFragment;
import org.gnucash.android.ui.report.linechart.CashFlowLineChartFragment;
import org.gnucash.android.ui.report.piechart.PieChartFragment;
import org.gnucash.android.ui.report.sheet.BalanceSheetFragment;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import org.joda.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import static com.github.mikephil.charting.components.Legend.LegendPosition;
/**
* Shows a summary of reports
* @author Ngewi Fet <[email protected]>
*/
public class ReportsOverviewFragment extends BaseReportFragment {
public static final int LEGEND_TEXT_SIZE = 14;
@BindView(R.id.btn_pie_chart) Button mPieChartButton;
@BindView(R.id.btn_bar_chart) Button mBarChartButton;
@BindView(R.id.btn_line_chart) Button mLineChartButton;
@BindView(R.id.btn_balance_sheet) Button mBalanceSheetButton;
@BindView(R.id.pie_chart) PieChart mChart;
@BindView(R.id.total_assets) TextView mTotalAssets;
@BindView(R.id.total_liabilities) TextView mTotalLiabilities;
@BindView(R.id.net_worth) TextView mNetWorth;
private AccountsDbAdapter mAccountsDbAdapter;
private Money mAssetsBalance;
private Money mLiabilitiesBalance;
private boolean mChartHasData = false;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
}
@Override
public int getLayoutResource() {
return R.layout.fragment_report_summary;
}
@Override
public int getTitle() {
return R.string.title_reports;
}
@Override
public ReportType getReportType() {
return ReportType.NONE;
}
@Override
public boolean requiresAccountTypeOptions() {
return false;
}
@Override
public boolean requiresTimeRangeOptions() {
return false;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(false);
mChart.setCenterTextSize(PieChartFragment.CENTER_TEXT_SIZE);
mChart.setDescription("");
mChart.setDrawSliceText(false);
Legend legend = mChart.getLegend();
legend.setEnabled(true);
legend.setWordWrapEnabled(true);
legend.setForm(LegendForm.CIRCLE);
legend.setPosition(LegendPosition.RIGHT_OF_CHART_CENTER);
legend.setTextSize(LEGEND_TEXT_SIZE);
ColorStateList csl = new ColorStateList(new int[][]{new int[0]}, new int[]{ContextCompat.getColor(getContext(), R.color.account_green)});
setButtonTint(mPieChartButton, csl);
csl = new ColorStateList(new int[][]{new int[0]}, new int[]{ContextCompat.getColor(getContext(), R.color.account_red)});
setButtonTint(mBarChartButton, csl);
csl = new ColorStateList(new int[][]{new int[0]}, new int[]{ContextCompat.getColor(getContext(), R.color.account_blue)});
setButtonTint(mLineChartButton, csl);
csl = new ColorStateList(new int[][]{new int[0]}, new int[]{ContextCompat.getColor(getContext(), R.color.account_purple)});
setButtonTint(mBalanceSheetButton, csl);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.menu_group_reports_by).setVisible(false);
}
@Override
protected void generateReport() {
PieData pieData = PieChartFragment.groupSmallerSlices(getData(), getActivity());
if (pieData != null && pieData.getYValCount() != 0) {
mChart.setData(pieData);
float sum = mChart.getData().getYValueSum();
String total = getResources().getString(R.string.label_chart_total);
String currencySymbol = mCommodity.getSymbol();
mChart.setCenterText(String.format(PieChartFragment.TOTAL_VALUE_LABEL_PATTERN, total, sum, currencySymbol));
mChartHasData = true;
} else {
mChart.setData(getEmptyData());
mChart.setCenterText(getResources().getString(R.string.label_chart_no_data));
mChart.getLegend().setEnabled(false);
mChartHasData = false;
}
List<AccountType> accountTypes = new ArrayList<>();
accountTypes.add(AccountType.ASSET);
accountTypes.add(AccountType.CASH);
accountTypes.add(AccountType.BANK);
mAssetsBalance = mAccountsDbAdapter.getAccountBalance(accountTypes, -1, System.currentTimeMillis());
accountTypes.clear();
accountTypes.add(AccountType.LIABILITY);
accountTypes.add(AccountType.CREDIT);
mLiabilitiesBalance = mAccountsDbAdapter.getAccountBalance(accountTypes, -1, System.currentTimeMillis());
}
/**
* Returns {@code PieData} instance with data entries, colors and labels
* @return {@code PieData} instance
*/
private PieData getData() {
PieDataSet dataSet = new PieDataSet(null, "");
List<String> labels = new ArrayList<>();
List<Integer> colors = new ArrayList<>();
for (Account account : mAccountsDbAdapter.getSimpleAccountList()) {
if (account.getAccountType() == AccountType.EXPENSE
&& !account.isPlaceholderAccount()
&& account.getCommodity().equals(mCommodity)) {
long start = new LocalDate().minusMonths(2).dayOfMonth().withMinimumValue().toDate().getTime();
long end = new LocalDate().plusDays(1).toDate().getTime();
double balance = mAccountsDbAdapter.getAccountsBalance(
Collections.singletonList(account.getUID()), start, end).asDouble();
if (balance > 0) {
dataSet.addEntry(new Entry((float) balance, dataSet.getEntryCount()));
colors.add(account.getColor() != Account.DEFAULT_COLOR
? account.getColor()
: ReportsActivity.COLORS[(dataSet.getEntryCount() - 1) % ReportsActivity.COLORS.length]);
labels.add(account.getName());
}
}
}
dataSet.setColors(colors);
dataSet.setSliceSpace(PieChartFragment.SPACE_BETWEEN_SLICES);
return new PieData(labels, dataSet);
}
@Override
protected void displayReport() {
if (mChartHasData){
mChart.animateXY(1800, 1800);
mChart.setTouchEnabled(true);
} else {
mChart.setTouchEnabled(false);
}
mChart.highlightValues(null);
mChart.invalidate();
TransactionsActivity.displayBalance(mTotalAssets, mAssetsBalance);
TransactionsActivity.displayBalance(mTotalLiabilities, mLiabilitiesBalance);
TransactionsActivity.displayBalance(mNetWorth, mAssetsBalance.subtract(mLiabilitiesBalance));
}
/**
* Returns a data object that represents situation when no user data available
* @return a {@code PieData} instance for situation when no user data available
*/
private PieData getEmptyData() {
PieDataSet dataSet = new PieDataSet(null, getResources().getString(R.string.label_chart_no_data));
dataSet.addEntry(new Entry(1, 0));
dataSet.setColor(PieChartFragment.NO_DATA_COLOR);
dataSet.setDrawValues(false);
return new PieData(Collections.singletonList(""), dataSet);
}
@OnClick({R.id.btn_bar_chart, R.id.btn_pie_chart, R.id.btn_line_chart, R.id.btn_balance_sheet})
public void onClickChartTypeButton(View view){
BaseReportFragment fragment;
switch (view.getId()){
case R.id.btn_pie_chart:
fragment = new PieChartFragment();
break;
case R.id.btn_bar_chart:
fragment = new StackedBarChartFragment();
break;
case R.id.btn_line_chart:
fragment = new CashFlowLineChartFragment();
break;
case R.id.btn_balance_sheet:
fragment = new BalanceSheetFragment();
break;
default:
fragment = this;
break;
}
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}
public void setButtonTint(Button button, ColorStateList tint) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && button instanceof AppCompatButton) {
((AppCompatButton) button).setSupportBackgroundTintList(tint);
} else {
ViewCompat.setBackgroundTintList(button, tint);
}
button.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white));
}
}
| 10,667 | 38.657993 | 145 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/report/barchart/StackedBarChartFragment.java
|
/*
* Copyright (c) 2015 Oleksandr Tyshkovets <[email protected]>
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.report.barchart;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.utils.LargeValueFormatter;
import org.gnucash.android.R;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.ui.report.BaseReportFragment;
import org.gnucash.android.ui.report.ReportType;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import static org.gnucash.android.ui.report.ReportsActivity.COLORS;
/**
* Activity used for drawing a bar chart
*
* @author Oleksandr Tyshkovets <[email protected]>
* @author Ngewi Fet <[email protected]>
*/
public class StackedBarChartFragment extends BaseReportFragment {
private static final String X_AXIS_MONTH_PATTERN = "MMM YY";
private static final String X_AXIS_QUARTER_PATTERN = "Q%d %s";
private static final String X_AXIS_YEAR_PATTERN = "YYYY";
private static final int ANIMATION_DURATION = 2000;
private static final int NO_DATA_BAR_COUNTS = 3;
private AccountsDbAdapter mAccountsDbAdapter = AccountsDbAdapter.getInstance();
@BindView(R.id.bar_chart) BarChart mChart;
private boolean mUseAccountColor = true;
private boolean mTotalPercentageMode = true;
private boolean mChartDataPresent = true;
@Override
public int getTitle() {
return R.string.title_cash_flow_report;
}
@Override
public int getLayoutResource() {
return R.layout.fragment_bar_chart;
}
@Override
public ReportType getReportType() {
return ReportType.BAR_CHART;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mUseAccountColor = PreferenceManager.getDefaultSharedPreferences(getActivity())
.getBoolean(getString(R.string.key_use_account_color), false);
mChart.setOnChartValueSelectedListener(this);
mChart.setDescription("");
// mChart.setDrawValuesForWholeStack(false);
mChart.getXAxis().setDrawGridLines(false);
mChart.getAxisRight().setEnabled(false);
mChart.getAxisLeft().setStartAtZero(false);
mChart.getAxisLeft().enableGridDashedLine(4.0f, 4.0f, 0);
mChart.getAxisLeft().setValueFormatter(new LargeValueFormatter(mCommodity.getSymbol()));
Legend chartLegend = mChart.getLegend();
chartLegend.setForm(Legend.LegendForm.CIRCLE);
chartLegend.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
chartLegend.setWordWrapEnabled(true);
}
/**
* Returns a data object that represents a user data of the specified account types
* @return a {@code BarData} instance that represents a user data
*/
protected BarData getData() {
List<BarEntry> values = new ArrayList<>();
List<String> labels = new ArrayList<>();
List<Integer> colors = new ArrayList<>();
Map<String, Integer> accountToColorMap = new LinkedHashMap<>();
List<String> xValues = new ArrayList<>();
LocalDateTime tmpDate = new LocalDateTime(getStartDate(mAccountType).toDate().getTime());
int count = getDateDiff(new LocalDateTime(getStartDate(mAccountType).toDate().getTime()),
new LocalDateTime(getEndDate(mAccountType).toDate().getTime()));
for (int i = 0; i <= count; i++) {
long start = 0;
long end = 0;
switch (mGroupInterval) {
case MONTH:
start = tmpDate.dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue().toDate().getTime();
end = tmpDate.dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime();
xValues.add(tmpDate.toString(X_AXIS_MONTH_PATTERN));
tmpDate = tmpDate.plusMonths(1);
break;
case QUARTER:
int quarter = getQuarter(tmpDate);
start = tmpDate.withMonthOfYear(quarter * 3 - 2).dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue().toDate().getTime();
end = tmpDate.withMonthOfYear(quarter * 3).dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime();
xValues.add(String.format(X_AXIS_QUARTER_PATTERN, quarter, tmpDate.toString(" YY")));
tmpDate = tmpDate.plusMonths(3);
break;
case YEAR:
start = tmpDate.dayOfYear().withMinimumValue().millisOfDay().withMinimumValue().toDate().getTime();
end = tmpDate.dayOfYear().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime();
xValues.add(tmpDate.toString(X_AXIS_YEAR_PATTERN));
tmpDate = tmpDate.plusYears(1);
break;
}
List<Float> stack = new ArrayList<>();
for (Account account : mAccountsDbAdapter.getSimpleAccountList()) {
if (account.getAccountType() == mAccountType
&& !account.isPlaceholderAccount()
&& account.getCommodity().equals(mCommodity)) {
double balance = mAccountsDbAdapter.getAccountsBalance(
Collections.singletonList(account.getUID()), start, end).asDouble();
if (balance != 0) {
stack.add((float) balance);
String accountName = account.getName();
while (labels.contains(accountName)) {
if (!accountToColorMap.containsKey(account.getUID())) {
for (String label : labels) {
if (label.equals(accountName)) {
accountName += " ";
}
}
} else {
break;
}
}
labels.add(accountName);
if (!accountToColorMap.containsKey(account.getUID())) {
Integer color;
if (mUseAccountColor) {
color = (account.getColor() != Account.DEFAULT_COLOR)
? account.getColor()
: COLORS[accountToColorMap.size() % COLORS.length];
} else {
color = COLORS[accountToColorMap.size() % COLORS.length];
}
accountToColorMap.put(account.getUID(), color);
}
colors.add(accountToColorMap.get(account.getUID()));
Log.d(TAG, mAccountType + tmpDate.toString(" MMMM yyyy ") + account.getName() + " = " + stack.get(stack.size() - 1));
}
}
}
String stackLabels = labels.subList(labels.size() - stack.size(), labels.size()).toString();
values.add(new BarEntry(floatListToArray(stack), i, stackLabels));
}
BarDataSet set = new BarDataSet(values, "");
set.setDrawValues(false);
set.setStackLabels(labels.toArray(new String[labels.size()]));
set.setColors(colors);
if (set.getYValueSum() == 0) {
mChartDataPresent = false;
return getEmptyData();
}
mChartDataPresent = true;
return new BarData(xValues, set);
}
/**
* Returns a data object that represents situation when no user data available
* @return a {@code BarData} instance for situation when no user data available
*/
private BarData getEmptyData() {
List<String> xValues = new ArrayList<>();
List<BarEntry> yValues = new ArrayList<>();
for (int i = 0; i < NO_DATA_BAR_COUNTS; i++) {
xValues.add("");
yValues.add(new BarEntry(i + 1, i));
}
BarDataSet set = new BarDataSet(yValues, getResources().getString(R.string.label_chart_no_data));
set.setDrawValues(false);
set.setColor(NO_DATA_COLOR);
return new BarData(xValues, set);
}
/**
* Returns the start data of x-axis for the specified account type
* @param accountType account type
* @return the start data
*/
private LocalDate getStartDate(AccountType accountType) {
TransactionsDbAdapter adapter = TransactionsDbAdapter.getInstance();
String code = mCommodity.getCurrencyCode();
LocalDate startDate;
if (mReportPeriodStart == -1) {
startDate = new LocalDate(adapter.getTimestampOfEarliestTransaction(accountType, code));
} else {
startDate = new LocalDate(mReportPeriodStart);
}
startDate = startDate.withDayOfMonth(1);
Log.d(TAG, accountType + " X-axis star date: " + startDate.toString("dd MM yyyy"));
return startDate;
}
/**
* Returns the end data of x-axis for the specified account type
* @param accountType account type
* @return the end data
*/
private LocalDate getEndDate(AccountType accountType) {
TransactionsDbAdapter adapter = TransactionsDbAdapter.getInstance();
String code = mCommodity.getCurrencyCode();
LocalDate endDate;
if (mReportPeriodEnd == -1) {
endDate = new LocalDate(adapter.getTimestampOfLatestTransaction(accountType, code));
} else {
endDate = new LocalDate(mReportPeriodEnd);
}
endDate = endDate.withDayOfMonth(1);
Log.d(TAG, accountType + " X-axis end date: " + endDate.toString("dd MM yyyy"));
return endDate;
}
/**
* Converts the specified list of floats to an array
* @param list a list of floats
* @return a float array
*/
private float[] floatListToArray(List<Float> list) {
float array[] = new float[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
return array;
}
@Override
public void generateReport() {
mChart.setData(getData());
setCustomLegend();
mChart.getAxisLeft().setDrawLabels(mChartDataPresent);
mChart.getXAxis().setDrawLabels(mChartDataPresent);
mChart.setTouchEnabled(mChartDataPresent);
}
@Override
protected void displayReport() {
mChart.notifyDataSetChanged();
mChart.highlightValues(null);
if (mChartDataPresent) {
mChart.animateY(ANIMATION_DURATION);
} else {
mChart.clearAnimation();
mSelectedValueTextView.setText(R.string.label_chart_no_data);
}
mChart.invalidate();
}
/**
* Sets custom legend. Disable legend if its items count greater than {@code COLORS} array size.
*/
private void setCustomLegend() {
Legend legend = mChart.getLegend();
BarDataSet dataSet = mChart.getData().getDataSetByIndex(0);
LinkedHashSet<String> labels = new LinkedHashSet<>(Arrays.asList(dataSet.getStackLabels()));
LinkedHashSet<Integer> colors = new LinkedHashSet<>(dataSet.getColors());
if (COLORS.length >= labels.size()) {
legend.setCustom(new ArrayList<>(colors), new ArrayList<>(labels));
return;
}
legend.setEnabled(false);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.menu_percentage_mode).setVisible(mChartDataPresent);
// hide pie/line chart specific menu items
menu.findItem(R.id.menu_order_by_size).setVisible(false);
menu.findItem(R.id.menu_toggle_labels).setVisible(false);
menu.findItem(R.id.menu_toggle_average_lines).setVisible(false);
menu.findItem(R.id.menu_group_other_slice).setVisible(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.isCheckable())
item.setChecked(!item.isChecked());
switch (item.getItemId()) {
case R.id.menu_toggle_legend:
Legend legend = mChart.getLegend();
if (!legend.isLegendCustom()) {
Toast.makeText(getActivity(), R.string.toast_legend_too_long, Toast.LENGTH_LONG).show();
item.setChecked(false);
} else {
item.setChecked(!mChart.getLegend().isEnabled());
legend.setEnabled(!mChart.getLegend().isEnabled());
mChart.invalidate();
}
return true;
case R.id.menu_percentage_mode:
mTotalPercentageMode = !mTotalPercentageMode;
int msgId = mTotalPercentageMode ? R.string.toast_chart_percentage_mode_total
: R.string.toast_chart_percentage_mode_current_bar;
Toast.makeText(getActivity(), msgId, Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
if (e == null || ((BarEntry) e).getVals().length == 0) return;
BarEntry entry = (BarEntry) e;
int index = h.getStackIndex() == -1 ? 0 : h.getStackIndex();
String stackLabels = entry.getData().toString();
String label = mChart.getData().getXVals().get(entry.getXIndex()) + ", "
+ stackLabels.substring(1, stackLabels.length() - 1).split(",")[index];
double value = Math.abs(entry.getVals()[index]);
double sum = 0;
if (mTotalPercentageMode) {
for (BarEntry barEntry : mChart.getData().getDataSetByIndex(dataSetIndex).getYVals()) {
sum += barEntry.getNegativeSum() + barEntry.getPositiveSum();
}
} else {
sum = entry.getNegativeSum() + entry.getPositiveSum();
}
mSelectedValueTextView.setText(String.format(SELECTED_VALUE_PATTERN, label.trim(), value, value / sum * 100));
}
}
| 15,938 | 39.764706 | 153 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/report/linechart/CashFlowLineChartFragment.java
|
/*
* Copyright (c) 2015 Oleksandr Tyshkovets <[email protected]>
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.report.linechart;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.utils.LargeValueFormatter;
import org.gnucash.android.R;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.ui.report.BaseReportFragment;
import org.gnucash.android.ui.report.ReportType;
import org.gnucash.android.ui.report.ReportsActivity.GroupInterval;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
/**
* Fragment for line chart reports
*
* @author Oleksandr Tyshkovets <[email protected]>
* @author Ngewi Fet <[email protected]>
*/
public class CashFlowLineChartFragment extends BaseReportFragment {
private static final String X_AXIS_PATTERN = "MMM YY";
private static final int ANIMATION_DURATION = 3000;
private static final int NO_DATA_BAR_COUNTS = 5;
private static final int[] COLORS = {
Color.parseColor("#68F1AF"), Color.parseColor("#cc1f09"), Color.parseColor("#EE8600"),
Color.parseColor("#1469EB"), Color.parseColor("#B304AD"),
};
private static final int[] FILL_COLORS = {
Color.parseColor("#008000"), Color.parseColor("#FF0000"), Color.parseColor("#BE6B00"),
Color.parseColor("#0065FF"), Color.parseColor("#8F038A"),
};
private AccountsDbAdapter mAccountsDbAdapter = AccountsDbAdapter.getInstance();
private Map<AccountType, Long> mEarliestTimestampsMap = new HashMap<>();
private Map<AccountType, Long> mLatestTimestampsMap = new HashMap<>();
private long mEarliestTransactionTimestamp;
private long mLatestTransactionTimestamp;
private boolean mChartDataPresent = true;
@BindView(R.id.line_chart) LineChart mChart;
@Override
public int getLayoutResource() {
return R.layout.fragment_line_chart;
}
@Override
public int getTitle() {
return R.string.title_cash_flow_report;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mChart.setOnChartValueSelectedListener(this);
mChart.setDescription("");
mChart.getXAxis().setDrawGridLines(false);
mChart.getAxisRight().setEnabled(false);
mChart.getAxisLeft().enableGridDashedLine(4.0f, 4.0f, 0);
mChart.getAxisLeft().setValueFormatter(new LargeValueFormatter(mCommodity.getSymbol()));
Legend legend = mChart.getLegend();
legend.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
legend.setTextSize(16);
legend.setForm(Legend.LegendForm.CIRCLE);
}
@Override
public ReportType getReportType() {
return ReportType.LINE_CHART;
}
/**
* Returns a data object that represents a user data of the specified account types
* @param accountTypeList account's types which will be displayed
* @return a {@code LineData} instance that represents a user data
*/
private LineData getData(List<AccountType> accountTypeList) {
Log.w(TAG, "getData");
calculateEarliestAndLatestTimestamps(accountTypeList);
// LocalDateTime?
LocalDate startDate;
LocalDate endDate;
if (mReportPeriodStart == -1 && mReportPeriodEnd == -1) {
startDate = new LocalDate(mEarliestTransactionTimestamp).withDayOfMonth(1);
endDate = new LocalDate(mLatestTransactionTimestamp).withDayOfMonth(1);
} else {
startDate = new LocalDate(mReportPeriodStart).withDayOfMonth(1);
endDate = new LocalDate(mReportPeriodEnd).withDayOfMonth(1);
}
int count = getDateDiff(new LocalDateTime(startDate.toDate().getTime()), new LocalDateTime(endDate.toDate().getTime()));
Log.d(TAG, "X-axis count" + count);
List<String> xValues = new ArrayList<>();
for (int i = 0; i <= count; i++) {
switch (mGroupInterval) {
case MONTH:
xValues.add(startDate.toString(X_AXIS_PATTERN));
Log.d(TAG, "X-axis " + startDate.toString("MM yy"));
startDate = startDate.plusMonths(1);
break;
case QUARTER:
int quarter = getQuarter(new LocalDateTime(startDate.toDate().getTime()));
xValues.add("Q" + quarter + startDate.toString(" yy"));
Log.d(TAG, "X-axis " + "Q" + quarter + startDate.toString(" MM yy"));
startDate = startDate.plusMonths(3);
break;
case YEAR:
xValues.add(startDate.toString("yyyy"));
Log.d(TAG, "X-axis " + startDate.toString("yyyy"));
startDate = startDate.plusYears(1);
break;
// default:
}
}
List<LineDataSet> dataSets = new ArrayList<>();
for (AccountType accountType : accountTypeList) {
LineDataSet set = new LineDataSet(getEntryList(accountType), accountType.toString());
set.setDrawFilled(true);
set.setLineWidth(2);
set.setColor(COLORS[dataSets.size()]);
set.setFillColor(FILL_COLORS[dataSets.size()]);
dataSets.add(set);
}
LineData lineData = new LineData(xValues, dataSets);
if (lineData.getYValueSum() == 0) {
mChartDataPresent = false;
return getEmptyData();
}
return lineData;
}
/**
* Returns a data object that represents situation when no user data available
* @return a {@code LineData} instance for situation when no user data available
*/
private LineData getEmptyData() {
List<String> xValues = new ArrayList<>();
List<Entry> yValues = new ArrayList<>();
for (int i = 0; i < NO_DATA_BAR_COUNTS; i++) {
xValues.add("");
yValues.add(new Entry(i % 2 == 0 ? 5f : 4.5f, i));
}
LineDataSet set = new LineDataSet(yValues, getResources().getString(R.string.label_chart_no_data));
set.setDrawFilled(true);
set.setDrawValues(false);
set.setColor(NO_DATA_COLOR);
set.setFillColor(NO_DATA_COLOR);
return new LineData(xValues, Collections.singletonList(set));
}
/**
* Returns entries which represent a user data of the specified account type
* @param accountType account's type which user data will be processed
* @return entries which represent a user data
*/
private List<Entry> getEntryList(AccountType accountType) {
List<String> accountUIDList = new ArrayList<>();
for (Account account : mAccountsDbAdapter.getSimpleAccountList()) {
if (account.getAccountType() == accountType
&& !account.isPlaceholderAccount()
&& account.getCommodity().equals(mCommodity)) {
accountUIDList.add(account.getUID());
}
}
LocalDateTime earliest;
LocalDateTime latest;
if (mReportPeriodStart == -1 && mReportPeriodEnd == -1) {
earliest = new LocalDateTime(mEarliestTimestampsMap.get(accountType));
latest = new LocalDateTime(mLatestTimestampsMap.get(accountType));
} else {
earliest = new LocalDateTime(mReportPeriodStart);
latest = new LocalDateTime(mReportPeriodEnd);
}
Log.d(TAG, "Earliest " + accountType + " date " + earliest.toString("dd MM yyyy"));
Log.d(TAG, "Latest " + accountType + " date " + latest.toString("dd MM yyyy"));
int xAxisOffset = getDateDiff(new LocalDateTime(mEarliestTransactionTimestamp), earliest);
int count = getDateDiff(earliest, latest);
List<Entry> values = new ArrayList<>(count + 1);
for (int i = 0; i <= count; i++) {
long start = 0;
long end = 0;
switch (mGroupInterval) {
case QUARTER:
int quarter = getQuarter(earliest);
start = earliest.withMonthOfYear(quarter * 3 - 2).dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue().toDate().getTime();
end = earliest.withMonthOfYear(quarter * 3).dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime();
earliest = earliest.plusMonths(3);
break;
case MONTH:
start = earliest.dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue().toDate().getTime();
end = earliest.dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime();
earliest = earliest.plusMonths(1);
break;
case YEAR:
start = earliest.dayOfYear().withMinimumValue().millisOfDay().withMinimumValue().toDate().getTime();
end = earliest.dayOfYear().withMaximumValue().millisOfDay().withMaximumValue().toDate().getTime();
earliest = earliest.plusYears(1);
break;
}
float balance = (float) mAccountsDbAdapter.getAccountsBalance(accountUIDList, start, end).asDouble();
values.add(new Entry(balance, i + xAxisOffset));
Log.d(TAG, accountType + earliest.toString(" MMM yyyy") + ", balance = " + balance);
}
return values;
}
/**
* Calculates the earliest and latest transaction's timestamps of the specified account types
* @param accountTypeList account's types which will be processed
*/
private void calculateEarliestAndLatestTimestamps(List<AccountType> accountTypeList) {
if (mReportPeriodStart != -1 && mReportPeriodEnd != -1) {
mEarliestTransactionTimestamp = mReportPeriodStart;
mLatestTransactionTimestamp = mReportPeriodEnd;
return;
}
TransactionsDbAdapter dbAdapter = TransactionsDbAdapter.getInstance();
for (Iterator<AccountType> iter = accountTypeList.iterator(); iter.hasNext();) {
AccountType type = iter.next();
long earliest = dbAdapter.getTimestampOfEarliestTransaction(type, mCommodity.getCurrencyCode());
long latest = dbAdapter.getTimestampOfLatestTransaction(type, mCommodity.getCurrencyCode());
if (earliest > 0 && latest > 0) {
mEarliestTimestampsMap.put(type, earliest);
mLatestTimestampsMap.put(type, latest);
} else {
iter.remove();
}
}
if (mEarliestTimestampsMap.isEmpty() || mLatestTimestampsMap.isEmpty()) {
return;
}
List<Long> timestamps = new ArrayList<>(mEarliestTimestampsMap.values());
timestamps.addAll(mLatestTimestampsMap.values());
Collections.sort(timestamps);
mEarliestTransactionTimestamp = timestamps.get(0);
mLatestTransactionTimestamp = timestamps.get(timestamps.size() - 1);
}
@Override
public boolean requiresAccountTypeOptions() {
return false;
}
@Override
protected void generateReport() {
LineData lineData = getData(new ArrayList<>(Arrays.asList(AccountType.INCOME, AccountType.EXPENSE)));
if (lineData != null) {
mChart.setData(lineData);
mChartDataPresent = true;
} else {
mChartDataPresent = false;
}
}
@Override
protected void displayReport() {
if (!mChartDataPresent) {
mChart.getAxisLeft().setAxisMaxValue(10);
mChart.getAxisLeft().setDrawLabels(false);
mChart.getXAxis().setDrawLabels(false);
mChart.setTouchEnabled(false);
mSelectedValueTextView.setText(getResources().getString(R.string.label_chart_no_data));
} else {
mChart.animateX(ANIMATION_DURATION);
}
mChart.invalidate();
}
@Override
public void onTimeRangeUpdated(long start, long end) {
if (mReportPeriodStart != start || mReportPeriodEnd != end) {
mReportPeriodStart = start;
mReportPeriodEnd = end;
mChart.setData(getData(new ArrayList<>(Arrays.asList(AccountType.INCOME, AccountType.EXPENSE))));
mChart.invalidate();
}
}
@Override
public void onGroupingUpdated(GroupInterval groupInterval) {
if (mGroupInterval != groupInterval) {
mGroupInterval = groupInterval;
mChart.setData(getData(new ArrayList<>(Arrays.asList(AccountType.INCOME, AccountType.EXPENSE))));
mChart.invalidate();
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.menu_toggle_average_lines).setVisible(mChartDataPresent);
// hide pie/bar chart specific menu items
menu.findItem(R.id.menu_order_by_size).setVisible(false);
menu.findItem(R.id.menu_toggle_labels).setVisible(false);
menu.findItem(R.id.menu_percentage_mode).setVisible(false);
menu.findItem(R.id.menu_group_other_slice).setVisible(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.isCheckable())
item.setChecked(!item.isChecked());
switch (item.getItemId()) {
case R.id.menu_toggle_legend:
mChart.getLegend().setEnabled(!mChart.getLegend().isEnabled());
mChart.invalidate();
return true;
case R.id.menu_toggle_average_lines:
if (mChart.getAxisLeft().getLimitLines().isEmpty()) {
for (LineDataSet set : mChart.getData().getDataSets()) {
LimitLine line = new LimitLine(set.getYValueSum() / set.getEntryCount(), set.getLabel());
line.enableDashedLine(10, 5, 0);
line.setLineColor(set.getColor());
mChart.getAxisLeft().addLimitLine(line);
}
} else {
mChart.getAxisLeft().removeAllLimitLines();
}
mChart.invalidate();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
if (e == null) return;
String label = mChart.getData().getXVals().get(e.getXIndex());
double value = e.getVal();
double sum = mChart.getData().getDataSetByIndex(dataSetIndex).getYValueSum();
mSelectedValueTextView.setText(String.format(SELECTED_VALUE_PATTERN, label, value, value / sum * 100));
}
}
| 16,303 | 40.06801 | 154 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/report/piechart/PieChartFragment.java
|
/*
* Copyright (c) 2014-2015 Oleksandr Tyshkovets <[email protected]>
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.report.piechart;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import org.gnucash.android.R;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.model.Account;
import org.gnucash.android.ui.report.BaseReportFragment;
import org.gnucash.android.ui.report.ReportType;
import org.gnucash.android.ui.report.ReportsActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import static com.github.mikephil.charting.components.Legend.LegendForm;
import static com.github.mikephil.charting.components.Legend.LegendPosition;
/**
* Activity used for drawing a pie chart
*
* @author Oleksandr Tyshkovets <[email protected]>
* @author Ngewi Fet <[email protected]>
*/
public class PieChartFragment extends BaseReportFragment {
public static final String TOTAL_VALUE_LABEL_PATTERN = "%s\n%.2f %s";
private static final int ANIMATION_DURATION = 1800;
public static final int CENTER_TEXT_SIZE = 18;
/**
* The space in degrees between the chart slices
*/
public static final float SPACE_BETWEEN_SLICES = 2f;
/**
* All pie slices less than this threshold will be group in "other" slice. Using percents not absolute values.
*/
private static final double GROUPING_SMALLER_SLICES_THRESHOLD = 5;
@BindView(R.id.pie_chart) PieChart mChart;
private AccountsDbAdapter mAccountsDbAdapter;
private boolean mChartDataPresent = true;
private boolean mUseAccountColor = true;
private boolean mGroupSmallerSlices = true;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mUseAccountColor = PreferenceManager.getDefaultSharedPreferences(getActivity())
.getBoolean(getString(R.string.key_use_account_color), false);
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
mChart.setCenterTextSize(CENTER_TEXT_SIZE);
mChart.setDescription("");
mChart.setOnChartValueSelectedListener(this);
mChart.getLegend().setForm(LegendForm.CIRCLE);
mChart.getLegend().setWordWrapEnabled(true);
mChart.getLegend().setPosition(LegendPosition.BELOW_CHART_CENTER);
}
@Override
public int getTitle() {
return R.string.title_pie_chart;
}
@Override
public ReportType getReportType() {
return ReportType.PIE_CHART;
}
@Override
public int getLayoutResource() {
return R.layout.fragment_pie_chart;
}
@Override
protected void generateReport() {
PieData pieData = getData();
if (pieData != null && pieData.getYValCount() != 0) {
mChartDataPresent = true;
mChart.setData(mGroupSmallerSlices ? groupSmallerSlices(pieData, getActivity()) : pieData);
float sum = mChart.getData().getYValueSum();
String total = getResources().getString(R.string.label_chart_total);
String currencySymbol = mCommodity.getSymbol();
mChart.setCenterText(String.format(TOTAL_VALUE_LABEL_PATTERN, total, sum, currencySymbol));
} else {
mChartDataPresent = false;
mChart.setCenterText(getResources().getString(R.string.label_chart_no_data));
mChart.setData(getEmptyData());
}
}
@Override
protected void displayReport() {
if (mChartDataPresent){
mChart.animateXY(ANIMATION_DURATION, ANIMATION_DURATION);
}
mSelectedValueTextView.setText(R.string.label_select_pie_slice_to_see_details);
mChart.setTouchEnabled(mChartDataPresent);
mChart.highlightValues(null);
mChart.invalidate();
}
/**
* Returns {@code PieData} instance with data entries, colors and labels
* @return {@code PieData} instance
*/
private PieData getData() {
PieDataSet dataSet = new PieDataSet(null, "");
List<String> labels = new ArrayList<>();
List<Integer> colors = new ArrayList<>();
for (Account account : mAccountsDbAdapter.getSimpleAccountList()) {
if (account.getAccountType() == mAccountType
&& !account.isPlaceholderAccount()
&& account.getCommodity().equals(mCommodity)) {
double balance = mAccountsDbAdapter.getAccountsBalance(Collections.singletonList(account.getUID()),
mReportPeriodStart, mReportPeriodEnd).asDouble();
if (balance > 0) {
dataSet.addEntry(new Entry((float) balance, dataSet.getEntryCount()));
int color;
if (mUseAccountColor) {
color = (account.getColor() != Account.DEFAULT_COLOR)
? account.getColor()
: ReportsActivity.COLORS[(dataSet.getEntryCount() - 1) % ReportsActivity.COLORS.length];
} else {
color = ReportsActivity.COLORS[(dataSet.getEntryCount() - 1) % ReportsActivity.COLORS.length];
}
colors.add(color);
labels.add(account.getName());
}
}
}
dataSet.setColors(colors);
dataSet.setSliceSpace(SPACE_BETWEEN_SLICES);
return new PieData(labels, dataSet);
}
/**
* Returns a data object that represents situation when no user data available
* @return a {@code PieData} instance for situation when no user data available
*/
private PieData getEmptyData() {
PieDataSet dataSet = new PieDataSet(null, getResources().getString(R.string.label_chart_no_data));
dataSet.addEntry(new Entry(1, 0));
dataSet.setColor(NO_DATA_COLOR);
dataSet.setDrawValues(false);
return new PieData(Collections.singletonList(""), dataSet);
}
/**
* Sorts the pie's slices in ascending order
*/
private void bubbleSort() {
List<String> labels = mChart.getData().getXVals();
List<Entry> values = mChart.getData().getDataSet().getYVals();
List<Integer> colors = mChart.getData().getDataSet().getColors();
float tmp1;
String tmp2;
Integer tmp3;
for(int i = 0; i < values.size() - 1; i++) {
for(int j = 1; j < values.size() - i; j++) {
if (values.get(j-1).getVal() > values.get(j).getVal()) {
tmp1 = values.get(j - 1).getVal();
values.get(j - 1).setVal(values.get(j).getVal());
values.get(j).setVal(tmp1);
tmp2 = labels.get(j - 1);
labels.set(j - 1, labels.get(j));
labels.set(j, tmp2);
tmp3 = colors.get(j - 1);
colors.set(j - 1, colors.get(j));
colors.set(j, tmp3);
}
}
}
mChart.notifyDataSetChanged();
mChart.highlightValues(null);
mChart.invalidate();
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.menu_order_by_size).setVisible(mChartDataPresent);
menu.findItem(R.id.menu_toggle_labels).setVisible(mChartDataPresent);
menu.findItem(R.id.menu_group_other_slice).setVisible(mChartDataPresent);
// hide line/bar chart specific menu items
menu.findItem(R.id.menu_percentage_mode).setVisible(false);
menu.findItem(R.id.menu_toggle_average_lines).setVisible(false);
menu.findItem(R.id.menu_group_reports_by).setVisible(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.isCheckable())
item.setChecked(!item.isChecked());
switch (item.getItemId()) {
case R.id.menu_order_by_size: {
bubbleSort();
return true;
}
case R.id.menu_toggle_legend: {
mChart.getLegend().setEnabled(!mChart.getLegend().isEnabled());
mChart.notifyDataSetChanged();
mChart.invalidate();
return true;
}
case R.id.menu_toggle_labels: {
mChart.getData().setDrawValues(!mChart.isDrawSliceTextEnabled());
mChart.setDrawSliceText(!mChart.isDrawSliceTextEnabled());
mChart.invalidate();
return true;
}
case R.id.menu_group_other_slice: {
mGroupSmallerSlices = !mGroupSmallerSlices;
refresh();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Groups smaller slices. All smaller slices will be combined and displayed as a single "Other".
* @param data the pie data which smaller slices will be grouped
* @param context Context for retrieving resources
* @return a {@code PieData} instance with combined smaller slices
*/
public static PieData groupSmallerSlices(PieData data, Context context) {
float otherSlice = 0f;
List<Entry> newEntries = new ArrayList<>();
List<String> newLabels = new ArrayList<>();
List<Integer> newColors = new ArrayList<>();
List<Entry> entries = data.getDataSet().getYVals();
for (int i = 0; i < entries.size(); i++) {
float val = entries.get(i).getVal();
if (val / data.getYValueSum() * 100 > GROUPING_SMALLER_SLICES_THRESHOLD) {
newEntries.add(new Entry(val, newEntries.size()));
newLabels.add(data.getXVals().get(i));
newColors.add(data.getDataSet().getColors().get(i));
} else {
otherSlice += val;
}
}
if (otherSlice > 0) {
newEntries.add(new Entry(otherSlice, newEntries.size()));
newLabels.add(context.getResources().getString(R.string.label_other_slice));
newColors.add(Color.LTGRAY);
}
PieDataSet dataSet = new PieDataSet(newEntries, "");
dataSet.setSliceSpace(SPACE_BETWEEN_SLICES);
dataSet.setColors(newColors);
return new PieData(newLabels, dataSet);
}
@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
if (e == null) return;
String label = mChart.getData().getXVals().get(e.getXIndex());
float value = e.getVal();
float percent = value / mChart.getData().getYValueSum() * 100;
mSelectedValueTextView.setText(String.format(SELECTED_VALUE_PATTERN, label, value, percent));
}
}
| 11,915 | 37.315113 | 120 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/report/sheet/BalanceSheetFragment.java
|
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.report.sheet;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TextView;
import org.gnucash.android.R;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.report.BaseReportFragment;
import org.gnucash.android.ui.report.ReportType;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
/**
* Balance sheet report fragment
* @author Ngewi Fet <[email protected]>
*/
public class BalanceSheetFragment extends BaseReportFragment {
@BindView(R.id.table_assets) TableLayout mAssetsTableLayout;
@BindView(R.id.table_liabilities) TableLayout mLiabilitiesTableLayout;
@BindView(R.id.table_equity) TableLayout mEquityTableLayout;
@BindView(R.id.total_liability_and_equity) TextView mNetWorth;
AccountsDbAdapter mAccountsDbAdapter = AccountsDbAdapter.getInstance();
private Money mAssetsBalance;
private Money mLiabilitiesBalance;
private List<AccountType> mAssetAccountTypes;
private List<AccountType> mLiabilityAccountTypes;
private List<AccountType> mEquityAccountTypes;
@Override
public int getLayoutResource() {
return R.layout.fragment_text_report;
}
@Override
public int getTitle() {
return R.string.title_balance_sheet_report;
}
@Override
public ReportType getReportType() {
return ReportType.TEXT;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAssetAccountTypes = new ArrayList<>();
mAssetAccountTypes.add(AccountType.ASSET);
mAssetAccountTypes.add(AccountType.CASH);
mAssetAccountTypes.add(AccountType.BANK);
mLiabilityAccountTypes = new ArrayList<>();
mLiabilityAccountTypes.add(AccountType.LIABILITY);
mLiabilityAccountTypes.add(AccountType.CREDIT);
mEquityAccountTypes = new ArrayList<>();
mEquityAccountTypes.add(AccountType.EQUITY);
}
@Override
public boolean requiresAccountTypeOptions() {
return false;
}
@Override
public boolean requiresTimeRangeOptions() {
return false;
}
@Override
protected void generateReport() {
mAssetsBalance = mAccountsDbAdapter.getAccountBalance(mAssetAccountTypes, -1, System.currentTimeMillis());
mLiabilitiesBalance = mAccountsDbAdapter.getAccountBalance(mLiabilityAccountTypes, -1, System.currentTimeMillis());
}
@Override
protected void displayReport() {
loadAccountViews(mAssetAccountTypes, mAssetsTableLayout);
loadAccountViews(mLiabilityAccountTypes, mLiabilitiesTableLayout);
loadAccountViews(mEquityAccountTypes, mEquityTableLayout);
TransactionsActivity.displayBalance(mNetWorth, mAssetsBalance.subtract(mLiabilitiesBalance));
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.menu_group_reports_by).setVisible(false);
}
/**
* Loads rows for the individual accounts and adds them to the report
* @param accountTypes Account types for which to load balances
* @param tableLayout Table layout into which to load the rows
*/
private void loadAccountViews(List<AccountType> accountTypes, TableLayout tableLayout){
LayoutInflater inflater = LayoutInflater.from(getActivity());
Cursor cursor = mAccountsDbAdapter.fetchAccounts(DatabaseSchema.AccountEntry.COLUMN_TYPE
+ " IN ( '" + TextUtils.join("' , '", accountTypes) + "' ) AND "
+ DatabaseSchema.AccountEntry.COLUMN_PLACEHOLDER + " = 0",
null, DatabaseSchema.AccountEntry.COLUMN_FULL_NAME + " ASC");
while (cursor.moveToNext()){
String accountUID = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_UID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_NAME));
Money balance = mAccountsDbAdapter.getAccountBalance(accountUID);
View view = inflater.inflate(R.layout.row_balance_sheet, tableLayout, false);
((TextView)view.findViewById(R.id.account_name)).setText(name);
TextView balanceTextView = (TextView) view.findViewById(R.id.account_balance);
TransactionsActivity.displayBalance(balanceTextView, balance);
tableLayout.addView(view);
}
View totalView = inflater.inflate(R.layout.row_balance_sheet, tableLayout, false);
TableLayout.LayoutParams layoutParams = (TableLayout.LayoutParams) totalView.getLayoutParams();
layoutParams.setMargins(layoutParams.leftMargin, 20, layoutParams.rightMargin, layoutParams.bottomMargin);
totalView.setLayoutParams(layoutParams);
TextView accountName = (TextView) totalView.findViewById(R.id.account_name);
accountName.setTextSize(16);
accountName.setText(R.string.label_balance_sheet_total);
TextView accountBalance = (TextView) totalView.findViewById(R.id.account_balance);
accountBalance.setTextSize(16);
accountBalance.setTypeface(null, Typeface.BOLD);
TransactionsActivity.displayBalance(accountBalance, mAccountsDbAdapter.getAccountBalance(accountTypes, -1, System.currentTimeMillis()));
tableLayout.addView(totalView);
}
}
| 6,528 | 38.331325 | 144 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/AboutPreferenceFragment.java
|
/*
* Copyright (c) 2012 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.settings;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import org.gnucash.android.BuildConfig;
import org.gnucash.android.R;
import org.gnucash.android.ui.account.AccountsActivity;
/**
* Fragment for displaying information about the application
* @author Ngewi Fet <[email protected]>
*
*/
public class AboutPreferenceFragment extends PreferenceFragmentCompat{
@Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.fragment_about_preferences);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.title_about_gnucash);
}
@Override
public void onResume() {
super.onResume();
Preference pref = findPreference(getString(R.string.key_about_gnucash));
if (BuildConfig.FLAVOR.equals("development")){
pref.setSummary(pref.getSummary() + " - Built: " + BuildConfig.BUILD_TIME);
}
pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
AccountsActivity.showWhatsNewDialog(getActivity());
return true;
}
});
}
}
| 2,243 | 32 | 86 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/AccountPreferencesFragment.java
|
/*
* Copyright (c) 2013 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.ListPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.CommoditiesDbAdapter;
import org.gnucash.android.export.ExportAsyncTask;
import org.gnucash.android.export.ExportFormat;
import org.gnucash.android.export.ExportParams;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.settings.dialog.DeleteAllAccountsConfirmationDialog;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* Account settings fragment inside the Settings activity
*
* @author Ngewi Fet <[email protected]>
* @author Oleksandr Tyshkovets <[email protected]>
*/
public class AccountPreferencesFragment extends PreferenceFragmentCompat implements
Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener{
private static final int REQUEST_EXPORT_FILE = 0xC5;
List<CharSequence> mCurrencyEntries = new ArrayList<>();
List<CharSequence> mCurrencyEntryValues = new ArrayList<>();
@Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.fragment_account_preferences);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
actionBar.setTitle(R.string.title_account_preferences);
Cursor cursor = CommoditiesDbAdapter.getInstance().fetchAllRecords(DatabaseSchema.CommodityEntry.COLUMN_MNEMONIC + " ASC");
while(cursor.moveToNext()){
String code = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.CommodityEntry.COLUMN_MNEMONIC));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.CommodityEntry.COLUMN_FULLNAME));
mCurrencyEntries.add(code + " - " + name);
mCurrencyEntryValues.add(code);
}
cursor.close();
}
@Override
public void onResume() {
super.onResume();
String defaultCurrency = GnuCashApplication.getDefaultCurrencyCode();
Preference pref = findPreference(getString(R.string.key_default_currency));
String currencyName = CommoditiesDbAdapter.getInstance().getCommodity(defaultCurrency).getFullname();
pref.setSummary(currencyName);
pref.setOnPreferenceChangeListener(this);
CharSequence[] entries = new CharSequence[mCurrencyEntries.size()];
CharSequence[] entryValues = new CharSequence[mCurrencyEntryValues.size()];
((ListPreference) pref).setEntries(mCurrencyEntries.toArray(entries));
((ListPreference) pref).setEntryValues(mCurrencyEntryValues.toArray(entryValues));
Preference preference = findPreference(getString(R.string.key_import_accounts));
preference.setOnPreferenceClickListener(this);
preference = findPreference(getString(R.string.key_export_accounts_csv));
preference.setOnPreferenceClickListener(this);
preference = findPreference(getString(R.string.key_delete_all_accounts));
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
showDeleteAccountsDialog();
return true;
}
});
preference = findPreference(getString(R.string.key_create_default_accounts));
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.title_create_default_accounts)
.setMessage(R.string.msg_confirm_create_default_accounts_setting)
.setIcon(R.drawable.ic_warning_black_24dp)
.setPositiveButton(R.string.btn_create_accounts, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
AccountsActivity.createDefaultAccounts(Money.DEFAULT_CURRENCY_CODE, getActivity());
}
})
.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.create()
.show();
return true;
}
});
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_import_accounts))){
AccountsActivity.startXmlFileChooser(this);
return true;
}
if (key.equals(getString(R.string.key_export_accounts_csv))){
selectExportFile();
return true;
}
return false;
}
/**
* Open a chooser for user to pick a file to export to
*/
private void selectExportFile() {
Intent createIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
createIntent.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
String bookName = BooksDbAdapter.getInstance().getActiveBookDisplayName();
String filename = Exporter.buildExportFilename(ExportFormat.CSVA, bookName);
createIntent.setType("application/text");
createIntent.putExtra(Intent.EXTRA_TITLE, filename);
startActivityForResult(createIntent, REQUEST_EXPORT_FILE);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference.getKey().equals(getString(R.string.key_default_currency))){
GnuCashApplication.setDefaultCurrencyCode(newValue.toString());
String fullname = CommoditiesDbAdapter.getInstance().getCommodity(newValue.toString()).getFullname();
preference.setSummary(fullname);
return true;
}
return false;
}
/**
* Show the dialog for deleting accounts
*/
public void showDeleteAccountsDialog(){
DeleteAllAccountsConfirmationDialog deleteConfirmationDialog = DeleteAllAccountsConfirmationDialog.newInstance();
deleteConfirmationDialog.show(getActivity().getSupportFragmentManager(), "account_settings");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case AccountsActivity.REQUEST_PICK_ACCOUNTS_FILE:
if (resultCode == Activity.RESULT_OK && data != null) {
AccountsActivity.importXmlFileFromIntent(getActivity(), data, null);
}
break;
case REQUEST_EXPORT_FILE:
if (resultCode == Activity.RESULT_OK && data != null){
ExportParams exportParams = new ExportParams(ExportFormat.CSVA);
exportParams.setExportTarget(ExportParams.ExportTarget.URI);
exportParams.setExportLocation(data.getData().toString());
ExportAsyncTask exportTask = new ExportAsyncTask(getActivity(), GnuCashApplication.getActiveDb());
try {
exportTask.execute(exportParams).get();
} catch (InterruptedException | ExecutionException e) {
Crashlytics.logException(e);
Toast.makeText(getActivity(), "An error occurred during the Accounts CSV export",
Toast.LENGTH_LONG).show();
}
}
}
}
}
| 9,435 | 41.313901 | 131 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/BackupPreferenceFragment.java
|
/*
* Copyright (c) 2012 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.CheckBoxPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.preference.PreferenceManager;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.dropbox.core.android.Auth;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.MetadataChangeSet;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.export.Exporter;
import org.gnucash.android.importer.ImportAsyncTask;
import org.gnucash.android.ui.settings.dialog.OwnCloudDialogFragment;
import org.gnucash.android.util.BackupManager;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* Fragment for displaying general preferences
* @author Ngewi Fet <[email protected]>
*
*/
public class BackupPreferenceFragment extends PreferenceFragmentCompat implements
Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {
/**
* Collects references to the UI elements and binds click listeners
*/
private static final int REQUEST_LINK_TO_DBX = 0x11;
public static final int REQUEST_RESOLVE_CONNECTION = 0x12;
/**
* Request code for the backup file where to save backups
*/
private static final int REQUEST_BACKUP_FILE = 0x13;
/**
* Testing app key for DropBox API
*/
final static public String DROPBOX_APP_KEY = "dhjh8ke9wf05948";
/**
* Testing app secret for DropBox API
*/
final static public String DROPBOX_APP_SECRET = "h2t9fphj3nr4wkw";
/**
* String for tagging log statements
*/
public static final String LOG_TAG = "BackupPrefFragment";
/**
* Client for Google Drive Sync
*/
public static GoogleApiClient mGoogleApiClient;
@Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.fragment_backup_preferences);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.title_backup_prefs);
mGoogleApiClient = getGoogleApiClient(getActivity());
}
@Override
public void onResume() {
super.onResume();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
//if we are returning from DropBox authentication, save the key which was generated
String keyDefaultEmail = getString(R.string.key_default_export_email);
Preference pref = findPreference(keyDefaultEmail);
String defaultEmail = sharedPrefs.getString(keyDefaultEmail, null);
if (defaultEmail != null && !defaultEmail.trim().isEmpty()){
pref.setSummary(defaultEmail);
}
pref.setOnPreferenceChangeListener(this);
String keyDefaultExportFormat = getString(R.string.key_default_export_format);
pref = findPreference(keyDefaultExportFormat);
String defaultExportFormat = sharedPrefs.getString(keyDefaultExportFormat, null);
if (defaultExportFormat != null && !defaultExportFormat.trim().isEmpty()){
pref.setSummary(defaultExportFormat);
}
pref.setOnPreferenceChangeListener(this);
pref = findPreference(getString(R.string.key_restore_backup));
pref.setOnPreferenceClickListener(this);
pref = findPreference(getString(R.string.key_create_backup));
pref.setOnPreferenceClickListener(this);
pref = findPreference(getString(R.string.key_backup_location));
pref.setOnPreferenceClickListener(this);
String defaultBackupLocation = BackupManager.getBookBackupFileUri(BooksDbAdapter.getInstance().getActiveBookUID());
if (defaultBackupLocation != null){
pref.setSummary(Uri.parse(defaultBackupLocation).getAuthority());
}
pref = findPreference(getString(R.string.key_dropbox_sync));
pref.setOnPreferenceClickListener(this);
toggleDropboxPreference(pref);
pref = findPreference(getString(R.string.key_owncloud_sync));
pref.setOnPreferenceClickListener(this);
toggleOwnCloudPreference(pref);
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_restore_backup))){
restoreBackup();
}
if (key.equals(getString(R.string.key_backup_location))){
Intent createIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
createIntent.setType("*/*");
createIntent.addCategory(Intent.CATEGORY_OPENABLE);
String bookName = BooksDbAdapter.getInstance().getActiveBookDisplayName();
createIntent.putExtra(Intent.EXTRA_TITLE, Exporter.sanitizeFilename(bookName)+ "_" + getString(R.string.label_backup_filename));
startActivityForResult(createIntent, REQUEST_BACKUP_FILE);
}
if (key.equals(getString(R.string.key_dropbox_sync))){
toggleDropboxSync();
toggleDropboxPreference(preference);
}
if (key.equals(getString(R.string.key_owncloud_sync))){
toggleOwnCloudSync(preference);
toggleOwnCloudPreference(preference);
}
if (key.equals(getString(R.string.key_create_backup))){
boolean result = BackupManager.backupActiveBook();
int msg = result ? R.string.toast_backup_successful : R.string.toast_backup_failed;
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
return false;
}
/**
* Listens for changes to the preference and sets the preference summary to the new value
* @param preference Preference which has been changed
* @param newValue New value for the changed preference
* @return <code>true</code> if handled, <code>false</code> otherwise
*/
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(newValue.toString());
if (preference.getKey().equals(getString(R.string.key_default_currency))){
GnuCashApplication.setDefaultCurrencyCode(newValue.toString());
}
if (preference.getKey().equals(getString(R.string.key_default_export_email))){
String emailSetting = newValue.toString();
if (emailSetting == null || emailSetting.trim().isEmpty()){
preference.setSummary(R.string.summary_default_export_email);
}
}
if (preference.getKey().equals(getString(R.string.key_default_export_format))){
String exportFormat = newValue.toString();
if (exportFormat == null || exportFormat.trim().isEmpty()){
preference.setSummary(R.string.summary_default_export_format);
}
}
return true;
}
/**
* Toggles the checkbox of the DropBox Sync preference if a DropBox account is linked
* @param pref DropBox Sync preference
*/
public void toggleDropboxPreference(Preference pref) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String accessToken = prefs.getString(getString(R.string.key_dropbox_access_token), null);
((CheckBoxPreference)pref).setChecked(accessToken != null);
}
/**
* Toggles the checkbox of the ownCloud Sync preference if an ownCloud account is linked
* @param pref ownCloud Sync preference
*/
public void toggleOwnCloudPreference(Preference pref) {
SharedPreferences mPrefs = getActivity().getSharedPreferences(getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
((CheckBoxPreference)pref).setChecked(mPrefs.getBoolean(getString(R.string.owncloud_sync), false));
}
/**
* Toggles the checkbox of the GoogleDrive Sync preference if a Google Drive account is linked
* @param pref Google Drive Sync preference
*/
public void toggleGoogleDrivePreference(Preference pref){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String appFolderId = sharedPreferences.getString(getString(R.string.key_google_drive_app_folder_id),null);
((CheckBoxPreference)pref).setChecked(appFolderId != null);
}
/**
* Toggles the authorization state of a DropBox account.
* If a link exists, it is removed else DropBox authorization is started
*/
private void toggleDropboxSync() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String accessToken = prefs.getString(getString(R.string.key_dropbox_access_token), null);
if (accessToken == null){
Auth.startOAuth2Authentication(getActivity(), getString(R.string.dropbox_app_key));
} else {
prefs.edit().remove(getString(R.string.key_dropbox_access_token)).apply();
}
}
/**
* Toggles synchronization with Google Drive on or off
*/
private void toggleGoogleDriveSync(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
final String appFolderId = sharedPreferences.getString(getString(R.string.key_google_drive_app_folder_id), null);
if (appFolderId != null){
sharedPreferences.edit().remove(getString(R.string.key_google_drive_app_folder_id)).commit(); //commit (not apply) because we need it to be saved *now*
mGoogleApiClient.disconnect();
} else {
mGoogleApiClient.connect();
}
}
/**
* Toggles synchronization with ownCloud on or off
*/
private void toggleOwnCloudSync(Preference pref){
SharedPreferences mPrefs = getActivity().getSharedPreferences(getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
if (mPrefs.getBoolean(getString(R.string.owncloud_sync), false))
mPrefs.edit().putBoolean(getString(R.string.owncloud_sync), false).apply();
else {
OwnCloudDialogFragment ocDialog = OwnCloudDialogFragment.newInstance(pref);
ocDialog.show(getActivity().getSupportFragmentManager(), "owncloud_dialog");
}
}
public static GoogleApiClient getGoogleApiClient(final Context context) {
return new GoogleApiClient.Builder(context)
.addApi(Drive.API)
.addScope(Drive.SCOPE_APPFOLDER)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String appFolderId = sharedPreferences.getString(context.getString(R.string.key_google_drive_app_folder_id), null);
if (appFolderId == null) {
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(context.getString(R.string.app_name)).build();
Drive.DriveApi.getRootFolder(mGoogleApiClient).createFolder(
mGoogleApiClient, changeSet).setResultCallback(new ResultCallback<DriveFolder.DriveFolderResult>() {
@Override
public void onResult(DriveFolder.DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
Log.e(LOG_TAG, "Error creating the application folder");
return;
}
String folderId = result.getDriveFolder().getDriveId().toString();
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putString(context.getString(R.string.key_google_drive_app_folder_id),
folderId).commit(); //commit because we need it to be saved *now*
}
});
}
Toast.makeText(context, R.string.toast_connected_to_google_drive, Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionSuspended(int i) {
Toast.makeText(context, "Connection to Google Drive suspended!", Toast.LENGTH_LONG).show();
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(PreferenceActivity.class.getName(), "Connection to Google Drive failed");
if (connectionResult.hasResolution() && context instanceof Activity) {
try {
Log.e(BackupPreferenceFragment.class.getName(), "Trying resolution of Google API connection failure");
connectionResult.startResolutionForResult((Activity) context, REQUEST_RESOLVE_CONNECTION);
} catch (IntentSender.SendIntentException e) {
Log.e(BackupPreferenceFragment.class.getName(), e.getMessage());
Toast.makeText(context, R.string.toast_unable_to_connect_to_google_drive, Toast.LENGTH_LONG).show();
}
} else {
if (context instanceof Activity)
GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), (Activity) context, 0).show();
}
}
})
.build();
}
/**
* Opens a dialog for a user to select a backup to restore and then restores the backup
*/
private void restoreBackup() {
Log.i("Settings", "Opening GnuCash XML backups for restore");
final String bookUID = BooksDbAdapter.getInstance().getActiveBookUID();
final String defaultBackupFile = BackupManager.getBookBackupFileUri(bookUID);
if (defaultBackupFile != null){
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getActivity())
.setTitle(R.string.title_confirm_restore_backup)
.setMessage(R.string.msg_confirm_restore_backup_into_new_book)
.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton(R.string.btn_restore, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
new ImportAsyncTask(getActivity()).execute(Uri.parse(defaultBackupFile));
}
});
builder.create().show();
return; //stop here if the default backup file exists
}
//If no default location was set, look in the internal SD card location
if (BackupManager.getBackupList(bookUID).isEmpty()){
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getActivity())
.setTitle(R.string.title_no_backups_found)
.setMessage(R.string.msg_no_backups_to_restore_from)
.setNegativeButton(R.string.label_dismiss, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
return;
}
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.select_dialog_singlechoice);
final DateFormat dateFormatter = SimpleDateFormat.getDateTimeInstance();
for (File backupFile : BackupManager.getBackupList(bookUID)) {
long time = Exporter.getExportTime(backupFile.getName());
if (time > 0)
arrayAdapter.add(dateFormatter.format(new Date(time)));
else //if no timestamp was found in the filename, just use the name
arrayAdapter.add(backupFile.getName());
}
AlertDialog.Builder restoreDialogBuilder = new AlertDialog.Builder(getActivity());
restoreDialogBuilder.setTitle(R.string.title_select_backup_to_restore);
restoreDialogBuilder.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
restoreDialogBuilder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
File backupFile = BackupManager.getBackupList(bookUID).get(which);
new ImportAsyncTask(getActivity()).execute(Uri.fromFile(backupFile));
}
});
restoreDialogBuilder.create().show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case REQUEST_LINK_TO_DBX:
Preference preference = findPreference(getString(R.string.key_dropbox_sync));
if (preference == null) //if we are in a preference header fragment, this may return null
break;
toggleDropboxPreference(preference);
break;
case REQUEST_RESOLVE_CONNECTION:
if (resultCode == Activity.RESULT_OK) {
mGoogleApiClient.connect();
Preference pref = findPreference(getString(R.string.key_dropbox_sync));
if (pref == null) //if we are in a preference header fragment, this may return null
break;
toggleDropboxPreference(pref);
}
break;
case REQUEST_BACKUP_FILE:
if (resultCode == Activity.RESULT_OK){
Uri backupFileUri = null;
if (data != null){
backupFileUri = data.getData();
}
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getActivity().getContentResolver().takePersistableUriPermission(backupFileUri, takeFlags);
PreferenceActivity.getActiveBookSharedPreferences()
.edit()
.putString(BackupManager.KEY_BACKUP_FILE, backupFileUri.toString())
.apply();
Preference pref = findPreference(getString(R.string.key_backup_location));
pref.setSummary(backupFileUri.getAuthority());
}
break;
}
}
}
| 18,531 | 37.289256 | 154 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/BookManagerFragment.java
|
/*
* Copyright (c) 2016 Ngewi Fet <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.settings;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseCursorLoader;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.DatabaseSchema.BookEntry;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.common.Refreshable;
import org.gnucash.android.ui.settings.dialog.DeleteBookConfirmationDialog;
import org.gnucash.android.util.BookUtils;
import org.gnucash.android.util.PreferencesHelper;
import java.sql.Timestamp;
/**
* Fragment for managing the books in the database
*/
public class BookManagerFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor>, Refreshable{
private static final String LOG_TAG = "BookManagerFragment";
private SimpleCursorAdapter mCursorAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_book_list, container, false);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCursorAdapter = new BooksCursorAdapter(getActivity(), R.layout.cardview_book,
null, new String[]{BookEntry.COLUMN_DISPLAY_NAME, BookEntry.COLUMN_SOURCE_URI},
new int[]{R.id.primary_text, R.id.secondary_text});
setListAdapter(mCursorAdapter);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
assert actionBar != null;
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.title_manage_books);
setHasOptionsMenu(true);
getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
}
@Override
public void onResume() {
super.onResume();
refresh();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.book_list_actions, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_create_book:
AccountsActivity.createDefaultAccounts(GnuCashApplication.getDefaultCurrencyCode(), getActivity());
return true;
default:
return false;
}
}
@Override
public void refresh() {
getLoaderManager().restartLoader(0, null, this);
}
@Override
public void refresh(String uid) {
refresh();
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(LOG_TAG, "Creating loader for books");
return new BooksCursorLoader(getActivity());
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.d(LOG_TAG, "Finished loading books from database");
mCursorAdapter.swapCursor(data);
mCursorAdapter.notifyDataSetChanged();
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
Log.d(LOG_TAG, "Resetting books list loader");
mCursorAdapter.swapCursor(null);
}
private class BooksCursorAdapter extends SimpleCursorAdapter {
BooksCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to, 0);
}
@Override
public void bindView(View view, final Context context, Cursor cursor) {
super.bindView(view, context, cursor);
final String bookUID = cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_UID));
setLastExportedText(view, bookUID);
setStatisticsText(view, bookUID);
setUpMenu(view, context, cursor, bookUID);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do nothing if the active book is tapped
if (!BooksDbAdapter.getInstance().getActiveBookUID().equals(bookUID)) {
BookUtils.loadBook(bookUID);
}
}
});
}
private void setUpMenu(View view, final Context context, Cursor cursor, final String bookUID) {
final String bookName = cursor.getString(
cursor.getColumnIndexOrThrow(BookEntry.COLUMN_DISPLAY_NAME));
ImageView optionsMenu = (ImageView) view.findViewById(R.id.options_menu);
optionsMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(context, v);
MenuInflater menuInflater = popupMenu.getMenuInflater();
menuInflater.inflate(R.menu.book_context_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.ctx_menu_rename_book:
return handleMenuRenameBook(bookName, bookUID);
case R.id.ctx_menu_sync_book:
//TODO implement sync
return false;
case R.id.ctx_menu_delete_book:
return handleMenuDeleteBook(bookUID);
default:
return true;
}
}
});
String activeBookUID = BooksDbAdapter.getInstance().getActiveBookUID();
if (activeBookUID.equals(bookUID)) {//we cannot delete the active book
popupMenu.getMenu().findItem(R.id.ctx_menu_delete_book).setEnabled(false);
}
popupMenu.show();
}
});
}
private boolean handleMenuDeleteBook(final String bookUID) {
DeleteBookConfirmationDialog dialog = DeleteBookConfirmationDialog.newInstance(bookUID);
dialog.show(getFragmentManager(), "delete_book");
dialog.setTargetFragment(BookManagerFragment.this, 0);
return true;
}
/**
* Opens a dialog for renaming a book
* @param bookName Current name of the book
* @param bookUID GUID of the book
* @return {@code true}
*/
private boolean handleMenuRenameBook(String bookName, final String bookUID) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
dialogBuilder.setTitle(R.string.title_rename_book)
.setView(R.layout.dialog_rename_book)
.setPositiveButton(R.string.btn_rename, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EditText bookTitle = (EditText) ((AlertDialog)dialog).findViewById(R.id.input_book_title);
BooksDbAdapter.getInstance()
.updateRecord(bookUID,
BookEntry.COLUMN_DISPLAY_NAME,
bookTitle.getText().toString().trim());
refresh();
}
})
.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
((TextView)dialog.findViewById(R.id.input_book_title)).setText(bookName);
return true;
}
private void setLastExportedText(View view, String bookUID) {
TextView labelLastSync = (TextView) view.findViewById(R.id.label_last_sync);
labelLastSync.setText(R.string.label_last_export_time);
Timestamp lastSyncTime = PreferencesHelper.getLastExportTime(bookUID);
TextView lastSyncText = (TextView) view.findViewById(R.id.last_sync_time);
if (lastSyncTime.equals(new Timestamp(0)))
lastSyncText.setText(R.string.last_export_time_never);
else
lastSyncText.setText(lastSyncTime.toString());
}
private void setStatisticsText(View view, String bookUID) {
DatabaseHelper dbHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), bookUID);
SQLiteDatabase db = dbHelper.getReadableDatabase();
TransactionsDbAdapter trnAdapter = new TransactionsDbAdapter(db, new SplitsDbAdapter(db));
int transactionCount = (int) trnAdapter.getRecordsCount();
String transactionStats = getResources().getQuantityString(R.plurals.book_transaction_stats, transactionCount, transactionCount);
AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(db, trnAdapter);
int accountsCount = (int) accountsDbAdapter.getRecordsCount();
String accountStats = getResources().getQuantityString(R.plurals.book_account_stats, accountsCount, accountsCount);
String stats = accountStats + ", " + transactionStats;
TextView statsText = (TextView) view.findViewById(R.id.secondary_text);
statsText.setText(stats);
if (bookUID.equals(BooksDbAdapter.getInstance().getActiveBookUID())){
((TextView)view.findViewById(R.id.primary_text))
.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_primary));
}
}
}
/**
* {@link DatabaseCursorLoader} for loading the book list from the database
* @author Ngewi Fet <[email protected]>
*/
private static class BooksCursorLoader extends DatabaseCursorLoader {
BooksCursorLoader(Context context){
super(context);
}
@Override
public Cursor loadInBackground() {
BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance();
Cursor cursor = booksDbAdapter.fetchAllRecords();
registerContentObserver(cursor);
return cursor;
}
}
}
| 12,746 | 39.855769 | 141 |
java
|
gnucash-android
|
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/GeneralPreferenceFragment.java
|
/*
* Copyright (c) 2014 - 2015 Oleksandr Tyshkovets <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.settings;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.CheckBoxPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.widget.Toast;
import org.gnucash.android.R;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.ui.passcode.PasscodeLockScreenActivity;
import org.gnucash.android.ui.passcode.PasscodePreferenceActivity;
/**
* Fragment for general preferences. Currently caters to the passcode and reporting preferences
* @author Oleksandr Tyshkovets <[email protected]>
*/
public class GeneralPreferenceFragment extends PreferenceFragmentCompat implements
android.support.v7.preference.Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {
/**
* Request code for retrieving passcode to store
*/
public static final int PASSCODE_REQUEST_CODE = 0x2;
/**
* Request code for disabling passcode
*/
public static final int REQUEST_DISABLE_PASSCODE = 0x3;
/**
* Request code for changing passcode
*/
public static final int REQUEST_CHANGE_PASSCODE = 0x4;
private SharedPreferences.Editor mEditor;
private CheckBoxPreference mCheckBoxPreference;
@Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.fragment_general_preferences);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.title_general_prefs);
}
@Override
public void onResume() {
super.onResume();
final Intent intent = new Intent(getActivity(), PasscodePreferenceActivity.class);
mCheckBoxPreference = (CheckBoxPreference) findPreference(getString(R.string.key_enable_passcode));
mCheckBoxPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ((Boolean) newValue) {
startActivityForResult(intent, PASSCODE_REQUEST_CODE);
} else {
Intent passIntent = new Intent(getActivity(), PasscodeLockScreenActivity.class);
passIntent.putExtra(UxArgument.DISABLE_PASSCODE, UxArgument.DISABLE_PASSCODE);
startActivityForResult(passIntent, REQUEST_DISABLE_PASSCODE);
}
return true;
}
});
findPreference(getString(R.string.key_change_passcode)).setOnPreferenceClickListener(this);
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_change_passcode))) {
startActivityForResult(
new Intent(getActivity(), PasscodePreferenceActivity.class),
REQUEST_CHANGE_PASSCODE
);
return true;
}
return false;
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference.getKey().equals(getString(R.string.key_enable_passcode))) {
if ((Boolean) newValue) {
startActivityForResult(new Intent(getActivity(), PasscodePreferenceActivity.class),
GeneralPreferenceFragment.PASSCODE_REQUEST_CODE);
} else {
Intent passIntent = new Intent(getActivity(), PasscodeLockScreenActivity.class);
passIntent.putExtra(UxArgument.DISABLE_PASSCODE, UxArgument.DISABLE_PASSCODE);
startActivityForResult(passIntent, GeneralPreferenceFragment.REQUEST_DISABLE_PASSCODE);
}
}
if (preference.getKey().equals(getString(R.string.key_use_account_color))) {
getPreferenceManager().getSharedPreferences()
.edit()
.putBoolean(getString(R.string.key_use_account_color), Boolean.valueOf(newValue.toString()))
.commit();
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (mEditor == null){
mEditor = getPreferenceManager().getSharedPreferences().edit();
}
switch (requestCode) {
case PASSCODE_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK && data != null) {
mEditor.putString(UxArgument.PASSCODE, data.getStringExtra(UxArgument.PASSCODE));
mEditor.putBoolean(UxArgument.ENABLED_PASSCODE, true);
Toast.makeText(getActivity(), R.string.toast_passcode_set, Toast.LENGTH_SHORT).show();
}
if (resultCode == Activity.RESULT_CANCELED) {
mEditor.putBoolean(UxArgument.ENABLED_PASSCODE, false);
mCheckBoxPreference.setChecked(false);
}
break;
case REQUEST_DISABLE_PASSCODE:
boolean flag = resultCode != Activity.RESULT_OK;
mEditor.putBoolean(UxArgument.ENABLED_PASSCODE, flag);
mCheckBoxPreference.setChecked(flag);
break;
case REQUEST_CHANGE_PASSCODE:
if (resultCode == Activity.RESULT_OK && data != null) {
mEditor.putString(UxArgument.PASSCODE, data.getStringExtra(UxArgument.PASSCODE));
mEditor.putBoolean(UxArgument.ENABLED_PASSCODE, true);
Toast.makeText(getActivity(), R.string.toast_passcode_set, Toast.LENGTH_SHORT).show();
}
break;
}
mEditor.commit();
}
}
| 6,967 | 40.47619 | 115 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.