Exemplo n.º 1
0
    /**
     * Returns the value for the cell at <code>columnIndex</code> and <code>rowIndex</code>.
     *
     * @param rowIndex the row whose value is to be queried
     * @param columnIndex the column whose value is to be queried
     * @return the value Object at the specified cell
     */
    @Override
    public Object getValueAt(final int rowIndex, final int columnIndex) {
      Wrapper w = wrapperList.get(rowIndex);

      Account baseAccount;

      if (w.transaction.getTransactionEntries().size() > 1) {
        baseAccount = w.transaction.getCommonAccount();
      } else {
        baseAccount = w.transaction.getTransactionEntries().get(0).getDebitAccount();
      }

      switch (columnIndex) {
        case 0:
          if (w.print) {
            return AccountTableModel.RECONCILED_SYM;
          }
          return null;
        case 1:
          return dateFormatter.format(w.transaction.getDate());
        case 2:
          return w.transaction.getPayee();
        case 3:
          return baseAccount.getName();
        case 4:
          return commodityformat.format(
              w.transaction.getAmount(baseAccount).abs(), baseAccount.getCurrencyNode());
        default:
          return null;
      }
    }
  @FXML
  @Override
  public void handleEnterAction() {
    if (validateForm()) {
      if (modTrans == null) { // new transaction
        Transaction newTrans = buildTransaction();

        ReconcileManager.reconcileTransaction(
            accountProperty.get(), newTrans, getReconciledState());

        newTrans = attachmentPane.buildTransaction(newTrans); // chain the transaction build

        final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

        if (engine != null) {
          engine.addTransaction(newTrans);
        }
      } else {
        Transaction newTrans = buildTransaction();

        newTrans.setDateEntered(modTrans.getDateEntered());

        // restore the reconciled state of the previous old transaction
        for (final Account a : modTrans.getAccounts()) {
          if (!a.equals(accountProperty.get())) {
            ReconcileManager.reconcileTransaction(a, newTrans, modTrans.getReconciled(a));
          }
        }

        /*
         * Reconcile the modified transaction for this account.
         * This must be performed last to ensure consistent results per the ReconcileManager rules
         */
        ReconcileManager.reconcileTransaction(
            accountProperty.get(), newTrans, getReconciledState());

        newTrans = attachmentPane.buildTransaction(newTrans); // chain the transaction build

        final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

        if (engine != null && engine.removeTransaction(modTrans)) {
          engine.addTransaction(newTrans);
        }
      }
      clearForm();

      if (payeeTextField != null) {
        payeeTextField.requestFocus();
      } else {
        memoTextField.requestFocus();
      }
    }
  }
  @Override
  @Nullable
  public JasperPrint createJasperPrint(final boolean formatForCSV) {
    final Account account = accountComboBox.getValue();

    if (account != null) { // a null account is possible
      final PortfolioReportTableModel model =
          new PortfolioReportTableModel(account.getCurrencyNode());

      return createJasperPrint(model, formatForCSV);
    }

    return null;
  }
Exemplo n.º 4
0
  private RegisterStage(@NotNull final Account account) {
    super(StageStyle.DECORATED);

    accountProperty.setValue(account);

    final String formResource;

    if (account.isLocked()) {
      if (account.memberOf(AccountGroup.INVEST)) {
        formResource = "LockedInvestmentRegisterPane.fxml";
      } else {
        formResource = "LockedBasicRegisterPane.fxml";
      }
    } else {
      if (account.memberOf(AccountGroup.INVEST)) {
        formResource = "InvestmentRegisterPane.fxml";
      } else {
        formResource = "BasicRegisterPane.fxml";
      }
    }

    controller =
        FXMLUtils.loadFXML(
            scene -> setScene(new Scene((Parent) scene)), formResource, ResourceUtils.getBundle());

    getScene().getStylesheets().addAll(MainApplication.DEFAULT_CSS);

    double minWidth = Double.MAX_VALUE;
    double minHeight = Double.MAX_VALUE;

    for (final Screen screen : Screen.getScreens()) {
      minWidth = Math.min(minWidth, screen.getVisualBounds().getWidth());
      minHeight = Math.min(minHeight, screen.getVisualBounds().getHeight());
    }

    setWidth(minWidth * SCALE_FACTOR);
    setHeight(minHeight * SCALE_FACTOR);

    // Push the account to the controller at the end of the application thread
    Platform.runLater(() -> controller.accountProperty().setValue(account));

    updateTitle(account);

    StageUtils.addBoundsListener(this, account.getUuid());

    registerStageListProperty.get().add(this);

    setOnHidden(event -> registerStageListProperty.get().remove(RegisterStage.this));
  }
  private void updateAccountCode(final Account account, final Integer code) {
    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    if (engine != null) {
      try {
        final Account template = (Account) account.clone();
        template.setAccountCode(code);

        engine.modifyAccount(template, account);
      } catch (final CloneNotSupportedException e) {
        Logger.getLogger(AccountsViewController.class.getName())
            .log(Level.SEVERE, e.getLocalizedMessage(), e);
      }
    }
  }
