o
    ̿SiJ                  
   @   s  d dl Z d dl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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mZmZ dd
lmZmZmZmZ ee Z!dZ"dZ#dZ$dZ%dZ&e 'dZ(de
dej)defddZ*dej)de+fddZ,de-dej)defddZ.dedej)de-fddZ/dedej)dede0fd d!Z1dedej)dede0fd"d#Z2de-dej)dedefd$d%Z3dej)de+fd&d'Z4dej)dede0fd(d)Z5d*edej)fd+d,Z6de-d-e-d.e-dej)de7f
d/d0Z8d-e-d.e-dej)de7fd1d2Z9d3e-d.e-dej)de7fd4d5Z:d6e-d-e-d.e-dej)de7f
d7d8Z;dej)fd9d:Z<dej)fd;d<Z=dej)fd=d>Z>dej)fd?d@Z?dAe-de0fdBdCZ@de-dej)de0fdDdEZAdS )F    N)	timedeltadatetime)
Collection)database   )SubscriptionTypeCreateSubscriptionTypeSubscriptionCreateSubscriptionPaymentCreatePaymentSubscriptionUpdateSubscriptionLog)User)str_to_objectid)create_checkout_sessionupdate_stripe_subscriptionverify_stripe_signature)send_subscription_success_emailsend_payment_success_emailsend_payment_failure_email!send_subscription_cancelled_emailsubscription_typessubscriptionspaymentsaccountssubscription_logsMY_APP_DOMAINsubscription_typedbreturnc                    s8   |t  }||  }tdi |  dt|jiS )Nsubscription_type_id )SUBSCRIPTION_TYPE_COLLECTION
insert_onedictr   strinserted_id)r   r   
collectionresultr"   r"   @/var/www/html/Trade-python/app/v1/services/saas/subscriptions.py create_subscription_type_service   s    r+   c                    sD   | t  }t| dd}|D ]	}|d|d< qdd |D S )Ntype   r!   c                 S      g | ]	}t d i |qS r"   )r   ).0str"   r"   r*   
<listcomp>,       z3list_subscription_types_service.<locals>.<listcomp>)r#   listfindsortpop)r   r(   r   r1   r"   r"   r*   list_subscription_types_service'   s   r8   subscription_idc                    sF   |t  }|dt| i}|stdt|d |d< tdi |S )N_idzSubscription not foundr9   r"   )SUBSCRIPTION_COLLECTIONfind_oner   
ValueErrorr&   r
   )r9   r   subscription_collectionsubscription_dictr"   r"   r*   get_subscription_service0   s   r@   subscription_logc                    s2   |t  }||  }t|j}td| |S )Nz&Logged subscription change with id: %s)LOG_SUBSCRIPTION_COLLECTIONr$   r%   r&   r'   loggerinfo)rA   r   log_collectionr)   log_idr"   r"   r*   log_subscription_change_service8   s   
rG   subscriptioncurrent_userc              
      s  |t  }|t }|d dkrtd|dt|d i}|  }t |d< |d |d< |d tdd	 |d
< |d|d i}|rS|d }|	d|id|i nd|d< |
|}	|	j}|d|i}
tdi |
dt|i}ttdi | t|d t d|I d H }|	d|jidt||j|jdi |t d| ji}|d}t|d |d |d t||j||jt|dI d H }||dddS )Nroles   z/You are not permitted to create a subscription.r:   
account_id
start_daterenew_start_date   )daysrenew_end_date$setnewstatusr9   updated_user_idupdated_dateuser_id)active_subscription_idsubscription_statusaccount_typer,   stripe_price_idaccount_nameemailrL   r]   r^   r9   r!   r\   quantityrF   url rH   checkout_urlr"   )r;   ACCOUNTS_COLLECTIONr=   r<   r   r%   r   utcnowr   
update_oner$   r'   r
   r&   rG   r   rX   rT   r!   r#   getr   subscription_agents_count)rH   r   rI   r>   account_collectionaccountr?   existing_subscriptionr9   r)   created_subscription_dictcreated_subscriptionrF   subscription_type_docr\   checkout_session_responser"   r"   r*   create_subscription_service?   s\   
