o
    -hf                     @   s  d dl mZ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 ddlmZmZmZmZ ddlmZm Z m!Z! d dl"m#Z#m$Z$m%Z% d dl&Z&d dl'Z'd dl(Z(d dl)m*Z* d dl+m,Z, d dl-Z-d dl.m/Z/m0Z0 d dl1m2Z2 edddd Z3edddd Z4edddd Z5edddd Z6edddd  Z7eddd!d" Z8eddd#d$ Z9eddd%d& Z:eddd'd( Z;eddd)d* Z<eddd+d, Z=eddd-d. Z>d d/l?m?Z? eddd0d1 Z@eddd2d3 ZAeeddd4d5 ZBeddd6d7 ZCeddd8d9 ZDeddd:d; ZEeddd<d= ZFdS )>    )renderredirectget_object_or_404)JsonResponseHttpResponse)	Paginator)messages)login_required)require_POST)reverse)PermissionDenied)canvas)code39)letter   )ProductCategoryBatchProductImage)ProductFormCategoryForm	BatchForm)SumQFN)transaction)IntegrityError)Font	Alignment)render_to_stringz/auth/login/)	login_urlc                 C   sL   t jjdddd}t j ddddd}t }t| d|||dS )	NT)parent__isnullsubcategoriesproductsparentnamezinventory/category_list.html)
categoriesall_categoriesform)r   objectsfilterprefetch_relatedallorder_byr   r   )requestr&   r'   r(    r/   $/var/www/html/pos/inventory/views.pycategory_list   s   r1   c                 C   sD   | j dkrt| j}| r| }tdS nt }t| dd|iS )NPOSTr1   zinventory/add_category.htmlr(   )methodr   r2   is_validsaver   r   )r.   r(   categoryr/   r/   r0   add_category+   s   

r7   c                 C   sX   t t|d}| jdkrt| j|d}| r|  tdS nt|d}t| dd|iS )Npkr2   instancer1   zinventory/edit_category.htmlr(   )	r   r   r3   r   r2   r4   r5   r   r   )r.   r9   r6   r(   r/   r/   r0   edit_category:   s   

r<   c                 C   sD   t t|d}| jdkr|  t| d|j d tdS tdS )Nr8   r2   z
Category "z " has been deleted successfully.r1   )r   r   r3   deleter   successr%   r   )r.   category_idr6   r/   r/   r0   delete_categoryJ   s   
r@   c                 C   sh  t j }tj d}| jd}|r|j|d}| jd}|dkr,|jdd}n|dkr7|jd	d}n|d
krC|jtdd}| jd}|r]|t	|dt	|dB t	|dB }| jdd}|dkrn|d}n7|dkrx|d}n-|dkr|d}n#|dkr|d}n|dkr|d}n|dkr|d}n|d}||||||d}t
| d|S ) Nr%   r6   )r?   statusactiveT	is_activeinactiveF	low_stocklow_stock_threshold)stock_quantity__ltesearchname__icontainsbarcode__icontainsdescription__icontainssort	price_ascselling_price
price_descz-selling_price	stock_ascstock_quantity
stock_descz-stock_quantitydate_asc
created_at	date_descz-created_at)r#   r&   current_categorycurrent_statuscurrent_sortsearch_queryzinventory/product_list.html)r   r)   r,   r   r-   GETgetr*   r   r   r   )r.   r&   r#   r?   rA   r]   sort_bycontextr/   r/   r0   product_listW   sV   

	rb   c                 C   s   | j dd }t|dk rtg ddS tjjt|dt|dB t|dB d	d
dd }g }|D ]}|	|j
|j|jp>dt|j|jtd|j
gdd q2t|ddS )z AJAX endpoint for product searchq    FsaferJ   rL   rN   TrC   N
   product_detail)args)idr%   barcodepricestockurl)r^   r_   striplenr   r   r)   r*   r   appendrk   r%   rl   strrR   rU   r   )r.   queryr#   resultsproductr/   r/   r0   search_products_ajax   s0   
	rw   c                 C   s(   t t|d}|j }t| d||dS )Nr8   zinventory/product_detail.html)rv   batches)r   r   rx   r,   r   )r.   r9   rv   rx   r/   r/   r0   ri      s   
