o
    %si                    @   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	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%edg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:dDdE Z;dFdG Z<dHdI Z=edJgdKdL Z>edJgdMdN Z?dS )O    )log)api_view)JsonResponseN)timezone)defaultdict)HTTPBasicAuthz"Starting the PPP Automation scripthttps://scic.crm.dynamics.com$6e5989aa-4fd1-4015-8648-8f75609d607b(tH58Q~s1P3BPDSOJihcaCLeMxdkU-UkjKyag6aSh$95f69e7d-1811-4ab9-9b5a-eba95d3eba9bc                 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_type	client_idclient_secretresource)data   zToken retrieved successfullyaccess_tokenzFailed to retrieve token: )base_urlrequestspoststatus_codeloggerinfojsongeterrortext	Exception)r   r   	tenant_id	token_urlpayloadresponse r#   -/var/www/html/PPP_Automation/ppp_app/views.py	get_token   s   

r%   c              
   C   s  d}d}d}d}z`t |||}d|  d}d| dd	d	d
}tj||d}| d}	|	d d}
|	d d}d| |dd	d	d}ddd}| d|
 d}tj|||d}td|j d|   |jW S  ty } ztd| d|   W Y d }~d S d }~ww )Nr	   r
   r   r   hhttps://scic.crm.dynamics.com/api/data/v9.1/trit_cerequests?$filter=_trit_eventregistrationid_value eq ''Bearer odata.maxpagesize=50004.0AuthorizationPreferOData-MaxVersionOData-Versionheadersvaluer   trit_cerequestidz@odata.etagapplication/json)r,   zIf-MatchContent-Typer.   r/      s)	statecode
statuscodez/api/data/v9.1/trit_cerequests()r1   r   z!Status code at update_no_request  for z:Error at update_no_request retrieving odata and record_id )	r%   r   r   r   patchr   r   r   r   )eventregistrationidr   r   r   r   tokentrit_cerequests_api_urlr1   	event_reqdt	record_idetagupdate_headersupdate_data
update_urlupdate_responseer#   r#   r$   update_no_request3   sB   	$rJ   c              
   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 )Nr	   r
   r   r(   r)   r*   r+   r&   r'   r0   r2   z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: r%   r   r   r   pd	DataFramer   r   lenr   r   )r>   r   r   r   r?   r1   r@   rA   rB   df
CE_REQ_ValrI   r#   r#   r$   ce_request_validation_apii   s6   
rQ   c              
   C   s   d}d}d}d}t |||}d| dddd}z"d	|  }tj||d
}| }	|	d }
t|
}|d }|d W S  tyT } ztd|  W Y d }~d S d }~ww )Nr	   r
   r   r   r(   r)   r*   r+   nhttps://scic.crm.dynamics.com/api/data/v9.1/trit_courseassignments?$filter=_trit_eventregistrationid_value eq r0   r2   r9   r   z8Error at courseassignment_statuscode and the error is - )	r%   r   r   r   rL   rM   r   r   r   )r>   r   r   r   r   r?   r1   trit_courseassignment_api_urlr"   resr   courseassigment_dfr   rI   r#   r#   r$   courseassignment_statuscode   s,   


rV   c              
   C   s   d}d}d}t |||}d| dddd}z^d|  d	}tj||d
}| }|dg }	|	s:td|   g W S |dd d}
d|
 d	}tj||d
}| }|d}g }|D ]
}||d q^td|  |W S  ty } ztd|  g W  Y d }~S d }~ww )Nr	   r
   r   r(   r)   r*   r+   zWhttps://scic.crm.dynamics.com/api/data/v9.1/msevtmgt_events?$filter=trit_eventcode eq 'r'   r0   r2   zNo event found for eventcode: r   msevtmgt_eventidzlhttps://scic.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   r   r   appendr   r   )	eventcoder   r   r   r?   r1   event_api_urlrA   rT   
event_dataevent_id"msevtmgt_eventregistration_api_urlmsevtmgt_eventregistration_reqmsevtmgt_eventregistration_resres1er_listerrI   r#   r#   r$   event_name_uuid   s@   
rd   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 = ?
            r   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connrk   rI   recordutc_nowr#   r#   r$   check_eventcode_exist   sV   
rw   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 )Nrx   z#Received GET request at validateapirZ   zThe Event code is:   z#Missing ?eventcode= in query stringre   statusz0https://corporateallibot.scic.com/PPP-Automationr5   r4   )r   r1   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)rf   rg   zResponse for Eventcode  F)safez(Error at validate api and the error is: zInternal server error)methodr   r   rx   r   r   r   r   r   r   r   rw   )requestrZ   urlr!   r1   post_responserI   rT   r#   r#   r$   validateapi  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: )paramsr"   z'Error fetching instructor approval ID: N)r   r   r   r   r   r   r   )
product_idstate_iddelivery_methodlicense_typer   r   r"   rI   r#   r#   r$   fetch_instructor_approval_idW  s   r   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   r{   zDFailed to get token at function ce_request_odata and the error is - Nr(   r)   r*   r+   z/api/data/v9.2/trit_cerequestsnullr;   )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   r   r   r   r   r   r   )
new_recordr   r   r   r   r?   rI   r1   ce_request_api_urlResponser"   r#   r#   r$   ce_request_odata  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+   bhttps://scic.crm.dynamics.com/api/data/v9.1/trit_instructorapprovals?$filter=_trit_state_value eq r0   r2   _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   rL   rM   iterrowsendswithrY   r   r   r   r   r   r   r   r   r   r?   r1   state_approval_api_urlstate_approval_reqrT   r   state_approval_tablestate_approvalstateapproval_id_lists_rowsr   state_approvaliddicts_of_state_approvestateapproval_idrI   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   r0   r2   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_statefilingidr0   r2   zMError at get_state_approval_guid function while fetching state filing data1: trit_statefilingidzState filing data for product z, state z, delivery mechanism r|   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   rY   r   )productstatedelivery_mechanismr   r   r   r   r?   r1   r   statefiling_api_urlstate_filing_reqstate_filing_jsonrI   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r]t d |dv rSg }|dkr%ddg}n|dkr.ddg}n|dkr7ddg}ndd gr?ddg}|D ]}	t| |||	}|rQ|  W S qAn^t d d	}|W S |d u se|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nanNr   r   r   r   z7lic LOH is not None but does not match any known valuesNullr7   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   )r   trit_license_trit_stateid_valuer   type_of_license!trit_license_trit_lineofauthoritytrit_licenseidr   lic_LOHlicense_priorityr   rI   r#   r#   r$   r     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: r6   r   -      zSkipping invalid format: zError processing r|   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rsplitrN   joinr   addr   itemsrangerY   rL   rM   columns)r   polls_by_product_hourr   rowr   product_hour_partpartsproduct_hourpoll_numr   hourrI   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+   zJhttps://scic.crm.dynamics.com/api/data/v9.1/products?$filter=productid eq z&$select=namer0   r2   zao am states product table - namer   zAO,AM&CC - r6   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 - )rL   
read_excelr%   r   r   r   rM   r   r   r   r   )trit_productr   aoamccr   r   r   r?   r1   product_api_urlr"   rT   r   r   AO_AM_CCno_of_cerequestindexr   r   rI   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)rL   rM   groupbyr   r   r  values)	
pquestionsr   grouped_dataresultscourse_valuegroupvalid_groupresult	result_ynr#   r#   r$   process_pquestionsu  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+   zphttps://scic.crm.dynamics.com/api/data/v9.1/msevtmgt_eventregistrations?$filter=msevtmgt_eventregistrationid eq r0   r2   _msevtmgt_eventid_valuer   trit_cedeclinationreason_msevtmgt_contactid_valuetrit_lgsstatetrit_lgsrequestrX   )rW   r$  msevtmgt_contactid_valuer&  r'  rX   z5Error at function evenregistration and the error is: 	r%   r   r   r   rL   rM   r   r   r   )eventregistration_idr   r   r   r?   r1   r^   r"   rT   r   msevtmgt_eventregistrationrW   r$  r(  r&  r'  rX   rI   r#   r#   r$   evenregistration  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+   zXhttps://scic.crm.dynamics.com/api/data/v9.1/msevtmgt_events?$filter=msevtmgt_eventid eq r0   r2   	trit_typer   r   trit_deliverymechanismsrW   )r-  r  r.  rW   z3Error at function msevtmgt_event and the error is: r)  )rW   r   r   r   r?   r1   msevtmgt_event_api_urlr"   rT   r   msevtmgt_eventr-  r  r.  rI   r#   r#   r$   r0    s4   

r0  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+   zJhttps://scic.crm.dynamics.com/api/data/v9.1/contacts?$filter=contactid eq r0   r2   	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?   r1   contacts_api_urlr"   rT   r   contactsr5  r6  r7  r8  rI   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+   zYhttps://scic.crm.dynamics.com/api/data/v9.1/trit_licenses?$filter=_trit_contact_value eq r0   r2   r8   r   r9   r6   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: rK   )r5  r   r   r   r?   r1   trit_license_api_urlr"   rT   r   trit_licenselicenrI   r#   r#   r$   licenses_check  sF   




r>  c              
   C   s  d}d}d}t |||}d| dddd}zd|  }tj||d	}| }|d
 }	t|	}
|
jr=td|   W d S d|
j	vrXtd|   td|
j	
   W d S |
|
d dk }
|
jrntd|   W d S |
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+   zUhttps://.crm.dynamics.com/api/data/v9.1/trit_licenses?$filter=_trit_contact_value eq r0   r2   z"No license data found for contact r9   z:'statuscode' column not found in license data for contact zAvailable columns: r6   z4No active licenses (statuscode=1) found for contact _trit_contact_valuer   r8   _trit_stateid_valuetrit_rlicensetrit_lineofauthorityr   r   cr726_firstnameonlicensecr726_lastnameonlicenser~   trit_typeoflicense)	trit_license_trit_contact_valuetrit_license_statecoder   trit_license_statuscoderA  r   
license_idName_on_licenserE  z-Error at function licenses and the error is: )r%   r   r   r   rL   rM   r   r   r   r   tolistr   )r5  r   r   r   r?   r1   r;  r"   rT   r   r<  rF  rG  r   rH  rA  r   rI  rJ  fnln	full_nametrit_license_trit_typeoflicenserI   r#   r#   r$   licenses>  sd   


rP  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+   fhttps://scic.crm.dynamics.com/api/data/v9.1/trit_courseassignments?$filter=trit_courseassignmentid eq r0   r2   z6Error at function course_assignment and the error is: r)  )course_assignment_idr]   r   r   r   r?   r1   rS   r"   rT   r   trit_courseassignmentrI   r#   r#   r$   course_assignment  s(   

rT  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+   ghttps://scic.crm.dynamics.com/api/data/v9.1/trit_pollquestions?$filter=_trit_courseassignment_value eq r0   r2   r   r   r  r   r   r  zThis Evenregistration z  doesn't contains poll questions)r%   r   r   r   rL   rM   r   r   )rR  r   r   r   r?   r1   trit_pollquestions_api_urlr"   rT   r   trit_pollquestionsr#   r#   r$   r    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+   zQhttps://scic.crm.dynamics.com/api/data/v9.1/trit_states?$filter=trit_stateid eq 'r'   r0   r2   z.No state data found for the provided state_id.Fr   r   zState name retrieved: zchttps://scic.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 r|   z for contact zTotal valid LGS entries: zUnexpected error: )r%   r   r   raise_for_statusr   r   r   rL   rM   RequestExceptionr   r   rn   strptimeyearatr   sum)r   contact_datar   r   r   tokensr1   state_api_urlstate_response
state_data
state_namedesignation_award_api_urlr"   designation_datadesignation_dfrI   idxr   award_date_str
award_datedesignationrow_state_name	row_errorgroup_designation	api_errorgeneral_errorr#   r#   r$   validate_lgs  s   	



rx  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_courseassignmentidrU  r(   r)   r*   r+   r0   r   r2   z Failed to fetch data for ca_id: z. Status Code: zError in fetch_poll_questions: N)r%   r   r   r   r   r   rL   rM   r   r   r   r   )rS  
dataframesr   r   r   r?   r  r   ca_idrW  r1   r"   rT   r   rO   rI   r#   r#   r$   fetch_poll_questionsh  s6   



r|  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
    
    rR   r	   r
   r   r(   r)   r*   r+   r0   r2   9Error at function course_assignment_df and the error is: Nr)  )event_reg_idrS   r   r   r   r?   r1   r"   rT   r   rS  rI   r#   r#   r$   course_assignment_df  s*   

r  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+   rQ  r0   r2   trit_admincomment)dtyperV  r   r   r  r   Nr   z
: questionTr}  )r   r%   r   r   r   rL   rM   Seriesobject
isinstancer   rY   r   r   r   r   r   r   )test_fpqresult_datar{  rO   r   r   r   r?   r1   rS   r"   rT   r   $comments_retrieval_course_assignmentr  pqr   r   r   r   joined_datarI   r#   r#   r$   process_course_assignments  sX   

r  c           .      C   sX  d}zt d|   d}d}t| }t d|  t|}t|}g }| D ]\}}t d|  t| }	|	d }
|	d }t|}|d }|d	 }t|
}|du rjt 	d
|
 d|   dd| f  W S |
d}t | |
d}|
d}|
d}|
d}|
d}t||||||}t||
}t d|  t|
}t|| }|d d }t d|  d}|dur|dk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yl }! 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rt d* d+}"n2|d( d,krt d- d.}"n#|d( d/krt d0 d1}"n|d( d2krt d3 d4}"nt d5 W n ty }! zt d6 t d7|!   d}!~!ww zC|	d8 d9vrt d: d}#n2|	d8 d)krt d; d<}#n#|	d8 d,krt d= d>}#n|	d8 d/kr&t d? d@}#nt dA W n tyG }! zt dB t dC|!   d}!~!ww za|d d,krXt dD dE}$nP|d d)krgt dF dG}$nA|d d/krvt dH dI}$n2|d dJkrt dK dL}$n#|d dMkrt dN dO}$n|d dPkrt dQ dR}$nt dS W n ty }! zt dT t dU|!   d}!~!ww |"|#|$dV}%t dW|%  W n  ty }! zt dX t dY|!  W Y d}!~!nd}!~!ww |d }t dZ|  |	d8 }&t d[|&  |d( }'t d\|  t d]|   z| |||||||%|||d%d^}(t d_|(  W n  tyZ }! zt d` t da|!  W Y d}!~!nd}!~!ww |d%krt db |d( d)kr|	d8 dcvr|d,krt dd|  de|  |d }zt|}|d }|d }t |  W n  ty }! zt df t dg|!  W Y d}!~!nd}!~!ww |dh dkrt dd|  di |d durt dd|  dj zt||}t d|  W n  ty }! zt dk t dl|!  W Y d}!~!nd}!~!ww |dkrt dm|  dn h do})g dp}*d}t|| }|d	 }t dq|  |drkrF|dskrFt dt n|duv rW|dvkrWt dw n|dxv rh|dykrht dz n|d{v ry|d|kryt d} n||*vs||)v r|d~krt d nv||)v rddddddd}+|d },|+
|,}-|-r||-krt d|- d|, d nI|s|r|
dd)krt d n4|
dd,krt d n%|
dd/krt d nt d n||*vs ||)v rJ|d~k rJt d zt|  t dt d|   W n% ty@ }! zt d|  d t d|! d W Y d}!~!nd}!~!ww t d|   nt d zt|  W n% tyz }! zt d|  d t d|! d W Y d}!~!nd}!~!ww t d|   n|dkrt d|  d nrt d nlt d nft d n`t d nZ|d%krt d nO|dkrt d nDt d zt|  t dt d|   W n% ty }! zt d|  d t d|! d W Y d}!~!nd}!~!ww t d|   || f  W S W dS  ty+ }! zt d|! d W Y d}!~!dS d}!~!ww )
    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 No_cerequest_check function for &No info acquired due to condition failcourse assign -  Processing DataFrame for ca_id: r(  rW   r.  r  'Failed to get license info for contact , skipping event registration FrI  rJ  r   rE  r   LGS Validated - trit_percentattendedr   percentage_attendance_check - %came into percentage_attendance_checkBIn courseassignment attendance percentage value present and it is r~   r5  contactID - license check License type - rA  Resident License State id - line of authority - r   Type of License - =This is where we retrieve License details  - comment to checkXException raised in cerequest_check function, while trying to get the license details - r6   !Satisfied lic_check = 1 conditionone Licenser-  r   The sales channel is SS typeSS or 314310000r   %The sales channel is High School typeHigh School or 314310001r   The sales channel is LS typeLS or 314310002yThe sales channel is UNIV typeUNIV or 314310009]The Sales channel is is None or other than these 314310000, 314310001, 314310002 or 3143100093Condition where we check ss type - comment to checkException in checking ss type r$  	314310000	314310001	314310002ce declination is none+ce declination is Credits Already SatisfiedCredits Already Satisfiedce declination is GrandfatheredGrandfatheredce declination is Not LicensedNot Licensed^The CE declination reason is not None neither they are these 314310000, 314310001 or 314310002:Condition where we check ce declination - comment to checkException in ce declination - Delivery Mechanism is webinarWebinarDelivery Mechanism is Classroom	Classroom Delivery Mechanism is Self-Paced
Self-Pacedr7   Delivery Mechanism is BlendedBlendedtDelivery Mechanism is Corp-WBCorp-WBu Delivery Mechanism is Corp-Class
Corp-ClasspThe Delivery Mechanism is not in any of these 314310000, 314310001, 314310002, 314310003, 314310004 or 314310005>Condition where we check delivery mechanism - comment to check"Exception in delivery mechanism - zSales ChannelzCE Declination reasonzDelivery MechanismHReturning Sales Channel, CE Declination reason and Delivery Mechanism - ZCondition where we check ss type, ce declination and delivery mechanism - comment to checkGException in checking ss type, ce declination and delivery mechanism - Delivery Mechanisms - ce declination reason Event ID - 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 LicensePDictionary of values Details_before_entering_condition_trit_rlicense_equal_to_1 MDetails_before_entering_condition_trit_rlicense_equal_to_1 - comment to checkHException in Details_before_entering_condition_trit_rlicense_equal_to_1 it is a resident licenser   r   r   This \ satisfied trit_type as SS & trit_cedeclinationreason is None and delivery method Webinar - ETry to get the license information for the contact - comment to checkBException in Try to get the license information for the contact - rG   have only one license have stateid valueZLGS Validation inside - Check if the license has a valid state id value - comment to checkWException in LGS Validation inside - Check if the license has a valid state id value -  This #'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`'7c1d0c2a-a600-ea11-a825-000d3a1cadb6' and percentage_attendance_check >= 70 no ce request check   r  r  U   zR# Attendance meets the threshold of 85% for specified states. no ce request check    r  r  Z   zR# Attendance meets the threshold of 90% for specified states. no ce request check    r  r  r  d   zS# Attendance meets the threshold of 100% for specified states. no ce request check P   zR# Attendance meets the threshold of 80% for specified states. no ce request check b   _   \   Y   S   C            r   r   r6   +trit_courseassignment_trit_instructionhours$# Attendance meets the threshold of % for z hours. no ce request check zP/C . no ce request check zL/H. no ce request check zP/C & L/H. no ce request check zlCe request declined with both attendance percentage and poll count conditions failing. no ce request check  zQCe request declined due to attendance percentage in Non-LGS. no ce request check zpassed at trit_license_trit_stateid_value not in State_Code or trit_license_trit_stateid_value in specified_states) and percentage_attendance_check < 80 with r<   zFailed at trit_license_trit_stateid_value not in State_Code or trit_license_trit_stateid_value in specified_states) and percentage_attendance_check < 80 function No_cerequest_check for z. no ce request check Error: z7no ce request check completed for eventregistration id z*Failed at function No_cerequest_check for TThis Event Registration ID - zM comes under LGS state, So no CE Request can be created. no ce request check zGfailed at trit_license_trit_residentstate is none. no ce request check zWtrit_license_statecode either have no license or multiple license. no ce request check z|It failed trit_type == 314310000 or trit_cedeclinationreason is None or delivery method is not webinar. no ce request check z2it is a non-resident license. no ce request check zMMore than one license so CE requests can not be created. no ce request check z No License. no ce request check zyAttendance percentage is none so no CE request can be created escaped in the first condition itself. no ce request check zlpassed Attendance percentage is none so no CE request can be created escaped in the first condition itself. )r   r   r  r|  r  r   r,  r0  rP  r   r   r   rx  r:  rT  r>  r   rJ   ).r*  r  info_after_percentage_checkca_dffpqpcaoverall_ce_request_event_reg_idr{  rO   rc   r(  rW   evr   r  licrI  license_namer   r   r   state_approval_idval_LGScontcapercentage_attendance_checkce_request_createdpercentage_checkr5  	lic_checktrit_license_trit_licensetyperA  r   rI   sales_channel_typece_decliDel_Mechr  dmt_type:Details_before_entering_condition_trit_rlicense_equal_to_1specified_states
State_Codeattendance_thresholdsinstruction_hoursrequired_percentager#   r#   r$   No_cerequest_check  sF  













































