
    08i                         d dl Z 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
  e j                  e      Z ej"                  d      dd	ee   d
eeef   fd       Zy# e$ rZ ede        dZ
Y dZ[QdZ[ww xY w)    N)DictAnyOptional)datetime	timedelta)
celery_app)get_db_sessionz,Warning: Could not import required modules: T)bindtarget_datereturnc                 P   	 ddl m}m}m} ddlm}m}m} 	 |r%t        j                  |d	      j!                         }	n/t        j"                         t%        d
      z
  j!                         }	t(        s1d}
t        j                  |
       d|
| j                  j                  dS 	 t        j+                  d       | j-                  dddi       t)               }	 | j-                  ddd|	 di       |j/                  |j0                  |j2                  |j4                  |j7                  |j8                        j;                  d      |j7                  |j8                  |j<                  z        j;                  d            j?                  ||j@                  |j                  k(        jC                  |j!                  |jD                        |	k(        jG                  |j0                  |j2                  |j4                        jI                         }|set        j+                  d|	        dd|	 t        |	      d| j                  j                  d}| j-                  d|       ||jK                          S | j-                  dddtM        |       d|	 di       d}d}d}|D ]\  }|j/                  |      jC                  |j0                  |j0                  k(  |j2                  |j2                  k(  |j4                  |j4                  k(  |j!                  |jN                        |	k(        jQ                         }|r1|jR                  |_)        tU        |jV                        |_+        |d
z  }n ||j0                  |j2                  |j4                  t        jX                  |	t        jZ                  j]                               |jR                  tU        |jV                              }|j_                  |       |d
z  }|d
z  }_ |ja                          dd |	 t        |	      |||| j                  j                  d!}t        j+                  d"|	 d#|        | j-                  d|       ||jK                          S # t        $ rH}t        j                  d|        ddt        |       | j                  j                  dcY d}~S d}~ww xY w# t&        $ r?}d| d}
t        j                  |
       d|
| j                  j                  dcY d}~S d}~ww xY w# tb        $ r~}|je                          d$t        |       }
t        j                  |
d%       d|
| j                  j                  d}| j-                  d&|       |cY d}~|jK                          S d}~ww xY w# |jK                          w xY w# tb        $ r^}d't        |       }
t        j                  |
d%       d|
| j                  j                  d}| j-                  d&|       |cY d}~S d}~ww xY w)(a6  
    Celery task to compute daily sales from SalesOrderLine and store in DailySales table
    Aggregates sales by product_id, location_id, and date
    
    Args:
        target_date: Date in YYYY-MM-DD format. If not provided, uses yesterday's date.
    
    Returns:
        Dict containing task results
    r   )SalesOrderLine
SalesOrder
DailySales)funcDateand_z#Failed to import required modules: FzModule import error: )successerrortask_idNz%Y-%m-%d   )dayszInvalid date format: z. Expected YYYY-MM-DDzDatabase session not availablez#Starting daily sales computation...PROGRESSmessagez'Initializing daily sales computation...)statemetazQuerying sales data for z...quantity_soldtotal_amountzNo sales data found for TzNo sales data to process for )r   r   r   processed_countr   SUCCESSzProcessing z daily sales records for )
company_id
product_idlocation_id	sale_dater   r   z3Daily sales computation completed successfully for )r   r   r   r   inserted_countupdated_countr   z&Daily sales computation completed for z: z&Error during daily sales computation: )exc_infoFAILUREz%Daily sales computation task failed: )3)src.smart_inventory.apps.inventory.modelsr   r   r   
sqlalchemyr   r   r   ImportErrorloggerr   strrequestidr   strptimedatenowr   
ValueErrorr	   infoupdate_statequeryr!   r"   r#   sumquantitylabel
unit_pricejoinsales_order_idfiltersold_atgroup_byallcloselenr$   firstr   floatr   combinemintimeaddcommit	Exceptionrollback)selfr   r   r   r   r   r   r   er$   	error_msgdbaggregated_salesresultr   r&   r%   saleexisting_recordnew_daily_sales                       I/var/www/html/hubwallet-dev/src/smart_inventory/tasks/daily_sales_task.pycompute_daily_salesrV      s   	
dd//
 ))+zBGGII!)*;;AACI 4	Y||
 	
x9:
)=f1gh d	JiC[\e[ffiAj5kl  "xx%%))&&00177H00>3L3LLMSSTbc  dN99Z]]Jf		*,,-:h%%))&& ce   $6ykBC#!>ykJ#&y>'(#|| !!	!?J HHJG Ji;sScOdNee~  @I  J  JM  BN  6O  P  OMN( %"$((:"6"="=))T__<))T__<**d.>.>>IIj223y@	#
 %'   #484F4FO1389J9J3KO0!Q&M &0#'??#'??$($4$4"*"2"29hll>O>O>Q"R&*&8&8%*4+<+<%=&N FF>*"a'N1$7%< IIK  PQZP[\"9~#2"0!.<<??F KK@2fXVWIF;  HHJY  
:1#>?,SVH5||
 	

  
+K=8MN	Y||
 	

`  
	KKM@QIILLTL2 "<<??F
 IF;M HHJ
	 HHJ ;CF8D	Y. ||
 		7s   R  AS %4V> FT (V> 9G6T /V>  	S	=SSS	T4TTT	V&(A#V!V&V) V> !V&&V) )V;;V> >	X%AX X% X%)N)loggingtypingr   r   r   r   r   src.utils.celery_workerr   src.utils.dbr	   r+   rM   print	getLogger__name__r,   taskr-   rV        rU   <module>ra      s     & & ( .+
 
		8	$ dh8C= hDcN h h  	8
<=Ns   A A:#A55A: