
    mh:                         d 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 ej                  ej                  j                         dZ
dadad Zd Zd Zd	 Zd
 Zd Zd Zd Zd Zd Zedk(  r e        yy)z
Job Applicant Creator for Wright Choice HS
Creates Job Applicant DocTypes directly via ERPNext API
Based on the email_intake_job_worker_v2.py structure
    N)datetimez&https://portal.wrightchoicehs.com:5750 c                      t        j                  d      at        j                  d      at        rt        s!t	        d       t        j                  d       yy)z/Load API credentials from environment variablesERPNEXT_API_KEYERPNEXT_API_SECRETzOERROR: ERPNEXT_API_KEY and ERPNEXT_API_SECRET environment variables must be set   N)osgetenvAPI_KEY
API_SECRETprintsysexit     3/var/www/wrightchoicehs/create_job_applicant_api.pyload_api_credentialsr      s@     ii)*G/0J*_` %r   c                  2    t          dt         } d|  dddS )z3Get authentication headers with proper token format:token application/json)AuthorizationAcceptzContent-Type)r   r   )tokens    r   get_auth_headersr   !   s,    iq%E!%)$* r   c                  v   	 t        j                  t         dt               dd      } | j                  dk(  r/| j                         }t        d|j                  dd              y	t        d
| j                   d| j                          y# t        $ r!}t        dt        |              Y d}~yd}~ww xY w)z$Test authentication with ERPNext APIz'/api/method/frappe.auth.get_logged_userF
   )headersverifytimeout   u&   ✅ Authentication successful - User: messageUnknownTu   ❌ Authentication failed:  - u   ❌ Authentication error: N)
requestsgetERPNEXT_URLr   status_codejsonr   text	Exceptionstr)responsedataes      r   test_authenticationr0   *   s    <<mBC$&	
 3&==?D:488Iy;Y:Z[\/0D0D/ESXY *3q6(34s   A%B (%B 	B8B33B8c           	         	 t        j                  t         ddt        j                  d|j                         j                         i      it               d      }|j                  dk(  rF|j                         j                  dg       }|r$|d   j                  d	      }t        d
|        |S | j                         j                  dd      }|r|d   nd}t        |      dkD  r|d   nd}| |||j                         j                         ddgd}	|r	|ddg|	d<   t        j                  t         d|	t               d      }|j                  dv r?|j                         j                  di       j                  d	      }t        d|        |S t        d|j                   d|j                          y# t        $ r!}
t        dt        |
              Y d}
~
yd}
~
ww xY w)z*Create or update a Contact via ERPNext APIz/api/resource/Contactfilterszemail_ids.email_idFparamsr   r   r!   r.   r   nameu   ℹ️ Found existing Contact:  r   r   )email_id
is_primary)	full_name
first_name	last_name	email_ids)phoneis_primary_mobile_no	phone_nosr)   r   r   r!      u   ✅ Created new Contact: u   ❌ Failed to create Contact: r$   Nu   ❌ Error creating Contact: )r%   r&   r'   r)   dumpslowerstripr   r(   r   splitlenpostr*   r+   r,   )r9   emailr=   r-   existing_contactscontact_name
name_partsr:   r;   contact_datar/   s              r   create_or_update_contactrN   @   s   0<<m01tzz+?ATATAV*WXY$&	
 3& ( 3 3FB ? 0377?7~FG## __&,,S!4
&0Z]b
%(_q%8JqMb	 #$"',{{}':':'<ANO	
 38RS)T(UL%==m01$&	
 :-#==?..vr:>>vFL-l^<=283G3G2HHMM?[\ ,SVH56s%   B/F= 2C$F= %F= =	G'G""G'c                    	 t        j                  t         d|  t               d      }|j                  dk7  rt        d|  d|j                          y|j                         j                  di       }|j                  d	g       }|D ]>  }|j                  d
      dk(  s|j                  d      |k(  s-t        d|  d|         y d	|vrg |d	<   |d	   j                  d|d       t        j                  t         d|  |t               d      }|j                  dk(  rt        d|  d|        yt        d|j                   d|j                          y# t        $ r!}t        dt        |              Y d}~yd}~ww xY w)z0Ensure Contact has dynamic link to Job Applicantz/api/resource/Contact/Fr   r   r!   u   ❌ Failed to get Contact z: Nr.   linkslink_doctypeJob Applicant	link_nameu   ℹ️ Contact z! already linked to Job Applicant )rR   rT   r@   u   ✅ Linked Contact z to Job Applicant u-   ❌ Failed to link Contact to Job Applicant: r$   u,   ❌ Error linking Contact to Job Applicant: )r%   r&   r'   r   r(   r   r)   appendputr*   r+   r,   )rK   job_applicant_namer-   contact_docexisting_linkslinkr/   s          r   ensure_contact_dynamic_linkr[   t   s   +G<<m1,@$&
 3&.|nBx?S?S>TUVmmo))&"5 %"5" 	Dxx'?:txx?TXj?j~5VWiVjkl	 +%#%K G##++%
 	 <<m1,@$&	
 3&'~5GHZG[\]A(BVBVAWWZ[c[h[hZijk G<SVHEFFGs8   AE AE "E 7E 
A+E 6%E 	F%FFc                    	 t        j                  t         ddt        j                  d| i      it               d      }|j                  dk(  r|j                         j                  dg       }|r|d   j                  d	      }t        j                  t         d
| t               d      }|j                  dk(  rW|j                         j                  di       }|j                  d      }|j                  d      }t        d| d|        ||fS t        d|         y# t        $ r!}t        dt        |              Y d}~yd}~ww xY w)z-Get Job Opening information by position titlez/api/resource/Job Openingr2   	job_titleFr3   r!   r.   r   r5   z/api/resource/Job Opening/rP   designationu   ✅ Found Job Opening: z -> u'   ❌ No Job Opening found for position: )NNu$   ❌ Error getting Job Opening info: N)
r%   r&   r'   r)   rC   r   r(   r   r+   r,   )	positionr-   job_openingsjob_namedetail_response
job_detailr]   r^   r/   s	            r   get_job_opening_inford      sH   !<<m45tzz;*ABC$&	
 3&#==?..vr:L'?..v6 #+,,"m#=hZH,. # #..#5!0!5!5!7!;!;FB!GJ *{ ;I",.."?K3I;d;-PQ#[007zBC 4SVH=>s   DD$ D$ $	E-E		Ec                 X   	 t        j                  t         ddt        j                  d| i      it               d      }|j                  dk(  r.|j                         j                  dg       }t        |      dkD  S y# t        $ r!}t        d	t        |              Y d
}~yd
}~ww xY w)z6Check if a Job Applicant already exists for this email/api/resource/Job Applicantr2   r7   Fr3   r!   r.   r   u,   ❌ Error checking for duplicate applicant: N)r%   r&   r'   r)   rC   r   r(   rG   r+   r   r,   )rI   r-   existing_applicantsr/   s       r   check_duplicate_applicantrh      s    <<m67tzz:u*=>?$&	
 3&"*--/"5"5fb"A*+a// <SVHEFs   A;A? ?	B)B$$B)c                    	 | rt         j                  j                  |       st        d|         yt	        | d      5 }|j                         }ddd       t         j                  j                  |       }|dfdd|fd|fd}t        j                  t         d|dt         d	t         d
dd      }|j                  dk(  r^|j                         }|j                  d      r$|d   j                  d      }	t        d|	        |	S t        d|j                          yt        d|j                   d|j                          y# 1 sw Y   xY w# t         $ r!}
t        dt#        |
              Y d}
~
yd}
~
ww xY w)z0Upload a file to ERPNext and return the file URLu   ❌ File not found: Nrbzapplication/pdf)N0)file
is_privatedoctypedocnamez/api/method/upload_filer   r   r   )r   r   F)filesr   r   r!   r"   file_urlu   ✅ File uploaded: u   ❌ File upload failed: r$   u   ❌ Error uploading file: )r	   pathexistsr   openreadbasenamer%   rH   r'   r   r   r(   r)   r&   r*   r+   r,   )	file_pathrn   ro   ffile_contentfilenamerp   r-   resultrq   r/   s              r   upload_file_to_erpnextr|      s   ,y 9(45 )T" 	$a668L	$ 77##I. |->?%gg	
 ==m23#)'!J<!@, 
 3&]]_Fzz)$!),00<+H:670@A,X-A-A,B#hmm_UVE	$ 	$H  *3q6(34s@   /E E EB9E 	E "%E EE 	E>E99E>c                    	 | j                  d      st        d       ydj                  | j                  dd      | j                  dd      g      j                         }|st        d       y| j                  d      j	                         j                         }t        |      rt        d	|        y| j                  d
d      }t        |      \  }}||| j                  dd      | j                  dd      | j                  dd      t        j                         j                         | j                  dd      | j                  dd      | j                  dd      | j                  dd      d
}|r||d<   |r||d<   t        j                  t         d|t               d      }|j                  dv r|j                         j                  di       j                  d      }t        d|        | j                  d      }	|	rt!        |	d|      }
|
rt        d|        t#        ||| j                  dd            }|rZd |i}t        j$                  t         d!| |t               d      }|j                  d"k(  rt        d#| d$|        t'        ||       |S t        d%|j                   d&|j(                          y# t*        $ r!}t        d't-        |              Y d}~yd}~ww xY w)(z&Create a Job Applicant via ERPNext APIrI   u   ❌ Email is requiredNr6   r:   r   r;   u   ❌ Full name is requiredu*   ⏭️ Duplicate Job Applicant exists for r_   r=   sourceWebsiter"   custom_citycustom_county_of_interestcustom_first_namecustom_last_name)
applicant_namer7   phone_numberr~   custom_why_are_you_a_good_fitcreated_on_displayr   r   r   r   r]   r^   rf   Fr@   rA   r.   r5   u   ✅ Created Job Applicant: resume_filepathrS   u*   ✅ Resume file attached to Job Applicant custom_contactz/api/resource/Job Applicant/r!   u   ✅ Updated Job Applicant z with Contact u$   ❌ Failed to create Job Applicant: r$   u"   ❌ Error creating Job Applicant: )r&   r   joinrE   rD   rh   rd   r   now	isoformatr%   rH   r'   r   r(   r)   r|   rN   rV   r[   r*   r+   r,   )applicant_datar9   rI   r_   job_opening_namer^   job_applicant_datar-   r   r   rq   rK   update_dataupdate_responser/   s                  r   create_job_applicant_via_apir     s   U!!'*)*HHn00rBNDVDVWbdfDghiooq	-.""7+11399; %U+>ugFG "%%j"5(<X(F%+ (*..w;$((9=-;-?-?	2-N"*,,.":":"<)--mR@)7););<WY[)\!/!3!34G!L . 2 23Er J
 .>{+0;}- ==m67#$&	
 :-%]]_00<@@HN//?@A -001BCO1/?TbcF~FVWX 4IunFXFXY`bdFefL/>"*,,"m#??OP$,. 	# #..#56~6FnUaTbcd ,L.I!!89M9M8NcRZR_R_Q`ab 23q6(;<s1   K AK .AK 5G(K %K 	K.K))K.c                  R   t        t        j                        dk7  r+t        d       t        d       t        j                  d       	 t                t        d       t               s t        d       t        j                  d       t        j                  d   } t        j                  |       }t        d|j                  dd	              t        |      }|r$t        d
