コード例 #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;
      }
    }
コード例 #2
0
  @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();
      }
    }
  }
コード例 #3
0
  @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;
  }
コード例 #4
0
ファイル: RegisterStage.java プロジェクト: Richie67/jgnash
  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));
  }
コード例 #5
0
  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);
      }
    }
  }
コード例 #6
0
ファイル: OfxExport.java プロジェクト: Cybernostics/jgnash
  /** 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);
      }
    }
  }
コード例 #7
0
  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();
  }
コード例 #8
0
  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);
          }
        });
  }
コード例 #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());
    }
  }
コード例 #10
0
ファイル: OfxExport.java プロジェクト: Cybernostics/jgnash
 private static String getTransactionList(final Account account) {
   switch (account.getAccountType()) {
     case INVEST:
     case MUTUAL:
       return INVTRANLIST;
     default:
       return BANKTRANLIST;
   }
 }
コード例 #11
0
  @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);
    }
  }
コード例 #12
0
ファイル: ImportSummary.java プロジェクト: laeubi/jgnash
  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));
  }
コード例 #13
0
ファイル: FeePanel.java プロジェクト: CptMauli/jgnash
  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")));
    }
  }
コード例 #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);
  }
コード例 #15
0
  @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:
              }
            }
          });
    }
  }
コード例 #16
0
ファイル: OfxExport.java プロジェクト: Cybernostics/jgnash
 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 "";
   }
 }
コード例 #17
0
ファイル: OfxExport.java プロジェクト: Cybernostics/jgnash
 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 "";
   }
 }
コード例 #18
0
ファイル: Import.java プロジェクト: CptMauli/jgnash
  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");
  }
コード例 #19
0
ファイル: OfxExport.java プロジェクト: Cybernostics/jgnash
 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 "";
   }
 }
コード例 #20
0
ファイル: ProfitLossTXT.java プロジェクト: tsachev/jgnash
  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);
      }
    }
  }
コード例 #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);
  }
コード例 #22
0
ファイル: OfxExport.java プロジェクト: Cybernostics/jgnash
  /**
   * 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);
  }
コード例 #23
0
ファイル: RegisterStage.java プロジェクト: Richie67/jgnash
 private void updateTitle(final Account account) {
   setTitle("jGnash - " + account.getPathName());
 }
コード例 #24
0
ファイル: OfxExport.java プロジェクト: Cybernostics/jgnash
 /** Writes all bank account transactions within the date range */
 private void writeBankTransactions() {
   for (Transaction transaction : account.getTransactions(startDate, endDate)) {
     writeBankTransaction(transaction);
   }
 }
コード例 #25
0
ファイル: AccountPanel.java プロジェクト: laeubi/jgnash
 public void setParentAccount(final Account parentAccount) {
   this.parentAccount = parentAccount;
   parentButton.setText(parentAccount.getName());
   setAccountCurrency(parentAccount.getCurrencyNode());
 }
コード例 #26
0
ファイル: Import.java プロジェクト: CptMauli/jgnash
  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;
  }
コード例 #27
0
ファイル: Import.java プロジェクト: CptMauli/jgnash
  @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);
    }
  }
コード例 #28
0
ファイル: Import.java プロジェクト: CptMauli/jgnash
  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;
  }
コード例 #29
0
ファイル: Import.java プロジェクト: CptMauli/jgnash
  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");
  }
コード例 #30
0
ファイル: OfxExport.java プロジェクト: Cybernostics/jgnash
  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);
    }
  }