o
    "$h                    @   s  d dl mZ d dlmZ d dlmZ d dlZd dlZd dlZd dl	Z	d dl
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 ejejeje d dlZe Zed d	d
 Zdd Zdd Zedgdd ZdZ dZ!dZ"dZ#dd Z$dd Z%dd Z&dd Z'dd Z(d d! Z)d"d# Z*d$d% Z+d&d' Z,d(d) Z-d*d+ Z.d,d- Z/d.d/ Z0d0d1 Z1d2d3 Z2d4d5 Z3d6d7 Z4d8d9 Z5d:d; Z6d<d= Z7d>d? Z8d@dA Z9dBdC Z:edDgdEdF Z;edDgdGdH Z<dS )I    )log)api_view)JsonResponseN)timezone)defaultdict)HTTPBasicAuthz"Starting the PPP Automation scriptc              
   C   s   d}d}d}t |||}d| dddd}zAd|  d	}tj||d
}| d}t|}	tdt|	 d|   t|	dkrGd}
|
W S t|	dkrRd}
|
W S d}
|
W S  t	yq } zt
d|  W Y d }~d S d }~ww )N$6e5989aa-4fd1-4015-8648-8f75609d607b(mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS$95f69e7d-1811-4ab9-9b5a-eba95d3eba9bBearer odata.maxpagesize=50004.0AuthorizationPreferzOData-MaxVersionzOData-Versionzkhttps://scicdev.crm.dynamics.com/api/data/v9.1/trit_cerequests?$filter=_trit_eventregistrationid_value eq ''headersvaluezce request count z for event registration id r   TFz!Error in validation of CE Requestz>Error at ce_request_validation_api function and the error is: 	get_tokenrequestsgetjsonpd	DataFrameloggerinfolen	Exceptionerror)eventregistrationid	client_idclient_secret	tenant_idtokenr   trit_cerequests_api_url	event_reqdtdf
CE_REQ_Vale r,   -/var/www/html/PPP_Automation/ppp_app/views.pyce_request_validation_api.   s6   
r.   c              
   C   s   d}d}d}t |||}d| dddd}zKd|  d	}tj||d
}| }|dd d}	d|	 d	}
tj|
|d
}| }|d}g }|D ]
}||d qKtd|  |W S  ty{ } ztd|  W Y d }~d S d }~ww )Nr   r	   r
   r   r   r   r   zZhttps://scicdev.crm.dynamics.com/api/data/v9.1/msevtmgt_events?$filter=trit_eventcode eq 'r   r   r   r   msevtmgt_eventidzohttps://scicdev.crm.dynamics.com/api/data/v9.1/msevtmgt_eventregistrations?$filter=_msevtmgt_eventid_value eq 'msevtmgt_eventregistrationidzevent registration ids list z4Error at event_name_uuid function and the error is: )	r   r   r   r   appendr   r   r   r    )	eventcoder"   r#   r$   r%   r   event_api_urlr'   resevent_id"msevtmgt_eventregistration_api_urlmsevtmgt_eventregistration_reqmsevtmgt_eventregistration_resres1er_listerr+   r,   r,   r-   event_name_uuidU   s6   
r<   c              
   C   s\  zt d}| }td W n ty* } ztd|  W Y d }~nd }~ww z|d| f | }W n tyR } ztd|  W Y d }~nd }~ww z?|rtt	j	
tj}|d|| f |  |  ddd	d
W S t	j	
tj}|d| ||f |  |  dddd
W S  ty } ztd|  W Y d }~d S d }~ww )Nz'/var/www/html/PPP_Automation/db.sqlite3zGConnected to SQLite database at /var/www/html/PPP_Automation/db.sqlite3z/Error at connection sqlitedb and the error is: zN
        SELECT * FROM ppp_events
        WHERE qs_ppp_event_code = ?
        z1Error at retrieving event code and the error is: z
            UPDATE ppp_events
            SET qs_ppp_last_modified_date = ?
            WHERE qs_ppp_event_code = ?
               z Event is already Trigged for PPPT
statusCodemessageisEventTriggedAlreadyz
            INSERT INTO ppp_events (qs_ppp_event_code, qs_ppp_created_date, qs_ppp_last_modified_date)
            VALUES (?, ?, ?)
            zEvent is new to PPPFz>Error at retrieving updating the event code and the error is: )sqlite3connectcursorr   r   r   r    executefetchonedatetimenowr   utccommitclose)
event_codeconnrD   r+   recordutc_nowr,   r,   r-   check_eventcode_exist   sV   
rP   GETc                 C   sF  | j dkr!td | jd}td|  zz;|sztddd dddW W |ryz/d	}d|i}d
di}tj|||d}td| d|j d|  td| d|j  W S  t	yx } zt
d| d|  W Y d }~S d }~ww S zt|}W nt t	y } zht
d|  tdddddW  Y d }~W W |rz/d	}d|i}d
di}tj|||d}td| d|j d|  td| d|j  W S  t	y } zt
d| d|  W Y d }~S d }~ww S d }~ww td| d| t|ddW W |rWz/d	}d|i}d
di}tj|||d}td| d|j d|  td| d|j  W S  t	yV } zt
d| d|  W Y d }~S d }~ww S  t	y } zjt
d|  tddd dddW  Y d }~W |rz/d	}d|i}d
di}tj|||d}td| d|j d|  td| d|j  W S  t	y } zt
d| d|  W Y d }~S d }~ww S d }~ww |r z/d	}d|i}d
di}tj|||d}td| d|j d|  td| d|j  W w  t	y } zt
d| d|  W Y d }~w d }~ww w d S )NrQ   z#Received GET request at validateapir2   zThe Event code is: i  z#Missing ?eventcode= in query stringr>   statusz0https://corporateallibot.scic.com/PPP-AutomationzContent-Typezapplication/json)r   r   zPOST to z completed with status z and post response zFailed to POST to : zcheck_eventcode_exist failed:   z"Internal error at event code check)r?   r@   zResponse for Eventcode  F)safez(Error at validate api and the error is: zInternal server error)methodr   r   rQ   r   r   r   poststatus_coder   r    rP   )requestr2   urlpayloadr   post_responser+   r4   r,   r,   r-   validateapi   s   
 " ""