&
	

rq   c              
      sZ  |   }|d }|std|d dkrtd|t }|t }|dt|i}|r5|d|d kr9td| j d	d
}d|v rQd|v rQ|d |d  |d< |t d|d i}	|	d}
|drt|d |
|d dI d H }|r|	dt|id|i |dt|i}t
tdi |t|d t d|I d H  ntdd }nV|dt|d i}|	dt|id|i |dt|i}t
tdi |t|d t d|I d H  t|d |d |d ||d |
|d ddI d H }|d}d|v r|	dt|d idd|d ii t|d |d< t|d |d< ||dS )Nr9   zSubscription ID is required.rJ   rK   z/You are not permitted to update a subscription.r:   rL   z'Subscription not found or access deniedT)exclude_noneri   peragent_cost
total_costr,   r!   r\   stripe_subscription_id)r9   new_price_idnew_quantityrR   rU   z!Stripe subscription update failednamer^   rb   r_   ra   r[   rc   r"   )r%   r=   r;   re   r<   r   rh   r#   r   rg   rG   r   r&   r   rf   r   )rH   r   rI   r?   r9   r>   rj   rl   updated_dataro   r\   stripe_updatedupdated_subscriptionrd   rk   rp   r"   r"   r*   update_subscription_service|   st   

""




r|   c                    s   |t  }|dt| i}|r|d |jkrtd|dt| idddii |t }|d|jidd ddi |dt| i}tdi |S )	Nr:   rX   z(Subscription not found or access denied.rR   rT   	cancelled)rY   rZ   r"   )r;   r<   r   rX   r=   rg   re   r
   )r9   r   rI   r>   rH   rj   r{   r"   r"   r*   cancel_subscription_service   s   r~   c                    s$   | t  }t| }dd |D S )Nc                 S   r.   r/   )r
   )r0   sr"   r"   r*   r2      r3   z.list_subscriptions_service.<locals>.<listcomp>)r;   r4   r5   )r   r(   r   r"   r"   r*   list_subscriptions_service   s   r   c                    sh   |d }|d dkrt d| t }d|i}t||}|D ]
}t|d |d< q t|}||dS )NrL   rJ   rK   z%Not permitted to view these payments.r:   
payment_id)r   total_count)r=   PAYMENTS_COLLECTIONr4   r5   r&   len)r   rI   rL   r(   payments_queryr   paymentr   r"   r"   r*   list_payments_service   s   
r   r   c                    s   |t  }||  }|S )N)r   r$   r%   )r   r   r(   r)   r"   r"   r*   create_payment_service   s   r   ru   rT   c                    s>   |t  }|dt| id||di}td| |jdkS )Nr:   rR   )rT   ru   zStripe ID updated to %sr   )r;   rg   r   rC   rD   modified_count)r9   ru   rT   r   r>   r)   r"   r"   r*   "update_subscription_status_service   s   

r   c           	         s   |t  }|d| i}|std|  dS |d }|d| idd|ii}|jdkrVt|||I d H  |d }|jd	t|d
 idgd}|rVtt|d
 | ||I d H  |jdkS )Nru   z(Subscription not found for Stripe ID: %sFrL   rR   rT   r   r   r9   r:   )rW   )r6   )	r;   r<   rC   errorrg   r   update_account_status_servicer&   update_log_status_service)	ru   rT   r   r>   rH   rL   r)   rE   
latest_logr"   r"   r*   "update_subscription_stripe_service   s*   


r   rL   c                    s0   |t  }|dt| idd|ii}|jdkS )Nr:   rR   rZ   r   )re   rg   r   r   )rL   rT   r   rj   r)   r"   r"   r*   r     s   


r   rF   c                    s2   |t  }|dt| id||di}|jdkS )Nr:   rR   )ru   rT   r   )rB   rg   r   r   )rF   ru   rT   r   rE   r)   r"   r"   r*   r     s   

