
    G	/iT                     H   d dl mZ d dlmZ d dlZd dl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mZ d d	lmZmZmZmZmZmZ 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.m/Z/m0Z0m1Z1m2Z2m3Z3 d dl4m5Z5  G d d      Z6y)    )HTTPException)SessionN)datetime)BytesIO)A4)colors)getSampleStyleSheetParagraphStyle)SimpleDocTemplate	ParagraphSpacerTable
TableStyleImage)TblNetworkPlanning)TblTradingMonth)TblPreOperatingExpense)
TblSummarySummaryBase)TblGroup)TblCivil)TblInfoTech)TblRentExpenses)
TblUtility)TblStoreLevelStaffNeeds)NetworkPlanningTradingMonthsPreOperatingExpensesStoreInvestmentSummaryModule3SummaryModule3ReportPreview)JWTPayloadSchemac                   l    e Z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fd
ZdedefdZy)Module3ReportServicedbtokenc                      || _         || _        y )N)r%   r&   )selfr%   r&   s      ?/var/www/html/retail-simulation-api/app/api/module_3/service.py__init__zModule3ReportService.__init__%   s    
    group_idreturnc                   K   |st        dd      | j                  j                  t              j	                  |      j                         xs| | j                  j                  t              j	                  |      j                         xs= | j                  j                  t              j	                  |      j                         }|r| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }	| j                  j                  t              j	                  |      j                         }