Exemplo n.º 6
0
  /** Writes all investment account transactions within the date range */
  private void writeInvestmentTransactions() {
    for (Transaction transaction : account.getTransactions(startDate, endDate)) {
      if (transaction instanceof InvestmentTransaction) {
        InvestmentTransaction invTransaction = (InvestmentTransaction) transaction;

        switch (invTransaction.getTransactionType()) {
          case ADDSHARE:
          case BUYSHARE:
            writeBuyStockTransaction(invTransaction);
            break;
          case REMOVESHARE:
          case SELLSHARE:
            writeSellStockTransaction(invTransaction);
            break;
          case DIVIDEND:
            writeDividendTransaction(invTransaction);
            break;
          case REINVESTDIV:
            writeReinvestStockTransaction(invTransaction);
            break;
          default:
            break;
        }
      } else { // bank transaction, write it
        indentedWriter.println(wrapOpen(INVBANKTRAN), indentLevel++);
        writeBankTransaction(transaction);
        indentedWriter.println(wrapClose(INVBANKTRAN), --indentLevel);
      }
    }
  }
  public AccountSecurityComboBox(final Account acc) {
    super();

    if (acc == null || acc.getAccountType().getAccountGroup() != AccountGroup.INVEST) {
      throw new IllegalArgumentException(
          Resource.get().getString("Message.Error.InvalidAccountGroup"));
    }

    this.account = acc;

    addAll(account.getSecurities());

    if (model.getSize() > 0) {
      setSelectedIndex(0);
    }

    registerListeners();
  }
  private void updateButtonStates() {
    Platform.runLater(
        () -> {
          final Account account = selectedAccountProperty.get();

          if (account != null) {
            final int count = account.getTransactionCount();

            deleteButton.setDisable(count > 0 || account.getChildCount() > 0);
            reconcileButton.setDisable(count <= 0);
            zoomButton.setDisable(account.isPlaceHolder());
          } else {
            deleteButton.setDisable(true);
            reconcileButton.setDisable(true);
            zoomButton.setDisable(true);
          }
        });
  }
Exemplo n.º 9
0
  private void accountAction() {
    destinationAccount = accountCombo.getSelectedAccount();

    /* Save the id of the selected account */
    if (destinationAccount != null) {
      pref.put(LAST_ACCOUNT, destinationAccount.getUuid());
      pref.putInt(DATE_FORMAT, dateFormatCombo.getSelectedIndex());
    }
  }
Exemplo n.º 10
0
 private static String getTransactionList(final Account account) {
   switch (account.getAccountType()) {
     case INVEST:
     case MUTUAL:
       return INVTRANLIST;
     default:
       return BANKTRANLIST;
   }
 }
  @Override
  protected void updateItem(final BigDecimal amount, final boolean empty) {
    super.updateItem(amount, empty); // required

    if (!empty && amount != null && getTreeTableRow().getTreeItem() != null) {
      final Account account = getTreeTableRow().getTreeItem().getValue();

      final NumberFormat format = CommodityFormat.getFullNumberFormat(account.getCurrencyNode());

      setText(format.format(amount));

      if (amount.signum() < 0) {
        setId(StyleClass.NORMAL_NEGATIVE_CELL_ID);
      } else {
        setId(StyleClass.NORMAL_CELL_ID);
      }
    } else {
      setText(null);
    }
  }
Exemplo n.º 12
0
  void refreshInfo() {
    destLabel.setText(account.getPathName());

    int count = 0;

    for (ImportTransaction tran : transactions) {
      if (tran.getState() == ImportState.NEW || tran.getState() == ImportState.NOT_EQUAL) { //
        count++;
      }
    }

    transCount.setText(Integer.toString(count));
  }
Exemplo n.º 13
0
  private void initComponents() {
    feeField = new JFloatField(account.getCurrencyNode());

    feeButton = new JButton(Resource.getIcon("/jgnash/resource/document-properties.png"));
    feeButton.setMargin(new Insets(0, 0, 0, 0));

    feeButton.addActionListener(this);
    feeButton.setFocusPainted(false);

    if (ThemeManager.isLookAndFeelNimbus()) {
      NimbusUtils.reduceNimbusButtonMargin(feeButton);
      feeButton.setIcon(
          NimbusUtils.scaleIcon(Resource.getIcon("/jgnash/resource/document-properties.png")));
    }
  }