""r_    https://scicdev.crm.dynamics.comr   r	   r
   c                 C   sl   d| d}d| |t d}tj||d}|jdkr%td | dS td	|j	  t
d	|j	 )
Nz"https://login.microsoftonline.com/z/oauth2/tokenclient_credentials)
grant_typer"   r#   resource)datar=   zToken retrieved successfullyaccess_tokenzFailed to retrieve token: )base_urlr   rY   rZ   r   r   r   r   r    textr   )r"   r#   r$   	token_urlr]   responser,   r,   r-   r      s   

r   c              
   C   sx   z d}| |||d}t d|  tj||d}| dW S  ty; } zt d|  W Y d}~dS d}~ww )a  
    Fetch the instructor approval ID based on provided parameters.

    Parameters:
        product_id (str): The unique identifier for the product.
        state_id (str): The unique identifier for the state.
        delivery_method (int): The code representing the delivery method.
        license_type (int): The code representing the type of license.

    Returns:
        str or None: The instructor approval ID if found, otherwise None.
    zMhttps://webapi.scic.com/OrganizerPython/api/PythonAPI/GetInstructorapprovalId)	ProductIdStateIdDeliveryMethodTypeofLicensez1Fetching instructor approval ID with parameters: )paramsri   z'Error fetching instructor approval ID: N)r   r   r   r   r   r   r    )
product_idstate_iddelivery_methodlicense_typer\   rn   ri   r+   r,   r,   r-   fetch_instructor_approval_id  s   rs   c              
   C   s@  d}d}d}d}zt |||}W n ty) } zdd| iW  Y d}~S d}~ww d| d	d
d
d}|d }ddi}	zDtj||| d}
|
jdv rWtd|
j ddi}	W |	S |
jdkrhtd ddi}	W |	S td|
j|
j dd|
j d|
j i}	W |	S  ty } ztd| dd| i}	W Y d}~|	S d}~ww )z
    Creates a new record in the Dynamics 365 CRM system using the OData API.

    Parameters:
        new_record (dict): The record data to be created in the CRM.

    Returns:
        dict: A dictionary containing the status of the operation.
    r   r	   r
   r`   rS   zDFailed to get token at function ce_request_odata and the error is - Nr   r   r   r   z/api/data/v9.2/trit_cerequestsnull)r   r   )r=      zLRecord created successfully with status code at unction ce_request_odata: %sSuccess   z1No content to update at function ce_request_odatazSuccess with no changesz<Failed to create record with status code %s and response: %sz)Failed to create record with status code z and response: z&Error at ce_request_odata function: %sz&Failed at ce_request_odata function - )	r   r   r   rY   rZ   r   r   r    rg   )
new_recordr"   r#   r$   rf   r%   r+   r   ce_request_api_urlResponseri   r,   r,   r-   ce_request_odata8  sJ   





r{   c              
   C   s  d}d}d}t |||}d| dddd}zd| }tj||d	}| }	|	d
 }
t|
}||d | k }g }| D ]r\}}|d }|d }|r|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|dr||d }|| q=|}t	
d!|  d"| d#|  |}t	
d!|  d"| d$|  |W S  ty } zt	d%| W Y d }~d S d }~ww )&Nr   r	   r
   r   r   r   r   ehttps://scicdev.crm.dynamics.com/api/data/v9.1/trit_instructorapprovals?$filter=_trit_state_value eq r   r   _trit_product_value	trit_nametrit_instructorapprovalidPCz(PC)z(PC/ETH)(PC/LH/ETH)(PC/LH)(LH/PC)PC/LHLH/PC(LH/PC/ETH)(ETH/PC/LH)	LH/PC/ETH	ETH/PC/LH	P/C & L/H(P/C & L/H)z(PC/LAH/ETH)z
PC/LAH/ETHz(P/C)P/Cr~   IdState approval ID for product 
 in state z pc 1: z pc 2: zError at function pc: %sr   r   r   r   r   r   iterrowsendswithr1   r   r   r   r    ro   rp   r"   r#   r$   r%   r   state_approval_api_urlstate_approval_reqr4   rd   state_approval_tablestate_approvalstateapproval_id_lists_rowsr~   state_approvaliddicts_of_state_approvestateapproval_idr+   r,   r,   r-   pc{  sF   


r   c              
   C   s  d}d}d}t |||}d| dddd}zd| }tj||d	}| }	|	d
 }
t|
}||d | k }g }| D ]r\}}|d }|d }|r|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|ds|dr||d}|| q=|}t	
d |  d!| d"|  |W S  ty } zt	d#| W Y d }~d S d }~ww )$Nr   r	   r
   r   r   r   r   r|   r   r   r}   r~   r   LHz(L/H)z(LH/ETH)r   r   z(LH/LAW/REG/ETH)zLH (Webinar)r   r   r   r   r   r   r   r   r   L/Hr   r   r   z LH function: zError at function lh: %sr   r   r,   r,   r-   lh  sB   


r   c                 C   s  d}d}d}t |||}d| dddd}d}	z-|	 d	|  d
| d| d}
t |||}d| dddd}tj|
|d}| d}W n ty^ } ztd|  W Y d }~nd }~ww z$g }|D ]}|d}|| qdtd|  d| d| d|  W n ty } ztd|  W Y d }~d S d }~ww zFg }|D ]*}|	 d| d| d}tj||d}| d}|D ]}|d}|| qqtd|  d| d| d| d| 
 |W S  ty } ztd|  W Y d }~d S d }~ww )Nr   r	   r
   r   r   r   r   r`   z@/api/data/v9.1/trit_statefilings?$filter=_trit_product_value eq z and _trit_state_value eq z  and trit_deliverymechanisms eq z&$select=trit_statefilingidr   r   zMError at get_state_approval_guid function while fetching state filing data1: trit_statefilingidzState filing data for product z, state z, delivery mechanism rT   zOError at get_state_approval_guid function while processing state filing data2: zL/api/data/v9.1/trit_instructorapprovals?$filter=_trit_statefiling_value eq 'z' and trit_typeoflicense eq z"&$select=trit_instructorapprovalidr   z State approval data for product z, license type zOError at get_state_approval_guid function while fetching state approval data3: )	r   r   r   r   r   r   r    r1   r   )productstatedelivery_mechanismrr   r"   r#   r$   r%   r   rf   statefiling_api_urlstate_filing_reqstate_filing_jsonr+   state_filing_dataiastate_approval_datajr   r   state_approval_jsonkbr,   r,   r-   get_state_approval_guid  s~   
