Coverage for django_napse/core/models/transactions/managers/transaction.py: 85%

26 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-03-12 13:49 +0000

1from django.db import models 

2from django.db.transaction import atomic 

3 

4from django_napse.utils.constants import TRANSACTION_TYPES 

5from django_napse.utils.errors import TransactionError 

6 

7 

8class TransactionManager(models.Manager): 

9 @atomic() 

10 def create(self, from_wallet, to_wallet, amount, ticker, transaction_type): 

11 """Create a Transaction object and update the wallets accordingly.""" 

12 if amount == 0: 

13 return None 

14 transaction = self.model( 

15 from_wallet=from_wallet, 

16 to_wallet=to_wallet, 

17 amount=amount, 

18 ticker=ticker, 

19 transaction_type=transaction_type, 

20 ) 

21 if from_wallet.exchange_account != to_wallet.exchange_account: 

22 error_msg = "Wallets must be on the same exchange_account." 

23 raise TransactionError.DifferentAccountError(error_msg) 

24 

25 if from_wallet == to_wallet: 

26 error_msg = "Wallets must be different." 

27 raise TransactionError.SameWalletError(error_msg) 

28 

29 if from_wallet.testing != to_wallet.testing: 

30 error_msg = f"Wallets must be both testing or both not testing. Here: {from_wallet.testing} -> {to_wallet.testing}." 

31 raise TransactionError.TestingError(error_msg) 

32 

33 if transaction_type not in TRANSACTION_TYPES: 

34 error_msg = f"Transaction type {transaction_type} not in {TRANSACTION_TYPES}." 

35 raise TransactionError.InvalidTransactionError(error_msg) 

36 

37 from_wallet.spend(amount, ticker, force=True) 

38 to_wallet.top_up(amount, ticker, mbp=from_wallet.currencies.get(ticker=ticker).mbp, force=True) 

39 transaction.save() 

40 return transaction