
    nh=                        d dl mZmZmZ d dlmZ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mZ d dlmZ d dlmZ  ede      Zd Z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"d dl mZmZ d dl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mZ ej?                  ddg      ed               Z)ej?                  ddg      ed               Z*y )!    )	Blueprintrequestjsonify)ValidationErrorDoesNotExist)datetime	timedelta)VideoCourseSubject)Ebook)MockTest)	OldPapers)jwt_required)User)Course)CartItem)SubExamcart_bpc                  n    t        j                  d      xs t         j                  j                         S )NTsilent)r   get_jsonformto_dict     '/var/www/html/eduruby.in/routes/cart.py_get_payloadr      s%    4(BGLL,@,@,BBr   c                 L    t        j                  | d      j                         S )N   user_idstatus)r   objectscount)users    r   _active_cart_countr&      s    D399;;r   z	/cart/addPOST)methodsc                  B   t               } | j                  d      }t        t        dd      }|st	        dddd      dfS 	 t        j                  |	      j                  d
dd      j                         }|st	        dddd      dfS t        |      }t        |j                  xs d      dk7  rt	        dd|d      dfS |st	        dd|d      dfS 	 t        j                  |	      j                         }|st	        dd|d      dfS t        |j                  xs d      dk7  rt	        dd|d      dfS t        j                  ||      j                         }|rF|j                  dk(  rt	        dd|d      dfS |j!                  dt#        j$                                n/t        ||dt#        j$                               j'                          t        |      }t	        dd|d      dfS # t        t        f$ r d}Y w xY w# t        t        f$ r d}Y $w xY w)z
    Add a course to the current user's cart (soft, status=1).
    Body (JSON or form-data):
      - course_id: <MongoID>
    user_id comes from JWT.
    	course_idr!   NFInvalid user idr   r"   messagecart_items_count  idr1   r"   coins_wallet_balance  r   User account not active  Invalid course id  zCourse is inactive)r!   r*   TzCourse already in cart   )set__statusset__created_date)r!   r*   r"   created_datezCourse added to cart)r   getgetattrr   r   r   r#   onlyfirstr   r   r&   intr"   r   r   updater   utcnowsave)datar*   r!   r%   
cart_countcourseexistings          r   add_to_cartrH      sD    >D%Igy$/G %4E[\]^`ccc||w',,T8=STZZ\ %4E[\]^`ccc#D)J
4;;!!%4Mcmnoqttt %4G]ghiknnn9-335 %4G]ghiknnn 6==A!#%4H^hijlooo ?EEGH??a3$.  	  	A9JKHYZ__a#D)J)&  		 _ \*   \* s$   5G1 $H	 1HH	HHz/cart/itemsc                     t        t        dd      } | st        dddd      dfS 	 t        j                  |       j                  d	d
      j                         }|st        dddd      dfS t        |j                  xs d      dk7  rt        |      }t        dd|d      dfS t        t        j                  |d      j                  d            }g }g }|D ]  }|j                  }|rt        t        |d
d            dk7  r|j!                  |j"                         G|j!                  t%        |j"                        |j&                  r|j&                  j)                         ndi d	t%        |j"                        d|j*                  dt        |j,                  xs d      d|j.                  dt        |j0                  xs d      dt        |j2                  xs d      d
t        |j                  xs d      dt        |j4                  xs d      dt        |dd      rt%        |j6                  j"                        nddt        |dd      rt%        |j8                  j"                        ndd|j:                  dt=        j                  |j"                  d      j?                         d|j&                  r|j&                  j)                         nddtA        j                  |j"                  d      j?                         dtC        j                  |j"                  d      j?                         dtE        j                  |j"                  d      j?                         d         |r&t        j                  |!      jG                  d"       t        d#d$tI        |      |d%      d&fS # t        t        f$ r d}Y uw xY w)'z
    Fetch active cart items for current user, and auto-soft-remove items whose course is inactive/missing.
    Body: none (user_id from JWT)
    r!   NFr+   r   r,   r/   r0   r1   r"   r3   r   r4   r5   r    z-created_datecourse_title
