o
    #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 d dlmZ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)Z0dyd!d"Z1d#e2d efd$d%Z3d&ed e4fd'd(Z5d&ed e4fd)d*Z6d&ed e4fd+d,Z7d d-l8m9Z9 d&ed e:fd.d/Z;d&ed e4fd0d1Z<d&ed e4fd2d3Z=d&ed e4fd4d5Z>d#e2d e4fd6d7Z?dyd8d9Z@d e
fd:d;ZAd<e
d=e2d#e2d dfd>d?ZBd@edAeCdBeCd dfdCdDZDd@edEe4d dfdFdGZEd@edHe4d dfdIdJZFdzd@edKe4dLeCd dfdMdNZGd@edOeCdPeHd dfdQdRZId{d@edTe:dPeHd dfdUdVZJd@edWe4d dfdXdYZKdZeHd e2fd[d\ZLdzd@ed]e4dLeCd dfd^d_ZMd@ed`e4d dfdadbZNdceddeCdeeCd dfdfdgZOdcedAeCd dfdhdiZPdcedjeCdkeCd dfdldmZQd=e2d#e2dne2d dfdodpZRd#e2d=e2d dfdqdrZSd#e2dse2d dfdtduZTd#e2dve2d dfdwdxZUdS )|    N)load_workbook)PatternFill)BorderSide)	Worksheet)Workbook)copy)coordinate_from_stringcolumn_index_from_string)	CellRange)
MergedCell)CustomOrderTrackingDiscountOrdersPaymentOrderProductsDeliverySlot)SKUProducts)Users)ShopProductionUnit)Font	Alignment)Path)	num2wordsc                       &   e Zd Zdeddf fddZ  ZS )OutputPDFNotFoundError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__strr%   __classcell__r*   r*   r(   r+   r          r   c                       r   )ErrorConvertingPDFr   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   )OuptputExcelNotFoundErrorr   r   Nc                    r    )Nz:Output excel file not found, please check the output path.r!   r"   r&   r(   r*   r+   r%   #   r,   z"OuptputExcelNotFoundError.__init__r-   r*   r*   r(   r+   r5   "   r3   r5   c                       r   )TemplateNotFoundErrorr   r   Nc                    r    )Nz&Invalid template path, file not found.r!   r"   r&   r(   r*   r+   r%   )   r,   zTemplateNotFoundError.__init__r-   r*   r*   r(   r+   r6   (   r3   r6   c                       s   e Zd Zd fddZ  ZS )OutputFolderCreationErrorr   Nc                    s*   d| _ d| _t | j d| j   d S )NzPlease check permission issueszError creating Output Foldersr!   r"   )r'   r(   r*   r+   r%   /   r,   z"OutputFolderCreationError.__init__r   N)r.   r/   r0   r%   r2   r*   r*   r(   r+   r7   .   s    r7   c                       r   )TemplateFileAlreadyOpenedr   r   Nc                    r    )NzBTemplate file already opened, please close the file and try again.r!   r"   r&   r(   r*   r+   r%   5   r,   z"TemplateFileAlreadyOpened.__init__r-   r*   r*   r(   r+   r9   4   r3   r9   c                       r   )DataNotFoundErrorr   r   Nc                    r    )NzData Not Foundr!   r"   r&   r(   r*   r+   r%   ;   r,   zDataNotFoundError.__init__r-   r*   r*   r(   r+   r:   :   r3   r:   r   c                 C   s   t j| s
t| d S N)ospathexistsr6   )template_pathr*   r*   r+   _check_template_existA   s   r@   order_idc                 C   s$   t jj| d}|std|  |S )Norder_IDNo data found for order ID: )r   objectsgetr:   )rA   orderr*   r*   r+   _fetch_order_dataF   s   rH   rG   c                 C   sJ   t jj| d }|std| j |jj|jr|jdndd}|S )NrG   z$No payment data found for order ID: %Y-%m-%dN/A)Invoice NumberInvoice Date)	r   rE   filterfirstr:   rC   rG   payment_datestrftime)rG   paymentinvoice_detailsr*   r*   r+   _fetch_invoice_detailsM   s   rT   c           
   
   C   s  zi| j r
