o
    4%i_                     @   s  d dl Z d dl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mZ d d	lmZ d d
lmZmZmZ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Zd dl Z d dlm!Z!m"Z" d dl#m$Z$ d dl%m%Z% G dd de&Z'G dd de&Z(G dd de&Z)G dd de&Z*G dd de&Z+G dd de&Z,G dd de&Z-G dd  d e&Z.dtd"d#Z/d$e0d!efd%d&Z1d'ed!e2fd(d)Z3d'ed!e2fd*d+Z4d'ed!e2fd,d-Z5d'ed!e6fd.d/Z7d'ed!e2fd0d1Z8d2e6d!e2fd3d4Z9d'ed!e2fd5d6Z:d'ed!e2fd7d8Z;d$e0d!e2fd9d:Z<dtd;d<Z=d!e
fd=d>Z>d!e?fd?d@Z@dAe
dBe0d$e0d!dfdCdDZAdEed2e2d!dfdFdGZBdEedHe2d!dfdIdJZCdEedKe2d!dfdLdMZDdEedNe2dOeEd!dfdPdQZFdEedRe6d!eEfdSdTZGdEedUe2d!dfdVdWZHdXeIfdYdZZJdEed[e2dOeEd!dfd\d]ZKdEed^e2d!dfd_d`ZLdadb ZMdceddeEd!dfdedfZNdgdh ZOdBe0d$e0die0d!dfdjdkZPd$e0dBe0d!dfdldmZQd$e0dne0d!dfdodpZRd$e0dqe0d!dfdrdsZSdS )u    N)load_workbook)PatternFill)BorderSide)	Worksheet)Workbook)copy)coordinate_from_stringcolumn_index_from_string)	CellRange)CustomOrderTrackingOrdersPaymentOrderProductsDeliverySlot)SKUProducts)Users)ShopProductionUnit)Font	Alignment)Path)	num2wordsc                       *   e Zd ZdZdeddf fddZ  ZS )OutputPDFNotFoundError
    Exception for Output pdf not found instance
    value -- path provided
    message -- output pdf file not found, please check the output path

    valuereturnNc                    *   || _ d| _t | j d| j   d S )Nz8Output pdf file not found, please check the output path.: r   messagesuper__init__selfr   	__class__ @/var/www/html/Testing_prj/Navya-Bakers/bill_writer/BillWriter.pyr$         zOutputPDFNotFoundError.__init____name__
__module____qualname____doc__strr$   __classcell__r)   r)   r'   r*   r          r   c                       r   )ErrorConvertingPDFr   r   r   Nc                    r   )Nz#Output pdf file generation failed!.r    r!   r%   r'   r)   r*   r$   *   r+   zErrorConvertingPDF.__init__r,   r)   r)   r'   r*   r4   "   r3   r4   c                       r   )OuptputExcelNotFoundErrorz
    Exception for Output Excel not found instance
    value -- path provided
    message -- output excel file not found, please check the output path

    r   r   Nc                    r   )Nz:Output excel file not found, please check the output path.r    r!   r%   r'   r)   r*   r$   8   r+   z"OuptputExcelNotFoundError.__init__r,   r)   r)   r'   r*   r5   0   r3   r5   c                       r   )TemplateNotFoundErrorz
    Exception for Template not found instance
    value -- path provided
    message -- invalid template path, file not found

    r   r   Nc                    r   )N&Invalid template path, file not found.r    r!   r%   r'   r)   r*   r$   F   r+   zTemplateNotFoundError.__init__r,   r)   r)   r'   r*   r6   >   r3   r6   c                       s"   e Zd ZdZd fddZ  ZS )OutputFolderCreationErrorz
    Exception for creating folder for storing ouput
    value -- Please check permission issues
    message -- Error creating Output Folders

    r   Nc                    s*   d| _ d| _t | j d| j   d S )NzPlease check permission issuesr7   r    r!   r&   r'   r)   r*   r$   T   r+   z"OutputFolderCreationError.__init__r   N)r-   r.   r/   r0   r$   r2   r)   r)   r'   r*   r8   L   s    r8   c                       r   )TemplateFileAlreadyOpenedz
    Exception for Template file already opened
    value -- path provided
    message -- template file already opened, please close the file and try again

    r   r   Nc                    r   )NzBTemplate file already opened, please close the file and try again.r    r!   r%   r'   r)   r*   r$   b   r+   z"TemplateFileAlreadyOpened.__init__r,   r)   r)   r'   r*   r;   Z   r3   r;   c                       s.   e Zd ZdZdededdf fddZ  ZS )HeaderMismatchErrorz
    Exception for Header mismatch
    value -- expected header, actual header
    message -- Header mismatch, please check the template file

    expected_headeractual_headerr   Nc                    s8   || _ || _d| _t | j d| j  d| j  d S )Nz0Header mismatch, please check the template file.z Expected: z
, Actual: )r=   r>   r"   r#   r$   )r&   r=   r>   r'   r)   r*   r$   p   s   &zHeaderMismatchError.__init__)r-   r.   r/   r0   listr$   r2   r)   r)   r'   r*   r<   h   s    "r<   c                       r   )DataNotFoundErrorz}
    Exception for Data not found
    value -- data provided
    message -- No data provided to write to the excel file

    r   r   Nc                    r   )NzData Not Foundr    r!   r%   r'   r)   r*   r$      r+   zDataNotFoundError.__init__r,   r)   r)   r'   r*   r@   w   r3   r@   r   c                 C   s   t j| s
t| d S N)ospathexistsr6   )template_pathr)   r)   r*   _check_template_exist   s   rF   order_idc                 C   s$   t jj| d}|std|  |S )z
    Fetch order data from the database.
    This is a placeholder function and should be replaced with actual logic to fetch order data.
    )order_IDNo data found for order ID: )r   objectsgetr@   )rG   orderr)   r)   r*   _fetch_order_data   s   rM   rL   c                 C   sJ   t jj| d }|std| j |jj|jr|jdndd}|S )z
    Fetch payment data related to the order.
    This is a placeholder function and should be replaced with actual logic to fetch payment data.
    rL   z$No payment data found for order ID: %Y-%m-%dN/A)Invoice NumberInvoice Date)	r   rJ   filterfirstr@   rH   rL   payment_datestrftime)rL   paymentinvoice_detailsr)   r)   r*   _fetch_invoice_details   s   rY   c           	      C   s   z`| j r
| j dnd}| jr| jdnd}| d| }|dkr$|}| jr-d| j nd}d}| jr:t| jjnd}| jd	krKtj	j
| d
 }nd}| j||||| jd	krZ|ndd}W |S    td| j )z
    Fetch additional details related to the order.
    This is a placeholder function and should be replaced with actual logic to fetch additional details.
    rO   rP   z%H:%M    ₹   ₹0UPI Custom OrdersrN      )Order NoSlotPayable AmountPayment ModeSourceNo of itemsz*No additional details found for order ID: )delivery_slot_daterV   delivery_slot_timegrand_total
store_uuidr1   	unit_name
order_typer   rJ   rS   countrH   r@   )	rL   rg   rh   slotpayable_amountpayment_modesourceno_of_itemsadditional_detailsr)   r)   r*   _fetch_additional_details   s,   

rt   c                 C   s   z:| j rd| j dnd}| jrd| jdnd}| jr#d| jdnd}| jr/d| jdnd}||||d}W |S    td| j )z
    Fetch other charges related to the order.
    This is a placeholder function and should be replaced with actual logic to fetch other charges.
    r[   .2fr\   )Handling ChargesDelivery ChargesDiscountTotal Amountz%No other charges found for order ID: )coupon_savingsdelivery_chargesdiscountri   r@   rH   )rL   handling_chargesr{   r|   total_amountother_chargesr)   r)   r*   _fetch_other_charges   s   r   c                 C   s  z| j dkrtjj| d}g }|D ]v}|jjjpd}|jjjp d}|jjjp'd}|| | d }t	|jj