course_feecourse_imagediscounted_feedurationpositionexam_idsub_exam_idlanguagevideo_count)r*   r"   r;   ebook_countmock_test_countold_papers_count)cart_item_idadded_atrF   id__inr9   TzCart fetched successfully)r"   r-   r.   itemsr8   )%r=   r   r   r   r#   r>   r?   r   r   r@   r"   r&   listr   order_byr*   appendr1   strr;   	isoformatrJ   rK   rL   rM   rN   rO   rP   rQ   rR   r
   r$   r   r   r   rA   len)r!   r%   current_countr\   to_soft_removepayloaditrF   s           r   get_cart_itemsrg      s    gy$/G%4E[\]^`ccc||w',,T8<BBD %4E[\]^`ccc
4;;!!*400 -
  	 	 !!$q9BB?STENG 3wvx;<A!!"%%(J79113Dc&))n 3 3 c&"3"3"8q9  3 3	
 !#f&;&;&@q"A C 415 #fmm0q1 C 415 WVYPT5U3v~~001[_ WV]\`=as6#5#5#8#89gk FOO 199FIIVWX^^` 6CVCV 3 3 = = ?\` u}}vyyKQQS "8#3#3fiiPQ#R#X#X#Z  #I$5$5		RS$T$Z$Z$\!
 	> /6616E.L	 
 	 i \* s   4N; ;OOz/cart/removec                     t               } | j                  d      }t        t        dd      }|st	        dddd      dfS 	 t        j                  |	      j                  d
d      j                         }|st	        dddd      dfS t        |      }t        |j                  xs d      dk7  rt	        dd|d      dfS |st	        dd|d      dfS 	 t        j                  ||d      j                  d      }t        |      }|dk(  rt	        dd|d      dfS t	        dd|d      dfS # t        t        f$ r d}Y w xY w# t        $ r d}Y Vw xY w)z
    Remove a course from the current user's cart (soft remove: status -> 0).
    Body (JSON or form-data):
      - course_id: <MongoID>
    user_id is taken from JWT.
    r*   r!   NFr+   r   r,   r/   r0   r1   r"   r3   r   r4   r5   r6   r7   r!   r*   r"   r[   zCourse not in cartTzCourse removed from cartr8   )r   r<   r=   r   r   r   r#   r>   r?   r   r   r&   r@   r"   r   rA   )rD   r*   r!   r%   rc   updated	new_counts          r   remove_from_cartrl   "  s    >D%Igy$/G %4E[\]^`ccc||w',,T8<BBD %4E[\]^`ccc 't,M
4;;!!0 -
  	 	 * -
  	 	""49QOVVcdVe #4(I!|+ )
  	 	 -%  		 S \* 6  s$   4D. (E .EEEE)r   r   )ReturnDocument)TransactionHistory)UserCoursePurchasez/cart/checkout-allc                  *   t        j                  d      xs  t         j                  j                  d      } d}t	        | t
              r+d| v r| j                  d      }nd| v r| j                  d      }|r$t	        |t        t        f      rt        |      dk(  rt        dd	d
      dfS t        t         dd      }|st        ddd
      dfS 	 t        j                  |      j                  ddd      j                         }|st        ddd
      dfS t%        |j&                  xs d      dk7  rt        ddd
      dfS 	 t        t)        j                  |            }|D ch c]  }t+        |j,                         }}|s2t        ddt        |      t%        |j.                  xs d      d      dfS t        t1        j                  |d|      j3                  d            }|D ch c].  }|j4                  st+        |j4                  j,                        0 }	}|D 
cg c]	  }
|
|	vs|
 }}
