Completed
Push — master ( c56c12...56a8bb )
by
unknown
59s
created

chezbetty.models.EmptySafe.__init__()   A

Complexity

Conditions 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 4
rs 10
1
from .model import *
2
from . import account
3
from . import event
4
from . import item
5
from . import box
6
from . import user
7
from chezbetty import utility
8
9
import arrow
10
from pyramid.threadlocal import get_current_registry
11
12
13
class Transaction(Base):
14
    __tablename__ = 'transactions'
15
16
    id                 = Column(Integer, primary_key=True, nullable=False)
17
18
    event_id           = Column(Integer, ForeignKey("events.id"))
19
20
    to_account_virt_id = Column(Integer, ForeignKey("accounts.id"))
21
    fr_account_virt_id = Column(Integer, ForeignKey("accounts.id"))
22
    to_account_cash_id = Column(Integer, ForeignKey("accounts.id"))
23
    fr_account_cash_id = Column(Integer, ForeignKey("accounts.id"))
24
    amount             = Column(Numeric, nullable=False)
25
26
                                        # Virtual Transaction Meaning     # Cash Transaction Meaning  # Notes required?
27
    type = Column(Enum("purchase",      # user_account -> chezbetty.        None
28
                       "deposit",
29
                       "cashdeposit",   # null         -> user_account.     null      -> cashbox.
30
                       "ccdeposit",     # null         -> user_account.     null      -> chezbetty
31
                       "btcdeposit",    # null         -> user_account      null      -> btcbox
32
                       "adjustment",    # chezbetty   <-> user              None                            Yes
33
                       "restock",       # chezbetty    -> null              chezbetty -> null
34
                       "inventory",     # chezbetty   <-> null              None
35
                       "emptycashbox",  # None                              cashbox   -> safe
36
                       "emptysafe",     # None                              safe      -> chezbetty
37
                       "emptybitcoin",  # None                              btcbox    -> chezbetty
38
                       "lost",          # None                              chezbetty/cashbox/btcbox -> null       Yes
39
                       "found",         # None                              null      -> chezbetty/cashbox/btcbox  Yes
40
                       "donation",      # null         -> chezbetty         null      -> chezbetty          Yes
41
                       "withdrawal",    # chezbetty    -> null              chezbetty -> null               Yes
42
                       name="transaction_type"), nullable=False)
43
    __mapper_args__ = {'polymorphic_on': type}
44
45
46
    to_account_virt = relationship(account.Account,
47
        foreign_keys=[to_account_virt_id,],
48
        backref="transactions_to_virt"
49
    )
50
    fr_account_virt = relationship(account.Account,
51
        foreign_keys=[fr_account_virt_id,],
52
        backref="transactions_from_virt"
53
    )
54
55
    to_account_cash = relationship(account.Account,
56
        foreign_keys=[to_account_cash_id,],
57
        backref="transactions_to_cash"
58
    )
59
    fr_account_cash = relationship(account.Account,
60
        foreign_keys=[fr_account_cash_id,],
61
        backref="transactions_from_cash"
62
    )
63
    event = relationship(event.Event,
64
        foreign_keys=[event_id,],
65
        backref="transactions"
66
    )
67
68
69
    def __init__(self, event, fr_acct_virt, to_acct_virt, fr_acct_cash, to_acct_cash, amount):
70
        self.to_account_virt_id = to_acct_virt.id if to_acct_virt else None
71
        self.fr_account_virt_id = fr_acct_virt.id if fr_acct_virt else None
72
        self.to_account_cash_id = to_acct_cash.id if to_acct_cash else None
73
        self.fr_account_cash_id = fr_acct_cash.id if fr_acct_cash else None
74
75
        self.to_acct_virt = to_acct_virt
76
        self.fr_acct_virt = fr_acct_virt
77
        self.to_acct_cash = to_acct_cash
78
        self.fr_acct_cash = fr_acct_cash
79
80
        self.event_id = event.id
81
        self.amount = amount
82
83
        # Update the balances of the accounts we are moving money between
84
        if to_acct_virt:
85
            to_acct_virt.balance += self.amount
86
        if fr_acct_virt:
87
            fr_acct_virt.balance -= self.amount
88
89
        if to_acct_cash:
90
            to_acct_cash.balance += self.amount
91
        if fr_acct_cash:
92
            fr_acct_cash.balance -= self.amount
93
94
    def update_amount(self, amount):
95
        # Remove the balance we added before (upon init or last update_amount)
96
        if self.to_acct_virt:
97
            self.to_acct_virt.balance -= self.amount
98
        if self.fr_acct_virt:
99
            self.fr_acct_virt.balance += self.amount
100
        if self.to_acct_cash:
101
            self.to_acct_cash.balance -= self.amount
102
        if self.fr_acct_cash:
103
            self.fr_acct_cash.balance += self.amount
104
105
        # Save the amount so we can subtract it later if needed
106
        self.amount = amount
107
108
        # Apply the new amount
109
        if self.to_acct_virt:
110
            self.to_acct_virt.balance += self.amount
111
        if self.fr_acct_virt:
112
            self.fr_acct_virt.balance -= self.amount
113
        if self.to_acct_cash:
114
            self.to_acct_cash.balance += self.amount
115
        if self.fr_acct_cash:
116
            self.fr_acct_cash.balance -= self.amount
117
118
    @classmethod
119
    def from_id(cls, id):
120
        return DBSession.query(cls)\
121
                        .filter(cls.id == id).one()
122
123
    @classmethod
124
    def get_balance(cls, trans_type, account_obj):
125
        return DBSession.query(coalesce(func.sum(cls.amount), 0).label("balance"))\
126
                     .join(event.Event)\
127
                     .filter(or_(cls.fr_account_cash_id==account_obj.id,
128
                                 cls.to_account_cash_id==account_obj.id,
129
                                 cls.fr_account_virt_id==account_obj.id,
130
                                 cls.to_account_virt_id==account_obj.id))\
131
                     .filter(cls.type==trans_type)\
132
                     .filter(event.Event.deleted==False).one()
133
134
    @classmethod
135
    def count(cls, trans_type=None):
136
        if not trans_type:
137
            return DBSession.query(func.count(cls.id).label('c'))\
138
                            .join(event.Event)\
139
                            .filter(event.Event.deleted==False).one().c
140
        else:
141
            return DBSession.query(func.count(cls.id).label('c'))\
142
                            .join(event.Event)\
143
                            .filter(cls.type==trans_type)\
144
                            .filter(event.Event.deleted==False).one().c
145
146
    @classmethod
147
    def total(cls, start=None, end=None):
148
        r = DBSession.query(func.sum(cls.amount).label('a'))\
149
                        .join(event.Event)\
150
                        .filter(event.Event.deleted==False)
151
152
        if start:
153
            r = r.filter(event.Event.timestamp>=start)
154
        if end:
155
            r = r.filter(event.Event.timestamp<end)
156
157
        return r.one().a or Decimal(0.0)
158
159
    # Get the total amount of discounts people have received for keeping
160
    # money in their account
161
    @classmethod
162
    def discounts(cls, start=None, end=None):
163
        r = DBSession.query(func.sum((cls.amount / (1-cls.discount)) - cls.amount).label('d'))\
164
                        .join(event.Event)\
165
                        .filter(cls.discount > 0)\
166
                        .filter(event.Event.deleted==False)
167
168
        if start:
169
            r = r.filter(event.Event.timestamp>=start)
170
        if end:
171
            r = r.filter(event.Event.timestamp<end)
172
173
        return r.one().d or Decimal(0.0)
174
175
    # Get the total amount of fees people have paid for being in debt
176
    @classmethod
177
    def fees(cls, start=None, end=None):
178
        r = DBSession.query(func.sum((cls.amount / (1-cls.discount)) - cls.amount).label('f'))\
179
                        .join(event.Event)\
180
                        .filter(cls.discount < 0)\
181
                        .filter(event.Event.deleted==False)
182
183
        if start:
184
            r = r.filter(event.Event.timestamp>=start)
185
        if end:
186
            r = r.filter(event.Event.timestamp<end)
187
188
        return r.one().f or Decimal(0.0)
189
190
    # Returns an array of tuples where the first item is a millisecond timestamp,
191
    # the next is the total amount of debt, and the next is the total amount
192
    # of stored money for users.
193
    @classmethod
194
    def get_balance_total_daily(cls):
195
        rows = DBSession.query(cls.amount,
196
                               cls.type,
197
                               cls.to_account_virt_id,
198
                               cls.fr_account_virt_id,
199
                               event.Event.timestamp)\
200
                        .join(event.Event)\
201
                        .filter(event.Event.deleted==False)\
202
                        .filter(or_(
203
                                  cls.type=='purchase',
204
                                  cls.type=='cashdeposit',
205
                                  cls.type=='ccdeposit',
206
                                  cls.type=='btcdeposit',
207
                                  cls.type=='adjustment'
208
                                ))\
209
                        .order_by(event.Event.timestamp)\
210
                        .all()
211
        return utility.timeseries_balance_total_daily(rows)
212
213
214
    @classmethod