|        t        j                  d       yt        d       t        j                  d       y# t        j                  $ r6}t        dt        |              t        j                  d       Y d}~yd}~wt        $ r6}t        dt        |              t        j                  d       Y d}~yd}~ww xY w)z5Main function to create Job Applicant from JSON input   z7Usage: python create_job_applicant_api.py '<json_data>'a4  Example: python create_job_applicant_api.py '{"first_name": "John", "last_name": "Doe", "email": "john@example.com", "phone": "555-1234", "position": "Companion/Sitter", "source": "website", "message": "I am interested in this position", "custom_city": "Springfield", "custom_county_of_interest": "Fairfax"}'r   u   🔐 Testing authentication...uM   ❌ Authentication failed. Please check your API credentials and ERPNext URL.u(   📥 Processing job applicant data for: rI   unknownu#   ✅ SUCCESS: Created Job Applicant r   u*   ❌ FAILED: Could not create Job Applicantu   ❌ Invalid JSON data: Nu   ❌ Unexpected error: )rG   r   argvr   r   r   r0   r)   loadsr&   r   JSONDecodeErrorr,   r+   )	json_datar   r   r/   s       r   mainr   d  sA   
388}GH  i  	j 	./"$abHHQK HHQK	I.89K9KGU^9_8`ab 6nE77GHIHHQK>?HHQK 'Ax01 &s1vh/0s+   	B5D  ? D   F&3,E$$F&0,F!!F&__main__)__doc__r%   r)   r   r	   r   urllib3disable_warnings
exceptionsInsecureRequestWarningr'   r   r   r   r   r0   rN   r[   rd   rh   r|   r   r   __name__r   r   r   <module>r      s      
 	     ++BB C 7

,2h-G^#J&.`Wr&P zF r   