| j dnd}| jr| jdnd}|dkr"| d| n|}| jr.d| jdnd}| jr7| jjnd}| jrBt| jjnd}| j	d	krSt
jj| d
 }nd}| j|||||d}td|  |W S  ty }	 ztd|	  td| j d }	~	ww )NrJ   rK   z%H:%M    ₹.2f   ₹0 Custom OrdersrI      )Order NoSlotPayable AmountPayment ModeSourceNo of itemszAdditional details: z#Error fetching additional details: z*No additional details found for order ID: )delivery_slot_daterQ   delivery_slot_timegrand_totalpayment_mode	mode_name
store_uuidr1   	unit_name
order_typer   rE   rN   countrC   logginginfo	Exceptionerrorr:   )
rG   rb   rc   slotpayable_amountre   sourceno_of_itemsadditional_detailser*   r*   r+   _fetch_additional_detailsX   s0   
	ru   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 )NrV   rW   rX   )Handling ChargesDelivery Chargesr   zTotal Amountz%No other charges found for order ID: )coupon_savingsdelivery_chargesdiscountrd   r:   rC   )rG   handling_chargesry   rz   total_amountother_chargesr*   r*   r+   _fetch_other_chargesx   s   r~   )Qc                 C   s\  z| j dkr'tjj| d}g }|D ]}|j}|j}t|jjp"d}t|jjp*d}t|jj	p2d}d}	t
jtd|jgdtd|jgdB td	|gd
B td|gdB }
|
D ]D}|jdkrm|j|j v rm|}	 n2|jdkr~|j|j v r~|}	 n!|jd	kr||j v r|}	 n|jdkr||j v r|}	 nqZt|j}t|j}|	rt|	j}t|| d d}nd}t|| d}t|| d}|| | d }t|| | d}t|| | d}|jr|jr|j d|j |j }n|j}||jt| rt|n||d|d|d||||d|dd}|| q|W S t jj| d}t!jj"| j#d}|j$r?t|j$nd}g }|D ]M}|j%rN|j%nd}|j d| & }t|j'p`d}d}t|| | d}|j(rt|j(ndd||d|d|dddd|d|dd}|| qE|W S  t)y } zt*d| j# d| d}~ww )uP  
    Returns item details with the updated calculation logic:

    - Gross Value   = Unit Price (MRP) × Quantity
    - Discount      = discount_per_unit × Quantity  (cumulative for all units)
    - Total Tax     = (Gross Value − Discount) × (CGST + SGST + CESS) / 100
    - Total Value   = Gross Value − Discount + Total Tax
    rZ   rI   r   NCategory)
DiscountOnApplicableCategory__inSubCategory)r   ApplicableSubCategory__inProduct)r   ApplicableProduct__inSku)r   ApplicableSku__ind              -rW   )Item DescriptionHSN CodeQuantity
Unit PriceGross Valuer   CGST Rate(%) AmountSGST Rate AmountCESS Amount	Total TaxTotal Value)rA   rB   rY   rU   zCustom Order ItemrK   z$No item details found for order ID:  :: )+ri   r   rE   rN   skuproductfloatc_gsts_gstcessr   r   item_categoryitem_sub_categoryr   ApplicableCategoryallApplicableSubCategoryApplicableProductApplicableSkusku_mrpquantityDiscountPercentageroundsku_quantitysku_unitsku_namesku_coder1   
is_integerintappendr   r   rF   rC   rz   quantity_unitstriprd   	item_namerm   r:   )rG   itemsitem_detailsitemr   r   r   r   r   applicable_discount	discountsrz   mrpr   discount_percentdiscount_per_unitgross_valuetotal_discounttax_rate	total_taxtotal_value	item_descitem_detailcustom_items	order_objdiscount_valqty_unitqty_displayrt   r*   r*   r+   _item_details   s   	



r   c                 C   s.   z| j | j }W n   d}Y | j|d}|S )Nr   )Totalz	Sub Total)	sub_totaltaxes_and_chargesrd   )rG   totaltotalsr*   r*   r+   _total  s   r   c           	   
   C   s  zU| j dkrr| j}|rLg }|jr||j |jr ||j |jr)||j |jr2||j |jr;||j |jrF|t	|j d