215
    def get_transactions_over_time_for_user(cls, user):
216
        return DBSession.query(cls.amount,
217
                               cls.type,
218
                               cls.to_account_virt_id,
219
                               cls.fr_account_virt_id,
220
                               event.Event.timestamp)\
221
                        .join(event.Event)\
222
                        .filter(event.Event.deleted==False)\
223
                        .filter(or_(
224
                                  cls.type=='purchase',
225
                                  cls.type=='cashdeposit',
226
                                  cls.type=='ccdeposit',
227
                                  cls.type=='btcdeposit',
228
                                  cls.type=='adjustment'
229
                                ))\
230
                        .filter(or_(
231
                            cls.to_account_virt_id == user.id,
232
                            cls.fr_account_virt_id == user.id,
233
                            ))\
234
                        .order_by(event.Event.timestamp)\
235
                        .all()
236
237
238
    @classmethod
239
    def get_balances_over_time_for_user(cls, user):
240
        rows = cls.get_transactions_over_time_for_user(user)
241
        # We can re-use the global balance calculation code because the query
242
        # filtered it down to only this user, only now the "global" total
243
        # positive values (r[2]) and total debt (r[1]) are just this user's
244
        # balance, so we pull out the right column at each point in time.
245
        rows = utility.timeseries_balance_total_daily(rows)
246
        rows = [(r[0],r[2]/100 if r[1]==0 else -r[1]/100) for r in rows]
247
        return rows
248
249
    @classmethod
250
    def get_days_in_debt_for_user(cls, user):
251
        rows = cls.get_transactions_over_time_for_user(user)
252
        days = utility.get_days_on_shame(user, rows)
253
        return days
254
255
256
def __get_transactions_query(self):
257
    return object_session(self).query(Transaction)\
258
            .join(event.Event)\
259
            .filter(or_(
260
                      or_(
261
                        Transaction.to_account_virt_id == self.id,
262
                        Transaction.fr_account_virt_id == self.id,
263
                        Transaction.to_account_cash_id == self.id,
264
                        Transaction.fr_account_cash_id == self.id),
265
                      and_(
266
                        or_(event.Event.type == "purchase",
267
                            event.Event.type == "deposit"),
268
                        event.Event.user_id == self.id)))\
269
            .filter(event.Event.deleted==False)\
270
            .order_by(desc(event.Event.timestamp))\
271
272
@limitable_all
273
def __get_transactions(self):
274
    return __get_transactions_query(self)
275
276
@property
277
def __transactions(self):
278
    return __get_transactions(self)
279
280
account.Account.get_transactions_query = __get_transactions_query
281
account.Account.get_transactions = __get_transactions
282
account.Account.transactions = __transactions
283
284
# This is in a stupid place due to circular input problems
285
@limitable_all
286
def __get_events(self):
287
    return object_session(self).query(event.Event)\
288
            .join(Transaction)\
289
            .filter(or_(
290
                      or_(
291
                        Transaction.to_account_virt_id == self.id,
292
                        Transaction.fr_account_virt_id == self.id,
293
                        Transaction.to_account_cash_id == self.id,
294
                        Transaction.fr_account_cash_id == self.id),
295
                      and_(
296
                        or_(event.Event.type == "purchase",
297
                            event.Event.type == "deposit"),
298
                        event.Event.user_id == self.id)))\
299
            .filter(event.Event.deleted==False)\
300
            .order_by(desc(event.Event.timestamp))
301
302
@property
303
def __events(self):
304
    return __get_events(self).all()
305
306
account.Account.get_events = __get_events
307
account.Account.events = __events
308
309
# This is in a stupid place due to circular input problems
310
@property
311
def __total_deposit_amount(self):
312
    return object_session(self).query(func.sum(Transaction.amount).label("total"))\
313
            .join(event.Event)\
314
            .filter(and_(
315
                        Transaction.to_account_virt_id == self.id,
316
                        or_(Transaction.type == 'cashdeposit',
317
                            Transaction.type == 'ccdeposit',
318
                            Transaction.type == 'btcdeposit')))\
319
            .filter(event.Event.deleted==False).one().total or Decimal(0.0)
320
account.Account.total_deposits = __total_deposit_amount
321
322
# This is in a stupid place due to circular input problems
323
@property
324
def __total_purchase_amount(self):
325
    return object_session(self).query(func.sum(Transaction.amount).label("total"))\
326
            .join(event.Event)\
327
            .filter(and_(
328
                        Transaction.fr_account_virt_id == self.id,
329
                        Transaction.type == 'purchase'))\
330
            .filter(event.Event.deleted==False).one().total or Decimal(0.0)
