
    )ifb                     r   d Z ddlZddlZddlmZmZmZmZmZ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mZ ddlZdd	lmZmZ dd
lmZ ddlmZ ddlmZmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m(Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: ddl;m<Z< ddlm=Z=m>Z>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZG ddl6m7Z7  ej                  eI      ZJ	 	 d+dede/de1de3ded eKd!eeK   d"e5fd#ZLdedede/d$e1d"eeeKf   f
d%ZMdede/de1de3def
d&ZNded'ee   d"dfd(ZOded)eeP   d"dfd*ZQy),z9
Payment Request services for business logic operations.
    N)OptionalListTupleAnyDictUnion)Session)IntegrityError)select)datetimetimezone)Requeststatus)get_customerget_customer_contact)APIException)generate_secure_id)get_full_nameget_device_details)AuthorizationRecordTypesPaymentTypesTransactionSourceTypesLimitationTypeInvoiceStatusTypes	LogLevels)PaymentRequestStatusTypesPaymentFrequenciesPaymentAuthorizationTypesTaxTypeSplitPaymentTypesr   )MerchantSchema)
UserSchema)"MerchantPaymentRequestCreateSchema)PaymentRequestResponseSchema)PaymentRequestAuthorizations)PaymentRequestpayment_request_attachments_map)PaymentRequestLineItems)round_half_upget_final_amount'generate_unique_payment_request_literal)PaymentRequestAdjustments)CustomerContact)PaymentRequestCustomer)PartialPaymentRequestsConfigsdbmerchantcurrent_userpayloadrequestpayment_request_created_fromcheckout_idreturnc                 	  K   	 i }g }t        |j                  xs d      }	|j                  }
t        | |j                  |j
                         d{   }t        | |j                         d{   }g }|j                  i d|j                  d|j                  d|j                  d|j                  d	|j                  d
|j                  d|j                  d|j                   d|j"                  ddd|j$                  d|j&                  d|j(                  d|j*                  d|j,                  d|j.                  d|j0                  i d|j2                  d|j4                  d|j6                  d|j8                  d|j:                  d|j<                  d|	d|j>                  d|j@                  r|j@                  ndd |jB                  d!|jD                  d"|j                  r|j                  nd#|jF                  r|jF                  nd#|jH                  |jJ                  |jL                  |jN                  |jP                  |jR                  d$d%|jT                  d&|jV                  d'|jX                  d(|jZ                  d)t\        j^                  d*di       |j                  t`        jb                  k(  r|jd                  d   j                   |d<   ne|j                  t`        jf                  k(  rH|jh                  jj                  |d<   |jh                  jl                  r|jh                  jn                  |d<   |
rtp        jr                  |d+<   tu        | ||||,       d{   \  }}|s!tw        tx        i tz        j|                  |-      t        | |||||||.       d{   }t        | |j                  |/       d{    |j                  r8t        |j                        dkD  r t        | |j                  |0       d{    |
s	 i }	 t        j                  |      }|S 7 7 7 7 7 o7 -# t        $ r" t        |d1      r|j                         n|}Y |S w xY w# tv        $ r  t        $ rI}t        j                  d2|        tw        tx        d3t        |      itz        j                  d4-      d}~ww xY ww)5a  
    Create a new payment request
    
    Args:
        db: Database session
        merchant: Merchant information
        current_user: Current user information
        payload: Payment request creation data
        request: HTTP request object
        payment_request_created_from: Source of payment request creation
        checkout_id: Optional checkout ID
        
    Returns:
        PaymentRequestResponseSchema: Created payment request
        
    Raises:
        APIException: If validation or creation fails
    r   )r0   customer_idmerchant_idN)r0   
contact_idamountcurrencypayment_frequencyauthorization_typeis_surcharge_enabledsurcharge_type	referencedue_datebilling_datesave_payment_methodT	allow_tiprequire_billing_addressrequire_sms_authorizationrequire_shipping_addressrequire_signature_authorizationrequire_cvvis_certifiedtax_typeconfigure_adjustmentmessagepayment_split_frequencydescriptiontax_percentshipping_feeenable_emailpayment_redirect_urlshipping_address_id
enable_smspayment_requests_customers )payer_idapprover_idpayer_email_request_enabledpayer_email_receipt_enabledpayer_sms_request_enabledpayer_sms_receipt_enabledapprover_email_receipt_enabledapprover_sms_receipt_enabledpayment_adjustmentspartial_paymentenable_email_receiptenable_sms_receiptpayment_typeinvoice_termsr   )r0   r3   r1   customer
created_bymoduleerrorstatus_coderO   )r0   payment_requestpayerr1   rh   r2   r3   r4   )r0   
line_itemsrn   )r0   attachmentsrn   _asdictz Error creating payment request: rl   z Failed to create payment request)Nr)   rS   is_draftr   r9   idr   rZ   updater<   r=   r>   r?   r@   rA   rB   rC   rD   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rT   rU   rV   rW   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   r   RECEIVE_PAYMENTr   SPLITsplit_config	RECURRINGrecurring_config
start_dateprorate_first_paymentprorate_dater   DRAFTsave_payment_requestr   __name__r   HTTP_400_BAD_REQUESTcreate_authorization_recordsave_line_itemsrp   rq   lensave_attachmentsr$   model_validate	Exceptionhasattrrr   loggerrl   strHTTP_500_INTERNAL_SERVER_ERROR)r0   r1   r2   r3   r4   r5   r6   payment_request_paramserrorsrS   rs   rh   ro   pm_entitiesnew_paymentreqmsgauth_recordresponsees                      `/var/www/html/hwPaymentPortal-be-dev/hw-payment-portal-api/src/apps/payment_requests/services.pycreate_payment_requestr   4   s    6z
. (*%'$W%9%9%>Q? )) &++ 
 
 +bW=M=MNN  	%% -'
gnn-'
((-'
  !:!:-'
 !'"<"<	-'

 #G$@$@-'
 g44-'
 **-'
 ((-'
 G00-'
 "4-'
 **-'
 &w'F'F-'
 ()J)J-'
 '(H(H-'
 .w/V/V-'
  7..!-'
" G00#-'
$ ((%-'
& #G$@$@'-'
( w)-'
* &w'F'F+-'
, 7..--'
. 7../-'
0 L1-'
2 G003-'
4 #GD`D`G$@$@fj5-'
6 "7#>#>7-'
8 ',,9-'
: )070@0@G,,b6=6I6Iw22r/6/R/R/6/R/R-4-N-N-4-N-N292X2X070T0T	+;-'
N "7#>#>O-'
P w66Q-'
R #G$@$@S-'
T !'"<"<U-'
V L88W-'
X TY-'
 -	` $$(:(@(@@181E1Ea1H1Q1Q":.&&*<*F*FF181I1I1T1T":.''==5<5M5M5Z5Z&z2 /H/N/N"8, %9*#%
 
 "77	  8>|W
 
 g00.
 	
 	
 3w':':#;a#?"7#6#6  
   	j3BB>RH e
 Oh
$
	
  	j3:>93U~--/[iH	j
   
7s;<CF#==6	
 	

s   SAQ< Q Q< 1Q2LQ< 9Q:A Q< :Q;Q< Q
AQ< Q	Q< )Q >Q< ?S Q< Q< Q< Q< 
Q< Q< 'Q95Q< 7S8Q99Q< <SASSSri   c                    K   |d   }|d= |d   }|d= |d   }|d= t        di |t        dd      |j                  |j                  t        | d      t	        j
                  t        j                        t	        j
                  t        j                        d	}| j                  |       | j                          | j                  |       |rt        |d
      r|j                         j                         n|j                         }	d}
|	j                  d      r	 d|	v r|	d= t        di |	|j                  |
r|
j                  ndd}| j                  |       | j                          |r{t        |d
      r|j                         j                         n|j                         }d|v r|d= t!        di |d|j                  i}| j                  |       | j                          d}d}|j                  d      rot#        t$              j'                  t$        j(                  |d   k(  t$        j*                  |j                  k(        }| j-                  |      }|j/                         }|j                  d      rot#        t$              j'                  t$        j(                  |d   k(  t$        j*                  |j                  k(        }| j-                  |      }|j/                         }t1        |j                  |j                  |r|j                  nd|r|j                  nd|j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  dd      |rdnd      }| j                  |       | j                          | j                  |       | j                  |       t2        j5                  d|j6                   d|j                          |dfS w)z Save payment request to databaserX   rb   rc   pr   prependlength	   )r0   r   )payment_request_idr:   created_by_idpayment_request_literal