| }t	|jj
| }	t	|j|	 }
|jjr^|jjr^|jj d|jj |jj n|jj|jjt|j|jj
d|d|	dt	|t	|t	||
dd
}|| q|W S tjj| d}g }|D ]5}|jr|jnd	}|j d
|  }t	| jpd}|}
dd||dd|dddd|
dd
}|| q|W S  ty } ztd| j d| d}~ww )zF
    Fetch item details for both normal orders and custom orders.
    r_   rN   r   d   -ru   )
Item DescriptionHSN CodeQuantity
Unit PriceUnit Tax ValueGross ValueCGST Rate(%) AmountSGST Rate AmountCESS AmountTotal)rG   r^   rZ   zCustom Order ItemrP   z0.00        z$No item details found for order ID:  :: N)rl   r   rJ   rS   skuproductc_gsts_gstcessfloatsku_mrpquantitysku_quantitysku_unitsku_namesku_coder1   appendr   quantity_unitstripri   	Exceptionr@   rH   )rL   itemsitem_detailsitemr   r   r   	tax_totalunit_tax_valuegross_valuetotalitem_detailcustom_itemsqty_unitqty_displaypriceer)   r)   r*   _item_details   sn   
 
r   c                 C   s.   z| j | j }W n   d}Y | j|d}|S )Nr   )r   	Sub Total)	sub_totaltaxes_and_chargesri   )rL   r   totalsr)   r)   r*   _total1  s   r   rX   c              
   C   s   z=d}d}d}| D ]+}z |t |dd }|t |dd }|t |dd }W q	 ty4   Y q	w |||d}|W S  tyM } ztdd }~ww )Nr   r   zTaxable ValueszOther Charges)r   zTotal Other ChargeszTotal Taxable Valuesz*Error calculating total for invoice detais)r   rK   
ValueErrorr   )rX   r   total_taxable_chargestotal_other_chargesir   r   r)   r)   r*   _item_details_total:  s(   r   c              
   C   sR  z| j dkrc| j}|rT|jr|j dnd}||jr!|j dnd7 }||jr.|j dn|jr9d|j d n|jrDd|j d nd7 }||jrPt|jnd7 }nd}|j	||j
|jd}|W S | j dkr| j}|r|jrv|j dnd}||jr|j dn,|jrd|j d n!|jrd|j d n|jrd|j d n|jrdt|j nd7 }nd}|j||j
|jd}|W S | j}|r|jr|j dnd}||jr|jnd7 }||jr|jn|jrd|j n	|jrd|j nd7 }||jrt|jnd7 }nd}|j	||j
|jd}|W S  ty( } ztd| j d| d	}~ww )
z
    Fetch shop details related to the order.
    This is a placeholder function and should be replaced with actual logic to fetch shop details.
    zLocal Orders
r^   rP   )	Shop NameShop Address
Shop Phone
Shop EmailzLong Distance Ordersz$No shop details found for order ID: r   N)rl   rj   unit_locationstreetcitydistrictstate_or_provincepin_coder1   rk   
contact_noemailpu_uuidpu_locationpu_namer   r@   rH   )rL   shopshop_addressshop_detailsproduction_unitproduction_unit_addressr   r)   r)   r*   _fetch_shop_detailsQ  s   


)



r   c              
   C   s  z| j }|std| j | jdkr| jjr| jj dnO| jjr+d| jj d nB| jjr8d| jj d n5| jjrEd| jj d n(| jj	rRd| jj	 d n| jj
r_d| jj
 d n| jjrld| jj d nd}| jjrv| jjn| jj}| jjr| jjn|jr|jnd}nd}|jrt|jn|jrdt|j nd}|jr|jnd}||||jr|jndd}|W S  ty } ztd| j d| d}~ww )	z
    Fetch user details related to the order.
    This is a placeholder function and should be replaced with actual logic to fetch user details.
    z$No user details found for order ID: zPick Upr   r^   rP   )	User NameUser Address
User Phone
User Emailz::N)	user_uuidr@   rH   rl   drop_addresshouse_number_or_namer   	land_markr   r   r   r   namecontact_numberphone_number
first_namer1   	last_namer   r   )rL   useruser_address	user_namer   user_detailsr   r)   r)   r*   _fetch_user_details  sX   
"(r   c           
   
   C   s   zFt | }t|}t|}t|}t|}td|  d|  t|}t|}t	|}|s5t