331
account.Account.total_purchases = __total_purchase_amount
332
333
# This is in a stupid place due to circular input problems
334
@classmethod
335
@limitable_all
336
def __get_cash_events(cls):
337
    return DBSession.query(event.Event)\
338
            .join(Transaction)\
339
            .filter(or_(
340
                      Transaction.to_account_cash_id == account.get_cash_account("chezbetty").id,
341
                      Transaction.fr_account_cash_id == account.get_cash_account("chezbetty").id))\
342
            .filter(event.Event.deleted==False)\
343
            .order_by(desc(event.Event.timestamp))
344
event.Event.get_cash_events = __get_cash_events
345
346
# This is in a stupid place due to circular input problems
347
@classmethod
348
@limitable_all
349
def __get_restock_events(cls):
350
    return DBSession.query(event.Event)\
351
            .join(Transaction)\
352
            .filter(Transaction.type == 'restock')\
353
            .filter(event.Event.deleted==False)\
354
            .order_by(desc(event.Event.timestamp))
355
event.Event.get_restock_events = __get_restock_events
356
357
# This is in a stupid place due to circular input problems
358
@classmethod
359
@limitable_all
360
def __get_emptycash_events(cls):
361
    return DBSession.query(event.Event)\
362
            .join(Transaction)\
363
            .filter(or_(
364
                      Transaction.type == 'emptycashbox',
365
                      Transaction.type == 'emptysafe',
366
                      Transaction.type == 'emptybitcoin'))\
367
            .filter(event.Event.deleted==False)\
368
            .order_by(desc(event.Event.timestamp))
369
event.Event.get_emptycash_events = __get_emptycash_events
370
371
# This is in a stupid place due to circular input problems
372
@classmethod
373
@limitable_all
374
def __get_deposit_events(cls):
375
    return DBSession.query(event.Event)\
376
            .join(Transaction)\
377
            .filter(or_(
378
                      Transaction.type == 'cashdeposit',
379
                      Transaction.type == 'ccdeposit',
380
                      Transaction.type == 'btcdeposit'))\
381
            .filter(event.Event.deleted==False)\
382
            .order_by(desc(event.Event.timestamp))
383
event.Event.get_deposit_events = __get_deposit_events
384
385
# This is in a stupid place due to circular input problems
386
@property
387
def __days_since_last_purchase(self):
388
    last_purchase = object_session(self).query(event.Event)\
389
            .join(Transaction)\
390
            .filter(Transaction.fr_account_virt_id == self.id)\
391
            .filter(event.Event.type == 'purchase')\
392
            .filter(event.Event.deleted==False)\
393
            .order_by(desc(event.Event.timestamp)).first()
394
395
    if last_purchase:
396
        diff = arrow.now() - last_purchase.timestamp
397
        return diff.days
398
    else:
399
        return None
400
user.User.days_since_last_purchase = __days_since_last_purchase
401
402
# This is in a stupid place due to circular input problems
403
@property
404
def __lifetime_fees(self):
405
    return object_session(self).query(func.sum((Purchase.amount / (1-Purchase.discount)) - Purchase.amount).label("f"))\
406
            .join(event.Event)\
407
            .filter(Purchase.fr_account_virt_id == self.id)\
408
            .filter(Purchase.discount < 0)\
409
            .filter(event.Event.type == 'purchase')\
410
            .filter(event.Event.deleted==False).one().f or Decimal(0.0)
411
user.User.lifetime_fees = __lifetime_fees
412
413
# This is in a stupid place due to circular input problems
414
@property
415
def __lifetime_discounts(self):
416
    return object_session(self).query(func.sum((Purchase.amount / (1-Purchase.discount)) - Purchase.amount).label("f"))\
417
            .join(event.Event)\
418
            .filter(Purchase.fr_account_virt_id == self.id)\
419
            .filter(Purchase.discount > 0)\
420
            .filter(event.Event.type == 'purchase')\
421
            .filter(event.Event.deleted==False).one().f or Decimal(0.0)
422
user.User.lifetime_discounts = __lifetime_discounts
423
424
425
class Purchase(Transaction):
426
    __mapper_args__ = {'polymorphic_identity': 'purchase'}
427
    discount = Column(Numeric)
428
429
    def __init__(self, event, user, discount=None):
430
        chezbetty_v = account.get_virt_account("chezbetty")
431
        Transaction.__init__(self, event, user, chezbetty_v, None, None, Decimal(0.0))
432
        self.discount = discount
433
434
435
class Deposit(Transaction):
436
    __mapper_args__ = {'polymorphic_identity': 'deposit'}
437
438
    @classmethod