created_at
updated_atdictNdiscount_id)r   r   calculated_valuer   rZ   r[   r\   Fr]   r^   r_   r`   ra   T)r   r9   rZ   r[   r\   r]   r^   r_   r`   ra   is_approver_approvedzPayment request z# created successfully for merchant zPayment Request created )r&   r   rt   r+   r   nowr   utcaddcommitrefreshr   r   copygetr,   r/   r   r-   wherer;   r9   executescalar_one_or_noner.   r   infor   )r0   r3   r1   rh   ri   payment_customer_payloadrb   rc   rn   new_adjustmentget_discount_idpayment_request_adjustmentpartial_payment_dictpayment_request_partial_detailsro   approver
payer_stmtpayer_resultapprover_stmtapprover_resultnew_payment_customers                        r   r   r     s      ''CD,-!"78%&/0O!" % 
-d2FKK mm G2VW X<<-<<-O FF?IIKJJ  ?FFY[a>b,11388:h{  iA  iA  iC m,N*}-%> &
&
.11.=**4&
"
 	)*
		 @GY_@`335::<fufzfzf|!55$%78*G +
"+
.11+
' 	./
		 EH##J/O,22&&*B:*NN''8;;6

 zz*-//1##M2/55&&*B=*QQ''8;;6
 **]3"5571*--KK"#+HKK$<$@$@A^`e$f$<$@$@A^`e$f":">">?Z\a"b":">">?Z\a"b'?'C'CDdfk'l%=%A%AB`bg%h&.UD FF IIKJJ#$JJ
KK"?#E#E"FFijrjujuivwx555s   PPc                   K   	 t        j                  |j                  j                        }|j                  j                  dd      }	t        |	      }
t        dd      }dt        d      j                          }|||j                  |j                  |j                  |j                  |j                  t        j                  t        j                  t        j                        ||j                  j                  |j                  j                  dd      t!        |      |j"                  t        j                  t        j                        j%                         |
j                  d	      |
j                  d
      |
j                  d      |
j                  d      dt&        j(                  dt        j                  t        j                        t        j                  t        j                        d}|j*                  t,        j.                  k(  r@|j0                  rt        j2                  |d<   n%|j4                  rt        j6                  |d<   nd|d<   t9        di |}| j;                  |       | j=                          | j?                  |       |S # t@        $ rI}tB        jE                  d|        tG        tH        dtK        |      itL        jN                  d      d}~ww xY ww)z/Create authorization record for payment requestz
user-agentrY   authr   r   zAUTH-   )r   osdeviceplatformbrowser)ip_addr
user_agentr2   current_user_id	timestampr   r   r   r   origin
txn_source)authorization_idauthorization_literalrZ   r:   r9   r   merchant_signer_idr?   authorization_date
ip_addressauth_metadatar   r   r?   Tis_verifiedz%Error creating authorization record: rl   z%Failed to create authorization recordrj   Nr   )(socketgethostbynameclienthostheadersr   r   r   upperrt   r   CHECKBOXr   r   r   r   r   user_idr   r   APIr?   r   REQUEST_AUTHrH   SMSrJ   	SIGNATUREr%   r   r   r   r   r   rl   r   r   r   r   r   )r0   rn   ro   r1   rh   r2   r3   r4   r   user_agent_stringdevice_detailsr   r   auth_payloadr   r   s                   r   r   r     sR    T
))'..*=*=>
#OO//bA+,=> .fRH"'(:!(D(J(J(L'M N !1%:#;;#;;"1"4"4".//":"C"C"*,,x||"<$">>..%oo11,C -l ;#/#7#7%\\(,,7AAC$((.(,,X6*..z:)--i8488 #,,x||4",,x||43
: --1J1W1WW005M5Q5Q12885M5W5W12)-L' 3B\B
{
		


;.  
<QC@ACF#==;	
 	

s*   K-JJ K-	K*!AK%%K**K-rp   c                   K   	 |t        |      dkD  rt        |      D ]?  \  }}t        |j                  dd            }t	        |j                  dd            }t        |j                  dd            }t        |j                  dd            }||z  }	|j                  d      d	k(  r|n|	|z  d
z  }
|	|
z
  }|dkD  r||z  d
z  nd}|j                  dd      |j                  d      ||||||j                  d      |j                  dd      |j                  dd      |dz   |j                  d      |j
                  d}t        di |}| j                  |       B | j                          t        j                  dt        |       d|j                          ydd|j                  ddddddd|j
                  d}t        di |}| j                  |       | j                          t        j                  d|j                          y# t        $ rV}t        j                  d|j                   d|        t        t         dt#        |      it$        j&                  d      d}~ww xY ww)z#Save line items for payment requestNr   
