o
    Ah)g                  
   @   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 d dl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Z0dedej+de/fddZ1dedej+d ede2fd!d"Z3dedej+d ede2fd#d$Z4de/dej+d edefd%d&Z5dej+de-fd'd(Z6dej+d ede2fd)d*Z7d+edej+fd,d-Z8de/d.e/d/e/dej+de9f
d0d1Z:d.e/d/e/dej+de9fd2d3Z;d4e/d/e/dej+de9fd5d6Z<d7e/d.e/d/e/dej+de9f
d8d9Z=dej+fd:d;Z>dej+fd<d=Z?dej+fd>d?Z@dej+fd@dAZAdBe/de2fdCdDZBde/dej+de2fdEdFZCde
dej+defdGdHZDdIe/dej+defdJdKZEdIe/dLe
dej+defdMdNZFdIe/dej+de9fdOdPZGdS )Q    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)get_next_sequence_value_intsubscription_typessubscriptionspaymentsaccountssubscription_logsMY_APP_DOMAINsubscription_typedbreturnc                    sD   |t  }td|}|  }||d< ||d< ||}tdi |S )Nsubscription_type_idtype )SUBSCRIPTION_TYPE_COLLECTIONr   dict
insert_oner   )r   r    
collection	custom_iddataresultr$   r$   >/var/www/html/moveengine/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 )Nr#      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   r2   r$   r$   r,   list_subscription_types_service5   s   r9   subscription_idc                    F   |t  }|dt| i}|stdt|d |d< tdi |S )N_idzSubscription not foundr:   r$   )SUBSCRIPTION_COLLECTIONfind_oner   
ValueErrorstrr
   )r:   r    subscription_collectionsubscription_dictr$   r$   r,   get_subscription_service>      rC   subscription_logc                    s2   |t  }||  }t|j}td| |S )Nz&Logged subscription change with id: %s)LOG_SUBSCRIPTION_COLLECTIONr'   r&   r@   inserted_idloggerinfo)rE   r    log_collectionr+   log_idr$   r$   r,   log_subscription_change_serviceF   s   
rL   subscriptioncurrent_userc              
      s  |t  }|t }|d dkr|d dkrtd|dt|d i}|  }t |d< |d |d< |d td	d
 |d< |t	 d| j
i}|rS|dd|d< td t| td |d|d i}|ry|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   d   z/You are not permitted to create a subscription.r<   
account_id
start_daterenew_start_date   )daysrenew_end_dater#   name 	plan_name<subscription_dictsubscription_dictsubscription_dictplan_namez!***************************** END$setnewstatusr:   updated_user_idupdated_dateuser_id)active_subscription_idsubscription_statusaccount_typestripe_price_idaccount_nameemailrR   rg   rh   r:   r"   rf   quantityrK   urlrM   checkout_urlr$   )r=   ACCOUNTS_COLLECTIONr?   r>   r   r&   r   utcnowr   r%   r"   getprint
update_oner'   rG   r
   r@   rL   r   rb   r^   r   subscription_agents_count)rM   r    rN   rA   account_collectionaccountrB   subscription_type_docexisting_subscriptionr:   r+   created_subscription_dictcreated_subscriptionrK   rf   checkout_session_responser$   r$   r,   create_subscription_serviceM   sl   
&
	

r{   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 )Nr:   zSubscription ID is required.rO   rP   z/You are not permitted to update a subscription.r<   rR   z'Subscription not found or access deniedT)exclude_noners   peragent_cost
total_costr#   r"   rf   stripe_subscription_id)r:   new_price_idnew_quantityr\   r_   z!Stripe subscription update failedrX   rh   rY   ri   rk   re   rl   r$   )r&   r?   r=   rn   r>   r   rp   r%   r   rr   rL   r   r@   r   ro   r   )rM   r    rN   rB   r:   rA   rt   rw   updated_datarv   rf   stripe_updatedupdated_subscriptionrm   ru   rz   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<   rb   z(Subscription not found or access denied.r\   r^   	cancelled)rc   rd   r$   )r=   r>   r   rb   r?   rr   rn   r
   )r:   r    rN   rA   rM   rt   r   r$   r$   r,   cancel_subscription_service   s   r   c                    s$   | t  }t| }dd |D S )Nc                 S   r/   r0   )r
   )r1   sr$   r$   r,   r3      r4   z.list_subscriptions_service.<locals>.<listcomp>)r=   r5   r6   )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 )NrR   rO   rP   z%Not permitted to view these payments.r<   
payment_id)r   total_count)r?   PAYMENTS_COLLECTIONr5   r6   r@   len)r    rN   rR   r(   payments_queryr   paymentr   r$   r$   r,   list_payments_service   s   
r   r   c                    s$   t d |t }||  }|S )Nz%Create payment service 25025222502520)rq   r   r'   r&   )r   r    r(   r+   r$   r$   r,   create_payment_service  s
   r   r   r^   c                    s>   |t  }|dt| id||di}td| |jdkS )Nr<   r\   )r^   r   zStripe ID updated to %sr   )r=   rr   r   rH   rI   modified_count)r:   r   r^   r    rA   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 )Nr   z(Subscription not found for Stripe ID: %sFrR   r\   r^   r   r   r:   r<   )ra   )r7   )	r=   r>   rH   errorrr   r   update_account_status_servicer@   update_log_status_service)	r   r^   r    rA   rM   rR   r+   rJ   
latest_logr$   r$   r,   "update_subscription_stripe_service  s*   


