
    G	/ik                     D   d dl mZ d dlmZ d dlmZmZ d dlZd dl	Z	d dl
m
Z
 d dlmZ d dlmZ d dlmZmZmZmZmZmZmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlm Z  d dl!m"Z" d dl#m$Z$ d dl%m&Z& d dl'm(Z( d dl)m*Z* d dl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 d dl4m5Z5  G d d      Z6y)    )HTTPException)Session)Environment
BaseLoaderN)datetime)BytesIO)A4)SimpleDocTemplate	ParagraphSpacerTable
TableStyleImage	PageBreak)getSampleStyleSheet)colors)TblBrandAttributeAssessment)TblBrandingAttributes)TblIntegratedMarketing)TblMarketingCompetitor)TblOptimisingAssets)
TblSummary)TblGroup)SummaryCreate)BrandAttributeAssessmentBrandingAttributesMarketingAndCommunicationIntegratedMarketingMarketingCompetitorOptimisingAssetsSummaryModule7ReportPreview)JWTPayloadSchemac                   l    e Zd ZdedefdZdedefdZdede	fdZ
d	ede	fd
Zdede	fdZdede	fdZy)Module7ReportServicedbtokenc                      || _         || _        y )N)r&   r'   )selfr&   r'   s      F/var/www/html/retail-simulation-api/app/api/module_7_report/service.py__init__zModule7ReportService.__init__$   s    
    group_idreturnc                   K   |st        dd      | j                  j                  t              j	                  |      j                         xs9 | j                  j                  t              j	                  |      j                         xs | j                  j                  t              j	                  |      j                         xs | j                  j                  t              j	                  |      j                         xs| | j                  j                  t              j	                  |      j                         xs= | j                  j                  t              j	                  |      j                         }|r| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }| j                  j                  t        j                  t        j                        j	                  |      j                         }| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }| j                  j                  t              j	                  |      j                         }	t        |      }
|rt        |j                  |j                   t#        |j$                  t&              rdj)                  |j$                        nt+        |j$                  xs d      |j,                  |j.                        }
g }|D ]0  }|j1                  t3        |j4                  t#        |j6                  t&              rdj)                  |j6                        nt+        |j6                  xs d      t#        |j8                  t&              rdj)                  |j8                        nt+        |j8                  xs d      |j:                  t#        |j<                  t&              rdj)                  |j<                        nt+        |j<                  xs d      |j>                  |j.                               3 tA        ||
|rtC        di |jD                  ntC        |      tG        |r|j                  nd	|r|j                  nd|
      |D cg c]  }tI        di |jD                   c}xs tI        |      g|rtK        di |jD                  ntK        |      |xs t3        |      g|	rtM        di |	jD                  ntM        |      tN        jP                  jS                         	      S | j                  j                  tT              j	                  |      j                         }|rxtA        |t        |      tC        |      tG        |      tI        |      gtK        |      t3        |      gtM        |      tN        jP                  jS                         	      S t        dd      c c}w w)z,Fetch module 7 data from all related tables.i  zgroup_id is required)status_codedetail)r-   z, N/A)brand_iddefine_research_methodologyname_top_10_attributesremarksr-   )optimising_idspace_resources_for_incomenon_space_resources_for_incomepercentage_of_salespredictions_around_changes"changes_in_marketing_communicationr-   g        )marketing_budgetrationalr-   )	r-   brand_attribute_assessmentbranding_attributesmarketing_and_communicationintegrated_marketingmarketing_competitoroptimising_assetssummarylast_updatedi  zGroup ID not found in database )+r   r&   queryr   	filter_byfirstr   r   r   r   r   r=   r>   allr   r3   r4   
