
    i'                         d dl Z d dlmZ d dlmZ d dlZ ej                  e      Zde _	        e j                  j                  d      e _        d Z G d d	      Z e       Zy)
    N)current_app)Decimal      )timeoutc                  v   t         j                  j                  di       } | j                  dd      st        d       yt         j                  j                  d      }t         j                  j                  d      }|st        d       y|st        d	       y|t        _        	 t        j                  j                          t        d
       y# t        j                  j                  $ r t        d       t        d       Y yt        $ r,}t        dt        |              t        d       Y d}~yd}~ww xY w)zKValidate Stripe API configuration at startup - ONLY if payments are enabledFEATURESpaymentsFz@[INFO] Payments feature is disabled - skipping Stripe validationNSTRIPE_PUBLISHABLE_KEYSTRIPE_SECRET_KEYzP[WARNING] STRIPE_PUBLISHABLE_KEY not set - using dummy key for disabled paymentszK[WARNING] STRIPE_SECRET_KEY not set - using dummy key for disabled paymentsz)[SUCCESS] Stripe API connection validatedzL[WARNING] Stripe API credentials invalid - payment features will be disabledzR   This is normal during deployment. Payment system will work when keys are valid.z([WARNING] Stripe API connection failed: z4   Payment system will retry connection when needed.)r   configgetprintstripeapi_keyAccountretrieveerrorAuthenticationError	Exceptionstr)featurespublishable_key
secret_keyes       app/services/stripe_service.pyvalidate_stripe_configr      s    !!%%j"5H<<
E*PQ "((,,-EFO##''(;<J`a[\  FNF!9:<<++ d\]bc F8QABDEEFs   %)C 3D8D8"D33D8c                   T    e Zd ZdZd Zd ZddZddZddZd Z	dd	Z
d
 Zd Zd Zy)StripeServicezAStripe payment processing for Australian construction marketplacec                      y N selfs    r   __init__zStripeService.__init__0   s        c                 v    t         j                  s)t        j                  j	                  d      t         _        yy)z4Ensure Stripe API key is set before making API callsr   N)r   r   r   r   r   r#   s    r   _ensure_stripe_keyz StripeService._ensure_stripe_key4   s'    ~~(//334GHFN r&   Nc                    | j                          	 t        t        |            }t        |dz        }|dk  rt	        d      |dkD  rt	        d      |||xs i dd}|r||d<   t        j                  j                  di |}t        j                  d	|j                   d
| d       |S # t
        j                  j                  $ r=}	t        j                  dt        |	              t        dt        |	             d}	~	ww xY w)z.Create Stripe PaymentIntent for escrow paymentd   r   zPayment amount must be positiveiz&Payment amount exceeds maximum allowedz"RateRight Construction Job Payment)amountcurrencymetadatadescriptionidempotency_keyzCreated PaymentIntent: z for $z AUDz%Stripe error creating PaymentIntent: zPayment processing error: Nr"   )r(   r   r   int
ValueErrorr   PaymentIntentcreateloggerinfoidr   StripeErrorr   )
r$   
amount_audr,   r-   r/   amount_decimalamount_centsintent_paramsintentr   s
             r   create_payment_intentz#StripeService.create_payment_intent9   s   !	C %S_5N~34L q  !BCCh& !IJJ '$$NC	M 3B/0))00A=AFKK1&))F:,dSTM||'' 	CLL@QIJ8QABB	Cs   BB- -D
8DDc                 d   | j                          	 t        j                  j                  |      }|rit	        t        |            }t        |dz        }|j                  }||kD  rt        d| d|dz         t        j                  j                  ||      }nt        j                  j                  |      }t        j                  d|        |S # t        j                  j                  $ r=}t        j                  dt        |              t        dt        |             d}~ww xY w)	z2Capture payment from escrow when work is completedr*   zCannot capture $z! - exceeds authorized amount of $)amount_to_capturezCaptured payment: z Stripe error capturing payment: zPayment capture error: N)r(   r   r2   r   r   r   r0   r+   r1   capturer4   r5   r   r7   r   )	r$   payment_intent_idr?   r<   r9   r:   authorized_amountcapturedr   s	            r   capture_paymentzStripeService.capture_payment\   s,   !	@))223DEF !(->)?!@">C#78 %+MM!"33$*+<*==^_pqt_t^uv  "//77%&2 8 
 "//778IJKK,->,?@AO||'' 	@LL;CF8DE5c!fX>??	@s   CC D/28D**D/c                    | j                          	 ||d}|r%t        t        |            }t        |dz        |d<   t	        j
                  j                  d	i |}t        j                  d|j                   d|        |S # t        j                  j                  $ r=}t        j                  dt        |              t        dt        |             d}~ww xY w)