g }g }g }|D ]  }|j4                  }|rt%        t        |dd            dk7  r|j7                  |j,                         Ft9        j                  ||d      j                         r|j7                  |j,                         |j7                  ||f        |r&t1        j                  |      j;                  d       |r&t1        j                  |      j;                  d       |sPt        ddt        |      t        |      t        |      t        |      t%        |j.                  xs d      d       dfS |j=                  d! "       g }|D ]V  \  }}t%        t        |d#d      xs d      }t%        t        |d$d      xs d      }|dkD  r|n|}|j7                  |||f       X t?        d% |D              }t%        |j.                  xs d      }|}|dkD  rt        j@                         }|jC                  |j,                  d&|id'd(d| iitD        jF                  )      }|s[t        dd*|t%        |j.                  xs d      t        |      t        |      t        |      t        |      t        |      d+	      dfS t%        |j                  d      xs d      }||z   }g }|}|D ]  \  }}}t9        ||t%        |xs d      tI        jJ                         d,      jM                         }|dkD  ritO        d|d-d.t%        |      d/|jP                   d||t%        |      z
  d0
      jM                         }|t%        |      z  }t+        |j,                        }nd}|j;                  d       |j7                  t+        |j,                        |jP                  t%        |xs d      t+        |j,                        |d1        t        dd2t        |      t        |      t        |      t        |      t        |      t        |      |||d3      d4fS # t         t"        f$ r d}Y kw xY w# t         $ r g }Y w xY wc c}w c c}w c c}
w )5a  
    Bulk purchase ONLY the specified cart items for current user.
    Body (JSON or form-data):
      - course_ids: [ "<course_id>", "<course_id>", ... ]  (REQUIRED)
    Uses discounted_fee when > 0 else course_fee.
    Zero-fee courses are allowed (no TransactionHistory entry).
    Tr   F)flatN
course_idszcourse_ids[]r   z4course_ids is required and must be a non-empty array)r"   r-   r7   r!   r+   r/   r0   r1   r"   r2   r3   r   r4   r5   rY   zNo valid course ids found)r"   r-   not_in_cartwallet_balance)r!   r"   course_id__inr;   ri   r[      z9No eligible items to purchase for the provided course_ids)r"   r-   selected_countrs   removed_inactivealready_purchasedrt   c                 L    | d   j                   xs t        j                         S )Nr   )r;   r   rB   )pairs    r   <lambda>z#checkout_all_cart.<locals>.<lambda>  s    47#7#7#L8??;L r   )keyrM   rK   c              3   4   K   | ]  \  }}}|d kD  s|  yw)r   Nr   ).0_fees      r   	<genexpr>z$checkout_all_cart.<locals>.<genexpr>  s     =IAq#S1WC=s   z$gte)_idr2   z$inc)return_documentzInsufficient coins)	r"   r-   requiredrt   rw   eligible_countrs   rx   ry   )r!   r*   purchase_coin_amountpurchase_dater"   course_purchasedebitzCourse purchase: )
	parent_idr!   transaction_type
entry_typeamountdescriptionrelated_user_idbalance_beforebalance_aftertransaction_status)r*   titler   purchase_idtransaction_idzCheckout completed)r"   r-   rw   r   rs   rx   ry   purchased_counttotal_spentrt   purchased_itemsr8   ))r   r   r   r   
isinstancedictr<   r]   tuplerb   r   r=   r   r#   r>   r?   r   r   r@   r"   r   r`   r1   r2   r   r^   r*   r_   ro   rA   sortsum_get_collectionfind_one_and_updaterm   AFTERr   rB   rC   rn   rJ   )re   rr   r!   r%   selected_coursescselected_course_ids
cart_itemsrf   in_cart_course_idscidrs   eligiblerx   ry   rF   enriched
discountedregulareffective_fee	total_feer   r   coll	after_docr   rolling_beforer   purchasetxtx_ids                                  r   checkout_all_cartr     s    d+Ow||/C/C/C/OGJ'4 7" \2Jw& ^4J Z
T5MBc*oYZFZ%4jklnqqq gy$/G%4EFGLL||w',,T8=STZZ\ %4EFGLL
4;;!!%4MNOQTTTj AB /??3qtt9??2z?!$";";"@qA	
 
  	 a?OPYYZhiJ
 :DT2r||#blloo.TT",N3;M0M3NKNH  &3wvx;<A##BEE* %%dfQOUUW$$RUU+V%&  0188Q8G 1299a9HR!*o{+ #$4 5!$%6!7!$";";"@qA
   	 MMLMM H 5