isinstancer5   listjoinstrr6   r-   appendr    r7   r8   r9   r:   r;   r<   r"   r   __dict__r   r   r   r!   pd	Timestampnowr   )r)   r-   module_data_existsr?   r@   marketing_and_communication_rowrB   rC   rD   rE   brand_assessment_dataoptimising_assets_dataoaimgroup_existss                  r*   _fetch_module7_dataz(Module7ReportService._fetch_module7_data(   sv    C8NOO GGMM56@@(@SYY[ KGGMM/0::H:MSSUKGGMM01;;X;NTTVK GGMM01;;X;NTTVK GGMM-.88(8KQQS	K
 GGMM*%///BHHJ 	 )-7R)S)])]go)])p)v)v)x&"&''--0E"F"P"PZb"P"c"i"i"k.2ggmm<R<c<ce{  fE  fE  /F  /P  /P  Zb  /P  /c  /i  /i  /k+#'77==1G#H#R#R\d#R#e#i#i#k #'77==1G#H#R#R\d#R#e#k#k#m  $.A B L LV^ L _ c c eggmmJ/9989LRRTG %=h$O!)(@7@@0J0f0fku  wQ  wh  wh  jn  lo4995O5f5f+g  ux  yS  yj  yj  ys  ns  ut6>>7@@)% &("'&--.>"$"2"2[efh  gD  gD  FJ  \Ktyy9V9V/W  QT  UW  Ur  Ur  U{  v{  Q|cmnp  oP  oP  RV  dW499R=^=^3_  ]`  ac  aB  aB  aK  FK  ]L(*(>(>[efh  gD  gD  FJ  \Ktyy9V9V/W  QT  UW  Ur  Ur  U{  v{  Q|797\7\[[/  ( (!+@Zm$6$V9L9U9U$V  tF  PX  tY,EYx%D%U%U  BIh<EEns%-
 Th%hSgR&9&HBKK&HSg%h  &U  nA  KS  nT  mU]q%8%Y;O;X;X%Y  xK  U]  x^"8"a=MW_=`<a7>3'"2"23GU]D^\\--/ "  77==2<<h<OUUWL+%/GQY/Z(:H(M0IS[0\*=x*P)Q)<h)O'7'J&K#X6!#!1!1!3
 
 $<\]]3 &is   U0[2[E[reportc                 x   K   d}t        t                     }|j                  |      j                  |      S w)z*Render Module 7 report as an HTML preview.u  
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                h1, h2 { color: #333; }
                table { width: 100%; border-collapse: collapse; margin-top: 15px; }
                th, td { border: 1px solid #ddd; padding: 8px; }
                th { background-color: #f5f5f5; text-align: left; }
                pre { background: #fafafa; padding: 10px; border: 1px solid #eee; }
            </style>
        </head>
        <body>
            <h1>Module 7 Report – Marketing & Communication</h1>

            <h2>Brand Attribute Assessment</h2>
            <table>
                <tr><th>Define Research Methodology</th><td>{{ report.brand_attribute_assessment.define_research_methodology }}</td></tr>
                <tr><th>Top 10 Attributes</th><td>{{ report.brand_attribute_assessment.name_top_10_attributes }}</td></tr>
                <tr><th>Remarks</th><td>{{ report.brand_attribute_assessment.remarks }}</td></tr>
            </table>

            <h2>Branding Attributes</h2>
            <table>
                <tr><th>Attributes</th><td>{{ report.branding_attributes.attributes }}</td></tr>
                <tr><th>Reference Retailer 1</th><td>{{ report.branding_attributes.reference_retailer_1 }}</td></tr>
                <tr><th>Reference Retailer 2</th><td>{{ report.branding_attributes.reference_retailer_2 }}</td></tr>
                <tr><th>Own Brand</th><td>{{ report.branding_attributes.own_brand }}</td></tr>
            </table>

            <h2>Marketing & Communication</h2>
            <table>
                <tr><th>Marketing Budget</th><td>{{ report.marketing_and_communication.marketing_budget }}</td></tr>
                <tr><th>Rationale</th><td>{{ report.marketing_and_communication.rational }}</td></tr>
            </table>

            <h2>Integrated Marketing Activities</h2>
            {% for im in report.integrated_marketing %}
            <table>
                <tr><th>Activity Name</th><td>{{ im.activity_name }}</td></tr>
                <tr><th>Budget Allocated</th><td>{{ im.budget_allocated }}</td></tr>
                <tr><th>Objective</th><td>{{ im.objective }}</td></tr>
                <tr><th>Measurement</th><td>{{ im.measurment }}</td></tr>
                <tr><th>Target Shopper Journey</th><td>{{ im.target_shopper_journey }}</td></tr>
                <tr><th>Actions</th><td>{{ im.actions }}</td></tr>
            </table>
            {% endfor %}

            <h2>Marketing Competitor Analysis</h2>
            <table>
                <tr><th>Reference Retailer</th><td>{{ report.marketing_competitor.name_of_the_refereance_retailer }}</td></tr>
                <tr><th>Marketing Communication</th><td>{{ report.marketing_competitor.marketing_communication }}</td></tr>
                <tr><th>Planned Activities</th><td>{{ report.marketing_competitor.plan_activities }}</td></tr>
            </table>

            <h2>Optimising Assets for Revenue</h2>
            {% for oa in report.optimising_assets %}
            <table>
                <tr><th>Space Resources for Income</th><td>{{ oa.space_resources_for_income }}</td></tr>
                <tr><th>Non-space Resources for Income</th><td>{{ oa.non_space_resources_for_income }}</td></tr>
                <tr><th>Percentage of Sales</th><td>{{ oa.percentage_of_sales }}</td></tr>
                <tr><th>Predictions Around Changes</th><td>{{ oa.predictions_around_changes }}</td></tr>
                <tr><th>Changes in Marketing Communication</th><td>{{ oa.changes_in_marketing_communication }}</td></tr>
            </table>
            {% endfor %}

            <h2>Summary</h2>
            <table>
                <tr><th>Marketing Submissions</th><td>{{ report.summary.marketing_submissions }}</td></tr>
                <tr><th>Summary</th><td>{{ report.summary.marketing_summarise }}</td></tr>
            </table>
        </body>
        </html>
        )loader)r]   )r   r   from_stringrender)r)   r]   templateenvs       r*   _render_htmlz!Module7ReportService._render_html}   s:     IT .x(//v/>>s   8:datac                 "   t               }t        |t        dddd      }t               }g }	 t	        ddd      }d|_        |j                  |       |j                  t        dd	             |d
   }d|_        |j                  t        d|             |j                  t        dd             |d   }d|_
        d	|_        d }	|j                  t        d|d                |j                  t        dd	             t        d|      t        d|      gt        d|      t        t        |j                  j                  xs d      |      gt        d|      t        t        |j                  j                  xs d      |      gt        d|      t        t        |j                  j                   xs d      |      gg}
t#        |
      }|j%                  t'        ddddt(        j*                  fddddt(        j*                  fdddd d!d"d#d$d%d&d'g             |j                  |       |j                  t        dd(             |j                  t        d)|d                |j                  t        dd	             t        d|      t        d|      gt        d*|      t        t        |j,                  j.                  xs d      |      gt        d+|      t        t        |j,                  j0                  xs d      |      gt        d,|      t        t        |j,                  j2                  xs d      |      gt        d-|      t        t        |j,                  j4                  xs d      |      gt        d.|      t        t        |j,                  j6                  xs d      |      gg}t#        |      }|j%                  t'        ddddt(        j*                  fddddt(        j*                  fdddd d!d"d#d$d%d&d'g             |j                  |       |j                  t        dd(             |j                  t        d/|d                |j                  t        dd	             t        d|      t        d|      gt        d0|      t         |	|j8                  j:                        |      gt        d1|      t        t        |j8                  j<                  xs d      |      gg}t#        |      }|j%                  t'        ddddt(        j*                  fddddt(        j*                  fdddd d!d"d#d$d%d&d'g             |j                  |       |j                  t        dd(             |j                  t        d2|d                |j                  t        dd	             t        d3|      t        d4|      t        d5|      t        d6|      t        d7|      t        d8|      g}|g}|j>                  D ]  }t        |j@                  xs d|      t        |jB                  r |	|jB                        nd9|      t        |jD                  xs d|      t        |jF                  xs d|      t        |jH                  xs d|      t        |jJ                  xs d|      g}|j                  |        t#        |d:      }|j%                  t'        ddddt(        j*                  fddddt(        j*                  fdd;dd<d!d"d#d$d%d&d'g             |j                  |       |j                  t        dd(             |j                  t        d=|d                |j                  t        dd	             t        d|      t        d|      gt        d>|      t        t        |jL                  jN                  xs d      |      gt        d?|      t        t        |jL                  jP                  xs d      |      gt        d@|      t        t        |jL                  jR                  xs d      |      gg}t#        |      }|j%                  t'        ddddt(        j*                  fddddt(        j*                  fdddd d!d"d#d$d%d&d'g             |j                  |       |j                  t        dd(             |j                  tU                      |j                  t        dA|d                |j                  t        dd	             t        dB|      t        dC|      t        dD|      t        dE|      t        dF|      g}|g}|jV                  D ]  }t        |jX                  xs d|      t        |jZ                  xs d|      t        t        |j\                  xs dG      |      t        |j^                  xs d|      t        |j`                  xs d|      g}|j                  |        t#        |d:      }|j%                  t'        ddddt(        j*                  fddddt(        j*                  fdd;dd<d!d"d#d$d%d&d'g             |j                  |       |j                  t        dd(             |j                  t        dH|d                |j                  t        dd	             t        d|      t        d|      gt        dI|      t        t        |jb                  jd                  xs d      |      gt        dJ|      t        t        |jb                  jf                  xs d      |      gg}t#        |      }|j%                  t'        ddddt(        j*                  fddddt(        j*                  fdddd d!d"d#d$d%d&d'g             |j                  |       |j                  t        dd(             |j                  t        dd	             |j                  t        dK|jh                  jk                  dL       |d                |jm                  |       |jo                  dG       tq        jr                         jk                  dM      }dN|jt                   dO| dP}dQ| }tw        jx                  tv        jz                  j}                  |      dRS       t        |dT      5 } | j                  |j                                dUdUdU       tv        jz                  j                  dV|      S #  Y xY w# 1 sw Y   1xY w)Wz(Generate PDF report and return file path2   )pagesize