d|  ||dddddd|||||dW S  ty\ }	 z
t
d|  d	|	 d }	~	ww )
Nz Item Details for all the orders r    rI   	   i     )CGST%SGST%SaleTaxable Value	Tax Value)rX   additonal_detailsgst_infor   r   r   r   r   r   )rM   rY   rt   r   r   logginginfor   r   r   r@   r   )
rG   
order_datarX   rs   r   r   r   r   r   r   r)   r)   r*   _serialize_order_data  s4   r   c               
   C   s   t jds(zt d t d t d W d S  ty' }  zt d } ~ ww t jds=zt d W d S    t t jdsRzt d W d S    t d S )Nz./media/outputz./media/output/excelz./media/output/pdf)rB   rC   rD   mkdirr   r8   )r   r)   r)   r*   _check_output_dir  s(   

r   c                 C   s   zt | }W |S    t| rA   )r   r;   )rE   wbr)   r)   r*   _open_excel  s
   
	r   c                 C   s&   | j stdt| j tstddS )zu
    Write data to the excel file
    data -- dictionary with key as column name and value as data to be written
    z,No data provided to write to the excel file.zTData should be a dictionary with key as column name and value as data to be written.T)datar@   
isinstancer?   	TypeErrorr9   r)   r)   r*   _write_excel  s
   r   r   output_excelc                 C   s>   | st d| |d| d  |   td|  dS )z0
    Save the excel file to the output path
    z?Workbook is not opened. Please open the workbook before saving./.xlsxzExcel file saved at N)r   savecloser   r   )r   r   rG   r)   r)   r*   _save_excel  s
   r   	worksheetc                 C   sj   t d|  |stdt|tstd|dd}|dd}| jdd|d	 | jd
d|d	 dS )z4
    Write the invoice details to the worksheet
    Invoice Details: z7No invoice details provided to write to the excel file.z_Invoice details should be a dictionary with key as column name and value as data to be written.rQ   rP   rR         rowcolumnr      N)r   r   r@   r   dictr   rK   cell)r   rX   invoice_numberinvoice_dater)   r)   r*   _write_invoice_details  s   
r  rs   c                 C   s   |st dt|tstd|dd}|dd}|dd}|dd}|dd}|d	d}| jd
d|d | jdd|d | jdd|d | jdd|d | jdd|d | jdd|d d S )Nz:No additional details provided to write to the excel file.zbAdditional details should be a dictionary with key as column name and value as data to be written.ra   rP   rb   rc   rd   re   rf      r   r   r   
            r@   r   r  r   rK   r  )r   rs   order_norn   ro   rp   rq   rr   r)   r)   r*   _write_additional_details*  s$   
r  r   c                 C   s   |st dt|tstd|dd}|dd}|dd}|dd}|dd}| jd	d
|d | jdd
|d | jdd
|d | jdd
|d | jdd
|d d S )Nz0No GST info provided to write to the excel file.zXGST info should be a dictionary with key as column name and value as data to be written.r   rP   r   r   r   r      r   r               r  )r   r   cgstsgstsaletaxable_value	tax_valuer)   r)   r*   _write_gst_info?  s   
r  r   row_noc                 C   s   |st dt|tstd|dd}|dd}|dd}|dd}| j|d d	|d
 | j|d d	|d
 | j|d d	|d
 d S )Nz5No other charges provided to write to the excel file.z]Other charges should be a dictionary with key as column name and value as data to be written.rv   rP   rw   rx   ry   r     r   r  r	  r  )r   r   r  r}   r{   r|   r~   r)   r)   r*   _write_other_chargesT  s   
