DBA Data[Home] [Help]

PACKAGE BODY: APPS.IEM_EMAIL_PROC_PVT

Source


1 PACKAGE BODY IEM_EMAIL_PROC_PVT as
2 /* $Header: iemmprpb.pls 120.45.12020000.5 2013/01/23 07:07:23 lkullamb ship $ */
3 
4 G_PKG_NAME CONSTANT varchar2(30) :='IEM_EMAIL_PROC_PVT ';
5 g_statement_log	boolean;		-- Statement Level Logging
6 g_exception_log	boolean;		-- Statement Level Logging
7 g_error_log	boolean;		-- Statement Level Logging
8 g_contact_id		number;
9 g_relation_id		number;
10 g_topscore		number;
11 g_topclass		varchar2(100);
12 
13 --siahmed 12.1.3 advanced sr creation
14  --global variable  for customer_id
15   g_customer_id  NUMBER;
16   g_account_type IEM_MSTEMAIL_ACCOUNTS.ACCOUNT_TYPE%TYPE;
17   --global variable for contact_party_id and party_type
18   g_contact_party_id    NUMBER;
19   g_contact_party_type  VARCHAR2(100);
20   g_contact_point_id    NUMBER;
21   --added for contact_point_type
22   g_contact_point_type  VARCHAR2(100);
23   g_party_role_code VARCHAR2 (100) := 'CONTACT';
24   --this is to hold the party_id value for the hz_party_relationships table
25   --and then that value is used in the hz_contact_points.owner_table_id to find
26   --the contact_point id
27   g_owner_table_id number;
28 --siahmed 12.1.3 end of advanced sr creation
29 
30 
31 PROCEDURE PROC_EMAILS(ERRBUF OUT NOCOPY		VARCHAR2,
32 		   ERRRET OUT NOCOPY		VARCHAR2,
33 		   p_api_version_number in number:= 1.0,
34  		   p_init_msg_list  IN   VARCHAR2 ,
35 	    	   p_commit	    IN   VARCHAR2 ,
36 		   p_count		IN NUMBER
37 			 	) IS
38 	l_post_rec	iem_rt_preproc_emails%rowtype;
39 	l_count		number:=1;
40 	l_index		number:=0;
41 	l_class		number;
42 	l_ret_status	varchar2(10);
43 	l_msg_data	varchar2(300);
44 	l_msg_count	number;
45 	l_media_id	number;
46 	l_group_id	number;
47 	l_rt_classification_id	number;
48 	l_stat				varchar2(10);
49 	l_out_text			varchar2(2000):=' ';
50 	l_routing_classification	varchar2(300);
51 	KeyValuePairs iem_route_pub.KeyVals_tbl_type;
52 	l_api_name	varchar2(100):='PROC_EMAILS';
53 	l_api_version_number	number:=1.0;
54 	l_Error_Message           VARCHAR2(2000);
55 	l_call_status             BOOLEAN;
56 	l_class_val_tbl		IEM_ROUTE_PUB.keyVals_tbl_type;
57 	l_param_rec_tbl		IEM_RULES_ENGINE_PUB.parameter_tbl_type;
58 	l_tag_keyval			IEM_TAGPROCESS_PUB.keyVals_tbl_type;
59 	l_action				varchar2(50);
60 	l_counter				number:=1;
61 	l_uid				number;
62  	l_media_lc_rec 		JTF_IH_PUB.media_lc_rec_type;
63  	l_milcs_id NUMBER;
64  	l_mp_milcs_id NUMBER; 	-- MLCS ID for MAIL PROCESSINGS
65 	l_message_id		number;
66 	l_email_rec		iem_rt_preproc_emails%ROWTYPE;
67 	x_stat		varchar2(10);
68 	l_status		varchar2(10);
69 	l_text		varchar2(32767);
70 	l_cust_stat		varchar2(10);
71 	l_process			varchar2(10);
72 	l_from_folder		varchar2(50):='/Inbox';
73 	l_folder_name		varchar2(100);
74 	l_f_name			varchar2(100);
75 	l_proc_stat		varchar2(10);
76 	l_autoproc_result		varchar2(1);
77 	l_contact_point_id	number;
78 	l_emp_flag		varchar2(10):='N';
79 	STOP_PROCESSING	EXCEPTION;
80 	ABORT_PROCESSING	EXCEPTION;
81 	ABORT_MOVE_PROCESSING	EXCEPTION;
82 	ERR_INSERTING		EXCEPTION;
83 	l_level			varchar2(20):='STATEMENT';
84 	l_logmessage		varchar2(2000):=' ';
85 	l_encrypted_id		varchar2(500);
86 	l_msgid1			number;
87 	l_index1			number;
88 	l_index2			number;
89 	l_autoack_count	number:=0;
90 	l_autoack_flag	     varchar2(1):='N';
91 	e_nowait			EXCEPTION;
92 	PRAGMA			EXCEPTION_INIT(e_nowait, -54);
93 	NO_ITEM_FOUND			EXCEPTION;
94 	NO_RECORD_TO_PROCESS		EXCEPTION;
95 	STOP_REDIRECT_PROCESSING		EXCEPTION;
96 	cursor c_class_id is
97 	select classification_id from iem_email_classifications
98 	where message_id=l_message_id
99 	order by score desc;
100 	l_intent_counter	number;
101 	l_start_search		number:=0;
102 	l_ih_subject		varchar2(80);
103 	l_search			varchar2(100);		-- search pattern in subject
104 	l_doc_id			number;
105 	l_sr_id			number;
106 	l_note_type		varchar2(100);
107 	l_agentid			number;
108 	l_ih_id			number;
109 	l_dflt_agt_id		number;
110 	l_agt_count		number;
111 	l_tag_custid		number;		-- Customer Id in Tag
112 	l_customer_id		number;
113 	l_enable			varchar2(1);
114 	l_auto_flag		varchar2(1):='N';
115 	l_noti_flag		varchar2(1);
116 	l_auto_value		varchar2(20);
117 	l_dflt_sender		varchar2(200);
118 	l_wf_custom_val		varchar2(200);
119 	l_media_rec	JTF_IH_PUB.media_rec_type;
120  	l_interaction_rec        JTF_IH_PUB.interaction_rec_type;
121  	l_activity_rec        JTF_IH_PUB.activity_rec_type;
122  	l_interaction_id        number;
123  	l_activity_id        number;
124  	l_param_index        number;
125 	l_cust_search_id		 number;
126 	l_status_id		 number;
127 	l_proc_name		 varchar2(100);
128 	l_result		 varchar2(100);
129 	l_run_proc_tbl		IEM_TAGPROCESS_PUB.keyVals_tbl_type;
130 	l_tbl_counter		number;
131 	l_redirect_id		varchar2(240);
132 	l_rt_media_item_id		number;
133 	l_rt_interaction_id	number;
134 	l_email_doc_tbl		email_doc_tbl;
135 	l_resource_id			number;
136 	l_qual_tbl		 IEM_OUTBOX_PROC_PUB.QualifierRecordList;
137 	l_outbox_tbl		IEM_OUTBOX_PROC_PUB.keyVals_tbl_type;
138 	l_auto_reply_flag		varchar2(1):='N';
139 	l_auto_forward_flag		varchar2(1);
140 	l_action_id		number;
141 	l_outbox_item_id		number;
142 	l_cat_counter		number;
143 	l_search_type		varchar2(10); -- ALL/MES/KM/CP -- Category Map
144 	l_cm_cat_id		number;	-- store the category for MES category based mapping
145 	l_kb_rank		number;
146 	l_contact_id		number;
147 	l_party_id		number;
148 	l_party_type		varchar2(100);
149 	l_id				number;
150    l_category_id     AMV_SEARCH_PVT.amv_number_varray_type:=AMV_SEARCH_PVT.amv_number_varray_type();
151    l_repos			varchar2(100);	-- MES/KM search repository
152    l_ext_address		varchar2(250);		--external email address  for redirecting
153    l_ext_temp_id		number;			-- template id created to be used for redirecting external
154    l_ext_subject		varchar2(500);		-- prefix for redirect email subject
155 	l_outbox_id		number;
156 	l_sender			varchar2(200);
157 	l_from1			number;
158 	l_from2			number;
159 	l_to_address			varchar2(200);
160 	l_redirect_flag		varchar2(1):='N';
161 	l_intent_flg			number(15,0);
162 	l_rule_id			number;
163 	l_acct_type		iem_mstemail_accounts.account_type%type;
164 	--12.1.3 Dev Threading
165 	l_thread_id		number;
166         --siahmed 12.1.3 Advanced SR creation
167         l_parser_id            NUMBER;
168 	--Fix for bug 14202765
169 	l_notes_flag           VARCHAR2(1) := 'Y';
170 
171    cursor c_item is select ib.item_id,ib.item_name,ib.last_update_date
172    from   amv_c_chl_item_match cim,jtf_amv_items_vl ib
173    where  cim.channel_category_id = l_cm_cat_id
174    and   cim.channel_id is null
175    and   cim.approval_status_type ='APPROVED'
176    and   cim.table_name_code ='ITEM'
177    and   cim.available_for_channel_date <= sysdate
178    and   cim.item_id = ib.item_id
179    and    nvl(ib.effective_start_date, sysdate) <= sysdate + 1
180    and   nvl(ib.expiration_date, sysdate) >= sysdate;
181    -- Introduce additional key Intent String
182    l_top_intent	varchar2(50);
183    l_top_score		number;
184 
185 -- sardas ,modified query for intent issue fix bug#13946049
186  cursor c_intent is select a.intent,b.score from
187  iem_intents a,iem_email_classifications b
188  where b.message_id=l_message_id
189  and a.intent_id=b.classification_id
190  order by b.score desc;
191 
192  l_intent_str			varchar2(700);
193  l_header_rec			iem_ms_base_headers%rowtype;
194  l_email_user_name		iem_mstemail_accounts.user_name%type;
195  l_email_address		iem_mstemail_accounts.user_name%type;
196  l_email_domain_name	varchar2(300);
197  l_auto_msgstatus		varchar2(10);		-- will store msg status for autoreply/autoxredirect;
198 l_cust_contact_id number;
199  STOP_AUTO_PROCESSING	EXCEPTION;
200 
201 
202  --siahmed
203  	l_msg_index_out		number;
204   --siahmed
205 begin
206 -- Standard call to check for call compatibility.
207 IF NOT FND_API.Compatible_API_Call (l_api_version_number,
208 				    p_api_version_number,
209 				    l_api_name,
210 				    G_PKG_NAME)
211 THEN
212 	 RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
213 END IF;
214 		FND_LOG_REPOSITORY.init(null,null);
215 		if( FND_LOG.LEVEL_PROCEDURE >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
216 			g_statement_log:=true;
217 		end if;
218 		if( FND_LOG.LEVEL_EXCEPTION >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
219 			g_exception_log:=true;
220 		end if;
221 		if( FND_LOG.LEVEL_ERROR >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
222 			g_error_log:=true;
223 		end if;
224 LOOP
225 		SAVEPOINT process_emails_pvt;
226  BEGIN
227 
228  /* Get the message in FIFO order to process from iem_rt_preproc_emails */
229 
230 	if g_statement_log then
231 	  l_logmessage:='starting to get the message in FIFO order to process from iem_rt_preproc_emails, messageID :';
232 	  iem_logger(l_logmessage||l_post_rec.message_id);
233 	end if;
234 
235 	IEM_EMAIL_PROC_PVT.iem_returned_msg_rec(l_post_rec);
236 	IF l_post_rec.message_id is null then
237 		raise NO_RECORD_TO_PROCESS ;
238 	END IF;
239 	l_message_id:=l_post_rec.message_id;
240 	select * into l_header_Rec
241 	from iem_ms_base_headers
242 	where message_id=l_message_id;
243 	select user_name,kem_flag,email_address,account_type
244 	into l_email_user_name,l_intent_flg,l_email_address,l_acct_type
245 	from iem_mstemail_accounts
246 	where email_account_id=l_post_rec.email_account_id;
247 	l_email_domain_name:=substr(l_email_address,instr(l_email_address,'@',1)+1,length(l_email_address));
248 
249 
250 	if g_statement_log then
251 	  l_logmessage:='email domain name :'||substr(l_email_address,instr(l_email_address,'@',1)+1,length(l_email_address));
252 	  iem_logger(l_logmessage);
253 	end if;
254 
255 	--  Do Intent Processing if Enabled for Intent
256 	IF l_intent_flg>0 THEN			-- intent is enabled for the account
257 
258 
259 		if g_statement_log then
260 		  l_logmessage:='intent is enabled for the account';
261 		  iem_logger(l_logmessage);
262 		end if;
263 		iem_email_proc_pvt.iem_process_intent(l_post_rec.email_account_id,l_post_rec.message_id,l_ret_status,l_out_text);
264 		IF l_ret_status<>'S' then
265 		if g_error_log then
266 			l_logmessage:='Error During Intent Processing.Not able to Map intent to inbound emails.Continued Processing ';
267 			iem_logger(l_logmessage);
268 		end if;
269 		ELSE
270 		if g_statement_log then
271 			l_logmessage:='Success in Intent  Processing  ';
272 			iem_logger(l_logmessage);
273 		end if;
274 		END IF;
275 	END IF;
276 
277 /* Find the profile value set for Processing Number of Intents for suggested Documents */
278 
279 	l_intent_counter:=FND_PROFILE.VALUE_SPECIFIC('IEM_INTENT_RESPONSE_NUM');
280 	if l_intent_counter is null then
281 		l_intent_counter:=1;
282 	end if;
283 
284 	if g_statement_log then
285 		l_logmessage:='Start Processing for message ID '||l_post_rec.message_id;
286 		iem_logger(l_logmessage);
287 	end if;
288 	-- resetting the below two value to null to get rid of cache data
289 	g_contact_id:=null;
290 	g_relation_id:=null;
291 
292  -- Check For TAG DATA in Inbound Emails
293 
294 	l_tag_keyval.delete;
295 
296 
297 	if g_statement_log then
298 		l_logmessage:='Calling tag api';
299 		iem_logger(l_logmessage);
300 	end if;
301 
302 	IEM_EMAIL_PROC_PVT.IEM_RETURN_ENCRYPTID
303 	(p_subject=>l_header_rec.subject,
304 	x_id=>l_encrypted_id,
305 	x_Status=>l_ret_status);
306 
307 
308 	if g_statement_log then
309 		l_logmessage:='email tag validation status:'|| l_ret_status;
310 		iem_logger(l_logmessage);
311 	end if;
312 
313     	if l_ret_status='E' then
314 		if g_statement_log then
315 			l_logmessage:='Error While searching for Tag in Subject ';
316 			iem_logger(l_logmessage);
317 		end if;
318 
319 
320 	if g_statement_log then
321 		l_logmessage:='calling abot_processing due to  tag failure';
322 		iem_logger(l_logmessage);
323 	end if;
324 		raise ABORT_PROCESSING;
325 	else
326 		if l_encrypted_id is not null then
327 				l_logmessage:='Found Encrypted Tag '||l_encrypted_id;
328 		else
329 				l_logmessage:='Inbound message does not contain any tag';
330 		end if;
331 
332 		if g_statement_log then
333 			iem_logger(l_logmessage);
334 		end if;
335 	end if;
336 
337 -- CALLING  TAGGING API TO RESET THE TAG DATA FOR REROUTED MESSAGE
338 IF l_post_rec.ih_media_item_id is not null then
339 
340 
341 	if g_statement_log then
342 		l_logmessage:='Resetting The Tag For Rerouted/Redirected Message';
343 		iem_logger(l_logmessage);
344 		l_logmessage:='Resetting The Tag For Rerouted/Redirected Message,messageID: ' ||l_post_rec.message_id ||' status : '||l_ret_status || ' msg_count: '|| l_msg_count || 'msg_data :'||l_msg_data ;
345 		iem_logger(l_logmessage);
346 	end if;
347 	IEM_ENCRYPT_TAGS_PVT.RESET_TAG
348              (p_api_version_number=>1.0,
349               p_message_id=>l_post_rec.message_id,
350               x_return_status=>l_ret_status ,
351               x_msg_count=>l_msg_count,
352               x_msg_data=>l_msg_data);
353 
354    	IF l_ret_status<>'S' THEN
355 	if g_error_log then
356 		l_logmessage:='Error while Resetting Tag For Rerouted Message';
357 		iem_logger(l_logmessage);
358 	end if;
359 
360 
361 	if g_statement_log then
362 		l_logmessage:='raise_abort_processing2:'|| l_ret_status;
363 		iem_logger(l_logmessage);
364 	end if;
365    		raise abort_processing;
366 	END IF;
367 END IF;
368 
369 -- Calling the Tag Processing Api
370 
371 	if g_statement_log then
372 		l_logmessage:='Calling Tag Processing Api ';
373 		iem_logger(l_logmessage);
374 	end if;
375 	IF l_encrypted_id is not null then
376 			IEM_TAGPROCESS_PUB.GETTAGVALUES
377 					(p_Api_Version_Number=>1.0,
378 					 p_encrypted_id =>l_encrypted_id,
379         				p_message_id=>l_post_rec.message_id,
380         				x_key_value=>l_tag_keyval,
381         				x_msg_count=>l_msg_count,
382         				x_return_status=>l_ret_status,
383         				x_msg_data=>l_msg_data);
384 
385 
386 			if g_statement_log then
387 				l_logmessage:='calling getTAGVALUES status:'|| l_ret_status;
388 				iem_logger(l_logmessage);
389 			end if;
390     			IF l_ret_status<>'S' THEN
391 			if g_error_log then
392 				l_logmessage:='Error while Calling Tag Processing Api ';
393 				iem_logger(l_logmessage);
394 			end if;
395 
396 			if g_statement_log then
397 				l_logmessage:='calling getTAGVALUES abort processing status';
398 				iem_logger(l_logmessage);
399 			end if;
400    				raise abort_processing;
401 			END IF;
402 	END IF;
403 
404   -- Retrieving Tag Data if Exists
405 				l_auto_reply_flag:='N';
406 
407 	IF l_tag_keyval.count>0 THEN
408 			for i in l_tag_keyval.FIRST..l_tag_keyval.LAST LOOP
409 
410 
411 			if g_statement_log then
412 				l_logmessage:='tag data : '|| l_tag_keyval(i).key ||'tag value : '||l_tag_keyval(i).value;
413 				iem_logger(l_logmessage);
414 			end if;
415 
416 			IF l_tag_keyval(i).key='IEMNBZTSRVSRID' then
417 				l_sr_id:=to_number(l_tag_keyval(i).value);
418 			ELSIF l_tag_keyval(i).key='IEMNAGENTID' THEN
419 				l_agentid:=to_number(l_tag_keyval(i).value);
420 			ELSIF l_tag_keyval(i).key='IEMNINTERACTIONID' THEN
421 				l_ih_id:=to_number(l_tag_keyval(i).value);
422 			ELSIF l_tag_keyval(i).key='IEMNCUSTOMERID' THEN
423 				l_tag_custid:=to_number(l_tag_keyval(i).value);
424 			ELSIF l_tag_keyval(i).key='IEMSAUTOREPLY' THEN
425 				l_auto_reply_flag:='Y';
426 			ELSIF l_tag_keyval(i).key='IEMSAUTOFORWARD' THEN
427 				l_auto_forward_flag:='Y';
428 			ELSIF l_tag_keyval(i).key='IEMNCONTACTID' THEN
429 				g_contact_id:=to_number(l_tag_keyval(i).value);
430 			ELSIF l_tag_keyval(i).key='IEMNRELATIONSHIPID' THEN
431 				g_relation_id:=to_number(l_tag_keyval(i).value);
432 			--12.1.3 Dev
433 			ELSIF l_tag_keyval(i).key='IEMNTHREADID' THEN
434 				l_thread_id:=to_number(l_tag_keyval(i).value);
435 		     END IF;
436 			END LOOP;
437 	END IF;	 -- End Of Retrieving Tag Data if Exists
438 
439 	--12.1.3 Dev
440     	IF l_tag_keyval.count = 0 and l_encrypted_id is not null THEN
441 
442      --siahmed added begin exeption and end block because it was failing in the select stmtnt
443     --for bug 12800961
444    begin
445 		select value into l_thread_id
446 		from IEM_ENCRYPTED_TAG_DTLS
447 		where key ='IEMNTHREADID' and encrypted_id = substr(l_encrypted_id,1,5);
448 
449 		select agent_id into l_agentid from
450 		IEM_ENCRYPTED_TAGS where encrypted_id = substr(l_encrypted_id,1,5);
451    EXCEPTION WHEN OTHERS THEN
452 				l_logmessage:=l_logmessage || '-error while selecting '||sqlerrm;
453 				iem_logger(l_logmessage);
454 
455    END;
456 	END IF;
457 
458 /*
459 fix for bug 13797286 . Don't insert into IEM_THREAD_DTLS if the message is redirected or rerouted.
460 */
461 
462 
463 	IF l_thread_id IS NOT NULL AND nvl(l_post_rec.msg_status,'NEW') not in
464 	('REDIRECT','REROUTE') THEN
465 
466 
467 	if g_statement_log then
468 		l_logmessage:='start insertion to  IEM_THREAD_DTLS';
469 		iem_logger(l_logmessage);
470 	end if;
471 
472 		insert into IEM_THREAD_DTLS(
473 		THREAD_ID,
474 		MESSAGE_ID,
475 		MESSAGE_TYPE,
476 		CREATED_BY,
477 		CREATION_DATE,
478 		LAST_UPDATED_BY,
479 		LAST_UPDATE_DATE,
480 		LAST_UPDATE_LOGIN)
481 		values(l_thread_id, l_post_rec.message_id,'I',l_agentid,sysdate, l_agentid,sysdate,l_agentid);
482 	END IF;
483 	--End of 12.1.3 dev changes
484 
485 	/* If interaction id exists in pre mdt , then the current processing should have that Id as the parent IH Id */
486 
487 	If l_post_rec.ih_interaction_id is not null then
488 
489 
490 		if g_statement_log then
491 			l_logmessage:='ih_interaction_id is not null';
492 			iem_logger(l_logmessage);
493 		end if;
494 		l_ih_id:=l_post_rec.ih_interaction_id;
495 	end if;
496 
497 -- Getting the customer Id for Interaction creation and passing it to all the rules engine. First we check
498 -- if the tag contain the customer id or not. If yes we used that first. Otherwise we check whether based
499 -- on email_address pre-processing able to retrieve a single hit customer id and use that.
500 -- Retrieve only the Email Address from From String in the BASE HEADER TABLE
501 
502 
503 	if g_statement_log then
504 		l_logmessage:=' Email Address from From String in the BASE HEADER TABLE : '||l_header_rec.from_str;
505 		iem_logger(l_logmessage);
506 	end if;
507 	l_from1:=instr(l_header_rec.from_str,'<',-1,1);
508 	l_from2:=instr(l_header_rec.from_str,'>',-1,1);
509 
510 
511 
512 	IF l_from1>0 then		-- From Address Contains Both Name and Address
513 		l_sender:=substr(l_header_rec.from_Str,l_from1+1,l_from2-l_from1-1);
514 	ELSE					-- From Address contains only Address
515 		l_sender:=l_header_rec.from_str;
516 	END IF;
517 
518 -- getting contact id for internal employee from the email address of
519 --the sender
520 	-- added another condition g_contact_id IS NULL. Employee Search. shramana
521 	if l_acct_Type='I' AND g_contact_id IS NULL then
522  		BEGIN
523 
524 
525 
526      --fix siahmed for bug 13702109
527      --if this fails it will go to exception block anyways
528       -- no need to validation here.
529 
530   		 Select person_id into l_contact_id
531   		 from per_workforce_current_x
532   		 Where upper(email_address)=upper(l_sender);
533       --end of fix siahmed for bug 13702109
534 
535        				IEM_GETCUST_PVT.GETCUSTOMERID
536  				(p_api_version_number=>1.0,
537  				p_email=>l_sender,
538  				p_party_id=>l_cust_contact_id,
539  				X_MSG_COUNT=>l_msg_count,
540  				X_RETURN_STATUS=>l_ret_status,
541  				X_MSG_DATA=>l_msg_data);
542 		 EXCEPTION
543 		 WHEN OTHERS THEN NULL;
544 		 END;
545 
546 
547 	if g_statement_log then
548 	 l_logmessage:='Get the emp contact Id '||l_cust_contact_id ||' For Sender '||l_sender ;
549 	 iem_logger(l_logmessage);
550 	end if;
551         end if;
552 		IF l_tag_custid is not null THEN
553 				l_customer_id:=l_tag_custid;
554 
555 		ELSE
556 				-- Get the Customer Id
557 		-- GETTING CUSTOMER ID BASED ON EMAIL ADDRESS
558  		BEGIN
559 
560 			if g_statement_log then
561 			 l_logmessage:='getting customer id based on email id' ;
562 			 iem_logger(l_logmessage);
563 			end if;
564  				IEM_GETCUST_PVT.GETCUSTOMERID
565  				(p_api_version_number=>1.0,
566  				p_email=>l_sender,
567  				p_party_id=>l_customer_id,
568  				X_MSG_COUNT=>l_msg_count,
569  				X_RETURN_STATUS=>l_ret_status,
570  				X_MSG_DATA=>l_msg_data);
571 		 EXCEPTION
572 		 WHEN OTHERS THEN NULL;
573 		 END;
574  	 if l_customer_id is null then
575 		l_customer_id:=-1;
576  	 end if;
577 	if g_statement_log then
578 	 l_logmessage:='Get the Customer Id '||l_customer_id ||' For Sender '||l_sender ;
579 	 iem_logger(l_logmessage);
580 	end if;
581 		END IF;
582 
583 
584 		-- CALLING THE CUSTOMISED WORKFLOW
585 		-- Removed the whole section of calling customized workflow --Ranjan
586 -- Calling Route Classification
587 
588 
589 	if g_statement_log then
590 	 l_logmessage:='Calling Route Classification ' ;
591 	 iem_logger(l_logmessage);
592 	end if;
593    For v1 in c_intent LOOP
594 	l_intent_str:=nvl(l_intent_str,' ')||v1.intent;
595 	if l_top_intent is null then
596 		l_top_intent:=v1.intent;
597 		l_top_score:=v1.score;
598      end if;
599    END LOOP;
600 -- Populating the Classification Engine input data
601 
602 	if g_statement_log then
603 	 l_logmessage:='Populating the Classification Engine input data' ;
604 	 iem_logger(l_logmessage);
605 	end if;
606 
607 	if g_statement_log then
608 		l_logmessage:='Start Populating Key value pair for Classification and Routing Processing ';
609 		iem_logger(l_logmessage);
610 	end if;
611 		l_counter:=1;
612 		l_class_val_tbl.delete;
613 
614 
615 	l_class_val_tbl(l_counter).key:='IEMNMESSAGESIZE';
616 	l_class_val_tbl(l_counter).value:=l_header_rec.message_size;
617 	l_class_val_tbl(l_counter).datatype:='N';
618 		l_counter:=l_counter+1;
619 	l_class_val_tbl(l_counter).key:='IEMSSENDERNAME';
620 	l_class_val_tbl(l_counter).value:=l_sender;
621 	l_class_val_tbl(l_counter).datatype:='S';
622 		l_counter:=l_counter+1;
623 	l_class_val_tbl(l_counter).key:='IEMSUSERACCTNAME';
624 	l_class_val_tbl(l_counter).value:=l_email_user_name;
625 	l_class_val_tbl(l_counter).datatype:='S';
626 		l_counter:=l_counter+1;
627 	l_class_val_tbl(l_counter).key:='IEMSDOMAINNAME';
628 	l_class_val_tbl(l_counter).value:=l_email_domain_name;
629 	l_class_val_tbl(l_counter).datatype:='S';
630 	/* this is missing for the time being
631 		l_counter:=l_counter+1;
632 	l_class_val_tbl(l_counter).key:='IEMSPRIORITY';
633 	l_class_val_tbl(l_counter).value:=l_post_rec.priority;
634 	l_class_val_tbl(l_counter).datatype:='S';
635 	*/
636 		l_counter:=l_counter+1;
637 	l_class_val_tbl(l_counter).key:='IEMSSUBJECT';
638 	l_class_val_tbl(l_counter).value:=l_header_rec.subject;
639 	l_class_val_tbl(l_counter).datatype:='S';
640 		l_counter:=l_counter+1;
641 	l_class_val_tbl(l_counter).key:='IEMDRECEIVEDDATE';
642 	l_class_val_tbl(l_counter).value:=to_char(l_post_rec.received_date,'YYYYMMDD');
643 	l_class_val_tbl(l_counter).datatype:='D';
644 		l_counter:=l_counter+1;
645 	l_class_val_tbl(l_counter).key:='IEMTRECEIVEDTIME';
646 	l_class_val_tbl(l_counter).value:=to_char(l_post_rec.received_date,'HH24:MI:SS');
647 	l_class_val_tbl(l_counter).datatype:='T';
648 		l_counter:=l_counter+1;
649 	l_class_val_tbl(l_counter).key:='IEMSEMAILINTENT';
650 	l_class_val_tbl(l_counter).value:=l_top_intent;
651 	l_class_val_tbl(l_counter).datatype:='S';
652 		l_counter:=l_counter+1;
653 	l_class_val_tbl(l_counter).key:='IEMNSCOREPERCENT';
654 	l_class_val_tbl(l_counter).value:=l_top_score;
655 	l_class_val_tbl(l_counter).datatype:='N';
656 		l_counter:=l_counter+1;
657 	l_class_val_tbl(l_counter).key:='IEMSLANGUAGE';
658 	l_class_val_tbl(l_counter).value:=l_header_rec.language;
659 	l_class_val_tbl(l_counter).datatype:='S';
660 		l_counter:=l_counter+1;
661 	l_class_val_tbl(l_counter).key:='IEMSORGANIZATION';
662 	l_class_val_tbl(l_counter).value:=l_header_rec.organization;
663 	l_class_val_tbl(l_counter).datatype:='S';
664 		l_counter:=l_counter+1;
665 	l_class_val_tbl(l_counter).key:='IEMDSYSTEMDATE';
666 	l_class_val_tbl(l_counter).value:=to_char(sysdate,'YYYYMMDD');
667 	l_class_val_tbl(l_counter).datatype:='D';
668 		l_counter:=l_counter+1;
669 	l_class_val_tbl(l_counter).key:='IEMTSYSTEMTIME';
670 	l_class_val_tbl(l_counter).value:=to_char(sysdate,'HH24:MI:SS');
671 	l_class_val_tbl(l_counter).datatype:='T';
672 		l_counter:=l_counter+1;
673 	l_class_val_tbl(l_counter).key:='IEMSTOADDRESS';
674 	l_class_val_tbl(l_counter).value:=l_header_rec.to_str;
675 	l_class_val_tbl(l_counter).datatype:='S';
676 
677 -- New KEYVALUE Pair Containing All Intents Changes MAde for MP-R By RT on 08/01/03
678 		l_counter:=l_counter+1;
679 	l_class_val_tbl(l_counter).key:='IEMSALLINTENTS';
680 	l_class_val_tbl(l_counter).value:=l_intent_str;
681 	l_class_val_tbl(l_counter).datatype:='S';
682 
683 	IF l_wf_custom_val is not null THEN
684 		l_counter:=l_counter+1;
685 	l_class_val_tbl(l_counter).key:='IEMSCUSTOMWFVAL';
686 	l_class_val_tbl(l_counter).value:=l_wf_custom_val;
687 	l_class_val_tbl(l_counter).datatype:='S';
688 	END IF;
689 	IF l_customer_id is not null THEN
690 		l_counter:=l_counter+1;
691 		l_class_val_tbl(l_counter).key:='IEMNCUSTOMERID';
692 		l_class_val_tbl(l_counter).value:=l_customer_id;
693 		l_class_val_tbl(l_counter).datatype:='N';
694 	END IF;
695 
696    IF l_tag_keyval.count>0 THEN
697 	FOR j in l_tag_keyval.FIRST..l_tag_keyval.LAST LOOP
698 		l_counter:=l_counter+1;
699 	l_class_val_tbl(l_counter).key:=l_tag_keyval(j).key;
700 	l_class_val_tbl(l_counter).value:=l_tag_keyval(j).value;
701 	l_class_val_tbl(l_counter).datatype:=l_tag_keyval(j).datatype;
702 	END LOOP;
703   END IF;
704 IF l_post_rec.rt_classification_id is null THEN
705 
706 	if g_statement_log then
707 	 l_logmessage:='rt_classification_id is null ,calling  IEM_CLASSIFICATION_PROC' ;
708 	 iem_logger(l_logmessage);
709 	end if;
710 IEM_EMAIL_PROC_PVT.IEM_CLASSIFICATION_PROC(
711 				p_email_account_id=>l_post_rec.email_account_id,
712 				p_keyval=>l_class_val_tbl   ,
713 			x_rt_classification_id=>l_rt_classification_id,
714 			x_status=>l_status,
715 		     x_out_text=>l_out_text) ;
716 	IF l_status <>'S' THEN
717 	if g_error_log then
718 		l_logmessage:=l_out_text;
719 		iem_logger(l_logmessage);
720 	end if;
721 		raise abort_processing;
722 	END IF;
723 	if g_statement_log then
724 		l_logmessage:='classification engine return route classificaion id '||l_rt_classification_id;
725 		iem_logger(l_logmessage);
726 	end if;
727 ELSE
728 	l_rt_classification_id:=l_post_rec.rt_classification_id;
729 	if g_statement_log then
730 		l_logmessage:='Use Old Classification Engine Value'||l_rt_classification_id||'  did not call Classification Processing again';
731 		iem_logger(l_logmessage);
732 	end if;
733 END IF;			-- End of if rt_classification_id is null
734 
735  BEGIN
736 	select name
737 	into l_folder_name
738 	from iem_route_classifications
739 	where route_classification_id=l_rt_classification_id;
740  EXCEPTION
741 	WHEN OTHERS THEN
742 	if g_exception_log then
743 		l_logmessage:='Error in getting folder name for the route classificaion id '||l_rt_classification_id||' and the error is '||sqlerrm;
744 		iem_logger(l_logmessage);
745 	end if;
746 	raise ABORT_PROCESSING;
747   END;
748 
749 
750 	if g_statement_log then
751 	 l_logmessage:='l_folder_name:'|| l_folder_name;
752 	 iem_logger(l_logmessage);
753 	end if;
754 
755 		l_counter:=l_counter+1;
756 	l_class_val_tbl(l_counter).key:='IEMSROUTINGCLASSIFICATION';
757   l_class_val_tbl(l_counter).value:=l_folder_name;
758 	l_class_val_tbl(l_counter).datatype:='S';
759 
760 				-- *** Open an Interaction  *** --
761 
762      		l_interaction_rec.start_date_time   := sysdate;
763      		l_resource_id:=FND_PROFILE.VALUE_SPECIFIC('IEM_SRVR_ARES') ;
764      			l_interaction_rec.resource_id:=l_resource_id ;
765 
766 
767 			if g_statement_log then
768 			 l_logmessage:='l_resource_id:'|| l_resource_id;
769 			 iem_logger(l_logmessage);
770 			end if;
771 
772 
773 			IF l_interaction_rec.resource_id is NULL THEN
774 				l_logmessage:='Default Resource Id is Not Set For Creating Interaction';
775 			raise ABORT_PROCESSING;
776 			END IF;
777      		l_interaction_rec.handler_id        := 680; -- IEM APPL_ID
778 			IF l_ih_id is not null then
779      			l_interaction_rec.parent_id  := l_ih_id;
780 			end if;
781 		if l_acct_type='I' then -- For internal account type it will come from profile
782      		l_customer_id := FND_PROFILE.VALUE_SPECIFIC('CS_SR_DEFAULT_CUSTOMER_NAME');
783 
784 
785 		if g_statement_log then
786 		 l_logmessage:='l_customer_id from profile CS_SR_DEFAULT_CUSTOMER_NAME : ' || l_customer_id;
787 		 iem_logger(l_logmessage);
788 		end if;
789 
790 
791 
792 		end if;
793 		if l_customer_id >0 then	-- Tag Data or pre processing  contain Customer Id
794      		l_interaction_rec.party_id          := l_customer_id;
795 		else 				-- Pre processing/TAg data  fails to retrun customer id
796 
797 
798 		if g_statement_log then
799 		 l_logmessage:='inside else of  l_customer_id >0 , before calling IEM_GETCUST_PVT.CustomerSearch ';
800 		 iem_logger(l_logmessage);
801 		end if;
802 
803 			IEM_GETCUST_PVT.CustomerSearch(
804  						P_Api_Version_Number=>1.0,
805  						p_email=>l_sender,
806  						x_party_id=>l_cust_search_id,
807  						x_msg_count=>l_msg_count,
808  						x_return_status=>l_ret_status,
809  						x_msg_data=>l_msg_data);
810 
811 
812 		if g_statement_log then
813 		 l_logmessage:='after calling IEM_GETCUST_PVT.CustomerSearch status : '||l_ret_status ||' l_msg_data : '||l_msg_data||' l_cust_search_id :'||l_cust_search_id;
814 		 iem_logger(l_logmessage);
815 		end if;
816 
817 		l_interaction_rec.party_id          := l_cust_search_id;
818 		end if;
819 
820 
821 		if g_statement_log then
822 		 l_logmessage:='l_tag_custid := ' ||l_tag_custid;
823 		 iem_logger(l_logmessage);
824 		end if;
825 
826 
827 		IF l_tag_custid>0 THEN
828 -- Tag DAta return customer contact details. So create the interaction by logging contact,primary party and
829 -- relation id.
830 				BEGIN
831 			 	select PARTY_TYPE into l_party_type from HZ_PARTIES
832 			   	where party_id = l_tag_custid;
833 				EXCEPTION WHEN OTHERS THEN
834 					l_logmessage:='Error in getting Party Type for Party id '||l_tag_custid;
835 					raise ABORT_PROCESSING;
836 				END;
837 
838 
839 				if g_statement_log then
840 				 l_logmessage:='l_party_type : '||l_party_type;
841 				 iem_logger(l_logmessage);
842 				end if;
843 
844 				IF l_party_type='PERSON' THEN
845 					 l_interaction_rec.primary_party_id:=l_tag_custid;
846 					 l_interaction_rec.contact_party_id:=l_tag_custid;
847 					 l_interaction_rec.contact_rel_party_id:=null;
848   				ELSIF ( l_party_type = 'ORGANIZATION') then
849 					 l_interaction_rec.primary_party_id:=l_tag_custid;
850     					 if ( g_contact_id > 0 ) then
851       					if ( (g_relation_id < 0)  OR (g_relation_id is null)) then
852 					 		l_interaction_rec.contact_party_id:=null;
853 					 		l_interaction_rec.contact_rel_party_id:=null;
854 						else
855 							l_interaction_rec.contact_rel_party_id:=g_relation_id;
856 							l_interaction_rec.contact_party_id:=g_contact_id;
857       					end if;
858     					else
859 					 		l_interaction_rec.contact_party_id:=null;
860 					 		l_interaction_rec.contact_rel_party_id:=null;
861     					end if;
862 			    ELSE				--- For PARTY_RELATIONSHIP
863 					 l_interaction_rec.primary_party_id:=null;
864 					 l_interaction_rec.contact_party_id:=null;
865 					 l_interaction_rec.contact_rel_party_id:=null;
866 			END IF;
867            END IF;			-- end if for if l_tag_custid>0
868 
869 	-- if account type is internal use employee party id as contact id for
870         --creating interaction
871 	--checking for l_cust_contact_id for bug 8337656, Sanjana Rao
872 
873 				if l_acct_type='I' then
874 				    if l_cust_contact_id > 0 then
875 					 l_interaction_rec.contact_party_id:=l_cust_contact_id;
876 					 -- Ranjan for bug 7018980 so that outbound interaction
877 					 -- has employee id as contact id;
878 					 g_contact_id:=l_cust_contact_id;
879 				    --added an elsif for Employee Search. shramana
880 				    -- use g_contact_id if it's populated from TAG DTLS
881 				    elsif g_contact_id > 0 then
882 					l_interaction_rec.contact_party_id:=g_contact_id;
883 				    end if;
884 					 l_interaction_rec.primary_party_id:=l_customer_id;
885 				end if;
886 IF l_post_rec.ih_interaction_id is not null and l_post_rec.msg_status='REDIRECT' THEN --chk auto redirected
887 	l_interaction_id:=l_post_rec.ih_interaction_id;
888 	if g_statement_log then
889 		l_logmessage:='New Interaction is not created and use old one for Redirect message  ';
890 		iem_logger(l_logmessage);
891 	end if;
892 ELSE
893 
894 			if g_statement_log then
895 			 l_logmessage:='Start calling add interaction';
896 			 iem_logger(l_logmessage);
897 			end if;
898 
899 			IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
900 				p_type=>'INTERACTION'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
901 				p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
902 				p_interaction_rec=>l_interaction_rec,
903 				p_activity_rec=>l_activity_rec     ,
904 				p_media_lc_rec=>l_media_lc_Rec ,
905 				p_media_rec=>l_media_rec	,
906 				x_id=>l_interaction_id,
907 				x_status=>l_stat		,
908 			     x_out_text=>l_out_text	);
909 
910 
911 				if g_statement_log then
912 				 l_logmessage:='status in IEM_EMAIL_PROC_PVT.IEM_PROC_IH : ' ||l_stat || 'l_out_text : '|| l_out_text;
913 				 iem_logger(l_logmessage);
914 				end if;
915 
916 			    	select contact_party_id into l_cust_contact_id from jtf_ih_interactions
917 				where interaction_id=l_interaction_id;
918 
919 
920 				if g_statement_log then
921 				 l_logmessage:='after calling add interaction : status :'||l_stat || 'text : '||l_out_text || 'l_interaction_id : '||l_interaction_id;
922 				 iem_logger(l_logmessage);
923 				end if;
924 
925 
926 		IF l_stat<>'S' THEN
927 				l_logmessage:=l_out_text;
928 				raise ABORT_PROCESSING;
929 			END IF;
930 END IF;		-- End of chk auto redirected
931 		-- Add Interaction ID as key value Pair
932 		l_counter:=l_counter+1;
933 		l_class_val_tbl(l_counter).key:='IEMNINTERACTIONID';
934 		l_class_val_tbl(l_counter).value:=l_interaction_id;
935 		l_class_val_tbl(l_counter).datatype:='N';
936 l_routing_classification:=l_folder_name;
937 IF lengthb(l_header_rec.subject)>80 then
938      l_ih_subject:=substrb(l_header_rec.subject,1,80);
939 ELSE
940      l_ih_subject:=l_header_rec.subject;
941 END IF;
942 IF l_post_rec.ih_media_item_id is null THEN		-- Normal Mail Proc create media
943     l_media_rec.media_id := NULL;
944     l_media_rec.source_id := l_post_rec.email_account_id;
945 	l_media_rec.direction:= 'INBOUND';
946     l_media_rec.start_date_time := sysdate;
947     l_media_rec.media_item_type := 'EMAIL';
948     l_media_rec.media_item_ref := l_post_rec.message_id;  -- Change for 11iX
949     l_media_rec.media_data := l_ih_subject;
950     l_media_rec.classification := l_routing_classification;
951     l_media_rec.address := l_sender; --new on MP-R 07/23/03 by rtripath
952 
953 
954 
955 	if g_statement_log then
956 	l_logmessage:='Before calling add IEM_EMAIL_PROC_PVT.IEM_PROC_IH media';
957 	iem_logger(l_logmessage);
958 	end if;
959 
960    IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
961 				p_type=>'MEDIA'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
962 				p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
963 				p_interaction_rec=>l_interaction_rec,
964 				p_activity_rec=>l_activity_rec     ,
965 				p_media_lc_rec=>l_media_lc_Rec ,
966 				p_media_rec=>l_media_rec	,
967 				x_id=>l_media_id,
968 				x_status=>l_stat		,
969 			     x_out_text=>l_out_text	);
970 
971 
972 
973 	if g_statement_log then
974 	l_logmessage:='After calling IEM_EMAIL_PROC_PVT.IEM_PROC_IH media: status : '||l_stat || 'text : '|| l_out_text || 'l_media_id : ' ||l_media_id;
975 	iem_logger(l_logmessage);
976 	end if;
977 
978 			IF l_stat<>'S' THEN
979 				l_logmessage:=l_out_text;
980 				raise ABORT_PROCESSING;
981 			END IF;
982 ELSE									-- Rerouted Message Need to update the media item
983 	l_media_rec.media_id:=l_post_rec.ih_media_item_id;
984      l_media_rec.source_id := l_post_rec.email_account_id;
985      l_media_rec.classification := l_routing_classification;
986      l_media_rec.address := l_sender; --new on MP-R 07/23/03 by rtripath
987 
988 
989 	if g_statement_log then
990 	l_logmessage:='Before calling update IEM_EMAIL_PROC_PVT.IEM_PROC_IH media';
991 	iem_logger(l_logmessage);
992 	end if;
993 
994 
995 			IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
996 				p_type=>'MEDIA'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
997 				p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
998 				p_interaction_rec=>l_interaction_rec,
999 				p_activity_rec=>l_activity_rec     ,
1000 				p_media_lc_rec=>l_media_lc_Rec ,
1001 				p_media_rec=>l_media_rec	,
1002 				x_id=>l_media_id,
1003 				x_status=>l_stat		,
1004 			     x_out_text=>l_out_text	);
1005 
1006 
1007 
1008 		if g_statement_log then
1009 		l_logmessage:='After calling IEM_EMAIL_PROC_PVT.IEM_PROC_IH media update: status : '||l_stat || 'text : '|| l_out_text || 'l_media_id : ' ||l_media_id;
1010 		iem_logger(l_logmessage);
1011 		end if;
1012 			IF l_stat<>'S' THEN
1013 				l_logmessage:=l_out_text;
1014 				raise ABORT_PROCESSING;
1015 			END IF;
1016 			l_media_id:=l_post_rec.ih_media_item_id;
1017 END IF;
1018 		-- Add Media Id to the key value Pair
1019 		l_counter:=l_counter+1;
1020 		l_class_val_tbl(l_counter).key:='IEMNMEDIAID';
1021 		l_class_val_tbl(l_counter).value:=l_media_id;
1022 		l_class_val_tbl(l_counter).datatype:='N';
1023 
1024 		-- Take out SOURCEMESSAGEID in 11iX as an input to Rules/ClassificationEngine
1025 
1026 		l_counter:=l_counter+1;
1027 		l_class_val_tbl(l_counter).key:='IEMNMESSAGEID';
1028 		l_class_val_tbl(l_counter).value:=l_post_rec.message_id;
1029 		l_class_val_tbl(l_counter).datatype:='N';
1030 
1031 	-- Create a Media Life Cycle for Mail Preprocessing
1032 
1033   l_media_lc_rec.media_id :=l_media_id ;
1034   l_media_lc_rec.milcs_type_id := 16; --MAIL_PREPROCESSING
1035   IF l_post_rec.ih_media_item_id is null THEN -- normal message
1036   	l_media_lc_rec.start_date_time := l_post_rec.received_date;
1037   else
1038 	l_media_lc_rec.start_date_time :=sysdate;		-- for reroute/redirected message
1039   end if;
1040   l_media_lc_rec.handler_id := 680;
1041   l_media_lc_rec.type_type := 'Email, Inbound';
1042 
1043 
1044 
1045 		if g_statement_log then
1046 		l_logmessage:='Before calling update IEM_EMAIL_PROC_PVT.IEM_PROC_IH MLCS add';
1047 		iem_logger(l_logmessage);
1048 		end if;
1049 
1050 IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1051 				p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1052 				p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
1053 				p_interaction_rec=>l_interaction_rec,
1054 				p_activity_rec=>l_activity_rec     ,
1055 				p_media_lc_rec=>l_media_lc_Rec ,
1056 				p_media_rec=>l_media_rec	,
1057 				x_id=>l_milcs_id,
1058 				x_status=>l_stat		,
1059 			     x_out_text=>l_out_text	);
1060 
1061 
1062 		if g_statement_log then
1063 		l_logmessage:='After calling update IEM_EMAIL_PROC_PVT.IEM_PROC_IH MLCS add :status : '||l_stat ||' text : '||l_out_text||' l_milcs_id :'||l_milcs_id;
1064 		iem_logger(l_logmessage);
1065 		end if;
1066 
1067 			IF l_stat<>'S' THEN
1068 				l_logmessage:=l_out_text;
1069 				raise ABORT_PROCESSING;
1070 			END IF;
1071 
1072 	-- Update  the Media Life Cycle for Mail Preprocessing
1073   l_media_lc_rec.milcs_id:=l_milcs_id;
1074 
1075 IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1076 				p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1077 				p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
1078 				p_interaction_rec=>l_interaction_rec,
1079 				p_activity_rec=>l_activity_rec     ,
1080 				p_media_lc_rec=>l_media_lc_Rec ,
1081 				p_media_rec=>l_media_rec	,
1082 				x_id=>l_milcs_id,
1083 				x_status=>l_stat		,
1084 			     x_out_text=>l_out_text	);
1085 
1086 
1087 		if g_statement_log then
1088 		l_logmessage:='After calling update IEM_EMAIL_PROC_PVT.IEM_PROC_IH MLCS add :status : '||l_stat ||' text : '||l_out_text||' l_milcs_id :'||l_milcs_id;
1089 		iem_logger(l_logmessage);
1090 		end if;
1091 
1092 			IF l_stat<>'S' THEN
1093 				l_logmessage:=l_out_text;
1094 				raise ABORT_PROCESSING;
1095 			END IF;
1096 
1097 	-- Create a Media Life Cycle for Mail Processing
1098   l_media_lc_rec.media_id :=l_media_id ;
1099   l_media_lc_rec.milcs_type_id := 17; --MAIL_PROCESSING
1100   l_media_lc_rec.start_date_time := sysdate;
1101   l_media_lc_rec.handler_id := 680;
1102   l_media_lc_rec.type_type := 'Email, Inbound';
1103 
1104 
1105 		if g_statement_log then
1106 		l_logmessage:='Before calling update IEM_EMAIL_PROC_PVT.IEM_PROC_IH MLCS update';
1107 		iem_logger(l_logmessage);
1108 		end if;
1109 
1110 	IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1111 				p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1112 				p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
1113 				p_interaction_rec=>l_interaction_rec,
1114 				p_activity_rec=>l_activity_rec     ,
1115 				p_media_lc_rec=>l_media_lc_Rec ,
1116 				p_media_rec=>l_media_rec	,
1117 				x_id=>l_mp_milcs_id,
1118 				x_status=>l_stat		,
1119 			     x_out_text=>l_out_text	);
1120 
1121 
1122 		if g_statement_log then
1123 		l_logmessage:='After calling update IEM_EMAIL_PROC_PVT.IEM_PROC_IH MLCS update :status : '||l_stat ||' text : '||l_out_text||' l_milcs_id :'||l_milcs_id;
1124 		iem_logger(l_logmessage);
1125 		end if;
1126 
1127 			IF l_stat<>'S' THEN
1128 				l_logmessage:=l_out_text;
1129 				raise ABORT_PROCESSING;
1130 			END IF;
1131 -- this is the new default activity for each mail that undergoes processing. Introduced in 11510.
1132 			-- Add a Activity for EMAILPROCESSING
1133      				l_activity_rec.start_date_time   := SYSDATE;
1134 	       			l_activity_rec.media_id          := l_media_id;
1135          				l_activity_rec.action_id         := 95;	-- EMAILPROCESSED
1136          				l_activity_rec.interaction_id    := l_interaction_id;
1137          				l_activity_rec.action_item_id    := 45;-- EMAIL
1138 
1139 
1140 		if g_statement_log then
1141 		l_logmessage:='Before calling  IEM_EMAIL_PROC_PVT.IEM_PROC_IH MLCS add for 17';
1142 		iem_logger(l_logmessage);
1143 		end if;
1144 
1145 		IEM_EMAIl_PROC_PVT.IEM_PROC_IH(
1146 				p_type=>'ACTIVITY'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1147 				p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
1148 				p_interaction_rec=>l_interaction_rec,
1149 				p_activity_rec=>l_activity_rec     ,
1150 				p_media_lc_rec=>l_media_lc_Rec ,
1151 				p_media_rec=>l_media_rec	,
1152 				x_id=>l_activity_id,
1153 				x_status=>l_stat		,
1154 			     x_out_text=>l_out_text	);
1155 
1156 
1157 
1158 		if g_statement_log then
1159 		l_logmessage:='After calling IEM_EMAIL_PROC_PVT.IEM_PROC_IH MLCS add for 17:status : '||l_stat ||' text : '||l_out_text||' l_milcs_id :'||l_milcs_id;
1160 		iem_logger(l_logmessage);
1161 		end if;
1162 
1163 			IF l_stat<>'S' THEN
1164 				l_logmessage:=l_out_text;
1165 				raise ABORT_PROCESSING;
1166 			END IF;
1167 
1168 -- Calling Auto Processing Engine For 'AUTODELETE'
1169 	iem_rules_engine_pub.auto_process_email(p_api_version_number=>1.0,
1170 									p_commit=>FND_API.G_FALSE,
1171 									p_rule_type=>'AUTODELETE',
1172 									p_keyvals_tbl=>l_class_val_tbl,
1173 									p_accountid=>l_post_rec.email_account_id,
1174 									x_result=>l_autoproc_result,
1175 									x_action=>l_action,
1176 									x_parameters=>l_param_rec_tbl,
1177 									x_return_status=>l_ret_status,
1178 									x_msg_count=>l_msg_count,
1179 									x_msg_data=>l_msg_data);
1180 			IF l_ret_status<>'S' THEN
1181 				l_logmessage:='Error While Calling rules Engine for Autodelete';
1182 				raise ABORT_PROCESSING;
1183 			END IF;
1184 	IF l_autoproc_result='T' THEN		-- Delete the message
1185 	 -- Create a New MLCS for AUTO_DELETE
1186   		l_media_lc_rec.media_id :=l_media_id ;
1187   		l_media_lc_rec.milcs_type_id := 42; --EMAIL_AUTO_DELETE
1188   		l_media_lc_rec.start_date_time := sysdate;
1189   		l_media_lc_rec.handler_id := 680;
1190   		l_media_lc_rec.type_type := 'Email, Inbound';
1191 
1192 
1193 
1194 		if g_statement_log then
1195 		l_logmessage:='Before call to add activity IEM_EMAIl_PROC_PVT.IEM_PROC_IH';
1196 		iem_logger(l_logmessage);
1197 		end if;
1198 
1199 		IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1200 				p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1201 				p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
1202 				p_interaction_rec=>l_interaction_rec,
1203 				p_activity_rec=>l_activity_rec     ,
1204 				p_media_lc_rec=>l_media_lc_Rec ,
1205 				p_media_rec=>l_media_rec	,
1206 				x_id=>l_milcs_id,
1207 				x_status=>l_stat		,
1208 			     x_out_text=>l_out_text	);
1209 
1210 
1211 		if g_statement_log then
1212 		l_logmessage:='After call to add activity IEM_EMAIl_PROC_PVT.IEM_PROC_IH status : '||l_stat ||' text : '||l_out_text||' l_activity_id : '||l_activity_id;
1213 		iem_logger(l_logmessage);
1214 		end if;
1215 			IF l_stat<>'S' THEN
1216 				l_logmessage:=l_out_text;
1217 				raise ABORT_PROCESSING;
1218 			END IF;
1219 			-- Update  the Media Life Cycle for Auto Delete
1220  			 l_media_lc_rec.milcs_id:=l_milcs_id;
1221 
1222 
1223 		if g_statement_log then
1224 		l_logmessage:='Before call to add activity IEM_EMAIl_PROC_PVT.IEM_PROC_IH';
1225 		iem_logger(l_logmessage);
1226 		end if;
1227 
1228 			IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1229 				p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1230 				p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
1231 				p_interaction_rec=>l_interaction_rec,
1232 				p_activity_rec=>l_activity_rec     ,
1233 				p_media_lc_rec=>l_media_lc_Rec ,
1234 				p_media_rec=>l_media_rec	,
1235 				x_id=>l_milcs_id,
1236 				x_status=>l_stat		,
1237 			     x_out_text=>l_out_text	);
1238 
1239 
1240 		if g_statement_log then
1241 		l_logmessage:='After call to add activity IEM_EMAIl_PROC_PVT.IEM_PROC_IH status : '||l_stat ||' text : '||l_out_text||' l_activity_id : '||l_activity_id;
1242 		iem_logger(l_logmessage);
1243 		end if;
1244 
1245 			IF l_stat<>'S' THEN
1246 				l_logmessage:=l_out_text;
1247 				raise ABORT_PROCESSING;
1248 			END IF;
1249 
1250 			-- Add a Activity for AUTO-DELETE
1251      				l_activity_rec.start_date_time   := SYSDATE;
1252 	       			l_activity_rec.media_id          := l_media_id;
1253          				l_activity_rec.action_id         := 72;	-- EMAIL AUTO _DELETED
1254          				l_activity_rec.interaction_id    := l_interaction_id;
1255          				l_activity_rec.action_item_id    := 45;-- EMAIL
1256 
1257 
1258 		if g_statement_log then
1259 		l_logmessage:='Before call to add activity IEM_EMAIl_PROC_PVT.IEM_PROC_IH';
1260 		iem_logger(l_logmessage);
1261 		end if;
1262 
1263 		IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1264 				p_type=>'ACTIVITY'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1265 				p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
1266 				p_interaction_rec=>l_interaction_rec,
1267 				p_activity_rec=>l_activity_rec     ,
1268 				p_media_lc_rec=>l_media_lc_Rec ,
1269 				p_media_rec=>l_media_rec	,
1270 				x_id=>l_activity_id,
1271 				x_status=>l_stat		,
1272 			     x_out_text=>l_out_text	);
1273 
1274 
1275 		if g_statement_log then
1276 		l_logmessage:='After call to add activity IEM_EMAIl_PROC_PVT.IEM_PROC_IH status : '||l_stat ||' text : '||l_out_text||' l_activity_id : '||l_activity_id;
1277 		iem_logger(l_logmessage);
1278 		end if;
1279 
1280 			IF l_stat<>'S' THEN
1281 				l_logmessage:=l_out_text;
1282 				raise ABORT_PROCESSING;
1283 			END IF;
1284 
1285 
1286 		if g_statement_log then
1287 		l_logmessage:='before calling IEM_RT_PROC_EMAILS_PVT.create_item';
1288 		iem_logger(l_logmessage);
1289 		end if;
1290 		IEM_RT_PROC_EMAILS_PVT.create_item (
1291 					p_api_version_number => 1.0,
1292   					p_init_msg_list=>'F' ,
1293 					p_commit=>'F',
1294 				p_message_id =>l_post_rec.message_id,
1295 				p_email_account_id  =>l_post_rec.email_account_id,
1296 				p_priority  =>l_post_rec.priority,
1297 				p_agent_id  =>-1,
1298 				p_group_id  =>-1,
1299 				p_sent_date =>l_header_Rec.sent_date,
1300 				p_received_date =>l_post_Rec.received_Date,
1301 				p_rt_classification_id =>l_rt_classification_id,
1302 				p_customer_id=>l_customer_id    ,
1303 				p_contact_id=>g_contact_id    ,
1304 				p_relationship_id=>g_relation_id    ,
1305 				p_interaction_id=>l_interaction_id ,
1306 				p_ih_media_item_id=>l_media_id ,
1307 				p_msg_status=>l_post_rec.msg_status  ,
1308 				p_mail_proc_status=>'D' ,
1309 				p_mail_item_status=>null ,
1310 				p_category_map_id=>null ,
1311 				p_rule_id=>l_rule_id,
1312 				p_subject=>l_header_rec.subject,
1313 				p_sender_address=>l_sender,
1314 				p_from_agent_id=>null,
1315      			x_return_status=>l_ret_status	,
1316   				x_msg_count=>l_msg_count	      ,
1317  				x_msg_data=>l_msg_data);
1318 
1319 
1320 			if g_statement_log then
1321 			l_logmessage:='After call to IEM_RT_PROC_EMAILS_PVT.create_item status :'||l_ret_status||' l_msg_data : '||l_msg_data;
1322 			iem_logger(l_logmessage);
1323 			end if;
1324 
1325 			IF l_ret_status<>'S' THEN
1326 				l_logmessage:='AUTODELETE:Error While Inserting Record in Proc Emails Table ';
1327 				raise ABORT_PROCESSING;
1328 			END IF;
1329 
1330 -- This wrapup procedure will close the interaction and media and Stamp the message as Deleted in Archived Table.
1331 
1332 			if g_statement_log then
1333 			l_logmessage:='before call to IEM_EMAIL_PROC_PVT.IEM_WRAPUP';
1334 			iem_logger(l_logmessage);
1335 			end if;
1336 
1337 			IEM_EMAIL_PROC_PVT.IEM_WRAPUP(p_interaction_id=>l_interaction_id,
1338 					p_media_id=>l_media_id		,
1339 					p_milcs_id=>l_mp_milcs_id,
1340 					p_action=>'D',
1341 					p_email_rec =>l_post_rec,
1342 					p_action_id=>72,
1343 					x_out_text=>l_out_text,
1344 					x_status=>l_stat );
1345 
1346 			if g_statement_log then
1347 			l_logmessage:='After call to IEM_EMAIL_PROC_PVT.IEM_WRAPUP status : '||l_stat ||' text : '||l_out_text;
1348 			iem_logger(l_logmessage);
1349 			end if;
1350 
1351 			IF l_stat<>'S' THEN
1352 				l_logmessage:='Error in Auto Delete '||l_out_text;
1353 				raise ABORT_PROCESSING;
1354 			ELSE						-- success in deleting the message
1355 				raise STOP_PROCESSING;
1356 			END IF;
1357 	END IF;
1358 
1359 	-- Calling Rules Engine for autoacknowledge
1360 	IF l_post_rec.ih_media_item_id is not null then	--chk  autoack for rerouted message
1361 		l_autoack_count:=0;
1362 		select count(*) into l_autoack_count
1363 		from jtf_ih_media_item_lc_segs
1364 		where media_id=l_post_rec.ih_media_item_id
1365 		and MILCS_TYPE_ID=29;
1366 	END IF;
1367 	IF l_autoack_count=0 then		--not auto acked yet  for this message
1368 			l_autoack_flag:='N';
1369 
1370 
1371 			if g_statement_log then
1372 			l_logmessage:='Calling Autoack RE iem_rules_engine_pub.auto_process_email';
1373 			iem_logger(l_logmessage);
1374 			end if;
1375 		iem_rules_engine_pub.auto_process_email(p_api_version_number=>1.0,
1376 									p_commit=>FND_API.G_FALSE,
1377 									p_rule_type=>'AUTOACKNOWLEDGE',
1378 									p_keyvals_tbl=>l_class_val_tbl,
1379 									p_accountid=>l_post_rec.email_account_id,
1380 									x_result=>l_autoproc_result,
1381 									x_action=>l_action,
1382 									x_parameters=>l_param_rec_tbl,
1383 									x_return_status=>l_ret_status,
1384 									x_msg_count=>l_msg_count,
1385 									x_msg_data=>l_msg_data);
1386 
1387 			if g_statement_log then
1388 			l_logmessage:='End of calling  Autoack RE iem_rules_engine_pub.auto_process_email : status : '||l_ret_status ||' l_msg_data : '||l_msg_data;
1389 			iem_logger(l_logmessage);
1390 			end if;
1391 				IF l_ret_status<>'S' THEN
1392 				l_logmessage:='Error While Calling rules Engine for Autoacknowledgement';
1393 					raise ABORT_PROCESSING;
1394 				END IF;
1395 		IF l_autoproc_result='T' THEN
1396 						FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
1397 							l_doc_id:=l_param_rec_tbl(l_param_index).parameter2;
1398 							EXIT;
1399 						END LOOP;
1400 			l_autoack_flag:='Y';
1401 		END IF;			-- For Autoack rule processing
1402 	END IF;					-- for if autaock=0
1403 	-- Calling Rules Engine for AutoProcessing
1404 					l_param_rec_tbl.delete;
1405 
1406 			if g_statement_log then
1407 			l_logmessage:='Calling auto processing RE iem_rules_engine_pub.auto_process_email';
1408 			iem_logger(l_logmessage);
1409 			end if;
1410 	iem_rules_engine_pub.auto_process_email(p_api_version_number=>1.0,
1411 									p_commit=>FND_API.G_FALSE,
1412 									p_rule_type=>'AUTOPROCESSING',
1413 									p_keyvals_tbl=>l_class_val_tbl,
1414 									p_accountid=>l_post_rec.email_account_id,
1415 									x_result=>l_autoproc_result,
1416 									x_action=>l_action,
1417 									x_parameters=>l_param_rec_tbl,
1418 									x_return_status=>l_ret_status,
1419 									x_msg_count=>l_msg_count,
1420 									x_msg_data=>l_msg_data);
1421 
1422 
1423 					if g_statement_log then
1424 					l_logmessage:='End Calling auto processing RE status : '||l_ret_status ||'data : '|| l_msg_data ||' result : '||l_autoproc_result||' action : '|| l_action;
1425 					iem_logger(l_logmessage);
1426 					end if;
1427 
1428 					IF l_ret_status<>'S' THEN
1429 						l_logmessage:='Error While Calling rules Engine for Autoprocessing';
1430 						raise ABORT_PROCESSING;
1431 					END IF;
1432 
1433 			IF l_autoproc_result='T' THEN
1434 				IF l_action='EXECPROCEDURE' THEN
1435 				   IF ((l_post_rec.ih_media_item_id is not null) and
1436 				      (FND_PROFILE.VALUE_SPECIFIC('IEM_RERUN_CUSTOM_PROCEDURE')='N')) THEN
1437 					if g_statement_log then
1438 						l_logmessage:='Not Executing Custom Procedure Again ';
1439 						iem_logger(l_logmessage);
1440 
1441 					end if;
1442 				    ELSE
1443 
1444 						FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
1445 							l_proc_name:=l_param_rec_tbl(l_param_index).parameter1;
1446 
1447 							EXIT;
1448 						END LOOP;
1449 					IF l_proc_name is not null THEN
1450 							l_run_proc_tbl.delete;
1451 							l_tbl_counter:=1;
1452 							FOR i in l_class_val_tbl.first..l_class_val_tbl.last LOOP
1453 								l_run_proc_tbl(l_tbl_counter).key:=l_class_val_tbl(i).key;
1454 								l_run_proc_tbl(l_tbl_counter).value:=l_class_val_tbl(i).value;
1455 								l_run_proc_tbl(l_tbl_counter).datatype:=l_class_val_tbl(i).datatype;
1456 								l_tbl_counter:=l_tbl_counter+1;
1457 							END LOOP;
1458 						IEM_TAG_RUN_PROC_PVT.run_Procedure (
1459                 						 p_api_version_number=>1.0  ,
1460             							 p_procedure_name=>l_proc_name      ,
1461   									 p_key_value =>l_run_proc_tbl,
1462                  						x_result=>l_result              ,
1463                						x_return_status=>l_ret_status	   ,
1464   		  	    						x_msg_count=>l_msg_count,
1465 	  	  	     					x_msg_data=>l_msg_data);
1466 			          	IF l_ret_status='E' THEN
1467 				     		l_logmessage:='Error While Executing  Custom Procedure';
1468 				     		raise ABORT_PROCESSING;
1469 				     	ELSE
1470 				     		IF l_result='N' THEN
1471      					l_activity_rec.start_date_time   := SYSDATE;
1472 	       				l_activity_rec.media_id          := l_media_id;
1473          					l_activity_rec.action_id         := 65;	-- EMAIL Resolved No Reply
1474          					l_activity_rec.interaction_id    := l_interaction_id;
1475          					l_activity_rec.action_item_id    := 45;-- EMAIL
1476 
1477 
1478 						if g_statement_log then
1479 						l_logmessage:='Calling add activity IEM_EMAIL_PROC_PVT.IEM_PROC_IH for action id 65';
1480 						iem_logger(l_logmessage);
1481 						end if;
1482 
1483 						IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1484 								p_type=>'ACTIVITY'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1485 								p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
1486 								p_interaction_rec=>l_interaction_rec,
1487 								p_activity_rec=>l_activity_rec     ,
1488 								p_media_lc_rec=>l_media_lc_Rec ,
1489 								p_media_rec=>l_media_rec	,
1490 								x_id=>l_activity_id,
1491 								x_status=>l_stat		,
1492 			     				x_out_text=>l_out_text	);
1493 
1494 
1495 						if g_statement_log then
1496 						l_logmessage:='after Calling add activity IEM_EMAIL_PROC_PVT.IEM_PROC_IH for action id 65 status : '||l_stat||' text : '||l_out_text||' act id : '||l_activity_id;
1497 						iem_logger(l_logmessage);
1498 						end if;
1499 
1500 							IF l_stat<>'S' THEN
1501 								l_logmessage:=l_out_text;
1502 								raise ABORT_PROCESSING;
1503 							END IF;
1504   							l_media_lc_rec.media_id :=l_media_id ;
1505   							l_media_lc_rec.milcs_type_id := 31; --EMAIL_AUTO_RESOLVED
1506   							l_media_lc_rec.start_date_time := sysdate;
1507   							l_media_lc_rec.handler_id := 680;
1508   							l_media_lc_rec.type_type := 'Email, Inbound';
1509 
1510 
1511 
1512 							if g_statement_log then
1513 							l_logmessage:='Calling add MLCS IEM_EMAIL_PROC_PVT.IEM_PROC_IH for milcs id 31 ';
1514 							iem_logger(l_logmessage);
1515 							end if;
1516 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1517 									p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1518 									p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
1519 									p_interaction_rec=>l_interaction_rec,
1520 									p_activity_rec=>l_activity_rec     ,
1521 									p_media_lc_rec=>l_media_lc_Rec ,
1522 									p_media_rec=>l_media_rec	,
1523 									x_id=>l_milcs_id,
1524 									x_status=>l_stat		,
1525 			     					x_out_text=>l_out_text	);
1526 
1527 
1528 							if g_statement_log then
1529 							l_logmessage:='After add MLCS IEM_EMAIL_PROC_PVT.IEM_PROC_IH for milcs id 31 staus : '||l_stat||' text : '||l_out_text||' l_milcs_id : '||l_milcs_id;
1530 							iem_logger(l_logmessage);
1531 							end if;
1532 
1533 								IF l_stat<>'S' THEN
1534 									l_logmessage:=l_out_text;
1535 									raise ABORT_PROCESSING;
1536 								END IF;
1537 			-- Update  the Media Life Cycle for Auto Resolve
1538  			 l_media_lc_rec.milcs_id:=l_milcs_id;
1539 
1540 
1541 							if g_statement_log then
1542 							l_logmessage:='Calling update MLCS IEM_EMAIL_PROC_PVT.IEM_PROC_IH for milcs id 31 ';
1543 							iem_logger(l_logmessage);
1544 							end if;
1545 
1546 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1547 								p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
1548 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
1549 								p_interaction_rec=>l_interaction_rec,
1550 								p_activity_rec=>l_activity_rec     ,
1551 								p_media_lc_rec=>l_media_lc_Rec ,
1552 								p_media_rec=>l_media_rec	,
1553 								x_id=>l_milcs_id,
1554 								x_status=>l_stat		,
1555 			     				x_out_text=>l_out_text	);
1556 
1557 
1558 
1559 							if g_statement_log then
1560 							l_logmessage:='After update MLCS IEM_EMAIL_PROC_PVT.IEM_PROC_IH for milcs id 31 staus : '||l_stat||' text : '||l_out_text||' l_milcs_id : '||l_milcs_id;
1561 							iem_logger(l_logmessage);
1562 							end if;
1563 
1564 							IF l_stat<>'S' THEN
1565 								l_logmessage:=l_out_text;
1566 								raise ABORT_PROCESSING;
1567 							END IF;
1568 		-- Create a Record in IEM_RT_PROC_EMAILS
1569 
1570 
1571 		if g_statement_log then
1572 		l_logmessage:='Calling IEM_RT_PROC_EMAILS_PVT.create_item after update mlcs 31';
1573 		iem_logger(l_logmessage);
1574 		end if;
1575 
1576 		IEM_RT_PROC_EMAILS_PVT.create_item (
1577 					p_api_version_number => 1.0,
1578   					p_init_msg_list=>'F' ,
1579 					p_commit=>'F',
1580 				p_message_id =>l_post_rec.message_id,
1581 				p_email_account_id  =>l_post_rec.email_account_id,
1582 				p_priority  =>l_post_rec.priority,
1583 				p_agent_id  =>-1,
1584 				p_group_id  =>-1,
1585 				p_sent_date =>l_header_Rec.sent_date,
1586 				p_received_date =>l_post_Rec.received_Date,
1587 				p_rt_classification_id =>l_rt_classification_id,
1588 				p_customer_id=>l_customer_id    ,
1589 				p_contact_id=>g_contact_id    ,
1590 				p_relationship_id=>g_relation_id    ,
1591 				p_interaction_id=>l_interaction_id ,
1592 				p_ih_media_item_id=>l_media_id ,
1593 				p_msg_status=>l_post_rec.msg_status  ,
1594 				p_mail_proc_status=>'R' ,
1595 				p_mail_item_status=>null ,
1596 				p_category_map_id=>null ,
1597 				p_rule_id=>l_rule_id,
1598 				p_subject=>l_header_rec.subject,
1599 				p_sender_address=>l_sender,
1600 				p_from_agent_id=>null,
1601      			x_return_status=>l_ret_status	,
1602   				x_msg_count=>l_msg_count	      ,
1603  				x_msg_data=>l_msg_data);
1604 
1605 
1606 				if g_statement_log then
1607 				l_logmessage:='After update MLCS IEM_EMAIL_PROC_PVT.IEM_PROC_IH for milcs id 31 staus : '||l_stat||' text : '||l_out_text||' l_milcs_id : '||l_milcs_id;
1608 				iem_logger(l_logmessage);
1609 				end if;
1610 
1611 			IF l_ret_status<>'S' THEN
1612 				l_logmessage:='EXECPROC:Error While Inserting Record in Proc Emails Table ';
1613 				raise ABORT_PROCESSING;
1614 			END IF;
1615 				-- Add a Activity for AUTO-UPDATE OF SR if the incoming email contain reference to SR
1616 				  if l_sr_id is not null then
1617      					l_activity_rec.start_date_time   := SYSDATE;
1618 	       				l_activity_rec.media_id          := l_media_id;
1619          				l_activity_rec.action_id         := 75;	-- Auto Update Of SR
1620          				l_activity_rec.interaction_id    := l_interaction_id;
1621          				l_activity_rec.action_item_id    := 45;-- EMAIL
1622          				l_activity_rec.DOC_ID   := l_sr_id;
1623          				l_activity_rec.DOC_REF := 'SR';
1624 					IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1625 							p_type=>'ACTIVITY',	-- MEDIA/ACTIVITY/MLCS/INTERACTION
1626 							p_action=>'ADD',	-- ADD/UPDATE/CLOSE
1627 							p_interaction_rec=>l_interaction_rec,
1628 							p_activity_rec=>l_activity_rec,
1629 							p_media_lc_rec=>l_media_lc_Rec,
1630 							p_media_rec=>l_media_rec,
1631 							x_id=>l_activity_id,
1632 							x_status=>l_stat,
1633 			     				x_out_text=>l_out_text	);
1634 
1635 						IF l_stat<>'S' THEN
1636 							l_logmessage:=l_out_text;
1637 							raise ABORT_PROCESSING;
1638 						END IF;
1639          				l_activity_rec.DOC_ID   := null;
1640          				l_activity_rec.DOC_REF := null;
1641 				end if;
1642 
1643 
1644 
1645 				if g_statement_log then
1646 				l_logmessage:='Calling IEM_EMAIL_PROC_PVT.IEM_WRAPUP after update mlcs 31';
1647 				iem_logger(l_logmessage);
1648 				end if;
1649 						IEM_EMAIL_PROC_PVT.IEM_WRAPUP(p_interaction_id=>l_interaction_id,
1650 								p_media_id=>l_media_id		,
1651 								p_milcs_id=>l_mp_milcs_id,
1652 								p_action=>'R',
1653 								p_email_rec =>l_post_rec,
1654 								p_action_id=>65,
1655 								x_out_text=>l_out_text,
1656 								x_status=>l_stat );
1657 
1658 
1659 				if g_statement_log then
1660 				l_logmessage:='End of  IEM_EMAIL_PROC_PVT.IEM_WRAPUP after update mlcs 31 status : '||l_stat ||' data: '||l_out_text;
1661 				iem_logger(l_logmessage);
1662 				end if;
1663 
1664 			          			IF l_stat='E' THEN
1665 				    					l_logmessage:=l_out_text;
1666 				     				raise ABORT_PROCESSING;
1667 					   		     END IF;
1668 				     	     	raise STOP_PROCESSING;
1669 				     		END IF;
1670 					     END IF;
1671 					 END IF;
1672 					END IF;  -- end if for if media id is not null
1673 				ELSIF l_action in ('AUTOCREATESR','UPDSERVICEREQID') then
1674                                   l_logmessage := 'AUTOCREATESR section';
1675                                   iem_logger(l_logmessage);
1676 
1677 			 -- Populate l_email_doc_tbl for both autocreate and autoupdate SR
1678 					FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
1679 					-- Added NVL condition for bug 11796985
1680 					l_status_id:=to_number(NVL(l_param_rec_tbl(l_param_index).parameter1,'0'));
1681 					l_email_doc_tbl(l_param_index).doc_id:=l_param_rec_tbl(l_param_index).parameter2;
1682                                           -- siahmed 12.1.3
1683                                           --this has been added in iemprulb.pls in procedure auto_process_email
1684 					 l_parser_id:=to_number(l_param_rec_tbl(l_param_index).parameter3);
1685 
1686                                               l_logmessage := 'status id is: ' || l_status_id ||'parser id is ' || l_parser_id ;
1687                                               iem_logger(l_logmessage);
1688 
1689 					l_email_doc_tbl(l_param_index).type:='I';
1690 							EXIT;
1691 					END LOOP;
1692 				l_qual_tbl.delete;
1693 
1694 
1695 				if g_statement_log then
1696 				l_logmessage:='before call to Getting mergeval status';
1697 				iem_logger(l_logmessage);
1698 				end if;
1699  		IEM_EMAIL_PROC_PVT.IEM_GET_MERGEVAL(p_email_account_id=>l_post_rec.email_account_id ,
1700 							p_mailer =>l_header_rec.from_str,
1701 				    p_dflt_sender=>l_sender	,
1702 				    p_subject=>l_header_rec.subject,
1703 				    x_qual_tbl=> l_qual_tbl,
1704 				    x_status=>l_status,
1705 				    x_out_text=>l_out_Text);
1706 
1707 
1708 				if g_statement_log then
1709 				l_logmessage:='Getting mergeval status '||l_status|| ' text : '||l_out_text;
1710 				iem_logger(l_logmessage);
1711 				end if;
1712 
1713 				 IF l_action='AUTOCREATESR' THEN
1714                                     l_logmessage := 'Entering into AUTOCREATESR section';
1715                                     iem_logger(l_logmessage);
1716 
1717 						-- Retrieve Party Id
1718 						if l_acct_type='I' then -- select the party id from profile
1719 							l_emp_flag:='Y';
1720 						BEGIN
1721 						 Select person_id into l_contact_id
1722 						 from per_workforce_current_x
1723 						 Where upper(email_address)=upper(l_sender);
1724 						 exception when others then
1725 						 	l_contact_id:=null;
1726 						END;
1727 							l_party_id:=FND_PROFILE.VALUE_SPECIFIC('CS_SR_DEFAULT_CUSTOMER_NAME');
1728 
1729 
1730 				if g_statement_log then
1731 				l_logmessage:='insided auto create sr account Type I : l_party_id : '||l_party_id;
1732 				iem_logger(l_logmessage);
1733 				end if;
1734 						else		-- External Account
1735 
1736 
1737 							l_emp_flag:='N';
1738 
1739 
1740 				if g_statement_log then
1741 				l_logmessage:=' inside auto create sr account type E l_customer_id : '||l_customer_id;
1742 				iem_logger(l_logmessage);
1743 				end if;
1744 							if l_customer_id>0 then
1745 								-- Check to see if party identified is a contact or not
1746 								select party_type into l_party_type from  hz_parties
1747 								where party_id=l_customer_id;
1748 								if l_party_type='PARTY_RELATIONSHIP' then
1749 									-- Try to identify the actual party here
1750 								begin
1751 								select object_id into l_party_id
1752 								from HZ_RELATIONSHIPS where party_id= l_customer_id and
1753 								(relationship_code='CONTACT_OF' or relationship_code='EMPLOYEE_OF')
1754 								and status='A';
1755 								l_contact_id:=l_customer_id;
1756 								select contact_point_id  into l_contact_point_id
1757     								from hz_contact_points
1758     								where owner_table_name='HZ_PARTIES'
1759 								and owner_table_id=l_customer_id
1760 								and contact_point_type='EMAIL'
1761 								and upper(email_address)=upper(l_sender)
1762     								and contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
1763     								where contact_level_table='HZ_CONTACT_POINTS' and status='A');
1764 
1765 
1766 								if g_statement_log then
1767 								l_logmessage:='getting contact point id   '||l_contact_point_id;
1768 								iem_logger(l_logmessage);
1769 								end if;
1770 
1771 								exception when others THEN
1772 
1773 
1774 								if g_statement_log then
1775 								l_logmessage:='in exception '||sqlerrm;
1776 								iem_logger(l_logmessage);
1777 								end if;
1778 									l_party_id:=null;
1779 								end;
1780 								else
1781 								l_party_id:=l_customer_id;		-- Exact match
1782 								l_Contact_id:=g_contact_id;
1783 								end if;
1784 
1785 
1786 								if g_statement_log then
1787 								l_logmessage:='l_party_id : '||l_party_id ||' contact id : '||l_Contact_id;
1788 								iem_logger(l_logmessage);
1789 								end if;
1790 
1791 							elsif l_customer_id=-1 then	-- No customer match check profile
1792 													-- for what to do next
1793 
1794 
1795 								if g_statement_log then
1796 								l_logmessage:='customer id is -1';
1797 								iem_logger(l_logmessage);
1798 								end if;
1799 
1800 								if fnd_profile.value_specific('IEM_SR_NO_CUST')='CREATESR' then
1801 									l_party_id:=fnd_profile.value_specific('IEM_DEFAULT_CUSTOMER_ID');
1802 							     else
1803 									l_party_id:=null;
1804 								end if;
1805 							else					-- Multiple Customer Match.
1806 								l_party_id:=null;
1807 							end if;
1808 
1809 
1810 								if g_statement_log then
1811 								l_logmessage:='l_party_id after all ifs: '||l_party_id;
1812 								iem_logger(l_logmessage);
1813 								END if;
1814 						end if;
1815 					   	  l_logmessage:= 'if party id is null no sr creation- l_party_id:'|| l_party_id;
1816                                                   iem_logger(l_logmessage);
1817 
1818                                         --added the OR with parser id becasue just incase l_party_id returns no rowns or null
1819                                         --but there is a parser_id there is a possibility that the user trying to create an SR via advanced email SR.
1820 
1821 					IF ((l_party_id is not null) OR (l_parser_id IS NOT NULL)) then 	-- Go ahead with creating service request
1822 							-- Retrieve the note  for the email
1823 							iem_text_pvt.RETRIEVE_TEXT(p_message_id=>l_message_id,
1824 				    							x_text=>l_text,
1825 			         							x_status=>l_status);
1826 
1827 								if g_statement_log then
1828 								l_logmessage:='after call to iem_text_pvt.RETRIEVE_TEXT l_status : '||l_status;
1829 								iem_logger(l_logmessage);
1830 								END if;
1831 
1832 							if l_status<>'S' then
1833 								l_logmessage:='Error Encountered while Retrieving Notes';
1834                                                                 iem_logger(l_logmessage);
1835 								raise ABORT_PROCESSING;
1836 							end if;
1837 							l_note_type:=FND_PROFILE.VALUE_SPECIFIC('IEM_SR_NOTE_TYPE');
1838 
1839 
1840 							if g_statement_log then
1841 							l_logmessage:='Message id '||l_message_id ||'Note '||substr(l_text,1,200)||'Party id '||l_party_id||'SR type Id  '||l_status_id||'Note type  '||l_note_type||'Contact id '||l_contact_id ||'Contact Point id '||l_contact_point_id;
1842 							iem_logger(l_logmessage);
1843 							END if;
1844 
1845 						       --Fix for bug 14202765
1846 						       l_notes_flag := FND_PROFILE.VALUE('IEM_AUTO_CREATE_SR_ADD_EMAIL_AS_NOTE');
1847 						       IF ( l_notes_flag = 'N') THEN
1848  								l_text := null;
1849                                                        END IF;
1850 
1851 						       if g_statement_log then
1852 							l_logmessage:=' l_notes_flag '||l_notes_flag;
1853 							iem_logger(l_logmessage);
1854 							END if;
1855 
1856 
1857 							--siahmed 12.1.3 project  Advanced SR creation
1858                                              		-- if l_parser_id is not null then call advanced SR creation procedure
1859 							--if it fails then run the normal sr creation
1860 					   	  l_logmessage:= 'before sdvanced sr processing';
1861                                                   iem_logger(l_logmessage);
1862 
1863                                                 IF (l_parser_id IS NOT NULL) THEN
1864 					   	  l_logmessage:=  'started sdvanced sr processing';
1865                                                   iem_logger(l_logmessage);
1866 
1867                                                     advanced_sr_processing (
1868 						                p_message_id           =>  l_message_id,
1869                   						p_parser_id            =>  l_parser_id,
1870                   						p_account_type         =>  l_acct_type,
1871                   						p_default_type_id      =>  l_status_id,
1872                   						p_default_customer_id  =>  l_party_id,
1873                   						p_init_msg_list	       =>  FND_API.G_TRUE,
1874                   						--p_commit	       =>  FND_API.G_FALSE,
1875                   						p_commit	       =>  FND_API.G_TRUE,
1876                   						p_note		       =>  l_text,
1877                   						p_subject              =>  l_header_rec.subject,
1878                   						p_note_type            =>  l_note_type,
1879                   						p_contact_id           =>  l_contact_id,
1880                   						p_contact_point_id     =>  l_contact_point_id,
1881                   						x_return_status	       =>  l_ret_status,
1882                   						x_msg_count	       =>  l_msg_count,
1883                   						x_msg_data	       =>  l_msg_data,
1884                   						x_request_id           =>  l_sr_id);
1885 					   	              l_logmessage:= 'Advanced sr creation status is:'||l_ret_status || 'sr_id is:'||l_sr_id;
1886                                                               iem_logger(l_logmessage);
1887 
1888 							 --if sr creation fails normally then try the old mehtod
1889 
1890 
1891                 --also make sure there is l_party_id that is being passed
1892 							 if ((l_ret_status <>'S') AND (l_party_id IS NOT NULL)) THEN
1893 					   	              l_logmessage:= 'advanced sr fail resort to normal processing';
1894                                                               iem_logger(l_logmessage);
1895 
1896 							        IEM_SERVICEREQUEST_PVT.IEM_CREATE_SR(
1897                   							p_api_version           => 1.0,
1898                   							p_init_msg_list         => FND_API.G_TRUE,
1899                  							 p_commit	          => FND_API.G_FALSE,
1900 		  							p_message_id   	  => l_message_id,
1901 		  							p_note		  => l_text,
1902 		  							p_party_id              => l_party_id,
1903 		  							p_sr_type_id            => l_status_id,
1904 									p_subject				=>l_header_rec.subject,
1905 									p_employee_flag	=>l_emp_flag,
1906 		  							p_note_type             =>  l_note_type,
1907 		  							p_contact_id            =>  l_contact_id,
1908 									p_contact_point_id		=>l_contact_point_id,
1909                   						x_return_status         => l_ret_status,
1910                   						x_msg_count             => l_msg_count,
1911                   						x_msg_data              => l_msg_data,
1912 		  					  		x_request_id	  => l_sr_id);
1913 					   	           l_logmessage:= 'normal not advaned  sr creation status is:'||l_ret_status || 'sr_id is:'||l_sr_id;
1914                                                            iem_logger(l_logmessage);
1915 
1916                       if l_ret_status <> 'S' THEN
1917                          FND_MSG_PUB.Count_And_Get(p_count => l_msg_count, p_data => l_msg_data);
1918                             FOR j in  1..FND_MSG_PUB.Count_Msg LOOP
1919 
1920                              FND_MSG_PUB.Get(
1921                                 p_msg_index     => j,
1922                                 p_encoded       => 'F',
1923                                 p_data          => l_msg_data,
1924                                 p_msg_index_out => l_msg_index_out);
1925 
1926                                 l_logmessage:='-----------ERROR-----------';
1927                                iem_logger(l_logmessage);
1928 
1929                                 l_logmessage:='MESSAGE INDEX1 = ' || l_msg_index_out;
1930                                iem_logger(l_logmessage);
1931 
1932                                 l_logmessage:='MESSAGE1 = ' || substr(l_msg_data ,1,150) ;
1933                                 iem_logger(l_logmessage);
1934 
1935                                 l_logmessage:='----------END OF ERROR-----------';
1936                                iem_logger(l_logmessage);
1937 
1938                           END LOOP;
1939                       END IF;
1940 
1941                          --comment out
1942 							 END IF; --end of old sr creation
1943  						     -- if there is no parser id then create sr the old way only if party_id exist
1944          				             ELSIF (l_party_id IS NOT NULL) THEN
1945 					   	          l_logmessage:= 'no advanced sr resort to normal processing';
1946                                                            iem_logger(l_logmessage);
1947 
1948               						  IEM_SERVICEREQUEST_PVT.IEM_CREATE_SR(
1949                   							p_api_version           => 1.0,
1950                   							p_init_msg_list         => FND_API.G_TRUE,
1951                  							 p_commit	          => FND_API.G_FALSE,
1952 		  							p_message_id   	  => l_message_id,
1953 		  							p_note		  => l_text,
1954 		  							p_party_id              => l_party_id,
1955 		  							p_sr_type_id            => l_status_id,
1956 									p_subject				=>l_header_rec.subject,
1957 									p_employee_flag	=>l_emp_flag,
1958 		  							p_note_type             =>  l_note_type,
1959 		  							p_contact_id            =>  l_contact_id,
1960 									p_contact_point_id		=>l_contact_point_id,
1961                   						x_return_status         => l_ret_status,
1962                   						x_msg_count             => l_msg_count,
1963                   						x_msg_data              => l_msg_data,
1964 		  					  		x_request_id	  => l_sr_id);
1965 					   	          l_logmessage:= 'creating normal after skipping adv sr processing status'||l_ret_status;
1966                                                           iem_logger(l_logmessage);
1967 
1968 					   	          l_logmessage:= 'sr_id is:'||l_sr_id;
1969                                                           iem_logger(l_logmessage);
1970 
1971                                                      END IF;
1972 							IF l_ret_status='S' then
1973 							-- Add MLCS for Email Resolved as SR created
1974   							l_media_lc_rec.media_id :=l_media_id ;
1975   							l_media_lc_rec.milcs_type_id := 31;
1976   							l_media_lc_rec.start_date_time := sysdate;
1977   							l_media_lc_rec.handler_id := 680;
1978   							l_media_lc_rec.type_type := 'Email, Inbound';
1979 
1980 
1981 
1982 								if g_statement_log then
1983 								l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_PROC_IH add activity for auto update sr';
1984 								iem_logger(l_logmessage);
1985 								end if;
1986 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
1987 									p_type=>'MLCS'		,	-- MEDIA/ACTIVITY/MLCS/INTERACTION
1988 									p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
1989 									p_interaction_rec=>l_interaction_rec,
1990 									p_activity_rec=>l_activity_rec     ,
1991 									p_media_lc_rec=>l_media_lc_Rec ,
1992 									p_media_rec=>l_media_rec	,
1993 									x_id=>l_milcs_id,
1994 									x_status=>l_stat		,
1995 			     					x_out_text=>l_out_text	);
1996 
1997 
1998 								if g_statement_log then
1999 								l_logmessage:='after IEM_EMAIL_PROC_PVT.IEM_PROC_IH add activity for auto update sr : status :  '||l_stat||' text :'||l_out_text||' act id : '||l_activity_id;
2000 								iem_logger(l_logmessage);
2001 								end if;
2002 
2003 								IF l_stat<>'S' THEN
2004 									l_logmessage:=l_out_text;
2005 									raise ABORT_PROCESSING;
2006 								END IF;
2007 
2008 
2009 
2010 								if g_statement_log then
2011 								l_logmessage:='calling IEM_RT_PROC_EMAILS_PVT.create_item after auto update sr';
2012 								iem_logger(l_logmessage);
2013 								end if;
2014 		IEM_RT_PROC_EMAILS_PVT.create_item (
2015 					p_api_version_number => 1.0,
2016   					p_init_msg_list=>'F' ,
2017 					p_commit=>'F',
2018 				p_message_id =>l_post_rec.message_id,
2019 				p_email_account_id  =>l_post_rec.email_account_id,
2020 				p_priority  =>l_post_rec.priority,
2021 				p_agent_id  =>-1,
2022 				p_group_id  =>-1,
2023 				p_sent_date =>l_header_Rec.sent_date,
2024 				p_received_date =>l_post_Rec.received_Date,
2025 				p_rt_classification_id =>l_rt_classification_id,
2026 				p_customer_id=>l_customer_id    ,
2027 				p_contact_id=>g_contact_id    ,
2028 				p_relationship_id=>g_relation_id    ,
2029 				p_interaction_id=>l_interaction_id ,
2030 				p_ih_media_item_id=>l_media_id ,
2031 				p_msg_status=>l_post_rec.msg_status  ,
2032 				p_mail_proc_status=>'R' ,
2033 				p_mail_item_status=>null ,
2034 				p_category_map_id=>null ,
2035 				p_rule_id=>l_rule_id,
2036 				p_subject=>l_header_rec.subject,
2037 				p_sender_address=>l_sender,
2038 				p_from_agent_id=>null,
2039      			x_return_status=>l_ret_status	,
2040   				x_msg_count=>l_msg_count	      ,
2041  				x_msg_data=>l_msg_data);
2042 
2043 
2044 				if g_statement_log then
2045 				l_logmessage:='after IEM_RT_PROC_EMAILS_PVT.create_item after auto update sr : status :'||l_ret_status ||' data : '||l_msg_data;
2046 				iem_logger(l_logmessage);
2047 				end if;
2048 
2049 
2050 			IF l_ret_status<>'S' THEN
2051 				l_logmessage:='AUTOCREATESR:Error While Inserting Record in Proc Emails Table '||'sqlerrm:'||sqlerrm;
2052                                 iem_logger(l_logmessage);
2053 
2054 				raise ABORT_PROCESSING;
2055 			END IF;
2056 							-- Update  the Media Life Cycle for Auto Create  SR
2057  							 l_media_lc_rec.milcs_id:=l_milcs_id;
2058 
2059 
2060 				if g_statement_log then
2061 				l_logmessage:='update interaction for auto update sr';
2062 				iem_logger(l_logmessage);
2063 				end if;
2064 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2065 								p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2066 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
2067 								p_interaction_rec=>l_interaction_rec,
2068 								p_activity_rec=>l_activity_rec     ,
2069 								p_media_lc_rec=>l_media_lc_Rec ,
2070 								p_media_rec=>l_media_rec	,
2071 								x_id=>l_id,
2072 								x_status=>l_stat		,
2073 			  				   x_out_text=>l_out_text	);
2074 
2075 				if g_statement_log then
2076 				l_logmessage:='END IEM_EMAIL_PROC_PVT.IEM_PROC_IH update interaction for auto update sr : status : '||l_stat||' text :'||l_out_text|| ' inter id : '||l_id;
2077 				iem_logger(l_logmessage);
2078 				end if;
2079 
2080 
2081 							IF l_stat<>'S' THEN
2082 								l_logmessage:=l_out_text;
2083 								raise ABORT_PROCESSING;
2084 							END IF;
2085 										-- Create Activity
2086 						-- Add a Activity for AUTO-CREATE  SR
2087      					l_activity_rec.start_date_time   := SYSDATE;
2088 	       				l_activity_rec.media_id          := l_media_id;
2089          					l_activity_rec.action_id         := 65;	-- Email Resolved
2090          					l_activity_rec.interaction_id    := l_interaction_id;
2091          					l_activity_rec.action_item_id    := 45;-- EMAIL
2092          					l_activity_rec.DOC_ID   := l_sr_id;
2093          					l_activity_rec.DOC_REF := 'SR';
2094 
2095 
2096 				if g_statement_log then
2097 				l_logmessage:='Calling IEM_EMAIL_PROC_PVT.IEM_PROC_IH add activity for auto create SR email resolved 65';
2098 				iem_logger(l_logmessage);
2099 				end if;
2100 
2101 						IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2102 								p_type=>'ACTIVITY'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2103 								p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
2104 								p_interaction_rec=>l_interaction_rec,
2105 								p_activity_rec=>l_activity_rec     ,
2106 								p_media_lc_rec=>l_media_lc_Rec ,
2107 								p_media_rec=>l_media_rec	,
2108 								x_id=>l_activity_id,
2109 								x_status=>l_stat		,
2110 			     				x_out_text=>l_out_text	);
2111 
2112 				if g_statement_log then
2113 				l_logmessage:='After IEM_EMAIL_PROC_PVT.IEM_PROC_IH add activity for auto create SR email resolved 65 status : '||l_stat ||'text : '||l_out_text|| 'activity id : '||l_activity_id;
2114 				iem_logger(l_logmessage);
2115 				end if;
2116 
2117 							IF l_stat<>'S' THEN
2118 								l_logmessage:=l_out_text;
2119 								raise ABORT_PROCESSING;
2120 							END IF;
2121 						-- Add a Activity for CREATE  SR
2122 					-- select result reason outcome for activity
2123 					select wu.outcome_id, wu.result_id, wu.reason_id INTO
2124  					l_activity_rec.outcome_id, l_activity_rec.result_id, l_activity_rec.reason_id
2125         				from jtf_ih_action_action_items aa, jtf_ih_wrap_ups wu
2126         				where aa.action_id =65
2127 					and aa.action_item_id =45
2128         				and aa.default_wrap_id = wu.wrap_id;
2129      					l_activity_rec.start_date_time   := SYSDATE;
2130 	       				l_activity_rec.media_id          := l_media_id;
2131          					l_activity_rec.action_id         := 13;	-- Create  SR
2132          					l_activity_rec.interaction_id    := l_interaction_id;
2133          					l_activity_rec.action_item_id    := 17;-- SR
2134          					l_activity_rec.DOC_ID   := l_sr_id;
2135          					l_activity_rec.DOC_REF := 'SR';
2136 						-- Added l_activity_rec.doc_source_object_name for bug 9169782
2137 						-- Changed by Sanjana Rao on 08-Jan-2010
2138 						select incident_number into l_activity_rec.doc_source_object_name
2139 						from cs_incidents_all_b where incident_id=l_sr_id;
2140 
2141 
2142 				if g_statement_log then
2143 				l_logmessage:='CAlling IEM_EMAIL_PROC_PVT.IEM_PROC_IH add activity for auto create SR';
2144 				iem_logger(l_logmessage);
2145 				end if;
2146 						IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2147 								p_type=>'ACTIVITY'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2148 								p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
2149 								p_interaction_rec=>l_interaction_rec,
2150 								p_activity_rec=>l_activity_rec     ,
2151 								p_media_lc_rec=>l_media_lc_Rec ,
2152 								p_media_rec=>l_media_rec	,
2153 								x_id=>l_activity_id,
2154 								x_status=>l_stat		,
2155 			     				x_out_text=>l_out_text	);
2156 
2157 				if g_statement_log then
2158 				l_logmessage:='After IEM_EMAIL_PROC_PVT.IEM_PROC_IH add activity for auto create SR e status : '||l_stat ||'text : '||l_out_text|| 'activity id : '||l_activity_id  ;
2159 				iem_logger(l_logmessage);
2160 				end if;
2161 
2162 							IF l_stat<>'S' THEN
2163 								l_logmessage:=l_out_text;
2164 								raise ABORT_PROCESSING;
2165 							END IF;
2166 					-- Update the mail Processing Life Cycles
2167  							 l_media_lc_rec.milcs_id:=l_mp_milcs_id;
2168  							 l_media_lc_rec.milcs_type_id:=17;
2169 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2170 								p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2171 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
2172 								p_interaction_rec=>l_interaction_rec,
2173 								p_activity_rec=>l_activity_rec     ,
2174 								p_media_lc_rec=>l_media_lc_Rec ,
2175 								p_media_rec=>l_media_rec	,
2176 								x_id=>l_id,
2177 								x_status=>l_stat		,
2178 			  				   x_out_text=>l_out_text	);
2179 
2180 							IF l_stat<>'S' THEN
2181 								l_logmessage:=l_out_text;
2182 								raise ABORT_PROCESSING;
2183 							END IF;
2184 						-- Check for Sending out notifications
2185 						l_noti_flag:=FND_PROFILE.VALUE_SPECIFIC('IEM_SR_CREATE_NOTI');
2186 						if l_noti_flag='Y' then
2187 					-- update the itneraction with result reason outcome
2188 					select wu.outcome_id, wu.result_id, wu.reason_id INTO
2189  					l_interaction_rec.outcome_id, l_interaction_rec.result_id, l_interaction_rec.reason_id
2190         				from jtf_ih_action_action_items aa, jtf_ih_wrap_ups wu
2191         				where aa.action_id =65
2192 					and aa.action_item_id =45
2193         				and aa.default_wrap_id = wu.wrap_id;
2194 					l_interaction_rec.interaction_id:=l_interaction_id;
2195 				select contact_party_id into l_cust_contact_id from jtf_ih_interactions
2196 				where interaction_id=l_interaction_id;
2197 						IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2198 								p_type=>'INTERACTION'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2199 								p_action=>'CLOSE'		,		-- ADD/UPDATE/CLOSE
2200 								p_interaction_rec=>l_interaction_rec,
2201 								p_activity_rec=>l_activity_rec     ,
2202 								p_media_lc_rec=>l_media_lc_Rec ,
2203 								p_media_rec=>l_media_rec	,
2204 								x_id=>l_id,
2205 								x_status=>l_stat		,
2206 			     				x_out_text=>l_out_text	);
2207 
2208 							IF l_stat<>'S' THEN
2209 								l_logmessage:=l_out_text;
2210 								raise ABORT_PROCESSING;
2211 							END IF;
2212 
2213 
2214 				if g_statement_log then
2215 				l_logmessage:='calling iem_email_proc_pvt.IEM_AUTOREPLY for auot update sr';
2216 				iem_logger(l_logmessage);
2217 				end if;
2218 						IEM_AUTOREPLY(p_interaction_id=>l_interaction_id	,
2219 									p_media_id=>l_media_id,
2220 									p_post_rec=>l_post_rec,
2221 									p_doc_tbl=>l_email_doc_tbl,
2222 									p_subject=>l_header_rec.subject,
2223  									P_TAG_KEY_VALUE_TBL=>l_outbox_tbl ,
2224  									P_CUSTOMER_ID=>l_customer_id ,
2225  									P_RESOURCE_ID=>l_resource_id,
2226  									p_qualifiers =>l_qual_tbl,
2227 									p_fwd_address=>null,
2228 									p_fwd_doc_id=>l_sr_id,		-- Pass SR id
2229 									p_req_type=>'N',		-- For autonotifications
2230 									x_out_text=>l_out_text,
2231 									x_status=>l_stat  ) ;
2232 
2233 
2234 				if g_statement_log then
2235 				l_logmessage:='END iem_email_proc_pvt.IEM_AUTOREPLY for auot update sr : status : '||l_stat ||' data : '||l_out_text;
2236 				iem_logger(l_logmessage);
2237 				end if;
2238 
2239 							IF l_stat<>'S' THEN
2240 								l_logmessage:=l_out_text;
2241 								raise ABORT_PROCESSING;
2242 							END IF;
2243 							l_autoack_flag:='N';  --so that no autoack is send.
2244 						else
2245 						-- Resolving the message without sending notifications
2246 
2247 
2248 				if g_statement_log then
2249 				l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_WRAPUP for resolve on auto update sr';
2250 				iem_logger(l_logmessage);
2251 				end if;
2252 							IEM_EMAIL_PROC_PVT.IEM_WRAPUP(p_interaction_id=>l_interaction_id,
2253 										p_media_id=>l_media_id		,
2254 										p_milcs_id=>l_mp_milcs_id,
2255 										p_action=>'R',
2256 										p_email_rec =>l_post_rec,
2257 										p_action_id=>65,
2258 										x_out_text=>l_out_text,
2259 										x_status=>l_stat );
2260 
2261 				if g_statement_log then
2262 				l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_WRAPUP for resolve on auto update sr status : '||l_stat||' data :'||l_out_text;
2263 				iem_logger(l_logmessage);
2264 				end if;
2265 										IF l_stat<>'S' THEN
2266 											l_logmessage:=l_out_text;
2267 											raise ABORT_PROCESSING;
2268 										END IF;
2269 						 end if;		-- for if l_noti_flag='Y'
2270 						 	raise STOP_PROCESSING;
2271 						 else		-- Sr creation fails so if it is internal type in that casecheck prfile value for next action. in case of external account it is always route.
2272 						  if l_acct_type='I' then
2273 						 	if (fnd_profile.value_specific('IEM_SR_NOT_UPDATED'))='REDIRECT'
2274  then
2275  							l_redirect_flag:='Y';
2276 							end if;
2277 						  end if;
2278 
2279            				 END IF;		-- for if l_Ret_status='S' from create sr api
2280 						 end if;		-- for if l_party_id is not null
2281 						-- End of create Sr
2282 				ELSE 	-- This is a update service request
2283 					IF (l_status_id is not null) and (l_sr_id is not null) then
2284 						-- If l_status id is 0 which means user do not want to update status
2285 						-- so do not call the update status API
2286 						If l_status_id=0 then
2287 						  	l_stat:='S';
2288 						ELSE
2289 
2290 
2291 				if g_statement_log then
2292 				l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_SRSTATUS_UPDATE for auto update sr';
2293 				iem_logger(l_logmessage);
2294 				end if;
2295 
2296 							IEM_EMAIL_PROC_PVT.IEM_SRSTATUS_UPDATE(p_sr_id=>l_sr_id	,
2297 												p_status_id=>l_status_id,
2298 												p_email_rec=>l_post_rec,
2299 												x_status =>l_stat,
2300 												x_out_text=>l_out_text) ;
2301 
2302 				if g_statement_log then
2303 				l_logmessage:='after IEM_EMAIL_PROC_PVT.IEM_SRSTATUS_UPDATE for auto update l_out_textsr : status : '||l_stat||' text : '||l_out_text;
2304 				iem_logger(l_logmessage);
2305 				end if;
2306 						end if;
2307 					IF l_stat='S' then
2308 						-- Add a Activity for AUTO-UPDATE OF SR
2309      					l_activity_rec.start_date_time   := SYSDATE;
2310 	       				l_activity_rec.media_id          := l_media_id;
2311          					l_activity_rec.action_id         := 75;	-- Auto Update Of SR
2312          					l_activity_rec.interaction_id    := l_interaction_id;
2313          					l_activity_rec.action_item_id    := 45;-- EMAIL
2314          					l_activity_rec.DOC_ID   := l_sr_id;
2315          					l_activity_rec.DOC_REF := 'SR';
2316 						IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2317 								p_type=>'ACTIVITY'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2318 								p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
2319 								p_interaction_rec=>l_interaction_rec,
2320 								p_activity_rec=>l_activity_rec     ,
2321 								p_media_lc_rec=>l_media_lc_Rec ,
2322 								p_media_rec=>l_media_rec	,
2323 								x_id=>l_activity_id,
2324 								x_status=>l_stat		,
2325 			     				x_out_text=>l_out_text	);
2326 
2327 							IF l_stat<>'S' THEN
2328 								l_logmessage:=l_out_text;
2329 								raise ABORT_PROCESSING;
2330 							END IF;
2331 					--Update Intearctionwith result reason outcome
2332 					-- Create a Media Life Cycle for Auto update of SR
2333   						l_media_lc_rec.media_id :=l_media_id ;
2334   						l_media_lc_rec.milcs_type_id := 40; --EMAIL_AUTO_UPDATED_SR
2335   						l_media_lc_rec.start_date_time := sysdate;
2336   						l_media_lc_rec.handler_id := 680;
2337 
2338 
2339 				if g_statement_log then
2340 				l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_PROC_IH update MLCS for auto ack';
2341 				iem_logger(l_logmessage);
2342 				end if;
2343 
2344 						IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2345 								p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2346 								p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
2347 								p_interaction_rec=>l_interaction_rec,
2348 								p_activity_rec=>l_activity_rec     ,
2349 								p_media_lc_rec=>l_media_lc_Rec ,
2350 								p_media_rec=>l_media_rec	,
2351 								x_id=>l_id,
2352 								x_status=>l_stat		,
2353 			    				 x_out_text=>l_out_text	);
2354 
2355 				if g_statement_log then
2356 				l_logmessage:='END IEM_EMAIL_PROC_PVT.IEM_PROC_IH update MLCS for auto ack :  status : '||l_stat||' txt : '||l_out_text||' mlcs id : '||l_milcs_id;
2357 				iem_logger(l_logmessage);
2358 				end if;
2359 
2360 							IF l_stat<>'S' THEN
2361 								l_logmessage:=l_out_text;
2362 								raise ABORT_PROCESSING;
2363 							END IF;
2364 							-- Update  the Media Life Cycle for Auto Update of SR
2365  							 l_media_lc_rec.milcs_id:=l_id;
2366 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2367 								p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2368 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
2369 								p_interaction_rec=>l_interaction_rec,
2370 								p_activity_rec=>l_activity_rec     ,
2371 								p_media_lc_rec=>l_media_lc_Rec ,
2372 								p_media_rec=>l_media_rec	,
2373 								x_id=>l_id,
2374 								x_status=>l_stat		,
2375 			  				   x_out_text=>l_out_text	);
2376 							IF l_stat<>'S' THEN
2377 								l_logmessage:=l_out_text;
2378 								raise ABORT_PROCESSING;
2379 							END IF;
2380 
2381 		IEM_RT_PROC_EMAILS_PVT.create_item (
2382 					p_api_version_number => 1.0,
2383   					p_init_msg_list=>'F' ,
2384 					p_commit=>'F',
2385 				p_message_id =>l_post_rec.message_id,
2386 				p_email_account_id  =>l_post_rec.email_account_id,
2387 				p_priority  =>l_post_rec.priority,
2388 				p_agent_id  =>-1,
2389 				p_group_id  =>-1,
2390 				p_sent_date =>l_header_Rec.sent_date,
2391 				p_received_date =>l_post_Rec.received_Date,
2392 				p_rt_classification_id =>l_rt_classification_id,
2393 				p_customer_id=>l_customer_id    ,
2394 				p_contact_id=>g_contact_id    ,
2395 				p_relationship_id=>g_relation_id    ,
2396 				p_interaction_id=>l_interaction_id ,
2397 				p_ih_media_item_id=>l_media_id ,
2398 				p_msg_status=>l_post_rec.msg_status  ,
2399 				p_mail_proc_status=>'R' ,
2400 				p_mail_item_status=>null ,
2401 				p_category_map_id=>null ,
2402 				p_rule_id=>l_rule_id,
2403 				p_subject=>l_header_rec.subject,
2404 				p_sender_address=>l_sender,
2405 				p_from_agent_id=>null,
2406      			x_return_status=>l_ret_status	,
2407   				x_msg_count=>l_msg_count	      ,
2408  				x_msg_data=>l_msg_data);
2409 			IF l_ret_status<>'S' THEN
2410 				l_logmessage:='AUTOUPDSR:Error While Inserting Record in Proc Emails Table ';
2411 				raise ABORT_PROCESSING;
2412 			END IF;
2413 			-- Check for Sending Out Notifications
2414 				l_noti_flag:=FND_PROFILE.VALUE_SPECIFIC('IEM_SR_UPDATE_NOTI');
2415 				if l_noti_flag='Y' then		-- Sends out notifications
2416 
2417 					-- update the itneraction with result reason outcome
2418 					select wu.outcome_id, wu.result_id, wu.reason_id INTO
2419  					l_interaction_rec.outcome_id, l_interaction_rec.result_id, l_interaction_rec.reason_id
2420         				from jtf_ih_action_action_items aa, jtf_ih_wrap_ups wu
2421         				where aa.action_id =75
2422 					and aa.action_item_id =45
2423         				and aa.default_wrap_id = wu.wrap_id;
2424 					l_interaction_rec.interaction_id:=l_interaction_id;
2425 						IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2426 								p_type=>'INTERACTION'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2427 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
2428 								p_interaction_rec=>l_interaction_rec,
2429 								p_activity_rec=>l_activity_rec     ,
2430 								p_media_lc_rec=>l_media_lc_Rec ,
2431 								p_media_rec=>l_media_rec	,
2432 								x_id=>l_id,
2433 								x_status=>l_stat		,
2434 			     				x_out_text=>l_out_text	);
2435 
2436 
2437 							IF l_stat<>'S' THEN
2438 								l_logmessage:=l_out_text;
2439 								raise ABORT_PROCESSING;
2440 							END IF;
2441 				l_outbox_tbl.delete;
2442 				IF l_tag_keyval.count>0 THEN
2443 						FOR i IN l_tag_keyval.FIRST..l_tag_keyval.LAST LOOP
2444 							l_outbox_tbl(i).key:=l_tag_keyval(i).key;
2445 							l_outbox_tbl(i).value:=l_tag_keyval(i).value;
2446 							l_outbox_tbl(i).datatype:=l_tag_keyval(i).datatype;
2447 						END LOOP;
2448 				END IF;
2449 
2450 
2451 						IEM_AUTOREPLY(p_interaction_id=>l_interaction_id	,
2452 									p_media_id=>l_media_id,
2453 									p_post_rec=>l_post_rec,
2454 									p_doc_tbl=>l_email_doc_tbl,
2455 									p_subject=>l_header_rec.subject,
2456  									P_TAG_KEY_VALUE_TBL=>l_outbox_tbl ,
2457  									P_CUSTOMER_ID=>l_customer_id ,
2458  									P_RESOURCE_ID=>l_resource_id,
2459  									p_qualifiers =>l_qual_tbl,
2460 									p_fwd_address=>null,
2461 									p_fwd_doc_id=>l_sr_id,		-- Pass the SR id
2462 									p_req_type=>'N',		-- For autonotifications
2463 									x_out_text=>l_out_text,
2464 									x_status=>l_stat  ) ;
2465 
2466 							IF l_stat<>'S' THEN
2467 								l_logmessage:=l_out_text;
2468 								raise ABORT_PROCESSING;
2469 							END IF;
2470 							l_autoack_flag:='N';
2471 					-- Update the mail Processing Life Cycles
2472  							 l_media_lc_rec.milcs_id:=l_mp_milcs_id;
2473  							 l_media_lc_rec.milcs_type_id:=17;
2474 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2475 								p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2476 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
2477 								p_interaction_rec=>l_interaction_rec,
2478 								p_activity_rec=>l_activity_rec     ,
2479 								p_media_lc_rec=>l_media_lc_Rec ,
2480 								p_media_rec=>l_media_rec	,
2481 								x_id=>l_id,
2482 								x_status=>l_stat		,
2483 			  				   x_out_text=>l_out_text	);
2484 
2485 							IF l_stat<>'S' THEN
2486 								l_logmessage:=l_out_text;
2487 								raise ABORT_PROCESSING;
2488 							END IF;
2489 				   else					-- notification flag is not set so resolve the message
2490 								IEM_EMAIL_PROC_PVT.IEM_WRAPUP(p_interaction_id=>l_interaction_id,
2491 										p_media_id=>l_media_id		,
2492 										p_milcs_id=>l_mp_milcs_id,
2493 										p_action=>'R',
2494 										p_email_rec =>l_post_rec,
2495 										p_action_id=>75,
2496 										x_out_text=>l_out_text,
2497 										x_status=>l_stat );
2498 										IF l_stat<>'S' THEN
2499 											l_logmessage:=l_out_text;
2500 											raise ABORT_PROCESSING;
2501 										END IF;
2502 					end if;		-- for if l_noti_flag='Y';
2503 								raise STOP_PROCESSING;
2504 					ELSE
2505 						 		-- Sr updation fails so if it is internal type in that casecheck prfile value for next action. in case of external account it is always route.
2506 						  if l_acct_type='I' then
2507 						 	if (fnd_profile.value_specific('IEM_SR_NOT_UPDATED'))='REDIRECT'
2508  then
2509  							l_redirect_flag:='Y';
2510 							end if;
2511 						  end if;
2512 					END IF;	-- if l_stat='S' from SR update api
2513 					ELSE
2514 				if g_statement_log then
2515 					l_logmessage:='Status Id is not Set at Profile OR SR# is not present in TAG Not updating the SR';
2516 					iem_logger(l_logmessage);
2517 				end if;
2518 					END IF;		-- if l_status_id is not null
2519 				END IF;	-- indicual processing ends
2520 			END IF;		-- elsif l_Action in ('AUTOCREATESR','AUTOUPDATESR');
2521 			END IF;		-- if l_autoproc_result='T'
2522 					  -- Check for autoack Flag if set then send autoack.
2523 					  IF l_autoack_flag='Y' then
2524 							if g_statement_log then
2525 								l_logmessage:='Start Sending Out Autoacknowledgement' ;
2526 								iem_logger(l_logmessage);
2527 							end if;
2528     						FND_MESSAGE.Set_Name('IEM','IEM_ADM_AUTO_ACK_CUSTOMER');
2529  						FND_MSG_PUB.Add;
2530  						l_dflt_sender :=  FND_MSG_PUB.GET(FND_MSG_pub.Count_Msg,FND_API.G_FALSE);
2531 					IEM_EMAIL_PROC_PVT.IEM_AUTOACK(p_email_user=>l_email_user_name,
2532 							p_mailer =>l_header_rec.from_str,
2533 							p_sender=>l_sender,
2534 							p_subject=>l_header_rec.subject,
2535 				 			 p_domain_name=>l_email_domain_name,
2536 				 			 p_document_id =>l_doc_id,
2537 				  			p_dflt_sender=>l_dflt_sender,
2538 							p_int_id=>l_interaction_id,
2539 				  			p_master_account_id=>l_post_rec.email_account_id,
2540 				 			 x_status=>l_status,
2541 				  			x_out_text=>l_out_text);
2542   						l_media_lc_rec.media_id :=l_media_id ;
2543   						l_media_lc_rec.milcs_type_id := 29; --MAIL_AUTOACKNOWLEDGED
2544   						l_media_lc_rec.start_date_time := sysdate;
2545   						l_media_lc_rec.handler_id := 680;
2546   						l_media_lc_rec.type_type := 'Email, Inbound';
2547 
2548 				IF l_status<>'S' THEN   -- Create MLCS after auto ack
2549 						if g_error_log then
2550 							l_logmessage:='Error In Autoack '||l_out_text;
2551 							iem_logger(l_logmessage);
2552 						end if;
2553 				ELSE
2554 					IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2555 						p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2556 						p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
2557 						p_interaction_rec=>l_interaction_rec,
2558 						p_activity_rec=>l_activity_rec     ,
2559 						p_media_lc_rec=>l_media_lc_Rec ,
2560 						p_media_rec=>l_media_rec	,
2561 						x_id=>l_milcs_id,
2562 						x_status=>l_stat		,
2563 			   	  	     x_out_text=>l_out_text	);
2564 
2565  			 		l_media_lc_rec.milcs_id:=l_milcs_id;
2566 					IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2567 						p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2568 						p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
2569 						p_interaction_rec=>l_interaction_rec,
2570 						p_activity_rec=>l_activity_rec     ,
2571 						p_media_lc_rec=>l_media_lc_Rec ,
2572 						p_media_rec=>l_media_rec	,
2573 						x_id=>l_milcs_id,
2574 						x_status=>l_stat		,
2575 			     		x_out_text=>l_out_text	);
2576 				END IF;				-- End of MLCS Creation
2577 				END IF;			-- End if for if l_autoack_flag='Y';
2578 -- Calling Rules Engine for AUTO-REDIRECT Type
2579 	-- Prior to calling this check if the email is to be redirected on the profile
2580 	-- set for  autocreate/auto update SR fails for employee type
2581 	if l_redirect_flag='N' then
2582 	iem_rules_engine_pub.auto_process_email(p_api_version_number=>1.0,
2583 									p_commit=>FND_API.G_FALSE,
2584 									p_rule_type=>'AUTOREDIRECT',
2585 									p_keyvals_tbl=>l_class_val_tbl,
2586 									p_accountid=>l_post_rec.email_account_id,
2587 									x_result=>l_autoproc_result,
2588 									x_action=>l_action,
2589 									x_parameters=>l_param_rec_tbl,
2590 									x_return_status=>l_ret_status,
2591 									x_msg_count=>l_msg_count,
2592 									x_msg_data=>l_msg_data);
2593 					IF l_ret_status<>'S' THEN
2594 						l_logmessage:='Error While Calling rules Engine for AUTOREDIRECT';
2595 						raise ABORT_PROCESSING;
2596 					END IF;
2597 		else		-- As auto redirect flag is set for autoupdate/create SR
2598 			l_autoproc_result:='T';
2599 			l_action:='AUTOREDIRECT_EXTERNAL';
2600 			l_ext_address:=fnd_profile.value_specific('IEM_SR_REDIRECT_EMAIL_ADDR');
2601 		end if;
2602 			if l_action='AUTOREDIRECT_EXTERNAL' and l_autoproc_result='T' THEN
2603      			IF l_auto_forward_flag='Y' THEN --donot autoforward to a already autofwd message
2604 					l_autoproc_result:='F';
2605 				END IF;
2606 		    end if;
2607 		IF ((l_autoproc_result='T') AND (l_action is not null)) THEN
2608 			-- Create the activity and necessary MLCS for auto redirect
2609 			 IF l_action='AUTOREDIRECT_EXTERNAL' THEN
2610   						l_media_lc_rec.milcs_type_id := 49; --EMAIL_AUTO_REDIRECTD_EXTERNAL
2611 				 ELSE
2612   						l_media_lc_rec.milcs_type_id := 48; --EMAIL_AUTO_REDIRECTD_INTERNAL
2613 						l_media_lc_rec.resource_id:=l_post_rec.email_account_id;
2614 
2615                     END IF;
2616 			-- Create the MILCS
2617 						l_media_lc_rec.media_id :=l_media_id ;
2618   						l_media_lc_rec.start_date_time := sysdate;
2619   						l_media_lc_rec.handler_id := 680;
2620 				-- Create MLCS for  Auto-Redirect
2621 						IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2622 								p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2623 								p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
2624 								p_interaction_rec=>l_interaction_rec,
2625 								p_activity_rec=>l_activity_rec     ,
2626 								p_media_lc_rec=>l_media_lc_Rec ,
2627 								p_media_rec=>l_media_rec	,
2628 								x_id=>l_milcs_id,
2629 								x_status=>l_stat		,
2630 			    				 x_out_text=>l_out_text	);
2631 							IF l_stat<>'S' THEN
2632 								l_logmessage:=l_out_text;
2633 								raise ABORT_PROCESSING;
2634 							END IF;
2635 							-- Update  the Media Life Cycle for Auto RRRR
2636  							 l_media_lc_rec.milcs_id:=l_milcs_id;
2637 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
2638 								p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
2639 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
2640 								p_interaction_rec=>l_interaction_rec,
2641 								p_activity_rec=>l_activity_rec     ,
2642 								p_media_lc_rec=>l_media_lc_Rec ,
2643 								p_media_rec=>l_media_rec	,
2644 								x_id=>l_milcs_id,
2645 								x_status=>l_stat		,
2646 			  				   x_out_text=>l_out_text	);
2647 
2648 							IF l_stat<>'S' THEN
2649 								l_logmessage:=l_out_text;
2650 								raise ABORT_PROCESSING;
2651 							END IF;
2652 		 IF (l_action='AUTOREDIRECT_EXTERNAL') THEN
2653 				if l_redirect_flag='N' then
2654 					FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
2655 							l_ext_address:=l_param_rec_tbl(l_param_index).parameter1;
2656 							l_ext_temp_id:=to_number(l_param_rec_tbl(l_param_index).type);
2657 							EXIT;
2658 						END LOOP;
2659 				end if;
2660 						-- Calling Outbox Processor API
2661 
2662 				l_outbox_tbl.delete;
2663 				l_qual_tbl.delete;
2664 				IF l_tag_keyval.count>0 THEN
2665 						FOR i IN l_tag_keyval.FIRST..l_tag_keyval.LAST LOOP
2666 							l_outbox_tbl(i).key:=l_tag_keyval(i).key;
2667 							l_outbox_tbl(i).value:=l_tag_keyval(i).value;
2668 							l_outbox_tbl(i).datatype:=l_tag_keyval(i).datatype;
2669 						END LOOP;
2670 				END IF;
2671 					l_f_name:=substr(l_from_folder,2,length(l_from_folder));
2672 					if l_customer_id>0 then
2673 						l_cust_search_id:=l_customer_id;
2674 					end if;
2675 
2676 
2677 				if g_statement_log then
2678 				l_logmessage:='Calling iem autoreply with ext address'||l_ext_address;
2679 				iem_logger(l_logmessage);
2680 				end if;
2681 
2682 						IEM_AUTOREPLY(p_interaction_id=>l_interaction_id	,
2683 									p_media_id=>l_media_id,
2684 									p_post_rec=>l_post_rec,
2685 									p_doc_tbl=>l_email_doc_tbl,
2686 									p_subject=>l_header_rec.subject,
2687  									P_TAG_KEY_VALUE_TBL=>l_outbox_tbl ,
2688  									P_CUSTOMER_ID=>l_cust_search_id ,
2689  									P_RESOURCE_ID=>l_resource_id,
2690  									p_qualifiers =>l_qual_tbl,
2691 									p_fwd_address=>l_ext_address,
2692 									p_fwd_doc_id=>l_ext_temp_id,
2693 									p_req_type=>'F',		-- For autoforward
2694 									x_out_text=>l_out_text,
2695 									x_status=>l_stat  ) ;
2696 
2697 				if g_statement_log then
2698 				l_logmessage:='end Calling iem autoreply: status : '||l_stat||' text : '||l_out_text;
2699 				iem_logger(l_logmessage);
2700 				end if;
2701 
2702 
2703 							IF l_stat<>'S' THEN
2704 								l_logmessage:=l_out_text;
2705 								raise ABORT_PROCESSING;
2706 							END IF;
2707 						   		l_auto_msgstatus:='XREDIRECT';		-- Xternal redirect
2708 				 			raise STOP_AUTO_PROCESSING;
2709 		 ELSIF (l_action='AUTOREDIRECT_INTERNAL') THEN
2710 				FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
2711 					l_redirect_id:=l_param_rec_tbl(l_param_index).parameter1;
2712 					EXIT;
2713 				END LOOP;
2714 				-- Need new code to complete this .
2715 				-- Create a Record for New Email Accounts in PREPROC Tables and Stop Processing for the
2716 				-- Current One
2717 				delete from iem_email_classifications where message_id=l_post_rec.message_id;
2718 				-- Fix for bug 14010115 ,update ih_interaction_id also with latest interaction_id in case new interaction is created.
2719 				-- else, row will be updated with old interaction id, in case of auto-redirect rule.
2720 				update iem_rt_preproc_emails
2721 				set email_account_id=l_redirect_id,
2722 				ih_interaction_id=l_interaction_id,
2723 				msg_status='REDIRECT',
2724 				ih_media_item_id=l_media_id
2725 				where message_id=l_post_rec.message_id;
2726 
2727 
2728 
2729 				if g_statement_log then
2730 				l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_WRAPUP inside  action = autoredirect internal';
2731 				iem_logger(l_logmessage);
2732 				end if;
2733 			IEM_EMAIL_PROC_PVT.IEM_WRAPUP(p_interaction_id=>l_interaction_id,
2734 					p_media_id=>l_media_id		,
2735 					p_milcs_id=>l_mp_milcs_id,
2736 					p_action=>null,
2737 					p_email_rec =>l_post_rec,
2738 					p_action_id=>72,
2739 					x_out_text=>l_out_text,
2740 					x_status=>l_stat );
2741 
2742 
2743 				if g_statement_log then
2744 				l_logmessage:='end IEM_EMAIL_PROC_PVT.IEM_WRAPUP inside  action = autoredirect internal status : '||l_stat||' text : '||l_out_text;
2745 				iem_logger(l_logmessage);
2746 				end if;
2747 
2748 							IF l_stat<>'S' THEN
2749 								l_logmessage:=l_out_text;
2750 								raise ABORT_PROCESSING;
2751 							END IF;
2752 					raise STOP_REDIRECT_PROCESSING;
2753 		END IF;		-- End if for both redirect actions
2754        END IF;		--End if for autoproc_result='T'
2755 -- Calling Rules Engine For Auto-Reply
2756 
2757 
2758 				if g_statement_log then
2759 				l_logmessage:='calling iem_rules_engine_pub.auto_process_email AUTORRRS';
2760 				iem_logger(l_logmessage);
2761 				end if;
2762 	iem_rules_engine_pub.auto_process_email(p_api_version_number=>1.0,
2763 									p_commit=>FND_API.G_FALSE,
2764 									p_rule_type=>'AUTORRRS',
2765 									p_keyvals_tbl=>l_class_val_tbl,
2766 									p_accountid=>l_post_rec.email_account_id,
2767 									x_result=>l_autoproc_result,
2768 									x_action=>l_action,
2769 									x_parameters=>l_param_rec_tbl,
2770 									x_return_status=>l_ret_status,
2771 									x_msg_count=>l_msg_count,
2772 									x_msg_data=>l_msg_data);
2773 
2774 
2775 				if g_statement_log then
2776 				l_logmessage:='calling iem_rules_engine_pub.auto_process_email AUTORRRS : status : '||l_ret_status||' data : '||l_msg_data;
2777 				iem_logger(l_logmessage);
2778 				end if;
2779 
2780 					IF l_ret_status<>'S' THEN
2781 						l_logmessage:='Error While Calling rules Engine for Auto-Reply';
2782 						raise ABORT_PROCESSING;
2783 					END IF;
2784 		IF ((l_autoproc_result='T') AND (l_action is not null)) THEN
2785 			IF ((l_action='AUTOREPLYSPECIFIEDDOC') AND  (l_auto_reply_flag='N')) THEN
2786 				FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
2787 				-- Add code for integration into Outbox Processing
2788 				l_email_doc_tbl(l_param_index).doc_id:=l_param_rec_tbl(l_param_index).parameter2;
2789 				l_email_doc_tbl(l_param_index).type:=l_param_rec_tbl(l_param_index).type;
2790 				END LOOP;
2791 				l_outbox_tbl.delete;
2792 				IF l_tag_keyval.count>0 THEN
2793 						FOR i IN l_tag_keyval.FIRST..l_tag_keyval.LAST LOOP
2794 							l_outbox_tbl(i).key:=l_tag_keyval(i).key;
2795 							l_outbox_tbl(i).value:=l_tag_keyval(i).value;
2796 							l_outbox_tbl(i).datatype:=l_tag_keyval(i).datatype;
2797 						END LOOP;
2798 				END IF;
2799 					if l_customer_id>0 then
2800 						l_cust_search_id:=l_customer_id;
2801 					end if;
2802 
2803 
2804 				if g_statement_log then
2805 				l_logmessage:='calling iem_email_proc_pvt.IEM_AUTOREPLY inside if';
2806 				iem_logger(l_logmessage);
2807 				end if;
2808 						IEM_AUTOREPLY(p_interaction_id=>l_interaction_id	,
2809 									p_media_id=>l_media_id,
2810 									p_post_rec=>l_post_rec,
2811 									p_doc_tbl=>l_email_doc_tbl,
2812 									p_subject=>l_header_rec.subject,
2813  									P_TAG_KEY_VALUE_TBL=>l_outbox_tbl ,
2814  									P_CUSTOMER_ID=>l_cust_search_id ,
2815  									P_RESOURCE_ID=>l_resource_id,
2816  									p_qualifiers =>l_qual_tbl,
2817 									p_fwd_address=>null,
2818 									p_fwd_doc_id=>null,
2819 									p_req_type=>'R',		--for autoreply
2820 									x_out_text=>l_out_text,
2821 									x_status=>l_stat  ) ;
2822 
2823 
2824 				if g_statement_log then
2825 				l_logmessage:='end iem_email_proc_pvt.IEM_AUTOREPLY inside if : status : '||l_stat||' text : '||l_out_text;
2826 				iem_logger(l_logmessage);
2827 				end if;
2828 
2829 						   IF l_stat='S' THEN
2830 						   		l_auto_msgstatus:='AUTOREPLY';
2831 								raise STOP_AUTO_PROCESSING;
2832 						   ELSE
2833 								l_logmessage:=l_out_text;
2834 						   END IF;
2835 
2836 		END IF;	-- End if for l_action=AUTOREPLYSPECIFIED
2837         END IF;	--	End if for autoproc_result='T'
2838 		-- Calling DOCUMENT_RETRIEVAL		11.5.10 feature
2839 				l_rule_id:=0;
2840 
2841 
2842 				if g_statement_log then
2843 				l_logmessage:='calling iem_rules_engine_pub.auto_process_email doc retrieval';
2844 				iem_logger(l_logmessage);
2845 				end if;
2846 	iem_rules_engine_pub.auto_process_email(p_api_version_number=>1.0,
2847 					p_commit=>FND_API.G_FALSE,
2848 					p_rule_type=>'DOCUMENTRETRIEVAL',
2849 					p_keyvals_tbl=>l_class_val_tbl,
2850 					p_accountid=>l_post_rec.email_account_id,
2851 					x_result=>l_autoproc_result,
2852 					x_action=>l_action,
2853 					x_parameters=>l_param_rec_tbl,
2854 					x_return_status=>l_ret_status,
2855 					x_msg_count=>l_msg_count,
2856 					x_msg_data=>l_msg_data);
2857 
2858 
2859 				if g_statement_log then
2860 				l_logmessage:='end iem_rules_engine_pub.auto_process_email doc retrieval : status : '||l_ret_status || ' text : '||l_msg_data;
2861 				iem_logger(l_logmessage);
2862 				end if;
2863 
2864 		    IF l_ret_status<>'S' THEN
2865 			   l_logmessage:='Error While Calling rules Engine for DOCUMENTRETRIEVAL';
2866 			   raise ABORT_PROCESSING;
2867 			END IF;
2868 			IF l_autoproc_result='T' THEN
2869 			 if l_action <> 'MES_CATEGORY_MAPPING'  THEN
2870 	     l_search_type:=substr(l_action,15,length(l_action));
2871 		 -- identfiying the repository to search
2872 				if l_search_type='MES' THEN
2873 					l_repos:='MES';
2874 				elsif l_search_type='KM' THEN
2875 					l_repos:='SMS';
2876 				elsif l_search_type='BOTH' THEN
2877 					l_repos:='ALL';
2878 				end if;
2879 				   l_cat_counter:=1;
2880 				   IF l_param_rec_tbl.count>0 THEN
2881 				   FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
2882 			 		IF l_param_rec_tbl(l_param_index).parameter1 <> to_char(-1)  then
2883 						IF l_param_rec_tbl(l_param_index).parameter1='RULE_ID' then
2884 							l_rule_id:=l_param_rec_tbl(l_param_index).parameter2;
2885 						ELSE
2886 							l_category_id.extend;
2887 					l_category_id(l_cat_counter):=l_param_rec_tbl(l_param_index).parameter1;
2888 							l_cat_counter:=l_cat_counter+1;
2889 						END IF;
2890 					END IF;
2891 				  END LOOP;
2892 				  END IF;
2893 			else
2894 					l_search_type:='CM';		--Category based mapping
2895 				   FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
2896 							l_cm_cat_id:=l_param_rec_tbl(l_param_index).parameter1;
2897 							EXIT;
2898 				   END LOOP;
2899 			end if;
2900 		else
2901 			l_search_type:=null;
2902 			l_cm_Cat_id:=0;
2903           end if ;		-- end if for l_autoproc_result='T'
2904 		-- CALLING ROUTING ----
2905 
2906 
2907 				if g_statement_log then
2908 				l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_ROUTING_PROC';
2909 				iem_logger(l_logmessage);
2910 				end if;
2911 
2912 IEM_EMAIL_PROC_PVT.IEM_ROUTING_PROC(
2913 					p_email_account_id=>l_post_rec.email_account_id,
2914 				p_keyval=>l_class_val_tbl,
2915 				x_routing_group_id=>l_group_id,
2916 					x_status=>l_status,
2917 		     		x_out_text=>l_out_text) ;
2918 
2919 
2920 				if g_statement_log then
2921 				l_logmessage:='end of IEM_EMAIL_PROC_PVT.IEM_ROUTING_PROC : status : '||l_status||' txt : '||l_out_text;
2922 				iem_logger(l_logmessage);
2923 				end if;
2924 
2925 
2926 	IF l_status <>'S' THEN
2927 		l_logmessage:=l_out_text;
2928 	if g_error_log then
2929 		iem_logger(l_logmessage);
2930 		raise abort_processing;
2931 	end if;
2932 	END IF;
2933 	IF l_group_id=-1 then
2934 		-- pre 11510 group id for the auto routed message is determined by first group the agent belongs to.Because of
2935 		-- supervisor agent inbox requeue message it is defaulted to 0 from 11.5.10.So that anybody can access it.
2936 			l_group_id:=0;
2937 			l_auto_flag:='Y';
2938 	END IF;
2939 
2940 
2941 				if g_statement_log then
2942 				l_logmessage:='calling IEM_RT_PROC_EMAILS_PVT.create_item after routing';
2943 				iem_logger(l_logmessage);
2944 				end if;
2945 		IEM_RT_PROC_EMAILS_PVT.create_item (
2946 					p_api_version_number => 1.0,
2947   					p_init_msg_list=>'F' ,
2948 					p_commit=>'F',
2949 				p_message_id =>l_post_rec.message_id,
2950 				p_email_account_id  =>l_post_rec.email_account_id,
2951 				p_priority  =>l_post_rec.priority,
2952 				p_agent_id  =>0,
2953 				p_group_id  =>l_group_id,
2954 				p_sent_date =>l_header_Rec.sent_date,
2955 				p_received_date =>l_post_Rec.received_Date,
2956 				p_rt_classification_id =>l_rt_classification_id,
2957 				p_customer_id=>l_customer_id    ,
2958 				p_contact_id=>g_contact_id    ,
2959 				p_relationship_id=>g_relation_id    ,
2960 				p_interaction_id=>l_interaction_id ,
2961 				p_ih_media_item_id=>l_media_id ,
2962 				p_msg_status=>l_post_rec.msg_status  ,
2963 				p_mail_proc_status=>'P' ,
2964 				p_mail_item_status=>'N' ,
2965 				p_category_map_id=>l_cm_cat_id ,
2966 				p_rule_id=>l_rule_id,
2967 				p_subject=>l_header_rec.subject,
2968 				p_sender_address=>l_sender	,
2969 				p_from_agent_id=>null,
2970      			x_return_status=>l_ret_status	,
2971   				x_msg_count=>l_msg_count	      ,
2972  				x_msg_data=>l_msg_data);
2973 
2974 
2975 				if g_statement_log then
2976 				l_logmessage:='end IEM_RT_PROC_EMAILS_PVT.create_item after routing : '||l_ret_status||' l_msg_data : '||l_msg_data;
2977 				iem_logger(l_logmessage);
2978 				end if;
2979 IF l_ret_status='S' THEN
2980 	IF l_auto_flag='Y' THEN		-- auto Routing Processing
2981 	 SAVEPOINT auto_route_main;
2982 		-- creating RT item  bug 7428636
2983 
2984 
2985 		if g_statement_log then
2986 		l_logmessage:='calling IEM_CLIENT_PUB.createRTItem';
2987 		iem_logger(l_logmessage);
2988 		end if;
2989 
2990 		IEM_CLIENT_PUB.createRTItem (p_api_version_number=>1.0,
2991 					p_init_msg_list=>'F',
2992 					p_commit=>'F',
2993    					p_message_id =>l_post_rec.message_id,
2994   					p_to_resource_id  =>l_agentid,
2995   					p_from_resource_id =>l_agentid,
2996   					p_status  =>'N',
2997   					p_reason =>'O',
2998   					p_interaction_id =>l_interaction_id,
2999   					x_return_status  =>l_ret_status,
3000   					x_msg_count =>l_msg_count,
3001   					x_msg_data   =>l_msg_data,
3002   					x_rt_media_item_id =>l_rt_media_item_id,
3003   					x_rt_interaction_id =>l_rt_interaction_id);
3004 
3005 		if g_statement_log then
3006 		l_logmessage:='end of  IEM_CLIENT_PUB.createRTItem : status : '||l_ret_status||' l_msg_data : '||l_msg_data;
3007 		iem_logger(l_logmessage);
3008 		end if;
3009 
3010 		 IF l_ret_status<>'S' THEN
3011 	if g_error_log then
3012 				l_logmessage:='Failed To Auto Route The Message due to error in create RT Item ';
3013 				iem_logger(l_logmessage);
3014 	end if;
3015 	ELSE     -- as part of bug fix 7428636
3016 	-- Able to create RT Item So do autorouting
3017 		update iem_rt_proc_emails
3018 		set resource_id=l_agentid
3019 		where message_id=l_post_rec.message_id;
3020 				-- Create MLCS for Auto Routing
3021 
3022   					l_media_lc_rec.media_id :=l_media_id ;
3023   					l_media_lc_rec.milcs_type_id := 30; --MAIL_AUTOROUTE
3024   					l_media_lc_rec.start_date_time := sysdate;
3025   					l_media_lc_rec.handler_id := 680;
3026   					l_media_lc_rec.type_type := 'Email, Inbound';
3027   					l_media_lc_rec.resource_id := l_agentid;
3028 					l_stat:='S' ; -- reset to 'S' before starting any MLCS
3029 				--	IH activity;
3030 
3031 
3032 		if g_statement_log then
3033 		l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_PROC_IH ADD MLCS for email inbound auto route ';
3034 		iem_logger(l_logmessage);
3035 		end if;
3036 						IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
3037 							p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
3038 								p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
3039 								p_interaction_rec=>l_interaction_rec,
3040 								p_activity_rec=>l_activity_rec     ,
3041 								p_media_lc_rec=>l_media_lc_Rec ,
3042 								p_media_rec=>l_media_rec	,
3043 								x_id=>l_milcs_id,
3044 								x_status=>l_stat		,
3045 			    				 x_out_text=>l_out_text	);
3046 
3047 
3048 		if g_statement_log then
3049 		l_logmessage:='end IEM_EMAIL_PROC_PVT.IEM_PROC_IH ADD MLCS for email inbound auto route status : '||l_stat||' text : '||l_out_text||' id : '||l_milcs_id;
3050 		iem_logger(l_logmessage);
3051 		end if;
3052 					IF l_stat<>'S' THEN
3053 					if g_error_log then
3054 						l_logmessage:='Error while creating MLCS for Auto Route '||l_out_text;
3055 						iem_logger(l_logmessage);
3056 						rollback to auto_route_main;
3057 					end if;
3058 					END IF;
3059 							-- Update  the Media Life Cycle for Auto Routing
3060                  if l_stat='S' then
3061  							 l_media_lc_rec.milcs_id:=l_milcs_id;
3062 
3063 
3064 
3065 
3066 		if g_statement_log then
3067 		l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_PROC_IH update MLCS for email inbound auto route ';
3068 		iem_logger(l_logmessage);
3069 		end if;
3070 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
3071 							p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
3072 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
3073 								p_interaction_rec=>l_interaction_rec,
3074 								p_activity_rec=>l_activity_rec     ,
3075 								p_media_lc_rec=>l_media_lc_Rec ,
3076 								p_media_rec=>l_media_rec	,
3077 								x_id=>l_milcs_id,
3078 								x_status=>l_stat		,
3079 			  				   x_out_text=>l_out_text	);
3080 
3081 
3082 		if g_statement_log then
3083 		l_logmessage:='end IEM_EMAIL_PROC_PVT.IEM_PROC_IH update MLCS for email inbound auto route status : '||l_stat||' text : '||l_out_text||' id : '||l_milcs_id;
3084 		iem_logger(l_logmessage);
3085 		end if;
3086 
3087 				IF l_stat<>'S' THEN
3088 					if g_error_log then
3089 						l_logmessage:='Error while updating MLCS for Auto Route '||l_out_text;
3090 						iem_logger(l_logmessage);
3091 						rollback to auto_route_main;
3092 					end if;
3093 				END IF;
3094 			  END IF; -- End If for if l_Stat='S'
3095 				 if l_stat='S' then
3096 			-- In case of autoroute update the interaction with resource id of the agent to which
3097 			-- the message is autorouted to
3098 			l_interaction_rec.interaction_id:=l_interaction_id;
3099 			l_interaction_rec.resource_id:=l_agentid;
3100 
3101 
3102 		if g_statement_log then
3103 		l_logmessage:='calling JTF_IH_PUB.Update_Interaction ';
3104 		iem_logger(l_logmessage);
3105 		end if;
3106 
3107      		JTF_IH_PUB.Update_Interaction( p_api_version     => 1.1,
3108                                   p_resp_appl_id    => TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
3109                                   p_resp_id         => TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
3110                          		p_user_id		  =>nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
3111 							p_login_id	  =>TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
3112                                   x_return_status   => l_ret_status,
3113                                   x_msg_count       => l_msg_count,
3114                                   x_msg_data        => l_msg_data,
3115                                   p_interaction_rec => l_interaction_rec
3116                                  );
3117 
3118 		if g_statement_log then
3119 		l_logmessage:='end JTF_IH_PUB.Update_Interaction status'||l_ret_status || ' txt : '||l_msg_data;
3120 		iem_logger(l_logmessage);
3121 		end if;
3122 
3123 					IF l_ret_status<>'S' THEN
3124 					IF g_error_log then
3125 							l_logmessage:='Error while updating Interactions for Auto Route ';
3126 							iem_logger(l_logmessage);
3127 					end if;
3128 						rollback to auto_route;
3129 					ELSE
3130 						if g_statement_log then
3131 							l_logmessage:='Successfully AutoRoute The Message ';
3132 							iem_logger(l_logmessage);
3133 						end if;
3134     				     END IF;  -- End If for if l_ret_status='S'
3135 					END IF; -- End if for if l_stat='S'
3136 				END IF; -- For the ELSE part  as part of bug fix 7428636
3137 			  END IF; -- End If for auto routing;
3138 
3139 ELSE
3140 
3141 
3142 		raise ERR_INSERTING;
3143  END IF;
3144 	-- Update  the Media Life Cycle for Mail processing
3145   l_media_lc_rec.milcs_id:=l_mp_milcs_id;
3146   l_media_lc_rec.milcs_type_id := 17;
3147 
3148 
3149 		if g_statement_log then
3150 		l_logmessage:='calling IEM_EMAIL_PROC_PVT.IEM_PROC_IH update MLCS after JTF call ';
3151 		iem_logger(l_logmessage);
3152 		end if;
3153 
3154 	IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
3155 				p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
3156 				p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
3157 				p_interaction_rec=>l_interaction_rec,
3158 				p_activity_rec=>l_activity_rec     ,
3159 				p_media_lc_rec=>l_media_lc_Rec ,
3160 				p_media_rec=>l_media_rec	,
3161 				x_id=>l_milcs_id,
3162 				x_status=>l_stat		,
3163 			     x_out_text=>l_out_text	);
3164 
3165 
3166 		if g_statement_log then
3167 		l_logmessage:='end IEM_EMAIL_PROC_PVT.IEM_PROC_IH update MLCS after JTF call : status : '||l_stat||' txt : '||l_out_text||' id : '||l_milcs_id;
3168 		iem_logger(l_logmessage);
3169 		end if;
3170 
3171 			IF l_stat<>'S' THEN
3172 				l_logmessage:=l_out_text;
3173 			raise ABORT_PROCESSING;
3174 			END IF;
3175 	delete from iem_rt_preproc_emails
3176 	where message_id=l_post_rec.message_id;
3177 	-- Calling the specific search at the End
3178 	if g_statement_log then
3179 		l_logmessage:='Calling Specific Search API ' ;
3180 		iem_logger(l_logmessage);
3181 	end if;
3182 	BEGIN
3183 	IF l_search_type<>'CM' THEN			-- Not a MES category based mapping
3184 			l_start_search:=1;
3185 			FOR v1 in c_class_id LOOP
3186 	IEM_EMAIL_PROC_PVT.IEM_WF_SPECIFICSEARCH(
3187     					l_post_rec.message_id  ,
3188     					l_post_rec.email_account_id ,
3189     					v1.classification_id,
3190 					l_category_id,
3191 					l_repos,
3192     					l_stat ,
3193     					l_out_text);
3194 		l_start_search:=l_start_search+1;
3195 		EXIT when l_start_search>l_intent_counter;
3196 		END LOOP;
3197 	ELSIF nvl(l_search_type,' ')='CM' and l_cm_cat_id is not null then
3198 		for v_item in c_item LOOP
3199 		select count(*) into l_kb_rank
3200 		from iem_doc_usage_stats
3201 		where kb_doc_id=v_item.item_id;
3202 		IEM_KB_RESULTS_PVT.create_item(p_api_version_number=>1.0,
3203  		  	      		p_init_msg_list=>'F' ,
3204 		    	      		p_commit=>'F'	    ,
3205 						 p_message_id =>l_post_rec.message_id,
3206 						 p_classification_id=>0,
3207  				p_email_account_id=>l_post_rec.email_account_id ,
3208  			p_document_id =>to_char(v_item.item_id),
3209  		p_kb_repository_name =>'MES',
3210  		p_kb_category_name =>'MES',
3211  			p_document_title =>v_item.item_name,
3212  p_doc_last_modified_date=>v_item.last_update_date,
3213  			p_score =>l_kb_rank,
3214  			p_url =>' ',
3215 			p_kb_delete=>'N',
3216 	p_CREATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
3217     	p_CREATION_DATE  =>SYSDATE,
3218     	p_LAST_UPDATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
3219     	p_LAST_UPDATE_DATE  =>SYSDATE,
3220     	p_LAST_UPDATE_LOGIN=>TO_NUMBER (FND_PROFILE.VALUE('LOGIN_ID')) ,
3221     	p_ATTRIBUTE1   =>null,
3222     	p_ATTRIBUTE2   =>null,
3223     	p_ATTRIBUTE3   =>null,
3224     	p_ATTRIBUTE4   =>null,
3225     	p_ATTRIBUTE5   =>null,
3226     	p_ATTRIBUTE6   =>null,
3227     	p_ATTRIBUTE7   =>null,
3228     	p_ATTRIBUTE8   =>null,
3229     	p_ATTRIBUTE9   =>null,
3230     	p_ATTRIBUTE10  =>null,
3231     	p_ATTRIBUTE11  =>null,
3232     	p_ATTRIBUTE12  =>null,
3233     	p_ATTRIBUTE13  =>null,
3234     	p_ATTRIBUTE14  =>null,
3235     	p_ATTRIBUTE15  =>null,
3236 			x_return_status=>l_ret_status,
3237 			x_msg_count=>l_msg_count,
3238 			x_msg_data=>l_msg_data);
3239 	END LOOP;
3240 	END IF;		-- Endof search_type<>'CM'
3241    	EXCEPTION WHEN OTHERS THEN
3242 		NULL;
3243 	END;
3244 	if g_statement_log then
3245 		l_logmessage:='End Of Calling Specific Search API  and end of Processing for the message ' ;
3246 		iem_logger(l_logmessage);
3247 	end if;
3248 	commit;
3249 	EXCEPTION
3250 	 when STOP_AUTO_PROCESSING THEN
3251 					-- Update  the Media Life Cycle for Mail processing  -- no need to call wrapup
3252  								 l_media_lc_rec.milcs_id:=l_mp_milcs_id;
3253  								 l_media_lc_rec.milcs_type_id := 17;
3254 
3255 		if g_statement_log then
3256 		l_logmessage:=' Calling iem_email_proc_pvt.IEM_PROC_IH update MLCS in STOP_AUTO_PROCESS';
3257 		iem_logger(l_logmessage);
3258 		end if;
3259 							iem_email_proc_pvt.IEM_PROC_IH(
3260 										p_type=>'MLCS'	,-- MEDIA/ACTIVITY/MLCS/INTERACTION
3261 										p_action=>'UPDATE'	,	-- ADD/UPDATE/CLOSE
3262 										p_interaction_rec=>l_interaction_rec,
3263 										p_activity_rec=>l_activity_rec     ,
3264 										p_media_lc_rec=>l_media_lc_Rec ,
3265 										p_media_rec=>l_media_rec	,
3266 										x_id=>l_milcs_id,
3267 										x_status=>l_stat		,
3268 			    						 x_out_text=>l_out_text	);
3269 
3270 		if g_statement_log then
3271 		l_logmessage:=' End  iem_email_proc_pvt.IEM_PROC_IH update MLCS in STOP_AUTO_PROCESS :status : '||l_stat||' txt :'||l_out_text||' id : '||l_milcs_id;
3272 		iem_logger(l_logmessage);
3273 		end if;
3274 
3275 									IF l_stat<>'S' THEN
3276 								if g_error_log then
3277 										l_logmessage:=l_out_text;
3278    										l_Error_Message := 'Abort Processing '||l_logmessage;
3279      									iem_logger(l_Error_Message);
3280 
3281 								end if;
3282 
3283 										ROLLBACK TO process_emails_pvt;
3284 										-- Timestamp the message to sent it to back of queue
3285 										update iem_rt_preproc_emails
3286 										set creation_date=sysdate
3287 										where message_id=l_post_rec.message_id;
3288 										commit;
3289 								     ELSE
3290 									-- Create a Record in IEM_RT_PROC_EMAILS_PVT
3291 
3292 		if g_statement_log then
3293 		l_logmessage:='Calling IEM_RT_PROC_EMAILS_PVT.create_item in STOP_AUTO_PROCESS';
3294 		iem_logger(l_logmessage);
3295 		end if;
3296 									IEM_RT_PROC_EMAILS_PVT.create_item (
3297 												p_api_version_number => 1.0,
3298   												p_init_msg_list=>'F' ,
3299 												p_commit=>'F',
3300 											p_message_id =>l_post_rec.message_id,
3301 											p_email_account_id  =>l_post_rec.email_account_id,
3302 											p_priority  =>l_post_rec.priority,
3303 											p_agent_id  =>-1,
3304 											p_group_id  =>-1,
3305 											p_sent_date =>l_header_Rec.sent_date,
3306 											p_received_date =>l_post_Rec.received_Date,
3307 											p_rt_classification_id =>l_rt_classification_id,
3308 											p_customer_id=>l_customer_id    ,
3309 											p_contact_id=>g_contact_id    ,
3310 											p_relationship_id=>g_relation_id    ,
3311 											p_interaction_id=>l_interaction_id ,
3312 											p_ih_media_item_id=>l_media_id ,
3313 											p_msg_status=>l_auto_msgstatus  ,
3314 											p_mail_proc_status=>'R' ,
3315 											p_mail_item_status=>null ,
3316 											p_category_map_id=>null ,
3317 											p_rule_id=>l_rule_id,
3318 											p_subject=>l_header_rec.subject,
3319 											p_sender_address=>l_sender,
3320 											p_from_agent_id=>null,
3321      										x_return_status=>l_ret_status	,
3322   											x_msg_count=>l_msg_count	      ,
3323  											x_msg_data=>l_msg_data);
3324 
3325 			if g_statement_log then
3326 			l_logmessage:=' Calling IEM_RT_PROC_EMAILS_PVT.create_item in STOP_AUTO_PROCESS :status : '||l_ret_status||' l_msg_data: '||l_msg_data;
3327 			iem_logger(l_logmessage);
3328 			end if;
3329 
3330 
3331 									IF l_ret_status<>'S' THEN
3332 								if g_error_log then
3333 										l_logmessage:='AUTOREPLY:Error While Inserting Record in Proc Emails Table ';
3334    										l_Error_Message := 'Abort Processing '||l_logmessage;
3335      									iem_logger(l_Error_Message);
3336 								end if;
3337 
3338 										ROLLBACK TO process_emails_pvt;
3339 										-- Timestamp the message to sent it to back of queue
3340 										update iem_rt_preproc_emails
3341 										set creation_date=sysdate
3342 										where message_id=l_post_rec.message_id;
3343 										commit;
3344 									ELSE
3345 											delete from iem_rt_preproc_emails where message_id=l_post_rec.message_id;
3346 											commit;
3347 									END IF;
3348 									END IF;
3349    WHEN STOP_PROCESSING THEN
3350 		delete from iem_rt_preproc_emails
3351 		where message_id=l_post_rec.message_id;
3352 					  -- Check for autoack Flag if set then send autoack.
3353 					  IF l_autoack_flag='Y' then
3354 							if g_statement_log then
3355 								l_logmessage:='Start Sending Out Autoacknowledgement' ;
3356 								iem_logger(l_logmessage);
3357 							end if;
3358     						FND_MESSAGE.Set_Name('IEM','IEM_ADM_AUTO_ACK_CUSTOMER');
3359  						FND_MSG_PUB.Add;
3360  						l_dflt_sender :=  FND_MSG_PUB.GET(FND_MSG_pub.Count_Msg,FND_API.G_FALSE);
3361 
3362 
3363 			if g_statement_log then
3364 			l_logmessage:='Calling 	IEM_EMAIL_PROC_PVT.IEM_AUTOACK in SSTOP_PROCESSING';
3365 			iem_logger(l_logmessage);
3366 			end if;
3367 
3368 					IEM_EMAIL_PROC_PVT.IEM_AUTOACK(p_email_user=>l_email_user_name,
3369 							p_mailer =>l_header_rec.from_str,
3370 							p_sender=>l_sender,
3371 							p_subject=>l_header_rec.subject,
3372 				 			 p_domain_name=>l_email_domain_name,
3373 				 			 p_document_id =>l_doc_id,
3374 				  			p_dflt_sender=>l_dflt_sender,
3375 							p_int_id=>l_interaction_id,
3376 				  			p_master_account_id=>l_post_rec.email_account_id,
3377 				 			 x_status=>l_status,
3378 				  			x_out_text=>l_out_text);
3379 
3380 			if g_statement_log then
3381 			l_logmessage:='End IEM_EMAIL_PROC_PVT.IEM_AUTOACK in SSTOP_PROCESSING status : '||l_status||' txt :'||l_out_text;
3382 			iem_logger(l_logmessage);
3383 			end if;
3384   						l_media_lc_rec.media_id :=l_media_id ;
3385   						l_media_lc_rec.milcs_type_id := 29; --MAIL_AUTOACKNOWLEDGED
3386   						l_media_lc_rec.start_date_time := sysdate;
3387   						l_media_lc_rec.handler_id := 680;
3388   						l_media_lc_rec.type_type := 'Email, Inbound';
3389 
3390 				IF l_status<>'S' THEN   -- Create MLCS after auto ack
3391 						if g_error_log then
3392 							l_logmessage:='Error In Autoack '||l_out_text;
3393 							iem_logger(l_logmessage);
3394 						end if;
3395 				ELSE
3396 
3397 
3398 			if g_statement_log then
3399 			l_logmessage:='call to IEM_EMAIL_PROC_PVT.IEM_PROC_IH ADD MLCS in else statement of stop_processing';
3400 			iem_logger(l_logmessage);
3401 			end IF;
3402 
3403 					IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
3404 						p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
3405 						p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
3406 						p_interaction_rec=>l_interaction_rec,
3407 						p_activity_rec=>l_activity_rec     ,
3408 						p_media_lc_rec=>l_media_lc_Rec ,
3409 						p_media_rec=>l_media_rec	,
3410 						x_id=>l_milcs_id,
3411 						x_status=>l_stat		,
3412 			   	  	     x_out_text=>l_out_text	);
3413 
3414 			if g_statement_log then
3415 			l_logmessage:='end to IEM_EMAIL_PROC_PVT.IEM_PROC_IH ADD MLCS in else statement of stop_processing status : '||l_stat||' txt :'||l_out_text||' id :'||l_milcs_id;
3416 			iem_logger(l_logmessage);
3417 			end IF;
3418 
3419 
3420  			 		l_media_lc_rec.milcs_id:=l_milcs_id;
3421 
3422 
3423 			if g_statement_log then
3424 			l_logmessage:='call to IEM_EMAIL_PROC_PVT.IEM_PROC_IH update MLCS in else statement of stop_processing';
3425 			iem_logger(l_logmessage);
3426 			end IF;
3427 
3428 					IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
3429 						p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
3430 						p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
3431 						p_interaction_rec=>l_interaction_rec,
3432 						p_activity_rec=>l_activity_rec     ,
3433 						p_media_lc_rec=>l_media_lc_Rec ,
3434 						p_media_rec=>l_media_rec	,
3435 						x_id=>l_milcs_id,
3436 						x_status=>l_stat		,
3437 			     		x_out_text=>l_out_text	);
3438 
3439 			if g_statement_log then
3440 			l_logmessage:='end to IEM_EMAIL_PROC_PVT.IEM_PROC_IH ADD MLCS in else statement of stop_processing status : '||l_stat||' txt :'||l_out_text;
3441 			iem_logger(l_logmessage);
3442 			end IF;
3443 				END IF;				-- End of MLCS Creation
3444 				END IF;			-- End if for if l_autoack_flag='Y';
3445 	     commit;
3446 	if g_statement_log then
3447       	l_Error_Message := 'stop Further Processing';
3448      	iem_logger(l_Error_Message);
3449 	end if;
3450    WHEN STOP_REDIRECT_PROCESSING THEN		-- Here record can not be deleted from preproc_emails table
3451 	if g_statement_log then
3452       l_Error_Message := 'stop Further Processing';
3453      	iem_logger(l_Error_Message);
3454 	end if;
3455 	     commit;
3456    WHEN ABORT_PROCESSING THEN
3457 	if g_exception_log then
3458    		l_Error_Message := 'Abort Processing Due to  Oracle Error'||sqlerrm;
3459      	iem_logger(l_Error_Message);
3460 	end if;
3461 
3462 	ROLLBACK TO process_emails_pvt;
3463 	-- Timestamp the message to sent it to back of queue
3464 	update iem_rt_preproc_emails
3465 	set creation_date=sysdate
3466 	where message_id=l_post_rec.message_id;
3467 	commit;
3468 
3469    WHEN ERR_INSERTING THEN
3470 	if g_exception_log then
3471    		l_logmessage := 'Unable To insert Record in Post MDT '||sqlerrm;
3472 		iem_logger(l_logmessage);
3473 	end if;
3474 
3475 	ROLLBACK TO process_emails_pvt;
3476 	update iem_rt_preproc_emails
3477 	set creation_date=sysdate
3478 	where message_id=l_post_rec.message_id;
3479 	commit;
3480   WHEN NO_RECORD_TO_PROCESS THEN
3481 	if g_statement_log then
3482 		l_logmessage:='No Valid Record Found For Processing';
3483 		iem_logger(l_logmessage);
3484 	end if;
3485   WHEN OTHERS THEN
3486 	if g_exception_log then
3487 		l_logmessage:='Oracle Error Encountered in Processing'||sqlerrm;
3488 		iem_logger(l_logmessage);
3489 	end if;
3490 
3491 	ROLLBACK TO process_emails_pvt;
3492 	update iem_rt_preproc_emails
3493 	set creation_date=sysdate
3494 	where message_id=l_post_rec.message_id;
3495 	commit;
3496 		null;
3497  END;
3498 	  l_count:=l_count+1;
3499        EXIT when l_count>p_count;
3500     END LOOP;
3501 -- Standard Check Of p_commit.
3502     IF FND_API.To_Boolean(p_commit) THEN
3503           COMMIT WORK;
3504      END IF;
3505 EXCEPTION
3506    WHEN FND_API.G_EXC_ERROR THEN
3507 
3508 	ROLLBACK TO process_emails_pvt;
3509         FND_MESSAGE.SET_NAME('IEM','IEM_RETRYPROCESS_EXEC_ERROR');
3510         l_Error_Message := FND_MESSAGE.GET;
3511         fnd_file.put_line(fnd_file.log, l_Error_Message);
3512         l_call_status := FND_CONCURRENT.SET_COMPLETION_STATUS('ERROR',l_Error_Message);
3513    WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
3514 
3515 	ROLLBACK TO process_emails_pvt;
3516         FND_MESSAGE.SET_NAME('IEM','IEM_RETRYPROCESS_UNXPTD_ERR');
3517         l_Error_Message := FND_MESSAGE.GET;
3518         fnd_file.put_line(fnd_file.log, l_Error_Message);
3519         l_call_status := FND_CONCURRENT.SET_COMPLETION_STATUS('ERROR',l_Error_Message);
3520    WHEN OTHERS THEN
3521 
3522 	ROLLBACK TO process_emails_pvt;
3523         FND_MESSAGE.SET_NAME('IEM','IEM_RETRYPROCESS_OTHER_ERR');
3524         l_Error_Message := SQLERRM;
3525      	fnd_file.put_line(fnd_file.log, l_Error_Message);
3526         l_call_status := FND_CONCURRENT.SET_COMPLETION_STATUS('ERROR',l_Error_Message);
3527 
3528 
3529 
3530  END	PROC_EMAILS;
3531 
3532 PROCEDURE iem_logger(l_logmessage in varchar2) IS
3533 begin
3534 	if g_statement_log THEN
3535 			if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3536 				FND_LOG.STRING(FND_LOG.LEVEL_STATEMENT,'IEM.PLSQL.IEM_EMAIL_PROC_PVT',l_logmessage);
3537 			end if;
3538 	end if;
3539 	if g_exception_log then
3540 			if( FND_LOG.LEVEL_EXCEPTION >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3541 				FND_LOG.STRING(FND_LOG.LEVEL_EXCEPTION,'IEM.PLSQL.IEM_EMAIL_PROC_PVT',l_logmessage);
3542 			end if;
3543 	 end if;
3544 	 if g_error_log then
3545 			if( FND_LOG.LEVEL_EXCEPTION >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3546 				FND_LOG.STRING(FND_LOG.LEVEL_EXCEPTION,'IEM.PLSQL.IEM_EMAIL_PROC_PVT',l_logmessage);
3547 			end if;
3548 	 end if;
3549 end iem_logger;
3550 
3551 Procedure iem_returned_msg_rec(x_msg_rec out nocopy iem_rt_preproc_emails%ROWTYPE) is
3552 	e_nowait	EXCEPTION;
3553 	PRAGMA	EXCEPTION_INIT(e_nowait, -54);
3554 	l_post_rec		iem_rt_preproc_emails%rowtype;
3555 	l_folder_name		varchar2(20):='/Inbox';
3556 	l_uid			number;
3557 	l_status			varchar2(10);
3558 	l_out_text		varchar2(1000);
3559 BEGIN
3560 	for x in ( select message_id
3561  	from iem_rt_preproc_emails
3562  	order by priority,creation_date)
3563 LOOP
3564 BEGIN
3565 	select * into x_msg_rec from iem_rt_preproc_emails
3566 	where message_id=x.message_id FOR UPDATE NOWAIT;
3567      	exit;
3568 EXCEPTION when e_nowait then
3569 		null;
3570 when others then
3571 		null ;
3572 END;
3573 END LOOP;
3574 END;
3575 PROCEDURE IEM_AUTOACK(p_email_user	 in varchar2,
3576 				  p_mailer in varchar2,
3577 				  p_sender in varchar2,
3578 				  p_subject in varchar2,
3579 				  p_domain_name	in varchar2,
3580 				  p_document_id in number,
3581 				  p_dflt_sender in varchar2,
3582 				  p_int_id	in number,
3583 				  p_master_account_id 	in number,
3584 				  x_status	OUT NOCOPY varchar2,
3585 				  x_out_text	OUT NOCOPY varchar2) IS
3586  l_str			varchar2(255);
3587 l_to_recip	varchar2(240);
3588 l_cc_recip	varchar2(240);
3589 l_index		number;
3590 l_ret		number;
3591 l_email_encrypt_tbl	IEM_SENDMAIL_PVT.email_encrypt_tbl;
3592 l_ack_sub			varchar2(250);
3593 l_status			varchar2(10);
3594 l_text_data		varchar2(500);
3595 l_reply_address	varchar2(500);
3596 l_resource_id		number;
3597 l_email_account_id	number;
3598 l_qual_tbl		 IEM_OUTBOX_PROC_PUB.QualifierRecordList;
3599  ACK_FAILED		EXCEPTION;
3600  l_ret_status		varchar2(10);
3601  l_msg_count		number;
3602  l_msg_data		varchar2(500);
3603  l_outbox_id		number;
3604  l_data			varchar2(500);
3605  l_error_text			varchar2(500);
3606  l_subject			varchar2(500);
3607 	l_msg_index_out		number;
3608 BEGIN
3609 	x_status:='S';
3610  IEM_EMAIL_PROC_PVT.IEM_GET_MERGEVAL(p_email_account_id=>p_master_account_id ,
3611 				    p_mailer=>p_mailer,
3612 				    p_dflt_sender=>p_dflt_sender	,
3613 				    p_subject=>p_subject,
3614 				    x_qual_tbl=> l_qual_tbl,
3615 				    x_status=>l_status,
3616 				    x_out_text=>l_text_data);
3617 			if l_status<>'S' THEN
3618 				raise ACK_FAILED;
3619 			end if;
3620 	-- Selecting Auto Ack. Subject which will be appended to original mail
3621 	BEGIN
3622 	select meaning||': '
3623 	into l_ack_sub
3624 	from fnd_lookups
3625 	where lookup_type='IEM_AUTO_ACKNOWLEDGE'
3626 	and lookup_code='SUBJECT';
3627 	l_subject:=substr(l_ack_sub||p_subject,1,240);
3628 	EXCEPTION WHEN OTHERS THEN
3629 		null;
3630      END;
3631 	-- Calling OP Api for sending Out Auto Acknowledgement
3632 
3633      		l_resource_id:=FND_PROFILE.VALUE_SPECIFIC('IEM_SRVR_ARES') ;
3634 			IEM_OUTBOX_PROC_PUB.createOutboxMessage(p_api_version_number=>1.0,
3635 			p_init_msg_list=>'F',
3636 			p_commit=>'F',
3637 			 P_RESOURCE_ID=>l_resource_id,
3638 			 p_application_id=>680,
3639 			 p_responsibility_id=>null,
3640 			 P_MASTER_ACCOUNT_ID=>p_master_account_id,
3641 			 P_TO_ADDRESS_LIST=>p_sender,
3642 			 p_cc_address_list=>null ,
3643 			 p_bcc_address_list=>null,
3644 			 P_SUBJECT=>l_subject,
3645 			 P_SR_ID=>null,
3646 			 P_CUSTOMER_ID=>null,
3647 			 P_CONTACT_ID=>g_contact_id,
3648 			 P_INTERACTION_ID=>p_int_id,
3649 			 p_qualifiers =>l_qual_tbl     ,
3650 			 P_MESSAGE_TYPE=>null,
3651 			 P_ENCODING=>null,
3652 			 P_CHARACTER_SET=>null,
3653 			 p_option=>'A',
3654 			 p_relationship_id=>g_relation_id,
3655 			 X_OUTBOX_ITEM_ID=>l_outbox_id,
3656 			 X_RETURN_STATUS=>l_ret_status,
3657 			 X_MSG_COUNT=>l_msg_count,
3658 			 X_MSG_DATA=>l_msg_data);
3659 	if l_ret_status<>'S' THEN
3660 		x_out_text:='Failed in createoutbox message '||l_text_data;
3661 		raise ACK_FAILED;
3662 	end if;
3663 			IEM_OUTBOX_PROC_PUB.insertDocument(
3664  			   p_api_version_number=>1.0    ,
3665    			   p_outbox_item_id=>l_outbox_id,
3666                   p_document_source=>'MES'       ,
3667                   p_document_id =>p_document_id ,
3668                   X_RETURN_STATUS=>l_ret_status,
3669 			   X_MSG_COUNT=>l_msg_count,
3670  			   X_MSG_DATA=>l_msg_data);
3671 	if l_ret_status<>'S' THEN
3672 		x_out_text:='Failed in insert document  '||l_text_data;
3673 		raise ACK_FAILED;
3674 	end if;
3675  				IEM_OUTBOX_PROC_PUB.submitOutboxMessage(
3676 				    p_api_version_number=>1.0    ,
3677 				    p_init_msg_list=>'F',
3678   				    p_commit  => 'F',
3679                         p_outbox_item_id=>l_outbox_id  ,
3680 				    p_preview_bool=>'N',
3681                         X_RETURN_STATUS=>l_ret_status,
3682                         X_MSG_COUNT=>l_msg_count,
3683                         X_MSG_DATA=>l_msg_data);
3684 	if l_ret_status<>'S' THEN
3685 		x_out_text:='Failed in submit  request  '||l_text_data;
3686 		raise ACK_FAILED;
3687 	end if;
3688 		x_status:='S';
3689 		x_out_text:='Send Acknowledgement Successfully';
3690    EXCEPTION WHEN ACK_FAILED THEN
3691 		x_status:='E';
3692     IF (l_msg_count >= 1) THEN
3693       --Only one error
3694       FND_MSG_PUB.Get(p_msg_index => FND_MSG_PUB.G_FIRST,
3695                       p_encoded=>'F',
3696                       p_data=>l_data,
3697                      p_msg_index_out=>l_msg_index_out);
3698       l_error_text:= substr(l_data,1,500);
3699       If (l_msg_count > 1) THEN
3700       --Display all the error messages
3701       	FOR j in  2..FND_MSG_PUB.Count_Msg LOOP
3702         	FND_MSG_PUB.Get(p_msg_index => FND_MSG_PUB.G_NEXT,
3703                         	p_encoded=>'F',
3704                         	p_data=>l_data,
3705                         	p_msg_index_out=>l_msg_index_out);
3706       	l_error_text:= l_error_text||substr(l_data,1,500);
3707       	END LOOP;
3708      END IF;
3709     END IF;
3710 		x_out_text:=x_out_text||l_error_text;
3711    When Others then
3712 		x_out_text:='Oracle Error During sendmail Processings '||sqlerrm;
3713 		x_status:='E';
3714    END;
3715 /* This Procedure is invoked for running the customised workflow.
3716 It return the following status .'Y' Process futher . 'N' Not required
3717 to process anymore . 'E' Returns an Error .
3718 */
3719 PROCEDURE IEM_INVOKE_WORKFLOW(p_message_id in number,
3720 						p_source_message_id in number,
3721   						p_message_size in number,
3722   						p_sender_name  in varchar2,
3723   						p_user_name in varchar2,
3724   						p_domain_name   in varchar2,
3725   						p_priority     in varchar2,
3726   						p_message_status in varchar2,
3727   						p_email_account_id in number,
3728 						x_wfoutval	out NOCOPY varchar2,
3729                			x_status out NOCOPY varchar2,
3730 						x_out_text out NOCOPY varchar2) IS
3731 
3732  PRAGMA autonomous_transaction;
3733  l_itemkey		varchar2(30);
3734  l_process			varchar2(1);
3735  l_class			number;
3736  l_stat			varchar2(10);
3737  l_outval			varchar2(200);
3738  l_out_text		varchar2(500);
3739  l_count			number;
3740  l_comp_id		number;	-- rt comps id
3741  l_wf_value		varchar2(500);
3742  l_ret_status		varchar2(10);
3743  l_msg_count		number;
3744  l_msg_data		varchar2(500);
3745  l_uid			number;
3746  l_status			varchar2(100);
3747  l_category_id     AMV_SEARCH_PVT.amv_number_varray_type:=AMV_SEARCH_PVT.amv_number_varray_type();
3748  CUSTOM_WF_EXCEP    EXCEPTION;
3749  MOVE_MSG_EXCEP    EXCEPTION;
3750  PROC_ERROR    EXCEPTION;
3751  PROCESS_BEFORE    EXCEPTION;
3752  BEGIN
3753 	-- Check whether the Workflow is already called for this message or not.
3754 	-- May be called by a profile value later
3755 	begin
3756 		select value into l_outval
3757 		from iem_comp_rt_stats
3758 		where type='WORKFLOW' AND param=to_char(p_message_id);
3759 		raise PROCESS_BEFORE;
3760 	exception when others then
3761 		null;
3762 	end;
3763 -- Call the specific search API
3764 	BEGIN
3765 			select classification_id into l_class
3766 			from iem_email_classifications
3767 			where message_id=p_message_id
3768 			and score = (select max(score) from iem_email_classifications
3769 			where message_id=p_message_id)
3770 			and rownum=1;
3771 	IEM_EMAIL_PROC_PVT.IEM_WF_SPECIFICSEARCH(
3772     					p_message_id  ,
3773     					p_email_account_id ,
3774     					l_class,
3775 					l_category_id,
3776 					null,		-- KB search based on profile value
3777     					l_stat ,
3778     					l_out_text);
3779     EXCEPTION WHEN OTHERS THEN
3780 		NULL;
3781     END;
3782    SELECT TO_CHAR(iem.IEM_MAILPREPROCWF_S1.nextval)
3783    INTO l_itemkey
3784    FROM dual;
3785 
3786 
3787 	IEM_MAILPREPROCWF_PUB.IEM_STARTPROCESS(
3788 			WorkflowProcess=>'MAILPREPROC',
3789   			ItemType=>'IEM_MAIL',
3790   			ItemKey=>l_itemkey,
3791   			p_itemuserkey =>'iemmail_preproc',
3792   			p_msgid =>p_message_id,
3793   			p_msgsize =>p_message_size,
3794   			p_sender=>p_sender_name,
3795   			p_username =>p_user_name,
3796   			p_domain=>p_domain_name,
3797   			p_priority=>p_priority,
3798   			p_msg_status =>p_message_status,
3799   			p_email_account_id=>p_email_account_id,
3800 			p_flow=>'N',
3801 			x_outval=>l_outval,
3802 			x_process=>l_process);
3803 
3804 		IF	IEM_Mailpreprocwf_PUB.G_STAT='E' then
3805 			raise CUSTOM_WF_EXCEP;
3806 		end if;
3807 
3808 	IEM_COMP_RT_STATS_PVT.create_item(p_api_version_number =>1.0,
3809                         p_init_msg_list => FND_API.G_FALSE,
3810                         p_commit         => FND_API.G_FALSE,
3811                         p_type => 'WORKFLOW',
3812                         p_param => p_message_id,
3813                         p_value => l_outval,
3814                         x_return_status  => l_stat,
3815                         x_msg_count      => l_count,
3816                         x_msg_data      => l_msg_data
3817                         );
3818 		if l_stat<>'S' THEN
3819 			x_out_text:='Error while logging WF Return Value';
3820 			raise PROC_ERROR;
3821 		end if;
3822 	x_wfoutval:=l_outval;
3823 	x_status:=l_process;
3824 	x_out_text:='Complete WF Processing ';
3825 	commit;
3826 	IF l_process='N' THEN		-- move the message to /Resolved folder
3827 			null;		-- incorporate appropriate changes later
3828 	END IF;
3829  EXCEPTION WHEN CUSTOM_WF_EXCEP THEN
3830 	x_status:='E';
3831 	x_out_text:=' Workflow Process Returns Error '||sqlerrm;
3832 	rollback;
3833  WHEN MOVE_MSG_EXCEP THEN
3834 	x_status:='E';
3835 	x_out_text:='Error while moving the message to Resolved Folder';
3836 	rollback;
3837  WHEN PROC_ERROR THEN
3838 	x_status:='E';
3839 	rollback;
3840  WHEN PROCESS_BEFORE THEN
3841 	x_status:='S';
3842 	x_wfoutval:=l_outval;
3843 	x_out_text:='Complete WF Processing ';
3844 	commit;
3845  WHEN OTHERS THEN
3846 	x_status:='E';
3847 	x_out_text:=' Oracle Error  Customise WF Processing '||sqlerrm;
3848 	rollback;
3849  END;
3850 
3851 PROCEDURE		IEM_SRSTATUS_UPDATE(p_sr_id	in number,
3852 							p_status_id in number,
3853 							p_email_rec in iem_rt_preproc_emails%rowtype,
3854 							x_status  out NOCOPY varchar2,
3855 							x_out_text out NOCOPY varchar2) IS
3856 
3857 l_service_request_rec          CS_ServiceRequest_PUB.service_request_rec_type;
3858 l_request_id  NUMBER;
3859 l_object_version_number  NUMBER;
3860 l_request_number VARCHAR2(64);
3861 l_sr_number		number;
3862 l_sr_status		varchar2(100);
3863 l_status_id		number;
3864 l_party_id		number;
3865 l_ret_status		varchar2(10);
3866 l_msg_count		number;
3867 l_count		number;
3868 l_interaction_id		number;
3869 l_msg_data		varchar2(500);
3870  l_out_text		varchar2(500);
3871  l_uid			number;
3872  l_status_flag		varchar2(100);
3873  l_str				varchar2(1000);
3874 Type get_data is REF CURSOR;
3875 c1		get_data;
3876 SR_STATUS_UPD_FAIL	EXCEPTION;
3877 BEGIN
3878 			-- code for auto sr update
3879 		x_status:='S';
3880 				-- select object version number
3881 		BEGIN
3882 			open c1 for
3883 				'select object_version_number,status_flag from cs_incidents_all_b where incident_id=:sr_id' using p_sr_id;
3884 LOOP
3885 	fetch c1 into l_object_version_number,l_status_flag;
3886 	exit;
3887 end loop;
3888 		EXCEPTION WHEN OTHERS THEN
3889 			x_out_Text:='Oracle Error for SR# '||p_sr_id|| 'While selecting object version number '||sqlerrm;
3890 				raise SR_STATUS_UPD_FAIL;
3891 		END;
3892 		IF (l_object_version_number is null) OR (l_status_flag is null) then
3893 			x_out_text:='Invalid  SR ID In the Tag Data # '||p_sr_id;
3894 			raise SR_STATUS_UPD_FAIL;
3895 		END IF;
3896 		IF l_status_flag<>'C' THEN		-- SR is not closed so we can update
3897 			l_status_id:=p_status_id;
3898  		     IEM_ServiceRequest_PVT.Update_Status_Wrap
3899   				( p_api_version =>2.0,
3900     				p_init_msg_list =>fnd_api.g_true,
3901 				p_commit => fnd_api.g_false,
3902                     p_resp_appl_id  => TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
3903                     p_resp_id       => TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
3904                    	p_user_id		  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
3905        			x_return_status =>l_ret_status,
3906     				x_msg_count=>l_msg_count,
3907     				x_msg_data =>l_msg_data,
3908     				p_request_id =>p_sr_id,
3909 				p_object_version_number =>l_object_version_number,
3910 				p_status_id=>l_status_id,
3911 				p_status=>l_sr_status,
3912  				x_interaction_id=>l_interaction_id);
3913 				IF l_ret_status<>'S' THEN
3914 				x_out_text:='SR update Status Api fails for SR# '||p_sr_id;
3915       FND_MSG_PUB.Get(p_msg_index => FND_MSG_PUB.G_FIRST,
3916                       p_encoded=>'F',
3917                       p_data=>l_str,
3918                      p_msg_index_out=>l_msg_count);
3919 				raise SR_STATUS_UPD_FAIL;
3920 				END IF;
3921 		x_status:='S';
3922 		x_out_text:='Successfully Update the SR '||p_sr_id;
3923 		ELSE
3924 			x_status:='E';
3925 			x_out_text:='SR '||p_sr_id||' is Closed  Hence Not updated ';
3926 		END IF;
3927 EXCEPTION WHEN SR_STATUS_UPD_FAIL THEN
3928 		x_status:='E';
3929 		x_out_text:=l_str;
3930 WHEN OTHERS THEN
3931 	x_out_text:='Error Encoutered While updating status of SR# '||p_sr_id||sqlerrm;
3932 	x_status:='E';
3933 end ;
3934 
3935 PROCEDURE IEM_CLASSIFICATION_PROC(
3936 				p_email_account_id	in number,
3937 				p_keyval   in iem_route_pub.keyVals_tbl_type,
3938 			x_rt_classification_id		out NOCOPY number,
3939 			x_status		out NOCOPY varchar2,
3940 		     x_out_text	out NOCOPY  varchar2) IS
3941 
3942 	l_ret_status			varchar2(10);
3943 	l_msg_count			number;
3944 	l_msg_data			varchar2(500);
3945 	CLASS_EXCEPTION		EXCEPTION;
3946 BEGIN
3947 	x_status:='S';
3948 	IEM_ROUTE_CLASS_PUB.CLASSIFY(
3949 	p_api_version_number=>1.0,
3950 	p_keyVals_tbl=>p_keyval,
3951 	p_accountId=>p_email_account_id,
3952 	x_classificationId=>x_rt_classification_id,
3953 	x_return_status=>l_ret_status,
3954 	x_msg_count=>l_msg_count,
3955 	x_msg_data=>l_msg_data);
3956 	IF l_ret_status <>'S' THEN
3957 	x_out_text:='classification engine return Error abandoning further Processing ';
3958 		raise class_exception;
3959 	END IF;
3960 	x_status:='S';
3961 	x_out_text:='Successfully Processed Classification Engine and Returned Classification Id '||x_rt_classification_id;
3962 EXCEPTION
3963 	WHEN class_exception THEN
3964 		x_status:='E';
3965 	WHEN OTHERS THEN
3966 		x_status:='E';
3967 	x_out_text:='Classification Processing Encountered Oracle Error '||sqlerrm;
3968 END IEM_CLASSIFICATION_PROC;
3969 
3970 PROCEDURE IEM_ROUTING_PROC(
3971 				p_email_account_id	in number,
3972 				p_keyval   in iem_route_pub.keyVals_tbl_type,
3973 				x_routing_group_id		out NOCOPY number,
3974 					x_status		out NOCOPY varchar2,
3975 					 x_out_text	out NOCOPY  varchar2) IS
3976 	KeyValuePairs 	iem_route_pub.KeyVals_tbl_type;
3977 	l_counter				number;
3978 	l_ret_status			varchar2(10);
3979 	l_msg_count			number;
3980 	l_msg_data			varchar2(500);
3981 	ROUTE_EXCEPTION		EXCEPTION;
3982 BEGIN
3983 		IEM_ROUTE_PUB.ROUTE(
3984 				P_API_VERSION_NUMBER =>1.0,
3985 				P_KEYVALS_TBL =>p_keyval,
3986 				P_ACCOUNTID =>p_email_account_id,
3987 				X_GROUPID =>x_routing_group_id,
3988 				X_RETURN_STATUS  =>l_ret_status,
3989 				X_MSG_COUNT =>l_msg_count,
3990 				X_MSG_DATA  =>l_msg_data);
3991 	IF l_ret_status <>'S' THEN
3992 	x_out_text:='Routing engine return Error abandoning further Processing ';
3993 		raise route_exception;
3994 	END IF;
3995 	x_status:='S';
3996 	x_out_text:='Successfully Processed Routing Engine and Returned Group Id '||x_routing_group_id;
3997 EXCEPTION
3998 	WHEN route_exception THEN
3999 		x_status:='E';
4000 	WHEN OTHERS THEN
4001 		x_status:='E';
4002 	x_out_text:='Routing Processing Encountered Oracle Error '||sqlerrm;
4003 END IEM_ROUTING_PROC;
4004 
4005 PROCEDURE IEM_PROC_IH(
4006 				p_type		in varchar2,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
4007 				p_action		in varchar2,		-- ADD/UPDATE/CLOSE
4008  				p_interaction_rec IN       JTF_IH_PUB.interaction_rec_type,
4009 				p_activity_rec      IN     JTF_IH_PUB.activity_rec_type,
4010 				p_media_lc_rec IN  JTF_IH_PUB.media_lc_rec_type,
4011 				p_media_rec	IN  JTF_IH_PUB.media_rec_type,
4012 				x_id			OUT NOCOPY NUMBER,
4013 				x_status		out NOCOPY varchar2,
4014 			     x_out_text	out NOCOPY  varchar2) IS
4015 	l_media_id		number;
4016 	l_milcs_id		number;
4017 	l_interaction_id		number;
4018  	l_activity_rec        JTF_IH_PUB.activity_rec_type;
4019 	l_activity_id		number;
4020 	l_ret_status		varchar2(10);
4021 	l_msg_data		varchar2(1500);
4022 	l_data		varchar2(1500);
4023 	l_error_text		varchar2(1500):=' ';
4024 	l_msg_count		number;
4025 	l_msg_index_out		number;
4026 	IH_EXCEPTION		EXCEPTION;
4027 BEGIN
4028 	if p_type='MEDIA' THEN
4029 		if p_action='ADD' THEN
4030 			JTF_IH_PUB.Open_MediaItem(1.0,
4031                           'T',
4032                           'F',
4033 					TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
4034 					TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
4035                          nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
4036 					TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
4037               			l_ret_status,
4038                   		l_msg_count,
4039                     	l_msg_data,
4040             			p_media_rec,
4041               			l_media_id);
4042 					if l_ret_status<>'S' then
4043 						x_out_text:='Error While Creating Media Item '||sqlerrm;
4044 						raise IH_EXCEPTION;
4045 					else
4046 						x_id:=l_media_id;
4047 					end if;
4048 
4049 		  elsif p_action='UPDATE' THEN
4050 
4051   				JTF_IH_PUB.Update_MediaItem( 1.0,
4052 						'T',
4053 						'F',
4054 						TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
4055 						TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
4056 						nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
4057 						TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
4058 						l_ret_status,
4059 						l_msg_count,
4060 						l_msg_data,
4061 						p_media_rec);
4062 					if l_ret_status<>'S' then
4063 						x_out_text:='Error While Updating Media Item ';
4064 						raise IH_EXCEPTION;
4065 					end if;
4066 		  elsif p_action='CLOSE' THEN
4067 
4068   				JTF_IH_PUB.Close_MediaItem( 1.0,
4069 						'T',
4070 						'F',
4071 						TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
4072 						TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
4073 						nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
4074 						TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
4075 						l_ret_status,
4076 						l_msg_count,
4077 						l_msg_data,
4078 						p_media_rec);
4079 					if l_ret_status<>'S' then
4080 						x_out_text:='Error While Closing Media Item ';
4081 						raise IH_EXCEPTION;
4082 					end if;
4083 		  end if;
4084 	elsif p_type='MLCS' THEN
4085 		if p_action='ADD' THEN
4086   			JTF_IH_PUB.Add_MediaLifeCycle( 1.0,
4087 						'T',
4088 						'F',
4089 						TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
4090 						TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
4091 						nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
4092 						TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
4093 						l_ret_status,
4094 						l_msg_count,
4095 						l_msg_data,
4096 						p_media_lc_rec,
4097 						l_milcs_id);
4098 
4099 					if l_ret_status<>'S' then
4100 						x_out_text:='Error While Creating Media Life Cycle ';
4101 						raise IH_EXCEPTION;
4102 					else
4103 						x_id:=l_milcs_id;
4104 					end if;
4105 		elsif p_action='UPDATE' THEN
4106   			JTF_IH_PUB.Update_MediaLifeCycle( 1.0,
4107 						'T',
4108 						'F',
4109 						TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
4110 						TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
4111 						nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
4112 						TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
4113 						l_ret_status,
4114 						l_msg_count,
4115 						l_msg_data,
4116 						p_media_lc_rec);
4117 					if l_ret_status<>'S' then
4118 						x_out_text:='Error While Updating Media Life Cycle ';
4119 						raise IH_EXCEPTION;
4120 					end if;
4121 		end if;
4122 	elsif p_type='INTERACTION' THEN
4123 		IF p_action='ADD' THEN
4124 
4125      		JTF_IH_PUB.Open_Interaction( p_api_version     => 1.1,
4126                                   p_resp_appl_id    => TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
4127                                   p_resp_id         => TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
4128                          		p_user_id		  =>nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
4129 							p_login_id	  =>TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
4130                                   x_return_status   => l_ret_status,
4131                                   x_msg_count       => l_msg_count,
4132                                   x_msg_data        => l_msg_data,
4133                                   x_interaction_id  => l_interaction_id,
4134                                   p_interaction_rec => p_interaction_rec
4135                                  );
4136 					if l_ret_status<>'S' then
4137 						x_out_text:='Error While Creating Interaction ';
4138 						raise IH_EXCEPTION;
4139 					else
4140 						   x_id:=l_interaction_id;
4141 					end if;
4142 		ELSIF p_action='UPDATE' THEN
4143      		JTF_IH_PUB.Update_Interaction( p_api_version     => 1.1,
4144                                   p_resp_appl_id    => TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
4145                                   p_resp_id         => TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
4146                          		p_user_id		  =>nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
4147 							p_login_id	  =>TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
4148                                   x_return_status   => l_ret_status,
4149                                   x_msg_count       => l_msg_count,
4150                                   x_msg_data        => l_msg_data,
4151                                   p_interaction_rec => p_interaction_rec
4152                                  );
4153 					IF l_ret_status<>'S' THEN
4154 						x_out_text:='Error While Updating Interaction ';
4155 						raise IH_EXCEPTION;
4156 					END IF;
4157 		ELSIF p_action='CLOSE' THEN
4158      		JTF_IH_PUB.Close_Interaction( p_api_version     => 1.1,
4159                                   p_resp_appl_id    => TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
4160                                   p_resp_id         => TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
4161                          		p_user_id		  =>nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
4162 							p_login_id	  =>TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
4163                                   x_return_status   => l_ret_status,
4164                                   x_msg_count       => l_msg_count,
4165                                   x_msg_data        => l_msg_data,
4166                                   p_interaction_rec => p_interaction_rec);
4167 					IF l_ret_status<>'S' THEN
4168 						x_out_text:='Error While Closing Interaction ';
4169 						raise IH_EXCEPTION;
4170 					END IF;
4171 		END IF;
4172 	elsif p_type='ACTIVITY' THEN
4173 		IF p_action='ADD' THEN
4174 					l_activity_rec:=p_activity_rec;
4175 				BEGIN
4176 					select wu.outcome_id, wu.result_id, wu.reason_id INTO
4177  					l_activity_rec.outcome_id, l_activity_rec.result_id, l_activity_rec.reason_id
4178         				from jtf_ih_action_action_items aa, jtf_ih_wrap_ups wu
4179         				where aa.action_id =l_activity_rec.action_id
4180 					and aa.action_item_id = l_activity_rec.action_item_id
4181         				and aa.default_wrap_id = wu.wrap_id;
4182 				EXCEPTION WHEN OTHERS THEN
4183 							NULL;
4184 				END;
4185          		JTF_IH_PUB.Add_Activity(p_api_version     => 1.0,
4186                                  p_resp_appl_id  => TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
4187                                  p_resp_id       => TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
4188                          		p_user_id		  =>nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
4189 							p_login_id	  =>TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
4190                                  x_return_status => l_ret_status,
4191                                  x_msg_count     => l_msg_count,
4192                                  x_msg_data      => l_msg_data,
4193                                  p_activity_rec  => l_activity_rec,
4194                                  x_activity_id   => l_activity_id
4195                                  );
4196 					if l_ret_status<>'S' then
4197 						x_out_text:='Error While Creating Activity ';
4198 						raise IH_EXCEPTION;
4199 					else
4200 						   x_id:=l_activity_id;
4201 					end if;
4202 		END IF;
4203 	end if;
4204 		x_Status:='S';
4205 EXCEPTION
4206 	WHEN IH_EXCEPTION THEN
4207 		x_status:='E';
4208     IF (l_msg_count >= 1) THEN
4209       --Only one error
4210       FND_MSG_PUB.Get(p_msg_index => FND_MSG_PUB.G_FIRST,
4211                       p_encoded=>'F',
4212                       p_data=>l_data,
4213                      p_msg_index_out=>l_msg_index_out);
4214       l_error_text:= substr(l_data,1,500);
4215     END IF;
4216 		x_out_text:=x_out_text||l_error_text;
4217 	WHEN OTHERS THEN
4218 		x_status:='E';
4219 	x_out_text:='Interaction History  Processing Encountered Oracle Error '||sqlerrm;
4220 END IEM_PROC_IH;
4221 
4222 PROCEDURE		IEM_WRAPUP(p_interaction_id	in number,
4223 					p_media_id		in number,
4224 					p_milcs_id		in number,
4225 					p_action		in varchar2,
4226 					p_email_rec in iem_rt_preproc_emails%rowtype,
4227 					p_action_id	in number,
4228 					x_out_text		out NOCOPY varchar2,
4229 					x_status  out NOCOPY varchar2) IS
4230 
4231 l_media_rec	JTF_IH_PUB.media_rec_type;
4232 l_interaction_rec        JTF_IH_PUB.interaction_rec_type;
4233 l_stat			varchar2(10);
4234 l_out_text		varchar2(500);
4235 l_uid			number;
4236 l_milcs_id		number;
4237 l_interaction_id	number;
4238 l_media_lc_rec 	JTF_IH_PUB.media_lc_rec_type;
4239 l_action_id		number;
4240 l_activity_rec        JTF_IH_PUB.activity_rec_type;
4241 WRAPUP_ERROR		EXCEPTION;
4242 l_ret_status		varchar2(10);
4243 l_msg_data		varchar2(300);
4244 l_msg_count		number;
4245 begin
4246 					-- Update the mail Processing Life Cycles
4247  							 l_media_lc_rec.milcs_id:=p_milcs_id;
4248 							IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
4249 								p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
4250 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
4251 								p_interaction_rec=>l_interaction_rec,
4252 								p_activity_rec=>l_activity_rec     ,
4253 								p_media_lc_rec=>l_media_lc_Rec ,
4254 								p_media_rec=>l_media_rec	,
4255 								x_id=>l_milcs_id,
4256 								x_status=>l_stat		,
4257 			  				   x_out_text=>l_out_text	);
4258 
4259 							IF l_stat<>'S' THEN
4260 								x_out_text:=l_out_text;
4261 								raise WRAPUP_ERROR;
4262 							END IF;
4263 		IF p_action is not null  THEN
4264 		-- incase of auto redirect this is set to null
4265 								l_interaction_rec.interaction_id:=p_interaction_id;
4266 								BEGIN
4267 									select wu.outcome_id, wu.result_id, wu.reason_id into
4268  									l_interaction_rec.outcome_id,
4269 									l_interaction_rec.result_id,
4270 									l_interaction_rec.reason_id
4271         								from jtf_ih_action_action_items aa, jtf_ih_wrap_ups wu
4272         								where aa.action_id =p_action_id
4273 									and aa.action_item_id = 45
4274         								and aa.default_wrap_id = wu.wrap_id;
4275 								EXCEPTION WHEN OTHERS THEN
4276 									null;
4277 								END;
4278 								IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
4279 								p_type=>'INTERACTION'		,	-- MEDIA/ACTIVITY/MLCS/INTERACTION
4280 								p_action=>'CLOSE'		,		-- ADD/UPDATE/CLOSE
4281 								p_interaction_rec=>l_interaction_rec,
4282 								p_activity_rec=>l_activity_rec     ,
4283 								p_media_lc_rec=>l_media_lc_Rec ,
4284 								p_media_rec=>l_media_rec	,
4285 								x_id=>l_interaction_id,
4286 								x_status=>l_stat		,
4287 			  				     x_out_text=>l_out_text	);
4288 								IF l_stat<>'S' THEN
4289 									x_out_text:=l_out_text;
4290 									raise WRAPUP_ERROR;
4291 								END IF;
4292 							--Closing the media Item
4293 								l_media_rec.media_id:=p_media_id;
4294 								IEM_EMAIL_PROC_PVT.IEM_PROC_IH(
4295 									p_type=>'MEDIA'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
4296 									p_action=>'CLOSE'		,		-- ADD/UPDATE/CLOSE
4297 									p_interaction_rec=>l_interaction_rec,
4298 									p_activity_rec=>l_activity_rec     ,
4299 									p_media_lc_rec=>l_media_lc_Rec ,
4300 									p_media_rec=>l_media_rec	,
4301 									x_id=>l_interaction_id,
4302 									x_status=>l_stat		,
4303 			   			 		 	x_out_text=>l_out_text	);
4304 
4305 								IF l_stat<>'S' THEN
4306 									raise WRAPUP_ERROR;
4307 								END IF;
4308 
4309 							IEM_MAILITEM_PUB.ResolvedMessage (p_api_version_number=>1.0 ,
4310  		  	     				 p_init_msg_list=>'F'  ,
4311 		    	     				 p_commit=>'F'	    ,
4312 								 p_message_id=>p_email_rec.message_id,
4313 								 p_action_flag=>p_action	,
4314 			     				 x_return_status=>l_ret_status,
4315   		  	     				 x_msg_count=>l_msg_count ,
4316 								 x_msg_data=>l_msg_data);
4317 								IF l_ret_status<>'S' THEN
4318 									l_out_text:='Error in Moving Message '||sqlerrm;
4319 									raise WRAPUP_ERROR;
4320 								END IF;
4321 						END IF;		-- for p_action is not null
4322 			x_status:='S';
4323 EXCEPTION WHEN WRAPUP_ERROR THEN
4324 		x_out_text:=l_out_text;
4325 		x_status:='E';
4326 WHEN OTHERS THEN
4327 	x_out_text:='Oracle Error Encountered in Wrapup '||sqlerrm;
4328 	x_status:='E';
4329 end	IEM_WRAPUP;
4330 
4331 PROCEDURE		IEM_AUTOREPLY(p_interaction_id	in number,
4332 					p_media_id		in number,
4333 					p_post_rec		in iem_rt_preproc_emails%rowtype,
4334 					p_doc_tbl		in email_doc_tbl,
4335 					p_subject		in varchar2,
4336  					P_TAG_KEY_VALUE_TBL in IEM_OUTBOX_PROC_PUB.keyVals_tbl_type,
4337  					P_CUSTOMER_ID in number,
4338  					P_RESOURCE_ID in number,
4339  					p_qualifiers in IEM_OUTBOX_PROC_PUB.QualifierRecordList,
4340 					p_fwd_address in varchar2,
4341 					p_fwd_doc_id in number,
4342 					p_req_type in varchar2,
4343 					x_out_text		out NOCOPY varchar2,
4344 					x_status  out NOCOPY varchar2) IS
4345 	l_outbox_id		number;
4346 	l_ret_status		varchar2(100);
4347 	l_msg_count		number;
4348 	l_msg_data		varchar2(500);
4349 	AUTOREPLY_ERROR	EXCEPTION;
4350 	l_folder_name		varchar2(240);
4351 	l_file_name		varchar2(256);
4352 	l_ext_subject		varchar2(100);
4353 	l_data			varchar2(500);
4354 	l_msg_index_out		varchar2(10);
4355 	l_qual_tbl		 IEM_OUTBOX_PROC_PUB.QualifierRecordList;
4356 	l_error_text		varchar2(1000);
4357 	l_dflt_sender		varchar2(250);
4358 	l_sender			varchar2(256);
4359 	l_from1			number;
4360 	l_from2			number;
4361  	l_header_rec			iem_ms_base_headers%rowtype;
4362 	l_notification_id	number;
4363 BEGIN
4364 select * into l_header_rec from iem_ms_base_headers
4365 where message_id=p_post_rec.message_id;
4366 	l_from1:=instr(l_header_rec.from_str,'<',1,1);
4367 	l_from2:=instr(l_header_rec.from_str,'>',1,1);
4368 	IF l_from1>0 then		-- From Address Contains Both Name and Address
4369 		l_sender:=substr(l_header_rec.from_Str,l_from1+1,l_from2-l_from1-1);
4370 	ELSE					-- From Address contains only Address
4371 		l_sender:=l_header_rec.from_str;
4372 	END IF;
4373 if p_req_type='R' then			-- Autoreply
4374 IEM_OUTBOX_PROC_PUB.createautoreply(p_api_version_number=>1.0,
4375  p_init_msg_list=>'F',
4376  p_commit=>'F',
4377  P_MEDIA_ID=>p_media_id,			--- Then next 3 parameter will be null
4378  P_RFC822_MESSAGE_ID =>null,
4379  p_folder_name=>null,
4380  P_MESSAGE_UID =>null,
4381  P_MASTER_ACCOUNT_ID=>p_post_rec.email_account_id,
4382  P_TO_ADDRESS_LIST=>l_sender,		-- need to pass sender name
4383  p_cc_address_list=>null ,
4384  p_bcc_address_list=>null,
4385  P_SUBJECT=>l_header_rec.subject,
4386  P_TAG_KEY_VALUE_TBL=>p_tag_key_value_tbl,
4387  P_CUSTOMER_ID=>p_customer_id,
4388  P_INTERACTION_ID=>p_interaction_id,
4389  P_RESOURCE_ID=>p_resource_id,
4390  p_qualifiers =>p_qualifiers ,
4391  p_contact_id=>g_contact_id,
4392  p_relationship_id=>g_relation_id,
4393  p_mdt_message_id=>p_post_rec.message_id,
4394  X_OUTBOX_ITEM_ID=>l_outbox_id,
4395  X_RETURN_STATUS=>l_ret_status,
4396  X_MSG_COUNT=>l_msg_count,
4397  X_MSG_DATA=>l_msg_data);
4398  IF l_ret_status<>'S' THEN
4399 	x_out_text:='Error Encountered While Calling Create Autoreply';
4400 	raise AUTOREPLY_ERROR;
4401  END IF;
4402  FOR i IN  p_doc_tbl.FIRST..p_doc_tbl.LAST LOOP
4403 	IF p_doc_tbl(i).type='I' THEN
4404 		IEM_OUTBOX_PROC_PUB.insertDocument(
4405    		 p_api_version_number=>1.0    ,
4406   		  p_outbox_item_id=>l_outbox_id,
4407   		  p_document_source=>'MES'       ,
4408    		 p_document_id =>p_doc_tbl(i).doc_id ,
4409 		 X_RETURN_STATUS=>l_ret_status,
4410 		 X_MSG_COUNT=>l_msg_count,
4411 		 X_MSG_DATA=>l_msg_data);
4412 
4413 		 IF l_ret_status<>'S' THEN
4414 			x_out_text:='Error Encountered While Calling Insert Document ';
4415 			raise AUTOREPLY_ERROR;
4416 		 END IF;
4417 	ELSIF p_doc_tbl(i).type='A' THEN
4418 
4419 		SELECT fl.file_name
4420 		INTO l_file_name
4421 		FROM jtf_amv_items_tl b ,jtf_amv_attachments a ,fnd_lobs fl
4422 		WHERE b.item_id = a.attachment_used_by_id
4423 		and a.attachment_used_by='ITEM'
4424 		AND a.file_id = fl.file_id
4425 		AND b.item_id=p_doc_tbl(i).doc_id
4426 		AND b.language=USERENV('LANG')
4427 		and rownum=1;
4428 
4429         IEM_OUTBOX_PROC_PUB.attachDocument(p_api_version_number=>1.0,
4430                          p_init_msg_list=>FND_API.G_FALSE,
4431                          p_commit=>FND_API.G_TRUE,
4432                          p_outbox_item_id=>l_outbox_id,
4433                          p_document_source=>'MES',
4434                          p_document_id=>p_doc_tbl(i).doc_id,
4435                          p_binary_source=>NULL,
4436                          p_attachment_name=>l_file_name,
4437                          x_return_status=>l_ret_status,
4438                          x_msg_count=>l_msg_count,
4439                          x_msg_data=>l_msg_data
4440                         );
4441 		 IF l_ret_status<>'S' THEN
4442 			x_out_text:='Error Encountered While Calling Attach Document ';
4443 			raise AUTOREPLY_ERROR;
4444 		 END IF;
4445 	END IF;
4446   END LOOP;
4447 elsif p_req_type='N' then		-- Auto Notifications
4448 	if l_header_rec.reply_to_str is not null then
4449 		l_from1:=instr(l_header_rec.reply_to_str,'<',1,1);
4450 		l_from2:=instr(l_header_rec.reply_to_str,'>',1,1);
4451 	IF l_from1>0 then		-- From Address Contains Both Name and Address
4452 		l_sender:=substr(l_header_rec.reply_to_str,l_from1+1,l_from2-l_from1-1);
4453 	ELSE					-- From Address contains only Address
4454 		l_sender:=l_header_rec.reply_to_str;
4455 	END IF;
4456 	END IF;
4457 				IEM_OUTBOX_PROC_PUB.createSRAutoNotification(p_api_version_number=>1.0,
4458  													p_init_msg_list=>'F',
4459  													p_commit=>'F',
4460  													P_MEDIA_ID=>p_media_id,
4461  												P_MASTER_ACCOUNT_ID=>p_post_rec.email_account_id,
4462  												P_TO_ADDRESS_LIST=>l_sender,		-- need to pass sender name
4463  												p_cc_address_list=>null ,
4464  												p_bcc_address_list=>null,
4465  												P_SUBJECT=>l_header_rec.subject,
4466  												P_TAG_KEY_VALUE_TBL=>p_tag_key_value_tbl,
4467  												P_CUSTOMER_ID=>p_customer_id,
4468  												P_INTERACTION_ID=>fnd_api.g_miss_num,
4469  												P_RESOURCE_ID=>p_resource_id,
4470  												p_qualifiers =>p_qualifiers ,
4471  												p_contact_id=>g_contact_id,
4472  												p_relationship_id=>g_relation_id,
4473  												p_message_id=>p_post_rec.message_id,
4474 												p_sr_id=>p_fwd_doc_id,
4475  												X_OUTBOX_ITEM_ID=>l_outbox_id,
4476  												X_RETURN_STATUS=>l_ret_status,
4477  												X_MSG_COUNT=>l_msg_count,
4478  												X_MSG_DATA=>l_msg_data);
4479  				IF l_ret_status<>'S' THEN
4480 					x_out_text:='Error Encountered While Calling Create Autonotification';
4481       FND_MSG_PUB.Get(p_msg_index => FND_MSG_PUB.G_FIRST,
4482                       p_encoded=>'F',
4483                       p_data=>l_data,
4484                      p_msg_index_out=>l_msg_index_out);
4485 					raise AUTOREPLY_ERROR;
4486  				END IF;
4487  FOR i IN  p_doc_tbl.FIRST..p_doc_tbl.LAST LOOP
4488  	l_notification_id:=p_doc_tbl(i).doc_id;
4489 	EXIT;
4490  END LOOP;
4491 		IEM_OUTBOX_PROC_PUB.insertDocument(
4492    		 p_api_version_number=>1.0    ,
4493   		  p_outbox_item_id=>l_outbox_id,
4494   		  p_document_source=>'MES'       ,
4495    		 p_document_id =>l_notification_id ,
4496 		 X_RETURN_STATUS=>l_ret_status,
4497 		 X_MSG_COUNT=>l_msg_count,
4498 		 X_MSG_DATA=>l_msg_data);
4499 
4500 		 IF l_ret_status<>'S' THEN
4501 			x_out_text:='Error Encountered While Calling Insert Document ';
4502       FND_MSG_PUB.Get(p_msg_index => FND_MSG_PUB.G_FIRST,
4503                       p_encoded=>'F',
4504                       p_data=>l_data,
4505                      p_msg_index_out=>l_msg_index_out);
4506 			raise AUTOREPLY_ERROR;
4507 		 END IF;
4508  else
4509     				FND_MESSAGE.Set_Name('IEM','IEM_REDIRECT_EXT_HDR');
4510  				FND_MSG_PUB.Add;
4511  				l_ext_subject :=  FND_MSG_PUB.GET(FND_MSG_pub.Count_Msg,FND_API.G_FALSE);
4512 				-- Get value for merge fields
4513     				FND_MESSAGE.Set_Name('IEM','IEM_ADM_AUTO_ACK_CUSTOMER');
4514  				FND_MSG_PUB.Add;
4515  				l_dflt_sender :=  FND_MSG_PUB.GET(FND_MSG_pub.Count_Msg,FND_API.G_FALSE);
4516  		IEM_EMAIL_PROC_PVT.IEM_GET_MERGEVAL(p_email_account_id=>p_post_rec.email_account_id,
4517 				    p_mailer=>l_header_rec.from_str,	-- passing the sender name, sanjana rao, bug 8839425
4518 				    p_dflt_sender=>l_dflt_sender	,
4519 				    p_subject=>l_header_rec.subject,	--passing the subject, sanjana rao , bug 8839425
4520 				    x_qual_tbl=> l_qual_tbl,
4521 				    x_status=>l_ret_status,
4522 				    x_out_text=>l_error_text);
4523 					IEM_OUTBOX_PROC_PUB.autoForward(
4524     						p_api_version_number=>1.0    ,
4525     						p_init_msg_list=>'F'         ,
4526     						p_commit=>'F'                ,
4527     						p_media_id=>p_media_id,
4528     						p_rfc822_message_id=>null,
4529     						p_folder_name=>null       ,
4530     						p_message_uid=>null,
4531     						p_master_account_id=>p_post_rec.email_account_id ,
4532     						p_to_address_list=>p_fwd_address       ,
4533    						 p_cc_address_list=>null       ,
4534     						p_bcc_address_list=>null      ,
4535     						p_subject=>l_ext_subject||p_subject ,
4536     						p_tag_key_value_tbl=>p_tag_key_value_tbl ,
4537  						P_CUSTOMER_ID=>p_customer_id,
4538  						P_INTERACTION_ID=>p_interaction_id,
4539  						P_RESOURCE_ID=>p_resource_id,
4540  						p_qualifiers =>l_qual_tbl ,
4541  						p_contact_id=>g_contact_id,
4542  						p_relationship_id=>g_relation_id,
4543     						p_attach_inb=>'A',
4544 						p_mdt_message_id=>p_post_rec.message_id,
4545 			 			X_OUTBOX_ITEM_ID=>l_outbox_id,
4546 			 			X_RETURN_STATUS=>l_ret_status,
4547 			 			X_MSG_COUNT=>l_msg_count,
4548 			 			X_MSG_DATA=>l_msg_data);
4549 					IF l_ret_status<>'S' THEN
4550 					  x_out_text:='Outbox Processing Return Error while creating a request for autoforward';
4551 						raise AUTOREPLY_ERROR;
4552 					END IF;
4553 					IEM_OUTBOX_PROC_PUB.insertDocument(
4554    		 			p_api_version_number=>1.0    ,
4555   		  			p_outbox_item_id=>l_outbox_id,
4556   		 			 p_document_source=>'MES'       ,
4557    					 p_document_id =>p_fwd_doc_id ,
4558 					 X_RETURN_STATUS=>l_ret_status,
4559 					 X_MSG_COUNT=>l_msg_count,
4560 					 X_MSG_DATA=>l_msg_data);
4561 
4562 		 		IF l_ret_status<>'S' THEN
4563 				  x_out_text:='Error Encountered While Calling Insert Document during autoforward';
4564 					raise AUTOREPLY_ERROR;
4565 				END IF;
4566  end if;
4567 --submitting the request
4568 				IEM_OUTBOX_PROC_PUB.submitOutboxMessage(
4569    				 p_api_version_number=>1.0    ,
4570 				 p_init_msg_list=>'F',
4571 				 p_commit=>'F',
4572   				  p_outbox_item_id=>l_outbox_id  ,
4573 				    p_preview_bool=>'N',
4574 				 X_RETURN_STATUS=>l_ret_status,
4575 				 X_MSG_COUNT=>l_msg_count,
4576 				 X_MSG_DATA=>l_msg_data);
4577 		 IF l_ret_status<>'S' THEN
4578 			x_out_text:='Error Encountered While Submitting Outbox Request';
4579       FND_MSG_PUB.Get(p_msg_index => FND_MSG_PUB.G_FIRST,
4580                       p_encoded=>'F',
4581                       p_data=>l_data,
4582                      p_msg_index_out=>l_msg_index_out);
4583 			raise AUTOREPLY_ERROR;
4584 		 END IF;
4585 	x_status:='S';
4586 	x_out_text:='Submit Request For Autoreply Successfully';
4587 EXCEPTION WHEN AUTOREPLY_ERROR THEN
4588 	x_status:='E';
4589 	x_out_text:=x_out_text||l_data;
4590 WHEN OTHERS THEN
4591 	x_out_text:='Oracle Error Encountered '||sqlerrm||' in autoreply processing ';
4592 	x_status:='E';
4593 end IEM_AUTOREPLY;
4594 
4595  PROCEDURE IEM_GET_MERGEVAL(p_email_account_id in number,
4596 				    p_mailer	in varchar2,
4597 				    p_dflt_sender	in varchar2,
4598 				    p_subject		in varchar2,
4599 				    x_qual_tbl out nocopy  IEM_OUTBOX_PROC_PUB.QualifierRecordList,
4600 				    x_status	out nocopy varchar2,
4601 				    x_out_text	out nocopy varchar2) IS
4602 	cursor c1 is select lookup_code,meaning
4603 	from fnd_lookups
4604 	where enabled_flag = 'Y'
4605 	AND NVL(start_date_active, SYSDATE) <= SYSDATE
4606 	AND NVL(end_date_active,SYSDATE) >= SYSDATE
4607 	AND lookup_type ='IEM_MERGE_FIELDS'
4608 	ANd lookup_code like 'ACK%';
4609 	l_index		number;
4610 	l_sender_name	 varchar2(250);
4611 	l_qual_tbl		 IEM_OUTBOX_PROC_PUB.QualifierRecordList;
4612 	l_from_name		iem_email_accounts.from_name%type;
4613 	l_reply_address	iem_email_accounts.reply_to_address%type;
4614  begin
4615 	select from_name,reply_to_address
4616 	INTO l_from_name,l_reply_address
4617 	from IEM_MSTEMAIL_ACCOUNTS
4618 	where email_account_id=p_email_account_id;
4619 	l_index:=instr(p_mailer,'<',1,1);
4620 	IF l_index>0 then
4621 		l_sender_name:=substr(p_mailer,1,l_index-1);
4622 		l_sender_name:=replace(l_sender_name,'"','');
4623 	else
4624 		l_sender_name:=p_dflt_sender; -- need to be from profile
4625 	end if;
4626 		l_index:=0;
4627 		x_qual_tbl.delete;
4628 	FOR v1 IN c1 LOOP
4629 	IF v1.lookup_code='ACK_SENDER_NAME' THEN
4630 		l_index:=l_index+1;
4631 		x_qual_tbl(l_index).qualifier_name:=v1.lookup_code;
4632 		x_qual_tbl(l_index).qualifier_value:=l_sender_name;
4633 	ELSIF v1.lookup_code='ACK_SUBJECT' THEN
4634 		l_index:=l_index+1;
4635 		x_qual_tbl(l_index).qualifier_name:=v1.lookup_code;
4636 		x_qual_tbl(l_index).qualifier_value:=p_subject;
4637 	ELSIF v1.lookup_code='ACK_RECEIVED_DATE' THEN
4638 		l_index:=l_index+1;
4639 		x_qual_tbl(l_index).qualifier_name:=v1.lookup_code;
4640 		x_qual_tbl(l_index).qualifier_value:=to_char(sysdate,'DD-MON-YYYY');
4641 	ELSIF v1.lookup_code='ACK_ACCT_FROM_NAME' THEN
4642 			l_index:=l_index+1;
4643 			x_qual_tbl(l_index).qualifier_name:=v1.lookup_code;
4644 			x_qual_tbl(l_index).qualifier_value:=l_from_name;
4645 	ELSIF v1.lookup_code='ACK_ACCT_EMAIL_ADDRESS' THEN
4646 			l_index:=l_index+1;
4647 			x_qual_tbl(l_index).qualifier_name:=v1.lookup_code;
4648 			x_qual_tbl(l_index).qualifier_value:=l_reply_address;
4649 	END IF;
4650 	END LOOP;
4651 		x_status:='S';
4652  exception when others then
4653 	x_out_Text:='Error Occured While Retrieving Merge Data Value '||sqlerrm;
4654 	x_status:='E';
4655 end IEM_GET_MERGEVAL;
4656 procedure IEM_PROCESS_INTENT(l_email_account_id in number,
4657 					  l_msg_id	in number,
4658 					  l_theme_status	out nocopy varchar2,
4659 					  l_out_text	out nocopy varchar2)
4660 
4661 is
4662 
4663 l_ret	number;
4664 l_ret1	number;
4665 l_gclassid	number;
4666 l_theme		varchar2(100);
4667 l_count		number:=0;
4668 l_counter		number:=0;
4669 l_tcount	number;
4670 l_markup_count		number;
4671 l_theme_count		number;
4672 l_markupcount	number;
4673 l_class_id	number;
4674 l_classification_id	number;
4675 l_tclassid	number;
4676 l_part		number;
4677 l_index		number;
4678 l_flag		number:=1;
4679 l_errtext	varchar2(600);
4680 l_qstr          varchar2(500);
4681 l_tstr          varchar2(2000);
4682 l_tclstr          varchar2(2000);
4683 l_class	number;
4684 l_first	varchar2(1);
4685 l_val	number:=0;
4686 l_match	varchar2(1):='F';
4687 l_msg_data	varchar2(200);
4688 l_data	iem_class_tbl_typ:=iem_class_tbl_typ();
4689 l_errmsg	varchar2(200);
4690 l_str	varchar2(200);
4691 l_class_scr	varchar2(3500);
4692 l_wtot		number:=0;
4693 theme_proc_excep	EXCEPTION;
4694 theme_proc_excep1	EXCEPTION;
4695 l_text		varchar2(100);
4696 l_status		varchar2(100);
4697 l_class_str	varchar2(32000);
4698 l_imt_string1	varchar2(4000);
4699 l_imt_string	varchar2(32000);
4700 l_occur		number;
4701 x_stat		varchar2(10);
4702 l_lang		varchar2(10);
4703 l_theme_code		varchar2(50);
4704 l_logmessage	varchar2(500);
4705 l_level		varchar2(20):='STATEMENT';
4706 l_tweight		number:=0;
4707 l_rms		number;
4708 l_class_count		number;
4709 l_theme_buf	IEM_TEXT_PVT.theme_tAble;
4710 l_token_buf	IEM_TEXT_PVT.token_table;
4711 cursor c1 is
4712  SELECT a.intent_id, a.keyword,a.weight
4713  from iem_intent_dtls a,iem_account_intents b
4714 WHERE   b.email_account_id=l_email_account_id
4715 AND a.intent_id=b.intent_id
4716 AND QUERY_RESPONSE='Q'
4717 and weight>0
4718 order by 1;
4719    CURSOR get_theme_csr IS
4720    SELECT keyword,weight FROM iem_intent_dtls
4721    where intent_id=l_class_id
4722    AND QUERY_RESPONSE='Q'
4723    and weight>0
4724    order by 2 desc;
4725 begin
4726 	l_theme_status:='S';
4727 	select kem_flag,account_language
4728 	INTO l_theme_code,l_lang
4729 	FROM IEM_MSTEMAIL_ACCOUNTS
4730 	WHERE EMAIL_ACCOUNT_ID=l_email_account_id;
4731 		l_theme_buf.delete;
4732 		l_token_buf.delete;
4733 		IF l_theme_code=1 then	-- Theme processing
4734 				iem_text_pvt.getthemes(l_msg_id,null,l_theme_buf,l_errmsg);
4735 		ELSIF l_theme_code=2 then -- Token Processing
4736 			iem_text_pvt.gettokens(l_msg_id,null,l_lang,l_token_buf,l_errmsg);
4737 			IF l_token_buf.count>0 THEN
4738 				l_counter:=1;
4739 			FOR i in l_token_buf.FIRST..l_token_buf.LAST LOOP
4740 				l_theme_buf(l_counter).theme:=l_token_buf(i).token;
4741 				l_theme_buf(l_counter).weight:=null;
4742 				l_counter:=l_counter+1;
4743 			END LOOP;
4744 			END IF;
4745 		END IF;
4746 		-- Need to Handle Error Processing
4747 	l_val:=0;
4748 		-- Create the classification String from the first top 10 theme
4749 		l_class_str:=' ';
4750 
4751 		IF l_theme_buf.count>0 then	-- Theme API return themes
4752 		if g_statement_log then
4753 			l_logmessage:='Number of  theme returned '||l_theme_buf.count ;
4754 			 iem_logger(l_logmessage);
4755 		end if;
4756 
4757 			-- normalised using RMS --
4758 			l_rms:=0;
4759 			l_count:=0;
4760 	  FOR l_ind in 1.. l_theme_buf.count LOOP
4761 				l_count:=l_count+1;
4762 				l_rms:= l_rms+power(l_theme_buf(l_ind).weight,2);
4763 			EXIT when l_count=10;
4764 			END LOOP;
4765 			l_rms:=sqrt(l_rms);
4766 	  FOR l_ind in 1.. l_theme_buf.count LOOP
4767 		l_count:=l_count+1;
4768 		l_theme_buf(l_ind).weight:=round(l_theme_buf(l_ind).weight/l_rms,2)*10;
4769 			EXIT when l_count=10;
4770 			END LOOP;
4771 	-- End of normalisation Using RMS
4772 	  FOR l_ind in 1.. l_theme_buf.count LOOP
4773 		l_class_str:=l_class_str||'about ('||l_theme_buf(l_ind).theme||'),';
4774 				l_count:=l_count+1;
4775 			END LOOP;
4776 		ELSE
4777 	if g_statement_log then
4778 			l_logmessage:='No themes  for  OES Message '||l_msg_id;
4779 			 iem_logger(l_logmessage);
4780 	end if;
4781 			raise theme_proc_excep1;	-- Theme API return zero Themes
4782 		END IF;
4783 		l_count:=0;
4784 FOR v1 in c1 loop
4785       FOR l_ind in l_theme_buf.FIRST .. l_theme_buf.LAST LOOP
4786 -- fix for 12.1.1 bug 7584830 to make intent case insensitive
4787 IF upper(v1.keyword)=upper(l_theme_buf(l_ind).theme) then
4788 IF (l_class<>v1.intent_id) and (l_class is not null) then
4789 	l_data.extend;
4790 	l_data(l_data.count):=iem_class_obj_typ(l_class,l_val);
4791 	l_val:=0;
4792  END IF;
4793           l_val:=v1.weight+nvl(l_val,0);
4794 		l_wtot:=l_wtot+l_val;
4795 		l_class:=v1.intent_id;
4796 END IF;
4797 	END LOOP;
4798 END LOOP;
4799 	if l_val<>0 then
4800 	l_data.extend;
4801 	l_data(l_data.count):=iem_class_obj_typ(l_class,l_val);
4802 	l_wtot:=l_wtot+l_val;
4803 	end if;
4804 l_class_count:=1;
4805 		g_topclass:=null;
4806 		g_topscore:=null;
4807 	  l_wtot:=0;
4808 	 FOR x in (select * from the(select cast(l_data as iem_class_tbl_typ)
4809 	  from dual)a where score>0 and rownum<8 order by score desc)
4810 	  LOOP
4811 		l_wtot:=l_wtot+x.score;
4812 	  END LOOP;
4813 	 FOR x in (select * from the(select cast(l_data as iem_class_tbl_typ)
4814 	  from dual)a where score>0 and rownum<8 order by score desc)
4815 	  LOOP
4816 		x.score:=x.score*100/l_wtot;
4817 IF x.score > 0 THEN			 -- -ve Classification score not allowed Start
4818 	IF x.score>100 THEN
4819 		x.score:=100;
4820 	END IF;
4821 	IF l_gclassid is null then
4822 	l_gclassid:=x.classification_id;
4823 	g_topscore:=x.score;
4824 	BEGIN
4825 	select intent into g_topclass
4826 	from iem_intents
4827 	where intent_id=l_gclassid;
4828 	EXCEPTION WHEN OTHERS THEN
4829 		null;
4830 	END;
4831 	end if;
4832 		l_classification_id:=x.classification_id;
4833 		l_imt_string:=' ';
4834 		l_count:=1;
4835 		l_class_str:=substr(l_class_str,1,length(l_class_str)-1);
4836           iem_eml_classifications_pvt.create_item(
4837           p_api_version_number=>1.0,
4838 		p_init_msg_list=>'F',
4839 		p_commit=>'F',
4840           p_email_account_id=>l_email_account_id,
4841           p_classification_id=>x.classification_id,
4842           p_score=>x.score,
4843           p_message_id=>l_msg_id,
4844 		p_class_string=>l_class_str,
4845                p_CREATED_BY =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
4846                p_CREATION_DATE=> SYSDATE,
4847                p_LAST_UPDATED_BY=>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')) ,
4848                p_LAST_UPDATE_DATE=>SYSDATE,
4849                p_LAST_UPDATE_LOGIN=>TO_NUMBER (FND_PROFILE.VALUE('LOGIN_ ID')) ,
4850           x_return_Status=>l_status,
4851           x_msg_count=>l_count,
4852           x_msg_data=>l_msg_data);
4853      l_class_count:=l_class_count+1;
4854  END IF;  				-- -ve Classification score not allowed end
4855      EXIT when l_class_count>7 ;
4856      END LOOP;
4857 	l_theme_status:='S';
4858 exception
4859   when theme_proc_excep1 then
4860 	l_theme_status:='S';
4861   when theme_proc_excep then
4862 	l_theme_status:='E';
4863   when others then
4864 		l_theme_status:='E';
4865 	if g_exception_log then
4866 			l_logmessage:='Oracle Error Encountered in IEM_THEMEPROC Procedure  for  OES Message '||l_msg_id||'  '||sqlerrm;
4867 			iem_logger(l_logmessage);
4868 	end if;
4869 		l_out_text:=l_out_text||' Oracle Error '||sqlerrm|| 'While theme classification processing for message id '||l_msg_id;
4870 end IEM_PROCESS_INTENT;
4871 PROCEDURE ReprocessAutoreply(p_api_version_number    IN   NUMBER,
4872                    p_init_msg_list  IN   VARCHAR2 ,
4873                    p_commit      IN   VARCHAR2 ,
4874                    p_media_id in number,
4875 		   		p_interaction_id	in number,
4876 	           	p_customer_id	in number,
4877 	           	p_contact_id	in number,
4878 	           	p_relationship_id	in number,
4879                    x_return_status    OUT NOCOPY      VARCHAR2,
4880                    x_msg_count              OUT NOCOPY           NUMBER,
4881                    x_msg_data OUT NOCOPY      VARCHAR2) IS
4882 
4883 	l_header_rec		iem_ms_base_headers%rowtype;
4884 	l_mail_rec		iem_rt_proc_emails%rowtype;
4885 	l_class_val_tbl		IEM_ROUTE_PUB.keyVals_tbl_type;
4886 	l_counter		number;
4887 	l_message_id			number;
4888    l_top_intent	varchar2(50);
4889    l_top_score		number;
4890  cursor c_intent is select a.intent,b.score from
4891  iem_intents a,iem_email_classifications b
4892  where b.message_id=l_message_id
4893  and a.intent_id=b.classification_id;
4894 g_statement_log	boolean;		-- Statement Level Logging
4895  l_intent_str			varchar2(700);
4896  l_index1				number;
4897  l_index2				number;
4898 	l_api_name	varchar2(100):='ReprocessAutoreply';
4899 	l_media_rec	JTF_IH_PUB.media_rec_type;
4900 	l_kb_rank		number;
4901 	l_api_version_number	number;
4902  l_rt_media_item_id		number;
4903  l_rt_interaction_id	number;
4904  l_milcs_id			number;
4905  l_intent_counter		number;
4906  	l_media_lc_rec 		JTF_IH_PUB.media_lc_rec_type;
4907  	l_interaction_rec        JTF_IH_PUB.interaction_rec_type;
4908  	l_activity_rec        JTF_IH_PUB.activity_rec_type;
4909 	l_Stat		varchar2(100);
4910  l_auto_flag		varchar2(10);
4911  l_encrypted_id		varchar2(100);
4912  l_ret_status			varchar2(10);
4913  l_search			varchar2(10);
4914  l_msg_count			number;
4915  l_msg_data			varchar2(255);
4916 l_tag_keyval			IEM_TAGPROCESS_PUB.keyVals_tbl_type;
4917 l_folder_name			varchar2(255);
4918 l_from_folder			varchar2(255);
4919 l_agentid				number;
4920 	l_autoproc_result		varchar2(1);
4921 	l_param_rec_tbl		IEM_RULES_ENGINE_PUB.parameter_tbl_type;
4922 	l_action				varchar2(50);
4923 	l_rule_id			number;
4924 	l_search_type		varchar2(100);
4925 	l_repos			varchar2(100);
4926 	l_cm_cat_id		number;	-- store the category for MES category based mapping
4927    l_category_id     AMV_SEARCH_PVT.amv_number_varray_type:=AMV_SEARCH_PVT.amv_number_varray_type();
4928 	l_cat_counter		number;
4929 	l_group_id		number;
4930 	l_status			varchar2(10);
4931 	l_out_text		varchar2(255);
4932 	l_uid			number;
4933 	cursor c_class_id is
4934 	select classification_id from iem_email_classifications
4935 	where message_id=l_message_id
4936 	order by score desc;
4937 	l_start_search		number;
4938 	ABORT_REPROCESSING	EXCEPTION;
4939 	l_logmessage		varchar2(1000);
4940 	l_level			varchar2(20);
4941    cursor c_item is select ib.item_id,ib.item_name,ib.last_update_date
4942    from   amv_c_chl_item_match cim,jtf_amv_items_vl ib
4943    where  cim.channel_category_id = l_cm_cat_id
4944    and   cim.channel_id is null
4945    and   cim.approval_status_type ='APPROVED'
4946    and   cim.table_name_code ='ITEM'
4947    and   cim.available_for_channel_date <= sysdate
4948    and   cim.item_id = ib.item_id
4949    and    nvl(ib.effective_start_date, sysdate) <= sysdate + 1
4950    and   nvl(ib.expiration_date, sysdate) >= sysdate;
4951    l_email_user_name		varchar2(500);
4952    l_email_domain_name		varchar2(500);
4953    l_email_address		varchar2(500);
4954    l_from1		number;
4955    l_from2		number;
4956    l_sender		varchar2(500);
4957 
4958 begin
4959 	l_api_version_number:=1.0;
4960 -- Standard call to check for call compatibility.
4961 IF NOT FND_API.Compatible_API_Call (l_api_version_number,
4962 				    p_api_version_number,
4963 				    l_api_name,
4964 				    G_PKG_NAME)
4965 THEN
4966 	 RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
4967 END IF;
4968 	l_level:='STATEMENT';
4969 		FND_LOG_REPOSITORY.init(null,null);
4970 		g_statement_log:= fnd_log.test(FND_LOG.LEVEL_STATEMENT,'IEM.PLSQL.iem_email_proc_pvt');
4971 	SAVEPOINT processautoreply;
4972 		-- Find the record from iem_rt_proc_emails  based on media id
4973 		BEGIN
4974 		select * into l_mail_rec from iem_rt_proc_emails
4975 		where ih_media_item_id=p_media_id and msg_status='AUTOREPLY';
4976 		EXCEPTION WHEN OTHERS THEN
4977 	if g_exception_log then
4978 		l_logmessage:='Error while selecting Message For re-processing '||sqlerrm;
4979 		iem_logger(l_logmessage);
4980 	end if;
4981 			raise abort_reprocessing;
4982 		END;
4983 
4984 	select * into l_header_Rec
4985 	from iem_ms_base_headers
4986 	where message_id=l_mail_Rec.message_id;
4987 
4988 	select user_name,email_address
4989 	into l_email_user_name,l_email_address
4990 	from iem_mstemail_accounts
4991 	where email_account_id=l_mail_rec.email_account_id;
4992 	l_email_domain_name:=substr(l_email_address,instr(l_email_address,'@',1)+1,length(l_email_address));
4993 	l_from1:=instr(l_header_rec.from_str,'<',1,1);
4994 	l_from2:=instr(l_header_rec.from_str,'>',1,1);
4995 	IF l_from1>0 then		-- From Address Contains Both Name and Address
4996 		l_sender:=substr(l_header_rec.from_Str,l_from1+1,l_from2-l_from1-1);
4997 	ELSE					-- From Address contains only Address
4998 		l_sender:=l_header_rec.from_str;
4999 	END IF;
5000 
5001 		-- Create the set of Key Value pairs to be passed to Rules Engine for Document Retrieval and Routing.
5002    For v1 in c_intent LOOP
5003 	l_intent_str:=nvl(l_intent_str,' ')||v1.intent;
5004 	if l_top_intent is null then
5005 		l_top_intent:=v1.intent;
5006 		l_top_score:=v1.score;
5007      end if;
5008    END LOOP;
5009 		l_counter:=1;
5010 		l_class_val_tbl.delete;
5011 	l_class_val_tbl(l_counter).key:='IEMNMESSAGESIZE';
5012 	l_class_val_tbl(l_counter).value:=l_header_rec.message_size;
5013 	l_class_val_tbl(l_counter).datatype:='N';
5014 		l_counter:=l_counter+1;
5015 	l_class_val_tbl(l_counter).key:='IEMSSENDERNAME';
5016 	l_class_val_tbl(l_counter).value:=l_sender;
5017 	l_class_val_tbl(l_counter).datatype:='S';
5018 		l_counter:=l_counter+1;
5019 	l_class_val_tbl(l_counter).key:='IEMSUSERACCTNAME';
5020 	l_class_val_tbl(l_counter).value:=l_email_user_name;
5021 	l_class_val_tbl(l_counter).datatype:='S';
5022 		l_counter:=l_counter+1;
5023 	l_class_val_tbl(l_counter).key:='IEMSDOMAINNAME';
5024 	l_class_val_tbl(l_counter).value:=l_email_domain_name;
5025 	l_class_val_tbl(l_counter).datatype:='S';
5026 	/* this is missing for the time being
5027 		l_counter:=l_counter+1;
5028 	l_class_val_tbl(l_counter).key:='IEMSPRIORITY';
5029 	l_class_val_tbl(l_counter).value:=l_post_rec.priority;
5030 	l_class_val_tbl(l_counter).datatype:='S';
5031 	*/
5032 		l_counter:=l_counter+1;
5033 	l_class_val_tbl(l_counter).key:='IEMSSUBJECT';
5034 	l_class_val_tbl(l_counter).value:=l_header_rec.subject;
5035 	l_class_val_tbl(l_counter).datatype:='S';
5036 		l_counter:=l_counter+1;
5037 	l_class_val_tbl(l_counter).key:='IEMDRECEIVEDDATE';
5038 	l_class_val_tbl(l_counter).value:=to_char(l_mail_rec.received_date,'YYYYMMDD');
5039 	l_class_val_tbl(l_counter).datatype:='D';
5040 		l_counter:=l_counter+1;
5041 	l_class_val_tbl(l_counter).key:='IEMTRECEIVEDTIME';
5042 	l_class_val_tbl(l_counter).value:=to_char(l_mail_rec.received_date,'HH24:MI:SS');
5043 	l_class_val_tbl(l_counter).datatype:='T';
5044 		l_counter:=l_counter+1;
5045 	l_class_val_tbl(l_counter).key:='IEMSEMAILINTENT';
5046 	l_class_val_tbl(l_counter).value:=l_top_intent;
5047 	l_class_val_tbl(l_counter).datatype:='S';
5048 		l_counter:=l_counter+1;
5049 	l_class_val_tbl(l_counter).key:='IEMNSCOREPERCENT';
5050 	l_class_val_tbl(l_counter).value:=l_top_score;
5051 	l_class_val_tbl(l_counter).datatype:='N';
5052 		l_counter:=l_counter+1;
5053 	l_class_val_tbl(l_counter).key:='IEMSLANGUAGE';
5054 	l_class_val_tbl(l_counter).value:=l_header_rec.language;
5055 	l_class_val_tbl(l_counter).datatype:='S';
5056 		l_counter:=l_counter+1;
5057 	l_class_val_tbl(l_counter).key:='IEMSORGANIZATION';
5058 	l_class_val_tbl(l_counter).value:=l_header_rec.organization;
5059 	l_class_val_tbl(l_counter).datatype:='S';
5060 		l_counter:=l_counter+1;
5061 	l_class_val_tbl(l_counter).key:='IEMDSYSTEMDATE';
5062 	l_class_val_tbl(l_counter).value:=to_char(sysdate,'YYYYMMDD');
5063 	l_class_val_tbl(l_counter).datatype:='D';
5064 		l_counter:=l_counter+1;
5065 	l_class_val_tbl(l_counter).key:='IEMTSYSTEMTIME';
5066 	l_class_val_tbl(l_counter).value:=to_char(sysdate,'HH24:MI:SS');
5067 	l_class_val_tbl(l_counter).datatype:='T';
5068 		l_counter:=l_counter+1;
5069 	l_class_val_tbl(l_counter).key:='IEMSTOADDRESS';
5070 	l_class_val_tbl(l_counter).value:=l_header_rec.to_str;
5071 	l_class_val_tbl(l_counter).datatype:='S';
5072 
5073 -- New KEYVALUE Pair Containing All Intents Changes MAde for MP-R By RT on 08/01/03
5074 		l_counter:=l_counter+1;
5075 	l_class_val_tbl(l_counter).key:='IEMSALLINTENTS';
5076 	l_class_val_tbl(l_counter).value:=l_intent_str;
5077 	l_class_val_tbl(l_counter).datatype:='S';
5078 -- Retrieving the Tag Data if any present ..
5079 	l_tag_keyval.delete;
5080 	l_search:='[REF:';
5081  l_index1:=instr(l_header_rec.subject,l_search,1,1);
5082  l_index2:=instr(substr(l_header_rec.subject,l_index1+length(l_search),length(l_header_rec.subject)-1),']',1,1);
5083  IF (l_index1 <> 0) and (l_index2<>0) THEN
5084 l_encrypted_id:=ltrim(substr(l_header_rec.subject,l_index1+length(l_search),l_index2-1));
5085 -- Reset the Tag
5086 	IEM_ENCRYPT_TAGS_PVT.RESET_TAG
5087              (p_api_version_number=>1.0,
5088               p_message_id=>l_mail_rec.message_id,
5089               x_return_status=>l_ret_status ,
5090               x_msg_count=>l_msg_count,
5091               x_msg_data=>l_msg_data);
5092 
5093 	IF l_ret_status<>'S' THEN
5094 	if g_error_log then
5095 		l_logmessage:='Error while Resetting Tag For Rerouted Message';
5096 		iem_logger(l_logmessage);
5097 	end if;
5098 	END IF;
5099 			IEM_TAGPROCESS_PUB.GETTAGVALUES
5100 					(p_Api_Version_Number=>1.0,
5101 					 p_encrypted_id =>l_encrypted_id,
5102         				p_message_id=>l_mail_rec.message_id,
5103         				x_key_value=>l_tag_keyval,
5104         				x_msg_count=>l_msg_count,
5105         				x_return_status=>l_ret_status,
5106         				x_msg_data=>l_msg_data);
5107 	IF l_ret_status<>'S' THEN
5108 	if g_error_log then
5109 	l_logmessage:='Error while Calling Tag Processing Api while reprocessing autoreplied message';
5110 		iem_logger(l_logmessage);
5111 		end if;
5112 		raise abort_reprocessing;
5113 	END IF;
5114   END IF;
5115 	IF p_customer_id is not null THEN
5116 		l_counter:=l_counter+1;
5117 		l_class_val_tbl(l_counter).key:='IEMNCUSTOMERID';
5118 		l_class_val_tbl(l_counter).value:=p_customer_id;
5119 		l_class_val_tbl(l_counter).datatype:='N';
5120 	END IF;
5121 
5122    IF l_tag_keyval.count>0 THEN
5123 	FOR j in l_tag_keyval.FIRST..l_tag_keyval.LAST LOOP
5124 		l_counter:=l_counter+1;
5125 	l_class_val_tbl(l_counter).key:=l_tag_keyval(j).key;
5126 	l_class_val_tbl(l_counter).value:=l_tag_keyval(j).value;
5127 	l_class_val_tbl(l_counter).datatype:=l_tag_keyval(j).datatype;
5128 	-- Check for Agent Id if exists in TAG
5129 			IF l_tag_keyval(l_counter).key='IEMNAGENTID' THEN
5130 				l_agentid:=to_number(l_tag_keyval(l_counter).value);
5131 			END IF;
5132 	END LOOP;
5133   END IF;
5134 
5135  BEGIN
5136 	select name
5137 	into l_folder_name
5138 	from iem_route_classifications
5139 	where route_classification_id=l_mail_Rec.rt_classification_id;
5140  EXCEPTION
5141 	WHEN OTHERS THEN
5142 	if g_exception_log then
5143 	l_logmessage:='Error in getting folder name for the route classificaion id '||l_mail_rec.rt_classification_id||' and the error is '||sqlerrm;
5144 		iem_logger(l_logmessage);
5145 	end if;
5146 		raise abort_reprocessing;
5147   END;
5148 		l_counter:=l_counter+1;
5149 	l_class_val_tbl(l_counter).key:='IEMSROUTINGCLASSIFICATION';
5150   l_class_val_tbl(l_counter).value:=l_folder_name;
5151 	l_class_val_tbl(l_counter).datatype:='S';
5152 
5153 		l_counter:=l_counter+1;
5154 		l_class_val_tbl(l_counter).key:='IEMNINTERACTIONID';
5155 		l_class_val_tbl(l_counter).value:=p_interaction_id;
5156 		l_class_val_tbl(l_counter).datatype:='N';
5157 
5158 		-- Add Media Id to the key value Pair
5159 		l_counter:=l_counter+1;
5160 		l_class_val_tbl(l_counter).key:='IEMNMEDIAID';
5161 		l_class_val_tbl(l_counter).value:=p_media_id;
5162 		l_class_val_tbl(l_counter).datatype:='N';
5163 		l_counter:=l_counter+1;
5164 		l_class_val_tbl(l_counter).key:='IEMNMESSAGEID';
5165 		l_class_val_tbl(l_counter).value:=l_mail_rec.message_id;
5166 		l_class_val_tbl(l_counter).datatype:='N';
5167 
5168 		-- Now Calling Document Retrieval Rule
5169 		l_rule_id:=0;
5170 	iem_rules_engine_pub.auto_process_email(p_api_version_number=>1.0,
5171 					p_commit=>FND_API.G_FALSE,
5172 					p_rule_type=>'DOCUMENTRETRIEVAL',
5173 					p_keyvals_tbl=>l_class_val_tbl,
5174 					p_accountid=>l_mail_rec.email_account_id,
5175 					x_result=>l_autoproc_result,
5176 					x_action=>l_action,
5177 					x_parameters=>l_param_rec_tbl,
5178 					x_return_status=>l_ret_status,
5179 					x_msg_count=>l_msg_count,
5180 					x_msg_data=>l_msg_data);
5181 		    IF l_ret_status<>'S' THEN
5182 			   l_logmessage:='Error While Calling rules Engine for DOCUMENTRETRIEVAL';
5183 			END IF;
5184 			IF l_autoproc_result='T' THEN
5185 			 if l_action <> 'MES_CATEGORY_MAPPING'  THEN
5186 	     l_search_type:=substr(l_action,15,length(l_action));
5187 		 -- identfiying the repository to search
5188 				if l_search_type='MES' THEN
5189 					l_repos:='MES';
5190 				elsif l_search_type='KM' THEN
5191 					l_repos:='SMS';
5192 				elsif l_search_type='BOTH' THEN
5193 					l_repos:='ALL';
5194 				end if;
5195 				   l_cat_counter:=1;
5196 				   IF l_param_rec_tbl.count>0 THEN
5197 				   FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
5198 			 		IF l_param_rec_tbl(l_param_index).parameter1 <> to_char(-1)  then
5199 						IF l_param_rec_tbl(l_param_index).parameter1='RULE_ID' then
5200 							l_rule_id:=l_param_rec_tbl(l_param_index).parameter2;
5201 						ELSE
5202 							l_category_id.extend;
5203 					l_category_id(l_cat_counter):=l_param_rec_tbl(l_param_index).parameter1;
5204 							l_cat_counter:=l_cat_counter+1;
5205 						END IF;
5206 					END IF;
5207 				  END LOOP;
5208 				  END IF;
5209 			else
5210 					l_search_type:='CM';		--Category based mapping
5211 				   FOR l_param_index in l_param_rec_tbl.FIRST..l_param_rec_tbl.LAST LOOP
5212 							l_cm_cat_id:=l_param_rec_tbl(l_param_index).parameter1;
5213 							EXIT;
5214 				   END LOOP;
5215 			end if;
5216 		else
5217 			l_search_type:=null;
5218 			l_cm_Cat_id:=0;
5219           end if ;		-- end if for l_autoproc_result='T'
5220 		-- CALLING ROUTING ----
5221 iem_email_proc_pvt.IEM_ROUTING_PROC(
5222 					p_email_account_id=>l_mail_rec.email_account_id,
5223 				p_keyval=>l_class_val_tbl,
5224 				x_routing_group_id=>l_group_id,
5225 					x_status=>l_status,
5226 		     		x_out_text=>l_out_text) ;
5227 	IF l_status <>'S' THEN
5228 	if g_error_log then
5229 		l_logmessage:=l_out_text;
5230 		iem_logger(l_logmessage);
5231 	end if;
5232 		raise abort_reprocessing;
5233 	END IF;
5234 	IF l_group_id=-1 then
5235 			l_group_id:=0;
5236 			l_auto_flag:='Y';
5237 	END IF;
5238 		update iem_rt_proc_emails
5239 		set resource_id=0,
5240 		group_id=l_group_id,
5241 		customer_id=p_customer_id,
5242 		contact_id=p_contact_id,
5243 		relationship_id=p_relationship_id,
5244 		msg_status=null,
5245 		mail_proc_status='P',
5246 		category_map_id=l_cm_cat_id
5247 		where message_id=l_mail_rec.message_id;
5248 
5249 	IF l_auto_flag='Y' THEN		-- auto Routing Processing
5250 		-- Create a Record in RT Table
5251 		BEGIN
5252 		SAVEPOINT AUTO_ROUTE;
5253 		IEM_CLIENT_PUB.createRTItem (p_api_version_number=>1.0,
5254 					p_init_msg_list=>'F',
5255 					p_commit=>'F',
5256    					p_message_id =>l_mail_rec.message_id,
5257   					p_to_resource_id  =>l_agentid,
5258   					p_from_resource_id =>l_agentid,
5259   					p_status  =>'N',
5260   					p_reason =>'O',
5261   					p_interaction_id =>p_interaction_id,
5262   					x_return_status  =>l_ret_status,
5263   					x_msg_count =>l_msg_count,
5264   					x_msg_data   =>l_msg_data,
5265   					x_rt_media_item_id =>l_rt_media_item_id,
5266   					x_rt_interaction_id =>l_rt_interaction_id);
5267 		 IF l_ret_status<>'S' THEN
5268 	if g_error_log then
5269 				l_logmessage:='Failed To Auto Route The Message due to error in create RT Item ';
5270 				iem_logger(l_logmessage);
5271 	end if;
5272 				rollback to auto_route;
5273 		 ELSE
5274 				-- Create MLCS for Auto Routing
5275 
5276   					l_media_lc_rec.media_id :=p_media_id ;
5277   					l_media_lc_rec.milcs_type_id := 30; --MAIL_AUTOROUTE
5278   					l_media_lc_rec.start_date_time := sysdate;
5279   					l_media_lc_rec.handler_id := 680;
5280   					l_media_lc_rec.type_type := 'Email, Inbound';
5281   					l_media_lc_rec.resource_id := l_agentid;
5282 
5283 						iem_email_proc_pvt.IEM_PROC_IH(
5284 							p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
5285 								p_action=>'ADD'		,		-- ADD/UPDATE/CLOSE
5286 								p_interaction_rec=>l_interaction_rec,
5287 								p_activity_rec=>l_activity_rec     ,
5288 								p_media_lc_rec=>l_media_lc_Rec ,
5289 								p_media_rec=>l_media_rec	,
5290 								x_id=>l_milcs_id,
5291 								x_status=>l_stat		,
5292 			    				 x_out_text=>l_out_text	);
5293 							IF l_stat<>'S' THEN
5294 					if g_error_log then
5295 						l_logmessage:='Error while creating MLCS for Auto Route '||l_out_text;
5296 								iem_logger(l_logmessage);
5297 					end if;
5298 								rollback to auto_route;
5299 							ELSE
5300 							-- Update  the Media Life Cycle for Auto Routing
5301  							 l_media_lc_rec.milcs_id:=l_milcs_id;
5302 							iem_email_proc_pvt.IEM_PROC_IH(
5303 							p_type=>'MLCS'		,		-- MEDIA/ACTIVITY/MLCS/INTERACTION
5304 								p_action=>'UPDATE'		,		-- ADD/UPDATE/CLOSE
5305 								p_interaction_rec=>l_interaction_rec,
5306 								p_activity_rec=>l_activity_rec     ,
5307 								p_media_lc_rec=>l_media_lc_Rec ,
5308 								p_media_rec=>l_media_rec	,
5309 								x_id=>l_milcs_id,
5310 								x_status=>l_stat		,
5311 			  				   x_out_text=>l_out_text	);
5312 							END IF;
5313 
5314 							IF l_stat<>'S' THEN
5315 					if g_error_log then
5316 						l_logmessage:='Error while updating MLCS for Auto Route '||l_out_text;
5317 								iem_logger(l_logmessage);
5318 					end if;
5319 								rollback to auto_route;
5320 							END IF;
5321 				-- In case of autoroute update the interaction with resource id of the agent to which
5322 				-- the message is autorouted to
5323 			l_interaction_rec.interaction_id:=p_interaction_id;
5324 			l_interaction_rec.resource_id:=l_agentid;
5325      		JTF_IH_PUB.Update_Interaction( p_api_version     => 1.1,
5326                                   p_resp_appl_id    => TO_NUMBER(FND_PROFILE.VALUE('RESP_APPL_ID')),
5327                                   p_resp_id         => TO_NUMBER(FND_PROFILE.VALUE('RESP_ID')),
5328                          		p_user_id		  =>nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
5329 							p_login_id	  =>TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID')),
5330                                   x_return_status   => l_ret_status,
5331                                   x_msg_count       => l_msg_count,
5332                                   x_msg_data        => l_msg_data,
5333                                   p_interaction_rec => l_interaction_rec
5334                                  );
5335 							IF l_ret_status<>'S' THEN
5336 					if g_error_log then
5337 						l_logmessage:='Error while updating Interactions for Auto Route ';
5338 								iem_logger(l_logmessage);
5339 						end if;
5340 								rollback to auto_route;
5341 							END IF;
5342 				if g_statement_log then
5343 					l_logmessage:='Successfully AutoRoute The Message ';
5344 					iem_logger(l_logmessage);
5345 				end if;
5346 		END IF;
5347 		EXCEPTION WHEN OTHERS THEN
5348 			rollback to auto_route;
5349 		END;
5350       END IF;		-- End for Auto-Routing
5351 	-- Calling the specific search at the End
5352 	if g_statement_log then
5353 	l_logmessage:='Calling Specific Search API ' ;
5354 	iem_logger(l_logmessage);
5355 	end if;
5356 	BEGIN
5357 	IF l_search_type<>'CM' THEN			-- Not a MES category based mapping
5358 			l_start_search:=1;
5359 			FOR v1 in c_class_id LOOP
5360 	IEM_EMAIL_PROC_PVT.IEM_WF_SPECIFICSEARCH(
5361     					l_mail_rec.message_id  ,
5362     					l_mail_rec.email_account_id ,
5363     					v1.classification_id,
5364 					l_category_id,
5365 					l_repos,
5366     					l_stat ,
5367     					l_out_text);
5368 		l_start_search:=l_start_search+1;
5369 		EXIT when l_start_search>l_intent_counter;
5370 		END LOOP;
5371 	ELSIF nvl(l_search_type,' ')='CM' and l_cm_cat_id is not null then
5372 		for v_item in c_item LOOP
5373 		select count(*) into l_kb_rank
5374 		from iem_doc_usage_stats
5375 		where kb_doc_id=v_item.item_id;
5376 		IEM_KB_RESULTS_PVT.create_item(p_api_version_number=>1.0,
5377  		  	      		p_init_msg_list=>'F' ,
5378 		    	      		p_commit=>'F'	    ,
5379 						 p_message_id =>l_mail_rec.message_id,
5380 						 p_classification_id=>0,
5381  				p_email_account_id=>l_mail_rec.email_account_id ,
5382  			p_document_id =>to_char(v_item.item_id),
5383  		p_kb_repository_name =>'MES',
5384  		p_kb_category_name =>'MES',
5385  			p_document_title =>v_item.item_name,
5386  p_doc_last_modified_date=>v_item.last_update_date,
5387  			p_score =>l_kb_rank,
5388  			p_url =>' ',
5389 			p_kb_delete=>'N',
5390 	p_CREATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5391     	p_CREATION_DATE  =>SYSDATE,
5392     	p_LAST_UPDATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5393     	p_LAST_UPDATE_DATE  =>SYSDATE,
5394     	p_LAST_UPDATE_LOGIN=>TO_NUMBER (FND_PROFILE.VALUE('LOGIN_ID')) ,
5395     	p_ATTRIBUTE1   =>null,
5396     	p_ATTRIBUTE2   =>null,
5397     	p_ATTRIBUTE3   =>null,
5398     	p_ATTRIBUTE4   =>null,
5399     	p_ATTRIBUTE5   =>null,
5400     	p_ATTRIBUTE6   =>null,
5401     	p_ATTRIBUTE7   =>null,
5402     	p_ATTRIBUTE8   =>null,
5403     	p_ATTRIBUTE9   =>null,
5404     	p_ATTRIBUTE10  =>null,
5405     	p_ATTRIBUTE11  =>null,
5406     	p_ATTRIBUTE12  =>null,
5407     	p_ATTRIBUTE13  =>null,
5408     	p_ATTRIBUTE14  =>null,
5409     	p_ATTRIBUTE15  =>null,
5410 			x_return_status=>l_ret_status,
5411 			x_msg_count=>l_msg_count,
5412 			x_msg_data=>l_msg_data);
5413 	END LOOP;
5414 	END IF;		-- Endof search_type<>'CM'
5415    	EXCEPTION WHEN OTHERS THEN
5416 	if g_exception_log then
5417 		l_logmessage:='Error in calling Document Search while reprocessing auto-reply message'||sqlerrm ;
5418 		iem_logger(l_logmessage);
5419 	end if;
5420 	END;
5421 	if g_statement_log then
5422 	l_logmessage:='End Of Calling Specific Search API  and end of Processing for the message ' ;
5423 	iem_logger(l_logmessage);
5424 	end if;
5425 -- Standard Check Of p_commit.
5426 	IF p_commit='T' THEN
5427 		COMMIT WORK;
5428 	END IF;
5429 -- Standard callto get message count and if count is 1, get message info.
5430        FND_MSG_PUB.Count_And_Get
5431 			( p_count =>  x_msg_count,
5432                  	p_data  =>    x_msg_data
5433 			);
5434 	x_return_status:='S';
5435 
5436  EXCEPTION WHEN ABORT_REPROCESSING THEN
5437 		x_Return_status:='E';
5438 		rollback to processautoreply;
5439  WHEN OTHERS THEN
5440 	if g_exception_log then
5441 	l_logmessage:='Error occur during Reprocessing autoreply message '||sqlerrm ;
5442 	iem_logger(l_logmessage);
5443 	end if;
5444 		rollback to processautoreply;
5445       x_return_status := FND_API.G_RET_STS_ERROR;
5446 	IF 	FND_MSG_PUB.Check_Msg_Level
5447 			(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR)
5448 		THEN
5449         		FND_MSG_PUB.Add_Exc_Msg
5450     	    		(	G_PKG_NAME  	    ,
5451     	    			l_api_name
5452 	    		);
5453 		END IF;
5454 		FND_MSG_PUB.Count_And_Get
5455     		( p_count         	=>      x_msg_count     	,
5456         	p_data          	=>      x_msg_data
5457     		);
5458  END REPROCESSAUTOREPLY;
5459 
5460 procedure IEM_WF_SPECIFICSEARCH(
5461     l_msg_id  in number,
5462     l_email_account_id   in number,
5463     l_classification_id	in number,
5464     l_category_id  AMV_SEARCH_PVT.amv_number_varray_type,
5465     l_repos		in varchar2,
5466     l_stat    out nocopy varchar2,
5467     l_out_text	out nocopy varchar2)
5468 is
5469   l_return_status      VARCHAR2(20);
5470   l_msg_count          NUMBER;
5471   l_msg_data           VARCHAR2(400);
5472   l_doc_id		number;
5473   l_kb_repos		iem_kb_results.kb_repository_name%type;
5474 l_rows_returned cs_kb_number_tbl_type :=cs_kb_number_tbl_type();
5475 l_next_row_pos cs_kb_number_tbl_type :=cs_kb_number_tbl_type();
5476 l_total_row_cnt cs_kb_number_tbl_type :=cs_kb_number_tbl_type();
5477 l_logmessage		varchar2(500);
5478 l_level			varchar2(20):='STATEMENT';
5479 l_app_id		number;
5480 l_part		number;
5481 l_flag		number:=1;
5482 l_ret		number;
5483 l_search		varchar2(100);
5484 l_theme		   varchar2(200);
5485 l_tstr		   varchar2(2000);
5486 l_errtext		   varchar2(200);
5487 l_score			number;
5488 l_class          NUMBER;
5489 l_count          NUMBER;
5490 l_next_row_tbl	cs_kb_number_tbl_type:=cs_kb_number_tbl_type();
5491 l_total_row_tbl	cs_kb_number_tbl_type:=cs_kb_number_tbl_type();
5492 l_area_array    AMV_SEARCH_PVT.amv_char_varray_type:=null;
5493 l_result_array       cs_kb_result_varray_type;
5494 l_amv_result_array    AMV_SEARCH_PVT.amv_searchres_varray_type;
5495 l_content_array AMV_SEARCH_PVT.amv_char_varray_type:=null;
5496 l_param_array AMV_SEARCH_PVT.amv_searchpar_varray_type;
5497 l_rep	cs_kb_varchar100_tbl_type ;
5498 l_imt_string varchar2(4000);
5499 r_imt_string varchar2(4000);
5500 l_proc_name	varchar2(30):='IEM_WF_SPECIFICSEARCH';
5501 --l_category_id	AMV_SEARCH_PVT.amv_number_varray_type:=AMV_SEARCH_PVT.amv_number_varray_type();
5502 l_tag1		number;
5503 l_cnt		number;
5504 l_res1		varchar2(10);
5505 l_res2		varchar2(10);
5506 l_search_repos		varchar2(10);
5507 l_days  number ;
5508 l_user_id number ;
5509 l_rows_req cs_kb_number_tbl_type ;
5510 l_rows		number;
5511 l_start_row cs_kb_number_tbl_type:=cs_kb_number_tbl_type(1,1);
5512 l_sms_string	varchar2(255);
5513 l_sms_count    number;
5514 l_counter    number:=1;
5515 g_app_id		number;
5516 cursor c1 is select category_id from iem_account_categories
5517 where email_account_id=l_email_account_id;
5518  cursor c2 is
5519  select keyword,weight from iem_intent_dtls where intent_id=l_classification_id
5520  and query_response='R';
5521  cursor c_doc is
5522  select document_id,KB_REPOSITORY_NAME,score,kb_result_id from iem_kb_results
5523  where message_id=l_msg_id
5524  order by 2,1,score asc;
5525 begin
5526 	select count(*) into l_cnt from iem_kb_results
5527 	where message_id=l_msg_id
5528 	and classification_id=l_classification_id
5529 	and email_account_id=l_email_account_id;
5530  IF l_cnt=0 THEN
5531 	if g_statement_log then
5532 		l_logmessage:= 'Start Initializing for Specific search  '||l_msg_id;
5533 		iem_logger(l_logmessage);
5534 	end if;
5535 	-- Prepare the response String  for Intent
5536 	for v2 in c2 loop
5537 		r_imt_string:=r_imt_string||'about ('||v2.keyword||')*'||v2.weight||',';
5538 	end loop;
5539 	if r_imt_string is not null then
5540 		r_imt_string:=substr(r_imt_string,1,length(r_imt_string)-1);
5541 	end if;
5542 
5543 	l_rows:=10;	-- Number of Document Retrieved...
5544 	l_rows_req :=cs_kb_number_tbl_type(l_rows,l_rows);
5545 	G_APP_ID:=520;
5546  l_area_array := AMV_SEARCH_PVT.amv_char_varray_type();
5547  l_area_array.extend;
5548 l_area_array(1) := 'ITEM';
5549 l_content_array := AMV_SEARCH_PVT.amv_char_varray_type();
5550 l_content_array.extend;
5551 l_content_array(1) := 'CONTENT';
5552 l_content_array.extend;
5553  l_param_array := AMV_SEARCH_PVT.amv_searchpar_varray_type();
5554 		l_rep	:=cs_kb_varchar100_tbl_type() ;
5555  begin
5556 	select classification_string into l_imt_string
5557 	from IEM_EMAIL_CLASSIFICATIONS
5558 	WHERE MESSAGE_ID=l_msg_id AND EMAIL_ACCOUNT_ID=l_email_account_id
5559 	and classification_id=l_classification_id;
5560 	IF l_repos is null then
5561 	l_search_repos:=FND_PROFILE.VALUE_SPECIFIC('IEM_KNOWLEDGE_BASE');
5562 	IF l_search_repos is null then
5563 		l_search_repos:='MES';
5564      END IF;
5565 	else
5566 		l_search_repos:=l_repos;
5567 	end if;
5568 IF (l_search_repos='MES') or (l_search_repos='ALL') Then
5569 	if g_statement_log then
5570 	l_logmessage:= 'Calling the MES Specific Search For Message Id '||l_msg_id;
5571 	iem_logger(l_logmessage);
5572 	end if;
5573 		l_rep	:=cs_kb_varchar100_tbl_type('MES') ;
5574   cs_knowledge_grp.Specific_Search(
5575       p_api_version => 1.0,
5576       p_init_msg_list => fnd_api.g_true,
5577       --p_validation_level => p_validation_level,
5578       x_return_status => l_return_status,
5579       x_msg_count => l_msg_count,
5580       x_msg_data => l_msg_data,
5581       p_repository_tbl => l_rep,
5582       p_search_string => l_imt_string,
5583       p_updated_in_days => l_days,
5584       p_check_login_user => FND_API.G_FALSE,
5585       p_application_id => G_APP_ID,
5586         p_area_array => l_area_array,
5587         p_content_array => l_content_array,
5588         p_param_array => l_param_array,
5589         p_user_id => l_user_id,
5590         p_category_id => l_category_id,
5591         p_include_subcats   => FND_API.G_FALSE,
5592         p_external_contents => FND_API.G_TRUE,
5593       p_rows_requested_tbl => l_rows_req,
5594       p_start_row_pos_tbl  => l_start_row,
5595       p_get_total_cnt_flag => 'T',
5596       x_rows_returned_tbl => l_rows_returned,
5597       x_next_row_pos_tbl => l_next_row_pos,
5598       x_total_row_cnt_tbl => l_total_row_cnt,
5599       x_result_array  => l_result_array);
5600 
5601 	if g_statement_log then
5602 		l_logmessage:= 'End Calling the Specific Search For Message Id '||l_msg_id||' No of document Returned '||l_result_array.count;
5603 	 	iem_logger(l_logmessage);
5604 	end if;
5605 -- Insert The Data into IEM_KB_RESULTS
5606 
5607 	FOR l_count IN 1..l_result_array.count LOOP
5608 		IEM_KB_RESULTS_PVT.create_item(p_api_version_number=>1.0,
5609  		  	      		p_init_msg_list=>'F' ,
5610 		    	      		p_commit=>'F'	    ,
5611 						 p_message_id =>l_msg_id,
5612 						 p_classification_id=>l_classification_id,
5613  				p_email_account_id=>l_email_account_id ,
5614  			p_document_id =>to_char(l_result_array(l_count).id) ,
5615  		p_kb_repository_name =>l_result_array(l_count).repository,
5616  		p_kb_category_name =>l_result_array(l_count).repository,
5617  			p_document_title =>l_result_array(l_count).title,
5618  p_doc_last_modified_date=>l_result_array(l_count).last_update_date,
5619  			p_score =>to_char(l_result_array(l_count).score),
5620  			p_url =>l_result_array(l_count).url_string,
5621 			p_kb_delete=>'N',
5622 	p_CREATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5623     	p_CREATION_DATE  =>SYSDATE,
5624     	p_LAST_UPDATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5625     	p_LAST_UPDATE_DATE  =>SYSDATE,
5626     	p_LAST_UPDATE_LOGIN=>TO_NUMBER (FND_PROFILE.VALUE('LOGIN_ID')) ,
5627     	p_ATTRIBUTE1   =>null,
5628     	p_ATTRIBUTE2   =>null,
5629     	p_ATTRIBUTE3   =>null,
5630     	p_ATTRIBUTE4   =>null,
5631     	p_ATTRIBUTE5   =>null,
5632     	p_ATTRIBUTE6   =>null,
5633     	p_ATTRIBUTE7   =>null,
5634     	p_ATTRIBUTE8   =>null,
5635     	p_ATTRIBUTE9   =>null,
5636     	p_ATTRIBUTE10  =>null,
5637     	p_ATTRIBUTE11  =>null,
5638     	p_ATTRIBUTE12  =>null,
5639     	p_ATTRIBUTE13  =>null,
5640     	p_ATTRIBUTE14  =>null,
5641     	p_ATTRIBUTE15  =>null,
5642 			x_return_status=>l_return_status,
5643 			x_msg_count=>l_msg_count,
5644 			x_msg_data=>l_msg_data);
5645 	END LOOP;
5646 --  Calling Search Api for Response String Separately
5647 IF r_imt_string is not null then
5648   cs_knowledge_grp.Specific_Search(
5649       p_api_version => 1.0,
5650       p_init_msg_list => fnd_api.g_true,
5651       --p_validation_level => p_validation_level,
5652       x_return_status => l_return_status,
5653       x_msg_count => l_msg_count,
5654       x_msg_data => l_msg_data,
5655       p_repository_tbl => l_rep,
5656       p_search_string => r_imt_string,
5657       p_updated_in_days => l_days,
5658       p_check_login_user => FND_API.G_FALSE,
5659       p_application_id => G_APP_ID,
5660         p_area_array => l_area_array,
5661         p_content_array => l_content_array,
5662         p_param_array => l_param_array,
5663         p_user_id => l_user_id,
5664         p_category_id => l_category_id,
5665         p_include_subcats   => FND_API.G_FALSE,
5666         p_external_contents => FND_API.G_TRUE,
5667       p_rows_requested_tbl => l_rows_req,
5668       p_start_row_pos_tbl  => l_start_row,
5669       p_get_total_cnt_flag => 'T',
5670       x_rows_returned_tbl => l_rows_returned,
5671       x_next_row_pos_tbl => l_next_row_pos,
5672       x_total_row_cnt_tbl => l_total_row_cnt,
5673       x_result_array  => l_result_array);
5674 
5675 	if g_statement_log then
5676 	l_logmessage:= 'End Calling the Specific Search For Message Id '||l_msg_id||' No of document Returned '||l_result_array.count;
5677 	 iem_logger(l_logmessage);
5678 	end if;
5679 -- Insert The Data into IEM_KB_RESULTS
5680 
5681 	FOR l_count IN 1..l_result_array.count LOOP
5682 		IEM_KB_RESULTS_PVT.create_item(p_api_version_number=>1.0,
5683  		  	      		p_init_msg_list=>'F' ,
5684 		    	      		p_commit=>'F'	    ,
5685 						 p_message_id =>l_msg_id,
5686 						 p_classification_id=>l_classification_id,
5687  				p_email_account_id=>l_email_account_id ,
5688  			p_document_id =>to_char(l_result_array(l_count).id) ,
5689  		p_kb_repository_name =>l_result_array(l_count).repository,
5690  		p_kb_category_name =>l_result_array(l_count).repository,
5691  			p_document_title =>l_result_array(l_count).title,
5692  p_doc_last_modified_date=>l_result_array(l_count).last_update_date,
5693  			p_score =>to_char(l_result_array(l_count).score),
5694  			p_url =>l_result_array(l_count).url_string,
5695 			p_kb_delete=>'N',
5696 	p_CREATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5697     	p_CREATION_DATE  =>SYSDATE,
5698     	p_LAST_UPDATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5699     	p_LAST_UPDATE_DATE  =>SYSDATE,
5700     	p_LAST_UPDATE_LOGIN=>TO_NUMBER (FND_PROFILE.VALUE('LOGIN_ID')) ,
5701     	p_ATTRIBUTE1   =>null,
5702     	p_ATTRIBUTE2   =>null,
5703     	p_ATTRIBUTE3   =>null,
5704     	p_ATTRIBUTE4   =>null,
5705     	p_ATTRIBUTE5   =>null,
5706     	p_ATTRIBUTE6   =>null,
5707     	p_ATTRIBUTE7   =>null,
5708     	p_ATTRIBUTE8   =>null,
5709     	p_ATTRIBUTE9   =>null,
5710     	p_ATTRIBUTE10  =>null,
5711     	p_ATTRIBUTE11  =>null,
5712     	p_ATTRIBUTE12  =>null,
5713     	p_ATTRIBUTE13  =>null,
5714     	p_ATTRIBUTE14  =>null,
5715     	p_ATTRIBUTE15  =>null,
5716 			x_return_status=>l_return_status,
5717 			x_msg_count=>l_msg_count,
5718 			x_msg_data=>l_msg_data);
5719 	END LOOP;
5720 	END IF;	-- End if for if r_imt_string is not null
5721   END IF;
5722 IF (l_search_repos='SMS') or (l_search_repos='ALL') Then
5723 	if g_statement_log then
5724 		l_logmessage:= 'Calling the SMS Specific Search For Message Id '||l_msg_id;
5725 		iem_logger(l_logmessage);
5726 	end if;
5727 		l_rep	:=cs_kb_varchar100_tbl_type('SMS') ;
5728 		-- Currently SMS has 255 character limitations . So we have to
5729 		--truncate the SMS search string to 255 character length which
5730 		--will removed later
5731   IF length(l_imt_string)>255 THEN
5732 		l_sms_string:=substr(l_imt_string,1,255);
5733 		l_sms_count:=instr(l_sms_string,',about',-1,1);
5734 		l_imt_string:=substr(l_sms_string,1,l_sms_count-1);
5735   END IF;
5736   cs_knowledge_grp.Specific_Search(
5737       p_api_version => 1.0,
5738       p_init_msg_list => fnd_api.g_true,
5739       --p_validation_level => p_validation_level,
5740       x_return_status => l_return_status,
5741       x_msg_count => l_msg_count,
5742       x_msg_data => l_msg_data,
5743       p_repository_tbl => l_rep,
5744       p_search_string => l_imt_string,
5745       p_updated_in_days => l_days,
5746       p_check_login_user => FND_API.G_FALSE,
5747       p_application_id => G_APP_ID,
5748         p_area_array => l_area_array,
5749         p_content_array => l_content_array,
5750         p_param_array => l_param_array,
5751         p_user_id => l_user_id,
5752         p_category_id => l_category_id,
5753         p_include_subcats   => FND_API.G_TRUE,
5754         p_external_contents => FND_API.G_TRUE,
5755       p_rows_requested_tbl => l_rows_req,
5756       p_start_row_pos_tbl  => l_start_row,
5757       p_get_total_cnt_flag => 'T',
5758       x_rows_returned_tbl => l_rows_returned,
5759       x_next_row_pos_tbl => l_next_row_pos,
5760       x_total_row_cnt_tbl => l_total_row_cnt,
5761       x_result_array  => l_result_array);
5762 
5763 	if g_statement_log then
5764 	l_logmessage:= 'End Calling the Specific Search For Message Id '||l_msg_id||' No of document Returned '||l_result_array.count;
5765 	 iem_logger(l_logmessage);
5766 	end if;
5767 -- Insert The Data into IEM_KB_RESULTS
5768 
5769 	FOR l_count IN 1..l_result_array.count LOOP
5770 		IEM_KB_RESULTS_PVT.create_item(p_api_version_number=>1.0,
5771  		  	      		p_init_msg_list=>'F' ,
5772 		    	      		p_commit=>'F'	    ,
5773 						 p_message_id =>l_msg_id,
5774 						 p_classification_id=>l_classification_id,
5775  				p_email_account_id=>l_email_account_id ,
5776  			p_document_id =>to_char(l_result_array(l_count).id) ,
5777  		p_kb_repository_name =>l_result_array(l_count).repository,
5778  		p_kb_category_name =>l_result_array(l_count).repository,
5779  			p_document_title =>l_result_array(l_count).title,
5780  p_doc_last_modified_date=>l_result_array(l_count).last_update_date,
5781  			p_score =>to_char(l_result_array(l_count).score),
5782  			p_url =>l_result_array(l_count).url_string,
5783 			p_kb_delete=>'N',
5784 	p_CREATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5785     	p_CREATION_DATE  =>SYSDATE,
5786     	p_LAST_UPDATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5787     	p_LAST_UPDATE_DATE  =>SYSDATE,
5788     	p_LAST_UPDATE_LOGIN=>TO_NUMBER (FND_PROFILE.VALUE('LOGIN_ID')) ,
5789     	p_ATTRIBUTE1   =>null,
5790     	p_ATTRIBUTE2   =>null,
5791     	p_ATTRIBUTE3   =>null,
5792     	p_ATTRIBUTE4   =>null,
5793     	p_ATTRIBUTE5   =>null,
5794     	p_ATTRIBUTE6   =>null,
5795     	p_ATTRIBUTE7   =>null,
5796     	p_ATTRIBUTE8   =>null,
5797     	p_ATTRIBUTE9   =>null,
5798     	p_ATTRIBUTE10  =>null,
5799     	p_ATTRIBUTE11  =>null,
5800     	p_ATTRIBUTE12  =>null,
5801     	p_ATTRIBUTE13  =>null,
5802     	p_ATTRIBUTE14  =>null,
5803     	p_ATTRIBUTE15  =>null,
5804 			x_return_status=>l_return_status,
5805 			x_msg_count=>l_msg_count,
5806 			x_msg_data=>l_msg_data);
5807 	END LOOP;
5808  IF r_imt_string is not null then
5809   -- Calling Specific Search for Response String
5810   cs_knowledge_grp.Specific_Search(
5811       p_api_version => 1.0,
5812       p_init_msg_list => fnd_api.g_true,
5813       --p_validation_level => p_validation_level,
5814       x_return_status => l_return_status,
5815       x_msg_count => l_msg_count,
5816       x_msg_data => l_msg_data,
5817       p_repository_tbl => l_rep,
5818       p_search_string => r_imt_string,
5819       p_updated_in_days => l_days,
5820       p_check_login_user => FND_API.G_FALSE,
5821       p_application_id => G_APP_ID,
5822         p_area_array => l_area_array,
5823         p_content_array => l_content_array,
5824         p_param_array => l_param_array,
5825         p_user_id => l_user_id,
5826         p_category_id => l_category_id,
5827         p_include_subcats   => FND_API.G_FALSE,
5828         p_external_contents => FND_API.G_TRUE,
5829       p_rows_requested_tbl => l_rows_req,
5830       p_start_row_pos_tbl  => l_start_row,
5831       p_get_total_cnt_flag => 'T',
5832       x_rows_returned_tbl => l_rows_returned,
5833       x_next_row_pos_tbl => l_next_row_pos,
5834       x_total_row_cnt_tbl => l_total_row_cnt,
5835       x_result_array  => l_result_array);
5836 
5837 	if g_statement_log then
5838 	l_logmessage:= 'End Calling the Specific Search For Message Id '||l_msg_id||' No of document Returned '||l_result_array.count;
5839 	 iem_logger(l_logmessage);
5840 	end if;
5841 -- Insert The Data into IEM_KB_RESULTS
5842 
5843 	FOR l_count IN 1..l_result_array.count LOOP
5844 		IEM_KB_RESULTS_PVT.create_item(p_api_version_number=>1.0,
5845  		  	      		p_init_msg_list=>'F' ,
5846 		    	      		p_commit=>'F'	    ,
5847 						 p_message_id =>l_msg_id,
5848 						 p_classification_id=>l_classification_id,
5849  				p_email_account_id=>l_email_account_id ,
5850  			p_document_id =>to_char(l_result_array(l_count).id) ,
5851  		p_kb_repository_name =>l_result_array(l_count).repository,
5852  		p_kb_category_name =>l_result_array(l_count).repository,
5853  			p_document_title =>l_result_array(l_count).title,
5854  p_doc_last_modified_date=>l_result_array(l_count).last_update_date,
5855  			p_score =>to_char(l_result_array(l_count).score),
5856  			p_url =>l_result_array(l_count).url_string,
5857 			p_kb_delete=>'N',
5858 	p_CREATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5859     	p_CREATION_DATE  =>SYSDATE,
5860     	p_LAST_UPDATED_BY  =>TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),
5861     	p_LAST_UPDATE_DATE  =>SYSDATE,
5862     	p_LAST_UPDATE_LOGIN=>TO_NUMBER (FND_PROFILE.VALUE('LOGIN_ID')) ,
5863     	p_ATTRIBUTE1   =>null,
5864     	p_ATTRIBUTE2   =>null,
5865     	p_ATTRIBUTE3   =>null,
5866     	p_ATTRIBUTE4   =>null,
5867     	p_ATTRIBUTE5   =>null,
5868     	p_ATTRIBUTE6   =>null,
5869     	p_ATTRIBUTE7   =>null,
5870     	p_ATTRIBUTE8   =>null,
5871     	p_ATTRIBUTE9   =>null,
5872     	p_ATTRIBUTE10  =>null,
5873     	p_ATTRIBUTE11  =>null,
5874     	p_ATTRIBUTE12  =>null,
5875     	p_ATTRIBUTE13  =>null,
5876     	p_ATTRIBUTE14  =>null,
5877     	p_ATTRIBUTE15  =>null,
5878 			x_return_status=>l_return_status,
5879 			x_msg_count=>l_msg_count,
5880 			x_msg_data=>l_msg_data);
5881 	END LOOP;
5882   END IF;		--End if for r_imt_string is not null
5883  END IF;
5884  -- Deleting duplicate rows from Document retrieval set
5885  l_doc_id:=0;
5886  l_kb_repos:=null;
5887  for v_doc in c_doc LOOP
5888  	if (v_doc.document_id = l_doc_id and v_doc.kb_repository_name=l_kb_repos) then
5889  		delete from iem_kb_results where message_id=l_msg_id and kb_result_id=v_doc.kb_result_id;
5890 	end if;
5891  l_doc_id:=v_doc.document_id;
5892  l_kb_repos:=v_doc.kb_repository_name;
5893  END LOOP;
5894 
5895 EXCEPTION when others then
5896 		null;
5897 END;
5898 	l_stat:='S';
5899 ELSE
5900 		l_stat:='S';
5901 END IF;
5902 exception
5903   when others then
5904 	if g_exception_log then
5905 		l_logmessage:='Oracle Error in MES Search '||sqlerrm||' while processing for message id '||l_msg_id;
5906 	 iem_logger(l_logmessage);
5907 	end if;
5908 		l_stat:='E';
5909 		l_out_text:='Oracle Error in Specific Search '||sqlerrm||' while processing for message id '||l_msg_id;
5910 end IEM_WF_SPECIFICSEARCH;
5911 procedure IEM_RETURN_ENCRYPTID
5912 	(p_subject	in varchar2,
5913 	x_id		out nocopy varchar2,
5914 	x_Status		out nocopy varchar2) IS
5915 l_search	varchar2(10);
5916 l_index1	number;
5917 l_index2	number;
5918 l_encrypted_id		varchar2(100);
5919 begin
5920 	l_search:='[REF:';
5921  l_index1:=instr(p_subject,l_search,1,1);
5922  l_index2:=instr(substr(p_subject,l_index1+length(l_search),length(p_subject)-1),']',1,1);
5923  IF (l_index1 <> 0) and (l_index2<>0) THEN
5924 	l_encrypted_id:=ltrim(substr(p_subject,l_index1+length(l_search),l_index2-1));
5925  END IF;
5926  x_id:=l_encrypted_id;
5927  x_status:='S';
5928  EXCEPTION WHEN OTHERS THEN
5929  	x_status:='E';
5930 end IEM_RETURN_ENCRYPTID;
5931 
5932 --siahmed 12.1.3 advanced SR processing changes begin
5933 
5934 
5935   --Developer attention:
5936   --I am using the rownum to restrict the number of rows that gets returned. Since
5937   --rownum will limit the number of rows it searches; if it finds more than one match
5938   --we are not interested with that data and therefore we need not proceed further.
5939   --Rownum works in the following manner therefore it should be ok for us to use as a
5940   --restricted methadology
5941   --1. The FROM/WHERE clause goes first.
5942   --2. ROWNUM is assigned and incremented to each output row from the FROM/WHERE clause.
5943 
5944   --p_account_type is to determine weather an account is internal or external
5945     --this will help us determine which processing route to proceede with during
5946     --contact processing. Account type can of be type I for internal
5947     --this is the p_employee_flag that gets passed to the create_Sr api
5948   --p_default_type_id is the default status id being used by the current sr processing
5949     --incase the user pass a sr_type but an associated Sr_type_id could not be recovered
5950     --then we need to use the default type_id to create the sr
5951   --p_default_customer_id this is the customer_id that will be used if no customer id could be
5952     --found using the values that the customer has provided.This is the default customer_id
5953     --which is currently being used during the R12 functionality of SR creation.
5954   PROCEDURE advanced_sr_processing (
5955                   p_message_id          IN NUMBER,
5956                   p_parser_id           IN NUMBER,
5957                   p_account_type        IN VARCHAR2 DEFAULT NULL, --p_employee_flag
5958                   p_default_type_id   IN NUMBER   DEFAULT NULL, --p_sr_type_id
5959                   p_default_customer_id IN NUMBER   DEFAULT NULL, --p_party_id
5960                   p_init_msg_list	IN   VARCHAR2 	:= FND_API.G_FALSE,
5961                   p_commit		IN   VARCHAR2 	:= FND_API.G_FALSE,
5962                   p_note		IN   VARCHAR2,
5963                   p_subject             IN   VARCHAR2,
5964                   p_note_type           IN   VARCHAR2,
5965                   p_contact_id          IN   NUMBER             := NULL,
5966                   p_contact_point_id    IN   NUMBER             := NULL,
5967                   x_return_status	OUT  NOCOPY   VARCHAR2,
5968                   x_msg_count		OUT  NOCOPY  NUMBER,
5969                   x_msg_data		OUT  NOCOPY  VARCHAR2,
5970                   x_request_id          OUT  NOCOPY  NUMBER
5971                 )
5972   IS
5973     -- local var for creating SR
5974     l_return_status        VARCHAR2(20) := FND_API.G_RET_STS_SUCCESS;
5975     l_msg_count            NUMBER := 0;
5976     l_msg_data             VARCHAR2(2000);
5977     l_index                NUMBER := 1;
5978 
5979     l_api_name            VARCHAR2(255):='ADVANCED_SR_PROCESSING';
5980     --l_api_version_number  NUMBER:=1.0;
5981     l_cs_version_number   NUMBER:=4.0;
5982 
5983     l_service_request_rec  CS_ServiceRequest_PUB.service_request_rec_type;
5984     p_notes                CS_ServiceRequest_PUB.notes_table;
5985     p_contacts             CS_ServiceRequest_PUB.contacts_table;
5986     l_sr_create_out_rec    CS_ServiceRequest_PUB.sr_create_out_rec_type;
5987     p_keyVals_tbl          IEM_ROUTE_PUB.keyVals_tbl_type;
5988 
5989     l_notes                CS_ServiceRequest_PUB.notes_table;
5990     l_contacts             CS_ServiceRequest_PUB.contacts_table;
5991     l_summary_prefix       VARCHAR2(80);
5992     l_summary              VARCHAR2(300);
5993     l_party_type           VARCHAR2(80);
5994     l_contact_type         VARCHAR2(80);
5995     l_auto_assign          VARCHAR2(10);
5996     --end of local var for SR
5997 
5998      l_coverage_template_id    NUMBER;
5999 
6000       IEM_SR_NOT_CREATE EXCEPTION;
6001 
6002     --local varaibles for getting values to be passed to the SR API
6003     l_cust_account_id     NUMBER; --to be passed as account_id in SR API
6004     l_customer_phone_id   NUMBER;
6005     l_customer_email_id   NUMBER;
6006     l_customer_product_id NUMBER;
6007     l_inventory_item_id   NUMBER;
6008     l_inventory_org_id    NUMBER;
6009     l_incident_location_id  NUMBER;
6010     l_type_id              NUMBER;
6011     l_problem_code        VARCHAR2(100);
6012     l_urgency_id          NUMBER;
6013     l_party_site_id       NUMBER;
6014     l_ext_ref             VARCHAR2(100);
6015 
6016 
6017     --cursor for doing customer info processing
6018     --in the order or rank. Attribute with the lower number
6019     --will get a higher precedence.  So 1 has a higer precedence over 2 or 3
6020     --Question
6021     -- we can also make these attributes dynamic by driving them from fnd tabel
6022     -- rather than hard coding them;where we can define which processing group each column name belongs to
6023     Cursor c_customer_attributes (l_parser_id IN NUMBER)
6024     IS
6025     Select parser_id, start_tag, end_tag, column_name, rank
6026     from iem_parser_dtls
6027     where parser_id = l_parser_id
6028     and UPPER(column_name) IN ('ACCOUNT_NUMBER','CUSTOMER_NUMBER','CUSTOMER_NAME',
6029                                'CUSTOMER_PHONE','CUSTOMER_EMAIL','INSTANCE_NUMBER',
6030       		  	       'INSTANCE_SERIAL_NUMBER','INCIDENT_SITE_NUMBER','CONTACT_NUMBER',
6031                                'CONTACT_NAME','CONTACT_PHONE','CONTACT_EMAIL')
6032     order by rank asc;
6033 
6034     --Note: serial number is not being implemented
6035     Cursor c_other_attributes (l_parser_id IN NUMBER)
6036     IS
6037     Select parser_id, start_tag, end_tag, column_name, rank
6038     from iem_parser_dtls
6039     where parser_id = l_parser_id
6040     and UPPER(column_name) IN ('ADDRESSEE', 'EXTERNAL_REFERENCE', 'INCIDENT_ADDRESS1', 'INCIDENT_ADDRESS2',
6041                                'INCIDENT_ADDRESS3', 'INCIDENT_ADDRESS4', 'INCIDENT_CITY', 'INCIDENT_COUNTRY',
6042                                'INCIDENT_COUNTY', 'INCIDENT_POSTAL_CODE', 'INCIDENT_PROVINCE', 'INCIDENT_STATE',
6043                                'PROBLEM_CODE',  'SERVICE_REQUEST_TYPE', 'SITE_NAME', 'URGENCY', 'INVENTORY_ITEM_NAME')
6044     order by rank asc;
6045 
6046    CURSOR caller_type
6047    IS
6048    SELECT party_type
6049    FROM  hz_parties a
6050    WHERE a.party_id = g_customer_id
6051    AND	a.status = 'A'
6052    AND   a.party_type IN ('ORGANIZATION','PERSON');
6053 
6054     --local varaibles to store parsed tag data information
6055     --these local var are needed because these att will go through
6056     --double processing. Once for finding the customer_id and once for
6057     --fiding more information from those attr. There fore the loc
6058     --var will prevent an extra trip to get the parsed values
6059     l_account_number VARCHAR2(100);
6060     l_customer_number VARCHAR2(100);
6061     l_customer_name VARCHAR2(100);
6062     l_customer_phone VARCHAR2(100);
6063     l_customer_email VARCHAR2(100);
6064     l_instance_number VARCHAR2(100);
6065     l_instance_serial_number VARCHAR2(100);
6066     l_incident_site_number VARCHAR2(100);
6067     l_contact_number VARCHAR2(100);
6068     l_contact_name VARCHAR2(100);
6069     l_contact_phone VARCHAR2(100);
6070     l_contact_email VARCHAR2(100);
6071 
6072     --getting parsed inventory values
6073     --for all other attrbutee processing we will use tag_Data
6074     l_tag_data    VARCHAR2(1000);
6075 
6076     l_addressee                     VARCHAR2(100);
6077     l_external_reference            VARCHAR2(100);
6078     l_incident_address1             VARCHAR2(100);
6079     l_incident_address2             VARCHAR2(100);
6080     l_incident_address3             VARCHAR2(100);
6081     l_incident_address4             VARCHAR2(100);
6082     l_incident_city                 VARCHAR2(100);
6083     l_incident_country              VARCHAR2(100);
6084     l_incident_county               VARCHAR2(100);
6085     l_incident_postal_code          VARCHAR2(100);
6086     l_incident_province             VARCHAR2(100);
6087     l_incident_state                VARCHAR2(100);
6088     l_inventory_item_name           VARCHAR2(100);
6089     l_serial_number                 VARCHAR2(100);
6090     l_service_request_type          VARCHAR2(100);
6091     l_site_name                     VARCHAR2(100);
6092     l_urgency                       VARCHAR2(100);
6093 
6094     --for debuggin remove late
6095    lx_msg_data                 VARCHAR2(2000);
6096    lx_return_status            VARCHAR2(1);
6097    lx_msg_index_out            NUMBER;
6098 
6099    --logger
6100    l_logmessage		varchar2(2000):=' ';
6101 
6102    --added for bug 12619947 by siahmed
6103    l_category_id   NUMBER;
6104    --l_category_set_id NUMBER;
6105 
6106     --bug 12663292
6107    l_bill_to_site_id   NUMBER;
6108    l_ship_to_site_id   NUMBER;
6109    l_billship_account  NUMBER;
6110    --end bug 12663292
6111 
6112 
6113   BEGIN
6114 
6115   --initialize all the global variables to null here to prevent session issues
6116   g_customer_id          := null;
6117   g_contact_party_id     := null;
6118   g_contact_party_type   := null;
6119   g_contact_point_id     := null;
6120   g_contact_point_type   := null;
6121 
6122 
6123     --assign the account_type to the global variable g_account_type
6124     --this global variabel will be later used in the contact processing
6125     l_logmessage:='account type:'|| p_account_type || 'p_default_Customer_id:'||p_default_customer_id ||'p_contact_id:'||p_contact_id;
6126     iem_logger(l_logmessage);
6127 
6128     g_account_type := p_account_type;
6129 
6130     -- process all the customer information tags to get customer_number
6131     --this will give us the req in sequence and we can process it for customer
6132     --note the internal getCustomerNumber procedure makes sure that if we have already
6133     --got a customer_id then dont try to fetch the customer_id
6134     IF (g_account_type = 'I') THEN
6135 
6136         l_logmessage:='Account type is of I ';
6137         iem_logger(l_logmessage);
6138 
6139 
6140          --we dont do any customer processing for internal accounts and use the default customer id
6141          g_customer_id := p_default_customer_id;
6142           l_logmessage:='Customer id used for internal processing is '||g_customer_id;
6143           iem_logger(l_logmessage);
6144 
6145          --if account type is of type I and the contact information has been passed in the email
6146          --then we should pick up the contact information from the email content otherwise we should
6147          --use the default
6148          FOR contact_rec in (Select start_tag, end_tag, column_name, rank
6149                                  from iem_parser_dtls
6150                                  where parser_id = p_parser_id
6151                                  and UPPER(column_name) IN ('CONTACT_PHONE','CONTACT_EMAIL')
6152                                  order by rank asc)
6153          LOOP
6154              IF (contact_rec.column_name = 'CONTACT_PHONE') THEN
6155                       BEGIN
6156                           l_contact_phone:= get_tag_data(contact_rec.start_tag, contact_rec.end_tag, p_message_id);
6157                           l_contact_phone:= REGEXP_REPLACE(l_contact_phone,'([[:punct:]|[:space:]]*)');
6158                           Select a.person_id, b.phone_id,  'PHONE','EMPLOYEE'
6159 	                  into g_contact_party_id,g_contact_point_id, g_contact_point_type, g_contact_party_type
6160 	                  from  per_workforce_x a,per_phones b
6161  			  where a.person_id = b.parent_id
6162 	                  and REGEXP_REPLACE(b.phone_number,'([[:punct:]|[:space:]]*)') = l_contact_phone;
6163                       EXCEPTION
6164                           when TOO_MANY_ROWS then
6165                              l_logmessage:='internal contact phone:'||l_contact_phone||' fetch returned too many rows'|| SQL%ROWCOUNT;
6166                              iem_logger(l_logmessage);
6167 
6168                              --plsql issue when there are many rows the first rows get associated with values
6169                               g_contact_party_id := null;
6170                               g_contact_point_id := null;
6171                               g_contact_point_type := null;
6172                               g_contact_party_type :=null;
6173                           when NO_DATA_FOUND then
6174                              l_logmessage:='contact phone:'||l_contact_phone||'  fetch returned 0 rows'|| SQL%ROWCOUNT;
6175                              iem_logger(l_logmessage);
6176 
6177                           when others then
6178                              l_logmessage:='cotanct_phone:'||l_contact_phone||'  other exception';
6179                              iem_logger(l_logmessage);
6180 
6181                       END;
6182              ELSIF (contact_rec.column_name = 'CONTACT_EMAIL') THEN
6183                       BEGIN
6184                           l_contact_email:= get_tag_data(contact_rec.start_tag, contact_rec.end_tag, p_message_id);
6185                           Select a.person_id, 'EMAIL','EMPLOYEE'
6186 	                  into g_contact_party_id, g_contact_point_type , g_contact_party_type
6187 	                  from per_workforce_current_x a
6188 	                  where UPPER(a.email_Address) = upper(l_contact_email);
6189                       EXCEPTION
6190                           when TOO_MANY_ROWS then
6191                              l_logmessage:='internal contact email:'||l_contact_email||' fetch returned too many rows'|| SQL%ROWCOUNT;
6192                              iem_logger(l_logmessage);
6193 
6194                              --plsql issue when there are many rows the first rows get associated with values
6195                               g_contact_party_id := null;
6196                               g_contact_point_type := null;
6197                               g_contact_party_type :=null;
6198                           when NO_DATA_FOUND then
6199                              l_logmessage:='contact email:'||l_contact_email||'  fetch returned 0 rows'|| SQL%ROWCOUNT;
6200                              iem_logger(l_logmessage);
6201 
6202                           when others then
6203                              l_logmessage:='cotanct_email:'||l_contact_email||'  other exception';
6204                              iem_logger(l_logmessage);
6205 
6206                       END;
6207             END IF; --end if of contact_phone and contact_Email
6208          END LOOP;
6209          -- if after the loop the values are still null then assign the default values
6210          IF g_contact_party_id IS NULL THEN
6211                     g_contact_party_id := p_contact_id;
6212                     g_contact_point_id := p_contact_point_id;
6213                     g_contact_point_type := 'EMAIL';
6214                     g_contact_party_type := 'EMPLOYEE';
6215          END IF;
6216     ELSE
6217 
6218       l_logmessage:='customer_id proessing ';
6219       iem_logger(l_logmessage);
6220 
6221       IF (g_customer_id IS NULL) THEN
6222           l_logmessage:='customer_id is null calling parser cursor ' || p_parser_id;
6223 
6224           iem_logger(l_logmessage);
6225 
6226 
6227        --this is where we will assign all the values so that we can process them later
6228        FOR r_sr_attr_assign IN c_customer_attributes(p_parser_id)
6229        LOOP
6230 
6231          IF r_sr_attr_assign.column_name ='CUSTOMER_NUMBER' THEN
6232 
6233            l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6234            iem_logger(l_logmessage);
6235            l_customer_number:= TO_NUMBER(get_tag_data(r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id));
6236          END IF;
6237 
6238          IF r_sr_attr_assign.column_name ='CUSTOMER_NAME' THEN
6239 
6240            l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6241            iem_logger(l_logmessage);
6242        	   l_customer_name:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6243          END IF;
6244 
6245          IF r_sr_attr_assign.column_name ='ACCOUNT_NUMBER' THEN
6246 
6247             l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6248             iem_logger(l_logmessage);
6249 	    l_account_number:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6250          END IF;
6251 
6252          IF r_sr_attr_assign.column_name ='CUSTOMER_PHONE' THEN
6253 
6254            l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6255            iem_logger(l_logmessage);
6256 	   l_customer_phone:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6257          END IF;
6258 
6259          IF r_sr_attr_assign.column_name ='CUSTOMER_EMAIL' THEN
6260 
6261            l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6262            iem_logger(l_logmessage);
6263 	   l_customer_email:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6264          END IF;
6265 
6266          IF r_sr_attr_assign.column_name ='INSTANCE_NUMBER' THEN
6267 
6268            l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6269            iem_logger(l_logmessage);
6270 	   l_instance_number:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6271          END IF;
6272 
6273          IF r_sr_attr_assign.column_name ='INSTANCE_SERIAL_NUMBER' THEN
6274 
6275            l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6276            iem_logger(l_logmessage);
6277 	   l_instance_serial_number:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6278          END IF;
6279 
6280          IF r_sr_attr_assign.column_name ='INCIDENT_SITE_NUMBER' THEN
6281 
6282            l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6283            iem_logger(l_logmessage);
6284 	   l_incident_site_number:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6285          END IF;
6286 
6287          IF r_sr_attr_assign.column_name ='CONTACT_NUMBER' THEN
6288            --dbms_output.put_line(r_sr_attr_assign.column_name || ' assigning ');
6289            l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6290            iem_logger(l_logmessage);
6291 	   l_contact_number:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6292          END IF;
6293 
6294          IF r_sr_attr_assign.column_name ='CONTACT_NAME' THEN
6295           --dbms_output.put_line(r_sr_attr_assign.column_name || ' assigning ');
6296 
6297           l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6298           iem_logger(l_logmessage);
6299 	   l_contact_name:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6300          END IF;
6301 
6302          IF r_sr_attr_assign.column_name ='CONTACT_PHONE' THEN
6303           --dbms_output.put_line(r_sr_attr_assign.column_name || ' assigning ');
6304           l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6305           iem_logger(l_logmessage);
6306 	   l_contact_phone:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6307          END IF;
6308 
6309          IF r_sr_attr_assign.column_name ='CONTACT_EMAIL' THEN
6310           --dbms_output.put_line(r_sr_attr_assign.column_name || ' assigning ');
6311           l_logmessage:=r_sr_attr_assign.column_name || ' assigning ';
6312           iem_logger(l_logmessage);
6313           --dbms_output.put_line(' passing contact_email_tag - starttag:'||r_sr_attr_assign.start_tag);
6314 	   l_contact_email:= get_tag_data (r_sr_attr_assign.start_tag, r_sr_attr_assign.end_tag, p_message_id);
6315          END IF;
6316        END LOOP;
6317 
6318   ---end of value assignment
6319 
6320 
6321 
6322 
6323        FOR r_sr_attr IN c_customer_attributes(p_parser_id)
6324        LOOP
6325 
6326          IF r_sr_attr.column_name ='CUSTOMER_NUMBER' THEN
6327            --dbms_output.put_line( r_sr_attr.column_name || ' proessing ');
6328            l_logmessage:=r_sr_attr.column_name || ' proessing ';
6329            iem_logger(l_logmessage);
6330 	   getCustomerNumber (p_customer_number => l_customer_number,
6331        		              x_customer_id     => g_customer_id);
6332          END IF;
6333 
6334          IF r_sr_attr.column_name ='CUSTOMER_NAME' THEN
6335            --dbms_output.put_line( r_sr_attr.column_name || ' proessing ');
6336            l_logmessage:=r_sr_attr.column_name || ' proessing ';
6337            iem_logger(l_logmessage);
6338 	   getCustomerNumber (p_customer_name => l_customer_name,
6339        	      	              x_customer_id   => g_customer_id);
6340          END IF;
6341 
6342          IF r_sr_attr.column_name ='ACCOUNT_NUMBER' THEN
6343           --dbms_output.put_line( r_sr_attr.column_name || ' proessing ');
6344           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6345           iem_logger(l_logmessage);
6346             getCustomerNumber (p_account_number => l_account_number,
6347                                x_customer_id => g_customer_id);
6348          END IF;
6349 
6350          IF r_sr_attr.column_name ='CUSTOMER_PHONE' THEN
6351           --dbms_output.put_line(  r_sr_attr.column_name || ' proessing ');
6352           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6353           iem_logger(l_logmessage);
6354 	   getCustomerNumber (p_customer_phone => l_customer_phone,
6355        	      	              x_customer_id   => g_customer_id);
6356          END IF;
6357 
6358          IF r_sr_attr.column_name ='CUSTOMER_EMAIL' THEN
6359           --dbms_output.put_line( r_sr_attr.column_name || ' proessing ');
6360           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6361           iem_logger(l_logmessage);
6362 	   getCustomerNumber (p_customer_email => l_customer_email,
6363        	      	              x_customer_id   => g_customer_id);
6364          END IF;
6365 
6366          IF r_sr_attr.column_name ='INSTANCE_NUMBER' THEN
6367           --dbms_output.put_line(r_sr_attr.column_name || ' proessing ');
6368           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6369           iem_logger(l_logmessage);
6370 	   getCustomerNumber (p_instance_number => l_instance_number,
6371        	      	              x_customer_id   => g_customer_id);
6372          END IF;
6373 
6374          IF r_sr_attr.column_name ='INSTANCE_SERIAL_NUMBER' THEN
6375           --dbms_output.put_line(r_sr_attr.column_name || ' proessing ');
6376           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6377           iem_logger(l_logmessage);
6378 	   getCustomerNumber (p_instance_serial_number => l_instance_serial_number,
6379        	      	              x_customer_id   => g_customer_id);
6380          END IF;
6381 
6382          IF r_sr_attr.column_name ='INCIDENT_SITE_NUMBER' THEN
6383           --dbms_output.put_line(r_sr_attr.column_name || ' proessing ');
6384           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6385           iem_logger(l_logmessage);
6386 	   getCustomerNumber (p_incident_site_number => l_incident_site_number,
6387        	      	              x_customer_id   => g_customer_id);
6388          END IF;
6389 
6390          IF r_sr_attr.column_name ='CONTACT_NUMBER' THEN
6391           --dbms_output.put_line(r_sr_attr.column_name || ' proessing ');
6392           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6393           iem_logger(l_logmessage);
6394 	   getCustomerNumber (p_contact_number => l_contact_number,
6395        	      	              x_customer_id   => g_customer_id);
6396          END IF;
6397 
6398          IF r_sr_attr.column_name ='CONTACT_NAME' THEN
6399           --dbms_output.put_line(r_sr_attr.column_name || ' proessing ');
6400 
6401           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6402           iem_logger(l_logmessage);
6403 	   getCustomerNumber (p_contact_name => l_contact_name,
6404        	      	              x_customer_id   => g_customer_id);
6405          END IF;
6406 
6407          IF r_sr_attr.column_name ='CONTACT_PHONE' THEN
6408           --dbms_output.put_line(r_sr_attr.column_name || ' proessing ');
6409           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6410           iem_logger(l_logmessage);
6411 	   getCustomerNumber (p_contact_phone => l_contact_phone,
6412        	      	              x_customer_id   => g_customer_id);
6413          END IF;
6414 
6415          IF r_sr_attr.column_name ='CONTACT_EMAIL' THEN
6416           --dbms_output.put_line(r_sr_attr.column_name || ' proessing ');
6417           l_logmessage:=r_sr_attr.column_name || ' proessing ';
6418           iem_logger(l_logmessage);
6419 	   getCustomerNumber (p_contact_email => l_contact_email,
6420        	      	              x_customer_id   => g_customer_id);
6421          END IF;
6422 
6423          --exit out of the loop if g_customer_id has been found
6424          --dbms_output.put_line(' G_CUSTOMER_ID in the loop is ' || g_customer_id);
6425          l_logmessage:=' G_CUSTOMER_ID in the loop is ' || g_customer_id;
6426           iem_logger(l_logmessage);
6427          EXIT WHEN g_customer_id IS NOT NULL;
6428 
6429        END LOOP;
6430 
6431          l_logmessage:=' sanity check no customer_id found exited loop';
6432          iem_logger(l_logmessage);
6433          --dbms_output.put_line(l_logmessage);
6434 
6435        --if after going throug the loop to find g_Customer_id was
6436        --not found then we should give it the default customer_id which got passed
6437        --we should exit this program if there is not defulat_Customer_id
6438        --IF (g_customer_id IS NULL) AND (p_default_customer_id >0) THEN
6439         --issue this i
6440        IF (g_customer_id IS NULL) THEN
6441            g_customer_id := p_default_customer_id;
6442        ELSIF ((g_customer_id is NULL) AND (p_default_customer_id IS NULL)) THEN
6443              --exit out of the program and dont do anything
6444            --dbms_output.put_line('Exiting plsql procedure no customer_id found');
6445            l_logmessage:=' Exiting plsql procedure no customer_id found';
6446           iem_logger(l_logmessage);
6447            x_return_status:= 'E';
6448            x_msg_count:= 1;
6449            x_msg_data:= 'Exiting out of the procedure because no customer_id found';
6450 
6451             --dbms_output.put_line(x_msg_data);
6452           --return statement will exit out of the procedure
6453            RETURN;
6454        END IF;
6455     END IF; --end of weather g_cutomer_id existance check
6456    END IF; --end of customer_type check
6457        l_logmessage:=' sanity check 2 g_customer_id is :'|| g_customer_id;
6458        iem_logger(l_logmessage);
6459       --dbms_output.put_line(l_logmessage);
6460 
6461     --once we have found the customer_id information we will use the same cursor
6462     --to find additinal information
6463       --Question: Should we even do the processing for all the attributes if we were not
6464       --able to find a customer_id and if are using the default customer_id ..
6465       -- so bascially should we check over here if g_customer_id <> p_default_customer_id
6466       --then only do this processing other wise why even bother with these processing with the
6467       --default customer_id.
6468     FOR r_sr_cust_attr IN c_customer_attributes(p_parser_id)
6469     LOOP
6470          IF ((r_sr_cust_attr.column_name ='ACCOUNT_NUMBER') AND (l_account_number IS NOT NULL)) THEN
6471            --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6472            l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6473           iem_logger(l_logmessage);
6474             getAccountNumber (p_account_number => l_account_number,
6475                                x_cust_account_id => l_cust_account_id);
6476          END IF;
6477 
6478          IF ((r_sr_cust_attr.column_name ='CUSTOMER_PHONE') AND (l_customer_phone IS NOT NULL)) THEN
6479            --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6480            l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6481           iem_logger(l_logmessage);
6482 	   getCustomerPhone (p_customer_phone => l_customer_phone,
6483        	      	              x_customer_phone_id   => l_customer_phone_id);
6484          END IF;
6485 
6486          IF ((r_sr_cust_attr.column_name ='CUSTOMER_EMAIL') AND (l_customer_email IS NOT NULL)) THEN
6487            --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6488            l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6489           iem_logger(l_logmessage);
6490 	   getCustomerEmail (p_customer_email => l_customer_email,
6491        	      	             x_customer_email_id   => l_customer_email_id);
6492          END IF;
6493 
6494          --putting in additional condition because if we have already found thesse values
6495          --that means we should honor those values and should not find them again as they
6496          --have been found with attributes that had a higer rank
6497          IF ((r_sr_cust_attr.column_name ='INSTANCE_NUMBER') AND (l_customer_product_id IS NULL)
6498               AND (l_inventory_item_id IS NULL) AND (l_instance_number IS NOT NULL))
6499          THEN
6500            --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6501            l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6502           iem_logger(l_logmessage);
6503            getInstanceNumber (p_instance_number     => l_instance_number,
6504                               p_cust_account_id     => l_cust_account_id,
6505                               x_customer_product_id => l_customer_product_id,
6506                               x_inventory_org_id => l_inventory_org_id,
6507                               x_inventory_item_id   => l_inventory_item_id);
6508          END IF;
6509 
6510          IF ((r_sr_cust_attr.column_name ='INSTANCE_SERIAL_NUMBER') AND (l_customer_product_id IS NULL)
6511               AND (l_inventory_item_id IS NULL) AND (l_instance_serial_number IS NOT NULL))
6512          THEN
6513            --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6514            l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6515           iem_logger(l_logmessage);
6516            getInstanceSerialNumber
6517                              (p_instance_serial_number     => l_instance_serial_number,
6518                               p_cust_account_id            => l_cust_account_id,
6519                               x_customer_product_id        => l_customer_product_id,
6520                               x_inventory_org_id           => l_inventory_org_id,
6521                               x_inventory_item_id          => l_inventory_item_id);
6522          END IF;
6523 
6524          IF ((r_sr_cust_attr.column_name ='INCIDENT_SITE_NUMBER') AND (l_incident_site_number is not null))  THEN
6525            --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6526            l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6527           iem_logger(l_logmessage);
6528 	   getIncidentSiteNumber (p_incident_site_number => l_incident_site_number,
6529        	      	                  x_incident_location_id   => l_incident_location_id);
6530          END IF;
6531 
6532          --all the contact related stuff should be there from customer processing so
6533          --we will pass all the contact related values to its procdure here
6534          --process the contact related information only if
6535          --type is external and g_customer_id not null and g_contact_party_id is null or g_contact_
6536          IF ((g_contact_party_id IS NULL) AND (g_customer_id IS NOT NULL)
6537              AND (r_sr_cust_attr.column_name ='CONTACT_NUMBER') AND (l_contact_number IS NOT NULL))
6538          THEN
6539            --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6540            l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6541            iem_logger(l_logmessage);
6542              getContactNumber (p_contact_number => l_contact_number,
6543                               p_parser_id       => p_parser_id ,
6544                               p_contact_phone   => l_contact_phone,
6545                               p_contact_email  => l_contact_email,
6546                               x_contact_party_id  => g_contact_party_id,
6547                               x_contact_type      => g_contact_party_type,
6548                               x_contact_point_type  => g_contact_point_type,
6549                               x_contact_point_id  => g_contact_point_id);
6550 
6551          END IF;
6552 
6553          IF ((g_contact_party_id IS NULL) AND (g_customer_id IS NOT NULL)
6554              AND (r_sr_cust_attr.column_name ='CONTACT_NAME') AND (l_contact_name IS NOT NULL))
6555          THEN
6556             --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6557             l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6558             iem_logger(l_logmessage);
6559                 l_logmessage:='before contact_name-call'||l_contact_name||'--partyid:'||g_contact_party_id||'point_id:'||g_contact_point_id ;
6560                 iem_logger(l_logmessage);
6561                 --dbms_output.put_line(l_logmessage);
6562             getContactName (p_contact_name       => l_contact_name,
6563                               p_parser_id        => p_parser_id ,
6564                               p_contact_phone    => l_contact_phone,
6565                               p_contact_email   => l_contact_email,
6566                               x_contact_party_id  => g_contact_party_id,
6567                               x_contact_type      => g_contact_party_type,
6568                               x_contact_point_type  => g_contact_point_type,
6569                               x_contact_point_id  => g_contact_point_id);
6570 
6571                 l_logmessage:='after contact_name-call'||l_contact_name||'--partyid:'||g_contact_party_id||'point_id'||g_contact_point_id ;
6572                 iem_logger(l_logmessage);
6573                 --dbms_output.put_line(l_logmessage);
6574          END IF;
6575 
6576          IF ((g_contact_party_id IS NULL) AND (g_customer_id IS NOT NULL)
6577              AND (r_sr_cust_attr.column_name ='CONTACT_PHONE') AND (l_contact_phone IS NOT NULL))
6578          THEN
6579            --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6580             l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6581           iem_logger(l_logmessage);
6582             getContactPhone (p_contact_phone   => l_contact_phone,
6583                               x_contact_party_id  => g_contact_party_id,
6584                               x_contact_type      => g_contact_party_type,
6585                               x_contact_point_type  => g_contact_point_type,
6586                               x_contact_point_id  => g_contact_point_id);
6587 
6588          END IF;
6589 
6590          IF ((g_contact_party_id IS NULL) AND (g_customer_id IS NOT NULL)
6591              AND (r_sr_cust_attr.column_name ='CONTACT_EMAIL') AND (l_contact_email IS NOT NULL))
6592          THEN
6593            --dbms_output.put_line('Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop');
6594             l_logmessage:=' Detailed '||r_sr_cust_attr.column_name || ' processing - 2nloop' ;
6595           iem_logger(l_logmessage);
6596            --dbms_output.put_line('contact_email is: '||l_contact_email);
6597             getContactEmail (p_contact_email   => l_contact_email,
6598                               x_contact_party_id  => g_contact_party_id,
6599                               x_contact_type      => g_contact_party_type,
6600                               x_contact_point_type  => g_contact_point_type,
6601                               x_contact_point_id  => g_contact_point_id);
6602 
6603          END IF;
6604 
6605     END LOOP;
6606          l_logmessage:= 'out of contact loop' ;
6607           iem_logger(l_logmessage);
6608         --dbms_output.put_line (l_logmessage);
6609 
6610 
6611      --added for bug  11834089
6612      -- At this point all customer and contact processing has finshed and if there is
6613      -- no contact_id at this point then it is a safe bet to go with the default
6614      -- contact id. This is not the most efficient solution but trivial when comes to processing time.
6615 
6616      --if we not able to find a customer based on the information in the email
6617      -- and there is nothing in the email body for contact processing then we should
6618      -- go with the default customer which has been taken care of by now
6619      -- and the default contact information that got passed
6620      if (g_customer_id = p_default_customer_id) AND (g_contact_party_id IS NULL) THEN
6621 
6622        BEGIN
6623          l_logmessage:= 'assigning default contact info because no contact information found' ;
6624           iem_logger(l_logmessage);
6625         --dbms_output.put_line (l_logmessage);
6626 
6627             g_contact_party_id := p_contact_id;
6628             g_contact_point_id := p_contact_point_id;
6629             g_contact_point_type := 'EMAIL';
6630 
6631            select party_type into g_contact_party_type
6632            from hz_parties
6633            where party_id = p_contact_id
6634            and rownum = 1;
6635        EXCEPTION
6636              when TOO_MANY_ROWS then
6637                 l_logmessage:='default contact info creation  too many rows'|| SQL%ROWCOUNT;
6638                 iem_logger(l_logmessage);
6639                 --dbms_output.put_line(l_logmessage);
6640                 l_cust_account_id := null;
6641              when NO_DATA_FOUND then
6642                 l_logmessage:='default contact info  returned 0 rows'|| SQL%ROWCOUNT;
6643                 iem_logger(l_logmessage);
6644                 --dbms_output.put_line(l_logmessage);
6645              when others then
6646                l_logmessage:='default contact info other exception'|| SQLCODE||'-ERROR- '||SQLERRM ;
6647                iem_logger(l_logmessage);
6648                --dbms_output.put_line(l_logmessage);
6649        END;
6650 
6651      END IF;
6652 
6653      --end of bug fix for 11834089
6654 
6655 
6656 
6657 
6658          l_logmessage:= 'processing other attributes' ;
6659           iem_logger(l_logmessage);
6660         --dbms_output.put_line (l_logmessage);
6661 
6662     --process all the other attributes
6663     FOR r_sr_other_attr IN c_other_attributes(p_parser_id)
6664     LOOP
6665        IF (r_sr_other_attr.column_name = 'INVENTORY_ITEM_NAME') THEN
6666            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6667            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6668           iem_logger(l_logmessage);
6669            l_tag_data:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6670             if l_tag_data IS NOT NULL THEN
6671               getInventoryItemName (p_inventory_item_name => l_tag_data,
6672                                     x_inventory_item_id   => l_inventory_item_id,
6673                                     x_inventory_org_id    => l_inventory_org_id);
6674              --set the tag_data to null for next processing
6675             END IF;
6676              l_tag_data := null;
6677        END IF;
6678 
6679        IF (r_sr_other_attr.column_name = 'SERVICE_REQUEST_TYPE') THEN
6680            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6681            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6682           iem_logger(l_logmessage);
6683            l_tag_data:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6684            if l_tag_data IS NOT NULL THEN
6685              getServiceRequestType (p_service_request_type => l_tag_data,
6686                                     p_default_type_id     => p_default_type_id,
6687 	                            x_type_id             => l_type_id);
6688            --set the tag_data to null for next processing
6689            END IF;
6690             l_tag_data := null;
6691 
6692        END IF;
6693 
6694        IF (r_sr_other_attr.column_name = 'PROBLEM_CODE') THEN
6695            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6696            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6697           iem_logger(l_logmessage);
6698            l_tag_data:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6699            if l_tag_data IS NOT NULL THEN
6700              getProblemCode (p_problem_code => l_tag_data,
6701                              x_problem_code => l_problem_code);
6702             --set the tag_data to null for next processing
6703            END IF;
6704             l_tag_data := null;
6705        END IF;
6706 
6707        IF (r_sr_other_attr.column_name = 'URGENCY') THEN
6708            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6709            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6710           iem_logger(l_logmessage);
6711            l_tag_data:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6712             getUrgency (p_urgency => l_tag_data,
6713                         x_urgency_id => l_urgency_id);
6714            --set the tag_data to null for next processing
6715            l_tag_data := null;
6716        END IF;
6717 
6718        IF (r_sr_other_attr.column_name = 'SITE_NAME') THEN
6719            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6720            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6721           iem_logger(l_logmessage);
6722            l_tag_data := get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6723             getSiteName(p_site_name    => l_tag_data,
6724                         x_party_site_id  => l_party_site_id);
6725           --set the tag_data to null for next processing
6726            l_tag_data := null;
6727        END IF;
6728 
6729        IF (r_sr_other_attr.column_name = 'EXTERNAL_REFERENCE') THEN
6730            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6731            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6732           iem_logger(l_logmessage);
6733            l_tag_data := get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6734            --we should have found l_customer_id from the customer related processing already
6735            --if the l_customer_id does not exist then there is no point calling the sub procedure
6736            IF l_customer_product_id is not null THEN
6737             getExtReference(p_ext_ref => l_tag_data,
6738                             p_customer_product_id => l_customer_product_id,
6739                             x_ext_ref          => l_ext_ref);
6740            END IF;
6741           --set the tag_data to null for next processing
6742            l_tag_data := null;
6743        END IF;
6744 
6745        IF (r_sr_other_attr.column_name = 'ADDRESSEE') THEN
6746            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6747            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6748           iem_logger(l_logmessage);
6749            l_addressee:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6750        END IF;
6751        IF (r_sr_other_attr.column_name = 'INCIDENT_ADDRESS1') THEN
6752            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6753            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6754           iem_logger(l_logmessage);
6755            l_incident_address1:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6756        END IF;
6757        IF (r_sr_other_attr.column_name = 'INCIDENT_ADDRESS2') THEN
6758            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6759            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6760           iem_logger(l_logmessage);
6761            l_incident_address2:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6762        END IF;
6763        IF (r_sr_other_attr.column_name = 'INCIDENT_ADDRESS3') THEN
6764            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6765            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6766           iem_logger(l_logmessage);
6767            l_incident_address3:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6768        END IF;
6769        IF (r_sr_other_attr.column_name = 'INCIDENT_ADDRESS4') THEN
6770            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6771            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6772           iem_logger(l_logmessage);
6773            l_incident_address4:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6774        END IF;
6775        IF (r_sr_other_attr.column_name = 'INCIDENT_CITY') THEN
6776            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6777            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6778           iem_logger(l_logmessage);
6779            l_incident_city:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6780        END IF;
6781        IF (r_sr_other_attr.column_name = 'INCIDENT_COUNTRY') THEN
6782            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6783            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6784           iem_logger(l_logmessage);
6785            l_incident_country:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6786        END IF;
6787        IF (r_sr_other_attr.column_name = 'INCIDENT_COUNTY') THEN
6788            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6789            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6790           iem_logger(l_logmessage);
6791            l_incident_county:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6792        END IF;
6793        IF (r_sr_other_attr.column_name = 'INCIDENT_POSTAL_CODE') THEN
6794            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6795            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6796           iem_logger(l_logmessage);
6797            l_incident_postal_code:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6798        END IF;
6799        IF (r_sr_other_attr.column_name = 'INCIDENT_PROVINCE') THEN
6800            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6801            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6802           iem_logger(l_logmessage);
6803            l_incident_province:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6804        END IF;
6805        IF (r_sr_other_attr.column_name = 'INCIDENT_STATE') THEN
6806            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6807            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6808           iem_logger(l_logmessage);
6809            l_incident_state:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6810        END IF;
6811        IF (r_sr_other_attr.column_name = 'SERIAL_NUMBER') THEN
6812            --dbms_output.put_line(r_sr_other_attr.column_name || ' processing - other Attributes' );
6813            l_logmessage:= r_sr_other_attr.column_name || ' processing - other Attributes' ;
6814           iem_logger(l_logmessage);
6815            l_serial_number:= get_tag_data (r_sr_other_attr.start_tag, r_sr_other_attr.end_tag, p_message_id);
6816        END IF;
6817 
6818     END LOOP;
6819 
6820          l_logmessage:= 'out of processing other attributes loop' ;
6821           iem_logger(l_logmessage);
6822         --dbms_output.put_line (l_logmessage);
6823       -- create the srevice record with the returned values
6824       --create_sr start
6825       -- Initialize message list if p_init_msg_list is set to TRUE.
6826       -- Standard Start of API savepoint
6827     BEGIN
6828        SAVEPOINT  ADVANCED_CREATE_SR;
6829 
6830     -- Standard call to check for call compatibility.
6831   /*
6832       IF NOT FND_API.Compatible_API_Call (l_api_version_number,
6833           1.0,
6834           l_api_name,
6835           G_PKG_NAME)
6836      THEN
6837         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6838       END IF;
6839   */
6840 
6841     l_logmessage:='Came to create SR  ' ;
6842           iem_logger(l_logmessage);
6843     --dbms_output.put_line(l_logmessage);
6844 
6845   -- Initialize message list if p_init_msg_list is set to TRUE.
6846     IF FND_API.to_Boolean( p_init_msg_list )
6847     THEN
6848       FND_MSG_PUB.initialize;
6849     END IF;
6850 
6851      FND_PROFILE.Get('IEM_SR_SUM_PREFIX', l_summary_prefix);
6852      l_summary :=  l_summary_prefix||' : '|| p_subject ;
6853 
6854         l_logmessage:='customer _id is '|| g_customer_id ;
6855           iem_logger(l_logmessage);
6856         --dbms_output.put_line(l_logmessage);
6857        CS_ServiceRequest_PUB.initialize_rec(l_service_request_rec);
6858 
6859 
6860   OPEN caller_type;
6861   FETCH caller_type INTO l_party_type;
6862 
6863   IF (caller_type%NOTFOUND) THEN
6864           l_logmessage:='caller type fail for customer_id '|| g_customer_id ;
6865           iem_logger(l_logmessage);
6866     --dbms_output.put_line(l_logmessage);
6867     x_return_status := FND_API.G_RET_STS_ERROR;
6868     CLOSE caller_type;
6869   END IF;
6870 
6871   CLOSE caller_type;
6872 
6873     -- sr can not be created without the sr_type_id if it did not go throught
6874     --any processing then just use what was passed in from via the calling program
6875      if l_type_id IS NULL THEN
6876         l_type_id := p_default_type_id;
6877      END IF;
6878 
6879     --siahmed changes made on jul30, 2009
6880     --change in the scenario to find account_id. If the customer g_customer_id has been found then we
6881     --try to find the account_id using the customer_id
6882        l_logmessage:='starting p_account_id fetch before sr creation';
6883        iem_logger(l_logmessage);
6884        --dbms_output.put_line(l_logmessage);
6885 
6886     IF (l_cust_account_id is NULL  AND g_customer_id is NOT NULL) THEN
6887        l_logmessage:='inside p_account_id fetch before sr creation';
6888        iem_logger(l_logmessage);
6889        --dbms_output.put_line(l_logmessage);
6890        BEGIN
6891 	     select cust_account_id into l_cust_account_id
6892 	     from hz_cust_accounts
6893 	     where party_id =g_customer_id;
6894        EXCEPTION
6895              when TOO_MANY_ROWS then
6896                 l_logmessage:='p_account_id fetch before sr creation  too many rows'|| SQL%ROWCOUNT;
6897                 iem_logger(l_logmessage);
6898                 --dbms_output.put_line(l_logmessage);
6899                 l_cust_account_id := null;
6900              when NO_DATA_FOUND then
6901                 l_logmessage:='p_account_id fetch before sr creation returned 0 rows'|| SQL%ROWCOUNT;
6902                 iem_logger(l_logmessage);
6903                 --dbms_output.put_line(l_logmessage);
6904              when others then
6905                l_logmessage:='p_account_id fetch  other exception'|| SQLCODE||'-ERROR- '||SQLERRM ;
6906                iem_logger(l_logmessage);
6907                --dbms_output.put_line(l_logmessage);
6908       END;
6909     END IF;
6910 
6911 
6912     l_logmessage:='p_account_id or l_cust_account_id or account_id :'|| l_cust_account_id ;
6913     iem_logger(l_logmessage);
6914     --dbms_output.put_line(l_logmessage);
6915 
6916 
6917     l_logmessage:='party type   '|| l_party_type ;
6918     iem_logger(l_logmessage);
6919     --dbms_output.put_line(l_logmessage);
6920 
6921     l_logmessage:='sr type_id   '|| l_type_id ;
6922     iem_logger(l_logmessage);
6923     --dbms_output.put_line(l_logmessage);
6924 
6925     l_logmessage:='add1:'|| l_incident_address1 ||'address2:'||l_incident_address2||'add3:'||l_incident_address3||'add4:'||l_incident_address4 ;
6926     iem_logger(l_logmessage);
6927     --dbms_output.put_line(l_logmessage);
6928 
6929     l_logmessage:='city:'|| l_incident_city ||'country:'||l_incident_country||'county:'||l_incident_county||'post:'||l_incident_postal_code ;
6930     iem_logger(l_logmessage);
6931     --dbms_output.put_line(l_logmessage);
6932 
6933       l_service_request_rec.caller_type  := l_party_type; -- 'ORGANIZATION'/'PERSON';
6934      --needed attributes
6935        --get the  severity id from profile; if its null then default to 4
6936        l_service_request_rec.severity_id                := nvl(TO_NUMBER(FND_PROFILE.VALUE('CS_DEFAULT_WEB_INC_SEVERITY')),4);
6937        --l_service_request_rec.severity_id                := 4;
6938        --l_service_request_rec.status_id                  := 1;
6939 
6940        l_service_request_rec.type_id                  := l_type_id;
6941        l_service_request_rec.summary                  := l_summary;
6942        l_service_request_rec.customer_id              := g_customer_id;
6943        l_service_request_rec.sr_creation_channel      := 'EMAIL';
6944        l_service_request_rec.creation_program_code    := 'EMAILCENTER';
6945 
6946        l_service_request_rec.urgency_id               :=  l_urgency_id;
6947        --l_service_request_rec.caller_type := p_service_request_rec.caller_type;
6948        l_service_request_rec.customer_product_id       := l_customer_product_id;
6949        l_service_request_rec.inventory_item_id         := l_inventory_item_id ;
6950        l_service_request_rec.inventory_org_id          := l_inventory_org_id ;
6951 
6952       -- added for bug 12619947 by siahmed
6953       -- to add inv_category_id if there is a single hit
6954 
6955       IF l_inventory_item_id IS NOT NULL THEN
6956        BEGIN
6957 
6958            SELECT distinct --c.concatenated_segments,
6959                 --cs.category_set_name,
6960                 --cs.description cat_set_description,
6961                 --t.description cat_description,
6962                 c.category_id  into l_category_Id
6963                -- ic.category_set_id  --Category_Set_Id
6964            FROM mtl_category_set_valid_cats ic,
6965            mtl_categories_kfv c,
6966            mtl_category_sets_vl cs,
6967              mtl_item_categories itc,
6968            mtl_categories_tl t
6969            WHERE ic.category_id = c.category_id
6970            AND t.category_id (+) = c.category_id
6971            AND t.language (+) = userenv('LANG')
6972            AND ic.category_set_id = cs.category_set_id
6973            AND ic.category_set_id =  fnd_profile.value('CS_SR_DEFAULT_CATEGORY_SET')
6974            AND itc.inventory_item_id = l_inventory_item_id
6975            AND itc.category_id = c.category_id
6976            AND itc.category_set_id = ic.category_set_id
6977            AND itc.organization_id = cs_std.Get_Item_Valdn_Orgzn_Id
6978            AND sysdate <= NVL(c.disable_date,sysdate);
6979 
6980 
6981        l_logmessage:=' inventory_item_id is '|| l_inventory_item_id;
6982        iem_logger(l_logmessage);
6983        --dbms_output.put_line(l_logmessage);
6984      EXCEPTION
6985          when TOO_MANY_ROWS then
6986               l_category_id := null;
6987               l_logmessage:='CategoryID fetch returned too many rows'|| SQL%ROWCOUNT;
6988               iem_logger(l_logmessage);
6989               --dbms_output.put_line(l_logmessage);
6990          when NO_DATA_FOUND then
6991               l_category_id := null;
6992               l_logmessage:='CategoryID fetch returned 0 rows'|| SQL%ROWCOUNT;
6993               iem_logger(l_logmessage);
6994             --dbms_output.put_line(l_logmessage);
6995          when others then
6996               l_category_id := null;
6997               l_logmessage:='CategoryID other exception';
6998               iem_logger(l_logmessage);
6999                 --dbms_output.put_line(l_logmessage);
7000      END;
7001 
7002      END IF;
7003 
7004       If l_category_id IS NOT NULL THEN
7005        l_service_request_rec.category_set_id :=  fnd_profile.value('CS_SR_DEFAULT_CATEGORY_SET');
7006        l_service_request_rec.category_id              := l_category_id;
7007 
7008       END IF;
7009 
7010       --end of addition
7011 
7012        l_service_request_rec.problem_code              := l_problem_code;
7013        l_service_request_rec.account_id                := l_cust_account_id;
7014        l_service_request_rec.incident_location_id      := l_incident_location_id;
7015        l_service_request_rec.site_id                   := l_party_site_id;
7016        l_service_request_rec.customer_phone_id        := l_customer_phone_id;
7017        l_service_request_rec.customer_email_id        := l_customer_email_id;
7018        l_service_request_rec.external_reference        := l_ext_ref;
7019        --l_service_request_rec.addressee                 := l_addressee;
7020        l_service_request_rec.incident_Address          := l_incident_address1;
7021        l_service_request_rec.incident_Address2         := l_incident_address2;
7022        l_service_request_rec.incident_Address3         := l_incident_address3;
7023        l_service_request_rec.incident_Address4         := l_incident_address4;
7024        l_service_request_rec.incident_city              := l_incident_city;
7025        l_service_request_rec.incident_country           := l_incident_country ;
7026        l_service_request_rec.incident_county            := l_incident_county    ;
7027        l_service_request_rec.incident_postal_code       := l_incident_postal_code;
7028        l_service_request_rec.incident_province         := l_incident_province    ;
7029        l_service_request_rec.incident_state             :=l_incident_state       ;
7030        l_service_request_rec.current_serial_number      := l_serial_number;
7031 
7032 
7033         l_index := 1;
7034         l_notes(l_index).NOTE                       := p_note ;
7035         l_notes(l_index).NOTE_TYPE                  := p_NOTE_TYPE;
7036       	--Fix for bug 12680622
7037         --lakshmi fix comment  by siahmed
7038 	      l_notes(l_index).NOTE_DETAIL                := NULL;
7039 
7040      If g_contact_party_id IS NOT NULL THEN
7041       --contact stuff
7042 
7043         l_logmessage:='contact party id :' ||g_contact_party_id ;
7044           iem_logger(l_logmessage);
7045     --dbms_output.put_line(l_logmessage);
7046         l_logmessage:='contact point id  :'|| g_contact_point_id ;
7047           iem_logger(l_logmessage);
7048     --dbms_output.put_line(l_logmessage);
7049         l_logmessage:='contact party_type  :'|| g_contact_party_type ;
7050           iem_logger(l_logmessage);
7051     --dbms_output.put_line(l_logmessage);
7052         l_logmessage:='contact point_type  :'|| g_contact_point_type ;
7053           iem_logger(l_logmessage);
7054     --dbms_output.put_line(l_logmessage);
7055         l_logmessage:='contact party role code  :'|| g_party_role_code ;
7056           iem_logger(l_logmessage);
7057     --dbms_output.put_line(l_logmessage);
7058       l_index := 1;
7059         l_contacts(l_index).PARTY_ID                   := g_contact_party_id;
7060         l_contacts(l_index).contact_point_id           := g_contact_point_id;
7061         l_contacts(l_index).contact_point_type         := g_contact_point_type;
7062         l_contacts(l_index).CONTACT_TYPE               := g_contact_party_type;
7063         l_contacts(l_index).party_role_code            := g_party_role_code;
7064         l_contacts(l_index).primary_flag            := 'Y';
7065 
7066      END IF;
7067 
7068         --added for bug 12663292
7069          getBillToShipTo(   p_customer_id      => g_customer_id,
7070                             p_contact_party_id => g_contact_party_id,
7071                             x_bill_to_site_id  => l_bill_to_site_id,
7072                             x_ship_to_site_id  => l_ship_to_site_id,
7073                             x_account_id       => l_billship_account);
7074 
7075         l_logmessage:='bill_to_site_id call finish' ;
7076           iem_logger(l_logmessage);
7077           --dbms_output.put_line(l_logmessage);
7078         l_logmessage:='bill_to_site_id is '|| l_bill_to_site_id ;
7079           iem_logger(l_logmessage);
7080           --dbms_output.put_line(l_logmessage);
7081         l_logmessage:='ship_to_site_id is '|| l_ship_to_site_id ;
7082           iem_logger(l_logmessage);
7083           --dbms_output.put_line(l_logmessage);
7084         l_logmessage:='ship_ship_account_id is '|| l_billship_account ;
7085           iem_logger(l_logmessage);
7086           --dbms_output.put_line(l_logmessage);
7087         --bill to stuff
7088 
7089       IF l_bill_to_site_id IS NOT NULL THEN
7090        l_service_request_rec.bill_to_party_id      :=g_customer_id;
7091        --l_service_request_rec.bill_to_contact_id    :=g_contact_party_id;
7092        l_service_request_rec.bill_to_site_id       :=l_bill_to_site_id;
7093       END IF;
7094          --ship to stuff
7095       IF l_ship_to_site_id IS NOT NULL THEN
7096        l_service_request_rec.ship_to_party_id      :=g_customer_id;
7097        --l_service_request_rec.ship_to_contact_id    :=g_contact_party_id;
7098        l_service_request_rec.ship_to_site_id       :=l_bill_to_site_id;
7099 
7100       END IF;
7101 
7102       --they are the same
7103       IF l_billship_account IS NOT NULL THEN
7104        l_service_request_rec.bill_to_account_id       :=l_billship_account;
7105        l_service_request_rec.ship_to_account_id       :=l_billship_account;
7106       END IF;
7107         --end of bug 12663292
7108 
7109        l_auto_assign := fnd_profile.value('CS_AUTO_ASSIGN_OWNER_HTML');
7110        l_coverage_template_id:=fnd_profile.value_specific('CS_SR_DEFAULT_COVERAGE');
7111 
7112         l_logmessage:='start calling service request' ;
7113           iem_logger(l_logmessage);
7114     --dbms_output.put_line(l_logmessage);
7115       CS_ServiceRequest_PUB.Create_ServiceRequest (
7116                   p_api_version           => l_cs_version_number,
7117                   p_init_msg_list         => FND_API.G_FALSE,
7118                   p_commit	          => FND_API.G_FALSE,
7119                   x_return_status         => l_return_status,
7120                   x_msg_count             => l_msg_count,
7121                   x_msg_data              => l_msg_data,
7122                   p_resp_appl_id	  => NULL,
7123                   p_resp_id		  => NULL,
7124                   p_user_id		  => nvl(TO_NUMBER (FND_PROFILE.VALUE('USER_ID')),-1),
7125                   --p_user_id		  => 1318,
7126                   p_login_id		  => NULL,
7127                   p_org_id		  => NULL,
7128                   p_request_id            => NULL,
7129                   p_request_number	  => NULL,
7130                   p_service_request_rec   => l_service_request_rec,
7131                   p_notes                 => l_notes,
7132                   p_contacts              => l_contacts,
7133                   p_auto_assign           => l_auto_assign,
7134                   p_auto_generate_tasks		  => 'N',
7135                   x_sr_create_out_rec	  	  => l_sr_create_out_rec,
7136                   -- added by siahmed for fixing the bug 8251673
7137                   p_default_contract_sla_ind	  => 'Y',
7138                   p_default_coverage_template_id  => l_coverage_template_id
7139                   --end of addition by siahmed for fixing the bug 8251673
7140                   );
7141 
7142      if (l_return_status <> FND_API.G_RET_STS_SUCCESS) then
7143         l_logmessage:='raise IEM_SR_NOT_CREATE ' ;
7144           iem_logger(l_logmessage);
7145           --dbms_output.put_line(l_logmessage);
7146         raise IEM_SR_NOT_CREATE;
7147      --end if;
7148      ELSIF  (l_return_status = FND_API.G_RET_STS_SUCCESS) THEN
7149         IF (FND_MSG_PUB.Count_Msg > 1) THEN
7150          --Display all the warning messages
7151          FOR j in  1..FND_MSG_PUB.Count_Msg LOOP
7152             FND_MSG_PUB.Get(
7153                p_msg_index     => j,
7154                p_encoded       => 'F',
7155                p_data          => lx_msg_data,
7156                p_msg_index_out => lx_msg_index_out);
7157 
7158               l_logmessage:= 'MESSAGE INDEX3 = ' || lx_msg_index_out;
7159               iem_logger(l_logmessage);
7160               --dbms_output.put_line(l_logmessage);
7161 
7162               l_logmessage:='MESSAGE3 = ' || substr(lx_msg_data ,1,150) ;
7163               iem_logger(l_logmessage);
7164               --dbms_output.put_line(l_logmessage);
7165          END LOOP;
7166        ELSE
7167          --Only one warning
7168          FND_MSG_PUB.Get(
7169             p_msg_index     => 1,
7170             p_encoded       => 'F',
7171             p_data          => lx_msg_data,
7172             p_msg_index_out => lx_msg_index_out);
7173 
7174           l_logmessage:= 'MESSAGE INDEX4 = ' || lx_msg_index_out;
7175           iem_logger(l_logmessage);
7176           --dbms_output.put_line(l_logmessage);
7177 
7178           l_logmessage:='MESSAGE4 = ' || substr(lx_msg_data,1,200);
7179           iem_logger(l_logmessage);
7180           --dbms_output.put_line(l_logmessage);
7181 
7182           l_logmessage:='MESSAGE4 = ' || substr(lx_msg_data,201);
7183           iem_logger(l_logmessage);
7184           --dbms_output.put_line(l_logmessage);
7185 
7186         END IF;
7187     END IF;
7188 
7189      l_logmessage:='INSERTED REQUEST ID  : ' || l_sr_create_out_rec.request_id ;
7190      iem_logger(l_logmessage);
7191      --dbms_output.put_line(l_logmessage);
7192 
7193      l_logmessage:='INSERTED REQUEST NUM : ' || l_sr_create_out_rec.request_number;
7194      iem_logger(l_logmessage);
7195      --dbms_output.put_line(l_logmessage);
7196 
7197 
7198      l_logmessage:='MESSAGE COUNT = ' || l_msg_count;
7199      iem_logger(l_logmessage);
7200      --dbms_output.put_line(l_logmessage);
7201 
7202 
7203      x_return_status := l_return_status ;
7204      x_request_id     := l_sr_create_out_rec.request_id;
7205 
7206    --Standard check of p_commit
7207     IF FND_API.to_Boolean(p_commit) THEN
7208         COMMIT WORK;
7209     END IF;
7210 
7211    EXCEPTION
7212       WHEN IEM_SR_NOT_CREATE THEN
7213           ROLLBACK TO ADVANCED_CREATE_SR;
7214           x_return_status := l_return_status ;
7215           FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
7216 
7217            FOR j in  1..FND_MSG_PUB.Count_Msg LOOP
7218 
7219             FND_MSG_PUB.Get(
7220                p_msg_index     => j,
7221                p_encoded       => 'F',
7222                p_data          => lx_msg_data,
7223                p_msg_index_out => lx_msg_index_out);
7224 
7225             l_logmessage:='-----------ERROR-----------';
7226            iem_logger(l_logmessage);
7227            --dbms_output.put_line(l_logmessage);
7228 
7229             l_logmessage:='MESSAGE INDEX1 = ' || lx_msg_index_out;
7230            iem_logger(l_logmessage);
7231            --dbms_output.put_line(l_logmessage);
7232             l_logmessage:='MESSAGE1 = ' || substr(lx_msg_data ,1,150) ;
7233             iem_logger(l_logmessage);
7234            --dbms_output.put_line(l_logmessage);
7235 
7236             l_logmessage:='----------END OF ERROR-----------';
7237            iem_logger(l_logmessage);
7238            --dbms_output.put_line(l_logmessage);
7239          END LOOP;
7240 
7241      WHEN FND_API.G_EXC_ERROR THEN
7242     	     ROLLBACK TO ADVANCED_CREATE_SR;
7243            x_return_status := FND_API.G_RET_STS_ERROR ;
7244            FND_MSG_PUB.Count_And_Get
7245     			( p_count => x_msg_count,p_data => x_msg_data);
7246 
7247      WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
7248 	   ROLLBACK TO ADVANCED_CREATE_SR;
7249        x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
7250        FND_MSG_PUB.Count_And_Get ( p_count => x_msg_count,p_data => x_msg_data);
7251 
7252     WHEN OTHERS THEN
7253             ROLLBACK TO ADVANCED_CREATE_SR;
7254             x_return_status := FND_API.G_RET_STS_ERROR;
7255             IF  FND_MSG_PUB.Check_Msg_Level (FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
7256                 FND_MSG_PUB.Add_Exc_Msg( G_PKG_NAME , l_api_name);
7257             END IF;
7258             FND_MSG_PUB.Count_And_Get ( p_count => x_msg_count, p_data => x_msg_data );
7259     END;
7260 
7261   END ADVANCED_SR_PROCESSING;
7262 
7263 
7264   Procedure  getCustomerNumber (
7265                     p_customer_number IN VARCHAR2   DEFAULT NULL,
7266 	            p_customer_name   IN VARCHAR2 DEFAULT NULL,
7267 		    p_account_number  IN VARCHAR2   DEFAULT NULL,
7268 		    p_customer_phone  IN VARCHAR2 DEFAULT NULL,
7269  		    p_customer_email  IN VARCHAR2 DEFAULT NULL,
7270 		    p_instance_number IN VARCHAR2   DEFAULT NULL,
7271 		    p_instance_serial_number IN VARCHAR2 DEFAULT NULL,
7272 		    p_incident_site_number   IN VARCHAR2 DEFAULT NULL,
7273                     --contact related stuff to find customerNumber
7274 		    p_contact_number  IN VARCHAR2 DEFAULT NULL,
7275  		    p_contact_name    IN VARCHAR2 DEFAULT NULL,
7276 		    p_contact_phone   IN VARCHAR2   DEFAULT NULL,
7277 		    p_contact_email   IN VARCHAR2   DEFAULT NULL,
7278 		    x_customer_id   OUT NOCOPY NUMBER)
7279   IS
7280    l_party_count NUMBER;
7281    l_party_type VARCHAR2(100);
7282    l_logmessage		varchar2(2000):=' ';
7283   BEGIN
7284     --this procedure is called to find the customer_id in giving precdence to
7285     -- the attribute defined by the users via the rank system in the definition page
7286     -- if g_customer_id is null then only we will go through different checks
7287     -- and try to find a valid customer_id based on the calling program
7288     --once an g_customer_id has been found this procedure will just come out
7289     --without doing any checks and return the first found g_customer_id
7290     --which is also the customer_id that the customer intended to used based on the
7291     --ranking system put in place.
7292 
7293     IF g_customer_id is NULL THEN
7294 	IF p_customer_number is not null THEN
7295          BEGIN
7296 	   select party_id into x_customer_id
7297            from hz_parties where party_number = p_customer_number;
7298          EXCEPTION
7299            when TOO_MANY_ROWS then
7300               x_customer_id := null;
7301              l_logmessage:='p_customer_number fetch returned too many rows'|| SQL%ROWCOUNT;
7302             iem_logger(l_logmessage);
7303             --dbms_output.put_line(l_logmessage);
7304            when NO_DATA_FOUND then
7305              l_logmessage:='p_customer_number fetch returned 0 rows'|| SQL%ROWCOUNT;
7306             iem_logger(l_logmessage);
7307             --dbms_output.put_line(l_logmessage);
7308            when others then
7309              l_logmessage:='p_customer_number other exception' || SQLCODE||'-ERROR- '||SQLERRM;
7310             iem_logger(l_logmessage);
7311             --dbms_output.put_line(l_logmessage);
7312          END;
7313 
7314         --since this is an exact text match, we will upper the party_name
7315         --to increase the chances of a party_name match.
7316         --it would be nice to have bitmap index on party_name for performance reasons
7317         ELSIF p_customer_name is not null then
7318          BEGIN
7319 	     select party_id into x_customer_id
7320 	     from hz_parties where UPPER(party_name) = UPPER(p_customer_name);
7321          EXCEPTION
7322            when TOO_MANY_ROWS then
7323               x_customer_id := null;
7324              l_logmessage:='p_customer_name fetch returned too many rows'|| SQL%ROWCOUNT;
7325              iem_logger(l_logmessage);
7326              --dbms_output.put_line(l_logmessage);
7327            when NO_DATA_FOUND then
7328              l_logmessage:='p_customer_name fetch returned 0 rows'|| SQL%ROWCOUNT;
7329              iem_logger(l_logmessage);
7330              --dbms_output.put_line(l_logmessage);
7331            when others then
7332              l_logmessage:='p_customer_name other exception '|| SQLCODE||'-ERROR- '||SQLERRM ;
7333              iem_logger(l_logmessage);
7334              --dbms_output.put_line(l_logmessage);
7335          END;
7336 
7337         ELSIF p_account_number is not null then
7338            BEGIN
7339 	     select party_id into x_customer_id
7340 	     from hz_cust_accounts
7341 	     where account_number=p_account_number;
7342            EXCEPTION
7343              when TOO_MANY_ROWS then
7344               x_customer_id := null;
7345                 l_logmessage:='p_account_number fetch returned too many rows'|| SQL%ROWCOUNT;
7346                 iem_logger(l_logmessage);
7347                 --dbms_output.put_line(l_logmessage);
7348              when NO_DATA_FOUND then
7349                 l_logmessage:='p_account_number fetch returned 0 rows'|| SQL%ROWCOUNT;
7350                 iem_logger(l_logmessage);
7351                 --dbms_output.put_line(l_logmessage);
7352              when others then
7353                   l_logmessage:='p_account_number other exception'|| SQLCODE||'-ERROR- '||SQLERRM ;
7354                 iem_logger(l_logmessage);
7355                 --dbms_output.put_line(l_logmessage);
7356            END;
7357 
7358 	ELSIF p_customer_phone is not null then
7359           BEGIN
7360             /*
7361 	    Select owner_table_id into x_customer_id
7362 	    From hz_contact_points
7363 	    where owner_table_name='HZ_PARTIES'
7364 	    and contact_point_type = 'PHONE'
7365 	    and phone_number =p_customer_phone;
7366             */
7367 	    Select owner_table_id into x_customer_id
7368             from hz_contact_points a, hz_parties b
7369             where a.owner_table_name='HZ_PARTIES'
7370             and a.contact_point_type='PHONE'
7371             and a.status='A'
7372             and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
7373     					 	 	  where contact_level_table='HZ_CONTACT_POINTS' and status='A')
7374 	    and a.owner_table_id = b.party_id
7375   	    and b.party_type in ('PERSON', 'ORGANIZATION')
7376             and reverse(a.transposed_phone_number)=REGEXP_REPLACE(p_customer_phone,'([[:punct:]|[:space:]]*)');
7377 
7378           EXCEPTION
7379              when TOO_MANY_ROWS then
7380                 x_customer_id := null;
7381                 l_logmessage:='p_customer_phone fetch returned too many rows'|| SQL%ROWCOUNT;
7382                 iem_logger(l_logmessage);
7383                 --dbms_output.put_line(l_logmessage);
7384              when NO_DATA_FOUND then
7385                 l_logmessage:='p_customer_phone fetch returned 0 rows'|| SQL%ROWCOUNT;
7386                 iem_logger(l_logmessage);
7387                 --dbms_output.put_line(l_logmessage);
7388              when others then
7389                l_logmessage:='p_customer_phone other exception';
7390                 iem_logger(l_logmessage);
7391                 --dbms_output.put_line(l_logmessage);
7392           END;
7393 
7394         ELSIF p_customer_email is not null then
7395           BEGIN
7396             /*
7397 	    Select owner_table_id into x_customer_id
7398 	    From hz_contact_points
7399 	    where owner_table_name='HZ_PARTIES'
7400 	    and contact_point_type = 'EMAIL'
7401 	    and upper(email_address) =upper(p_customer_email);
7402             */
7403             l_logmessage:='p_customer_email address is '|| p_customer_email;
7404             iem_logger(l_logmessage);
7405             --dbms_output.put_line(l_logmessage);
7406              Select a.owner_table_id into x_customer_id
7407             from hz_contact_points a, hz_parties b
7408             where a.owner_table_name='HZ_PARTIES'
7409 	    and a.contact_point_type = 'EMAIL'
7410             and a.status='A'
7411             and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
7412     					 	 	  where contact_level_table='HZ_CONTACT_POINTS' and status='A')
7413 	    and a.owner_table_id = b.party_id
7414   	    and b.party_type in ('PERSON', 'ORGANIZATION')
7415 	    and upper(a.email_address) =upper(p_customer_email);
7416 
7417             l_logmessage:='p_customer_email x_Customer_id is '|| p_customer_email;
7418             iem_logger(l_logmessage);
7419             --dbms_output.put_line(l_logmessage);
7420           EXCEPTION
7421              when TOO_MANY_ROWS then
7422                 x_customer_id := null;
7423                 l_logmessage:='p_customer_email fetch returned too many rows'|| SQL%ROWCOUNT;
7424                 iem_logger(l_logmessage);
7425                 --dbms_output.put_line(l_logmessage);
7426              when NO_DATA_FOUND then
7427                 l_logmessage:='p_customer_email fetch returned 0 rows'|| SQL%ROWCOUNT;
7428                 iem_logger(l_logmessage);
7429                 --dbms_output.put_line(l_logmessage);
7430              when others then
7431                l_logmessage:='p_customer_email other exception';
7432                 iem_logger(l_logmessage);
7433                 --dbms_output.put_line(l_logmessage);
7434           END;
7435 
7436 	 --and inventory_item_id is of mtl_system_items_b.serv_req_enabled_code = 'E'
7437 	ELSIF p_instance_number is not null then
7438           BEGIN
7439             select distinct owner_party_id
7440             into x_customer_id
7441             from csi_item_instances
7442 	    where instance_number = p_instance_number;
7443           EXCEPTION
7444              when TOO_MANY_ROWS then
7445                 x_customer_id := null;
7446                 l_logmessage:='p_instance_number fetch returned too many rows'|| SQL%ROWCOUNT;
7447                 iem_logger(l_logmessage);
7448                 --dbms_output.put_line(l_logmessage);
7449              when NO_DATA_FOUND then
7450                 l_logmessage:='p_instance_number fetch returned 0 rows'|| SQL%ROWCOUNT;
7451                 iem_logger(l_logmessage);
7452                 --dbms_output.put_line(l_logmessage);
7453              when others then
7454                l_logmessage:='p_instance_number other exception';
7455                 iem_logger(l_logmessage);
7456                 --dbms_output.put_line(l_logmessage);
7457           END;
7458 
7459 	 --Item must be service- request enabled (serv_req_enabled_code = 'E').
7460 	 -- The itemmust not be a service item (contract_item_type_code is Null).
7461 	 ELSIF p_instance_serial_number is not null then
7462            BEGIN
7463             select distinct owner_party_id
7464             into x_customer_id
7465             from csi_item_instances
7466 	    where serial_number = p_instance_serial_number;
7467            EXCEPTION
7468              when TOO_MANY_ROWS then
7469                 x_customer_id := null;
7470                 l_logmessage:='p_instance_serial fetch returned too many rows'|| SQL%ROWCOUNT;
7471                 iem_logger(l_logmessage);
7472                 --dbms_output.put_line(l_logmessage);
7473              when NO_DATA_FOUND then
7474                 l_logmessage:='p_instance_serial fetch returned 0 rows'|| SQL%ROWCOUNT;
7475                 iem_logger(l_logmessage);
7476                 --dbms_output.put_line(l_logmessage);
7477              when others then
7478                l_logmessage:='p_instance_serial other exception';
7479                 iem_logger(l_logmessage);
7480                 --dbms_output.put_line(l_logmessage);
7481            END;
7482 
7483          ELSIF p_incident_site_number is not null then
7484           BEGIN
7485              select party_id into x_customer_id
7486              from hz_party_sites
7487              where party_site_number = p_incident_site_number;
7488           EXCEPTION
7489              when TOO_MANY_ROWS then
7490                 x_customer_id := null;
7491                 l_logmessage:='p_incident_site_number fetch returned too many rows'|| SQL%ROWCOUNT;
7492                 iem_logger(l_logmessage);
7493                 --dbms_output.put_line(l_logmessage);
7494              when NO_DATA_FOUND then
7495                 l_logmessage:='p_incident_site_number fetch returned 0 rows'|| SQL%ROWCOUNT;
7496                 iem_logger(l_logmessage);
7497                 --dbms_output.put_line(l_logmessage);
7498              when others then
7499                l_logmessage:='p_incident_site_number other exception';
7500                iem_logger(l_logmessage);
7501               --dbms_output.put_line(l_logmessage);
7502           END;
7503 
7504          --we are entering contact related customer_processing section
7505          ELSIF p_contact_number is not null then
7506            BEGIN
7507               --this is being fixed by the QA bug 8860086
7508               --the ditinct is doen to get a unique customer_id as this query will pass the multiple
7509               --rows with the same customer_id. Multiple rows comes because based on a party_number a
7510               --particular organization might have multiple contacts
7511               --NEW REQUIREMENT
7512               --the user can either pass the contact_number (party_number) of the RELATIONHIP record
7513               --or the contact or organization record. In either case I have to create the org.
7514               --therefore i have to fist find out what type of contact_number it is and accordingly
7515               --find the customer information.
7516            /* --old query
7517               Select distinct b.subject_id
7518               into g_customer_id
7519 	      from hz_contact_points a,hz_relationships b, hz_parties c
7520               where a.owner_table_name='HZ_PARTIES'
7521               and a.status='A'
7522 	      and a.primary_flag = 'Y'
7523               and a.owner_table_id = b.party_id
7524 	      and directional_flag = 'B'
7525               and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
7526      	  	                              where contact_level_table='HZ_CONTACT_POINTS' and status='A')
7527 	      and b.object_id = c.party_id
7528 	      and c.party_number = p_contact_number;
7529             */
7530              select upper(party_type) into l_party_type
7531              from hz_parties
7532              where party_number = p_contact_number;
7533 
7534                 l_logmessage:='p_contact_number processing for party and party_type is  '|| l_party_type;
7535                 iem_logger(l_logmessage);
7536                 --dbms_output.put_line(l_logmessage);
7537 
7538              IF (l_party_type = 'PARTY_RELATIONSHIP') THEN
7539                  select distinct a.subject_id
7540                  into g_customer_id
7541   	         from hz_relationships a, hz_parties b
7542 	         where a.party_id = b.party_id
7543                  and directional_flag = 'B'
7544                  and b.party_number = p_contact_number;
7545 
7546                  l_logmessage:='p_contact_number inside PARTY_RELATIONSHIP ';
7547                  iem_logger(l_logmessage);
7548                  --dbms_output.put_line(l_logmessage);
7549              ELSIF (l_party_type = 'PERSON') THEN
7550                  select distinct a.subject_id
7551                  into g_customer_id
7552           	 from hz_relationships a, hz_parties b
7553 	         where a.object_id = b.party_id
7554                  and directional_flag = 'B'
7555                  and b.party_number = p_contact_number;
7556 
7557                  l_logmessage:='p_contact_number inside PERSON ';
7558                  iem_logger(l_logmessage);
7559                  --dbms_output.put_line(l_logmessage);
7560              ELSIF (l_party_type = 'ORGANIZATION') THEN
7561                  select party_id into g_customer_id
7562                  from hz_parties
7563                  where party_number = p_contact_number;
7564 
7565                  l_logmessage:='p_contact_number inside ORGANIZATION ';
7566                  iem_logger(l_logmessage);
7567                  --dbms_output.put_line(l_logmessage);
7568              END IF;
7569            EXCEPTION
7570              when TOO_MANY_ROWS then
7571                 g_customer_id := null;
7572                 l_logmessage:='p_contact_number fetch returned too many rows'|| SQL%ROWCOUNT;
7573                 iem_logger(l_logmessage);
7574                 --dbms_output.put_line(l_logmessage);
7575              when NO_DATA_FOUND then
7576                 l_logmessage:='p_contact_number fetch returned 0 rows'|| SQL%ROWCOUNT;
7577                 iem_logger(l_logmessage);
7578                 --dbms_output.put_line(l_logmessage);
7579              when others then
7580                l_logmessage:='p_contact_number other exception';
7581                 iem_logger(l_logmessage);
7582                 --dbms_output.put_line(l_logmessage);
7583           END;
7584 
7585          ELSIF p_contact_name is not null then
7586            BEGIN
7587              --i did distinct because there may be many contacts for a single party_id
7588              --since we are trying to find the party_id of type organization or person here a distinct is a better match
7589              select distinct a.subject_id
7590              into g_customer_id
7591   	     from hz_relationships a, hz_parties b
7592 	     where a.object_id = b.party_id
7593              and directional_flag = 'B'
7594              and upper(b.party_name) = upper(p_contact_name);
7595 
7596            EXCEPTION
7597              when TOO_MANY_ROWS then
7598                 g_customer_id := null;
7599                 l_logmessage:='p_contact_name fetch returned too many rows'|| SQL%ROWCOUNT;
7600                 iem_logger(l_logmessage);
7601                 --dbms_output.put_line(l_logmessage);
7602              when NO_DATA_FOUND then
7603                 l_logmessage:='p_contact_name fetch returned 0 rows'|| SQL%ROWCOUNT;
7604                 iem_logger(l_logmessage);
7605                 --dbms_output.put_line(l_logmessage);
7606              when others then
7607                l_logmessage:='p_contact_name other exception';
7608                 iem_logger(l_logmessage);
7609                 --dbms_output.put_line(l_logmessage);
7610           END;
7611 
7612          ELSIF p_contact_phone is not null then
7613           BEGIN
7614              --i did distinct because there may be many contacts for a single party_id
7615              --since we are trying to find the party_id  distinct is a valid assumption
7616             /*
7617              select distinct b.object_id into g_customer_id
7618              from hz_parties a, hz_party_relationships b, hz_contact_points c
7619              where  c.phone_number = p_contact_phone
7620              where and reverse(c.transposed_phone_number)=REGEXP_REPLACE(p_contact_phone,'([[:punct:]|[:space:]]*)')
7621              and a.party_id = b.subject_id
7622              and c.owner_table_id = b.party_id
7623              and c.contact_point_type = 'PHONE'
7624              and c.owner_table_name = 'HZ_PARTIES';
7625             */
7626              Select distinct b.subject_id into g_customer_id
7627 	     from hz_contact_points a,hz_relationships b, hz_parties c
7628              where a.owner_table_name='HZ_PARTIES'
7629 	     and  a.contact_point_type='PHONE'
7630              and a.status='A'
7631 	     and a.primary_flag = 'Y'
7632              and a.owner_table_id = b.party_id
7633 	     and directional_flag = 'B'
7634              and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
7635      	  	                              where contact_level_table='HZ_CONTACT_POINTS' and status='A')
7636 	     and b.object_id = c.party_id
7637 	     and reverse(a.transposed_phone_number)=REGEXP_REPLACE(p_contact_phone,'([[:punct:]|[:space:]]*)');
7638          EXCEPTION
7639              when TOO_MANY_ROWS then
7640                 g_customer_id := null;
7641                 l_logmessage:='p_contact_phone fetch returned too many rows'|| SQL%ROWCOUNT;
7642                 iem_logger(l_logmessage);
7643                 --dbms_output.put_line(l_logmessage);
7644              when NO_DATA_FOUND then
7645                 l_logmessage:='p_contact_phone fetch returned 0 rows'|| SQL%ROWCOUNT;
7646                 iem_logger(l_logmessage);
7647                 --dbms_output.put_line(l_logmessage);
7648              when others then
7649                l_logmessage:='p_contact_phone other exception';
7650                 iem_logger(l_logmessage);
7651                 --dbms_output.put_line(l_logmessage);
7652           END;
7653 
7654          ELSIF p_contact_email is not null then
7655            BEGIN
7656              --i did distinct because there may be many contacts for a single party_id
7657              --since we are trying to find the party_id  distinct is a valid assumption
7658              /*
7659              select distinct b.object_id into g_customer_id
7660              from hz_parties a, hz_party_relationships b, hz_contact_points c
7661 	     where upper(c.email_address) =upper(p_contact_email)
7662              and a.party_id = b.subject_id
7663              and c.owner_table_id = b.party_id
7664              and c.contact_point_type = 'EMAIL'
7665              and c.owner_table_name = 'HZ_PARTIES';
7666              */
7667              Select distinct b.subject_id into g_customer_id
7668 	     from hz_contact_points a,hz_relationships b, hz_parties c
7669              where a.owner_table_name='HZ_PARTIES'
7670 	     and  a.contact_point_type='EMAIL'
7671              and a.status='A'
7672 	     and a.primary_flag = 'Y'
7673              and a.owner_table_id = b.party_id
7674 	     and directional_flag = 'B'
7675              and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
7676      	  	                              where contact_level_table='HZ_CONTACT_POINTS' and status='A')
7677 	     and b.object_id = c.party_id
7678 	     and upper(a.email_address) =upper(p_contact_email);
7679 
7680            EXCEPTION
7681              when TOO_MANY_ROWS then
7682                 g_customer_id := null;
7683                 l_logmessage:='p_contact_email fetch returned too many rows'|| SQL%ROWCOUNT;
7684           iem_logger(l_logmessage);
7685     --dbms_output.put_line(l_logmessage);
7686              when NO_DATA_FOUND then
7687                 l_logmessage:='p_contact_email fetch returned 0 rows'|| SQL%ROWCOUNT;
7688           iem_logger(l_logmessage);
7689     --dbms_output.put_line(l_logmessage);
7690              when others then
7691                l_logmessage:='p_contact_email other exception';
7692           iem_logger(l_logmessage);
7693     --dbms_output.put_line(l_logmessage);
7694            END;
7695 
7696        END IF; --END IF of all the validation
7697     ELSE
7698          --if customer id exist in that case pass the existing customer_id so that the x_value does not
7699          --go back as null causing issues in the program
7700          x_customer_id := g_customer_id;
7701     END IF; --END IF of customer_id chevk
7702   END getCustomerNumber;
7703 
7704   --Account number can be used to get customer_id as well as the cust_account_id
7705   --therefore we will automatically try to get the customer_id if it has not
7706   --been found already and try to populate the global variable
7707   --g_customer_id if a match is found; we will also return
7708   --the cust_account_id when ever there is a single match
7709   --NOTE: Reason for splitting account_id and customer_id processing is that
7710   --you can create a SR without account_id but you can not create a sr without customer_id
7711   Procedure getAccountNumber(p_account_number IN VARCHAR2,
7712                              x_cust_account_id    OUT NOCOPY NUMBER)
7713   IS
7714     l_account_count number;
7715     l_logmessage		varchar2(2000):=' ';
7716   BEGIN
7717 
7718       --try to find customer_id if its not been found yet
7719       --it should not come here but left the package here for future
7720       --change in processing use. Ignore for now
7721 
7722       IF g_customer_id IS NULL THEN
7723 	getCustomerNumber (p_account_number  => p_account_number,
7724        		           x_customer_id   => g_customer_id);
7725       END IF;
7726 
7727       IF (g_customer_id IS NOT NULL) AND (p_account_number IS NOT NULL) THEN
7728         BEGIN
7729           --the status must be active for cust_account_id
7730 	  Select cust_account_id into x_cust_account_id
7731 	  from hz_cust_accounts
7732 	  where party_id=g_customer_id
7733 	  and account_number=p_account_number
7734           and status = 'A';
7735         EXCEPTION
7736              when TOO_MANY_ROWS then
7737                 x_cust_account_id :=null;
7738                 l_logmessage:=p_account_number|| ' p_account_number fetch returned too many rows'|| SQL%ROWCOUNT;
7739           iem_logger(l_logmessage);
7740     --dbms_output.put_line(l_logmessage);
7741              when NO_DATA_FOUND then
7742                 l_logmessage:=p_account_number ||  'p_account_number fetch returned 0 rows'|| SQL%ROWCOUNT;
7743           iem_logger(l_logmessage);
7744     --dbms_output.put_line(l_logmessage);
7745              when others then
7746                l_logmessage:=p_account_number || 'p_account_number other exception';
7747           iem_logger(l_logmessage);
7748     --dbms_output.put_line(l_logmessage);
7749         END;
7750       -- try to find account_number related info even if there is no customer_id
7751      ELSE
7752         BEGIN
7753 	  Select cust_account_id into x_cust_account_id
7754 	  from hz_cust_accounts
7755 	  where account_number=p_account_number
7756           and status = 'A';
7757         EXCEPTION
7758              when TOO_MANY_ROWS then
7759                 x_cust_account_id :=null;
7760                 l_logmessage:=p_account_number|| ' p_account_number fetch returned too many rows'|| SQL%ROWCOUNT;
7761           iem_logger(l_logmessage);
7762     --dbms_output.put_line(l_logmessage);
7763              when NO_DATA_FOUND then
7764                 l_logmessage:=p_account_number ||  'p_account_number fetch returned 0 rows'|| SQL%ROWCOUNT;
7765           iem_logger(l_logmessage);
7766     --dbms_output.put_line(l_logmessage);
7767              when others then
7768                l_logmessage:=p_account_number || 'p_account_number other exception';
7769           iem_logger(l_logmessage);
7770     --dbms_output.put_line(l_logmessage);
7771         END;
7772 
7773       END IF;
7774   END getAccountNumber;
7775 
7776   --Question: Should we try to find contact related information from this
7777   -- we can find contact_point_id in this case too. so the question is should we seperate
7778   --out the contact point processing from the contact processing section; for now we are not treating
7779   --customer_phone_id and customer_email_id as the contact_point_id of contact information. How are things
7780   --going to work if the customer passes the contact_information as well as the customer information such as
7781   --customer_phone and customer_email apart from contact_phone and contact_email. We need to discuss
7782 
7783   --Qeustion: if this procedure like all other procedure you will see we have IF g_Customer_id is not null / ELSE section
7784   --where we try to find information without the cutomer_id. The question is lets see we finished our customer processing
7785   --and we did not find a customer_id from the parsed value. The what should the program do.
7786   --1. Should I break out of the program and return the status E to the calling program and revert to old processing
7787   --2. Should I continu processing trying to get information regarding customer_phone_id and other related information
7788       --with the default customer_id
7789   --3. Should I even have a condition in this section where I try to get values without the customer_number; since I should have
7790       --found a customer_id by now; and If i a havent found a customer_id by now; that means I cant create SR anyways. So why
7791       --bother with the porcessing and trying to find things without the customer_id
7792   Procedure getCustomerPhone (p_customer_phone     IN VARCHAR2,
7793                               x_customer_phone_id  OUT NOCOPY NUMBER)
7794   IS
7795    l_phone_count NUMBER;
7796    l_logmessage		varchar2(2000):=' ';
7797   BEGIN
7798         --try to find customer_id IF its not been found yet
7799       IF g_customer_id IS NULL THEN
7800            getCustomerNumber (p_customer_phone  => p_customer_phone,
7801                               x_customer_id   => g_customer_id);
7802       END IF;
7803 
7804       IF (g_customer_id IS NOT NULL) AND (p_customer_phone IS NOT NULL) THEN
7805          BEGIN
7806             Select contact_point_id into x_customer_phone_id
7807             From hz_contact_points
7808             where contact_point_type = 'PHONE'
7809             --and phone_number = p_customer_phone
7810             and reverse(transposed_phone_number)=REGEXP_REPLACE(p_customer_phone,'([[:punct:]|[:space:]]*)')
7811             and owner_table_id = g_customer_id;
7812           EXCEPTION
7813              when TOO_MANY_ROWS then
7814                 x_customer_phone_id := null;
7815                 l_logmessage:=p_customer_phone|| ' p_customer_phone fetch returned too many rows'|| SQL%ROWCOUNT;
7816                 iem_logger(l_logmessage);
7817                 --dbms_output.put_line(l_logmessage);
7818              when NO_DATA_FOUND then
7819                 l_logmessage:=p_customer_phone ||  'p_customer_phone fetch returned 0 rows'|| SQL%ROWCOUNT;
7820                 iem_logger(l_logmessage);
7821                 --dbms_output.put_line(l_logmessage);
7822              when others then
7823                l_logmessage:=p_customer_phone || 'p_customer_phone other exception';
7824                 iem_logger(l_logmessage);
7825                 --dbms_output.put_line(l_logmessage);
7826           END;
7827       ELSE
7828          BEGIN
7829            Select contact_point_id into x_customer_phone_id
7830             From hz_contact_points
7831             where owner_table_name='HZ_PARTIES'
7832             and contact_point_type = 'PHONE'
7833             and reverse(transposed_phone_number)=REGEXP_REPLACE(p_customer_phone,'([[:punct:]|[:space:]]*)');
7834          EXCEPTION
7835              when TOO_MANY_ROWS then
7836                 x_customer_phone_id := null;
7837                 l_logmessage:=p_customer_phone|| ' p_customer_phone fetch returned too many rows'|| SQL%ROWCOUNT;
7838                 iem_logger(l_logmessage);
7839                 --dbms_output.put_line(l_logmessage);
7840              when NO_DATA_FOUND then
7841                 l_logmessage:=p_customer_phone ||  'p_customer_phone fetch returned 0 rows'|| SQL%ROWCOUNT;
7842                 iem_logger(l_logmessage);
7843                 --dbms_output.put_line(l_logmessage);
7844              when others then
7845                l_logmessage:=p_customer_phone || 'p_customer_phone other exception';
7846                 iem_logger(l_logmessage);
7847                 --dbms_output.put_line(l_logmessage);
7848          END;
7849       END IF;
7850 
7851   END getCustomerPhone;
7852 
7853   Procedure getCustomerEmail (p_customer_email VARCHAR2,
7854                               x_customer_email_id  out NOCOPY number)
7855   IS
7856    l_email_count NUMBER;
7857    l_logmessage		varchar2(2000):=' ';
7858   BEGIN
7859 
7860         --try to find customer_id IF its not been found yet
7861         IF g_customer_id IS NULL THEN
7862         getCustomerNumber ( p_customer_email  => p_customer_email,
7863                             x_customer_id   => g_customer_id);
7864         END IF;
7865 
7866         --convert email address to uppercase to prevent case relative mismatch
7867         IF (g_customer_id IS NOT Null) AND (p_customer_email IS NOT NULL) THEN
7868          BEGIN
7869             Select contact_point_id into x_customer_email_id
7870             From hz_contact_points
7871             where contact_point_type = 'EMAIL'
7872             and upper(email_address) =upper(p_customer_email)
7873             and owner_table_id = g_customer_id;
7874           EXCEPTION
7875              when TOO_MANY_ROWS then
7876                 x_customer_email_id := null;
7877                 l_logmessage:=p_customer_email|| ' p_customer_email fetch returned too many rows'|| SQL%ROWCOUNT;
7878           iem_logger(l_logmessage);
7879     --dbms_output.put_line(l_logmessage);
7880              when NO_DATA_FOUND then
7881                 l_logmessage:=p_customer_email ||  'p_customer_email fetch returned 0 rows'|| SQL%ROWCOUNT;
7882           iem_logger(l_logmessage);
7883     --dbms_output.put_line(l_logmessage);
7884              when others then
7885                l_logmessage:=p_customer_email || 'p_customer_email other exception';
7886           iem_logger(l_logmessage);
7887     --dbms_output.put_line(l_logmessage);
7888           END;
7889 
7890         ELSE
7891           BEGIN
7892              Select contact_point_id into x_customer_email_id
7893              From hz_contact_points
7894              where owner_table_name='HZ_PARTIES'
7895              and contact_point_type = 'EMAIL'
7896              and upper(email_address) =upper(p_customer_email);
7897           EXCEPTION
7898              when TOO_MANY_ROWS then
7899                 x_customer_email_id := null;
7900                 l_logmessage:=p_customer_email|| ' p_customer_email fetch returned too many rows'|| SQL%ROWCOUNT;
7901           iem_logger(l_logmessage);
7902     --dbms_output.put_line(l_logmessage);
7903              when NO_DATA_FOUND then
7904                 l_logmessage:=p_customer_email ||  'p_customer_email fetch returned 0 rows'|| SQL%ROWCOUNT;
7905           iem_logger(l_logmessage);
7906     --dbms_output.put_line(l_logmessage);
7907              when others then
7908                l_logmessage:=p_customer_email || 'p_customer_email other exception';
7909           iem_logger(l_logmessage);
7910     --dbms_output.put_line(l_logmessage);
7911           END;
7912 
7913        END IF;
7914   END getCustomerEmail;
7915 
7916   --this procedure will accept a cust_account_id as avalue if it not passed
7917   --it is defaulted to null. However if its passed then it will use the cust_account_id
7918   --as an additional filter while retrieving value. The additional filter will
7919   -- further retrict the result set to retrive a unique match
7920 
7921   --Questions: what happens if the customer has ranked customer_number (Customer_number gives use
7922   -- cust_account_id) lower in the ranking and a cust_account_id has not yet been found
7923   --but would be found after processing getInstnaceNumber.
7924   --Should we try to find a cust_account_id if it has not been found at this stage
7925   --- ANSWSER: Go with the way things are right now.. if ranking is preventing us we are not going to do it
7926 
7927   --Question: in this query you will notice we are checking for customer_id and createing one set of query
7928   --and then another set of query without the customer_id. Now there are several scenarios.
7929   -- 1. Technically we should not be doing any of these processing if a customer_id hsa not been found already
7930         --so shall we take out the section with where we are trying to get info without the customer_id
7931   -- 2. OR shall we try to get the information withe the customer_id as customer_id will be present by now,
7932         --and if we are not able to get a single hit with customer_id; shall we try to get a single hit without the
7933         --customer_id
7934   Procedure getInstanceNumber (p_instance_number     IN VARCHAR2,
7935                                p_cust_account_id     IN NUMBER DEFAULT NULL,
7936                                x_customer_product_id OUT NOCOPY NUMBER,
7937                                x_inventory_org_id    OUT NOCOPY NUMBER,
7938                                x_inventory_item_id   OUT NOCOPY NUMBER)
7939   IS
7940    l_instance_count number;
7941    l_logmessage		varchar2(2000):=' ';
7942   BEGIN
7943        --Item must inventroy_item_id of (mtl_system_items_b.serv_req_enabled_code = 'E').
7944        -- The item must not be a service item (contract_item_type_code is Null).
7945        IF g_customer_id IS NULL THEN
7946         getCustomerNumber ( p_instance_number => p_instance_number,
7947                             x_customer_id     => g_customer_id);
7948        END IF;
7949 
7950         IF (g_customer_id IS NOT NULL) AND (p_instance_number IS NOT NULL) THEN
7951 
7952             --cust_account_id is found in the call getAccountNumber
7953             --this procedure will accept a cust_account_id as avalue if it not passed
7954             --it is defaulted to null. However if its passed then it will use the cust_account_id
7955             --as an additional filter while retrieving value. The additional filter will
7956             -- further retrict the result set to retrive a unique match
7957             IF (p_cust_account_id IS NOT NULL) THEN
7958                 BEGIN
7959                   select instance_id,inventory_item_id, inv_master_organization_id
7960                   into x_customer_product_id, x_inventory_item_id, x_inventory_org_id
7961                   from csi_item_instances
7962                   where instance_number = p_instance_number
7963                   and owner_party_account_id = p_cust_account_id
7964                   and owner_party_id = g_customer_id;
7965                 EXCEPTION
7966                   when TOO_MANY_ROWS then
7967                      x_customer_product_id := null;
7968                      x_inventory_item_id := null;
7969                      x_inventory_org_id := null;
7970                      l_logmessage:=p_instance_number|| '1p_instance_number fetch returned too many rows'|| SQL%ROWCOUNT;
7971           	     iem_logger(l_logmessage);
7972     	    	      --dbms_output.put_line(l_logmessage);
7973                   when NO_DATA_FOUND then
7974                      l_logmessage:=p_instance_number || '1p_instance_number fetch returned 0 rows'|| SQL%ROWCOUNT;
7975           	     iem_logger(l_logmessage);
7976     	    	      --dbms_output.put_line(l_logmessage);
7977                   when others then
7978                     l_logmessage:=p_instance_number || '1p_instance_number other exception';
7979           	     iem_logger(l_logmessage);
7980     	    	      --dbms_output.put_line(l_logmessage);
7981                 END;
7982             ELSE
7983                BEGIN
7984                   select instance_id,inventory_item_id, inv_master_organization_id
7985                   into x_customer_product_id, x_inventory_item_id, x_inventory_org_id
7986                   from csi_item_instances
7987                   where instance_number = p_instance_number
7988                   and owner_party_id = g_customer_id;
7989                EXCEPTION
7990                   when TOO_MANY_ROWS then
7991                      x_customer_product_id := null;
7992                      x_inventory_item_id := null;
7993                      x_inventory_org_id := null;
7994                      l_logmessage:=p_instance_number|| '2p_instance_number fetch returned too many rows'|| SQL%ROWCOUNT;
7995           	     iem_logger(l_logmessage);
7996     	    	      --dbms_output.put_line(l_logmessage);
7997                   when NO_DATA_FOUND then
7998                      l_logmessage:=p_instance_number || '2p_instance_number fetch returned 0 rows'|| SQL%ROWCOUNT;
7999           	     iem_logger(l_logmessage);
8000     	    	      --dbms_output.put_line(l_logmessage);
8001                   when others then
8002                     l_logmessage:=p_instance_number || '2p_instance_number other exception';
8003           	     iem_logger(l_logmessage);
8004     	    	      --dbms_output.put_line(l_logmessage);
8005                END;
8006            END IF;
8007         ELSE
8008           IF (p_cust_account_id IS NOT NULL) THEN
8009              BEGIN
8010                 select instance_id,inventory_item_id, inv_master_organization_id
8011                 into x_customer_product_id, x_inventory_item_id, x_inventory_org_id
8012                 from csi_item_instances
8013                 where instance_number = p_instance_number
8014                 and owner_party_account_id = p_cust_account_id;
8015              EXCEPTION
8016                 when TOO_MANY_ROWS then
8017                      x_customer_product_id := null;
8018                      x_inventory_item_id := null;
8019                      x_inventory_org_id := null;
8020                    l_logmessage:=p_instance_number|| '3p_instance_number fetch returned too many rows'|| SQL%ROWCOUNT;
8021                     iem_logger(l_logmessage);
8022     	          --dbms_output.put_line(l_logmessage);
8023                 when NO_DATA_FOUND then
8024                    l_logmessage:=p_instance_number || '3p_instance_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8025                     iem_logger(l_logmessage);
8026                    --dbms_output.put_line(l_logmessage);
8027                 when others then
8028                    l_logmessage:=p_instance_number || '3p_instance_number other exception';
8029                     iem_logger(l_logmessage);
8030                    --dbms_output.put_line(l_logmessage);
8031              END;
8032           ELSE
8033             BEGIN
8034               select instance_id,inventory_item_id, inv_master_organization_id
8035               into x_customer_product_id, x_inventory_item_id, x_inventory_org_id
8036               from csi_item_instances
8037               where instance_number = p_instance_number;
8038             EXCEPTION
8039                 when TOO_MANY_ROWS then
8040                      x_customer_product_id := null;
8041                      x_inventory_item_id := null;
8042                      x_inventory_org_id := null;
8043                    l_logmessage:=p_instance_number|| '4p_instance_number fetch returned too many rows'|| SQL%ROWCOUNT;
8044                     iem_logger(l_logmessage);
8045                    --dbms_output.put_line(l_logmessage);
8046                 when NO_DATA_FOUND then
8047                    l_logmessage:=p_instance_number || '4p_instance_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8048                     iem_logger(l_logmessage);
8049                    --dbms_output.put_line(l_logmessage);
8050                 when others then
8051                    l_logmessage:=p_instance_number || '4p_instance_number other exception';
8052                     iem_logger(l_logmessage);
8053                    --dbms_output.put_line(l_logmessage);
8054             END;
8055         END IF;
8056       END IF; --end if of g_customer_id check
8057   END getInstanceNumber;
8058 
8059 
8060   --this procedure will accept a cust_account_id as avalue if it not passed
8061   --it is defaulted to null. However if its passed then it will use the
8062   -- cust_account_id
8063   --as an additional filter while retrieving value. The additional filter will
8064   -- further retrict the result set to retrive a unique match
8065 
8066   --Questions: what happens if the customer has ranked customer_number lower in
8067   -- the ranking and a customer a cust_account_id has not yet been found but would b e found
8068   -- after processing getInstnaceNumber. Should we try to find a cust_account_id if it has not
8069   -- been found at this stage
8070    --ANSWER: No go with the current way we are handling things
8071 
8072   Procedure getInstanceSerialNumber (p_instance_serial_number     IN VARCHAR2,
8073                                p_cust_account_id     IN NUMBER DEFAULT NULL,
8074                                x_customer_product_id OUT NOCOPY NUMBER,
8075                                x_inventory_org_id    OUT NOCOPY NUMBER,
8076                                x_inventory_item_id   OUT NOCOPY NUMBER)
8077   IS
8078    l_instance_count number;
8079    l_logmessage		varchar2(2000):=' ';
8080   BEGIN
8081        --Item must inventroy_item_id of
8082        --(mtl_system_items_b.serv_req_enabled_code = 'E').
8083        -- The item must not be a service item (contract_item_type_code is Null).
8084   --IGNORE this section as we should have already found the customer_id but
8085        --leaving the code here for futere purpose if we change our mind
8086        IF g_customer_id IS NULL THEN
8087         getCustomerNumber ( p_instance_serial_number => p_instance_serial_number,
8088                             x_customer_id             => g_customer_id);
8089        END IF;
8090 
8091         IF (g_customer_id IS NOT NULL) AND (p_instance_serial_number IS NOT NULL) THEN
8092 
8093                       l_logmessage:=p_instance_serial_number|| 'inside customer_id not null and instance_Serila not null';
8094                       iem_logger(l_logmessage);
8095                       --dbms_output.put_line(l_logmessage);
8096             --this procedure will accept a cust_account_id
8097             --as avalue if it not passed
8098             --it is defaulted to null. However if its passed
8099             --then it will use the cust_account_id
8100             --as an additional filter while retrieving value.
8101             --The additional filter will
8102             -- further retrict the result set to retrive a unique match
8103             IF (p_cust_account_id IS NOT NULL) THEN
8104                  BEGIN
8105                       l_logmessage:='instance_Serial:'||p_instance_serial_number|| 'cust_account_id not null';
8106                       iem_logger(l_logmessage);
8107                       --dbms_output.put_line(l_logmessage);
8108                    select instance_id,inventory_item_id,inv_master_organization_id
8109                    into x_customer_product_id, x_inventory_item_id, x_inventory_org_id
8110                    from csi_item_instances
8111                    where serial_number = p_instance_serial_number
8112                    and owner_party_account_id = p_cust_account_id
8113                    and owner_party_id = g_customer_id;
8114 
8115                    l_logmessage:='customer_product_id:'||x_customer_product_id|| 'inv_item_id:'||x_inventory_item_id||'org:'||x_inventory_org_id;
8116                    iem_logger(l_logmessage);
8117                    --dbms_output.put_line(l_logmessage);
8118                  EXCEPTION
8119                    when TOO_MANY_ROWS then
8120                      x_customer_product_id := null;
8121                      x_inventory_item_id := null;
8122                      x_inventory_org_id := null;
8123                       l_logmessage:=p_instance_serial_number|| 'inst_ser_number fetch returned too many rows'|| SQL%ROWCOUNT;
8124                       iem_logger(l_logmessage);
8125                       --dbms_output.put_line(l_logmessage);
8126                    when NO_DATA_FOUND then
8127                       l_logmessage:=p_instance_serial_number || 'inst_ser_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8128                       iem_logger(l_logmessage);
8129                       --dbms_output.put_line(l_logmessage);
8130                    when others then
8131                       l_logmessage:=p_instance_serial_number || 'inst_ser_number other exception';
8132                       iem_logger(l_logmessage);
8133                       --dbms_output.put_line(l_logmessage);
8134                 END;
8135            ELSE
8136                 BEGIN
8137                   select instance_id,inventory_item_id,inv_master_organization_id
8138                   into x_customer_product_id, x_inventory_item_id, x_inventory_org_id
8139                   from csi_item_instances
8140                   where serial_number = p_instance_serial_number
8141                   and owner_party_id = g_customer_id;
8142                    l_logmessage:='account_id is null ';
8143                    iem_logger(l_logmessage);
8144                    --dbms_output.put_line(l_logmessage);
8145 
8146                    l_logmessage:='customer_product_id:'||x_customer_product_id|| 'inv_item_id:'||x_inventory_item_id||'org:'||x_inventory_org_id;
8147                    iem_logger(l_logmessage);
8148                    --dbms_output.put_line(l_logmessage);
8149                 EXCEPTION
8150                   when TOO_MANY_ROWS then
8151                      x_customer_product_id := null;
8152                      x_inventory_item_id := null;
8153                      x_inventory_org_id := null;
8154                      l_logmessage:=p_instance_serial_number|| 'inst_ser_number fetch returned too many rows'|| SQL%ROWCOUNT;
8155                     iem_logger(l_logmessage);
8156                     --dbms_output.put_line(l_logmessage);
8157                   when NO_DATA_FOUND then
8158                      l_logmessage:=p_instance_serial_number || 'inst_ser_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8159                       iem_logger(l_logmessage);
8160                      --dbms_output.put_line(l_logmessage);
8161                   when others then
8162                      l_logmessage:=p_instance_serial_number || 'inst_ser_number other exception';
8163                       iem_logger(l_logmessage);
8164                       --dbms_output.put_line(l_logmessage);
8165                 END;
8166 
8167            END IF;
8168         ELSE
8169            IF (p_cust_account_id IS NOT NULL) THEN
8170              BEGIN
8171                 select instance_id,inventory_item_id, inv_master_organization_id
8172                 into x_customer_product_id, x_inventory_item_id, x_inventory_org_id
8173                 from csi_item_instances
8174                 where serial_number = p_instance_serial_number
8175                 and owner_party_account_id = p_cust_account_id;
8176                    l_logmessage:='account_id is not null in the else section meaning g_customer_id is null ';
8177                    iem_logger(l_logmessage);
8178                    --dbms_output.put_line(l_logmessage);
8179 
8180                    l_logmessage:='customer_product_id:'||x_customer_product_id|| 'inv_item_id:'||x_inventory_item_id||'org:'||x_inventory_org_id;
8181                    iem_logger(l_logmessage);
8182                    --dbms_output.put_line(l_logmessage);
8183              EXCEPTION
8184                 when TOO_MANY_ROWS then
8185                      x_customer_product_id := null;
8186                      x_inventory_item_id := null;
8187                      x_inventory_org_id := null;
8188                    l_logmessage:='p_instance_serial_number fetch returned too many rows'|| SQL%ROWCOUNT;
8189                    iem_logger(l_logmessage);
8190                    --dbms_output.put_line(l_logmessage);
8191                 when NO_DATA_FOUND then
8192                    l_logmessage:='p_instance_serial_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8193                    iem_logger(l_logmessage);
8194                    --dbms_output.put_line(l_logmessage);
8195                 when others then
8196                    l_logmessage:='p_instance_serial_number other exception';
8197                    iem_logger(l_logmessage);
8198                       --dbms_output.put_line(l_logmessage);
8199              END;
8200           ELSE
8201              BEGIN
8202                select instance_id,inventory_item_id, inv_master_organization_id
8203                into x_customer_product_id, x_inventory_item_id, x_inventory_org_id
8204                from csi_item_instances
8205                 where serial_number = p_instance_serial_number;
8206 
8207                    l_logmessage:='account_id is null ';
8208                    iem_logger(l_logmessage);
8209                    --dbms_output.put_line(l_logmessage);
8210 
8211                    l_logmessage:='customer_product_id:'||x_customer_product_id|| 'inv_item_id:'||x_inventory_item_id||'org:'||x_inventory_org_id;
8212                    iem_logger(l_logmessage);
8213                    --dbms_output.put_line(l_logmessage);
8214              EXCEPTION
8215                 when TOO_MANY_ROWS then
8216                      x_customer_product_id := null;
8217                      x_inventory_item_id := null;
8218                      x_inventory_org_id := null;
8219                    l_logmessage:='p_instance_serial_number fetch returned too many rows'|| SQL%ROWCOUNT;
8220                    iem_logger(l_logmessage);
8221                       --dbms_output.put_line(l_logmessage);
8222                 when NO_DATA_FOUND then
8223                    l_logmessage:='p_instance_serial_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8224                    iem_logger(l_logmessage);
8225                       --dbms_output.put_line(l_logmessage);
8226                 when others then
8227                    l_logmessage:='p_instance_serial_number other exception';
8228                    iem_logger(l_logmessage);
8229                     --dbms_output.put_line(l_logmessage);
8230              END;
8231           END IF;
8232        END IF;
8233   END getInstanceSerialNumber;
8234 
8235 
8236   Procedure getIncidentSiteNumber (p_incident_site_number IN VARCHAR2,
8237                                    x_incident_location_id out NOCOPY NUMBER)
8238   IS
8239     l_site_count number;
8240     l_logmessage		varchar2(2000):=' ';
8241   BEGIN
8242       IF g_customer_id IS NULL THEN
8243           getCustomerNumber ( p_incident_site_number  => p_incident_site_number,
8244                               x_customer_id   => g_customer_id);
8245       END IF;
8246 
8247       IF (g_customer_id IS NOT NULL) AND (p_incident_site_number IS NOT NULL) THEN
8248           BEGIN
8249             select party_site_id into x_incident_location_id
8250             from hz_party_sites
8251             where party_site_number = p_incident_site_number
8252             and party_id = g_customer_id;
8253           EXCEPTION
8254             when TOO_MANY_ROWS then
8255                x_incident_location_id := null;
8256                 l_logmessage:='p_instance_serial_number fetch returned too many rows'|| SQL%ROWCOUNT;
8257                 iem_logger(l_logmessage);
8258                 --dbms_output.put_line(l_logmessage);
8259             when NO_DATA_FOUND then
8260                 l_logmessage:='p_instance_serial_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8261                 iem_logger(l_logmessage);
8262                 --dbms_output.put_line(l_logmessage);
8263             when others then
8264                 l_logmessage:='p_instance_serial_number other exception';
8265                 iem_logger(l_logmessage);
8266                 --dbms_output.put_line(l_logmessage);
8267           END;
8268       ELSE
8269         BEGIN
8270           select party_site_id into x_incident_location_id
8271           from hz_party_sites
8272           where party_site_number = p_incident_site_number;
8273         EXCEPTION
8274            when TOO_MANY_ROWS then
8275                x_incident_location_id := null;
8276                 l_logmessage:='p_instance_serial_number fetch returned too many rows'|| SQL%ROWCOUNT;
8277                 iem_logger(l_logmessage);
8278                 --dbms_output.put_line(l_logmessage);
8279            when NO_DATA_FOUND then
8280                  l_logmessage:='p_instance_serial_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8281                 iem_logger(l_logmessage);
8282                 --dbms_output.put_line(l_logmessage);
8283            when others then
8284                 l_logmessage:='p_instance_serial_number other exception';
8285           iem_logger(l_logmessage);
8286     --dbms_output.put_line(l_logmessage);
8287         END;
8288       END IF;
8289   END getIncidentSiteNumber;
8290 
8291   ------------------------------------------------------------
8292   -- contact processing
8293   -------------------------------------------------------------
8294   --this are few essential information whihc is needed
8295   --party_id of type contact
8296   --contact_point_id from hz_contact_points of the contact
8297   --party_id is the object_id of the type contact_of from hz_parties.party_id
8298   --contact_point id is the contact_point_id from hz_contact_points where object_id
8299   --NOTE: Make sure we are not calling this procedure if the account type if of Internal
8300   --if its internal then we will just use the passed contact_party_id and contact_point_id
8301 
8302   Procedure getContactNumber (p_contact_number IN VARCHAR2,
8303                               p_parser_id      IN NUMBER,
8304                               p_contact_phone  IN VARCHAR2,
8305                               p_contact_email IN VARCHAR2,
8306                               x_contact_party_id  OUT NOCOPY NUMBER,
8307                               x_contact_type      OUT NOCOPY VARCHAR2,
8308                               x_contact_point_type      OUT NOCOPY VARCHAR2,
8309                               x_contact_point_id  OUT NOCOPY NUMBER)
8310   IS
8311     l_party_count NUMBER;
8312     l_logmessage		varchar2(2000):=' ';
8313     l_party_type VARCHAR2(100) :=null;
8314   BEGIN
8315 
8316         --process this attribute only if g_contact_party_id has not been found yet.
8317         --if it has been found then there is not need to process this attribute a
8318         IF g_contact_party_id IS NULL THEN
8319 
8320             l_logmessage:='entered contact_number processing and g_contact party id is null';
8321             iem_logger(l_logmessage);
8322             --dbms_output.put_line(l_logmessage);
8323 
8324              --check what is the contact type for the contact number
8325              select upper(party_type) into l_party_type
8326              from hz_parties
8327              where party_number = p_contact_number;
8328 
8329             l_logmessage:='contact_party_type is ' || l_party_type ;
8330             iem_logger(l_logmessage);
8331             --dbms_output.put_line(l_logmessage);
8332 
8333              FOR contact_rec in (Select column_name, rank
8334                                  from iem_parser_dtls
8335                                  where parser_id = p_parser_id
8336                                  and UPPER(column_name) IN ('CONTACT_PHONE','CONTACT_EMAIL')
8337                                  order by rank asc)
8338              LOOP
8339                 --only go throug the processing if the value has not been found
8340                 --in the last itiration there fore checking the x_contact_party_id value
8341                 --we are also looking for contact_phone and contact_email because its very rare to get a
8342                 --single hit from just from the contact_number.
8343                 IF x_contact_party_id IS NULL THEN
8344 
8345                    IF ((contact_rec.column_name = 'CONTACT_PHONE') AND (p_contact_phone is not null)) THEN
8346                       BEGIN
8347                         IF (l_party_type = 'PERSON') THEN
8348                             l_logmessage:='contact_number->contact_phone->type:person processing';
8349                             iem_logger(l_logmessage);
8350                             --dbms_output.put_line(l_logmessage);
8351 
8352                             --i am using reglar expression here to check if there are any unwanted chars that are
8353                             --passed by users and strip those off.
8354                             Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8355 		            into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8356                             from hz_contact_points a,hz_relationships b, hz_parties c
8357                             where a.owner_table_name='HZ_PARTIES'
8358                             and  a.contact_point_type='PHONE'
8359                             and a.status='A'
8360                             and a.owner_table_id = b.party_id
8361                             and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8362      	 					    where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8363 	                    and b.party_id = c.party_id
8364                             and b.object_id in (select party_id from hz_parties where party_number = p_contact_number)
8365                             --and c.party_number =p_contact_number
8366                             and reverse(a.transposed_phone_number)=REGEXP_REPLACE(p_contact_phone,'([[:punct:]|[:space:]]*)')
8367 	                    and b.subject_id = g_customer_id;
8368                          ELSIF (l_party_type = 'PARTY_RELATIONSHIP') THEN
8369                             l_logmessage:='contact_number->contact_phone->type:party_relationship processing';
8370                             iem_logger(l_logmessage);
8371                             --dbms_output.put_line(l_logmessage);
8372 
8373                             Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8374 		            into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8375                             from hz_contact_points a,hz_relationships b, hz_parties c
8376                             where a.owner_table_name='HZ_PARTIES'
8377                             and  a.contact_point_type='PHONE'
8378                             and a.status='A'
8379                             and a.owner_table_id = b.party_id
8380                             and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8381      	 					    where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8382 	                    and b.party_id = c.party_id
8383                             --and b.object_id in (select party_id from hz_parties where party_number = p_contact_number)
8384                             and c.party_number =p_contact_number
8385                             and reverse(a.transposed_phone_number)=REGEXP_REPLACE(p_contact_phone,'([[:punct:]|[:space:]]*)')
8386 	                    and b.subject_id = g_customer_id;
8387                          END IF;
8388 
8389                        EXCEPTION
8390                            when TOO_MANY_ROWS then
8391                               x_contact_party_id := null;
8392                               x_contact_type := null;
8393                               x_contact_point_id := null;
8394                               x_contact_point_type := null;
8395 
8396                               l_logmessage:='contact_number fetch returned too many rows'|| SQL%ROWCOUNT;
8397                               iem_logger(l_logmessage);
8398                               --dbms_output.put_line(l_logmessage);
8399                            when NO_DATA_FOUND then
8400                               l_logmessage:='contact_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8401                               iem_logger(l_logmessage);
8402                               --dbms_output.put_line(l_logmessage);
8403                            when others then
8404                               l_logmessage:='contact_number other exception';
8405                               iem_logger(l_logmessage);
8406                               --dbms_output.put_line(l_logmessage);
8407                        END;
8408                      --run the queries to get values
8409                    ELSIF ((contact_rec.column_name = 'CONTACT_EMAIL') AND (p_contact_email IS NOT NULL)) THEN
8410                         BEGIN
8411                         IF (l_party_type = 'PERSON') THEN
8412                             l_logmessage:='contact_number->contact_email->type:person processing';
8413                             iem_logger(l_logmessage);
8414                             --dbms_output.put_line(l_logmessage);
8415 
8416                             Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8417 		            into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8418                             from hz_contact_points a,hz_relationships b, hz_parties c
8419                             where a.owner_table_name='HZ_PARTIES'
8420                             and a.contact_point_type = 'EMAIL'
8421                             and a.status='A'
8422                             and a.owner_table_id = b.party_id
8423                             and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8424      	 					    where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8425 	                    and b.party_id = c.party_id
8426                             and b.object_id in (select party_id from hz_parties where party_number = p_contact_number)
8427                             --and c.party_number =p_contact_number
8428                             and upper(c.email_address) = upper(p_contact_email)
8429 	                    and b.subject_id = g_customer_id;
8430 
8431                          ELSIF (l_party_type = 'PARTY_RELATIONSHIP') THEN
8432                             l_logmessage:='contact_number->contact_email->type:party_relationship processing';
8433                             iem_logger(l_logmessage);
8434                             --dbms_output.put_line(l_logmessage);
8435                             Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8436 		            into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8437                             from hz_contact_points a,hz_relationships b, hz_parties c
8438                             where a.owner_table_name='HZ_PARTIES'
8439                             and a.contact_point_type = 'EMAIL'
8440                             and a.status='A'
8441                             and a.owner_table_id = b.party_id
8442                             and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8443      	 					    where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8444 	                    and b.party_id = c.party_id
8445                             --and b.object_id in (select party_id from hz_parties where party_number = p_contact_number)
8446                             and c.party_number =p_contact_number
8447                             and upper(c.email_address) = upper(p_contact_email)
8448 	                    and b.subject_id = g_customer_id;
8449                           END IF;
8450 
8451                          EXCEPTION
8452                            when TOO_MANY_ROWS then
8453                               x_contact_party_id := null;
8454                               x_contact_type := null;
8455                               x_contact_point_id := null;
8456                               x_contact_point_type := null;
8457                               l_logmessage:='contact_number fetch returned too many rows'|| SQL%ROWCOUNT;
8458                               iem_logger(l_logmessage);
8459                                --dbms_output.put_line(l_logmessage);
8460                            when NO_DATA_FOUND then
8461                               l_logmessage:='contact_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8462                               iem_logger(l_logmessage);
8463                                             --dbms_output.put_line(l_logmessage);
8464                            when others then
8465                               l_logmessage:='contact_number other exception';
8466                               iem_logger(l_logmessage);
8467                                             --dbms_output.put_line(l_logmessage);
8468                          END;
8469                     END IF;  --end if of contact_Column name checl
8470 
8471                 --exit loop if x_contact_party_id has been found
8472                 EXIT WHEN x_contact_party_id IS NOT NULL;
8473                 END IF; --end if of x_contact_party_id check
8474              END LOOP;
8475 
8476             ---after going throug the loop if the x_contact_party_id was not populated then try alone
8477             -- wit the p_Contact_number information
8478             --NOTE: I am doing rownum = 1 here to get the top hit. Since we are given only contact_number
8479             --which can yeild multiple contact values for mail and phone.
8480             IF x_contact_party_id IS NULL THEN
8481                   BEGIN
8482                    IF (l_party_type = 'PERSON') THEN
8483                       --If we were not able to match in this case we are hoping to get single hit
8484                       -- based on the primary flag but many a times both phone and email are flagged Y
8485                             l_logmessage:='contact_number->no email or phone ->type:person processing';
8486                             iem_logger(l_logmessage);
8487                             --dbms_output.put_line(l_logmessage);
8488                       Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8489 		      into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8490                       from hz_contact_points a,hz_relationships b, hz_parties c
8491                       where a.owner_table_name='HZ_PARTIES'
8492                       and a.status='A'
8493                       and a.primary_flag = 'Y'
8494                       and a.owner_table_id = b.party_id
8495                       and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8496      	 			  where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8497 	               and b.party_id = c.party_id
8498                        and b.object_id in (select party_id from hz_parties where party_number = p_contact_number)
8499                       -- and c.party_number =p_contact_number
8500 	               and b.subject_id = g_customer_id
8501                        and rownum = 1;
8502                     ELSIF (l_party_type = 'PARTY_RELATIONSHIP') THEN
8503                             l_logmessage:='contact_number->no email or phone ->type:party_relationship processing';
8504                             iem_logger(l_logmessage);
8505                             --dbms_output.put_line(l_logmessage);
8506                       Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8507 		      into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8508                       from hz_contact_points a,hz_relationships b, hz_parties c
8509                       where a.owner_table_name='HZ_PARTIES'
8510                       and a.status='A'
8511                       and a.primary_flag = 'Y'
8512                       and a.owner_table_id = b.party_id
8513                       and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8514      	 			  where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8515 	               and b.party_id = c.party_id
8516                        --and b.object_id in (select party_id from hz_parties where party_number = p_contact_number)
8517                        and c.party_number =p_contact_number
8518 	               and b.subject_id = g_customer_id
8519                        and rownum = 1;
8520                     END IF;
8521 
8522                   EXCEPTION
8523                      when TOO_MANY_ROWS then
8524                               x_contact_party_id := null;
8525                               x_contact_type := null;
8526                               x_contact_point_id := null;
8527                               x_contact_point_type := null;
8528                         l_logmessage:='contact_number fetch returned too many rows'|| SQL%ROWCOUNT;
8529                         iem_logger(l_logmessage);
8530                                 --dbms_output.put_line(l_logmessage);
8531                      when NO_DATA_FOUND then
8532                         l_logmessage:='contact_number fetch returned 0 rows'|| SQL%ROWCOUNT;
8533                         iem_logger(l_logmessage);
8534                                 --dbms_output.put_line(l_logmessage);
8535                      when others then
8536                         l_logmessage:='contact_number other exception';
8537                         iem_logger(l_logmessage);
8538                                 --dbms_output.put_line(l_logmessage);
8539                   END;
8540             END IF;
8541         END IF; --end if of of contact_id processing
8542   END getContactNumber;
8543 
8544  Procedure getContactName   (p_contact_name IN VARCHAR2,
8545                               p_parser_id      IN NUMBER,
8546                               p_contact_phone  IN VARCHAR2,
8547                               p_contact_email IN VARCHAR2,
8548                               x_contact_party_id  OUT NOCOPY NUMBER,
8549                               x_contact_type      OUT NOCOPY VARCHAR2,
8550                               x_contact_point_type    OUT NOCOPY VARCHAR2,
8551                               x_contact_point_id  OUT NOCOPY NUMBER)
8552   IS
8553     l_party_count NUMBER;
8554     l_logmessage		varchar2(2000):=' ';
8555   BEGIN
8556 
8557         --process this attribute only if g_contact_party_id has not been found yet.
8558         --if it has been found then there is not need to process this attribute a
8559           l_logmessage:='inside getContactName sub proc';
8560           iem_logger(l_logmessage);
8561            --dbms_output.put_line(l_logmessage);
8562         IF g_contact_party_id IS NULL THEN
8563 
8564              FOR contact_rec in (Select column_name, rank
8565                                  from iem_parser_dtls
8566                                  where parser_id = p_parser_id
8567                                  and UPPER(column_name) IN ('CONTACT_PHONE','CONTACT_EMAIL')
8568                                  order by rank asc)
8569              LOOP
8570                 --only go throug the processing if the value has not been found
8571                 --in the last itiration there fore checking the x_contact_party_id value
8572                 IF (x_contact_party_id) IS NULL THEN
8573                    IF (contact_rec.column_name = 'CONTACT_PHONE') THEN
8574                       BEGIN
8575                           Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8576 		          into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8577                           from hz_contact_points a,hz_relationships b, hz_parties c
8578                           where a.owner_table_name='HZ_PARTIES'
8579                           and  a.contact_point_type='PHONE'
8580                           and a.status='A'
8581                           and a.owner_table_id = b.party_id
8582                           and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8583      	 					  where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8584 	                  and b.party_id = c.party_id
8585                           and b.object_id in (select party_id from hz_parties where upper(party_name) =upper(p_contact_name))
8586                           --and upper(c.party_name) =upper(p_contact_name)
8587                           and reverse(a.transposed_phone_number)=REGEXP_REPLACE(p_contact_phone,'([[:punct:]|[:space:]]*)')
8588 	                  and b.subject_id = g_customer_id;
8589                              l_logmessage:='cotanct_name-phone'||p_contact_name||'--partyid:'||x_contact_party_id||'point_id'||x_contact_point_id ;
8590                              iem_logger(l_logmessage);
8591                              --dbms_output.put_line(l_logmessage);
8592                       EXCEPTION
8593                           when TOO_MANY_ROWS then
8594                               x_contact_party_id := null;
8595                               x_contact_type := null;
8596                               x_contact_point_id := null;
8597                               x_contact_point_type := null;
8598                              l_logmessage:='cotanct_name fetch returned too many rows'|| SQL%ROWCOUNT;
8599                              iem_logger(l_logmessage);
8600                                           --dbms_output.put_line(l_logmessage);
8601                           when NO_DATA_FOUND then
8602                              l_logmessage:='cotanct_name fetch returned 0 rows'|| SQL%ROWCOUNT;
8603                              iem_logger(l_logmessage);
8604                                           --dbms_output.put_line(l_logmessage);
8605                           when others then
8606                              l_logmessage:='cotanct_name other exception';
8607                              iem_logger(l_logmessage);
8608                                           --dbms_output.put_line(l_logmessage);
8609                       END;
8610 
8611                      --run the queries to get values
8612                    ELSIF (contact_rec.column_name = 'CONTACT_EMAIL') THEN
8613                         BEGIN
8614                           Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8615 		          into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8616                           from hz_contact_points a,hz_relationships b, hz_parties c
8617                           where a.owner_table_name='HZ_PARTIES'
8618                           and a.contact_point_type = 'EMAIL'
8619                           and a.status='A'
8620                           and a.owner_table_id = b.party_id
8621                           and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8622      	 					  where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8623 	                  and b.party_id = c.party_id
8624                          -- and upper(c.party_name) =upper(p_contact_name)
8625                           and b.object_id in (select party_id from hz_parties where upper(party_name) =upper(p_contact_name))
8626                           and upper(c.email_address) = upper(p_contact_email)
8627 	                  and b.subject_id = g_customer_id;
8628                              l_logmessage:='cotanct_name-email'||p_contact_name||'--partyid:'||x_contact_party_id||'point_id'||x_contact_point_id ;
8629                                iem_logger(l_logmessage);
8630                                --dbms_output.put_line(l_logmessage);
8631                          EXCEPTION
8632                             when TOO_MANY_ROWS then
8633                               x_contact_party_id := null;
8634                               x_contact_type := null;
8635                               x_contact_point_id := null;
8636                               x_contact_point_type := null;
8637                                l_logmessage:='cotanct_name fetch returned too many rows'|| SQL%ROWCOUNT;
8638                                iem_logger(l_logmessage);
8639                                               --dbms_output.put_line(l_logmessage);
8640                             when NO_DATA_FOUND then
8641                                l_logmessage:='cotanct_name fetch returned 0 rows'|| SQL%ROWCOUNT;
8642                                iem_logger(l_logmessage);
8643                                               --dbms_output.put_line(l_logmessage);
8644                             when others then
8645                                l_logmessage:='cotanct_name other exception';
8646                                iem_logger(l_logmessage);
8647                                               --dbms_output.put_line(l_logmessage);
8648                          END;
8649                     END IF;  --end if of contact_Column name checl
8650                 --exit out of the loop if x_contact_party_id was found
8651                 EXIT WHEN x_contact_party_id IS NOT NULL;
8652                 END IF; --end if of x_contact_party_id check
8653              END LOOP;
8654 
8655             ---after going throug the loop if the x_contact_party_id was not populated then try alone
8656             -- wit the p_Contact_name information
8657             IF x_contact_party_id IS NULL THEN
8658                   BEGIN
8659                       Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8660 		      into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8661                       from hz_contact_points a,hz_relationships b, hz_parties c
8662                       where a.owner_table_name='HZ_PARTIES'
8663                       and a.status='A'
8664                       and a.primary_flag = 'Y'
8665                       and a.owner_table_id = b.party_id
8666                       and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8667      	 			  where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8668 	               and b.party_id = c.party_id
8669                        and b.object_id in (select party_id from hz_parties where upper(party_name) =upper(p_contact_name))
8670                        --and upper(c.party_name) =upper(p_contact_name)
8671 	               and b.subject_id = g_customer_id;
8672                           l_logmessage:='cotanct_name-alone'||p_contact_name||'--partyid:'||x_contact_party_id||'point_id'||x_contact_point_id ;
8673                                iem_logger(l_logmessage);
8674                                --dbms_output.put_line(l_logmessage);
8675                   EXCEPTION
8676                           when TOO_MANY_ROWS then
8677                               x_contact_party_id := null;
8678                               x_contact_type := null;
8679                               x_contact_point_id := null;
8680                               x_contact_point_type := null;
8681                              l_logmessage:='cotanct_name fetch returned too many rows'|| SQL%ROWCOUNT;
8682                              iem_logger(l_logmessage);
8683                                           --dbms_output.put_line(l_logmessage);
8684                           when NO_DATA_FOUND then
8685                              l_logmessage:='cotanct_name fetch returned 0 rows'|| SQL%ROWCOUNT;
8686                              iem_logger(l_logmessage);
8687                                           --dbms_output.put_line(l_logmessage);
8688                           when others then
8689                              l_logmessage:='cotanct_name other exception';
8690                              iem_logger(l_logmessage);
8691                                           --dbms_output.put_line(l_logmessage);
8692                   END;
8693             END IF;
8694         END IF; --end if of of contact_id processing
8695   END getContactName;
8696 
8697 
8698 
8699   --Qestion: check the parent_id = contact_point_id match
8700   --primary flag is not a required filed for the sr contact rec type
8701   --Note we should not call this procedure if the account type is of internal
8702   --and we should pass the contact_id and contact_point_id that is passed by the
8703   --calling api
8704   Procedure getContactPhone (p_contact_phone IN VARCHAR2,
8705                              x_contact_party_id  OUT NOCOPY NUMBER,
8706                              x_contact_type      OUT NOCOPY VARCHAR2,
8707                              x_contact_point_type      OUT NOCOPY VARCHAR2,
8708                              x_contact_point_id  OUT NOCOPY NUMBER)
8709   IS
8710     l_phone_count number;
8711     l_logmessage		varchar2(2000):=' ';
8712   BEGIN
8713 
8714      --part_role_code is a required field for contact SR information
8715      --there for populating it.
8716      IF (g_contact_party_id IS NULL)  THEN
8717            BEGIN
8718                   Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8719 		  into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8720                   from hz_contact_points a,hz_relationships b, hz_parties c
8721                   where a.owner_table_name='HZ_PARTIES'
8722                   and  a.contact_point_type='PHONE'
8723                   and a.status='A'
8724                   and a.owner_table_id = b.party_id
8725                   and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8726      	 					  where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8727 	          and b.party_id = c.party_id
8728                   and reverse(a.transposed_phone_number)=REGEXP_REPLACE(p_contact_phone,'([[:punct:]|[:space:]]*)')
8729 	          and b.subject_id = g_customer_id;
8730             EXCEPTION
8731                  when TOO_MANY_ROWS then
8732                               x_contact_party_id := null;
8733                               x_contact_type := null;
8734                               x_contact_point_id := null;
8735                               x_contact_point_type := null;
8736                       l_logmessage:='cotanct_phone fetch returned too many rows'|| SQL%ROWCOUNT;
8737                       iem_logger(l_logmessage);
8738                             --dbms_output.put_line(l_logmessage);
8739                  when NO_DATA_FOUND then
8740                       l_logmessage:='cotanct_phone fetch returned 0 rows'|| SQL%ROWCOUNT;
8741                       iem_logger(l_logmessage);
8742                             --dbms_output.put_line(l_logmessage);
8743                  when others then
8744                        l_logmessage:='cotanct_phone other exception';
8745                       iem_logger(l_logmessage);
8746                             --dbms_output.put_line(l_logmessage);
8747              END;
8748      END IF;
8749   END getContactPhone;
8750 
8751 
8752   Procedure getContactEmail (p_contact_email IN VARCHAR2,
8753                              x_contact_party_id  OUT NOCOPY NUMBER,
8754                              x_contact_type      OUT NOCOPY VARCHAR2,
8755                              x_contact_point_type      OUT NOCOPY VARCHAR2,
8756                              x_contact_point_id  OUT NOCOPY NUMBER)
8757   IS
8758     l_email_count number;
8759     l_logmessage		varchar2(2000):=' ';
8760   BEGIN
8761 
8762      IF (g_contact_party_id IS NULL)  THEN
8763            BEGIN
8764                   Select c.party_id, c.party_type,  a.contact_point_id, a.contact_point_type
8765 		  into x_contact_party_id, x_contact_type, x_contact_point_id, x_contact_point_type
8766                   from hz_contact_points a,hz_relationships b, hz_parties c
8767                   where a.owner_table_name='HZ_PARTIES'
8768                   and  a.contact_point_type='EMAIL'
8769                   and a.status='A'
8770                   and a.owner_table_id = b.party_id
8771                   and a.contact_point_id not in  (select contact_level_table_id from HZ_CONTACT_PREFERENCES
8772      	 					  where contact_level_table='HZ_CONTACT_POINTS' and status='A')
8773 	          and b.party_id = c.party_id
8774                   and upper(a.email_address)=upper(p_contact_email)
8775 	          and b.subject_id = g_customer_id;
8776             EXCEPTION
8777                  when TOO_MANY_ROWS then
8778                               x_contact_party_id := null;
8779                               x_contact_type := null;
8780                               x_contact_point_id := null;
8781                               x_contact_point_type := null;
8782                       l_logmessage:='cotanct_email fetch returned too many rows'|| SQL%ROWCOUNT;
8783                       iem_logger(l_logmessage);
8784                             --dbms_output.put_line(l_logmessage);
8785                  when NO_DATA_FOUND then
8786                     l_logmessage:='cotanct_email fetch returned 0 rows'|| SQL%ROWCOUNT || 'email is:'||p_contact_email||'cust_id:'||g_customer_id;
8787                       iem_logger(l_logmessage);
8788                             --dbms_output.put_line(l_logmessage);
8789                  when others then
8790                        l_logmessage:='cotanct_email other exception';
8791                       iem_logger(l_logmessage);
8792                             --dbms_output.put_line(l_logmessage);
8793              END;
8794       END IF;
8795 
8796   END getContactEmail;
8797 
8798   --inventory stuff
8799   Procedure getInventoryItemName (p_inventory_item_name IN VARCHAR2,
8800                                   x_inventory_item_id OUT NOCOPY NUMBER,
8801                                   x_inventory_org_id OUT NOCOPY NUMBER)
8802   IS
8803     l_inventory_count number;
8804     l_logmessage		varchar2(2000):=' ';
8805   BEGIN
8806 
8807      BEGIN
8808        select DISTINCT inventory_item_id, organization_id
8809        into x_inventory_item_id, x_inventory_org_id
8810        from mtl_system_items_b
8811        where organization_id=FND_PROFILE.value('CS_INV_VALIDATION_ORG') and
8812        upper(segment1)= upper(p_inventory_item_name);
8813 
8814        l_logmessage:='inventoryItemName is '||p_inventory_item_name||' inventory_item_id is '|| x_inventory_item_id;
8815        iem_logger(l_logmessage);
8816        --dbms_output.put_line(l_logmessage);
8817        l_logmessage:='inventoryItemName is '||p_inventory_item_name||' inventory_org_id is '|| x_inventory_org_id;
8818        iem_logger(l_logmessage);
8819        --dbms_output.put_line(l_logmessage);
8820      EXCEPTION
8821          when TOO_MANY_ROWS then
8822               x_inventory_item_id := null;
8823               x_inventory_org_id  := null;
8824               l_logmessage:='inventoryItemName fetch returned too many rows'|| SQL%ROWCOUNT;
8825               iem_logger(l_logmessage);
8826               --dbms_output.put_line(l_logmessage);
8827          when NO_DATA_FOUND then
8828               l_logmessage:='inventoryItemName fetch returned 0 rows'|| SQL%ROWCOUNT;
8829               iem_logger(l_logmessage);
8830             --dbms_output.put_line(l_logmessage);
8831          when others then
8832               l_logmessage:='inventoryItemName other exception';
8833               iem_logger(l_logmessage);
8834                 --dbms_output.put_line(l_logmessage);
8835      END;
8836 
8837   END getInventoryItemName;
8838   --end of inventory related stuff
8839 
8840 
8841   --get service request type and if no type is found get the default
8842   --type from the calling program to use it.
8843   PROCEDURE getServiceRequestType (p_service_request_type IN VARCHAR2,
8844                                    p_default_type_id      IN NUMBER,
8845 	                           x_type_id              OUT NOCOPY NUMBER)
8846   IS
8847    l_type_id number;
8848    l_return_status varchar2(10);
8849    l_logmessage		varchar2(2000):=' ';
8850   BEGIN
8851     --Validate against CS_ServiceRequest_UTIL.Convert_Type_To_ID Where pass subtype='INC'
8852     CS_ServiceRequest_UTIL.Convert_Type_To_ID (
8853         p_api_name             => 'Advanced_SR_PROCESSING.GETSERVICEREQUESTTYPE',
8854 	p_parameter_name       => 'LOOKUP_TYPE',
8855         p_type_name            => p_service_request_type,
8856         p_subtype              => 'INC',
8857         p_parent_type_id       => FND_API.G_MISS_NUM,
8858         p_type_id              => l_type_id,
8859         x_return_status        => l_return_status);
8860 
8861     IF (l_return_status = FND_API.G_RET_STS_SUCCESS) THEN
8862          x_type_id := l_type_id;
8863            l_logmessage:='sr_type_id found sr_type_id :'||l_type_id;
8864            iem_logger(l_logmessage);
8865            --dbms_output.put_line(l_logmessage);
8866     ELSE
8867         --use the default type id
8868          x_type_id := p_default_type_id;
8869            l_logmessage:='sr_type_id not found using default type id :'||p_default_type_id;
8870            iem_logger(l_logmessage);
8871            --dbms_output.put_line(l_logmessage);
8872     END IF;
8873   END getServiceRequestType;
8874 
8875 
8876  Procedure getProblemCode (p_problem_code in VARCHAR2,
8877                            x_problem_code OUT NOCOPY VARCHAR2)
8878   IS
8879     l_code_count NUMBER;
8880     l_logmessage		varchar2(2000):=' ';
8881   BEGIN
8882      select count(problem_code) into l_code_count
8883      from cs_sr_prob_code_mapping_detail
8884      where problem_code = p_problem_code;
8885 
8886      l_logmessage:='problemcode rowcount for'|| p_problem_code ||' returned count'|| l_code_count;
8887      iem_logger(l_logmessage);
8888      --dbms_output.put_line(l_logmessage);
8889 
8890      --the code exisit in the system
8891      IF l_code_count >0 THEN
8892         x_problem_code := p_problem_code;
8893      ELSE
8894         x_problem_code := null;
8895      END IF;
8896   EXCEPTION
8897          when TOO_MANY_ROWS then
8898               l_logmessage:='problemcode fetch returned too many rows'|| SQL%ROWCOUNT;
8899               iem_logger(l_logmessage);
8900     --dbms_output.put_line(l_logmessage);
8901          when NO_DATA_FOUND then
8902               l_logmessage:='problemcode fetch returned 0 rows'|| SQL%ROWCOUNT;
8903           iem_logger(l_logmessage);
8904     --dbms_output.put_line(l_logmessage);
8905          when others then
8906               l_logmessage:='problemcode other exception';
8907           iem_logger(l_logmessage);
8908     --dbms_output.put_line(l_logmessage);
8909 
8910   END getProblemCode;
8911 
8912   Procedure getUrgency (p_urgency IN VARCHAR2,
8913   	                x_urgency_id OUT NOCOPY NUMBER)
8914   IS
8915    l_urgency_id number;
8916    l_return_status VARCHAR2(10);
8917    l_logmessage		varchar2(2000):=' ';
8918   BEGIN
8919    --  Validate against CS_ServiceRequest_UTIL. Convert_Urgency_To_ID
8920     CS_ServiceRequest_UTIL.Convert_Urgency_To_ID
8921       ( p_api_name            => 'ADVANCED_SR_PROCESSING.GETURGENCY',
8922         p_parameter_name      => 'Urgency Name',
8923         p_urgency_name        => p_urgency,
8924         p_urgency_id          => l_urgency_id,
8925         x_return_status       => l_return_status);
8926 
8927      IF l_return_status = FND_API.G_RET_STS_SUCCESS THEN
8928         x_urgency_id := l_urgency_id;
8929      END IF;
8930 
8931   END getUrgency;
8932 
8933   Procedure getSiteName(p_site_name      IN VARCHAR2,
8934                         x_party_site_id  OUT NOCOPY NUMBER)
8935   IS
8936     l_site_count NUMBER;
8937      l_logmessage		varchar2(2000):=' ';
8938   BEGIN
8939     IF (g_customer_id IS NOT NULL) THEN
8940         BEGIN
8941           select party_site_id into x_party_site_id
8942           from hz_party_sites
8943           where upper(party_site_name) = upper(p_site_name)
8944           and party_id = g_customer_id;
8945         EXCEPTION
8946           when TOO_MANY_ROWS then
8947                x_party_site_id := null;
8948               l_logmessage:='inventoryItemName fetch returned too many rows'|| SQL%ROWCOUNT;
8949           iem_logger(l_logmessage);
8950     --dbms_output.put_line(l_logmessage);
8951           when NO_DATA_FOUND then
8952               l_logmessage:='inventoryItemName fetch returned 0 rows'|| SQL%ROWCOUNT;
8953           iem_logger(l_logmessage);
8954     --dbms_output.put_line(l_logmessage);
8955           when others then
8956               l_logmessage:='inventoryItemName other exception';
8957           iem_logger(l_logmessage);
8958     --dbms_output.put_line(l_logmessage);
8959         END;
8960     END IF;
8961   END getSiteName;
8962 
8963   --initially we had decided that we will call the utilpackage.Validate_External_Reference
8964   --to ensure weather a valid ext_ref was passed. However the util procedure expects a
8965   --lot of values to do that particuualr validation and since we dont have all the attributes
8966   --to be passed to the util package; we will validate the ext ref passed with the
8967   --csi_item_instance table only. The other thing to keep in mind is that the UTIL procdure
8968   --is not checking the case during its validation
8969   Procedure getExtReference(p_ext_ref               IN VARCHAR2,
8970                             p_customer_product_id   IN NUMBER,
8971                             x_ext_ref               OUT NOCOPY VARCHAR2)
8972    IS
8973     l_ext_ref_count NUMBER;
8974      l_logmessage		varchar2(2000):=' ';
8975    BEGIN
8976    --took out the if condition and will let the api handle any errors
8977     --IF (p_customer_product_id is not null) THEN
8978         --we will just do a simple validation for ext_Ref_item and if it exists
8979         --then we will just pass it to the SR API and the let the SR api handle
8980         --additional validation.
8981         select count(external_reference) into l_ext_ref_count
8982         from   csi_item_instances
8983         where  upper(external_reference) = upper(p_ext_ref);
8984         --where instance_id = p_customer_product_id
8985          l_logmessage:='external reference count for '|| p_ext_Ref||' is '||l_ext_ref_count;
8986          iem_logger(l_logmessage);
8987          --dbms_output.put_line(l_logmessage);
8988 
8989 
8990         IF l_ext_ref_count >0 THEN
8991           x_ext_ref := p_ext_ref;
8992         END IF;
8993 
8994    -- END IF;
8995 
8996     --signature of util prcodeure which is not being called due to the extensive
8997     --requirement of the attributes
8998     /*
8999     Validate_External_Reference(
9000     p_api_name			     IN  VARCHAR2,
9001     p_parameter_name		 IN  VARCHAR2,
9002     p_external_reference     IN  VARCHAR2,
9003     p_customer_product_id    IN  NUMBER,
9004     p_inventory_item_id      IN  NUMBER   := NULL,
9005     p_inventory_org_id       IN  NUMBER   := NULL,
9006     p_customer_id            IN NUMBER    := NULL,
9007     x_return_status			 OUT  NOCOPY VARCHAR2
9008     */
9009    END getExtReference;
9010 
9011 
9012 
9013 --siahmed
9014 -- this is for bug 12663292
9015 -- where we are trying to get the bill_to and ship_to information
9016   Procedure getBillToShipTo(p_customer_id           IN NUMBER,
9017                             p_contact_party_id      IN NUMBER,
9018                             x_bill_to_site_id    OUT NOCOPY NUMBER,
9019                             x_ship_to_site_id    OUT NOCOPY NUMBER,
9020                              x_account_id         OUT NOCOPY NUMBER
9021                             )
9022    IS
9023      l_logmessage		varchar2(2000):=' ';
9024    BEGIN
9025 
9026      --set the status to E and only change to S after its a success
9027 
9028 
9029       --addd  validation for getting x_account_id
9030       BEGIN
9031         select cust_account_id into x_account_id
9032         from   hz_cust_accounts
9033         where    party_id = p_customer_id
9034         AND   status = 'A';
9035 
9036          l_logmessage:='cust_account_id id is: '|| x_account_id ;
9037          iem_logger(l_logmessage);
9038          --dbms_output.put_line(l_logmessage);
9039 
9040      EXCEPTION
9041           when TOO_MANY_ROWS then
9042                x_account_id := null;
9043               l_logmessage:=' fetch returned too many rows for cust_account_id'|| SQL%ROWCOUNT;
9044               iem_logger(l_logmessage);
9045               --dbms_output.put_line(l_logmessage);
9046           when NO_DATA_FOUND then
9047                x_account_id := null;
9048               l_logmessage:='x_account_id fetch returned 0 rows'|| SQL%ROWCOUNT;
9049               iem_logger(l_logmessage);
9050                 --dbms_output.put_line(l_logmessage);
9051           when others then
9052                x_account_id := null;
9053               l_logmessage:='x_account_id other exception';
9054               iem_logger(l_logmessage);
9055               --dbms_output.put_line(l_logmessage);
9056 
9057     END;
9058 
9059 
9060     BEGIN
9061         SELECT s.party_site_id into x_bill_to_site_id
9062              FROM hz_party_sites s,
9063                hz_parties p,
9064                hz_locations l,
9065                hz_party_site_uses u
9066              WHERE p.party_id = p_customer_id
9067               AND p.party_id = s.party_id
9068               AND s.status = 'A'
9069               AND s.location_id = l.location_id
9070               AND s.party_site_id = u.party_site_id
9071               AND u.site_use_type = 'BILL_TO'
9072               AND u.primary_per_type = 'Y'
9073               AND u.status = 'A';
9074 
9075 
9076          l_logmessage:='billtosite id is: '|| x_bill_to_Site_id ;
9077          iem_logger(l_logmessage);
9078          --dbms_output.put_line(l_logmessage);
9079 
9080      EXCEPTION
9081           when TOO_MANY_ROWS then
9082                x_bill_to_site_id := null;
9083                x_ship_to_site_id := null;
9084               l_logmessage:=' fetch returned too many rows for bill_to_site_id'|| SQL%ROWCOUNT;
9085              iem_logger(l_logmessage);
9086              --dbms_output.put_line(l_logmessage);
9087           when NO_DATA_FOUND then
9088               l_logmessage:='bill_to_Site_id fetch returned 0 rows'|| SQL%ROWCOUNT;
9089              iem_logger(l_logmessage);
9090              --dbms_output.put_line(l_logmessage);
9091           when others then
9092               l_logmessage:='bill_to_site_id other exception';
9093              iem_logger(l_logmessage);
9094              --dbms_output.put_line(l_logmessage);
9095 
9096     END;
9097 
9098     BEGIN
9099       SELECT s.party_site_id into x_ship_to_site_id
9100              FROM hz_party_sites s,
9101                hz_parties p,
9102                hz_locations l,
9103                hz_party_site_uses u
9104              WHERE p.party_id = p_customer_id
9105               AND p.party_id = s.party_id
9106               AND s.status = 'A'
9107               AND s.location_id = l.location_id
9108               AND s.party_site_id = u.party_site_id
9109               AND u.site_use_type = 'SHIP_TO'
9110               AND u.primary_per_type = 'Y'
9111               AND u.status = 'A';
9112 
9113 
9114          l_logmessage:='ship_to_site_id is:' || x_ship_to_Site_id;
9115          iem_logger(l_logmessage);
9116          --dbms_output.put_line(l_logmessage);
9117 
9118      EXCEPTION
9119           when TOO_MANY_ROWS then
9120                x_bill_to_site_id := null;
9121                x_ship_to_site_id := null;
9122               l_logmessage:=' fetch returned too many rows for ship_to_site_id'|| SQL%ROWCOUNT;
9123              iem_logger(l_logmessage);
9124     --dbms_output.put_line(l_logmessage);
9125           when NO_DATA_FOUND then
9126               l_logmessage:='ship_to_Site_id fetch returned 0 rows'|| SQL%ROWCOUNT;
9127              iem_logger(l_logmessage);
9128              --dbms_output.put_line(l_logmessage);
9129           when others then
9130               l_logmessage:='ship_to_site_id other exception';
9131              iem_logger(l_logmessage);
9132              --dbms_output.put_line(l_logmessage);
9133      END;
9134 
9135       l_logmessage:=' x_bill_to_Site: '|| x_bill_to_Site_id ||' x_ship_to_site_id:'|| x_ship_to_site_id ||' x_bill_ship_account_id:'||x_account_id;
9136       iem_logger(l_logmessage);
9137       --dbms_output.put_line(l_logmessage);
9138 
9139 
9140    END getBillToShipTo;
9141 
9142 -- end for bug 12663292
9143 
9144 
9145 
9146 
9147   FUNCTION GET_TAG_DATA
9148   ( p_start_tag   IN VARCHAR2,
9149     p_end_tag     IN VARCHAR2,
9150     p_message_id  IN NUMBER
9151    ) return VARCHAR2
9152   IS
9153     l_start_pos number;
9154     l_end_pos   number;
9155     l_length    number;
9156     l_body      varchar2(32000);
9157     l_start_tag VARCHAR2(300);
9158     l_end_tag   VARCHAR2(300);
9159     l_token     varchar2(5000);
9160     l_logmessage		varchar2(2000):=' ';
9161 
9162     cursor c_msg_body (l_message_id IN NUMBER)
9163     IS
9164     select upper(value) email
9165     from IEM_MS_MSGBODYS
9166     where message_id = l_message_id
9167     order by order_id asc;
9168   BEGIN
9169 
9170     l_logmessage:='tag processing ';
9171           iem_logger(l_logmessage);
9172     --dbms_output.put_line(l_logmessage);
9173     l_logmessage:='message_id '|| p_message_id ;
9174           iem_logger(l_logmessage);
9175     --dbms_output.put_line(l_logmessage);
9176     --get the body
9177     for msg in c_msg_body(p_message_id)
9178     LOOP
9179      l_body:= l_body || msg.email;
9180     END LOOP;
9181 
9182     --set everything to uppercase to prevent case validation run time error
9183     l_start_tag := upper(p_start_tag);
9184     l_end_tag := upper(p_end_tag);
9185 
9186     --get the start position for for the tag
9187     l_start_pos := INSTR(l_body,l_start_tag);
9188 
9189     --get the first occurance of the end position of the tag
9190     l_end_pos := INSTR(l_body,l_end_tag,l_start_pos,1);
9191 
9192     --get the length between the start and the end position.
9193     l_length := l_end_pos - l_start_pos;
9194 
9195     --get all the characters starting from the start tag till the starting of the end tag
9196     --note this includes the start tag
9197     l_token := SUBSTR(l_body,l_start_pos,l_length);
9198 
9199     --since we grabbed everything including the start tag
9200     --we need to replace the start tag with blank to get the raw value of the tag data
9201     l_token := REPLACE(l_token,l_start_tag,'');
9202 
9203     --trim the text so that leading and trailing spaces are taken out.
9204     l_token := TRIM(l_token);
9205 
9206     l_logmessage:='start_tag '|| l_Start_tag ;
9207           iem_logger(l_logmessage);
9208     --dbms_output.put_line(l_logmessage);
9209     l_logmessage:='end tag '|| l_end_tag ;
9210           iem_logger(l_logmessage);
9211     --dbms_output.put_line(l_logmessage);
9212     l_logmessage:='value '|| l_token ;
9213           iem_logger(l_logmessage);
9214     --dbms_output.put_line(l_logmessage);
9215     -- return the trimmed information to the calling program
9216     return l_token;
9217 
9218   END GET_TAG_DATA;
9219 
9220 
9221 --siahmed end of 12.1.3 advanced sr processing
9222 
9223 end IEM_EMAIL_PROC_PVT;