
    di!                        d 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
  ej                  dd	      	 d	 	 	 	 	 dd
       Zy)z
Celery task for running monthly demand prediction job for all product/location combinations.
Uses the generate_monthly_forecasts function from controller to generate and save forecasts.
    )annotations)Dict)datetimedate)
celery_app)dispatch_taskTz^src.smart_inventory.tasks.monthly_demand_prediction_job_task.run_monthly_demand_prediction_job)bindnamec                6   ddl m} ddlm}m}m} ddlm} ddlm	} ddl
m}	 t         |             }
d}| j                  j                  }t        d| d	|        	 |
j!                  |      j#                  |j$                  |k(        j'                         }t        d
|        |rF|j(                  |_        t-        j.                         |_        |
j3                          t        d       nt        d|        |
j!                   ||j4                        |j6                        j#                  |j8                  |k(        j;                  |j4                  |j6                        j=                         }|sb|rD|j>                  |_        d| |_         t-        j.                         |_!        |
j3                          dd| |dddd|
jE                          S tG        jH                         }tG        |jJ                  |jL                  d      }| |	|dz
        z   }tO        d |D              }tO        d |D              }tQ        |      }d}d}g }t        d| d|        t        dtQ        |       dtQ        |              t        d| d| d| d       |D ]3  \  }}	  ||
|||||       |dz  }|dz  dk(  rt        d| d| d        5 |r:|jX                  |_        t-        j.                         |_!        |
j3                          	 tG        jH                         j[                  d%      }t        d&|        t]        d'|f(      }|j                  } ||d)|j^                  |t-        j.                         *      }|
ja                  |       |
j3                          t        d+|        d-d.| |||j[                  d/      |j[                  d/      tQ        |      tQ        |      ||||r|dd0 ng d1}t        d2| d3| d4       ||
jE                          S # tR        $ rC}|dz  }d!| d"| d#tU        |       }|jW                  |       t        d$|        Y d}~d}~ww xY w# tR        $ r}t        d,|        Y d}~d}~ww xY w# tR        $ r}tU        |      } 	 |s;|
j!                  |      j#                  |j$                  |k(        j'                         }|rD|j>                  |_        | dd5 |_         t-        j.                         |_!        |
j3                          n$# tR        $ r}!t        d6|!        Y d}!~!nd}!~!ww xY wt        d7|         dd8|  || d9cY d}~|
jE                          S d}~ww xY w# |
jE                          w xY w):a   
    Run monthly demand prediction for all product/location combinations for a company.
    
    This task:
    - Finds all unique product_id and location_id combinations for the company
    - Generates monthly forecasts for each combination
    - Saves predictions to the MonthlyForecast table
    
    Args:
        company_id: Company ID to run predictions for
        months_ahead: Number of months to predict ahead (default: 6)
    
    Returns:
        Dict with success status, counts, and any errors
    r   )get_db)CeleryTaskTrackerCeleryTaskStatus
DailySales)generate_monthly_forecasts)distinct)relativedeltaNz>[CELERY TASK] Starting monthly demand prediction job with ID: z for company_id: z"[CELERY TASK] Found task_tracker: z'[CELERY TASK] Updated status to STARTEDz:[CELERY TASK] WARNING: No task_tracker found for task_id: z3No product/location combinations found for company F)successmessage
company_idtotal_combinationssuccessful_predictionsfailed_predictions   )monthsc              3  &   K   | ]	  }|d      yw)r   N .0combos     [/var/www/html/hubwallet-dev/src/smart_inventory/tasks/monthly_demand_prediction_job_task.py	<genexpr>z4run_monthly_demand_prediction_job.<locals>.<genexpr>e   s      Deq D   c              3  &   K   | ]	  }|d      yw)r   Nr   r   s     r    r!   z4run_monthly_demand_prediction_job.<locals>.<genexpr>f   s     !Eu%(!Er"   z[CELERY TASK] Processing z combinations for company z[CELERY TASK] Unique products: z, Unique locations: z[CELERY TASK] Predicting from z to z (z months))dbr   location_id
product_idstart_month	end_monthd   z[CELERY TASK] Processed /z combinationszproduct_id=z, location_id=z: z[CELERY TASK] Error: z%Y-%m-%dz9[CELERY TASK] Triggering inventory planning snapshot for zUsrc.smart_inventory.tasks.inventory_planning_task.compute_inventory_planning_snapshot)args#compute_inventory_planning_snapshot)task_id	task_namestatusr   
created_atzB[CELERY TASK] Inventory planning snapshot task triggered with ID: z<[CELERY TASK] Error triggering inventory planning snapshot: Tz4Monthly demand prediction job completed for company z%Y-%m
   )r   r   r   months_aheadr'   r(   unique_product_idsunique_location_idsr   r   r   errorsz[CELERY TASK] Job completed: z successful, z failedi  z+[CELERY TASK] Error updating task tracker: z%[CELERY TASK] Job failed with error: z&Monthly demand prediction job failed: )r   r   r   error)1src.utils.dbr   )src.smart_inventory.apps.inventory.modelsr   r   r   -src.smart_inventory.apps.inventory.controllerr   
sqlalchemyr   dateutil.relativedeltar   nextrequestidprintqueryfilterr-   firstSTARTEDr/   r   now
started_atcommitr&   r%   r   group_byallFAILUREerror_messagecompleted_atcloser   todayyearmonthsetlen	ExceptionstrappendSUCCESSstrftimer   PENDINGadd)"selfr   r2   r   r   r   r   r   r   r   r$   task_trackerr-   combinationsrM   r'   r(   r3   r4   r   r   r   r5   r&   r%   e	error_msg	today_strplanning_taskplanning_task_idplanning_trackerresultrJ   db_errors"                                     r    !run_monthly_demand_prediction_jobrd      s   * $ 
 Y#4 
fhBLllooG	J7)Sdeodp
qrbxx 1299%%0

%' 	 	2<.AB"2":":L&.llnL#IIK;=NwiXY xxZ**+""
 &!!Z/

(!!""
 #% 	 &6&>&>#/bcmbn-o*,4LLN)		 !PQ[P\](&'*+&'~ 	
k 

5::u{{A6-|a7G"HH	 ! D| DD!!E!EE .!")*<)==WXbWcde/4F0G/HH\]`at]u\vwx.{m4	{"\NZbcd'3 	#J*) +) +' '!+&)C/1445K4LAN`Maanop	0 "2":":L(0L%IIK	V

--j9IMi[YZ *g\M  -//  1(?'//%#<<>  FF#$IIKVWgVhij
 Mj\Z$(&//8"++G4"%&8"9#&':#;"4&<"4%+fSbk
 	-.D-E]SeRffmno8 	
i  "a'")*^K=PRSVWXSYRZ[	i(-i[9:J  	VPQRPSTUU	V*  
A	L!xx(9:AA%--8 %'  &6&>&>#-:5D-A*,4LLN)		 	L?zJKK	L 	5m_EF ?O$"	
 	
 	
5
4 	
s   E,R C
R %-P!>R B#Q0 4AR !	Q-*8Q("R (Q--R 0	R9RR RR 	VU>)BT-,U>-	U6U	U>	UU>(V)V >VV VN)   )r   intr2   rf   returnr   )__doc__
__future__r   typingr   r   r   src.utils.celery_workerr   )src.smart_inventory.utils.celery_dispatchr   taskrd   r       r    <module>ro      sj    #  # . C d  "B  C GG G 
	G CGrn   