
    i                         d dl Z d dlmZmZmZ ddlmZ ddlmZm	Z	 d dl
Z
 e
j                  e      Z G d dej                        Zd Zd	 Zd
 Zd Zy)    N)requestjsonifycurrent_app   )db)PaymentContractc                   R   e Zd ZdZdZ ej                  ej                  d      Z ej                   ej                  d      ddd      Z
 ej                   ej                  d            Z ej                  ej                  ej                  j                         	      Zd
 Zy)ProcessedWebhookEventz;Track processed Stripe webhook events to prevent duplicatesprocessed_webhook_eventsT)primary_key   F)uniquenullableindexd   )defaultc                 "    d| j                    dS )Nz<ProcessedWebhookEvent >)stripe_event_id)selfs    'app/blueprints/legal/stripe_webhooks.py__repr__zProcessedWebhookEvent.__repr__   s    ()=)=(>a@@    N)__name__
__module____qualname____doc____tablename__r   ColumnIntegeridStringr   
event_typeDateTimefuncnowprocessed_atr    r   r   r   r   
   s    E.M	2::4	0Bbii			#teSWXO9299S>*J299R[["''++-@LAr   r   c                     t        j                         } t         j                  j                  d      }	 t        j
                  j                  | |t        j                  d         }	 t        |d	   |d
         }t        j                   j#                  |       t        j                   j%                          |d
   dk(  r|d   d   }t1        |       nS|d
   dk(  r|d   d   }t3        |       n7|d
   dk(  r|d   d   }t5        |       nt        j/                  d|d
           t        ddi      dfS # t        $ r' t        j                  d       t        ddi      dfcY S t        j                  j                  $ r' t        j                  d       t        ddi      dfcY S w xY w# t&        $ r}t        j                   j)                          dt+        |      j-                         v sdt+        |      j-                         v r0t        j/                  d|d	    d       t        ddi      dfcY d}~S t        j                  d|        Y d}~d}~ww xY w)z*Handle Stripe webhooks for payment updateszStripe-SignatureSTRIPE_WEBHOOK_SECRETz!Invalid payload in Stripe webhookerrorzInvalid payloadi  z#Invalid signature in Stripe webhookzInvalid signaturer"   type)r   r$   r   	duplicatezWebhook event z already processed, ignoringstatusalready_processed   Nz)Failed to store processed webhook event: zpayment_intent.succeededdataobjectzpayment_intent.payment_failedzpayment_intent.canceledzUnhandled Stripe event type: success)r   get_dataheadersgetstripeWebhookconstruct_eventr   config
ValueErrorloggerr,   r   SignatureVerificationErrorr   r   sessionaddcommit	Exceptionrollbackstrlowerinfohandle_payment_succeededhandle_payment_failedhandle_payment_canceled)payload
sig_headereventprocessed_eventepayment_intents         r   handle_stripe_webhookrP      s"    G$$%78J	<..Z!3!34K!L
J/!$KV}
 	

'


 V}22vx0 0	v9	9vx0n-	v3	3vx0/ 	3E&M?CDHi()3..S  :89!234c99<<22 <:;!456;;<  J


s1v||~%A)FKK.t5QRSH&9:;S@@LLDQCHIIJs>   2D6 (AF+ 6-F(%A F('F(+	I4A>I2I8IIc                 V   	 t         j                  j                  | d         j                         j	                         }|r|j
                  dvrSd|_        | d   |_        t        j                  j                          t        j                  d|j                   d       yt        j                  d|j                   d|j
                   d	       yy# t        $ rI}t        j                  d
t        |              t        j                  j!                          Y d}~yd}~ww xY w)z*Handle successful payment - move to escrowr"   stripe_payment_intent_id)held_escrowtransferredrefundedrT   r/   Payment z moved to escrowz already in state z
, skippingz Error handling payment success: N)r   query	filter_bywith_for_updatefirstr/   stripe_statusr   r?   rA   r=   rF   payment_referencerB   r,   rD   rC   rO   paymentrN   s      r   rG   rG   J   s    --))%3D%9 * 

/
EEG 	 ~~%OO!.(6x(@%

!!#hw'@'@&AAQRShw'@'@&AAST[TbTbSccmno   7Ax@A


s   B!C $0C 	D(?D##D(c                    	 t         j                  j                  | d         j                         }|rSd|_        | d   |_        t        j                  j                          t        j                  d|j                   d       yy# t        $ rI}t        j                  dt        |              t        j                  j                          Y d}~yd}~ww xY w)	zHandle failed paymentr"   rR   failedr/   rW   z failedz Error handling payment failure: N)r   rX   rY   r[   r/   r\   r   r?   rA   r=   warningr]   rB   r,   rD   rC   r^   s      r   rH   rH   `   s    --))%3D%9 * 

%' 	 %GN$28$<G!JJNNXg&?&?%@HI   7Ax@A


   BB	 		C?CCc                    	 t         j                  j                  | d         j                         }|rSd|_        | d   |_        t        j                  j                          t        j                  d|j                   d       yy# t        $ rI}t        j                  dt        |              t        j                  j                          Y d}~yd}~ww xY w)	zHandle canceled paymentr"   rR   canceledr/   rW   z	 canceledz%Error handling payment cancellation: N)r   rX   rY   r[   r/   r\   r   r?   rA   r=   rF   r]   rB   r,   rD   rC   r^   s      r   rI   rI   r   s    --))%3D%9 * 

%' 	 'GN$28$<G!JJKK(7#<#<"=YGH   <SVHEF


rc   )r8   flaskr   r   r   
extensionsr   modelsr   r	   logging	getLoggerr   r=   Modelr   rP   rG   rH   rI   r)   r   r   <module>rl      sP     / /  & 			8	$
ABHH 
A2/h,$r   