Search in sources :

Example 6 with ImportTransaction

use of jgnash.convert.imports.ImportTransaction in project jgnash by ccavanaugh.

the class Mt940Test method testMt940.

/**
     * Rudimentary test for mt940 importing: creates a parser, parses a given
     * mt940 file and checks that indeed, 18 transactions have been generated.
     * 
     * Then, converts the parsed file to an ImportBank and verifies that there's
     * still 18 transactions.
     * 
     * @throws Exception
     *             throws assert exception
     */
@Test
public void testMt940() throws Exception {
    int nTransactions = 18;
    Mt940Parser parser = new Mt940Parser();
    InputStream inputStream = this.getClass().getResourceAsStream("/bank1.STA");
    try (LineNumberReader reader = new LineNumberReader(new InputStreamReader(inputStream))) {
        Mt940File file = parser.parse(reader);
        assertEquals(nTransactions, file.getEntries().size());
        ImportBank<ImportTransaction> bank = Mt940Exporter.convert(file);
        assertEquals(nTransactions, bank.getTransactions().size());
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Mt940Parser(net.bzzt.swift.mt940.parser.Mt940Parser) LineNumberReader(java.io.LineNumberReader) ImportTransaction(jgnash.convert.imports.ImportTransaction) Test(org.junit.Test)

Example 7 with ImportTransaction

use of jgnash.convert.imports.ImportTransaction in project jgnash by ccavanaugh.

the class Mt940Exporter method convert.

/**
     * Convert a single Mt940-entry to a jGnash-Transaction
     *
     * @param entry Mt940Entry to convert
     * @return new import transaction
     */
private static ImportTransaction convert(Mt940Entry entry) {
    BigDecimal amount;
    if (entry.getSollHabenKennung() == SollHabenKennung.CREDIT) {
        // The bank account is credited, so we gained income
        amount = entry.getBetrag();
    } else if (entry.getSollHabenKennung() == SollHabenKennung.DEBIT) {
        // The bank account is debited, so we made expenses
        // withdrawals have a negative 'amount'
        amount = BigDecimal.valueOf(0L).subtract(entry.getBetrag());
    } else {
        throw new UnsupportedOperationException("SollHabenKennung " + entry.getSollHabenKennung() + " not supported");
    }
    ImportTransaction tran = new ImportTransaction();
    tran.setAmount(amount);
    tran.setDatePosted(entry.getValutaDatum());
    tran.setMemo(entry.getMehrzweckfeld());
    tran.setAccount(null);
    return tran;
}
Also used : BigDecimal(java.math.BigDecimal) ImportTransaction(jgnash.convert.imports.ImportTransaction)

Example 8 with ImportTransaction

use of jgnash.convert.imports.ImportTransaction in project jgnash by ccavanaugh.

the class OfxImport method importTransactions.

public static void importTransactions(final OfxBank ofxBank, final Account baseAccount) {
    Objects.requireNonNull(ofxBank.getTransactions());
    Objects.requireNonNull(baseAccount);
    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
    Objects.requireNonNull(engine);
    for (final ImportTransaction tran : ofxBank.getTransactions()) {
        // do not import matched transactions
        if (tran.getState() == ImportState.NEW || tran.getState() == ImportState.NOT_EQUAL) {
            Transaction transaction = null;
            if (tran.isInvestmentTransaction()) {
                if (baseAccount.getAccountType().getAccountGroup() == AccountGroup.INVEST) {
                    transaction = importInvestmentTransaction(ofxBank, tran, baseAccount);
                    if (transaction != null) {
                        // check and add the security node to the account if not present
                        if (!baseAccount.containsSecurity(((InvestmentTransaction) transaction).getSecurityNode())) {
                            engine.addAccountSecurity(((InvestmentTransaction) transaction).getInvestmentAccount(), ((InvestmentTransaction) transaction).getSecurityNode());
                        }
                    }
                } else {
                    // Signal an error
                    System.out.println("Base account was not an investment account type");
                }
            } else {
                if (baseAccount.equals(tran.getAccount())) {
                    // single entry oTran
                    transaction = TransactionFactory.generateSingleEntryTransaction(baseAccount, tran.getAmount(), tran.getDatePosted(), tran.getMemo(), tran.getPayee(), tran.getCheckNumber());
                } else {
                    // double entry
                    if (tran.getAmount().signum() >= 0) {
                        transaction = TransactionFactory.generateDoubleEntryTransaction(baseAccount, tran.getAccount(), tran.getAmount().abs(), tran.getDatePosted(), tran.getMemo(), tran.getPayee(), tran.getCheckNumber());
                    } else {
                        transaction = TransactionFactory.generateDoubleEntryTransaction(tran.getAccount(), baseAccount, tran.getAmount().abs(), tran.getDatePosted(), tran.getMemo(), tran.getPayee(), tran.getCheckNumber());
                    }
                }
            }
            // add the new transaction
            if (transaction != null) {
                transaction.setFitid(tran.getFITID());
                engine.addTransaction(transaction);
            }
        }
    }
}
Also used : InvestmentTransaction(jgnash.engine.InvestmentTransaction) ImportTransaction(jgnash.convert.imports.ImportTransaction) Transaction(jgnash.engine.Transaction) InvestmentTransaction(jgnash.engine.InvestmentTransaction) Engine(jgnash.engine.Engine) ImportTransaction(jgnash.convert.imports.ImportTransaction)

Example 9 with ImportTransaction

use of jgnash.convert.imports.ImportTransaction in project jgnash by ccavanaugh.

the class OfxV2Parser method postProcess.

/**
     * Post processes the OFX transactions for import.  Income transactions with a reinvestment transaction will be
     * stripped out. jGnash has a reinvested dividend transaction that reduces overall transaction count.
     *
     * @param ofxBank OfxBank to process
     * @return OfxBank with post processed transactions
     */
private static OfxBank postProcess(final OfxBank ofxBank) {
    // Clone the original list
    final List<ImportTransaction> importTransactions = ofxBank.getTransactions();
    // Create a list of Reinvested dividends
    final List<ImportTransaction> reinvestedDividends = importTransactions.stream().filter(importTransaction -> importTransaction.getTransactionType() == TransactionType.REINVESTDIV).collect(Collectors.toList());
    // Search through the list and remove matching income transactions
    for (final ImportTransaction reinvestDividend : reinvestedDividends) {
        final Iterator<ImportTransaction> iterator = importTransactions.iterator();
        while (iterator.hasNext()) {
            final ImportTransaction otherTran = iterator.next();
            // if this was OFX income and the securites match and the amount match, remove the transaction
            if (reinvestDividend != otherTran && OfxTags.INCOME.equals(otherTran.getTransactionTypeDescription())) {
                if (otherTran.getAmount().equals(reinvestDividend.getAmount().abs())) {
                    if (otherTran.getSecurityId().equals(reinvestDividend.getSecurityId())) {
                        // remove it
                        iterator.remove();
                        // reverse sign
                        reinvestDividend.setAmount(reinvestDividend.getAmount().abs());
                    }
                }
            }
        }
    }
    return ofxBank;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) XMLInputFactory(javax.xml.stream.XMLInputFactory) SimpleFormatter(java.util.logging.SimpleFormatter) ResourceUtils(jgnash.util.ResourceUtils) ImportSecurity(jgnash.convert.imports.ImportSecurity) NumberFormat(java.text.NumberFormat) Level(java.util.logging.Level) BigDecimal(java.math.BigDecimal) FileHandler(java.util.logging.FileHandler) XMLStreamConstants(javax.xml.stream.XMLStreamConstants) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLStreamReader(javax.xml.stream.XMLStreamReader) Locale(java.util.Locale) XMLStreamException(javax.xml.stream.XMLStreamException) ParseException(java.text.ParseException) Path(java.nio.file.Path) OfxTags(jgnash.convert.common.OfxTags) ImportTransaction(jgnash.convert.imports.ImportTransaction) Iterator(java.util.Iterator) Files(java.nio.file.Files) FileMagic(jgnash.util.FileMagic) DecimalFormat(java.text.DecimalFormat) IOException(java.io.IOException) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) TransactionType(jgnash.engine.TransactionType) List(java.util.List) LocalDate(java.time.LocalDate) QName(javax.xml.namespace.QName) Handler(java.util.logging.Handler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InputStream(java.io.InputStream) ImportTransaction(jgnash.convert.imports.ImportTransaction)

Example 10 with ImportTransaction

use of jgnash.convert.imports.ImportTransaction in project jgnash by ccavanaugh.

the class OfxV2Parser method parseInvestmentTransaction.

private void parseInvestmentTransaction(final XMLStreamReader reader) throws XMLStreamException {
    logger.entering(OfxV2Parser.class.getName(), "parseInvestmentTransaction");
    final QName parsingElement = reader.getName();
    final ImportTransaction tran = new ImportTransaction();
    // set the descriptive transaction type text as well
    tran.setTransactionTypeDescription(parsingElement.toString());
    // extract the investment transaction type from the element name
    switch(parsingElement.toString()) {
        case BUYMF:
        case BUYOTHER:
        case BUYSTOCK:
            tran.setTransactionType(TransactionType.BUYSHARE);
            break;
        case SELLMF:
        case SELLOTHER:
        case SELLSTOCK:
            tran.setTransactionType(TransactionType.SELLSHARE);
            break;
        case // dividend
        INCOME:
            tran.setTransactionType(TransactionType.DIVIDEND);
            break;
        case REINVEST:
            tran.setTransactionType(TransactionType.REINVESTDIV);
            break;
        default:
            logger.log(Level.WARNING, "Unknown investment transaction type: {0}", parsingElement.toString());
            break;
    }
    parse: while (reader.hasNext()) {
        final int event = reader.next();
        switch(event) {
            case XMLStreamConstants.START_ELEMENT:
                switch(reader.getLocalName()) {
                    case DTSETTLE:
                        tran.setDatePosted(parseDate(reader.getElementText()));
                        break;
                    case DTTRADE:
                        tran.setDateUser(parseDate(reader.getElementText()));
                        break;
                    case // total of the investment transaction
                    TOTAL:
                        tran.setAmount(parseAmount(reader.getElementText()));
                        break;
                    case FITID:
                        tran.setFITID(reader.getElementText());
                        break;
                    case // the security for the transaction
                    UNIQUEID:
                        tran.setSecurityId(reader.getElementText());
                        break;
                    case // the type of security for the transaction
                    UNIQUEIDTYPE:
                        tran.setSecurityType(reader.getElementText());
                        break;
                    case UNITS:
                        tran.setUnits(parseAmount(reader.getElementText()));
                        break;
                    case UNITPRICE:
                        tran.setUnitPrice(parseAmount(reader.getElementText()));
                        break;
                    case // investment fees
                    FEES:
                        tran.setFees(parseAmount(reader.getElementText()));
                        break;
                    case // investment commission
                    COMMISSION:
                        tran.setCommission(parseAmount(reader.getElementText()));
                        break;
                    case INCOMETYPE:
                        tran.setIncomeType(reader.getElementText());
                        break;
                    case SUBACCTSEC:
                    case SUBACCTFROM:
                    case SUBACCTTO:
                    case SUBACCTFUND:
                        tran.setSubAccount(reader.getElementText());
                        break;
                    case CHECKNUM:
                        tran.setCheckNumber(reader.getElementText());
                        break;
                    case NAME:
                    case // either PAYEE or NAME will be used
                    PAYEE:
                        tran.setPayee(reader.getElementText().replaceAll(EXTRA_SPACE_REGEX, " ").trim());
                        break;
                    case MEMO:
                        tran.setMemo(reader.getElementText().replaceAll(EXTRA_SPACE_REGEX, " ").trim());
                        break;
                    case // Chase bank mucking up the OFX standard
                    CATEGORY:
                        break;
                    case SIC:
                        tran.setSIC(reader.getElementText());
                        break;
                    case REFNUM:
                        tran.setRefNum(reader.getElementText());
                        break;
                    case PAYEEID:
                        tran.setPayeeId(reader.getElementText().replaceAll(EXTRA_SPACE_REGEX, " ").trim());
                        break;
                    case // currency used for the transaction
                    CURRENCY:
                        //tran.currency = reader.getElementText();
                        consumeElement(reader);
                        break;
                    case ORIGCURRENCY:
                        tran.setCurrency(reader.getElementText());
                        break;
                    case TAXEXEMPT:
                        tran.setTaxExempt(parseBoolean(reader.getElementText()));
                        break;
                    case BUYTYPE:
                    // consume
                    case INVBUY:
                    case INVTRAN:
                    case SECID:
                        break;
                    // consume 401k loan information
                    case LOANID:
                    case LOANPRINCIPAL:
                    case LOANINTEREST:
                        break;
                    // consume 401k information
                    case INV401KSOURCE:
                    case DTPAYROLL:
                    case PRIORYEARCONTRIB:
                        break;
                    default:
                        logger.log(Level.WARNING, "Unknown investment transaction element: {0}", reader.getLocalName());
                        break;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (reader.getName().equals(parsingElement)) {
                    //logger.fine("Found the end of the investment transaction");
                    break parse;
                }
            default:
        }
    }
    bank.addTransaction(tran);
    logger.exiting(OfxV2Parser.class.getName(), "parseInvestmentTransaction");
}
Also used : QName(javax.xml.namespace.QName) ImportTransaction(jgnash.convert.imports.ImportTransaction)

Aggregations

ImportTransaction (jgnash.convert.imports.ImportTransaction)15 BigDecimal (java.math.BigDecimal)5 InputStream (java.io.InputStream)4 Account (jgnash.engine.Account)4 LocalDate (java.time.LocalDate)3 List (java.util.List)3 QName (javax.xml.namespace.QName)3 ImportBank (jgnash.convert.imports.ImportBank)3 ImportState (jgnash.convert.imports.ImportState)3 Engine (jgnash.engine.Engine)3 Transaction (jgnash.engine.Transaction)3 TransactionType (jgnash.engine.TransactionType)3 ResourceUtils (jgnash.util.ResourceUtils)3 Test (org.junit.Test)3 IOException (java.io.IOException)2 InputStreamReader (java.io.InputStreamReader)2 LineNumberReader (java.io.LineNumberReader)2 NumberFormat (java.text.NumberFormat)2 Map (java.util.Map)2 ResourceBundle (java.util.ResourceBundle)2