|}nd}|rS|jnd||rZ|jnd|r`|jnd|rkt|drk|jndd}|W S | j dkr| j}|rg }|jr||j |jr||j |jr||j |jr||j |jr||j |jr|t	|j d
|}nd}|r|jnd||r|jnd|r|jnd|rt|dr|jndd}|W S | j}|r,g }|jr||j |jr||j |jr||j |jr||j |jr||j |jr&|t	|j d
|}nd}|r4|jnd||r<|jnd|rC|jnd|rPt|drP|jndd}|W S  tyn } ztd| j d| d }~ww )	NzLocal Orders
rK   gstin)	Shop NameShop Address
Shop Phone
Shop Email
Shop GSTINzLong Distance Ordersz$No shop details found for order ID: r   )ri   rg   unit_locationr   streetcitydistrictstate_or_provincepin_coder1   joinrh   
contact_noemailhasattrr   pu_uuidpu_locationpu_namerm   r:   rC   )	rG   shopshop_address_linesshop_addressshop_detailsproduction_unitproduction_unit_address_linesproduction_unit_addressrt   r*   r*   r+   _fetch_shop_details  s   
>
#r   c              
   C   s  z| j }|std| j | jdkr| jrg }| jjr#|| jj | jjr.|| jj | jjr9|| jj | jj	rD|| jj	 | jj
rO|| jj
 | jjrZ|| jj | jjrg|t| jj d|}| jjrt| jjnd}| jjr~| jjn|jr|jnd}nd}|js|jr|j d|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 )	Nz$No user details found for order ID: zPick Upr   rY   rK   rU   )	User NameUser Address
User Phone
User Emailz::)	user_uuidr:   rC   ri   drop_addresshouse_number_or_namer   r   	land_markr   r   r   r   r1   r   namecontact_numberphone_number
first_name	last_namer   r   rm   )rG   useruser_address_linesuser_address	user_namer   user_detailsrt   r*   r*   r+   _fetch_user_detailsm  sH   
"&r   c           
   
   C   s   z?t | }t|}t|}t|}t|}td|  d|  t|}t|}t	|}|s5t
d|  |||||||dW S  tyU }	 z
t
d|  d|	 d }	~	ww )NzItem Details for order r!   rD   )rS   additonal_detailsr}   r   r   r   r   r   )rH   rT   ru   r~   r   rk   rl   r   r   r   r:   rm   )
rA   
order_datarS   rs   r}   r   r   r   r   rt   r*   r*   r+   _serialize_order_data  s0   
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 n   t t jdsQzt d W d S    t d S )Nz./media/outputz./media/output/excelz./media/output/pdf)r<   r=   r>   mkdirrm   r7   )rt   r*   r*   r+   _check_output_dir  s(   

r  c                 C   s   zt | }|W S    t| r;   )r   r9   )r?   wbr*   r*   r+   _open_excel  s
   r  r  output_excelc                 C   s>   | st d| |d| d  |   td|  d S )Nz?Workbook is not opened. Please open the workbook before saving./.xlsxzExcel file saved at )
ValueErrorsavecloserk   rl   )r  r  rA   r*   r*   r+   _save_excel  s
   r
  	worksheetrowcolumnc                 C   s  zO| j ||d}t|trJg }| jjD ]#}|j|  kr!|jkr6n q|j|  kr/|jkr6n q|	| q|D ]	}| 
t| q9| j ||d}||_W dS  ty } z+td| d| d|  z
| j |||d W n   Y W Y d}~dS W Y d}~dS d}~ww )z>Safely write to a cell, unmerging merged cells before writing.r  r  zError writing to cell (, z): )r  r  r   N)cell
isinstancer   merged_cellsrangesmin_rowmax_rowmin_colmax_colr   unmerge_cellsr1   r   rm   rk   rn   )r  r  r  r   r  ranges_to_unmergemerged_rangert   r*   r*   r+   _safe_write_cell  s,   

r  rS   c                 C   sT   t d|  |std|dd}|dd}t| dd| t| dd| d S )	NzInvoice Details: z7No invoice details provided to write to the excel file.rL   rK   rM            )rk   rl   r:   rF   r  )r  rS   invoice_numberinvoice_dater*   r*   r+   _write_invoice_details  s   r!  rs   c                 C   s   |st d|dd}|dd}|dd}|dd}|dd}|dd}t| d	d
| t| dd
| t| dd
| t| dd
| t| dd
| t| dd
| td| d| d| d| d| d|  d S )Nz:No additional details provided to write to the excel file.r\   rK   r]   r^   r_   r`   ra      r  	   
            z%Written additional details: Order No=z, Slot=z	, Amount=z, Mode=z	, Source=z, Items=r:   rF   r  rk   rl   )r  rs   order_noro   rp   re   rq   rr   r*   r*   r+   _write_additional_details  s.   r*  r}   
