
    7i"o                         d dl Zd dlZd dlmZ d dlZd dlmZ d dlmZm	Z	 ddl
mZmZmZmZmZ ddlmZ  G d d	      Zy)
    N)load_workbook)Session)DictAny   )Module10RequestModule10ResponseMetricValueCapExMetricValueOverview)DatabaseServicec                       e Zd ZddefdZdedefdZdedefdZ	de
defd	Zd
edefdZdededefdZdedefdZdedefdZdedee
ef   defdZdefdZdedefdZy)Module10ServiceNdbc                 F    d| _         || _        |rt        |      | _        y y )Nzod:\after train\report\retail-simulation-api\excel_project\data\Simulation Test file - clean_complete_model.xlsx)
excel_pathr   r   
db_service)selfr   s     G/var/www/html/retail-simulation-api/app/api/module10_metrics/service.py__init__zModule10Service.__init__   s'     M-b1DO     requestreturnc                    K   	 | j                  |      }| j                  ||      }t        dg d||      S # t        $ r2}t	        dt        |              | j                  |      cY d}~S d}~ww xY ww)z<Calculate Module 10 metrics dynamically based on user inputs+Module 10 - Metrics and Performance IndexesY1-Y2Y3-Y4Y5-Y6zY7-Y8moduleperiods_analyzedmetrics_valuesoverviewzError in calculate_metrics: N)_calculate_dynamic_metrics_generate_dynamic_overviewr	   	Exceptionprintstr_get_fallback_response)r   r   metrics_datar$   es        r   calculate_metricsz!Module10Service.calculate_metrics   s|     	8::7CL66|WMH#D!E+!	   	80Q9:..w77	8s1   A638 A6	A3'A.(A3)A6.A33A6c                 b   i }i }t        |      D ])  }|j                  d      rt        ||d      }|%|||<   + t        dt	        |       d       |j                         D ]5  \  }}t        |d      s| j                  ||      }|j                  |       7 |s| j                  |      }|S )z2Calculate metrics dynamically based on user inputs_NzProcessing z input fields dynamicallyY1_Y2)
dir
startswithgetattrr(   lenitemshasattr_derive_metrics_from_inputupdate#_calculate_default_business_metrics)r   r   r+   input_fields
field_namefield_valueperiod_increasebase_metricss           r   r%   z*Module10Service._calculate_dynamic_metrics$   s     g,J((-%gz4@*/:L,	 ' 	C-..GHI ,8+=+=+?'J0#>>z?[##L1	 ,@ CCLQLr   
input_namec                 d   i }|dk(  rt        |j                  |j                  |j                        |d<   t        |j                  r|j                  dz  nd|j                  r|j                  dz  nd|j                  r|j                  dz  nd      |d<   |S |d	k(  rlt        |j                  |j                  |j                        |d
<   t        |j                   dz  |j                   dz  |j                   dz        |d<   |S |dk(  r1t        |j                  |j                  |j                        |d<   |S |dk(  rit        |j                  |j                  |j                        |d<   t        |j                  dz  |j                  dz  |j                  dz        |d<   |S |dk(  rit        |j                  |j                  |j                        |d<   t        |j                  dz  |j                  dz  |j                  dz        |d<   |S |dk(  rit        |j                  |j                  |j                        |d<   t        |j                  dz  |j                  dz  |j                  dz        |d<   |S |dk(  rit        |j                  |j                  |j                        |d <   t        |j                  d!z  |j                  d!z  |j                  d!z        |d"<   |S |d#k(  r1t        |j                  |j                  |j                        |d$<   |S |d%k(  r1t        |j                  |j                  |j                        |d&<   |S |d'k(  r1t        |j                  |j                  |j                        |d(<   |S |d)k(  r1t        |j                  |j                  |j                        |d*<   |S |d+k(  r1t        |j                  |j                  |j                        |d,<   |S |d-k(  r1t        |j                  |j                  |j                        |d.<   |S |d/k(  rQt	        |j
                  r|j
                  nd01      |d2<   |j
                  rt	        |j
                  dz  1      |d3<   |S |d4k(  rit        |j                  |j                  |j                        |d5<   t        |j                  dz  |j                  d6z  |j                  d7z        |d8<   |S |d9k(  rit        |j                  |j                  |j                        |d:<   t        |j                  dz  |j                  dz  |j                  dz        |d;<   |S |d<k(  rit        |j                  |j                  |j                        |d=<   t        |j                  dz  |j                  d!z  |j                  d>z        |d?<   |S |j                  d@dA      j                         dBz   }t        |j                  |j                  |j                        ||<   |S )CzCDerive business metrics from specific input field based on UI namesinvestment_and_capital_expensesY1_Y2_increaseY3_Y4_increaseY5_Y6_increasez$Investment & Capital Expenses Growthg333333?Ng?gffffff?zCapital ROIpre_operating_expenseszPre-Operating Expenses Impactg?g333333?g?zStartup Cost Efficiencyrental_advance_depositzRental Advance (Deposit) ImpactrentzRent Cost Impactg?gffffff?g333333?zOccupancy Cost Ratio	inventoryzInventory Growthg      ?zInventory Turnover Ratiobills_per_monthzBills per Month Growthg?zCustomer Traffic Growthaverage_price_per_itemzAverage Price per Item Growthg?zRevenue per Transactionother_incomezOther Income Growth	utilitieszUtilities Cost Impactcorporate_employee_salaryz Corporate Employee Salary Impactconcept_employee_salaryzConcept Employee Salary Impactstore_level_employee_salaryz"Store Level Employee Salary Impactlogistics_and_transportationz!Logistics and Transportation Costcap_ex_refurbish        Y7_Y8_increasezCap-Ex Refurbish ImpactzAsset Refurbishment ROI&online_investment_and_capital_expensesz$Online Investment & Capital Expensesg?g333333?zDigital Platform ROInumber_of_transactionszNumber of Transactions GrowthzOnline Customer Acquisitionaverage_transaction_valuez Average Transaction Value Growthg      ?zOnline Revenue per Customerr/    z Impact)r
   r0   Y3_Y4Y5_Y6r   Y7_Y8replacetitle)r   r?   r=   metricsmetric_names        r   r7   z*Module10Service._derive_metrics_from_input?   s    ::>I.44.44.44?G:;
 &1>M>S>S44s:Y]>M>S>S44s:Y]>M>S>S44s:Y]&GM"R G 337B.44.44.448G34
 2= / 5 55; / 5 55; / 5 55;2G-.z o 339D.44.44.44:G56l a 6!*5.44.44.44+G&'
 /:.44s:.44s:.44s:/G*+T I ;&*5.44.44.44+G&'
 3>.44s:.44s:.44s:3G./| q ,,0;.44.44.441G,-
 2=.44s:.44s:.44s:2G-.d Y 337B.44.44.448G34
 2=.44s:.44s:.44s:2G-.L A >)-8.44.44.44.G)*~ s ;&/:.44.44.440G+,p e 66:E.44.44.44;G67b W 448C.44.44.449G45T I 88<G.44.44.44=G89F { 99;F.44.44.44<G78x m --1A8G8M8M44SV2G-. $$5E#2#8#83#>612b [ CC>I.44.44.44?G:;
 /:.44s:.44s:.44s:/G*+N C 337B.44.44.448G34
 6A.44s:.44s:.44s:6G126 + 66:E.44.44.44;G67
 6A.44s:.44s:.44s:6G12  %,,S#6<<>JK#..44.44.44$GK  r   r:   c                 "    dt        ddd      iS )zCCalculate default business metrics when no specific inputs providedzBusiness Performance      $@       @      @rB   )r
   )r   r:   s     r   r9   z3Module10Service._calculate_default_business_metrics   s!     #K#""%
 	
r   r+   c                    g }|j                         D ]  \  }}t        |d      r9t        |d      s-|j                  }|s.|dkD  s4|j                  | d| d       Lt	        |dd      }t	        |dd      }t	        |dd      }	|r|d	kD  r|j                  | d
| d       n|r|dk  r|j                  | d| d       |r|r||kD  r|j                  | d       n |r|r||dz  k  r|j                  | d       |	s|	dkD  s|j                  | d|	 d        t        fdt              D              }
t        t        |      |t        |
      t        t        |            ddddd      S )zGGenerate dynamic overview based on actual inputs and calculated metricsrU   rC      z(: Significant refurbishment investment (z% in Y7-Y8)r   rD   rE      z: Strong early growth (z% in Y1-Y2)z: Initial decline (z: Accelerating growth trendg      ?z: Growth slowing in mid-term
   z: Sustained long-term growth (z%)c              3   \   K   | ]#  }|j                  d       st        |      d % yw)r/   Nr   )r2   r3   ).0r;   r   s     r   	<genexpr>z=Module10Service._generate_dynamic_overview.<locals>.<genexpr>  s3      il
 * 5 5c :wwPZ?[?g ls   ),z(Dynamic calculation based on user inputsz-Initial period with user-defined growth ratesz.Mid-term period with projected business impactz+Long-term period with sustained performance)inputs_providedmetrics_calculatedanalysis_typeY1_Y2_periodY3_Y4_periodY5_Y6_periodtotal_metrics_analyzedkey_insightsperformance_summary)
