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
|
from datetime import datetime
from decimal import Decimal
from random import randint
from typing import Optional, Dict, Callable, TYPE_CHECKING
from uuid import uuid4
import pytest
from generalresearch.currency import USDCent
from test_utils.models.conftest import (
product_factory,
user,
product,
user_factory,
product_user_wallet_no,
wall,
product_amt_true,
product_user_wallet_yes,
session_factory,
session,
wall_factory,
payout_config,
)
_ = (
user_factory,
product_user_wallet_no,
wall,
product_amt_true,
product_user_wallet_yes,
session_factory,
session,
wall_factory,
payout_config,
)
if TYPE_CHECKING:
from generalresearch.currency import LedgerCurrency
from generalresearch.models.thl.ledger import (
Direction,
AccountType,
LedgerTransaction,
)
from generalresearch.models.thl.ledger import (
LedgerEntry,
LedgerAccount,
)
from generalresearch.models.thl.payout import UserPayoutEvent
@pytest.fixture(scope="function")
def ledger_account(request, lm, currency) -> "LedgerAccount":
from generalresearch.models.thl.ledger import (
Direction,
AccountType,
LedgerAccount,
)
account_type = getattr(request, "account_type", AccountType.CASH)
direction = getattr(request, "direction", Direction.CREDIT)
acct_uuid = uuid4().hex
qn = ":".join([currency, account_type, acct_uuid])
acct_model = LedgerAccount(
uuid=acct_uuid,
display_name=f"test-{acct_uuid}",
currency=currency,
qualified_name=qn,
account_type=account_type,
normal_balance=direction,
)
return lm.create_account(account=acct_model)
@pytest.fixture(scope="function")
def ledger_account_factory(request, thl_lm, lm, currency) -> Callable:
from generalresearch.models.thl.ledger import (
Direction,
AccountType,
LedgerAccount,
)
def _ledger_account_factory(
product,
account_type: AccountType = AccountType.CASH,
direction: Direction = Direction.CREDIT,
):
thl_lm.get_account_or_create_bp_wallet(product=product)
acct_uuid = uuid4().hex
qn = ":".join([currency, account_type, acct_uuid])
acct_model = LedgerAccount(
uuid=acct_uuid,
display_name=f"test-{acct_uuid}",
currency=currency,
qualified_name=qn,
account_type=account_type,
normal_balance=direction,
)
return lm.create_account(account=acct_model)
return _ledger_account_factory
@pytest.fixture(scope="function")
def ledger_account_credit(request, lm, currency) -> "LedgerAccount":
from generalresearch.models.thl.ledger import Direction, AccountType
account_type = AccountType.REVENUE
acct_uuid = uuid4().hex
qn = ":".join([currency, account_type, acct_uuid])
from generalresearch.models.thl.ledger import LedgerAccount
acct_model = LedgerAccount(
uuid=acct_uuid,
display_name=f"test-{acct_uuid}",
currency=currency,
qualified_name=qn,
account_type=account_type,
normal_balance=Direction.CREDIT,
)
return lm.create_account(account=acct_model)
@pytest.fixture(scope="function")
def ledger_account_debit(request, lm, currency) -> "LedgerAccount":
from generalresearch.models.thl.ledger import Direction, AccountType
account_type = AccountType.EXPENSE
acct_uuid = uuid4().hex
qn = ":".join([currency, account_type, acct_uuid])
from generalresearch.models.thl.ledger import LedgerAccount
acct_model = LedgerAccount(
uuid=acct_uuid,
display_name=f"test-{acct_uuid}",
currency=currency,
qualified_name=qn,
account_type=account_type,
normal_balance=Direction.DEBIT,
)
return lm.create_account(account=acct_model)
@pytest.fixture(scope="function")
def tag(request, lm) -> str:
from generalresearch.currency import LedgerCurrency
return (
request.param
if hasattr(request, "tag")
else f"{LedgerCurrency.TEST}:{uuid4().hex}"
)
@pytest.fixture(scope="function")
def usd_cent(request) -> USDCent:
amount = randint(99, 9_999)
return request.param if hasattr(request, "usd_cent") else USDCent(amount)
@pytest.fixture(scope="function")
def bp_payout_event(
product, usd_cent, business_payout_event_manager, thl_lm
) -> "UserPayoutEvent":
return business_payout_event_manager.create_bp_payout_event(
thl_ledger_manager=thl_lm,
product=product,
amount=usd_cent,
skip_wallet_balance_check=True,
skip_one_per_day_check=True,
)
@pytest.fixture
def bp_payout_event_factory(brokerage_product_payout_event_manager, thl_lm) -> Callable:
from generalresearch.models.thl.product import Product
from generalresearch.currency import USDCent
def _create_bp_payout_event(
product: Product, usd_cent: USDCent, ext_ref_id: Optional[str] = None
):
return brokerage_product_payout_event_manager.create_bp_payout_event(
thl_ledger_manager=thl_lm,
product=product,
amount=usd_cent,
ext_ref_id=ext_ref_id,
skip_wallet_balance_check=True,
skip_one_per_day_check=True,
)
return _create_bp_payout_event
@pytest.fixture(scope="function")
def currency(lm) -> "LedgerCurrency":
# return request.param if hasattr(request, "currency") else LedgerCurrency.TEST
return lm.currency
@pytest.fixture(scope="function")
def tx_metadata(request) -> Optional[Dict[str, str]]:
return (
request.param
if hasattr(request, "tx_metadata")
else {f"key-{uuid4().hex[:10]}": uuid4().hex}
)
@pytest.fixture(scope="function")
def ledger_tx(
request,
ledger_account_credit,
ledger_account_debit,
tag,
currency,
tx_metadata,
lm,
) -> "LedgerTransaction":
from generalresearch.models.thl.ledger import Direction, LedgerEntry
amount = int(Decimal("1.00") * 100)
entries = [
LedgerEntry(
direction=Direction.CREDIT,
account_uuid=ledger_account_credit.uuid,
amount=amount,
),
LedgerEntry(
direction=Direction.DEBIT,
account_uuid=ledger_account_debit.uuid,
amount=amount,
),
]
return lm.create_tx(entries=entries, tag=tag, metadata=tx_metadata)
@pytest.fixture(scope="function")
def create_main_accounts(lm, currency) -> Callable:
def _create_main_accounts():
from generalresearch.models.thl.ledger import (
LedgerAccount,
Direction,
AccountType,
)
account = LedgerAccount(
display_name="Cash flow task complete",
qualified_name=f"{currency.value}:revenue:task_complete",
normal_balance=Direction.CREDIT,
account_type=AccountType.REVENUE,
currency=lm.currency,
)
lm.get_account_or_create(account=account)
account = LedgerAccount(
display_name="Operating Cash Account",
qualified_name=f"{currency.value}:cash",
normal_balance=Direction.DEBIT,
account_type=AccountType.CASH,
currency=currency,
)
lm.get_account_or_create(account=account)
return _create_main_accounts
@pytest.fixture(scope="function")
def delete_ledger_db(thl_web_rw) -> Callable:
def _delete_ledger_db():
for table in [
"ledger_transactionmetadata",
"ledger_entry",
"ledger_transaction",
"ledger_account",
]:
thl_web_rw.execute_write(
query=f"DELETE FROM {table};",
)
return _delete_ledger_db
@pytest.fixture(scope="function")
def wipe_main_accounts(thl_web_rw, lm, currency) -> Callable:
def _wipe_main_accounts():
db_table = thl_web_rw.db_name
qual_names = [
f"{currency.value}:revenue:task_complete",
f"{currency.value}:cash",
]
res = thl_web_rw.execute_sql_query(
query=f"""
SELECT lt.id as ltid, le.id as leid, tmd.id as tmdid, la.uuid as lauuid
FROM `{db_table}`.`ledger_transaction` AS lt
LEFT JOIN `{db_table}`.ledger_entry le
ON lt.id = le.transaction_id
LEFT JOIN `{db_table}`.ledger_account la
ON la.uuid = le.account_id
LEFT JOIN `{db_table}`.ledger_transactionmetadata tmd
ON lt.id = tmd.transaction_id
WHERE la.qualified_name IN %s
""",
params=[qual_names],
)
lt = {x["ltid"] for x in res if x["ltid"]}
le = {x["leid"] for x in res if x["leid"]}
tmd = {x["tmdid"] for x in res if x["tmdid"]}
la = {x["lauuid"] for x in res if x["lauuid"]}
thl_web_rw.execute_sql_query(
query=f"""
DELETE FROM `{db_table}`.`ledger_transactionmetadata`
WHERE id IN %s
""",
params=[tmd],
commit=True,
)
thl_web_rw.execute_sql_query(
query=f"""
DELETE FROM `{db_table}`.`ledger_entry`
WHERE id IN %s
""",
params=[le],
commit=True,
)
thl_web_rw.execute_sql_query(
query=f"""
DELETE FROM `{db_table}`.`ledger_transaction`
WHERE id IN %s
""",
params=[lt],
commit=True,
)
thl_web_rw.execute_sql_query(
query=f"""
DELETE FROM `{db_table}`.`ledger_account`
WHERE uuid IN %s
""",
params=[la],
commit=True,
)
return _wipe_main_accounts
@pytest.fixture(scope="function")
def account_cash(lm, currency) -> "LedgerAccount":
from generalresearch.models.thl.ledger import (
LedgerAccount,
Direction,
AccountType,
)
account = LedgerAccount(
display_name="Operating Cash Account",
qualified_name=f"{currency.value}:cash",
normal_balance=Direction.DEBIT,
account_type=AccountType.CASH,
currency=currency,
)
return lm.get_account_or_create(account=account)
@pytest.fixture(scope="function")
def account_revenue_task_complete(lm, currency) -> "LedgerAccount":
from generalresearch.models.thl.ledger import (
LedgerAccount,
Direction,
AccountType,
)
account = LedgerAccount(
display_name="Cash flow task complete",
qualified_name=f"{currency.value}:revenue:task_complete",
normal_balance=Direction.CREDIT,
account_type=AccountType.REVENUE,
currency=currency,
)
return lm.get_account_or_create(account=account)
@pytest.fixture(scope="function")
def account_expense_tango(lm, currency) -> "LedgerAccount":
from generalresearch.models.thl.ledger import (
LedgerAccount,
Direction,
AccountType,
)
account = LedgerAccount(
display_name="Tango Fee",
qualified_name=f"{currency.value}:expense:tango_fee",
normal_balance=Direction.DEBIT,
account_type=AccountType.EXPENSE,
currency=currency,
)
return lm.get_account_or_create(account=account)
@pytest.fixture(scope="function")
def user_account_user_wallet(lm, user, currency) -> "LedgerAccount":
from generalresearch.models.thl.ledger import (
LedgerAccount,
Direction,
AccountType,
)
account = LedgerAccount(
display_name=f"{user.uuid} Wallet",
qualified_name=f"{currency.value}:user_wallet:{user.uuid}",
normal_balance=Direction.CREDIT,
account_type=AccountType.USER_WALLET,
reference_type="user",
reference_uuid=user.uuid,
currency=currency,
)
return lm.get_account_or_create(account=account)
@pytest.fixture(scope="function")
def product_account_bp_wallet(lm, product, currency) -> "LedgerAccount":
from generalresearch.models.thl.ledger import (
LedgerAccount,
Direction,
AccountType,
)
account = LedgerAccount.model_validate(
dict(
display_name=f"{product.name} Wallet",
qualified_name=f"{currency.value}:bp_wallet:{product.uuid}",
normal_balance=Direction.CREDIT,
account_type=AccountType.BP_WALLET,
reference_type="bp",
reference_uuid=product.uuid,
currency=currency,
)
)
return lm.get_account_or_create(account=account)
@pytest.fixture(scope="function")
def setup_accounts(product_factory, lm, user, currency) -> None:
from generalresearch.models.thl.ledger import (
LedgerAccount,
Direction,
AccountType,
)
# BP's wallet and a revenue from their commissions account.
p1 = product_factory()
account = LedgerAccount(
display_name=f"Revenue from {p1.name} commission",
qualified_name=f"{currency.value}:revenue:bp_commission:{p1.uuid}",
normal_balance=Direction.CREDIT,
account_type=AccountType.REVENUE,
reference_type="bp",
reference_uuid=p1.uuid,
currency=currency,
)
lm.get_account_or_create(account=account)
account = LedgerAccount.model_validate(
dict(
display_name=f"{p1.name} Wallet",
qualified_name=f"{currency.value}:bp_wallet:{p1.uuid}",
normal_balance=Direction.CREDIT,
account_type=AccountType.BP_WALLET,
reference_type="bp",
reference_uuid=p1.uuid,
currency=currency,
)
)
lm.get_account_or_create(account=account)
# BP's wallet, user's wallet, and a revenue from their commissions account.
p2 = product_factory()
account = LedgerAccount(
display_name=f"Revenue from {p2.name} commission",
qualified_name=f"{currency.value}:revenue:bp_commission:{p2.uuid}",
normal_balance=Direction.CREDIT,
account_type=AccountType.REVENUE,
reference_type="bp",
reference_uuid=p2.uuid,
currency=currency,
)
lm.get_account_or_create(account)
account = LedgerAccount(
display_name=f"{p2.name} Wallet",
qualified_name=f"{currency.value}:bp_wallet:{p2.uuid}",
normal_balance=Direction.CREDIT,
account_type=AccountType.BP_WALLET,
reference_type="bp",
reference_uuid=p2.uuid,
currency=currency,
)
lm.get_account_or_create(account)
account = LedgerAccount(
display_name=f"{user.uuid} Wallet",
qualified_name=f"{currency.value}:user_wallet:{user.uuid}",
normal_balance=Direction.CREDIT,
account_type=AccountType.USER_WALLET,
reference_type="user",
reference_uuid=user.uuid,
currency="test",
)
lm.get_account_or_create(account=account)
@pytest.fixture(scope="function")
def session_with_tx_factory(
user_factory,
product,
session_factory,
session_manager,
wall_manager,
utc_hour_ago,
thl_lm,
) -> Callable:
from generalresearch.models.thl.session import (
Status,
Session,
StatusCode1,
)
from generalresearch.models.thl.user import User
def _session_with_tx_factory(
user: User,
final_status: Status = Status.COMPLETE,
wall_req_cpi: Decimal = Decimal(".50"),
started: datetime = utc_hour_ago,
) -> Session:
s: Session = session_factory(
user=user,
wall_count=2,
final_status=final_status,
wall_req_cpi=wall_req_cpi,
started=started,
)
last_wall = s.wall_events[-1]
wall_manager.finish(
wall=last_wall,
status=Status.COMPLETE,
status_code_1=StatusCode1.COMPLETE,
finished=last_wall.finished,
)
status, status_code_1 = s.determine_session_status()
thl_net, commission_amount, bp_pay, user_pay = s.determine_payments()
session_manager.finish_with_status(
session=s,
finished=last_wall.finished,
payout=bp_pay,
user_payout=user_pay,
status=status,
status_code_1=status_code_1,
)
thl_lm.create_tx_task_complete(
wall=last_wall,
user=user,
created=last_wall.finished,
force=True,
)
thl_lm.create_tx_bp_payment(session=s, created=last_wall.finished, force=True)
return s
return _session_with_tx_factory
@pytest.fixture(scope="function")
def adj_to_fail_with_tx_factory(session_manager, wall_manager, thl_lm) -> Callable:
from generalresearch.models.thl.session import (
Session,
)
from datetime import timedelta
from generalresearch.models.thl.definitions import WallAdjustedStatus
def _adj_to_fail_with_tx_factory(
session: Session,
created: datetime,
) -> None:
w1 = wall_manager.get_wall_events(session_id=session.id)[-1]
# This is defined in `thl-grpc/thl/user_quality_history/recons.py:150`
# so we can't use it as part of this test anyway to add rows to the
# thl_taskadjustment table anyway.. until we created a
# TaskAdjustment Manager to put into py-utils!
# create_task_adjustment_event(
# wall,
# user,
# adjusted_status,
# amount_usd=amount_usd,
# alert_time=alert_time,
# ext_status_code=ext_status_code,
# )
wall_manager.adjust_status(
wall=w1,
adjusted_status=WallAdjustedStatus.ADJUSTED_TO_FAIL,
adjusted_cpi=Decimal("0.00"),
adjusted_timestamp=created,
)
thl_lm.create_tx_task_adjustment(
wall=w1,
user=session.user,
created=created + timedelta(milliseconds=1),
)
session.wall_events = wall_manager.get_wall_events(session_id=session.id)
session_manager.adjust_status(session=session)
thl_lm.create_tx_bp_adjustment(
session=session, created=created + timedelta(milliseconds=2)
)
return None
return _adj_to_fail_with_tx_factory
@pytest.fixture(scope="function")
def adj_to_complete_with_tx_factory(session_manager, wall_manager, thl_lm) -> Callable:
from generalresearch.models.thl.session import (
Session,
)
from datetime import timedelta
from generalresearch.models.thl.definitions import WallAdjustedStatus
def _adj_to_complete_with_tx_factory(
session: Session,
created: datetime,
) -> None:
w1 = wall_manager.get_wall_events(session_id=session.id)[-1]
wall_manager.adjust_status(
wall=w1,
adjusted_status=WallAdjustedStatus.ADJUSTED_TO_COMPLETE,
adjusted_cpi=w1.req_cpi,
adjusted_timestamp=created,
)
thl_lm.create_tx_task_adjustment(
wall=w1,
user=session.user,
created=created + timedelta(milliseconds=1),
)
session.wall_events = wall_manager.get_wall_events(session_id=session.id)
session_manager.adjust_status(session=session)
thl_lm.create_tx_bp_adjustment(
session=session, created=created + timedelta(milliseconds=2)
)
return None
return _adj_to_complete_with_tx_factory
|