Exemplo n.º 14
0
  @Test
  public void testExportBudgetResultsModel() throws Exception {

    File file = File.createTempFile("budget", ".xml");
    file.deleteOnExit();

    Engine e =
        EngineFactory.bootLocalEngine(
            file.getName(), EngineFactory.DEFAULT, PASSWORD, DataStoreType.XML);
    CurrencyNode node = e.getDefaultCurrency();

    Account account1 = new Account(AccountType.EXPENSE, node);
    account1.setName("Expense 1");
    e.addAccount(e.getRootAccount(), account1);

    Account account2 = new Account(AccountType.EXPENSE, node);
    account2.setName("Expense 2");
    e.addAccount(e.getRootAccount(), account2);

    Budget budget = new Budget();
    budget.setName("My Budget");
    budget.setDescription("Test");
    budget.setBudgetPeriod(BudgetPeriod.MONTHLY);

    e.addBudget(budget);

    BudgetResultsModel model = new BudgetResultsModel(budget, 2012, node);

    BudgetResultsExport.exportBudgetResultsModel(
        new File(System.getProperty("java.io.tmpdir") + File.separator + "testworkbook.xls"),
        model);

    // file.delete();

    assertTrue(true);
  }
  @Override
  public void messagePosted(final Message event) {
    final Account a = (Account) event.getObject(MessageProperty.ACCOUNT);

    if (account.equals(a)) {
      final SecurityNode node = (SecurityNode) event.getObject(MessageProperty.COMMODITY);

      EventQueue.invokeLater(
          new Runnable() {

            @Override
            public void run() {
              switch (event.getEvent()) {
                case ACCOUNT_REMOVE:
                  MessageBus.getInstance()
                      .unregisterListener(
                          AccountSecurityComboBox.this,
                          MessageChannel.ACCOUNT,
                          MessageChannel.COMMODITY);
                  model.removeAllElements();
                  account = null;
                  break;
                case ACCOUNT_SECURITY_ADD:
                  model.addElement(node);
                  break;
                case SECURITY_REMOVE:
                case ACCOUNT_SECURITY_REMOVE:
                  CommodityNode snode = getSelectedNode();
                  model.removeElement(node);

                  if (snode != null && node != null) {
                    if (snode.equals(node)) {
                      setSelectedItem(null);
                    }
                  }
                  break;
                case SECURITY_MODIFY:
                  updateNode(node);
                  break;
                default:
              }
            }
          });
    }
  }
Exemplo n.º 16
0
 private static String getBankingMessageSetAggregate(final Account account) {
   switch (account.getAccountType()) {
     case ASSET:
     case BANK:
     case CASH:
     case CHECKING:
     case SIMPLEINVEST:
       return BANKMSGSRSV1;
     case CREDIT:
     case LIABILITY:
       return CREDITCARDMSGSRSV1;
     case INVEST:
     case MUTUAL:
       return INVSTMTMSGSRSV1;
     default:
       return "";
   }
 }
Exemplo n.º 17
0
 private static String getStatementResponse(final Account account) {
   switch (account.getAccountType()) {
     case ASSET:
     case BANK:
     case CASH:
     case CHECKING:
     case SIMPLEINVEST:
       return STMTRS;
     case CREDIT:
     case LIABILITY:
       return CCSTMTRS;
     case INVEST:
     case MUTUAL:
       return INVSTMTRS;
     default:
       return "";
   }
 }
Exemplo n.º 18
0
  void importAccounts(final XMLStreamReader reader) {

    logger.info("Begin Account import");

    try {
      parse:
      while (reader.hasNext()) {
        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            if (reader.getAttributeCount() > 0) {
              if (reader.getAttributeValue(0).contains("Account")) {
                logger.finest("Found the start of an Account");
                parseAccount(reader);
              }
            }
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getLocalName().equals("objects")) {
              logger.finest("Found the end of the object list and accounts");
              break parse;
            }
            break;
          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.log(Level.SEVERE, e.toString(), e);
    }

    logger.info("Linking accounts");

    Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    for (Account account : parentMap.keySet()) {
      if (account.getAccountType() != AccountType.ROOT) {
        Account parent = accountMap.get(parentMap.get(account));
        if (!account.getParent().equals(parent)) {
          if (engine.moveAccount(account, parent)) {
            logger.log(
                Level.FINEST,
                "Moving {0} to {1}",
                new Object[] {account.getName(), parent.getName()});
          }
        }
      }
    }

    logger.info("Account import complete");
  }
Exemplo n.º 19
0
 private static String getAccountFromAggregate(final Account account) {
   switch (account.getAccountType()) {
     case ASSET:
     case BANK:
     case CASH:
     case CHECKING:
     case SIMPLEINVEST:
       return BANKACCTFROM;
     case CREDIT:
     case LIABILITY:
       return CCACCTFROM;
     case INVEST:
     case MUTUAL:
       return INVACCTFROM;
     default:
       return "";
   }
 }
Exemplo n.º 20
0
  void getBalances(final Account a, final Date[] dates1, final AccountType type) {

    for (Account child : a.getChildren()) {
      int len = child.getTransactionCount();
      if ((SHOW_EMPTY_ACCOUNT || len > 0) && type == child.getAccountType()) {
        String acctName = child.getName();

        BigDecimal acctBal =
            AccountBalanceDisplayManager.convertToSelectedBalanceMode(
                child.getAccountType(), child.getBalance(dates1[0], dates1[1], baseCommodity));

        // output account name and balance
        pl.add(formatAcctNameOut(acctName) + " " + formatDecimalOut(acctBal));

        balance.add(acctBal);
      }
      if (child.isParent()) {
        getBalances(child, dates1, type);
      }
    }
  }
