o
    i	                     @   s@   d dl mZmZ d dlmZ d dlmZ d dlmZ dd ZdS )    )requestjsonify)closing)connect_to_database)datetimec           
   
   C   s  t  }|d}t }zzt|jdd}|d| f | }|s:tddddfW  d    W W |	  S |d|f | }|s]td	ddd
fW  d    W W |	  S |d dkrn|d |d d  }n	t
|d |d }|d | }|d||| f |d|d f |  td|dddfW  d    W W |	  S 1 sw   Y  W n) ty }	 z|  tdt|	 dddfW  Y d }	~	W |	  S d }	~	ww W |	  d S |	  w )Ndiscount_codeT)
dictionaryz:SELECT * FROM invoices WHERE id = %s AND status = 'unpaid'zUnpaid invoice not found)messageerrori  a8  
                SELECT * FROM discounts 
                WHERE code = %s 
                AND is_active = TRUE
                AND (start_date <= NOW() OR start_date IS NULL)
                AND (end_date >= NOW() OR end_date IS NULL)
                AND (max_uses IS NULL OR used_count < max_uses)
            zInvalid discount codei  Zdiscount_typeZ
percentagetotal_amountamountd   z
                UPDATE invoices 
                SET discount_amount = %s,
                    total_amount = %s
                WHERE id = %s
            z~
                UPDATE discounts 
                SET used_count = used_count + 1 
                WHERE id = %s
            idzDiscount applied successfullyF)r	   	new_totalr
      zError applying discount: i  )r   get_jsongetr   r   cursorexecutefetchoner   closemincommit	Exceptionrollbackstr)

invoice_iddatar   
connectionr   invoiceZdiscountZdiscount_amountr   e r!   T/Users/harjaapdhillon/Desktop/newidea/medvista_backend/Services/Billing/Discounts.pyapply_discount   s`   

6
6
62(
6r#   N)	flaskr   r   
contextlibr   confr   r   r#   r!   r!   r!   r"   <module>   s
    