Beispiel #1
0
def command(args):
    import os
    from subprocess import check_call

    from sr.tools import spending
    from sr.tools.budget import BudgetTree

    root = spending.find_root()
    budget = spending.load_budget_with_spending(root)
    line = budget.path(args.budgetline)

    if isinstance(line, BudgetTree):
        print("Summary for tree", args.budgetline)
        budgeted = sum([x.cost for x in line.walk()])
        spent = sum([x.spent for x in line.walk()])
    else:
        print("Summary for line", args.budgetline)
        budgeted = line.cost
        spent = line.spent

    print("Budgeted:\t", budgeted)
    print("Spent:\t\t", spent)

    if spent > budgeted:
        print("OVER BUDGET")

    print("Transactions:")

    account = spending.budget_line_to_account(args.budgetline)
    check_call([
        "ledger", "--file",
        os.path.join(root, "spending.dat"), "reg", account
    ])
Beispiel #2
0
def command(args):
    import os
    from subprocess import check_call

    from sr.tools import spending
    from sr.tools.budget import BudgetTree

    root = spending.find_root()
    budget = spending.load_budget_with_spending(root)
    line = budget.path(args.budgetline)

    if isinstance(line, BudgetTree):
        print("Summary for tree", args.budgetline)
        budgeted = sum([x.cost for x in line.walk()])
        spent = sum([x.spent for x in line.walk()])
    else:
        print("Summary for line", args.budgetline)
        budgeted = line.cost
        spent = line.spent

    print("Budgeted:\t", budgeted)
    print("Spent:\t\t", spent)

    if spent > budgeted:
        print("OVER BUDGET")

    print("Transactions:")

    account = spending.budget_line_to_account(args.budgetline)
    check_call(["ledger",
                "--file", os.path.join(root, "spending.dat"),
                "reg", account])
Beispiel #3
0
def command(args):
    import re
    import sys
    import six.moves.xmlrpc_client as xmlrpclib

    from sr.tools import spending
    from sr.tools.trac import TracProxy

    try:
        root = spending.find_root()
    except spending.NotSpendingRepo:
        print(
            "Please run in spending.git top level directory", file=sys.stderr)
        exit(1)

    spends = spending.load_transactions(root)

    spendsumgrp = {}
    for s in spends:
        if s.trac in spendsumgrp:
            spendsumgrp[s.trac] += float(s.cost)
        else:
            spendsumgrp[s.trac] = float(s.cost)

    server = TracProxy(anon=True)
    mserver = xmlrpclib.MultiCall(server)

    tickets = server.ticket.query("status!=closed&component=Purchasing")
    for ticket in tickets:
        mserver.ticket.get(ticket)

    costsumgrp = {}
    for ticket in mserver():
        match = re.search(
            'Total cost: \xa3([0-9.]+)', ticket[3]['description'])
        if match is None:
            print("Unable to determine cost for ticket " +
                  str(ticket[0]) + ". Invalid formatting")
            continue

        if ticket[0] in costsumgrp:
            costsumgrp[ticket[0]] += float(match.groups()[0])
        else:
            costsumgrp[ticket[0]] = float(match.groups()[0])

    for val in costsumgrp:
        if spendsumgrp[val] != costsumgrp[val]:
            print("Ticket " + str(val) + " does not match transactions")
            print("\tTicket cost:  £" + str(costsumgrp[val]))
            print("\tTransactions: £" + str(spendsumgrp[val]))
