
    i[                     ,   d dl mZmZ d dlmZmZ d dlmZmZmZ d dl	Z	d dl
Z
ddlmZ ddlmZmZmZmZmZ dd	lmZmZmZ dd
lmZmZmZmZmZ dZ e	j<                  e      Z  ejB                  ddg       e       d               Z" ejB                  ddg       e       d               Z# ejB                  ddg       ejH                  d      d               Z% ejB                  ddg       e       d               Z& ejB                  ddg       e       d               Z' ejB                  ddg       e       d               Z( ejB                  ddg       e       d               Z) ejB                  ddg       e       d                Z* ejB                  d!dg       ejH                  d"      ejV                  d#                      Z, ejB                  d$dg       e       d%               Z- ejB                  d&dg      d'        Z.y)(    )requestjsonify)jwt_requiredget_jwt_identity)datetimedate	timedeltaN   )legal_bp   )ContractPaymentInvoiceJobUser)dblimitercsrf)calculate_gstgenerate_payment_referencecalculate_withholding_taxvalidate_contract_termscalculate_total_with_gsti@B z
/contractsPOST)methodsc                     	 t               } t        j                         }g d}|D ]'  }|j                  |      rt	        d| di      dfc S  t
        j                  j                  |d         }|r|j                  | k7  rt	        ddi      dfS t        j                  j                  |d         }|r|j                  d	k7  rt	        dd
i      dfS t        j                  |d   d      j                         }t        j                  |d   d      j                         }t        ||t        |d               \  }}	|st	        d|	d      dfS t        |d   | |d   |d   |j                  dd      |||d   |j                  dd      |j                  d      
      }
t         j"                  j%                  |
       t         j"                  j'                          t	        d|
j(                  |
j*                  t        |
j,                        |
j.                  j1                         |
j2                  j1                         |
j4                  |
j7                         dd      dfS # t8        $ r%}t	        ddt;        |       i      dfcY d}~S d}~wt<        $ rC}t         j"                  j?                          t	        ddt;        |       i      dfcY d}~S d}~ww xY w) z1Create new contract between contractor and worker)job_id	worker_idagreed_rate
start_dateend_datescope_of_workerror is required  r   zJob not found or unauthorized  r   workerzInvalid workerr    z%Y-%m-%dr!   r   zContract validation failedr#   details	rate_typetotalr"   payment_terms
completionpayment_schedule)
r   contractor_idr   r   r*   r    r!   r"   r,   r.   zContract created successfully)idr   r   r    r!   statustotal_value)messagecontract   zInvalid date format: NzContract creation failed:   ) r   r   get_jsongetr   r   queryr/   r   roler   strptimer   r   floatr   r   sessionaddcommitr0   r   r   r    	isoformatr!   r1   calculate_total_value
ValueErrorstr	Exceptionrollback)current_user_iddatarequired_fieldsfieldjobr'   r    r!   is_validvalidation_errorsr4   es               app/blueprints/legal/routes.pycreate_contractrO      s   AN*,! l$ 	GE88E?E7,)?@A3FF	G
 iimmDN+c''?:G%DEFKK [ 120G%567<< &&tL'9:FKKM
$$T*%5zBGGI '>%](;"<'
## %AN_`acfff >);']+hh{G4!/((?LA!XX&89
 	

x 


6kk"//$X%9%9:&11;;=$--779"//'==?
   	  I#8Q!ABCSHH N


#=c!fX!FGH#MMNsP   8I$ I$ AI$ AI$ A;I$ DI$ $	K-JKK8KKKz!/contracts/<int:contract_id>/signPUTc                    	 t               }t        j                  j                  |       }||j                  |j
                  fvrt        ddi      dfS |j                  |k(  r!d|_        t        j                         |_
        n/|j
                  |k(  r d|_        t        j                         |_        |j                         rd|_        t        j                   j#                          t        d|j                  |j                         d      S # t$        $ rC}t        j                   j'                          t        ddt)        |       i      d	fcY d
}~S d
}~ww xY w)z$Sign contract (contractor or worker)r#   z"Unauthorized to sign this contract  TsignedzContract signed successfully)r3   contract_statusfully_signedzContract signing failed: r6   N)r   r   r9   
get_or_404r/   r   r   contractor_signedr   utcnowcontractor_signed_dateworker_signedworker_signed_dateis_fully_signedr1   r   r=   r?   rD   rE   rC   contract_idrF   r4   rM   s       rN   sign_contractr_   ^   s3   M*,>>,,[9 8#9#98;M;M"NNG%IJKSPP !!_4)-H&.6oo.?H+?2%)H"*2//*;H' ##%&HO


5'$446
  	  M


#<SVH!EFGLLMs%   AD B:D 	E8EEEz	/paymentsz10 per hourc                     ddl m}  | j                  s5t        j	                  dt
        j                          t        ddi      dfS t        t        j                               }	 ddlm} dd	l}| j                  }t        j                  d
