flowrate / flowrate / __init__.py

  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
"""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
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

db = None

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


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))
                    else:
                        i.append(int(r[0].strip()))
    return list(set(i))


def transactions(accounts=None, credits=None, debits=None,
                 years=None, months=None, days=None, description=None):
    """Return Transaction objects (dicts) matching the given criteria."""
    whereclause, args = [], {}
    if accounts:
        whereclause.append("(ARRAY[credit_account] <@ %(accounts)s"
                           " OR ARRAY[debit_account] <@ %(accounts)s)")

        # Grab all subaccounts of the given accounts.
        all_accts = [row.id for row in db.execute(
                     "SELECT id FROM accounts;").fetchall()]
        def isSubAccount(child, parents):
            for p in parents:
                for scale in (1000, 100, 10, 1):
                    if p % scale == 0 and p <= child < (p + scale):
                        return True
            return False
        accounts = [a for a in all_accts if isSubAccount(a, accounts)]

        args['accounts'] = accounts
    if credits:
        whereclause.append("ARRAY[credit_account] <@ %(credits)s")
        args['credits'] = credits
    if debits:
        whereclause.append("ARRAY[debit_account] <@ %(debits)s")
        args['debits'] = debits
    if description:
        whereclause.append("description ILIKE %(desc)s")
        args['desc'] = '%' + description + '%';
    if years:
        whereclause.append("ARRAY[EXTRACT(year FROM postdate)::integer] <@ %(years)s")
        args['years'] = years
    if months:
        whereclause.append("ARRAY[EXTRACT(month FROM postdate)::integer] <@ %(months)s")
        args['months'] = months
    if days:
        whereclause.append("ARRAY[EXTRACT(day FROM postdate)::integer] <@ %(days)s")
        args['days'] = days

    if not whereclause:
        # If there are no filters, return nothing instead of everything
        return

    # Yield all real transactions
    whereclause = " AND ".join(whereclause)
    sql = ("SELECT * FROM transactions WHERE " + whereclause +
           " ORDER BY postdate DESC, credit_account, debit_account;")
    rows = db.execute(sql, args).fetchall()
    for row in rows:
        yield {"id": row.id, "postdate": row.postdate,
               "amount": row.amount,
               "credit": row.credit_account, "debit": row.debit_account,
               "description": row.description,
               }


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

        row = db.execute(
            "SELECT * FROM transactions WHERE id = %s;", (req.txid,)).fetchone()
        if row is None:
            raise cherrypy.NotFound()

        return {
            'self': cherrypy.url(),
            'description': self.description % vars(),
            'body': {
                'amount': row['amount'],
                'credit': cherrypy.url("/accounts/%s" % row['credit_account']),
                'debit': cherrypy.url("/accounts/%s" % row['debit_account']),
                'postdate': row['postdate'].isoformat(),
                'description': row['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

        row = db.execute(
            "SELECT * FROM transactions WHERE id = %s;", (req.txid,)).fetchone()
        if row is None:
            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"]
        credit, debit = popint(vals['credit']), popint(vals['debit'])
        credit_type = db.execute(
            "SELECT type FROM accounts WHERE id = %s", (credit,)).fetchone()
        debit_type = db.execute(
            "SELECT type FROM accounts WHERE id = %s", (debit,)).fetchone()
        amount = vals['amount']
        txrow = db.execute(
            "UPDATE transactions SET amount = %s, "
            "credit_account = %s, debit_account = %s, postdate = %s, "
            "description = %s, credit_mult = %s, debit_mult = %s "
            "WHERE id = %s RETURNING *;",
            (amount, credit, debit,
             vals['postdate'], vals['description'],
             -1 if credit_type['type'] in ('asset', 'expense') else 1,
             1 if debit_type['type'] in ('asset', 'expense') else -1,
             req.txid)).fetchone()

        flows.unfulfill(txrow.id)
        flows.fulfill(txrow)

        cherrypy.response.status = 204

    def DELETE(self):
        """Destroy the definition of this transaction."""
        req = cherrypy.serving.request
        flows.unfulfill(req.txid)
        db.execute("DELETE FROM transactions WHERE id = %s;", (req.txid,))
        cherrypy.response.status = 204


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


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)

        realdata = transactions(accounts, credits, debits,
                                years, months, days, description)
        flowdata = flows.transactions(accounts, credits, debits,
                                      years, months, days, description)
        for tx in heapq.merge(realdata, flowdata):
            if tx.get('id', None):
                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"]
        credit, debit = popint(vals['credit']), popint(vals['debit'])
        credit_type = db.execute(
            "SELECT type FROM accounts WHERE id = %s", (credit,)).fetchone()
        debit_type = db.execute(
            "SELECT type FROM accounts WHERE id = %s", (debit,)).fetchone()
        amount = vals['amount']
        newrow = db.execute(
            "INSERT INTO transactions"
            " (amount, credit_account, debit_account, postdate, description, "
            "credit_mult, debit_mult) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING *",
            (amount, credit, debit,
             vals["postdate"], vals['description'],
             -1 if credit_type['type'] in ('asset', 'expense') else 1,
             1 if debit_type['type'] in ('asset', 'expense') else -1,
             )).fetchone()

        flows.fulfill(newrow)

        cherrypy.response.status = 201
        cherrypy.response.headers['Location'] = cherrypy.url("%s" % newrow.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 = [row.year for row in db.execute(
                "SELECT DISTINCT EXTRACT(year FROM postdate) AS year "
                "FROM transactions;").fetchall()]
            if not years:
                years = [datetime.date.today().year]
        if not months:
            months = range(1, 13)

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

        # 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)
        whereclause, args = [], {}
        if accounts:
            whereclause.append("ARRAY[account] <@ %(accounts)s")
            args['accounts'] = accounts
        for dg in dategroups:
            wc = whereclause + [
                "to_char(postdate, %(df)s) = %(dg)s"]
            args['df'] = pgdatefmt
            args['dg'] = dg
            sql = ("SELECT account, SUM(total) AS budget "
                   "FROM flowledger WHERE " +  " AND ".join(wc) +
                   " GROUP BY 1 ORDER BY 1;")
            for row in db.execute(sql, args).fetchall():
                budgets[row.account][dg][0] = row.budget
            sql = ("SELECT account, SUM(amount) AS spent "
                   "FROM ledger WHERE " +  " AND ".join(wc) +
                   " GROUP BY 1 ORDER BY 1;")
            for row in db.execute(sql, args).fetchall():
                budgets[row.account][dg][1] = row.spent

        b['data'] = budgets

        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

        flow = flows.Flow(req.flowid)
        flow.find()
        if flow.row is None:
            raise cherrypy.NotFound()

        return {'self': cherrypy.url(),
                'description': self.description % vars(),
                'body': {
                    'credit': cherrypy.url("/accounts/%s" % flow.credit_account),
                    'debit': cherrypy.url("/accounts/%s" % flow.debit_account),
                    'amount': flow.amount,
                    'start': flow.range_start,
                    'end': flow.range_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

        flow = flows.Flow(req.flowid)
        flow.find()
        if flow.row is None:
            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"]
        credit, debit = popint(vals['credit']), popint(vals['debit'])

        refs = set()
        finder = ReferenceFinder()
        for key in ('start', 'end', 'amount'):
            val = vals[key].strip()
            if val.startswith("="):
                newrefs = finder.find(val[1:])
                refs.update(newrefs)

        flow.row = db.execute(
            "UPDATE flows SET amount = %s, "
            "credit_account = %s, debit_account = %s, "
            "range_start = %s, range_end = %s, "
            "period = %s, unit = %s, days = %s, "
            "description = %s, variables = %s "
            "WHERE id = %s RETURNING *;",
            (vals['amount'], credit, debit, vals['start'], vals['end'],
            vals['period'], vals['unit'], vals['days'], vals['description'],
            list(refs), flow.id)).fetchone()

        flow.clear_obligations()
        flow.obligate()

        cherrypy.response.status = 204

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

        f = flows.Flow(req.flowid)
        f.clear_obligations()
        f.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",
                                 }},
            }

        whereclause, args = [], {}
        if accounts:
            whereclause.append("(ARRAY[credit_account] <@ %(accounts)s"
                               " OR ARRAY[debit_account] <@ %(accounts)s)")
            args['accounts'] = toInts(accounts)
        if credits:
            whereclause.append("ARRAY[credit_account] <@ %(credit)s")
            args['credits'] = toInts(credits)
        if debits:
            whereclause.append("ARRAY[debit_account] <@ %(debits)s")
            args['debits'] = toInts(debits)
        if description:
            whereclause.append("description ILIKE %(desc)s")
            args['desc'] = '%' + description + '%';

        # TODO: try to filter by years/months/days?

        sql = "SELECT * FROM flows"
        if whereclause:
            sql += " WHERE " + " AND ".join(whereclause)
        sql += " ORDER BY debit_account, credit_account, range_start DESC;"
        rows = db.execute(sql, args).fetchall()
        t['data'] = [
            {"id": cherrypy.url("/flows/%s" % row.id),
             "start": row.range_start,
             "end": row.range_end,
             "period": row.period,
             "unit": row.unit,
             "days": row.days,
             "amount": row.amount,
             "credit": cherrypy.url("/accounts/%s" % row.credit_account),
             "debit": cherrypy.url("/accounts/%s" % row.debit_account),
             "description": row.description,
             } for row in rows]

        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["credit"])
        vals["debit"] = popint(vals["debit"])
        flow = flows.Flow.insert(**vals)
        flow.obligate()

        cherrypy.response.status = 201
        cherrypy.response.headers['Location'] = cherrypy.url("%s" % flow.row.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 = list(env.calc(name))
        dependents.append(name)

        # Recalc any flows which depend on these variables.
        for row in db.execute(
                "SELECT * FROM flows WHERE variables && %(names)s;",
                {"names": dependents or '{}'}).fetchall():
            flow = flows.Flow(row.id, row)
            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


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

    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),
            "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 = [row.id for row in db.execute(
                  "SELECT id FROM accounts WHERE type = 'asset';").fetchall()]
        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 = [row.year for row in db.execute(
                "SELECT DISTINCT EXTRACT(year FROM postdate) AS year "
                "FROM transactions;").fetchall()]
            if not years:
                years = [datetime.date.today().year]
        if not months:
            months = range(1, 13)

        if dategroup == 'year':
            balance_dates = [datetime.date(y, 12, 31) for y in years]
            dategroups = [str(y) for y in years]
        elif dategroup == 'day':
            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
            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)
        whereclause, args = [], {}
        if accounts:
            whereclause.append("ARRAY[account] <@ %(accounts)s")
            args['accounts'] = accounts
        for bd, dg in zip(balance_dates, dategroups):
            # Grab ledger from transactions and obligations together
            wc = whereclause + ["postdate <= %(balance_date)s"]
            args['balance_date'] = bd
            sql = ("SELECT account, SUM(amount) AS balance "
                   "FROM fullledger WHERE " +  " AND ".join(wc) +
                   " GROUP BY 1;")
            for row in db.execute(sql, args).fetchall():
                balances[row.account][dg] = row.balance

        b['data'] = balances

        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.
        row = db.execute(
            "SELECT * FROM accounts WHERE id = %s;", (req.account,)).fetchone()
        if row is None:
            raise cherrypy.NotFound()
        
        return {
            "self": cherrypy.url(),
            "description": self.description % vars(),
            "views": {"balances": "/balances?account=%s" % req.account},
            "body": {
                "name": row.name,
                "type": row.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.
        row = db.execute("SELECT * FROM accounts WHERE id = %s;",
                         (req.account,)).fetchone()
        vals = req.json["body"]
        if row is None:
            db.execute("INSERT INTO accounts (id, name, type) "
                       "VALUES (%s, %s, %s)",
                       (req.account, vals["name"], vals["type"]))
            cherrypy.response.headers['Location'] = cherrypy.url()
        else:
            db.execute("UPDATE accounts SET name = %s, type = %s "
                       "WHERE id = %s;",
                       (vals["name"], vals["type"], req.account))
        cherrypy.response.status = 201 if row is None else 204

    def DELETE(self):
        req = cherrypy.serving.request
        # TODO: require ?force=true if any flows or transactions exist
        db.execute("DELETE FROM accounts WHERE id = %s;", (req.account,))
        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):
        rows = db.execute(
            "SELECT id, name, type FROM accounts ORDER BY id;").fetchall()
        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" % row.id),
                      "name": row.name,
                      "type": row.type,
                      }
                     for row in rows],
            }
    
    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()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.