Source

flowrate / flowrate / __init__.py

Full commit
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
"""Flowrate, a web-based cash flow planner.

Flowrate's main task is to record and report cash flows and their fulfillment.

"""

import calendar
import datetime
import decimal
import heapq
from operator import itemgetter
import os
os.umask(000)
thisdir = os.path.abspath(os.path.dirname(__file__))
uidir = os.path.join(thisdir, 'ui')
import sys

import cherrypy
from cherrypy import _cpreqbody, process
from cherrypy.lib import cpstats, static

import simplejson
def json_processor(entity):
    """Read application/json data into request.json."""
    if not entity.headers.get("Content-Length", ""):
        raise cherrypy.HTTPError(411)
    
    body = entity.fp.read()
    try:
        cherrypy.serving.request.json = simplejson.loads(
            body.decode('utf-8'), parse_float=decimal.Decimal)
    except ValueError:
        raise cherrypy.HTTPError(400, 'Invalid JSON document')
def json_handler(*args, **kwargs):
    value = cherrypy.serving.request._json_inner_handler(*args, **kwargs)
    return simplejson.dumps(value, use_decimal=True)

from sqlalchemy import create_engine

from flowrate import csvutil, ledger, flows, cmpdates
from flowrate.variables import ReferenceFinder, environment as env


db = None

def set_db(connstring, **kwargs):
    """Replace the global db with a new SQLAlchemy Engine."""
    global db
    db = create_engine(connstring, **kwargs)


def index(index=True):
    cherrypy.request.is_index = index
cherrypy.tools.index = cherrypy.Tool('on_start_resource', index)

def last_content_type():
    # The Content-Type that Chrome sends can't be overridden, just appended to,
    # and CherryPy takes content_type[0]. So do this til either gets fixed.
    req = cherrypy.serving.request
    ct = req.headers.elements('Content-Type')
    if ct:
        req.body.content_type = ct[-1]
cherrypy.tools.last_content_type = cherrypy.Tool('before_request_body', last_content_type)

def popint(uri):
    if not uri:
        return None
    return int(uri.rstrip('/').rsplit('/', 1)[-1])

def toInts(s):
    """Return ints from a string. '1,2-4,7+11' -> [1, 2, 3, 4, 7, 11].

    Whitespace is ignored. Any non-int'able segments will raise ValueError.
    """
    i = []
    for x in s.split(","):
        if x:
            for y in x.split("+"):
                if y:
                    r = y.split("-", 1)
                    if len(r) == 2:
                        # Range of ids
                        lo, hi = [int(z.strip()) for z in r]
                        if lo > hi:
                            continue
                        i.extend(range(lo, hi + 1))
                    else:
                        i.append(int(r[0].strip()))
    return list(set(i))

def parse_date(date_string):
    """Parse the given date string and return a datetime.date."""
    return datetime.date(*map(int, date_string.split('-')))

def ordered(iterable, *keys):
    """Return the iterator, ordered by keys (descending if '-key')."""
    for k in reversed(keys):
        if k.startswith('-'):
            iterable = sorted(iterable, key=itemgetter(k[1:]), reverse=True)
        else:
            iterable = sorted(iterable, key=itemgetter(k), reverse=False)
    return iterable

_subaccountmap = {}
def isSubAccount(child, parents):
    if isinstance(parents, tuple):
        pass
    elif isinstance(parents, list):
        parents = tuple(parents)
    else:
        parents = (parents,)

    try:
        return _subaccountmap[(child, parents)]
    except KeyError:
        for p in parents:
            for scale in (1000, 100, 10, 1):
                if p % scale == 0 and p <= child < (p + scale):
                    _subaccountmap[(child, parents)] = True
                    return True
        _subaccountmap[(child, parents)] = False
        return False