Exemplo n.º 21
0
  /**
   * Creates new form AbstractDateChkNumberDialog
   *
   * @param a the account for the transaction. This can be null.
   * @param title Title for the dialog
   */
  DateChkNumberDialog(final Account a, final String title) {
    super(UIApplication.getFrame(), ModalityType.APPLICATION_MODAL);

    setTitle(title);

    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    this.account = a;

    buildPanel();

    if (a != null) {
      numberCombo.setText(a.getNextTransactionNumber());
    }

    pack();
    setMinimumSize(getSize());

    DialogUtils.addBoundsListener(this);
  }
Exemplo n.º 22
0
  /**
   * Writes one bank transaction
   *
   * @param transaction <code>Transaction</code> to write
   */
  private void writeBankTransaction(final Transaction transaction) {
    indentedWriter.println(wrapOpen(STMTTRN), indentLevel++);
    indentedWriter.println(
        wrapOpen(TRNTYPE)
            + (transaction.getAmount(account).compareTo(BigDecimal.ZERO) == 1 ? CREDIT : DEBIT),
        indentLevel);

    indentedWriter.println(wrapOpen(DTPOSTED) + encodeDate(transaction.getDate()), indentLevel);
    indentedWriter.println(
        wrapOpen(TRNAMT) + transaction.getAmount(account).toPlainString(), indentLevel);
    indentedWriter.println(wrapOpen(REFNUM) + transaction.getUuid(), indentLevel);
    indentedWriter.println(wrapOpen(NAME) + transaction.getPayee(), indentLevel);
    indentedWriter.println(wrapOpen(MEMO) + transaction.getMemo(), indentLevel);

    // write the check number if applicable
    if (account.getAccountType() == AccountType.CHECKING && !transaction.getNumber().isEmpty()) {
      indentedWriter.println(wrapOpen(CHECKNUM) + transaction.getNumber(), indentLevel);
    }

    // write out the banks transaction id if previously imported
    writeFitID(transaction);

    indentedWriter.println(wrapClose(STMTTRN), --indentLevel);
  }
Exemplo n.º 23
0
 private void updateTitle(final Account account) {
   setTitle("jGnash - " + account.getPathName());
 }
Exemplo n.º 24
0
 /** Writes all bank account transactions within the date range */
 private void writeBankTransactions() {
   for (Transaction transaction : account.getTransactions(startDate, endDate)) {
     writeBankTransaction(transaction);
   }
 }
Exemplo n.º 25
0
 public void setParentAccount(final Account parentAccount) {
   this.parentAccount = parentAccount;
   parentButton.setText(parentAccount.getName());
   setAccountCurrency(parentAccount.getCurrencyNode());
 }
Exemplo n.º 26
0
  private Account generateAccount(final String accountClass, final Map<String, Object> elementMap) {

    Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    CurrencyNode node = decodeCurrency((String) elementMap.get("commodity"));

    if (accountClass.equals("RootAccount")) {
      engine.setDefaultCurrency(node);
      return engine.getRootAccount();
    }

    Account account = null;

    switch (accountClass) {
      case "BankAccount":
        account = new Account(AccountType.BANK, node);
        break;
      case "ExpenseAccount":
        account = new Account(AccountType.EXPENSE, node);
        break;
      case "IncomeAccount":
        account = new Account(AccountType.INCOME, node);
        break;
      case "InvestmentAccount":
        {
          account = new Account(AccountType.INVEST, node);

          String[] securities = (String[]) elementMap.get("securities");

          if (securities != null) {
            for (String s : securities) {
              SecurityNode sNode = decodeSecurity(s);
              account.addSecurity(sNode);
            }
          }
          break;
        }
      case "MutualFundAccount":
        {
          account = new Account(AccountType.MUTUAL, node);

          String[] securities = (String[]) elementMap.get("securities");

          if (securities != null) {
            for (String s : securities) {
              SecurityNode sNode = decodeSecurity(s);
              account.addSecurity(sNode);
            }
          }
          break;
        }
      case "CreditAccount":
        account = new Account(AccountType.CREDIT, node);
        break;
      case "CashAccount":
        account = new Account(AccountType.CASH, node);
        break;
      case "EquityAccount":
        account = new Account(AccountType.EQUITY, node);
        break;
      case "LiabilityAccount":
        account = new Account(AccountType.LIABILITY, node);
        break;
      case "AssetAccount":
        account = new Account(AccountType.ASSET, node);
        break;
      default:
        break;
    }

    if (account != null) {
      account.setName((String) elementMap.get("name"));
      account.setDescription((String) elementMap.get("description"));
      account.setNotes((String) elementMap.get("notes"));
      account.setVisible(Boolean.parseBoolean((String) elementMap.get("visible")));
      account.setPlaceHolder(Boolean.parseBoolean((String) elementMap.get("placeHolder")));
      account.setAccountNumber((String) elementMap.get("code"));
    }
    return account;
  }