leftMarginrightMargin	topMarginbottomMarginzTS Logo.png   K   )widthheightLEFT   
   Titlez(Module 7: Marketing &amp; Communications   Normal   c                     | | dk(  ryd| dS )zFormat currency with Rs. prefixr   Rs. 0zRs. z,.0frG   )amounts    r*   format_currencyzBModule7ReportService._generate_pdf_report.<locals>.format_currency   s    ~1&''r,   zBrand Attribute AssessmentHeading2z<b>Field</b>z<b>Value</b>zDefine Research Methodologyr2   zName Top 10 AttributesRemarksGRIDr   r   r   g      ?BOX)FONTNAMEr   r   r   zHelvetica-Bold)FONTSIZEr   r   rw   )r   r   rr   r   	Helvetica)r   r   r   rw   )LEFTPADDINGr   r      )RIGHTPADDINGr   r   r   )
TOPPADDINGr   r   r   )BOTTOMPADDINGr   r   r   )VALIGNr   r   TOP)ALIGNr   r   rq   )WORDWRAPr   r   T   zBranding Attributes
AttributeszReference Retailer 1zReference Retailer 2z	Own BrandzBrand Positioning StatementzMarketing and CommunicationzMarketing BudgetRationalzIntegrated MarketingzActivity<br/>NamezBudget<br/>Allocated	ObjectiveMeasurementzTarget Shopper<br/>JourneyActionsry   )
repeatRows)r   r   r      )r   r   r   r   zMarketing CompetitorzName of Reference RetailerzMarketing CommunicationzPlan ActivitieszBrand JourneyzSpace Resources<br/>for Incomez"Non-Space Resources<br/>for IncomezPercentage<br/>of SaleszPredictions Around<br/>Changesz&Changes in Marketing<br/>Communicationr   r!   zMarketing SubmissionszMarketing SummarisezLast Updated: z%Y-%m-%d %H:%M:%Sz%Y%m%d_%H%M%Smodule7_complete_report_group__z.pdfzuploaded_files/T)exist_okwbNuploaded_files)Cr   r
   r	   r   r   hAlignrP   r   	alignmentr   fontSizeleadingrO   r?   r4   r5   r6   r   setStyler   r   blackr@   