&
















        r&  c           1      C   sZ  d}zt d|   d}d}t| }t d|  t|}t|}g }| D ]e\}}t d|  t| }	|	d }
|	d }t|}|d }|d	 }t d
|  t|
}|du rrt 	d|
 d|   dd| f  W S |
d}|
d}|
d}|
d}|
d}t||||||}t||
}t d|  t|
}t|| }|d d }t d|  d}|dur|dk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yj }! 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rt d+ d,}"n2|d) d-krt d. d/}"n#|d) d0krt d1 d2}"n|d) d3krt d4 d5}"nt d6 W n ty }! zt d7 t d8|!   d}!~!ww zC|	d9 d:vrt d; d}#n2|	d9 d*krt d< d=}#n#|	d9 d-krt d> d?}#n|	d9 d0kr$t d@ dA}#nt dB W n tyE }! zt dC t dD|!   d}!~!ww za|d d-krVt dE dF}$nP|d d*kret dG dH}$nA|d d0krtt dI dJ}$n2|d dKkrt dL dM}$n#|d dNkrt dO dP}$n|d dQkrt dR dS}$nt dT W n ty }! zt dU t dV|!   d}!~!ww |"|#|$dW}%t dX|%  W n  ty }! zt dY t dZ|!  W Y d}!~!nd}!~!ww |d }t d[|  |	d9 }&t d\|&  |d) }'t d]|  t d^|   z| |||||||%|||d&d_}(t d`|(  W n  tyX }! zt da t db|!  W Y d}!~!nd}!~!ww |d&krt dc |d) d*kr|	d9 ddvr|d-krt de|  df|  |d }zt|}|d }|d }t |  W n  ty }! zt dg t dh|!  W Y d}!~!nd}!~!ww |di dkrt de|  dj |d durt de|  dk zt||}t d|  W n  ty	 }! zt dl t dm|!  W Y d}!~!nd}!~!ww |dkrt dn|  do h dp})g dq}*d}t|| }|drkr|dskrt dt t du|  t||d }t dv|  ||(|di ||||dw}|| |
d}t|||||| }|d| D ]s}+t dx z
t |+
dy W n	   t dz Y |+}t | d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|d&d},z	t|, d}W qr ty }! zt 	d|,  t 	d|!  W Y d}!~!qrd}!~!ww ||| f  W S |dv r|dkrt d t d|  t||d }t dv|  d}||(|di ||||dw}|| |
d}t|||||| }|d| D ]q}+t dx z
t |+
dy W n	   t dz Y |+}t | d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|d&d},zt|, W q; ty }! zt d|,  t d|!  W Y d}!~!q;d}!~!ww ||| f  W S |dv rw|dkrwt d t d|  t||d }t dv|  d}||(|di ||||dw}|| |
d}t|||||| }|d| D ]l}+t dx z
t |+
dy W n	   t dz Y |+}d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|d&d},zt|, W q tyn }! zt d|,  t d|!  W Y d}!~!qd}!~!ww ||| f  W S |dv r9|dkr9t d t d|  t||d }t dv|  d}||(|di ||||dw}|| |
d}t|||||| }|d| D ]l}+t dx z
t |+
dy W n	   t dz Y |+}d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|d&d},zt|, W q ty0 }! zt d|,  t d|!  W Y d}!~!qd}!~!ww ||| f  W S ||*vsC||)v r/|dkr/t d|  t||d }t dv|  d}||(|di ||||dw}|| |
d}t|||||| }t dt|  t dt|  t d|  |d| D ]}+t dx z|+}t d|  W n ty }! zt d|!  W Y d}!~!nd}!~!ww |+}d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|d&d},t |, zt|, W q ty' }! zt d|,  t d|!  W Y d}!~!qd}!~!ww ||f  W S ||)v 
rHddddddd}-|d }.|-
|.}/|/	r||/krkt d|/ d|. d t||d }t d|  d}||(|di ||||dw}|| |
d}t|||||| }|d| D ]u}+t dx zt |+ W n	   t dz Y |+}d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|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 | np|	s|	rt| t d t||d }t dv|  d}|
dd*k	rRt d |
d"}t|||}0nK|
dd-k	rkt d |
d"}t|||}0n2|
dd0k	rt d z|
d"}t|||}0W n   |
d"}t|||}0Y nt d d}0||(|di ||||dw}||| f  W S t d t||d }|
d}t||||||}|}t d|  |d| D ]j}+zt |+ W n	   t dz Y |+}d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|dKd&d	},zt|, W n# t
y> }! zt d|,  t d|!  W Y d}!~!nd}!~!ww t | 	qېnA||*v
sR||)v r|dk rt d t||d }t d|  |
d}t|||||| }t d|  |d| D ]y}+zt |+ W n	   t dz Y |+}t d d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|dKd&d	},t |, zt|, t d W n# t
y }! zt d|,  t d|!  W Y d}!~!nd}!~!ww t | 
qt | nt d t||d }|
d}t||||||}|}t d|  |d| D ]j}+zt |+ W n	   t dz Y |+}d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|dKd&d	},zt|, W n# ty }! zt d|,  t d|!  W Y d}!~!nd}!~!ww t | q2n|dkrt 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 dz Y |+}d{|  d|d}| d|| d~|
 d|d| d|d| d|d| d|dKd&d	},zt|, W n# ty }! zt d|,  t d|!  W Y d}!~!nd}!~!ww t | q||| f  W S W dS  ty }! zt |! W Y d}!~!dS d}!~!ww )r  Nz%entered cerequest_check function for r  r  r  r(  rW   r.  r  zProduct ID: r  r  FrI  rJ  r   rE  r   r  r  r   r  r  r  r~   r5  r  r  r  rA  r  r  r  r   r  r  r  r6   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  r  r  r  r  r  r  r  r  r  r  r  r7   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  r  r  r  r  rG  r  r  r  r  r  r  r  r  r  r  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