Exemplo n.º 27
0
  @SuppressWarnings({"unchecked", "ConstantConditions"})
  private void parseAccount(final XMLStreamReader reader) {

    assert reader.getAttributeCount() == 2;

    Map<String, Object> elementMap = new HashMap<>();

    /* still at start of the account.  Need to know when end is reached */
    QName parsingElement = reader.getName();

    String accountClass = reader.getAttributeValue(0);
    String accountId = reader.getAttributeValue(1);

    try {
      while (reader.hasNext()) {
        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            String element = reader.getLocalName();

            switch (element) {
              case "securities":
                logger.info("Parsing account securities");
                elementMap.put("securities", parseAccountSecurities(reader));
                break;
              case "amortize":
                logger.info("Parsing amortize object");
                elementMap.put("amortize", parseAmortizeObject(reader));
                break;
              case "locked":
                lockMap.put(accountId, Boolean.valueOf(reader.getElementText()));
                break;
              default:
                elementMap.put(element, reader.getElementText());
                break;
            }
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getName().equals(parsingElement)) {
              logger.finest("Found the end of an Account");

              Account account = generateAccount(accountClass, elementMap);

              if (account != null) {
                accountMap.put(accountId, account);

                // do not put the root account into the parent map
                if (account.getAccountType() != AccountType.ROOT) {
                  parentMap.put(account, (String) elementMap.get("parentAccount"));
                }

                if (account.getAccountType() != AccountType.ROOT) {
                  Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

                  engine.addAccount(engine.getRootAccount(), account);

                  if (account.getAccountType() == AccountType.LIABILITY) {
                    Map<String, String> amortizeObject =
                        (Map<String, String>) elementMap.get("amortize");

                    if (amortizeObject != null) {
                      AOThread t = new AOThread(account, amortizeObject);
                      workQueue.add(t);
                    }
                  }
                }
              }
              return;
            }
            break;
          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.log(Level.SEVERE, "Error importing account id: {0}", accountId);
      logger.log(Level.SEVERE, e.toString(), e);
    }
  }
