+
    5)i<                     j    R t ^ RIHtHtHtHtHt ^ RIt^ RI	H	t	H
t
 ^ RIHt ^ RIHt  ! R R4      tR# )zS
OMS Data Service
Service for extracting time series data from OMS database tables
)ListDictAnyOptionalTupleN)datetime	timedelta)DatabaseService)
get_loggerc                      a  ] tR t^t o RtR tRV 3R lR lltV 3R lR ltV 3R lR	 ltV 3R
 lR lt	RV 3R lR llt
V 3R lR ltRV 3R lR lltRtV tR# )OMSDataServicez9Service for extracting time series data from OMS databasec                *   \        4       V n        \        R 4      V n        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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/ /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/ /R#RR$RRRR%RRR	R&.R/ //V n        R'# )(oms_data_serviceorderstabledate_column
order_datevalue_columnorder_total
value_funcSUMextra_conditionszdeleted_at IS NULLfiltersorder_countidCOUNTrevenuetransaction_sales	bill_datez
status = 1zdeleted_by IS NULLcollections
collectioncredited_dateamountzstatus = 17zcredited_date IS NOT NULLcredit_notestransaction_cnzstatus IN (12, 13, 14)stock_outwardproduct_stock
created_atchange_stockzstock_type = 2zentity_type = 2purchase_orderspurchase_orderquantityzstatus != 9N)r	   
db_servicer
   loggertable_configsselfs   &JD:\Projects\python\client-ideal-oms_pyapi\app\services\oms_data_service.py__init__OMSDataService.__init__   sa   )+ !342 |e"%9$:2 |g"%9$:2 ,{e"\3G$H2 e"]4O$P2 ){e"%=$>2 |e"%57H$I2 )|
e"]O2 i\
    Nc                   < V ^8  d   QhRS[ RS[S[ ,          RS[S[ ,          RS[S[S[ S[3,          ,          RS[S[ ,          RS[S[S[ S[3,          ,          /# )   	table_key
start_dateend_dater   aggregationreturn)strr   r   r   r   )format__classdict__s   "r1   __annotate__OMSDataService.__annotate__   sm     / // SM/ 3-	/
 $sCx.)/ c]/ 
d38n	/r4   c           	         WP                   9  d3   \        RV R\        V P                   P                  4       4       24      hV P                   V,          P	                  4       p/ VP                  R/ 4      CT;'       g    / CVR&   V P                  WbW54      pV P                  P                  RV RV 24       V P                  P                  V4      pV'       g"   V P                  P                  RV R24       . # V P                  P                  R\        V4       R	V R
24       V#   \         d1   p	T P                  P                  RT R\        T	4       24       h Rp	?	ii ; i)a[  
Extract time series data from an OMS table.

Args:
    table_key:   Key in table_configs (e.g. 'revenue', 'collections')
    start_date:  Inclusive lower bound on the date column (YYYY-MM-DD)
    end_date:    Inclusive upper bound on the date column (YYYY-MM-DD)
    filters:     Additional col=value conditions merged at request time.
                 Pass {"company_id": <id>} for per-company scoping.
                 Omit or pass {} for all-companies (collective) data.
    aggregation: 'daily' | 'weekly' | 'monthly'

Returns:
    List of {"ds": <date_str>, "y": <float>} dicts ready for Prophet.