|        t        j                          }ddg}|D ]'  }|j#                  |      rt        d| di      dfc S  |d   }	 t$        j&                  j)                  |      j+                         j-                         }	|	r|	j.                  |k7  rt        ddi      dfS |	j0                  dv rt        dd|	j0                   di      dfS |	j2                  rt        ddi      dfS t4        j&                  j7                  t4        j8                  |	j                  k(  t4        j0                  j;                  g d            j+                         j-                         }
|
rt        ddi      dfS t5        |	j                  t=               dd      }|	|_        |jA                          tB        jD                  jG                  |       tB        jD                  jI                          	 |jK                         xs |jL                  |_&        |jK                          |jN                  jQ                  dd|j                  |	j                  |jR                  ddd|      }t        j                  d |j                          |j                  |_-        t]        j^                         |_0        	 dd$l1m2}  |d%|	j                  d&d'(      }|jN                  jg                  |j                  |d   || d)*      }t        j                  d+|j0                          |j0                  |_5        |j0                  d/v rd0|_        t]        j^                         |_6        d&|	_        d0|	_7        |	jq                         r#d1|	_        t        j                  d2| d3       	 dd4l9m:} dd5l;m<} dd$l1m2} |j{                  |	j|                  |j~                  d6d7|	j                  j                   d8d9d: |d;|	j                  d&<      =       n|j0                  d?k(  rJd?|_        tB        jD                  ji                          t        d&|j                  |j                  d@      dAfS d-|_        tB        jD                  ji                          t        dB|j0                  dC      dfS tB        jD                  ji                          t        dD|j                  |jR                  dEdFdG|j0                  dH|	j                  |	j0                  dIdJ      dKfS # tT        $ rY}t        jW                  d!|        tB        jD                  jY                          t        d"t        |      d#      dfcY d	}~S d	}~ww xY w# tT        $ r`}t        jW                  d,|        d-|_        tB        jD                  ji                          t        d.t        |      d#      dfcY d	}~S d	}~ww xY w# tT        $ r#}t        jW                  d>|        Y d	}~cd	}~ww xY w# tT        $ r<}tB        jD                  jY                          t        jW                  dL|         d	}~ww xY w# tT        $ rf}tB        jD                  jY                          t        jW                  dMt        |       d&N       t        ddMt        |       i      dOfcY d	}~S d	}~ww xY w)Pz.Process $50 flat hiring fee payment via Striper   )current_userz)Unauthenticated payment attempt from IP: r#   zAuthentication requiredi  r   stripe_serviceNz%Hiring fee payment initiated by user r^   payment_method_idr$   r%   )r0   z"Contract not found or unauthorizedr&   )	cancelled	completeddisputedz-Cannot process payment - contract status is ''z)Hiring fee already paid for this contract)pending_paymentheld_escrowpaidz(Payment already exists for this contractri   )r^   payment_referencedispute_period_daysr1   i|  aud
hiring_fee)
payment_idr^   rl   typezRateRight Hiring Fee)amountcurrencymetadatadescriptionidempotency_keyzStripe PaymentIntent created: z Failed to create PaymentIntent: zFailed to create payment intentr(   )url_forpayment_return_handlerThttps)r^   	_external_schemez-confirm)payment_method
return_urlrv   zPayment confirmed, status: zPayment confirmation failed: payment_failedzPayment confirmation failed)	succeededrequires_capturerk   activez	Contract z# activated after hiring fee payment)notification_service)NotificationTypezContract is Now Active!zThe contract for 'z$' is now active. You can start work!r
   r4   contract_review)r^   rz   )user_idnotification_typetitlecontentprioritycategory