unit_pricequantity   taxdiscountdiscount_typer<   d   titlerY   rQ   costupcharge
product_id)r   rQ   r   r   r   
tax_amountr   r   r   r   display_orderr   r   Saved z  line items for payment request zQuick Chargez+Payment request without specific line items)r   rQ   r   r   r   r   r   r   r   r   r   z3Created quick charge line item for payment request z,Error saving line items for payment request : rl   zFailed to save line itemsrj   r   )r   	enumeratefloatr   intrt   r(   r   r   r   r   r   r<   r   rl   r   r   r   r   r   )r0   rp   rn   indexitemr   r   rR   r   subtotaldiscount_amounttaxable_amountr   line_item_data	line_itemquick_charge_dataquick_charge_itemr   s                     r   r   r     st    D
!c*o&9(4 "t"488L!#<=
txx
A67#DHHUA$67 *a!89 &0.2hh.G8.S(ZbemZmpsZs!)O!;CNQR?^k9C?XY
 "XXgr2#'88M#:", (&", (%)XXo%> HHVQ/ $Q 7%*QY"&((<"8*9*<*<"" 4EnE	y!?"B IIKKK&Z 11QRaRtRtQuvw
 (L-44!"&5&8&8! !8 L:K LFF$%IIKKKMoNpNpMqrs 
CODfDfCggijkilmnCF#==/	
 	

s7   I6FH "I6#A0H I6	I3AI..I33I6rq   c                   K   	 |D ]B  }t        j                         j                  |j                  |      }| j	                  |       D | j                          t        j                  dt        |       d|j                          y	# t        $ rV}t        j                  d|j                   d|        t        t        dt        |      it        j                   d      d	}~wt"        $ rV}t        j                  d
|j                   d|        t        t        dt        |      it        j$                  d      d	}~ww xY ww)z Save payment request attachments)r   file_idr   z! attachments for payment request z7Integrity error saving attachments for payment request r   rl   z,Attachment already exists or invalid file IDrj   Nz-Error saving attachments for payment request zFailed to save attachments)r'   insertvaluesrt   r   r   r   r   r   r   r
   rl   r   r   r   r   r   r   r   )r0   rq   rn   r   insert_stmtr   s         r   r   r   /  s8    
" 	$G9@@BII#2#5#5 J K JJ{#	$ 			fS-..OP_PrPrOstu 
NOqOqNrrtuvtwxyCF#33B	
 	
  
D_EgEgDhhjkljmnoCF#==0	
 	

s7   E	BB
 	E	
	EAC$$E0AEEE	)USERN)R__doc__base64r   typingr   r   r   r   r   r   sqlalchemy.ormr	   sqlalchemy.excr
   
sqlalchemyr   r   r   fastapir   r   loggingsrc.apps.customers.servicesr   r   src.core.exceptionsr   src.apps.base.utils.functionsr   )src.apps.payment_requests.utils.functionsr   r   src.core.utils.enumsr   r   r   r   r   r   src.apps.payment_requests.enumsr   r   r   r   r    StatusTypes*src.apps.merchants.schemas.merchant_commonr!   "src.apps.users.schemas.user_commonr"   *src.apps.payment_requests.schemas.requestsr#   +src.apps.payment_requests.schemas.responsesr$   ?src.apps.payment_requests.models.payment_request_authorizationsr%   0src.apps.payment_requests.models.payment_requestr&   r'   ;src.apps.payment_requests.models.payment_request_line_itemsr(   r)   r*   r+   <src.apps.payment_requests.models.payment_request_adjustmentsr,   *src.apps.customers.models.customer_contactr-   9src.apps.payment_requests.models.payment_request_customerr.   @src.apps.payment_requests.models.partial_payment_request_configsr/   	getLoggerr   r   r   r   r   r   r   r   r   r       r   <module>r     s     : : " )  ' #  J , < W   F 9 Y T h l _ ~ ~ b F \ j h			8	$ )/!%U
U
U
 U
 0	U

 U
 #&U
 #U
 "U
tk6k6k6*8k6$k6 38_k6n[
[
3A[
&[
1S[
 [
@F
g F
8D> F
W[ F
T
w 
T#Y 
TX 
r  