attributesreference_retailer_1reference_retailer_2	own_brandbrand_positioning_statementrA   r=   r>   rB   activity_namebudget_allocated	objective
measurmenttarget_shopper_journeyactionsrC   name_of_the_reference_retailermarketing_communicationplan_activitiesr   rD   r8   r9   r:   r;   r<   rE   marketing_submissionsmarketing_summariserF   strftimebuildseekr   rT   r-   osmakedirspathdirnameopenwritegetvaluerN   )!r)   re   bufferdocstylesstorylogotitle_stylenormal_styler{   
brand_databrand_tablebranding_databranding_tablemarketing_datamarketing_tableintegrated_headersintegrated_rows
integratedrowintegrated_tablecompetitor_datacompetitor_tableassets_headersassets_rowsassetassets_tablesummary_datasummary_table	timestampfilenamefilepathfs!                                    r*   _generate_pdf_reportz)Module7ReportService._generate_pdf_report   s*   PR^`oqr$&	c"=D DKLLLL2'
 Wo !YI;WXVAr]#h' !!	( 	Y;VJ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Y0A0A0J0JK^0_/`acijrcstu		%A LLN++O<	3DMM?!I;dS$XJ/
BGGOOH-=(D!QGGFOO%& " ww||,h77o	f "!s   As= 5 t=ttc                    K   | j                  |       d{   }| j                  |      }| j                  ||       |S 7 )w)z3Generate PDF and save to database, return file pathN)r\   r   _save_file_path_to_db)r)   r-   report_data	file_paths       r*   generate_and_save_pdfz*Module7ReportService.generate_and_save_pdf  sD      44X>>--k:	""8Y7 ?s   AA*Ar   c                    	 d| d}t        d|        | j                  j                  t              j	                  t        j
                  |k(        j                         }|rSt        d       ||_        | j                  j                          | j                  j                  |       t        d       yt        d       t        |||      }| j                  j                  |       | j                  j                          | j                  j                  |       t        d|j                          y# t        $ rF}| j                  j                          t        d	|        d