r5   r6   rU   appendr3   sumr1   r   r4   r)   )r   r+   r   rt   r`   metric_valuey7_y8y1_y2y3_y4y5_y6input_counts     `        r   r&   z*Module10Service._generate_dynamic_overview   s    *6););)=%K|%56w|Ue?f$33UQY '';-7_`e_ffq(rs  .>B.>B.>B URZ '';-7NugU`(abuqy '';-7J5'Q\(]^Uuu} '';-7R(STu)< '';-7S(TUURZ '';-7UV[U\\^(_`1 *>6  ic'l i i #&|#4%#&{#3&)#l*;&<!K O P M!
 	
r   c                 j    | j                  |      }| j                  ||      }t        dg d||      S )z(Fallback response when calculation failsr   )r   r   r   r    )r%   r&   r	   )r   r   fallback_metricsr$   s       r   r*   z&Module10Service._get_fallback_response/  s?    ::7C223CWM@8+	
 	
r   group_idc                   K   | j                   s| j                  |      S 	 | j                   j                  |      }| j                  |      S # t        $ r2}t	        dt        |              | j                  |      cY d}~S d}~ww xY ww)z;Calculate metrics using database data for specific group_idz$Error in calculate_from_simulation: N)r   _get_dynamic_response_for_groupget_simulation_inputsr'   r(   r)   )r   r   	db_inputsr,   s       r   calculate_from_simulationz)Module10Service.calculate_from_simulation;  s     77AA		B==hGI 77AA 	B8QAB77AA	Bs4   B+A B	B'B=B>BBBresultr   c           
         	 |j                   j                  j                         }d|v r<|d   }|j                  d|d    d|d    d       |j                  d|d   d	d
       d|v r>|d   }|d   }|dz  }|j                  d|dd       |j                  d|d   d	d       d|v rP|d   }|d   }	|j                  d|	dd       d|v r,|d   d   dz  }|dz  |	z  dz  }