class Transaction(object):

    exposed = True
    description = (
"""A Flowrate transaction. PUT a Transaction representation to replace it
(but note that the server will ignore any members other than those
in the 'body' object). GET to return it. DELETE to destroy it.""")

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self):
        """Return the transaction."""
        req = cherrypy.serving.request

        try:
            tx = ledger.transactions[req.txid]
        except KeyError:
            raise cherrypy.NotFound()

        return {
            'self': cherrypy.url(),
            'description': self.description % vars(),
            'body': {
                'amount': tx['amount'],
                'credit': cherrypy.url("/accounts/%s" % tx['credit']),
                'debit': cherrypy.url("/accounts/%s" % tx['debit']),
                'postdate': tx['postdate'].isoformat(),
                'description': tx['description'],
                },
            }

    @cherrypy.tools.json_in(processor=json_processor)
    @cherrypy.tools.last_content_type()
    def PUT(self):
        """Update the given transaction entity."""
        req = cherrypy.serving.request

        try:
            tx = ledger.transactions[req.txid]
        except KeyError:
            raise cherrypy.NotFound()

        if "body" not in req.json:
            raise cherrypy.HTTPError("400 No Body",
                "Transactions MUST include a 'body' member.")

        # Accept the new transaction definition.
        vals = req.json["body"]
        tx['credit'] = popint(vals['credit'])
        tx['debit'] = popint(vals['debit'])
        credit_type = ledger.accounts[tx['credit']]['type']
        tx['credit_mult'] = -1 if credit_type in ('asset', 'expense') else 1
        debit_type = ledger.accounts[tx['debit']]['type']
        tx['debit_mult'] = 1 if debit_type in ('asset', 'expense') else -1

        tx['amount'] = vals['amount']
        tx['postdate'] = parse_date(vals['postdate'])
        tx['description'] = vals['description']
        tx.save()

        flows.unfulfill(tx)
        flows.fulfill(tx)

        cherrypy.response.status = 204

    def DELETE(self):
        """Destroy the definition of this transaction."""
        req = cherrypy.serving.request

        try:
            tx = ledger.transactions[req.txid]
        except KeyError:
            raise cherrypy.NotFound()

        flows.unfulfill(tx)
        tx.delete()

        cherrypy.response.status = 204


txmanager = cherrypy.tools.staticfile.handler(
    filename=os.path.join(uidir, "transactions.html"))
txmanager.GET = txmanager


def filters(accts=None, credits=None, debits=None,
            years=None, months=None, days=None, description=None):
    """Return a list of boolean functions to check the given criteria."""
    filters = []
    if accts:
        # Grab all subaccounts of the given accounts.
        accts = [a for a in ledger.accounts if isSubAccount(a, accts)]
        filters.append(
            lambda tx: tx['credit'] in accts or tx['debit'] in accts)
    if credits:
        filters.append(lambda tx: tx['credit'] in credits)
    if debits:
        filters.append(lambda tx: tx['debit'] in debits)
    if description:
        filters.append(lambda tx: description.lower() in tx['description'].lower())
    if years:
        filters.append(lambda tx: tx['postdate'].year in years)
    if months:
        filters.append(lambda tx: tx['postdate'].month in months)
    if days:
        filters.append(lambda tx: tx['postdate'].day in days)
    return filters


class Transactions(object):
    
    exposed = True
    description = (
"""A table of transactions. POST a Transaction representation
to define a new transaction.""")

    manager = txmanager

    def __init__(self):
        # This triggers tools.trailing_slash to force a redirect if missing
        self.index = self

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self, accounts='', credits='', debits='',
            years='', months='', days='', description='',
            # This querystring arg doesn't actually do anything; it's here
            # just to make constructing URI's to various resources easy
            # by sharing the full querystring.
            dategroup=''):
        """Return a table of transactions."""
        t = {
            "self": cherrypy.url(qs=cherrypy.request.query_string),
            "description": self.description % vars(),
            "manager": cherrypy.url('/transactions/manager',
                                    qs=cherrypy.request.query_string),
            "views": {"filtered": "{?account+,credit+,debit+,year+,month+,day+,description}"},
            "example": {"body": {"amount": "1000.34",
                                 "credit": "/accounts/3011",
                                 "debit": "/accounts/1021",
                                 "postdate": "2011-12-31",
                                 }},
            }

        data = []

        accounts = toInts(accounts)
        credits = toInts(credits)
        debits = toInts(debits)
        years = toInts(years)
        months = toInts(months)
        days = toInts(days)

        fs = filters(accounts, credits, debits,
                     years, months, days, description)
        # Decorate with the negative postdate ordinal so heapq.merge can sort.
        realdata = ((-tx['postdate'].toordinal(), tx)
                    for tx in ledger.find_transactions(fs))
        flowdata = ((-tx['postdate'].toordinal(), tx)
                    for tx in flows.find_transactions(fs))
        for postdate, tx in heapq.merge(realdata, flowdata):
            if tx['id'] is None:
                del tx['id']
            else:
                tx['id'] = cherrypy.url("/transactions/%s" % tx['id'])
            tx['credit'] = cherrypy.url("/accounts/%s" % tx['credit'])
            tx['debit'] = cherrypy.url("/accounts/%s" % tx['debit'])
            tx['postdate'] = tx['postdate'].isoformat()
            data.append(tx)

        if data:
            t['data'] = data

        return t

    @cherrypy.tools.json_in(processor=json_processor)
    @cherrypy.tools.last_content_type()
    def POST(self):
        """Insert the given transaction entity."""
        req = cherrypy.serving.request
        if "body" not in req.json:
            raise cherrypy.HTTPError("400 No Body",
                "Transactions MUST include a 'body' member.")

        # Accept the new transaction definition.
        vals = req.json["body"]
        vals['credit'] = popint(vals['credit'])
        vals['debit'] = popint(vals['debit'])
        credit_type = ledger.accounts[vals['credit']]['type']
        vals['credit_mult'] = -1 if credit_type in ('asset', 'expense') else 1
        debit_type = ledger.accounts[vals['debit']]['type']
        vals['debit_mult'] = 1 if debit_type in ('asset', 'expense') else -1
        vals['postdate'] = parse_date(vals['postdate'])

        tx = ledger.Transaction(id=None, **vals)
        tx.save()

        flows.fulfill(tx)

        cherrypy.response.status = 201
        cherrypy.response.headers['Location'] = cherrypy.url("%s" % tx.id)

    def _cp_dispatch(self, vpath):
        segment = vpath.pop(0)
        try:
            cherrypy.serving.request.txid = int(segment)
        except ValueError:
            raise cherrypy.NotFound()
        return Transaction()