| j                  j                  t              j	                  |      j                         }| j                  |||||	|
|      }t!        ||D cg c]  }t#        di |j$                   c}xs t#               g|rt'        di |j$                  n	t'               |rt)        di |j$                  n	t)               ||rt+        di |j$                  n	t+               t,        j.                  j1                               S | j                  j                  t2              j	                  |      j                         }|rat!        |t#        |      gt'        |      t)        |      t5        |      t+        |      t,        j.                  j1                               S t        dd      c c}w w)	Ni  zgroup_id is required)status_codedetailr,   )r,   network_planningtrading_monthspre_operating_expensesstore_investment_summarysummarylast_updatedi  zGroup ID not found in database )r   r%   queryr   	filter_byfirstr   r   allr   r   r   r   r   r    _create_store_investment_summaryr!   r   __dict__r   r   r    pd	Timestampnowr   r   )r(   r,   module_data_existsnetwork_recordstrading_recordpre_operating_recordsummary_record
civil_datait_data	rent_datautility_data
staff_datastore_investmentngroup_existss                  r)   _fetch_module3_dataz(Module3ReportService._fetch_module3_data)   sx    C8NOO GGMM,-777JPPR WGGMM/*44h4GMMOWGGMM01;;X;NTTV 	 "ggmm,>?IIS[I\``bO!WW]]?;EExEX^^`N#'77==1G#H#R#R\d#R#e#k#k#m !WW]]:6@@(@SYY[N x0::H:MQQSJggmmK0::H:MQQSGo6@@(@SWWYI77==4>>>QUUWL'>?IIS[I\``bJ  $DD.
GYP\^h  (!IX!YA/"?AJJ"?!Y!p^m^o]pKY}G~/F/FG_l_n`t';'\>R>[>['\  {O  {Q)9ESA)@)@AYgYi\\--/   77==2<<h<OUUWL+%&5x&H%I#0(#C+?+R-CX-V*H=!#!1!1!3  $<\]]1 "Zs   LQ7Q2
2EQ7c                 X   t        |      }dd}	d }
 |
|d      |_         |
|d      |_         |	|d      |_         |	|d      |_        |D ]  }dt        |j                  xs d      v r+|j                  xs d|_        |j                  xs d|_
        Idt        |j                  xs d      v se|j                  xs d|_        |j                  xs d|_         |D ]  }dt        |j                  xs d      v r$|xj                  |j                  xs dz  c_        Bdt        |j                  xs d      v s^|xj                  |j                  xs dz  c_         |D ]  }|j                   xs d|j"                  xs dz  }dt        |j$                  xs d      v r|xj&                  |z  c_        Udt        |j$                  xs d      v sq|xj(                  |z  c_         |r|j*                  xs d|_        |j.                  xs d|_        |j2                  xs d|_        |j6                  xs d|_        |j:                  |_        |j>                  |_         |jB                  |_"        |jF                  |_$        |jJ                  |_&        |jN                  |_(        |S )	z6Create store investment summary from cross-module datar1   c                 8    t        fd| xs g D              S )Nc           	   3   p   K   | ]-  }t        t        |d d            v rt        |d      xs d / ywstore_format_type r   N)strgetattr).0itemattr
fmt_letters     r)   	<genexpr>z`Module3ReportService._create_store_investment_summary.<locals>.sum_for_format.<locals>.<genexpr>h   sA      ,DWT3F%K!LL tQ',1,,s   36sum)	data_listr[   rZ   s    ``r)   sum_for_formatzMModule3ReportService._create_store_investment_summary.<locals>.sum_for_formatg   s#     &_"_  r+   c                 4    t        fd| xs g D              S )Nc           	   3      K   | ]=  }t        t        |d d            v r#|j                  xs d|j                  xs dz   ? ywrS   )rV   rW   rate_per_sqft
total_sqft)rX   rY   r[   s     r)   r\   zfModule3ReportService._create_store_investment_summary.<locals>.sum_civil_for_format.<locals>.<genexpr>o   sI      ,DWT3F%K!LL $$)doo.BC,s   AAr]   )r_   r[   s    `r)   sum_civil_for_formatzSModule3ReportService._create_store_investment_summary.<locals>.sum_civil_for_formatn   s#     &_"_  r+   ABrU   r   )total))r   capital_expenses_acapital_expenses_bit_capital_expenses_ait_capital_expenses_brV   rT   rental_advance_amountrental_advance_arent_per_monthrent_per_month_arental_advance_brent_per_month_butilities_acost_per_monthutilities_baverage_salarycountstore_formate_typeemployee_wages_aemployee_wages_bmarketing_expenses_store_amarketing_expenses_amarketing_expenses_store_bmarketing_expenses_bpre_operating_months_store_apre_operating_months_apre_operating_months_store_bpre_operating_months_b#calculated_pre_operating_expenses_apre_operating_expenses_a#calculated_pre_operating_expenses_bpre_operating_expenses_b#calculated_total_capital_expenses_atotal_store_capital_expenses_a#calculated_total_capital_expenses_btotal_store_capital_expenses_b#calculated_total_store_investment_atotal_store_investment_a#calculated_total_store_investment_btotal_store_investment_b)r(   r,   rE   rG   rH   rI   rJ   rK   rL   r`   re   rentutilitystaffwages                  r)   r=   z5Module3ReportService._create_store_investment_summaryc   s   18D		 /C:s.S+.B:s.S+1?1M.1?1M. Dc$006B77484N4N4SRS 1484G4G4L1 1D228b99484N4N4SRS 1484G4G4L1 1  $Gc'339r:: ,,0F0F0K!K,G55;<< ,,0F0F0K!K,	 $  E((-A%++2BCDc%228b99 11T91E44:;; 11T91    4H4c4c4hgh14H4c4c4hgh16J6g6g6lkl36J6g6g6lkl3 9I8l8l58H8l8l5>N>r>r;>N>r>r;8H8l8l58H8l8l5r+   datac                    t               }t        |t        dddd      }t               }g }	 t	        ddd      }d|_        |j                  |       |j                  t        dd	             t        d
|d   dddd      }|j                  t        d|             |j                  t        dd             t        d|d   dd	d      }|j                  t        d|             |j                  rPg d}	|	g}
|j                  D ]  }|
j                  t        |j                  xs d      t        |j                  xs d      t        |j                  xs d      t        |j                  xs d      t        |j                   xs d      t        |j"                  xs d      t        |j$                  xs d      t        |j&                  xs d      t        |j(                  xs d      g	        t+        |
      }|j-                  t/        ddddddd t0        j2                  fd!d"g             |j                  |       |j                  t        dd#             |d$   }d%|_        d&|_        |j                  t        d'|             |j                  t        dd	             t        d(|      t        d)|      t        d*|      t        d+|      g}t        t        |j8                  j:                  xs d      |      t        t        |j8                  j<                  xs d      |      t        t        |j8                  j>                  xs d      |      t        t        |j8                  j@                  xs d      |      g}||g}g d,}t+        ||d-      }|j-                  t/        dddd t0        j2                  fd.dddt0        j2                  fdd/d0d1d2d3d4d5d!dg             |j                  |       |j                  t        dd#             |d$   }d6|_        d7|_        |j                  t        d8|             |j                  t        dd	             t        d9|      t        d:|      t        d;|      t        d<|      t        d=|      t        d>|      t        d?|      t        d@|      g}t        t        |jB                  jD                  xs d      |      t        t        |jB                  jF                  xs d      |      t        t        |jB                  jH                  xs d      |      t        t        |jB                  jJ                  xs d      |      t        t        |jB                  jL                  xs d      |      t        t        |jB                  jN                  xs d      |      t        t        |jB                  jP                  xs d      |      t        t        |jB                  jR                  xs d      |      g}||g}t+        |dA      }|j-                  t/        dddd t0        j2                  fd.dddt0        j2                  fddBd0dCdDdEdFdGd!dd"g             |j                  |       |j                  t        dd#             |j                  t        dH|             g dI}|g}|j                  dJt        |jT                  jV                  xs d      t        |jT                  jX                  xs d      g       |j                  dKt        |jT                  jZ                  xs d      t        |jT                  j\                  xs d      g       |j                  dLt        |jT                  j^                  xs d      t        |jT                  j`                  xs d      g       |j                  dMt        |jT                  jb                  xs d      t        |jT                  jd                  xs d      g       |j                  dNt        |jT                  jf                  xs d      t        |jT                  jh                  xs d      g       |j                  dOt        |jT                  jj                  xs d      t        |jT                  jl                  xs d      g       |j                  dPt        |jT                  jn                  xs d      t        |jT                  jp                  xs d      g       |j                  dQt        |jT                  jr                  xs d      t        |jT                  jt                  xs d      g       |j                  dRt        |jT                  jv                  xs d      t        |jT                  jx                  xs d      g       t+        |      }|j-                  t/        dddSdddd t0        j2                  fd!d"g             |j                  |       |j                  t        dd#             |j                  t        dT|             dUdVgg}|j                  t        |jz                  j|                  xs d      t        |jz                  j~                  xs d      g       t+        |      }|j-                  t/        dddSdddd t0        j2                  fd!d"g             |j                  |       |j                  t        dd	             |j                  t        dW|j                  j                  dX       |d$                |j                  |       |j                  d       t        j                         j                  dY      }dZ|j                   d[| d\}d]| }t        j                  t        j                  j                  |      d^_       t        |d`      5 }|j                  |j                                dadada       t        j                  j                  db|      S #  Y xY w# 1 sw Y   1xY w)cz%Generate PDF report from Module3 data2   )pagesize
leftMarginrightMargin	topMarginbottomMarginzTS Logo.png   K   )widthheightLEFT   
   CustomTitleHeading1      Helvetica-Bold)parentfontSize
spaceAfter	alignmentfontNamezModule 3: Network Planning   SectionHeaderHeading2   )r   r   r   r   zNetwork Planning)	LocationStatezTotal HHz	Target HHAreaActionzFormat A Y5zFormat B Y5zTotal Stores Y5zN/Ar   )ALIGNr   r   r   r   )FONTNAMEr   r   r   r   )FONTSIZEr   r      GRIDr   r   g      ?)VALIGNr   r   TOP)WORDWRAPr   r   T   Normal   	   zTrading MonthszStore A<br/>Trading<br/>MonthszStore B<br/>Trading<br/>MonthszRationale Store AzRationale Store B)<   r      r   )	colWidths
repeatRowsBOX)r   r   r   r   )r   r   r   r   	Helvetica)r   r   r   r   )LEFTPADDINGr   r      )RIGHTPADDINGr   r   r   )
TOPPADDINGr   r      )BOTTOMPADDINGr   r   r   g      @   zPre Operating Expensesz(Pre<br/>Operating<br/>Months<br/>Store Az(Pre<br/>Operating<br/>Months<br/>Store Bz"Marketing<br/>Expenses<br/>Store Az"Marketing<br/>Expenses<br/>Store BzAccounting Benefits<br/>Store AzAccounting Benefits<br/>Store BzOther Remarks<br/>Store AzOther Remarks<br/>Store B)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   zStore Investment Summary)FieldzStore Format AzStore Format BzCapital Expenses AzIT Capital ExpenseszRental AdvancezRent Per Month	UtilitieszEmployee WageszMarketing ExpenseszPre Operating MonthszTotal Store Investment)r   r   r   r   SummaryzNetwork SubmissionszNetwork SummarisezLast Updated: z%Y-%m-%d %H:%M:%Sz%Y%m%d_%H%M%Smodule3_complete_report_group__z.pdfzuploaded_files/T)exist_okwbNuploaded_files)Or   r   r   r	   r   hAlignappendr   r
   r   r2   rV   locationstatetotal_hh	target_hhareaactionformat_a_y5format_b_y5total_store_count_y5r   setStyler   r   blackr   leadingr3   store_a_trading_monthsstore_b_trading_monthsrationale_for_store_arationale_for_store_br4   r   r   r{   r}   accounting_benefits_store_aaccounting_benefits_store_bother_remarks_store_aother_remarks_store_br5   ri   rj   rk   rl   rn   rq   rp   rr   rs   ru   ry   rz   r|   r~   r   r   r   r   r6   network_submissionsnetwork_summariser7   strftimebuildseekr   rA   r,   osmakedirspathdirnameopenwritegetvaluejoin)r(   r   bufferdocstylesstorylogotitle_stylesection_stylenetwork_headersnetwork_rowsnetworknetwork_tablenormal_styleheadersrow
table_datacolumn_widthstrading_tablepre_op_normal_stylepre_op_tableinvestment_headersinvestment_rowsinvestment_tablesummary_datasummary_table	timestampfilenamefilepathfs                                 r)   _generate_pdf_reportz)Module3ReportService._generate_pdf_report   s)   PR^`oqr$&	c"=D DKLLLL2'
 %*%%
 	Y;[IJVAr]# '*%%
 	Y1=AB   PO+,L00##((1E2./((-A.)).Q/)*/%0++0q1++0q1449:
% 
 1 ",/M"":3?13=34/ $  LL'VAr]# h' ! Y/?@VAr]# 6E6E)<8)<8	
 c$--DDMNP\]c$--DDMNP\]c$--CCLuM|\c$--CCLuM|\	
 s^
*jMaPzVXsFLL9FHa6;,7-01/2//+
   	 	]#VAr]# %X.'*$&'#Y7GHVAr]# @BUV@BUV:<OP:<OP79LM79LM13FG13FG	
 c$55RR[V[\^qrc$55RR[V[\^qrc$55PPYTYZ\opc$55PPYTYZ\opc$55QQZUZ[]pqc$55QQZUZ[]pqc$55KKTuUWjkc$55KKTuUWjk	
 s^
ZA6jVXsFLL9FHa6;,7-01/2//0*
  	  	\"VAr]# 	Y9=IJJ-. 4c$:W:W:j:j:ono6pruvz  wT  wT  wg  wg  wl  kl  sm   n  	o 5s4;X;X;n;n;srs7tvyz~  {X  {X  {n  {n  {s  rs  wt   u  	v 0#d6S6S6d6d6ihi2jlopt  qN  qN  q_  q_  qd  cd  me   f  	g 0#d6S6S6d6d6ihi2jlopt  qN  qN  q_  q_  qd  cd  me   f  	gS1N1N1Z1Z1_^_-`befj  gD  gD  gP  gP  gU  TU  cV   W  	X 0#d6S6S6d6d6ihi2jlopt  qN  qN  q_  q_  qd  cd  me   f  	g 4c$:W:W:l:l:qpq6rtwx|  yV  yV  yk  yk  yp  op  uq   r  	s 6D<Y<Y<p<p<utu8vx{  }A  }Z  }Z  }q  }q  }v  uv  yw   x  	y 8#d>[>[>>  ?E  DE  ;F  HK  LP  Li  Li  LM  LM  LR  QR  HS   T  	U 1!!*/;-VXsFLL9/0.
 # 	 	%&VAr]# 	Yy-89.0CDES!A!A!JUKSQUQ]Q]QoQoQxsxMyz{l+z/;-VXsFLL9/0+
   	 	]# 	VAr]#Y0A0A0J0JK^0_/`acijrcstu		%A LLN++O<	3DMM?!I;dS$XJ/
BGGOOH-=(D!QGGFOO%& " ww||,h77a	X "!s   Ap4 , p<4p9<qc                    K   | j                  |       d{   }| j                  |      }| j                  ||       |S 7 )w)z3Generate PDF and save to database, return file pathN)rO   r  _save_file_path_to_db)r(   r,   report_data	file_paths       r)   generate_and_save_pdfz*Module3ReportService.generate_and_save_pdf  sD      44X>>--k:	""8Y7 ?s   AA*Ar  c                    	 d| d}t        d|        | j                  j                  t              j	                  t        j
                  |k(        j                         }|rSt        d       ||_        | j                  j                          | j                  j                  |       t        d       yt        d       t        |||      }| j                  j                  |       | j                  j                          | j                  j                  |       t        d|j                          y# t        $ rF}| j                  j                          t        d	|        d