Exemplo n.º 28
0
  private Transaction generateTransaction(
      final String transactionClass, final Map<String, String> elementMap) {
    // logger.finest("Being generateTransaction");
    switch (transactionClass) {
      case "SplitTransaction":
        logger.finest("Found SplitTransaction");
        splitList.add(elementMap);
        return null;
      case "SplitEntryTransaction":
        logger.finest("Found SplitEntryTransaction");
        splitEntryList.add(elementMap);
        return null;
    }

    // logger.finest("Building base transation");

    Transaction transaction = null;

    Date actDate = decodeDate(elementMap.get("actTransDate"));
    Date date = decodeDate(elementMap.get("voucherDate"));
    String memo = elementMap.get("memo");
    String payee = elementMap.get("payee");
    String number = elementMap.get("number");
    CurrencyNode node = decodeCurrency(elementMap.get("commodity"));

    // logger.finest(transactionClass);

    if (transactionClass.equals("AddXTransaction")
        || transactionClass.equals("RemoveXTransaction")) {
      BigDecimal price = new BigDecimal(elementMap.get("price"));
      BigDecimal quantity = new BigDecimal(elementMap.get("quantity"));
      Account investmentAccount = accountMap.get(elementMap.get("investmentAccount"));
      boolean reconciled = Boolean.parseBoolean(elementMap.get("reconciled"));
      SecurityNode sNode =
          EngineFactory.getEngine(EngineFactory.DEFAULT).getSecurity(elementMap.get("security"));

      transaction = new InvestmentTransaction();

      AbstractInvestmentTransactionEntry entry;

      if (transactionClass.equals("AddXTransaction")) {
        entry = new TransactionEntryAddX(investmentAccount, sNode, price, quantity);
      } else {
        entry = new TransactionEntryRemoveX(investmentAccount, sNode, price, quantity);
      }

      entry.setMemo(memo);

      transaction.setDate(date);
      transaction.setDateEntered(actDate);
      transaction.setPayee(payee);
      transaction.addTransactionEntry(entry);

      transaction.setReconciled(
          investmentAccount,
          reconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);
    }

    if (transactionClass.equals("SplitXTransaction")
        || transactionClass.equals("MergeXTransaction")) {
      BigDecimal price = new BigDecimal(elementMap.get("price"));
      BigDecimal quantity = new BigDecimal(elementMap.get("quantity"));
      Account investmentAccount = accountMap.get(elementMap.get("investmentAccount"));
      boolean reconciled = Boolean.parseBoolean(elementMap.get("reconciled"));
      SecurityNode sNode =
          EngineFactory.getEngine(EngineFactory.DEFAULT).getSecurity(elementMap.get("security"));

      transaction = new InvestmentTransaction();

      AbstractInvestmentTransactionEntry entry;

      if (transactionClass.equals("SplitXTransaction")) {
        entry = new TransactionEntrySplitX(investmentAccount, sNode, price, quantity);
      } else {
        entry = new TransactionEntryMergeX(investmentAccount, sNode, price, quantity);
      }

      entry.setMemo(memo);

      transaction.setDate(date);
      transaction.setDateEntered(actDate);
      transaction.setPayee(payee);
      transaction.addTransactionEntry(entry);

      transaction.setReconciled(
          investmentAccount,
          reconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);
    }

    if (transactionClass.equals("BuyXTransaction") || transactionClass.equals("SellXTransaction")) {
      BigDecimal fees = new BigDecimal(elementMap.get("fees"));
      BigDecimal price = new BigDecimal(elementMap.get("price"));
      BigDecimal quantity = new BigDecimal(elementMap.get("quantity"));
      Account investmentAccount = accountMap.get(elementMap.get("investmentAccount"));
      Account account = accountMap.get(elementMap.get("account"));
      boolean accountReconciled = Boolean.parseBoolean(elementMap.get("accountReconciled"));
      boolean investmentAccountReconciled =
          Boolean.parseBoolean(elementMap.get("investmentAccountReconciled"));
      SecurityNode sNode =
          EngineFactory.getEngine(EngineFactory.DEFAULT).getSecurity(elementMap.get("security"));

      BigDecimal exchangeRate = BigDecimal.ONE;

      if (sNode != null) {

        if (transactionClass.equals("BuyXTransaction")) {
          transaction =
              TransactionFactory.import1xBuyXTransaction(
                  account,
                  investmentAccount,
                  sNode,
                  price,
                  quantity,
                  exchangeRate,
                  fees,
                  date,
                  memo);
        } else {
          transaction =
              TransactionFactory.import1xSellXTransaction(
                  account,
                  investmentAccount,
                  sNode,
                  price,
                  quantity,
                  exchangeRate,
                  fees,
                  date,
                  memo);
        }

        transaction.setDateEntered(actDate);
        transaction.setPayee(payee);

        transaction.setReconciled(
            investmentAccount,
            investmentAccountReconciled
                ? ReconciledState.RECONCILED
                : ReconciledState.NOT_RECONCILED);
        transaction.setReconciled(
            account,
            accountReconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);
      }
    }

    if (transactionClass.equals("DividendTransaction")) {

      BigDecimal amount = new BigDecimal(elementMap.get("amount"));
      Account investmentAccount = accountMap.get(elementMap.get("investmentAccount"));
      Account account = accountMap.get(elementMap.get("account"));
      boolean accountReconciled = Boolean.parseBoolean(elementMap.get("accountReconciled"));
      boolean investmentAccountReconciled =
          Boolean.parseBoolean(elementMap.get("investmentAccountReconciled"));
      SecurityNode sNode =
          EngineFactory.getEngine(EngineFactory.DEFAULT).getSecurity(elementMap.get("security"));

      transaction =
          TransactionFactory.generateDividendXTransaction(
              investmentAccount,
              investmentAccount,
              account,
              sNode,
              amount,
              amount.negate(),
              amount,
              date,
              memo,
              accountReconciled);

      ReconcileManager.reconcileTransaction(
          investmentAccount,
          transaction,
          investmentAccountReconciled
              ? ReconciledState.RECONCILED
              : ReconciledState.NOT_RECONCILED);

      ReconcileManager.reconcileTransaction(
          account,
          transaction,
          accountReconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);
    }

    if (transactionClass.equals("ReinvestDivTransaction")) {
      BigDecimal fees = new BigDecimal(elementMap.get("fees"));
      BigDecimal price = new BigDecimal(elementMap.get("price"));
      BigDecimal quantity = new BigDecimal(elementMap.get("quantity"));
      SecurityNode sNode =
          EngineFactory.getEngine(EngineFactory.DEFAULT).getSecurity(elementMap.get("security"));
      Account investmentAccount = accountMap.get(elementMap.get("investmentAccount"));
      boolean reconciled = Boolean.parseBoolean(elementMap.get("reconciled"));

      transaction = new InvestmentTransaction();

      AbstractInvestmentTransactionEntry entry =
          new TransactionEntryReinvestDivX(investmentAccount, sNode, price, quantity);

      entry.setMemo(memo);

      transaction.setDate(date);
      transaction.setDateEntered(actDate);
      transaction.setPayee(payee);

      transaction.addTransactionEntry(entry);

      if (fees.compareTo(BigDecimal.ZERO) > 0) {
        TransactionEntry fTran = new TransactionEntry(investmentAccount, fees.negate());
        fTran.setMemo(memo);
        fTran.setTransactionTag(TransactionTag.INVESTMENT_FEE);

        transaction.addTransactionEntry(fTran);
      }

      transaction.setReconciled(
          investmentAccount,
          reconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);
    }
    switch (transactionClass) {
      case "SingleEntryTransaction":
        {
          BigDecimal amount = new BigDecimal(elementMap.get("amount"));
          Account account = accountMap.get(elementMap.get("account"));
          boolean reconciled = Boolean.parseBoolean(elementMap.get("reconciled"));
          transaction =
              TransactionFactory.generateSingleEntryTransaction(
                  account, amount, date, reconciled, memo, payee, number);
          transaction.setDateEntered(actDate);
          break;
        }
      case "DoubleEntryTransaction":
        {
          Account creditAccount = accountMap.get(elementMap.get("creditAccount"));
          Account debitAccount = accountMap.get(elementMap.get("debitAccount"));
          BigDecimal amount = new BigDecimal(elementMap.get("amount"));
          boolean creditReconciled = Boolean.parseBoolean(elementMap.get("creditReconciled"));
          boolean debitReconciled = Boolean.parseBoolean(elementMap.get("debitReconciled"));
          transaction = new Transaction();
          transaction.setDate(date);
          transaction.setDateEntered(actDate);
          transaction.setNumber(number);
          transaction.setPayee(payee);
          TransactionEntry entry = new TransactionEntry();
          entry.setMemo(memo);
          entry.setCreditAccount(creditAccount);
          entry.setDebitAccount(debitAccount);
          if (creditAccount.getCurrencyNode().equals(node)) {
            entry.setCreditAmount(amount);
          } else {
            BigDecimal exchangeRate = new BigDecimal(elementMap.get("exchangeRate"));
            entry.setCreditAmount(amount.multiply(exchangeRate));
          }
          if (debitAccount.getCurrencyNode().equals(node)) {
            entry.setDebitAmount(amount.negate());
          } else {
            BigDecimal exchangeRate = new BigDecimal(elementMap.get("exchangeRate"));
            entry.setDebitAmount(amount.multiply(exchangeRate).negate());
          }
          transaction.addTransactionEntry(entry);
          transaction.setReconciled(
              creditAccount,
              creditReconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);
          transaction.setReconciled(
              debitAccount,
              debitReconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);
          break;
        }
    }
    return transaction;
  }
