
    %fj2                    n   d dl mZ d dlmZ d dlmZ d dlmZ d dlm	Z	m
Z
 d dlmZ ddlmZ d:d;dZd<dZd=dZd>dZd?dZd@d Zd!d!d!d!d!d!d!d!d!d!d!d!d"dAd/Z ed	          d0dBd3ZdCd4Z ed	          d!d5dDd6Z ed	          d! ed	          d!d7dEd8Z ed	          d! ed	          d!d7dFd9Zd!S )G    )annotations)Decimal)
Connection)record_audit_event)	stable_idutc_now)create_alert   )calculate_crypto_holdings0valueobjectdefaultstrreturnr   c                    | %t          |                                           dk    rt          |          S t          t          |                     S )N )r   stripr   )r   r   s     )src/jarvis_finance/crypto/transactions.py_dr      sE    }E

((**b00w3u::    Decimal | None
str | Nonec                *    | t          | d          nd S )Nf)format)r   s    r   _dsr      s    !&!26%<r   fx_rate_to_chfc                .    |d S t          | |z            S )N)r   )r   r   s     r   _chfr       s     tu~%&&&r   quantityNonec                0    | dk    rt          d          d S )Nr   zquantity must be > 0)
ValueError)r!   s    r   _ensure_positiver%      s!    1}}/000 }r   connr   	wallet_idasset_idc                    t          |           }|j                            ||f          }|r|j        nt	          d          S )Nr   )r   wallet_holdingsgetr!   r   )r&   r'   r(   resultholdings        r   _current_quantityr.   !   sC    &t,,F$(()X)>??G&87GCLL8r   	attempted	availablec                    t          | ddd|dd|t          |          t          |          d           |                                  d S )Nkritischcryptocrypto_walletcrypto_negative_wallet_balancezJCrypto transaction would create a negative wallet balance and was blocked.)r(   attempted_deltar0   prioritycategoryentity_type	entity_idrule_idmessageevidence)r	   r   commit)r&   r'   r(   r/   r0   s        r   _critical_negative_alertr@   '   s^    #0\&3y>>X[\eXfXfgg	 	 	 	 	KKMMMMMr   N)from_wallet_idto_wallet_idtransaction_idprice_originalcurrencygross_amount_originalfee_quantityfee_originalfee_currencyr   tx_hashnotetx_typerA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   c               f   t                      }t          d||||pd|pd|          }|                     d||||t          |          t          |          |t          |	          t          |
          t          |          |t          |          |	t	          |	|          nd ||||||f           |S )Ncryptotxr   a  
        INSERT INTO crypto_transactions(
            crypto_transaction_id, transaction_id, transaction_type, asset_id, quantity,
            price_original, currency_original, gross_amount_original, fee_quantity,
            fee_original, fee_currency, fx_rate_to_chf, amount_chf, from_wallet_id,
            to_wallet_id, transaction_datetime, tx_hash, source, confirmation_status,
            parse_confidence, notes, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'manual', 'confirmed', 1, ?, ?)
        )r   r   executer   r    )r&   rL   r(   r!   rA   rB   rC   rD   rE   rF   rG   rH   rI   r   rJ   rK   nowcrypto_txids                     r   _insert_crypto_transactionrR   5   s    & ))CJ8^EYWY[g[mkmorssKLL	 (CMMc/00#n--;P;\D&777bfL#wc		
  * r   )rH   
account_id	source_idc               D   t                      }	t          dd|||||          }
|dnd}|dnd}|dv r||z
  n|}|                     d|
|||	d d         t          |          t          |          t          |          |                                t          |          |t          ||          t          ||          t          ||          ||||	f           |D|                                d	k    r,t          | d
dd|
dd|                                |d           |
S )Nledgerr3   okmissing
incomplete>   	full_sellpartial_sella  
        INSERT INTO transactions(
            transaction_id, transaction_type, account_id, trade_date, gross_amount_original,
            fee_original, net_amount_original, currency_original, fx_rate_to_chf, fx_status,
            gross_amount_chf, fee_chf, net_amount_chf, source_type, source_id,
            is_confirmed, quality_status, notes, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'crypto', ?, 1, ?, ?, ?)
        
   CHFr2   transaction
missing_fxzGCrypto fiat ledger transaction is missing FX; CHF impact is incomplete.)rE   rT   r7   )r   r   rO   r   upperr    r	   )r&   rL   rS   rT   rF   rE   r   rK   rH   rP   txid	fx_statusqualitysign_nets                 r   _insert_ledger_transactionre   b   sd    ))CXx*iI^`lmmD&2	I$0ddlG7>B_7_7_$|33ezHLL	 ':s3B3x5J1K1KSQ]M^M^`cdl`m`mNNc.119&77lN9[9[]abjlz]{]{wc		
    (.."2"2e";";% ]"*.."2"2KK		
 		
 		
 		
 Kr   c                   |dk    rd S |s(t          | ddd|dddt          |          i           d S t          | d	||||||
          S )Nr   warnungr3   crypto_transactioncrypto_fee_currency_unclearzXCrypto fiat fee currency is unclear; ledger fee is not created to avoid double counting.rH   r7   feerL   rS   rT   rF   rE   r   rK   )r	   r   re   )r&   rS   rT   rH   rI   r   rK   s          r   _insert_fee_ledgerrl      s     qt ,1n$c,&7&78		
 		
 		
 		
 t%*%	 	 	 	r   )rG   rJ   c                  t          |           |dk     rt          d          ||k    rt          d          ||z   }t          | ||          }	|	|k     r"t          | ||||	           t          d          t	          | d|||||||	  	        }