r  r   c                 C   s  |st dt|tstdd}t|ddD ]\}}|dd}|dd}|d	d}|d
d}|dd}	|dd}
|dd}|dd}|dd}|dd}| jd| d|d | jd| d|d | jd| d|d | jd| d|d | jd| d|d | jd| d|	d | jd| d|
d | jd| dt|d d | jd| dt|d d | jd| dt|d d | jd| d|d d| }q|S )Nz4No item details provided to write to the excel file.zfItem details should be a list of dictionaries with key as column name and value as data to be written.r  r`   )startr   rP   r   r   r   r   r   r   r   r   r   r   r   r  r         r  r   r  r	  r
  r   r  r  )r@   r   r?   r   	enumeraterK   r  r   )r   r   r  idxr   item_descriptionhsn_coder   
unit_pricer   r   cgst_rate_amountsgst_rate_amountcess_amountr   r)   r)   r*   _write_item_detailse  s>   

r(  r   c                 C   s   |st dt|tstd|dd}|dd}|dd}|dd}d| d	 | d	 | d	 | }| jd
d|d d S )Nz4No shop details provided to write to the excel file.z\Shop details should be a dictionary with key as column name and value as data to be written.r   rP   r   r   r   zDetails of Supplier

r   r   r  r   r  )r   r   	shop_namer   
shop_phone
shop_email	shop_datar)   r)   r*   _write_shop_details  s   
 r-  r   c                 C   s^   t | }t t| | d }dt|dd  }|dkr)|dt|dd d7 }|d7 }|S )	Nr   zRupees en_IN)langr   z and z paisez only)introundr   
capitalize)r   rupeespaisewordsr)   r)   r*   _convert_to_words  s   r6  r   c                 C   s   |st dt|tstd|dd}|dd}t|}|r'd|dnd}|r1d|dnd}| j|d	 d
|d | j|d d|d tddd| j|d dd_| j|d d|d d S )Nz5No total details provided to write to the excel file.z]Total details should be a dictionary with key as column name and value as data to be written.r   r   r   r[   ru   r\   r`   r   r   r
  leftcenter)
horizontalverticalr   r   r  )	r@   r   r  r   rK   r6  r  r   	alignment)r   r   r  item_details_totalri   textr)   r)   r*   _write_totals  s   
r?  r   c                 C   s   |st dt|tstd|dd}|dd}|dd}|dd}d}||r3|  d	nd
7 }||r@|  d	nd
7 }||rM|  d	nd
7 }||rZ|  d	nd
7 }| jdd|d d S )Nz4No user details provided to write to the excel file.z\User details should be a dictionary with key as column name and value as data to be written.r   rP   r   r   r   zBill to/Ship to

r   r^   r   r   r   )r@   r   r  r   rK   r   r  )r   r   r   r   
user_phone
user_email	user_datar)   r)   r*   _write_user_details  s   
rC  c                 C   st   g }t | jjD ]#}|j|kr+| jj| t|j| |j| |j|jd}|	| q|D ]	}| 
t| q.d S )N)min_rowmax_rowmin_colmax_col)r?   merged_cellsrangesrD  remover   rE  rF  rG  r   merge_cellsr1   )ws	start_rowoffset
new_rangescrnew_crrr)   r)   r*   _shift_merged_cells  s   

rS  rL  r   c                 C   s   t | |d | j|d dS )z
    Add a new row to the worksheet with the given data.
    :param ws: The worksheet to add the row to.
    :param row_data: A list of values to be added in the new row.
    :param start_row: The row number where the new row will be added.
    r`   )r!  N)rS  insert_rows)rL  r   r)   r)   r*   _add_row  s   rU  c                 C   s4  | j }td|d D ]}| j||d}| j||d}|j|_|jrt|j|_|dkrD|dkrDttddtddtddtddd|_	|dkrQttddd	|_	|d
kr^ttddd|_	|dksj|dksj|dkrmd|_
t|j|_t|j|_t|j|_t|j|_t|j|_q
d| j| _d| j| _d S )Nr`   r;  r   r   thin)style)bottomr7  righttop   )r7  r  )rY  r
  r  r  z0.00%(   )