z.Refund payment (for disputes or cancellations))payment_intentreasonr*   r+   zCreated refund: z for PaymentIntent: zStripe error creating refund: zRefund processing error: Nr"   )r(   r   r   r0   r   Refundr3   r4   r5   r6   r   r7   r   )r$   rA   amount_to_refundrG   refund_datar9   refundr   s           r   refund_paymentzStripeService.refund_payment|   s    !	B"3 K
  !(-=)>!?(+NS,@(AH%]]))8K8FKK*699+5IJ[I\]^M||'' 	BLL9#a&BC7Ax@AA	Bs   A1B C!8CCc                    | j                          	 t        j                  j                  dd|j	                  d      d|j	                  d      |j	                  d      |j	                  d      ddd	idd	id
      }t
        j                  d|j                          |S # t        j                  j                  $ r=}t
        j                  dt        |              t        dt        |             d}~ww xY w)z5Create Stripe Connect account for contractors/workersexpressAUemail
individual
first_name	last_name)rR   rS   rP   	requestedT)card_payments	transfers)typecountryrP   business_typerQ   capabilitiesz Created Stripe Connect account: z'Stripe error creating Connect account: zAccount creation error: N)r(   r   r   r3   r   r4   r5   r6   r   r7   r   r   )r$   	user_dataaccountr   s       r   create_connect_accountz$StripeService.create_connect_account   s    !	Ann++mmG,*"+--"=!*{!;&]]73 '24%8"-t!4 , G  KK:7::,GHN||'' 	ALLB3q6(KL6s1vh?@@	As   BB" "C<?8C77C<c                    | j                          	 t        t        |            }t        |dz        }t        j
                  j                  |d||xs i       }t        j                  d|j                   d|        |S # t        j                  j                  $ r=}t        j                  dt        |              t        dt        |             d}~ww xY w)	z/Transfer payment to worker after escrow releaser*   aud)r+   r,   destinationr-   zCreated transfer: z to z Stripe error creating transfer: zTransfer error: N)r(   r   r   r0   r   Transferr3   r4   r5   r6   r   r7   r   )r$   r8   destination_account_idr-   r9   r:   transferr   s           r   transfer_to_workerz StripeService.transfer_to_worker   s    !	9$S_5N~34L--#2!R	 . H KK,X[[M>T=UVWO||'' 	9LL;CF8DE.s1vh788	9s   A/B C8CCc                 X   | j                          	 t        j                  j                  |||d      }t        j                  d|        |S # t        j                  j                  $ r=}t        j                  dt        |              t        dt        |             d}~ww xY w)z;Create Stripe Connect onboarding link for hosted onboardingaccount_onboarding)r\   
return_urlrefresh_urlrW   z%Created onboarding link for account: z'Stripe error creating onboarding link: zOnboarding link error: N)
r(   r   AccountLinkr3   r4   r5   r   r7   r   r   )r$   
account_idrg   rh   account_linkr   s         r   create_onboarding_linkz$StripeService.create_onboarding_link   s    !	@!--44"%')	 5 L KK?
|LM||'' 	@LLB3q6(KL5c!fX>??	@s   <A B),8B$$B)c                    | j                          	 t        j                  j                  |      }|j                  |j
                  |j                  |j                  |j                  |j                  dS # t        j                  j                  $ r=}t        j                  dt        |              t        dt        |             d}~ww xY w)z2Get Stripe Connect account status and capabilities)r6   charges_enabledpayouts_enableddetails_submittedrequirementsrZ   z!Stripe error retrieving account: zAccount status error: N)r(   r   r   r   r6   rn   ro   rp   rq   rZ   r   r7   r4   r   r   )r$   rj   r\   r   s       r   get_account_statusz StripeService.get_account_status   s    !	?nn--j9G jj#*#:#:#*#:#:%,%>%> ' 4 4 ' 4 4  ||'' 	?LL<SVHEF4SVH=>>	?s   A#A6 6C8CCc                 P   | j                          	 t        j                  j                  |      }t        j                  d|        |S # t        j                  j                  $ r=}t        j                  dt        |              t        dt        |             d}~ww xY w)z>Create link to Stripe Express dashboard for account managementz$Created dashboard link for account: z&Stripe error creating dashboard link: zDashboard link error: N)
r(   r   r   create_login_linkr4   r5   r   r7   r   r   )r$   rj   
login_linkr   s       r   create_dashboard_linkz#StripeService.create_dashboard_link   s    !	?99*EJKK>zlKL||'' 	?LLA#a&JK4SVH=>>	?s   8A B%(8B  B%)r_   NNr!   )Nrequested_by_customer)__name__
__module____qualname____doc__r%   r(   r=   rD   rL   r]   rd   rl   rr   rv   r"   r&   r   r   r   -   s?    KI
!CF@@B,A69*@$?&?r&   r   )r   flaskr   decimalr   logging	getLoggerrx   r4   max_network_retrieshttp_clientRequestsClientdefault_http_clientr   r   stripe_servicer"   r&   r   <module>r      sf       			8	$  #//>>r>J F@E? E?P r&   