Beispiel #4
0
def command(args):
    from decimal import Decimal as D
    import sys

    from sr.tools import spending
    from sr.tools.budget import BudgetTree

    try:
        root = spending.find_root()
    except spending.NotSpendingRepo:
        print("Please run in spending.git", file=sys.stderr)
        sys.exit(1)

    bud = spending.load_budget_with_spending(root)

    if args.path != "/":
        try:
            budline = bud.path(args.path)
        except KeyError:
            print("Budget line '" + args.path + "' not found", file=sys.stderr)
            sys.exit(1)
    else:
        budline = bud

    total = D(0)
    spent = D(0)
    total_unspent = D(0)

    if isinstance(budline, BudgetTree):
        for line in budline.walk():
            spent += line.spent
            total += line.cost
            unspent = line.cost - line.spent

            if unspent != D(0):
                print(line.name, unspent)
            total_unspent += unspent

        print("-" * 10)

    else:
        total_unspent = budline.cost - budline.spent

    print("Total budget:\t", total)
    print("Total unspent:\t", total_unspent)
Beispiel #5
0
def command(args):
    import os
    import sys

    from sr.tools import spending
    from sr.tools.config import Config
    from sr.tools.environment import get_config_filename

    # Invoke ledger on the SR spending repo
    # Check that we are indeed invoking it on spending.git
    config = Config()

    # Default to using the spending.git specified in the config
    root = config["spending"]
    if root is not None:
        root = os.path.expanduser(root)
    else:
        # Not specified in the config
        root = os.getcwd()

    try:
        # Check that it's actually spending.git
        root = spending.find_root(path=root)
    except spending.NotSpendingRepo:
        print("This isn't SR spending.git", file=sys.stderr)
        print("Solve this by either:", file=sys.stderr)
        print(" - Changing working directory to spending.git", file=sys.stderr)
        print(" - Set the 'spending' config option in {}".format(
            get_config_filename()),
              file=sys.stderr)
        sys.exit(1)

    ledger_args = ['ledger'] + args.command
    if "--file" not in args:
        # Tell ledger where to look
        ledger_args = ['ledger', "--file", os.path.join(root, "spending.dat")] \
            + args.command

    os.execvp("ledger", ledger_args)
Beispiel #6
0
def command(args):
    import os
    import sys

    from sr.tools import spending
    from sr.tools.config import Config
    from sr.tools.environment import get_config_filename

    # Invoke ledger on the SR spending repo
    # Check that we are indeed invoking it on spending.git
    config = Config()

    # Default to using the spending.git specified in the config
    root = config["spending"]
    if root is not None:
        root = os.path.expanduser(root)
    else:
        # Not specified in the config
        root = os.getcwd()

    try:
        # Check that it's actually spending.git
        root = spending.find_root(path=root)
    except spending.NotSpendingRepo:
        print("This isn't SR spending.git", file=sys.stderr)
        print("Solve this by either:", file=sys.stderr)
        print(" - Changing working directory to spending.git", file=sys.stderr)
        print(" - Set the 'spending' config option in {}"
              .format(get_config_filename()), file=sys.stderr)
        sys.exit(1)

    ledger_args = ['ledger'] + args.command
    if "--file" not in args:
        # Tell ledger where to look
        ledger_args = ['ledger', "--file", os.path.join(root, "spending.dat")] \
            + args.command

    os.execvp("ledger", ledger_args)
Beispiel #7
0
def command(args):
    import re
    import sys

    import sr.tools.spending as srspending
    import sr.tools.budget as srbudget

    try:
        spending_root = srspending.find_root()
    except srspending.NotSpendingRepo:
        print("Please run in spending.git repository", file=sys.stderr)
        exit(1)

    budget = srspending.load_budget_with_spending(spending_root)

    path = budget.path(args.LINE)

    if isinstance(path, srbudget.BudgetItem):
        items = [path]
    else:
        items = path.walk()

    for item in items:
        if item.closed:
            # Line is already closed; nothing to do
            continue

        if item.spent > (item.cost * srbudget.FUDGE_FACTOR):
            # More has been spent than the budget line's value
            print(
                "Cannot close {0}: More has been spent than budgeted.".format(
                    item.name),
                file=sys.stderr)
            print("\tSpent: £{0}\n\tBudgeted: £{1}".format(
                item.spent, item.cost * srbudget.FUDGE_FACTOR),
                  file=sys.stderr)
            # Skip this item
            continue

        orig_contents = open(item.fname, 'r').read()
        contents = re.sub(r'^(\s*cost\s*:\s*).+$',
                          r'\g<1>{0}'.format(item.spent), orig_contents, 0,
                          re.MULTILINE)

        # Check that the cost has actually been changed
        # within the string if it actually needed to be
        if item.spent != item.cost and contents == orig_contents:
            print("Warning: Failed to set the cost of {0} -- skipping it.".
                  format(item.name),
                  file=sys.stderr)
            continue

        # Mark as closed
        m = re.search(r"^\s*closed\s*:.*$", contents, flags=re.MULTILINE)
        if m is not None:
            # There's a closed line in there already
            contents = re.sub(r"^(\s*closed\s*:\s*).*$",
                              r"\1true",
                              contents,
                              flags=re.MULTILINE)
        else:
            contents += "\nclosed: true\n"

        with open(item.fname, 'w') as file:
            file.write(contents)