t          | ddd	|
|||t          |          t          |          d
|dd	  	         |                                  |
S )Nr   zfee_quantity must be >= 0z+source and target wallets must be differentnegative wallet balance blockedtransfer)rL   r(   r!   rG   rA   rB   rJ   rK   crypto_transactionscrypto_transferrh   )r(   rA   rB   r!   rG   Tsystemsourceactionr:   r;   
new_valuesuser_text_note	confirmed
created_by)	r%   r$   r.   r@   rR   r   r   r   r?   )r&   r(   rA   rB   r!   rG   rJ   rK   requiredr0   rQ   s              r   record_crypto_transferr{      sN    Xa4555%%FGGG,&H!$AAI8 ~x9UUU:;;;,!%!
 
 
K $ ( (N\hvy  {C  wD  wD  VY  Zf  Vg  Vg  h  h
 
 
 
 	KKMMMr   )rH   rI   rG   r   c                  t          |           |
dk     s|dk     rt          d          t          d|||t                                }t	          | d||||||          }t          | d||||||
||	|                                ||          }|                     d||f           t          | ||||	||           t          | d	d
d|||t          |          |d|dd	  	         |                                  |S )Nr   fees must be >= 0	cryptobuybuyrk   )rL   r(   r!   rB   rC   rF   rG   rH   rI   rE   r   rK   :UPDATE transactions SET source_id=? WHERE transaction_id=?)rS   rT   rH   rI   r   rK   rp   
crypto_buyrh   )r(   rB   r!   ledger_transaction_idTrr   rs   )r%   r$   r   r   re   rR   r`   rO   rl   r   r   r?   )r&   rS   r(   rB   r!   rF   rE   rK   rH   rI   rG   r   provisionalledger_txidrQ   s                  r   record_crypto_buyr      s}    Xa<!++,---K<799UUK,3%	 	 	K -!"3!!!!!%  K 	LLMP[]hOijjjt
kXds  Q_  fj  k  k  k  k$( (,TWX`TaTa  }H  I  I
 
 
 
 	KKMMMr   c                  t          |           |
dk     s|dk     rt          d          ||
z   }t          | ||          }||k     r"t          | ||||           t          d          t	          d|||t                                }t          | d|||||||	  	        }t          | d||||||
||	|                                ||          }| 	                    d	||f           |dk    r(|	s&t          | d
dd|dddt          |          i           t          | ddd|||t          |          |d|dd	  	         |                                  |S )Nr   r}   rn   
cryptosellr[   )rL   rS   rT   rF   rH   rE   r   rK   sell)rL   r(   r!   rA   rC   rF   rG   rH   rI   rE   r   rK   r   rg   r3   rh   ri   zNCrypto sell fee currency is unclear; fee remains embedded in sell transaction.rH   r7   rp   crypto_sell)r(   rA   r!   r   Trr   rs   )r%   r$   r.   r@   r   r   re   rR   r`   rO   r	   r   r   r   r?   )r&   rS   r(   rA   r!   rF   rE   rK   rH   rI   rG   r   rz   r0   r   r   rQ   s                    r   record_crypto_sellr   "  s    Xa<!++,---,&H!$AAI8 ~x9UUU:;;;L(NHgiiXXK,3!%
 
 
K -%"3!!!!!%  K 	LLMP[]hOijjja,!1d$c,&7&78		
 		
 		
 		
 $( (NX[\dXeXe  AL  M  M
 
 
 
 	KKMMMr   )r   )r   r   r   r   r   r   )r   r   r   r   )r   r   r   r   r   r   )r!   r   r   r"   )r&   r   r'   r   r(   r   r   r   )r&   r   r'   r   r(   r   r/   r   r0   r   r   r"   )"r&   r   rL   r   r(   r   r!   r   rA   r   rB   r   rC   r   rD   r   rE   r   rF   r   rG   r   rH   r   rI   r   r   r   rJ   r   rK   r   r   r   )r&   r   rL   r   rS   r   rT   r   rF   r   rE   r   r   r   rK   r   rH   r   r   r   )r&   r   rS   r   rT   r   rH   r   rI   r   r   r   rK   r   r   r   )r&   r   r(   r   rA   r   rB   r   r!   r   rG   r   rJ   r   rK   r   r   r   )r&   r   rS   r   r(   r   rB   r   r!   r   rF   r   rE   r   rK   r   rH   r   rI   r   rG   r   r   r   r   r   )r&   r   rS   r   r(   r   rA   r   r!   r   rF   r   rE   r   rK   r   rH   r   rI   r   rG   r   r   r   r   r   )
__future__r   decimalr   sqlite3r   jarvis_finance.audit.logr   jarvis_finance.imports.commonr   r   jarvis_finance.quality.alertsr	   holdingsr   r   r   r    r%   r.   r@   rR   re   rl   r{   r   r    r   r   <module>r      sF   " " " " " "             7 7 7 7 7 7 < < < < < < < < 6 6 6 6 6 6 / / / / / /    = = = =' ' ' '1 1 1 1
9 9 9 9   ( "&#!%%),0#'#'#%)#* * * * * *n $GCLL, , , , , ,^! ! ! !V $GCLL, , , , , ,r $GCLL##GCLL%); ; ; ; ; ;P $GCLL##GCLL%)K K K K K K K Kr   