&
(r   c              
   C   s  zd }|}t d|  |d urYt d |dv rOg }|dkr%ddg}n|dkr.ddg}n|dkr7ddg}nddg}|D ]}	t| |||	}|rM|  W S q=n^t d d}|W S |d u sa|d	krt d
|  t d d}zt d t| |||}t d t d| W |W S  ty }
 zt d|
  W Y d }
~
|W S d }
~
ww t d t d|  |W S  ty }
 zt d|
  W Y d }
~
d S d }
~
ww )Nzlic LOH check - zlic LOH is not Nonepqrr   r   r   z7lic LOH is not None but does not match any known valuesNullszlic LOH is zlic LOH is None or 314310003zstep 1 passzstep 2 passz these are the state approval idszstate approv error z$error value type in lic_LOH variablezstate_approval_id - z;Error at function state_approval function and the error is )r   r   r   r   )ro   trit_license_trit_stateid_valuer   type_of_license!trit_license_trit_lineofauthoritytrit_licenseidr   lic_LOHlicense_priorityrr   r+   r,   r,   r-   r   X  s\   









r   c                 C   s"  | j s	t| d std dS tdd }|  D ]u\}}|d }d|vr/td|  qzC|dd	d
 }|dd}t|dkrNtd|  W q|d d |d }}d	|}	t
|d	 d d	 }
||	 |
 | W q ty } ztd| d|  W Y d }~qd }~ww d}tdd }| D ]\}	}td	dD ]}
t||
 }|||	 |
< qqg }| D ]!\}	}td	dD ]}
||
 }||	|
||||krdndd qqt|}d|jv r
||d dk }|j s
td td t| td dS td dS )Ntrit_answeredz4No valid trit_name found with trit_answered as True.noc                   S      t tS N)r   setr,   r,   r,   r-   <lambda>      z)check_poll_requirements.<locals>.<lambda>r~   :zInvalid format, missing colon:    r   -      zSkipping invalid format: zError processing rT   c                   S   r   r   )r   intr,   r,   r,   r-   r     r      
SufficientInsufficient)ProductHourzRequired PollszTotal PollsStatusr   z"
Products with insufficient polls:z"#####Insufficient data starts#####z #####Insufficient data ends#####z2This product have sufficient polls for every hour.yes)emptyanyr   r   r   r   splitrsplitr   joinr   addr   itemsranger1   r   r   columns)rd   polls_by_product_hourr   rowr~   product_hour_partpartsproduct_hourpoll_numr   hourr+   required_polls_per_hourproduct_poll_summaryhourstotal_poll_countsummary_records	hour_datatotal_polls
summary_dfinsufficient_pollsr,   r,   r-   check_poll_requirements  sj   

"







r   c              
   C   s4  t jddd}t jddd}t jddd}d}d}d}t|||}d	| d
ddd}	d|  d}
tj|
|	d}| }|d }t |}td|  |d d }td|  d}z|d d dkrtd |	 D ]\}}|d |kr|d }td|  |d } |W S qn|W S |d d dkrtd |	 D ]\}}|d |kr|d }td|  |d } |W S q|W S |d d dkrtd |	 D ]\}}|d |kr|d }td|  |d } |W S q|W S td |W S  t
y } ztd |  W Y d }~d S d }~ww )!NzG/var/www/html/PPP_Automation/ppp_app/AO and AM state and statecode.xlsxAO)
sheet_nameAMCCr   r	   r
   r   r   r   r   zMhttps://scicdev.crm.dynamics.com/api/data/v9.1/products?$filter=productid eq z&$select=namer   r   zao am states product table - namer   zAO,AM&CC - r   z!This event number is in AO statesstateidr~   zAO state name is z
CE requestzThis event is in AM stateszAM state name is zThis event is in CC stateszCC state name is z'It doesn't comes under AO or AM productz!fails at ao_am_states function - )r   
read_excelr   r   r   r   r   r   r   r   r   )trit_productr   aoamccr"   r#   r$   r%   r   product_api_urlri   r4   rd   r   AO_AM_CCno_of_cerequestindexr   r~   r+   r,   r,   r-   ao_am_states  s|   




