Esempio n. 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])
Esempio n. 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
    ])
Esempio n. 3
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))
Esempio n. 4
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))