F)91=BC
gflA6;!<&01n
'V]34	5 ===I 116Q7M"N1}##%,,GGfi5HI,yj9:*00 - 
	
 /%"%d&?&?&D1"E"%j/"%h-";/$'(8$9%():%;
 
 
 
 IMM*@AFQG&2 O#N# %FC%!$SXA"//+
 $& 	 7#!2"3x/0C0C/DE $-,s3x7#$ df  c#h&NJEE 			a	 VYY((#(mx{{+# 
 	?%N 'j/h-;' 01 !23/ '*  	 o \*   ?  UNsB   5Y Y4 'Z-Z?!Z&	Z0ZY10Y14ZZz/courses/purchasedc                     t        t        dd      } | st        ddg d      dfS 	 t        j                  |       j                  dd	      j                         }|st        ddg d      d
fS t        |j                  xs d      dk7  rt        ddg d      dfS t        t        j                  |d      j                  d            }|st        ddg d      dfS t        j                         }g }g }|D ]  }|j                   }|st        t        |dd      xs d      }|j"                  xs |}	|dkD  r@|	t%        |      z   }
||
kD  }|
j&                   d|
j)                  d       }|rdnd d| }nd}|j+                  t-        |j.                        t        |dd      rt-        |j0                  j.                        ndt        |dd      rt-        |j2                  j.                        nd|j4                  |j6                  t        |j8                  xs d      ||	j;                         t        |j                  xs d      ||j;                         d       |j+                  |j.                          |st        ddg d      dfS 	 |r&t        j                  |      j=                  |       t        d d!|d      dfS # t        t        f$ r d}Y w xY w# t>        $ r Y 4w xY w)"al  
    Fetch purchased courses for the current user.
    Steps:
      1) Validate user exists and is active
      2) Fetch purchase list (status=1), compute course_expiring using Course.duration
         - "Expires on <D Mon YYYY>" if not expired
         - "Expired on <D Mon YYYY>" if expired
      3) Update last_opened_date for the returned purchases to now
    r!   NFr+   )r"   r-   purchased_coursesr/   r0   r1   r"   r3   r   r   r4   r5   r    z-purchase_datezNo courses purchased yetr8   rN   )days z%b %YExpiredExpiresz on zExpires on N/ArP   rQ   )r*   rP   rQ   rJ   rL   rK   rN   r   r"   course_expiringlast_opened_daterY   )set__last_opened_dateTz&Purchased courses fetched successfully) r=   r   r   r   r#   r>   r?   r   r   r@   r"   r]   ro   r^   r   rB   r*   r   r	   daystrftimer_   r`   r1   rP   rQ   rJ   rL   rK   ra   rA   	Exception)r!   r%   	purchasesnowre   touched_idsprF   duration_dayspdateexpire_dateexpiredexp_strr   s                 r   r   r   f  s     gy$/G%4E\^_`beee||w',,T8<BBD %4E\^_`beee
4;;!!%4Mdfghjmmm ""4:CCDTUI 1!#
  	 	 //
CGK "! GFJ:?a@&3 1)"??KK'G$);+?+?+H*IJG.59 ET'SO /OVYY18D1Qs6>>,,-W[9@X\9]3v11445cg"//"//f//415%"__.!((-a(. #
 	 	144 E"!H 1!#
  	 	&&k:AAX[A\
 ;$  		 W \* N  s#   4K (K# K K #	K/.K/N)+flaskr   r   r   mongoengine.errorsr   r   r   r	   models.video_courses_modelr
   models.ebooks_modelr   models.mock_test_modelr   models.old_papers_modelr   utils.jwt_servicer   models.userr   models.courser   models.cart_itemr   models.sub_examr   __name__r   r   r&   routerH   rg   rl   pymongorm   models.transaction_historyrn   #models.user_course_purchase_historyro   r   r   r   r   r   <module>r      sQ  n . - < ' 9 % + - *    % # Ix
(C< 	{VH-E  .EP 	}vh/E  0EP 	~x0?  1?F # ' " < *    % 9 B #^	 	#fX6A  7AF 	#fX6`  7`r   