def generate_record(title,
                    date,
                    auxdate,
                    state,
                    accountamounts,
                    validate=False):
    """Generates a transaction record.
    See callee.  Validate uses Ledger to validate the record.
    """
    lines = generate_record_novalidate(title, date, auxdate, state,
                                       accountamounts)

    if validate:
        sess = ledger.Session()
        try:
            sess.read_journal_from_string("\n".join(lines))
        except RuntimeError as e:
            lines = [x.strip() for x in str(e).splitlines() if x.strip()]
            lines = [x for x in lines if not x.startswith("While")]
            lines = [x + ("." if not x.endswith(":") else "") for x in lines]
            lines = " ".join(lines)
            if lines:
                raise LedgerParseError(lines)
            else:
                raise LedgerParseError(
                    "Ledger could not validate this transaction")

    return lines
Exemple #2
0
    def __init__(self, ledger_file=None, string_read=True):
        # sanity check for ledger python interface
        try:
            import ledger
        except ImportError:
            raise Exception("Ledger python interface not found!")
        if ledger_file is None:
            # TODO - better loading
            raise Exception
        else:
            if string_read:
                self.session = ledger.Session()
                self.journal = self.session.read_journal_from_string(
                    open(ledger_file).read())
            else:
                self.journal = ledger.read_journal(ledger_file)

        super(LedgerPython, self).__init__()
def generate_record(title, date, auxdate, state, accountamounts,
                    validate=False):
    """Generates a transaction record.

    date is a datetime.date
    title is a string describing the title of the transaction
    auxdate is the date when the transaction cleared, or None
    statechar is a char from parser.CHAR_* or empty string
    accountamounts is a list of:
    (account, amount)
    """
    def stramt(amt):
        assert type(amt) not in (tuple, list), amt
        if not amt:
            return ""
        return str(amt).strip()

    if state:
        state = state + " "
    else:
        state = ""

    lines = [""]
    linesemptyamts = []
    if auxdate:
        if auxdate != date:
            lines.append("%s=%s %s%s" % (date, auxdate, state, title))
        else:
            lines.append("%s %s%s" % (date, state, title))
    else:
        lines.append("%s %s%s" % (date, state, title))

    try:
        longest_acct = max(list(len(a) for a, _ in accountamounts))
        longest_amt = max(list(len(stramt(am)) for _, am in accountamounts))
    except ValueError:
        longest_acct = 30
        longest_amt = 30
    pattern = "    %-" + str(longest_acct) + "s    %" + str(longest_amt) + "s"
    pattern2 = "    %-" + str(longest_acct) + "s"
    for account, amount in accountamounts:
        if stramt(amount):
            lines.append(pattern % (account, stramt(amount)))
        else:
            linesemptyamts.append((pattern2 % (account,)).rstrip())
    lines = lines + linesemptyamts
    lines.append("")

    if validate:
        sess = ledger.Session()
        try:
            sess.read_journal_from_string("\n".join(lines))
        except RuntimeError as e:
            lines = [x.strip() for x in str(e).splitlines() if x.strip()]
            lines = [x for x in lines if not x.startswith("While")]
            lines = [x + ("." if not x.endswith(":") else "") for x in lines]
            lines = " ".join(lines)
            if lines:
                raise LedgerParseError(lines)
            else:
                raise LedgerParseError("Ledger could not validate this transaction")

    return lines
Exemple #4
0
 def reparse_ledger(self):
     self.logger.debug("Reparsing ledger.")
     session = ledger.Session()
     journal = session.read_journal_from_string(self.get_text())
     self.session = session
     self.journal = journal