action_urlz(Failed to send activation notification: requires_action)r   payment_intent_client_secretpayment_intent_id   zPayment failed)r#   r1   z1Hiring fee paid successfully - contract activatedg     K@g      I@g      @)r0   rl   gross_amountplatform_fee
gst_amountr1   )r0   r1   )r3   paymentr4   r5   zDatabase error during payment: zPayment processing failed: )exc_infor6   )Cflask_loginra   is_authenticatedloggerwarningr   remote_addrr   rC   uuiduuid4services.stripe_servicerc   striper0   infor7   r8   r   r9   	filter_bywith_for_updatefirstr/   r1   hiring_fee_paidr   filterr^   in_r   r4   calculate_amountsr   r=   r>   flush_ensure_stripe_keyapi_keyPaymentIntentcreaterl   rD   r#   rE   stripe_payment_intent_idr   rX   date_initiatedflaskrw   confirmr?   stripe_statusdate_held_escrowpayment_statusr\   !app.services.notification_servicer   app.models.notificationr   send_notificationr   CONTRACT_AWARDEDrJ   r   client_secret)ra   rv   rc   r   rF   rG   rH   rI   r^   r4   existing_paymentr   intentintent_errorrw   r}   confirmed_intentstripe_errorr   r   rM   db_errors                         rN   process_stripe_paymentr      s    )((B7CVCVBWXY!:;<cAA$**,'OcO=&//;O;LMN!(*=>$ 	GE88E?E7,)?@A3FF	G =)N	~~//;/?OOQWWYHx55H)MNOQTTT"HH+XYaYhYhXiij)klmorrr'')TUVX[[[  '}}33##x{{2""#MN  o 
  )STUWZZZ $KK"<">$%(	G  (G%%'JJNN7#JJp!/!B!B!D!V113--44"&-jj'/{{-4-F-F ,	 !7$3 5  <VYYKHI 06yyG,%-__%6G"l)$%=08.2,35

 $*#7#7#?#?II#'(;#<)'6&7x$@	 $@ $  9:J:Q:Q9RST %5$;$;G!&&*KK!'+3??+<(+/(*0' ++-&.HOKK)K=8[ \]UZL1,>>$,$6$6.>.O.O";&89K9K8LLp$q%&%/'./@hkkei'j ?  "((,==!2

!!#'+4D4R4R)9)<)<   	  "2

!!#)9EUE\E\]^`cccJJN!**)0)B)B$)$)"&%nn #++&oo   Q  p?~NO

##%)JWZ[gWhijlooop.  l<\NKL!1

!!#)FSVWcSdefhkkk	l> % U'OPQs%STTUD  	JJ!LL:8*EF	
  O


23q6(;dK#>s1vh!GHI3NNOs  &A[! [! [! AZ :*Z %Z  BZ A5Z =BV *Z  A-W> -A>Z ,A)Y* AZ />Z .A*Z 	W;"AW60W;1Z 6W;;Z >	Y'AY"Y'Z "Y''Z *	Z3ZZ ZZ 	["7[[[! !	]*A]]]z)/contract/<int:contract_id>/mark-completec                 |   	 t               }t        j                  j                  |       }|j                  |k7  rt        ddi      dfS |j                  dk7  rt        ddi      dfS d|_        |j                  j                  d	      j                         }|rd
|_        d|_
        t        j                  j                          t        d|j                  |r|j                  ndd      dfS # t        $ rC}t        j                  j                          t        ddt!        |       i      dfcY d}~S d}~ww xY w)z&Worker marks contract work as completer#   z)Only the worker can mark work as completerR   r   z(Contract must be active to mark completer%   pending_reviewrj   r1   pending_releaseTz4Work marked as complete - awaiting contractor reviewN)r3   rT   r   r   zFailed to mark complete: r6   )r   r   r9   rV   r   r   r1   paymentsr   r   release_conditions_metr   r=   r?   rD   rE   rC   )r^   rF   r4   r   rM   s        rN   mark_contract_completer   5  s3   M*,>>,,[9 0G%PQRTWWW??h&G%OPQSVVV + ##--]-CIIK.GN-1G*


M'07gnnT
  	 	  M


#<SVH!EFGLLMs+   AC/ 	C/ 'BC/ /	D;88D60D;6D;z./contract/<int:contract_id>/approve-completionc                    	 t               }t        j                  j                  |       }|j                  |k7  rt        ddi      dfS |j                  dk7  rt        ddi      dfS |j                          t        j                  j                          t        d|j                  d      d	fS # t        $ rC}t        j                  j                          t        dd
t        |       i      dfcY d}~S d}~ww xY w)zRContractor approves work completion (no escrow release needed with flat fee model)r#   z*Only the contractor can approve completionrR   r   )Contract is not pending completion reviewr%   z/Work approved - contract completed successfully)r3   rT   r   zFailed to approve completion: r6   N)r   r   r9   rV   r/   r   r1   mark_as_completedr   r=   r?   rD   rE   rC   r]   s       rN   approve_contract_completionr   [  s    R*,>>,,[9!!_4G%QRSUXXX??..G%PQRTWWW 	""$


H'
   	
  R


#A#a&!JKLcQQRs+   AB/ 	B/ 'AB/ /	C;88C60C;6C;z./contract/<int:contract_id>/dispute-completionc                    	 t               }t        j                         }t        j                  j                  |       }|j                  |k7  rt        ddi      dfS |j                  dk7  rt        ddi      dfS |j                  dd      }d	|_        |j                  j                  d
      j                         }|rd	|_        t        j                  j                          t        d|j                  |dd      dfS # t         $ rC}t        j                  j#                          t        ddt%        |       i      dfcY d}~S d}~ww xY w)z#Contractor disputes work completionr#   z*Only the contractor can dispute completionrR   r   r   r%   reasonzWork does not meet requirementsrg   r   r   z2Completion disputed - contract requires resolutionz/Contact support or resolve directly with worker)r3   rT   dispute_reason
next_stepsr   zFailed to dispute completion: r6   N)r   r   r7   r   r9   rV   r/   r   r1   r8   r   r   r   r   r=   r?   rD   rE   rC   )r^   rF   rG   r4   r   r   rM   s          rN   dispute_contract_completionr   x  sG   "R*,!>>,,[9 !!_4G%QRSUXXX??..G%PQRTWWW(,MN % ##--5F-GMMO'GN