class Import(object):
    
    exposed = True

    def GET(self):
        page = open(os.path.join(uidir, "import.html"), "rb").read()
        return page % {'body': '<p>Please select a Mint CSV file to import</p>'}

    def POST(self, csvfile):
        """Process the given CSV file."""
        mi = csvutil.ErrorGatheringMintImporter()
        mi.load_mint_csv(csvfile.file)

        page = open(os.path.join(uidir, "import.html"), "rb").read()
        errors = ["<tr><td>Unknown account name: %s</td>"
                      "<td>Description: %s</td></tr>" %
                  (e.account_name, e.tx['Description'])
                  for e in mi.errors]
        if errors:
            body = ('<p>Errors encountered:</p>\n'
                    '<table id="errors">\n' + "\n".join(errors) + '</table>')
        else:
            body = '<p>Import successful!</p>'
        return page % {'body': body}


class Budgets(object):

    exposed = True
    description = "A table of account budgets."

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self, accounts='', years='', months='', days='', dategroup='month',
            **kwargs):
        """Return a table of budgets."""
        b = {
            "self": cherrypy.url(qs=cherrypy.request.query_string),
            "description": self.description % vars(),
            "views": {"filtered": "{?accounts+,years+,months+,days+.dategroup}"},
            }

        accounts = toInts(accounts)
        years = toInts(years)
        months = toInts(months)
        days = toInts(days)

        if not (accounts or years or months or days):
            # No filters. Return nothing rather than everything.
            return b

        # Determine the full range of buckets; even if our ledger has no
        # transactions within a given bucket, we still want to output it.
        if not years:
            years = [tx['postdate'].year
                     for tx in ledger.transactions.itervalues()]
            if not years:
                years = [datetime.date.today().year]
        if not months:
            months = range(1, 13)

        if dategroup == 'year':
            coerce_date = cmpdates.strkeys['years']
            dategroups = [str(y) for y in years]
        elif dategroup == 'day':
            coerce_date = cmpdates.strkeys['days']
            dategroups = []
            for y in years:
                for m in months:
                    for d in days or xrange(1, calendar.monthrange(y, m)[1] + 1):
                        dategroups.append('%04d-%02d-%02d' % (y, m, d))
        else:
            # dategroup == 'month' or other
            coerce_date = cmpdates.strkeys['months']
            dategroups = ['%04d-%02d' % (y, m) for y in years for m in months]

        # Calculate the budget of each requested account for each
        # dategroup in the output.
        budgets = dict((a, dict((dg, [0, 0]) for dg in dategroups))
                       for a in accounts)

        for tx in ledger.transactions.itervalues():
            txdate = coerce_date(tx['postdate'])
            if txdate not in dategroups:
                continue

            if (not accounts) or tx['credit'] in accounts:
                credit_amount = tx['amount'] * tx['credit_mult']
                budgets[tx['credit']][txdate][1] += credit_amount

            if (not accounts) or tx['debit'] in accounts:
                debit_amount = tx['amount'] * tx['debit_mult']
                budgets[tx['debit']][txdate][1] += debit_amount

        for flowid, flow in flows.flows.iteritems():
            credit = (not accounts) or flow['credit'] in accounts
            debit = (not accounts) or flow['debit'] in accounts
            if not (credit or debit):
                continue

            if credit:
                credit_bucket = budgets[flow['credit']]
            if debit:
                debit_bucket = budgets[flow['debit']]

            for ob in flow.obligations:
                obdate = coerce_date(ob['postdate'])
                if obdate not in dategroups:
                    continue

                if credit:
                    credit_bucket[obdate][0] += ob['amount'] * ob['credit_mult']

                if debit:
                    debit_bucket[obdate][0] += ob['amount'] * ob['debit_mult']


        # Touch up the data for JSON, which doesn't allow non-string keys
        b['data'] = dict(
            (str(accountid), bucket)
            for accountid, bucket in budgets.iteritems()
            )

        return b