439
    def deposits_by_period(cls, period, start=None, end=None):
440
        r = DBSession.query(cls.amount.label('summable'), event.Event.timestamp)\
441
                     .join(event.Event)\
442
                     .order_by(event.Event.timestamp)\
443
                     .filter(event.Event.deleted==False)
444
        if start:
445
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
446
        if end:
447
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
448
449
        return utility.group(r.all(), period)
450
451
452
class CashDeposit(Deposit):
453
    __mapper_args__ = {'polymorphic_identity': 'cashdeposit'}
454
455
    CONTENTS_THRESHOLD = 1000
456
    REPEAT_THRESHOLD = 100
457
458
    def __init__(self, event, user, amount):
459
        cashbox_c = account.get_cash_account("cashbox")
460
        prev = cashbox_c.balance
461
        Transaction.__init__(self, event, None, user, None, cashbox_c, amount)
462
        new = cashbox_c.balance
463
464
        # It feels like the model should not have all of this application
465
        # specific logic in it. What does sending an email have to do with
466
        # representing a transaction. I think this should be moved to
467
        # datalayer.py which does handle application logic.
468
        try:
469
            if prev < CashDeposit.CONTENTS_THRESHOLD and new > CashDeposit.CONTENTS_THRESHOLD:
470
                self.send_alert_email(new)
471
            elif prev > CashDeposit.CONTENTS_THRESHOLD:
472
                pr = int((prev - CashDeposit.CONTENTS_THRESHOLD) / CashDeposit.REPEAT_THRESHOLD)
473
                nr = int((new - CashDeposit.CONTENTS_THRESHOLD) / CashDeposit.REPEAT_THRESHOLD)
474
                if pr != nr:
475
                    self.send_alert_email(new, nr)
476
        except:
477
            # Some error sending email. Let's not prevent the deposit from
478
            # going through.
479
            pass
480
481
    def send_alert_email(self, amount, repeat=0):
482
        settings = get_current_registry().settings
483
484
        SUBJECT = 'Time to empty Betty. Cash box has ${}.'.format(amount)
485
        TO = '[email protected]'
486
487
        body = """
488
        <p>Betty's cash box is getting full. Time to go to the bank.</p>
489
        <p>The cash box currently contains ${}.</p>
490
        """.format(amount)
491
        if repeat > 8:
492
            body = """
493
            <p><strong>Yo! Get your shit together! That's a lot of cash lying
494
            around!</strong></p>""" + body
495
        elif repeat > 4:
496
            body = body + """
497
            <p><strong>But seriously, you should probably go empty the cashbox
498
            like, right meow.</strong></p>"""
499
500
        if 'debugging' in settings and bool(int(settings['debugging'])):
501
            SUBJECT = '[ DEBUG_MODE ] ' + SUBJECT
502
            body = """
503
            <p><em>This message was sent from a debugging session and may be
504
            safely ignored.</em></p>""" + body
505
506
        utility.send_email(TO=TO, SUBJECT=SUBJECT, body=body)
507
508
509
class CCDeposit(Deposit):
510
    __mapper_args__ = {'polymorphic_identity': 'ccdeposit'}
511
512
    stripe_id = Column(Text)
513
    cc_last4 = Column(Text)
514
515
    def __init__(self, event, user, amount, stripe_id, last4):
516
        chezbetty_c = account.get_cash_account("chezbetty")
517
        Transaction.__init__(self, event, None, user, None, chezbetty_c, amount)
518
        self.stripe_id = stripe_id
519
        self.cc_last4 = last4
520
521
522
class BTCDeposit(Deposit):
523
    __mapper_args__ = {'polymorphic_identity': 'btcdeposit'}
524
525
    btctransaction = Column(String(64))
526
    address        = Column(String(64))
527
    amount_btc     = Column(Numeric, nullable=True)
528
529
    def __init__(self, event, user, amount, btctransaction, address, amount_btc):
530
        btcbox_c = account.get_cash_account("btcbox")
531
        Transaction.__init__(self, event, None, user, None, btcbox_c, amount)
532
        self.btctransaction = btctransaction
533
        self.address = address
534
        self.amount_btc = amount_btc
535
536
    def __getattr__(self, name):
537
        if name == 'img':
538
            return utility.string_to_qrcode(self.btctransaction)
539
        else:
540
            raise AttributeError
541
542
    @classmethod
543
    def from_address(cls, address):
544
        return DBSession.query(cls).join(event.Event)\
545
                        .filter(cls.address == address)\
546
                        .filter(event.Event.deleted == False).one()
