
    iH                     0   d dl m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 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  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.  G d d      Z/y)    )List)Session)schema)SummaryBase
TblSummary)CustomResponse)Messages)HTTPException)JWTPayloadSchema)CivilService)DisplayRackingUnitService)CarpentryService)ElectricalCablingService)DisplayBoardService)CommercialEquipmentService)VisualMerchElementsService)PlumlingService)AdditionalInstallationService)InfoTechService)Customer_location)Catchment_Potential)CompetitorIntensityService)%LocationSpillageFactorAnalysisService)SalesEstimateServicec                       e Zd ZdedefdZdej                  fdZde	fdZ
deej                     fdZd	e	fd
Zde	fdZde	fdZy)SummaryServicedbtokenc                      || _         || _        y )N)r   r   )selfr   r   s      >/var/www/html/retail-simulation-api/app/api/summary/service.py__init__zSummaryService.__init__   s    
    requestc                    K   t        j                  |j                               }t        j                  || j
                         | j
                  j                          t        dt        j                        S w)N1statusmessage)
r   model_validate
model_dumpr   creater   commitr   r	   SUMMARY)r    r$   created_datas      r!   createdzSummaryService.created"   sT     "11'2D2D2FG,0S(2B2BCCs   A9A;group_idc                    K   t        j                  || j                        }|st        dd      |D cg c]!  }t        j
                  j                  |      # c}S c c}w w)Ni  zGet group ID not foundstatus_codedetail)r   getr   r
   r   SummaryResponser*   )r    r1   
geted_data	get_groups       r!   getedzSummaryService.geted(   sV     ^^Hdgg6
C8PQQR\]R\Y&&55i@R\]]]s   4A$&AA$c                 p  K   |D ]y  }t        j                  |j                               }|j                  t	        dt
        j                        c S t        j                  |j                  || j                         { | j                  j                          t	        dt
        j                        S wNz-1r'   r&   )r   r*   r+   
summary_idr   r	   SUMMARY_NOTr   updater   r-   SUMMARY_UPDATE)r    r$   requpdated_datas       r!   updatedzSummaryService.updated.   s     C&55cnn6FGL&&.%T8;O;OPPl55|TWWM	 
 	S(2I2IJJs   B4B6r=   c                    K   t        j                  || j                        }|st        dt        j
                        S t        dt        j                        S wr<   )r   deleter   r   r	   r>   SUMMARY_DELETE)r    r=   deleted_datas      r!   deletedzSummaryService.deleted7   sE     !((TWW=!x7K7KLLS(2I2IJJs   AAc                 .  K   t        | j                  | j                        }t        | j                  | j                        }t	        | j                  | j                        }t        | j                  | j                        }t        | j                  | j                        }t        | j                  | j                        }t        | j                  | j                        }t        | j                  | j                        }	t        | j                  | j                        }