class Flow(object):

    exposed = True
    description = (
"""A Flowrate Flow. PUT a Flow representation to replace it
(but note that the server will ignore any members other than those
in the 'body' object). GET to return it. DELETE to destroy it.""")
    
    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self):
        """Return the flow."""
        req = cherrypy.serving.request

        try:
            flow = flows.flows[req.flowid]
        except KeyError:
            raise cherrypy.NotFound()

        return {'self': cherrypy.url(),
                'description': self.description % vars(),
                'body': {
                    'credit': cherrypy.url("/accounts/%s" % flow['credit']),
                    'debit': cherrypy.url("/accounts/%s" % flow['debit']),
                    'amount': flow['amount'],
                    'start': flow['start'],
                    'end': flow['end'],
                    'period': flow['period'],
                    'unit': flow['unit'],
                    'days': flow['days'],
                    'description': flow['description'],
                    },
                }

    @cherrypy.tools.json_in(processor=json_processor)
    @cherrypy.tools.last_content_type()
    def PUT(self):
        """Update the given flow entity."""
        req = cherrypy.serving.request

        try:
            flow = flows.flows[req.flowid]
        except KeyError:
            raise cherrypy.NotFound()

        if "body" not in req.json:
            raise cherrypy.HTTPError("400 No Body",
                "Flows MUST include a 'body' member.")

        # Accept the new flow definition.
        vals = req.json["body"]
        vals['credit'] = popint(vals['credit'])
        vals['debit'] = popint(vals['debit'])
        flow.row.update(vals)

        flow.save()
        flow.clear_obligations()
        flow.obligate()

        cherrypy.response.status = 204

    def DELETE(self):
        """Destroy the definition of this flow."""
        req = cherrypy.serving.request

        flow = flows.flows[req.flowid]
        flow.clear_obligations()
        flow.delete()
        cherrypy.response.status = 204

flowsmanager = cherrypy.tools.staticfile.handler(
    filename=os.path.join(uidir, "flows.html"))
flowsmanager.GET = flowsmanager