547
548
549
class Adjustment(Transaction):
550
    __mapper_args__ = {'polymorphic_identity': 'adjustment'}
551
552
    def __init__(self, event, user, amount):
553
        chezbetty_v = account.get_virt_account("chezbetty")
554
        Transaction.__init__(self, event, chezbetty_v, user, None, None, amount)
555
556
557
class Restock(Transaction):
558
    __mapper_args__ = {'polymorphic_identity': 'restock'}
559
560
    # Additional cost that should get distributed over the entire restock
561
    amount_restock_cost = Column(Numeric, nullable=True)
562
563
    def __init__(self, event, global_cost):
564
        chezbetty_v = account.get_virt_account("chezbetty")
565
        chezbetty_c = account.get_cash_account("chezbetty")
566
        Transaction.__init__(self, event, chezbetty_v, None, chezbetty_c, None, Decimal(0.0))
567
        self.amount_restock_cost = global_cost
568
569
570
class Inventory(Transaction):
571
    __mapper_args__ = {'polymorphic_identity': 'inventory'}
572
    def __init__(self, event):
573
        chezbetty_v = account.get_virt_account("chezbetty")
574
        Transaction.__init__(self, event, chezbetty_v, None, None, None, Decimal(0.0))
575
576
577
class EmptyCashBox(Transaction):
578
    __mapper_args__ = {'polymorphic_identity': 'emptycashbox'}
579
    def __init__(self, event):
580
        cashbox_c = account.get_cash_account("cashbox")
581
        amount = cashbox_c.balance
582
        safe_c = account.get_cash_account("safe")
583
        Transaction.__init__(self, event, None, None, cashbox_c, safe_c, amount)
584
585
586
class EmptySafe(Transaction):
587
    __mapper_args__ = {'polymorphic_identity': 'emptysafe'}
588
    def __init__(self, event, amount):
589
        safe_c = account.get_cash_account("safe")
590
        chezbetty_c = account.get_cash_account("chezbetty")
591
        Transaction.__init__(self, event, None, None, safe_c, chezbetty_c, amount)
592
593
594
class EmptyBitcoin(Transaction):
595
    __mapper_args__ = {'polymorphic_identity': 'emptybitcoin'}
596
    def __init__(self, event, amount):
597
        btnbox_c = account.get_cash_account("btcbox")
598
        chezbetty_c = account.get_cash_account("chezbetty")
599
        Transaction.__init__(self, event, None, None, btnbox_c, chezbetty_c, amount)
600
601
602
class Lost(Transaction):
603
    __mapper_args__ = {'polymorphic_identity': 'lost'}
604
    def __init__(self, event, source_acct, amount):
605
        Transaction.__init__(self, event, None, None, source_acct, None, amount)
606
607
608
class Found(Transaction):
609
    __mapper_args__ = {'polymorphic_identity': 'found'}
610
    def __init__(self, event, dest_acct, amount):
611
        Transaction.__init__(self, event, None, None, None, dest_acct, amount)
612
613
614
class Donation(Transaction):
615
    __mapper_args__ = {'polymorphic_identity': 'donation'}
616
    def __init__(self, event, amount):
617
        chezbetty_v = account.get_virt_account("chezbetty")
618
        chezbetty_c = account.get_cash_account("chezbetty")
619
        Transaction.__init__(self, event, None, chezbetty_v, None, chezbetty_c, amount)
620
621
622
class Withdrawal(Transaction):
623
    __mapper_args__ = {'polymorphic_identity': 'withdrawal'}
624
    def __init__(self, event, amount):
625
        chezbetty_v = account.get_virt_account("chezbetty")
626
        chezbetty_c = account.get_cash_account("chezbetty")
627
        Transaction.__init__(self, event, chezbetty_v, None, chezbetty_c, None, amount)
628
629
630
################################################################################
631
## SUB TRANSACTIONS
632
################################################################################
633
634
class SubTransaction(Base):
635
    __tablename__   = "subtransactions"
636
637
    id              = Column(Integer, primary_key=True, nullable=False)
638
    transaction_id  = Column(Integer, ForeignKey("transactions.id"), nullable=False)
639
    amount          = Column(Numeric, nullable=False)
640
    type            = Column(Enum("purchaselineitem", "restocklineitem",
641
                                  "restocklinebox", "inventorylineitem",
642
                                  name="subtransaction_type"), nullable=False)
643
    item_id         = Column(Integer, ForeignKey("items.id"), nullable=True)
644
    quantity        = Column(Integer, nullable=False)
645
    wholesale       = Column(Numeric, nullable=False)
646
647
    # For restocks
648
    coupon_amount   = Column(Numeric, nullable=True) # Amount of discount on the item