Exemplo n.º 29
0
  void importTransactions(final XMLStreamReader reader) {

    logger.info("Begin transaction import");

    try {
      parse:
      while (reader.hasNext()) {
        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            if (reader.getAttributeCount() > 0
                && reader.getAttributeValue(0).contains("Transaction")) {
              logger.finest("Found the start of a Transaction");
              parseTransaction(reader);
            }
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getLocalName().equals("objects")) {
              logger.fine("Found the end of the object list and transactions");
              break parse;
            }
            break;
          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.log(Level.SEVERE, e.toString(), e);
    }

    logger.log(Level.INFO, "Generating {0} Split Transactions", splitList.size());

    /* loop through the lists and add split transactions */
    for (Iterator<Map<String, String>> i = splitList.iterator(); i.hasNext(); ) {

      Map<String, String> map = i.next();

      String id = map.get(ID);

      Transaction transaction = new Transaction();

      transaction.setDate(decodeDate(map.get("voucherDate")));
      transaction.setDateEntered(decodeDate(map.get("actTransDate")));
      transaction.setNumber(map.get("number"));
      transaction.setPayee(map.get("payee"));
      transaction.setMemo(map.get("memo"));

      for (Iterator<Map<String, String>> j = this.splitEntryList.iterator(); j.hasNext(); ) {
        Map<String, String> entryMap = j.next();

        if (entryMap.get("parent").equals(id)) {

          TransactionEntry entry = new TransactionEntry();

          entry.setMemo(entryMap.get("memo"));

          Account creditAccount = accountMap.get(entryMap.get("creditAccount"));
          Account debitAccount = accountMap.get(entryMap.get("debitAccount"));

          boolean creditReconciled = Boolean.parseBoolean(entryMap.get("creditReconciled"));
          boolean debitReconciled = Boolean.parseBoolean(entryMap.get("debitReconciled"));

          entry.setCreditAccount(creditAccount);
          entry.setDebitAccount(debitAccount);

          CurrencyNode node = decodeCurrency(entryMap.get("commodity"));
          BigDecimal amount = new BigDecimal(entryMap.get("amount"));

          if (creditAccount.getCurrencyNode().equals(node)) {
            entry.setCreditAmount(amount);
          } else {
            BigDecimal exchangeRate = new BigDecimal(entryMap.get("exchangeRate"));
            entry.setCreditAmount(amount.multiply(exchangeRate));
          }

          if (debitAccount.getCurrencyNode().equals(node)) {
            entry.setDebitAmount(amount.negate());
          } else {
            BigDecimal exchangeRate = new BigDecimal(entryMap.get("exchangeRate"));
            entry.setDebitAmount(amount.multiply(exchangeRate).negate());
          }

          transaction.addTransactionEntry(entry);

          transaction.setReconciled(
              creditAccount,
              creditReconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);

          transaction.setReconciled(
              debitAccount,
              debitReconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);

          j.remove();
        }
      }

      assert transaction.size() > 0;

      Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

      if (!engine.addTransaction(transaction)) {
        logger.log(Level.SEVERE, "Failed to import transaction: {0}", id);
      }

      i.remove();
    }

    logger.info("Transaction import complete");
  }