Unknown table configuration: 'z'. Available: r   zExecuting query for '': zNo data found for 'z' with the given filtersz
Retrieved z records for ''z'Error extracting time series data for 'N)r.   
ValueErrorlistkeyscopyget_build_queryr-   infor,   execute_mysql_querywarninglen	Exceptionerrorr<   )
r0   r7   r8   r9   r   r:   configqueryresultses
   &&&&&&    r1   get_time_series_data#OMSDataService.get_time_series_data   sa   .	 2 22 #A) M//3D4F4F4K4K4M/N.O"Q R R
 ''	2779F P6::i#< PB PF9%%f(PEKK4YKs5'JKoo99%@G##&9)D\$]^	KKz#g,~i[PQRSN 	KK G	{RUVYZ[V\U]^_	s%   A>D, A=D, ?,D, ,E'7+E""E'c          
      n   < V ^8  d   QhRS[ S[S[3,          RS[S[,          RS[S[,          RS[RS[/# )r6   rQ   r8   r9   r:   r;   )r   r<   r   r   )r=   r>   s   "r1   r?   r@      sT     G GS#XG SMG 3-	G
 G 
Gr4   c           	        VR,          pVR,          pVR,          pVP                  RR4      pVR8X  d   RV RV R	V R
2p	RV R2p
MDVR8X  d   RV RV RV R	V R
2	p	RV R2p
M'VR8X  d   RV RV R	V R
2p	RV RV R2p
M
V RV R2p	Rp
RV	 RV 2p. pVP                  R. 4       F  pVP                  V4       K  	  V'       d   VP                  V RV R24       V'       d   VP                  V R V R24       VP                  R!/ 4      P                  4        F  w  r\        V\        4      '       d2   R"P                  R# V 4       4      pVP                  V R$V R24       KL  \        V\        4      '       d   VP                  V R%V R24       K{  VP                  V R&V 24       K  	  V'       d    VR'R(P                  V4      ,           ,          pV
'       d   VR)V
 2,          pVR*,          pV# )+u<  
Build a parameterised aggregation query for Prophet input.

Aggregation levels:
    daily   → DATE(date_col)                        GROUP BY DATE(date_col)
    weekly  → Monday of ISO week                    GROUP BY YEARWEEK(date_col)
    monthly → first day of month                    GROUP BY YEAR, MONTH
r   r   r   r   r   dailyzDATE(z	) AS ds, (z) AS yzGROUP BY DATE()weeklyzDATE(DATE_SUB(z, INTERVAL WEEKDAY(z) DAY)) AS ds, zGROUP BY YEARWEEK(z, 1)monthlyzDATE_FORMAT(z, '%Y-%m-01') AS ds, zGROUP BY YEAR(z	), MONTH( AS ds, z AS y SELECT z FROM r    >= 'rD    <= 'r   z, c              3   p   "   T F,  p\        V\        4      '       d   R V R 2M
\        V4      x  K.  	  R# 5i)rD   N)
isinstancer<   ).0vs   & r1   	<genexpr>.OMSDataService._build_query.<locals>.<genexpr>   s0      [UZPQZ3-?-?1QCqSV!KUZs   46z IN (z = 'z =  WHERE  AND  z ORDER BY ds)rI   appenditemsrd   rF   joinr<   )r0   rQ   r8   r9   r:   r   date_col	value_colr   select_clausegroup_clauserR   where_conditionscondkeyvaluevalss   &&&&&            r1   rJ   OMSDataService._build_query   sS    G_M*N+	ZZe4
'!#H:Yzl!I;fUM,XJa8LH$ 
*=hZ,a	{&2  0z>LI%xj(=,a	{&2  ,H:YxjJL'j5AML-ug6 JJ126D##D) 7 ##xjj\$CD##xjhZq$AB !**Y399;JC%&&yy [UZ [[ ''3%uTF!(<=E3'' ''3%tE7!(<= ''3%s5'(:; < Y.>!???Eq''Er4   c                0   < V ^8  d   QhRS[ S[,          /# )r6   r;   )r   r<   )r=   r>   s   "r1   r?   r@      s     / /d3i /r4   c                H    \        V P                  P                  4       4      # )z)Return the list of configured table keys.)rF   r.   rG   r/   s   &r1   get_available_tables#OMSDataService.get_available_tables   s    D&&++-..r4   c                L   < V ^8  d   QhRS[ RS[S[S[ S[3,          ,          /# r6   r7   r;   )r<   r   r   r   )r=   r>   s   "r1   r?   r@     s(       c3h0H r4   c                h    WP                   9   d"   V P                   V,          P                  4       # R# )z2Return a copy of the config for a given table key.N)r.   rH   )r0   r7   s   &&r1   get_table_infoOMSDataService.get_table_info  s+    ***%%i05577r4   c                   < V ^8  d   QhRS[ RS[ RS[ RS[ RS[ RS[S[S[ ,          ,          RS[S[ ,          RS[S[S[ S[3,          ,          /# )	r6   ru   r   r   r   r   r   group_byr   )r<   r   r   r   r   )r=   r>   s   "r1   r?   r@     s      Q  Q Q  Q 	 Q
  Q  Q #49- Q 3- Q $sCx.) Qr4   c	                    RTRTRTRTRT;'       g    . RT;'       g    / /V P                   V&   V P                  P                  RV RV 24       R	# )
a  
Register a custom table configuration at runtime.

Args:
    key:               Lookup key used in API calls
    table:             Physical table name
    date_column:       Column used as the time axis
    value_column:      Column to aggregate
    value_func:        'SUM' or 'COUNT'
    extra_conditions:  List of raw SQL predicates always added to WHERE
    group_by:          Unused legacy parameter (kept for compatibility)
    filters:           Default col=value filters
r   r   r   r   r   r   z!Registered table configuration: 'u   ' → N)r.   r-   rK   )	r0   ru   r   r   r   r   r   r   r   s	   &&&&&&&&&r1   add_table_configOMSDataService.add_table_config  se    2 U;L* 0 6 6Bw}}"#
3 	<SEwOPr4   c                <   < V ^8  d   QhRS[ RS[S[S[ 3,          /# r~   )r<   r   bool)r=   r>   s   "r1   r?   r@   )  s$     8 8s 8uT3Y7G 8r4   c                p    WP                   9  d.   \        V P                   P                  4       4      pRRV RV 23# V P                   V,          pV P                  P	                  RVR,           24      pV'       g   RRVR,           R23# R
#   \
         d   pRR\        T4       23u R	p?# R	p?ii ; i)z
Validate that a table key exists and its underlying table is reachable.

Returns:
    (True, "") on success, (False, reason) on failure.
FzTable configuration 'z' not found. Available: zSELECT COUNT(*) AS cnt FROM r   zTable 'z&' does not exist or returned no resultzValidation error: N)Tr_   )r.   rF   rG   r,   rL   rO   r<   )r0   r7   	availablerQ   resultrT   s   &&    r1   validate_table_config$OMSDataService.validate_table_config)  s    	8 2 22 !3!3!8!8!:;	!6yk B--6K 9 : : ''	2F__88.vg.?@F w'88^___O 	8.s1vh777	8s.   <B ?B ?B B B5B0*B50B5c                ~   < V ^8  d   QhRS[ RS[RS[S[ ,          RS[S[ ,          RS[S[S[ S[3,          ,          /# )r6   r7   limitr8   r9   r;   )r<   intr   r   r   r   )r=   r>   s   "r1   r?   r@   C  sR     1 11 1 SM	1
 3-1 
d38n	1r4   c           	         WP                   9  d   \        RV R24      hV P                   V,          p\        VP                  R. 4      4      pV'       d   VP	                  VR,           RV R24       V'       d   VP	                  VR,           RV R24       RVR,           RVR	,           R
VR,           2pV'       d    VRRP                  V4      ,           ,          pVRVR,           RV 2,          pV P                  P                  V4      pT;'       g    . #   \         d1   p	T P                  P                  RT R\        T	4       24       h Rp	?	ii ; i)u  
Return a raw (non-aggregated) preview of the most recent rows for a table key.
extra_conditions from the config are applied so the preview reflects the same
filtered dataset that would be used for training.

Args:
    table_key:   Configured table key
    limit:       Number of rows to return (1–100)
    start_date:  Optional lower bound on the date column
    end_date:    Optional upper bound on the date column

Returns:
    List of {"ds": <value>, "y": <value>} dicts (raw, not aggregated).
rB   rD   r   r   ra   rb   r`   r^   r   z AS y FROM r   ri   rj   z
 ORDER BY z DESC LIMIT z Error getting data preview for 'rC   N)r.   rE   rF   rI   rl   rn   r,   rL   rO   r-   rP   r<   )
r0   r7   r   r8   r9   rQ   rs   rR   rS   rT   s
   &&&&&     r1   get_data_previewOMSDataService.get_data_previewC  sa   *	 2 22 #A)A!NOO''	2F#FJJ/A2$FG ''6-+@*AzlRS(TU ''6-+@*AxjPQ(RS &/09O8P Qw(* 
  W\\2B%CCCz&"7!8UGLLEoo99%@G==b  	KK @3sSTvhWX	s,   A:D =AD AD D E*+EE)r,   r-   r.   )NNNrY   )r   NNN)
   NN)__name__
__module____qualname____firstlineno____doc__r2   rU   rJ   r{   r   r   r   r   __static_attributes____classdictcell__)r>   s   @r1   r   r      sa     Cq
f/ /bG GR/ /  Q  QD8 841 1 1r4   r   )r   typingr   r   r   r   r   pandaspdr   r   app.services.database_servicer	   app.utils.helpersr
   r    r4   r1   <module>r      s*   
 4 3  ( 9 (g gr4   