row_offsetc                 C   s   |st d|dd}|dd}|dd}t| d| d| t| d| d| t| d	| d| td
| d| d|  d S )Nz5No other charges provided to write to the excel file.rw   rX   r   rv               z Written other charges: Delivery=z, Discount=z	, Coupon=r(  )r  r}   r+  ry   rz   r{   r*   r*   r+   _write_other_charges  s    r0  	total_rowrd   c                 C   s   t dd}t||||d}d| d| }z| | W n	 ty%   Y nw | j|dd}d|_td	d
|_tddd|_	||_
| j|dd}d|d|_td	d
|_tddd|_	||_
d| j| _dS )zBWrite the grand-total summary row immediately after all item rows.thinstyle)topbottomleftrightEz:Or  r  r   T)boldr8  center)
horizontalverticalr  rV   rW      N)r   r   merge_cellsrm   r  r   r   fontr   	alignmentborderrow_dimensionsheight)r  r1  rd   r2  full_borderlabel_range
label_cell
value_cellr*   r*   r+   _write_row_total*  s&   
rI  r   r   c                 C   s  |st dd}t|ddD ]\}}|| d }|dd}|dd}|dd}	|d	d}
|d
d}|dd}t|dd}t|dd}t|dd}|dd}|dd}t| |d| t| |d| t| |d| t| |d|	 t| |d|
 t| |d| t| |dt|dsd| n| t| |d| d t| |d| d t| |d| d t| |d| t| |d| tdd D ]}| j||d!}t	d"d"d#d$|_
qq|t| }t| || d%S )&u%  
    Write item rows using the updated template column layout:

    E(5)  = Sl No.
    F(6)  = Item Description
    G(7)  = SKU Code
    H(8)  = Quantity
    I(9)  = Unit Price*
    J(10) = Gross Value*          (Unit Price × Quantity)
    K(11) = Discount*             (discount_per_unit × Quantity)
    L(12) = CGST Rate(%) Amount
    M(13) = SGST/UTGST Rate(%) Amount
    N(14) = CESS Amount
    O(15) = Total Tax             ((Gross Value − Discount) × tax_rate)
    P(16) = TOTAL Value           (Gross Value − Discount + Total Tax)
    z4No item details provided to write to the excel file.r  r[   )startr   rK   r   r   r   r   r   z0.00r   r   r   r   r   r   r        r"  r#  r$  r%  rV   r&  %r'     r-     r  r;  Tr<  r=  	wrap_textN)r:   	enumeraterF   r   r  r1   