t        | j                  | j                        }i }i }	 	 |j                  |      }	 |j                  |      }	 |j                  |       d{   }	 |j                  |       d{   }	 |j                  |       d{   }	 |j!                  |       d{   }|j#                  |       d{   }|	j%                  |       d{   }|
j'                  |       d{   }	 |j+                  |       d{   }d }|D ](  } ||d         }|j-                  |d      |d   z   ||<   * |D ](  } ||d         }|j-                  |d      |d   z   ||<   * |D ]C  } ||j.                        }|j-                  |d      t1        |j2                  xs d      z   ||<   E |D ]C  } ||j.                        }|j-                  |d      t1        |j2                  xs d      z   ||<   E |D ]C  } ||j.                        }|j-                  |d      t1        |j2                  xs d      z   ||<   E |D ]]  }t5        |d      st5        |d      s ||j.                        }|j-                  |d      t1        |j6                  xs d      z   ||<   _ |D ]]  }t5        |d      st5        |d      s ||j.                        }|j-                  |d      t1        |j6                  xs d      z   ||<   _ t9        d |D              }t9        d |D              }d	D ]  }|j-                  |d      |z   |z   ||<    |D ]C  } ||j.                        }|j-                  |d      t1        |j2                  xs d      z   ||<   E i }d	D ]*  }|j-                  |d      |j-                  |d      z   ||<   , |||d
S #  g }Y xY w#  g }Y xY w7 #  g }Y xY w7 }#  g }Y xY w7 p#  g }Y uxY w7 c7 M7 77 !# t(        $ r g }g }g }g }Y 3w xY w7 "# t(        $ r g }Y .w xY w# t:        $ r}t)        ddt=        |             d}~ww xY ww)z^Calculate capital expenses (excluding IT) + IT capital expenses = total store capital expensesNc                 @    t        |       }d|v sd|v ryd|v sd|v ry|S )NSTORE_FORMAT_AStore Format ASTORE_FORMAT_BStore Format B)str)fmtfmt_strs     r!   normalize_formatzISummaryService.get_capital_expenses_calculation.<locals>.normalize_formatz   s6    c(#w.2Bg2M+%04D4O+r#   store_format_typer   subtotaltotalc              3   P   K   | ]  }t        t        |d d      xs d         ywrU   r   Nfloatgetattr.0items     r!   	<genexpr>zBSummaryService.get_capital_expenses_calculation.<locals>.<genexpr>   s&     $iWhtU74!+D+I%JWh   $&c              3   P   K   | ]  }t        t        |d d      xs d         ywrW   rX   r[   s     r!   r^   zBSummaryService.get_capital_expenses_calculation.<locals>.<genexpr>   s(     /b~Z^gdGQ6O6TST0Ub~r_   rL   rN   )capital_expenses_excluding_itit_capital_expensestotal_store_capital_expenses  z$Error calculating capital expenses: r3   )r   r   r   r   r   r   r   r   r   r   r   r   get_subtotal_by_store_formatget_and_sum_carpentryget_sum_electricalget_and_sum_display_boardget_commercial_equipmentget_group_visual_merch_elementsget_plumbing!get_group_additional_installationr
   get_and_sum_info_techr6   rS   rY   	total_sumhasattrrU   sum	ExceptionrO   ) r    r1   civil_servicedisplay_racking_servicecarpentry_serviceelectrical_servicedisplay_board_servicecommercial_equipment_servicevisual_merch_serviceplumbing_serviceadditional_installation_serviceinfo_tech_servicerb   rc   civil_totalsdisplay_racking_totalscarpentry_totalselectrical_totalsdisplay_board_totalscommercial_equipment_datavisual_merch_dataplumbing_dataadditional_installation_data	it_totalsrR   r]   store_formatvisual_merch_totaladditional_installation_totalformat_namerd   es                                    r!    get_capital_expenses_calculationz/SummaryService.get_capital_expenses_calculation=   s     %TWWdjj9";DGGTZZ"P,TWWdjjA5dggtzzJ 3DGGTZZ H'A$''4::'V$9$''4::N*477DJJ?*GQUQ[Q[*\'+DGGTZZ@(*% m	i",II(S,)@)])]^f)g&&):)P)PQY)Z#Z '*<*O*OPX*Y$Y!*-B-\-\]e-f'f$	22N2g2ghp2q,q)*>*^*^_g*h$h!&6&C&CH&M M5T5v5vw  6A  0A,"3"I"I("SS	 %/5H0IJ>[>_>_`lno>psw  yC  tD  ?D-l; % //5H0IJ>[>_>_`lno>psw  yC  tD  ?D-l; / )/0F0FG>[>_>_`lno>psxy}  zH  zH  zM  LM  tN  ?N-l; ) */0F0FG>[>_>_`lno>psxy}  zH  zH  zM  LM  tN  ?N-l; * -/0F0FG>[>_>_`lno>psxy}  zH  zH  zM  LM  tN  ?N-l; - 24!45'$:P#3D4J4J#KLB_BcBcdprsBtw|  ~B  ~H  ~H  ~M  LM  xN  CN1,? 2
 &4!45'$:P#3D4J4J#KLB_BcBcdprsBtw|  ~B  ~H  ~H  ~M  LM  xN  CN1,? & "%$iWh$i!i,//b~/,)C=Z=^=^_jlm=n  rD  >D  Gd  >d-k:  D "/0F0FG4G4K4KLZ[4\_deiesesexwx_y4y#L1 "
 ,.(C155k1E'++K;< -[9  D 2O':0L E"!,)+& $[&#%  %Z'$&! (g*')$ -r$h M 0A  2,.)$&! "/1,	2 T  	H  	iC:^_bcd_e^f8ghh	isk  EV	S7 T -T TT T TT !T( 5T%6T( ;T> T2T> (T5)T> T8T> T;T>  U 4U5U 9EU+  U+ AU+ "U+ /DU+ 6V7S>;U+ TU+ T TU+ T T"U+ %T( (T/,U+ 2T> 5T> 8T> ;T> >UU+ UU+ U U($U+ 'U((U+ +	V4VVVc                 P
  K   t        | j                  | j                        }t        | j                  | j                        }t	        | j                  | j                        }t        | j                  | j                        }t        | j                  | j                        }	 |j                  |       d{   }|j                  |       d{   }|j                  |       d{   }	|j                  |       d{   }
t        dt        |       d       t        dt        |       d       t        dt        |	       d       t        dt        |
       d       |xr# t        |d   d      xr t        |d   dd      du}t        d	|        i }|rd
D ]  }|dk(  rdnd}d}|D ]>  }t        t        |dd            }||v s||v s"|t!        t        |dd      xs d      z  }@ d}|D ]`  }t        t        |dd            }||v s||v s"t!        t        |dd      xs d      }t!        t        |dd      xs d      }||dz  |z  z  }b d}|	D ]S  }t        t        |dd            }||v s||v s"t        t        |dd            j#                         }d|v rd}nd|v rd} n d}|
D ]S  }t        t        |dd            }||v s||v s"t        t        |dd            j#                         }d|v rd}nd|v rd} n t        d| d| d| d | d!| 
       ||z  d"z  |z  |z  }|||<    nt%        d# |D              }d}|D ]A  }t!        t        |dd      xs d      }t!        t        |dd      xs d      }||dz  |z  z  }C d}|	r4t        t        |	d   dd            j#                         }d|v rd}nd|v rd}d}|