649
    sales_tax       = Column(Boolean, nullable=True) # Whether sales tax was charged
650
    bottle_deposit  = Column(Boolean, nullable=True) # Whether there was a bottle deposit
651
652
    transaction     = relationship(Transaction, backref="subtransactions", cascade="all")
653
    item            = relationship(item.Item, backref="subtransactions")
654
655
    __mapper_args__ = {'polymorphic_on': type}
656
657
    def __init__(self, transaction, amount, item_id, quantity, wholesale):
658
        self.transaction_id = transaction.id
659
        self.amount = amount
660
        self.item_id = item_id
661
        self.quantity = quantity
662
        self.wholesale = wholesale
663
664
    def __getattr__(self, name):
665
        if name == 'deleted':
666
            return self.transaction.event.deleted
667
        else:
668
            raise AttributeError
669
670
    @classmethod
671
    @limitable_all
672
    def all_item(cls, id):
673
        return DBSession.query(cls)\
674
                        .join(Transaction)\
675
                        .join(event.Event)\
676
                        .filter(cls.item_id == id)\
677
                        .filter(event.Event.deleted==False)\
678
                        .order_by(desc(event.Event.timestamp))
679
680
    @classmethod
681
    @limitable_all
682
    def all_item_purchases(cls, id):
683
        return DBSession.query(cls)\
684
                        .join(Transaction)\
685
                        .join(event.Event)\
686
                        .filter(cls.item_id == id)\
687
                        .filter(event.Event.deleted==False)\
688
                        .filter(event.Event.type=="purchase")\
689
                        .order_by(desc(event.Event.timestamp))
690
691
    @classmethod
692
    @limitable_all
693
    def all_item_events(cls, id):
694
        return DBSession.query(cls)\
695
                        .join(Transaction)\
696
                        .join(event.Event)\
697
                        .filter(cls.item_id == id)\
698
                        .filter(event.Event.deleted==False)\
699
                        .filter(or_(event.Event.type=="inventory", event.Event.type =="restock"))\
700
                        .order_by(desc(event.Event.timestamp))
701
702
    @classmethod
703
    @limitable_all
704
    def all(cls, trans_type=None):
705
        if not trans_type:
706
            return DBSession.query(cls)\
707
                            .join(Transaction)\
708
                            .join(event.Event)\
709
                            .filter(event.Event.deleted==False)\
710
                            .order_by(desc(event.Event.timestamp))
711
        else:
712
            return DBSession.query(cls)\
713
                            .join(Transaction)\
714
                            .join(event.Event)\
715
                            .filter(cls.type==trans_type)\
716
                            .filter(event.Event.deleted==False)\
717
                            .order_by(desc(event.Event.timestamp))
718
719
class PurchaseLineItem(SubTransaction):
720
    __mapper_args__ = {'polymorphic_identity': 'purchaselineitem'}
721
    price           = Column(Numeric)
722
    def __init__(self, transaction, amount, item, quantity, price, wholesale):
723
        SubTransaction.__init__(self, transaction, amount, item.id, quantity, wholesale)
724
        self.price = price
725
726
    @classmethod
727
    def quantity_by_period(cls, period, start=None, end=None):
728
        r = DBSession.query(cls.quantity.label('summable'), event.Event.timestamp)\
729
                     .join(Transaction)\
730
                     .join(event.Event)\
731
                     .filter(event.Event.deleted==False)\
732
                     .order_by(event.Event.timestamp)
733
        if start:
734
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
735
        if end:
736
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
737
        return utility.group(r.all(), period)
738
739
    @classmethod
740
    def virtual_revenue_by_period(cls, period, start=None, end=None):
741
        r = DBSession.query(cls.amount.label('summable'), event.Event.timestamp)\
742
                     .join(Transaction)\
743
                     .join(event.Event)\
744
                     .filter(event.Event.deleted==False)\
745
                     .order_by(event.Event.timestamp)
746
        if start:
747
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
748
        if end:
749
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
750
        return utility.group(r.all(), period)
751
752
    @classmethod
753
    def profit_on_sales(cls, start=None, end=None):
754
        r = DBSession.query(func.sum(cls.amount-(cls.wholesale*cls.quantity)).label('p'))\
755
                        .join(Transaction)\
756
                        .join(event.Event)\
757
                        .filter(event.Event.deleted==False)
758
        if start:
759
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
760
        if end:
761
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
762
763
        return r.one().p or Decimal(0.0)
764
765
    @classmethod
766
    def item_sale_quantities(cls, item_id):
767
        return DBSession.query(cls, event.Event)\
768
                        .join(Transaction)\