|j                  d|
dd       d|v r+|d   }|d   |d   z   }|dz  }|j                  d |dd!       |j                  j                         }d|v rd|v r|d   }|d   }|j                  di       j                  dd"      d"kD  r+|d   dz  |d   d   z  }t        |d#z  |d$z  |d%z  &      |d'<   |d   dz  |d   z  }t        |d(z  |dz  |d)z  &      |d*<   |j                   j                  j                         }d+|d,<   d-|d.<   d/|d0<   t        |j                  |j                  |t        t        |      ||1      2      }|S # t        $ r#}t        d3t        |              |cY d4}~S d4}~ww xY w)5z7Enhance Module 10 results with actual database insights
brand_datazBrand Analysis: 
brand_namez with store_formatsz store formatszTotal Store Area: total_store_size,z sq ft planned
sales_datatotal_monthly_sales   u   Revenue Projection: ₹z,.0fz annual sales targetzCustomer Traffic: rJ   z bills per monthinvestment_datatotal_capital_investmentu   Capital Investment: ₹z total investment plannedg333333?d   zProjected ROI: z.1fz% annual return on investmentoperational_datamonthly_rentmonthly_utilitiesu   Operating Expenses: ₹z annual operational costsr   g?g{Gz?gQ?rB   zSales per Sq Ftrg   rh   zAsset Turnover Ratioz1Dynamic calculation from actual simulation inputsdata_sourcezAll 10 modules data integratedmodules_integratedz/Database-driven with business logic enhancementcalculation_methodrr   r    z(Error enhancing with database insights: N)r$   rt   copyrv   r#   getr
   ru   r	   r!   r"   r   r4   r'   r(   r)   )r   r   r   enhanced_insightsr   r   monthly_salesannual_salesr   total_investmentroi_percentager   monthly_opexannual_opexenhanced_metricssales_per_sqftasset_turnoverenhanced_summaryenhanced_resultr,   s                       r   _enhance_with_database_insightsz/Module10Service._enhance_with_database_insightsK  sr   T	 & < < A A C y(&|4
!((+;J|<T;UU[\fgv\w[x  yG  *H  I!((+=jI[>\]^=__m)no y(&|4
 *+@ A,r1!((+B<PTBUUi)jk!((+=jIZ>[\]=^^n)op !I-"+,=">#23M#N !((+BCSTXBYYr)st  9,#,\#:;P#QTV#VL&2T&9=M%MPS%SN%,,~c>RRo-pq "Y.#,-?#@ /?BRSfBgg*R/!((+B;tBTTm)no  &4499; y(->)-K&|4
"+,="> ==r2667I1MPQQ%/0E%F%KiXdNefxNy%yN:E'5';'5'<'5'<;$%67 ",,A!BR!G/ZtJu!u;F#1B#6#1B#6#1B#6< !78  &BBGGI.a]+5U125f12 /}}!'!8!8/!+./?+@!2(8		O #" 	<SVHEFM	s   H9H< <	I(I#I(#I(c                 `   i dt        ddd      dt        ddd      dt        ddd      dt        ddd      dt        ddd      dt        ddd      d	t        ddd      d
t        ddd      dt        ddd      dt        ddd      dt        ddd      dt        ddd      dt        ddd      dt        d      dt        ddd      dt        ddd      dt        ddd      }g d}t        dg d|t        t	        |      |dddddd            S ) z,Response with all UI input fields as metricsInvestment & Capital ExpensesrS   rB   Pre Operating ExpenseszRental Advance (Deposit)Rent	InventoryBills per monthzAverage Price per ItemzOther Income	UtilitieszCorporate Employee SalaryzConcept Employee SalaryzStore Level Employee SalaryzLogistics and TransportationCap Ex RefurbishrT   z&Investment & Capital Expenses (Online)Number of TransactionszAverage Transaction Value)z-All input fields initialized with 0% increasezOPhysical Store Format: 13 metrics covering investment, operations, and staffingz?Cap-Ex Refurbish: Y7-Y8 period for asset refurbishment planningz:Online Store Format: 3 metrics for digital business growthz<Ready to accept group-specific data for dynamic calculationsr   r   zUI-based input field structurez*13 fields covering all operational aspectsz$Y7-Y8 period for asset refurbishmentz&3 fields for digital business trackingz)Group-specific database integration ready)rn   physical_store_metricsrR   online_store_metricsr   rr   r    )r
   r   r	   r   r4   )r   sample_metricssample_insightss      r   _get_sample_responsez$Module10Service._get_sample_response  s+   W
+[""".W
 %k"""'W
 '""")W
" K"""#W
, """-W
6 {""" 7W
@ %k"""'AW
J K"""KW
T """UW
^ ("""*_W
h &{"""(iW
r *;""",sW
| +K"""-}W
H  0"!IW
P 5k"""7QW
Z %k"""'[W
d ("""*eW
r
  @A)'*>':,%E.Z(N,T#N%
	
 	
r   c                 4   |dk(  rgt        ddd      t        ddd      t        d	d	d	      t        d
dd      t        ddd      t        d      t        ddd      d}d| ddddg}n=t        ddd      t        ddd      t        ddd      t        d	      d}d| ddg}| j                         j                  }|j	                         D ]  \  }}||vs|||<    t        dg d|t        t        |      |t        |      dddd       !      S )"z8Get dynamic response with actual data for specific group   g      .@g      (@rb   rB   rc   rd   g      @g      @g      4@g      9@g      2@rT   g      >@g      6@)r   r   r   r   r   r   r   zGroup z* (Test Store A): Strong growth projectionsz)Investment expenses show 15% Y1-Y2 growthz0Online transactions projected 30% initial growthz,Cap-Ex refurbishment planned at 8% for Y7-Y8g      @)r   r   r   r   z: Standard growth projectionsz3Moderate investment and operational growth expectedr   r   z,Dynamic calculation from group-specific datazGroup-based performance metricsz#Database-driven with business logic)r   r   rn   r   rr   r    )	r
   r   r   r#   r5   r	   r   r4   r)   )r   r   dynamic_metricsinsightsall_metricsr`   rx   s          r   r   z/Module10Service._get_dynamic_response_for_group  s    q=1<#'#'#'2
 +6#&#&#&+
 $#&#&#&
 )#'#'#'
 $/#'#'#'$
 %5#&% +6#'#'#'+;"OH 
"LM;B>	H 2=#'#&#&2
 $#&#&#&
 )#'#'#&
 %5#&%!O* 
"?@EH //1@@)4):):)<%K/1/;, *=  @A*'*?';% #H#Q%F*O	%		
 	
r   )N)__name__
__module____qualname__r   r   r   r	   r-   dictr%   r)   r7   r9   r   r&   r*   intr   r   r   r   r   r    r   r   r   r   
   s    27 28 8CS 8&/ d 6tS td tl
 
 
.
t .
o .
Zb .
`

o 

BR 

B B@P B V6F VSWX[]`X`Sa Vfv Vpr
&6 r
h]
 ]
@P ]
r   r   )pandaspdopenpyxlr   ossqlalchemy.ormr   typingr   r   schemar   r	   r
   r   r   r   r   r   r   r   r   <module>r      s,      " 	 "  ^ ^ 'j	
 j	
r   