r4t        t        |
d   dd            j#                         }d|v rd}nd|v rd}t        d$| d| d | d!|        ||z  d"z  |z  |z  }||d
}i }|j'                  |       d{   }d
D ]  }|dk(  rdnd}d}d}d}|D ]r  }t        |d%d      }t        |d&d      } t!        t        |d'd      xs d      }!||k(  xs ||v xs ||k(  xs ||v }"|"sRd(| v sd)| v r|!}]d*| v sd+| v r|!}hd,| v sd-| v sq|!}t ||z  |z  ||<    ||d.S 7 67  7 
7 7 # t(        $ r}#t+        d/d0t        |#       1      d}#~#ww xY ww)2zPCalculate sales potential, sales estimate, and validation for both store formatsNzDEBUG - Customer data: z recordszDEBUG - Catchment data: zDEBUG - Competitor data: zDEBUG - Spillage data: r   rS   zDEBUG - Has format column: ra   rL   FORMAT_AFORMAT_B household_consumption_per_monthpercentage_of_segmentnumber_of_householdsd   g      ?total_square_footagehighgffffff?mediumg333333?estimated_spillage_factorg333333?lowg?zDEBUG - z: consumption=z, catchment=z, competition=z, spillage=g333333?c              3   P   K   | ]  }t        t        |d d      xs d         yw)r   r   NrX   r[   s     r!   r^   z8SummaryService.get_sales_calculations.<locals>.<genexpr>  s5       ,G  yFptE'$@acd2e2jij,k  yFr_   zDEBUG - Shared: consumption=store_formate_type	parametervaluezBills per MonthBILLS_PER_MONTHzItems per BillITEMS_PER_BILLzAverage Price	AVG_PRICE)sales_potentialsales_estimatere   zError calculating sales: r3   )r   r   r   r   r   r   r   get_customer_locations_by_group get_catchment_poteneial_by_groupget_group_competitorget_locationprintlenrp   rZ   rO   rY   lowerrq   get_group_sales_estimaterr   r
   )$r    r1   customer_location_servicecatchment_servicecompetitor_servicespillage_servicesales_estimate_servicecustomer_datacatchment_datacompetitor_dataspillage_datahas_format_columnr   format_type