769
                        .join(event.Event)\
770
                        .filter(event.Event.deleted==False)\
771
                        .filter(cls.item_id==int(item_id))\
772
                        .order_by(event.Event.timestamp).all()
773
774
775
# This is slowww:
776
# @property
777
# def __number_sold(self):
778
#     return object_session(self).query(func.sum(PurchaseLineItem.quantity).label('c'))\
779
#                                .join(Transaction)\
780
#                                .join(event.Event)\
781
#                                .filter(PurchaseLineItem.item_id==self.id)\
782
#                                .filter(event.Event.deleted==False).one().c
783
# item.Item.number_sold = __number_sold
784
785
786
class RestockLineItem(SubTransaction):
787
    __mapper_args__ = {'polymorphic_identity': 'restocklineitem'}
788
    def __init__(self,
789
                 transaction,
790
                 amount,
791
                 item,
792
                 quantity,
793
                 wholesale,
794
                 coupon,
795
                 sales_tax,
796
                 bottle_deposit):
797
        SubTransaction.__init__(self, transaction, amount, item.id, quantity, wholesale)
798
        self.coupon_amount = coupon
799
        self.sales_tax = sales_tax
800
        self.bottle_deposit = bottle_deposit
801
802
803
class RestockLineBox(SubTransaction):
804
    __mapper_args__ = {'polymorphic_identity': 'restocklinebox'}
805
    box_id          = Column(Integer, ForeignKey("boxes.id"), nullable=True)
806
807
    box             = relationship(box.Box, backref="subtransactions")
808
809
    def __init__(self,
810
                 transaction,
811
                 amount,
812
                 box,
813
                 quantity,
814
                 wholesale,
815
                 coupon,
816
                 sales_tax,
817
                 bottle_deposit):
818
        self.transaction_id = transaction.id
819
        self.amount = amount
820
        self.box_id = box.id
821
        self.quantity = quantity
822
        self.wholesale = wholesale
823
        self.coupon_amount = coupon
824
        self.sales_tax = sales_tax
825
        self.bottle_deposit = bottle_deposit
826
827
828
class InventoryLineItem(SubTransaction):
829
    __mapper_args__    = {'polymorphic_identity': 'inventorylineitem'}
830
    quantity_predicted = synonym(SubTransaction.quantity)
831
    quantity_counted   = Column(Integer)
832
833
    def __init__(self, transaction, amount, item, quantity_predicted, quantity_counted, wholesale):
834
        SubTransaction.__init__(self, transaction, amount, item.id, quantity_predicted, wholesale)
835
        self.quantity_counted = quantity_counted
836
837
838
839
################################################################################
840
## SUBSUB TRANSACTIONS
841
################################################################################
842
843
# This is for tracking which items were in which boxes when we restocked
844
845
class SubSubTransaction(Base):
846
    __tablename__      = "subsubtransactions"
847
848
    id                 = Column(Integer, primary_key=True, nullable=False)
849
    subtransaction_id  = Column(Integer, ForeignKey("subtransactions.id"), nullable=False)
850
    type               = Column(Enum("restocklineboxitem",
851
                                     name="subsubtransaction_type"), nullable=False)
852
    item_id            = Column(Integer, ForeignKey("items.id"), nullable=True)
853
    quantity           = Column(Integer, nullable=False)
854
855
    subtransaction     = relationship(SubTransaction, backref="subsubtransactions", cascade="all")
856
    item               = relationship(item.Item, backref="subsubtransactions")
857
858
    __mapper_args__    = {'polymorphic_on': type}
859
860
    def __init__(self, subtransaction, item_id, quantity):
861
        self.subtransaction_id = subtransaction.id
862
        self.item_id = item_id
863
        self.quantity = quantity
864
865
    def __getattr__(self, name):
866
        if name == 'deleted':
867
            return self.subtransaction.transaction.event.deleted
868
        else:
869
            raise AttributeError
870
871
    @classmethod
872
    @limitable_all
873
    def all_item(cls, item_id):
874
        return DBSession.query(cls)\
875
                        .join(SubTransaction)\
876
                        .join(Transaction)\
877
                        .join(event.Event)\
878
                        .filter(cls.item_id == item_id)\
879
                        .filter(event.Event.deleted==False)\
880
                        .order_by(cls.id)
881
882
883
class RestockLineBoxItem(SubSubTransaction):
884
    __mapper_args__ = {'polymorphic_identity': 'restocklineboxitem'}
885
    def __init__(self, subtransaction, item, quantity):
886
        SubSubTransaction.__init__(self, subtransaction, item.id, quantity)
887
888
889
890