class Flows(object):
    
    exposed = True
    description = (
"""A catalog of available flows. POST a Flow representation
to self to define a new flow.

Set the unit field to 'months' to declare that the flow repeats every month.
For example, if a flow repeats on the 3rd of each month, set days to 3 and
unit to 'months'. If a flow repeats on February 14th of each year, set days
to 14, and unit to 'months'.

The start and end dates are inclusive.

The credit, debit, amount, and description fields will be used
to populate dummy future items when you GET /transactions
""")

    manager = flowsmanager

    def __init__(self):
        # This triggers tools.trailing_slash to force a redirect if missing
        self.index = self

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self, accounts='', credits='', debits='',
            years='', months='', days='', description='',
            # This querystring arg doesn't actually do anything; it's here
            # just to make constructing URI's to various resources easy
            # by sharing the full querystring.
            dategroup=''):
        """Return a catalog of flows."""
        t = {
            "self": cherrypy.url(qs=cherrypy.request.query_string),
            "description": self.description % vars(),
            "manager": cherrypy.url('/transactions/manager', qs=cherrypy.request.query_string),
            "views": {"filtered": "{?accounts+,credits+,debits+,years+,months+,days+,description}"},
            "example": {"body": {"amount": "1000.34",
                                 "credit": "/accounts/3011",
                                 "debit": "/accounts/1021",
                                 "start": "2011-11-01",
                                 "end": "2012-03-01",
                                 "period": "1",
                                 "unit": "months", "days": [15],
                                 "description": "Rent",
                                 }},
            }

        fs = filters(accts=toInts(accounts), credits=toInts(credits),
                     debits=toInts(debits),
                     # TODO: try to filter by years/months/days?
                     years=None, months=None, days=None,
                     description=description)

        flowobs = [flow for flow in flows.flows.itervalues()
                   if all(f(flow) for f in fs)]
        t['data'] = [
            {"id": cherrypy.url("/flows/%s" % flow.id),
             "start": flow['start'],
             "end": flow['end'],
             "period": flow['period'],
             "unit": flow['unit'],
             "days": flow['days'],
             "amount": flow['amount'],
             "credit": cherrypy.url("/accounts/%s" % flow['credit']),
             "debit": cherrypy.url("/accounts/%s" % flow['debit']),
             "description": flow['description'],
             } for flow in ordered(flowobs, 'debit', 'credit', '-start')]

        return t

    @cherrypy.tools.json_in(processor=json_processor)
    @cherrypy.tools.last_content_type()
    def POST(self):
        """Insert the given flow entity."""
        req = cherrypy.serving.request
        if "body" not in req.json:
            raise cherrypy.HTTPError("400 No Body",
                "Flows MUST include a 'body' member.")
    
        # Accept the new flow definition.
        vals = req.json["body"]
        vals["credit"] = popint(vals.pop("credit"))
        vals["debit"] = popint(vals.pop("debit"))
        flow = flows.Flow(None, **vals)
        flow.save()
        flow.obligate()

        cherrypy.response.status = 201
        cherrypy.response.headers['Location'] = cherrypy.url("%s" % flow.id)

    def _cp_dispatch(self, vpath):
        cherrypy.serving.request.flowid = int(vpath.pop(0))
        return Flow()


class Variable(object):
    
    exposed = True
    description = (
"""A Flowrate Variable. PUT a Variable representation to replace it
(but note that the server will ignore any members other than those
in the 'body' object). GET to return it. DELETE to destroy it.""")

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self):
        """Return the variable."""
        req = cherrypy.serving.request

        try:
            var = env.variables[req.varname]
        except KeyError:
            raise cherrypy.NotFound()

        return {'self': cherrypy.url(),
                'description': self.description % vars(),
                'body': {
                    'source': var.source,
                    'references': list(var.references),
                    },
                }

    @cherrypy.tools.json_in(processor=json_processor)
    @cherrypy.tools.last_content_type()
    def PUT(self):
        """Update the given variable entity."""
        req = cherrypy.serving.request
        name = req.varname

        if "body" not in req.json:
            raise cherrypy.HTTPError("400 No Body",
                "Variables MUST include a 'body' member.")

        # Accept the new variable definition.
        vals = req.json["body"]
        exists = name in env.variables
        env.bind(name, vals['source'])

        # Calculate this variable and all its dependents.
        dependents = set(env.calc(name))
        dependents.add(name)

        # Recalc any flows which depend on these variables.
        for flow in flows.flows.itervalues():
            if set(flow['variables']).intersection(dependents):
                flow.clear_obligations()
                flow.obligate()

        if exists:
            db.execute("UPDATE variables SET source = %s WHERE name = %s;",
                       (vals['source'], name))
            cherrypy.response.status = 204
        else:
            db.execute("INSERT INTO variables (name, source) VALUES (%s, %s);",
                       (name, vals['source']))
            cherrypy.response.headers['Location'] = cherrypy.url()
            cherrypy.response.status = 201


varsmanager = cherrypy.tools.staticfile.handler(
    filename=os.path.join(uidir, "variables.html"))
varsmanager.GET = varsmanager


class Variables(object):
    
    exposed = True
    description = """A catalog of available variables."""

    manager = varsmanager

    def __init__(self):
        # This triggers tools.trailing_slash to force a redirect if missing
        self.index = self

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self):
        """Return a catalog of variables."""
        t = {
            "self": cherrypy.url(qs=cherrypy.request.query_string),
            "manager": cherrypy.url('/variables/manager',
                                    qs=cherrypy.request.query_string),
            "description": self.description % vars(),
            }
        t['data'] = [
            {"link": cherrypy.url("/variables/%s" % k),
             "name": k,
             "source": v.source,
             } for k, v in env.variables.iteritems()]

        return t

    def _cp_dispatch(self, vpath):
        cherrypy.serving.request.varname = vpath.pop(0)
        return Variable()


class Balances(object):

    exposed = True
    description = "A table of account balances."

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self, accounts='', years='', months='', days='', dategroup='month'):
        """Return a table of balances."""
        b = {
            "self": cherrypy.url(qs=cherrypy.request.query_string),
            "description": self.description % vars(),
            "views": {"filtered": "{?accounts+,years+,months+,dategroup}"},
            }

        assets = [id for id, acct in ledger.accounts.iteritems()
                  if acct['type'] == 'asset']
        accounts = toInts(accounts)
        if accounts:
            accounts = [x for x in accounts if x in assets]
        else:
            accounts = assets
        years = toInts(years)
        months = toInts(months)
        days = toInts(days)

        if not (accounts or years or months or days):
            # No filters. Return nothing rather than everything.
            return b

        # Determine the full range of buckets; even if our ledger has no
        # transactions within a given bucket, we still want to output it.
        if not years:
            years = [tx['postdate'].year
                     for tx in ledger.transactions.itervalues()]
            if not years:
                years = [datetime.date.today().year]
        if not months:
            months = range(1, 13)

        if dategroup == 'year':
            coerce_date = cmpdates.units['years']
            balance_dates = [datetime.date(y, 12, 31) for y in years]
            dategroups = [str(y) for y in years]
        elif dategroup == 'day':
            coerce_date = cmpdates.units['days']
            balance_dates = []
            for y in years:
                for m in months:
                    for d in days or xrange(1, calendar.monthrange(y, m)[1] + 1):
                        balance_dates.append(datetime.date(y, m, d))
            dategroups = [d.isoformat() for d in balance_dates]
        else:
            # dategroup == 'month' or other
            coerce_date = cmpdates.units['months']
            balance_dates = [datetime.date(y, m, calendar.monthrange(y, m)[1])
                             for y in years for m in months]
            dategroups = ['%04d-%02d' % (y, m) for y in years for m in months]

        # Calculate the balance of each requested account for each
        # dategroup in the output.
        balances = dict((a, dict((dg, 0) for dg in dategroups))
                       for a in accounts)

        dates_and_groups = zip(balance_dates, dategroups)

        # Grab ledger entries from transactions
        for tx in ledger.transactions.itervalues():
            if (not accounts) or (tx['credit'] in accounts):
                credit_amount = tx['amount'] * tx['credit_mult']
                credit_bucket = balances[tx['credit']]
            else:
                credit_amount = None

            if (not accounts) or (tx['debit'] in accounts):
                debit_amount = tx['amount'] * tx['debit_mult']
                debit_bucket = balances[tx['debit']]
            else:
                debit_amount = None

            if credit_amount is None and debit_amount is None:
                # This transaction doesn't bear on the selected accounts.
                continue

            for bd, dg in dates_and_groups:
                if tx["postdate"] <= bd:
                    if credit_amount is not None:
                        credit_bucket[dg] += credit_amount
                    if debit_amount is not None:
                        debit_bucket[dg] += debit_amount

        # Grab obligations between 30 days ago and the balance date
        age = datetime.date.today() - datetime.timedelta(days=30)
        for flow in flows.flows.itervalues():
            if (not accounts) or (flow['credit'] in accounts):
                credit_bucket = balances[flow['credit']]
            else:
                credit_bucket = None

            if (not accounts) or (flow['debit'] in accounts):
                debit_bucket = balances[flow['debit']]
            else:
                debit_bucket = None

            if credit_bucket is None and debit_bucket is None:
                # This obligation doesn't bear on the selected accounts.
                continue

            for ob in flow.obligations:
                if ob['postdate'] < age:
                    continue

                credit_amount = ob['remaining'] * ob['credit_mult']
                debit_amount = ob['remaining'] * ob['debit_mult']

                for bd, dg in dates_and_groups:
                    if ob["postdate"] <= bd:
                        if credit_bucket is not None:
                            credit_bucket[dg] += credit_amount

                        if debit_bucket is not None:
                            debit_bucket[dg] += debit_amount

        # Touch up the data for JSON, which doesn't allow non-string keys
        b['data'] = dict(
            (str(accountid), bucket)
            for accountid, bucket in balances.iteritems()
            )

        return b