r   c           	      C   s   t | }|d}i }|D ]\}}td| d ||d dk }t|}|||< q| D ]}|dkr<td q0|dkrFtd	 q0td
 q0d S )N_trit_courseassignment_valuez
Processing for r   r   Tr   z#We can create CE requestr   z# We can't create CERequestzNull in results)r   r   groupbyr   r   r   values)	
pquestionsrd   grouped_dataresultscourse_valuegroupvalid_groupresult	result_ynr,   r,   r-   process_pquestions.  s   


r	  c              
   C   s   d}d}d}t |||}d| dddd}d|  }zBtj||d	}| }|d
 }	t|	}
|
d d }|
d d }|
d d }|
d d }|
d d }|
d d }||||||dW S  tyw } ztd|  W Y d }~d S d }~ww )Nr   r	   r
   r   r   r   r   zshttps://scicdev.crm.dynamics.com/api/data/v9.1/msevtmgt_eventregistrations?$filter=msevtmgt_eventregistrationid eq r   r   _msevtmgt_eventid_valuer   trit_cedeclinationreason_msevtmgt_contactid_valuetrit_lgsstatetrit_lgsrequestr0   )r/   r  msevtmgt_contactid_valuer  r  r0   z5Error at function evenregistration and the error is: 	r   r   r   r   r   r   r   r   r    )eventregistration_idr"   r#   r$   r%   r   r6   ri   r4   rd   msevtmgt_eventregistrationr/   r  r  r  r  r0   r+   r,   r,   r-   evenregistrationG  s8   

r  c              
   C   s   d}d}d}t |||}d| dddd}d|  }z4tj||d	}| }|d
 }	t|	}
|
d d }|
d d }|
d d }|
d d } |||| dW S  tyi } ztd|  W Y d }~d S d }~ww )Nr   r	   r
   r   r   r   r   z[https://scicdev.crm.dynamics.com/api/data/v9.1/msevtmgt_events?$filter=msevtmgt_eventid eq r   r   	trit_typer   r}   trit_deliverymechanismsr/   )r  r   r  r/   z3Error at function msevtmgt_event and the error is: r  )r/   r"   r#   r$   r%   r   msevtmgt_event_api_urlri   r4   rd   msevtmgt_eventr  r   r  r+   r,   r,   r-   r  r  s4   

r  c              
   C   s   d}d}d}t |||}d| dddd}d|  }z4tj||d	}| }|d
 }	t|	}
|
d d }|
d d }|
d d }|
d d }||||dW S  tyi } ztd|  W Y d }~d S d }~ww )Nr   r	   r
   r   r   r   r   zMhttps://scicdev.crm.dynamics.com/api/data/v9.1/contacts?$filter=contactid eq r   r   	contactidr   	firstnamelastnamefullname)contacts_contactidcontacts_firstnamecontacts_lastnamecontacts_fullnamez-Error at function contacts and the error is: r  )r  r"   r#   r$   r%   r   contacts_api_urlri   r4   rd   contactsr  r  r  r  r+   r,   r,   r-   r!    s4   

r!  c              
   C   s.  d}d}d}t |||}d| dddd}zfd|  }tj||d	}| }|d
 }	t|	}
|
|
d dk }
|
|
d dk }
tdt|
  t|
dkrYtd d}|W S t|
dkritd d}|W S t|
dkrytd d}|W S W d S  t	y } zt
d|  W Y d }~d S d }~ww )Nr   r	   r
   r   r   r   r   \https://scicdev.crm.dynamics.com/api/data/v9.1/trit_licenses?$filter=_trit_contact_value eq r   r   	statecoder   
statuscoder   zlength of license zonly one licensez
No licensez1leave the process there are more than one licenser   z3Error at function licenses_check and the error is: r   )r  r"   r#   r$   r%   r   trit_license_api_urlri   r4   rd   trit_licenselicenr+   r,   r,   r-   licenses_check  sF   




r(  c              
   C   s>  d}d}d}t |||}d| dddd}znd|  }tj||d	}| }|d
 }	t|	}
|
d d }|
d d }|
d d }|
d d }|
d d }|
d d }|
d d }|
d d }|
d d }|
d d }|d | }|
d d }|||||||||d	W S  ty } ztd|  W Y d }~d S d }~ww )Nr   r	   r
   r   r   r   r   r"  r   r   _trit_contact_valuer   r#  _trit_stateid_valuer$  trit_rlicensetrit_lineofauthorityr   r~   cr726_firstnameonlicensecr726_lastnameonlicenserV   trit_typeoflicense)	trit_license_trit_contact_valuetrit_license_statecoder   trit_license_statuscoder+  r   
license_idName_on_licenser/  z-Error at function licenses and the error is: r  )r  r"   r#   r$   r%   r   r%  ri   r4   rd   r&  r0  r1  r   r2  r+  r   r3  r4  fnln	full_nametrit_license_trit_typeoflicenser+   r,   r,   r-   licenses  sL   

r9  c              
   C   s   z1d}d}d}t |||}d| dddd}d|  }tj||d	}| }	|	d
 }
t|
}|W S  tyL } ztd|  W Y d }~d S d }~ww )Nr   r	   r
   r   r   r   r   ihttps://scicdev.crm.dynamics.com/api/data/v9.1/trit_courseassignments?$filter=trit_courseassignmentid eq r   r   z6Error at function course_assignment and the error is: r  )course_assignment_idr5   r"   r#   r$   r%   r   trit_courseassignment_api_urlri   r4   rd   trit_courseassignmentr+   r,   r,   r-   course_assignment/  s(   

