
    Yhlc                        d Z ddlmZmZmZ ddlmZ ddlZddlZddl	m	Z	m
Z
 ddlZddlmZ ddlmZ ddlmZmZmZmZ dd	lmZ dd
lmZmZmZmZ  ej8                  e      Z ej>                  ddg      d        Z  ej>                  ddg      ed               Z! ej>                  ddg      d        Z" ej>                  ddg      ed               Z# ej>                  ddg      ed               Z$ ej>                  ddg      ed               Z% ej>                  ddg      ed               Z& ej>                  ddg      ed               Z'y)ze
Subscription routes for the SQLGenAI API.
These routes handle subscription management using Stripe.
    )requestjsonifycurrent_app)current_userN)datetime	timedelta)db)api_bp)SubscriptionSubscriptionPlanPaymentHistory
QueryUsage)token_required)SUBSCRIPTION_PLANSFEATURE_DISPLAY_NAMESSUPPORT_LEVELSUPCOMING_FEATURESz/subscription/plans/configGET)methodsc            	         g } t        j                         D ]  \  }}g }g }|d   j                         D ]  \  }}|dk(  r3|dk(  r|j                  d|d       &|j                  d| d|d       ?|dk(  r3|dk(  r|j                  d	|d       ^|j                  d| d
|d       w|dk(  r3|dk(  r|j                  d|d       |j                  d| d|d       |dk(  r3|dk(  r|j                  d|d       |j                  d| d|d       |dk(  r*|j                  t        j                  |d      |d       t        |t              s(t        j                  ||j                  dd      j                               }|t        v }|r/|r|j                  ||dd       |j                  ||d       |r|j                  d| |dd       |j                  d| |d        g }	|D ][  }
t        |
t              r8d|
v r4d|
v r|	j                  |
d   |
d   d       6|	j                  |
d          K|	j                  |
       ] g }|D ][  }t        |t              r8d|v r4d|v r|j                  |d   |d   d       6|j                  |d          K|j                  |       ] ||d   |d   |d   |d   |	|d }| j                  |        t        d!| d"      S )#z>Get all available subscription plans with pricing and featuresfeaturesquery_limitzUnlimited SQL queries)textvaluezUp to z SQL queries per monthexplain_limitzUnlimited explain plan analysesz  explain plan analyses per monthconnection_limitzUnlimited database connectionsz database connectionsquery_history_dayszQuery history (unlimited)zQuery history (z days)support_levelSupport_ soon)r   r   tagzNo r   r$   )r   r$   namedescriptionmonthly_priceannual_price)idr%   r&   monthlyPriceannualPricer   limitationsTsuccessplans)r   itemsappendr   get
isinstanceboolr   replacetitler   dictr   )formatted_plansplan_id	plan_datar   r,   feature_keyfeature_valuedisplay_nameis_upcomingsimplified_featuresfeaturesimplified_limitations
limitationformatted_plans                 ,/var/www/html/app/api/subscription_routes.pyget_subscription_plans_configrE      sl    O0668 [/*3J*?*E*E*G )	c&Km+ B&OO-D}$]^OOvm_DZ-[fs$tu/ B&OO-NYf$ghOOvm_Dd-ep}$~ 22 B&OO-MXe$fgOOvm_DY-Zer$st 44 B&OO-HS`$abOO}oV-T_l$mn/););M9)U`m noM40488kFYFYZ]_bFcFiFiFkl *->> " ^d(ef (VW ##**c,4HS`io+pq#**c,4HS`+abS)	cX ! 	4G'4(Vw->G#'.. '&u~0  (..wv?#**73	4 "$% 	:J*d+*0DJ&*11 *6 2)%03  +11*V2DE&--j9	:  f%$]3%o6$^4+1
 	~.w[/z        z/subscriptionc                  
   t         j                  } t        j                  j	                  | j
                        j                         }|st        ddd      dfS t        j                  j	                  |j                        j                         }t        j                         }t        |j                  |j                  d      }t        j                  j                  t        j                   | j
                  k(  t        j"                  |k\        j%                         }t        j                  j                  t        j                   | j
                  k(  t        j"                  |k\  t        j&                  dk(        j%                         }t        j                  j                  t        j                   | j
                  k(  t        j"                  |k\  t        j&                  d	k(        j%                         }t        j                  j                  t        j                   | j
                  k(  t        j"                  |k\  t        j&                  d
k(        j%                         }||z   }	d}
|rg|j(                  r[|j(                  }t+        |t,              r
d|v r|d   }
n5|j                  dk(  rd}
n#|j                  dk(  rd}
n|j                  dk(  rd}
t        d|j
                  |j                  |r|j.                  nd|j0                  |j2                  |j4                  r|j4                  j7                         nd|j8                  r|j8                  j7                         nd|r|j(                  ni ||
|	|||dd	d      S )z<Get current user's subscription with query usage informationuser_idFNo subscription foundr.   message  r9      generateexplainexecute
   r   basicd   professional  
enterprisei TUnknownN)monthly_countlimitai_credits_countgenerate_countexplain_countexecute_count)	r)   r9   	plan_namestatus	is_annual
start_dateend_dater   query_usage)r.   subscription)r   r   r   query	filter_byr)   firstr   r   r9   r   utcnowyearmonthr   filterrI   execution_timecount
query_typer   r3   r7   r%   ra   rb   rc   	isoformatrd   )r   rf   plantodaymonth_startquery_countr]   r^   r_   r\   r   plan_featuress               rD   get_subscriptionrw   |   s   
 ''L%%///HNNPL.
   	 !!++L4H4H+IOOQD OOE5::u{{A6K ""))loo-!![0 eg   %%,,loo-!![0+ eg	  $$++loo-!![0* eg	  $$++loo-!![0* eg	  &5 KmT*}/M'6K ||w&!/!-%//#++&*	"))%//AMAXAX,11;;=^b=I=R=R--779X\)-2!,$$4"0!.!.
  rF   z/subscription/plansc                     t         j                  j                         } d}t        j                  j                  d      }|r|j                  d      r|j                  d      d   }t        j                  j                  |      j                         }|rt        j                  j                  |j                        j                         }|rt         j                  j                  |j                        j                         }t        j                  d	|j                   d
|j                   d|j                           nt        j                  d       g }| D ]  }d}|r|j                   |j                   k  rd}|j                  |j                  |j"                  |j$                  |j                   |j&                  |j(                  |j*                  |d	}	|j-                  |	        t/        d|d      S )zZGet available subscription plans with can_select flag based on user's current subscriptionNAuthorizationzBearer r"   rO   )
auth_tokenrH   rN   zFound current plan for user z: z with price z:User is not authenticated, showing all plans as selectableTF)	r)   r9   r%   r&   r'   r(   r   r,   
can_selectr-   )r   rg   allr   headersr2   
startswithsplitUserrh   ri   r   r)   r9   loggerinfor'   r%   r&   r(   r   r,   r1   r   )
r/   current_planauth_headertokenusercurrent_subscription	plan_listrr   r{   r:   s
             rD   get_subscription_plansr      s    ""&&(E L //%%o6K {--i8!!#&q)zz##u#5;;=#/#5#5#?#?#?#P#V#V#X #/55??H\HdHd?ekkm:477)2lFZFZE[[ght  iC  iC  hD  E  FPQI $
 D..1K1KKJ ''||II++!// --++$

	 	#)$,   rF   z/subscription/checkoutPOSTc                  P   t         j                  } t        j                         }|st        ddd      dfS ddg}|D ]  }||vst        dd| d      dfc S  t        j
                  j                  |d         j                         }|st        dd	d      dfS 	 d
dlm	}  || j                  |d   |d         }t        d|d   |d   d      S # t        $ rG}t        j                  dt        |              t        ddt        |       d      dfcY d}~S d}~ww xY w)z1Create a Stripe checkout session for subscriptionFNo data providedrK     r9   billing_cycleMissing required field: rN   Invalid plan IDr   )create_checkout_session)rI   r9   r   Tcheckout_urlcheckout_id)r.   r   r   z!Error creating checkout session: z#Failed to create checkout session: rW   N)r   r   get_jsonr   r   rg   rh   ri   app.utils.stripe_utilsr   r)   	Exceptionr   errorstr)r   datarequired_fieldsfieldrr   create_stripe_checkoutcheckout_dataes           rD   r   r   	  s   
 ''LD)
   	 !/2O   5eW=    !!++DO+DJJLD(
   	
\ / OOO/
 ).9(7
  	
  8QAB<SVHE
   	s   5C 	D%<D D% D%z/subscription/processc                     t         j                  } t        j                         }|st        ddd      dfS dg}|D ]  }||vst        dd| d      dfc S  	 ddl}t
        j                  d	   |_        |j                  j                  j                  |d         }|j                  d
k7  rt        ddd      dfS t        |j                  j                  d            }|| j                  k7  rt        ddd      dfS |j                   }|j"                  j                  |      }|j                  j                  d      }	|j                  j                  d      }
t$        j&                  j)                  |	      j+                         }|st        ddd      dfS t"        j&                  j)                  | j                        j+                         }d}|r|	|_        |
dv |_        d|_        ||_        t5        j6                  |j8                        |_        t5        j6                  |j<                        |_        |}t@        jB                  jE                          nt#        | j                  |	|
dv d|t5        j6                  |j8                        t5        j6                  |j<                              }t@        jB                  jG                  |       t@        jB                  jE                          t@        jB                  jI                  |       |}tK        | j                  |j                  |jL                  dz  |jN                  jQ                         t5        jR                         d|jT                  d      }t@        jB                  jG                  |       t@        jB                  jE                          |jV                  }|jX                  }t        dd|	|jZ                  |||
dk(  |j:                  j]                         |j>                  j]                         dd      S # t^        $ rG}t`        jc                  d te        |              t        dd!te        |       d      d"fcY d}~S d}~ww xY w)#z(Process subscription payment with StripeFr   rK   r   
session_idr   r   NSTRIPE_SECRET_KEYpaidzPayment not completedrI   zUser ID mismatchi  r9   r   rN   r   rH   )yearlyannualactive)rI   r9   rb   ra   subscription_idrc   rd   rU   credit_cardr.   )rI   r   amountcurrencypayment_datepayment_methodtransaction_idra   TzPayment processed successfullyr   )r9   r`   r   r,   rb   rc   rd   r.   rL   rf   zError processing payment: zFailed to process payment: rW   )3r   r   r   r   striper   configapi_keycheckoutSessionretrievepayment_statusintmetadatar2   r)   rf   r   r   rg   rh   ri   r9   rb   ra   r   r   fromtimestampcurrent_period_startrc   current_period_endrd   r	   sessioncommitaddrefreshr   amount_totalr   upperrj   payment_intentr   r,   r%   rq   r   r   r   r   )r   r   r   r   r   r   rI   r   stripe_subscriptionr9   r   rr   existing_subscriptionsubscription_objnew_subscriptionpaymentrv   plan_limitationsr   s                      rD   process_subscription_paymentr   ?  sX   
 ''LD)
   	 $nO   5eW=   r$++,?@ //))2243EF !!V+ 2    g&&**956 loo% -    ".. %11::?K ""&&y1((,,_=  %%///@FFH ,    !- 2 2 < <\__ < U [ [ ]   ,3!).;?S.S!++3!(4C!1/7/E/EFYFnFn/o!,-5-C-CDWDjDj-k!*4JJ  ,$'+?? /#112E2Z2Z[!//0C0V0VW  JJNN+,JJJJ/0/ ! OO,//''#-%%++-!*("11	
 	

w


 ++7"!YY)/*h6.99CCE,55??A
  	  1#a&:;4SVH=
   	s4   A"P( >AP( BP( J	P( (	Q81<Q3-Q83Q8z/subscription/cancelc                  P   t         j                  } t        j                  j	                  | j
                        j                         }|st        ddd      dfS |j                  st        ddd      dfS 	 dd	l	m
}  ||j                        }|r3d
|_        t        j                  j                          t        ddd      S t        ddd      dfS # t        $ rG}t         j#                  dt%        |              t        ddt%        |       d      dfcY d}~S d}~ww xY w)z%Cancel current subscription in StriperH   FzNo active subscription foundrK   rM   No Stripe subscription ID foundr   r   )cancel_stripe_subscription	cancelledTz#Subscription cancelled successfullyz'Failed to cancel subscription in StriperW   zError cancelling subscription: zFailed to cancel subscription: N)r   r   r   rg   rh   r)   ri   r   r   r   r   ra   r	   r   r   r   r   r   r   )r   rf   r   r.   r   s        rD   cancel_subscriptionr     sO   
 ''L%%///HNNPL5
   	
 ''8
   	
E -\-I-IJ"-LJJ@  
  D     6s1vh?@8QA
   	s%   8AC C 	D%<D D% D%z/subscription/updatePUTc                  P   t         j                  } t        j                         }|st        ddd      dfS ddg}|D ]  }||vst        dd| d      dfc S  t        j
                  j                  |d         j                         }|st        dd	d      dfS t        j
                  j                  | j                  
      j                         }|st        ddd      dfS |j                  st        ddd      dfS 	 ddl}t        j                  d   |_        d|d    d|d    }|j                  j                  |j                        }|j                  j!                  |j                  |d   d   d   j                  |dgd       |j                  j                  |j                        }	|d   |_        |d   dk(  |_        t'        j(                  |	j*                        |_        t'        j(                  |	j.                        |_        t2        j4                  j7                          t        dd|j                  |j"                  |j8                  |j:                  |j$                  |j,                  r|j,                  j=                         nd|j0                  r|j0                  j=                         nd|j>                  dd      S # t@        $ rG}
tB        jE                  dtG        |
              t        ddtG        |
       d      dfcY d}
~
S d}
~
ww xY w) z(Update current subscription using StripeFr   rK   r   r9   r   r   rN   r   rH   rJ   rM   r   r   Nr   z	sqlgenai--r0   r   )r)   pricecreate_prorations)r0   proration_behaviorr   Tz!Subscription updated successfully)r)   r9   r`   ra   rb   rc   rd   r   r   zError updating subscription: zFailed to update subscription: rW   )$r   r   r   r   r   rg   rh   ri   r   r)   r   r   r   r   r   r   modifyr9   rb   r   r   r   rc   r   rd   r	   r   r   r%   ra   rq   r   r   r   r   r   )r   r   r   r   rr   rf   r   price_idr   updated_stripe_subr   s              rD   update_subscriptionr     s]   
 ''LD)
   	 !/2O   5eW=    !!++DO+DJJLD(
   	  %%///HNNPL.
   	
 ''8
   	
3$++,?@ tI/qo1F0GH %11::<;W;WX 	""(()'26:1=@@!   3 	# 	
 $0099,:V:VW  $I!%o!6(!B"*"8"89K9`9`"a ( 6 67I7\7\ ]


:"oo'//!YY&--)33EQE\E\l55??AbfAMAVAVL11;;=\` MM	
  	  4SVH=>8QA
   	s   GK 	L%<L L% L%z/subscription/paymentsc                     t         j                  } 	 t        j                  j	                  | j
                        j                  t        j                  j                               j                         }g }|D ]  }|j                  r)t        j                  j                  |j                        nd}d}|rFt        j                  j	                  |j                        j                         }|r|j                   }|j#                  |j
                  |j                  j%                         |j&                  |j(                  |j*                  |r| d|r|j,                  rdnd dnd	|j.                  d
        t1        d|d      S # t2        $ rG}t4        j7                  dt9        |              t1        ddt9        |       d      dfcY d}~S d}~ww xY w)zGet payment historyrH   NrY   rN   z - AnnualMonthlyz SubscriptionPayment)r)   dater   r   ra   r&   r   T)r.   paymentszError getting payment history: FzFailed to get payment history: rK   rW   )r   r   r   rg   rh   r)   order_byr   descr|   r   r   r2   r   r9   ri   r%   r1   rq   r   r   ra   rb   r   r   r   r   r   r   )r   r   payment_listr   rf   r`   rr   r   s           rD   get_payment_historyr   ]  s   
 ''L#!''11,//1JSSTbToToTtTtTvw{{} 	GNUNeNe<--11'2I2IJkoL "I'--77@T@T7U[[] $		Ijj,,668!..#,,!.. FR)CL\McMcir/s  tA   B  Xa")"8"8! 	* $
  	  6s1vh?@8QA
   	s   E9F 	G<GGG)(__doc__flaskr   r   r   flask_loginr   r   secretsr   r   loggingapp.extensionsr	   app.apir
   app.auth.modelsr   r   r   r   app.utils.authr   app.subscription_configr   r   r   r   	getLogger__name__r   routerE   rw   r   r   r   r   r   r    rF   rD   <module>r      s   0 / $   (    V V ) p p 
		8	$*UG<d =dL ow/T  0Tl #eW52 62h &92  :2h %x8G  9GR $vh7,  8,\ $ug6_  7_B &8(  9(rF   