format_keyhousehold_consumptionr]   item_formatcatchment_potential
percentage
householdscompetition_factor	intensityspillage_factorspillagepotential_valuer   
sales_databills_per_monthitems_per_bill	avg_pricer   r   r   format_matchr   s$                                       r!   get_sales_calculationsz%SummaryService.get_sales_calculations   s     %6dggtzz$J!/D7L@$**U!5dggtzz!JR	^";"["[\d"eeM#4#U#UV^#__N$6$K$KH$UUO"2"?"?"IIM+C,>+?xHI,S-@,AJK-c/.B-C8LM+C,>+?xHI   V'-*:<O"P  VU\]jkl]m  pC  EI  VJ  RV  VV  /0A/BCD O #GK/:>N/NT^J -.) -&)'$8KR*P&Q%4{8R1U74Ijlm;n;srs5tt1 !. +,' .&)'$8KR*P&Q%4{8R).wt=TVW/X/]\])^J).wt=SUV/W/\[\)]J/J4D
3RR/ !/ *-& /&)'$8KR*P&Q%4{8R(+GD:PRT,U(V(\(\(^I%258 2!)Y!659 2! !0 '*O -&)'$8KR*P&Q%4{8R'*749TVX+Y'Z'`'`'bH%125!&(!225! !. H[M@U?VVbcvbw  xF  GY  FZ  Ze  fu  ev  w  x ':<Q&QTX&X[m&mp&O3BOK0_ $Hd ),  ,G  yF  ,G  )G%&'#*D!&wt5La'P'UTU!VJ!&wt5KQ'O'TST!UJ'J,<
+JJ' +
 &)"" #GOA,>@VXZ$[ \ b b dI*-0*!Y.-1*"% "7=+;=XZ\#]^ddfH)*-(**-45J4K<XkWllz  |N  {O  OZ  [j  Zk  l  m"58M"MPT"TWi"il{"{&5&5#  N5NNxXXJ  D+6:J+JZPZ
"#!"	&D#*41Er#JL 'k2 >I!'$";"@qAE %
2 4"l24$34 $|3	 ! $,	9=NR[=[.3O-:>NR[>[-2N,	9[I=U(-I' '* />.NQZ.Z{+9  D> $3"0 U f_UIL YL  	^C:STWXYTZS[8\]]	^s   B!T&$S< 8S.9S< S1S< *S4+S< S7CS< AS< A&S< AS< E/S< S:A+S< 9S< S< -T&.S< 1S< 4S< 7S< :S< <	T#TT##T&N)__name__
__module____qualname__r   r   r"   r   SummaryCreater0   intr:   r   SummaryUpdaterC   rH   r   r    r#   r!   r   r      s    ' )9 DF$8$8 D^3 ^KD)=)=$> KKs Kis iB[^S [^r#   r   N)0typingr   sqlalchemy.ormr   app.api.summaryr   app.models.main.summaryr   r   app.utils.schemas_utilsr   app.locale.messagesr	   fastapir
   app.dependency.authanticationr   app.api.civil.servicer   &app.api.display_racking_create.servicer   app.api.carpentry.servicer   "app.api.electrical_cabling.servicer   app.api.display_board.servicer   $app.api.commercial_equipment.servicer   -app.api.visual_merchandising_elements.servicer   app.api.plumbing.servicer   *app.api.addtional_installation_fix.servicer   app.api.info_tech.servicer   !app.api.customer_location.servicer   #app.api.catchment_potential.servicer   $app.api.competitor_intensity.servicer   1app.api.location_spillage_factor_analysis.servicer   app.api.sales_estimate.servicer   r   r   r#   r!   <module>r      s]     " " ; 2 ( ! : / L 6 G = K T 4 T 5 @ C K c ?|^ |^r#   