ri   c                 C   s   | j dkrIt| j| j}| rB|jdd}d| jv r!| jd |_|  | jd}|D ]
}tj	j
||d q-t| d tdS t| d	 nt }tj	 }t| d
||dS )Nr2   Fcommitimageimagesrv   r{   zProduct added successfully!rb   z&There was an error adding the product.zinventory/add_product.html)r(   r&   )r3   r   r2   FILESr4   r5   r{   getlistr   r)   creater   r>   r   errorr   r,   r   )r.   r(   rv   r|   r{   r&   r/   r/   r0   add_product   s&   


r   c                 C   s   t t|d}| jdkrQt| j| j|d}| rJ|jdd}d| jv r)| jd |_|  | j	d}|D ]
}t
jj||d q5t| d	 td
S t| d nt|d}tj }t| d|||dS )Nr8   r2   r:   Fry   r{   r|   r}   zProduct updated successfully!rb   z(There was an error updating the product.zinventory/edit_product.html)r(   rv   r&   )r   r   r3   r   r2   r~   r4   r5   r{   r   r   r)   r   r   r>   r   r   r   r,   r   )r.   r9   rv   r(   r|   r{   r&   r/   r/   r0   edit_product   s*   



r   c                 C   s   t t|d}|  tdS )Nr8   rb   )r   r   r=   r   )r.   r9   rv   r/   r/   r0   delete_product  s   r   c                 C   s   t t|d}| jdkr@t| j}| r?|jdd}||_| |_	|  | j
|j7  _
|  t| d td|jdS nt }t| d||d	S )
N)rk   r2   Fry   zStock received successfully!ri   r8   zinventory/receive_stock.html)rv   r(   )r   r   r3   r   r2   r4   r5   rv   generate_batch_code
batch_coderU   quantityr   r>   r   rk   r   )r.   
product_idrv   r(   batchr/   r/   r0   receive_stock  s$   


r   c                 C   sx   t j }tdd}d|d< t|}|g d |D ]}||j|j|j	|j
|j|j|j|jr5|jjndg q|S )Nztext/csvcontent_typez#attachment; filename="products.csv"Content-Disposition)BarcodeNameBuying PriceSelling PriceStock QuantityzExpiry DatezPackaging Typer   Uncategorized)r   r)   r,   r   csvwriterwriterowrl   r%   buying_pricerR   rU   expiry_datepackaging_typer6   )r.   r#   responser   rv   r/   r/   r0   export_products1  s"   


r   )datetimec                 C   sz  | j dkr9| jd}|jdst| d tdS z| 	d}t
|}t| t  ttj|ddd	d
D ]\}}zt|dk rTt| d| d W q=|d r^|d  nd }|d  }t|d	  }t|d  }	t|dkr|d  rt|d  nd }
t|dkr|d  rt|d  d nd }t|dkr|d  nd }t|dkr|d  nd}tjj|d\}}tjj|||
||	|||dd W q= ty } zt| d| dt|  W Y d }~q=d }~ww W d    n	1 sw   Y  t | d W tdS  ty8 } zt| dt|  W Y d }~tdS d }~ww tdS )Nr2   imported_filez.csvzFile is not CSV typerb   zUTF-8,)	delimiterre   start   Row z: Missing required fields.r   r         %Y-%m-%d      r   r%   )r%   r   rR   rU   r   r   r6   )rl   defaultszError on row : zProducts imported successfully!Error processing file: )!r3   r~   r_   r%   endswithr   r   r   readdecodeioStringIOnextr   atomic	enumerater   readerrq   rp   floatintr   strptimedater   r)   get_or_creater   update_or_create	Exceptionrs   r>   )r.   csv_filedata_set	io_string
row_numbercolumnrl   r%   rR   rU   r   r   r   category_namer6   _er/   r/   r0   import_productsN  sd   

,4
( r   c              
   C   s   | j dd }|r;ztjt|dt|dB ddddd	}t|}W n t	y: } zg }W Y d }~nd }~ww g }t
|d
dS )Nrc   rd   rJ   rL   rk   r%   rl   rR   rU   Frf   )r^   r_   rp   r   r)   r*   r   valueslistr   r   )r.   rt   r#   ru   r   r/   r/   r0   product_live_search  s   r   c              
   C   s   z.| j dd}|r|d}tjj|d  t| d nt	| d W tdS W tdS  t
yN } zt	| dt|  W Y d }~tdS d }~ww )	Nselected_productsrd   r   id__inz1Selected products have been deleted successfully.z'No products were selected for deletion.zAn error occurred: rb   )r2   r_   splitr   r)   r*   r=   r   r>   r   r   rs   r   )r.   product_idsidsr   r/   r/   r0   delete_selected_products  s   
 r   c              	   C   s   | j dg }t| j dd}tjj|d}tdd}d|d< tj	|t
d	}t
\}}|d
 }|D ]:}	tj|	jdddd}
t|D ])}|dk rO|  |d
 }|
|d
| |d
|d |	j d|	j  |d
8 }qAq1|  |S )Nr   r   r   r   zapplication/pdfr   z#attachment; filename="barcodes.pdf"r   )pagesized      g      ?F)	barHeightbarWidthchecksum2   z - )r^   r   r   r_   r   r)   r*   r   r   Canvasr   r   
Extended39rl   rangeshowPagedrawOn
drawStringr%   r5   )r.   r   r   r#   r   cwidthheight
y_positionrv   rl   r   r/   r/   r0   print_barcodes  s(   
 
r   c                 C   s  | j dkrfz@| jd}|st| d t| dW S |jds.t| d t| dW S t	|}|j
}d}d}g }t|jdd	d
ddD ]\}}zt|sRW qG|dd \}	}
}}}}}}|	sq|d| d |d7 }W qGd}|rtjj| d\}}|	 |
r|
 nd||rt|nd|rt|nd|rt|nd|rt|nd|r| ndd	d	}d}|