r>  c                 C   s   d}d}d}t |||}d| dddd}z&d|  }tj||d	}| }|d
 }	t|	}
|
d |
d |
d dW S    td|  d Y d S )Nr   r	   r
   r   r   r   r   jhttps://scicdev.crm.dynamics.com/api/data/v9.1/trit_pollquestions?$filter=_trit_courseassignment_value eq r   r   r~   r   r   r~   r   r   zThis Evenregistration z  doesn't contains poll questions)r   r   r   r   r   r   r   r   )r;  r"   r#   r$   r%   r   trit_pollquestions_api_urlri   r4   rd   trit_pollquestionsr,   r,   r-   r  Q  s$   

r  c                 C   sD  d}d}d}zbt |||}d| dddd}d|  d	}zdtj||d
}|  | dg }	|	s=td W W dS |	d d}
td|
  d| d	}tj||d
}|  | dg }|sptd W W dS t|}|
|d< td|  W n tj	y } zt
d|  W Y d}~nd}~ww | D ]\}}z|d }|rtd|  tj|d}td|  nd}|d }|d }|dkrd|v r|jdk s|dkrd|v s|dkrd|v s|d krd|v s|d!krd|v s|d!krd"|v rd#|j|d$f< td%| d& nd|j|d$f< td%| d' W q tyV } zt
d(| d)| d*|  d|j|d$f< W Y d}~qd}~ww |d$  }td+|  |dkW S  tj	y } zt
d|  W Y d}~dS d}~w ty } zt
d,|  W Y d}~dS d}~ww )-a!  
    Validates the designation logic based on state, designation, and contact data.

    :param state_id: The state code as a string.
    :param contact_data: The contact identifier to filter designation awards.
    :return: True if the validation conditions are met, False otherwise.
    r   r	   r
   r   r   r   r   zThttps://scicdev.crm.dynamics.com/api/data/v9.1/trit_states?$filter=trit_stateid eq 'r   r   r   z.No state data found for the provided state_id.Fr   r~   zState name retrieved: zfhttps://scicdev.crm.dynamics.com/api/data/v9.1/trit_designationawards?$filter=_trit_contact_value eq 'z1No designation awards found for the contact data.r   zinfo of designation df: zAPI request failed: Ntrit_awarddatezawarded date z%Y-%m-%d_trit_designation_valueALz$c75f2772-389c-e911-a819-000d3a1ca508i  NJz$89a1dfa4-cd65-ef11-bfe2-000d3a99f7aaNVUTz$cb5f2772-389c-e911-a819-000d3a1ca508TLGSzRow z: Validated as True (LGS).z: Validated as False (LGS).zError processing row rT   z for contact zTotal valid LGS entries: zUnexpected error: )r   r   r   raise_for_statusr   r   r   r   r   RequestExceptionr    r   rG   strptimeyearatr   sum)rp   contact_datar"   r#   r$   tokensr   state_api_urlstate_response
state_data
state_namedesignation_award_api_urlri   designation_datadesignation_dfr+   idxr   award_date_str
award_datedesignationrow_state_name	row_errorgroup_designation	api_errorgeneral_errorr,   r,   r-   validate_lgss  s   	



rb  c              
   C   s   i }d}d}d}t |||}zJ|  D ]B\}}|d }d| }	d| dddd	}
tj|	|
d
}|jdkrI| }|dg }t|}|||< qt	d| d|j  q|W S  t
yt } ztd|  i W  Y d}~S d}~ww )a  
    Fetch poll questions for each course assignment and return a dictionary of DataFrames.

    Parameters:
        trit_courseassignment (DataFrame): DataFrame containing course assignments.
        client_id (str): Client ID for authentication.
        client_secret (str): Client Secret for authentication.
        tenant_id (str): Tenant ID for authentication.

    Returns:
        dict: A dictionary where keys are `ca_id` and values are DataFrames containing poll questions.
    r   r	   r
   trit_courseassignmentidr?  r   r   r   r   r   r=   r   z Failed to fetch data for ca_id: z. Status Code: zError in fetch_poll_questions: N)r   r   r   r   rZ   r   r   r   r   r   r   r    )r=  
dataframesr"   r#   r$   r%   r   r   ca_idrA  r   ri   r4   rd   r)   r+   r,   r,   r-   fetch_poll_questions  s6   



rf  c              
   C   s   d|  }d}d}d}t |||}d| dddd}ztj||d	}| }|d
 }	t|	}
|
W S  tyO } ztd|  t W  Y d}~S d}~ww )ze
    This is used to retrieve all course assignments records based on event registration ID
    
    zqhttps://scicdev.crm.dynamics.com/api/data/v9.1/trit_courseassignments?$filter=_trit_eventregistrationid_value eq r   r	   r
   r   r   r   r   r   r   9Error at function course_assignment_df and the error is: Nr  )event_reg_idr<  r"   r#   r$   r%   r   ri   r4   rd   r=  r+   r,   r,   r-   course_assignment_df  s*   

ri  c              
   C   s  zi }|   D ]\}}d}d}d}t|||}d| dddd}d| }	tj|	|d	}
|
 }|d