Percentager  zNo of CE Requestzce creationr   zno approv id exceptionz/msevtmgt_eventregistrations(r:   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.bindr9   TzFailed to submit record: r  r  r  zHI or VA State & >= 85%z3# Check for AO&AM products - based on percentage 2 r  r  zTX, ND >= 90%z3# Check for AO&AM products - based on percentage 3 r  r  zMD, MI, MN state and = 100 %z3# Check for AO&AM products - based on percentage 4 r  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 - r  r  r  r  r  r   r  r  r  r  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 7 - )	r*  r+  r   r,  r-  r.  r/  r9   r8   zinto 6z	into 6 - zinto the loopzpassed the else statementz;Ce request declined due to attendance percentage in Non-LGSr	  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 itself)r   r   r  r|  r  r   r,  r0  rP  r   r   r   rx  r:  rT  r>  r   r  rY   r   typerN   r"  r   r   )1r*  r  r
  r  r  r  r  r{  rO   rc   r(  rW   r  r   r  r  rI  r  r   r   r   r  r  r  r  r  r  r  r5  r  r  rA  r   rI   r  r  r  r  r  r  r   r!  r"  salr   r#  r$  r%  LOAr#   r#   r$   cerequest_check  s  











































&


























































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

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

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


























              r3  c              
   C   s   z8t | }|d u rtd|   dd| dW S t|tr0t|dkr0|\}}}d|||dW S dd	t|d