max_columnranger  r   	has_styler   fontr   r   bordernumber_formatfill
protectionr<  comment	hyperlinkrow_dimensionsheight)rL  from_rowto_rowrG  colsource_celltarget_cellr)   r)   r*   	_copy_row  s0   rn  pdf_dirc           
   
   C   s  zt j| | d}d}|}t| }t| }|jddd | s-td| d| d| d}t j	 }t 
 d	kr_td
 d|d< ||d< t j|d dd t |d d ztjdddtjd}td|  W n ty }	 ztd|	  W Y d}	~	nd}	~	ww ztj|ddtj|d}W n ty }	 z|	}td|  tt|	d}	~	ww td| d|  W dS  ty }	 ztd|	  td|	 d}	~	ww )z
    Convert the excel file to pdf format.
    This is a placeholder function and should be replaced with actual logic to convert excel to pdf.
    r   z*/var/www/.cache/.config/libreoffice/4/userT)parentsexist_oku   ❌ Input file not found:zLlibreoffice --headless --norestore --nolockcheck --convert-to pdf --outdir 'z' ''r   zRunning as Root Userz/tmp/libreoffice-profile/XDG_RUNTIME_DIRHOME)rq  i  pwdz	/bin/bash)shell
executablestderrz"PDF conversion working directory: zChecking logic error: N)rv  rw  rx  envzError in PDF Conversion: zConverting z to zError converting excel to pdf: )rB   rC   joinr   resolver   rD   r4   environr   geteuidr   r   makedirschmod
subprocesscheck_outputSTDOUTr   r1   error)
r   rG   ro  output_filelibreoffice_home	file_pathcommandry  resultr   r)   r)   r*   _convert_to_pdf"  sP   


r  c                 C   B   t j||  d}t j|std| td|  dS )a   Check if the output excel file exists.
    Args:
        order_id (str): The order ID to check.
        output_excel (str): The path to the output excel directory.

    # output path creation pending
    Raises:
        DataNotFoundError: If the output excel file does not exist.
    r   z"Output excel file does not exist: zOutput excel file exists: N)rB   rC   rz  rD   r5   r   r   )rG   r   r  r)   r)   r*   _check_ouptput_excel_existW     
r  
output_pdfc                 C   r  )a   Check if the output pdf file exists.
    Args:
        order_id (str): The order ID to check.
        output_pdf (str): The path to the output excel directory.

    # output path creation pending
    Raises:
        DataNotFoundError: If the output pdf file does not exist.
    z.pdfz Output pdf file does not exist: zOutput pdf file exists: N)rB   rC   rz  rD   r   r   r   )rG   r  r  r)   r)   r*   _check_ouptput_pdf_existf  r  r  rE   c                 C   s  t d t| t  t|}|d }d|j_t| }t d|  |di }t d|  |di }|di }|d	i }|d
i }	|di }
|di }t	|| t
|| d}|dg }t|dkrtdt|D ]}t|d|  t|dd|  qut||}t||| t||| t||	 t||
 d}d}t|||  t| | t|| | t| | t d d S )NzExcel Writer ModuleSheet2FzData Details: rX   r   r   r   r   r   r   r   r   r   r`   r  zmedia/output/excelzmedia/output/pdfz)Excel Writer Module Executed Successfully)r   r   rF   r   r   
sheet_viewshowGridLinesr   rK   r  r  lenr^  rU  rn  r(  r?  r  r-  rC  r   r  r  r  )rG   rE   r   r   r   rX   rs   r   r   r   r   total_calculated_chargescounterr   r   r  r   ro  r)   r)   r*   template_writerv  sH   







r  r:   )TrB   openpyxlr   openpyxl.stylesr   r   r   openpyxl.worksheet.worksheetr   openpyxl.workbookr   r   openpyxl.utils.cellr	   r
   openpyxl.worksheet.cell_ranger   orders.modelsr   r   r   r   r   products.modelsr   r   accounts.modelsr   shops.modelsr   r   r   r  r   r   pathlibr   r   r   r   r4   r5   r6   r8   r;   r<   r@   rF   r1   rM   r  rY   rt   r   r?   r   r   r   r   r   r   r   r   boolr   r   r  r  r  r0  r  r(  r-  r   r6  r?  rC  rS  rU  rn  r  r  r  r  r)   r)   r)   r*   <module>   sr    
 U	?!
'*#5