g }t|}|dtjtd}g g g d}t	|tjr|
 D ]N\}}|d |d  |d |d  |d |d  |js|D ])}|r|ddd }d|d }|d | |d d |d | qyqU|||< q|W S  ty } ztd|  t W  Y d}~S d}~ww )a  
    Process course assignments and generate a structured dictionary.

    Args:
        test_fpq (dict): A dictionary where keys are `ca_id` and values are DataFrames.
        client_id (str): Client ID for API authentication.
        client_secret (str): Client Secret for API authentication.
        tenant_id (str): Tenant ID for API authentication.

    Returns:
        dict: Processed data for all course assignments.
    r   r	   r
   r   r   r   r   r:  r   r   trit_admincomment)dtyper@  r~   r   r   r   Nr   z
: questionTrg  )r   r   r   r   r   r   r   Seriesobject
isinstancer   r1   r   r   r   r   r   r    )test_fpqresult_datare  r)   r"   r#   r$   r%   r   r<  ri   r4   rd   $comments_retrieval_course_assignmentrj  pqr   r   r   r  joined_datar+   r,   r,   r-   process_course_assignments7  sX   

rt  c           1      C   s  d}z\t d|   d}d}t| }t d|  t|}t|}g }| D ]1\}}t d|  t| }	|	d }
|	d }t|}|d }|d	 }t|
}|	d
}|	d}|	d}|	d}|	d}t
||||||}t||
}t d|  t|
}t|| }|d d }t d|  d}|du
rt d |}t d| d |d }t d|  t|}t d|  z^t|}|	d}t d|  |	d}t d|  |	d}t d|  |	d}t d|  |	d
}|	d} |	d}t d |  t||}t d|  W n  tyF }! zt d! t d"|!  W Y d}!~!nd}!~!ww |d#k
rt d$ t d% t| }	|	d }t|}zKzC|d& d'krtt d( d)}"n2|d& d*krt d+ d,}"n#|d& d-krt d. d/}"n|d& d0krt d1 d2}"nt d3 W n ty }! zt d4 t d5|!   d}!~!ww zC|	d6 d7vrt d8 d}#n2|	d6 d'krt d9 d:}#n#|	d6 d*krt d; d<}#n|	d6 d-kr t d= d>}#nt d? W n ty! }! zt d@ t dA|!   d}!~!ww za|d d*kr2t dB dC}$nP|d d'krAt dD dE}$nA|d d-krPt dF dG}$n2|d dHkr_t dI dJ}$n#|d dKkrnt dL dM}$n|d dNkr}t dO dP}$nt dQ W n ty }! zt dR t dS|!   d}!~!ww |"|#|$dT}%t dU|%  W n  ty }! zt dV t dW|!  W Y d}!~!nd}!~!ww |d }t dX|  |	d6 }&t dY|&  |d& }'t dZ|  t d[|   z| |||||||%|||d#d\}(t d]|(  W n  ty4 }! zt d^ t d_|!  W Y d}!~!nd}!~!ww |d#k
rt d` |d& d'k
r|	d6 dav
r|d*k
rt db|  dc|  |d }zt|}|d }|d }t |  W n  ty }! zt dd t de|!  W Y d}!~!nd}!~!ww |df dk
rt db|  dg |d du
ryt db|  dh zt||}t d|  W n  ty }! zt di t dj|!  W Y d}!~!nd}!~!ww |dk
rjt dk|  dl h dm})g dn}*d}t|| }|d	 }t do|  |dpkr|dqkrt dr t ds|  t||d }t dt|  ||(|df ||||du}|| |	d}t
|||||| }|d| D ]s}+t dv z
t |+	dw W n	   t dx Y |+}t | dy|  dzd{| dz| d||
 dzd}| dzd~| dzd| dzd#d},z	t|, d}W qZ ty }! zt d|,  t d|!  W Y d}!~!qZd}!~!ww ||| f  W S |dv r|dkrt d t d|  t||d }t dt|  d}||(|df ||||du}|| |	d}t
|||||| }|d| D ]q}+t dv z
t |+	dw W n	   t dx Y |+}t | dy|  dzd{| dz| d||
 dzd}| dzd~| dzd| dzd#d},zt|, W q# ty }! zt d|,  t d|!  W Y d}!~!q#d}!~!ww ||| f  W S |dv r_|dkr_t d t d|  t||d }t dt|  d}||(|df ||||du}|| |	d}t
|||||| }|d| D ]l}+t dv z
t |+	dw W n	   t dx Y |+}dy|  dzd{| dz| d||
 dzd}| dzd~| dzd| dzd#d},zt|, W q tyV }! zt d|,  t d|!  W Y d}!~!qd}!~!ww ||| f  W S |dv r!|dkr!t d t d|  t||d }t dt|  d}||(|df ||||du}|| |	d}t
|||||| }|d| D ]l}+t dv z
t |+	dw W n	   t dx Y |+}dy|  dzd{| dz| d||
 dzd}| dzd~| dzd| dzd#d},zt|, W q ty }! zt d|,  t d|!  W Y d}!~!qd}!~!ww ||| f  W S ||*vs+||)v r|dkrt d|  t||d }t dt|  d}||(|df ||||du}|| |	d}t
|||||| }t dt|  t dt|  t d|  |d| D ]}+t dv z|+}t d|  W n ty }! zt d|!  W Y d}!~!nd}!~!ww |+}dy|  dzd{| dz| d||
 dzd}| dzd~| dzd| dzd#d},t |, zt|, W q ty }! zt d|,  t d|!  W Y d}!~!qd}!~!ww ||f  W S ||)v 	rddddddd}-|d }.|-	|.}/|/	r||/krSt d|/ d|. d t||d }t d|  d}||(|df ||||du}|| |	d}t
|||||| }|d| D ]u}+t dv zt |+ W n	   t dx Y |+}dy|  dzd{| dz| d||
 dzd}| dzd~| dzd| dzd#d},t |, zt|, W n# ty }! zt d|,  t d|!  W Y d}!~!nd}!~!ww ||f    W S t d|/ d|. d t | nT|	s|	rt| t d t||d }t dt|  d}|	dd'k	r:t d |	d}t|||}0nK|	dd*k	rSt d |	d}t|||}0n2|	dd-k	r~t d z|	d}t|||}0W n   |	d}t|||}0Y nt d d}0||(|df ||||du}||| f  W S t d t | n||*v	s||)v 
rd|dk 
rdt d t||d }t d|  |	d}t
|||||| }t d|  |d| D ]y}+zt |+ W n	   t dx Y |+}t d dy|  dzd{| dz| d||
 dzd}| dzd~| dzd| dzdHd#d	},t |, zt|, t d W n# t
yV }! zt d|,  t d|!  W Y d}!~!nd}!~!ww t | 	qt | nt d n|dk
rxt d|  d nt d t | nt d t | nt d t | nt d t | n|d#k
rt d t | n|dk
rt d nt d t||d }|	d}t
||||||}|}t d|  |d| D ]j}+zt |+ W n	   t dx Y |+}dy|  dzd{| dz| d||
 dzd}| dzd~| dzd| dzdHd#d	},zt|, W n# tyM }! zt d|,  t d|!  W Y d}!~!nd}!~!ww t | 
q||| f  W S W dS  tyx }! zt |! W Y d}!~!dS d}!~!ww )z
    SS type - 314310000

    Not a SS type - 314310001

    Delivery Mechanism - 314310001 - Webinar

    Trit ce declination other than "314310000 - Credit Already Satisfied","314310001 - GrandFathered","Not Licensed - 314310002"s
    Nz%entered cerequest_check function for z&No info acquired due to condition failzcourse assign - z Processing DataFrame for ca_id: r  r/   r  r   r3  r4  r   r/  r   zLGS Validated - trit_percentattendedr   zpercentage_attendance_check - Fz%came into percentage_attendance_checkzBIn courseassignment attendance percentage value present and it is rV   r  zcontactID - zlicense check zLicense type - r+  zResident License zState id - zline of authority - r   zType of License - z=This is where we retrieve License details  - comment to checkzXException raised in cerequest_check function, while trying to get the license details - r   z!Satisfied lic_check = 1 conditionzone Licenser  r   zThe sales channel is SS typezSS or 314310000r   z%The sales channel is High School typezHigh School or 314310001r   zThe sales channel is LS typezLS or 314310002iyzThe sales channel is UNIV typezUNIV or 314310009z]The Sales channel is is None or other than these 314310000, 314310001, 314310002 or 314310009z3Condition where we check ss type - comment to checkzException in checking ss type r  )	314310000	314310001	314310002zce declination is nonez+ce declination is Credits Already SatisfiedzCredits Already Satisfiedzce declination is GrandfatheredGrandfatheredzce declination is Not LicensedzNot Licensedz^The CE declination reason is not None neither they are these 314310000, 314310001 or 314310002z:Condition where we check ce declination - comment to checkzException in ce declination - zDelivery Mechanism is webinarWebinarzDelivery Mechanism is Classroom	Classroomz Delivery Mechanism is Self-Pacedz
Self-Pacedr   zDelivery Mechanism is BlendedBlendeditzDelivery Mechanism is Corp-WBzCorp-WBiuz Delivery Mechanism is Corp-Classz
Corp-ClasszpThe Delivery Mechanism is not in any of these 314310000, 314310001, 314310002, 314310003, 314310004 or 314310005z>Condition where we check delivery mechanism - comment to checkz"Exception in delivery mechanism - )zSales ChannelzCE Declination reasonzDelivery MechanismzHReturning Sales Channel, CE Declination reason and Delivery Mechanism - zZCondition where we check ss type, ce declination and delivery mechanism - comment to checkzGException in checking ss type, ce declination and delivery mechanism - zDelivery Mechanisms - zce declination reason zEvent ID - zEvent Registration id - )zEvent Registration idzEvent IDz
Contact IDz
License IDz Name on LicensezType Of LicensezState ID in LicenseSc_CE_dec_del_mechzValidated LGSzLine Of AuthorityzResident LicensezActive LicensezPDictionary of values Details_before_entering_condition_trit_rlicense_equal_to_1 zMDetails_before_entering_condition_trit_rlicense_equal_to_1 - comment to checkzHException in Details_before_entering_condition_trit_rlicense_equal_to_1 zit is a resident licenser   zThis z\ satisfied trit_type as SS & trit_cedeclinationreason is None and delivery method Webinar - zETry to get the license information for the contact - comment to checkzBException in Try to get the license information for the contact - r1  z have only one licensez have stateid valuezZLGS Validation inside - Check if the license has a valid state id value - comment to checkzWException in LGS Validation inside - Check if the license has a valid state id value - z This z#'s State comes under Non-LGS states>   $33805427-a600-ea11-a826-000d3a1ca610$861d0c2a-a600-ea11-a825-000d3a1cadb6$881d0c2a-a600-ea11-a825-000d3a1cadb6$9544192b-a600-ea11-a827-000d3a1cac04)$8b44192b-a600-ea11-a827-000d3a1cac04$d21d0c2a-a600-ea11-a825-000d3a1cadb6$cb1d0c2a-a600-ea11-a825-000d3a1cadb6$c91d0c2a-a600-ea11-a825-000d3a1cadb6$ab1d0c2a-a600-ea11-a825-000d3a1cadb6$7c1d0c2a-a600-ea11-a825-000d3a1cadb6$40805427-a600-ea11-a826-000d3a1ca610$3c805427-a600-ea11-a826-000d3a1ca610zprod - r  F   zPR state 70%z3# Check for AO&AM products - based on percentage 1 zno of ce requests )Course_Assignment_IDzLicensee detailsz7Licensee have active license or not(0 - Active License)
Product_ID
Percentagece_request_createdzNo of CE Requestzce creationr   zno approv id exceptionz/msevtmgt_eventregistrations()z/msevtmgt_events(z
/contacts(z
/products(z/trit_licenses(z/trit_instructorapprovals()#trit_EventRegistrationId@odata.bindtrit_msevtmgt_Event@odata.bindr~   trit_ParticipantId@odata.bindtrit_ProductId@odata.bind$trit_ParticipantLicenseId@odata.bindcr726_StateApproval@odata.bindr$  TzFailed to submit record: zError: >   r  r  U   zHI or VA State & >= 85%z3# Check for AO&AM products - based on percentage 2 >   r  r  Z   zTX, ND >= 90%z3# Check for AO&AM products - based on percentage 3 >   r  r  r  d   zMD, MI, MN state and = 100 %z3# Check for AO&AM products - based on percentage 4 P   z3# Check for AO&AM products - based on percentage 5 ztype of state_approval_id - zLength of state_approval_id: zstate approval list - zExtracted state approval ID: zno approv id exception - b   _   \   Y   S   C   )         r   r   r   +trit_courseassignment_trit_instructionhoursz$# Attendance meets the threshold of z% for z hours.zNumber of CE requests: z(# Attendance does NOT meet the required z6# Created cerequest based on polls for specified stater   r   r   r   zVCe request declined with both attendance percentage and poll count conditions failing zinto 6z	into 6 - zinto the loop)	r  r  r~   r  r  r  r  r$  r#  zpassed the else statementz;Ce request declined due to attendance percentage in Non-LGSzThis Event Registration ID - z7 comes under LGS state, So no CE Request can be createdz1failed at trit_license_trit_residentstate is nonezAtrit_license_statecode either have no license or multiple licensezfIt failed trit_type == 314310000 or trit_cedeclinationreason is None or delivery method is not webinarzit is a non-resident licensez7More than one license so CE requests can not be createdz
No LicensezcAttendance percentage is none so no CE request can be created escaped in the first condition itselfz	into 7 - )r   r   ri  rf  rt  r   r  r  r9  r   r   rb  r!  r>  r(  r   r    r   r1   r{   typer   r	  r   r   )1r  r   info_after_percentage_checkca_dffpqpcaoverall_ce_request_event_reg_idre  r)   r;   r  r/   evr   r   licr3  license_namer   r   r   state_approval_idval_LGScontcapercentage_attendance_checkr  percentage_checkr  	lic_checktrit_license_trit_licensetyper+  r   r+   sales_channel_typece_decliDel_Mechr}  dmt_type:Details_before_entering_condition_trit_rlicense_equal_to_1specified_states
State_Codesalrx   attendance_thresholdsinstruction_hoursrequired_percentageLOAr,   r,   r-   cerequest_check  s  












































&































































	















































            >r  c              
   C   s   zIt | }|d u rtd| d|   |W S |d dkr+td| d|   |W S |d dkr?td| d|   |W S td|   |W S  tyj } ztd	|  td	| W  Y d }~S d }~ww )
Nzcerequest_check returned None: z for eventregistration_id: r   Tzcerequest_check returned True: Fz cerequest_check returned False: z8Cannot create CE request for this event registration ID zError in ce_request_last_check )r  r   r   r   r    r   )r  cer+   r,   r,   r-   ce_request_last_check  s$   r  POSTc              
   C   s   z| j dkr| jd}t|}t| td|iW S W d S  ty? } zt| tdt|iddW  Y d }~S d }~ww )Nr  eventreg_idri   r    rU   rR   )	rX   rd   r   r  r   r   r   r   str)r[   r  r  r+   r,   r,   r-   index_ce_request  s   


 r  c                 C   s  z| j dkr| jd}t|}td|  g }g }g }|D ]}}td|  td|  zDt|}|du rPtd|  t|}|||d n%|du rbtd	|  || ntd
|  td| d|  W q  t	y }	 zt
d| d|	  ||t|	d W Y d }	~	q d }	~	ww |||d}
td|iW S W d S  t	y }	 zt|	 td|	  tdt|	iddW  Y d }	~	S d }	~	ww )Nr  r2   z*event registration id list index function zEvent Registration ID: Fzevent registration ids false: )id
last_checkTzevent registration ids true: zevent registration ids else: z2This Event Registration ID has unexpected result: z - zError in event registration id rT   )r  r    )zevent reg idszeligible to check ce listalready_exists_listinvalid_ce_listzerror at index exception r    rU   rR   )rX   rd   r   r<   r   r   r.   r  r1   r   r    r  r   )r[   r2   event_reg_idsr  r  	valid_idsersis_validr  r+   r  r,   r,   r-   r   	  sP   
 $
 r   )=asyncior   rest_framework.decoratorsr   django.httpr   ossysr   rG   inspectr   rB   pandasr   collectionsr   requests.authr   pathr1   r   dirname__file__LogUtilsgetRootLoggerr   r   r.   r<   rP   r_   rf   r"   r#   r$   r   rs   r{   r   r   r   r   r   r   r	  r  r  r!  r(  r9  r>  r  rb  rf  ri  rt  r  r  r  r   r,   r,   r,   r-   <module>   sv    
'/2
=(C1/}<PJ+.'17""i6%M      e