Beispiel #8
0
def command(args):
    import re
    import sys

    import sr.tools.spending as srspending
    import sr.tools.budget as srbudget

    try:
        spending_root = srspending.find_root()
    except srspending.NotSpendingRepo:
        print("Please run in spending.git repository", file=sys.stderr)
        exit(1)

    budget = srspending.load_budget_with_spending(spending_root)

    path = budget.path(args.LINE)

    if isinstance(path, srbudget.BudgetItem):
        items = [path]
    else:
        items = path.walk()

    for item in items:
        if item.closed:
            # Line is already closed; nothing to do
            continue

        if item.spent > (item.cost * srbudget.FUDGE_FACTOR):
            # More has been spent than the budget line's value
            print("Cannot close {0}: More has been spent than budgeted."
                  .format(item.name), file=sys.stderr)
            print("\tSpent: £{0}\n\tBudgeted: £{1}"
                  .format(item.spent, item.cost * srbudget.FUDGE_FACTOR),
                  file=sys.stderr)
            # Skip this item
            continue

        orig_contents = open(item.fname, 'r').read()
        contents = re.sub(r'^(\s*cost\s*:\s*).+$',
                          r'\g<1>{0}'.format(item.spent),
                          orig_contents, 0, re.MULTILINE)

        # Check that the cost has actually been changed
        # within the string if it actually needed to be
        if item.spent != item.cost and contents == orig_contents:
            print("Warning: Failed to set the cost of {0} -- skipping it."
                  .format(item.name), file=sys.stderr)
            continue

        # Mark as closed
        m = re.search(r"^\s*closed\s*:.*$", contents, flags=re.MULTILINE)
        if m is not None:
            # There's a closed line in there already
            contents = re.sub(r"^(\s*closed\s*:\s*).*$",
                              r"\1true",
                              contents,
                              flags=re.MULTILINE)
        else:
            contents += "\nclosed: true\n"

        with open(item.fname, 'w') as file:
            file.write(contents)