K',K	
 
  	  R


#A#a&!JKLcQQRs+   AD D ;BD 	E
8EEEz"/contract/<int:contract_id>/cancelc                 J   	 ddl m} t               }t        j                         }t
        j                  j                  |       }|j                  |k7  r|j                  |k7  rt        ddi      dfS |j                  dv rt        ddi      dfS |j                  d	d
      }|j                  j                  d      j                         }|r7|j                   r+|j#                  |j                   d      }d|_        d|_        d|_        t&        j(                  j+                          t        d|j                  |r|j                  dk(  nd|d      dfS # t,        $ rC}t&        j(                  j/                          t        ddt1        |       i      dfcY d}~S d}~ww xY w)z0Cancel contract and refund payment if applicable   rb   r#   z$Unauthorized to cancel this contractrR   )rf   re   zContract cannot be cancelledr%   r   zContract cancelled by agreementrj   r   requested_by_customer)r   refundedre   zContract cancelled successfullyF)r3   rT   payment_refundedcancellation_reasonr   zFailed to cancel contract: r6   N)r   rc   r   r   r7   r   r9   rV   r/   r   r   r1   r8   r   r   r   r   refund_paymentr   r   r=   r?   rD   rE   rC   )	r^   rc   rF   rG   r4   r   r   refundrM   s	            rN   cancel_contractr     s   *O<*,!>>,,[9 !!_49K9K9^G%KLMsRR??88G%CDEsJJ"hhx1RS ##--]-CIIKw77#2200. 3 F (GN$.G! &


8'@G* <U#6	
 
  	  O