class Account(object):
    
    exposed = True
    description = (
"""A Flowrate account. PUT a account representation to replace
it (but note that the server will ignore any members other than those
in the 'body' object). Performing a DELETE on this resource will
delete all its transactions! Use with care!""")

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self):
        """Return information about the account."""
        req = cherrypy.serving.request
        
        # Return the definition for this account.
        # Look up the name in our config DB.
        try:
            acct = ledger.accounts[req.account]
        except KeyError:
            raise cherrypy.NotFound()
        
        return {
            "self": cherrypy.url(),
            "description": self.description % vars(),
            "views": {"balances": "/balances?account=%s" % acct.id},
            "body": {
                "name": acct['name'],
                "type": acct['type'],
                },
            }
    
    @cherrypy.tools.json_in(processor=json_processor)
    @cherrypy.tools.last_content_type()
    def PUT(self):
        """Accept (upsert) the given account entity."""
        req = cherrypy.serving.request
        if "body" not in req.json:
            raise cherrypy.HTTPError("400 No Body",
                "Accounts MUST include a 'body' member.")
        
        # Accept the new account definition.
        # Look up the name in our config DB.
        vals = req.json["body"]
        try:
            acct = ledger.accounts[req.account]
        except KeyError:
            acct = ledger.Account(
                id=req.account, name=vals['name'], type=vals['type'])
            acct.create()
            cherrypy.response.status = 201
            cherrypy.response.headers['Location'] = cherrypy.url()
        else:
            acct['name'] = vals["name"]
            acct['vals'] = vals["type"]
            acct.update()
            cherrypy.response.status = 204

    def DELETE(self):
        req = cherrypy.serving.request
        # TODO: require ?force=true if any flows or transactions exist
        try:
            acct = ledger.accounts[req.account]
        except KeyError:
            raise cherrypy.NotFound()
        acct.delete()
        cherrypy.response.status = 204

account = Account()


acctmanager = cherrypy.tools.staticfile.handler(
    filename=os.path.join(uidir, "accounts.html"))
acctmanager.GET = acctmanager

class Accounts(object):
    
    exposed = True
    description = (
"""A catalog of accounts. PUT an account representation to
self/{account}/ to define a new account. GET it to read the definition.""")

    manager = acctmanager

    def __init__(self):
        # This triggers tools.trailing_slash to force a redirect if missing
        self.index = self

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self):
        return {
            "self": cherrypy.url(),
            "description": self.description % vars(),
            "manager": cherrypy.url('/accounts/manager'),
            "example": {"body": {"name": "Gas & Electric", "type": "asset"}},
            "data": [{"id": cherrypy.url("/accounts/%s" % id),
                      "name": acct['name'],
                      "type": acct['type'],
                      }
                     for id, acct in sorted(ledger.accounts.items())],
            }
    
    def _cp_dispatch(self, vpath):
        cherrypy.request.account = int(vpath.pop(0))
        return account


json2_js = cherrypy.tools.staticfile.handler(
    filename=os.path.join(uidir, "json2.js"))
json2_js.GET = json2_js

common_js = cherrypy.tools.staticfile.handler(
    filename=os.path.join(uidir, "common.js"))
common_js.GET = common_js

class Root(object):
    
    exposed = True

    accounts = Accounts()
    balances = Balances()
    budgets = Budgets()
    flows = Flows()
    variables = Variables()
    transactions = Transactions()
    json2_js = json2_js
    common_js = common_js

    def __init__(self):
        # This triggers tools.trailing_slash to force a redirect if missing
        self.index = self

    @cherrypy.tools.json_out(handler=json_handler)
    def GET(self):
        return {
            "self": cherrypy.url(),
            "description": __doc__,
            "okapi": cherrypy.url("okapi/okapi.html"),
            "prettier JSON for your browser": {
                "Chrome": "https://chrome.google.com/extensions/detail/chklaanhfefbnpoihckbnefhakgolnmc",
                "Firefox": "https://addons.mozilla.org/en-us/firefox/addon/jsonview/",
                "IE": "http://stackoverflow.com/questions/2483771/",
                },
            "catalogs": {
                "accounts": cherrypy.url("accounts"),
                "flows": cherrypy.url("flows"),
                "transactions": cherrypy.url("transactions"),
                },
            }


root = Root()
setattr(root, 'import', Import())
root.cpstats = cpstats.StatsPage()