r   rR   c                    s0   |t  }|dt| idd|ii}|jdkS )Nr<   r\   rd   r   )rn   rr   r   r   )rR   r^   r    rt   r+   r$   r$   r,   r   -  s   


r   rK   c                    s2   |t  }|dt| id||di}|jdkS )Nr<   r\   )r   r^   r   )rF   rr   r   r   )rK   r   r^   r    rJ   r+   r$   r$   r,   r   5  s   

r   c              
      s  zlt | I d H }td|d  |di di }|d}|dkr3d}t||||I d H  n7|dv r|d}|d	}|d
}	|d}
td|	 d| d|  z|d jd|id||	|
t didd td W n ty } zt	d|  W Y d }~nd }~ww t
||I d H  n|dkrt|d|I d H  |}|d}|d}|r|rztj|}|d
d}W n ty } ztd|  d}W Y d }~nd }~ww |jt|||ddd n{|d krt|d|I d H  nm|d!krWt|d"|I d H  |}|d}|d}|rV|rVztj|}|d
d}W n tyH } ztd|  d}W Y d }~nd }~ww |jt|||ddd n|d#krbtd$ ntd%|  d&d'iW S  ty } zdd l}t	d(|  td)d*d+d }~ww ),Nu   ✅ Stripe event received: %sr#   r*   objectzcheckout.session.completedactive)zcustomer.subscription.createdzcustomer.subscription.updatedidrh   rX   phoneu"   👤 New Stripe customer created: z (z) - ID: stripe_customersstripe_customer_idr\   )rh   rX   r   
created_atT)upsertu(   ✅ Stripe customer stored successfully.u%   ❌ Failed to store Stripe customer: zcustomer.subscription.deletedr   customer_emailcustomerzValued CustomerzStripe Customer fetch failed: 
amount_duer   )rh   rX   amountzpayment.payment_failedzinvoice.payment_failedholdzcustomer.createduA   🔔 customer.created event received. No action needed currently.u$   ℹ️ Unhandled Stripe event type: r^   successu(   🔥 Error in stripe_webhook_service:
%si  z(Internal error processing Stripe webhook)status_codedetail)r   rH   rI   rp   )handle_checkout_session_completed_servicerr   r   ro   	Exceptionr   "handle_subscription_update_service%handle_payment_payment_failed_servicestripeCustomerretrievewarningadd_taskr   	traceback
format_excHTTPException)requestbackground_tasksr    event
stripe_obj
event_type	setstatuscustomer_idrh   rX   r   db_errinvoice
user_emailr   customer_nameer   r$   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metadatar:   rR   rg   rh   rM   amount_totalrQ   payment_intentrK   rj   paid)r:   r   stripe_transaction_idrR   r   due_dater^   )rh   rX   countr   zIUpdated local subscription %s with Stripe ID %s and set status to active.)rp   r   r   r   r   r   ro   r   r   r   rH   rI   )session_objr   r    r   r   local_subscription_idrR   rg   rh   r   r   r   rK   agent_countpayment_datar$   r$   r,   r     s>   








	r   c                    sF   | d }| d }|dkrdnd}t |||I d H  td|| d S )Nr   r^   r   r   zSubscription %s updated to %s.r   rH   rI   )subscription_objr    r   r^   
new_statusr$   r$   r,   r     s   r   c                    s,   | d }t |||I d H  td| d S )NrM   z5Payment failed for subscription %s. Set to cancelled.r   )payment_objr   r    r   r$   r$   r,   r     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   messager^   FzPayment verification failed.)r   r   z#Error verifying payment session: %s)r   checkoutSessionr   payment_statusr   rH   r   )r   sessionr   r$   r$   r,   verify_payment_service  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<   r   zBStripe Subscription ID not found for the provided subscription ID.zStripe API error: z/billing)r   
return_urlrk   )r=   r>   r   r?   r   r
   r   r   r   StripeErrorr@   billing_portalr   creater   rk   )	r:   r    rA   rM   r   subscription_detailsr   r   r   r$   r$   r,   create_portal_session_service  s$   

r   c                    s@   |t  }|  }d|d< ||}t|j|d< tdi |S )NTr^   r"   r$   )r%   r&   r'   r@   rG   r   )r   r    r(   rB   r+   r$   r$   r,   #create_subscription_type_serviceNew  s   
r   r"   c                    r;   )Nr<   Subscription type not found.r"   r$   )r%   r>   r   r?   r@   r   )r"   r    r(   docr$   r$   r,   get_subscription_type_service  rD   r   r*   c                    st   |t  }| }d|d< |dt| id|i}|jdkr"td|dt| i}t|d |d< tdi |S )	NTr^   r<   r\   r   r   r"   r$   )	r%   r&   rr   r   matched_countr?   r>   r@   r   )r"   r*   r    r(   update_datar+   r   r$   r$   r,    update_subscription_type_service  s   
r   c                    s&   |t  }|dt| i}|jdkS )Nr<   r   )r%   
delete_oner   deleted_count)r"   r    r(   r+   r$   r$   r,    delete_subscription_type_service%  s   
r   )H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   app.v1.services.sequencer   	getLogger__name__rH   r%   r=   r   rn   rF   getenvr   MongoDBr-   r5   r9   r@   rC   rL   r&   r{   r   r   r   r   r   boolr   r   r   r   r   r   r   r   r   r   r   r   r   r   r$   r$   r$   r,   <module>   s    (


	
H
J


 ([