W S  ty_ } ztd|  t	d dt|| dW  Y d }~S d }~ww )Nz8cerequest_check returned None for eventregistration_id: r   zcerequest_check returned None)r{   rg   r~  r   success)r{   r  
ce_createdr~  warningzUnexpected return format)r{   rg   r   z Error in ce_request_last_check: Full traceback:)
r3  r   r   r  tuplerN   strr   r   	exception)r*  ceno_of_requestscreatedreg_idrI   r#   r#   r$   ce_request_last_check  s8   

r?  POSTc              
   C   s   z6| j dkr4| jd}|stdddddW S td|  t|}td	|  td
|dW S W d S  ty` } ztd|  t	d tdt
|dddW  Y d }~S d }~ww )Nr@  eventreg_idr   zeventreg_id is required)r{   rg   ry   rz   z.Processing CE request for event registration: zCE result: r4  )r{   r"   zError in index_ce_request: r7  r}   )r   r   r   r   r   r   r?  r   r   r:  r9  )r   r*  r;  rI   r#   r#   r$   index_ce_request  s:   


rB  c                 C   s@  z| j dkr| jd}|stddiddW S t|}td|  |s1tdd| id	dW S g }g }g }|D ]}td
|  zst|}t|}|du rm|dksX|dkrmtd|  t	|}	|
||	d nH|du rtd|  |
| zt| W n0 ty }
 ztd| d|
  W Y d }
~
nd }
~
ww td|  td| d|  W q9 ty }
 ztd| d|
  |
|t|
d W Y d }
~
q9d }
~
ww |||d}t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@  rZ   r   zeventcode is requiredry   rz   z*event registration id list index function z,No event registrations found for eventcode: i  zEvent Registration ID: Fr   r   zevent registration ids false: )id
last_checkTzevent registration ids true: z Error in No_cerequest_check for r|   zevent registration ids else: z2This Event Registration ID has unexpected result: z - zError in event registration id )rC  r   )zevent reg idszeligible to check ce listalready_exists_listzindex details invalid_ce_listzerror at index exception r}   )r   r   r   r   rd   r   r   rQ   rV   r?  rY   r&  r   r   r9  )r   rZ   event_reg_idsrF  rE  	valid_idsersis_validstatus_checkr;  rI   r   r#   r#   r$   r    sv   


" 3
 r  )@asyncior   rest_framework.decoratorsr   django.httpr   ossysr   rn   inspectr   ri   pandasrL   collectionsr   requests.authr   pathrY   r   dirname__file__LogUtilsgetRootLoggerr   r   r   r   r   r   r%   rJ   rQ   rV   rd   rw   r   r   r   r   r   r   r   r  r  r"  r,  r0  r:  r>  rP  rT  r  rx  r|  r  r  r&  r3  r?  rB  r  r#   r#   r#   r$   <module>   s    
6&$42
=(C1/}<PJ+.'0}""i6%L   I       R4