Exemplo n.º 30
0
  public void exportAccount() {

    final Date exportDate = new Date();

    if (account == null || startDate == null || endDate == null || file == null) {
      throw new RuntimeException();
    }

    // force a correct file extension
    final String fileName = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".ofx";

    try (IndentedPrintWriter writer =
        new IndentedPrintWriter(
            new BufferedWriter(
                new OutputStreamWriter(
                    new FileOutputStream(fileName), Charset.forName("windows-1252"))))) {

      indentedWriter = writer;

      // write the required header
      for (String line : OFXHEADER) {
        writer.println(line, indentLevel);
      }
      writer.println();

      // start of data
      writer.println(wrapOpen(OFX), indentLevel++);

      // write sign-on response
      writer.println(wrapOpen(SIGNONMSGSRSV1), indentLevel++);
      writer.println(wrapOpen(SONRS), indentLevel++);
      writer.println(wrapOpen(STATUS), indentLevel++);
      writer.println(wrapOpen(CODE) + "0", indentLevel);
      writer.println(wrapOpen(SEVERITY) + "INFO", indentLevel);
      writer.println(wrapClose(STATUS), --indentLevel);
      writer.println(wrapOpen(DTSERVER) + encodeDate(exportDate), indentLevel);
      writer.println(wrapOpen(LANGUAGE) + "ENG", indentLevel);
      writer.println(wrapClose(SONRS), --indentLevel);
      writer.println(wrapClose(SIGNONMSGSRSV1), --indentLevel);

      writer.println(wrapOpen(getBankingMessageSetAggregate(account)), indentLevel++);
      writer.println(wrapOpen(getResponse(account)), indentLevel++);
      writer.println(wrapOpen(TRNUID) + "1", indentLevel);
      writer.println(wrapOpen(STATUS), indentLevel++);
      writer.println(wrapOpen(CODE) + "0", indentLevel);
      writer.println(wrapOpen(SEVERITY) + "INFO", indentLevel);
      writer.println(wrapClose(STATUS), --indentLevel);

      // begin start of statement response
      writer.println(wrapOpen(getStatementResponse(account)), indentLevel++);
      writer.println(wrapOpen(CURDEF) + account.getCurrencyNode().getSymbol(), indentLevel);

      // write account identification
      writer.println(wrapOpen(getAccountFromAggregate(account)), indentLevel++);

      switch (account.getAccountType()) {
        case INVEST:
        case MUTUAL:
          writer.println(
              wrapOpen(BROKERID),
              indentLevel); //  required for investment accounts, but jGnash does not manage a
                            // broker ID, normally a web URL
          break;
        default:
          writer.println(
              wrapOpen(BANKID) + account.getBankId(), indentLevel); // savings and checking only
          break;
      }

      writer.println(wrapOpen(ACCTID) + account.getAccountNumber(), indentLevel);

      // write the required account type
      switch (account.getAccountType()) {
        case CHECKING:
          writer.println(wrapOpen(ACCTTYPE) + CHECKING, indentLevel);
          break;
        case ASSET:
        case BANK:
        case CASH:
          writer.println(wrapOpen(ACCTTYPE) + SAVINGS, indentLevel);
          break;
        case CREDIT:
        case LIABILITY:
          writer.println(wrapOpen(ACCTTYPE) + CREDITLINE, indentLevel);
          break;
        case SIMPLEINVEST:
          writer.println(wrapOpen(ACCTTYPE) + MONEYMRKT, indentLevel);
          break;
        default:
          break;
      }

      writer.println(wrapClose(getAccountFromAggregate(account)), --indentLevel);

      // begin start of transaction list
      writer.println(wrapOpen(getTransactionList(account)), indentLevel++);
      writer.println(wrapOpen(DTSTART) + encodeDate(startDate), indentLevel);
      writer.println(wrapOpen(DTEND) + encodeDate(endDate), indentLevel);

      // write the transaction list
      if (account.getAccountType() == AccountType.INVEST
          || account.getAccountType() == AccountType.MUTUAL) {
        writeInvestmentTransactions();
      } else {
        writeBankTransactions();
      }

      // end of transaction list
      writer.println(wrapClose(getTransactionList(account)), --indentLevel);

      // write ledger balance
      writer.println(wrapOpen(LEDGERBAL), indentLevel++);
      writer.println(wrapOpen(BALAMT) + account.getBalance(endDate).toPlainString(), indentLevel);
      writer.println(wrapOpen(DTASOF) + encodeDate(exportDate), indentLevel);
      writer.println(wrapClose(LEDGERBAL), --indentLevel);

      // end of statement response
      writer.println(wrapClose(getStatementResponse(account)), --indentLevel);
      writer.println(wrapClose(getResponse(account)), --indentLevel);
      writer.println(wrapClose(getBankingMessageSetAggregate(account)), --indentLevel);

      // finished
      writer.println(wrapClose(OFX), --indentLevel);
    } catch (IOException e) {
      Logger.getLogger(OfxExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
  }