r   c           
         s~  t | I d H }td|d  |d d }|d dkr,d}t||||I d H  ddiS |d dv r>t||I d H  ddiS |d dv rtt|d	|I d H  |d d }|d
 }tj|d }|	dd}	|j
t||	|d d ddiS |d dkrd	}t|||I d H  ddiS |d dkrt|d|I d H  |d d }|d
 }tj|d }|	dd}	|j
t||	|d d ddiS )NzReceived event: %sr,   dataobjectzcheckout.session.completedactive)zcustomer.subscription.createdzcustomer.subscription.updated)zcustomer.subscription.deletedr}   customer_emailcustomerrx   zValued Customer
amount_due)r^   rx   amountzpayment.payment_failedzinvoice.payment_failedholdrT   success)r   rC   rD   )handle_checkout_session_completed_service"handle_subscription_update_service%handle_payment_payment_failed_servicestripeCustomerretrieverh   add_taskr   )
requestbackground_tasksr   event
stripe_obj	setstatusinvoice
user_emailr   customer_namer"   r"   r*   stripe_webhook_service%  s>   r   c              	      s  |  di }| d}| d}| d}| d}|  d}	|  dd }
|  d	}| d
}| d}|r|  d}	|	rt||	||I d H  t|||I d H  t||	||I d H  t||	|||
t dd}t||I d H  |jt	||||
d t
d||	 d S d S d S )Nmetadatar9   rL   r]   r^   rH   amount_totald   payment_intentrF   r`   paid)r9   ru   stripe_transaction_idrL   r   due_daterT   )r^   rx   countr   zIUpdated local subscription %s with Stripe ID %s and set status to active.)rh   r   r   r   r   r   rf   r   r   r   rC   rD   )session_objr   r   r   r   local_subscription_idrL   r]   r^   ru   r   r   rF   agent_countpayment_datar"   r"   r*   r   B  s>   








	r   c                    sF   | d }| d }|dkrdnd}t |||I d H  td|| d S )NidrT   r   r   zSubscription %s updated to %s.r   rC   rD   )subscription_objr   ru   rT   
new_statusr"   r"   r*   r   a  s   r   c                    s,   | d }t |||I d H  td| d S )NrH   z5Payment failed for subscription %s. Set to cancelled.r   )payment_objr   r   ru   r"   r"   r*   r   h  s   r   
session_idc              
      s^   zt jj| }|jdkrddddW S dddW S  ty. } ztd	| |d }~ww )
Nr   TzPayment verified successfully.r   )r   messagerT   FzPayment verification failed.)r   r   z#Error verifying payment session: %s)r   checkoutSessionr   payment_status	ExceptionrC   r   )r   sessioner"   r"   r*   verify_payment_servicem  s   
r   c           	   
      s   |t  }|dt| i}|rd|vrtd|d }ztj|}|j}W n tjj	y> } z	tdt
| d }~ww tjjj|t dd}d|jiS )Nr:   ru   zBStripe Subscription ID not found for the provided subscription ID.zStripe API error: z/billing)r   
return_urlra   )r;   r<   r   r=   r   r
   r   r   r   StripeErrorr&   billing_portalr   creater   ra   )	r9   r   r>   rH   ru   subscription_detailscustomer_idr   r   r"   r"   r*   create_portal_session_servicex  s$   

r   )Bosr   loggingr   r   pymongo.collectionr   app.dbr   models.saas.subscriptionsr   r   r	   r
   r   r   r   r   models.saas.usersmodelr   app.v1.libraries.objectr   libraries.striper   r   r   libraries.email_templatesr   r   r   r   	getLogger__name__rC   r#   r;   r   re   rB   getenvr   MongoDBr+   r4   r8   r&   r@   rG   r%   rq   r|   r~   r   r   r   boolr   r   r   r   r   r   r   r   r   r   r"   r"   r"   r*   <module>   s    (


	
=
J


 