dl}|j                          Y d}~yd}~ww xY w)z;Save or update file path in summary table with group_id_modg_m3z6DEBUG: Looking for existing record with group_id_mod: z5DEBUG: Found existing record, updating uploaded_filesz"DEBUG: Updated record successfullyz1DEBUG: No existing record found, creating new one)r,   group_id_modr   z+DEBUG: Created new record with summary_id: z$ERROR saving file path to database: r   N)printr%   r9   r   filterr"  r;   r   commitrefreshadd
summary_id	Exceptionrollback	traceback	print_exc)r(   r,   r  r"  existing_summarynew_summaryer+  s           r)   r  z*Module3ReportService._save_file_path_to_db  s:   	"xj,LJ<.YZ#ww}}Z8??
@W@W[g@ghnnpMO2; /  01:<IK(%!-#,
 K( ,CKDZDZC[\] 	"GG8<=!!		"s   B5D: 8BD: :	F	<FF	N)__name__
__module____qualname__r   r"   r*   intr!   rO   r   r=   rV   r  r  r  r8   r+   r)   r$   r$   $   s    7 +; 8^# 8^:N 8^t?  ?   Rh ? B]8)= ]8# ]8~C C "c "c "r+   r$   )7fastapir   sqlalchemy.ormr   pandasr?   r   r   ior   reportlab.lib.pagesizesr   reportlab.libr   reportlab.lib.stylesr	   r
   reportlab.platypusr   r   r   r   r   r   app.models.main.network_planr   app.models.main.trading_monthsr   &app.models.main.pre_operating_expensesr   app.models.main.summaryr   r   app.models.main.groupr   app.models.main.civilr   app.models.main.info_techr   app.models.main.rent_expensesr   app.models.main.utilityr   'app.models.main.store_level_staff_needsr   app.api.module_3.schemar   r   r   r   r    r!   app.dependency.authanticationr"   r$   r8   r+   r)   <module>rH     s_    ! "  	   &   D ] ] ; : I ; * * 1 9 . K  ;B" B"r+   