startswithranger  r   rA  lenrI  )r  r   rd   	start_rowidxr   current_rowitem_descriptionhsn_coder   
unit_pricer   rz   	cgst_rate	sgst_ratecess_amountr   r   colr  r1  r*   r*   r+   _write_item_detailsF  sD   &r`  r   c           	      C   s   |st d|dd}|dd}|dd}|dd}|dd}d	dg}|| |r;|dkr;||d
 |rF|dkrF|| |rQ|dkrQ|| |r_|dvr_|d|  t| ddd
| | jddd}tdddd|_	d S )Nz4No shop details provided to write to the excel file.r   rK   r   r   r   r   rY   zDetails of Supplierr   )rK   rY   zGSTIN: r  r  r  r7  r5  TrP  )
r:   rF   r   extendsplitr  r   r  r   rA  )	r  r   	shop_namer   
shop_phone
shop_email
shop_gstinlinesr  r*   r*   r+   _write_shop_details  s(   


rh  r   c                 C   sz   z0t | }t t| | d }dt|dd  }|dkr*|dt|dd d7 }|d7 }|W S    d| d	d Y S )
Nr   zRupees en_IN)langr   z and z paisez onlyrW   )r   r   r   
capitalize)r   rupeespaisewordsr*   r*   r+   _convert_to_words  s   ro  r   c           
      C   s   |st d|dd}t|}d| }d| }t| |dd|d t| |d| |df|dffD ]\}}| j||d	}	td
ddd|	_q2td| d|  d S )Nz5No total details provided to write to the excel file.r   r         r&  rV   rW   r  r7  r;  TrP  zWritten totals: Amount=z, Words=)	r:   rF   ro  r  r  r   rA  rk   rl   )
r  r   r+  item_details_totaltextfig_rowwrd_rowr  r_  r  r*   r*   r+   _write_totals  s   rv  r   c                 C   s   |st d|dd}|dd}|dd}|dd}ddg}|r/| r/||  |r?| r?|| d	 |rL| rL||  |rY| rY||  t| d
dd	| | jd
dd}t	dddd|_
td| d|  d S )Nz4No user details provided to write to the excel file.r   rK   r   r   r   zBill to/Ship torY   r   r  r#  r  r7  r5  TrP  zWritten user details: r  )r:   rF   r   r   ra  rb  r  r   r  r   rA  rk   rl   )r  r   r   r   
user_phone
user_emailrg  r  r*   r*   r+   _write_user_details  s&   ry  wsrV  offsetc                 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)r  r  r  r  )listr  r  r  remover   r  r  r  r   r?  r1   )rz  rV  r{  
new_rangescrnew_crrr*   r*   r+   _shift_merged_cells  s   

r  c                 C   s   t | |d | j|d d S )Nr[   )rW  )r  insert_rows)rz  r  r*   r*   r+   _add_row  s   r  from_rowto_rowc                 C   s   | j }ttddtddtddtddd}td|d D ]O}| j||d}| j||d}t|ts7|j|_|jrat	|j
|_
t	|j|_t	|j|_t	|j|_d|  kr\dkran n||_t	|j|_t	|j|_qd| j| _d S )	Nr2  r3  )r6  r7  r8  r5  r[   r  r  r  (   )
max_columnr   r   rT  r  r  r   r   	has_styler   r@  fill
protectionrA  rB  comment	hyperlinkrC  rD  )rz  r  r  r  thin_borderr_  source_celltarget_cellr*   r*   r+   	_copy_row  s,   
r  pdf_dirc           	   
   C   sN  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tj|d td W W d S  ty } ztd|  tt|d }~ww  ty } ztd|  td| d }~ww )Nr  z*/var/www/.cache/.config/libreoffice/4/userT)parentsexist_okz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)r  i  z	/bin/bash)shell
executablestderrenvzPDF conversion successfulzError in PDF Conversion: zError converting excel to pdf: )r<   r=   r   r   resolver   r>   r4   environr   geteuidrk   rl   makedirschmod
subprocesscheck_outputSTDOUTrm   rn   r1   )	r  rA   r  output_filelibreoffice_home	file_pathcommandr  rt   r*   r*   r+   _convert_to_pdf  sJ   

r  c                 C   B   t j||  d}t j|std| td|  d S )Nr  z"Output excel file does not exist: zOutput excel file exists: )r<   r=   r   r>   r5   rk   rl   )rA   r  r  r*   r*   r+   _check_ouptput_excel_exist2     r  
output_pdfc                 C   r  )Nz.pdfz Output pdf file does not exist: zOutput pdf file exists: )r<   r=   r   r>   r   rk   rl   )rA   r  r  r*   r*   r+   _check_ouptput_pdf_exist9  r  r  r?   c                 C   s  t d t| t  t|}|d }d|j_t| }t d|  |di }|di }|di }|di }|d	i }	|d
i }
t	|| t
|| t||	 t|| |dg }tdt|d }|dkrtdt|D ]}t|d|  t|dd|  qvt|
ddpd}t|||d t|||d t||
|d d}d}t|||  t| | t|| | t| | t d d S )NzExcel Writer ModuleSheet2FzData Details: rS   r   r}   r   r   r   r   r   r[   r  r   )rd   )r+  zmedia/output/excelzmedia/output/pdfz)Excel Writer Module Executed Successfully)rk   rl   r@   r  r  
sheet_viewshowGridLinesr   rF   r!  rh  ry  r*  maxrU  rT  r  r  r   r`  r0  rv  r
  r  r  r  )rA   r?   r  r  datarS   rs   r}   r   r   total_calculated_chargesr   r+  ird   r  r  r*   r*   r+   template_writer@  sF   






r  r8   )r   )r   )Vr<   openpyxlr   openpyxl.stylesr   r   r   openpyxl.worksheet.worksheetr   openpyxl.workbookr   r   openpyxl.utils.cellr	   r
   openpyxl.worksheet.cell_ranger   openpyxl.cellr   orders.modelsr   r   r   r   r   r   products.modelsr   r   accounts.modelsr   shops.modelsr   r   rk   r  r   r   pathlibr   r   rm   r   r4   r5   r6   r7   r9   r:   r@   r1   rH   dictrT   ru   r~   django.db.modelsr   r|  r   r   r   r   r   r  r  r
  r   r  r!  r*  r0  r   rI  r`  rh  ro  rv  ry  r  r  r  r  r  r  r  r*   r*   r*   r+   <module>   sr     
 	Y*
<&