o
    -hv0                     @   s$  d dl mZmZ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lmZ d dlmZ d dlmZ d d	lmZ d d
lZd d
lZd dlmZ ddlmZmZ ddlmZ eeZ edd Z!edd Z"edd Z#e
edgdd Z$edd Z%edd Z&edd Z'dd Z(d
S )     )renderredirectget_object_or_404)login_required)JsonResponseHttpResponse)csrf_exempt)require_http_methods)messages)reverse)timezone)	timedeltaN)Tenant   )SubscriptionMpesaPayment)MpesaAPIc                 C   s\   | j j }|r|j}dddg dddddg d	dd
ddg ddg}t| d||dS )zDisplay subscription plansBasicbasic  )z1 Shopz3 UserszBasic ReportszEmail Support)namecodepricefeaturesStandardstandard  )z3 Shopsz10 UserszAdvanced ReportszPhone SupportzMulti-location SupportPremiumpremium'  )zUnlimited ShopszUnlimited UserszAll ReportszPriority Supportz
API AccesszCustom Featureszbilling/subscription_plans.html)planscurrent_tenant)usertenant_membershipsfirsttenantr   )requestr%   r     r'   "/var/www/html/pos/billing/views.pysubscription_plans   s.   'r)   c                 C   s  | j dkr| jj }|r|jdvrt| d tdS |j}| j	
d}|s1t| d tdS ddd	d
}|
|}|sHt| d tdS t }|tdd }tjj||||dd}	tjj|	||dd}
t }| td}|j||d|	j d|  d|d}|
dr|
d|
_|
d|
_|
  t| d td|
jdS d|
_|
d|
_|
  t| d|
d  tdS tdS )zInitiate subscription paymentPOST)owneradminz3You do not have permission to manage subscriptions.zbilling:subscription_plansphone_numberPhone number is required.r   r   r   )r   r   r   zInvalid plan selected.   dayspending)planamount
start_dateend_datepayment_statussubscriptionr-   r4   statusbilling:mpesa_callbackzSUB-zSubscription  Planr-   r4   account_referencetransaction_desccallback_urlsuccessmerchant_request_idcheckout_request_idz@Payment request sent to your phone. Please complete the payment.billing:payment_status
payment_idfailedmessagezPayment failed: )methodr"   r#   r$   roler
   errorr   r%   r*   getr   nowr   r   objectscreater   r   build_absolute_urir   stk_pushidtitlerB   rC   saverA   r:   result_desc)r&   	plan_codetenant_membershipr%   r-   plan_pricesr4   r5   r6   r9   mpesa_payment	mpesa_apir@   resultr'   r'   r(   initiate_subscriptionF   sl   

	

r\   c                 C   s   | j d}| j dd}||d}|dkrY|rYz2tjj|d}|jdkrId|_|  |jj}d|_t	 t
d	d
 |_|  ||d< d|d< W n tjyX   d|d< Y nw t| d|S )z*Handle M-Pesa payment status and callbacksrF   r:   r2   )rF   r:   rA   rR   	completedactiver/   r0   r%   z4Payment successful! Your subscription is now active.rH   zPayment record not found.zbilling/payment_status.html)GETrL   r   rN   r:   rT   r9   r%   r   rM   r   subscription_ends_atDoesNotExistr   )r&   rF   r:   contextpaymentr%   r'   r'   r(   r7      s,   
r7   r*   c              
   C   sH  zt | j}td|  |di di }|d}|d}|d}|d}z	tjj|d}W n tjyN   t	d	|  t
d
 Y W S w |dkr|di dg }d}	d}
d}d}|D ]'}|d}|d}|dkrz|}	qg|dkr|}
qg|dkr|}qg|dkr|}qgd|_|
|_||_|rzddlm} |t|d|_W n	   t |_Y |  |j}d|_t |_|
|_|  |j}d|_|j|_|j|_|  td|j  nd|_||_|  td|jj d|  t
d
W S  ty# } zt	d|  t
dd d!W  Y d}~S d}~ww )"zHandle M-Pesa callbackzM-Pesa callback received: BodystkCallbackMerchantRequestIDCheckoutRequestID
ResultCode
ResultDesc)rC   z+Payment not found for checkout_request_id: OKr   CallbackMetadataItemNNameValueAmountMpesaReceiptNumberTransactionDatePhoneNumberrA   )datetimez%Y%m%d%H%M%Spaidr_   z$Payment successful for subscription rG   z Payment failed for subscription z: zM-Pesa callback error: ERRORi  )r:   ) jsonloadsbodyloggerinforL   r   rN   rb   rK   r   r:   mpesa_receipt_numberrU   rt   strptimestrtransaction_dater   rM   rT   r9   r7   paid_atmpesa_referencer%   r3   r6   ra   rR   warning	Exception)r&   datastk_callbackrB   rC   result_coderU   rd   callback_metadatar4   r|   r   r-   itemr   valuert   r9   r%   er'   r'   r(   mpesa_callback   s   








r   c                 C   s    t j d}t| dd|iS )zView subscription historyz-created_atz!billing/subscription_history.htmlsubscriptions)r   rN   allorder_byr   )r&   r   r'   r'   r(   subscription_history  s   r   c                 C   s   t t|d}t| dd|iS )zView subscription detailr]   z billing/subscription_detail.htmlr9   )r   r   r   )r&   subscription_idr9   r'   r'   r(   subscription_detail  s   r   c                 C   s*  t t|dd}| jdkr| jd}|s!t| d td|jdS t	j
j|||jdd	}t }| td
}|j||jd|j d|  d|d}|drm|d|_|d|_|  t| d td|jdS d|_|d|_|  t| d|d  td|jdS t| dd|iS )zRetry failed paymentrG   )rR   r7   r*   r-   r.   zbilling:subscription_detail)r   r2   r8   r;   zRETRY-zRetry r<   r=   rA   rB   rC   zCPayment retry initiated. Please complete the payment on your phone.rD   rE   rH   zPayment retry failed: zbilling/retry_payment.htmlr9   )r   r   rI   r*   rL   r
   rK   r   rR   r   rN   rO   r4   r   rP   r   rQ   get_plan_displayrB   rC   rT   rA   r:   rU   r   )r&   r   r9   r-   rY   rZ   r@   r[   r'   r'   r(   retry_payment   sN   


r   c                 C   sN   z
t jj|dd}W n t jy   t| d td Y S w t| dd|iS )z,Show tenant expiry page with payment detailsexpired)tenant_coder:   z Tenant not found or not expired.zlanding:homezbilling/tenant_expired.htmlr%   )r   rN   rL   rb   r
   rK   r   r   )r&   r   r%   r'   r'   r(   tenant_expiredW  s   r   ))django.shortcutsr   r   r   django.contrib.auth.decoratorsr   django.httpr   r   django.views.decorators.csrfr   django.views.decorators.httpr	   django.contribr
   django.urlsr   django.utilsr   rt   r   rw   loggingtenants.modelsr   modelsr   r   mpesar   	getLogger__name__rz   r)   r\   r7   r   r   r   r   r   r'   r'   r'   r(   <module>   s>    

2
M
 U
	
	
6