Beispiel #9
0
def command(args):
    import datetime

    import sr.tools.spending as srspending
    import sr.tools.budget as srbudget
    from sr.tools.trac import TracProxy, WrongServer

    try:
        spending_root = srspending.find_root()
    except srspending.NotSpendingRepo:
        print("Please run in spending.git top level directory",
              file=sys.stderr)
        sys.exit(1)

    try:
        budget = srspending.load_budget_with_spending(spending_root)
    except srbudget.NoBudgetConfig as nbc:
        print("Error:", nbc.message, file=sys.stderr)
        print("Have you initialised the budget submodule?", file=sys.stderr)
        print("If not, run 'git submodule update --init'.", file=sys.stderr)
        sys.exit(1)

    if args.spend_file is not None:
        spend_request = SpendRequest(args.spend_file)
    else:
        spend_request = SpendRequest.from_editor()

    ticket_text = "Payee: {} \\\\\n".format(spend_request.username)

    if spend_request.supplier_url is None:
        ticket_text += "Supplier: {} \\\\\n".format(spend_request.supplier)
    else:
        ticket_text += "Supplier: [{url} {supplier}] \\\\\n" \
                       .format(url=spend_request.supplier_url,
                               supplier=spend_request.supplier)

    budget_line_totals = {}

    for purchase in spend_request.purchases:
        try:
            budget_line = budget.path(purchase.budget_line)
        except KeyError:
            # TODO: Move this check up into the parser so it's caught and the
            # user can fix it
            print('Budget line "{0}" not found', file=sys.stderr)
            sys.exit(1)

        bl_request_total = D(0)

        ticket_text += """
    === Items from [budget:{budget_line}] ===
    {summary} \\\\
    ||= '''Item''' =||= '''Cost''' =||
    """.format(budget_line=purchase.budget_line,
               summary=purchase.summary)

        for item in purchase.items:
            ticket_text += "|| {desc} || £{cost} ||\n".format(desc=item.desc,
                                                              cost=item.cost)

            bl_request_total += item.cost

        # How much has already been spent against this budget line
        spent = budget_line.spent

        req_total = spent + bl_request_total

        # It is over the limit?
        if req_total > budget_line.cost:
            print("Warning: This purchase exceeds the budget line '{0}'"
                  .format(purchase.budget_line))
            print("\tBudget line's value: £{0}".format(budget_line.cost))
            print("\tRequested Expenditure: £{0} ({1}%)"
                  .format(req_total, 100 * (req_total) / budget_line.cost))
            if not input("Continue anyway? [y/N] ").lower() == 'y':
                sys.exit()

        if purchase.budget_line not in budget_line_totals:
            budget_line_totals[purchase.budget_line] = D(0)
        budget_line_totals[purchase.budget_line] += bl_request_total

    ticket_text += """
    === Budget Line Totals ===
    ||= '''Budget Line''' =||= '''Total''' =||
    """
    for line, total in budget_line_totals.items():
        ticket_text += "|| [budget:{line}] || £{total} ||\n" \
                       .format(line=line, total=total)

    print(ticket_text)

    if args.dry_run:
        print("Stopping before actually creating ticket.")
        sys.exit(0)

    try:
        server = TracProxy(server=args.server, port=args.port)
    except WrongServer:
        print("Error: The specified server is not a Trac instance",
              file=sys.stderr)
        sys.exit(1)

    ticketNum = server.ticket.create(spend_request.summary,
                                     ticket_text,
                                     {'component': "Purchasing",
                                      'owner': "treasurer",
                                      'type': "task"})

    if not ticketNum > 0:
        print("Unable to create a valid ticket")
        sys.exit()

    if args.port == 443:
        hostname = args.server
    else:
        hostname = "{0}:{1}".format(args.server, args.port)

    print("Purchasing ticket created: https://{0}/trac/ticket/{1}".format(
        hostname, ticketNum))

    print("Spending Entries:")

    for purchase in spend_request.purchases:
        print()
        today = datetime.date.today()

        i = "{date} ! {summary}\n"
        i += "    {account}\t£{amount}\n"
        i += "    Liabilities:{payee}\n"
        i += "    ; trac: #{trac}"

        print(i.format(date=today.isoformat(),
                       summary=purchase.summary,
                       account=srspending.budget_line_to_account(
                           purchase.budget_line),
                       amount=sum([x.cost for x in purchase.items]),
                       payee=spend_request.username,
                       trac=ticketNum))