rtjj|
 d }|s|	rtjj|	 d }|r| D ]
\}}t||| q|  n	tjjdi | |d7 }W qG ty } z|d| dt|  |d7 }W Y d}~qGd}~ww |dkr(t| d| d |dkrFt| | d |dd D ]	}t| | q<W n tye } zt| dt|  W Y d}~nd}~ww t| dS )z%Handle product import from Excel filer2   
excel_filez&Please select an Excel file to upload.zinventory/product_import.htmlz.xlsxz.Please upload a valid Excel file (.xlsx only).r   re   T)min_rowvalues_onlyr   N   r   z: Product name is requiredr   r   rd   r   )	r%   rl   r6   r   rR   rU   rG   descriptionrD   )rl   r   zSuccessfully imported z
 products.z$ rows had errors. See details below.rh   r   r/   ) r3   r~   r_   r   r   r   r%   r   openpyxlload_workbookrB   r   	iter_rowsanyrr   r   r)   r   rp   r   r   r   r*   firstitemssetattrr5   r   r   rs   r>   warning)r.   r   workbook	worksheetimported_counterror_counterrorsrow_numrowr%   rl   r   r   rR   rU   rG   r   r6   createdproduct_dataexisting_productkeyvaluer   r   r/   r/   r0   product_import  s   



"
r   c              
   C   s4  zt  }|j}d|_g d}t|dD ]\}}|jd|d}||_tdd|_t	dd|_
qtjd	d
}t|ddD ]s\}}	|j|d|	jd |j|d|	jpSdd |j|d|	jra|	jjndd |j|dt|	jd |j|dt|	jd |j|d|	jd |j|d|	jd |j|d|	jpdd |j|d|	jrdndd |j|d|	jdd q>|jD ]1}
d}|
d j}|
D ]}ztt|j|krtt|j}W q   Y q|d d }||j| _ qt!dd}d|d< |"| |W S  t#y } zt$%| d t|  t&d!W  Y d"}~S d"}~ww )#zExport products to Excel fileProducts)
Product Namer   r   r   r   r   Low Stock ThresholdDescriptionActivezCreated Dater   r   r   Tboldcenter
horizontalr6   r%   re   r   r   r   r   rd   r   r   r   r   r   r   	   YesNorh   r   r   333333?Aapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheetr   z+attachment; filename="products_export.xlsx"r   zError exporting products: rb   N)'r   WorkbookrB   titler   cellr   r   fontr   	alignmentr   r)   select_relatedr-   r%   rl   r6   r   r   rR   rU   rG   r   rD   rX   strftimecolumnscolumn_letterrq   rs   column_dimensionsr   r   r5   r   r   r   r   )r.   r   r   headerscol_numheaderr  r#   r   rv   col
max_lengthr   adjusted_widthr   r   r/   r/   r0   product_export.  sV   



r  c              
   C   s~  zt  }|j}d|_g d}t|dD ]\}}|jd|d}||_tdd|_t	dd|_
qg d	g d
g dg}t|ddD ]\}}	t|	ddD ]\}}
|j|||
d qJq@|jD ]1}d}|d j}|D ]}ztt|j|krytt|j}W qf   Y qf|d d }||j| _q[tdd}d|d< || |W S  ty } zt| dt|  tdW  Y d}~S d}~ww )z1Download sample Excel template for product importzProduct Import Template)r   r   r   r   r   r   r   r   r   r  Tr  r  r  )zSample Product 11234567890123Electronicsg      I@g     R@r   rh   z Sample description for product 1)zSample Product 21234567890124Clothingg      4@g     A@r   r   z Sample description for product 2)zSample Product 3rd   Booksg      $@g      .@   r   z'Leave barcode empty for auto-generationre   r   r  r   r  r  r   z3attachment; filename="product_import_template.xlsx"r   zError creating template: rb   N)r   r  rB   r  r   r  r   r   r  r   r  r  r  rq   rs   r  r   r   r5   r   r   r   r   )r.   r   r   r  r  r  r  sample_datar   row_datar   r  r  r   r  r   r   r/   r/   r0   download_sample_templatek  sN   



r&  )Gdjango.shortcutsr   r   r   django.httpr   r   django.core.paginatorr   django.contribr   django.contrib.auth.decoratorsr	   django.views.decorators.httpr
   django.urlsr   django.core.exceptionsr   reportlab.pdfgenr   reportlab.graphics.barcoder   reportlab.lib.pagesizesr   modelsr   r   r   r   formsr   r   r   django.db.modelsr   r   r   r   r   json	django.dbr   django.db.utilsr   r   openpyxl.stylesr   r   django.template.loaderr   r1   r7   r<   r@   rb   rw   ri   r   r   r   r   r   r   r   r   r   r   r   r  r&  r/   r/   r/   r0   <module>   s|    




<


$
$



<

&
W
<