#>s1vh!GHI3NNOs+   A/E 2E CE 	F"8FF"F"z!/payments/<int:payment_id>/statusGETc                 L   	 t               }t        j                  j                  |       }|j                  }|j
                  |k7  r|j                  |k7  rt        ddi      dfS t        |j                  |j                  |j                  t        |j                        t        |j                        t        |j                        |j                  j!                         |j"                  r|j"                  j!                         nd|j$                  r|j$                  j!                         nd|j&                  r|j&                  j!                         nd|j(                  d|j                  d      dfS # t*        $ r%}t        ddt-        |       i      d	fcY d}~S d}~ww xY w)
z&Get current payment status and detailsr#   z!Unauthorized to view this paymentrR   N)r0   	referencer1   r   r   net_to_workerr   r   date_releaseddispute_deadliner   )r   rT   r   zFailed to get payment status: r6   )r   r   r9   rV   r4   r/   r   r   r0   rl   r1   r<   r   r   r   r   r@   r   r   r   r   rD   rC   )rp   rF   r   r4   rM   s        rN   get_payment_statusr     st   R*,--**:6## !!_49K9K9^G%HIJCOOjj$66!.. %g&:&: ; %g&:&: ;!&w'<'<!=")"8"8"B"B"DLSLdLdG$<$<$F$F$HjnFMF[F[!6!6!@!@!BaeLSLdLdG$<$<$F$F$Hjn!(!6!6  (
   	"  R#A#a&!JKLcQQRs%   A!E5 $DE5 5	F#>FF#F#z/stripe/webhookz100 per minutec                      ddl m}   |        S )zHandle Stripe webhooksr
   handle_stripe_webhook)stripe_webhooksr   r   s    rN   stripe_webhookr     s    
 7 ""    z	/invoicesc                     	 t               } t        j                         }|j                  d      st	        ddi      dfS t
        j                  j                  |d         }|st	        ddi      dfS |j                  }|j                  | k7  rt	        ddi      dfS t        j                  j                  |j                        }|j                  st	        dd	i      dfS |j                         }|st	        dd
i      dfS t        j                  j                          t	        d|j                  |j                   t#        |j$                        t#        |j&                        t#        |j(                        |j*                  j-                         |j.                  |j0                  dd      dfS # t2        $ rC}t        j                  j5                          t	        ddt7        |       i      dfcY d}~S d}~ww xY w)zGenerate GST-compliant invoicerp   r#   zpayment_id is requiredr%   zPayment not foundr&   z%Only the worker can generate invoicesrR   z/Worker must be GST registered to issue invoiceszQFailed to generate invoice. Invoice may already exist or payment data is invalid.z"GST invoice generated successfully)r0   invoice_numberamount_ex_gstr   total_amountdue_datesupplier_abn	buyer_abn)r3   invoicer5   zInvoice generation failed: r6   N)r   r   r7   r8   r   r   r9   r4   r   r   gst_registeredauto_generate_invoicer   r=   r?   r0   r   r<   r   r   r   r   r@   r   r   rD   rE   rC   )rF   rG   r   r4   r'   r   rM   s          rN   generate_invoicer     s   .O*,!xx%G%=>?DD--##D$67G%89:C??## 0G%LMNPSSS  2 23$$G%VWXZ]]] //1G%xyz|


;jj")"8"8!&w'<'<!=#G$6$67 %g&:&: ;#,,668 ' 4 4$..	
   	  O


#>s1vh!GHI3NNOs=   =F2  2F2 3)F2 AF2 ! F2 B/F2 2	G>;8G93G>9G>z/validate-abnc            	         	 t        j                         } | j                  d      }|st        ddi      dfS ddlm}  ||      }t        j                  j                  |      j                         }|r|j                  nd}| }t        ||||t        |      d	      S # t        $ r%}t        dd
t        |       i      dfcY d}~S d}~ww xY w)z#Validate Australian Business Numberabnr#   zABN is requiredr%   r   )validate_abn)
abn_numberF)r   rK   r   withholding_tax_requiredregistered_userzABN validation failed: r6   N)r   r7   r8   r   utils.validatorsr   r   r9   r   r   r   boolrD   rC   )rG   r   r   rK   userr   withholding_requiredrM   s           rN   r   r   3  s    K!hhuoG%678#==4$ zz##s#399;04,,% $21 ,(<#Dz
  	  K#:3q6(!CDEsJJKs#   5B! A(B! !	C*C
C
C)/r   r   r   flask_jwt_extendedr   r   r   r   r	   loggingr    r   modelsr   r   r   r   r   
extensionsr   r   r   utils.compliancer   r   r   r   r   MAX_PAYMENT_AMOUNT_AUD	getLogger__name__r   routerO   r_   limitr   r   r   r   r   r   exemptr   r   r    r   rN   <module>r     s{   " = . .    ; ; + +  ! 			8	$ vh/CN  0CNL 3eWE M  F MF fX.}mO  /mO` ;fXN!M  O!MH @6(SR  TR6 @6(S$R  T$RN 4vhG,O  H,O^ 3eWER  FRB !F84 #  ! 5# fX.0O  /0Of &2K 3Kr   