dl}|j                          Y d}~yd}~ww xY w)z;Save or update file path in summary table with group_id_modg_m7z6DEBUG: 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&   rH   r   filterr   rJ   r   commitrefreshadd
summary_id	Exceptionrollback	traceback	print_exc)r)   r-   r   r   existing_summarynew_summaryer   s           r*   r   z*Module7ReportService._save_file_path_to_db  s:   	"xj,LJ<.YZ#ww}}Z8??
@W@W[g@ghnnpMO2; /  01:<IK(%!-#,
 K( ,CKDZDZC[\] 	"GG8<=!!		"s   B5D: 8BD: :	F	<FF	N)__name__
__module____qualname__r   r#   r+   intr"   r\   rO   rd   r   r   r   rG   r,   r*   r%   r%   #   s    7 +; S^# S^:N S^jM?)= M?# M?^d8)= d8# d8L	C C "c "c "r,   r%   )7fastapir   sqlalchemy.ormr   jinja2r   r   pandasrR   r   r   ior   reportlab.lib.pagesizesr	   reportlab.platypusr
   r   r   r   r   r   r   reportlab.lib.stylesr   reportlab.libr   *app.models.main.brand_attribute_assessmentr   #app.models.main.branding_attributesr   $app.models.main.integrated_marketingr   -app.models.main.marketing_competitor_analysisr   -app.models.main.optimising_assets_for_revenuer   app.models.main.summaryr   app.models.main.groupr   app.api.summary.schemar   app.api.module_7_report.schemar   r   r   r   r   r    r!   r"   app.dependency.authanticationr#   r%   rG   r,   r*   <module>r
     sd    ! " *  	   & h h h 4   R E G P M . * 0	 	 	 ;r" r"r,   