Beispiel #10
0
def command(args):
    import datetime

    import sr.tools.spending as srspending
    import sr.tools.budget as srbudget
    from sr.tools.trac import TracProxy, WrongServer

    try:
        spending_root = srspending.find_root()
    except srspending.NotSpendingRepo:
        print("Please run in spending.git top level directory",
              file=sys.stderr)
        sys.exit(1)

    try:
        budget = srspending.load_budget_with_spending(spending_root)
    except srbudget.NoBudgetConfig as nbc:
        print("Error:", nbc.message, file=sys.stderr)
        print("Have you initialised the budget submodule?", file=sys.stderr)
        print("If not, run 'git submodule update --init'.", file=sys.stderr)
        sys.exit(1)

    if args.spend_file is not None:
        spend_request = SpendRequest(args.spend_file)
    else:
        spend_request = SpendRequest.from_editor()

    ticket_text = "Payee: {} \\\\\n".format(spend_request.username)

    if spend_request.supplier_url is None:
        ticket_text += "Supplier: {} \\\\\n".format(spend_request.supplier)
    else:
        ticket_text += "Supplier: [{url} {supplier}] \\\\\n" \
                       .format(url=spend_request.supplier_url,
                               supplier=spend_request.supplier)

    budget_line_totals = {}

    for purchase in spend_request.purchases:
        try:
            budget_line = budget.path(purchase.budget_line)
        except KeyError:
            # TODO: Move this check up into the parser so it's caught and the
            # user can fix it
            print('Budget line "{0}" not found', file=sys.stderr)
            sys.exit(1)

        bl_request_total = D(0)

        ticket_text += """
    === Items from [budget:{budget_line}] ===
    {summary} \\\\
    ||= '''Item''' =||= '''Cost''' =||
    """.format(budget_line=purchase.budget_line, summary=purchase.summary)

        for item in purchase.items:
            ticket_text += "|| {desc} || £{cost} ||\n".format(desc=item.desc,
                                                              cost=item.cost)

            bl_request_total += item.cost

        # How much has already been spent against this budget line
        spent = budget_line.spent

        req_total = spent + bl_request_total

        # It is over the limit?
        if req_total > budget_line.cost:
            print(
                "Warning: This purchase exceeds the budget line '{0}'".format(
                    purchase.budget_line))
            print("\tBudget line's value: £{0}".format(budget_line.cost))
            print("\tRequested Expenditure: £{0} ({1}%)".format(
                req_total, 100 * (req_total) / budget_line.cost))
            if not input("Continue anyway? [y/N] ").lower() == 'y':
                sys.exit()

        if purchase.budget_line not in budget_line_totals:
            budget_line_totals[purchase.budget_line] = D(0)
        budget_line_totals[purchase.budget_line] += bl_request_total

    ticket_text += """
    === Budget Line Totals ===
    ||= '''Budget Line''' =||= '''Total''' =||
    """
    for line, total in budget_line_totals.items():
        ticket_text += "|| [budget:{line}] || £{total} ||\n" \
                       .format(line=line, total=total)

    print(ticket_text)

    if args.dry_run:
        print("Stopping before actually creating ticket.")
        sys.exit(0)

    try:
        server = TracProxy(server=args.server, port=args.port)
    except WrongServer:
        print("Error: The specified server is not a Trac instance",
              file=sys.stderr)
        sys.exit(1)

    ticketNum = server.ticket.create(spend_request.summary, ticket_text, {
        'component': "Purchasing",
        'owner': "treasurer",
        'type': "task"
    })

    if not ticketNum > 0:
        print("Unable to create a valid ticket")
        sys.exit()

    if args.port == 443:
        hostname = args.server
    else:
        hostname = "{0}:{1}".format(args.server, args.port)

    print("Purchasing ticket created: https://{0}/trac/ticket/{1}".format(
        hostname, ticketNum))

    print("Spending Entries:")

    for purchase in spend_request.purchases:
        print()
        today = datetime.date.today()

        i = "{date} ! {summary}\n"
        i += "    {account}\t£{amount}\n"
        i += "    Liabilities:{payee}\n"
        i += "    ; trac: #{trac}"

        print(
            i.format(date=today.isoformat(),
                     summary=purchase.summary,
                     account=srspending.budget_line_to_account(
                         purchase.budget_line),
                     amount=sum([x.cost for x in purchase.items]),
                     payee=spend_request.username,
                     trac=ticketNum))