DBA Data[Home] [Help]

PACKAGE BODY: APPS.PO_COMMUNICATION_PVT

Source


1 PACKAGE BODY PO_COMMUNICATION_PVT AS
2 /* $Header: POXVCOMB.pls 120.107.12020000.8 2013/03/22 10:42:14 inagdeo ship $ */
3 
4 -- Read the profile option that enables/disables the debug log
5   g_po_wf_debug VARCHAR2(1) := NVL(FND_PROFILE.VALUE('PO_SET_DEBUG_WORKFLOW_ON'), 'N');
6   G_PKG_NAME CONSTANT VARCHAR2(30) := 'PO_COMMUNICATION_PVT';
7   g_log_head CONSTANT VARCHAR2(30) := 'po.plsql.PO_COMMUNICATION_PVT.';
8   g_ship_cont_phone VARCHAR2(200);
9   g_ship_cont_email VARCHAR2(2000);
10   g_deliver_cont_phone VARCHAR2(200);
11   g_deliver_cont_email VARCHAR2(2000);
12   g_ship_cont_name VARCHAR2(400);
13   g_deliver_cont_name VARCHAR2(400);
14   g_ship_cust_name VARCHAR2(400);
15   g_ship_cust_location VARCHAR2(2000);
16   g_deliver_cust_name VARCHAR2(400);
17   g_deliver_cust_location VARCHAR2(2000);
18   g_ship_contact_fax VARCHAR2(200);
19   g_deliver_contact_name VARCHAR2(400);
20   g_deliver_contact_fax VARCHAR2(200);
21   g_shipping_method VARCHAR2(240);
22   g_shipping_instructions VARCHAR2(2000);
23   g_packing_instructions VARCHAR2(2000);
24   g_customer_product_desc VARCHAR2(1000);
25   g_customer_po_number VARCHAR2(50);
26   g_customer_po_line_num VARCHAR2(50);
27   g_customer_po_shipment_num VARCHAR2(50);
28   g_document_id NUMBER;
29   g_revision_num NUMBER;
30   g_vendor_id PO_HEADERS_ALL.vendor_id%type;
31   g_cover_message VARCHAR2(2001);
32   g_amendment_message VARCHAR2(2001);
33   g_test_flag VARCHAR2(1);
34   g_release_header_id PO_HEADERS_ALL.po_header_id%type;
35   g_location_id number;
36   g_address_line1 HR_LOCATIONS.ADDRESS_LINE_1%type := null;
37   g_address_line2 HR_LOCATIONS.ADDRESS_LINE_2%type := null;
38   g_address_line3 HR_LOCATIONS.ADDRESS_LINE_3%type := null;
39   g_Territory_short_name FND_TERRITORIES_TL.TERRITORY_SHORT_NAME%type := null;
40   g_address_info varchar2(500) := null;
41   g_org_id PO_HEADERS_ALL.ORG_ID%type := null;
42 
43 -- Global variables to hold the Operating Unit details --
44   g_ou_name HR_ORGANIZATION_UNITS_V.NAME%type := null;
45   g_ou_address_line_1 HR_ORGANIZATION_UNITS_V.ADDRESS_LINE_1 %type := null;
46   g_ou_address_line_2 HR_ORGANIZATION_UNITS_V.ADDRESS_LINE_2%type := null;
47   g_ou_address_line_3 HR_ORGANIZATION_UNITS_V.ADDRESS_LINE_3%type := null;
48   g_ou_town_or_city HR_ORGANIZATION_UNITS_V.TOWN_OR_CITY%type := null;
49   g_ou_region2 HR_ORGANIZATION_UNITS_V.REGION_1%type := null;
50   g_ou_postal_code HR_ORGANIZATION_UNITS_V.POSTAL_CODE%type := null;
51   g_ou_country HR_ORGANIZATION_UNITS_V.COUNTRY%type := null;
52 -- End of Operation Unit detail variables --
53 
54   g_header_id PO_HEADERS_ALL.PO_HEADER_ID%type := null;
55   g_quote_number PO_HEADERS_ALL.QUOTE_VENDOR_QUOTE_NUMBER%type := null;
56   g_agreement_number PO_HEADERS_ALL.SEGMENT1%type := null;
57   g_agreement_flag PO_HEADERS_ALL.GLOBAL_AGREEMENT_FLAG%type := null;
58   g_agreementLine_number PO_LINES_ALL.LINE_NUM%type := null;
59   g_line_id PO_LINES_ALL.FROM_LINE_ID%type := null;
60   g_arcBuyer_fname PER_ALL_PEOPLE_F.FIRST_NAME%type := null;
61   g_arcBuyer_lname PER_ALL_PEOPLE_F.LAST_NAME%type := null;
62   g_arcBuyer_title PER_ALL_PEOPLE_F.TITLE%type := null;
63   g_arcAgent_id PO_HEADERS_ARCHIVE_ALL.AGENT_ID%type := null;
64   g_header_id1 PO_HEADERS_ALL.PO_HEADER_ID%type := null;
65   g_release_id PO_RELEASES_ALL.PO_RELEASE_ID%type := null;
66   g_timezone VARCHAR2(255) := NULL;
67   g_vendor_address_line_2 PO_VENDOR_SITES.ADDRESS_LINE2%type := null;
68   g_vendor_address_line_3 PO_VENDOR_SITES.ADDRESS_LINE3%type := null;
69   g_vendor_country FND_TERRITORIES_TL.TERRITORY_SHORT_NAME%type := null;
70   g_vendor_city_state_zipInfo varchar2(500) := null;
71   g_vendor_site_id PO_HEADERS_ALL.vendor_site_id%type := null;
72   g_job_id PO_LINES_ALL.JOB_ID%type := null;
73   g_job_name PER_JOBS_VL.name%type := null;
74   g_phone HR_LOCATIONS.TELEPHONE_NUMBER_1%type := null;
75 --Bug 4504228 START
76   g_person_id PER_ALL_PEOPLE_F.PERSON_ID%type := null;
77   g_buyer_email_address PER_ALL_PEOPLE_F.EMAIL_ADDRESS%type := null;
78   g_buyer_phone PER_ALL_PEOPLE_F.office_number%type := null;
79 --Bug 4504228 END
80   g_buyer_fax HR_LOCATIONS.TELEPHONE_NUMBER_2%type := null; --Bug5671523 Adding g_buyer_fax
81   g_fax HR_LOCATIONS.TELEPHONE_NUMBER_2%type := null;
82   g_location_name HR_LOCATIONS.LOCATION_CODE%type := null;
83   g_documentType PO_DOCUMENT_TYPES_TL.TYPE_NAME%type;
84   g_currency_code PO_HEADERS_ALL.CURRENCY_CODE%type := null;
85   g_current_currency_code PO_HEADERS_ALL.CURRENCY_CODE%type := null;
86   g_format_mask varchar2(100) := null;
87   g_buyer_org HR_ALL_ORGANIZATION_UNITS.NAME%type := NULL;
88   g_address_line4 HZ_LOCATIONS.ADDRESS4%TYPE := NULL; -- bug: 3463617
89   g_vendor_address_line_4 HZ_LOCATIONS.ADDRESS4%TYPE := NULL; -- bug: 3463617
90 --bug#3438608 added the three global variables g_town_or_city
91 --g_postal_code and g_state_or_province
92 /*Begin Edit Akyanama Bug # 11062630 */
93 /*Increased variable g_town_or_city , g_postal_code limit from
94   hr_locations.town_or_city or hr_locations.postal_code (30) to varchar2(100) */
95   g_town_or_city varchar2(100) := NULL;
96   g_postal_code varchar2(100) := NULL;
97   g_state_or_province varchar2(100) := NULL;
98 /*End Edit Akyanama Bug # 11062630 */
99 --Start of global variables to hold the legal entity details --
100 
101   g_legal_entity_name HR_ORGANIZATION_UNITS_V.NAME%type := null;
102   g_legal_entity_address_line_1 HR_LOCATIONS.ADDRESS_LINE_1 %type := null;
103   g_legal_entity_address_line_2 HR_LOCATIONS.ADDRESS_LINE_2%type := null;
104   g_legal_entity_address_line_3 HR_LOCATIONS.ADDRESS_LINE_3%type := null;
105   g_legal_entity_town_or_city HR_LOCATIONS.TOWN_OR_CITY%type := null;
106   g_legal_entity_state HR_LOCATIONS.REGION_1%type := null;
107   g_legal_entity_postal_code HR_LOCATIONS.POSTAL_CODE%type := null;
108   g_legal_entity_country FND_TERRITORIES_TL.TERRITORY_SHORT_NAME%type := null;
109   g_legal_entity_org_id PO_HEADERS_ALL.ORG_ID%type := null;
110 
111 -- End of Legal Entity details ----
112 
113   g_dist_shipto_count number := NULL ; -- Variable which holds count of distinct shipment ship to ids
114   g_line_org_amount number := NULL;
115 
116 /*Bug#35833910 the variable determines whether the po has Terms and Conditions */
117   g_with_terms po_headers_all.conterms_exist_flag%type;
118 
119 -- <Bug 3619689 Start> Use proper debug logging
120   g_debug_stmt CONSTANT BOOLEAN := PO_DEBUG.is_debug_stmt_on;
121   g_debug_unexp CONSTANT BOOLEAN := PO_DEBUG.is_debug_unexp_on;
122 -- <Bug 3619689 End>
123 
124   g_documentName varchar2(200) := null; --bug#3630737:Holds concatinated value of DocumentType, po number and revision number
125 
126 --Start Bug#3771735
127   g_documentTypeCode PO_DOCUMENT_TYPES_TL.DOCUMENT_TYPE_CODE%type;
128 --End Bug#3771735
129 
130 -- Bug 4026592
131   g_is_contract_attached_doc varchar2(1);
132 
133 
134 -- <Complex Work R12 Start>
135   g_is_complex_work_po VARCHAR2(1);
136 
137 --Bug 4568471/6829381
138   g_is_one_time_location varchar2(2) := 'N';
139 
140   PROCEDURE setIsComplexWorkPO(
141                                p_document_id IN NUMBER
142                                , p_revision_num IN NUMBER DEFAULT NULL
143                                , p_which_tables IN VARCHAR2 DEFAULT 'MAIN'
144                                );
145 -- <Complex Work R12 End>
146 
147 
148 -- <Word Integration 11.5.10+: Forward declare helper function>
149   FUNCTION getDocFileName(p_document_type varchar2,
150                           p_terms varchar2,
151                           p_orgid number,
152                           p_document_id varchar2,
153                           p_revision_num number,
154                           p_draft_id number, --CLM
155                           p_language_code varchar2,
156                           p_extension varchar2,
157 			  p_is_conf_doc varchar2 default 'N') RETURN varchar2;
158 
159 
160 /*=======================================================================+
161  | FILENAME
162  |   POXVCOMB.pls
163  |
164  | DESCRIPTION
165  |   PL/SQL body for package:  PO_COMMUNICATION_PVT
166  |
167  | NOTES        VSANJAY Created  08/07/2003
168  | MODIFIED    (MM/DD/YY)
169  | VSANJAY      08/07/2003
170  | AMRITUNJ     09/29/2003   - API Change and added commit after fnd_request.submit_request
171  |                            As specified in AOL standards guide for concurrent request API
172  |                            It can have side effects. For more info, search for COMMIT_NOTE
173  |                            in this file.
174  *=======================================================================*/
175 
176   PROCEDURE GENERATE_PDF (itemtype IN VARCHAR2,
177                           itemkey IN VARCHAR2,
178                           actid IN NUMBER,
179                           funcmode IN VARCHAR2,
180                           resultout OUT NOCOPY VARCHAR2)
181   IS
182 
183   l_document_id number;
184   l_document_subtype po_headers.type_lookup_code%TYPE;
185        --Bug13774287
186    l_document_type po_headers.type_lookup_code%TYPE;
187    --END Bug13774287
188   l_revision_num number;
189   l_request_id number;
190   l_authorization_status varchar2(25);
191   x_progress varchar2(100);
192   l_with_terms PO_HEADERS_ALL.CONTERMS_EXIST_FLAG%TYPE;
193   l_set_lang boolean;
194   l_draft_id number; -- CLM
195   --<BUG 9136162 START>
196   l_language_code  fnd_languages.language_code%type;
197   l_language       fnd_languages.nls_language%TYPE;
198   l_territory      fnd_languages.nls_territory%TYPE;
199   --<BUG 9136162 END>
200 /*Begin Changes by Akyanama Bug # 12969112*//*Declaring Exception*/
201   submission_error exception;
202  /*End Changes by Akyanama Bug # 12969112*/
203 
204   BEGIN
205 
206     x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF';
207 
208     IF (g_po_wf_debug = 'Y') THEN
209       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
210     END IF;
211 
212     --Start of code changes for the bug 12403413
213     -- Do nothing in cancel or timeout modes. Similar to the bug 4100416
214     IF (funcmode <> wf_engine.eng_run)
215       THEN
216       resultout := wf_engine.eng_null;
217       return;
218     END IF;
219     --End of code changes for the bug 12403413
220 
221     l_document_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
222                                                        itemkey => itemkey,
223                                                        aname => 'DOCUMENT_ID');
224 
225   --Bug13774287
226   l_document_type := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
227  	                                             itemkey  => itemkey,
228                                                 aname    => 'DOCUMENT_TYPE');
229   --End Bug13774287
230 
231 	-- CLM
232 	l_draft_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
233                                                        itemkey => itemkey,
234                                                        aname => 'DRAFT_ID');
235 
236     l_document_subtype := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
237                                                           itemkey => itemkey,
238                                                           aname => 'DOCUMENT_SUBTYPE');
239 
240     l_revision_num := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
241                                                         itemkey => itemkey,
242                                                         aname => 'REVISION_NUMBER');
243 
244     l_authorization_status := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
245                                                               itemkey => itemkey,
246                                                               aname => 'AUTHORIZATION_STATUS');
247 
248     l_with_terms := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
249                                                     itemkey => itemkey,
250                                                     aname => 'WITH_TERMS');
251 
252     --<BUG 9136162 START>
253     l_language_code := PO_WF_UTIL_PKG.GetItemAttrText(itemtype => itemtype,
254 						      itemkey => itemkey,
255 						      aname=>'LANGUAGE_CODE');
256 
257  --Bug 13069700 - Adding exception block.
258      BEGIN
259        SELECT nls_language, nls_territory
260              INTO l_language, l_territory
261           FROM fnd_languages
262           WHERE language_code = l_language_code;
263      EXCEPTION
264          WHEN NO_DATA_FOUND THEN
265                x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF : in exception handler';
266                   IF (g_po_wf_debug = 'Y') THEN
267                           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
268                   END IF;
269       END;
270     --<BUG 9136162 END>
271 
272     x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF :launching the java concurrent program ';
273 
274     IF (g_po_wf_debug = 'Y') THEN
275       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
276     END IF;
277 
278 --if the po has T's and C's then launch the concurrent request to generate the pdf with T's and C's
279 --Bug5080617 Pass the parameters P_PO_TEMPLATE_CODE and P_CONTRACT_TEMPLATE_CODE as null
280 
281     IF l_document_subtype in ('STANDARD', 'BLANKET', 'CONTRACT') THEN
282       IF (l_with_terms = 'Y') THEN
283 
284     /*Bug 8135201
285       Passing ICX_NUMERIC_CHARACTERS profile value to the POPDF program */
286         l_set_lang := fnd_request.set_options('NO', 'NO', l_language, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS')); --<BUG 9136162>
287 
288 --<R12 MOAC START>
289         po_moac_utils_pvt.set_request_context(po_moac_utils_pvt.get_current_org_id);
290 --<R12 MOAC END>
291 
292 
293 		--Bug13774287 Need to pass document type as
294 		--RELEASE in case of a release to the concurrent program
295 		IF l_document_type ='RELEASE' THEN
296 		   l_document_subtype :='RELEASE';
297 		END IF;
298 		--END Bug13774287
299 
300 
301         l_request_id := fnd_request.submit_request('PO',
302                                                    'POXPOPDF',
303                                                    null,
304                                                    null,
305                                                    false,
306                                                    'R', --P_report_type
307                                                    null , --P_agend_id
308                                                    null, --P_po_num_from
309                                                    null , --P_po_num_to
310                                                    null , --P_relaese_num_from
311                                                    null , --P_release_num_to
312                                                    null , --P_date_from
313                                                    null , --P_date_to
314                                                    null , --P_approved_flag
315                                                    'N', --P_test_flag
316                                                    null , --P_print_releases
317                                                    null , --P_sortby
318                                                    null , --P_user_id
319                                                    null , --P_fax_enable
320                                                    null , --P_fax_number
321                                                    null , --P_BLANKET_LINES
322                                                    'View', --View_or_Communicate,
323                                                    'Y', --P_WITHTERMS
324                                                    'Y', --P_storeFlag
325                                                    'N', --P_PRINT_FLAG
326                                                    l_document_id, --P_DOCUMENT_ID
327 												   l_draft_id,  -- P_DRAFT_ID
328                                                    l_revision_num, --P_REVISION_NUM
329                                                    l_authorization_status, --P_AUTHORIZATION_STATUS
330                                                    l_document_subtype, --P_DOCUMENT_TYPE
331                                                    0,--P_max_zip_size, <PO Attachment Support 11i.11>
332                                                    null, -- P_PO_TEMPLATE_CODE
333                                                    null, -- P_CONTRACT_TEMPLATE_CODE
334                                                    fnd_global.local_chr(0),
335                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
336                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
337                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
338                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
339                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
340                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
341                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
342                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
343                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
344                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
345                                                    NULL);
346             /*Begin Changes by Akyanama Bug # 12969112*//*Checking if the request id is valid or not before setting work flow variables*/
347 			        if (l_request_id <= 0 or l_request_id is null) then
348 						raise submission_error;
349 					end if;
350 			/*End Changes by Akyanama Bug # 12969112*/
351         PO_WF_UTIL_PKG.SetItemAttrNumber (itemtype => itemtype,
352                                           itemkey => itemkey,
353                                           aname => 'REQUEST_ID',
354                                           avalue => l_request_id);
355 
356         x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF : Request id is  '|| l_request_id;
357 
358         IF (g_po_wf_debug = 'Y') THEN
359           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
360         END IF;
361 
362       END IF;
363     END IF;
364 
365   EXCEPTION
366    /*Begin Changes by Akyanama Bug # 12969112*//*Throwing Submission error*/
367 	  WHEN submission_error THEN
368       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF : Exception submitting concurrent request';
369 	  IF (g_po_wf_debug = 'Y') THEN
370          PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
371 		 x_progress := fnd_message.get;
372  	     PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
373       END IF;
374 	  wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF', itemtype, itemkey, 'PO', x_progress);
375       RAISE;
376 
377 	/*End Changes by Akyanama Bug # 12969112*/
378     WHEN OTHERS THEN
379       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF : In Exception handler';
380       IF (g_po_wf_debug = 'Y') THEN
381         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
382       END IF;
383       wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF', x_progress);
384       RAISE;
385 
386   END GENERATE_PDF;
387 
388   PROCEDURE PO_NEW_COMMUNICATION (itemtype IN VARCHAR2,
389                                   itemkey IN VARCHAR2,
390                                   actid IN NUMBER,
391                                   funcmode IN VARCHAR2,
392                                   resultout OUT NOCOPY VARCHAR2) is
393   x_progress varchar2(100);
394   l_document_subtype po_headers.type_lookup_code%TYPE;
395   l_document_type po_headers.type_lookup_code%TYPE;
396 
397   Begin
398     x_progress := 'PO_COMMUNICATION_PVT.PO_NEW_COMMUNICATION';
399 
400     IF (g_po_wf_debug = 'Y') THEN
401       PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
402     END IF;
403 
404 
405   -- <Bug 4100416 Start>: Do nothing in cancel or timeout modes.
406     IF (funcmode <> wf_engine.eng_run)
407       THEN
408       resultout := wf_engine.eng_null;
409       return;
410     END IF;
411   -- <Bug 4100416 End>
412 
413 
414 --Get the document type
415 
416     l_document_type := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
417                                                        itemkey => itemkey,
418                                                        aname => 'DOCUMENT_TYPE');
419 
420 
421     l_document_subtype := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
422                                                           itemkey => itemkey,
423                                                           aname => 'DOCUMENT_SUBTYPE');
424 
425     x_progress := 'PO_COMMUNICATION_PVT.PO_NEW_COMMUNICATION: Verify whether XDO Product is installed or not';
426 
427     IF (g_po_wf_debug = 'Y') THEN
428       PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
429     END IF;
430 
431 
432     IF PO_COMMUNICATION_PROFILE = 'T' THEN
433       IF l_document_type in ('PO', 'PA') and l_document_subtype in ('STANDARD', 'BLANKET', 'CONTRACT')
434         or (l_document_type = 'RELEASE' and l_document_subtype = 'BLANKET' ) THEN
435         resultout := wf_engine.eng_completed || ':' || 'Y';
436       ELSE
437         resultout := wf_engine.eng_completed || ':' || 'N';
438       END IF;
439 
440     Else
441       resultout := wf_engine.eng_completed || ':' || 'N';
442     END IF;
443 
444   EXCEPTION
445 
446     WHEN OTHERS THEN
447       x_progress := 'PO_COMMUNICATION_PVT.PO_NEW_COMMUNICATION: In Exception handler';
448       IF (g_po_wf_debug = 'Y') THEN
449         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
450       END IF;
451       wf_core.context('PO_COMMUNICATION_PVT', 'PO_NEW_COMMUNICATION', x_progress);
452       raise;
453 
454   END PO_NEW_COMMUNICATION;
455 
456   PROCEDURE DELETE_PDF_ATTACHMENTS (itemtype IN VARCHAR2,
457                                     itemkey IN VARCHAR2,
458                                     actid IN NUMBER,
459                                     funcmode IN VARCHAR2,
460                                     resultout OUT NOCOPY VARCHAR2) is
461   l_document_id number;
462   l_document_subtype po_headers.type_lookup_code%TYPE;
463   l_revision_num number;
464   l_draft_id number; --CLM
465   l_draft_id_char varchar2(30); --CLM
466   l_orgid number;
467   l_entity_name varchar2(30);
468   l_language_code fnd_languages.language_code%type;
469   x_progress varchar2(100);
470   l_document_type po_headers.type_lookup_code%TYPE;
471 
472   Begin
473     x_progress := 'PO_COMMUNICATION_PVT.DELETE_PDF_ATTACHMENTS';
474 
475     IF (g_po_wf_debug = 'Y') THEN
476       PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
477     END IF;
478 
479   -- <Bug 4100416 Start>: Do nothing in cancel or timeout modes.
480     IF (funcmode <> wf_engine.eng_run)
481       THEN
482       resultout := wf_engine.eng_null;
483       return;
484     END IF;
485   -- <Bug 4100416 End>
486 
487 
488     l_document_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
489                                                        itemkey => itemkey,
490                                                        aname => 'DOCUMENT_ID');
491 
492     l_revision_num := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
493                                                         itemkey => itemkey,
494                                                         aname => 'REVISION_NUMBER');
495 
496     l_document_type := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
497                                                        itemkey => itemkey,
498                                                        aname => 'DOCUMENT_TYPE');
499 
500 
501     l_document_subtype := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
502                                                           itemkey => itemkey,
503                                                           aname => 'DOCUMENT_SUBTYPE');
504 
505 --CLM
506     l_draft_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
507                                                           itemkey => itemkey,
508                                                           aname => 'DRAFT_ID');
509     IF l_draft_id is NULL then
510         l_draft_id := -1;
511     END IF;
512     IF l_draft_id <> -1 then
513         l_draft_id_char := to_char(l_draft_id);
514     ELSE
515         l_draft_id_char :=  null;
516     END IF;
517 --CLM
518     IF l_document_type in ('PO', 'PA') and l_document_subtype in ('STANDARD', 'BLANKET', 'CONTRACT') THEN
519       l_entity_name := 'PO_HEAD';
520     ELSIF l_document_type = 'RELEASE' and l_document_subtype = 'BLANKET' THEN
521       l_entity_name := 'PO_REL';
522     END IF;
523 
524     x_progress := 'PO_COMMUNICATION_PVT.DELETE_PDF_ATTACHMENTS :Calling the Delete attachments procedure';
525 
526     IF (g_po_wf_debug = 'Y') THEN
527       PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
528     END IF;
529 
530     FND_ATTACHED_DOCUMENTS2_PKG.delete_attachments(X_entity_name => l_entity_name,
531                                                    X_pk1_value => to_char(l_document_id),
532                                                    X_pk2_value => to_char(l_revision_num),
533                                                    --X_pk3_value => null, -- CLM
534                                                    X_pk3_value => l_draft_id_char, -- CLM
535                                                    X_pk4_value => null,
536                                                    X_pk5_value => null,
537                                                    X_delete_document_flag => 'Y',
538                                                    X_automatically_added_flag => 'N');
539 
540 -- Bug 4088074 Set the REQUEST_ID item attribute to Null after deleting pdf
541     PO_WF_UTIL_PKG.SetItemAttrNumber (itemtype => itemtype,
542                                       itemkey => itemkey,
543                                       aname => 'REQUEST_ID',
544                                       avalue => NULL);
545 
546 
547   EXCEPTION
548 
549     WHEN OTHERS THEN
550       x_progress := 'PO_COMMUNICATION_PVT.DELETE_PDF_ATTACHMENTS:In Exception handler';
551       IF (g_po_wf_debug = 'Y') THEN
552         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
553       END IF;
554       wf_core.context('PO_COMMUNICATION_PVT', 'DELETE_PDF_ATTACHMENTS', x_progress);
555       raise;
556 
557 
558   END DELETE_PDF_ATTACHMENTS;
559 
560   PROCEDURE PO_PDF_EXISTS (itemtype IN VARCHAR2,
561                            itemkey IN VARCHAR2,
562                            actid IN NUMBER,
563                            funcmode IN VARCHAR2,
564                            resultout OUT NOCOPY VARCHAR2) is
565 
566   l_language_code fnd_languages.language_code%type;
567   l_document_id number;
568   l_revision_num number;
569   l_terms_flag po_headers_all.CONTERMS_EXIST_FLAG%type;
570   l_document_subtype po_headers_all.type_lookup_code%TYPE;
571   l_document_type po_headers_all.type_lookup_code%TYPE;
572   l_count number;
573   l_filename fnd_lobs.file_name%type;
574   l_orgid number;
575   x_progress varchar2(100);
576   l_with_terms PO_HEADERS_ALL.CONTERMS_EXIST_FLAG%TYPE;
577   l_terms varchar2(10);
578 
579   Begin
580     x_progress := 'PO_COMMUNICATION_PVT.PO_PDF_EXISTS';
581 
582     IF (g_po_wf_debug = 'Y') THEN
583      /* DEBUG */ PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
584     END IF;
585 
586 
587     l_document_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
588                                                        itemkey => itemkey,
589                                                        aname => 'DOCUMENT_ID');
590 
591     l_revision_num := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
592                                                         itemkey => itemkey,
593                                                         aname => 'REVISION_NUMBER');
594 
595     l_document_type := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
596                                                        itemkey => itemkey,
597                                                        aname => 'DOCUMENT_TYPE');
598 
599 
600     l_document_subtype := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
601                                                           itemkey => itemkey,
602                                                           aname => 'DOCUMENT_SUBTYPE');
603 
604     l_orgid := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
605                                                  itemkey => itemkey,
606                                                  aname => 'ORG_ID');
607 
608     l_language_code := PO_WF_UTIL_PKG.GetItemAttrText(itemtype => itemtype,
609                                                       itemkey => itemkey,
610                                                       aname => 'LANGUAGE_CODE');
611 
612     l_with_terms := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
613                                                     itemkey => itemkey,
614                                                     aname => 'WITH_TERMS');
615     IF l_with_terms = 'Y' THEN
616       l_terms := '_TERMS_';
617     ELSE
618       l_terms := '_';
619     END IF;
620 
621 
622 --frame the file name based on po_has_terms_conditions (eg POTERMS_204_1234_1_US.pdf, PO_204_1234_1_US.pdf)
623 
624 --bug#3463617:
625     l_filename := po_communication_pvt.getPDFFileName(l_document_type, l_terms, l_orgid, l_document_id, l_revision_num, l_language_code);
626 
627     x_progress := 'PO_COMMUNICATION_PVT.PO_PDF_EXISTS: Verify whether the pdf exists for the document';
628 
629     IF (g_po_wf_debug = 'Y') THEN
630      /* DEBUG */ PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
631     END IF;
632 
633     BEGIN
634 
635       IF l_with_terms = 'Y' THEN
636 --search in contracts repository
637         x_progress := 'PO_COMMUNICATION_PVT.PO_PDF_EXISTS:Searching in the Contracts Repository';
638 
639         IF (g_po_wf_debug = 'Y') THEN
640      /* DEBUG */ PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
641         END IF;
642 
643 
644         SELECT count(*) into l_count from fnd_lobs fl, fnd_attached_docs_form_vl fad
645         WHERE
646         fl.file_id = fad.media_id and
647         fad.pk2_value = to_char(l_document_id) and
648         fad.pk3_value = to_char(l_revision_num) and
649         fl.file_name = l_filename and
650         fad.entity_name in ('PO_HEAD', 'PO_REL');
651       ELSE
652 --search in PO repository
653         x_progress := 'PO_COMMUNICATION_PVT.PO_PDF_EXISTS: Searching in the PO Repository';
654 
655         IF (g_po_wf_debug = 'Y') THEN
656      /* DEBUG */ PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
657         END IF;
658 
659 
660 -- Bug6139548
661 -- Added TO_CHAR() wherever a numeric value is compared with pk1_value or pk2_value.
662 
663 -- bug4931216
664 -- Add enttiy name filtering to utilize the index
665         SELECT count(*) into l_count from fnd_lobs fl, fnd_attached_docs_form_vl fad
666         WHERE
667         fl.file_id = fad.media_id and
668         fad.pk1_value = to_char(l_document_id) and
669         fad.pk2_value = to_char(l_revision_num) and
670         fl.file_name = l_filename and
671         fad.entity_name IN ('PO_HEAD', 'PO_REL');
672 
673       END IF;
674 
675     Exception
676       WHEN OTHERS THEN
677         l_count := 0;
678     END ;
679 
680 
681     IF l_count >0 THEN
682       resultout := wf_engine.eng_completed || ':' || 'Y';
683     Else
684       resultout := wf_engine.eng_completed || ':' || 'N';
685     End if;
686 
687   EXCEPTION
688     When others then
689       x_progress := 'PO_COMMUNICATION_PVT.PO_PDF_EXISTS: In Exception handler';
690       IF (g_po_wf_debug = 'Y') THEN
691         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
692       END IF;
693       wf_core.context('PO_COMMUNICATION_PVT', 'PO_PDF_EXISTS', x_progress);
694       resultout := wf_engine.eng_completed || ':' || 'N';
695       raise;
696 
697   END PO_PDF_EXISTS;
698 
699   PROCEDURE Start_Email_WF_Process (p_document_id NUMBER,
700                                     p_revision_num NUMBER,
701                                     p_document_type VARCHAR2,
702                                     p_document_subtype VARCHAR2,
703                                     p_email_address VARCHAR2,
704                                     p_language_code VARCHAR2,
705                                     p_store_flag VARCHAR2,
706                                     p_with_terms VARCHAR2 ) is
707 
708   l_progress varchar2(100);
709   l_seq_for_item_key varchar2(25); --Bug14305923
710   l_itemkey varchar2(60);
711   l_itemtype po_document_types.wf_approval_itemtype%type;
712   l_workflow_process po_document_types.wf_approval_process%type;
713   l_vendor_site_code varchar2(15);
714   l_vendor_site_id number;
715   l_vendor_site_lang PO_VENDOR_SITES.LANGUAGE%TYPE;
716   l_adhocuser_lang WF_LANGUAGES.NLS_LANGUAGE%TYPE;
717   l_adhocuser_territory WF_LANGUAGES.NLS_TERRITORY%TYPE;
718   l_po_email_add_prof WF_USERS.EMAIL_ADDRESS%TYPE;
719   l_po_email_performer WF_USERS.NAME%TYPE;
720   l_display_name WF_USERS.DISPLAY_NAME%TYPE;
721   l_performer_exists number;
722   l_notification_preference varchar2(20) := 'MAILHTM2';
723 --Bug13871793
724   l_orgid number;
725 --l_legal_name   hr_all_organization_units.name%TYPE;
726 --bug##3682458 replaced legal entity name with operating unit
727   l_operating_unit hr_all_organization_units.name%TYPE;
728 
729   l_document_id PO_HEADERS_ALL.po_header_id%TYPE;
730   l_docNumber PO_HEADERS_ALL.SEGMENT1%TYPE;
731   l_doc_num_rel varchar2(30);
732   l_release_num PO_RELEASES.release_num%TYPE; -- Bug 3215186;
733   l_ga_flag varchar2(1) := null; -- Bug # 3290385
734   l_doc_display_name FND_NEW_MESSAGES.message_text%TYPE; -- Bug 3215186
735   l_attachments_exist VARCHAR2(1); --<PO Attachment Support 11i.11>
736 
737 -- Bug 4099027. length 50 because this variable is a concatenation of
738 -- document_type_code and document_subtype
739   l_okc_doc_type varchar2(50);
740 
741   -- bug 16475213 start
742   l_zip_exists NUMBER;
743   l_filename fnd_lobs.file_name%type;
744   l_entity_name varchar2(30);
745   -- bug 16475213 end
746 
747   BEGIN
748 
749     select to_char (PO_WF_ITEMKEY_S.NEXTVAL) into l_seq_for_item_key from sys.dual;
750 
751     l_itemkey := to_char(p_document_id) || '-' || l_seq_for_item_key;
752 
753     l_itemtype := 'POAPPRV';
754 
755 
756     l_progress := 'PO_COMMUNICATION_PVT.Start_Email_WF_Process: at beginning of Start_Email_WF_Process';
757 
758     IF (g_po_wf_debug = 'Y') THEN
759       PO_WF_DEBUG_PKG.insert_debug (l_itemtype, l_itemkey, l_progress);
760     END IF;
761 
762 
763     l_workflow_process := 'EMAIL_PO_PDF';
764 
765     wf_engine.CreateProcess(ItemType => l_itemtype,
766                             ItemKey => l_itemkey,
767                             process => l_workflow_process );
768 
769 
770     PO_WF_UTIL_PKG.SetItemAttrNumber (itemtype => l_itemtype,
771                                       itemkey => l_itemkey,
772                                       aname => 'DOCUMENT_ID',
773                                       avalue => p_document_id);
774 
775     PO_WF_UTIL_PKG.SetItemAttrNumber (itemtype => l_itemtype,
776                                       itemkey => l_itemkey,
777                                       aname => 'REVISION_NUMBER',
778                                       avalue => p_revision_num);
779 
780     PO_WF_UTIL_PKG.SetItemAttrText (itemtype => l_itemtype,
781                                     itemkey => l_itemkey,
782                                     aname => 'DOCUMENT_TYPE',
783                                     avalue => p_document_type);
784 
785     PO_WF_UTIL_PKG.SetItemAttrText (itemtype => l_itemtype,
786                                     itemkey => l_itemkey,
787                                     aname => 'DOCUMENT_SUBTYPE',
788                                     avalue => p_document_subtype);
789 
790     PO_WF_UTIL_PKG.SetItemAttrText (itemtype => l_itemtype,
791                                     itemkey => l_itemkey,
792                                     aname => 'EMAIL_ADDRESS',
793                                     avalue => p_email_address);
794 
795     PO_WF_UTIL_PKG.SetItemAttrText (itemtype => l_itemtype,
796                                     itemkey => l_itemkey,
797                                     aname => 'WITH_TERMS',
798                                     avalue => p_with_terms);
799 
800     PO_WF_UTIL_PKG.SetItemAttrText (itemtype => l_itemtype,
801                                     itemkey => l_itemkey,
802                                     aname => 'LANGUAGE_CODE',
803                                     avalue => p_language_code);
804 
805     PO_WF_UTIL_PKG.SetItemAttrText(itemtype => l_itemtype,
806                                    itemkey => l_itemkey,
807                                    aname => 'EMAIL_TEXT_WITH_PDF',
808                                    avalue => FND_MESSAGE.GET_STRING('PO', 'PO_PDF_EMAIL_TEXT'));
809 
810     l_orgid := po_moac_utils_pvt.get_current_org_id; --<R12 MOAC>
811 
812     IF l_orgid is not null THEN
813 --bug#3682458 replaced the sql that retrieves legal entity
814 --name with sql that retrieves operating unit name
815       BEGIN
816         SELECT hou.name
817         into l_operating_unit
818         FROM
819                hr_organization_units hou
820         WHERE
821                hou.organization_id = l_orgid;
822       EXCEPTION
823         WHEN OTHERS THEN
824           l_operating_unit := null;
825       END;
826     END IF;
827 
828     PO_WF_UTIL_PKG.SetItemAttrNumber (itemtype => l_itemtype,
829                                       itemkey => l_itemkey,
830                                       aname => 'ORG_ID',
831                                       avalue => l_orgid );
832 --bug#3682458 replaced legal_entity_name with operating_unit_name
833     PO_WF_UTIL_PKG.SetItemAttrText(itemtype => l_itemtype,
834                                    itemkey => l_itemkey,
835                                    aname => 'OPERATING_UNIT_NAME',
836                                    avalue => l_operating_unit);
837 
838 -- Bug # 3290385 Start
839     if p_document_type = 'RELEASE' then
840       select po_header_id, release_num into l_document_id, l_release_num
841       from po_releases_all
842       where
843       po_release_id = p_document_id;
844     else
845       l_document_id := p_document_id;
846     end if;
847 
848     select segment1, global_agreement_flag into l_docNumber, l_ga_flag
849     from po_headers_all
850     where po_header_id = l_document_id;
851 
852     wf_engine.SetItemAttrText (itemtype => l_itemtype,
853                                itemkey => l_itemkey,
854                                aname => 'DOCUMENT_NUMBER',
855                                avalue => l_docNumber);
856 
857 
858     select DECODE(p_document_subtype, 'BLANKET', FND_MESSAGE.GET_STRING('POS', 'POS_POTYPE_BLKT'),
859             'CONTRACT', FND_MESSAGE.GET_STRING('POS', 'POS_POTYPE_CNTR'),
860             'STANDARD', FND_MESSAGE.GET_STRING('POS', 'POS_POTYPE_STD'),
861             'PLANNED', FND_MESSAGE.GET_STRING('POS', 'POS_POTYPE_PLND')) into l_doc_display_name from dual;
862     if l_ga_flag = 'Y' then
863       l_doc_display_name := FND_MESSAGE.GET_STRING('PO', 'PO_GA_TYPE');
864     end if;
865 
866     if p_document_type = 'RELEASE' then
867       l_doc_num_rel := l_docNumber || '-' || l_release_num;
868       l_doc_display_name := FND_MESSAGE.GET_STRING('POS', 'POS_POTYPE_BLKTR');
869     else
870       l_doc_num_rel := l_docNumber;
871     end if;
872     if l_doc_num_rel is not null then
873       wf_engine.SetItemAttrText (itemtype => l_itemtype,
874                                  itemkey => l_itemkey,
875                                  aname => 'DOCUMENT_NUM_REL',
876                                  avalue => l_doc_num_rel);
877     end if;
878 
879     IF (p_document_type = 'PA' AND p_document_subtype IN ('BLANKET', 'CONTRACT')) OR
880       (p_document_type = 'PO' AND p_document_subtype = 'STANDARD') THEN
881 
882       l_doc_display_name := PO_DOC_STYLE_PVT.GET_STYLE_DISPLAY_NAME(l_document_id);
883 
884     END IF;
885 
886 
887     wf_engine.SetItemAttrText (itemtype => l_itemtype,
888                                itemkey => l_itemkey,
889                                aname => 'DOCUMENT_DISPLAY_NAME',
890                                avalue => l_doc_display_name );
891 -- Bug # 3290385 End
892 
893     l_progress := 'PO_COMMUNICATION_PVT.Start_Email_WF_Process: Get the Supplier site language';
894 
895     IF (g_po_wf_debug = 'Y') THEN
896       PO_WF_DEBUG_PKG.insert_debug (l_itemtype, l_itemkey, l_progress);
897     END IF;
898 
899     if p_document_type = 'RELEASE' then
900       select poh.vendor_site_id, pvs.vendor_site_code, pvs.language
901       into l_vendor_site_id, l_vendor_site_code, l_vendor_site_lang
902       from po_headers poh, po_vendor_sites pvs, po_releases por
903       where pvs.vendor_site_id = poh.vendor_site_id
904       and poh.po_header_id = por.po_header_id
905       and por.po_release_id = p_document_id;
906     else
907       select poh.vendor_site_id, pvs.vendor_site_code, pvs.language
908       into l_vendor_site_id, l_vendor_site_code, l_vendor_site_lang
909       from po_headers poh, po_vendor_sites pvs
910       where pvs.vendor_site_id = poh.vendor_site_id
911       and poh.po_header_id = p_document_id;
912     end if;
913 
914     IF l_vendor_site_lang is NOT NULL then
915 
916       SELECT wfl.nls_language, wfl.nls_territory INTO l_adhocuser_lang, l_adhocuser_territory
917       FROM wf_languages wfl, fnd_languages_vl flv
918       WHERE wfl.code = flv.language_code AND flv.nls_language = l_vendor_site_lang;
919 
920     ELSE
921 
922       SELECT wfl.nls_language, wfl.nls_territory into l_adhocuser_lang, l_adhocuser_territory
923       FROM wf_languages wfl, fnd_languages_vl flv
924       WHERE wfl.code = flv.language_code AND flv.installed_flag = 'B';
925 
926     END IF;
927 
928     l_po_email_performer := p_email_address || '.' || l_adhocuser_lang;
929     l_po_email_performer := upper(l_po_email_performer);
930     l_display_name := p_email_address; -- Bug # 3290385
931 
932     l_progress := 'PO_COMMUNICATION_PVT.Start_Email_WF_Process: Verify whether the role exists in wf_users';
933 
934     IF (g_po_wf_debug = 'Y') THEN
935       PO_WF_DEBUG_PKG.insert_debug (l_itemtype, l_itemkey, l_progress);
936     END IF;
937 
938 
939     select count(1) into l_performer_exists
940     from wf_users where name = l_po_email_performer;
941 
942     if (l_performer_exists = 0) then
943 
944 -- Pass in the correct adhocuser language and territory for CreateAdHocUser and SetAdhocUserAttr instead of null
945 
946       WF_DIRECTORY.CreateAdHocUser(l_po_email_performer, l_display_name, l_adhocuser_lang, l_adhocuser_territory, null, l_notification_preference, p_email_address, null, 'ACTIVE', null);
947 
948     else
949 
950       WF_DIRECTORY.SETADHOCUSERATTR(l_po_email_performer, l_display_name, l_notification_preference, l_adhocuser_lang, l_adhocuser_territory, p_email_address, null);
951 
952     end if;
953 
954     PO_WF_UTIL_PKG.SetItemAttrText (itemtype => l_itemtype,
955                                     itemkey => l_itemkey,
956                                     aname => 'PO_PDF_EMAIL_PERFORMER',
957                                     avalue => l_po_email_performer);
958     PO_WF_UTIL_PKG.SetItemAttrText (itemtype => l_itemtype,
959                                     itemkey => l_itemkey,
960                                     aname => 'PDF_ATTACHMENT',
961                                     avalue => 'PLSQLBLOB:PO_COMMUNICATION_PVT.PDF_ATTACH_SUPP/' || l_itemtype || ':' || l_itemkey);
962 
963 --Bug6998166, to increase print_count
964     PO_REQAPPROVAL_INIT1.update_print_count(p_document_id, p_document_type);
965 
966   --<Bug 4099027 Start> Set up okc doc attachment attribute, if necessary
967     IF (p_with_terms = 'Y') THEN
968       l_okc_doc_type := PO_CONTERMS_UTL_GRP.get_po_contract_doctype(p_document_subtype);
969 
970       IF (('STRUCTURED' <> OKC_TERMS_UTIL_GRP.get_contract_source_code
971            (p_document_type => l_okc_doc_type
972             , p_document_id => p_document_id))
973           AND
974           ('N' = OKC_TERMS_UTIL_GRP.is_primary_terms_doc_mergeable
975            (p_document_type => l_okc_doc_type
976             , p_document_id => p_document_id))
977           ) THEN
978 
979         PO_WF_UTIL_PKG.SetItemAttrText
980         (itemtype => l_itemtype,
981          itemkey => l_itemkey,
982          aname => 'OKC_DOC_ATTACHMENT',
983          avalue => 'PLSQLBLOB:PO_COMMUNICATION_PVT.OKC_DOC_ATTACH/' ||
984          l_itemtype || ':' || l_itemkey);
985       END IF; -- not structured and not mergeable
986 
987     END IF; --IF (p_with_terms = 'Y')
988   --<Bug 4099027 End>
989 
990 
991   --<PO Attachment Support 11i.11>
992   -- Get the 'Maximum Attachment Size' value from Purchasing Options
993   -- A value of 0 means Zip Attachments are not supported.
994 
995   -- bug 16475213 start
996     IF get_max_zip_size(l_itemtype, l_itemkey) > 0 THEN
997       Begin
998         --Bug# 5240634 Pass in the org_id to getZIPFileName
999         l_filename := getZIPFileName(l_orgid);
1000 
1001       Exception When others Then
1002         l_progress := 'PO_COMMUNICATION_PVT.Start_Email_WF_Process : Exception in getZIPFileName';
1003         raise;
1004       End;
1005 
1006       l_progress := 'PO_COMMUNICATION_PVT.Start_Email_WF_Process : Query the Zip blob';
1007       --Bug #4865352 - Added a join with fnd_documents and selected media_id from it
1008 
1009 
1010       IF p_document_type in ('PO', 'PA') THEN
1011         l_entity_name := 'PO_HEAD';
1012       ELSIF p_document_type = 'RELEASE' THEN
1013         l_entity_name := 'PO_REL';
1014       END IF;
1015 
1016       Begin
1017         SELECT count(*)
1018         INTO l_zip_exists
1019         FROM fnd_lobs fl,
1020              fnd_attached_documents fad,
1021              fnd_documents fd,
1022              fnd_documents_tl fdl
1023         WHERE fad.pk1_value = to_char(p_document_id)
1024         and fad.pk2_value = to_char(p_revision_num)
1025         and fad.entity_name = l_entity_name
1026         and fdl.document_id = fad.document_id
1027         and fdl.document_id = fd.document_id
1028           --Bug 5017976 selecting media_id from fd instead of fdl
1029         and fd.media_id = fl.file_id
1030         and fl.file_name = l_filename;
1031       Exception
1032         When others Then
1033           l_progress := 'PO_COMMUNICATION_PVT.Start_Email_WF_Process : error';
1034           raise;
1035       End;
1036 
1037       IF l_zip_exists > 0 THEN
1038             -- bug 16475213 end
1039           PO_WF_UTIL_PKG.SetItemAttrText (itemtype => l_itemtype,
1040                                         itemkey => l_itemkey,
1041                                         aname => 'ZIP_ATTACHMENT',
1042                                         avalue => 'PLSQLBLOB:PO_COMMUNICATION_PVT.ZIP_ATTACH/' || l_itemtype || ':' || l_itemkey);
1043       END IF;
1044     END IF;
1045 
1046     l_progress := 'PO_COMMUNICATION_PVT.Start_Email_WF_Process:Start the workflow process';
1047 
1048     IF (g_po_wf_debug = 'Y') THEN
1049       PO_WF_DEBUG_PKG.insert_debug (l_itemtype, l_itemkey, l_progress);
1050     END IF;
1051 
1052     wf_engine. StartProcess (itemtype => l_itemtype, itemkey => l_itemkey);
1053 
1054 
1055   EXCEPTION
1056     WHEN OTHERS THEN
1057 
1058       l_progress := 'PO_COMMUNICATION_PVT.Start_WF_Process_Email: In Exception handler';
1059 
1060       IF (g_po_wf_debug = 'Y') THEN
1061         PO_WF_DEBUG_PKG.insert_debug(l_itemtype, l_itemkey, l_progress);
1062       END IF;
1063 
1064       RAISE;
1065 
1066   END Start_Email_WF_Process;
1067 
1068 
1069 --<FP 11i10+ - R12 Contract ER TC Sup Lang Start >
1070 -- Generates the pdf doc with terms in suppliers language
1071   PROCEDURE GENERATE_PDF_SUPP_TC (itemtype IN VARCHAR2,
1072                                   itemkey IN VARCHAR2,
1073                                   actid IN NUMBER,
1074                                   funcmode IN VARCHAR2,
1075                                   resultout OUT NOCOPY VARCHAR2)
1076   IS
1077 
1078   l_document_id po_headers.po_header_id%TYPE;
1079   l_revision_num po_headers.revision_num%TYPE;
1080   l_document_subtype po_headers.type_lookup_code%TYPE;
1081   l_document_type po_headers.type_lookup_code%TYPE;
1082   l_territory fnd_languages.nls_territory%type;
1083   l_language_code fnd_languages.language_code%type;
1084   l_supp_lang po_vendor_sites_all.language%TYPE;
1085   l_language fnd_languages.nls_language%type;
1086   l_authorization_status po_headers.authorization_status%TYPE;
1087   l_header_id po_headers.po_header_id%TYPE;
1088 
1089   l_with_terms varchar2(1);
1090    --l_old_request_id  number; --Bug 7299381
1091   l_request_id number;
1092   l_set_lang boolean;
1093 
1094   x_progress varchar2(100);
1095   l_draft_id number; -- CLM
1096 /*Begin Changes by Akyanama Bug # 12969112*//*Declaring Exception*/
1097   submission_error exception;
1098  /*End Changes by Akyanama Bug # 12969112*/
1099   begin
1100     x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP_TC';
1101 
1102     IF (g_po_wf_debug = 'Y') THEN
1103       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
1104     END IF;
1105 
1106     --Start of code changes for the bug 12403413
1107     -- Do nothing in cancel or timeout modes. Similar to the bug 4100416
1108     IF (funcmode <> wf_engine.eng_run)
1109       THEN
1110       resultout := wf_engine.eng_null;
1111       return;
1112     END IF;
1113     --End of code changes for the bug 12403413
1114 
1115     l_document_type := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1116                                                        itemkey => itemkey,
1117                                                        aname => 'DOCUMENT_TYPE');
1118 
1119     l_document_subtype := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1120                                                           itemkey => itemkey,
1121                                                           aname => 'DOCUMENT_SUBTYPE');
1122 
1123     l_document_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
1124                                                        itemkey => itemkey,
1125                                                        aname => 'DOCUMENT_ID');
1126 
1127 	-- CLM
1128 	l_draft_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
1129                                                        itemkey => itemkey,
1130                                                        aname => 'DRAFT_ID');
1131 
1132     l_revision_num := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
1133                                                         itemkey => itemkey,
1134                                                         aname => 'REVISION_NUMBER');
1135 
1136     l_language_code := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1137                                                        itemkey => itemkey,
1138                                                        aname => 'LANGUAGE_CODE');
1139 
1140     l_with_terms := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1141                                                     itemkey => itemkey,
1142                                                     aname => 'WITH_TERMS');
1143 
1144   --Bug# 5498523: We need the correct Authurization status so the logic in PoGenerateDocument.StorePDF
1145   --will store the PDF in the contracts repository.
1146     l_authorization_status := PO_WF_UTIL_PKG.GetItemAttrText(itemtype => itemtype,
1147                                                              itemkey => itemkey,
1148                                                              aname => 'AUTHORIZATION_STATUS');
1149 
1150     IF l_document_type in ('PO', 'PA') and
1151       l_document_subtype in ('STANDARD', 'BLANKET', 'CONTRACT') and
1152       l_with_terms = 'Y' THEN
1153 
1154       l_header_id := l_document_id;
1155 
1156       --Bug 13069700 - Adding exception block.
1157       BEGIN
1158 
1159       SELECT pv.language
1160       INTO l_supp_lang
1161       FROM po_vendor_sites_all pv,
1162            po_headers_all ph
1163       WHERE ph.po_header_id = l_header_id
1164       AND ph.vendor_site_id = pv.vendor_site_id;
1165 
1166        EXCEPTION
1167             WHEN NO_DATA_FOUND THEN
1168                x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP_TC -001: in exception handler';
1169                   IF (g_po_wf_debug = 'Y') THEN
1170                           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
1171                   END IF;
1172        END;
1173 
1174 
1175       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP_TC :launching the Dispatch Purchase Order concurrent program ';
1176 
1177       IF (g_po_wf_debug = 'Y') THEN
1178         PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
1179       END IF;
1180 
1181 
1182   --set the suppliers language before launching the concurrent request
1183   --Bug6841986/6528046 userenv('LANG')==> l_language_code
1184      --Bug 13069700 - Adding exception block.
1185       BEGIN
1186 
1187       SELECT nls_language
1188       INTO l_language
1189       FROM fnd_languages
1190       WHERE language_code = l_language_code;
1191 
1192       EXCEPTION
1193            WHEN NO_DATA_FOUND THEN
1194                x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP_TC -002: in exception handler';
1195                   IF (g_po_wf_debug = 'Y') THEN
1196                           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
1197                   END IF;
1198       END;
1199   --End Bug6841986/6528046
1200 
1201       IF l_language <> l_supp_lang then
1202     --Bug 13069700 - Adding exception block.
1203         BEGIN
1204 
1205         SELECT nls_territory
1206         INTO l_territory
1207         FROM fnd_languages
1208         WHERE nls_language = l_supp_lang;
1209 
1210 	 EXCEPTION
1211              WHEN NO_DATA_FOUND THEN
1212                x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP_TC -003: in exception handler';
1213                   IF (g_po_wf_debug = 'Y') THEN
1214                           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
1215                   END IF;
1216          END;
1217 
1218      /*Bug 8135201*/
1219         l_set_lang := fnd_request.set_options('NO', 'NO', l_supp_lang, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS'));
1220 
1221   --<Bug 5373928 START>- Set the org context
1222   --<R12 MOAC START>
1223         po_moac_utils_pvt.set_request_context(po_moac_utils_pvt.get_current_org_id);
1224   --<R12 MOAC END>
1225   --<Bug 5373928 END>
1226   --Bug5080617 Pass the parameters P_PO_TEMPLATE_CODE and P_CONTRACT_TEMPLATE_CODE as null
1227         l_request_id := fnd_request.submit_request('PO',
1228                                                    'POXPOPDF',
1229                                                    null,
1230                                                    null,
1231                                                    false,
1232                                                    'R', --P_report_type
1233                                                    null , --P_agend_id
1234                                                    null, --P_po_num_from
1235                                                    null , --P_po_num_to
1236                                                    null , --P_relaese_num_from
1237                                                    null , --P_release_num_to
1238                                                    null , --P_date_from
1239                                                    null , --P_date_to
1240                                                    null , --P_approved_flag
1241                                                    'N', --P_test_flag
1242                                                    null , --P_print_releases
1243                                                    null , --P_sortby
1244                                                    null , --P_user_id
1245                                                    null , --P_fax_enable
1246                                                    null , --P_fax_number
1247                                                    null , --P_BLANKET_LINES
1248                                                    'View', --View_or_Communicate,
1249                                                    l_with_terms, --P_WITHTERMS
1250                                                    'Y', --P_storeFlag
1251                                                    'N', --P_PRINT_FLAG
1252                                                    l_document_id, --P_DOCUMENT_ID
1253 												   l_draft_id, --P_DRAFT_ID
1254                                                    l_revision_num, --P_REVISION_NUM
1255                                                    l_authorization_status, --P_AUTHORIZATION_STATUS
1256                                                    l_document_subtype, --P_DOCUMENT_TYPE
1257                                                    null, -- P_PO_TEMPLATE_CODE
1258                                                    null, -- P_CONTRACT_TEMPLATE_CODE
1259                                                    fnd_global.local_chr(0),
1260                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1261                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1262                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1263                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1264                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1265                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1266                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1267                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1268                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1269                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1270                                                    NULL, NULL);
1271 
1272     /*Begin Changes by Akyanama Bug # 12969112*//*Checking if the request id is valid or not before setting work flow variables*/
1273 		if (l_request_id <= 0 or l_request_id is null) then
1274 			raise submission_error;
1275 		end if;
1276 	/*End Changes by Akyanama Bug # 12969112*/
1277    -- Bug 7299381
1278    /*Changed the order of calling 4 PDF generation CPs for different cases.
1279      Setting the REQUEST_ID attribute (w/o any condition) in all 4 procedures */
1280         PO_WF_UTIL_PKG.SetItemAttrNumber(itemtype => itemtype,
1281                                          itemkey => itemkey,
1282                                          aname => 'REQUEST_ID',
1283                                          avalue => l_request_id);
1284    -- End Bug 7299381
1285 
1286         x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP_TC : Request id is - '|| l_request_id;
1287 
1288         IF (g_po_wf_debug = 'Y') THEN
1289           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
1290         END IF;
1291 
1292       END IF; -- language <> supplier language
1293 
1294     END IF; -- if with terms = 'Y' and doc type = std, blanket, contract
1295 
1296   EXCEPTION
1297      /*Begin Changes by Akyanama Bug # 12969112*//*Throwing Submission error*/
1298 	  WHEN submission_error THEN
1299       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF : Exception submitting concurrent request';
1300 	  IF (g_po_wf_debug = 'Y') THEN
1301         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
1302 		x_progress := fnd_message.get;
1303  	    PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
1304       END IF;
1305 	  wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF', itemtype, itemkey, 'PO', x_progress);
1306       RAISE;
1307 	/*End Changes by Akyanama Bug # 12969112*/
1308     WHEN OTHERS THEN
1309       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP_TC: In Exception handler';
1310 
1311       IF (g_po_wf_debug = 'Y') THEN
1312         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
1313       END IF;
1314       wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF_SUPP_TC', x_progress);
1315       raise;
1316 
1317   END GENERATE_PDF_SUPP_TC;
1318 --<FP 11i10+ - R12 Contract ER TC Sup Lang End >
1319 
1320   PROCEDURE GENERATE_PDF_BUYER (itemtype IN VARCHAR2,
1321                                 itemkey IN VARCHAR2,
1322                                 actid IN NUMBER,
1323                                 funcmode IN VARCHAR2,
1324                                 resultout OUT NOCOPY VARCHAR2)
1325   IS
1326 
1327   l_document_id number;
1328   l_document_subtype po_headers.type_lookup_code%TYPE;
1329   l_document_type po_headers.type_lookup_code%TYPE;
1330   l_revision_num number;
1331   l_request_id number;
1332   l_conterm_exists PO_HEADERS_ALL.CONTERMS_EXIST_FLAG%TYPE;
1333   l_authorization_status varchar2(25);
1334   l_progress varchar2(200);
1335    --l_old_request_id  number; --Bug 7299381
1336   l_withterms varchar2(1);
1337 
1338    --<PO Attachment Support 11i.11 Start>
1339   l_attachments_exist varchar2(1); -- holds 'Y' if there are any supplier
1340                                       -- file attachments
1341   l_duplicate_filenames varchar2(1); -- holds 'Y' if there are any supplier
1342                                       -- file attachments with same filename
1343   l_error_flag number; -- determines if the error condition (same file name
1344                         -- but different file lengths has been met or not)
1345   l_max_attachment_size po_system_parameters_all.max_attachment_size%type;
1346   l_filename fnd_lobs.file_name%type;
1347   l_filename_new fnd_lobs.file_name%type;
1348   l_length number;
1349   l_length_new number;
1350   l_set_lang boolean; /*Bug 8135201*/
1351   l_draft_id number; -- CLM
1352   --<BUG 9136162 START>
1353   l_language_code  FND_LANGUAGES.language_code%TYPE;
1354   l_language       fnd_languages.nls_language%TYPE;
1355   l_territory      fnd_languages.nls_territory%TYPE;
1356   --<BUG 9136162 END>
1357   /*Begin Changes by Akyanama Bug # 12969112*//*Declaring Exception*/
1358   submission_error exception;
1359  /*End Changes by Akyanama Bug # 12969112*/
1360    -- bug4931216
1361    -- Join directly to the base table to improve performance
1362   cursor l_get_po_attachments_csr(l_po_header_id number) is
1363     select fl.file_name, dbms_lob.getlength(fl.file_data)
1364     from fnd_documents d,
1365            fnd_attached_documents ad,
1366            fnd_doc_category_usages dcu,
1367            fnd_attachment_functions af,
1368            fnd_lobs fl
1369     where ((ad.pk1_value = to_char(l_po_header_id) and ad.entity_name = 'PO_HEADERS')
1370            OR
1371            (ad.pk1_value = to_char((select vendor_id from po_headers_all
1372                            where po_header_id = l_po_header_id)) and ad.entity_name = 'PO_VENDORS')
1373            OR
1374            (ad.pk1_value in (select to_char(po_line_id) from po_lines_all
1375                               where po_header_id = l_po_header_id
1376                              ) and ad.entity_name = 'PO_LINES')
1377            OR
1378            (ad.pk1_value in (select to_char(from_header_id) from po_lines_all
1379                               where po_header_id = l_po_header_id
1380                               and from_header_id is not null
1381                              ) and ad.entity_name = 'PO_HEADERS')
1382            OR
1383            (ad.pk1_value in (select to_char(from_line_id) from po_lines_all
1384                               where po_header_id = l_po_header_id
1385                               and from_line_id is not null
1386                              ) and ad.entity_name = 'PO_LINES')
1387            OR
1388            (ad.pk1_value in (select to_char(line_location_id) from po_line_locations_all
1389                               where po_header_id = l_po_header_id
1390                               and shipment_type in ('PRICE BREAK', 'STANDARD', 'PREPAYMENT') -- <Complex Work R12>
1391                              ) and ad.entity_name = 'PO_SHIPMENTS')
1392            OR
1393            (ad.pk2_value in (select item_id from po_lines_all
1394                               where po_header_id = l_po_header_id
1395                               and to_char(PO_COMMUNICATION_PVT.getInventoryOrgId()) = ad.pk1_value --Bug 4673653 Use Inventory OrgId
1396                               and item_id is not null
1397                              ) and ad.entity_name = 'MTL_SYSTEM_ITEMS')
1398           )
1399     and d.document_id = ad.document_id
1400     and dcu.category_id = d.category_id
1401     and dcu.attachment_function_id = af.attachment_function_id
1402     and d.datatype_id = 6
1403     and af.function_name = 'PO_PRINTPO'
1404     and d.media_id = fl.file_id
1405     and dcu.enabled_flag = 'Y'
1406     group by fl.file_name, dbms_lob.getlength(fl.file_data)
1407     order by fl.file_name;
1408 
1409    -- bug4931216
1410    -- Join directly to the base table to improve performance
1411   cursor l_get_release_attachments_csr(l_po_release_id number) is
1412     select fl.file_name, dbms_lob.getlength(fl.file_data)
1413     from fnd_documents d,
1414            fnd_attached_documents ad,
1415            fnd_doc_category_usages dcu,
1416            fnd_attachment_functions af,
1417            fnd_lobs fl
1418     where ((ad.pk1_value = to_char((select po_header_id from po_releases_all
1419                            where po_release_id = l_po_release_id
1420                           )) and ad.entity_name = 'PO_HEADERS')
1421            OR
1422            (ad.pk1_value = to_char(l_po_release_id) and ad.entity_name = 'PO_RELEASES')
1423            OR
1424            (ad.pk1_value = to_char((select pha.vendor_id
1425                            from po_headers_all pha, po_releases_all pra
1426                            where pra.po_release_id = l_po_release_id
1427                            and pha.po_header_id = pra.po_header_id
1428                           )) and ad.entity_name = 'PO_VENDORS')
1429            OR
1430            (ad.pk1_value in (select to_char(po_line_id) from po_line_locations_all
1431                               where po_release_id = l_po_release_id
1432                               and shipment_type = 'BLANKET'
1433                              ) and ad.entity_name = 'PO_LINES')
1434            OR
1435            (ad.pk1_value in (select to_char(line_location_id) from po_line_locations_all
1436                               where po_release_id = l_po_release_id
1437                               and shipment_type = 'BLANKET'
1438                              ) and ad.entity_name = 'PO_SHIPMENTS')
1439            OR
1440            (ad.pk2_value in (select pl.item_id
1441                               from po_lines_all pl, po_line_locations_all pll
1442                               where pll.po_release_id = l_po_release_id
1443                               and pll.shipment_type = 'BLANKET'
1444                               and pll.po_line_id = pl.po_line_id
1445                               and to_char(PO_COMMUNICATION_PVT.getInventoryOrgId()) = ad.pk1_value --Bug 4673653 Use Inventory OrgId
1446                               and pl.item_id is not null
1447                              ) AND ad.entity_name = 'MTL_SYSTEM_ITEMS')
1448           )
1449     and d.document_id = ad.document_id
1450     and dcu.category_id = d.category_id
1451     and dcu.attachment_function_id = af.attachment_function_id
1452     and d.datatype_id = 6
1453     and af.function_name = 'PO_PRINTPO'
1454     and d.media_id = fl.file_id
1455     and dcu.enabled_flag = 'Y'
1456     group by fl.file_name, dbms_lob.getlength(fl.file_data)
1457     order by fl.file_name;
1458    --<PO Attachment Support 11i.11 End>
1459 
1460   begin
1461     l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer ';
1462 
1463     IF (g_po_wf_debug = 'Y') THEN
1464       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, l_progress);
1465     END IF;
1466 
1467   -- <Bug 4100416 Start>: Do nothing in cancel or timeout modes.
1468     IF (funcmode <> wf_engine.eng_run)
1469       THEN
1470       resultout := wf_engine.eng_null;
1471       return;
1472     END IF;
1473   -- <Bug 4100416 End>
1474 
1475 
1476     l_document_type := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1477                                                        itemkey => itemkey,
1478                                                        aname => 'DOCUMENT_TYPE');
1479 
1480     l_document_subtype := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1481                                                           itemkey => itemkey,
1482                                                           aname => 'DOCUMENT_SUBTYPE');
1483 
1484     l_document_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
1485                                                        itemkey => itemkey,
1486                                                        aname => 'DOCUMENT_ID');
1487 
1488 	-- CLM
1489 	l_draft_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
1490                                                     itemkey => itemkey,
1491                                                     aname => 'DRAFT_ID');
1492 
1493     l_revision_num := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
1494                                                         itemkey => itemkey,
1495                                                         aname => 'REVISION_NUMBER');
1496 
1497     l_authorization_status := PO_WF_UTIL_PKG.GetItemAttrText(itemtype => itemtype,
1498                                                              itemkey => itemkey,
1499                                                              aname => 'AUTHORIZATION_STATUS');
1500 /*Bug#3583910 Modified the name of the attribute to WITH_TERMS from WITHTERMS */
1501     l_withterms := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1502                                                    itemkey => itemkey,
1503                                                    aname => 'WITH_TERMS');
1504 
1505     --<BUG 9136162 START>
1506     l_language_code := PO_WF_UTIL_PKG.GetItemAttrText(itemtype => itemtype,
1507 			    			      itemkey => itemkey,
1508 						      aname=>'LANGUAGE_CODE');
1509 
1510     --Bug 13069700 - Adding exception block.
1511     BEGIN
1512        SELECT nls_language, nls_territory
1513              INTO l_language, l_territory
1514           FROM fnd_languages
1515           WHERE language_code = l_language_code;
1516     EXCEPTION
1517          WHEN NO_DATA_FOUND THEN
1518                l_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_BUYER : in exception handler';
1519                   IF (g_po_wf_debug = 'Y') THEN
1520                           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,l_progress);
1521                   END IF;
1522      END;
1523     --<BUG 9136162 END>
1524 
1525   --Bug 7299381
1526   /*
1527   l_old_request_id := PO_WF_UTIL_PKG.GetItemAttrNumber(itemtype   => itemtype,
1528                                                     itemkey    => itemkey,
1529                 aname=>'REQUEST_ID');
1530   */
1531 
1532   /*  Bug6841986/6528046
1533     PO Approval Workflow makes some calls to these procedures, to create pdf files, based on
1534     some criteria like Terms and Conditions attached or not and whether Supplier language is
1535     different from Buyer's language or not.
1536     From those different calls, these procedures return the CP request IDs based on different
1537     priorities. Corrected the calls order and Request ID updation criteria based on their priorities.
1538   */
1539 
1540   /* Bug6841986/6528046
1541     IF l_document_type in ('PO','PA') and l_document_subtype in ('STANDARD','BLANKET','CONTRACT') THEN
1542       IF l_old_request_id is null and l_withterms = 'Y' THEN
1543         l_withterms := 'Y' ;
1544       ELSIF l_old_request_id is not null THEN
1545         l_withterms := 'N';
1546       END IF;
1547     ELSE
1548       l_withterms :='N';
1549     END IF;
1550   */ --End Bug6841986/6528046
1551 
1552     l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer :Launching the Dispatch Purchase Order program ';
1553 
1554     IF (g_po_wf_debug = 'Y') THEN
1555       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, l_progress);
1556     END IF;
1557 
1558 --Bug#3481824 Need to pass document type as
1559 --RELEASE in case of a release to the concurrent program
1560 
1561     IF l_document_type = 'RELEASE' THEN
1562       l_document_subtype := 'RELEASE';
1563     END IF;
1564 
1565     --<PO Attachment Support 11i.11 Start>
1566     -- In the whole of Zip generation process, all unexpected exceptions must
1567     -- be handled and none should be raised to the workflow because that will
1568     -- stop the workflow process would prevent sending the error notification.
1569     -- In case of any unexpected exceptions, the exception should be handled
1570     -- and workflow attribute ZIP_ERROR_CODE should be set to 'UNEXPECTED' so
1571     -- that corresponding error notification can be sent to buyer and supplier.
1572     -- Also in case of exception, l_max_attachment_size should be set to 0 so
1573     -- that Zip file is not generated.
1574     Begin
1575         -- Get the 'Maximum Attachment Size' value from Purchasing Options
1576         -- A value of 0 means Zip Attachments are not supported
1577       l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer: Get max zip attachment size ';
1578       l_max_attachment_size := get_max_zip_size(itemtype, itemkey);
1579 
1580       IF l_max_attachment_size > 0 THEN
1581             -- If PO has no 'To Supplier' file attachments then 'Zip Attachment' link
1582             -- should not show up in the notifications and Zip file should not be generated
1583         l_attachments_exist := 'N';
1584         l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer: Checking for supplier file attachments';
1585         Begin
1586           l_attachments_exist := check_for_attachments(p_document_type => l_document_type,
1587                                                        p_document_id => l_document_id);
1588         Exception when no_data_found then
1589             l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer: No supplier file attachments exist for this document';
1590             IF (g_po_wf_debug = 'Y') THEN
1591               PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, l_progress);
1592             END IF;
1593             l_max_attachment_size := 0; -- No need to generate zip file if no 'To Supplier' file attachments exist
1594         End;
1595 
1596         IF l_attachments_exist = 'Y' THEN
1597           l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer: Setting workflow attribute to display Zip Attachment';
1598           PO_WF_UTIL_PKG.SetItemAttrText (itemtype => itemtype,
1599                                           itemkey => itemkey,
1600                                           aname => 'ZIP_ATTACHMENT',
1601                                           avalue => 'PLSQLBLOB:PO_COMMUNICATION_PVT.ZIP_ATTACH/' || itemtype || ':' || itemkey);
1602 
1603 
1604                 -- An error condition is when two or more file attachments have the same file name
1605                 -- but different file sizes. In this case a zip error notification should be sent
1606                 -- and zip file should not be generated.
1607                 -- Following two cases are ok:
1608                 --   1. There are no duplicate file names in the PO Attachments
1609                 --   2. Files with same name also have the same sizes
1610                 -- Case 1 would be most common and is given highest priority in terms of performance.
1611                 -- So a separate query for finding duplicate file names is written. If no duplicate
1612                 -- file names then cursors for checking the error condition are not opened.
1613 
1614           l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer : Check for duplicate filenames';
1615           l_duplicate_filenames := 'N';
1616 
1617 
1618           IF (l_document_subtype = 'RELEASE') THEN
1619 
1620                     -- bug4917605
1621                     -- User base table to improve performance
1622             Begin
1623               select 'Y' into l_duplicate_filenames from dual
1624               where exists
1625               (
1626                   select fl.file_name
1627                   from fnd_documents d,
1628                        fnd_attached_documents ad,
1629                        fnd_doc_category_usages dcu,
1630                        fnd_attachment_functions af,
1631                        fnd_lobs fl
1632                   where ((ad.pk1_value = to_char((select po_header_id from po_releases_all
1633                                          where po_release_id = l_document_id
1634                                         )) and ad.entity_name = 'PO_HEADERS')
1635                          OR
1636                          (ad.pk1_value = to_char(l_document_id) and ad.entity_name = 'PO_RELEASES')
1637                          OR
1638                          (ad.pk1_value = (select pha.vendor_id
1639                                          from po_headers_all pha, po_releases_all pra
1640                                          where pra.po_release_id = l_document_id
1641                                          and pha.po_header_id = pra.po_header_id
1642                                         ) and ad.entity_name = 'PO_VENDORS')
1643                          OR
1644                          (ad.pk1_value in (select to_char(po_line_id) from po_line_locations_all
1645                                             where po_release_id = l_document_id
1646                                             and shipment_type = 'BLANKET'
1647                                            ) and ad.entity_name = 'PO_LINES')
1648                          OR
1649                          (ad.pk1_value in (select to_char(line_location_id) from po_line_locations_all
1650                                             where po_release_id = l_document_id
1651                                             and shipment_type = 'BLANKET'
1652                                            ) and ad.entity_name = 'PO_SHIPMENTS')
1653                          OR
1654                          (ad.pk2_value in (select pl.item_id
1655                                             from po_lines_all pl, po_line_locations_all pll
1656                                             where pll.po_release_id = l_document_id
1657                                             and pll.shipment_type = 'BLANKET'
1658                                             and pll.po_line_id = pl.po_line_id
1659                                             and to_char(PO_COMMUNICATION_PVT.getInventoryOrgId()) = ad.pk1_value --Bug 4673653 Use Inventory OrgId
1660                                             and pl.item_id is not null
1661                                            ) AND ad.entity_name = 'MTL_SYSTEM_ITEMS')
1662                         )
1663                   and d.document_id = ad.document_id
1664                   and dcu.category_id = d.category_id
1665                   and dcu.attachment_function_id = af.attachment_function_id
1666                   and d.datatype_id = 6
1667                   and af.function_name = 'PO_PRINTPO'
1668                   and d.media_id = fl.file_id
1669                   and dcu.enabled_flag = 'Y'
1670                   group by fl.file_name
1671                   having count(*)>1
1672               );
1673                     -- If no_data_found then let l_duplicate_filename remain 'N'
1674                     -- so that cursor is not opened. All other exceptions raised
1675                     -- until caught by outer exception handler
1676             Exception when no_data_found then
1677                 l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer: No duplicate filenames exist in the attachments for this Release';
1678                 IF (g_po_wf_debug = 'Y') THEN
1679                   PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, l_progress);
1680                 END IF;
1681             End;
1682           ELSE
1683                     -- bug4917605
1684                     -- User base table to improve performance
1685             Begin
1686               select 'Y' into l_duplicate_filenames from dual
1687               where exists
1688               (
1689                   select fl.file_name
1690                   from fnd_documents d,
1691                        fnd_attached_documents ad,
1692                        fnd_doc_category_usages dcu,
1693                        fnd_attachment_functions af,
1694                        fnd_lobs fl
1695                   where ((ad.pk1_value = to_char(l_document_id) and ad.entity_name = 'PO_HEADERS')
1696                          OR
1697                          (ad.pk1_value = to_char((select vendor_id from po_headers_all
1698                                          where po_header_id = l_document_id)) and ad.entity_name = 'PO_VENDORS')
1699                          OR
1700                          (ad.pk1_value in (select to_char(po_line_id) from po_lines_all
1701                                             where po_header_id = l_document_id
1702                                            ) and ad.entity_name = 'PO_LINES')
1703                          OR
1704                          (ad.pk1_value in (select to_char(from_header_id) from po_lines_all
1705                                             where po_header_id = l_document_id
1706                                             and from_header_id is not null
1707                                            ) and ad.entity_name = 'PO_HEADERS')
1708                          OR
1709                          (ad.pk1_value in (select to_char(from_line_id) from po_lines_all
1710                                             where po_header_id = l_document_id
1711                                             and from_line_id is not null
1712                                            ) and ad.entity_name = 'PO_LINES')
1713                          OR
1714                          (ad.pk1_value in (select to_char(line_location_id) from po_line_locations_all
1715                                             where po_header_id = l_document_id
1716                                             and shipment_type in ('PRICE BREAK', 'STANDARD', 'PREPAYMENT') -- <Complex Work R12>
1717                                            ) and ad.entity_name = 'PO_SHIPMENTS')
1718                          OR
1719                          (ad.pk2_value in (select item_id from po_lines_all
1720                                             where po_header_id = l_document_id
1721                                             and to_char(PO_COMMUNICATION_PVT.getInventoryOrgId()) = ad.pk1_value --Bug 4673653 Use Inventory OrgId
1722                                             and item_id is not null
1723                                            ) and ad.entity_name = 'MTL_SYSTEM_ITEMS')
1724                         )
1725                   and d.document_id = ad.document_id
1726                   and dcu.category_id = d.category_id
1727                   and dcu.attachment_function_id = af.attachment_function_id
1728                   and d.datatype_id = 6
1729                   and af.function_name = 'PO_PRINTPO'
1730                   and d.media_id = fl.file_id
1731                   and dcu.enabled_flag = 'Y'
1732                   group by fl.file_name
1733                   having count(*)>1
1734               );
1735                     -- If no_data_found then let l_duplicate_filename remain 'N'
1736                     -- so that cursor is not opened. All other exceptions raised
1737                     -- until caught by outer exception handler
1738             Exception when no_data_found then
1739                 l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer: No duplicate filenames exist in the attachments for this PO';
1740                 IF (g_po_wf_debug = 'Y') THEN
1741                   PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, l_progress);
1742                 END IF;
1743             End;
1744           END IF;
1745 
1746           IF l_duplicate_filenames = 'Y' THEN
1747             l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer : Duplicate filenames found.';
1748             IF (l_document_subtype = 'RELEASE') THEN
1749               open l_get_release_attachments_csr(l_document_id);
1750             ELSE
1751               open l_get_po_attachments_csr(l_document_id);
1752             END IF;
1753 
1754             l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer : execute loop to get duplicate filenames with error condition';
1755             IF (g_po_wf_debug = 'Y') THEN
1756               PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, l_progress);
1757             END IF;
1758 
1759             l_error_flag := 0;
1760             LOOP
1761               IF (l_document_subtype = 'RELEASE') THEN
1762                 fetch l_get_release_attachments_csr into l_filename_new, l_length_new;
1763                 exit when (l_get_release_attachments_csr%notfound);
1764               ELSE
1765                 fetch l_get_po_attachments_csr into l_filename_new, l_length_new;
1766                 exit when (l_get_po_attachments_csr%notfound);
1767               END IF;
1768               IF (l_filename_new = l_filename AND l_length_new <> l_length) THEN
1769                 l_error_flag := 1;
1770                 exit;
1771               END IF;
1772               l_filename := l_filename_new; l_length := l_length_new;
1773             END LOOP;
1774             IF (l_document_subtype = 'RELEASE') THEN
1775               close l_get_release_attachments_csr;
1776             ELSE
1777               close l_get_po_attachments_csr;
1778             END IF;
1779 
1780             l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer : error flag = '|| l_error_flag;
1781             IF (g_po_wf_debug = 'Y') THEN
1782               PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, l_progress);
1783             END IF;
1784 
1785             IF l_error_flag = 1 THEN
1786               set_zip_error_code(itemtype, itemkey, 'DUPLICATE_FILENAME');
1787               l_max_attachment_size := 0; -- No need to generate zip file if it is an error
1788             END IF;
1789           END IF; --IF l_duplicate_filenames = 'Y'
1790         END IF; --IF l_attachments_exist = 'Y'
1791       END IF; --IF l_max_attachment_size > 0
1792     Exception when others then
1793         IF (g_po_wf_debug = 'Y') THEN
1794           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, l_progress);
1795           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,'PO_COMMUNICATION_PVT.generate_pdf_buyer: Caught Zip generation exception '|| SQLERRM);
1796         END IF;
1797         set_zip_error_code(itemtype, itemkey, 'UNEXPECTED');
1798         l_max_attachment_size := 0; -- No need to generate zip file if it is an error
1799     End;
1800     --<PO Attachment Support 11i.11 End>
1801 
1802 
1803   -- Generate the pdf in the Buyers language without T's and C's
1804   /*Bug 8135201*/
1805     l_set_lang := fnd_request.set_options('NO', 'NO', l_language, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS')); --<BUG 9136162>
1806 
1807 --<R12 MOAC START>
1808     po_moac_utils_pvt.set_request_context(po_moac_utils_pvt.get_current_org_id);
1809 --<R12 MOAC END>
1810   --Bug5080617 Pass the parameters P_PO_TEMPLATE_CODE and P_CONTRACT_TEMPLATE_CODE as null
1811     l_request_id := fnd_request.submit_request('PO',
1812                                                'POXPOPDF',
1813                                                null,
1814                                                null,
1815                                                false,
1816                                                'R', --P_report_type
1817                                                null , --P_agend_id
1818                                                null, --P_po_num_from
1819                                                null , --P_po_num_to
1820                                                null , --P_relaese_num_from
1821                                                null , --P_release_num_to
1822                                                null , --P_date_from
1823                                                null , --P_date_to
1824                                                null , --P_approved_flag
1825                                                'N', --P_test_flag
1826                                                null , --P_print_releases
1827                                                null , --P_sortby
1828                                                null , --P_user_id
1829                                                null , --P_fax_enable
1830                                                null , --P_fax_number
1831                                                null , --P_BLANKET_LINES
1832                                                'View', --View_or_Communicate,
1833         --Bug6841986/6528046
1834         --l_withterms,--P_WITHTERMS
1835                                                'N', --P_WITHTERMS
1836                                                'Y', --P_storeFlag
1837                                                'N', --P_PRINT_FLAG
1838                                                l_document_id, --P_DOCUMENT_ID
1839 											   l_draft_id,  -- P_DRAFT_ID
1840                                                l_revision_num, --P_REVISION_NUM
1841                                                l_authorization_status, --P_AUTHORIZATION_STATUS
1842                                                l_document_subtype, --P_DOCUMENT_TYPE
1843                                                l_max_attachment_size,--P_max_zip_size, <PO Attachment Support 11i.11>
1844                                                null, -- P_PO_TEMPLATE_CODE
1845                                                null, -- P_CONTRACT_TEMPLATE_CODE
1846                                                fnd_global.local_chr(0),
1847                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1848                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1849                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1850                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1851                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1852                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1853                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1854                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1855                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1856                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1857                                                NULL);
1858 
1859     l_progress := 'PO_COMMUNICATION_PVT.generate_pdf_buyer : Request id is - '|| l_request_id;
1860     /*Begin Changes by Akyanama Bug # 12969112*//*Checking if the request id is valid or not before setting work flow variables*/
1861 	       if (l_request_id <= 0 or l_request_id is null) then
1862 				raise submission_error;
1863 			end if;
1864 	/*End Changes by Akyanama Bug # 12969112*/
1865     IF (g_po_wf_debug = 'Y') THEN
1866       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, l_progress);
1867     END IF;
1868 
1869     PO_WF_UTIL_PKG.SetItemAttrNumber (itemtype => itemtype,
1870                                       itemkey => itemkey,
1871                                       aname => 'REQUEST_ID',
1872                                       avalue => l_request_id);
1873 
1874   EXCEPTION
1875     /*Begin Changes by Akyanama Bug # 12969112*//*Throwing Submission error*/
1876 	  WHEN submission_error THEN
1877       l_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF : Exception submitting concurrent request';
1878 	  IF (g_po_wf_debug = 'Y') THEN
1879         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, l_progress);
1880       END IF;
1881 	  wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF', itemtype, itemkey, 'PO', l_progress);
1882       RAISE;
1883     /*End Changes by Akyanama Bug # 12969112*/
1884     WHEN OTHERS THEN
1885 
1886       IF (g_po_wf_debug = 'Y') THEN
1887         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, l_progress);
1888       END IF;
1889 
1890       wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF_BUYER', l_progress);
1891       raise;
1892 
1893   END GENERATE_PDF_BUYER;
1894 
1895   PROCEDURE GENERATE_PDF_SUPP (itemtype IN VARCHAR2,
1896                                itemkey IN VARCHAR2,
1897                                actid IN NUMBER,
1898                                funcmode IN VARCHAR2,
1899                                resultout OUT NOCOPY VARCHAR2)
1900   IS
1901   l_document_id number;
1902   l_document_subtype po_headers.type_lookup_code%TYPE;
1903   l_document_type po_headers.type_lookup_code%TYPE;
1904   l_revision_num number;
1905   l_request_id number;
1906   l_territory varchar2(30);
1907   l_set_lang boolean;
1908   x_progress varchar2(100);
1909   l_language_code fnd_languages.language_code%type;
1910   l_supp_lang varchar2(30);
1911   l_language varchar2(25);
1912   l_authorization_status varchar2(25);
1913    --l_old_request_id  number; --Bug 7299381
1914   l_header_id number;
1915    --Bug6841986/6528046
1916   l_withterms varchar2(1);
1917    --End Bug6841986/6528046
1918    l_draft_id number;  -- CLM
1919    /*Begin Changes by Akyanama Bug # 12969112*//*Declaring Exception*/
1920   submission_error exception;
1921  /*End Changes by Akyanama Bug # 12969112*/
1922   begin
1923     x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP';
1924 
1925     IF (g_po_wf_debug = 'Y') THEN
1926       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
1927     END IF;
1928 
1929     --Start of code changes for the bug 12403413
1930     -- Do nothing in cancel or timeout modes. Similar to the bug 4100416
1931     IF (funcmode <> wf_engine.eng_run)
1932       THEN
1933       resultout := wf_engine.eng_null;
1934       return;
1935     END IF;
1936     --End of code changes for the bug 12403413
1937 
1938     l_document_type := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1939                                                        itemkey => itemkey,
1940                                                        aname => 'DOCUMENT_TYPE');
1941 
1942     l_document_subtype := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1943                                                           itemkey => itemkey,
1944                                                           aname => 'DOCUMENT_SUBTYPE');
1945 
1946     l_document_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
1947                                                        itemkey => itemkey,
1948                                                        aname => 'DOCUMENT_ID');
1949 
1950 	-- CLM
1951 	l_draft_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
1952                                                        itemkey => itemkey,
1953                                                        aname => 'DRAFT_ID');
1954 
1955     l_revision_num := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
1956                                                         itemkey => itemkey,
1957                                                         aname => 'REVISION_NUMBER');
1958 
1959     l_language_code := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1960                                                        itemkey => itemkey,
1961                                                        aname => 'LANGUAGE_CODE');
1962 
1963   --Bug6841986/6528046 Added
1964     l_withterms := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
1965                                                    itemkey => itemkey,
1966                                                    aname => 'WITH_TERMS');
1967 
1968   --Bug 7299381
1969   /*l_old_request_id := PO_WF_UTIL_PKG.GetItemAttrNumber(itemtype   => itemtype,
1970                                          itemkey    => itemkey,
1971                                          aname=>'REQUEST_ID');
1972   */
1973   --End Bug6841986/6528046
1974 
1975     IF l_document_type in ('PO', 'PA') and l_document_subtype in ('STANDARD', 'BLANKET', 'CONTRACT') THEN
1976       l_header_id := l_document_id;
1977     ELSE
1978     /* Bug 8372255 Added exception handler for the below sqls.*/
1979      BEGIN
1980       SELECT po_header_id into l_header_id FROM po_releases_all
1981       WHERE po_release_id = l_document_id;
1982     EXCEPTION
1983       WHEN NO_DATA_FOUND THEN
1984               x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP -000: in exception handler';
1985            IF (g_po_wf_debug = 'Y') THEN
1986 	 PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
1987             END IF;
1988      END;
1989     END IF;
1990 
1991    BEGIN
1992     SELECT pv.language into l_supp_lang
1993     FROM po_vendor_sites_all pv, po_headers_all ph
1994     WHERE
1995     ph.po_header_id = l_header_id and ph.vendor_site_id = pv.vendor_site_id;
1996    EXCEPTION
1997      WHEN NO_DATA_FOUND THEN
1998            x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP -001: in exception handler';
1999          IF (g_po_wf_debug = 'Y') THEN
2000  	  PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
2001          END IF;
2002     END;
2003 
2004     x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP :launching the Dispatch Purchase Order concurrent program ';
2005 
2006     IF (g_po_wf_debug = 'Y') THEN
2007       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
2008     END IF;
2009 
2010   --set the suppliers language before launching the concurrent request
2011   -- Bug6841986/6528046 changed userenv('LANG')==> l_language_code
2012   BEGIN
2013     SELECT nls_language INTO l_language
2014     FROM fnd_languages
2015     WHERE language_code = l_language_code;
2016   EXCEPTION
2017     WHEN NO_DATA_FOUND THEN
2018                x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP -002: in exception handler';
2019                   IF (g_po_wf_debug = 'Y') THEN
2020                           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
2021                   END IF;
2022    END;
2023 
2024   --End Bug6841986/6528046
2025 
2026     if l_language <> l_supp_lang then
2027      BEGIN
2028       select nls_territory into l_territory from fnd_languages where
2029       nls_language = l_supp_lang;
2030      EXCEPTION
2031        WHEN NO_DATA_FOUND THEN
2032                    x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP -003: in exception handler';
2033                      IF (g_po_wf_debug = 'Y') THEN
2034                               PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
2035                     END IF;
2036       END;
2037 
2038    /*Bug 8135201*/
2039       l_set_lang := fnd_request.set_options('NO', 'NO', l_supp_lang, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS'));
2040 
2041 --Bug#3481824 Need to pass document type as
2042 --RELEASE in case of a release to the concurrent program
2043       IF l_document_type = 'RELEASE' THEN
2044         l_document_subtype := 'RELEASE';
2045       END IF;
2046 
2047 --<R12 MOAC START>
2048       po_moac_utils_pvt.set_request_context(po_moac_utils_pvt.get_current_org_id);
2049 --<R12 MOAC END>
2050 --Bug5080617 Pass the parameters P_PO_TEMPLATE_CODE and P_CONTRACT_TEMPLATE_CODE as null
2051       l_request_id := fnd_request.submit_request('PO',
2052                                                  'POXPOPDF',
2053                                                  null,
2054                                                  null,
2055                                                  false,
2056                                                  'R', --P_report_type
2057                                                  null , --P_agend_id
2058                                                  null, --P_po_num_from
2059                                                  null , --P_po_num_to
2060                                                  null , --P_relaese_num_from
2061                                                  null , --P_release_num_to
2062                                                  null , --P_date_from
2063                                                  null , --P_date_to
2064                                                  null , --P_approved_flag
2065                                                  'N', --P_test_flag
2066                                                  null , --P_print_releases
2067                                                  null , --P_sortby
2068                                                  null , --P_user_id
2069                                                  null , --P_fax_enable
2070                                                  null , --P_fax_number
2071                                                  null , --P_BLANKET_LINES
2072                                                  'View', --View_or_Communicate,
2073                                                  'N', --P_WITHTERMS
2074                                                  'Y', --P_storeFlag
2075                                                  'N', --P_PRINT_FLAG
2076                                                  l_document_id, --P_DOCUMENT_ID
2077 												 l_draft_id,  --P_DRAFT_ID
2078                                                  l_revision_num, --P_REVISION_NUM
2079                                                  l_authorization_status, --P_AUTHORIZATION_STATUS
2080                                                  l_document_subtype, --P_DOCUMENT_TYPE
2081                                                  0,--P_max_zip_size, <PO Attachment Support 11i.11>
2082                                                  null, --P_PO_TEMPLATE_CODE
2083                                                  null, --P_CONTRACT_TEMPLATE_CODE
2084                                                  fnd_global.local_chr(0),
2085                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2086                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2087                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2088                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2089                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2090                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2091                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2092                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2093                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2094                                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2095                                                  NULL);
2096 
2097       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP : Request id is - '|| l_request_id;
2098 
2099       IF (g_po_wf_debug = 'Y') THEN
2100         PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
2101       END IF;
2102       /*Begin Changes by Akyanama Bug # 12969112*//*Checking if the request id is valid or not before setting work flow variables*/
2103 		if (l_request_id <= 0 or l_request_id is null) then
2104 			raise submission_error;
2105 		end if;
2106 	  /*End Changes by Akyanama Bug # 12969112*/
2107   -- Bug 7299381
2108       PO_WF_UTIL_PKG.SetItemAttrNumber (itemtype => itemtype,
2109                                         itemkey => itemkey,
2110                                         aname => 'REQUEST_ID',
2111                                         avalue => l_request_id);
2112   -- End Bug 7299381
2113 
2114     end if;
2115 
2116   EXCEPTION
2117     /*Begin Changes by Akyanama Bug # 12969112*//*Throwing Submission error*/
2118 	  WHEN submission_error THEN
2119       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF : Exception submitting concurrent request';
2120 	  IF (g_po_wf_debug = 'Y') THEN
2121         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
2122 		x_progress := fnd_message.get;
2123  	    PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
2124       END IF;
2125 	  wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF', itemtype, itemkey, 'PO', x_progress);
2126       RAISE;
2127 
2128 	/*End Changes by Akyanama Bug # 12969112*/
2129     WHEN OTHERS THEN
2130       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_SUPP: In Exception handler';
2131 
2132       IF (g_po_wf_debug = 'Y') THEN
2133         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
2134       END IF;
2135       wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF_SUPP', x_progress);
2136       raise;
2137 
2138   END GENERATE_PDF_SUPP;
2139 
2140   PROCEDURE GENERATE_PDF_EMAIL_PROCESS (itemtype IN VARCHAR2,
2141                                         itemkey IN VARCHAR2,
2142                                         actid IN NUMBER,
2143                                         funcmode IN VARCHAR2,
2144                                         resultout OUT NOCOPY VARCHAR2)
2145   IS
2146 
2147   l_document_id number;
2148   l_document_subtype po_headers.type_lookup_code%TYPE;
2149      	--Bug13774287
2150    l_document_type po_headers.type_lookup_code%TYPE;
2151    	--End Bug13774287
2152   l_revision_num number;
2153   l_request_id number;
2154   l_language_code varchar2(25);
2155   x_progress varchar2(200);
2156   l_withterms varchar2(1);
2157   l_set_lang boolean;
2158   l_territory varchar2(30);
2159   l_authorization_status varchar2(25);
2160   --l_language varchar2(10);
2161   /*Begin Changes by Akyanama Bug # 12969112*/
2162    l_language fnd_languages.nls_language%type ;
2163    /*End Changes by Akyanama Bug # 12969112*/
2164   l_draft_id number;
2165   /*Begin Changes by Akyanama Bug # 12969112*//*Declaring Exception*/
2166   submission_error exception;
2167  /*End Changes by Akyanama Bug # 12969112*/
2168 
2169   begin
2170     x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_EMAIL_PROCESS';
2171 
2172     IF (g_po_wf_debug = 'Y') THEN
2173       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
2174     END IF;
2175 
2176     l_language_code := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
2177                                                        itemkey => itemkey,
2178                                                        aname => 'LANGUAGE_CODE');
2179 
2180 --set the suppliers language before launching the concurrent request
2181 
2182      --Bug 13069700 - Adding exception block.
2183     BEGIN
2184         select nls_territory into l_territory from fnd_languages where
2185          language_code = l_language_code;
2186     EXCEPTION
2187           WHEN NO_DATA_FOUND THEN
2188                x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_EMAIL_PROCESS -001: in exception handler';
2189                   IF (g_po_wf_debug = 'Y') THEN
2190                           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
2191                   END IF;
2192      END;
2193 	  --Bug13774287
2194   l_document_type := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
2195  	                                             itemkey  => itemkey,
2196                                                 aname    => 'DOCUMENT_TYPE');
2197   --End Bug13774287
2198 
2199 
2200 
2201     l_document_subtype := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
2202                                                           itemkey => itemkey,
2203                                                           aname => 'DOCUMENT_SUBTYPE');
2204 
2205     l_document_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
2206                                                        itemkey => itemkey,
2207                                                        aname => 'DOCUMENT_ID');
2208 
2209 	l_draft_id := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
2210                                                        itemkey => itemkey,
2211                                                        aname => 'DRAFT_ID');
2212 
2213     l_withterms := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
2214                                                    itemkey => itemkey,
2215                                                    aname => 'WITH_TERMS');
2216 
2217     l_revision_num := PO_WF_UTIL_PKG.GetItemAttrNumber (itemtype => itemtype,
2218                                                         itemkey => itemkey,
2219                                                         aname => 'REVISION_NUMBER');
2220 
2221     l_authorization_status := PO_WF_UTIL_PKG.GetItemAttrText (itemtype => itemtype,
2222                                                               itemkey => itemkey,
2223                                                               aname => 'AUTHORIZATION_STATUS');
2224 
2225     x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_EMAIL_PROCESS:launching the Dispatch Purchase Order concurrent program ';
2226 
2227     IF (g_po_wf_debug = 'Y') THEN
2228       PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY, x_progress);
2229     END IF;
2230 
2231     IF l_language_code <> userenv('LANG') THEN
2232 
2233 --set the suppliers language before launching the concurrent request
2234 
2235       --Bug 13069700 - Adding exception block.
2236       BEGIN
2237 
2238       select nls_language, nls_territory into l_language , l_territory from fnd_languages where
2239       language_code = l_language_code;
2240 
2241       EXCEPTION
2242           WHEN NO_DATA_FOUND THEN
2243                x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_EMAIL_PROCESS -002: in exception handler';
2244                   IF (g_po_wf_debug = 'Y') THEN
2245                           PO_WF_DEBUG_PKG.INSERT_DEBUG(ITEMTYPE, ITEMKEY,x_progress);
2246                   END IF;
2247        END;
2248 
2249     /*Bug 8135201*/
2250       l_set_lang := fnd_request.set_options('NO', 'NO', l_language, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS'));
2251 
2252     END IF;
2253 
2254 --<R12 MOAC START>
2255     po_moac_utils_pvt.set_request_context(po_moac_utils_pvt.get_current_org_id);
2256 --<R12 MOAC END>
2257 		--Bug13774287 Need to pass document type as
2258 	--RELEASE in case of a release to the concurrent program
2259 	IF l_document_type ='RELEASE' THEN
2260 	   l_document_subtype :='RELEASE';
2261 	END IF;
2262 	--END Bug13774287
2263 
2264 --Bug5080617 Pass the parameters P_PO_TEMPLATE_CODE and P_CONTRACT_TEMPLATE_CODE as null
2265     l_request_id := fnd_request.submit_request('PO',
2266                                                'POXPOPDF',
2267                                                null,
2268                                                null,
2269                                                false,
2270                                                'R', --P_report_type
2271                                                null , --P_agent_name
2272                                                null, --P_po_num_from
2273                                                null , --P_po_num_to
2274                                                null , --P_relaese_num_from
2275                                                null , --P_release_num_to
2276                                                null , --P_date_from
2277                                                null , --P_date_to
2278                                                null , --P_approved_flag
2279                                                'N', --P_test_flag
2280                                                null , --P_print_releases
2281                                                null , --P_sortby
2282                                                null , --P_user_id
2283                                                null , --P_fax_enable
2284                                                null , --P_fax_number
2285                                                null , --P_BLANKET_LINES
2286                                                'Communicate', --View_or_Communicate,
2287                                                l_withterms, --P_WITHTERMS
2288                                                'Y', --P_storeFlag
2289                                                'N', --P_PRINT_FLAG
2290                                                l_document_id, --P_DOCUMENT_ID
2291 											   l_draft_id, -- P_DRAFT_ID
2292                                                l_revision_num, --P_REVISION_NUM
2293                                                l_authorization_status, --P_AUTHORIZATION_STATUS
2294                                                l_document_subtype, --P_DOCUMENT_TYPE
2295                                                0,--P_max_zip_size, <PO Attachment Support 11i.11>
2296                                                null, -- P_PO_TEMPLATE_CODE
2297                                                null, -- P_CONTRACT_TEMPLATE_CODE
2298                                                fnd_global.local_chr(0),
2299                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2300                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2301                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2302                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2303                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2304                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2305                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2306                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2307                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2308                                                NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2309                                                NULL);
2310 
2311             /*Begin Changes by Akyanama Bug # 12969112*//*Checking if the request id is valid or not before setting work flow variables*/
2312 			  if (l_request_id <= 0 or l_request_id is null) then
2313 				raise submission_error;
2314 			  end if;
2315 			/*End Changes by Akyanama Bug # 12969112*/
2316     PO_WF_UTIL_PKG.SetItemAttrNumber (itemtype => itemtype,
2317                                       itemkey => itemkey,
2318                                       aname => 'REQUEST_ID',
2319                                       avalue => l_request_id);
2320 
2321 
2322   EXCEPTION
2323     /*Begin Changes by Akyanama Bug # 12969112*//*Throwing Submission error*/
2324 	  WHEN submission_error THEN
2325       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF : Exception submitting concurrent request';
2326 	  IF (g_po_wf_debug = 'Y') THEN
2327         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
2328 		 x_progress := fnd_message.get;
2329  	    PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
2330       END IF;
2331 	  wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF', itemtype, itemkey, 'PO', x_progress);
2332       RAISE;
2333 
2334 	/*End Changes by Akyanama Bug # 12969112*/
2335     WHEN OTHERS THEN
2336       x_progress := 'PO_COMMUNICATION_PVT.GENERATE_PDF_EMAIL_PROCESS: In Exception handler';
2337 
2338       IF (g_po_wf_debug = 'Y') THEN
2339         PO_WF_DEBUG_PKG.insert_debug(itemtype, itemkey, x_progress);
2340       END IF;
2341       wf_core.context('PO_COMMUNICATION_PVT', 'GENERATE_PDF_EMAIL_PROCESS', x_progress);
2342       RAISE ;
2343 
2344   END GENERATE_PDF_EMAIL_PROCESS;
2345 
2346 
2347 
2348   PROCEDURE launch_communicate(p_mode in varchar2,
2349                                p_document_id in number ,
2350                                p_revision_number in number ,
2351                                p_document_type in varchar2,
2352                                p_authorization_status in varchar2,
2353                                p_language_code in varchar2,
2354                                p_fax_enable in varchar2,
2355                                p_fax_num in varchar2,
2356                                p_with_terms in varchar2,
2357                                p_print_flag in varchar2,
2358                                p_store_flag in varchar2,
2359                                p_request_id out NOCOPY number) is
2360 
2361   l_po_num po_headers.segment1%type := NULL;
2362   l_po_header_id po_headers.po_header_id%type := NULL;
2363   l_po_release_id po_releases.po_release_id%type := NULL;
2364   l_communication varchar2(1);
2365   l_api_name CONSTANT VARCHAR2(25) := 'launch_communicate';
2366 
2367   BEGIN
2368     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
2369       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name || '.begin', 'launch_communicate');
2370     END IF;
2371     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
2372       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name || 'Communication method ', p_mode);
2373     END IF;
2374     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
2375       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name || 'Document Type  ', p_document_type);
2376     END IF;
2377 
2378     if p_mode = 'PRINT' then
2379 
2380       if p_document_type in ('STANDARD', 'BLANKET', 'CONTRACT') then
2381 
2382 
2383 --<R12 MOAC START>
2384         po_moac_utils_pvt.set_request_context(po_moac_utils_pvt.get_current_org_id);
2385 --<R12 MOAC END>
2386 --Bug5080617 Pass the parameters P_PO_TEMPLATE_CODE and P_CONTRACT_TEMPLATE_CODE as null
2387         p_request_id := fnd_request.submit_request('PO',
2388                                                    'POXPOPDF',
2389                                                    null,
2390                                                    null,
2391                                                    false,
2392                                                    'R', --P_report_type
2393                                                    null , --P_agent_name
2394                                                    null, --P_po_num_from
2395                                                    null , --P_po_num_to
2396                                                    null , --P_relaese_num_from
2397                                                    null , --P_release_num_to
2398                                                    null , --P_date_from
2399                                                    null , --P_date_to
2400                                                    null , --P_approved_flag
2401                                                    'N', --P_test_flag
2402                                                    null , --P_print_releases
2403                                                    null , --P_sortby
2404                                                    null , --P_user_id
2405                                                    null , --P_fax_enable
2406                                                    null , --P_fax_number
2407                                                    null , --P_BLANKET_LINES
2408                                                    'Communicate', --View_or_Communicate,
2409                                                    p_with_terms, --P_WITHTERMS
2410                                                    p_store_flag, --P_storeFlag
2411                                                    p_print_flag, --P_PRINT_FLAG
2412                                                    p_document_id, --P_DOCUMENT_ID
2413                                                    p_revision_number, --P_REVISION_NUM
2414                                                    p_authorization_status, --P_AUTHORIZATION_STATUS
2415                                                    p_document_type, --P_DOCUMENT_TYPE
2416                                                    0,--P_max_zip_size, <PO Attachment Support 11i.11>
2417                                                    null, --P_PO_TEMPLATE_CODE
2418                                                    null, --P_CONTRACT_TEMPLATE_CODE
2419                                                    fnd_global.local_chr(0),
2420                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2421                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2422                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2423                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2424                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2425                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2426                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2427                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2428                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2429                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2430                                                    NULL, NULL);
2431 
2432 
2433 
2434       elsif p_document_type = 'RELEASE' then
2435 --<R12 MOAC START>
2436         po_moac_utils_pvt.set_request_context(po_moac_utils_pvt.get_current_org_id);
2437 --<R12 MOAC END>
2438 --Bug5080617 Pass the parameters P_PO_TEMPLATE_CODE and P_CONTRACT_TEMPLATE_CODE as null
2439         p_request_id := fnd_request.submit_request('PO',
2440                                                    'POXPOPDF',
2441                                                    null,
2442                                                    null,
2443                                                    false,
2444                                                    'R', --P_report_type
2445                                                    null , --P_agent_name
2446                                                    null, --P_po_num_from
2447                                                    null , --P_po_num_to
2448                                                    null , --P_relaese_num_from
2449                                                    null , --P_release_num_to
2450                                                    null , --P_date_from
2451                                                    null , --P_date_to
2452                                                    null , --P_approved_flag
2453                                                    'N', --P_test_flag
2454                                                    null , --P_print_releases
2455                                                    null , --P_sortby
2456                                                    null , --P_user_id
2457                                                    null , --P_fax_enable
2458                                                    null , --P_fax_number
2459                                                    null , --P_BLANKET_LINES
2460                                                    'Communicate', --View_or_Communicate,
2461                                                    p_with_terms, --P_WITHTERMS
2462                                                    p_store_flag, --P_storeFlag
2463                                                    p_print_flag, --P_PRINT_FLAG
2464                                                    p_document_id, --P_DOCUMENT_ID
2465                                                    p_revision_number, --P_REVISION_NUM
2466                                                    p_authorization_status, --P_AUTHORIZATION_STATUS
2467                                                    p_document_type, --P_DOCUMENT_TYPE
2468                                                    0,--P_max_zip_size, <PO Attachment Support 11i.11>
2469                                                    null, --P_PO_TEMPLATE_CODE
2470                                                    null, --P_CONTRACT_TEMPLATE_CODE
2471                                                    fnd_global.local_chr(0),
2472                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2473                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2474                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2475                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2476                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2477                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2478                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2479                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2480                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2481                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2482                                                    NULL, NULL);
2483 
2484       end if;
2485 
2486     end if;
2487 
2488 
2489     if p_mode = 'FAX' then
2490 
2491       if p_document_type in ('STANDARD', 'BLANKET', 'CONTRACT') then
2492 
2493 --<R12 MOAC START>
2494         po_moac_utils_pvt.set_request_context(po_moac_utils_pvt.get_current_org_id);
2495 --<R12 MOAC END>
2496 --Bug5080617 Pass the parameters P_PO_TEMPLATE_CODE and P_CONTRACT_TEMPLATE_CODE as null
2497         p_request_id := fnd_request.submit_request('PO',
2498                                                    'POXPOFAX',--Bug 6332444
2499                                                    null,
2500                                                    null,
2501                                                    false,
2502                                                    'R', --P_report_type
2503                                                    null , --P_agend_id
2504                                                    null, --P_po_num_from
2505                                                    null , --P_po_num_to
2506                                                    null , --P_relaese_num_from
2507                                                    null , --P_release_num_to
2508                                                    null , --P_date_from
2509                                                    null , --P_date_to
2510                                                    null , --P_approved_flag
2511                                                    'N', --P_test_flag
2512                                                    null , --P_print_releases
2513                                                    null , --P_sortby
2514                                                    null , --P_user_id
2515                                                    p_fax_enable , --P_fax_enable
2516                                                    p_fax_num , --P_fax_number
2517                                                    null , --P_BLANKET_LINES
2518                                                    'Communicate', --View_or_Communicate,
2519                                                    p_with_terms, --P_WITHTERMS
2520                                                    p_store_flag, --P_storeFlag
2521                                                    p_print_flag, --P_PRINT_FLAG
2522                                                    p_document_id, --P_DOCUMENT_ID
2523                                                    p_revision_number, --P_REVISION_NUM
2524                                                    p_authorization_status, --P_AUTHORIZATION_STATUS
2525                                                    p_document_type, --P_DOCUMENT_TYPE
2526                                                    0,--P_max_zip_size, <PO Attachment Support 11i.11>
2527                                                    null, --P_PO_TEMPLATE_CODE
2528                                                    null, --P_CONTRACT_TEMPLATE_CODE
2529                                                    fnd_global.local_chr(0),
2530                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2531                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2532                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2533                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2534                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2535                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2536                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2537                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2538                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2539                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2540                                                    NULL, NULL);
2541 
2542 
2543       elsif p_document_type = 'RELEASE' then
2544 --<R12 MOAC START>
2545         po_moac_utils_pvt.set_request_context(po_moac_utils_pvt.get_current_org_id);
2546 --<R12 MOAC END>
2547 --Bug5080617 Pass the parameters P_PO_TEMPLATE_CODE and P_CONTRACT_TEMPLATE_CODE as null
2548 
2549 /*Bug5134811 For release fax the fax number and fax enable parameters are not passed due to which
2550    it was not possible to communicate the release through fax using Tools->Communicate.Passed
2551    the parameters as faxing is based on these two parameters*/
2552 
2553         p_request_id := fnd_request.submit_request('PO',
2554                                                    'POXPOFAX',--Bug 6332444
2555                                                    null,
2556                                                    null,
2557                                                    false,
2558                                                    'R', --P_report_type
2559                                                    null , --P_agent_name
2560                                                    null, --P_po_num_from
2561                                                    null , --P_po_num_to
2562                                                    null , --P_relaese_num_from
2563                                                    null , --P_release_num_to
2564                                                    null , --P_date_from
2565                                                    null , --P_date_to
2566                                                    null , --P_approved_flag
2567                                                    'N', --P_test_flag
2568                                                    null , --P_print_releases
2569                                                    null , --P_sortby
2570                                                    null , --P_user_id
2571                                                    p_fax_enable ,--P_fax_enable Bug5134811
2572                                                    p_fax_num ,--P_fax_number Bug5134811
2573                                                    null , --P_BLANKET_LINES
2574                                                    'Communicate', --View_or_Communicate,
2575                                                    p_with_terms, --P_WITHTERMS
2576                                                    p_store_flag, --P_storeFlag
2577                                                    p_print_flag, --P_PRINT_FLAG
2578                                                    p_document_id, --P_DOCUMENT_ID
2579                                                    p_revision_number, --P_REVISION_NUM
2580                                                    p_authorization_status, --P_AUTHORIZATION_STATUS
2581                                                    p_document_type, --P_DOCUMENT_TYPE
2582                                                    0,--P_max_zip_size, <PO Attachment Support 11i.11>
2583                                                    null, --P_PO_TEMPLATE_CODE
2584                                                    null, --P_CONTRACT_TEMPLATE_CODE
2585                                                    fnd_global.local_chr(0),
2586                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2587                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2588                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2589                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2590                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2591                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2592                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2593                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2594                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2595                                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2596                                                    NULL, NULL);
2597 
2598 
2599 
2600       end if;
2601 
2602     end if;
2603     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
2604       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name || 'After launching the Dispatch Purchase order CP.', 0);
2605     END IF;
2606 
2607   EXCEPTION
2608     when others then
2609       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_EXCEPTION) THEN
2610         FND_LOG.string(FND_LOG.LEVEL_EXCEPTION, g_log_head || l_api_name || '.EXCEPTION',
2611                        'launch_communicate: Inside exception :'|| '000' || sqlcode);
2612       END IF;
2613 
2614 
2615   end launch_communicate;
2616 
2617 /* <Bug 3619689> Restructured the following procedure
2618  * Removed redundant code and SQLs
2619  * Used proper debug logging
2620  * Introduced l_progress info and exception handling
2621  * Modified the SQLs used for selecting from PO and OKC Repository
2622  * Now selecting release revision number from po_release_archives_all
2623  */
2624   procedure Communicate(p_authorization_status in varchar2,
2625                         p_with_terms in varchar2,
2626                         p_language_code in varchar2,
2627                         p_mode in varchar2,
2628                         p_document_id in number ,
2629                         p_revision_number in number,
2630                         p_document_type in varchar2,
2631                         p_fax_number in varchar2,
2632                         p_email_address in varchar2,
2633                         p_request_id out nocopy number)
2634   IS
2635 
2636   l_conterm_exists_flag po_headers_all.CONTERMS_EXIST_FLAG%type;
2637   l_supp_lang fnd_languages.nls_language%type;
2638   l_territory fnd_languages.nls_territory%type;
2639   l_revision_num number;
2640   l_set_lang boolean;
2641   l_doctype po_document_types_all.document_type_code%type;
2642   l_document_subtype po_document_types_all.document_subtype%type;
2643   l_language_code fnd_languages.language_code%type;
2644   l_api_name CONSTANT VARCHAR2(25) := 'Communicate';
2645 
2646   l_pdf_tc_buyer_exists number(1); -- Whether PDF with Terms in buyers language already exists in Contracts Repository
2647   l_pdf_nt_buyer_exists number(1); -- Whether PDF without Terms in buyers language already exists in PO Repository
2648   l_pdf_nt_sup_exists number(1); -- Whether PDF without Terms in suppliers language already exists in PO Repository
2649   l_pdf_tc_sup_exists number(1); -- Whether PDF with Terms in suppliers language already exists in Contracts Repository
2650 
2651   l_tc_buyer_gen_flag varchar2(1); -- Whether PDF with Terms in buyers language needs to be generated
2652   l_nt_buyer_gen_flag varchar2(1); -- Whether PDF without Terms in buyers language needs to be generated
2653   l_nt_sup_gen_flag varchar2(1); -- Whether PDF without Terms in suppliers language needs to be generated
2654   l_tc_sup_gen_flag varchar2(1); -- Whether PDF without Terms in suppliers language needs to be generated
2655 
2656   l_store_flag varchar2(1); -- To store PDF or not
2657 
2658   l_org_id varchar2(10);
2659 
2660   l_request_id number := NULL;
2661 
2662   l_progress VARCHAR2(3);
2663   l_entity_name fnd_attached_documents.entity_name%type;
2664   l_buyer_language_code fnd_documents_tl.language%type;
2665   l_pdf_file_name fnd_lobs.file_name%type; --<FP 11i10+- R12 Contract ER TC Sup Lang>
2666 
2667   BEGIN
2668     l_progress := '000';
2669     IF g_debug_stmt THEN
2670       PO_DEBUG.debug_begin(p_log_head => g_log_head || l_api_name);
2671       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2672                           p_token => l_progress,
2673                           p_message => 'Communication method '|| p_mode);
2674       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2675                           p_token => l_progress,
2676                           p_message => 'Document Type '|| p_document_type);
2677       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2678                           p_token => l_progress,
2679                           p_message => 'Authorization Status '|| p_authorization_status);
2680       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2681                           p_token => l_progress,
2682                           p_message => 'Document Id '|| p_document_id);
2683       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2684                           p_token => l_progress,
2685                           p_message => 'With Terms '|| p_with_terms);
2686     END IF;
2687 
2688     l_org_id := po_moac_utils_pvt.get_current_org_id; --<R12 MOAC>
2689 
2690     l_doctype := p_document_type;
2691     if p_document_type in ('BLANKET', 'CONTRACT') then
2692       l_doctype := 'PA';
2693     end if;
2694 
2695     if p_document_type = 'STANDARD' then
2696       l_doctype := 'PO';
2697     end if;
2698 
2699     l_tc_buyer_gen_flag := 'N';
2700     l_nt_buyer_gen_flag := 'N';
2701     l_tc_sup_gen_flag := 'N';
2702     l_nt_sup_gen_flag := 'N';
2703 
2704     l_store_flag := 'N';
2705 
2706     l_progress := '010';
2707     begin
2708       if p_document_type in ('STANDARD', 'BLANKET', 'CONTRACT') then
2709         l_entity_name := 'PO_HEAD';
2710         select pvs.language into l_supp_lang from po_vendor_sites pvs , po_headers_all ph
2711           where po_header_id = p_document_id and ph.vendor_site_id = pvs.vendor_site_id ;
2712       else
2713         l_entity_name := 'PO_REL';
2714         select pvs.language into l_supp_lang from po_vendor_sites pvs , po_headers_all ph, po_releases_all pr
2715           where ph.po_header_id = pr.po_header_id and pr.po_release_id = p_document_id and
2716                    ph.vendor_site_id = pvs.vendor_site_id ;
2717       end if;
2718       IF g_debug_stmt THEN
2719         PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2720                             p_token => l_progress,
2721                             p_message => 'Supplier Language: '|| l_supp_lang);
2722       END IF;
2723     exception
2724       when others then l_supp_lang := NULL;
2725         IF g_debug_stmt THEN
2726           PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2727                               p_token => l_progress,
2728                               p_message => 'Supplier Language not found');
2729         END IF;
2730     end;
2731 
2732     l_progress := '020';
2733     if l_supp_lang is not null then
2734       select language_code, nls_territory into l_language_code, l_territory from fnd_languages fl where
2735         fl.nls_language = l_supp_lang;
2736     end if;
2737 
2738     l_buyer_language_code := userenv('LANG');
2739     begin
2740       select NVL(conterms_exist_flag, 'N') into l_conterm_exists_flag from po_headers_all
2741       where
2742         po_header_id = p_document_id and revision_num = p_revision_number;
2743 
2744     exception
2745       when others then l_conterm_exists_flag := 'N';
2746     end;
2747 
2748     if (p_authorization_status = 'APPROVED' or p_authorization_status = 'PRE-APPROVED') then
2749 
2750       l_revision_num := p_revision_number;
2751 
2752       if l_conterm_exists_flag = 'Y' then
2753         l_progress := '030';
2754         IF g_debug_stmt THEN
2755           PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2756                               p_token => l_progress,
2757                               p_message => 'Checking for latest PDF with terms in Contracts Repository');
2758         END IF;
2759 
2760       --<FP:11i10+-R12 Contract ER TC Sup Lang>
2761       -- Brought the call out of the select
2762         l_pdf_file_name := po_communication_pvt.getPDFFileName(l_doctype, '_TERMS_', l_org_id, p_document_id,
2763                                                                l_revision_num, l_buyer_language_code);
2764       --Bug #4865352 - Replaced fnd_documents_tl with fnd_documents_vl
2765         select count(1) into l_pdf_tc_buyer_exists from fnd_lobs fl, fnd_attached_documents fad, fnd_documents_vl fdl
2766         where
2767           fad.pk2_value = TO_CHAR(p_document_id) and
2768           fad.pk3_value = TO_CHAR(l_revision_num) and
2769           fad.entity_name = 'OKC_CONTRACT_DOCS' and
2770           fdl.document_id = fad.document_id and
2771           fdl.media_id = fl.file_id and
2772           fl.file_name = l_pdf_file_name;
2773 
2774       --<FP 11i10+ - R12 Contract ER TC Sup Lang Start >
2775         -- Check if the document with terms exist in suppliers language in the repository
2776         -- if the supplier language is provided
2777         if l_supp_lang is null then
2778 
2779           l_pdf_tc_sup_exists := 1;
2780 
2781         else
2782           l_progress := '031';
2783           IF g_debug_stmt THEN
2784             PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2785                                 p_token => l_progress,
2786                                 p_message => 'Checking for latest PDF without terms in suppliers language in PO Repository');
2787           END IF;
2788 
2789           l_pdf_file_name := po_communication_pvt.getPDFFileName(l_doctype, '_TERMS_', l_org_id, p_document_id,
2790                                                                  l_revision_num, l_buyer_language_code); --bug#3463617
2791              --Bug #4865352 - Added a join with fnd_documents
2792           select count(1) into l_pdf_tc_sup_exists from fnd_lobs fl, fnd_attached_documents fad, fnd_documents fd, fnd_documents_tl fdl
2793           where
2794           fad.pk1_value = TO_CHAR(p_document_id) and
2795           fad.pk2_value = TO_CHAR(l_revision_num) and
2796           fad.entity_name = l_entity_name and
2797           fdl.document_id = fad.document_id and
2798           fd.media_id = fl.file_id and
2799           fd.document_id = fdl.document_id and
2800           fdl.language = l_language_code and
2801           fl.file_name = l_pdf_file_name;
2802 
2803         end if;
2804 
2805          --<FP 11i10+ - R12  Contract ER TC Sup Lang End>
2806       else
2807 
2808         l_pdf_tc_buyer_exists := 0;
2809         l_pdf_tc_sup_exists := 0; --<FP 11i10+ - R12  Contract ER TC Sup Lang>
2810 
2811       end if;
2812 
2813       l_progress := '040';
2814       IF g_debug_stmt THEN
2815         PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2816                             p_token => l_progress,
2817                             p_message => 'Checking for latest PDF without terms in buyers language in PO Repository');
2818       END IF;
2819 
2820     --<FP 11i10+ - R12 Contract ER TC Sup Lang>
2821     -- Brought the call out of the select
2822       l_pdf_file_name := po_communication_pvt.getPDFFileName(l_doctype, '_TERMS_', l_org_id, p_document_id,
2823                                                              l_revision_num, l_buyer_language_code);
2824     --Bug #4865352
2825       select count(1) into l_pdf_nt_buyer_exists from fnd_lobs fl, fnd_attached_documents fad, fnd_documents_vl fdl
2826       where
2827         fad.pk1_value = TO_CHAR(p_document_id) and
2828         fad.pk2_value = TO_CHAR(l_revision_num) and
2829         fad.entity_name = l_entity_name and
2830         fdl.document_id = fad.document_id and
2831         fdl.media_id = fl.file_id and
2832         fl.file_name = l_pdf_file_name;
2833 
2834 
2835       if l_supp_lang is null then
2836 
2837         l_pdf_nt_sup_exists := 1;
2838 
2839       else
2840         l_progress := '050';
2841         IF g_debug_stmt THEN
2842           PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2843                               p_token => l_progress,
2844                               p_message => 'Checking for latest PDF without terms in suppliers language in PO Repository');
2845         END IF;
2846 
2847       --<FP 11i10+ - R12 Contract ER TC Sup Lang>
2848       -- Brought the call out of the select
2849         l_pdf_file_name := po_communication_pvt.getPDFFileName(l_doctype, '_TERMS_', l_org_id, p_document_id,
2850                                                                l_revision_num, l_language_code);
2851       --Bug #4865352 - Added a join with fnd_documents
2852         select count(1) into l_pdf_nt_sup_exists from fnd_lobs fl, fnd_attached_documents fad, fnd_documents fd, fnd_documents_tl fdl
2853         where
2854           fad.pk1_value = TO_CHAR(p_document_id) and
2855           fad.pk2_value = TO_CHAR(l_revision_num) and
2856           fad.entity_name = l_entity_name and
2857           fdl.document_id = fad.document_id and
2858           fd.media_id = fl.file_id and
2859           fd.document_id = fdl.document_id and
2860           fdl.language = l_language_code and
2861           fl.file_name = l_pdf_file_name;
2862 
2863       end if;
2864 
2865     else -- Authorization status is not in (Approved or Pre-Approved)
2866 
2867       l_progress := '060';
2868       Begin
2869         IF p_document_type in ('STANDARD', 'BLANKET', 'CONTRACT') THEN
2870           select max(revision_num)
2871           into l_revision_num
2872           from po_headers_archive_all
2873           where po_header_id = p_document_id
2874           and authorization_status = 'APPROVED';
2875         ELSE
2876           select max(revision_num)
2877           into l_revision_num
2878           from po_releases_archive_all
2879           where po_release_id = p_document_id
2880           and authorization_status = 'APPROVED';
2881         END IF;
2882       Exception
2883         When others then
2884           l_progress := '070';
2885           IF g_debug_unexp THEN
2886             PO_DEBUG.debug_exc(p_log_head => g_log_head || l_api_name,
2887                                p_progress => l_progress);
2888           END IF;
2889           raise;
2890       End;
2891     -- select max(revision_num) would not raise a no_data_found
2892     -- Instead it would return null, so raise exception explicitly
2893       IF l_revision_num IS NULL THEN
2894         l_progress := '080';
2895         IF g_debug_unexp THEN
2896           PO_DEBUG.debug_exc(p_log_head => g_log_head || l_api_name,
2897                              p_progress => l_progress);
2898         END IF;
2899         raise no_data_found;
2900       END IF;
2901 
2902     -- No cache documents are to be generated if status is any
2903     -- other than 'Approved' or 'Pre-Approved'
2904       l_pdf_tc_buyer_exists := 1;
2905       l_pdf_nt_buyer_exists := 1;
2906       l_pdf_tc_sup_exists := 1; --<FP 11i10+ - R12 Contract ER TC Sup Lang>
2907       l_pdf_nt_sup_exists := 1;
2908 
2909     end if; -- if (p_authorization_status = 'APPROVED' or p_authorization_status = 'PRE-APPROVED')
2910 
2911     l_progress := '090';
2912     IF g_debug_stmt THEN
2913       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2914                           p_token => l_progress,
2915                           p_message => 'Decide on which PDFs to generate and store');
2916     END IF;
2917 
2918     if p_with_terms = 'Y' then
2919 
2920     --<FP 11i10+ - R12 Contract ER TC Sup Lang Start>
2921     -- Modified the following logic such that -
2922     -- If the doc with terms does not exist in suppliers language
2923     -- generate and store it depending on the language passed in
2924 
2925       if p_language_code = l_buyer_language_code then
2926 
2927         if l_pdf_tc_buyer_exists = 0 then
2928           l_store_flag := 'Y';
2929         end if;
2930 
2931         if l_pdf_nt_buyer_exists = 0 then
2932           l_nt_buyer_gen_flag := 'Y';
2933         end if;
2934 
2935       else -- if p_language_code = l_buyer_language_code
2936 
2937         l_progress := '095';
2938       -- Bug 4116063: Set the language if different from buyers lang
2939         select nls_language, nls_territory into l_supp_lang, l_territory from fnd_languages fl where
2940           fl.language_code = p_language_code ;
2941         l_set_lang := fnd_request.set_options('NO', 'NO', l_supp_lang, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS')); -- <BUG 9079824>
2942 
2943         if l_pdf_tc_sup_exists = 0 then
2944           l_store_flag := 'Y';
2945         end if;
2946 
2947         if l_pdf_nt_sup_exists = 0 then
2948           l_nt_sup_gen_flag := 'Y';
2949         end if;
2950 
2951       end if;
2952     --<FP 11i10+ - R12 Contract ER TC Sup Lang End>
2953 
2954     else -- if p_with_terms = 'N'
2955 
2956      --<FP 11i10+ - R12 Contract ER TC Sup Lang >
2957     -- If the doc with terms does not exist in suppliers language
2958     -- generate it.
2959       if l_conterm_exists_flag = 'Y' and l_pdf_tc_buyer_exists = 0 then
2960         l_tc_buyer_gen_flag := 'Y';
2961       elsif l_conterm_exists_flag = 'Y' and l_pdf_tc_sup_exists = 0 then
2962         l_tc_sup_gen_flag := 'Y';
2963       end if;
2964 
2965       if p_language_code = l_buyer_language_code then
2966 
2967         if l_pdf_nt_buyer_exists = 0 then
2968           l_store_flag := 'Y';
2969         end if;
2970 
2971         if l_pdf_nt_sup_exists = 0 then
2972           l_nt_sup_gen_flag := 'Y';
2973         end if;
2974 
2975       else -- if p_language_code = l_buyer_language_code
2976 
2977         l_progress := '100';
2978         select nls_language, nls_territory into l_supp_lang, l_territory from fnd_languages fl where
2979           fl.language_code = p_language_code ;
2980         l_set_lang := fnd_request.set_options('NO', 'NO', l_supp_lang, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS')); -- <BUG 9079824>
2981 
2982         if l_pdf_nt_sup_exists = 0 then
2983           l_store_flag := 'Y';
2984         end if;
2985 
2986         if l_pdf_nt_buyer_exists = 0 then
2987           l_nt_buyer_gen_flag := 'Y';
2988         end if;
2989 
2990       end if; -- if p_language_code = l_buyer_language_code
2991 
2992     end if; -- if p_with_terms = 'Y'
2993 
2994     l_progress := '110';
2995     IF g_debug_stmt THEN
2996       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
2997                           p_token => l_progress,
2998                           p_message => 'Lanuch Communicate Requests');
2999     END IF;
3000 
3001     if p_mode = 'PRINT' then
3002       l_progress := '120';
3003       launch_communicate(p_mode,
3004                          p_document_id,
3005                          l_revision_num,
3006                          p_document_type,
3007                          p_authorization_status,
3008                          p_language_code,
3009                          null,
3010                          null,
3011                          p_with_terms, -- with terms
3012                          'Y', -- print flag
3013                          l_store_flag,
3014                          p_request_id);
3015 
3016     elsif p_mode = 'FAX' then
3017       l_progress := '130';
3018       launch_communicate(p_mode,
3019                          p_document_id,
3020                          l_revision_num,
3021                          p_document_type,
3022                          p_authorization_status,
3023                          p_language_code,
3024                          'Y', -- fax enable
3025                          p_fax_number,
3026                          p_with_terms, -- with terms
3027                          'Y', -- print flag
3028                          l_store_flag,
3029                          p_request_id);
3030 
3031     elsif p_mode = 'EMAIL' then
3032       if p_document_type in ('STANDARD', 'BLANKET', 'CONTRACT') then
3033         l_progress := '140';
3034         Start_Email_WF_Process(p_document_id,
3035                                l_revision_num,
3036                                l_doctype,
3037                                p_document_type,
3038                                p_email_address ,
3039                                p_language_code,
3040                                l_store_flag,
3041                                p_with_terms) ; -- with terms
3042       elsif p_document_type = 'RELEASE' then
3043         l_progress := '150';
3044         Start_Email_WF_Process(p_document_id,
3045                                l_revision_num,
3046                                p_document_type,
3047                                'BLANKET',
3048                                p_email_address,
3049                                p_language_code,
3050                                l_store_flag,
3051                                p_with_terms); -- with terms
3052       end if;
3053 
3054     end if; -- if p_mode = 'PRINT'
3055     commit;
3056 
3057   -- Now make cache documents
3058     l_progress := '160';
3059     IF g_debug_stmt THEN
3060       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
3061                           p_token => l_progress,
3062                           p_message => 'Generate Cache PDFs and store them in the repository');
3063     END IF;
3064 
3065     if l_tc_buyer_gen_flag = 'Y' then
3066       select nls_language, nls_territory into l_supp_lang, l_territory from fnd_languages fl where
3067         fl.language_code = l_buyer_language_code;
3068       l_set_lang := fnd_request.set_options('NO', 'NO', l_supp_lang, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS')); -- <BUG 9079824>
3069 
3070       l_progress := '170';
3071       launch_communicate('PRINT',
3072                          p_document_id,
3073                          l_revision_num,
3074                          p_document_type,
3075                          p_authorization_status,
3076                          p_language_code,
3077                          null,
3078                          null,
3079                          'Y', -- with terms
3080                          'N', -- print flag
3081                          'Y', -- store flag
3082                          l_request_id);
3083       commit;
3084     end if;
3085 
3086     l_progress := '180';
3087     if l_nt_buyer_gen_flag = 'Y' then
3088       select nls_language, nls_territory into l_supp_lang, l_territory from fnd_languages fl where
3089         fl.language_code = l_buyer_language_code;
3090       l_set_lang := fnd_request.set_options('NO', 'NO', l_supp_lang, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS')); -- <BUG 9079824>
3091 
3092       l_progress := '190';
3093       launch_communicate('PRINT',
3094                          p_document_id,
3095                          l_revision_num,
3096                          p_document_type,
3097                          p_authorization_status,
3098                          p_language_code,
3099                          null,
3100                          null,
3101                          'N', -- with terms
3102                          'N', -- print flag
3103                          'Y', -- store flag
3104                          l_request_id);
3105       commit;
3106     end if;
3107 
3108     l_progress := '200';
3109     if p_document_type in ('STANDARD', 'BLANKET', 'CONTRACT') then
3110       select pvs.language into l_supp_lang from po_vendor_sites pvs , po_headers_all ph
3111         where po_header_id = p_document_id and ph.vendor_site_id = pvs.vendor_site_id ;
3112     else
3113       select pvs.language into l_supp_lang from po_vendor_sites pvs , po_headers_all ph, po_releases_all pr
3114         where ph.po_header_id = pr.po_header_id and pr.po_release_id = p_document_id and
3115                  ph.vendor_site_id = pvs.vendor_site_id ;
3116     end if;
3117 
3118     if l_nt_sup_gen_flag = 'Y' then
3119 
3120       l_progress := '210';
3121       if l_supp_lang is not null then
3122         select language_code, nls_territory into l_language_code, l_territory from fnd_languages fl where
3123           fl.nls_language = l_supp_lang;
3124         l_set_lang := fnd_request.set_options('NO', 'NO', l_supp_lang, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS')); -- <BUG 9079824>
3125 
3126         l_progress := '220';
3127         launch_communicate('PRINT',
3128                            p_document_id,
3129                            l_revision_num,
3130                            p_document_type,
3131                            p_authorization_status,
3132                            p_language_code,
3133                            null,
3134                            null,
3135                            'N', -- with terms
3136                            'N', -- print flag
3137                            'Y', -- store flag
3138                            l_request_id);
3139         commit;
3140       end if;
3141     end if;
3142 
3143    --<FP 11i10+ - R12 Contract ER TC Sup Lang Start>
3144     if l_tc_sup_gen_flag = 'Y' then
3145 
3146       l_progress := '220';
3147       if l_supp_lang is not null then
3148         select language_code, nls_territory
3149           into l_language_code, l_territory
3150         from fnd_languages fl
3151         where fl.nls_language = l_supp_lang;
3152 
3153         l_set_lang := fnd_request.set_options('NO', 'NO', l_supp_lang, l_territory, NULL, FND_PROFILE.VALUE('ICX_NUMERIC_CHARACTERS')); -- <BUG 9079824>
3154 
3155         l_progress := '220';
3156         launch_communicate('PRINT',
3157                            p_document_id,
3158                            l_revision_num,
3159                            p_document_type,
3160                            p_authorization_status,
3161                            p_language_code,
3162                            null,
3163                            null,
3164                            'Y', -- with terms
3165                            'N', -- print flag
3166                            'Y', -- store flag
3167                            l_request_id);
3168         commit;
3169       end if;
3170     end if;
3171   --<FP 11i10+ - R12 Contract ER TC Sup Lang End>
3172 
3173     commit;
3174 
3175     l_progress := '230';
3176     IF g_debug_stmt THEN
3177       PO_DEBUG.debug_end(p_log_head => g_log_head || l_api_name);
3178     END IF;
3179 
3180   exception
3181     when others then
3182       IF g_debug_unexp THEN
3183         PO_DEBUG.debug_exc(p_log_head => g_log_head || l_api_name,
3184                            p_progress => l_progress);
3185       END IF;
3186       raise;
3187   end Communicate;
3188 
3189 
3190   function po_communication_profile RETURN VARCHAR2 IS
3191   l_communication varchar2(1);
3192   l_format po_system_parameters_all.po_output_format%type;
3193   BEGIN
3194 
3195     select po_output_format into l_format from po_system_parameters;
3196 
3197     IF (l_format = 'PDF' ) THEN
3198       RETURN FND_API.G_TRUE;
3199     ELSE
3200       RETURN FND_API.G_FALSE;
3201     END IF;
3202 
3203   END po_communication_profile;
3204 
3205 /* Bug # 3222207: Added the following function to return whether XDO is installed or not*/
3206   function IS_PON_PRINTING_ENABLED RETURN VARCHAR2 IS
3207   l_communication varchar2(1);
3208   BEGIN
3209     IF (po_core_s.get_product_install_status('XDO') = 'I' ) THEN
3210       RETURN FND_API.G_TRUE;
3211     ELSE
3212       RETURN FND_API.G_FALSE;
3213     END IF;
3214   END IS_PON_PRINTING_ENABLED;
3215 
3216   function USER_HAS_ACCESS_TC RETURN VARCHAR2 IS
3217   BEGIN
3218     IF (fnd_function.test('PO_CONTRACT_TERMS')) THEN
3219       RETURN 'Y';
3220     ELSE
3221       RETURN 'N';
3222     END IF;
3223   END USER_HAS_ACCESS_TC;
3224 
3225   procedure Store_Blob(p_document_id number,
3226                        p_revision_number number ,
3227                        p_document_type varchar2,
3228                        p_file_name varchar2,
3229                        p_blob_type IN varchar2, --<PO Attachment Support 11i.11>
3230                        x_media_id out nocopy number)
3231   IS
3232   BEGIN
3233     Store_Blob(p_document_id ,
3234                        p_revision_number ,
3235                        -1, -- CLM Project
3236                        p_document_type ,
3237                        p_file_name ,
3238                        p_blob_type , --<PO Attachment Support 11i.11>
3239                        x_media_id );
3240   END;
3241 
3242 --<PO Attachment Support 11i.11>
3243 -- Generalized the existing procedure Store_PDF for adding any type of Blob
3244 -- Introduced exception handling
3245   procedure Store_Blob(p_document_id number,
3246                        p_revision_number number ,
3247                        p_draft_id number , -- CLM Project
3248                        p_document_type varchar2,
3249                        p_file_name varchar2,
3250                        p_blob_type IN varchar2, --<PO Attachment Support 11i.11>
3251                        x_media_id out nocopy number)
3252   IS
3253 
3254   Row_id_tmp varchar2(100);
3255   Document_id_tmp number;
3256   Media_id_tmp number;
3257   l_blob_data blob;
3258   l_entity_name varchar2(30);
3259   Seq_num number;
3260   l_category_id number;
3261   l_count number;
3262   l_draft_id varchar2(30) := null; --CLM Project
3263 
3264         --<PO Attachment Support 11i.11>
3265   l_file_name fnd_lobs.file_name%type;
3266   l_file_content_type fnd_lobs.file_content_type%type;
3267   l_org_id po_headers_all.org_id%type;
3268   l_api_name CONSTANT VARCHAR2(25) := 'Store_Blob';
3269   l_progress VARCHAR2(3);
3270 
3271   Begin
3272     l_progress := '000';
3273     IF g_debug_stmt THEN
3274       PO_DEBUG.debug_begin(p_log_head => g_log_head || l_api_name);
3275       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
3276                           p_token => l_progress,
3277                           p_message => p_document_type ||' '|| p_document_id ||' '|| p_revision_number ||' '|| p_blob_type);
3278     END IF;
3279 
3280 --CLM
3281     IF p_draft_Id <> -1 THEN
3282         l_draft_id := to_char(p_draft_id);
3283     END IF;
3284 
3285     --<PO Attachment Support 11i.11>
3286     IF p_blob_type = 'PDF' THEN
3287       l_file_content_type := 'application/pdf';
3288       l_file_name := p_file_name;
3289     ELSIF p_blob_type = 'ZIP' THEN
3290       l_org_id := po_moac_utils_pvt.get_current_org_id; --<R12 MOAC>
3291       IF g_debug_stmt THEN
3292         PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
3293                             p_token => l_progress,
3294                             p_message => 'Calculated org_id = '|| l_org_id);
3295       END IF;
3296 
3297       --Start of code changes for the bug 12799972
3298       IF (l_org_id IS  null) THEN
3299       	SELECT org_id INTO l_org_id FROM po_headers_all WHERE po_header_id = p_document_id;
3300 	po_moac_utils_pvt.SET_POLICY_CONTEXT('S', l_org_id );
3301       END IF;
3302       -- End of code changes for the bug 12799972
3303 
3304       l_file_content_type := 'application/x-zip-compressed';
3305         --Bug# 5240634 Pass the org_id to getZIPFileName
3306       l_file_name := getZIPFileName(l_org_id);
3307     END IF;
3308 
3309     l_progress := '010';
3310 
3311     l_blob_data := empty_blob();
3312     l_count := 0;
3313 
3314     l_progress := '020';
3315 --Assign the Entity name depending on the document type
3316 
3317 
3318     if p_document_type in ('PO', 'PA') then
3319       l_entity_name := 'PO_HEAD';
3320     else
3321       l_entity_name := 'PO_REL';
3322     end if;
3323 
3324     l_progress := '030';
3325     --<PO Attachment Support 11i.11>
3326     -- For PDF preventing duplicate records is taken care of by explicitly deleting
3327     -- them before generating it everytime. For ZIP, it will be done by returning
3328     -- the same file id as the existing one so that an explicit delete would not be
3329     -- necessary
3330     --Bug #4865352 - Replaced fnd_documents_tl with fnd_documents_vl
3331     IF p_blob_type = 'ZIP' THEN
3332       Begin
3333         SELECT fdl.media_id
3334         INTO x_media_id
3335         FROM fnd_attached_documents fad,
3336              fnd_documents_vl fdl
3337         WHERE fad.pk1_value = to_char(p_document_id)
3338         and fad.pk2_value = to_char(p_revision_number)
3339         and nvl(fad.pk3_value, '*') = nvl(l_draft_id, '*') -- CLM
3340         and fad.entity_name = l_entity_name
3341         and fdl.document_id = fad.document_id;
3342 
3343       Exception when others Then
3344             -- do nothing. If no_data_found then x_media_id will be null and a new lob
3345             -- locator will be inserted into fnd_lobs. If too_many_rows (though should
3346             -- not occur because the locator gets overwritten everytime) then the first blob found will be overwritten
3347           null;
3348       End;
3349     END IF;
3350     l_progress := '040';
3351     IF g_debug_stmt THEN
3352       PO_DEBUG.debug_stmt(p_log_head => g_log_head || l_api_name,
3353                           p_token => l_progress,
3354                           p_message => 'x_media_id = '|| x_media_id);
3355     END IF;
3356 
3357     IF x_media_id IS NULL THEN
3358 
3359       l_progress := '050';
3360 --Get the Category Id of 'PO Documents' Category
3361       SELECT category_id into l_category_id from fnd_document_categories
3362       where name = 'CUSTOM2446' ;
3363 
3364       l_progress := '006';
3365       FND_DOCUMENTS_PKG.Insert_Row(
3366                                    row_id_tmp,
3367                                    document_id_tmp,
3368                                    SYSDATE,
3369                                    1, --NVL(X_created_by,0),
3370                                    SYSDATE,
3371                                    1, --NVL(X_created_by,0),
3372                                    1, --X_last_update_login,
3373                                    6,
3374                                    l_category_id, --Get the value for the category id 'PO Documents'
3375                                    1, --null,--security_type,
3376                                    null, --security_id,
3377                                    'Y', --null,--publish_flag,
3378                                    null, --image_type,
3379                                    null, --storage_type,
3380                                    'O', --usage_type,
3381                                    sysdate, --start_date_active,
3382                                    null, --end_date_active,
3383                                    null,--X_request_id, --null
3384                                    null,--X_program_application_id, --null
3385                                    null, --X_program_id,--null
3386                                    SYSDATE,
3387                                    null, --language,
3388                                    null, --description,
3389                                    l_file_name,
3390                                    x_media_id);
3391 
3392       l_progress := '060';
3393 
3394       INSERT INTO fnd_lobs (
3395          file_id,
3396          File_name,
3397          file_content_type,
3398          upload_date,
3399          expiration_date,
3400          program_name,
3401          program_tag,
3402          file_data,
3403          language,
3404          oracle_charset,
3405          file_format)
3406          VALUES
3407           (x_media_id,
3408          l_file_name, --<PO Attachment Support 11i.11> Changed p_file_name to l_file_name
3409          l_file_content_type, --<PO Attachment Support 11i.11> Changed hardcoded value to l_file_content_type
3410          sysdate,
3411          null,
3412          null,
3413          null,
3414          l_blob_data,
3415          null,
3416          null,
3417                'binary');
3418 
3419       l_progress := '070';
3420 
3421       INSERT INTO fnd_attached_documents (attached_document_id,
3422       document_id,
3423       creation_date,
3424        created_by,
3425        last_update_date,
3426       last_updated_by,
3427         last_update_login,
3428       seq_num,
3429        entity_name,
3430       pk1_value,
3431        pk2_value,
3432       pk3_value,
3433       pk4_value,
3434        pk5_value,
3435       automatically_added_flag,
3436       program_application_id,
3437        program_id,
3438        program_update_date,
3439       request_id,
3440       attribute_category,
3441        attribute1,
3442       attribute2,
3443       attribute3,
3444       attribute4,
3445       attribute5,
3446       attribute6,
3447       attribute7,
3448       attribute8,
3449        attribute9,
3450        attribute10,
3451       attribute11,
3452       attribute12,
3453        attribute13,
3454       attribute14,
3455        attribute15,
3456        column1)
3457       VALUES
3458        (fnd_attached_documents_s.nextval,
3459       document_id_tmp,
3460       sysdate,
3461       1, --NVL(X_created_by,0),
3462       sysdate,
3463       1, --NVL(X_created_by,0),
3464       null,-- X_last_update_login,
3465       10,
3466        l_entity_name,
3467        to_char(p_document_id),
3468        to_char(p_revision_number),
3469 --       null,
3470        l_draft_id, -- CLM
3471        null,
3472        null,
3473        'N',
3474       null,
3475       null,
3476       sysdate,
3477       null,
3478       null,
3479       null,
3480       null,
3481 null,
3482 null,
3483 null,
3484 null,
3485 null,
3486 null,
3487 null,
3488 null,
3489 null,
3490 null,
3491 null,
3492 null,
3493 null,
3494 null);
3495       l_progress := '080';
3496     END IF;
3497 
3498     IF g_debug_stmt THEN
3499       PO_DEBUG.debug_end(p_log_head => g_log_head || l_api_name);
3500     END IF;
3501 
3502   Exception
3503     WHEN OTHERS THEN
3504       IF g_debug_unexp THEN
3505         PO_DEBUG.debug_exc(p_log_head => g_log_head || l_api_name,
3506                            p_progress => l_progress);
3507       END IF;
3508       raise;
3509   end Store_Blob;
3510 
3511   procedure pdf_attach_app (document_id in varchar2,
3512                             content_type in varchar2,
3513                             document in out NOCOPY blob,
3514                             document_type in out NOCOPY varchar2) IS
3515   l_filename fnd_lobs.file_name%type;
3516   l_document_id number;
3517   l_document_type po_headers.type_lookup_code%TYPE;
3518   l_org_id number;
3519   l_revision_number number;
3520   l_language fnd_languages.language_code%type;
3521   l_entity_name varchar2(30);
3522   l_itemtype po_document_types.wf_approval_itemtype%type;
3523   l_itemkey varchar2(60);
3524   l_document blob;
3525   l_withTerms varchar2(1);
3526   l_document_length number;
3527   l_message FND_NEW_MESSAGES.message_text%TYPE; --Bug 3274081
3528   x_progress varchar2(300);
3529 
3530    l_draft_id number;
3531 
3532   BEGIN
3533 
3534     l_itemtype := substr(document_id, 1, instr(document_id, ':') - 1);
3535 
3536     l_itemkey := substr(document_id, instr(document_id, ':') + 1, length(document_id) - 2);
3537 
3538     x_progress := 'PO_COMMUNICATION_PVT.pdf_attach_app ';
3539 
3540     IF (g_po_wf_debug = 'Y') THEN
3541       PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, x_progress);
3542     END IF;
3543 
3544     l_document_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3545                                                   itemkey => l_itemkey,
3546                                                   aname => 'DOCUMENT_ID');
3547 
3548     l_org_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3549                                              itemkey => l_itemkey,
3550                                              aname => 'ORG_ID');
3551 
3552     l_document_type := wf_engine.GetItemAttrText (itemtype => l_itemtype,
3553                                                   itemkey => l_itemkey,
3554                                                   aname => 'DOCUMENT_TYPE');
3555 
3556     l_language := wf_engine.GetItemAttrText (itemtype => l_itemtype,
3557                                              itemkey => l_itemkey,
3558                                              aname => 'LANGUAGE_CODE');
3559 
3560     l_revision_number := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3561                                                       itemkey => l_itemkey,
3562                                                       aname => 'REVISION_NUMBER');
3563 
3564     l_withTerms := wf_engine.GetItemAttrText (itemtype => l_itemtype,
3565                                               itemkey => l_itemkey,
3566                                               aname => 'WITH_TERMS');
3567 
3568     l_draft_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3569                                                   itemkey => l_itemkey,
3570                                                   aname => 'DRAFT_ID');
3571 
3572 /* Bug 7424634
3573    PDF without TERMS should be sent to Buyer
3574    Commenting the condition for TERMS */
3575 
3576 --if   PO_CONTERMS_UTL_GRP.is_procurement_contract_doc(document_id) then
3577 --Bug 9794433 we have pdf with terms now after 9301926 fix we have file with terms so refering that
3578   if l_withTerms ='Y' then
3579 
3580   --bug#3463617
3581      l_filename := po_communication_pvt.getPDFFileName(l_document_type,'_TERMS_',l_org_id,l_document_id,l_revision_number,l_draft_id,l_language,'N');
3582  else
3583   --bug#3463617
3584     l_filename := po_communication_pvt.getPDFFileName(l_document_type, '_', l_org_id, l_document_id, l_revision_number,l_draft_id, l_language,'N');
3585  end if;
3586 --Bug 9794433 we have pdf with terms now after 9301926 fix we have file with terms so refering that
3587 
3588 /* End Bug 7424634 */
3589 
3590     if l_document_type = 'RELEASE' then
3591       l_entity_name := 'PO_REL';
3592     end if;
3593 
3594     if l_document_type in ('PO', 'PA') then
3595       l_entity_name := 'PO_HEAD';
3596     end if;
3597 
3598 --Bug #4865352 - Added join with fnd_documents and selected media_id from it
3599 --Bug #5232999 - Added file name as criterion so that we get only the PDF
3600    /* SELECT file_data into l_document
3601     FROM fnd_lobs fl,
3602          fnd_attached_documents fad,
3603          fnd_documents fd,
3604          fnd_documents_tl fdl
3605     WHERE fad.pk1_value = to_char(l_document_id) and fad.pk2_value = to_char(l_revision_number)
3606     and fdl.document_id = fad.document_id and fdl.document_id = fd.document_id and fd.media_id = fl.file_id
3607     and fad.entity_name = l_entity_name and fdl.language = l_language
3608     and fl.file_name = l_filename ;*/
3609 
3610      /* FP Bug 13870183 : Logic while fetching pdf is now changed to, fetch pdf from PO_HEAD/PO_REL,
3611         If document does not exists on PO_HEAD and PO_REL, fetch it from OKC_CONTRACT_DOCS*/
3612  	     BEGIN
3613  	      SELECT file_data into l_document
3614  	      FROM fnd_lobs fl,
3615  	         fnd_attached_documents fad,
3616  	         fnd_documents fd,
3617  	         fnd_documents_tl fdl
3618  	      WHERE fad.pk1_value = to_char(l_document_id)
3619  	          and fad.pk2_value = to_char(l_revision_number)
3620  	          and fdl.document_id = fad.document_id
3621  	          and fdl.document_id = fd.document_id
3622  	          and fd.media_id = fl.file_id
3623  	          and fad.entity_name = l_entity_name
3624  	          and fdl.language = l_language
3625  	          and fl.file_name = l_filename ;
3626 
3627  	         IF (g_po_wf_debug = 'Y') THEN
3628  	            PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, 'Fetching from PO_HEAD/PO_REL....');
3629  	         END IF;
3630 
3631  	     EXCEPTION
3632  	         WHEN No_Data_Found THEN
3633  	             IF (g_po_wf_debug = 'Y') THEN
3634  	                 PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, 'Fetching from OKC_CONTRACT_DOC entity.....');
3635  	          END IF;
3636 
3637  	             SELECT file_data into l_document
3638  	             FROM fnd_lobs fl,
3639  	                 fnd_attached_documents fad,
3640  	                 fnd_documents fd,
3641  	                 fnd_documents_tl fdl
3642  	             WHERE fad.pk2_value = to_char(l_document_id)
3643  	                 and fad.pk3_value = to_char(l_revision_number)
3644  	                 and fdl.document_id = fad.document_id
3645  	                 and fdl.document_id = fd.document_id
3646  	                 and fd.media_id = fl.file_id
3647  	         	 and fad.entity_name = 'OKC_CONTRACT_DOCS'
3648  	                 and fdl.language = l_language
3649              		 and fl.file_name = l_filename ;
3650     	    END;
3651    	     l_document_length := dbms_lob.GetLength(l_document);
3652 	     IF (g_po_wf_debug = 'Y') THEN
3653  	         PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, 'Document Length : '||l_document_length);
3654  	     END IF;
3655     dbms_lob.copy(document, l_document, l_document_length, 1, 1);
3656 
3657     document_type :='application/pdf; name='|| l_filename;
3658 
3659   EXCEPTION
3660     WHEN OTHERS THEN
3661    --l_document:=fnd_message.get_string('PO','PO_PDF_FAILED');
3662    --WF_NOTIFICATION.WriteToBlob(document, l_document);
3663       x_progress := 'PO_COMMUNICATION_PVT.pdf_attach_app-Exception ';
3664 
3665       IF (g_po_wf_debug = 'Y') THEN
3666         PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, x_progress);
3667       END IF;
3668 
3669 --Bug#3274081 Display the message to the user incase the pdf fails.
3670       document_type :='text/html; name='|| l_filename;
3671       l_message := fnd_message.get_string('PO', 'PO_PDF_FAILED');
3672       DBMS_LOB.write(document, lengthb(l_message), 1, UTL_RAW.cast_to_raw(l_message));
3673 
3674   END pdf_attach_app;
3675 
3676 -- Bug 3823799. Recoded following procedure. This procedure is to
3677 -- Communicate the PDF document in the language selected in
3678 -- Communicate window. Earlier this procedure was not used at all
3679 -- and PDF_ATTACH was being used for the same purpose
3680   PROCEDURE pdf_attach_supp(document_id in varchar2,
3681                             content_type in varchar2,
3682                             document in out nocopy blob,
3683                             document_type in out nocopy varchar2) IS
3684   l_filename fnd_lobs.file_name%type;
3685   l_document_id number;
3686   l_document_type po_headers.type_lookup_code%TYPE;
3687   l_org_id number;
3688   l_revision_number number;
3689   l_language fnd_languages.language_code%type;
3690   l_entity_name varchar2(30);
3691   l_itemtype po_document_types.wf_approval_itemtype%type;
3692   l_itemkey varchar2(60);
3693   l_document blob;
3694   l_withTerms varchar2(1);
3695   l_document_length number;
3696   l_message FND_NEW_MESSAGES.message_text%TYPE;
3697 
3698   x_progress varchar2(300);
3699 
3700   BEGIN
3701     x_progress := 'PO_COMMUNICATION_PVT.pdf_attach_supp';
3702 
3703     l_itemtype := substr(document_id, 1, instr(document_id, ':') - 1);
3704     l_itemkey := substr(document_id, instr(document_id, ':') + 1, length(document_id) - 2);
3705 
3706     IF (g_po_wf_debug = 'Y') THEN
3707       PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, x_progress);
3708     END IF;
3709 
3710     l_document_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3711                                                   itemkey => l_itemkey,
3712                                                   aname => 'DOCUMENT_ID');
3713 
3714     l_org_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3715                                              itemkey => l_itemkey,
3716                                              aname => 'ORG_ID');
3717 
3718     l_document_type := wf_engine.GetItemAttrText (itemtype => l_itemtype,
3719                                                   itemkey => l_itemkey,
3720                                                   aname => 'DOCUMENT_TYPE');
3721 
3722     l_language := wf_engine.GetItemAttrText (itemtype => l_itemtype,
3723                                              itemkey => l_itemkey,
3724                                              aname => 'LANGUAGE_CODE');
3725 
3726     l_revision_number := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3727                                                       itemkey => l_itemkey,
3728                                                       aname => 'REVISION_NUMBER');
3729 
3730     l_withTerms := wf_engine.GetItemAttrText (itemtype => l_itemtype,
3731                                               itemkey => l_itemkey,
3732                                               aname => 'WITH_TERMS');
3733 
3734     IF l_withTerms = 'Y' THEN
3735       l_filename := po_communication_pvt.getPDFFileName(l_document_type, '_TERMS_', l_org_id, l_document_id, l_revision_number, l_language);
3736     ELSE
3737       l_filename := po_communication_pvt.getPDFFileName(l_document_type, '_', l_org_id, l_document_id, l_revision_number, l_language);
3738     END IF;
3739     --Bug #4865352 - Added join with fnd_documents and selected media_id from it
3740     -- Bug 4047688
3741     -- Added join condition on file name of PDF
3742     IF l_withTerms = 'Y' AND l_document_type in ('PO', 'PA') THEN
3743       SELECT file_data into l_document
3744       FROM fnd_lobs fl,
3745            fnd_attached_documents fad,
3746            fnd_documents fd,
3747            fnd_documents_tl fdl
3748       WHERE fad.pk2_value = to_char(l_document_id) and fad.pk3_value = to_char(l_revision_number)
3749       and fdl.document_id = fad.document_id and fdl.document_id = fd.document_id and fd.media_id = fl.file_id
3750       and fad.entity_name = 'OKC_CONTRACT_DOCS' and fdl.language = l_language
3751       and fl.file_name = l_filename
3752       and rownum = 1;   -- Bug 10410956
3753     END IF;
3754 
3755     IF l_document_type in ('PO', 'PA') THEN
3756       l_entity_name := 'PO_HEAD';
3757     ELSIF l_document_type = 'RELEASE' THEN
3758       l_entity_name := 'PO_REL';
3759     END IF;
3760     --Bug #4865352 - Added a join with fnd_documents
3761     IF l_document_type in ('PO', 'PA', 'RELEASE') AND l_withTerms = 'N' THEN
3762       SELECT file_data into l_document
3763       FROM fnd_lobs fl,
3764            fnd_attached_documents fad,
3765            fnd_documents fd,
3766            fnd_documents_tl fdl
3767       WHERE fad.pk1_value = to_char(l_document_id) and fad.pk2_value = to_char(l_revision_number)
3768       and fdl.document_id = fad.document_id and fd.media_id = fl.file_id
3769       and fd.document_id = fdl.document_id
3770       and fad.entity_name = l_entity_name and fl.file_name = l_filename and fdl.language = l_language and rownum = 1;
3771       -- Bug 10410956 ;
3772     END IF;
3773 
3774     l_document_length := dbms_lob.GetLength(l_document);
3775     dbms_lob.copy(document, l_document, l_document_length, 1, 1);
3776     document_type :='application/pdf; name='|| l_filename;
3777 
3778   EXCEPTION
3779     WHEN OTHERS THEN
3780       x_progress := 'PO_COMMUNICATION_PVT.pdf_attach_supp - Exception ';
3781 
3782       IF (g_po_wf_debug = 'Y') THEN
3783         PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, x_progress);
3784       END IF;
3785 
3786     -- Display the message to the user incase the pdf fails.
3787     -- Bug 4047688
3788     -- Removed concatenation of l_filename from document_type
3789       document_type := 'text/html';
3790       l_message := fnd_message.get_string('PO', 'PO_PDF_FAILED');
3791       DBMS_LOB.write(document, lengthb(l_message), 1, UTL_RAW.cast_to_raw(l_message));
3792   END pdf_attach_supp;
3793 
3794 
3795   procedure pdf_attach(document_id in varchar2,
3796                        content_type in varchar2,
3797                        document in out nocopy blob,
3798                        document_type in out nocopy varchar2) IS
3799   l_filename fnd_lobs.file_name%type;
3800   l_document_id number;
3801   l_document_type po_headers.type_lookup_code%TYPE;
3802   l_org_id number;
3803   l_revision_number number;
3804   l_language fnd_languages.language_code%type;
3805   l_entity_name varchar2(30);
3806   l_itemtype po_document_types.wf_approval_itemtype%type;
3807   l_itemkey varchar2(60);
3808   l_document blob;
3809   l_withTerms varchar2(1);
3810   l_document_length number;
3811   l_message FND_NEW_MESSAGES.message_text%TYPE; --Bug#3274081
3812 
3813 
3814   x_progress varchar2(300);
3815    l_draft_id number;
3816 
3817   begin
3818     x_progress := 'PO_COMMUNICATION_PVT.pdf_attach';
3819 
3820     l_itemtype := substr(document_id, 1, instr(document_id, ':') - 1);
3821     l_itemkey := substr(document_id, instr(document_id, ':') + 1, length(document_id) - 2);
3822 
3823     IF (g_po_wf_debug = 'Y') THEN
3824       PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, x_progress);
3825     END IF;
3826 
3827     l_document_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3828                                                   itemkey => l_itemkey,
3829                                                   aname => 'DOCUMENT_ID');
3830 
3831     l_org_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3832                                              itemkey => l_itemkey,
3833                                              aname => 'ORG_ID');
3834 
3835     l_document_type := wf_engine.GetItemAttrText (itemtype => l_itemtype,
3836                                                   itemkey => l_itemkey,
3837                                                   aname => 'DOCUMENT_TYPE');
3838 
3839     l_language := wf_engine.GetItemAttrText (itemtype => l_itemtype,
3840                                              itemkey => l_itemkey,
3841                                              aname => 'LANGUAGE_CODE');
3842 
3843     l_revision_number := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3844                                                       itemkey => l_itemkey,
3845                                                       aname => 'REVISION_NUMBER');
3846 
3847     l_withTerms := wf_engine.GetItemAttrText (itemtype => l_itemtype,
3848                                               itemkey => l_itemkey,
3849                                               aname => 'WITH_TERMS');
3850 
3851      l_draft_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
3852                                                   itemkey => l_itemkey,
3853                                                   aname => 'DRAFT_ID');
3854 
3855     /* Bug 13330239. Below block of code is common for both With and Without contract terms */
3856     /* Bug 3849854. PDF is not communicated in Suppliers language
3857        According to the document_id (po_header_id/po_release_id),
3858        the language is found from po_vendor_sites and corresponding
3859        PDF is retrieved
3860        Bug 3851357. Changed po_vendor_sites to po_vendor_sites_all because
3861        po_vendor_sites is an org striped view. The query was failing in the
3862        particular case when the MO:Operating unit site level value was
3863        different from buyer's user level value */
3864       Begin
3865 
3866         if l_document_type in ('PO', 'PA') then
3867           select fl.language_code into l_language
3868           from po_vendor_sites_all pvs, po_headers_all ph, fnd_languages fl
3869           where ph.vendor_site_id = pvs.vendor_site_id
3870           and ph.po_header_id = l_document_id
3871           and pvs.language = fl.nls_language;
3872         elsif l_document_type = 'RELEASE' then
3873           select fl.language_code into l_language
3874           from po_vendor_sites_all pvs , po_headers_all ph,
3875                po_releases_all pr, fnd_languages fl
3876           where ph.po_header_id = pr.po_header_id
3877           and pr.po_release_id = l_document_id
3878           and ph.vendor_site_id = pvs.vendor_site_id
3879           and pvs.language = fl.nls_language;
3880         end if;
3881       Exception when others Then
3882         -- A no_data_found exception will be raised if language preference is
3883         -- left null in the vendor sites form. In this case communicate the
3884         -- PDF in buyer's language only.
3885         -- If there is any other exception then also leave the language to
3886         -- buyer's as selected from the workflow attribute above
3887           null;
3888       End;
3889 
3890     if l_withTerms = 'Y' then
3891       --bug#3463617
3892       l_filename := po_communication_pvt.getPDFFileName(l_document_type, '_TERMS_', l_org_id, l_document_id, l_revision_number, l_draft_id, l_language, 'N');
3893     else
3894       --bug#3463617
3895       l_filename := po_communication_pvt.getPDFFileName(l_document_type, '_', l_org_id, l_document_id, l_revision_number, l_draft_id, l_language, 'N');
3896 
3897     end if;
3898 
3899 	/*Begin Edit Akyanama Bug # 13242469 */
3900 	/*The Below Piece of code is moved up so that the l_entity_name gets populated before the usage of the same in the below query*/
3901 	if l_document_type in ('PO', 'PA') then
3902       l_entity_name := 'PO_HEAD';
3903     end if;
3904 
3905     if l_document_type = 'RELEASE' then
3906       l_entity_name := 'PO_REL';
3907     end if;
3908 	/*Begin Edit Akyanama Bug # 13242469 */
3909 
3910       /*IF l_withTerms = 'Y' THEN
3911 --Bug #4865352 - Replaced fnd_documents_tl with fnd_documents_vl
3912 -- Bug 4047688
3913 -- Appended join condition on file name of document to prevent return of multiple rows
3914         SELECT file_data into l_document
3915         FROM fnd_lobs fl,
3916              fnd_attached_documents fad,
3917              fnd_documents_vl fdl
3918         --Begin Edit Akyanama Bug # 13242469
3919 	--Changed the below line
3920 		From : fad.pk2_value = to_char(l_document_id) and fad.pk3_value = to_char(l_revision_number)
3921 		To   : fad.pk1_value = to_char(l_document_id) and fad.pk2_value = to_char(l_revision_number)
3922         WHERE fad.pk1_value = to_char(l_document_id) and fad.pk2_value = to_char(l_revision_number)
3923 	--Replacing 'OKC_CONTRACT_DOCS' in the below line with l_entity_name since PDF with terms and conditions
3924          --is stored in PO_HEAD or PO_REL entity rather than 'OKC_CONTRACT_DOCS'*/
3925        /*  and fdl.document_id = fad.document_id and fdl.media_id = fl.file_id and fad.entity_name = l_entity_name --'OKC_CONTRACT_DOCS'
3926 		--End Edit Akyanama Bug # 13242469
3927 		and fl.file_name = l_filename; --Bug 4047688
3928 
3929       END IF;
3930 
3931     END IF;
3932 
3933     if l_document_type in ('PO', 'PA', 'RELEASE') and l_withTerms = 'N' then
3934     --Bug #4865352 - Added a join with fnd_documents
3935       SELECT file_data into l_document
3936       FROM fnd_lobs fl,
3937            fnd_attached_documents fad,
3938            fnd_documents fd,
3939           fnd_documents_tl fdl
3940       WHERE fad.pk1_value = to_char(l_document_id) and fad.pk2_value = to_char(l_revision_number)
3941       and fdl.document_id = fad.document_id and fd.media_id = fl.file_id and fd.document_id = fdl.document_id
3942       and fad.entity_name = l_entity_name and fl.file_name = l_filename and fdl.language = l_language; */
3943 
3944    	  /* FP Bug 13870183 : Logic while fetching pdf is now changed to, fetch pdf from PO_HEAD/PO_REL,
3945  	     If document does not exists on PO_HEAD and PO_REL, fetch it from OKC_CONTRACT_DOCS*/
3946  	   IF l_document_type in ('PO', 'PA', 'RELEASE') THEN
3947 
3948  	     BEGIN
3949  	      SELECT file_data into l_document
3950  	      FROM fnd_lobs fl,
3951  	         fnd_attached_documents fad,
3952  	         fnd_documents fd,
3953  	         fnd_documents_tl fdl
3954  	      WHERE fad.pk1_value = to_char(l_document_id)
3955  	          and fad.pk2_value = to_char(l_revision_number)
3956  	      	  and fdl.document_id = fad.document_id
3957  	          and fdl.document_id = fd.document_id
3958  	          and fd.media_id = fl.file_id
3959  	      	  and fad.entity_name = l_entity_name
3960  	          and fdl.language = l_language
3961  	      	  and fl.file_name = l_filename ;
3962 
3963  	         IF (g_po_wf_debug = 'Y') THEN
3964  	            PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, 'Fetching from PO_HEAD/PO_REL....');
3965  	         END IF;
3966 
3967  	     EXCEPTION
3968  	         WHEN No_Data_Found THEN
3969  	          IF (g_po_wf_debug = 'Y') THEN
3970  	                 PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, 'Fetching from OKC_CONTRACT_DOC entity.....');
3971  	          END IF;
3972 
3973  	             SELECT file_data into l_document
3974  	             FROM fnd_lobs fl,
3975  	                 fnd_attached_documents fad,
3976  	                 fnd_documents fd,
3977  	                 fnd_documents_tl fdl
3978  	             WHERE fad.pk2_value = to_char(l_document_id)
3979  	                 and fad.pk3_value = to_char(l_revision_number)
3980  	            	 and fdl.document_id = fad.document_id
3981  	                 and fdl.document_id = fd.document_id
3982  	                 and fd.media_id = fl.file_id
3983  	       		 and fad.entity_name = 'OKC_CONTRACT_DOCS'
3984  	                 and fdl.language = l_language
3985  	             	 and fl.file_name = l_filename ;
3986  	     END;
3987            END IF;
3988 
3989     l_document_length := dbms_lob.GetLength(l_document);
3990       IF (g_po_wf_debug = 'Y') THEN
3991  	         PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, 'Document Length : '||l_document_length);
3992       END IF;
3993     dbms_lob.copy(document, l_document, l_document_length, 1, 1);
3994 
3995     document_type :='application/pdf; name='|| l_filename;
3996 
3997   EXCEPTION
3998     WHEN OTHERS THEN
3999    --l_document:=fnd_message.get_string('PO','PO_PDF_FAILED');
4000    --WF_NOTIFICATION.WriteToBlob(document, l_document);
4001       x_progress := 'PO_COMMUNICATION_PVT.pdf_attach - Exception ';
4002 
4003       IF (g_po_wf_debug = 'Y') THEN
4004         PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, x_progress);
4005       END IF;
4006 
4007 --Bug#3274081 Display the message to the user incase the pdf fails.
4008 --Bug 4047688: Removed concatenation of l_filename from document_type
4009       document_type := 'text/html';
4010       l_message := fnd_message.get_string('PO', 'PO_PDF_FAILED');
4011       DBMS_LOB.write(document, lengthb(l_message), 1, UTL_RAW.cast_to_raw(l_message));
4012 
4013   END pdf_attach;
4014 
4015 
4016 -- <Start Word Integration 11.5.10+>
4017 -------------------------------------------------------------------------------
4018 --Start of Comments
4019 --Name: okc_doc_attach
4020 --Pre-reqs:
4021 --  Should only be called if contracts document exists and is not merged
4022 --  into the PO PDF file.
4023 --Modifies:
4024 --  None.
4025 --Locks:
4026 --  None.
4027 --Function:
4028 --  Attaches "attached document" contract terms from contracts.
4029 --Parameters:
4030 --IN:
4031 --  Follows the workflow document attachment API specification.
4032 --Testing:
4033 --
4034 --End of Comments
4035 -------------------------------------------------------------------------------
4036   PROCEDURE okc_doc_attach(document_id in varchar2,
4037                            content_type in varchar2,
4038                            document in out nocopy blob,
4039                            document_type in out nocopy varchar2)
4040   IS
4041 
4042   l_okc_file_id fnd_lobs.file_id%TYPE;
4043   l_okc_file_name fnd_lobs.file_name%TYPE;
4044   l_okc_file_data fnd_lobs.file_data%TYPE;
4045   l_okc_file_content_type fnd_lobs.file_content_type%TYPE;
4046 
4047   l_po_document_id number;
4048   l_po_document_type po_headers.type_lookup_code%TYPE;
4049   l_po_document_subtype po_headers.type_lookup_code%TYPE;
4050   l_po_org_id number;
4051   l_po_revision_number number;
4052   l_language fnd_languages.language_code%type;
4053   l_withTerms varchar2(1);
4054 
4055   l_itemtype po_document_types.wf_approval_itemtype%type;
4056   l_itemkey PO_HEADERS_ALL.wf_item_key%TYPE;
4057   l_message FND_NEW_MESSAGES.message_text%TYPE;
4058 
4059   l_okc_doc_length number; -- Bug 4173198
4060 
4061   x_progress varchar2(300);
4062 
4063   l_draft_id number; --Mod Project
4064 
4065   BEGIN
4066 
4067     x_progress := 'PO_COMMUNICATION_PVT.okc_doc_attach:010';
4068 
4069     l_itemtype := substr(document_id, 1, instr(document_id, ':') - 1);
4070     l_itemkey := substr(document_id, instr(document_id, ':') + 1,
4071                         length(document_id) - 2);
4072 
4073     IF (g_po_wf_debug = 'Y') THEN
4074       PO_WF_DEBUG_PKG.insert_debug(l_itemtype, l_itemkey, x_progress);
4075     END IF;
4076 
4077     l_po_document_id := PO_WF_UTIL_PKG.GetItemAttrNumber (
4078                                                           itemtype => l_itemtype,
4079                                                           itemkey => l_itemkey,
4080                                                           aname => 'DOCUMENT_ID');
4081 
4082     l_po_org_id := PO_WF_UTIL_PKG.GetItemAttrNumber(
4083                                                     itemtype => l_itemtype,
4084                                                     itemkey => l_itemkey,
4085                                                     aname => 'ORG_ID');
4086 
4087     l_po_document_type := PO_WF_UTIL_PKG.GetItemAttrText (
4088                                                           itemtype => l_itemtype,
4089                                                           itemkey => l_itemkey,
4090                                                           aname => 'DOCUMENT_TYPE');
4091 
4092     l_po_document_subtype := PO_WF_UTIL_PKG.GetItemAttrText(
4093                                                             itemtype => l_itemtype,
4094                                                             itemkey => l_itemkey,
4095                                                             aname => 'DOCUMENT_SUBTYPE');
4096 
4097     l_language := PO_WF_UTIL_PKG.GetItemAttrText (
4098                                                   itemtype => l_itemtype,
4099                                                   itemkey => l_itemkey,
4100                                                   aname => 'LANGUAGE_CODE');
4101 
4102     l_po_revision_number := PO_WF_UTIL_PKG.GetItemAttrNumber (
4103                                                               itemtype => l_itemtype,
4104                                                               itemkey => l_itemkey,
4105                                                               aname => 'REVISION_NUMBER');
4106 
4107     l_withTerms := PO_WF_UTIL_PKG.GetItemAttrText (
4108                                                    itemtype => l_itemtype,
4109                                                    itemkey => l_itemkey,
4110                                                    aname => 'WITH_TERMS');
4111 
4112 --Mod Project
4113     l_draft_id := PO_WF_UTIL_PKG.GetItemAttrNumber (
4114                                                               itemtype => l_itemtype,
4115                                                               itemkey => l_itemkey,
4116                                                               aname => 'DRAFT_ID');
4117     if l_draft_id is null then
4118         l_draft_id := -1;
4119     end if;
4120 --Mod Project
4121     x_progress := '020';
4122 
4123     IF (g_po_wf_debug = 'Y') THEN
4124       PO_WF_DEBUG_PKG.insert_debug(l_itemtype, l_itemkey, x_progress);
4125     END IF;
4126 
4127     IF l_withTerms <> 'Y' THEN
4128       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
4129     END IF;
4130 
4131     if l_draft_id = -1 then
4132         l_okc_file_id := OKC_TERMS_UTIL_GRP.GET_PRIMARY_TERMS_DOC_FILE_ID(
4133                                                                       P_document_type =>
4134                                                                       PO_CONTERMS_UTL_GRP.get_po_contract_doctype(l_po_document_subtype)
4135                                                                       , P_document_id => l_po_document_id
4136                                                                       );
4137     else
4138         l_okc_file_id := OKC_TERMS_UTIL_GRP.GET_PRIMARY_TERMS_DOC_FILE_ID(
4139                                                                       P_document_type =>
4140                                                                       PO_CONTERMS_UTL_GRP.get_po_contract_doctype_mod(l_po_document_subtype)
4141                                                                       , P_document_id => l_draft_id
4142                                                                       );
4143     end if; --Mod Project
4144 
4145     x_progress := '030; l_okc_file_id = ' || l_okc_file_id;
4146 
4147     IF (g_po_wf_debug = 'Y') THEN
4148       PO_WF_DEBUG_PKG.insert_debug(l_itemtype, l_itemkey, x_progress);
4149     END IF;
4150 
4151     IF (l_okc_file_id > 0)
4152       THEN
4153 
4154     -- Bug 4173198: Select file_data from fnd_lobs into local variable
4155     -- l_okc_file_data first and then use dbms_lob.copy
4156 
4157       SELECT fl.file_name, fl.file_content_type, fl.file_data
4158       INTO l_okc_file_name, l_okc_file_content_type, l_okc_file_data
4159       FROM fnd_lobs fl
4160       WHERE fl.file_id = l_okc_file_id;
4161 
4162       document_type := l_okc_file_content_type || '; name=' || l_okc_file_name;
4163 
4164       l_okc_doc_length := dbms_lob.GetLength(l_okc_file_data);
4165       dbms_lob.copy(document, l_okc_file_data, l_okc_doc_length, 1, 1);
4166 
4167     ELSE
4168 
4169     /* file does not exist; return a null */
4170       document := NULL;
4171       document_type := NULL;
4172 
4173     END IF; /* l_okc_file_id > 0 */
4174 
4175     x_progress := 'END OF okc_doc_attach';
4176 
4177     IF (g_po_wf_debug = 'Y') THEN
4178       PO_WF_DEBUG_PKG.insert_debug(l_itemtype, l_itemkey, x_progress);
4179     END IF;
4180 
4181   EXCEPTION
4182 
4183   /* Handle Exceptions */
4184     WHEN others THEN
4185       x_progress := 'PO_COMMUNICATION_PVT.pdf_attach - Exception ';
4186 
4187       IF (g_po_wf_debug = 'Y') THEN
4188         PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, x_progress);
4189       END IF;
4190 
4191       document_type :='text/html; name='|| l_okc_file_name;
4192       l_message := fnd_message.get_string('PO', 'PO_OKC_DOC_FAILED');
4193       DBMS_LOB.write(document, lengthb(l_message), 1, UTL_RAW.cast_to_raw(l_message));
4194 
4195   END okc_doc_attach;
4196 
4197 
4198 -- <End Word Integration 11.5.10+>
4199 
4200 
4201 
4202 -------------------------------------------------------------------------------
4203 --Start of Comments
4204 --Name: zip_attach
4205 --Pre-reqs:
4206 --  Zip file should be generated correctly and stored in the database
4207 --Modifies:
4208 --  None.
4209 --Locks:
4210 --  None.
4211 --Function:
4212 --  Queries the Zip Blob for specified document and returns it as a blob
4213 --  to attach to the workflow notification
4214 --Parameters:
4215 --  Follows workflow standatd API specification for documents
4216 --IN:
4217 --document_id
4218 --  A string the uniquely identifies the document to be attached
4219 --content_type
4220 --  For PL/SQL Blob documents, the values is ''
4221 --IN OUT:
4222 --document
4223 --  Outbound Lob locator for the Blob to be attached
4224 --document_type
4225 --  String buffer that contains the content type of outbound Blob
4226 --Notes:
4227 --  Added as a part of <PO Attachment Support 11i.11>
4228 --End of Comments
4229 -------------------------------------------------------------------------------
4230   PROCEDURE zip_attach(document_id in varchar2,
4231                        content_type in varchar2,
4232                        document in out nocopy blob,
4233                        document_type in out nocopy varchar2) IS
4234   l_filename fnd_lobs.file_name%type;
4235   l_document_id po_headers_all.po_header_id%type;
4236   l_document_number po_headers_all.segment1%type;
4237   l_document_type po_headers_all.type_lookup_code%TYPE;
4238   l_org_id po_headers_all.org_id%type;
4239   l_revision_number po_headers_all.revision_num%type;
4240   l_language fnd_languages.language_code%type;
4241   l_entity_name fnd_attached_documents.entity_name%type;
4242   l_itemtype wf_items.item_type%type;
4243   l_itemkey wf_items.item_key%type;
4244   l_document fnd_lobs.file_data%type;
4245   l_document_length number;
4246   l_progress varchar2(300);
4247   l_filecontent_type fnd_lobs.file_content_type%type;
4248   l_message FND_NEW_MESSAGES.message_text%TYPE;
4249 
4250 
4251   BEGIN
4252     l_progress := 'PO_COMMUNICATION_PVT.zip_attach : Begin';
4253 
4254     l_itemtype := substr(document_id, 1, instr(document_id, ':') - 1);
4255     l_itemkey := substr(document_id, instr(document_id, ':') + 1, length(document_id) - 2);
4256 
4257     IF (g_po_wf_debug = 'Y') THEN
4258       PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, l_progress);
4259     END IF;
4260 
4261     l_progress := 'PO_COMMUNICATION_PVT.zip_attach : Get item attributes';
4262     l_document_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
4263                                                   itemkey => l_itemkey,
4264                                                   aname => 'DOCUMENT_ID');
4265 
4266     l_org_id := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
4267                                              itemkey => l_itemkey,
4268                                              aname => 'ORG_ID');
4269 
4270     l_document_type := wf_engine.GetItemAttrText (itemtype => l_itemtype,
4271                                                   itemkey => l_itemkey,
4272                                                   aname => 'DOCUMENT_TYPE');
4273 
4274     l_language := wf_engine.GetItemAttrText (itemtype => l_itemtype,
4275                                              itemkey => l_itemkey,
4276                                              aname => 'LANGUAGE_CODE');
4277 
4278     l_revision_number := wf_engine.GetItemAttrNumber (itemtype => l_itemtype,
4279                                                       itemkey => l_itemkey,
4280                                                       aname => 'REVISION_NUMBER');
4281 
4282     l_progress := 'PO_COMMUNICATION_PVT.zip_attach : Decide Entity to query';
4283     IF l_document_type in ('PO', 'PA') THEN
4284       l_entity_name := 'PO_HEAD';
4285     ELSIF l_document_type = 'RELEASE' THEN
4286       l_entity_name := 'PO_REL';
4287     END IF;
4288 
4289     l_progress := 'PO_COMMUNICATION_PVT.zip_attach : Get Zip file name';
4290     Begin
4291         --Bug# 5240634 Pass in the org_id to getZIPFileName
4292       l_filename := getZIPFileName(l_org_id);
4293     Exception When others Then
4294         l_progress := 'PO_COMMUNICATION_PVT.zip_attach : Exception in getZIPFileName';
4295         raise;
4296     End;
4297 
4298     l_progress := 'PO_COMMUNICATION_PVT.zip_attach : Query the Zip blob';
4299     --Bug #4865352 - Added a join with fnd_documents and selected media_id from it
4300     Begin
4301       SELECT fl.file_data, fl.file_content_type
4302       INTO l_document, l_filecontent_type
4303       FROM fnd_lobs fl,
4304            fnd_attached_documents fad,
4305            fnd_documents fd,
4306            fnd_documents_tl fdl
4307       WHERE fad.pk1_value = to_char(l_document_id)
4308       and fad.pk2_value = to_char(l_revision_number)
4309       and fad.entity_name = l_entity_name
4310       and fdl.document_id = fad.document_id
4311       and fdl.document_id = fd.document_id
4312       and fdl.language = l_language
4313         --Bug 5017976 selecting media_id from fd instead of fdl
4314       and fd.media_id = fl.file_id
4315       and fl.file_name = l_filename;
4316     Exception
4317       When others Then
4318         l_progress := 'PO_COMMUNICATION_PVT.zip_attach : no_data_found';
4319         raise;
4320     End;
4321 
4322     l_progress := 'PO_COMMUNICATION_PVT.zip_attach : Get blob length';
4323     l_document_length := dbms_lob.GetLength(l_document);
4324 
4325     l_progress := 'PO_COMMUNICATION_PVT.zip_attach : Copy zip blob';
4326     dbms_lob.copy(document, l_document, l_document_length, 1, 1);
4327 
4328     l_progress := 'PO_COMMUNICATION_PVT.zip_attach : Set document type';
4329     document_type := l_filecontent_type ||'; name='|| l_filename;
4330 
4331     l_progress := 'PO_COMMUNICATION_PVT.zip_attach : End';
4332   EXCEPTION
4333     WHEN OTHERS THEN
4334 
4335       IF (g_po_wf_debug = 'Y') THEN
4336         PO_WF_DEBUG_PKG.INSERT_DEBUG(l_itemtype, l_itemkey, l_progress ||' '|| SQLERRM);
4337       END IF;
4338 
4339       document_type :='text/html; name='|| l_filename;
4340       l_message := fnd_message.get_string('PO', 'PO_ZIP_FAILED');
4341       DBMS_LOB.write(document, lengthb(l_message), 1, UTL_RAW.cast_to_raw(l_message));
4342 
4343   END zip_attach;
4344 
4345 -------------------------------------------------------------------------------
4346 --Start of Comments
4347 --Name: set_zip_error_code
4348 --Pre-reqs:
4349 --  None.
4350 --Modifies:
4351 --  Workflow Attribute zip_error_code
4352 --Locks:
4353 --  None.
4354 --Function:
4355 --  Sets the workflow attribute zip_error_code to the value passed in
4356 --Parameters:
4357 --IN:
4358 --p_itemtype
4359 --  String that identifies the workflow process
4360 --p_itemkey
4361 --  Uniquely identifies the current instance of the workflow process
4362 --p_zip_error_code
4363 --  Value to which the workflow attribute zip_error_code should be
4364 --  set to. Possible values can be OVERSIZED, DUPLICATE_FILENAME
4365 --  and UNEXPECTED (values of lookup type POAPPRV_ZIP_ERROR_CODE)
4366 --Notes:
4367 --  Added as a part of <PO Attachment Support 11i.11>
4368 --End of Comments
4369 -------------------------------------------------------------------------------
4370   PROCEDURE set_zip_error_code (p_itemtype IN VARCHAR2,
4371                                 p_itemkey IN VARCHAR2,
4372                                 p_zip_error_code IN VARCHAR2) IS
4373   BEGIN
4374     -- Set the value of the workflow attribute zip_error_code
4375     PO_WF_UTIL_PKG.SetItemAttrText(itemtype => p_itemtype,
4376                                    itemkey => p_itemkey,
4377                                    aname => 'ZIP_ERROR_CODE',
4378                                    avalue => p_zip_error_code);
4379   END set_zip_error_code;
4380 
4381 -------------------------------------------------------------------------------
4382 --Start of Comments
4383 --Name: get_zip_error_code
4384 --Pre-reqs:
4385 --  None.
4386 --Modifies:
4387 --  None.
4388 --Locks:
4389 --  None.
4390 --Function:
4391 --  Returns the value of workflow attribute ZIP_ERROR_CODE
4392 --Parameters:
4393 --  Follows standard workflow API specification
4394 --IN:
4395 --itemtype
4396 --  String that identifies the workflow process
4397 --itemkey
4398 --  Uniquely identifies the current instance of the workflow process
4399 --actid
4400 --  The ID number of the activity from which this procedure is callled
4401 --funcmode
4402 --  The execution mode of the activity
4403 --OUT:
4404 --resultout
4405 --  Holds the value of the workflow attribute zip_error_code. Possible
4406 --  values can be OVERSIZED, DUPLICATE_FILENAME and UNEXPECTED
4407 --  (values of lookup type POAPPRV_ZIP_ERROR_CODE)
4408 --Notes:
4409 --  Added as a part of <PO Attachment Support 11i.11>
4410 --End of Comments
4411 -------------------------------------------------------------------------------
4412   PROCEDURE get_zip_error_code (itemtype IN VARCHAR2,
4413                                 itemkey IN VARCHAR2,
4414                                 actid IN NUMBER,
4415                                 funcmode IN VARCHAR2,
4416                                 resultout OUT NOCOPY VARCHAR2) IS
4417   l_progress varchar2(200);
4418   BEGIN
4419     -- Get the value of the workflow attribute zip_error_code
4420     l_progress := 'PO_COMMUNICATION_PVT.get_zip_error_code: 01';
4421     resultout := PO_WF_UTIL_PKG.GetItemAttrText(itemtype => itemtype,
4422                                                 itemkey => itemkey,
4423                                                 aname => 'ZIP_ERROR_CODE');
4424     l_progress := 'PO_COMMUNICATION_PVT.get_zip_error_code: 02';
4425     resultout := wf_engine.eng_completed || ':' || resultout;
4426   EXCEPTION when others THEN
4427       WF_CORE.context('PO_COMMUNICATION_PVT', 'get_zip_error_code', l_progress);
4428       raise;
4429   END get_zip_error_code;
4430 
4431 -------------------------------------------------------------------------------
4432 --Start of Comments
4433 --Name: get_max_zip_size
4434 --Pre-reqs:
4435 --  Column max_attachment_size should exist in table po_system_parameters_all
4436 --  Org context should be set correctly to enable querying from org striped
4437 --  view po_system_parameters
4438 --Modifies:
4439 --  None.
4440 --Locks:
4441 --  None.
4442 --Function:
4443 --  Queries the value of 'Maximum Attachment Size' which is the maximum
4444 --  allowed size of the Zip file.
4445 --Parameters:
4446 --IN:
4447 --itemtype
4448 --  String that identifies the workflow process
4449 --itemkey
4450 --  Uniquely identifies the current instance of the workflow process
4451 --Returns:
4452 --  For functions:
4453 --    Returns the values of 'Maximum Attachment Size' in Purchasing Options
4454 --    Setup form. This is the maximum allowed size of the Zip file.
4455 --Notes:
4456 --  Added as a part of <PO Attachment Support 11i.11>
4457 --  A value of 0 means Zip Attachments are not supported
4458 --End of Comments
4459 -------------------------------------------------------------------------------
4460   FUNCTION get_max_zip_size (p_itemtype IN VARCHAR2,
4461                              p_itemkey IN VARCHAR2) RETURN NUMBER IS
4462   l_max_attachment_size po_system_parameters_all.max_attachment_size%type;
4463   l_progress varchar2(200);
4464   BEGIN
4465     l_progress := 'PO_COMMUNICATION_PVT.get_max_zip_size : Querying max_attachment_size';
4466     IF (g_po_wf_debug = 'Y') THEN
4467       PO_WF_DEBUG_PKG.insert_debug(p_itemtype, p_itemkey, l_progress);
4468     END IF;
4469     select nvl(psp.max_attachment_size, 0)
4470     into l_max_attachment_size
4471     from po_system_parameters psp;
4472     l_progress := 'PO_COMMUNICATION_PVT.get_max_zip_size : maximum attachment size = '|| l_max_attachment_size;
4473     IF (g_po_wf_debug = 'Y') THEN
4474       PO_WF_DEBUG_PKG.insert_debug(p_itemtype, p_itemkey, l_progress);
4475     END IF;
4476     return l_max_attachment_size;
4477   Exception
4478     when others then
4479       l_progress := 'PO_COMMUNICATION_PVT.get_max_zip_size : handled exception while getting Maximum Attachment Size ';
4480       IF (g_po_wf_debug = 'Y') THEN
4481         PO_WF_DEBUG_PKG.insert_debug(p_itemtype, p_itemkey, l_progress);
4482       END IF;
4483       l_max_attachment_size := 0;
4484   END get_max_zip_size;
4485 
4486 
4487 -------------------------------------------------------------------------------
4488 --Start of Comments
4489 --Name: check_for_attachments
4490 --Pre-reqs:
4491 --  None.
4492 --Modifies:
4493 --  None.
4494 --Locks:
4495 --  None.
4496 --Function:
4497 --  Checks if any attachments of category 'To Supplier' and type 'File'
4498 --  exist for the current PO/Release
4499 --Parameters:
4500 --IN:
4501 --p_document_type
4502 --  Document Type, can be PO, PA or RELEASE
4503 --p_document_id
4504 --  po_header_id for PO, PA and po_release_id for RELEASE
4505 --Returns:
4506 --  For functions:
4507 --    Returns 'Y' if any attachments of category 'To Supplier' and type 'File'
4508 --    exist for the current PO/Release
4509 --Notes:
4510 --  Added as a part of <PO Attachment Support 11i.11>
4511 --  Exception handling for this light weight function is left to the calling
4512 --  code. This is because the exception handling will be different in
4513 --  different calls
4514 --End of Comments
4515 -------------------------------------------------------------------------------
4516   FUNCTION check_for_attachments(p_document_type IN VARCHAR2,
4517                                  p_document_id IN NUMBER) RETURN VARCHAR2 IS
4518   l_attachments_exist VARCHAR2(1);
4519   -- bug 8930818 : To make computation faster segregation OR clauses into independant select queries summed by UNION ALL
4520   BEGIN
4521     IF (p_document_type = 'RELEASE') THEN
4522 
4523         -- bug4931216
4524         -- Go directly to the base tables for better performance
4525       select 'Y' into l_attachments_exist from dual
4526       where exists
4527       (
4528           select fl.file_name
4529             from   fnd_documents d,
4530                    fnd_attached_documents ad,
4531                    fnd_doc_category_usages dcu,
4532                    fnd_attachment_functions af,
4533                    fnd_lobs fl
4534             where (ad.pk1_value=to_char((select po_header_id from po_releases_all
4535                                    where po_release_id=p_document_id
4536                                   ))and ad.entity_name='PO_HEADERS')
4537 
4538             and d.document_id = ad.document_id
4539             and dcu.category_id = d.category_id
4540             and dcu.attachment_function_id = af.attachment_function_id
4541             and d.datatype_id=6
4542             and af.function_name='PO_PRINTPO'
4543             and d.media_id=fl.file_id
4544             and dcu.enabled_flag = 'Y'
4545 
4546 	  UNION ALL
4547 
4548 	   select fl.file_name
4549             from   fnd_documents d,
4550                    fnd_attached_documents ad,
4551                    fnd_doc_category_usages dcu,
4552                    fnd_attachment_functions af,
4553                    fnd_lobs fl
4554 	    where (
4555 		   (ad.pk1_value=to_char(p_document_id) and ad.entity_name='PO_RELEASES'))
4556             and d.document_id = ad.document_id
4557             and dcu.category_id = d.category_id
4558             and dcu.attachment_function_id = af.attachment_function_id
4559             and d.datatype_id=6
4560             and af.function_name='PO_PRINTPO'
4561             and d.media_id=fl.file_id
4562             and dcu.enabled_flag = 'Y'
4563 
4564            UNION ALL
4565 
4566 	     select fl.file_name
4567             from   fnd_documents d,
4568                    fnd_attached_documents ad,
4569                    fnd_doc_category_usages dcu,
4570                    fnd_attachment_functions af,
4571                    fnd_lobs fl
4572 	    where (
4573                    (ad.pk1_value=to_char((select pha.vendor_id
4574                                    from po_headers_all pha,po_releases_all pra
4575                                    where pra.po_release_id=p_document_id
4576                                    and pha.po_header_id=pra.po_header_id
4577                                   )) and ad.entity_name='PO_VENDORS'))
4578             and d.document_id = ad.document_id
4579             and dcu.category_id = d.category_id
4580             and dcu.attachment_function_id = af.attachment_function_id
4581             and d.datatype_id=6
4582             and af.function_name='PO_PRINTPO'
4583             and d.media_id=fl.file_id
4584             and dcu.enabled_flag = 'Y'
4585 
4586             Union ALL
4587 
4588 	    select fl.file_name
4589             from   fnd_documents d,
4590                    fnd_attached_documents ad,
4591                    fnd_doc_category_usages dcu,
4592                    fnd_attachment_functions af,
4593                    fnd_lobs fl
4594   	    where (
4595                    (ad.pk1_value in (select po_line_id from po_line_locations_all
4596                                       where po_release_id=p_document_id
4597                                       and shipment_type='BLANKET'
4598                                      ) and ad.entity_name='PO_LINES'))
4599             and d.document_id = ad.document_id
4600             and dcu.category_id = d.category_id
4601             and dcu.attachment_function_id = af.attachment_function_id
4602             and d.datatype_id=6
4603             and af.function_name='PO_PRINTPO'
4604             and d.media_id=fl.file_id
4605             and dcu.enabled_flag = 'Y'
4606 
4607 	    union all
4608 
4609 	    select fl.file_name
4610             from   fnd_documents d,
4611                    fnd_attached_documents ad,
4612                    fnd_doc_category_usages dcu,
4613                    fnd_attachment_functions af,
4614                    fnd_lobs fl
4615 	    where (
4616                    (ad.pk1_value in (select line_location_id from po_line_locations_all
4617                                       where po_release_id=p_document_id
4618                                       and shipment_type='BLANKET'
4619                                      ) and ad.entity_name='PO_SHIPMENTS'))
4620             and d.document_id = ad.document_id
4621             and dcu.category_id = d.category_id
4622             and dcu.attachment_function_id = af.attachment_function_id
4623             and d.datatype_id=6
4624             and af.function_name='PO_PRINTPO'
4625             and d.media_id=fl.file_id
4626             and dcu.enabled_flag = 'Y'
4627 
4628 	                union all
4629              /*bug 13528070*/
4630 	    select /*+ leading(AD) */ fl.file_name
4631             from   fnd_documents d,
4632                    fnd_attached_documents ad,
4633                    fnd_doc_category_usages dcu,
4634                    fnd_attachment_functions af,
4635                    fnd_lobs fl
4636 	    where (                            /*bug 13528070*/
4637                    (ad.pk2_value in (select /*+ push_subq no_unnest */ pl.item_id
4638                                       from po_lines_all pl, po_line_locations_all pll
4639                                       where pll.po_release_id=p_document_id
4640                                       and pll.shipment_type='BLANKET'
4641                                       and pll.po_line_id=pl.po_line_id
4642                                       and pl.item_id is not null
4643                                      ) AND ad.entity_name='MTL_SYSTEM_ITEMS'))
4644             /*bug 13528070*/
4645             and to_char(PO_COMMUNICATION_PVT.getInventoryOrgId())=ad.pk1_value --Bug 4673653 Use Inventory OrgId
4646             and d.document_id = ad.document_id
4647             and dcu.category_id = d.category_id
4648             and dcu.attachment_function_id = af.attachment_function_id
4649             and d.datatype_id=6
4650             and af.function_name='PO_PRINTPO'
4651             and d.media_id=fl.file_id
4652             and dcu.enabled_flag = 'Y'
4653       );
4654     ELSE
4655 
4656 
4657         -- bug4931216
4658         -- Go directly to the base tables for better performance
4659          select 'Y' into l_attachments_exist from dual
4660         where exists
4661         (
4662             select fl.file_name
4663             from fnd_documents d,
4664                  fnd_attached_documents ad,
4665                  fnd_doc_category_usages dcu,
4666                  fnd_attachment_functions af,
4667                  fnd_lobs fl
4668             where (ad.pk1_value=to_char(p_document_id) and ad.entity_name='PO_HEADERS')
4669 	    and d.document_id = ad.document_id
4670             and dcu.category_id = d.category_id
4671             and dcu.attachment_function_id = af.attachment_function_id
4672             and d.datatype_id=6
4673             and af.function_name='PO_PRINTPO'
4674             and d.media_id=fl.file_id
4675             and dcu.enabled_flag = 'Y'
4676 
4677            Union all
4678 
4679 	    select fl.file_name
4680             from fnd_documents d,
4681                  fnd_attached_documents ad,
4682                  fnd_doc_category_usages dcu,
4683                  fnd_attachment_functions af,
4684                  fnd_lobs fl
4685             where (
4686                    (ad.pk1_value=to_char((select vendor_id from po_headers_all
4687                                    where po_header_id=p_document_id)) and ad.entity_name='PO_VENDORS'))
4688 
4689             and d.document_id = ad.document_id
4690             and dcu.category_id = d.category_id
4691             and dcu.attachment_function_id = af.attachment_function_id
4692             and d.datatype_id=6
4693             and af.function_name='PO_PRINTPO'
4694             and d.media_id=fl.file_id
4695             and dcu.enabled_flag = 'Y'
4696 
4697             Union all
4698 
4699            select fl.file_name
4700            from fnd_documents d,
4701                 fnd_attached_documents ad,
4702                  fnd_doc_category_usages dcu,
4703                  fnd_attachment_functions af,
4704                  fnd_lobs fl
4705            where (                      /*bug 13528070 Changing to to_char*/
4706                    (ad.pk1_value in (select to_char(po_line_id) from po_lines_all
4707                                       where po_header_id=p_document_id
4708                                      ) and ad.entity_name='PO_LINES'))
4709 
4710             and d.document_id = ad.document_id
4711             and dcu.category_id = d.category_id
4712             and dcu.attachment_function_id = af.attachment_function_id
4713             and d.datatype_id=6
4714             and af.function_name='PO_PRINTPO'
4715             and d.media_id=fl.file_id
4716             and dcu.enabled_flag = 'Y'
4717 
4718      	    Union ALL
4719 
4720             select fl.file_name
4721             from fnd_documents d,
4722                  fnd_attached_documents ad,
4723                  fnd_doc_category_usages dcu,
4724                  fnd_attachment_functions af,
4725                  fnd_lobs fl
4726             where (
4727                    (ad.pk1_value in (select from_header_id from po_lines_all
4728                                       where po_header_id=p_document_id
4729                                       and from_header_id is not null
4730                                      ) and ad.entity_name='PO_HEADERS'))
4731 
4732             and d.document_id = ad.document_id
4733             and dcu.category_id = d.category_id
4734             and dcu.attachment_function_id = af.attachment_function_id
4735             and d.datatype_id=6
4736             and af.function_name='PO_PRINTPO'
4737             and d.media_id=fl.file_id
4738             and dcu.enabled_flag = 'Y'
4739 
4740         Union ALL
4741 
4742             select fl.file_name
4743             from fnd_documents d,
4744                  fnd_attached_documents ad,
4745                  fnd_doc_category_usages dcu,
4746                  fnd_attachment_functions af,
4747                  fnd_lobs fl
4748             where (
4749                    (ad.pk1_value in (select from_line_id from po_lines_all
4750                                       where po_header_id=p_document_id
4751                                       and from_line_id is not null
4752                                      ) and ad.entity_name='PO_LINES'))
4753 
4754             and d.document_id = ad.document_id
4755             and dcu.category_id = d.category_id
4756             and dcu.attachment_function_id = af.attachment_function_id
4757             and d.datatype_id=6
4758             and af.function_name='PO_PRINTPO'
4759             and d.media_id=fl.file_id
4760             and dcu.enabled_flag = 'Y'
4761 
4762 	    Union all
4763 
4764 	    select fl.file_name
4765             from fnd_documents d,
4766                  fnd_attached_documents ad,
4767                  fnd_doc_category_usages dcu,
4768                  fnd_attachment_functions af,
4769                  fnd_lobs fl
4770             where (
4771                    (ad.pk1_value in (select line_location_id from po_line_locations_all
4772                                       where po_header_id=p_document_id
4773                                       and shipment_type in ('PRICE BREAK','STANDARD','PREPAYMENT')  -- <Complex Work R12>
4774                                      ) and ad.entity_name='PO_SHIPMENTS'))
4775 
4776             and d.document_id = ad.document_id
4777             and dcu.category_id = d.category_id
4778             and dcu.attachment_function_id = af.attachment_function_id
4779             and d.datatype_id=6
4780             and af.function_name='PO_PRINTPO'
4781             and d.media_id=fl.file_id
4782             and dcu.enabled_flag = 'Y'
4783 
4784 	    Union ALL
4785                    /*bug 13528070*/
4786             select /*+ leading(AD) */ fl.file_name
4787             from fnd_documents d,
4788                  fnd_attached_documents ad,
4789                  fnd_doc_category_usages dcu,
4790                  fnd_attachment_functions af,
4791                  fnd_lobs fl
4792             where (                    /*bug 13528070*/
4793                    (ad.pk2_value in (select /*+ push_subq no_unnest */ item_id from po_lines_all
4794                                       where po_header_id=p_document_id
4795                                       and item_id is not null
4796                                      ) and ad.entity_name='MTL_SYSTEM_ITEMS'))
4797             /*bug 13528070*/
4798             and to_char(PO_COMMUNICATION_PVT.getInventoryOrgId())=ad.pk1_value --Bug 4673653 Use Inventory OrgId
4799             and d.document_id = ad.document_id
4800             and dcu.category_id = d.category_id
4801             and dcu.attachment_function_id = af.attachment_function_id
4802             and d.datatype_id=6
4803             and af.function_name='PO_PRINTPO'
4804             and d.media_id=fl.file_id
4805             and dcu.enabled_flag = 'Y'
4806       );
4807     END IF;
4808     return l_attachments_exist;
4809   END check_for_attachments;
4810 
4811   FUNCTION POXMLGEN(p_api_version in NUMBER,
4812                     p_document_id in NUMBER,
4813                     p_revision_num in NUMBER,
4814                     p_document_type in VARCHAR2,
4815                     p_document_subtype in VARCHAR2,
4816                     p_test_flag in VARCHAR2,
4817                     p_which_tables in VARCHAR2,
4818                     p_with_terms in VARCHAR2 --Bug#3583910
4819             -- Bug 3690810. Removed the file.encoding parameter
4820                     ) RETURN clob IS
4821 
4822   l_api_name CONSTANT VARCHAR2(30) := 'POXMLGEN';
4823   l_api_version CONSTANT NUMBER := 1.0;
4824   l_xml_result CLOB;
4825   l_version varchar2(20);
4826   l_compatibility varchar2(20);
4827   l_majorVersion number;
4828   l_queryCtx DBMS_XMLquery.ctxType;
4829   l_xml_query varchar2(32000);
4830   l_xml_message_query varchar2(6000);
4831   l_xml9_stmt varchar2(8000);
4832   l_head_short_attachment_query varchar2(6000);
4833   l_line_short_attachment_query varchar2(6000);
4834 
4835   --<Enhanced Pricing Start:>
4836   l_price_modifier_query1 varchar2(6000);
4837   l_price_modifier_query2 varchar2(6000);
4838   l_price_modifier_query3 varchar2(6000);
4839   --<Enhanced Pricing End>
4840 
4841   l_shipment_short_attach_query varchar2(6000);
4842     --<PO Attachment Support 11i.11 Start>
4843   l_head_url_attachment_query varchar2(6000);
4844   l_head_file_attachment_query varchar2(6000);
4845   l_line_url_attachment_query varchar2(6000);
4846   l_line_file_attachment_query varchar2(6000);
4847   l_shipment_url_attach_query varchar2(6000);
4848   l_shipment_file_attach_query varchar2(6000);
4849     --<PO Attachment Support 11i.11 End>
4850   l_headerAttachments clob;
4851   l_headerAttachmentsQuery varchar2(1000);
4852   l_count number;
4853   g_log_head CONSTANT VARCHAR2(30) := 'po.plsql.PO_COMMUNICATION_PVT.';
4854   l_eventType varchar2(20);
4855   l_lineAttachQuery varchar2(8000); --Bug 13082363 : Increasing length
4856   l_line_Attachments clob;
4857   l_shipmentAttachmentQuery varchar2(1200); --Bug5213932 increase length
4858   l_disAttachments clob;
4859   l_time varchar2(50);
4860   l_vendor_id PO_HEADERS_ALL.vendor_id%type;
4861   l_release_header_id PO_HEADERS_ALL.po_header_id%type;
4862   l_supp_org PO_VENDORS.VENDOR_NAME%type;
4863   l_po_number PO_HEADERS.SEGMENT1%type;
4864   l_message varchar2(2001);
4865   l_ammendment_message varchar2(2001);
4866   l_change_summary PO_HEADERS.CHANGE_SUMMARY%type;
4867   l_timezone HZ_TIMEZONES_VL.NAME%TYPE;
4868   l_timezone_id varchar2(10);
4869   l_agreement_assign_query varchar2(2001);
4870   l_arc_agreement_assign_query varchar2(2001);
4871   l_fileClob CLOB := NULL;
4872   l_variablePosition number := 0;
4873   l_resultOffset number ; -- to store the offset
4874   l_tempXMLResult clob; -- temp xml clob;
4875   l_offset HZ_TIMEZONES_VL.GMT_DEVIATION_HOURS%type; -- to store GMT time difference
4876   l_address_details clob; -- bug#3580225: Clob to hold the address details XML
4877 
4878   l_okc_doc_type VARCHAR2(20); -- <Word Integration 11.5.10+>
4879 
4880   -- <Complex Work R12 Start>
4881 
4882   l_adv_amount_query VARCHAR2(160) := '';
4883   l_complex_lloc_query VARCHAR2(500) := '';
4884   l_complex_dist_query VARCHAR2(1300) := '';
4885 
4886   -- <Complex Work R12 End>
4887    /*Bug5983107 */
4888   l_legal_entity_id NUMBER;
4889   x_legalentity_info xle_utilities_grp.LegalEntity_Rec;
4890   x_return_status VARCHAR2(20) ;
4891   x_msg_count NUMBER ;
4892   x_msg_data VARCHAR2(4000) ;
4893   l_org_id number;
4894   /*Bug 5983107*/
4895 
4896   /*Bug 10388305 Added l_tax_name_query to get tax names*/
4897  	   l_tax_name_query VARCHAR2(6000);
4898 
4899     l_custom_xml clob; --<bug 14677799>: clob to hold xml from custom code
4900   BEGIN
4901     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
4902       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ||'Document Id:', p_document_id);
4903     END IF;
4904     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
4905       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ||'Document Type:', p_document_type);
4906     END IF;
4907     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
4908       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ||'Document SubType:', p_document_subtype);
4909     END IF;
4910     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
4911       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ||'Table Type:', p_which_tables);
4912     END IF;
4913 
4914 /* Check the package name and version. IF wrong package or version raise the exception and exit */
4915     IF NOT FND_API.COMPATIBLE_API_CALL(l_api_version,
4916                                        p_api_version,
4917                                        l_api_name,
4918                                        G_PKG_NAME)
4919       THEN
4920       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
4921     END IF;
4922 
4923     PO_COMMUNICATION_PVT.g_document_id := p_document_id;
4924     PO_COMMUNICATION_PVT.g_revision_num := p_revision_num;
4925     PO_COMMUNICATION_PVT.g_test_flag := p_test_flag;
4926 
4927 
4928 --Start Bug#3771735
4929 --Assigned the Document Type Code to global variable
4930     PO_COMMUNICATION_PVT.g_documentTypeCode := p_document_type;
4931 --End Bug#3771735
4932 
4933 /*Bug#3583910 Assigned the parameter value to the g_with_terms variable*/
4934     PO_COMMUNICATION_PVT.g_with_terms := p_with_terms;
4935 
4936 
4937 -- SQl What:  Querying for document type.
4938 -- SQL why: To display the Document type at header level in PO cover and details page.
4939 -- SQL Join:
4940 
4941     PO_COMMUNICATION_PVT.g_documentType := null;
4942 --Bug#3279968 Added the language column to the below sql statement to fetch onlyone record.
4943  --Bug 9391634 org_id was not set because of which fetching data from PO_DOCUMENT_TYPES_TL give error
4944       l_org_id := po_moac_utils_pvt.get_current_org_id;
4945 
4946      IF(l_org_id IS  null) Then
4947 
4948          SELECT org_id INTO l_org_id FROM po_headers_all WHERE po_header_id = p_document_id;
4949          po_moac_utils_pvt.SET_POLICY_CONTEXT('S', l_org_id );
4950 
4951      END IF;
4952   --Bug 9391634 org_id was not set because of which fetching data from PO_DOCUMENT_TYPES_TL give error
4953 
4954     SELECT TYPE_NAME into PO_COMMUNICATION_PVT.g_documentType FROM PO_DOCUMENT_TYPES_TL
4955     WHERE document_type_code = p_document_type and document_subtype = p_document_subtype and language = USERENV('LANG');
4956 
4957 /* For balnket documents eventtype is 'BLANKET LINE' and
4958 for other documents 'PO LINE' is event type, to get the price differentials*/
4959 
4960     IF(p_document_subtype <> 'BLANKET') THEN
4961       l_eventType := 'PO LINE';
4962     ELSE
4963       l_eventType := 'BLANKET LINE';
4964     END IF;
4965 
4966 -- SQl What:  Querying for buyer organisation, supplier organisation, PO number, change summary, vendor id and currency code
4967 -- SQL why: To get long attachments from headers that are attached by vendor, Vendor Id is required.
4968 --    Buyer, supplier organisations, po number and change summary is used to replace the
4969 --    tokens in message text of PO_FO_COVERING_MESSAGE and PO_FO_AMENDMENT_MESSAGE.
4970 -- SQL Join:  vendor_id and org_id
4971 -- Logic: Based on the p_document_type and p_which_tables table names will change
4972 -- Added the sql conditions to find the distinct count of shipment level ship to from header level ship to. This count is
4973 -- used in XSL to identify what to display in ship to address at header and shipment level
4974 
4975     BEGIN
4976       PO_COMMUNICATION_PVT.g_current_currency_code := null;
4977 
4978       IF(p_document_type in ('PO', 'PA')) THEN
4979         IF p_which_tables = 'MAIN' THEN
4980 
4981   /*Bug5983107 Commenting out the below sql and writing the new sql below without reference to  hr_all_organization_units*/
4982   /* SELECT hle.name, vn.vendor_name, ph.segment1, ph.change_summary, ph.vendor_id, ph.currency_code
4983   INTO po_communication_pvt.g_buyer_org, l_supp_org, l_po_number, l_change_summary, l_vendor_id, g_current_currency_code
4984     FROM hr_all_organization_units hle,  po_vendors vn, po_headers_all ph
4985     WHERE to_char(hle.organization_id) =  (select org_information2 from hr_organization_information where
4986     org_information_context = 'Operating Unit Information'  and organization_id = ph.org_id) AND vn.vendor_id = ph.vendor_id
4987     AND ph.po_header_id = p_document_id AND ph.revision_num = p_revision_num; */
4988 
4989           SELECT vn.vendor_name, ph.segment1, ph.change_summary, ph.vendor_id, ph.currency_code
4990           INTO l_supp_org, l_po_number, l_change_summary, l_vendor_id, g_current_currency_code
4991           FROM po_vendors vn, po_headers_all ph
4992           WHERE vn.vendor_id = ph.vendor_id
4993           AND ph.po_header_id = p_document_id AND ph.revision_num = p_revision_num;
4994 
4995 
4996           SELECT count(distinct(plla.SHIP_TO_LOCATION_ID)) INTO PO_COMMUNICATION_PVT.g_dist_shipto_count
4997           FROM po_line_locations_all plla
4998           WHERE plla.po_header_id = p_document_id
4999           AND NVL(plla.payment_type, 'NONE') NOT IN ('ADVANCE', 'DELIVERY'); -- <Complex Work R12>
5000 
5001 
5002         ELSIF p_which_tables = 'ARCHIVE' THEN
5003 
5004     /*Bug5983107 Modifying the below sql by removing reference to  hr_all_organization_units*/
5005 
5006           SELECT vn.vendor_name, ph.segment1, ph.change_summary, ph.vendor_id, ph.currency_code
5007           INTO l_supp_org, l_po_number, l_change_summary, l_vendor_id, g_current_currency_code
5008           FROM po_vendors vn, po_headers_archive_all ph
5009           WHERE vn.vendor_id = ph.vendor_id
5010           AND ph.po_header_id = p_document_id AND ph.revision_num = p_revision_num;
5011 
5012           SELECT count(distinct(plla.SHIP_TO_LOCATION_ID)) INTO PO_COMMUNICATION_PVT.g_dist_shipto_count
5013           FROM po_line_locations_archive_all plla
5014           WHERE plla.po_header_id = p_document_id
5015           and plla.revision_num = p_revision_num
5016           AND NVL(plla.payment_type, 'NONE') NOT IN ('ADVANCE', 'DELIVERY'); -- <Complex Work R12>
5017 
5018         END IF;
5019 
5020   /*Bug5983107  Use the below API to get the legal entity name */
5021         BEGIN
5022           select org_id into l_org_id from po_headers_all where po_header_id = p_document_id ;
5023           l_legal_entity_id := PO_CORE_S.get_default_legal_entity_id(l_org_id);
5024 
5025           XLE_UTILITIES_GRP.Get_LegalEntity_Info(
5026                                                  x_return_status,
5027                                                  x_msg_count,
5028                                                  x_msg_data,
5029                                                  null,
5030                                                  l_legal_entity_id,
5031                                                  x_legalentity_info);
5032 
5033           PO_COMMUNICATION_PVT.g_buyer_org := x_legalentity_info.name;
5034 
5035         EXCEPTION
5036           WHEN OTHERS then
5037             po_communication_pvt.g_buyer_org := null;
5038         END;
5039 
5040   /*Bug5983107 */
5041 
5042         -- bug#3698674: inserted header/release id and revision num into global temp table
5043         -- bug#3823799: Moved the query from top to here to insert data in table based on the document type.
5044         --              po_release_id is inserted as null
5045   -- bug#3853109: Added the column names in the insert clause as per the review comments
5046         insert into PO_COMMUNICATION_GT(po_header_id, po_release_id, revision_number, format_mask)
5047                       values(p_document_id, null, p_revision_num, PO_COMMUNICATION_PVT.getFormatMask);
5048       ELSE
5049     -- Modified as a part of bug #3274076
5050     -- Vendor id is same for revisied and non revised documents. So vendor id is retreived from the releases table.
5051 
5052     -- select the header id into g_release_header_id global variable for a given release id.
5053         SELECT po_header_id INTO PO_COMMUNICATION_PVT.g_release_header_id FROM po_releases_all WHERE po_release_id = p_document_id;
5054 
5055         SELECT ph.vendor_id, ph.currency_code INTO l_vendor_id, g_current_currency_code
5056         FROM po_vendors vn, po_headers_all ph
5057         WHERE vn.vendor_id = ph.vendor_id
5058         AND ph.po_header_id = PO_COMMUNICATION_PVT.g_release_header_id ;
5059 
5060         IF p_which_tables = 'MAIN' THEN
5061           SELECT count(distinct(plla.SHIP_TO_LOCATION_ID)) INTO PO_COMMUNICATION_PVT.g_dist_shipto_count
5062           FROM po_line_locations_all plla
5063           WHERE plla.po_release_id = p_document_id;
5064 
5065         ELSE
5066           SELECT count(distinct(plla.SHIP_TO_LOCATION_ID)) INTO PO_COMMUNICATION_PVT.g_dist_shipto_count
5067           FROM po_line_locations_archive_all plla
5068           WHERE plla.po_release_id = p_document_id
5069           and plla.revision_num = p_revision_num;
5070         END IF;
5071 
5072         -- bug#3698674: inserted header/release id and revision num into global temp table
5073         -- bug#3823799: Moved the query from top to here to insert data in table based on the document type.
5074         --              po_header_id is inserted as null
5075   -- bug#3853109: Added the column names in the insert clause as per the review comments
5076         insert into PO_COMMUNICATION_GT(po_header_id, po_release_id, revision_number, format_mask)
5077                             values(null, p_document_id, p_revision_num, PO_COMMUNICATION_PVT.getFormatMask);
5078       END IF;
5079 
5080     EXCEPTION
5081       WHEN OTHERS then
5082    --Bug5983107  po_communication_pvt.g_buyer_org := null;
5083         l_supp_org := null;
5084         l_po_number := null;
5085         l_change_summary := null;
5086         l_vendor_id := null;
5087     END;
5088     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
5089   /*
5090   To find the version of the database. If the db version is >8 AND <9
5091   XMLQUERY is used to generate the XML AND IF the version is 9 XMLGEN is used.
5092 */
5093 
5094 
5095 
5096       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name || 'POXMLGEN', 'Executing DB Version');
5097     END IF;
5098 
5099     DBMS_UTILITY.DB_VERSION(l_version, l_compatibility);
5100     l_majorVersion := to_number(substr(l_version, 1, instr(l_version, '.') - 1));
5101     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
5102       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name , 'DB Version'|| l_majorVersion);
5103     END IF;
5104 
5105 /*Bug 6692126 Call the procedure gettandc which in turn calls
5106 the procedure get_preparer_profile which gets the profile option values
5107 in preparers context */
5108 /* get terms and conditions message*/
5109 /*IF FND_PROFILE.VALUE('PO_EMAIL_TERMS_FILE_NAME') IS NOT NULL THEN
5110    PO_XML_UTILS_GRP.getTandC(fnd_global.user_id(), fnd_global.resp_id(), fnd_global.resp_appl_id(), l_fileClob );
5111   IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
5112     FND_LOG.string(FND_LOG.LEVEL_STATEMENT,g_log_head || l_api_name , 'After getting the fileClob');
5113   END IF;
5114 END IF; */
5115 
5116     PO_XML_UTILS_GRP.getTandC(p_document_id, p_document_type, l_fileClob); --Bug 6692126
5117     if (FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL) then
5118       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name , 'After getting the fileClob');
5119     end if;
5120 
5121 -- <Start Word Integration 11.5.10+>
5122     l_okc_doc_type := PO_CONTERMS_UTL_GRP.get_po_contract_doctype(p_document_subtype);
5123 
5124     IF (('STRUCTURED' =
5125          OKC_TERMS_UTIL_GRP.get_contract_source_code(p_document_id => p_document_id
5126                                                      , p_document_type => l_okc_doc_type))
5127         OR
5128         ('Y' =
5129          OKC_TERMS_UTIL_GRP.is_primary_terms_doc_mergeable(p_document_id => p_document_id
5130                                                            , p_document_type => l_okc_doc_type))
5131         )
5132       THEN
5133 
5134   -- contract terms are structured and/or mergeable
5135   -- so, show old cover page message (with no mention to look elsewhere for terms)
5136 
5137   /*Get the messages in covering page by replacing the tokens with correponding value.*/
5138       FND_MESSAGE.SET_NAME('PO', 'PO_FO_COVERING_MESSAGE');
5139       FND_MESSAGE.SET_TOKEN('BUYER_ORG', po_communication_pvt.g_buyer_org);
5140       FND_MESSAGE.SET_TOKEN('SUPP_ORG', l_supp_org);
5141       PO_COMMUNICATION_PVT.g_cover_message := FND_MESSAGE.GET;
5142 
5143 
5144       FND_MESSAGE.SET_NAME('PO', 'PO_FO_AMENDMENT_MESSAGE');
5145       FND_MESSAGE.SET_TOKEN('PO_NUM', l_po_number);
5146       FND_MESSAGE.SET_TOKEN('CHANGE_SUMMARY', l_change_summary);
5147       PO_COMMUNICATION_PVT.g_amendment_message := FND_MESSAGE.GET;
5148 
5149       g_is_contract_attached_doc := 'N'; -- bug4026592
5150 
5151     ELSIF (- 1 <> OKC_TERMS_UTIL_GRP.get_primary_terms_doc_file_id(p_document_id => p_document_id
5152                                                                    , p_document_type => l_okc_doc_type))
5153       THEN
5154 
5155   -- Primary document exists, but is not mergeable
5156 
5157   /*Get the messages in covering page by replacing the tokens with correponding value.*/
5158       FND_MESSAGE.SET_NAME('PO', 'PO_FO_COVER_MSG_NOT_MERGED');
5159       FND_MESSAGE.SET_TOKEN('BUYER_ORG', po_communication_pvt.g_buyer_org);
5160       FND_MESSAGE.SET_TOKEN('SUPP_ORG', l_supp_org);
5161       PO_COMMUNICATION_PVT.g_cover_message := FND_MESSAGE.GET;
5162 
5163 
5164       FND_MESSAGE.SET_NAME('PO', 'PO_FO_AMEND_MSG_NOT_MERGED');
5165       FND_MESSAGE.SET_TOKEN('PO_NUM', l_po_number);
5166       FND_MESSAGE.SET_TOKEN('CHANGE_SUMMARY', l_change_summary);
5167       PO_COMMUNICATION_PVT.g_amendment_message := FND_MESSAGE.GET;
5168 
5169       g_is_contract_attached_doc := 'Y'; -- bug4026592
5170 
5171     ELSE
5172 
5173   -- Primary attached document does not exist!
5174   -- Bug 4014230: Get buyer and supplier org tokens
5175 
5176       FND_MESSAGE.SET_NAME('PO', 'PO_FO_MSG_TERMS_DOC_MISSING');
5177       FND_MESSAGE.SET_TOKEN('BUYER_ORG', po_communication_pvt.g_buyer_org);
5178       FND_MESSAGE.SET_TOKEN('SUPP_ORG', l_supp_org);
5179       PO_COMMUNICATION_PVT.g_cover_message := FND_MESSAGE.GET;
5180 
5181       FND_MESSAGE.SET_NAME('PO', 'PO_FO_MSG_TERMS_DOC_MISSING');
5182       FND_MESSAGE.SET_TOKEN('BUYER_ORG', po_communication_pvt.g_buyer_org);
5183       FND_MESSAGE.SET_TOKEN('SUPP_ORG', l_supp_org);
5184       PO_COMMUNICATION_PVT.g_amendment_message := FND_MESSAGE.GET;
5185 
5186       g_is_contract_attached_doc := 'Y'; -- bug4026592
5187 
5188     END IF;
5189 -- <End Word Integration 11.5.10+>
5190 
5191 --Bug 6692126 Get the profile value based on prepares context
5192 --Bug 6692126 IF fnd_profile.value('ENABLE_TIMEZONE_CONVERSIONS')='Y' THEN
5193 
5194     IF get_preparer_profile(p_document_id, p_document_type, 'ENABLE_TIMEZONE_CONVERSIONS') = 'Y' THEN --Bug 6692126
5195       BEGIN
5196      --Bug 6692126 Get the profile value based on prepares context
5197      --Bug 6692126 SELECT fnd_profile.value('SERVER_TIMEZONE_ID') into l_timezone_id from dual;
5198         l_timezone_id := get_preparer_profile(p_document_id, p_document_type, 'SERVER_TIMEZONE_ID'); --Bug 6692126
5199         SELECT name, gmt_deviation_hours into l_timezone, l_offset from HZ_TIMEZONES_VL where timezone_id = to_number(l_timezone_id);
5200       EXCEPTION
5201         WHEN OTHERS THEN
5202           IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
5203             FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ||'Timezone: ','Inside Timezone Exception Handler');
5204           END IF;
5205           RAISE;
5206       END;
5207       FND_MESSAGE.SET_NAME('PO', 'PO_FO_TIMEZONE');
5208       FND_MESSAGE.SET_TOKEN('TIME_OFFSET', l_offset);
5209       FND_MESSAGE.SET_TOKEN('TIMEZONE_NAME', l_timezone);
5210       PO_COMMUNICATION_PVT.g_timezone := FND_MESSAGE.GET;
5211     END IF;
5212 
5213     PO_COMMUNICATION_PVT.g_vendor_id := l_vendor_id;
5214 
5215 /*bug#3630737.
5216 Retrieve PO_FO_DOCUMENT_NAME from fnd_new_messages by passing
5217 DocumentType, po number and revision number as tokens*/
5218     FND_MESSAGE.SET_NAME('PO', 'PO_FO_DOCUMENT_NAME');
5219     FND_MESSAGE.SET_TOKEN('DOCUMENT_TYPE', PO_COMMUNICATION_PVT.g_documentType);
5220     FND_MESSAGE.SET_TOKEN('PO_NUMBER', l_po_number);
5221     FND_MESSAGE.SET_TOKEN('REVISION_NUMBER', PO_COMMUNICATION_PVT.g_revision_num);
5222     PO_COMMUNICATION_PVT.g_documentName := FND_MESSAGE.GET;
5223 
5224 -- SQl What:  Querying for header short attachments
5225 -- SQL why: To display note to supplier data in header part of pdf document.
5226 -- SQL Join:  vendor_id and header_id
5227 
5228 --bug#3760632 replaced the function PO_POXPOEPO
5229 --with PO_PRINTPO
5230 
5231 --bug#3768142 added the condtion if p_document_type='RELEASE'
5232 --so that the attachments for Releases are also displayed
5233 --correctly. An order by is used so that first the
5234 --PO_HEADERS(BPA) attachments are printed followed by PO_RELEASES
5235 --attachments and then finally PO_VENDORS. This is necessary
5236 --only for the Releases because you can display the BPA header
5237 --attachments also with a release.
5238 
5239     if(p_document_type = 'RELEASE')then
5240 --Bug#4683170
5241 --Appended fad.datatype_id=1 condition for retrieving the
5242 --short_text attachment for the current document only.
5243 --bug6133951 added seq_num in order_by clause.
5244       l_head_short_attachment_query := 'CURSOR( SELECT fds.short_text
5245          FROM
5246           fnd_attached_docs_form_vl fad,
5247           fnd_documents_short_text fds
5248          WHERE  ((entity_name=''PO_HEADERS'' AND
5249             pk1_value=to_char(phx.po_header_id))OR
5250           (entity_name = ''PO_RELEASES'' AND
5251           pk1_value = to_char(phx.po_release_id)) OR
5252           (entity_name = ''PO_VENDORS'' AND
5253                 pk1_value = to_char(phx.vendor_id))  OR
5254                                         (entity_name = ''PO_VENDOR_SITES'' AND
5255                                         pk1_value = to_char(phx.vendor_site_id))) AND  -- bug6154354
5256                 function_name = ''PO_PRINTPO''
5257                 AND fad.media_id = fds.media_id
5258           AND fad.datatype_id=1
5259           order by entity_name, seq_num) AS header_short_text'; --bug6133951
5260     --<PO Attachment Support 11i.11 Start>
5261       l_head_url_attachment_query := 'CURSOR(
5262         SELECT fad.url web_page --Bug#4958642
5263         FROM fnd_attached_docs_form_vl fad
5264         WHERE ((fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(phx.po_header_id)) OR
5265                (fad.entity_name=''PO_RELEASES'' AND fad.pk1_value=to_char(phx.po_release_id)) OR
5266                (fad.entity_name=''PO_VENDORS'' AND fad.pk1_value=to_char(phx.vendor_id)) OR
5267                (fad.entity_name=''PO_VENDOR_SITES'' AND fad.pk1_value=to_char(phx.vendor_site_id)) --bug6154354
5268               )
5269         AND fad.datatype_id=5
5270         AND fad.function_name=''PO_PRINTPO''
5271         order by fad.entity_name,fad.seq_num) AS header_url_attachments'; --bug6133951
5272 
5273       l_head_file_attachment_query := 'CURSOR(
5274         SELECT fad.file_name
5275         FROM fnd_attached_docs_form_vl fad
5276         WHERE ((fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(phx.po_header_id)) OR
5277                (fad.entity_name=''PO_RELEASES'' AND fad.pk1_value=to_char(phx.po_release_id)) OR
5278                (fad.entity_name=''PO_VENDORS'' AND fad.pk1_value=to_char(phx.vendor_id)) OR
5279                (fad.entity_name=''PO_VENDOR_SITES'' AND fad.pk1_value=to_char(phx.vendor_site_id))  --bug6154354
5280               )
5281         AND fad.datatype_id=6
5282         AND fad.function_name=''PO_PRINTPO''
5283         order by fad.entity_name,fad.seq_num) AS header_file_attachments'; --bug6133951
5284     --<PO Attachment Support 11i.11 End>
5285 
5286     else
5287 --Bug#4683170
5288 --Appended fad.datatype_id=1 condition for retrieving the
5289 --short_text attachment for the current document only.
5290 --bug6133951 added seq_num in order_by clause.
5291       l_head_short_attachment_query := 'CURSOR( SELECT fds.short_text
5292           FROM
5293           fnd_attached_docs_form_vl fad,
5294           fnd_documents_short_text fds
5295          WHERE  ((entity_name = ''PO_HEADERS'' AND
5296           pk1_value = to_char(phx.po_header_id)) OR
5297           (entity_name = ''PO_VENDORS'' AND
5298                 pk1_value = to_char(phx.vendor_id))  OR
5299                                         (entity_name = ''PO_VENDOR_SITES'' AND
5300                                         pk1_value = to_char(phx.vendor_site_id))) AND  -- bug6154354
5301                 function_name = ''PO_PRINTPO''
5302                 AND fad.media_id = fds.media_id
5303           AND fad.datatype_id=1 order by fad.seq_num) AS header_short_text'; --bug6133951
5304 
5305     --<PO Attachment Support 11i.11 Start>
5306       l_head_url_attachment_query := 'CURSOR(
5307         SELECT fad.url web_page --Bug#4958642
5308         FROM fnd_attached_docs_form_vl fad
5309         WHERE ((fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(phx.po_header_id)) OR
5310                (fad.entity_name=''PO_VENDORS'' AND fad.pk1_value=to_char(phx.vendor_id)) OR
5311                (fad.entity_name=''PO_VENDOR_SITES'' AND fad.pk1_value=to_char(phx.vendor_site_id))  --bug6154354
5312               )
5313         AND fad.datatype_id=5
5314         AND fad.function_name=''PO_PRINTPO''
5315         order by fad.entity_name,fad.seq_num) AS header_url_attachments'; --bug6133951
5316 
5317       l_head_file_attachment_query := 'CURSOR(
5318         SELECT fad.file_name
5319         FROM fnd_attached_docs_form_vl fad
5320         WHERE ((fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(phx.po_header_id)) OR
5321                (fad.entity_name=''PO_VENDORS'' AND fad.pk1_value=to_char(phx.vendor_id)) OR
5322                (fad.entity_name=''PO_VENDOR_SITES'' AND fad.pk1_value=to_char(phx.vendor_site_id))  --bug6154354
5323               )
5324         AND fad.datatype_id=6
5325         AND fad.function_name=''PO_PRINTPO''
5326         order by fad.entity_name,fad.seq_num) AS header_file_attachments'; --bug6133951
5327     --<PO Attachment Support 11i.11 End>
5328 
5329     end if;
5330 --bug3768142 end
5331 
5332 -- SQl What:  Querying for line short attachments
5333 -- SQL why: To display note to supplier data at line level in pdf document.
5334 -- SQL Join:  vendor_id and header_id
5335 
5336 
5337 --bug#3760632 replaced the function PO_POXPOEPO
5338 --with PO_PRINTPO
5339   --Bug#4683170
5340   --Appended fad.datatype_id=1 condition for retrieving the
5341   --short_text attachment for the current document only.
5342   --Bug 4673653 - Added condition to show item level short text attachments
5343 
5344 /*Bug7426541 -  Added the clauses to select the attachments from BLANKET 'S header and lines
5345   and CONTRACT 'S header- if there is a source document.
5346   Entity types :-  source doc's header -> 'PO_HEADERS' source doc's line -> 'PO_IN_GA_LINES'*/
5347 
5348     l_line_short_attachment_query := ' CURSOR( SELECT plx.po_line_id , fds.short_text
5349    FROM
5350     fnd_attached_docs_form_vl fad,
5351     fnd_documents_short_text fds
5352    WHERE ((fad.entity_name=''PO_LINES'' AND fad.pk1_value=to_char(plx.po_line_id))
5353            OR
5354            (fad.entity_name=''MTL_SYSTEM_ITEMS'' AND
5355             fad.pk1_value=to_char(PO_COMMUNICATION_PVT.getInventoryOrgId()) AND --Bug6139548
5356             fad.pk2_value=to_char(plx.item_id) AND plx.item_id is not null)
5357              OR
5358              (fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(plx.from_header_id)
5359                AND plx.from_header_id IS NOT NULL)
5360              OR
5361              (fad.entity_name=''PO_IN_GA_LINES'' AND fad.pk1_value=to_char(plx.from_line_id)
5362                AND plx.from_line_id IS NOT NULL)
5363              OR
5364              (fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(plx.CONTRACT_ID)
5365                AND plx.CONTRACT_ID IS NOT NULL)
5366          ) AND
5367          function_name = ''PO_PRINTPO''
5368          AND fad.media_id = fds.media_id
5369            AND fad.datatype_id=1 order by fad.seq_num) AS line_short_text'; --bug6133951
5370 
5371     --<PO Attachment Support 11i.11 Start>
5372     --Bug 4673653 - Use inventory org id instead of Org Id to get the item attachments
5373 
5374 /*Bug7426541 -  Added the clauses to select the attachments from BLANKET 'S header and lines
5375   and CONTRACT 'S header- if there is a source document.
5376   Entity types :-  source doc's header -> 'PO_HEADERS' source doc's line -> 'PO_IN_GA_LINES'*/
5377 
5378     l_line_url_attachment_query := 'CURSOR(
5379         SELECT fad.url web_page --Bug#4958642
5380         FROM fnd_attached_docs_form_vl fad
5381         WHERE ((fad.entity_name=''PO_LINES'' AND fad.pk1_value=to_char(plx.po_line_id))
5382                OR
5383                (fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(plx.from_header_id)
5384                 AND plx.from_header_id IS NOT NULL)
5385                OR
5386                (fad.entity_name=''PO_IN_GA_LINES'' AND fad.pk1_value=to_char(plx.from_line_id)
5387                 AND plx.from_line_id IS NOT NULL)
5388                OR
5389                (fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(plx.contract_id)
5390                 AND plx.contract_id IS NOT NULL)
5391                OR
5392                (fad.entity_name=''MTL_SYSTEM_ITEMS'' AND
5393                 fad.pk1_value=to_char(PO_COMMUNICATION_PVT.getInventoryOrgId()) AND
5394                 fad.pk2_value=to_char(plx.item_id) AND plx.item_id is not null)
5395               )
5396         AND fad.datatype_id=5
5397         AND fad.function_name=''PO_PRINTPO'' order by fad.seq_num) AS line_url_attachments'; --bug6133951
5398 
5399     --Bug 4673653 - Use inventory org id instead of Org Id to get the item attachments
5400 
5401     /*Bug7426541 -  Added the clauses to select the attachments from BLANKET 'S header and lines
5402   and CONTRACT 'S header- if there is a source document.
5403   Entity types :-  source doc's header -> 'PO_HEADERS' source doc's line -> 'PO_IN_GA_LINES'*/
5404 
5405     l_line_file_attachment_query := 'CURSOR(
5406         SELECT fad.file_name
5407         FROM fnd_attached_docs_form_vl fad
5408         WHERE ((fad.entity_name=''PO_LINES'' AND fad.pk1_value=to_char(plx.po_line_id))
5409                OR
5410                (fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(plx.from_header_id)
5411                 AND plx.from_header_id IS NOT NULL)
5412                OR
5413                (fad.entity_name=''PO_IN_GA_LINES'' AND fad.pk1_value=to_char(plx.from_line_id)
5414                 AND plx.from_line_id IS NOT NULL)
5415                OR
5416                (fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(plx.contract_id)
5417                 AND plx.contract_id IS NOT NULL)
5418                OR
5419                (fad.entity_name=''MTL_SYSTEM_ITEMS'' AND
5420                 fad.pk1_value=to_char(PO_COMMUNICATION_PVT.getInventoryOrgId()) AND
5421                 fad.pk2_value=to_char(plx.item_id) AND plx.item_id is not null)
5422               )
5423         AND fad.datatype_id=6
5424         AND fad.function_name=''PO_PRINTPO''
5425         order by fad.seq_num) AS line_file_attachments'; --bug6133951
5426     --<PO Attachment Support 11i.11 End>
5427 
5428 -- SQl What:  Querying for shipment short attachments
5429 -- SQL why: To display note to supplier data at shipmentlevel in pdf document.
5430 -- SQL Join:  vendor_id and header_id
5431 
5432 --bug#3760632 replaced the function PO_POXPOEPO
5433 --with PO_PRINTPO
5434 --Bug#4683170
5435   --Appended fad.datatype_id=1 condition for retrieving the
5436         --short_text attachment for the current document only
5437     l_shipment_short_attach_query := 'CURSOR( SELECT pllx.line_location_id, fds.short_text
5438    FROM
5439     fnd_attached_docs_form_vl fad,
5440     fnd_documents_short_text fds
5441    WHERE entity_name = ''PO_SHIPMENTS'' AND
5442      pk1_value = to_char(pllx.line_location_id) AND
5443          function_name = ''PO_PRINTPO''
5444          AND fad.media_id = fds.media_id
5445            AND fad.datatype_id=1
5446                order by fad.seq_num) AS line_loc_short_text'; --bug6133951
5447 
5448 --<PO Attachment Support 11i.11 Start>
5449     l_shipment_url_attach_query := 'CURSOR(
5450         SELECT fad.url web_page --Bug#4958642
5451         FROM fnd_attached_docs_form_vl fad
5452         WHERE fad.entity_name=''PO_SHIPMENTS''
5453         AND fad.pk1_value=to_char(pllx.line_location_id)
5454         AND fad.datatype_id=5
5455         AND fad.function_name=''PO_PRINTPO''
5456         order by fad.seq_num ) AS line_loc_url_attachments'; --bug6133951
5457 
5458     l_shipment_file_attach_query := 'CURSOR(
5459         SELECT fad.file_name
5460         FROM fnd_attached_docs_form_vl fad
5461         WHERE fad.entity_name=''PO_SHIPMENTS''
5462         AND fad.pk1_value=to_char(pllx.line_location_id)
5463         AND fad.datatype_id=6
5464         AND fad.function_name=''PO_PRINTPO''
5465         order by fad.seq_num) AS line_loc_file_attachments'; --bug6133951
5466 --<PO Attachment Support 11i.11 End>
5467 
5468 	 /*Bug 10388305 Added l_tax_name_query to get tax names*/
5469      --<Bug 16369996>: added RELEASE when comparing with zl.event_class_code
5470      --retrieved additional columns: TAX_LINE_ID,TAX_STATUS_CODE,TAX_JURISDICTION_CODE,TAXABLE_AMT,TAX_TYPE_CODE
5471      --<Bug 14526396 Start>
5472         l_tax_name_query:= 'CURSOR(SELECT zl.tax_rate_id tax_code_id, zl.tax_rate_code tax_name
5473                            , zl.TAX_RATE
5474                            , zl.TAX_RATE_TYPE
5475                            , zl.ENTITY_CODE
5476                            , zl.EVENT_CLASS_CODE
5477                            , zl.TRX_ID
5478                            , zl.APPLICATION_ID
5479                            , zl.TRX_LEVEL_TYPE
5480                            , zl.TRX_LINE_ID
5481                            , zl.TRX_NUMBER
5482                            , zl.TRX_LINE_NUMBER
5483                            , zl.TAX_LINE_NUMBER
5484                            , zl.TAX_REGIME_CODE
5485                            , zl.TAX
5486                            , zl.TAX_APPORTIONMENT_LINE_NUMBER
5487                            , zl.UNIT_PRICE
5488                            , zl.LINE_AMT
5489                            , zl.TRX_LINE_QUANTITY
5490                            , zl.UNROUNDED_TAXABLE_AMT
5491                            , zl.UNROUNDED_TAX_AMT
5492                            , zl.TAX_CURRENCY_CODE
5493                            , zl.TAX_AMT
5494                            , zl.TAX_AMT_TAX_CURR
5495                            , zl.TAX_AMT_FUNCL_CURR
5496                            , zl.TAXABLE_AMT_TAX_CURR
5497                            , zl.TAXABLE_AMT_FUNCL_CURR
5498                            , zl.TAX_LINE_ID
5499                            , zl.TAX_STATUS_CODE
5500                            , zl.TAX_JURISDICTION_CODE
5501                            , zl.TAXABLE_AMT
5502                            , zl.TAX_TYPE_CODE
5503                            FROM zx_lines zl
5504                            WHERE zl.application_id = 201
5505                            AND zl.entity_code IN (''PURCHASE_ORDER'',''RELEASE'')
5506                            AND zl.event_class_code IN (''PO_PA'',''RELEASE'')
5507                            AND zl.trx_id = decode(zl.event_class_code, ''RELEASE'', pllx.po_release_id, pllx.po_header_id)
5508                            AND zl.trx_line_id = pllx.line_location_id
5509                            ) AS tax_names';
5510 --<Bug 14526396 End>
5511 
5512 -- SQl What:  Querying for boiler plate text
5513 -- SQL why: To display boiler plate text in pdf document.
5514 -- SQL Join:
5515 -- Change: Commented some message tokens and added new message tokens as part of new layout changes.
5516 
5517 -- Bug#3823799: removed the inline comments and placed here, other wise XML generation failing using dbms_xmlquery.
5518 --Bug 3670603: Added "PO_WF_NOTIF_PROMISED_DATE" message name
5519 --Bug3670603: Added "PO_WF_NOTIF_NEEDBY_DATE" message name
5520 --Bug3836856: Addded "PO_FO_PAGE"for retrieving the page number message
5521 
5522     l_xml_message_query :='CURSOR (SELECT message_name message, message_text text FROM fnd_new_messages WHERE message_name in (
5523 ''PO_WF_NOTIF_REVISION'',
5524 ''PO_WF_NOTIF_VENDOR_NO'',
5525 ''PO_WF_NOTIF_PAYMENT_TERMS'',
5526 ''PO_WF_NOTIF_FREIGHT_TERMS'',
5527 ''PO_WF_NOTIF_FOB'',
5528 ''PO_WF_NOTIF_SHIP_VIA'',
5529 ''PO_WF_NOTIF_CONFIRM_TO_TELE'',
5530 ''PO_WF_NOTIF_REQUESTER_DELIVER'',
5531 ''PO_WF_NOTIF_DESCRIPTION'',
5532 ''PO_WF_NOTIF_TAX'',
5533 ''PO_WF_NOTIF_UOM'',
5534 ''PO_WF_NOTIF_UNIT_PRICE'',
5535 ''PO_WF_NOTIF_QUANTITY'',
5536 ''PO_WF_NOTIF_PURCHASE_ORDER'',
5537 ''PO_WF_NOTIF_BUYER'',
5538 ''PO_WF_NOTIF_AMOUNT'',
5539 ''PO_WF_NOTIF_EFFECTIVE_DATE'',
5540 ''PO_WF_NOTIF_HEADER_NOTE'',
5541 ''PO_WF_NOTIF_LINE_NUMBER'',
5542 ''PO_WF_NOTIF_LINE_PAYITEM_NUM'',  -- <Complex Work R12>
5543 ''PO_WF_NOTIF_MULTIPLE'',
5544 ''PO_WF_NOTIF_PART_NO_DESC'',
5545 ''PO_WF_NOTIF_SUPPLIER_ITEM'',
5546 ''PO_WF_NOTIF_TOTAL'',
5547 ''PO_WF_NOTIF_NOTE'',
5548 ''PO_FO_PACKING_INSTRUCTION'',
5549 ''PO_FO_CUST_PO_NUMBER'',
5550 ''PO_FO_CUST_ITEM_DESC'',
5551 ''PO_FO_LINE_NUMBER'',
5552 ''PO_FO_SHIP_NUMBER'',
5553 ''PO_FO_AMOUNT_BASED'',
5554 ''PO_FO_CONTRACTOR_NAME'',
5555 ''PO_FO_START_DATE'',
5556 ''PO_FO_END_DATE'',
5557 ''PO_FO_WORK_SCHEDULE'',
5558 ''PO_FO_SHIFT_PATTERN'',
5559 ''PO_FO_PRICE_DIFFERENTIALS'',
5560 ''PO_FO_DELIVER_TO_LOCATION'',
5561 ''PO_FO_EFFECTIVE_START_DATE'',
5562 ''PO_FO_AMOUNT_AGREED'',
5563 ''PO_FO_ADVANCE'',                  -- <Complex Work R12>
5564 ''PO_FO_RETAINAGE_RATE'',           -- <Complex Work R12>
5565 ''PO_FO_MAX_RETAINAGE_AMOUNT'',     -- <Complex Work R12>
5566 ''PO_FO_PROGRESS_PAYMENT_RATE'',    -- <Complex Work R12>
5567 ''PO_FO_RECOUPMENT_RATE'',          -- <Complex Work R12>
5568 ''PO_FO_PRICE_BREAK'',
5569 ''PO_FO_CHARGE_ACCOUNT'',
5570 ''PO_FO_CONTRACTOR'',
5571 ''PO_FO_CONTACT_NAME'',
5572 ''PO_FO_TELEPHONE'',
5573 ''PO_FO_FAX'',
5574 ''PO_FO_NAME'',
5575 ''PO_FO_TITLE'',
5576 ''PO_FO_DATE'',
5577 ''PO_FO_REVISION'',
5578 ''PO_FO_AMENDMENT'',
5579 ''PO_FO_SHIP_METHOD'',
5580 ''PO_FO_SHIPPING_INSTRUCTION'',
5581 ''PO_FO_DRAFT'',
5582 ''PO_FO_PROPRIETARY_INFORMATION'',
5583 ''PO_FO_TRANSPORTAION_ARRANGED'',
5584 ''PO_FO_DELIVER_TO_LOCATION'',
5585 ''PO_FO_NO'',
5586 ''PO_FO_COMPANY'',
5587 ''PO_FO_SUBMIT_RESPONSE'',
5588 ''PO_FO_EMAIL'',
5589 ''PO_WF_NOTIF_EXPIRES_ON'',
5590 ''PO_FO_TEST'',
5591 ''PO_FO_ORG_AGR_ASS'',
5592 ''PO_FO_EFFECTIVE_END_DATE'',
5593 ''PO_FO_PURCHASING_ORGANIZATION'',
5594 ''PO_FO_PURCHASING_SUPPLIER_SITE'',
5595 ''PO_FO_TRANSPORTATION_ARRANGED'',
5596 ''PO_WF_NOTIF_ADDRESS'',
5597 ''PO_WF_NOTIF_ORDER'',
5598 ''PO_WF_NOTIF_ORDER_DATE'',
5599 ''PO_FO_VENDOR'',
5600 ''PO_FO_SHIP_TO'',
5601 ''PO_FO_BILL_TO'',
5602 ''PO_FO_CONFIRM_NOT_DUPLICATE'',
5603 ''PO_FO_AGREEMENT_CANCELED'',
5604 ''PO_FO_FORMAL_ACCEPT'',
5605 ''PO_FO_TYPE'',
5606 ''PO_FO_REVISION_DATE'',
5607 ''PO_FO_REVISED_BY'',
5608 ''PO_FO_PRICES_EXPRESSED'',
5609 ''PO_FO_NOTES'',
5610 ''PO_WF_NOTIF_PREPARER'',
5611 ''PO_FO_SUPPLIER_CONFIGURATION'',
5612 ''PO_FO_DELIVER_DATE_TIME'',
5613 ''PO_FO_LINE_REF_BPA'',
5614 ''PO_FO_LINE_REF_CONTRACT'',
5615 ''PO_FO_LINE_SUPPLIER_QUOTATION'',
5616 ''PO_FO_USE_SHIP_ADDRESS_TOP'',
5617 ''PO_FO_LINE_CANCELED'',
5618 ''PO_FO_ORIGINAL_QTY_ORDERED'',
5619 ''PO_FO_QUANTITY_CANCELED'',
5620 ''PO_FO_SHIPMENT_CANCELED'',
5621 ''PO_FO_ORIGINAL_SHIPMENT_QTY'',
5622 ''PO_FO_CUSTOMER_ACCOUNT_NO'',
5623 ''PO_FO_RELEASE_CANCELED'',
5624 ''PO_FO_PO_CANCELED'',
5625 ''PO_FO_TOTAL'',
5626 ''PO_FO_SUPPLIER_ITEM'',
5627 ''PO_FO_ORIGINAL_AMOUNT_ORDERED'',
5628 ''PO_FO_AMOUNT_CANCELED'',
5629 ''PO_FO_UN_NUMBER'',
5630 ''PO_WF_NOTIF_PROMISED_DATE'',
5631 ''PO_WF_NOTIF_NEEDBY_DATE'',
5632 ''PO_FO_HAZARD_CLASS'',
5633 ''PO_FO_PAGE'',
5634 ''PO_FO_REFERENCE_DOCUMENTS'',
5635 ''PO_FO_PAYITEM_CANCELED'', --<Bug#: 4899200>
5636 ''PO_FO_ORIGINAL_PAYITEM_QTY'', --<Bug#: 4899200>
5637 ''PO_FO_PAYITEM_QTY_CANCELED'', --<Bug#: 4899200>
5638 ''PO_FO_ORIGINAL_PAYITEM_AMT'', --<Bug#: 5464968>
5639 ''PO_FO_MODIFIER_TYPE'', --Enhanced Pricing
5640 ''PO_FO_BLANKET'', --Enhanced Pricing
5641 ''PO_FO_BLANKET_PRICE_STRUCT'', --Enhanced Pricing
5642 ''PO_FO_MODIFIER_DESC'', --Enhanced Pricing
5643 ''PO_FO_RATE'', --Enhanced Pricing
5644 ''PO_FO_ADJUSTED_AMT'', --Enhanced Pricing
5645 ''PO_FO_RATE_APP_METHOD'', --Enhanced Pricing
5646 ''PO_FO_LIST_LINE_PRICE'', --Enhanced Pricing
5647 ''PO_FO_PAYITEM_AMT_CANCELED'', --<Bug#: 5464968>
5648 ''PO_FO_USE_SHIP_ADDRESS'' --Bug 9855114
5649 ) AND application_id = 201 AND language_code = '''|| userenv('LANG') ||''') AS message';
5650 
5651 
5652 -- <Complex Work R12 Start>
5653 -- Set complex work global and query strings
5654 
5655     IF (p_document_type = 'PO') THEN
5656 
5657       setIsComplexWorkPO(
5658                          p_document_id => p_document_id
5659                          , p_revision_num => p_revision_num
5660                          , p_which_tables => p_which_tables
5661                          );
5662 
5663     ELSE
5664 
5665       g_is_complex_work_po := 'N';
5666 
5667     END IF;
5668 
5669     IF (g_is_complex_work_po = 'Y') THEN
5670 
5671   -- set up dynamic SQL query strings for complex work
5672 
5673       IF (p_which_tables = 'MAIN') THEN
5674 
5675         l_adv_amount_query :=
5676         'PO_COMPLEX_WORK_PVT.get_advance_amount(plx.po_line_id) advance_amount, ';
5677 
5678         l_complex_lloc_query :=
5679         ', CURSOR(SELECT del.* FROM po_line_locations_xml del'
5680         || ' WHERE del.po_line_id = plx.po_line_id AND del.payment_type = ''DELIVERY'')'
5681         || ' AS line_delivery ';
5682 
5683         l_complex_dist_query :=
5684         ', CURSOR(SELECT adv.* FROM po_distribution_xml adv, po_line_locations_xml pllx2'
5685         || ' WHERE pllx2.po_line_id = plx.po_line_id AND pllx2.payment_type = ''ADVANCE'''
5686         || ' AND adv.line_location_id = pllx2.line_location_id) AS line_advance_distributions,'
5687         || ' CURSOR(SELECT del.*, CURSOR(SELECT deldist.* FROM po_distribution_xml deldist'
5688         || ' WHERE deldist.line_location_id = del.line_location_id) AS distributions'
5689         || ' FROM po_line_locations_xml del WHERE del.po_line_id = plx.po_line_id'
5690         || ' AND del.payment_type = ''DELIVERY'') AS line_delivery ';
5691 
5692 
5693       ELSIF (p_which_tables = 'ARCHIVE') THEN
5694 
5695         l_adv_amount_query :=
5696         'PO_COMPLEX_WORK_PVT.get_advance_amount(plx.po_line_id, pcgt.revision_num,'
5697         || '''ARCHIVE'') advance_amount, ';
5698 
5699 
5700         l_complex_lloc_query :=
5701         ', CURSOR(SELECT del.* FROM po_line_locations_archive_xml del'
5702         || ' WHERE del.po_line_id = plx.po_line_id AND del.payment_type = ''DELIVERY'''
5703         || ' AND del.revision_num = (SELECT  /*+ push_subq no_unnest */ max(dela.revision_num)'
5704         || ' FROM po_line_locations_archive_all dela WHERE del.line_location_id = '
5705         || ' dela.line_location_id AND del.revision_num <= pcgt.revision_number) '
5706         || ' ) AS line_delivery ';
5707 
5708 
5709 
5710         l_complex_dist_query :=
5711         ', CURSOR(SELECT adv.* FROM po_distribution_archive_xml adv,'
5712         || ' po_line_locations_archive_xml pllx2 WHERE pllx2.po_line_id = plx.po_line_id'
5713         || ' AND pllx2.payment_type = ''ADVANCE'' AND adv.line_location_id = pllx2.line_location_id'
5714         || ' AND adv.revision_num = (SELECT max(adva.revision_num)'
5715         || ' FROM po_distributions_archive_all adva WHERE adv.po_distribution_id ='
5716         || ' adv.po_distribution_id AND adva.revision_num <= pcgt.revision_number))'
5717         || ' AS line_advance_distributions, CURSOR(SELECT del.*, CURSOR(SELECT deldist.*'
5718         || ' FROM po_distribution_xml deldist WHERE deldist.line_location_id = del.line_location_id'
5719         || ' AND deldist.revision_num = (SELECT max(deldista.revision_num)'
5720         || ' FROM po_distributions_archive_all deldista WHERE deldist.po_distribution_id ='
5721         || ' deldista.po_distribution_id AND deldista.revision_num <= pcgt.revision_number))'
5722         || ' AS distributions FROM po_line_locations_xml del WHERE del.po_line_id = plx.po_line_id'
5723         || ' AND del.payment_type = ''DELIVERY'' AND del.revision_num = ('
5724         || ' SELECT /*+ push_subq no_unnest */ max(dela.revision_num) FROM po_line_locations_archive_all dela'
5725         || ' WHERE del.line_location_id = dela.line_location_id'
5726         || ' AND del.revision_num <= pcgt.revision_number)) AS line_delivery';
5727 
5728 
5729 
5730       END IF; -- if p_which_tables = ...
5731 
5732     END IF; -- if g_is_complex_work_po
5733 
5734 
5735 
5736 -- <Complex Work R12 End>
5737 
5738 
5739 /*
5740   These are the queries used to get purchasing organization and purchasing supplier details for main
5741   and archive tables.
5742 */
5743     l_agreement_assign_query := ' CURSOR( select rownum, PO_COMMUNICATION_PVT.GETOPERATIONINFO(PGA.PURCHASING_ORG_ID) OU_NAME,
5744       PO_COMMUNICATION_PVT.getVendorAddressLine1(PGA.vendor_site_id) VENDOR_ADDRESS_LINE1,
5745       PO_COMMUNICATION_PVT.getVendorAddressLine2() VENDOR_ADDRESS_LINE2,
5746       PO_COMMUNICATION_PVT.getVendorAddressLine3() VENDOR_ADDRESS_LINE3,
5747       PO_COMMUNICATION_PVT.getVendorCityStateZipInfo() VENDOR_CITY_STATE_ZIP,
5748       PO_COMMUNICATION_PVT.getVendorCountry() VENDOR_COUNTRY
5749       FROM po_ga_org_assignments PGA
5750       WHERE PGA.ENABLED_FLAG = ''Y'' and PGA.PO_HEADER_ID = PHX.PO_HEADER_ID) as organization_details ';
5751 
5752     l_arc_agreement_assign_query := ' CURSOR( select rownum, PO_COMMUNICATION_PVT.GETOPERATIONINFO(PGA.PURCHASING_ORG_ID) OU_NAME,
5753       PO_COMMUNICATION_PVT.getVendorAddressLine1(PGA.vendor_site_id) VENDOR_ADDRESS_LINE1,
5754       PO_COMMUNICATION_PVT.getVendorAddressLine2() VENDOR_ADDRESS_LINE2,
5755       PO_COMMUNICATION_PVT.getVendorAddressLine3() VENDOR_ADDRESS_LINE3,
5756       PO_COMMUNICATION_PVT.getVendorCityStateZipInfo() VENDOR_CITY_STATE_ZIP,
5757       PO_COMMUNICATION_PVT.getVendorCountry() VENDOR_COUNTRY
5758       FROM po_ga_org_assignments_archive PGA
5759       WHERE PGA.ENABLED_FLAG = ''Y'' and PGA.PO_HEADER_ID = PHX.PO_HEADER_ID) as organization_details ';
5760 
5761 -- SQl What:  Query for header, line, locations, line locations, shipments and distribution information based on
5762 --    document and document type
5763 -- SQL why: To get xml which is used to generate the pdf document.
5764 -- SQL Join:
5765 /* Logic for framing the query:-
5766 
5767   1. If the document type is PO or PA then query has to be join with headers else with Releases.
5768 */
5769 
5770 /*Bug#3583910 Added the function getWithTerms() in the below sql strings such
5771 that the generated xml document will have the value */
5772 
5773 -- bug4026592: Added the function call getIsContermsAttachedDoc()
5774 -- to the xml sql strings below
5775 
5776 /*bug#3630737.
5777 Added the function getDocumentName which returns concatinated value of
5778 DocumentType, po number and revision number*/
5779 /*
5780    bug#3823799: Removed the join with pllx.po_line_id = plx.po_line_id as it appears twice.
5781    Removed the join condition of shipment header id with headers header id as there is a condition
5782    with lines.
5783 */
5784 
5785 -- <Complex Work R12>: Modify queries below to include complex work information
5786 
5787     IF(p_document_type in ('PO', 'PA')) THEN
5788       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
5789         FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ||'NON Release:','Entered into Non Release Query Loop');
5790       END IF;
5791 
5792       PO_COMMUNICATION_PVT.g_release_header_id := p_document_id; -- For documents other than Releases join is based on header id for getting the attachments.
5793       IF p_which_tables = 'MAIN' THEN
5794 
5795     --<Enhanced Pricing Start>
5796     --<BUG 8840221 Added order by clause to sort the modifiers according to the bucket# >
5797         l_price_modifier_query1 := 'CURSOR (SELECT pax1.* FROM PO_PRICE_ADJUSTMENTS_XML pax1 '
5798           || 'WHERE pax1.po_header_id = plx.po_header_id AND pax1.po_line_id = plx.po_line_id '
5799           || 'AND pax1.parent_adjustment_id is null order by pax1.pricing_group_sequence) AS PRICE_MODIFIERS';
5800         l_price_modifier_query2 := 'CURSOR (SELECT pax2.* FROM PO_PRICE_ADJUSTMENTS_XML pax2 '
5801           || 'WHERE pax2.po_header_id = plx.from_header_id AND pax2.po_line_id = plx.from_line_id '
5802           || 'AND pax2.parent_adjustment_id is null order by pax2.pricing_group_sequence) AS ADD_PRICE_MODIFIERS';
5803         l_price_modifier_query3 := 'CURSOR (SELECT pha.segment1 ponum FROM po_headers_all pha '
5804           || 'WHERE pha.po_header_id = plx.from_header_id) AS ADD_PRICE_PONUM';
5805     --<Enhanced Pricing End>
5806 
5807         l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getIsComplexWorkPO() is_complex_work_po, PO_COMMUNICATION_PVT.getDocumentType() document_type,
5808     PO_COMMUNICATION_PVT.getCoverMessage() cover_message,PO_COMMUNICATION_PVT.getTimezone() timezone,
5809     PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
5810     PO_COMMUNICATION_PVT.getDocumentName() document_name,
5811     PO_COMMUNICATION_PVT.IsDocumentSigned(PO_COMMUNICATION_PVT.getDocumentId()) Signed,
5812     fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile,
5813     PO_COMMUNICATION_PVT.getWithTerms() With_Terms , PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , '
5814     || l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||'
5815       FROM PO_HEADERS_XML phx WHERE phx.PO_HEADER_ID = PO_COMMUNICATION_PVT.getDocumentId() AND phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
5816 
5817         IF(p_document_subtype <> 'CONTRACTS') THEN -- contracts will have only headers
5818 
5819           SELECT count(*) into l_count FROM po_lines_all WHERE po_header_id = p_document_id;
5820 
5821           IF l_count >0 THEN
5822 
5823         /*
5824           for getting the price differentials FROM po_price_differentials_v
5825           the entity _name is 'PO LINE' except for blanket AND entity_name is 'BLANKET LINE'
5826           for blanket
5827         */
5828           --Bug 5506417: Added order by plx.line_num clause
5829             l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getIsComplexWorkPO() is_complex_work_po, PO_COMMUNICATION_PVT.getDocumentType() document_type, PO_COMMUNICATION_PVT.getCoverMessage() cover_message,
5830               PO_COMMUNICATION_PVT.getTimezone() timezone,PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
5831               PO_COMMUNICATION_PVT.getDistinctShipmentCount() DIST_SHIPMENT_COUNT,
5832               PO_COMMUNICATION_PVT.getDocumentName() document_name,
5833               PO_COMMUNICATION_PVT.IsDocumentSigned(PO_COMMUNICATION_PVT.getDocumentId()) Signed,
5834               fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile,PO_COMMUNICATION_PVT.getWithTerms() With_Terms , PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , '||
5835             l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||',
5836               CURSOR(SELECT plx.*, '|| l_adv_amount_query ||' CURSOR(SELECT  PRICE_TYPE_DSP PRICE_TYPE, MULTIPLIER,MIN_MULTIPLIER, MAX_MULTIPLIER FROM po_price_differentials_v
5837               WHERE entity_type='''|| l_eventType ||''' AND entity_id = plx.po_line_id and enabled_flag=''Y'') AS price_diff,
5838               '|| l_line_short_attachment_query || ',' || l_price_modifier_query1 || ',' || l_price_modifier_query2 || ',' || l_price_modifier_query3
5839               || ',' || l_line_url_attachment_query || ',' || l_line_file_attachment_query ||' FROM po_lines_xml plx
5840               WHERE  plx.po_header_id = phx.po_header_id and not exists
5841               (select ''x'' from po_lines_archive_all  plaa where
5842                 plaa.po_line_id = plx.po_line_id and
5843                       plaa.cancel_flag= ''Y'' and plaa.revision_num< PO_COMMUNICATION_PVT.getRevisionNum() ) order by plx.line_num) AS lines
5844               FROM PO_HEADERS_XML phx WHERE phx.PO_HEADER_ID = PO_COMMUNICATION_PVT.getDocumentId() AND phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
5845 
5846           END IF;
5847 
5848           SELECT count(*) into l_count FROM po_line_locations_all WHERE po_header_id = p_document_id;
5849 
5850           IF l_count >0 THEN
5851 
5852         /*  Bug#3574748: Added the condition SHIPMENT_TYPE in ('BLANKET','STANDARD') in shipment query. */
5853         --Bug 5506417: Added order by pllx.shipment_num and order by plx.line_num clauses
5854             l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getIsComplexWorkPO() is_complex_work_po, PO_COMMUNICATION_PVT.getDocumentType() document_type, PO_COMMUNICATION_PVT.getCoverMessage() cover_message,
5855             PO_COMMUNICATION_PVT.getTimezone() timezone,PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
5856             PO_COMMUNICATION_PVT.getDistinctShipmentCount() DIST_SHIPMENT_COUNT,
5857             PO_COMMUNICATION_PVT.getDocumentName() document_name,
5858             PO_COMMUNICATION_PVT.IsDocumentSigned( PO_COMMUNICATION_PVT.getDocumentId()) Signed,
5859             fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile, PO_COMMUNICATION_PVT.getWithTerms() With_Terms  , '||
5860             ' PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , ' || l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||',
5861             CURSOR(SELECT plx.*, '|| l_adv_amount_query ||' CURSOR(SELECT  PRICE_TYPE_DSP PRICE_TYPE, MULTIPLIER, MIN_MULTIPLIER,MAX_MULTIPLIER FROM po_price_differentials_v
5862               WHERE entity_type='''|| l_eventType ||''' AND entity_id = plx.po_line_id and enabled_flag=''Y'') AS price_diff,
5863               '|| l_line_short_attachment_query || ',' || l_price_modifier_query1 || ',' || l_price_modifier_query2 || ',' || l_price_modifier_query3 || ',' || l_line_url_attachment_query || ',' || l_line_file_attachment_query ||',
5864             CURSOR(SELECT pllx.*,';
5865             IF (p_document_subtype <> 'STANDARD') THEN
5866               l_xml_query := l_xml_query ||'CURSOR(SELECT PRICE_TYPE_DSP PRICE_TYPE, MIN_MULTIPLIER,  MAX_MULTIPLIER FROM po_price_differentials_v
5867               WHERE entity_type=''PRICE BREAK'' AND entity_id = pllx.line_location_id and enabled_flag=''Y'') AS price_break,';
5868             END IF;
5869              /*Bug 10388305 Added l_tax_name_query to get tax names*/
5870             l_xml_query := l_xml_query || l_tax_name_query || ',' || l_shipment_short_attach_query || ',' || l_shipment_url_attach_query || ',' || l_shipment_file_attach_query ||'
5871             FROM po_line_locations_xml pllx WHERE pllx.po_line_id = plx.po_line_id and SHIPMENT_TYPE in (''BLANKET'',''STANDARD'',''PREPAYMENT'') AND NVL(pllx.payment_type,''NONE'') NOT IN (''ADVANCE'',''DELIVERY'') and not exists
5872             (select ''x'' from po_line_locations_archive_all pllaa where pllaa.line_location_id = pllx.line_location_id
5873             and pllaa.cancel_flag=''Y'' and pllaa.revision_num < PO_COMMUNICATION_PVT.getRevisionNum()) order by pllx.shipment_num ) AS line_locations' || l_complex_lloc_query || '
5874             FROM po_lines_xml plx
5875             WHERE  plx.po_header_id = phx.po_header_id and not exists
5876               (select ''x'' from po_lines_archive_all  plaa where
5877                 plaa.po_line_id = plx.po_line_id and
5878                       plaa.cancel_flag= ''Y'' and plaa.revision_num< PO_COMMUNICATION_PVT.getRevisionNum() ) order by plx.line_num) AS lines
5879             FROM PO_HEADERS_XML phx WHERE phx.PO_HEADER_ID = PO_COMMUNICATION_PVT.getDocumentId() AND phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
5880           END IF;
5881 
5882           IF(p_document_subtype <> 'BLANKET') THEN -- blankets will not have distributions
5883             SELECT count(*) into l_count FROM po_distributions_all WHERE po_header_id = p_document_id;
5884 
5885             IF l_count >0 THEN
5886           --Bug 5506417 :Added order by pllx.shipment_num and order by plx.line_num clauses
5887            /*Bug 10388305 Added l_tax_name_query to get tax names*/
5888               l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getIsComplexWorkPO() is_complex_work_po, PO_COMMUNICATION_PVT.getDocumentType() document_type, PO_COMMUNICATION_PVT.getCoverMessage() cover_message,
5889               PO_COMMUNICATION_PVT.getTimezone() timezone,PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
5890               PO_COMMUNICATION_PVT.getDistinctShipmentCount() DIST_SHIPMENT_COUNT,
5891               PO_COMMUNICATION_PVT.getDocumentName() document_name,
5892               PO_COMMUNICATION_PVT.IsDocumentSigned(PO_COMMUNICATION_PVT.getDocumentId()) Signed,
5893               fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile,PO_COMMUNICATION_PVT.getWithTerms() With_Terms  , '||
5894               ' PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , ' || l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||',
5895               CURSOR(SELECT plx.*, '|| l_adv_amount_query ||' CURSOR(SELECT  PRICE_TYPE_DSP PRICE_TYPE, MULTIPLIER FROM po_price_differentials_v
5896               WHERE entity_type=''PO LINE'' AND entity_id = plx.po_line_id and enabled_flag=''Y'') AS price_diff,
5897               '|| l_line_short_attachment_query || ',' || l_price_modifier_query1 || ',' || l_price_modifier_query2 || ',' || l_price_modifier_query3 || ',' || l_line_url_attachment_query || ',' || l_line_file_attachment_query ||',
5898               CURSOR(SELECT pllx.*, ' || l_tax_name_query || ',' || l_shipment_short_attach_query || ',' || l_shipment_url_attach_query || ',' || l_shipment_file_attach_query ||',
5899               CURSOR(SELECT pdx.* FROM po_distribution_xml pdx WHERE pdx.po_header_id = phx.po_header_id and pdx.LINE_LOCATION_ID = pllx.LINE_LOCATION_ID) AS distributions
5900               FROM po_line_locations_xml pllx WHERE pllx.po_line_id = plx.po_line_id AND NVL(pllx.payment_type,''NONE'') NOT IN (''ADVANCE'',''DELIVERY'') and not exists
5901             (select ''x'' from po_line_locations_archive_all pllaa where pllaa.line_location_id = pllx.line_location_id
5902             and pllaa.cancel_flag=''Y'' and pllaa.revision_num < PO_COMMUNICATION_PVT.getRevisionNum()) order by pllx.shipment_num ) AS line_locations' || l_complex_dist_query || '
5903               FROM po_lines_xml plx WHERE plx.po_header_id = phx.po_header_id and not exists
5904               (select ''x'' from po_lines_archive_all  plaa where
5905                 plaa.po_line_id = plx.po_line_id and
5906                       plaa.cancel_flag= ''Y'' and plaa.revision_num< PO_COMMUNICATION_PVT.getRevisionNum() ) order by plx.line_num) AS lines
5907               FROM PO_HEADERS_XML phx WHERE phx.PO_HEADER_ID = PO_COMMUNICATION_PVT.getDocumentId() AND
5908               phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
5909 
5910             END IF;
5911           END IF;
5912 
5913       /*As per the new layouts there is no block for displaying Purchasing organization
5914             and Purchasing site information for a Global contract and Blanket agreement.
5915             Removed the condition part, which will add the agreement assignment query to main query.*/
5916         END IF;
5917 
5918       ELSIF p_which_tables = 'ARCHIVE' THEN
5919 
5920      --<Enhanced Pricing Start>
5921      --<BUG 8840221 Added order by clause to sort the modifiers according to the bucket# >
5922 	l_price_modifier_query1 := 'CURSOR (SELECT pax1.* FROM PO_PRICE_ADJS_ARCHIVE_XML pax1 '
5923           || 'WHERE pax1.po_header_id = plx.po_header_id AND pax1.po_line_id = plx.po_line_id '
5924           || 'AND pax1.revision_num= PO_COMMUNICATION_PVT.getRevisionNum() '
5925           || 'AND pax1.parent_adjustment_id is null order by pax1.pricing_group_sequence) AS PRICE_MODIFIERS';
5926         l_price_modifier_query2 := 'CURSOR (SELECT pax2.* FROM PO_PRICE_ADJS_ARCHIVE_XML pax2 '
5927           || 'WHERE pax2.po_header_id = plx.from_header_id AND pax2.po_line_id = plx.from_line_id '
5928           || 'AND pax2.revision_num= PO_COMMUNICATION_PVT.getRevisionNum() AND '
5929           || 'pax2.parent_adjustment_id is null order by pax2.pricing_group_sequence) AS ADD_PRICE_MODIFIERS';
5930         l_price_modifier_query3 := 'CURSOR (SELECT pha.segment1 ponum FROM po_headers_archive_all pha '
5931           || 'WHERE pha.po_header_id = plx.from_header_id) AS ADD_PRICE_PONUM';
5932      --<Enhanced Pricing End>
5933 
5934   /*  Bug#3574748: Added the condition SHIPMENT_TYPE in ('BLANKET','STANDARD') in shipment query. */
5935         /*  Bug#3698674: SQL for generation of XML is framed by checking whether the values are exists at each
5936             level i.e line level, shipment level and distribution level. If the sql query is not framed with out
5937             checking the values exists in the corresponding levels in 8i "Exhausted Result" error is raised.
5938         */
5939         l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getIsComplexWorkPO() is_complex_work_po, PO_COMMUNICATION_PVT.getDocumentType() document_type,
5940     PO_COMMUNICATION_PVT.getCoverMessage() cover_message,PO_COMMUNICATION_PVT.getTimezone() timezone,
5941     PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag()
5942     test_flag,
5943     PO_COMMUNICATION_PVT.getDocumentName() document_name,
5944     PO_COMMUNICATION_PVT.IsDocumentSigned(PO_COMMUNICATION_PVT.getDocumentId()) Signed,
5945     fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile, PO_COMMUNICATION_PVT.getWithTerms() With_Terms , PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , '||
5946         l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||'
5947     FROM PO_HEADERS_ARCHIVE_XML phx WHERE phx.PO_HEADER_ID = PO_COMMUNICATION_PVT.getDocumentId() AND phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
5948 
5949         IF(p_document_subtype <> 'CONTRACTS') THEN -- contracts will have only headers
5950 
5951           SELECT count(*) into l_count FROM po_lines_archive_all WHERE po_header_id = p_document_id;
5952 
5953           IF l_count >0 THEN
5954 
5955       /* for getting the price differentials FROM po_price_differentials_v
5956          the entity _name is 'PO LINE' except for blanket AND entity_name is 'BLANKET LINE'
5957          for blanket */
5958       --Bug 5506417: Added order by plx.line_num clause
5959             l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getIsComplexWorkPO() is_complex_work_po, PO_COMMUNICATION_PVT.getDocumentType() document_type, PO_COMMUNICATION_PVT.getCoverMessage() cover_message,
5960           PO_COMMUNICATION_PVT.getTimezone() timezone,PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
5961           PO_COMMUNICATION_PVT.getDistinctShipmentCount() DIST_SHIPMENT_COUNT,
5962           PO_COMMUNICATION_PVT.getDocumentName() document_name,
5963           PO_COMMUNICATION_PVT.IsDocumentSigned(PO_COMMUNICATION_PVT.getDocumentId()) Signed,
5964           fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile,PO_COMMUNICATION_PVT.getWithTerms() With_Terms  , PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , '||
5965             l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||',
5966           CURSOR(SELECT plx.*, '|| l_adv_amount_query ||' CURSOR(SELECT  PRICE_TYPE_DSP PRICE_TYPE, MULTIPLIER,MIN_MULTIPLIER, MAX_MULTIPLIER FROM po_price_differentials_v
5967               WHERE entity_type='''|| l_eventType ||''' AND entity_id = plx.po_line_id and enabled_flag=''Y'') AS price_diff,
5968           '|| l_line_short_attachment_query || ',' || l_price_modifier_query1 || ',' || l_price_modifier_query2 || ',' || l_price_modifier_query3
5969           || ',' || l_line_url_attachment_query || ',' || l_line_file_attachment_query ||' FROM PO_LINES_ARCHIVE_XML plx WHERE plx.po_header_id = phx.po_header_id
5970           AND plx.REVISION_NUM = (select /*+ push_subq no_unnest */ max(revision_num) from po_lines_archive_all pla where pla.po_line_id = plx.po_line_id
5971           and pla.revision_num <= pcgt.revision_number ) and  ''Y'' = decode(nvl(plx.cancel_flag,''N''),''N'',''Y'',''Y'',decode(plx.revision_num,PO_COMMUNICATION_PVT.getRevisionNum(),''Y'',''N'') )  order by plx.line_num) AS lines
5972           FROM PO_HEADERS_ARCHIVE_XML phx, PO_COMMUNICATION_GT pcgt
5973           WHERE phx.PO_HEADER_ID = PO_COMMUNICATION_PVT.getDocumentId()
5974           AND phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
5975 
5976           END IF;
5977 
5978           SELECT count(*) into l_count FROM po_line_locations_archive_all WHERE po_header_id = p_document_id;
5979 
5980           IF l_count >0 THEN
5981       --Bug 5506417: Added order by pllx.shipment_num and order by plx.line_num clauses
5982             l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getIsComplexWorkPO() is_complex_work_po, PO_COMMUNICATION_PVT.getDocumentType() document_type, PO_COMMUNICATION_PVT.getCoverMessage() cover_message,
5983           PO_COMMUNICATION_PVT.getTimezone() timezone,PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
5984           PO_COMMUNICATION_PVT.getDistinctShipmentCount() DIST_SHIPMENT_COUNT,
5985           PO_COMMUNICATION_PVT.getDocumentName() document_name,
5986           PO_COMMUNICATION_PVT.IsDocumentSigned( PO_COMMUNICATION_PVT.getDocumentId()) Signed,
5987           fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile, PO_COMMUNICATION_PVT.getWithTerms() With_Terms  , PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , '||
5988             l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||',
5989           CURSOR(SELECT plx.*, '|| l_adv_amount_query ||' CURSOR(SELECT  PRICE_TYPE_DSP PRICE_TYPE, MULTIPLIER, MIN_MULTIPLIER,MAX_MULTIPLIER FROM po_price_differentials_v
5990             WHERE entity_type='''|| l_eventType ||''' AND entity_id = plx.po_line_id and enabled_flag=''Y'') AS price_diff,
5991             '|| l_line_short_attachment_query || ',' || l_price_modifier_query1 || ',' || l_price_modifier_query2 || ',' || l_price_modifier_query3 || ',' || l_line_url_attachment_query || ',' || l_line_file_attachment_query ||',
5992           CURSOR(SELECT pllx.*,';
5993             IF (p_document_subtype <> 'STANDARD') THEN
5994               l_xml_query := l_xml_query ||'CURSOR(SELECT PRICE_TYPE_DSP PRICE_TYPE, MIN_MULTIPLIER,  MAX_MULTIPLIER FROM po_price_differentials_v
5995             WHERE entity_type=''PRICE BREAK'' AND entity_id = pllx.line_location_id and enabled_flag=''Y'') AS price_break,';
5996             END IF;
5997              /*Bug 10388305 Added l_tax_name_query to get tax names*/
5998             l_xml_query := l_xml_query || l_tax_name_query || ','  || l_shipment_short_attach_query || ',' || l_shipment_url_attach_query || ',' || l_shipment_file_attach_query ||'
5999           FROM PO_LINE_LOCATIONS_ARCHIVE_XML pllx WHERE pllx.po_line_id = plx.po_line_id and SHIPMENT_TYPE in (''BLANKET'',''STANDARD'',''PREPAYMENT'') AND NVL(pllx.payment_type, ''NONE'') NOT IN (''ADVANCE'',''DELIVERY'')
6000           and pllx.revision_num = (SELECT  /*+ push_subq no_unnest */  MAX(plla.REVISION_NUM) FROM PO_LINE_LOCATIONS_ARCHIVE_ALL plla
6001           where plla.LINE_LOCATION_ID = pllx.LINE_LOCATION_ID and plla.revision_num <= pcgt.revision_number  )
6002           and ''Y'' = decode(nvl(pllx.cancel_flag,''N''),''N'',''Y'',''Y'',decode(pllx.revision_num,PO_COMMUNICATION_PVT.getRevisionNum(),''Y'',''N'') ) order by pllx.shipment_num ) AS line_locations' || l_complex_lloc_query || '
6003           FROM PO_LINES_ARCHIVE_XML plx WHERE plx.po_header_id = phx.po_header_id
6004           AND plx.REVISION_NUM = (SELECT  /*+ push_subq no_unnest */   max(revision_num) from po_lines_archive_all pla where pla.po_line_id = plx.po_line_id
6005           and pla.revision_num <= pcgt.revision_number  ) and  ''Y'' = decode(nvl(plx.cancel_flag,''N''),''N'',''Y'',''Y'',decode(plx.revision_num,PO_COMMUNICATION_PVT.getRevisionNum(),''Y'',''N'') ) order by plx.line_num) AS lines
6006           FROM PO_HEADERS_ARCHIVE_XML phx, PO_COMMUNICATION_GT pcgt   WHERE phx.PO_HEADER_ID = PO_COMMUNICATION_PVT.getDocumentId() AND phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
6007           END IF;
6008 
6009           IF(p_document_subtype <> 'BLANKET') THEN -- blankets will not have distributions
6010             SELECT count(*) into l_count FROM po_distributions_archive_all WHERE po_header_id = p_document_id;
6011 
6012             IF l_count >0 THEN
6013         --Bug 5506417: Added order by pllx.shipment_num and order by plx.line_num clauses
6014          /*Bug 10388305 Added l_tax_name_query to get tax names*/
6015               l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getIsComplexWorkPO() is_complex_work_po, PO_COMMUNICATION_PVT.getDocumentType() document_type, PO_COMMUNICATION_PVT.getCoverMessage() cover_message,
6016             PO_COMMUNICATION_PVT.getTimezone() timezone,PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
6017             PO_COMMUNICATION_PVT.getDistinctShipmentCount() DIST_SHIPMENT_COUNT,
6018             PO_COMMUNICATION_PVT.getDocumentName() document_name,
6019             PO_COMMUNICATION_PVT.IsDocumentSigned(PO_COMMUNICATION_PVT.getDocumentId()) Signed,
6020             fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile, PO_COMMUNICATION_PVT.getWithTerms() With_Terms  , PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , '||
6021               l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||',
6022             CURSOR(SELECT plx.*, '|| l_adv_amount_query ||' CURSOR(SELECT  PRICE_TYPE_DSP PRICE_TYPE, MULTIPLIER FROM po_price_differentials_v
6023             WHERE entity_type=''PO LINE'' AND entity_id = plx.po_line_id and enabled_flag=''Y'') AS price_diff,
6024             '|| l_line_short_attachment_query || ',' || l_price_modifier_query1 || ',' || l_price_modifier_query2 || ',' || l_price_modifier_query3 || ',' || l_line_url_attachment_query || ',' || l_line_file_attachment_query ||',
6025             CURSOR(SELECT pllx.*, ' || l_tax_name_query || ',' || l_shipment_short_attach_query || ',' || l_shipment_url_attach_query || ',' || l_shipment_file_attach_query ||',
6026             CURSOR(SELECT pdx.* FROM po_distribution_archive_xml pdx WHERE pdx.po_header_id = phx.po_header_id and pdx.LINE_LOCATION_ID = pllx.LINE_LOCATION_ID
6027             and pdx.REVISION_NUM = (SELECT MAX(pda.REVISION_NUM) FROM PO_DISTRIBUTIONS_ARCHIVE_ALL pda
6028             WHERE pda.PO_DISTRIBUTION_ID = pdx.PO_DISTRIBUTION_ID AND pda.REVISION_NUM <= pcgt.revision_number ) ) AS distributions
6029             FROM PO_LINE_LOCATIONS_ARCHIVE_XML pllx WHERE pllx.po_line_id = plx.po_line_id and SHIPMENT_TYPE in (''BLANKET'',''STANDARD'',''PREPAYMENT'') AND NVL(pllx.payment_type,''NONE'') NOT IN (''ADVANCE'',''DELIVERY'')
6030             and pllx.revision_num = (SELECT /*+ push_subq no_unnest */ MAX(plla.REVISION_NUM) FROM PO_LINE_LOCATIONS_ARCHIVE_ALL plla
6031             where plla.LINE_LOCATION_ID = pllx.LINE_LOCATION_ID and plla.revision_num <= pcgt.revision_number )
6032             and ''Y'' = decode(nvl(pllx.cancel_flag,''N''),''N'',''Y'',''Y'',decode(pllx.revision_num,PO_COMMUNICATION_PVT.getRevisionNum(),''Y'',''N'') ) order by pllx.shipment_num ) AS line_locations'|| l_complex_dist_query || '
6033             FROM PO_LINES_ARCHIVE_XML plx WHERE plx.po_header_id = phx.po_header_id
6034             AND plx.REVISION_NUM = (select /*+ push_subq no_unnest */ max(revision_num) from po_lines_archive_all pla where pla.po_line_id = plx.po_line_id
6035             and pla.revision_num <= pcgt.revision_number ) and  ''Y'' = decode(nvl(plx.cancel_flag,''N''),''N'',''Y'',''Y'',decode(plx.revision_num,PO_COMMUNICATION_PVT.getRevisionNum(),''Y'',''N'') ) order by plx.line_num) AS lines
6036             FROM PO_HEADERS_ARCHIVE_XML phx, PO_COMMUNICATION_GT pcgt WHERE phx.PO_HEADER_ID = PO_COMMUNICATION_PVT.getDocumentId() AND
6037             phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
6038 
6039             END IF; -- end of
6040           END IF; -- end of balnket if condition
6041         END IF; -- end of Contracts if condition
6042 
6043     /*As per the new layouts there is no block for displaying Purchasing organization
6044     and Purchasing site information for a Global contract and Blanket agreement.
6045     Removed the condition part, which will add the agreement assignment query to main query.*/
6046 
6047       END IF; -- end of else if
6048 
6049     else
6050    /*  Bug#3698674: In 8i db, the functions used to retrieve revision number and release id are not working
6051              properly. Created a global temporary table po_communication_pvt and retrieved the values from the
6052              global temporary table in both main and archive queries.*/
6053       IF p_which_tables = 'MAIN' THEN
6054         IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6055           FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name || 'Releases:','Entered into Release loop');
6056         END IF;
6057 
6058         l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getDocumentType() document_type, PO_COMMUNICATION_PVT.getCoverMessage() cover_message,
6059         PO_COMMUNICATION_PVT.getTimezone() timezone,PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
6060         PO_COMMUNICATION_PVT.getDistinctShipmentCount() DIST_SHIPMENT_COUNT,
6061         PO_COMMUNICATION_PVT.getDocumentName() document_name,
6062         fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile, PO_COMMUNICATION_PVT.getWithTerms() With_Terms  , PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , '||
6063         l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||'
6064         FROM PO_RELEASE_XML phx WHERE phx.PO_RELEASE_ID = PO_COMMUNICATION_PVT.getDocumentId() AND phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
6065 
6066 
6067         SELECT count(*) into l_count FROM po_line_locations_all WHERE po_release_id = p_document_id ;
6068 
6069         IF l_count >0 THEN
6070           IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6071             FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name || 'Releases:','Assigning Releases line/line locations query');
6072           END IF;
6073         -- Added release id in condition
6074         --Bug 5506417: Added order by pllx.shipment_num and order by plx.line_num clauses
6075 	/* Bug 8886244 .
6076  	            As Part of This Bug ,removed the variables l_price_modifier_query1,l_price_modifier_query2,l_price_modifier_query3 while constructing
6077  	            l_xml_query. This is because we are initializing these variables incase of Standard,Blanket Purchase Orders Only.
6078  	            These variables are null incase of RELEASE due to which PO Communication program was failing with missing expression error for Releases.
6079  	            As we did Pricing Enhancement in case of Standard,Blanket only we need not have these variables incase of Release while constructin the queries.
6080  	 */
6081          /*Bug 10388305 Added l_tax_name_query to get tax names*/
6082           l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getDocumentType() document_type, PO_COMMUNICATION_PVT.getCoverMessage() cover_message,
6083             PO_COMMUNICATION_PVT.getTimezone() timezone,PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
6084             PO_COMMUNICATION_PVT.getDistinctShipmentCount() DIST_SHIPMENT_COUNT,
6085             PO_COMMUNICATION_PVT.getDocumentName() document_name,
6086             fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile, PO_COMMUNICATION_PVT.getWithTerms() With_Terms  , PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , '||
6087           l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||',
6088             CURSOR(SELECT plx.*,CURSOR(SELECT  PRICE_TYPE_DSP PRICE_TYPE, MULTIPLIER FROM po_price_differentials_v
6089               WHERE entity_type='''|| l_eventType ||''' AND entity_id = plx.po_line_id and enabled_flag=''Y'') AS price_diff,
6090               '|| l_line_short_attachment_query || ',' || l_line_url_attachment_query || ',' || l_line_file_attachment_query ||',
6091             CURSOR(SELECT pllx.*,' || l_tax_name_query || ','  || l_shipment_short_attach_query || ',' || l_shipment_url_attach_query || ',' || l_shipment_file_attach_query ||',
6092             CURSOR(SELECT pd.*
6093             FROM po_distribution_xml pd WHERE pd.po_release_id = pllx.po_release_id and pd.LINE_LOCATION_ID = pllx.LINE_LOCATION_ID) AS distributions
6094             FROM po_line_locations_xml pllx WHERE pllx.po_release_id in (select po_release_id from PO_COMMUNICATION_GT) and pllx.po_line_id = plx.po_line_id
6095             and not exists (select ''x'' from po_line_locations_archive_all  pllaa where
6096                 pllaa.line_location_id = pllx.line_location_id and
6097                       pllaa.cancel_flag= ''Y'' and pllaa.revision_num< PO_COMMUNICATION_PVT.getRevisionNum() ) order by pllx.shipment_num ) AS line_locations
6098             FROM po_lines_xml plx WHERE  exists (SELECT ''x'' from po_line_locations_all
6099             WHERE po_line_locations_all.po_line_id = plx.po_line_id and  po_release_id = phx.po_release_id and not exists (select ''x'' from po_line_locations_archive_all  pllaa where
6100                 pllaa.line_location_id = po_line_locations_all.line_location_id and
6101                       pllaa.cancel_flag= ''Y'' and pllaa.revision_num< PO_COMMUNICATION_PVT.getRevisionNum() ) ) and plx.po_header_id = phx.po_header_id  order by plx.line_num) AS lines
6102             FROM PO_RELEASE_XML phx WHERE phx.PO_RELEASE_ID = PO_COMMUNICATION_PVT.getDocumentId() AND phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
6103 
6104         END IF;
6105 
6106 
6107 
6108       ELSIF p_which_tables = 'ARCHIVE' THEN
6109         IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6110           FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ||'Release Archive:','Assigning Releases Archive Query');
6111         END IF;
6112 
6113         /* The following query gets the release details, the outermost cursor selects headers information,
6114             and we move to the details (line, shipments, distributions) as we move inside each cursor. The
6115             lines have to be selected from the corresponding blanket since they are not present in the release */
6116         -- Bug 3727808. Use blanket revision number rather than release revision number. Added the max(pb.revision_num) query in lines SQL
6117         -- Bug 5506417: Added order by pllx.shipment_num and order by plx.line_num clauses
6118 	/* Bug 8886244 .
6119  	            As Part of This Bug ,removed the variables l_price_modifier_query1,l_price_modifier_query2,l_price_modifier_query3 while constructing
6120  	            l_xml_query. This is because we are initializing these variables incase of Standard,Blanket Purchase Orders Only.
6121  	            These variables are null incase of RELEASE due to which PO Communication program was failing with missing expression error for Releases.
6122  	            As we did Pricing Enhancement in case of Standard,Blanket only we need not have these variables incase of Release while constructin the queries.
6123  	          */
6124          /*Bug 10388305 Added l_tax_name_query to get tax names*/
6125         l_xml_query := 'SELECT phx.*, PO_COMMUNICATION_PVT.getDocumentType() document_type, PO_COMMUNICATION_PVT.getCoverMessage() cover_message,PO_COMMUNICATION_PVT.getTimezone() timezone,
6126       PO_COMMUNICATION_PVT.getAmendmentMessage() ammendment_message,PO_COMMUNICATION_PVT.getTestFlag() test_flag,
6127       PO_COMMUNICATION_PVT.getDistinctShipmentCount() DIST_SHIPMENT_COUNT,
6128       PO_COMMUNICATION_PVT.getDocumentName() document_name,
6129       fnd_profile.value(''PO_GENERATE_AMENDMENT_DOCS'') amendment_profile, PO_COMMUNICATION_PVT.getWithTerms() With_Terms  , PO_COMMUNICATION_PVT.getIsContractAttachedDoc() Is_Attached_Doc , '||
6130         l_xml_message_query || ',' || l_head_short_attachment_query || ',' || l_head_url_attachment_query || ',' || l_head_file_attachment_query ||',
6131       CURSOR(SELECT plx.*,CURSOR(SELECT  PRICE_TYPE_DSP PRICE_TYPE, MULTIPLIER FROM po_price_differentials_v
6132         WHERE entity_type='''|| l_eventType ||''' AND entity_id = plx.po_line_id and enabled_flag=''Y'') AS price_diff,
6133         '|| l_line_short_attachment_query ||  ','  || l_line_url_attachment_query || ',' || l_line_file_attachment_query ||',
6134       CURSOR(SELECT pllx.*,'|| l_tax_name_query || ','  || l_shipment_short_attach_query || ',' || l_shipment_url_attach_query || ',' || l_shipment_file_attach_query ||',
6135       CURSOR(SELECT pd.*
6136       FROM po_distribution_archive_xml pd WHERE pd.po_release_id = pllx.po_release_id and pd.line_location_id  = pllx.line_location_id
6137       and pd.REVISION_NUM = (SELECT MAX(pda.REVISION_NUM) FROM PO_DISTRIBUTIONS_ARCHIVE_ALL pda
6138       WHERE pda.PO_DISTRIBUTION_ID = pd.PO_DISTRIBUTION_ID AND pda.REVISION_NUM <= PO_COMMUNICATION_PVT.getRevisionNum() ) ) AS distributions
6139       FROM PO_LINE_LOCATIONS_ARCHIVE_XML pllx WHERE pllx.po_release_id = pcgt.po_release_id  and pllx.po_line_id = plx.po_line_id
6140       and pllx.revision_num = (SELECT/*+ push_subq no_unnest */  MAX(plla.REVISION_NUM) FROM PO_LINE_LOCATIONS_ARCHIVE_ALL plla
6141       where plla.LINE_LOCATION_ID = pllx.LINE_LOCATION_ID and plla.revision_num <= pcgt.revision_number  ) order by pllx.shipment_num ) AS line_locations
6142       FROM PO_LINES_ARCHIVE_XML plx
6143       WHERE exists (SELECT ''x'' from po_line_locations_archive_all pllaa
6144       WHERE pllaa.po_line_id = plx.po_line_id and  po_release_id = phx.po_release_id
6145       and pllaa.REVISION_NUM = (select /*+ push_subq no_unnest */ max(revision_num) from po_line_locations_archive_all pllaa1 where pllaa1.line_location_id = pllaa.line_location_id
6146       and pllaa1.revision_num <= pcgt.revision_number  )
6147       and ''Y'' = decode(nvl(pllaa.cancel_flag,''N''),''N'',''Y'',''Y'',decode(pllaa.revision_num,PO_COMMUNICATION_PVT.getRevisionNum(),''Y'',''N'') ) )
6148       and plx.po_header_id = phx.po_header_id
6149       AND plx.REVISION_NUM = (select /*+ push_subq no_unnest */ max(revision_num) from po_lines_archive_all pla where pla.po_line_id = plx.po_line_id
6150       and pla.revision_num <= (select max(pb.revision_num)
6151                                                                  from po_headers_archive_all pb, po_releases_archive_all pr
6152                                                                  where pb.po_header_id = pr.po_header_id
6153                                                                  and pr.po_release_id = pcgt.po_release_id
6154                                                                  and pr.revision_num= pcgt.revision_number
6155                                                                  and pb.approved_date <= pr.approved_date
6156                                                                 ) )   order by plx.line_num desc) AS lines
6157       FROM PO_RELEASE_ARCHIVE_XML phx, PO_COMMUNICATION_GT pcgt WHERE phx.PO_RELEASE_ID = PO_COMMUNICATION_PVT.getDocumentId() AND phx.revision_num = PO_COMMUNICATION_PVT.getRevisionNum()';
6158 
6159       END IF;
6160 
6161 
6162     END IF;
6163 
6164 
6165 --bug#3760632 replaced the function PO_POXPOEPO
6166 --with PO_PRINTPO
6167   /* for header long text */
6168 --bug#3768142 also added the condition to check if the document
6169 --type is a release so that even the release header documents
6170 --are retrieved. An order by is used so that first the
6171 --PO_HEADERS(BPA) attachments are printed followed by PO_RELEASES
6172 --attachments and then finally PO_VENDORS. This is necessary
6173 --only for the Releases because you can display the BPA header
6174 --attachments also with a release.
6175 --bug#3823799: Replaced the hard coded p_document id with PO_COMMUNICATION_PVT.getDocumentId() function
6176     if(p_document_type = 'RELEASE')then
6177   --Bug#4683170
6178   --Appended fad.datatype_id=2 condition for retrieving the
6179         --long_text attachment for the current document only.
6180 
6181   /*Bug5213932 : To convert nonxml characters into their escape equivalents
6182     long text should be converted to clob. Hence calling function get_clob.
6183     Replacing fdl.long_text with get_clob(fdl.rowid) */
6184 
6185       l_headerAttachmentsQuery := 'select fdl.long_text long_text
6186    FROM
6187     fnd_attached_docs_form_vl fad,
6188     fnd_documents_long_text fdl
6189    WHERE ( (entity_name=''PO_RELEASES'' AND
6190      pk1_value= to_char(PO_COMMUNICATION_PVT.getDocumentId()) ) OR
6191      (entity_name = ''PO_HEADERS'' AND
6192      pk1_value = to_char(PO_COMMUNICATION_PVT.getReleaseHeaderId())) OR --Bug6139548
6193      (entity_name = ''PO_VENDORS'' AND
6194      pk1_value = to_char(PO_COMMUNICATION_PVT.getVendorId()))) AND
6195      function_name = ''PO_PRINTPO''
6196      and fad.media_id = fdl.media_id
6197      and fad.datatype_id=2
6198      order by entity_name,seq_num'; --bug6133951
6199 
6200     else
6201   --Bug#4683170
6202   --Appended fad.datatype_id=2 condition for retrieving the
6203         --long_text attachment for the current document only.
6204 
6205   /*Bug5213932 : To convert nonxml characters into their escape equivalents
6206      long text should be converted to clob.Hence calling function get_clob.
6207      Replacing fdl.long_text with get_clob(fdl.rowid) */
6208 
6209       l_headerAttachmentsQuery := 'select fdl.long_text long_text
6210    FROM
6211     fnd_attached_docs_form_vl fad,
6212     fnd_documents_long_text fdl
6213    WHERE ((entity_name = ''PO_HEADERS'' AND
6214      pk1_value = to_char(PO_COMMUNICATION_PVT.getReleaseHeaderId())) OR --Bug6139548
6215     (entity_name = ''PO_VENDORS'' AND
6216      pk1_value = to_char(PO_COMMUNICATION_PVT.getVendorId()))) AND
6217      function_name = ''PO_PRINTPO''
6218      and fad.media_id = fdl.media_id
6219      AND fad.datatype_id=2
6220                  order by seq_num'; --bug6133951
6221     end if;
6222 --bug#3760632 replaced the function PO_POXPOEPO
6223 --with PO_PRINTPO
6224   --Bug#4683170
6225   --Appended fad.datatype_id=2 condition for retrieving the
6226         --long_text attachment for the current document only.
6227   -- Bug 4673653 - Added condition to show item level long text attachments
6228   /* for line long attachments */
6229 
6230     /*Bug5213932 : To convert nonxml characters into their escape equivalents
6231    long text should be converted to clob. Hence calling function get_clob.
6232    Replacing fdl.long_text with get_clob(fds.rowid) */
6233 
6234  /*Bug7426541 -  Added the clauses to select the attachments from BLANKET 'S header and lines
6235   and CONTRACT 'S header- if there is a source document.
6236   Entity types :-  source doc's header -> 'PO_HEADERS' source doc's line -> 'PO_IN_GA_LINES'*/
6237 
6238    /*l_lineAttachQuery :='SELECT  fds.long_text text, plx.po_line_id id
6239    FROM
6240     fnd_attached_docs_form_vl fad,
6241     fnd_documents_long_text fds,
6242     po_lines_all plx
6243   WHERE ((fad.entity_name=''PO_LINES'' AND fad.pk1_value=to_char(plx.po_line_id))
6244            OR
6245                (fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(plx.from_header_id)
6246                 AND plx.from_header_id IS NOT NULL)
6247                OR
6248                (fad.entity_name=''PO_IN_GA_LINES'' AND fad.pk1_value=to_char(plx.from_line_id)
6249                 AND plx.from_line_id IS NOT NULL)
6250                OR
6251                (fad.entity_name=''PO_HEADERS'' AND fad.pk1_value=to_char(plx.CONTRACT_ID)
6252                 AND plx.CONTRACT_ID IS NOT NULL)
6253              OR
6254            (fad.entity_name=''MTL_SYSTEM_ITEMS'' AND
6255             fad.pk1_value=to_char(PO_COMMUNICATION_PVT.getInventoryOrgId()) AND --Bug6139548
6256             fad.pk2_value=to_char(plx.item_id) AND plx.item_id is not null)
6257          ) AND
6258          function_name = ''PO_PRINTPO''
6259          AND fad.media_id = fds.media_id
6260          AND fad.datatype_id=2
6261          AND plx.po_header_id = PO_COMMUNICATION_PVT.getReleaseHeaderId()
6262                order by seq_num'; --bug6133951*/
6263 
6264  /* Bug 13082363 : Improving performance of l_lineAttachQuery query using UNION ALL approach. Plus adding hint so that CBO would start
6265     optimization from po_lines_all table (plx) rather than fnd_attached_document (ad).Using base tables instead of view
6266     fnd_attached_docs_form_vl. For last part of query while fetching attachments for entity MTL_SYSTEM_ITEMS, added hint
6267      use_nl(ad) so that optimizer would perform nl join and the condition ad.pk2_value=to_char ( plx.item_id )
6268        gets evaluated at index level*/
6269 -- Bug 14476193 : Changing condition DT.media_id = fds.media_id to D.media_id = fds.media_id
6270   l_lineAttachQuery :='select text, id from
6271  (SELECT /*+ leading (plx ad)  use_nl(ad)*/
6272        fds.long_text text , plx.po_line_id id,  seq_num
6273   FROM fnd_documents_long_text fds ,
6274     FND_ATTACHED_DOCUMENTS AD,
6275     FND_DOCUMENTS_TL DT ,
6276     FND_DOCUMENTS D ,
6277     FND_ATTACHMENT_FUNCTIONS AF,
6278     fnd_doc_category_usages DCU,
6279     po_lines_all plx
6280   WHERE ( ad.entity_name=''PO_LINES''
6281     AND ad.pk1_value=to_char ( plx.po_line_id ) )
6282     AND DCU.category_id = D.category_id
6283     AND DCU.attachment_function_id = AF.attachment_function_id
6284     AND AF.function_name = ''PO_PRINTPO''
6285     AND D.media_id = fds.media_id
6286     AND D.datatype_id=2
6287     AND D.DOCUMENT_ID = AD.DOCUMENT_ID
6288     AND DT.DOCUMENT_ID = D.DOCUMENT_ID
6289     AND DT.LANGUAGE = USERENV (''LANG'')
6290     AND plx.po_header_id = PO_COMMUNICATION_PVT.getReleaseHeaderId ()
6291   UNION ALL
6292   SELECT /*+ leading (plx ad) use_nl(ad) */
6293         fds.long_text text , plx.po_line_id id, seq_num
6294   FROM fnd_documents_long_text fds ,
6295     FND_ATTACHED_DOCUMENTS AD,
6296     FND_DOCUMENTS_TL DT ,
6297     FND_DOCUMENTS D ,
6298     FND_ATTACHMENT_FUNCTIONS AF,
6299     fnd_doc_category_usages DCU,
6300     po_lines_all plx
6301   WHERE ( ad.entity_name=''PO_HEADERS''
6302     AND ad.pk1_value=to_char ( plx.from_header_id )
6303     AND plx.from_header_id IS NOT NULL )
6304     AND DCU.category_id = D.category_id
6305     AND DCU.attachment_function_id = AF.attachment_function_id
6306     AND AF.function_name = ''PO_PRINTPO''
6307     AND D.media_id = fds.media_id
6308     AND D.datatype_id=2
6309     AND D.DOCUMENT_ID = AD.DOCUMENT_ID
6310     AND DT.DOCUMENT_ID = D.DOCUMENT_ID
6311     AND DT.LANGUAGE = USERENV (''LANG'')
6312     AND plx.po_header_id = PO_COMMUNICATION_PVT.getReleaseHeaderId ()
6313     UNION ALL
6314      SELECT /*+ leading (plx ad)  use_nl(ad) */
6315           fds.long_text text , plx.po_line_id id,  seq_num
6316   FROM fnd_documents_long_text fds ,
6317     FND_ATTACHED_DOCUMENTS AD,
6318     FND_DOCUMENTS_TL DT ,
6319     FND_DOCUMENTS D ,
6320     FND_ATTACHMENT_FUNCTIONS AF,
6321     fnd_doc_category_usages DCU,
6322     po_lines_all plx
6323   WHERE ( ad.entity_name=''PO_IN_GA_LINES''
6324     AND ad.pk1_value=to_char ( plx.from_line_id )
6325     AND plx.from_line_id IS NOT NULL )
6326     AND DCU.category_id = D.category_id
6327     AND DCU.attachment_function_id = AF.attachment_function_id
6328     AND AF.function_name = ''PO_PRINTPO''
6329     AND D.media_id = fds.media_id
6330     AND D.datatype_id=2
6331     AND D.DOCUMENT_ID = AD.DOCUMENT_ID
6332     AND DT.DOCUMENT_ID = D.DOCUMENT_ID
6333     AND DT.LANGUAGE = USERENV (''LANG'')
6334     AND plx.po_header_id = PO_COMMUNICATION_PVT.getReleaseHeaderId ()
6335        UNION ALL
6336      SELECT /*+ leading (plx ad)  use_nl(ad) */
6337          fds.long_text text , plx.po_line_id id, seq_num
6338   FROM fnd_documents_long_text fds ,
6339     FND_ATTACHED_DOCUMENTS AD,
6340     FND_DOCUMENTS_TL DT ,
6341     FND_DOCUMENTS D ,
6342     FND_ATTACHMENT_FUNCTIONS AF,
6343     fnd_doc_category_usages DCU,
6344     po_lines_all plx
6345   WHERE ( ad.entity_name=''PO_HEADERS''
6346     AND ad.pk1_value=to_char ( plx.CONTRACT_ID )
6347     AND plx.CONTRACT_ID IS NOT NULL )
6348     AND DCU.category_id = D.category_id
6349     AND DCU.attachment_function_id = AF.attachment_function_id
6350     AND AF.function_name = ''PO_PRINTPO''
6351     AND D.media_id = fds.media_id
6352     AND D.datatype_id=2
6353     AND D.DOCUMENT_ID = AD.DOCUMENT_ID
6354     AND DT.DOCUMENT_ID = D.DOCUMENT_ID
6355     AND DT.LANGUAGE = USERENV (''LANG'')
6356     AND plx.po_header_id = PO_COMMUNICATION_PVT.getReleaseHeaderId ()
6357        UNION ALL
6358     SELECT /*+ leading (plx ad)  use_nl(ad) */
6359         fds.long_text text , plx.po_line_id id , seq_num
6360    FROM fnd_documents_long_text fds ,
6361     FND_ATTACHED_DOCUMENTS AD,
6362     FND_DOCUMENTS_TL DT ,
6363     FND_DOCUMENTS D ,
6364     FND_ATTACHMENT_FUNCTIONS AF,
6365     fnd_doc_category_usages DCU,
6366     po_lines_all plx
6367   WHERE ( ad.entity_name=''MTL_SYSTEM_ITEMS''
6368     AND ad.pk1_value=to_char ( PO_COMMUNICATION_PVT.getInventoryOrgId ( ) )
6369     AND -- Bug6139548
6370       ad.pk2_value=to_char ( plx.item_id )
6371     AND plx.item_id is not null )
6372     AND DCU.category_id = D.category_id
6373     AND DCU.attachment_function_id = AF.attachment_function_id
6374     AND AF.function_name = ''PO_PRINTPO''
6375     AND D.media_id = fds.media_id
6376     AND D.datatype_id=2
6377     AND D.DOCUMENT_ID = AD.DOCUMENT_ID
6378     AND DT.DOCUMENT_ID = D.DOCUMENT_ID
6379     AND DT.LANGUAGE = USERENV (''LANG'')
6380     AND plx.po_header_id = PO_COMMUNICATION_PVT.getReleaseHeaderId ())
6381     order by seq_num';
6382 
6383 --bug#3760632 replaced the function PO_POXPOEPO
6384 --with PO_PRINTPO
6385   --Bug#4683170
6386   --Appended fad.datatype_id=2 condition for retrieving the
6387         --long_text attachment for the current document only.
6388    /* for shipments long attachments */
6389 
6390       /*Bug52139320 : To convert nonxml characters into their escape equivalents
6391       long text should be converted to clob.Hence calling function get_clob.
6392       Replacing fdl.long_text with get_clob(fds.rowid) */
6393 
6394   /* Bug 4568471/6829381 Exclude the One Time Address attachments when printing shipment long text.
6395     as this text is already printed as shipto Location */
6396 
6397  --  BeginBug16076162
6398  -- Rewriting the following query for performance improvements.
6399     /*l_shipmentAttachmentQuery := 'SELECT fds.long_text long_text, pllx.LINE_LOCATION_ID
6400    FROM
6401     fnd_attached_docs_form_vl fad,
6402     fnd_documents_long_text fds,
6403     po_line_locations_all pllx
6404   WHERE entity_name = ''PO_SHIPMENTS'' AND
6405      pk1_value =  to_char(pllx.LINE_LOCATION_ID) AND
6406          function_name = ''PO_PRINTPO''
6407          AND fad.media_id = fds.media_id
6408        AND fad.document_description not like ''POR%''
6409          AND fad.datatype_id=2
6410          AND pllx.po_header_id = PO_COMMUNICATION_PVT.getReleaseHeaderId()
6411                order by seq_num'; --bug6133951
6412     */
6413 l_shipmentAttachmentQuery := 'SELECT PO_COMMUNICATION_PVT.get_clob(fds.rowid) long_text, pllx.LINE_LOCATION_ID
6414   FROM
6415     fnd_attached_docs_form_vl fad,
6416     fnd_documents_long_text fds,
6417     po_line_locations_all pllx
6418   WHERE entity_name = ''PO_SHIPMENTS'' AND
6419    pk1_value =  to_char(pllx.LINE_LOCATION_ID) AND
6420    function_name = ''PO_PRINTPO''
6421    AND fad.media_id = fds.media_id
6422    AND fad.document_description not like ''POR%''
6423    AND fad.datatype_id=2
6424    AND pllx.po_header_id = PO_COMMUNICATION_PVT.getReleaseHeaderId() ';
6425 
6426 if(p_document_type = 'RELEASE') then
6427   l_shipmentAttachmentQuery := l_shipmentAttachmentQuery || ' AND pllx.po_release_id = PO_COMMUNICATION_PVT.getReleaseId() order by seq_num';
6428 Else
6429   l_shipmentAttachmentQuery := l_shipmentAttachmentQuery || ' order by seq_num';
6430 End If;
6431 -- End Bug16076162
6432 
6433     select TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') into l_time from dual;
6434     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6435       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ||'Start of executing queries', l_time);
6436     END IF;
6437 
6438 
6439     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6440       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name || 'POXMLGEN','Generating XML using XMLGEN');
6441     END IF;
6442     l_xml9_stmt := 'declare
6443        context DBMS_XMLGEN.ctxHandle;
6444                    l_xml_query varchar2(15000) ;
6445        l_headerAttach_query varchar2(1000);
6446        l_lineAttach_query varchar2(8000) ; --Bug13082363 : Increasing length
6447        l_disAttach_query varchar2(1200) ; --Bug5213932 increase length
6448        l_time varchar2(50);
6449        g_log_head    CONSTANT VARCHAR2(30) := ''po.plsql.PO_COMMUNICATION_PVT.'';
6450        l_api_name CONSTANT VARCHAR2(30):= ''POXMLGEN'';
6451        TYPE ref_cursorType IS REF CURSOR;
6452        refcur ref_cursorType;
6453        l_fileClob CLOB := NULL;
6454           Begin
6455 
6456       l_xml_query := :1 ;
6457       l_headerAttach_query := :2;
6458       l_lineAttach_query := :3;
6459       l_disAttach_query := :4;
6460       l_fileClob := :5;
6461 
6462       select TO_CHAR(SYSDATE, ''DD-MON-YYYY HH24:MI:SS'') into l_time from dual;
6463       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6464         FND_LOG.string(FND_LOG.LEVEL_STATEMENT,g_log_head || l_api_name ||''Before Executing the Main Query'', l_time);
6465       END IF;
6466 
6467       context := dbms_xmlgen.newContext(l_xml_query);
6468       dbms_xmlgen.setRowsetTag(context,''PO_DATA'');
6469       dbms_xmlgen.setRowTag(context,NULL);
6470       dbms_xmlgen.setConvertSpecialChars ( context, TRUE);
6471       :xresult := dbms_xmlgen.getXML(context,DBMS_XMLGEN.NONE);
6472       dbms_xmlgen.closeContext(context);
6473 
6474       select TO_CHAR(SYSDATE, ''DD-MON-YYYY HH24:MI:SS'') into l_time from dual;
6475       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6476         FND_LOG.string(FND_LOG.LEVEL_STATEMENT,g_log_head || l_api_name ||''After Executing the Main Query'', l_time);
6477       END IF;
6478 
6479       context := dbms_xmlgen.newContext(l_headerAttach_query);
6480       dbms_xmlgen.setRowsetTag(context,''HEADER_ATTACHMENTS'');
6481       dbms_xmlgen.setRowTag(context,NULL);
6482       dbms_xmlgen.setConvertSpecialChars ( context, TRUE);
6483       :xheaderAttach := dbms_xmlgen.getXML(context,DBMS_XMLGEN.NONE);
6484       dbms_xmlgen.closeContext(context);
6485 
6486       select TO_CHAR(SYSDATE, ''DD-MON-YYYY HH24:MI:SS'') into l_time from dual;
6487       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6488         FND_LOG.string(FND_LOG.LEVEL_STATEMENT,g_log_head || l_api_name ||''After Executing the header attachment Query'', l_time);
6489       END IF;
6490 
6491       context := dbms_xmlgen.newContext(l_lineAttach_query);
6492       dbms_xmlgen.setRowsetTag(context,''LINE_ATTACHMENTS'');
6493       dbms_xmlgen.setRowTag(context,NULL);
6494       dbms_xmlgen.setConvertSpecialChars ( context, TRUE);
6495       :xlineAttach := dbms_xmlgen.getXML(context,DBMS_XMLGEN.NONE);
6496       dbms_xmlgen.closeContext(context);
6497 
6498       select TO_CHAR(SYSDATE, ''DD-MON-YYYY HH24:MI:SS'') into l_time from dual;
6499       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6500         FND_LOG.string(FND_LOG.LEVEL_STATEMENT,g_log_head || l_api_name ||''After Executing the line attachment Query'', l_time);
6501       END IF;
6502 
6503       context := dbms_xmlgen.newContext(l_disAttach_query);
6504       dbms_xmlgen.setRowsetTag(context,''SHIPMENT_ATTACHMENTS'');
6505       dbms_xmlgen.setRowTag(context,NULL);
6506       dbms_xmlgen.setConvertSpecialChars ( context, TRUE);
6507       :xdisAttach := dbms_xmlgen.getXML(context,DBMS_XMLGEN.NONE);
6508       dbms_xmlgen.closeContext(context);
6509 
6510       select TO_CHAR(SYSDATE, ''DD-MON-YYYY HH24:MI:SS'') into l_time from dual;
6511       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6512         FND_LOG.string(FND_LOG.LEVEL_STATEMENT,g_log_head || l_api_name ||''After Executing the shipment attachment Query'', l_time);
6513       END IF;
6514 
6515       IF l_fileClob is not null THEN
6516 
6517             open refcur for ''select :l_fileClob1 as text_file from dual'' using l_fileClob;
6518             context := DBMS_XMLGEN.newContext(refcur);
6519             DBMS_XMLGEN.setRowTag(context,NULL);
6520             DBMS_XMLGEN.setRowSetTag(context,NULL);
6521             :xfileClob := DBMS_XMLGEN.getXML(context,DBMS_XMLGEN.NONE);
6522             DBMS_XMLGEN.closeContext(context);
6523             close refcur;
6524             IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6525               FND_LOG.string(FND_LOG.LEVEL_STATEMENT,g_log_head || l_api_name , ''After executing the file clob'');
6526             END IF;
6527       ELSE
6528             IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6529               FND_LOG.string(FND_LOG.LEVEL_STATEMENT,g_log_head || l_api_name , ''Value of File clob is null'');
6530             END IF;
6531            :xfileClob := null;
6532       END IF;
6533 
6534       -- bug#3580225 Start --
6535 
6536       select TO_CHAR(SYSDATE, ''DD-MON-YYYY HH24:MI:SS'') into l_time from dual;
6537       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6538         FND_LOG.string(FND_LOG.LEVEL_STATEMENT,g_log_head || l_api_name ||''Before calling PO_HR_LOCATION.populate_gt'', l_time);
6539       END IF;
6540 
6541       /* Call PO_HR_LOCATION.populate_gt procedure to insert address values into global temp table from PL/SQL table*/
6542       PO_HR_LOCATION.populate_gt();
6543 
6544       BEGIN
6545         context := dbms_xmlgen.newContext(''select * from po_address_details_gt '');
6546         dbms_xmlgen.setRowsetTag(context,''ADDRESS_DETAILS'');
6547         dbms_xmlgen.setRowTag(context,''ADDRESS_DETAILS_ROW'');
6548         :xaddrDetails := dbms_xmlgen.getXML(context,DBMS_XMLGEN.NONE);
6549         dbms_xmlgen.closeContext(context);
6550       EXCEPTION
6551        WHEN OTHERS THEN
6552           NULL;
6553       END;
6554       -- bug#3580225 Start --
6555 
6556 
6557           End;';
6558 
6559     execute immediate l_xml9_stmt USING l_xml_query , l_headerAttachmentsQuery, l_lineAttachQuery, l_shipmentAttachmentQuery, l_fileClob,
6560     OUT l_xml_result, OUT l_headerAttachments, OUT l_line_Attachments, OUT l_disAttachments, OUT l_fileClob, OUT l_address_details;
6561 
6562 
6563     select TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') into l_time from dual;
6564     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6565       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ||'End of executing queries', l_time);
6566     END IF;
6567 
6568 /*Delete the records from global temp table*/
6569     DELETE po_address_details_gt;
6570     DELETE po_communication_gt ; -- Added this line for bug:3698674
6571 
6572 
6573 
6574 
6575     IF dbms_lob.getlength(l_xml_result) >0 THEN
6576       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6577         FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name , 'inside manuplating l_xml_result');
6578       END IF;
6579   -- add charset.
6580       l_resultOffset := DBMS_LOB.INSTR(l_xml_result, '>');
6581       l_tempXMLResult := l_xml_result;
6582       dbms_lob.write(l_xml_result, length('<?xml version="1.0" encoding="UTF-16"?>'), 1,'<?xml version="1.0" encoding="UTF-16"?>');
6583       dbms_lob.copy(l_xml_result, l_tempXMLResult, dbms_lob.getlength(l_tempXMLResult) - l_resultOffset, length('<?xml version="1.0" encoding="UTF-16"?>'), l_resultOffset);
6584 
6585       IF dbms_lob.getlength(l_headerAttachments) >0 THEN
6586 
6587         l_variablePosition := DBMS_LOB.INSTR(l_headerAttachments, '>');
6588         dbms_lob.copy(l_xml_result, l_headerAttachments, dbms_lob.getlength(l_headerAttachments) - l_variablePosition, (dbms_lob.getlength(l_xml_result) - length('</PO_DATA>') ), l_variablePosition + 1);
6589         IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6590           FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ,'Added header attachments to XML');
6591         END IF;
6592 
6593       END IF;
6594 
6595       IF dbms_lob.getlength(l_line_Attachments) >0 THEN
6596 
6597         l_variablePosition := DBMS_LOB.INSTR(l_line_Attachments, '>');
6598 
6599         IF(DBMS_LOB.INSTR(l_xml_result, '</PO_DATA>') > 0) THEN
6600           dbms_lob.copy(l_xml_result, l_line_Attachments, dbms_lob.getlength(l_line_Attachments) - l_variablePosition, (dbms_lob.getlength(l_xml_result) - length('</PO_DATA>') ), l_variablePosition + 1);
6601         ELSE
6602           dbms_lob.copy(l_xml_result, l_line_Attachments, dbms_lob.getlength(l_line_Attachments) - l_variablePosition, dbms_lob.getlength(l_xml_result), l_variablePosition + 1);
6603         END IF;
6604         IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6605           FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ,'Added line attachments to XML');
6606         END IF;
6607 
6608 
6609       END IF;
6610 
6611       IF dbms_lob.getlength(l_disAttachments) >0 THEN
6612 
6613         l_variablePosition := DBMS_LOB.INSTR(l_disAttachments, '>');
6614         IF(DBMS_LOB.INSTR(l_xml_result, '</PO_DATA>') > 0) THEN
6615           dbms_lob.copy(l_xml_result, l_disAttachments, dbms_lob.getlength(l_disAttachments) - l_variablePosition, (dbms_lob.getlength(l_xml_result) - length('</PO_DATA>') ), l_variablePosition + 1);
6616         ELSE
6617           dbms_lob.copy(l_xml_result, l_disAttachments, dbms_lob.getlength(l_disAttachments) - l_variablePosition, dbms_lob.getlength(l_xml_result), l_variablePosition + 1);
6618         END IF;
6619         IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6620           FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ,'Added distribution attachments to XML');
6621         END IF;
6622 
6623       END IF;
6624 
6625       IF dbms_lob.getlength(l_fileClob) >0 THEN
6626 
6627         l_variablePosition := DBMS_LOB.INSTR(l_fileClob, '>');
6628         IF(DBMS_LOB.INSTR(l_xml_result, '</PO_DATA>') > 0) THEN
6629           dbms_lob.copy(l_xml_result, l_fileClob, dbms_lob.getlength(l_fileClob) - l_variablePosition, (dbms_lob.getlength(l_xml_result) - length('</PO_DATA>') ), l_variablePosition + 1);
6630         ELSE
6631           dbms_lob.copy(l_xml_result, l_fileClob, dbms_lob.getlength(l_fileClob) - l_variablePosition, dbms_lob.getlength(l_xml_result), l_variablePosition + 1);
6632         END IF;
6633         IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6634           FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ,'Added file to XML');
6635         END IF;
6636 
6637 
6638       END IF;
6639 
6640       IF dbms_lob.getlength(l_address_details) >0 THEN -- bug#3580225 Start --
6641 
6642     --Add l_address_details to final XML
6643 
6644         l_variablePosition := DBMS_LOB.INSTR(l_address_details, '>');
6645         IF(DBMS_LOB.INSTR(l_xml_result, '</PO_DATA>') > 0) THEN
6646           dbms_lob.copy(l_xml_result, l_address_details, dbms_lob.getlength(l_address_details) - l_variablePosition, (dbms_lob.getlength(l_xml_result) - length('</PO_DATA>') ), l_variablePosition + 1);
6647         ELSE
6648           dbms_lob.copy(l_xml_result, l_address_details, dbms_lob.getlength(l_address_details) - l_variablePosition, dbms_lob.getlength(l_xml_result), l_variablePosition + 1);
6649         END IF;
6650         IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6651           FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ,'Added Address details to XML');
6652         END IF;
6653 
6654 
6655       END IF; -- bug#3580225 end --
6656 
6657       --<Bug 14677799 Start>
6658       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6659         FND_LOG.string
6660         (FND_LOG.LEVEL_STATEMENT
6661          , g_log_head || l_api_name
6662          , 'Calling custom hook PO_CUSTOM_XMLGEN_PKG.generate_xml_fragment'
6663          );
6664       END IF;
6665 
6666       PO_CUSTOM_XMLGEN_PKG.generate_xml_fragment(p_document_id
6667                                         , p_revision_num
6668                                         , p_document_type
6669                                         , p_document_subtype
6670                                         , l_custom_xml);
6671 
6672       IF dbms_lob.getlength(l_custom_xml) >0 THEN
6673 
6674         l_variablePosition := DBMS_LOB.INSTR(l_custom_xml, '>');
6675         IF(DBMS_LOB.INSTR(l_xml_result, '</PO_DATA>') > 0) THEN
6676           dbms_lob.copy
6677           (l_xml_result
6678           , l_custom_xml
6679           , dbms_lob.getlength(l_custom_xml) - l_variablePosition
6680           , (dbms_lob.getlength(l_xml_result) - length('</PO_DATA>'))
6681           , l_variablePosition + 1
6682           );
6683         ELSE
6684           dbms_lob.copy
6685           (l_xml_result
6686           , l_custom_xml
6687           , dbms_lob.getlength(l_custom_xml) - l_variablePosition
6688           , dbms_lob.getlength(l_xml_result)
6689           , l_variablePosition + 1
6690           );
6691         END IF;
6692         IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6693           FND_LOG.string(FND_LOG.LEVEL_STATEMENT
6694                         , g_log_head || l_api_name
6695                         , 'Added Custom XML');
6696         END IF;
6697 
6698       END IF;
6699       --<Bug 14677799 End>
6700 
6701       IF(DBMS_LOB.INSTR(l_xml_result, '</PO_DATA>') = 0) THEN
6702         dbms_lob.write(l_xml_result, 10, dbms_lob.getlength(l_xml_result), '</PO_DATA>');
6703       END IF;
6704 
6705     END IF;
6706 
6707 /*
6708   If the test flasg is D then the query is executing as part of debugging processos.
6709   Add the final xml query in the clob.
6710 */
6711     IF(p_test_flag = 'D') then
6712 
6713       dbms_lob.write(l_xml_result, 11, dbms_lob.getlength(l_xml_result) - 9, '<XML_QUERY>');
6714       dbms_lob.write(l_xml_result, length(l_xml_query ||'</XML_QUERY> </PO_DATA>'), dbms_lob.getlength(l_xml_result) + 1, l_xml_query ||'</XML_QUERY> </PO_DATA>');
6715 
6716     END IF;
6717     IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6718       FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name ,'END OF POXMLGEN');
6719     END IF;
6720 
6721 
6722     RETURN l_xml_result;
6723   EXCEPTION
6724 
6725     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
6726       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6727         FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name , SQLERRM);
6728       END IF;
6729       RAISE;
6730     WHEN OTHERS THEN
6731       IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
6732         FND_LOG.string(FND_LOG.LEVEL_STATEMENT, g_log_head || l_api_name , SQLERRM);
6733       END IF;
6734       RAISE;
6735 
6736   END;
6737 
6738 /**
6739   drop ship details
6740 */
6741 
6742   function get_drop_ship_details(p_location_id in number) RETURN number is
6743 
6744 
6745   l_po_header_id NUMBER ;
6746   l_po_line_id NUMBER ;
6747   l_po_release_id NUMBER ;
6748   X_ORDER_LINE_INFO_REC OE_DROP_SHIP_GRP.Order_Line_Info_Rec_Type;
6749   X_MSG_DATA VARCHAR2(100) ;
6750   X_MSG_COUNT NUMBER ;
6751   X_RETURN_STATUS VARCHAR2(100) ;
6752 
6753 
6754   BEGIN
6755 
6756     OE_DROP_SHIP_GRP.get_order_line_info(
6757                                          P_API_VERSION => 1.0,
6758                                          P_PO_HEADER_ID => l_po_header_id,
6759                                          P_PO_LINE_ID => l_po_line_id,
6760                                          P_PO_LINE_LOCATION_ID => p_location_id,
6761                                          P_PO_RELEASE_ID => l_po_release_id,
6762                                          P_MODE => 2,
6763                                          X_ORDER_LINE_INFO_REC => X_ORDER_LINE_INFO_REC,
6764                                          X_MSG_DATA => X_MSG_DATA,
6765                                          X_MSG_COUNT => X_MSG_COUNT,
6766                                          X_RETURN_STATUS => X_RETURN_STATUS );
6767 
6768     g_ship_cont_phone := x_order_line_info_rec.SHIP_TO_CONTACT_PHONE;
6769     g_ship_cont_email := x_order_line_info_rec.SHIP_TO_CONTACT_EMAIL;
6770     g_deliver_cont_phone := x_order_line_info_rec.DELIVER_TO_CONTACT_PHONE;
6771     g_deliver_cont_email := x_order_line_info_rec.DELIVER_TO_CONTACT_EMAIL;
6772     g_ship_cont_name := x_order_line_info_rec.SHIP_TO_CONTACT_NAME;
6773     g_deliver_cont_name := x_order_line_info_rec.DELIVER_TO_CONTACT_NAME;
6774     g_ship_cust_name := x_order_line_info_rec.SHIP_TO_CUSTOMER_NAME;
6775     g_ship_cust_location := x_order_line_info_rec.SHIP_TO_CUSTOMER_LOCATION;
6776     g_deliver_cust_name := x_order_line_info_rec.DELIVER_TO_CUSTOMER_NAME;
6777     g_deliver_cust_location := x_order_line_info_rec.DELIVER_TO_CUSTOMER_LOCATION;
6778     g_ship_contact_fax := x_order_line_info_rec.SHIP_TO_CONTACT_FAX;
6779     g_deliver_contact_name := x_order_line_info_rec.DELIVER_TO_CONTACT_NAME;
6780     g_deliver_contact_fax := x_order_line_info_rec.DELIVER_TO_CONTACT_FAX;
6781     g_shipping_method := x_order_line_info_rec.SHIPPING_METHOD;
6782     g_shipping_instructions := x_order_line_info_rec.SHIPPING_INSTRUCTIONS;
6783     g_packing_instructions := x_order_line_info_rec.PACKING_INSTRUCTIONS;
6784     g_customer_product_desc := x_order_line_info_rec.CUSTOMER_PRODUCT_DESCRIPTION;
6785     g_customer_po_number := x_order_line_info_rec.CUSTOMER_PO_NUMBER;
6786     g_customer_po_line_num := x_order_line_info_rec.CUSTOMER_PO_LINE_NUMBER;
6787     g_customer_po_shipment_num := x_order_line_info_rec.CUSTOMER_PO_SHIPMENT_NUMBER;
6788 
6789     RETURN 1.0;
6790   END ;
6791 
6792 
6793   function getShipContPhone RETURN VARCHAR2 is
6794   begin
6795     RETURN g_ship_cont_phone;
6796   END ;
6797 
6798   function getShipContEmail RETURN VARCHAR2 is
6799   begin
6800     RETURN g_ship_cont_email;
6801   END ;
6802 
6803   function getDeliverContPhone RETURN VARCHAR2 is
6804   begin
6805     RETURN g_deliver_cont_phone;
6806   END ;
6807 
6808   function getDeliverContEmail RETURN VARCHAR2 is
6809   begin
6810     RETURN g_deliver_cont_email;
6811   END ;
6812 
6813   function getShipContName RETURN VARCHAR2 is
6814   begin
6815     RETURN g_ship_cont_name;
6816   END ;
6817 
6818   function getDeliverContName RETURN VARCHAR2 is
6819   begin
6820     RETURN g_deliver_cont_name;
6821   END ;
6822 
6823   function getShipCustName RETURN VARCHAR2 is
6824   begin
6825     RETURN g_ship_cust_name;
6826   END ;
6827 
6828   function getShipCustLocation RETURN VARCHAR2 is
6829   begin
6830     RETURN g_ship_cust_location;
6831   END ;
6832 
6833   function getDeliverCustName RETURN VARCHAR2 is
6834   begin
6835     RETURN g_deliver_cust_name;
6836   END ;
6837 
6838 
6839   function getDeliverCustLocation RETURN VARCHAR2 is
6840   begin
6841     RETURN g_deliver_cust_location;
6842   END ;
6843 
6844   function getShipContactfax return VARCHAR2 is
6845   begin
6846     return g_ship_contact_fax;
6847   end;
6848   function getDeliverContactName return VARCHAR2 is
6849   begin
6850     return g_deliver_contact_name;
6851   end;
6852   function getDeliverContactFax return VARCHAR2 is
6853   begin
6854     return g_deliver_contact_fax;
6855   end;
6856   function getShippingMethod return VARCHAR2 is
6857   begin
6858     return g_shipping_method;
6859   end;
6860   function getShippingInstructions return VARCHAR2 is
6861   begin
6862     return g_shipping_instructions;
6863   end;
6864   function getPackingInstructions return VARCHAR2 is
6865   begin
6866     return g_packing_instructions;
6867   end;
6868   function getCustomerProductDesc return VARCHAR2 is
6869   begin
6870     return g_customer_product_desc;
6871   end;
6872   function getCustomerPoNumber return VARCHAR2 is
6873   begin
6874     return g_customer_po_number;
6875   end;
6876   function getCustomerPoLineNum return VARCHAR2 is
6877   begin
6878     return g_customer_po_line_num;
6879   end;
6880   function getCustomerPoShipmentNum return VARCHAR2 is
6881   begin
6882     return g_customer_po_shipment_num;
6883   end;
6884 
6885   function getDocumentId RETURN NUMBER is
6886   begin
6887     RETURN g_document_id;
6888   END ;
6889 
6890 
6891   function getRevisionNum RETURN NUMBER is
6892   begin
6893     RETURN g_revision_num;
6894   END ;
6895 
6896   function getVendorId RETURN NUMBER is
6897   begin
6898     RETURN g_vendor_id;
6899   END ;
6900 
6901   function getCoverMessage RETURN VARCHAR2 is
6902   begin
6903     RETURN g_cover_message;
6904   END ;
6905 
6906   function getAmendmentMessage RETURN VARCHAR2 is
6907   begin
6908     RETURN g_amendment_message;
6909   END ;
6910 
6911   function getTimezone RETURN VARCHAR2 is
6912   begin
6913     RETURN g_timezone;
6914   end;
6915 
6916   function getTestFlag RETURN VARCHAR2 is
6917   begin
6918     RETURN g_test_flag;
6919   END ;
6920 
6921   function getReleaseHeaderId RETURN VARCHAR2 is
6922   begin
6923     RETURN g_release_header_id ;
6924   END ;
6925 
6926   --Bug 16076162
6927   function getReleaseId RETURN VARCHAR2 is
6928   begin
6929     RETURN g_release_id ;
6930   END ;
6931 
6932   function getLocationInfo(p_location_id in number) return number is
6933   begin
6934 
6935     if PO_COMMUNICATION_PVT.g_location_id <> p_location_id or
6936       PO_COMMUNICATION_PVT.g_location_id is null then
6937 
6938       PO_COMMUNICATION_PVT.g_location_id := p_location_id;
6939 
6940       PO_COMMUNICATION_PVT.g_address_line1 := null;
6941       PO_COMMUNICATION_PVT.g_address_line2 := null;
6942       PO_COMMUNICATION_PVT.g_address_line3 := null;
6943       PO_COMMUNICATION_PVT.g_Territory_short_name := null;
6944       PO_COMMUNICATION_PVT.g_address_info := null;
6945       PO_COMMUNICATION_PVT.g_location_name := null;
6946       PO_COMMUNICATION_PVT.g_phone := null;
6947       PO_COMMUNICATION_PVT.g_fax := null;
6948       PO_COMMUNICATION_PVT.g_address_line4 := null;
6949 --bug#3438608
6950       PO_COMMUNICATION_PVT.g_town_or_city := null;
6951       PO_COMMUNICATION_PVT.g_state_or_province := null;
6952       PO_COMMUNICATION_PVT.g_postal_code := null;
6953 --bug#3438608
6954 
6955 --bug#3438608 passed the out variables PO_COMMUNICATION_PVT.g_town_or_city
6956 --PO_COMMUNICATION_PVT.g_postal_code,PO_COMMUNICATION_PVT.g_state_or_province
6957 --to the procedure PO_HR_LOCATION.get_alladdress_lines
6958 
6959       -- bug#3580225: changed the procedure name to  get_alladdress_lines from get_address--
6960       po_hr_location.get_alladdress_lines(p_location_id,
6961                                           PO_COMMUNICATION_PVT.g_address_line1,
6962                                           PO_COMMUNICATION_PVT.g_address_line2,
6963                                           PO_COMMUNICATION_PVT.g_address_line3,
6964                                           PO_COMMUNICATION_PVT.g_Territory_short_name,
6965                                           PO_COMMUNICATION_PVT.g_address_info,
6966                                           PO_COMMUNICATION_PVT.g_location_name,
6967                                           PO_COMMUNICATION_PVT.g_phone,
6968                                           PO_COMMUNICATION_PVT.g_fax,
6969                                           PO_COMMUNICATION_PVT.g_address_line4,
6970                                           PO_COMMUNICATION_PVT.g_town_or_city,
6971                                           PO_COMMUNICATION_PVT.g_postal_code,
6972                                           PO_COMMUNICATION_PVT.g_state_or_province);
6973 
6974     end if;
6975     return p_location_id;
6976 
6977   end;
6978 
6979 
6980   function getAddressLine1 return varchar2 is
6981   begin
6982     return PO_COMMUNICATION_PVT.g_address_line1;
6983   end;
6984   function getAddressLine2 return varchar2 is
6985   begin
6986     return PO_COMMUNICATION_PVT.g_address_line2;
6987   end;
6988   function getAddressLine3 return varchar2 is
6989   begin
6990     return PO_COMMUNICATION_PVT.g_address_line3;
6991   end;
6992 
6993   function getTerritoryShortName return varchar2 is
6994   begin
6995     return PO_COMMUNICATION_PVT.g_Territory_short_name;
6996   end;
6997 
6998   function getAddressInfo return varchar2 is
6999   begin
7000     return PO_COMMUNICATION_PVT.g_address_info;
7001   end;
7002 --bug#3438608 added three function getTownOrCity
7003 --getPostalCode and getStateOrProvince
7004 --toreturn the values in global variables
7005 --po_communication_pvt.g_town_or_city
7006 --po_communication_pvt.g_postal_code
7007 --and po_communication_pvt.g_state_or_province.
7008 --These functions are  called by the PO_HEADERS_CHANGE_PRINT
7009 --report
7010 
7011   function getTownOrCity return varchar2 is
7012   begin
7013     return PO_COMMUNICATION_PVT.g_town_or_city;
7014   end;
7015 
7016   function getPostalCode return varchar2 is
7017   begin
7018     return PO_COMMUNICATION_PVT.g_postal_code;
7019   end;
7020 
7021   function getStateOrProvince return varchar2 is
7022   begin
7023     return PO_COMMUNICATION_PVT.g_state_or_province;
7024   end;
7025 --bug#3438608
7026 
7027 /*Bug 4504228 START Retrieving the phone and email contact of buyer from
7028  per_all_people_f rather than the hr_locations.So commenting out
7029  the below function and adding two functions getPhone(p_agent_id)
7030  and getEmail()*/
7031 
7032 /*function getPhone return varchar2 is
7033 begin
7034   return PO_COMMUNICATION_PVT.g_phone;
7035 end; */
7036 
7037   function getPhone(p_agent_id in number) return varchar2 is
7038   begin
7039     if PO_COMMUNICATION_PVT.g_person_id <> p_agent_id or
7040       PO_COMMUNICATION_PVT.g_person_id is null then
7041 
7042       PO_COMMUNICATION_PVT.g_person_id := p_agent_id;
7043       PO_COMMUNICATION_PVT.g_buyer_phone := null;
7044       PO_COMMUNICATION_PVT.g_buyer_email_address := null;
7045       PO_COMMUNICATION_PVT.g_buyer_fax := null; --Bug5671523
7046 
7047      /* Bug5191404  Buyer phone number was incorrectly taken from office details
7048          tab.Now with this fix the buyers phone willbe taken from per_phones work
7049          phone type.Commenting out the below sql and adding a new sql*/
7050 
7051 -- bug#5999438 modified the below sqls where clause date checking condition for work phone and work fax.
7052 -- added nvl to pph.date_from
7053 /*Begin Edit Akyanama Bug # 12970846 */
7054       BEGIN
7055 /*End Edit Akyanama Bug # 12970846 */
7056       SELECT
7057            pap.email_address,
7058            pph.phone_number
7059       INTO PO_COMMUNICATION_PVT.g_buyer_email_address,
7060            PO_COMMUNICATION_PVT.g_buyer_phone
7061       FROM per_phones pph,
7062            per_all_people_f pap
7063       WHERE pph.parent_id(+) = pap.person_id
7064            AND pph.parent_table(+) = 'PER_ALL_PEOPLE_F'
7065            AND pph.phone_type (+) = 'W1'
7066            AND pap.person_id = p_agent_id
7067            AND trunc(sysdate) BETWEEN pap.effective_start_date AND pap.effective_end_date
7068        AND trunc(sysdate) BETWEEN nvl(pph.date_from, trunc(sysdate)) AND nvl(pph.date_to, trunc(sysdate))
7069        AND ROWNUM = 1; -- Bug5671523
7070       /* Bug5191404   End */
7071       /*Begin Edit Akyanama Bug # 12970846 */
7072 	   EXCEPTION
7073           WHEN No_Data_Found THEN
7074                    NULL;
7075       END;
7076 	  /*End Edit Akyanama Bug # 12970846 */
7077 
7078 	  --Bug5671523 start
7079 	  /*Begin Edit Akyanama Bug # 12970846 */
7080       BEGIN
7081       /*End Edit Akyanama Bug # 12970846 */
7082       SELECT
7083              pph.phone_number
7084         INTO PO_COMMUNICATION_PVT.g_buyer_fax
7085         FROM per_phones pph,
7086              per_all_people_f pap
7087        WHERE pph.parent_id(+) = pap.person_id
7088          AND pph.parent_table(+) = 'PER_ALL_PEOPLE_F'
7089          AND pph.phone_type(+) = 'WF'
7090          AND pap.person_id = p_agent_id
7091          AND trunc(sysdate) BETWEEN pap.effective_start_date AND pap.effective_end_date
7092          AND trunc(sysdate) BETWEEN nvl(pph.date_from, trunc(sysdate)) AND nvl(pph.date_to, trunc(sysdate)) -- bug#5999438
7093          AND ROWNUM = 1;
7094    --Bug5671523 end
7095    /*Begin Edit Akyanama Bug # 12970846 */
7096 	  EXCEPTION
7097           WHEN No_Data_Found THEN
7098                    NULL;
7099       END;
7100 	  /*End Edit Akyanama Bug # 12970846 */
7101 
7102     end if;
7103 
7104 --Bug4686436    return PO_COMMUNICATION_PVT.g_phone;
7105     return PO_COMMUNICATION_PVT.g_buyer_phone;
7106   end;
7107 
7108   function getEmail return varchar2 is
7109   begin
7110     return PO_COMMUNICATION_PVT.g_buyer_email_address;
7111   end;
7112 
7113 /*Bug 4504228 END */
7114 
7115   function getFax return varchar2 is
7116   begin
7117  --Bug5671523 return PO_COMMUNICATION_PVT.g_fax;
7118     return PO_COMMUNICATION_PVT.g_buyer_fax;
7119   end;
7120   function getLocationName return varchar2 is
7121   begin
7122     return PO_COMMUNICATION_PVT.g_location_name;
7123   end;
7124 
7125 /* Bug#3580225: Changed the function to call po_hr_location.get_alladdress_lines PROCEDURE*/
7126   function getOperationInfo(p_org_id in NUMBER) return varchar2 is
7127   l_address_line4 varchar2(240) := null;
7128   l_ou_location_code HR_LOCATIONS.LOCATION_CODE%type := null;
7129   l_ou_phone HR_LOCATIONS.TELEPHONE_NUMBER_1%type := null;
7130   l_ou_fax HR_LOCATIONS.TELEPHONE_NUMBER_2%type := null;
7131   l_address_info varchar2(500) := null;
7132   l_location_id PO_HR_LOCATIONS.LOCATION_ID%type := null;
7133 
7134   begin
7135     if PO_COMMUNICATION_PVT.g_org_id <> p_org_id or
7136       PO_COMMUNICATION_PVT.g_org_id is null then
7137 
7138       PO_COMMUNICATION_PVT.g_org_id := p_org_id;
7139 
7140       PO_COMMUNICATION_PVT.g_ou_name := null;
7141       PO_COMMUNICATION_PVT.g_ou_address_line_1 := null;
7142       PO_COMMUNICATION_PVT.g_ou_address_line_2 := null;
7143       PO_COMMUNICATION_PVT.g_ou_address_line_3 := null;
7144       PO_COMMUNICATION_PVT.g_ou_town_or_city := null;
7145       PO_COMMUNICATION_PVT.g_ou_region2 := null;
7146       PO_COMMUNICATION_PVT.g_ou_postal_code := null;
7147       PO_COMMUNICATION_PVT.g_ou_country := null;
7148 
7149     /*select name and location id from hr_all_organization_units*/
7150 
7151       SELECT name, location_id into PO_COMMUNICATION_PVT.g_ou_name, l_location_id
7152       FROM hr_all_organization_units
7153       WHERE organization_id = p_org_id;
7154 
7155     /* Call get_alladdress_lines procedure to retrieve address details*/
7156 
7157       po_hr_location.get_alladdress_lines(l_location_id,
7158                                           PO_COMMUNICATION_PVT.g_ou_address_line_1,
7159                                           PO_COMMUNICATION_PVT.g_ou_address_line_2,
7160                                           PO_COMMUNICATION_PVT.g_ou_address_line_3,
7161                                           PO_COMMUNICATION_PVT.g_ou_country,
7162                                           l_address_info,
7163                                           l_ou_location_code,
7164                                           l_ou_phone,
7165                                           l_ou_fax,
7166                                           l_address_line4,
7167                                           PO_COMMUNICATION_PVT.g_ou_town_or_city,
7168                                           PO_COMMUNICATION_PVT.g_ou_postal_code,
7169                                           PO_COMMUNICATION_PVT.g_ou_region2);
7170 
7171 
7172     end if;
7173     return PO_COMMUNICATION_PVT.g_ou_name;
7174   end;
7175 
7176 
7177   function getOUAddressLine1 return varchar2 is
7178   begin
7179     return PO_COMMUNICATION_PVT.g_ou_address_line_1;
7180   end;
7181   function getOUAddressLine2 return varchar2 is
7182   begin
7183     return PO_COMMUNICATION_PVT.g_ou_address_line_2;
7184   end;
7185   function getOUAddressLine3 return varchar2 is
7186   begin
7187     return PO_COMMUNICATION_PVT.g_ou_address_line_3;
7188   end;
7189   function getOUTownCity return varchar2 is
7190   begin
7191     return PO_COMMUNICATION_PVT.g_ou_town_or_city;
7192   end;
7193   function getOURegion2 return varchar2 is
7194   begin
7195     return PO_COMMUNICATION_PVT.g_ou_region2;
7196   end;
7197   function getOUPostalCode return varchar2 is
7198   begin
7199     return PO_COMMUNICATION_PVT.g_ou_postal_code;
7200   end;
7201 
7202 /*  Function retuns the Operation Unit country value that
7203   retreived in getOperationInfo function.
7204 */
7205 
7206   function getOUCountry return varchar2 is
7207   begin
7208     return PO_COMMUNICATION_PVT.g_ou_country;
7209   end;
7210 
7211 
7212 
7213   function getSegmentNum(p_header_id in NUMBER) return VARCHAR2 is
7214   begin
7215 
7216   -- bug5386806
7217   -- If p_header_id is null, set all dependent fields to NULL
7218     IF (p_header_id IS NULL) THEN
7219 
7220       PO_COMMUNICATION_PVT.g_header_id := NULL;
7221       PO_COMMUNICATION_PVT.g_quote_number := NULL;
7222       PO_COMMUNICATION_PVT.g_agreement_number := NULL;
7223       PO_COMMUNICATION_PVT.g_agreement_flag := NULL;
7224 
7225     ELSIF PO_COMMUNICATION_PVT.g_header_id <> p_header_id or
7226       PO_COMMUNICATION_PVT.g_header_id is null then
7227 
7228       PO_COMMUNICATION_PVT.g_header_id := p_header_id;
7229 
7230       Select ph.QUOTE_VENDOR_QUOTE_NUMBER, ph.SEGMENT1, ph.GLOBAL_AGREEMENT_FLAG into
7231         PO_COMMUNICATION_PVT.g_quote_number, PO_COMMUNICATION_PVT.g_agreement_number,
7232         PO_COMMUNICATION_PVT.g_agreement_flag
7233       FROM
7234         po_headers_all ph
7235       WHERE
7236         ph.PO_HEADER_ID = p_header_id;
7237 
7238 
7239     end if;
7240 
7241     RETURN PO_COMMUNICATION_PVT.g_agreement_number;
7242 
7243   end;
7244 
7245   function getAgreementLineNumber return VARCHAR2 is
7246   begin
7247     return PO_COMMUNICATION_PVT.g_agreementLine_number;
7248   end;
7249   function getQuoteNumber return VARCHAR2 is
7250   begin
7251     return PO_COMMUNICATION_PVT.g_quote_number;
7252   end;
7253 
7254   function getAgreementFlag return VARCHAR2 is
7255   begin
7256     return PO_COMMUNICATION_PVT.g_agreement_flag;
7257   end;
7258 
7259   function getAgreementLineNumber(p_line_id in NUMBER) return NUMBER is
7260   begin
7261     if PO_COMMUNICATION_PVT.g_line_id <> p_line_id or
7262       PO_COMMUNICATION_PVT.g_line_id is null then
7263 
7264       PO_COMMUNICATION_PVT.g_line_id := p_line_id;
7265 
7266       Select LINE_NUM into PO_COMMUNICATION_PVT.g_agreementLine_number
7267       FROM PO_LINES_ALL
7268       WHERE PO_LINE_ID = p_line_id;
7269     end if;
7270     return PO_COMMUNICATION_PVT.g_agreementLine_number;
7271 
7272   end;
7273 
7274   function getArcBuyerAgentID(p_header_id in NUMBER) return NUMBER is
7275   begin
7276     if PO_COMMUNICATION_PVT.g_header_id1 <> p_header_id or
7277       PO_COMMUNICATION_PVT.g_header_id1 is null then
7278 
7279       PO_COMMUNICATION_PVT.g_header_id1 := p_header_id;
7280 
7281       PO_COMMUNICATION_PVT.g_arcBuyer_fname := null;
7282       PO_COMMUNICATION_PVT.g_arcBuyer_lname := null;
7283       PO_COMMUNICATION_PVT.g_arcAgent_id := null;
7284 
7285       SELECT HRE.FIRST_NAME,
7286         HRE.LAST_NAME,
7287         HRL.MEANING,
7288         PHA.AGENT_ID
7289       INTO PO_COMMUNICATION_PVT.g_arcBuyer_fname, PO_COMMUNICATION_PVT.g_arcBuyer_lname,
7290            PO_COMMUNICATION_PVT.g_arcBuyer_title, PO_COMMUNICATION_PVT.g_arcAgent_id
7291 
7292       FROM
7293         PER_ALL_PEOPLE_F HRE,
7294         PO_HEADERS_ARCHIVE_ALL PHA,
7295         HR_LOOKUPS HRL
7296      WHERE HRL.LOOKUP_CODE(+)       = HRE.TITLE AND
7297         HRL.LOOKUP_TYPE(+)       = 'TITLE' AND
7298         HRE.PERSON_ID = PHA.AGENT_ID AND
7299       --HRE.EMPLOYEE_NUMBER IS NOT NULL AND    --<R12 CWK Enhancemment>
7300         TRUNC(SYSDATE) BETWEEN HRE.EFFECTIVE_START_DATE AND HRE.EFFECTIVE_END_DATE AND
7301         PHA.PO_HEADER_ID = p_header_id AND
7302         PHA.REVISION_NUM = 0 ;
7303     end if;
7304 
7305     return g_arcAgent_id;
7306 
7307   end;
7308 
7309   function getArcBuyerFName return VARCHAR2 is
7310   begin
7311     return PO_COMMUNICATION_PVT.g_arcBuyer_fname;
7312   end;
7313 
7314   function getArcBuyerLName return VARCHAR2 is
7315   begin
7316     return PO_COMMUNICATION_PVT.g_arcBuyer_lname;
7317   end;
7318 
7319   function getArcBuyerTitle return VARCHAR2 is
7320   begin
7321     return PO_COMMUNICATION_PVT.g_arcBuyer_title;
7322   end;
7323 
7324 
7325   function getRelArcBuyerAgentID(p_release_id in NUMBER) return NUMBER is
7326   begin
7327     if PO_COMMUNICATION_PVT.g_release_id <> p_release_id or
7328       PO_COMMUNICATION_PVT.g_release_id is null then
7329 
7330       PO_COMMUNICATION_PVT.g_release_id := p_release_id;
7331 
7332       PO_COMMUNICATION_PVT.g_arcBuyer_fname := null;
7333       PO_COMMUNICATION_PVT.g_arcBuyer_lname := null;
7334       PO_COMMUNICATION_PVT.g_arcAgent_id := null;
7335 
7336       SELECT HRE.FIRST_NAME,
7337         HRE.LAST_NAME,
7338         PHA.AGENT_ID
7339       INTO PO_COMMUNICATION_PVT.g_arcBuyer_fname, PO_COMMUNICATION_PVT.g_arcBuyer_lname, PO_COMMUNICATION_PVT.g_arcAgent_id
7340 
7341       FROM
7342         PER_ALL_PEOPLE_F HRE,
7343         PO_RELEASES_ARCHIVE_ALL PHA
7344       WHERE
7345         HRE.PERSON_ID = PHA.AGENT_ID AND
7346       -- HRE.EMPLOYEE_NUMBER IS NOT NULL AND   --<R12 CWK Enhancemment>
7347         TRUNC(SYSDATE) BETWEEN HRE.EFFECTIVE_START_DATE AND HRE.EFFECTIVE_END_DATE AND
7348         PHA.PO_RELEASE_ID = p_release_id AND
7349         PHA.REVISION_NUM = 0 ;
7350     end if;
7351 
7352     return g_arcAgent_id;
7353 
7354   end;
7355 
7356   function getVendorAddressLine1(p_vendor_site_id in NUMBER) return VARCHAR2 is
7357 
7358   l_city PO_VENDOR_SITES.city%type := null;
7359   l_state PO_VENDOR_SITES.state%type := null;
7360   l_zip PO_VENDOR_SITES.zip%type := null;
7361   l_address_line_1 PO_VENDOR_SITES.ADDRESS_LINE1%type := null;
7362 
7363   begin
7364 
7365     if PO_COMMUNICATION_PVT.g_vendor_site_id <> p_vendor_site_id or
7366       PO_COMMUNICATION_PVT.g_vendor_site_id is null then
7367 
7368       PO_COMMUNICATION_PVT.g_vendor_address_line_2 := null;
7369       PO_COMMUNICATION_PVT.g_vendor_address_line_3 := null;
7370       PO_COMMUNICATION_PVT.g_vendor_country := null;
7371       PO_COMMUNICATION_PVT.g_vendor_city_state_zipInfo := null;
7372       PO_COMMUNICATION_PVT.g_vendor_address_line_4 := null; --bug: 3463617
7373 
7374   --bug: 3463617 : Retreived address_line4 from po_vendor_sites_all.
7375       SELECT PVS.ADDRESS_LINE1 ,
7376         PVS.ADDRESS_LINE2 ,
7377         PVS.ADDRESS_LINE3 ,
7378         PVS.CITY ,
7379         DECODE(PVS.STATE, NULL, DECODE(PVS.PROVINCE, NULL, PVS.COUNTY, PVS.PROVINCE), PVS.STATE),
7380         PVS.ZIP ,
7381         FTE.TERRITORY_SHORT_NAME,
7382         PVS.ADDRESS_LINE4 --bug: 3463617
7383         INTO
7384         l_address_line_1, PO_COMMUNICATION_PVT.g_vendor_address_line_2, PO_COMMUNICATION_PVT.g_vendor_address_line_3,
7385         l_city, l_state, l_zip, PO_COMMUNICATION_PVT.g_vendor_country, PO_COMMUNICATION_PVT.g_vendor_address_line_4
7386       FROM
7387         PO_VENDOR_SITES_ALL PVS,
7388         FND_TERRITORIES_TL FTE
7389       WHERE
7390         PVS.COUNTRY = FTE.TERRITORY_CODE AND
7391         DECODE(FTE.TERRITORY_CODE, NULL, '1', FTE.LANGUAGE) = DECODE(FTE.TERRITORY_CODE, NULL, '1', USERENV('LANG')) AND
7392         PVS.VENDOR_SITE_ID = p_vendor_site_id ;
7393 
7394 
7395       If (l_city is null) then
7396         PO_COMMUNICATION_PVT.g_vendor_city_state_zipInfo := l_state ||' '|| l_zip;
7397       else
7398         PO_COMMUNICATION_PVT.g_vendor_city_state_zipInfo := l_city || ',' || l_state ||' '|| l_zip;
7399       end if;
7400     end if;
7401 
7402     return l_address_line_1;
7403 
7404   end;
7405 
7406   function getVendorAddressLine2 return VARCHAR2 is
7407   begin
7408     return PO_COMMUNICATION_PVT.g_vendor_address_line_2;
7409   end;
7410   function getVendorAddressLine3 return VARCHAR2 is
7411   begin
7412     return PO_COMMUNICATION_PVT.g_vendor_address_line_3;
7413   end;
7414   function getVendorCityStateZipInfo return VARCHAR2 is
7415   begin
7416     return PO_COMMUNICATION_PVT.g_vendor_city_state_zipInfo;
7417   end;
7418   function getVendorCountry return VARCHAR2 is
7419   begin
7420     return PO_COMMUNICATION_PVT.g_vendor_country ;
7421   end;
7422 
7423 
7424   function getJob(p_job_id in NUMBER) return VARCHAR2 is
7425   begin
7426     if PO_COMMUNICATION_PVT.g_job_id <> p_job_id or
7427       PO_COMMUNICATION_PVT.g_job_id is null then
7428 
7429       PO_COMMUNICATION_PVT.g_job_name := null;
7430 
7431       SELECT
7432         name
7433       INTO
7434         PO_COMMUNICATION_PVT.g_job_name
7435       FROM
7436         PER_JOBS_VL
7437       WHERE
7438         job_id = p_job_id;
7439     end if;
7440 
7441     return PO_COMMUNICATION_PVT.g_job_name;
7442   end;
7443 
7444   function getDocumentType return VARCHAR2 is
7445   begin
7446     return PO_COMMUNICATION_PVT.g_documentType;
7447   end;
7448 
7449   function getFormatMask return VARCHAR2 is
7450   begin
7451     if PO_COMMUNICATION_PVT.g_currency_code <> g_current_currency_code or
7452       PO_COMMUNICATION_PVT.g_currency_code is null then
7453 
7454       PO_COMMUNICATION_PVT.g_currency_code := PO_COMMUNICATION_PVT.g_current_currency_code;
7455       PO_COMMUNICATION_PVT.g_format_mask := null;
7456 
7457       g_format_mask := FND_CURRENCY.GET_FORMAT_MASK(g_current_currency_code, 60);
7458     end if;
7459 
7460     return PO_COMMUNICATION_PVT.g_format_mask;
7461 
7462   end;
7463 
7464   function getLegalEntityName return VARCHAR2 is
7465   begin
7466     return PO_COMMUNICATION_PVT.g_buyer_org;
7467   end;
7468 
7469   function IsDocumentSigned(p_header_id in Number) return VARCHAR2 is
7470   l_signed boolean;
7471   l_signatures VARCHAR2(1) := 'N'; -- bug#3297926
7472   l_acceptance_req_flag  varchar2(1) ; --Bug9535677
7473   begin
7474 
7475  -- bug#3297926 Start --
7476  --l_signed :=  PO_SIGNATURE_PVT.Was_Signature_Required(p_document_id => p_header_id);
7477  -- SQL What:Checks if there is any record in the PO_ACTION_HISTORY with the
7478  --          action code as 'SIGNED' and revision less than current revision.
7479  -- SQL Why :To find out if the document was ever signed
7480     begin
7481     /*Bug9535677  Donot check for the signed status if the acceptance type is not
7482  	          document and signature */
7483 
7484        select acceptance_required_flag
7485        into l_acceptance_req_flag
7486        from po_headers_all
7487        where po_header_id= p_header_id;
7488 
7489       IF (nvl(l_acceptance_req_flag,'N') <> 'S') THEN
7490          l_signed := TRUE;
7491       else
7492        SELECT 'Y'
7493         INTO l_signatures
7494         FROM dual
7495        WHERE EXISTS (SELECT 1
7496                        FROM PO_ACTION_HISTORY
7497                       WHERE object_id = p_header_id
7498                         AND object_type_code IN ('PO', 'PA')
7499                         AND action_code = 'SIGNED'
7500       AND OBJECT_REVISION_NUM < PO_COMMUNICATION_PVT.g_revision_num);
7501 
7502       IF l_signatures = 'Y' THEN
7503         l_signed := TRUE;
7504       ELSE
7505         l_signed := FALSE;
7506       END IF;
7507   END IF;--Bug9535677
7508   EXCEPTION
7509       WHEN NO_DATA_FOUND THEN
7510         l_signed := FALSE;
7511     END; -- End of bug#3297926  --
7512 
7513     IF l_signed THEN
7514       RETURN FND_API.G_TRUE;
7515     ELSE
7516       RETURN FND_API.G_FALSE;
7517     END IF;
7518 
7519 
7520   end;
7521 
7522 -- <Start Word Integration 11.5.10+>
7523 
7524 /*
7525   This function frames a document's file name
7526    given the passed in parameters.
7527 */
7528   FUNCTION getDocFileName(p_document_type varchar2,
7529                           p_terms varchar2,
7530                           p_orgid number,
7531                           p_document_id varchar2,
7532                           p_revision_num number,
7533                           p_draft_id number, --CLM
7534                           p_language_code varchar2,
7535                           p_extension varchar2,
7536 			  p_is_conf_doc varchar2 default 'N') RETURN varchar2 IS
7537 
7538   l_po_number po_drafts.modification_number%type;
7539   l_language_code fnd_languages.language_code%type;
7540   l_api_name CONSTANT VARCHAR2(25) := 'PDFFileName';
7541   l_file_name fnd_lobs.file_name%type;
7542   l_revision_num po_drafts.revision_num%type;
7543   l_progress VARCHAR2(3);
7544  /* Begin Add By Akyanama Bug # 13342437*/
7545   l_release_num po_releases_all.release_num%type;
7546   /* End Add By Akyanama Bug # 13342437*/
7547    BEGIN
7548 
7549     l_progress := '000';
7550 
7551     IF g_debug_stmt THEN
7552       PO_DEBUG.debug_begin(p_log_head => g_log_head || l_api_name);
7553       PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'p_document_id', p_document_id);
7554       PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'p_document_type', p_document_type);
7555     END IF;
7556 
7557     BEGIN
7558 
7559       l_revision_num := p_revision_num;
7560 
7561     -- If the language code is null the get the userenv language.
7562       IF p_language_code IS NULL THEN
7563         SELECT userenv('LANG') INTO l_language_code FROM dual;
7564       ELSE
7565         l_language_code := p_language_code;
7566       END IF;
7567 
7568       l_progress := '020';
7569 
7570       IF g_debug_stmt THEN
7571         PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'l_language_code', l_language_code);
7572       END IF;
7573 
7574     -- Query for getting the PO number i.e segment1.
7575       IF p_document_type in ('PO', 'PA') THEN
7576         IF (p_draft_id = -1 or p_is_conf_doc = 'Y') THEN --CLM
7577             SELECT ph.segment1 into l_po_number
7578             FROM po_headers_all ph
7579             WHERE po_header_id = p_document_id ;
7580         ELSE --CLM
7581            SELECT modification_number into l_po_number
7582             FROM po_drafts
7583             WHERE draft_id = p_draft_id;
7584         END IF; --CLM
7585       ELSE
7586        /* Begin Edit By Akyanama Bug # 13342437*/
7587            SELECT ph.segment1, release_num  into l_po_number, l_release_num
7588 	  /* End Edit By Akyanama Bug # 13342437*/
7589         FROM po_headers_all ph, po_releases_all pr
7590         WHERE ph.po_header_id = pr.po_header_id and pr.po_release_id = p_document_id ;
7591       END IF;
7592 
7593     EXCEPTION
7594       WHEN others THEN l_po_number := NULL;
7595     END;
7596 
7597   --if the po number is null assign the document id to po number.
7598     IF l_po_number IS NULL THEN
7599       l_po_number := p_document_id;
7600     END IF;
7601 
7602     IF p_is_conf_doc = 'Y' THEN
7603 	l_revision_num := l_revision_num + 1;
7604     END IF;
7605 
7606       /* Begin Edit By Akyanama Bug # 13342437*/
7607       /* Changes to add the Release number to the file name in case of a
7608  * Release */
7609 	IF p_document_type in ('PO','PA') THEN
7610 		l_file_name := p_document_type || p_terms || p_orgid || '_' ||
7611                 l_po_number || '_' || p_revision_num || '_' || l_language_code || p_extension;
7612 	ELSE
7613 		l_file_name :=
7614                 p_document_type||p_terms||p_orgid||'_'||l_po_number||'_'||l_release_num||'_'||p_revision_num||'_'||l_language_code||p_extension;
7615 	END IF;
7616 	/* Begin Edit By Akyanama Bug # 13342437*/
7617     l_progress := '900';
7618     IF g_debug_stmt THEN
7619       PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'l_file_name', l_file_name);
7620       PO_DEBUG.debug_end(g_log_head || l_api_name);
7621     END IF;
7622 
7623     RETURN l_file_name;
7624 
7625   END getDocFileName;
7626 
7627 
7628 -------------------------------------------------------------------------------
7629 --Start of Comments
7630 --Name: getPDFFileName
7631 --Pre-reqs:
7632 --  None.
7633 --Modifies:
7634 --  None.
7635 --Locks:
7636 --  None.
7637 --Function:
7638 --  Given parameters, returns a file name for an pdf file to use when
7639 --  representing the document.
7640 --Parameters:
7641 --IN:
7642 -- p_document_type: either 'PO' or 'PA'
7643 -- p_terms: either '_' or '_TERMS_'
7644 -- p_orgid: org id of the document
7645 -- p_document_id: document id of a document.
7646 -- p_revision_num: revision of the document
7647 -- p_draft_id: draft id of the document
7648 -- p_language_code: language short code, e.g. 'US' or 'KO'
7649 --Testing:
7650 --
7651 --End of Comments
7652 -------------------------------------------------------------------------------
7653   FUNCTION getPDFFileName(p_document_type varchar2,
7654                           p_terms varchar2,
7655                           p_orgid number,
7656                           p_document_id varchar2,
7657                           p_revision_num number,
7658                           p_language_code varchar2) RETURN varchar2 IS
7659   BEGIN
7660       return(getPDFFileName(p_document_type ,
7661                           p_terms ,
7662                           p_orgid ,
7663                           p_document_id ,
7664                           p_revision_num ,
7665                           -1,  -- CLM
7666                           p_language_code,
7667 			  'N'));
7668   END;
7669 
7670   FUNCTION getPDFFileName(p_document_type varchar2,
7671                           p_terms varchar2,
7672                           p_orgid number,
7673                           p_document_id varchar2,
7674                           p_revision_num number,
7675                           p_draft_id number,  -- CLM
7676                           p_language_code varchar2,
7677 			  p_is_conf_doc varchar2) RETURN varchar2 IS
7678   BEGIN
7679 
7680     RETURN getDocFileName(p_document_type => p_document_type
7681                           , p_terms => p_terms
7682                           , p_orgid => p_orgid
7683                           , p_document_id => p_document_id
7684                           , p_revision_num => p_revision_num
7685                           , p_draft_id => p_draft_id  -- CLM
7686                           , p_language_code => p_language_code
7687                           , p_extension => '.pdf'
7688 			  , p_is_conf_doc => p_is_conf_doc );
7689 
7690   END getPDFFileName;
7691 
7692 -------------------------------------------------------------------------------
7693 --Start of Comments
7694 --Name: getRTFFileName
7695 --Pre-reqs:
7696 --  None.
7697 --Modifies:
7698 --  None.
7699 --Locks:
7700 --  None.
7701 --Function:
7702 --  Given parameters, returns a file name for an rtf file to use when
7703 --  representing the document.
7704 --Parameters:
7705 --IN:
7706 -- p_document_type: either 'PO' or 'PA'
7707 -- p_terms: either '_' or '_TERMS_'
7708 -- p_orgid: org id of the document
7709 -- p_document_id: document id of a document.
7710 -- p_revision_num: revision of the document
7711 -- p_draft_id: draft id of the document
7712 -- p_language_code: language short code, e.g. 'US' or 'KO'
7713 --Testing:
7714 --
7715 --End of Comments
7716 -------------------------------------------------------------------------------
7717   FUNCTION getRTFFileName(p_document_type varchar2,
7718                           p_terms varchar2,
7719                           p_orgid number,
7720                           p_document_id varchar2,
7721                           p_revision_num number,
7722                           p_language_code varchar2) RETURN varchar2 IS
7723   BEGIN
7724     return(getRTFFileName(p_document_type ,
7725                           p_terms ,
7726                           p_orgid ,
7727                           p_document_id ,
7728                           p_revision_num ,
7729                           -1, -- CLM
7730                           p_language_code ));
7731   END;
7732 
7733   FUNCTION getRTFFileName(p_document_type varchar2,
7734                           p_terms varchar2,
7735                           p_orgid number,
7736                           p_document_id varchar2,
7737                           p_revision_num number,
7738                           p_draft_id number,  -- CLM
7739                           p_language_code varchar2) RETURN varchar2 IS
7740   BEGIN
7741 
7742     RETURN getDocFileName(p_document_type => p_document_type
7743                           , p_terms => p_terms
7744                           , p_orgid => p_orgid
7745                           , p_document_id => p_document_id
7746                           , p_revision_num => p_revision_num
7747                           , p_draft_id => p_draft_id  -- CLM
7748                           , p_language_code => p_language_code
7749                           , p_extension => '.rtf' );
7750 
7751   END getRTFFileName;
7752 
7753 -- <End Word Integration 11.5.10+>
7754 
7755 -------------------------------------------------------------------------------
7756 --Start of Comments
7757 --Name: getZipFileName
7758 --Pre-reqs:
7759 --  Column EMAIL_ATTACHMENT_FILENAME should exist in table po_system_parameters_all
7760 --Modifies:
7761 --  None.
7762 --Locks:
7763 --  None.
7764 --Function:
7765 --  Queries the value of 'Email Attachment Filename' which acts as filename of the
7766 --  zipped file sent in the communication
7767 --Parameters:
7768 --  p_org_id Id of the organization that we will get the value for.
7769 --Returns:
7770 --  For functions:
7771 --    Returns the values of 'Email Attachment Filename' in Purchasing Options
7772 --    Setup form. Returns 'Attachments.zip' if the value in the database is null.
7773 --Notes:
7774 --  Added as a part of <PO Attachment Support 11i.11>
7775 --  History
7776 --    Bug# 5240634 Changed the signature to take in a org_id
7777 --
7778 --    The function used to construct the zip file name using
7779 --    document type, orgid, document id and revision num as
7780 --    p_document_type||'_'||p_orgid||'_'||l_document_number||'_'||p_revision_num||'.zip';
7781 --    This was changed as per ECO Bug #43877577 to return static string 'Attachments.zip'
7782 --    This was then made a parameter in po_system_parameters_all as per ECO Bug #5069318
7783 --End of Comments
7784 -------------------------------------------------------------------------------
7785   FUNCTION getZIPFileName(p_org_id in number) RETURN VARCHAR2 IS
7786   l_email_attachment_filename po_system_parameters_all.email_attachment_filename%type;
7787   l_progress varchar2(200);
7788   d_progress NUMBER;
7789   d_module VARCHAR2(70) := 'PO_COMMUNICATION_PVT.getZIPFileName';
7790   BEGIN
7791     d_progress := 0;
7792     IF (PO_LOG.d_proc) THEN
7793       PO_LOG.proc_begin(d_module);
7794     END IF;
7795 
7796     select nvl(psp.email_attachment_filename, 'Attachments.zip')
7797     into l_email_attachment_filename
7798     from po_system_parameters_all psp
7799     where org_id = p_org_id;
7800 
7801     d_progress := 10;
7802     IF (PO_LOG.d_proc) THEN
7803       PO_LOG.proc_begin(d_module, 'Email Attachment Filename', l_email_attachment_filename);
7804       PO_LOG.proc_end(d_module);
7805     END IF;
7806     return l_email_attachment_filename;
7807   Exception
7808     when others then
7809       IF (PO_LOG.d_exc) THEN
7810         PO_LOG.exc(d_module, d_progress, SQLCODE || SQLERRM);
7811       END IF;
7812   END getZIPFileName;
7813 
7814 --bug:346361
7815   function getAddressLine4 return varchar2 is
7816   begin
7817     return PO_COMMUNICATION_PVT.g_address_line4;
7818   end;
7819 
7820 --bug:346361
7821   function getVendorAddressLine4 return VARCHAR2 is
7822   begin
7823     return PO_COMMUNICATION_PVT.g_vendor_address_line_4;
7824   end;
7825 
7826 
7827 /* function to retrieve legal entity details for given Inventory Organization */
7828 
7829   function getLegalEntityDetails(p_org_id in NUMBER) return varchar2 is
7830 
7831   l_location_id HR_LOCATIONS.location_id%type := null;
7832   l_address_line4 varchar2(240) := null;
7833   l_legal_entity_location_code HR_LOCATIONS.LOCATION_CODE%type := null;
7834   l_legal_entity_phone HR_LOCATIONS.TELEPHONE_NUMBER_1%type := null;
7835   l_legal_entity_fax HR_LOCATIONS.TELEPHONE_NUMBER_2%type := null;
7836   l_address_info varchar2(500) := null;
7837 
7838 /*Bug5983107 */
7839   l_legal_entity_id NUMBER;
7840   x_legalentity_info xle_utilities_grp.LegalEntity_Rec;
7841   x_return_status VARCHAR2(20) ;
7842   x_msg_count NUMBER ;
7843   x_msg_data VARCHAR2(4000) ;
7844 /*Bug 5983107*/
7845 
7846 
7847   begin
7848 
7849     if PO_COMMUNICATION_PVT.g_legal_entity_org_id <> p_org_id or
7850       PO_COMMUNICATION_PVT.g_legal_entity_org_id is null then
7851 
7852       PO_COMMUNICATION_PVT.g_legal_entity_org_id := p_org_id;
7853 
7854       PO_COMMUNICATION_PVT.g_legal_entity_name := null;
7855       PO_COMMUNICATION_PVT.g_legal_entity_address_line_1 := null;
7856       PO_COMMUNICATION_PVT.g_legal_entity_address_line_2 := null;
7857       PO_COMMUNICATION_PVT.g_legal_entity_address_line_3 := null;
7858       PO_COMMUNICATION_PVT.g_legal_entity_town_or_city := null;
7859       PO_COMMUNICATION_PVT.g_legal_entity_state := null;
7860       PO_COMMUNICATION_PVT.g_legal_entity_postal_code := null;
7861 
7862     /*Bug5983107 Commenting out the sql below and replacing the API's provided by XLE*/
7863 
7864    /* SELECT name, LOCATION_ID
7865     INTO PO_COMMUNICATION_PVT.g_legal_entity_name, l_location_id
7866     FROM hr_all_organization_units
7867     WHERE to_char(organization_id) = ( SELECT org_information2 FROM hr_organization_information WHERE  org_information_context = 'Accounting Information'
7868               and organization_id = p_org_id ) ;  */
7869 
7870       l_legal_entity_id := PO_CORE_S.get_default_legal_entity_id(p_org_id);
7871 
7872       XLE_UTILITIES_GRP.Get_LegalEntity_Info(
7873                                              x_return_status,
7874                                              x_msg_count,
7875                                              x_msg_data,
7876                                              null,
7877                                              l_legal_entity_id,
7878                                              x_legalentity_info);
7879 
7880       PO_COMMUNICATION_PVT.g_legal_entity_name := x_legalentity_info.name;
7881       l_location_id := x_legalentity_info.location_id;
7882 
7883      /*End bug5983107 */
7884 
7885 
7886 /* call procedure get_address in po_hr_location package to retrieve
7887     address information for given location id*/
7888 
7889       po_hr_location.get_alladdress_lines(l_location_id,
7890                                           PO_COMMUNICATION_PVT.g_legal_entity_address_line_1,
7891                                           PO_COMMUNICATION_PVT.g_legal_entity_address_line_2,
7892                                           PO_COMMUNICATION_PVT.g_legal_entity_address_line_3,
7893                                           PO_COMMUNICATION_PVT.g_legal_entity_country,
7894                                           l_address_info,
7895                                           l_legal_entity_location_code,
7896                                           l_legal_entity_phone,
7897                                           l_legal_entity_fax,
7898                                           l_address_line4,
7899                                           PO_COMMUNICATION_PVT.g_legal_entity_town_or_city,
7900                                           PO_COMMUNICATION_PVT.g_legal_entity_postal_code,
7901                                           PO_COMMUNICATION_PVT.g_legal_entity_state);
7902 
7903     end if;
7904     return PO_COMMUNICATION_PVT.g_legal_entity_name ;
7905 
7906   EXCEPTION
7907     WHEN OTHERS THEN
7908       PO_COMMUNICATION_PVT.g_legal_entity_name := null;
7909       PO_COMMUNICATION_PVT.g_legal_entity_address_line_1 := null;
7910       PO_COMMUNICATION_PVT.g_legal_entity_address_line_2 := null;
7911       PO_COMMUNICATION_PVT.g_legal_entity_address_line_3 := null;
7912       PO_COMMUNICATION_PVT.g_legal_entity_town_or_city := null;
7913       PO_COMMUNICATION_PVT.g_legal_entity_state := null;
7914       PO_COMMUNICATION_PVT.g_legal_entity_postal_code := null;
7915       return PO_COMMUNICATION_PVT.g_legal_entity_name ;
7916 
7917 
7918   end getLegalEntityDetails;
7919 
7920 /* start of functions to return legal entity address details */
7921 
7922   function getLEAddressLine1 return varchar2 is
7923   begin
7924     return PO_COMMUNICATION_PVT.g_legal_entity_address_line_1;
7925   end;
7926 
7927   function getLEAddressLine2 return varchar2 is
7928   begin
7929     return PO_COMMUNICATION_PVT.g_legal_entity_address_line_2;
7930   end;
7931 
7932   function getLEAddressLine3 return varchar2 is
7933   begin
7934     return PO_COMMUNICATION_PVT.g_legal_entity_address_line_3;
7935   end;
7936 
7937   function getLECountry return varchar2 is
7938   begin
7939     return PO_COMMUNICATION_PVT.g_legal_entity_country;
7940   end;
7941 
7942   function getLETownOrCity return varchar2 is
7943   begin
7944     return PO_COMMUNICATION_PVT.g_legal_entity_town_or_city;
7945   end;
7946 
7947   function getLEPostalCode return varchar2 is
7948   begin
7949     return PO_COMMUNICATION_PVT.g_legal_entity_postal_code;
7950   end;
7951 
7952   function getLEStateOrProvince return varchar2 is
7953   begin
7954     return PO_COMMUNICATION_PVT.g_legal_entity_state;
7955   end;
7956 
7957 -- end of functions to return legal entity address details --
7958 
7959 /*
7960   Function returns distinct count of shipment level ship to from header level ship to. This count is
7961   used in XSL to identify what to display in ship to address at header and shipment level
7962 */
7963   function getDistinctShipmentCount return number is
7964   begin
7965     return PO_COMMUNICATION_PVT.g_dist_shipto_count;
7966   end;
7967 
7968 /*
7969   Function to retrieve cancel date for Standard, Blanket and Contract PO's
7970 */
7971 
7972   function getPOCancelDate(p_po_header_id in NUMBER) return date is
7973   l_cancel_date date := null;
7974   begin
7975     SELECT action_date
7976     INTO l_cancel_date
7977     FROM po_action_history pah
7978     WHERE pah.object_id = p_po_header_id
7979     AND ((pah.object_type_code = 'PO'
7980     AND pah.object_sub_type_code in ('PLANNED', 'STANDARD'))
7981     OR (pah.object_type_code = 'PA'
7982     AND pah.object_sub_type_code in ('BLANKET', 'CONTRACT')))
7983     AND pah.action_code = 'CANCEL';
7984 
7985     return l_cancel_date;
7986   EXCEPTION
7987     WHEN OTHERS THEN
7988       l_cancel_date := null;
7989       return l_cancel_date;
7990 
7991   end getPOCancelDate;
7992 
7993 
7994 /*******************************************************************************
7995   FUNCTION NAME :  getCanceledAmount
7996 
7997   Description   : This function retreives Canceled Line amount and Total
7998   line amount for given line id. Returns canceled_amount and populates
7999   g_line_org_amount global variable with original line amount
8000 
8001   Referenced by :
8002   parameters    : p_po_line_id of type number as IN parameter
8003       p_po_revision_num of type number as IN parameter
8004       p_po_header_id of type number as IN parameter
8005 
8006   CHANGE History: Created    MANRAM
8007 ********************************************************************************/
8008   function getCanceledAmount(p_po_line_id IN NUMBER,
8009                              p_po_revision_num IN NUMBER,
8010                              p_po_header_id IN NUMBER) return varchar2 is
8011 
8012   l_canceled_amount number := null;
8013   l_amount number := null;
8014   begin
8015 
8016     SELECT sum(AMOUNT_CANCELLED), pl.amount
8017     INTO l_canceled_amount, l_amount
8018           FROM po_line_locations_all pll,
8019                po_lines_all pl
8020           WHERE pll.po_line_id = p_po_line_id AND
8021           pll.po_header_id = p_po_header_id AND
8022           pl.po_line_id = pll.po_line_id AND
8023           pll.CANCEL_FLAG = 'Y'
8024           AND pll.shipment_type <> 'PREPAYMENT' -- <Complex Work R12>
8025     group by pl.amount;
8026 
8027     PO_COMMUNICATION_PVT.g_line_org_amount := l_canceled_amount + l_amount ;
8028 
8029     return l_canceled_amount;
8030 
8031   EXCEPTION
8032     WHEN NO_DATA_FOUND THEN
8033       begin
8034         SELECT sum(AMOUNT_CANCELLED), pl.amount
8035         INTO l_canceled_amount, l_amount
8036         FROM po_line_locations_archive_all plla,
8037              po_lines_all pl
8038         WHERE plla.po_line_id = p_po_line_id AND
8039               plla.po_header_id = p_po_header_id AND
8040               plla.revision_num = p_po_revision_num AND
8041               pl.po_line_id = plla.po_line_id AND
8042               plla.CANCEL_FLAG = 'Y'
8043               AND plla.shipment_type <> 'PREPAYMENT' -- <Complex Work R12>
8044               group by pl.amount;
8045 
8046         PO_COMMUNICATION_PVT.g_line_org_amount := l_canceled_amount + l_amount ;
8047 
8048       EXCEPTION
8049         WHEN OTHERS THEN
8050           l_canceled_amount := null;
8051           l_amount := null;
8052           PO_COMMUNICATION_PVT.g_line_org_amount := null;
8053           return l_canceled_amount;
8054       end;
8055 
8056   end getCanceledAmount;
8057 
8058 
8059   function getLineOriginalAmount return number is
8060   begin
8061     return PO_COMMUNICATION_PVT.g_line_org_amount;
8062   end;
8063 
8064 /*Bug#3583910 return the global variable g_with_terms */
8065   function getWithTerms return varchar2 is
8066   begin
8067     return PO_COMMUNICATION_PVT.g_with_terms;
8068   end;
8069 
8070 
8071 /*******************************************************************************
8072   bug#3630737.
8073   PROCEDURE NAME : getOUDocumentDetails
8074 
8075   Description   :  This procedure is called from the PoGenerateDocument.java
8076   file. This procedure retrieves and returns OperatingUnitName, Draft message
8077   from and concatinated message of DocumentType, po number and revision number.
8078 
8079   Referenced by : PoGenerateDocument.java
8080    CHANGE History: Created    MANRAM
8081 ********************************************************************************/
8082 
8083   PROCEDURE getOUDocumentDetails(p_documentID IN NUMBER,
8084                                  p_draftId IN NUMBER := -1, --CLM
8085                                  x_pendingSignatureFlag OUT NOCOPY VARCHAR2,
8086                                  x_documentName OUT NOCOPY VARCHAR2,
8087                                  x_organizationName OUT NOCOPY VARCHAR2,
8088                                  x_draft OUT NOCOPY VARCHAR2) IS
8089 
8090   BEGIN
8091 
8092   -- Bug 4044904: Get organization name from database
8093   -- as PO_COMMUNICATION_PVT.g_ou_name was never being populated anywhere
8094   -- Moved query up from below
8095 
8096     SELECT NVL(poh.pending_signature_flag, 'N')
8097          , hou.name
8098     INTO x_pendingSignatureFlag
8099        , PO_COMMUNICATION_PVT.g_ou_name
8100 --    FROM po_headers_all poh
8101     FROM po_headers_merge_v poh
8102        , hr_all_organization_units hou
8103     WHERE poh.po_header_id = p_documentID
8104       AND poh.draft_id = p_draftId --CLM
8105       AND hou.organization_id = poh.org_id;
8106 
8107     x_organizationName := PO_COMMUNICATION_PVT.g_ou_name; -- operating unit name
8108     x_documentName := PO_COMMUNICATION_PVT.g_documentName; -- document name
8109 
8110   -- Bug 4044904 : Moved query above
8111 
8112   --retrieve draf from fnd_new_messages.
8113     FND_MESSAGE.SET_NAME('PO', 'PO_FO_DRAFT');
8114     x_draft := FND_MESSAGE.GET;
8115 
8116   EXCEPTION
8117     WHEN OTHERS THEN
8118       x_pendingSignatureFlag := 'N';
8119       x_documentName := null;
8120       x_organizationName := null;
8121       x_draft := null;
8122 
8123 
8124   END;
8125 
8126   function getDocumentName return VARCHAR2 is
8127   BEGIN
8128     return PO_COMMUNICATION_PVT.g_documentName;
8129   END;
8130 
8131 --Start Bug#3771735
8132 --The function returns DocumentTypeCode
8133   function getDocumentTypeCode return VARCHAR2 is
8134   BEGIN
8135     return PO_COMMUNICATION_PVT.g_documentTypeCode;
8136   END;
8137 --End Bug#3771735
8138 
8139 -- Start Bug 4026592
8140   FUNCTION getIsContractAttachedDoc return VARCHAR2
8141   IS
8142   BEGIN
8143     return PO_COMMUNICATION_PVT.g_is_contract_attached_doc;
8144   END getIsContractAttachedDoc;
8145 -- End Bug 4026592
8146 
8147 -- <Complex Work R12 Start>
8148 
8149 -- Calls complex work APIs to determine if a document is a complex work doc.
8150 -- If so, sets the global variable g_is_complex_work_po to 'Y', otherwise 'N'
8151   PROCEDURE setIsComplexWorkPO(
8152                                p_document_id IN NUMBER
8153                                , p_revision_num IN NUMBER DEFAULT NULL
8154                                , p_which_tables IN VARCHAR2 DEFAULT 'MAIN'
8155                                )
8156   IS
8157 
8158   d_progress NUMBER;
8159   d_module VARCHAR2(70) := 'po.plsql.PO_COMMUNICATION_PVT.setIsComplexWorkPO';
8160   l_is_complex BOOLEAN;
8161   l_style_id PO_HEADERS_ALL.style_id%TYPE;
8162 
8163 
8164   BEGIN
8165 
8166     d_progress := 0;
8167 
8168     IF (PO_LOG.d_proc) THEN
8169       PO_LOG.proc_begin(d_module);
8170       PO_LOG.proc_begin(d_module, 'p_document_id', p_document_id);
8171       PO_LOG.proc_begin(d_module, 'p_revision_num', p_revision_num);
8172       PO_LOG.proc_begin(d_module, 'p_which_tables', p_which_tables);
8173     END IF;
8174 
8175 
8176     IF (p_which_tables = 'MAIN') THEN
8177 
8178       d_progress := 10;
8179 
8180       l_is_complex := PO_COMPLEX_WORK_PVT.is_complex_work_po(
8181                                                              p_po_header_id => p_document_id
8182                                                              );
8183 
8184       d_progress := 15;
8185 
8186     ELSE
8187 
8188       d_progress := 20;
8189 
8190       SELECT poha.style_id
8191       INTO l_style_id
8192       FROM po_headers_archive_all poha
8193       WHERE poha.po_header_id = p_document_id
8194         AND poha.revision_num = p_revision_num;
8195 
8196       d_progress := 25;
8197 
8198       l_is_complex := PO_COMPLEX_WORK_PVT.is_complex_work_style(
8199                                                                 p_style_id => l_style_id
8200                                                                 );
8201 
8202       d_progress := 30;
8203 
8204     END IF;
8205 
8206     IF (PO_LOG.d_stmt) THEN
8207       PO_LOG.stmt(d_module, d_progress, 'l_is_complex', l_is_complex);
8208     END IF;
8209 
8210     IF (l_is_complex) THEN
8211       g_is_complex_work_po := 'Y';
8212     ELSE
8213       g_is_complex_work_po := 'N';
8214     END IF;
8215 
8216     d_progress := 50;
8217 
8218     IF (PO_LOG.d_proc) THEN
8219       PO_LOG.stmt(d_module, d_progress, 'g_is_complex_work_po', g_is_complex_work_po);
8220       PO_LOG.proc_end(d_module);
8221     END IF;
8222 
8223   EXCEPTION
8224     WHEN OTHERS THEN
8225       IF (PO_LOG.d_exc) THEN
8226         PO_LOG.exc(d_module, d_progress, SQLCODE || SQLERRM);
8227       END IF;
8228       g_is_complex_work_po := 'N';
8229   END setIsComplexWorkPO;
8230 
8231 
8232   FUNCTION getIsComplexWorkPO RETURN VARCHAR2
8233   IS
8234   BEGIN
8235     RETURN g_is_complex_work_po;
8236   END;
8237 
8238 -- <Complex Work R12 End>
8239 --Bug 4673653 START
8240 /*********************************************************************************
8241 Returns the Inventory Org Id stored in FINANCIALS_SYSTEM_PARAMETERS.
8242 
8243 We do not store this value in a global variable, as it would not change even when the
8244 inventory org is changed.  See bug 4431545 for more info.
8245 **********************************************************************************/
8246   FUNCTION getInventoryOrgId return NUMBER
8247   IS
8248   l_inventory_org_id FINANCIALS_SYSTEM_PARAMETERS.INVENTORY_ORGANIZATION_ID%type;
8249   BEGIN
8250     BEGIN
8251       SELECT INVENTORY_ORGANIZATION_ID
8252       INTO l_inventory_org_id
8253       FROM FINANCIALS_SYSTEM_PARAMETERS;
8254     EXCEPTION
8255       WHEN OTHERS THEN
8256         IF (PO_LOG.d_exc) THEN
8257           PO_LOG.exc('PO_COMMUNICATION_PVT.getInventoryOrgId', 0, SQLCODE || SQLERRM);
8258         END IF;
8259         l_inventory_org_id := null;
8260     END;
8261     return l_inventory_org_id;
8262   END getInventoryOrgId;
8263 --Bug 4673653 END
8264 
8265 -- Package Body
8266 -- Added for bug 6692126
8267 -- The function is intended to return the profile option value as per the
8268 -- submitter context.
8269 -- Incase if we do not get hold of submitter context, then we get the profile
8270 -- from current context.
8271 
8272   FUNCTION get_preparer_profile (p_document_id NUMBER,
8273                                  p_document_type VARCHAR2,
8274                                  p_profile_option VARCHAR2) RETURN VARCHAR2
8275   IS
8276 
8277   x_item_type po_headers_all.wf_item_type%TYPE;
8278   x_item_key po_headers_all.wf_item_key%TYPE;
8279   l_profile_value fnd_profile_option_values.profile_option_value%TYPE;
8280   l_progress VARCHAR2(10);
8281 
8282   l_preparer_user_id NUMBER;
8283   l_preparer_resp_id NUMBER;
8284   l_preparer_resp_appl_id NUMBER;
8285 
8286   l_api_name CONSTANT VARCHAR2(25) := 'Get_Preparer_Profile';
8287 
8288   BEGIN
8289     l_progress := '000';
8290 
8291     IF g_debug_stmt THEN
8292       PO_DEBUG.debug_begin(p_log_head => g_log_head || l_api_name);
8293       PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'p_document_id', p_document_id);
8294       PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'p_document_type', p_document_type);
8295       PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'p_profile_option', p_profile_option);
8296     END IF;
8297 
8298     IF p_document_type = 'RELEASE' THEN
8299       SELECT wf_item_type, wf_item_key
8300         INTO x_item_type, x_item_key
8301         FROM po_releases_all
8302        WHERE po_release_id = p_document_id;
8303 
8304       l_progress := '001';
8305 
8306     ELSE
8307       SELECT wf_item_type, wf_item_key
8308         INTO x_item_type, x_item_key
8309         FROM po_headers_all
8310        WHERE po_header_id = p_document_id;
8311 
8312       l_progress := '002';
8313 
8314     END IF;
8315 
8316     IF g_debug_stmt THEN
8317       PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'x_item_type', x_item_type);
8318       PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'x_item_key', x_item_key);
8319     END IF;
8320 
8321     l_progress := '003';
8322     IF x_item_type IS NOT NULL AND
8323       x_item_key IS NOT NULL AND
8324       PO_APPROVAL_REMINDER_SV.is_active(x_item_type, x_item_key)
8325       THEN
8326       l_progress := '004';
8327       l_preparer_user_id := PO_WF_UTIL_PKG.GetItemAttrNumber
8328       (itemtype => x_item_type,
8329        itemkey => x_item_key,
8330        aname => 'USER_ID');
8331 
8332       l_progress := '005';
8333       l_preparer_resp_id := PO_WF_UTIL_PKG.GetItemAttrNumber
8334       (itemtype => x_item_type,
8335        itemkey => x_item_key,
8336        aname => 'RESPONSIBILITY_ID');
8337 
8338       l_progress := '006';
8339       l_preparer_resp_appl_id := PO_WF_UTIL_PKG.GetItemAttrNumber
8340       (itemtype => x_item_type,
8341        itemkey => x_item_key,
8342        aname => 'APPLICATION_ID');
8343 
8344       IF g_debug_stmt THEN
8345         PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'l_preparer_user_id', l_preparer_user_id);
8346         PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'l_preparer_resp_id', l_preparer_resp_id);
8347         PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'l_preparer_resp_appl_id', l_preparer_resp_appl_id);
8348       END IF;
8349 
8350       l_progress := '007';
8351 
8352       IF Nvl(l_preparer_user_id, - 1) <>  - 1 AND
8353         Nvl(l_preparer_resp_id, - 1) <>  - 1 AND
8354         Nvl(l_preparer_resp_appl_id, - 1) <>  - 1 THEN
8355 
8356         l_progress := '008';
8357 
8358         l_profile_value := FND_PROFILE.VALUE_SPECIFIC(
8359                                                       name => p_profile_option,
8360                                                       user_id => l_preparer_user_id,
8361                                                       responsibility_id => l_preparer_resp_id,
8362                                                       application_id => l_preparer_resp_appl_id);
8363 
8364         l_progress := '009';
8365 
8366       ELSE
8367         l_progress := '010';
8368         FND_PROFILE.GET(p_profile_option, l_profile_value);
8369         l_progress := '011';
8370       END IF;
8371     ELSE
8372       l_progress := '012';
8373       FND_PROFILE.GET(p_profile_option, l_profile_value);
8374       l_progress := '013';
8375     END IF;
8376 
8377     IF g_debug_stmt THEN
8378       PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'l_profile_value', l_profile_value);
8379     END IF;
8380 
8381     RETURN l_profile_value;
8382 
8383   EXCEPTION
8384     WHEN OTHERS THEN
8385       IF g_debug_stmt THEN
8386         PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'IN Exception sqlcode', SQLCODE);
8387       END IF;
8388 
8389       FND_PROFILE.GET(p_profile_option, l_profile_value);
8390 
8391       IF g_debug_stmt THEN
8392         PO_DEBUG.debug_var(g_log_head || l_api_name, l_progress, 'l_profile_value', l_profile_value);
8393         PO_DEBUG.debug_end(g_log_head || l_api_name);
8394       END IF;
8395 
8396       RETURN l_profile_value;
8397 
8398   END get_preparer_profile;
8399 
8400 --Bug5213932 start
8401   FUNCTION get_clob(p_row_id IN ROWID) RETURN CLOB is
8402   l_long LONG;
8403   l_clob CLOB;
8404   BEGIN
8405     SELECT fds.long_text INTO
8406     l_long
8407     FROM
8408     fnd_documents_long_text fds
8409     WHERE fds.ROWID = p_row_id;
8410 
8411     l_clob := l_long;
8412 
8413     RETURN l_clob;
8414   END get_clob;
8415  --Bug5213932 end
8416 
8417 /*Bug4568471/6829381 Below function would determine if the ship-to-location is onetime location*/
8418   function get_oneTime_loc(p_location_id in number) return varchar2 is
8419   l_one_time_location varchar2(3000);
8420   l_location_id number;
8421   begin
8422 
8423     l_one_time_location := FND_PROFILE.VALUE('POR_ONE_TIME_LOCATION');
8424 
8425     if l_one_time_location is not null then
8426       SELECT location_id into l_location_id FROM hr_locations
8427       where location_code = l_one_time_location;
8428     end if;
8429 
8430     if (l_location_id = p_location_id) then
8431       g_is_one_time_location := 'Y';
8432     else
8433       g_is_one_time_location := 'N';
8434     end if;
8435 
8436     return g_is_one_time_location;
8437   end get_oneTime_loc;
8438 
8439 /*Bug4568471/6829381  The below function returns the one time address for the line_location
8440   if the shipment has one time location as an attachment */
8441   function get_oneTime_address(p_line_location_id in number) return CLOB is
8442   --Bug  13712851 - the long_text column is changed to clob
8443   --l_one_time_address_details long;
8444   l_one_time_address_clob clob;
8445   begin
8446 
8447     if (g_is_one_time_location = 'Y') then
8448 
8449       SELECT fds.long_text
8450       INTO
8451        l_one_time_address_clob
8452       FROM
8453       fnd_attached_docs_form_vl fad,
8454       fnd_documents_long_text fds
8455        WHERE entity_name = 'PO_SHIPMENTS' AND
8456        pk1_value = To_Char(p_line_location_id) AND
8457        function_name = 'PO_PRINTPO'
8458        AND fad.media_id = fds.media_id
8459       AND fad.document_description like 'POR%'
8460       AND ROWNUM = 1;
8461     end if;
8462 
8463     --l_one_time_address_clob := l_one_time_address_details;
8464     return l_one_time_address_clob;
8465   end get_oneTime_address;
8466 /*Bug4568471/6829381 end*/
8467 
8468 /*Below function for bug8982745*/
8469 
8470 FUNCTION get_item_num(p_item_id NUMBER,p_org_id NUMBER) RETURN VARCHAR2 is
8471 l_concatenated_segments VARCHAR2(500);
8472 
8473 begin
8474 
8475 select concatenated_segments
8476 into l_concatenated_segments
8477 from mtl_system_items_kfv
8478 where INVENTORY_ITEM_ID = p_item_id
8479 and organization_id = p_org_id;
8480 
8481 return l_concatenated_segments;
8482 
8483 EXCEPTION
8484  WHEN OTHERS THEN
8485   return NULL;
8486 
8487 end get_item_num;
8488 
8489 end PO_COMMUNICATION_PVT;