DBA Data[Home] [Help]

PACKAGE BODY: APPS.PO_INTERFACE_S

Source


1 PACKAGE BODY po_interface_s AS
2 /* $Header: POXBWP1B.pls 120.121.12020000.11 2013/06/05 10:40:03 kuichen ship $*/
3 
4 g_pkg_name    CONSTANT VARCHAR2(30) := 'PO_INTERFACE_S';  --<SharedProc FPJ>
5 g_log_head    CONSTANT VARCHAR2(30) := 'po.plsql.PO_INTERFACE_S.';
6 
7 --<ENCUMBRANCE FPJ>
8 g_dest_type_code_SHOP_FLOOR      CONSTANT
9    PO_DISTRIBUTIONS_ALL.destination_type_code%TYPE
10    := 'SHOP FLOOR'
11    ;
12 
13 -- <INVCONV R12>
14 g_chktype_TRACKING_QTY_IND CONSTANT
15    MTL_SYSTEM_ITEMS_B.TRACKING_QUANTITY_IND%TYPE
16    := 'PS';
17 
18 -- <Unified Catalog R12>
19 g_ATTR_VALUES_NULL_ID CONSTANT NUMBER := PO_ATTRIBUTE_VALUES_PVT.g_ATTR_VALUES_NULL_ID;
20 
21 /* Type declaration for WHO information structure */
22 TYPE who_record_type IS RECORD
23 (user_id           number := 0,
24  login_id          number := 0,
25  resp_id           number := 0);
26 
27 /* Type declaration for  Receiving Controls structure */
28 TYPE rcv_controls_type IS RECORD
29 (enforce_ship_to_location_code  varchar2(25):= null,
30  allow_substitute_receipts_flag varchar2(1),
31  receiving_routing_id           number,
32  qty_rcv_tolerance              number,
33  qty_rcv_exception_code         varchar2(25),
34  days_early_receipt_allowed     number,
35  days_late_receipt_allowed      number,
36  receipt_days_exception_code    varchar2(25));
37 
38 /* Type declaration for Vendor defaults structure */
39 TYPE vendor_defaults_type IS RECORD
40 (vendor_id             number := null,
41  ship_to_location_id   number := null,
42  bill_to_location_id   number := null,
43 -- Bug# 4546121:All columns that referred to the obsolete columns in po_vendors have
44 --              been modified to point to PO_HEADERS_ALL type.
45  ship_via_lookup_code  PO_HEADERS_ALL.ship_via_lookup_code%type := null,
46  fob_lookup_code       PO_HEADERS_ALL.fob_lookup_code%type := null,
47  pay_on_code           varchar2(25) := null,
48  freight_terms_lookup_code PO_HEADERS_ALL.freight_terms_lookup_code%type := null,
49  terms_id              number := null,
50  type_1099             po_vendors.type_1099%type := null,
51  hold_flag             po_vendors.hold_flag%type := null,
52  invoice_currency_code po_vendors.invoice_currency_code%type := null,
53  receipt_required_flag po_vendors.receipt_required_flag%type := null,
54  num_1099              po_vendors.num_1099%type := null,
55  vat_registration_num  po_vendors.vat_registration_num%type := null, --<Bug#4723671>
56  inspection_required_flag po_vendors.inspection_required_flag%type := null,
57  /** bgu, Dec. 7, 98
58   *  Used to default invoice match flag from financial system parameter,
59   *  vendor and vendor site
60   */
61  invoice_match_option    po_vendors.match_option%type := null,
62  shipping_control      PO_VENDOR_SITES.shipping_control%TYPE := NULL -- <INBOUND LOGISTICS FPJ>
63 );
64 
65 /* Type declaration for Item defaults structure */
66 /*Bug 1391523 . Added market price to the record
67 to default market price while autocreating */
68 TYPE item_defaults_type IS RECORD
69 (list_price_per_unit   number:=null,
70  market_price          number:=null,
71  taxable_flag          varchar2(1):=null,
72  unit_meas_lookup_code varchar2(25):=null,
73  inspection_required_flag varchar2(1):=null,
74  receipt_required_flag varchar2(1):=null,
75  invoice_close_tolerance number:=null,
76  receive_close_tolerance number:=null,
77  secondary_uom_code varchar2(3):= null, --<INVCONV R12>
78  grade_control_flag varchar2(1):=null   --<INVCONV R12>
79  );
80 
81 /* Type declaration for  System Parameters structure */
82 TYPE system_parameters_type IS RECORD
83 (currency_code             gl_sets_of_books.currency_code%type,
84  coa_id                    number,
85  po_encumbrance_flag       varchar2(1),
86  req_encumbrance_flag      varchar2(1),
87  sob_id                    number,
88  ship_to_location_id       number,
89  bill_to_location_id       number,
90  fob_lookup_code           financials_system_parameters.fob_lookup_code%type,
91  freight_terms_lookup_code
92                financials_system_parameters.freight_terms_lookup_code%type,
93  terms_id                  number,
94  default_rate_type         po_system_parameters.default_rate_type%type,
95  taxable_flag              varchar2(1),
96  receiving_flag            varchar2(1),
97  enforce_buyer_name_flag   varchar2(1),
98  enforce_buyer_auth_flag   varchar2(1),
99  line_type_id              number := null,
100  manual_po_num_type        po_system_parameters.manual_po_num_type%type,
101  po_num_code               po_system_parameters.user_defined_po_num_code%type,
102  price_type_lookup_code    po_system_parameters.price_type_lookup_code%type,
103  invoice_close_tolerance   number,
104  receive_close_tolerance   number,
105  security_structure_id     number,
106  expense_accrual_code      po_system_parameters.price_type_lookup_code%type,
107  inventory_organization_id number,
108  rev_sort_ordering         number,
109  min_rel_amount            number,
110  notify_blanket_flag       varchar2(1),
111  budgetary_control_flag    varchar2(1),
112  user_defined_req_num_code po_system_parameters.user_defined_req_num_code%type,
113  rfq_required_flag         varchar2(1),
114  manual_req_num_type       po_system_parameters.manual_req_num_type%type,
115  enforce_full_lot_qty  po_system_parameters.enforce_full_lot_quantities%type,
116  disposition_warning_flag    varchar2(1),
117  reserve_at_completion_flag  varchar2(1),
118  user_defined_rcpt_num_code
119                        po_system_parameters.user_defined_receipt_num_code%type,
120  manual_rcpt_num_type        po_system_parameters.manual_receipt_num_type%type,
121  use_positions_flag      varchar2(1),
122  default_quote_warning_delay number,
123  inspection_required_flag    varchar2(1),
124  user_defined_quote_num_code
125                        po_system_parameters.user_defined_quote_num_code%type,
126  manual_quote_num_type po_system_parameters.manual_quote_num_type%type,
127  user_defined_rfq_num_code
128                        po_system_parameters.user_defined_rfq_num_code%type,
129  manual_rfq_num_type       po_system_parameters.manual_rfq_num_type%type,
130  ship_via_lookup_code  financials_system_parameters.ship_via_lookup_code%type,
131  qty_rcv_tolerance number,
132  period_name gl_period_statuses.period_name%type,
133  acceptance_required_flag po_system_parameters.acceptance_required_flag%type);   /* Bug 7518967 : Default Acceptance Required Check ER */
134 
135 --<Unified Catalog R12: Start>
136 TYPE po_line_id_tbl IS TABLE OF PO_LINES_ALL.po_line_id%TYPE INDEX BY PLS_INTEGER;
137 TYPE interface_header_id_tbl IS TABLE OF PO_ATTR_VALUES_INTERFACE.interface_header_id%TYPE INDEX BY PLS_INTEGER;
138 TYPE interface_line_id_tbl IS TABLE OF PO_ATTR_VALUES_INTERFACE.interface_line_id%TYPE INDEX BY PLS_INTEGER;
139 --<Unified Catalog R12: End>
140 
141 /* ecso 5/14/97
142  * Add order by unit_price to interface_cursor.
143  * This is for handling the case when multiple req lines with diff prices
144  * are combined into one PO line. The line_num and shipment_num
145  * are the same for them.
146  */
147 
148 /* iali 08/26/99
149    Added note_to_vendor to the interface cursor
150 */
151 
152 /* Cursor for retrieving information from the interface tables */
153 CURSOR interface_cursor(x_interface_header_id number) IS
154        SELECT phi.interface_header_id interface_header_id,
155               phi.interface_source_code interface_source_code,
156               phi.batch_id batch_id,
157               phi.process_code process_code,
158               phi.action action,
159               phi.document_subtype document_subtype,
160               phi.document_num document_num,
161               phi.po_header_id po_header_id,
162               phi.release_num release_num,
163               phi.agent_id agent_id,
164               phi.vendor_id vendor_id,
165               phi.vendor_site_id vendor_site_id,
166               phi.vendor_contact_id vendor_contact_id,
167 	      phi.vendor_contact vendor_contact,
168               phi.ship_to_location_id ship_to_location_id,
169               phi.bill_to_location_id bill_to_location_id,
170               phi.terms_id terms_id,
171               phi.freight_carrier ship_via_lookup_code,
172               phi.fob fob_lookup_code,
173               phi.pay_on_code pay_on_code,
174               phi.freight_terms freight_terms_lookup_code,
175               phi.creation_date creation_date,
176               phi.created_by created_by,
177               phi.last_update_date last_update_date,
178               phi.last_updated_by last_updated_by,
179               phi.last_update_login last_update_login,
180               phi.revision_num revision_num,
181               phi.print_count print_count,
182               phi.closed_code h_closed_code,
183               phi.frozen_flag frozen_flag,
184               phi.firm_flag h_firm_status_lookup_code,
185               pli.firm_flag l_firm_status_lookup_code,
186               phi.confirming_order_flag confirming_order_flag,
187               phi.acceptance_required_flag acceptance_required_flag,
188               phi.currency_code h_currency_code,
189               phi.rate_type_code h_rate_type,
190               phi.rate_date h_rate_date,
191               phi.rate h_rate,
192               phi.min_release_amount h_min_release_amount,
193               pli.min_release_amount l_min_release_amount,
194               phi.release_date release_date,
195               phi.document_subtype quote_type_lookup_code,
196               phi.vendor_list_header_id vendor_list_header_id,
197 --DPCARD{
198               phi.pcard_id,
199 --DPCARD}
200               pli.interface_line_id interface_line_id,
201               pli.line_num line_num,
202               pli.shipment_num shipment_num,
203               pli.line_location_id line_location_id,
204               pli.requisition_line_id requisition_line_id,
205               pli.line_type_id line_type_id,
206               pli.item_id item_id,
207               pli.category_id category_id,
208               pli.item_revision item_revision,
209               pli.item_description item_description,
210               -- <FPJ Advanced Price START>
211               pli.base_unit_price base_unit_price,
212               -- <FPJ Advanced Price END>
213               pli.unit_price unit_price,
214               pli.price_type price_type_lookup_code,
215               pli.unit_of_measure unit_meas_lookup_code,
216               pli.un_number_id un_number_id,
217               pli.hazard_class_id hazard_class_id,
218               -- pli.contract_num contract_num,   -- <GC FPJ>
219               pli.contract_id contract_id,         -- <GC FPJ>
220               pli.vendor_product_num vendor_product_num,
221               pli.type_1099 type_1099,
222               pli.need_by_date need_by_date,
223               pli.quantity quantity,
224               pli.amount,                                     -- <SERVICES FPJ>
225               pli.negotiated_by_preparer_flag negotiated_by_preparer_flag,
226               pli.closed_code l_closed_code,
227               pli.transaction_reason_code transaction_reason_code,
228               pli.from_header_id from_header_id,
229               pli.from_line_id from_line_id,
230               pli.from_line_location_id from_line_location_id,-- <SERVICES FPJ>
231               pli.receipt_required_flag receipt_required_flag,
232 --DWR4{
233               pli.tax_status_indicator,
234 --DWR4}
235               pli.tax_code_id,
236         pli.note_to_vendor,
237         --togeorge 09/27/2000
238         --Bug#1433282
239         --added note to receiver and oke columns
240         pli.note_to_receiver,
241         pli.oke_contract_header_id,
242         pli.oke_contract_version_id,
243         pdi.oke_contract_line_id,
244         pdi.oke_contract_deliverable_id,
245 -- adding process related columns
246 -- start of 1548597
247               pli.secondary_unit_of_measure,
248               pli.secondary_quantity,
249               pli.preferred_grade,
250 -- end of 1548597
251         --<SOURCING TO PO FPH START>
252         phi.amount_agreed,          --Bug# 2288408
253         phi.effective_date,         --Bug# 2288408
254         phi.expiration_date,        --Bug# 2288408
255               pli.committed_amount,     --Bug# 2288408
256               pli.promised_date promised_date,
257               pli.auction_header_id,
258               pli.auction_line_number,
259         pli.auction_display_number,
260               pli.bid_number,
261               pli.bid_line_number,
262         pli.orig_from_req_flag,
263             pdi.charge_account_id,
264         pdi.accrual_account_id,
265         pdi.variance_account_id,
266         pdi.encumbered_flag,
267         pdi.budget_account_id,
268         --<SOURCING TO PO FPH END>
269         --<RENEG BLANKET FPI START>
270         phi.amount_limit,
271               phi.global_agreement_flag,
272               pli.ship_to_location_id line_ship_to_loc_id,
273               pli.ship_to_organization_id line_ship_to_org_id,
274               pli.price_discount,
275               pli.effective_date line_effective_date,
276               pli.expiration_date line_expiration_date,
277               pli.shipment_type,
278               --Bug #2715037 :Need to capture this coming from Sourcing
279               pli.price_break_lookup_code,
280               --<RENEG BLANKET FPI END>
281         pdi.destination_type_code destination_type_code,
282         pdi.deliver_to_location_id deliver_to_location_id,
283         pdi.destination_organization_id destination_organization_id,
284               pli.vmi_flag,   --  VMI FPH
285               pli.drop_ship_flag,   --  <DropShip FPJ>
286         --<CONSUME REQ DEMAND FPI>
287         phi.consume_req_demand_flag,
288               pli.consigned_flag,      -- CONSIGNED FPI
289               phi.shipping_control,    -- <INBOUND LOGISTICS FPJ>
290               pli.supplier_ref_number, --<CONFIG_ID FPJ>
291               pli.job_id,                                     -- <SERVICES FPJ>
292               pli.contractor_first_name,                      -- <SERVICES FPJ>
293               pli.contractor_last_name,                       -- <SERVICES FPJ>
294         pli.transaction_flow_header_id,                 -- <Shared Proc. FPJ>
295         phi.org_id                                      -- <R12 MOAC>
296               --<Complex Work R12 Start>
297             , phi.style_id              style_id
298             , pli.retainage_rate        retainage_rate
299             , pli.max_retainage_amount  max_retainage_amount
300             , pli.progress_payment_rate progress_payment_rate
301             , pli.recoupment_rate       recoupment_rate
302             , pli.advance_amount        advance_amount
303             , NVL(pli.line_loc_populated_flag, 'N') poll_interface_pop_flag
304             , NVL2(pli.advance_amount, 'Y', 'N') has_advance_flag
305               --<Complex Work R12 End>
306               --<Unified Catalog R12 Begin: Bug#4656615>
307             , phi.created_language    created_language
308             , phi.cpa_reference       cpa_reference
309             , pli.ip_category_id      ip_category_id
310             , pli.supplier_part_auxid supplier_part_auxid
311             , pli.catalog_name        catalog_name
312               --<Unified Catalog R12 End>
313          FROM po_headers_interface phi,
314               po_lines_interface pli,
315         po_distributions_interface pdi
316         WHERE phi.interface_header_id = pli.interface_header_id
317     AND pli.interface_line_id = pdi.interface_line_id
318           AND phi.interface_header_id = x_interface_header_id
319     AND pdi.interface_distribution_id =
320     (SELECT min(pdi2.interface_distribution_id)
321            FROM   po_distributions_interface pdi2
322            WHERE  pdi2.interface_line_id = pli.interface_line_id)
323      ORDER BY pli.line_num,
324         --<RENEG BLANKET FPI>
325               nvl(pli.shipment_num,0),
326               pli.unit_price;
327 
328 /* Global variable declarations */
329 who who_record_type;
330 
331 vendor vendor_defaults_type;
332 
333 item item_defaults_type;
334 
335 params system_parameters_type;
336 
337 rc rcv_controls_type;
338 
339 interface interface_cursor%rowtype;
340 --<SOURCING TO PO FPH START>
341 g_sourcing_errorcode number;
342 g_interface_source_code varchar2(25);
343 --<SOURCING TO PO FPH END>
344 
345 g_mode              po_headers_interface.action%type := null;
346 g_group_code        po_headers_interface.group_code%type := null;
347 g_document_subtype  po_headers_interface.document_subtype%type := null;
348 g_po_release_id     number := null;
349 g_document_type     varchar2(25) := null;
350 g_number_records_processed number;
351 g_purchasing_ou_id  PO_HEADERS_ALL.org_id%TYPE;  --<Shared Proc FPJ>
352 g_hdr_requesting_ou_id  PO_HEADERS_ALL.org_id%TYPE;  --<Shared Proc FPJ>
353 g_rate_for_req_fields NUMBER;  --<Shared Proc FPJ>
354 g_line_requesting_ou_id PO_REQUISITION_LINES_ALL.org_id%TYPE; --<Sourcing 11.5.10+>
355 
356 /* Global variable to hold number of req lines
357 ** in the po_lines_interface table. Thie determines
358 ** if we copy project_id, task_id from req to rfq
359 */
360 g_req_lines_to_process  number:=0;
361 
362 -- Bug 2875346 start.
363 --< Bug 3210331 Start >
364 -- Debugging booleans used to bypass logging when turned off
365 g_debug_stmt  CONSTANT BOOLEAN := PO_DEBUG.is_debug_stmt_on;
366 g_debug_unexp CONSTANT BOOLEAN := PO_DEBUG.is_debug_unexp_on;
367 --< Bug 3210331 End >
368 
369 g_calculate_tax_flag VARCHAR2(1); --<eTax Integration Enhancement R12>
370 
371 /*===========================================================================*/
372 /*======================== SPECIFICATIONS (PRIVATE) =========================*/
373 /*===========================================================================*/
374 
375 -- Private function to check if a req line has a one-time location
376 FUNCTION has_one_time_location(p_req_line_id IN NUMBER)
377     RETURN BOOLEAN;
378 
379 -- Bug 2875346 end.
380 
381 /*<Bug 14608120 Autocreate GE ER>
382  Private function to check whether the Req has been created from WIP.*/
383 FUNCTION is_wip_enabled(p_req_line_id IN NUMBER)
384     RETURN BOOLEAN;
385 
386 /* Private Procedure prototypes */
387 PROCEDURE get_system_defaults;
388 
389 /* bgu, Dec. 10, 98 */
390 PROCEDURE get_invoice_match_option(x_vendor_id    IN number,
391          x_vendor_site_id IN number,
392          x_invoice_match_option OUT NOCOPY varchar2);
393 
394 PROCEDURE wrapup(x_interface_header_id IN number);
395 
396 PROCEDURE update_shipment(x_interface_header_id IN NUMBER,
397         x_po_shipment_num IN NUMBER,
398         x_po_line_num IN NUMBER,
399         x_requisition_line_id IN NUMBER,
400         x_po_line_id IN NUMBER,
401         x_document_num IN VARCHAR2,
402         x_release_num IN NUMBER,
403                           x_create_new_line IN VARCHAR2,  -- GA FPI
404                           x_row_id IN VARCHAR2 default null);
405 
406 PROCEDURE group_interface_lines(
407   x_interface_header_id IN number
408 , p_is_complex_work_po  IN BOOLEAN
409 , p_group_shipments     IN VARCHAR2  DEFAULT NULL --<Bug 14608120 Autocreate GE ER>
410 );
411 
412 -- <Complex Work R12>: Added p_is_complex_work_po parameter
413 PROCEDURE setup_interface_tables(
414   x_interface_header_id  IN             NUMBER
415 , x_document_id          IN OUT NOCOPY  NUMBER
416 , p_is_complex_work_po   IN             BOOLEAN
417 );
418 
419 -- <Complex Work R12>: Added p_is_complex_work_po parameter
420 PROCEDURE create_line(
421   x_interface_header_id IN NUMBER
422 , p_is_complex_work_po  IN BOOLEAN
423 );
424 
425 PROCEDURE create_shipment(
426   x_po_line_id IN number,
427   p_rate_for_req_fields IN NUMBER, -- <ACHTML R12>
428   x_line_location_id IN OUT NOCOPY number,
429   p_outsourced_assembly IN NUMBER --<SHIKYU R12>
430 );
431 
432 PROCEDURE create_distributions(
433   x_po_line_id IN number,
434   x_line_location_id IN number,
435   x_po_release_id IN number,
436   p_rate_for_req_fields IN NUMBER --<ACHTML R12>
437 );
438 
439 -- <Complex Work R12 Start>
440 PROCEDURE create_payitems(
441   p_interface_line_id IN         NUMBER
442 , p_po_line_id        IN         NUMBER
443 , p_precision         IN         NUMBER
444 , p_ext_precision     IN         NUMBER
445 , x_line_location_id  OUT NOCOPY NUMBER
446 , x_line_loc_id_tbl   OUT NOCOPY po_tbl_number
447 );
448 
449 PROCEDURE create_payitem_dists(
450   p_po_line_id         IN NUMBER
451 , p_req_line_id        IN NUMBER
452 , p_interface_line_id  IN NUMBER
453 , p_precision          IN NUMBER
454 , p_ext_precision      IN NUMBER
455 );
456 
457 PROCEDURE create_po(x_interface_header_id IN number,
458         x_document_id IN OUT NOCOPY number
459            ,p_sourcing_k_doc_type  IN VARCHAR2 DEFAULT NULL --<CONTERMS FPJ>
460            ,p_conterms_exist_flag  IN VARCHAR2 DEFAULT 'N'  --<CONTERMS FPJ>
461      ,p_document_creation_method IN VARCHAR2 DEFAULT NULL--<DBI FPJ>
462 	 ,p_group_shipments IN VARCHAR2 DEFAULT NULL  --<Bug 14608120 Autocreate GE ER>
463          );
464 
465 PROCEDURE create_rfq(x_interface_header_id IN number,
466          x_document_id IN OUT NOCOPY number);
467 
468 PROCEDURE get_shipment_num(x_need_by_date IN DATE,
469          x_deliver_to_location_id IN NUMBER,
470          x_destination_org_id IN NUMBER,
471          x_po_line_id IN NUMBER,
472          x_po_line_num IN NUMBER,
473          x_requisition_line_id IN NUMBER,
474                x_interface_header_id IN NUMBER,
475          x_po_shipment_num IN OUT NOCOPY NUMBER,
476          --togeorge 09/27/2000
477          x_note_to_receiver IN varchar2,
478 -- start of 1548597
479                            x_preferred_grade IN VARCHAR2,
480 -- end of 15485097
481                            x_vmi_flag        IN VARCHAR2,         --  VMI FPH
482                            x_consigned_flag IN VARCHAR2   ,       -- CONSIGNED FPI
483                            x_drop_ship_flag IN VARCHAR2,          --  <DropShip FPJ>
484                            x_create_new_line OUT NOCOPY VARCHAR2 ,   -- GA FPI
485 						   x_group_shipments IN VARCHAR2 DEFAULT NULL  -- <Bug 14608120 Autocreate GE ER>
486 						   ) ;
487 
488 -- This procedure calculate the global attribute value based on the document
489 -- type, level, and id.  This is just a hook to the actual function.
490 -- Parameter:
491 -- document_type: 'STANDARD', 'BLANKET', 'PLANNED', 'RELEASES'
492 -- level_type: 'HEADER', 'LINE', 'SHIPMENT', 'DISTRIBUTION', 'DOCUMENT'
493 -- level_id: ID of the relevant level: po_header_id, po_line_id,...
494 
495 procedure calculate_local(document_type varchar2,
496                           level_type    varchar2,
497                           level_id      number
498 );
499 
500 --<RENEG BLANKET FPI START>
501 PROCEDURE create_price_break(p_po_line_id IN number,
502                           x_line_location_id OUT NOCOPY number,
503                   p_outsourced_assembly IN NUMBER); --<SHIKYU R12>
504 --<RENEG BLANKET FPI END>
505 
506 FUNCTION get_ship_to_loc(p_deliver_to_loc_id IN NUMBER)
507 RETURN NUMBER;
508 
509 --<CONFIG_ID FPJ START>
510 
511 FUNCTION validate_interface_records (
512   p_interface_header_id IN PO_HEADERS_INTERFACE.interface_header_id%TYPE
513 ) RETURN BOOLEAN;
514 
515 FUNCTION validate_config_id (
516   p_interface_header_id IN PO_HEADERS_INTERFACE.interface_header_id%TYPE
517 ) RETURN BOOLEAN;
518 
519 --<CONFIG_ID FPJ END>
520 
521 --<Shared Proc FPJ START>
522 PROCEDURE get_rate_for_req_price(
523   p_requesting_ou_id IN NUMBER, -- <ACHTML R12>
524   p_purchasing_ou_id IN NUMBER, -- <ACHTML R12>
525   p_po_currency_code IN VARCHAR2,
526   p_rate_type        IN VARCHAR2,
527   p_rate_date        IN DATE,
528   x_rate             OUT NOCOPY NUMBER
529 );
530 --<Shared Proc FPJ END>
531 
532 PROCEDURE do_currency_conversion                               -- <BUG 3322948>
533 (   p_order_type_lookup_code   IN              VARCHAR2
534 ,   p_interface_source_code    IN              VARCHAR2
535 ,   p_rate                     IN              NUMBER
536 ,   p_po_currency_code         IN              VARCHAR2
537 ,   p_requisition_line_id      IN              NUMBER
538 ,   x_quantity                 IN OUT NOCOPY   NUMBER
539 ,   x_unit_price               IN OUT NOCOPY   NUMBER
540 ,   x_base_unit_price          IN OUT NOCOPY   NUMBER --bug 3401653
541 ,   x_amount                   IN OUT NOCOPY   NUMBER
542 );
543 
544 /*===========================================================================*/
545 /*============================ BODY (PUBLIC) ================================*/
546 /*===========================================================================*/
547 
548 --<SOURCING TO PO FPH START>
549 PROCEDURE create_documents(x_batch_id     IN     number,
550          x_document_id  IN OUT NOCOPY number,
551          x_number_lines   IN OUT NOCOPY number,
552          p_document_creation_method IN VARCHAR2,  --<DBI FPJ>
553          p_orig_org_id                IN               NUMBER DEFAULT NULL,    -- <R12 MOAC>
554          p_group_shipments            IN               VARCHAR2  DEFAULT NULL --<Bug 14608120 Autocreate GE ER>
555 		 ) IS
556   x_document_number po_headers.segment1%type;
557   x_errorcode   number;
558   l_progress VARCHAR2(3) := '000';                          --< Bug 3210331 >
559   l_api_name VARCHAR2(30) := 'create_documents(wrapper1)';  --< Bug 3210331 >
560 BEGIN
561   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
562       PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
563   END IF;
564 
565   create_documents(x_batch_id => x_batch_id,
566        x_document_id => x_document_id,
567        x_number_lines => x_number_lines,
568        x_document_number => x_document_number,
569        x_errorcode => x_errorcode,
570        p_document_creation_method => p_document_creation_method, --<DBI FPJ>
571                    p_orig_org_id => p_orig_org_id,                 -- <R12 MOAC>
572 				   p_group_shipments => p_group_shipments  --<Bug 14608120 Autocreate GE ER>
573        );
574 
575   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
576       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
577                           p_token    => l_progress,
578                           p_message  => 'error code: '||x_errorcode);
579       PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
580   END IF;
581 
582 EXCEPTION
583   WHEN OTHERS THEN
584      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
585          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
586                             p_progress => l_progress);
587      END IF;
588      po_message_s.sql_error('CREATE_DOCUMENTS wrapper',l_progress,sqlcode);
589      raise;
590 END create_documents;
591 --<SOURCING TO PO FPH END>
592 
593 /*============================================================================
594      Name: CREATE_DOCUMENTS
595      DESC: Create/Add to document from requisition data in the PO_HEADERS,LINES
596            and DISTRIBUTION interface tables.
597      ARGS: IN : x_batch_id IN number
598 --<CONTERMS FPJ START>
599            IN: p_sourcing_k_doc_type   IN   VARCHAR2 - The document type that Sourcing
600                              has seeded in Contracts.
601                              Deafault null
602           IN: p_conterms_exist_flag   IN    VARCHAR2 - Whether the sourcing document
603                               has contract template attached.
604                               Deafult - N
605 --<CONTERMS FPJ END>
606      ALGR:
607 
608    ==========================================================================*/
609 PROCEDURE create_documents(x_batch_id     IN     number,
610          x_document_id  IN OUT NOCOPY number,
611          x_number_lines   IN OUT NOCOPY number,
612          --<SOURCING TO PO FPH>
613          x_document_number  IN OUT NOCOPY    varchar2,
614          x_errorcode      OUT NOCOPY    number
615               ,p_sourcing_k_doc_type  IN VARCHAR2 --<CONTERMS FPJ>
616               ,p_conterms_exist_flag  IN VARCHAR2 --<CONTERMS FPJ>
617          ,p_document_creation_method IN VARCHAR2 --<DBI FPJ>
618               ,p_orig_org_id                IN               NUMBER DEFAULT NULL   -- <R12 MOAC>
619 			  ,p_group_shipments  IN VARCHAR2  DEFAULT NULL  --<Bug 14608120 Autocreate GE ER>
620      ) IS
621 --<Shared Proc FPJ Start>
622 l_api_name                  VARCHAR2(30) := 'create_documents(wrapper2)'; --< Bug 3210331 >
623 l_return_status             VARCHAR2(1);
624 l_msg_count                 NUMBER;
625 l_msg_data                  VARCHAR2(2000);
626 l_req_operating_unit_id     PO_SYSTEM_PARAMETERS_ALL.org_id%TYPE;
627 l_purch_operating_unit_id   PO_SYSTEM_PARAMETERS_ALL.org_id%TYPE;
628 l_progress VARCHAR2(3) := '000';                            --< Bug 3210331 >
629 
630 BEGIN
631     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
632         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
633     END IF;
634 
635     create_documents (p_api_version             => 1.0,
636                       x_return_status           => l_return_status,
637                       x_msg_count               => l_msg_count,
638                       x_msg_data                => l_msg_data,
639                       p_batch_id                => x_batch_id,
640                       p_req_operating_unit_id   => l_req_operating_unit_id,
641                       p_purch_operating_unit_id => l_purch_operating_unit_id,
642                       x_document_id             => x_document_id,
643                       x_number_lines            => x_number_lines,
644                       x_document_number         => x_document_number
645                      ,p_sourcing_k_doc_type     => p_sourcing_k_doc_type--<CONTERMS FPJ>
646                      ,p_conterms_exist_flag     => p_conterms_exist_flag--<CONTERMS FPJ>
647          ,p_document_creation_method => p_document_creation_method --<DBI FPJ>
648                      ,p_orig_org_id              => p_orig_org_id                 -- <R12 MOAC>
649 					 ,p_group_shipments          => p_group_shipments  --<Bug 14608120 Autocreate GE ER>
650     );
651 
652     IF (l_return_status = FND_API.g_ret_sts_success
653         AND x_number_lines >0 AND x_document_id is NOT NULL) --<Bug 3268483>
654     THEN
655          x_errorcode := 1;
656     ELSIF g_sourcing_errorcode = 2 THEN
657          x_errorcode := 2;
658     ELSE
659          x_errorcode := 3;
660     END IF;
661 
662     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
663         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
664                             p_token    => l_progress,
665                             p_message  => 'error code: '||x_errorcode);
666         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
667     END IF;
668 
669 EXCEPTION
670     WHEN OTHERS THEN
671         IF g_debug_unexp THEN          --< Bug 3210331: use proper debugging >
672             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
673                                p_progress => l_progress);
674         END IF;
675         PO_MESSAGE_S.sql_error (routine    => 'CREATE_DOCUMENTS',
676                                 location   => l_progress,
677                                 error_code => SQLCODE
678         );
679         RAISE;
680 
681 END create_documents;
682 
683 -- CLM changes Start
684 PROCEDURE create_documents (
685     p_api_version                IN               NUMBER,
686     x_return_status              OUT    NOCOPY    VARCHAR2,
687     x_msg_count                  OUT    NOCOPY    NUMBER,
688     x_msg_data                   OUT    NOCOPY    VARCHAR2,
689     p_batch_id                   IN               NUMBER,
690     p_req_operating_unit_id      IN               NUMBER,
691     p_purch_operating_unit_id    IN               NUMBER,
692     x_document_id                IN OUT NOCOPY    NUMBER,
693     x_number_lines               OUT    NOCOPY    NUMBER,
694     x_document_number            OUT    NOCOPY    VARCHAR2
695    ,p_sourcing_k_doc_type        IN               VARCHAR2 DEFAULT NULL--<CONTERMS FPJ>
696    ,p_conterms_exist_flag        IN               VARCHAR2 DEFAULT 'N' --<CONTERMS FPJ>
697    ,p_document_creation_method   IN		  VARCHAR2 DEFAULT NULL --<DBI FPJ>
698    ,p_orig_org_id                IN               NUMBER DEFAULT NULL    -- <R12 MOAC>
699    ,x_draft_id                   OUT   NOCOPY NUMBER
700    ,x_error_code_tbl             IN OUT   NOCOPY PO_TBL_VARCHAR2000 --CLM Phase 2
701    ,p_group_shipments  IN VARCHAR2  DEFAULT NULL
702 )
703 IS
704 
705 l_api_name                  VARCHAR2(30) := 'create_documents(CLM wrapper)';
706 l_progress VARCHAR2(3) := '000';
707 
708 BEGIN
709     l_progress := '010';
710     IF g_debug_stmt THEN
711         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
712     END IF;
713 
714     /*CLM Phase 2Autocreate grouping
715     Initialising variable*/
716     x_error_code_tbl := PO_TBL_VARCHAR2000();
717     PO_AUTOCREATE_PARAMS.g_error_code_tbl := PO_TBL_VARCHAR2000();
718     /*CLM Phase 2Autocreate grouping*/
719 
720       l_progress := '020';
721       create_documents (
722                           p_api_version   =>  p_api_version
723                          ,x_return_status =>  x_return_status
724                          ,x_msg_count     => x_msg_count
725                          ,x_msg_data      => x_msg_data
726                          ,p_batch_id      => p_batch_id
727                          ,p_req_operating_unit_id => p_req_operating_unit_id
728                          ,p_purch_operating_unit_id  => p_purch_operating_unit_id
729                          ,x_document_id     => x_document_id
730                          ,x_number_lines    => x_number_lines
731                          ,x_document_number => x_document_number
732                          ,p_sourcing_k_doc_type   => p_sourcing_k_doc_type
733                          ,p_conterms_exist_flag   => p_conterms_exist_flag
734                          ,p_document_creation_method => p_document_creation_method
735                          ,p_orig_org_id              => p_orig_org_id
736 						 ,p_group_shipments			 => p_group_shipments
737                          );
738 
739          l_progress := '030';
740          x_draft_id := po_autocreate_params.g_draft_id;
741 
742          /*CLM Phase 2 Autocreate Grouping.
743          Error handling : initialize the error table
744          */
745 
746           x_error_code_tbl :=  PO_AUTOCREATE_PARAMS.g_error_code_tbl;
747 
748         /*CLM Phase 2 Ends*/
749 
750          IF g_debug_stmt THEN
751                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
752                                             p_token    => l_progress,
753                                             p_message  =>   'x_draft_id : ' || x_draft_id
754                                                           ||' x_document_number : '||x_document_number
755                                                           ||' x_return_status : '|| x_return_status
756                                                           ||' x_document_id : '||x_document_id
757                                                           ||' x_number_lines : '|| x_number_lines
758                                            );
759 
760          END IF;
761 
762 
763     IF g_debug_stmt THEN
764         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
765     END IF;
766 
767 EXCEPTION
768     WHEN OTHERS THEN
769         IF g_debug_unexp THEN
770             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
771                                p_progress => l_progress);
772         END IF;
773         PO_MESSAGE_S.sql_error (routine    => 'CREATE_DOCUMENTS_CLM',
774                                 location   => l_progress,
775                                 error_code => SQLCODE
776         );
777         RAISE;
778 END create_documents;
779 
780 
781 
782 -------------------------------------------------------------------------------
783 --Start of Comments
784 --Name: create_documents
785 --Pre-reqs:
786 --  None
787 --Modifies:
788 --  Transaction tables for the requested document
789 --Locks:
790 --  None.
791 --Function:
792 --  Creates/Adds To a Document. Can create Purchase Orders, Blankets, Global Agreements,
793 --  RFQs, Consumption Advice among others
794 --Parameters:
795 --IN:
796 --p_api_version
797 --  API standard IN parameter
798 --p_batch_id
799 --  The id that will be used to identify the rows in the interface table. The unique identifier
800 --  for the all the documents to be created. It will be the same as interface_header_id
801 --  as we always create 1 doc at a time.
802 --p_req_operating_unit_id
803 --   The Operating Unit of Requisition raising Operating Unit, or the current Operating Unit
804 --   of the environment if called from Oracle Sourcing 11.5.10+ and beyond
805 --p_purch_operating_unit_id
806 --   The Operating Unit where the PO is being created
807 --p_sourcing_k_doc_type   --<CONTERMS FPJ>
808 --   The document type that Sourcing has seeded in Contracts. --<CONTERMS FPJ>
809 --   Valid only When called from Sourcing --<CONTERMS FPJ>
810 --   Default value Null  --<CONTERMS FPJ>
811 --p_conterms_exist_flag   --<CONTERMS FPJ>
812 --   Whether the sourcing document has contract template attached. --<CONTERMS FPJ>
813 --   Valid only When called from Sourcing--<CONTERMS FPJ>
814 --   Default value N  --<CONTERMS FPJ>
815 --INOUT:
816 --x_document_id
817 --   Used as IN  for document id to ADD to N/A for sourcing.
818 --   Used as OUT for returning the id of the document created.
819 --OUT:
820 --x_return_status
821 --   The standard OUT parameter giving return status of the API call.
822 --x_msg_count
823 --   The count of number of messages added to the message list in this call
824 --x_msg_data
825 --   If the count is 1 then x_msg_data contains the message returned
826 --x_number_lines
827 --   Returns the number of interface records processed
828 --x_document_number
829 --   Returns the PO/Blanket number when for sourcing, null for existing autocreate.
830 --Notes:
831 --   None
832 --Testing:
833 --  None
834 --End of Comments
835 -------------------------------------------------------------------------------
836 PROCEDURE create_documents (
837     p_api_version                IN               NUMBER,
838     x_return_status              OUT    NOCOPY    VARCHAR2,
839     x_msg_count                  OUT    NOCOPY    NUMBER,
840     x_msg_data                   OUT    NOCOPY    VARCHAR2,
841     p_batch_id                   IN               NUMBER,
842     p_req_operating_unit_id      IN               NUMBER,
843     p_purch_operating_unit_id    IN               NUMBER,
844     x_document_id                IN OUT NOCOPY    NUMBER,
845     x_number_lines               OUT    NOCOPY    NUMBER,
846     x_document_number            OUT    NOCOPY    VARCHAR2
847    ,p_sourcing_k_doc_type        IN               VARCHAR2 --<CONTERMS FPJ>
848    ,p_conterms_exist_flag        IN               VARCHAR2 --<CONTERMS FPJ>
849    ,p_document_creation_method   IN               VARCHAR2 --<DBI FPJ>
850    ,p_orig_org_id                IN               NUMBER DEFAULT NULL    -- <R12 MOAC>
851    ,p_group_shipments            IN               VARCHAR2  DEFAULT NULL --<Bug 14608120 Autocreate GE ER>
852 ) IS
853 --<Shared Proc FPJ End>
854     x_errorcode NUMBER;  --<temp added>
855     x_interface_header_id number:= 0;
856     x_unique_document_num boolean;
857     x_release_number  number;   -- CONSIGNED FPI
858 
859     l_api_name    CONSTANT VARCHAR2(30) := 'create_documents';
860     --<Shared Proc FPJ Start>
861     l_api_version     CONSTANT NUMBER := 1.0;
862     l_original_operating_unit_id    NUMBER;
863     l_org_context_changed    VARCHAR2(1) := 'N';
864     l_req_operating_unit_id     PO_SYSTEM_PARAMETERS_ALL.org_id%TYPE;
865     l_purch_operating_unit_id   PO_SYSTEM_PARAMETERS_ALL.org_id%TYPE;
866 
867     --<Shared Proc FPJ End>
868     l_progress VARCHAR2(3) := '000';            --< Bug 3210331 >
869 
870     -- CLM Autocreate
871     l_style_id                      PO_HEADERS_INTERFACE.style_id%TYPE;
872     l_clm_enabled_flag              VARCHAR2(1):= 'N';
873     l_change_process_type           PO_DOC_STYLE_HEADERS.change_process_type%TYPE;
874     l_is_clm_flow                   VARCHAR2(1):= 'N';
875 
876 BEGIN
877     --<Shared Proc FPJ Start>
878       -- Standard Start of API savepoint
879       SAVEPOINT create_documents_pvt;
880 
881     -- Standard call to check for call compatibility.
882     IF NOT FND_API.compatible_api_call (
883                p_current_version_number => l_api_version,
884                p_caller_version_number  => p_api_version,
885                p_api_name               => l_api_name,
886                p_pkg_name               => g_pkg_name
887            )
888     THEN
889         RAISE FND_API.g_exc_unexpected_error;
890     END IF;
891 
892     l_progress := '010';
893     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
894         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
895     END IF;
896 
897     /* For now a batch has only one header, so get the document header id */
898     SELECT min(phi.interface_header_id)
899       INTO x_interface_header_id
900       FROM po_headers_interface phi
901      WHERE phi.batch_id = p_batch_id;
902 
903     /* Getting the style_id of the target document */
904     SELECT phi.style_id
905       INTO l_style_id
906       FROM po_headers_interface phi
907      WHERE phi.interface_header_id=x_interface_header_id;
908 
909    l_progress := '015';
910    IF g_debug_stmt THEN
911                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
912                                             p_token    => l_progress,
913                                             p_message  => 'Before checking for CLM Flow : Doc Style Id : '||l_style_id);
914    END IF;
915 
916 
917    -- Determines which flow to use
918     IF l_style_id IS NOT NULL THEN
919 
920          /* Check if the doc style is clm enabled */
921 
922          SELECT nvl(pdsh.clm_flag,'N'),
923                 Nvl(pdsh.change_process_type,'CHANGE_ORDER')
924            INTO l_clm_enabled_flag,
925                 l_change_process_type
926            FROM po_doc_style_headers pdsh
927           WHERE pdsh.style_id=l_style_id;
928 
929           l_progress := '016';
930           IF g_debug_stmt THEN
931                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
932                                                     p_token    => l_progress,
933                                                     p_message  => 'Inside checking for CLM Flow : l_clm_enabled_flag :'||l_clm_enabled_flag);
934 
935                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
936                                                     p_token    => l_progress,
937                                                     p_message  => 'Inside checking for CLM Flow : l_change_process_type :'||l_change_process_type);
938           END IF;
939 
940 
941         -- CLM Flow/ Modification Flow
942         IF l_clm_enabled_flag = 'Y' THEN
943                  l_is_clm_flow := 'Y';
944 
945                  l_progress := '017';
946                  IF g_debug_stmt THEN
947                                       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
948                                                           p_token    => l_progress,
949                                                           p_message  => 'Is CLM Flow :'||l_is_clm_flow);
950                  END IF;
951         END IF;
952     END IF;
953 
954 
955    -- CLM AutoCreate changes
956    -- CLM Flow check
957     IF l_is_clm_flow = 'Y' THEN
958 
959                    PO_AUTOCREATE_PARAMS.g_is_clm_po := l_clm_enabled_flag;
960                    PO_AUTOCREATE_PVT.create_po(x_interface_header_id
961                                               ,x_document_id
962                                               ,p_sourcing_k_doc_type
963                                               ,p_conterms_exist_flag
964                                               ,p_document_creation_method
965                                               ,p_req_operating_unit_id
966                                               ,p_purch_operating_unit_id
967                                               ,p_orig_org_id
968                                               );
969 
970                    x_number_lines := PO_AUTOCREATE_PARAMS.g_number_records_processed;
971                    g_document_subtype := PO_AUTOCREATE_PARAMS.g_document_subtype;
972                    g_interface_source_code := PO_AUTOCREATE_PARAMS.g_interface_source_code;
973                    l_original_operating_unit_id := PO_AUTOCREATE_PARAMS.g_original_operating_unit_id;
974                    l_org_context_changed := PO_AUTOCREATE_PARAMS.g_org_context_changed;
975 
976                    l_progress := '018';
977                    IF g_debug_stmt THEN
978                                           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
979                                                               p_token    => l_progress,
980                                                               p_message  => 'After create_po in CLM flow : Number of lines processed : '||x_number_lines);
981                    END IF;
982 
983                    COMMIT;
984 
985     ELSE    -- Non CLM/ Non Modification Flow
986 
987                     -- Bug 4778867:If p_orig_org_id is not specified get the current
988                     -- Operating Unit Info from the Environment
989                     --<R12 MOAC START>
990                     IF p_orig_org_id IS NOT NULL THEN
991                       l_original_operating_unit_id := p_orig_org_id;
992                     ELSE
993                       l_original_operating_unit_id := po_moac_utils_pvt.get_current_org_id;
994                     END IF;
995                     --<R12 MOAC END>
996 
997                     l_progress := '020';
998 
999                     -- If requesting Org ID is not passed set it to  current operating unit id
1000                     IF (p_req_operating_unit_id IS NULL) THEN
1001                         l_req_operating_unit_id := l_original_operating_unit_id;
1002                     ELSE
1003                         l_req_operating_unit_id := p_req_operating_unit_id;
1004                     END IF;
1005 
1006                     -- If purchasing Org ID is not passed then create PO in Req raising Operating Unit
1007                     IF (p_purch_operating_unit_id IS NULL) THEN
1008                         l_purch_operating_unit_id := l_req_operating_unit_id;
1009                     ELSE
1010                         l_purch_operating_unit_id := p_purch_operating_unit_id;
1011                     END IF;
1012 
1013                     --Set the context of Purchasing Operating Unit
1014                     -- <ACHTML R12 START>
1015                     -- Modified if condition to also return true if l_purch_operating_unit_id
1016                     -- is not null but l_req_operating_unit_id is null.
1017                     IF (l_purch_operating_unit_id IS NOT NULL
1018                   AND (l_req_operating_unit_id IS NULL
1019                       OR l_purch_operating_unit_id <> l_req_operating_unit_id))
1020                     THEN
1021                         l_org_context_changed := 'Y';
1022                         PO_MOAC_UTILS_PVT.set_org_context(l_purch_operating_unit_id) ;       -- <R12 MOAC>
1023                     END IF;
1024 
1025                     -- Initialize API return status to success
1026                     x_return_status := FND_API.G_RET_STS_SUCCESS;
1027 
1028                     -- Initialize the Operating Units
1029                     g_purchasing_ou_id := l_purch_operating_unit_id;
1030                     g_hdr_requesting_ou_id := l_req_operating_unit_id;
1031 
1032                     --<Shared Proc FPJ End>
1033 
1034                     g_number_records_processed := 0;
1035                     g_req_lines_to_process:=0;
1036 
1037                     l_progress:='030';
1038 
1039                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1040                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1041                                             p_token    => l_progress,
1042                                             p_message  => 'Before select min interface header for batch_id: '||p_batch_id);
1043                     END IF;
1044 
1045                     /* For now a batch has only one header, so get the document header id */
1046                       SELECT min(interface_header_id)
1047                       INTO x_interface_header_id
1048                       FROM po_headers_interface
1049                       WHERE batch_id = p_batch_id;  --<Shared Proc FPJ>
1050 
1051                     l_progress:='040';
1052                     --<SOURCING TO PO FPH>
1053                     /* determine whether the document to be created is a PO,PA or an RFQ */
1054                     --<CONFIG_ID FPJ>
1055                     --Modified the select statement to select document_subtype as well.
1056                     SELECT document_type_code,document_subtype,nvl(interface_source_code,'NOCODE')
1057                       INTO g_document_type,g_document_subtype,g_interface_source_code
1058                       FROM po_headers_interface
1059                     WHERE interface_header_id = x_interface_header_id;
1060 
1061                     --<eTax Integration R12> Populate global variable to indicate whether
1062                     -- tax is calculated for this document type
1063 
1064                     IF (g_document_type = 'PO' and
1065                         g_document_subtype in ('STANDARD', 'PLANNED', 'RELEASE')) THEN
1066                         g_calculate_tax_flag := 'Y';
1067                     END IF;
1068 
1069 
1070                     l_progress := '050';
1071                     --<SOURCING TO PO FPH START>
1072                     --Check for the uniqueness of the document number if manual numbering.
1073                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1074                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1075                                             p_token    => l_progress,
1076                                             p_message  => 'Document type is :'||g_document_type);
1077                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1078                                             p_token    => l_progress,
1079                                             p_message  => 'Sourcing to FPH-1 starts');
1080                     END IF;
1081 
1082                     if g_interface_source_code='SOURCING' then
1083                       --Since we allowe cancellation and finally close of reqs it's possible
1084                       --that the requistion reference sourcing passed to interface tables
1085                       --are already cancelled or finally closed.
1086                       --So we update the requisition line ids of such interface line
1087                       --records before starting the process. And treat them as non req
1088                       --backing negotiations.
1089 
1090                       --<CONSUME REQ DEMAND FPI>
1091                       --In FPI sourcing places the reqs back to pool at the time of splitting.
1092                       --By the time if some one has place these reqs on another PO document
1093                       --or sourcing doc autocreate should treat it as not backed by a req.
1094                       --Included the where clause
1095                       --a."prl.line_location_id is not null"
1096                       --b."(prl.auction_header_id<>pli.auction_header_id
1097                       --     and prl.auction_line_number<>pli.auction_line_number)" in the
1098                       --following sql.
1099 
1100                       l_progress:='060';
1101                       update po_lines_interface pli
1102                           set pli.requisition_line_id= null
1103                         where pli.interface_header_id= x_interface_header_id
1104                           and exists
1105                   (select requisition_line_id
1106                             from po_requisition_lines_all prl  --<Shared Proc FPJ>
1107                     where prl.requisition_line_id= pli.requisition_line_id
1108                       and (prl.line_location_id is not null
1109                             or prl.cancel_flag='Y'
1110                       or prl.closed_code='FINALLY CLOSED'
1111                       or (prl.auction_header_id<>pli.auction_header_id
1112                           and prl.auction_line_number<>pli.auction_line_number
1113                         )
1114                     )
1115                   );
1116 
1117                       l_progress := '070';
1118                       --bug#2729465, with drawn req lines are deleted from po_requisition_lines
1119                       --table. Hence require a separate update.
1120                       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1121                           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1122                                               p_token    => l_progress,
1123                                               p_message  => 'Sourcing to PO FPH-1: before the update for withdrawn reqs');
1124                       END IF;
1125 
1126                       UPDATE po_lines_interface pli
1127                           SET pli.requisition_line_id= null
1128                         WHERE pli.interface_header_id= x_interface_header_id
1129                           AND NOT EXISTS
1130                   (SELECT requisition_line_id
1131                             FROM po_requisition_lines_all prl  --<Shared Proc FPJ>
1132                     WHERE prl.requisition_line_id= pli.requisition_line_id);
1133 
1134                     end if;
1135 
1136                     l_progress := '080';
1137                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1138                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1139                                             p_token    => l_progress,
1140                                             p_message  => 'Sourcing to FPH-1 Ends');
1141                     END IF;
1142                     --<SOURCING TO PO FPH END>
1143 
1144 
1145 
1146                     /* Enhancement Request from Proj Manufacturing ecso 10/22/97
1147                     * Count number of req lines in the line interface table
1148                     * This is used to determine whether we will copy
1149                     * project/task reference from RFQ to Quote
1150                     */
1151                     SELECT count(*)
1152                       INTO g_req_lines_to_process
1153                       FROM po_lines_interface
1154                     WHERE interface_header_id = x_interface_header_id;
1155 
1156                     l_progress:='090';
1157 
1158                     -- <CONFIG_ID FPJ>
1159                     IF ( validate_interface_records(x_interface_header_id) ) THEN
1160                       -- Only create the document if the interface records pass the validations.
1161 
1162                       /* Call the appropriate function based on the document type */
1163                       --<SOURCING TO PO FPH>
1164                       --We are modifying the procedure create_po to create Blanket also.
1165                       --So Modify the following IF clause accordingly.
1166                       --IF(g_document_type = 'PO') THEN
1167                       IF(g_document_type in ('PO','PA')) THEN
1168 
1169                         l_progress := '100';
1170                         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1171                             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1172                                                 p_token    => l_progress,
1173                                                 p_message  => 'Before create_po:');
1174                         END IF;
1175 
1176                         create_po(x_interface_header_id, x_document_id
1177                                 ,p_sourcing_k_doc_type --<CONTERMS FPJ>
1178                                 ,p_conterms_exist_flag --<CONTERMS FPJ>
1179                     ,p_document_creation_method --<DBI FPJ>
1180 					,p_group_shipments  --<Bug 14608120 Autocreate GE ER>
1181                                 );
1182 
1183 
1184                       ELSE
1185 
1186                         l_progress := '110';
1187                         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1188                             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1189                                                 p_token    => l_progress,
1190                                                 p_message  => 'Before create_rfq:');
1191                         END IF;
1192 
1193                         create_rfq(x_interface_header_id, x_document_id);
1194 
1195                       END IF;
1196 
1197                     END IF; -- <CONFIG_ID FPJ> validate_interface
1198 
1199                     -- Copy the number of requisition lines processed back to
1200                     -- the client side.
1201                     x_number_lines := g_number_records_processed;
1202 
1203                     l_progress:='120';
1204                     --<SOURCING TO PO FPH>
1205                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1206                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1207                                             p_token    => l_progress,
1208                                             p_message  => 'Sourcing to FPH -2 starts');
1209                   END IF;
1210     END IF;
1211 
1212     if g_interface_source_code  in ('SOURCING','CONSUMPTION_ADVICE') then   -- CONSIGNED FPI
1213        if x_number_lines>0 and x_document_id is not null then
1214           begin
1215         x_errorcode :=1;  --success.
1216         x_return_status := FND_API.G_RET_STS_SUCCESS ; --<Shared Proc FPJ>
1217 
1218        /* CONSIGNED FPI start : return the release number for the release */
1219        IF g_document_subtype = 'RELEASE' THEN
1220             l_progress:= '130';
1221             select release_num
1222         into x_release_number
1223             from po_releases_all  --<Shared Proc FPJ>
1224             where po_release_id=x_document_id;
1225 
1226          x_document_number := interface.document_num || '-' || to_char(x_release_number);
1227 
1228        ELSE
1229             l_progress:= '140';
1230            select segment1
1231        into x_document_number
1232            from po_headers_all  --<Shared Proc FPJ>
1233            where po_header_id=x_document_id;
1234 
1235        END IF;
1236        /* CONSIGNED FPI end */
1237 
1238           exception
1239            when others then
1240             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
1241                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
1242                                    p_progress => l_progress);
1243             END IF;
1244             wrapup(x_interface_header_id);
1245             --<Shared Proc FPJ Start>
1246             x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1247 
1248             --set the org context back to original one
1249             IF (l_org_context_changed = 'Y') THEN
1250                 PO_MOAC_UTILS_PVT.set_org_context(l_original_operating_unit_id) ;       -- <R12 MOAC>
1251             END IF;
1252             --<Shared Proc FPJ End>
1253             po_message_s.sql_error('CREATE_DOCUMENTS',l_progress,sqlcode);
1254             raise;
1255           end;
1256        else
1257          if g_sourcing_errorcode =2 then
1258             --this will be set to 2 when dup_val_on_idex happen in create_po.
1259             x_errorcode:=2;
1260             x_return_status := PO_INTERFACE_S.G_RET_STS_DUP_DOC_NUM ; --<Shared Proc FPJ>
1261          else
1262             --when 0 lines are created, we assume that there is some erro happened
1263             --which is not related to manual PO numbering.
1264             x_errorcode:=3;
1265             x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ; --<Shared Proc FPJ>
1266          end if;
1267        end if; --Num_line_checked
1268     --<Shared Proc FPJ START>
1269     else --Calls other than Sourcing and Consumption Advice
1270        if x_number_lines>0 and x_document_id is not null then
1271           x_return_status := FND_API.G_RET_STS_SUCCESS ;
1272           -- <ACHTML R12 START>
1273           -- Need to populate document number for autocreate success message
1274           IF g_document_subtype = 'STANDARD' THEN
1275             select segment1
1276             into x_document_number
1277             from po_headers_all
1278             where po_header_id = x_document_id;
1279     END IF;
1280           -- <ACHTML R12 END>
1281        else
1282           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
1283        end if;
1284     end if; --check doc type
1285     --<Shared Proc FPJ END>
1286 
1287     l_progress:= '150';
1288     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1289         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1290                             p_token    => l_progress,
1291                             p_message  => 'Sourcing to FPH-2 Ends');
1292         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1293                             p_token    => l_progress,
1294                             p_message  => 'Create_documents: number of records processed: '||x_number_lines);
1295     END IF;
1296 
1297    /* CONSIGNED FPI Start : A consumption advice PO should always be created in an approved status.
1298       so update the header with 'approved' status and the shipment with the approved flag */
1299 
1300       IF (g_interface_source_code  = 'CONSUMPTION_ADVICE') and
1301          (x_errorcode = 1      )                          THEN
1302 
1303         IF g_document_subtype = 'STANDARD' THEN
1304 
1305           l_progress:= '160';
1306           update po_headers_all
1307           set authorization_status = 'APPROVED',
1308           approved_date = sysdate,
1309           approved_flag = 'Y'
1310           where po_header_id = x_document_id;
1311 
1312           update po_line_locations_all
1313           set approved_flag = 'Y',
1314               approved_date = sysdate
1315           where po_header_id = x_document_id ;
1316 
1317         ELSIF g_document_subtype = 'RELEASE'  THEN
1318 
1319           l_progress:= '170';
1320           update po_releases_all
1321           set authorization_status = 'APPROVED',
1322           approved_date = sysdate,
1323           approved_flag = 'Y'
1324           where po_release_id = x_document_id;
1325 
1326           update po_line_locations_all
1327           set approved_flag = 'Y',
1328               approved_date = sysdate
1329           where po_release_id = x_document_id ;
1330 
1331         END IF;
1332 
1333      END IF;
1334 
1335     /* CONSIGNED FPI END */
1336     l_progress:= '180';
1337 
1338     --<Shared Proc FPJ Start>
1339     --set the org context back to original one
1340     IF (l_org_context_changed = 'Y') THEN
1341         PO_MOAC_UTILS_PVT.set_org_context(l_original_operating_unit_id) ;       -- <R12 MOAC>
1342     END IF;
1343     --<Shared Proc FPJ End>
1344 
1345     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1346         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
1347     END IF;
1348 
1349 EXCEPTION
1350 
1351   WHEN OTHERS THEN
1352      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
1353          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
1354                             p_progress => l_progress);
1355      END IF;
1356      wrapup(x_interface_header_id);
1357 
1358     --<Shared Proc FPJ Start>
1359      x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
1360     --<Bug 3491323 mbhargav START>
1361      x_number_lines :=  g_number_records_processed;
1362      x_document_id := null;
1363      x_document_number := null;
1364     --<Bug 3491323 mbhargav END>
1365 
1366      --set the org context back to original one
1367      IF (l_org_context_changed = 'Y') THEN
1368          PO_MOAC_UTILS_PVT.set_org_context(l_original_operating_unit_id) ;       -- <R12 MOAC>
1369      END IF;
1370     --<Shared Proc FPJ End>
1371 
1372      po_message_s.sql_error('CREATE_DOCUMENTS',l_progress,sqlcode);
1373 
1374      --<Bug 3336920 mbhargav START>
1375      --No need to raise as we are setting the return status and error msg
1376      --raise;
1377      IF FND_MSG_PUB.check_msg_level(FND_MSG_PUB.g_msg_lvl_unexp_error) THEN
1378                FND_MSG_PUB.add_exc_msg(G_PKG_NAME, l_api_name,
1379                      SUBSTRB (SQLERRM , 1 , 200) || ' at location ' || l_progress);
1380      END IF;
1381      x_msg_data := FND_MSG_PUB.GET(p_msg_index => FND_MSG_PUB.G_LAST,
1382             p_encoded => 'F');
1383      --<Bug 3336920 mbhargav END>
1384 
1385     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1386         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
1387     END IF;
1388 
1389 END create_documents;
1390 
1391 /*===========================================================================*/
1392 /*============================ BODY (PRIVATE) ===============================*/
1393 /*===========================================================================*/
1394 
1395 /* ============================================================================
1396      NAME: CREATE_PO
1397      DESC: Create/Add to PO from requisition data in the PO_HEADERS,LINES
1398            and DISTRIBUTION interface tables.
1399      ARGS: IN : x_interface_header_id IN number
1400 --<CONTERMS FPJ START>
1401            IN: p_sourcing_k_doc_type   IN   VARCHAR2 - The document type that Sourcing
1402                              has seeded in Contracts.
1403                              Deafault null
1404           IN: p_conterms_exist_flag   IN    VARCHAR2 - Whether the sourcing document
1405                               has contract template attached.
1406                               Deafult - N
1407 --<CONTERMS FPJ END>
1408      ALGR:
1409 
1410    ==========================================================================*/
1411 PROCEDURE create_po(x_interface_header_id IN number,
1412         x_document_id IN OUT NOCOPY number
1413            ,p_sourcing_k_doc_type  IN VARCHAR2 --<CONTERMS FPJ>
1414            ,p_conterms_exist_flag  IN VARCHAR2 --<CONTERMS FPJ>
1415      ,p_document_creation_method IN VARCHAR2 --<DBI FPJ>
1416 	 ,p_group_shipments IN VARCHAR2  DEFAULT NULL --<Bug 14608120 Autocreate GE ER>
1417          ) IS
1418 x_max_revision_num number := null;
1419 
1420 -- Bug 902976, zxzhang, 10/04/99
1421 -- Change REVISED_DATE from VarChar(25) to Date.
1422 -- x_new_revised_date varchar2(25):= null;
1423 x_new_revised_date Date := null;
1424 
1425 X_line_found varchar2(1) := 'N';
1426 x_release_num number;
1427 
1428 x_document_num po_headers.segment1%type:=null; -- Bug 1093645
1429 
1430 l_api_name CONSTANT VARCHAR2(30) := 'create_po';
1431 
1432 x_org_id  number;
1433 /*bug # 2997337 */
1434   x_valid_ship_to po_headers.ship_to_location_id%TYPE;
1435   x_valid_bill_to po_headers.bill_to_location_id%TYPE;
1436   x_is_valid VARCHAR(1) := 'N';
1437 /*bug # 2997337 */
1438 
1439 --<Bug 3054563 mbhargav START>
1440 l_org_assign_rec   po_ga_org_assignments%ROWTYPE;
1441 l_org_row_id       varchar2(30);
1442 l_return_status     varchar2(1);
1443 --<Bug 3054563 mbhargav END>
1444 
1445 --<MRC FPJ Start>
1446 l_msg_data VARCHAR2(2000);
1447 l_msg_count NUMBER;
1448 --<MRC FPJ End>
1449 
1450 --<CONTERMS FPJ START>
1451 l_contracts_call_exception Exception;
1452 --For using %type, dependence on OKC tables. Consider for refactor
1453 l_contract_doc_type    VARCHAR2(150);
1454 --<CONTERMS FPJ END>
1455 l_document_creation_method po_headers_all.document_creation_method%type := p_document_creation_method; --<DBI FPJ>
1456 l_progress VARCHAR2(3) := '000';            --< Bug 3210331 >
1457 
1458 l_terms_id                   PO_HEADERS.terms_id%TYPE;
1459 l_fob_lookup_code            PO_HEADERS.fob_lookup_code%TYPE;
1460 l_freight_lookup_code        PO_HEADERS.freight_terms_lookup_code%TYPE;
1461 l_ship_via_lookup_code       PO_HEADERS_ALL.ship_via_lookup_code%TYPE;
1462 l_vs_terms_id                   PO_HEADERS.terms_id%TYPE;
1463 l_vs_fob_lookup_code            PO_HEADERS.fob_lookup_code%TYPE;
1464 l_vs_freight_lookup_code        PO_HEADERS.freight_terms_lookup_code%TYPE;
1465 l_vs_ship_via_lookup_code       PO_HEADERS_ALL.ship_via_lookup_code%TYPE;
1466 
1467 l_is_complex_work_po         BOOLEAN := FALSE;  -- <Complex Work R12>
1468 l_style_id                   NUMBER;            -- <Complex Work R12>
1469 tax_document_id              NUMBER;
1470 
1471 --<Bug :11071489 REQ_AUTOCREATE Start>--
1472 l_parameter_list  PO_CORE_S4.p_parameter_list;
1473 l_event_name VARCHAR2(100);
1474 --<REQ_AUTOCREATE END>--
1475 
1476 ----10214347
1477 l_doc_type  VARCHAR2(20);
1478 l_keep_summary VARCHAR2(10);
1479 
1480 
1481 --<Bug 13542989 :START, Included Bug Fix:14080332 >
1482 l_default_method VARCHAR2(30);
1483 l_email_address  PO_VENDOR_SITES_ALL.email_address%TYPE;
1484 l_fax_number     VARCHAR2(100);
1485 l_document_num   PO_HEADERS_ALL.segment1%TYPE;
1486 l_vendor_id      PO_VENDOR_SITES_ALL.vendor_id%TYPE;
1487 l_vendor_site_id PO_VENDOR_SITES_ALL.vendor_site_id%TYPE;
1488 --<Bug 13542989 :END, Included Bug Fix:14080332>
1489 
1490 
1491 BEGIN
1492     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1493         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
1494     END IF;
1495     --<R12 eTax Integration Start>
1496     SAVEPOINT TAX_CALCULATION_ERROR;
1497 
1498    /*Bug 4314776:Requisition import errors out with unique constraint voilation
1499    error on po_requsition_header_id when the create_po raises an unhandled exception.
1500    Establishing a savepoint here so that when an exception is raised in create_po
1501    procedure it will be rolled back to  this savepoint */
1502 
1503    savepoint create_po;    --Bug 4314776
1504 
1505     --<R12 eTax Integration End>
1506     get_system_defaults;
1507 
1508     -- <Complex Work R12 Start>
1509     SELECT phi.style_id
1510     INTO l_style_id
1511     FROM po_headers_interface phi
1512     WHERE phi.interface_header_id = x_interface_header_id;
1513 
1514     IF (l_style_id IS NOT NULL) THEN
1515       l_is_complex_work_po := PO_COMPLEX_WORK_PVT.is_complex_work_style(
1516                                 p_style_id => l_style_id
1517                               );
1518     ELSE
1519       l_is_complex_work_po := FALSE;
1520     END IF;
1521     -- <Complex Work R12 End>
1522 
1523     -- populate the interface tables with data from the
1524     -- requisition.
1525 
1526     l_progress := '010';
1527     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1528         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1529                             p_token    => l_progress,
1530                             p_message  => 'Create PO: Before setup interface table');
1531     END IF;
1532 
1533     l_progress:='020';
1534     -- <Complex Work R12 Start>: Pass in l_is_complex_work_po
1535     setup_interface_tables(
1536       x_interface_header_id => x_interface_header_id
1537     , x_document_id => x_document_id
1538     , p_is_complex_work_po => l_is_complex_work_po
1539     );
1540     -- <Complex Work R12 End>: Pass in l_is_complex_work_po
1541 
1542     -- determine which interface lines and shipments should
1543     -- be grouped.
1544     l_progress := '030';
1545     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1546         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1547                             p_token    => l_progress,
1548                             p_message  => 'Create PO: Before Group interface lines');
1549     END IF;
1550 
1551     --<RENEG BLANKET FPI START>
1552     -- DO not do grouping if document is Blanket and request is coming from Sourcing
1553     if (g_document_type <> 'PA') then
1554         group_interface_lines(
1555           x_interface_header_id => x_interface_header_id
1556         , p_is_complex_work_po  => l_is_complex_work_po
1557 		, p_group_shipments     => p_group_shipments --<Bug 14608120 Autocreate GE ER>
1558         );
1559     end if;
1560     --<RENEG BLANKET FPI END>
1561 
1562     l_progress := '040';
1563     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1564         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1565                             p_token    => l_progress,
1566                             p_message  => 'Create PO: After Group interface lines');
1567     END IF;
1568 
1569     -- If the document type is Release, then do not continue
1570     -- processing if there are no lines with a line number
1571     -- This means that none of the requisition lines matched
1572     -- the blanket line.  We do not want to create the release.
1573     IF (g_document_subtype='RELEASE')THEN
1574 
1575        BEGIN
1576 
1577           l_progress := '050';
1578           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1579               PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1580                                   p_token    => l_progress,
1581                                   p_message  => 'Create po: Interface header id is '|| x_interface_header_id);
1582           END IF;
1583 
1584           select distinct 'Y'
1585           into   X_line_found
1586           from   po_lines_interface
1587           where  interface_header_id = x_interface_header_id
1588           and    line_num is not null;
1589 
1590           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1591               PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1592                                   p_token    => l_progress,
1593                                   p_message  => 'Create PO : Line found in po_lines_interfaces');
1594           END IF;
1595 
1596        EXCEPTION
1597           WHEN OTHERS THEN
1598               IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
1599                   PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
1600                                      p_progress => l_progress);
1601               END IF;
1602               wrapup(x_interface_header_id);
1603               RAISE;
1604        END;
1605 
1606     END IF;
1607 
1608     l_progress := '060';
1609     OPEN interface_cursor(x_interface_header_id);
1610 
1611     FETCH interface_cursor INTO interface;
1612 
1613     IF interface_cursor%notfound THEN
1614       CLOSE interface_cursor;
1615       RETURN;
1616     END IF;
1617 
1618 
1619 /* Bug 2786897: Start
1620    Prior the fix the following code was getting executed only when
1621    a new PO was created through autocreate. It should get executed
1622    while adding requisition lines to an existing PO also.  Hence
1623    shifting the following piece of code out of the 'IF' condition
1624    on 'g_mode'
1625 */
1626 
1627     l_progress := '070';
1628     IF(interface.vendor_id is not null) THEN
1629 
1630     /*Bug 5715411 Null out the vendor record details as it is global record type */
1631        vendor.ship_via_lookup_code := null;
1632        vendor.fob_lookup_code := null;
1633        vendor.freight_terms_lookup_code := null;
1634        vendor.terms_id := null;
1635        /*Bug 5715411 end */
1636 
1637           po_vendors_sv.get_vendor_info
1638                            (interface.vendor_id,
1639                             vendor.ship_to_location_id,
1640                             vendor.bill_to_location_id,
1641                             l_ship_via_lookup_code,
1642                             l_fob_lookup_code,
1643                             l_freight_lookup_code,
1644                             l_terms_id,
1645                             vendor.type_1099,
1646                             vendor.hold_flag,
1647                             vendor.invoice_currency_code,
1648                             vendor.receipt_required_flag,
1649                             vendor.num_1099,
1650                             vendor.vat_registration_num,
1651                             vendor.inspection_required_flag);
1652 
1653          IF(interface.vendor_site_id is not null) THEN
1654                   po_vendor_sites_sv.get_vendor_site_info
1655                               (interface.vendor_site_id,
1656                                vendor.ship_to_location_id,
1657                                vendor.bill_to_location_id,
1658                                l_vs_ship_via_lookup_code,
1659                                l_vs_fob_lookup_code,
1660                                vendor.pay_on_code,
1661                                l_vs_freight_lookup_code,
1662                                l_vs_terms_id,
1663                                vendor.invoice_currency_code,
1664                                vendor.shipping_control    -- <INBOUND LOGISTICS FPJ>
1665                               );
1666 
1667                   -- Bug 3807992 start : Do not override the following terms with null
1668                   -- values. If the site has values validate them. If not valid take the
1669                   -- values from the vendor and validate them
1670 
1671                   -- Validate ship via
1672                   if l_vs_ship_via_lookup_code is not null then
1673                      po_vendors_sv.val_freight_carrier(l_vs_ship_via_lookup_code,
1674                                                        params.inventory_organization_id,
1675                                                        vendor.ship_via_lookup_code);
1676                   end if;
1677 
1678                   if vendor.ship_via_lookup_code is null then
1679                      po_vendors_sv.val_freight_carrier(l_ship_via_lookup_code,
1680                                                        params.inventory_organization_id,
1681                                                        vendor.ship_via_lookup_code);
1682                   end if;
1683 
1684                   -- Validate fob code
1685                   if l_vs_fob_lookup_code is not null then
1686                      po_vendors_sv.val_fob(l_vs_fob_lookup_code,vendor.fob_lookup_code);
1687                   end if;
1688 
1689                   if vendor.fob_lookup_code is null then
1690                      po_vendors_sv.val_fob(l_fob_lookup_code,vendor.fob_lookup_code);
1691                   end if;
1692 
1693                   -- Validate freight terms
1694                   if l_vs_freight_lookup_code is not null then
1695                      po_vendors_sv.val_freight_terms(l_vs_freight_lookup_code,
1696                                                      vendor.freight_terms_lookup_code);
1697                   end if;
1698 
1699                   if vendor.freight_terms_lookup_code is null then
1700                      po_vendors_sv.val_freight_terms(l_freight_lookup_code,
1701                                                      vendor.freight_terms_lookup_code);
1702                   end if;
1703 
1704                   -- Validate payment terms
1705                   if l_vs_terms_id is not null then
1706                      po_terms_sv.val_ap_terms(l_vs_terms_id,vendor.terms_id);
1707                   end if;
1708 
1709                   if vendor.terms_id is null then
1710                      po_terms_sv.val_ap_terms(l_terms_id,vendor.terms_id);
1711                   end if;
1712                   -- Bug 3807992 end
1713 
1714 		  -- bug 13091785
1715                   if interface.vendor_contact_id is null then
1716                      po_vendor_contacts_sv.get_vendor_contact(interface.vendor_site_id,
1717                                              interface.vendor_contact_id,
1718                                              interface.vendor_contact);
1719                   end if;
1720 
1721                   --  Bug 2816396 START
1722                   --  Default the pay_on_code for a Standard PO based
1723                   --  on the vendor site value.
1724                   if (vendor.pay_on_code = 'RECEIPT_AND_USE') then
1725                      vendor.pay_on_code := 'RECEIPT';
1726                   elsif (vendor.pay_on_code = 'USE') then
1727                      vendor.pay_on_code := null;
1728                   end if;
1729                   -- Bug 2816396 END
1730 
1731          END IF;
1732     END IF;
1733 
1734 /* Bug 2786897: End */
1735     l_progress := '080';
1736 
1737    --<Sourcing 11.5.10+> If called from Sourcing, simply assign interface.h_rate to
1738    -- g_rate_for_req_fields
1739    --<Shared Proc FPJ START>
1740    IF (g_interface_source_code <> 'SOURCING'
1741        AND g_purchasing_ou_id <> g_hdr_requesting_ou_id
1742        AND interface.document_subtype = 'STANDARD')
1743    THEN
1744      get_rate_for_req_price(
1745        p_requesting_ou_id => g_hdr_requesting_ou_id, -- <ACHTML R12>
1746        p_purchasing_ou_id => g_purchasing_ou_id, -- <ACHTML R12>
1747        p_po_currency_code => interface.h_currency_code,
1748        p_rate_type        => interface.h_rate_type,
1749        p_rate_date        => interface.h_rate_date,
1750        x_rate             => g_rate_for_req_fields
1751      );
1752      IF g_rate_for_req_fields IS NULL
1753      THEN
1754        g_rate_for_req_fields := interface.h_rate;
1755      END IF;
1756    ELSE
1757      g_rate_for_req_fields := interface.h_rate;
1758    END IF;
1759    --<Shared Proc FPJ END>
1760 
1761     l_progress := '090';
1762 
1763     IF (g_mode = 'ADD') THEN
1764 
1765      -----------10214347START
1766         -- Only clear amendment for PO/PA
1767             IF ((g_document_type = 'PO') OR (g_document_type = 'PA')) THEN
1768 
1769               -- p_doc_type is always passed as 'PO' regardless of the subtype
1770               -- Should set doc_type to PA for Blanket and Contract
1771               IF (g_document_subtype IN ('BLANKET', 'CONTRACT')) THEN
1772                 l_doc_type := 'PA';
1773               ELSE
1774                 l_doc_type := 'PO';
1775               END IF; /*IF (p_doc_subtype IN ('BLANKET', 'CONTRACT'))*/
1776 
1777               -- Call Clear_Amendment at the time of creating new revision.
1778               -- o If the pervious version is approved or require-reapproval
1779               --   the call OKC_TERMS_VERSION_GRP.CLEAR_AMENDMENT() with
1780               --   p_keey_summary = 'N'
1781               -- o Else call OKC_TERMS_VERSION_GRP.CLEAR_AMENDMENT() with
1782               --   p_keey_summary = 'Y'
1783               BEGIN
1784                 SELECT 'N'
1785                 INTO   l_keep_summary
1786                 FROM   dual
1787                 WHERE  exists (SELECT 'approved document'
1788                                FROM   po_headers
1789                                WHERE  po_header_id = interface.po_header_id
1790                                AND    NVL(approved_flag, 'N') IN ('R', 'Y'));
1791               EXCEPTION
1792                 WHEN NO_DATA_FOUND THEN
1793                   l_keep_summary := 'Y';
1794               END;
1795 
1796 
1797              /* IF g_fnd_debug = 'Y' THEN
1798      	   IF (FND_LOG.G_CURRENT_RUNTIME_LEVEL <= FND_LOG.LEVEL_STATEMENT) THEN
1799      	     FND_LOG.string(FND_LOG.LEVEL_STATEMENT, c_log_head || l_api_name||'.'
1800      	     || l_progress, 'Call OKC_TERMS_VERSION_GRP.clear_amendment '
1801      	     || ' p_doc_id:' || interface.po_header_id
1802      	     || ' g_document_type:' || (l_doc_type ||'_'||g_document_subtype)
1803      	     || ' p_keep_summary:' || l_keep_summary);
1804      	   END IF;
1805      	 END IF; */
1806 
1807               -- Calls Contracts API to clear Amendment related columns
1808               OKC_TERMS_VERSION_GRP.clear_amendment(
1809                 p_api_version   => 1.0,
1810                 p_init_msg_list => FND_API.G_FALSE,
1811                 p_commit        => FND_API.G_FALSE,
1812                 x_return_status => l_return_status,
1813                 x_msg_data      => l_msg_data,
1814                 x_msg_count     => l_msg_count,
1815                 p_doc_type      => (l_doc_type ||'_'||g_document_subtype),
1816                 p_doc_id        => interface.po_header_id,
1817                 p_keep_summary  => l_keep_summary);
1818 
1819             END IF; /*IF ((g_document_type = 'PO') OR (g_document_type = 'PA'))*/
1820 
1821 	    -----------10214347END
1822 
1823 
1824 /*Bug no 718918:sarunach
1825    The x_new_revised_date was added for bug no 491306 to update
1826    the revised_date.But it was inside the loop for standard and planned
1827    po's only.So the revised_date was Releases was incorrect.
1828    Removed those line and put it here to update the revised date for
1829    Standard,planned and Releases.
1830 */
1831 -- Bug 902976, zxzhang, 10/04/99
1832 -- Change REVISED_DATE from VarChar(25) to Date.
1833 /*
1834           x_new_revised_date := to_char(interface.last_update_date,
1835                                       'DD/MM/YYYY HH24:MI');
1836 */
1837     x_new_revised_date := interface.last_update_date;
1838 
1839        /* Bug# 1734108
1840        * When a line was added to a existing PO the invoice_match_option
1841        * was not Calculated. This resulted in creating shipments with
1842        * invoice_match_option as NULL. Due to this when navigating out of
1843        * Shipment Window we get the Error "FRM-40202:  Field must be
1844        * entered"
1845        * Default invoice match flag in turn from vendor site, vendor and
1846        * Financial system in that Order.
1847        */
1848        if g_interface_source_code  <> 'CONSUMPTION_ADVICE' then   -- bug 2741985
1849            get_invoice_match_option(interface.vendor_id,
1850                  interface.vendor_site_id,
1851                vendor.invoice_match_option);
1852        end if;
1853 
1854        IF(interface.document_subtype = 'STANDARD' or
1855           interface.document_subtype = 'PLANNED') THEN
1856 
1857           l_progress:='100';
1858 
1859           /*
1860           ** Get the max revision that exists in the archive
1861           ** table for this purchase order.  We will compare
1862           ** this against the current revision on the PO
1863           ** to determine if the revision needs to be incremented.
1864           ** If there is not a record in the archive table,
1865           **  the revision will not be incremented.
1866           ** If the po is currently approved and the revision
1867           **  number in the archive table is the same as
1868           **  the revision on the PO, then increment the
1869           **  revision on the PO by one.
1870           */
1871           SELECT max(revision_num)
1872           INTO   x_max_revision_num
1873           FROM   po_headers_archive_all poha  --<Shared Proc FPJ>
1874           WHERE  poha.po_header_id = interface.po_header_id;
1875 
1876          /* Bug 493106 ecso 9/24/97
1877           * Revised date should be updated
1878           * the same time revision is incremented.
1879           * Database field revised_date is defined as varchar(25).
1880           * Use same format as in po_headers_pkg2.check_new_revision
1881           x_new_revised_date := to_char(interface.last_update_date,
1882                                        'DD-MON-YY HH24:MI');
1883           */
1884 
1885           l_progress:='110';
1886           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1887               PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1888                                   p_token    => l_progress,
1889                                   p_message  => 'Update PO_Headers Doc subtype is Std or planned');
1890           END IF;
1891 --Bug 2295672 jbalakri : added 'REJECTED' case in decode statement.
1892 
1893           UPDATE po_headers_all  --<Shared Proc FPJ>
1894              SET approved_flag =
1895                        decode(nvl(approved_flag,'N'),'N','N','F','F','R'),
1896                  authorization_status =
1897                        decode(nvl(authorization_status,'INCOMPLETE'),
1898                               'INCOMPLETE','INCOMPLETE','REJECTED','REJECTED',
1899                               'REQUIRES REAPPROVAL'),
1900                  closed_code = 'OPEN',
1901 -- Bug 1199462 Amitabh
1902                  closed_date = NULL,
1903            revision_num =  decode(x_max_revision_num, '',
1904           revision_num,
1905         decode(nvl(authorization_status,'INCOMPLETE'),
1906                  'APPROVED',
1907            decode(revision_num, x_max_revision_num,
1908             revision_num + 1, revision_num),
1909         revision_num)),
1910                  revised_date =  decode(x_max_revision_num, '',
1911                                        revised_date,
1912                                decode(nvl(authorization_status,'INCOMPLETE'),
1913                                   'APPROVED',
1914                                   decode(revision_num, x_max_revision_num,
1915                                          x_new_revised_date, revised_date),
1916                                revised_date)),
1917                  last_update_date  = interface.last_update_date,
1918                  last_updated_by   = interface.last_updated_by,
1919                  last_update_login = interface.last_update_login
1920            WHERE po_header_id = interface.po_header_id;
1921 
1922        ELSIF (interface.document_subtype = 'RELEASE') THEN
1923 
1924          l_progress:='120';
1925          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1926              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1927                                  p_token    => l_progress,
1928                                  p_message  => 'Update PO_Headers Doc subtype is Release');
1929          END IF;
1930 
1931          UPDATE po_headers_all  --<Shared Proc FPJ>
1932            SET closed_code = 'OPEN',
1933                closed_date = NULL,
1934                last_update_date  = interface.last_update_date,
1935                last_updated_by   = interface.last_updated_by ,
1936                last_update_login = interface.last_update_login
1937          WHERE po_header_id = interface.po_header_id;
1938 
1939         l_progress:='130';
1940 
1941         SELECT po_release_id
1942           INTO g_po_release_id
1943           FROM po_releases_all  --<Shared Proc FPJ>
1944          WHERE release_num = interface.release_num
1945            AND po_header_id = interface.po_header_id
1946            FOR UPDATE OF approved_flag;
1947 
1948         l_progress:='140';
1949 
1950   /*
1951   ** Get max revision num from the archive table to
1952   ** determine if the revision on the release needs to
1953   ** be incremented.
1954   */
1955         SELECT max(revision_num)
1956     INTO x_max_revision_num
1957     FROM po_releases_archive_all  --<Shared Proc FPJ>
1958    WHERE po_release_id = g_po_release_id;
1959 
1960 /*Bug No.1793703:The decode statement below for updating the revision_num
1961                  was not complete.It was updating the revision_num with null
1962                  when the document added to was in 'Requires Re-approval stage'.
1963                  Added the revision_num at the end of the decode statement.*/
1964 
1965         l_progress:='150';
1966         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1967             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1968                                 p_token    => l_progress,
1969                                 p_message  => 'Update PO_Releases Doc subtype is Release');
1970         END IF;
1971 	/*bug 12674183 While trying to add a req line to Blanket Release in Incomplete status
1972 	The Approved flag in po_releases all was having null value.
1973 	so the value of approved_flag in this update statement was being set to R,
1974 	Hence added NVL condition for Approved_flag.*/
1975         UPDATE PO_RELEASES_ALL  --<Shared Proc FPJ>
1976            SET last_update_date = interface.last_update_date,
1977                last_updated_by = interface.last_updated_by,
1978                last_update_login = interface.last_update_login,
1979          closed_code = 'OPEN',
1980                approved_flag = DECODE(nvl(approved_flag,'N'), --bug 12674183
1981                                       'N','N','F','F',
1982                                       'R'),
1983                authorization_status = DECODE(authorization_status,
1984                                              'INCOMPLETE','INCOMPLETE','REJECTED','REJECTED',
1985                                              'REQUIRES REAPPROVAL'),
1986          revision_num =  decode(x_max_revision_num, '',
1987           revision_num,
1988             decode(nvl(authorization_status, 'INCOMPLETE'),
1989             'APPROVED',
1990         decode(x_max_revision_num, revision_num,
1991           revision_num+1, revision_num),
1992                                         revision_num)),
1993                revised_date =  decode(x_max_revision_num, '',
1994                                        revised_date,
1995                                decode(nvl(authorization_status,'INCOMPLETE'),
1996                                   'APPROVED',
1997                                   decode(revision_num, x_max_revision_num,
1998                                          x_new_revised_date, revised_date),
1999                                revised_date))
2000          WHERE po_release_id = g_po_release_id;
2001 
2002        END IF; /* of document type */
2003 
2004     ELSIF (g_mode = 'NEW') THEN
2005 
2006        l_progress:='160';
2007 
2008     /* bgu, Dec. 10, 98
2009      * Default invoice match flag in turn from Financial system default,
2010      * vendor, vendor site.
2011      */
2012 
2013     /* bug 2741985 :
2014      * for a consumption advice we do not need to get the match option from the
2015      *  site because we always insert a match type of 'PO' */
2016 
2017     if g_interface_source_code  <> 'CONSUMPTION_ADVICE' then   -- bug 2741985
2018        get_invoice_match_option(interface.vendor_id,
2019                  interface.vendor_site_id,
2020                vendor.invoice_match_option);
2021     end if;
2022 
2023     l_progress:='170';
2024 
2025     /** BUG 873209
2026      *  The date mask on interface.h_rate_date causes this insertion
2027      *  failed on tst115 database.
2028      */
2029     IF(interface.document_subtype = 'STANDARD' or
2030        interface.document_subtype = 'PLANNED'  or
2031        --<SOURCING TO PO FPH>
2032        --Allow to create blanket also
2033        interface.document_subtype = 'BLANKET'
2034        ) THEN
2035       l_progress:= '180';
2036       BEGIN
2037 
2038       if interface.global_agreement_flag = 'N' then
2039           interface.global_agreement_flag := null;
2040       end if;
2041 
2042       -- Bug 2690933
2043       if interface.global_agreement_flag = 'Y' then
2044             interface.h_min_release_amount := null;
2045       end if;
2046 
2047       --<SOURCING TO PO FPH>
2048       --The following insert is modified to take care of defaulting for sourcing
2049       --For more comments please refer to update po_headers_interface phi
2050       --in setup_interface_tables procedure.
2051       /* Bug 2816396
2052          Use the interface table value for pay_on_code when inserting into po_headers.pay_on_code
2053       */
2054 
2055 
2056 /*bug #2997337
2057     validating the ship_to and bill_to locations to check whether they are
2058     active or inactive before inserting into the PO_HEADERS table. If any of them
2059     is found inactive then a null value is inserted in the table in the respective
2060     column*/
2061 
2062      if (g_interface_source_code = 'SOURCING') then
2063        x_valid_ship_to := nvl(interface.ship_to_location_id, nvl(vendor.ship_to_location_id,
2064                                                                      params.ship_to_location_id));
2065        x_valid_bill_to := nvl(interface.bill_to_location_id, nvl(vendor.bill_to_location_id,
2066                                                                params.bill_to_location_id));
2067      else
2068        x_valid_ship_to := nvl(vendor.ship_to_location_id, interface.ship_to_location_id);
2069        x_valid_bill_to := nvl(vendor.bill_to_location_id, interface.bill_to_location_id);
2070      end if;
2071 
2072      l_progress:= '190';
2073      --bug 4229954
2074      --we will validate a location based on Bill-To-Location and Ship-To-Location flags
2075      --of hr_locations_all along with inactive date check
2076      BEGIN
2077         select 'Y' into x_is_valid
2078           from hr_locations_all
2079           where location_id = x_valid_ship_to
2080           and NVL(ship_to_site_flag, 'N') = 'Y' --bug 4229954
2081           and NVL(trunc(inactive_date),trunc(SYSDATE)+1) > trunc(SYSDATE);
2082 
2083      EXCEPTION
2084 
2085          WHEN NO_DATA_FOUND then
2086              IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2087                  PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2088                                      p_token    => l_progress,
2089                                      p_message  => 'NO_DATA_FOUND: '||SQLERRM);
2090              END IF;
2091            x_is_valid:='N';
2092           x_valid_ship_to := NULL;
2093 
2094          WHEN OTHERS  then
2095              IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
2096                  PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
2097                                     p_progress => l_progress);
2098              END IF;
2099           raise;
2100      End;
2101 
2102       l_progress:= '200';
2103  BEGIN
2104           select 'Y' into x_is_valid
2105           from hr_locations_all
2106           where location_id = x_valid_bill_to
2107           and NVL(bill_to_site_flag, 'N') = 'Y'  --bug 4229954
2108           and NVL(trunc(inactive_date),trunc(SYSDATE)+1) > trunc(SYSDATE);
2109 
2110      EXCEPTION
2111 
2112          WHEN NO_DATA_FOUND then
2113             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2114                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2115                                     p_token    => l_progress,
2116                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
2117             END IF;
2118             x_is_valid:='N';
2119             x_valid_bill_to := NULL;
2120 
2121          WHEN OTHERS  then
2122              IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
2123                  PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
2124                                     p_progress => l_progress);
2125              END IF;
2126             raise;
2127      End;
2128   /*end of addition for bug# 2997337 */
2129 
2130 --<DBI FPJ Start>
2131 IF g_interface_source_code = 'CONSUMPTION_ADVICE' THEN
2132   -- Bug 3648268 Use lookup code instead of hardcoded value
2133   l_document_creation_method := 'CREATE_CONSUMPTION';
2134 END IF;
2135 --<DBI FPJ End>
2136 
2137       l_progress:= '210';
2138       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2139           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2140                               p_token    => l_progress,
2141                               p_message  => 'Before Insert into PO_headers');
2142       END IF;
2143 
2144       INSERT INTO po_headers_all  --<Shared Proc FPJ>
2145             (po_header_id,
2146                    last_update_date,
2147                    last_updated_by,
2148                    segment1,
2149              created_by,
2150                    last_update_login,
2151              summary_flag,
2152                    enabled_flag,
2153                    type_lookup_code,
2154                    agent_id,
2155                    creation_date,
2156                    revision_num,
2157                    print_count,
2158                    closed_code,
2159                    frozen_flag,
2160                    vendor_id,
2161                    vendor_site_id,
2162        vendor_contact_id,
2163                    ship_to_location_id,
2164                    bill_to_location_id,
2165                    terms_id,
2166                    ship_via_lookup_code,
2167                    fob_lookup_code,
2168                    pay_on_code,
2169                    freight_terms_lookup_code,
2170              confirming_order_flag,
2171                    currency_code,
2172              rate_type,
2173                    rate_date,
2174                    rate,
2175                    acceptance_required_flag,
2176                    firm_status_lookup_code,
2177                    min_release_amount,
2178 --DPCARD{
2179                    pcard_id,
2180 --DPCARD}
2181              --<SOURCING TO PO FPH START>
2182              blanket_total_amount,--Bug# 2288408
2183              start_date,          --Bug# 2288408
2184              end_date,        --Bug# 2288408
2185              --<SOURCING TO PO FPH END>
2186        --<RENEG BLANKET FPI START>
2187        amount_limit,
2188                    global_agreement_flag,
2189        --<RENEG BLANKET FPI END>
2190        --<CONSUME REQ DEMAND FPI>
2191        consume_req_demand_flag,
2192                    consigned_consumption_flag,   -- CONSIGNED FPI
2193                    shipping_control,    -- <INBOUND LOGISTICS FPJ>
2194                    org_id  --<Shared Proc FPJ>
2195                   ,conterms_exist_flag     --<CONTERMS FPJ>
2196       ,document_creation_method --<DBI FPJ>
2197                  ,style_id --<R12 STYLES PHASE II>
2198      ,tax_attribute_update_code   --<eTax Integration R12>
2199             , created_language --<Unified Catalog R12: Bug#4656615>
2200             , cpa_reference    --<Unified Catalog R12: Bug#4656615>
2201             , clm_document_number
2202        )
2203       VALUES (interface.po_header_id,
2204                     interface.last_update_date,
2205                     interface.last_updated_by,
2206                     interface.document_num,
2207                     interface.created_by,
2208                     interface.last_update_login,
2209               'N',
2210                     'Y',
2211                     interface.document_subtype,
2212                     interface.agent_id,
2213                     interface.creation_date,
2214                     interface.revision_num,
2215                     interface.print_count,
2216                     interface.h_closed_code,
2217                     interface.frozen_flag,
2218                     interface.vendor_id,
2219                     interface.vendor_site_id,
2220         interface.vendor_contact_id,
2221                     x_valid_ship_to,
2222                     x_valid_bill_to,
2223         decode(g_interface_source_code,'SOURCING',
2224           nvl(interface.terms_id,
2225                     nvl(vendor.terms_id,
2226             params.terms_id)),
2227                             nvl(vendor.terms_id,
2228                                 interface.terms_id)),
2229         decode(g_interface_source_code,'SOURCING',
2230                            nvl(interface.ship_via_lookup_code,
2231              nvl(vendor.ship_via_lookup_code,
2232                  params.ship_via_lookup_code)),
2233                            nvl(vendor.ship_via_lookup_code,
2234                                interface.ship_via_lookup_code)),
2235         decode(g_interface_source_code,'SOURCING',
2236                            nvl(interface.fob_lookup_code,
2237              nvl(vendor.fob_lookup_code,
2238            params.fob_lookup_code)),
2239                            nvl(vendor.fob_lookup_code,
2240                                interface.fob_lookup_code)),
2241         decode(g_interface_source_code,'SOURCING',
2242                          nvl(interface.pay_on_code,
2243              vendor.pay_on_code),
2244                            'CONSUMPTION_ADVICE',
2245                            interface.pay_on_code,
2246                            nvl(vendor.pay_on_code,
2247                                interface.pay_on_code)),
2248         decode(g_interface_source_code,'SOURCING',
2249                            nvl(interface.freight_terms_lookup_code,
2250                                nvl(vendor.freight_terms_lookup_code,
2251            params.freight_terms_lookup_code)),
2252                            nvl(vendor.freight_terms_lookup_code,
2253                                interface.freight_terms_lookup_code)),
2254                     interface.confirming_order_flag,
2255                     interface.h_currency_code,
2256                     interface.h_rate_type,
2257 --                    to_date(interface.h_rate_date, 'DD/MM/YYYY'),
2258                     interface.h_rate_date,
2259                     interface.h_rate,
2260                     decode(g_interface_source_code,'CONSUMPTION_ADVICE','N',interface.acceptance_required_flag), -- bug 13799841
2261                     interface.h_firm_status_lookup_code,
2262                     interface.h_min_release_amount,
2263 --DPCARD{
2264                     interface.pcard_id,
2265 --DPCARD}
2266               --<SOURCING TO PO FPH START>
2267               decode(g_document_type,'PA',interface.amount_agreed,null),
2268               decode(g_document_type,'PA',interface.effective_date,null),
2269               decode(g_document_type,'PA',interface.expiration_date,null),
2270               --<SOURCING TO PO FPH END>
2271         --<RENEG BLANKET FPI START>
2272         decode(g_document_type, 'PA', nvl(interface.amount_limit, interface.amount_agreed), null),
2273                     decode(interface.global_agreement_flag,'N',null,'Y','Y',null),   -- bug 2754954
2274         --<RENEG BLANKET FPI END>
2275         --<CONSUME REQ DEMAND FPI>
2276         interface.consume_req_demand_flag,
2277                     decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'Y',null),
2278                     vendor.shipping_control,    -- <INBOUND LOGISTICS FPJ>
2279                     g_purchasing_ou_id  --<Shared Proc FPJ>
2280                    ,p_conterms_exist_flag     --<CONTERMS FPJ>
2281        ,l_document_creation_method --<DBI FPJ>
2282                    ,decode(g_interface_source_code,'CONSUMPTION_ADVICE',
2283                            PO_DOC_STYLE_GRP.get_standard_doc_style ,interface.style_id)  --<R12 STYLES PHASE II >
2284        ,nvl2(g_calculate_tax_flag, 'CREATE', null)  --<eTax Integration R12>
2285             , interface.created_language --<Unified Catalog R12: Bug#4656615>
2286             , interface.cpa_reference    --<Unified Catalog R12: Bug#4656615>
2287             , interface.document_num
2288         );
2289     EXCEPTION
2290         WHEN DUP_VAL_ON_INDEX THEN
2291             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2292                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2293                                         p_token    => l_progress,
2294                                         p_message  => 'DUP_VAL_ON_INDEX: '||SQLERRM);
2295             END IF;
2296 
2297             IF g_interface_source_code ='SOURCING' then
2298                 g_sourcing_errorcode:=2; --duplicate document number
2299                 RAISE;
2300             ELSE
2301                 RAISE;
2302             END IF;
2303     END;
2304 
2305     l_progress:= '220';
2306     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2307         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2308                             p_token    => l_progress,
2309                             p_message  => 'After Insert into PO_headers');
2310     END IF;
2311 
2312     /* Bug#13542989: Start : Get Default document transimmision information and
2313        Calling PO_VENDOR_SITES_SV.get_transmission_defaults only when vendor_id and
2314        vendor_site_id is present on PO to avoid no_data_found exception. */
2315 
2316        SELECT vendor_id, vendor_site_id
2317        INTO l_vendor_id, l_vendor_site_id
2318        FROM po_headers_all
2319        WHERE po_header_id = INTERFACE.po_header_id;
2320        IF l_vendor_id IS NOT NULL AND
2321          l_vendor_site_id IS NOT NULL THEN
2322 
2323 	PO_VENDOR_SITES_SV.get_transmission_defaults
2324 	( p_document_id => interface.po_header_id,
2325         p_document_type => g_document_type,
2326         p_document_subtype => interface.document_subtype,
2327         p_preparer_id => interface.agent_id,
2328         x_default_method => l_default_method,
2329         x_email_address => l_email_address,
2330         x_fax_number => l_fax_number,
2331         x_document_num => l_document_num
2332        );
2333 
2334 	update po_headers_all
2335         set SUPPLIER_NOTIF_METHOD = nvl(l_default_method,'NONE'),
2336         EMAIL_ADDRESS         = decode(l_default_method, 'EMAIL', l_email_address, null),
2337         FAX                   = decode(l_default_method, 'FAX', l_fax_number, null)
2338         where po_header_id        =  interface.po_header_id;
2339 
2340 	END IF;
2341 
2342 	IF g_debug_stmt THEN
2343         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2344                             p_token    => l_progress,
2345                             p_message  => 'After Default of Suppler Notification Method');
2346         END IF;
2347 	--Bug#13542989: End : Get Default document transimission information
2348 
2349 
2350     --Bug#5024876: Removed the dangling 'END IF' left by Bug#4886821
2351 
2352         -- After insert into po_headers, insert a row into org_assignments for a global agreement
2353            IF nvl(interface.global_agreement_flag, 'N') = 'Y' then
2354              l_progress:= '240';
2355              select org_id
2356              into x_org_id
2357              from po_headers_all
2358              where po_header_id = interface.po_header_id;
2359 
2360                --<Bug 3054563 mbhargav START>
2361                --Replaced the INSERT statement with call to Row Handler.
2362                -- call the GA org assignments table handler to insert a row
2363                -- for the owning org into the org assignments table
2364                l_org_assign_rec.po_header_id      := interface.po_header_id;
2365                l_org_assign_rec.organization_id   := x_org_id;
2366                l_org_assign_rec.purchasing_org_id := l_org_assign_rec.organization_id;
2367                l_org_assign_rec.enabled_flag      := 'Y';
2368                l_org_assign_rec.vendor_site_id    := interface.vendor_site_id;
2369                l_org_assign_rec.last_update_date  := interface.last_update_date;
2370                l_org_assign_rec.last_updated_by   := interface.last_updated_by;
2371                l_org_assign_rec.creation_date     := interface.creation_date;
2372                l_org_assign_rec.created_by        := interface.created_by;
2373                l_org_assign_rec.last_update_login := interface.last_update_login;
2374 
2375                PO_GA_ORG_ASSIGN_PVT.insert_row(p_init_msg_list  => 'T',
2376                                         x_return_status  => l_return_status,
2377                                         p_org_assign_rec => l_org_assign_rec,
2378                                         x_row_id         => l_org_row_id);
2379                --<Bug 3054563 mbhargav END>
2380 
2381               IF g_debug_stmt THEN
2382                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2383                                     p_token    => l_progress,
2384                                     p_message  => 'After inserting into Org Assignments');
2385               END IF;
2386             END IF;
2387 
2388       l_progress:= '250';
2389 
2390    --<RENEG BLANKET FPI START>
2391          --<BUG 2695661>
2392          -- The header level attachments should be copied if the call is coming from Sourcing.
2393          -- irrespective of doc type or subtype. Removing 'Blanket' check.
2394          if (g_interface_source_code ='SOURCING') then
2395 
2396               -- copy attachments from negotiation header to blanket header
2397          po_negotiations_sv2.copy_attachments('PON_AUCTION_HEADERS_ALL',
2398                             interface.auction_header_id,
2399                                 null,
2400                                 null,
2401                                 null,
2402                                 null,
2403                                 'PO_HEADERS',
2404                                 interface.po_header_id,
2405                                 null,
2406                                 null,
2407                                 null,
2408                                 null,
2409                                 interface.created_by,
2410                                 interface.last_update_login,
2411                                 null,
2412                                 null,
2413                                 null,
2414                                 'NEG');
2415 
2416               -- build and attach negotiation header notes as to supplier attachments
2417               -- on po/blanket header.
2418               po_negotiations_sv2.add_attch_dynamic('PON_AUC_SUPPLIER_HEADER_NOTES' ,
2419                         interface.auction_header_id,
2420                         interface.auction_line_number,
2421                         interface.bid_number,
2422                         interface.bid_line_number,
2423                         'PO_HEADERS',
2424                         interface.po_header_id,
2425                         interface.created_by,
2426                         interface.last_update_login ,
2427                         null,
2428                         null,
2429                         null);
2430 
2431               -- Bug# 3207840. build and attach negotiation/bid header
2432         -- attributes as to supplier attachment on po/blanket header
2433         -- from FPJ.
2434               po_negotiations_sv2.add_attch_dynamic('PON_BID_HEADER_ATTRIBUTES' ,
2435                         interface.auction_header_id,
2436                         NULL,
2437                         interface.bid_number,
2438                         NULL,
2439                         'PO_HEADERS',
2440                         interface.po_header_id,
2441                         interface.created_by,
2442                         interface.last_update_login ,
2443                         null,
2444                         null,
2445                         null);
2446 
2447           IF g_debug_stmt THEN
2448             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2449                                 p_token    => l_progress,
2450                                 p_message  => 'After copying attachments from Sourcing');
2451           END IF;
2452         end if; --attachments for header
2453 
2454       l_progress:= '260';
2455    -- the call to procedure calculate_local should happen only for doc_type PO
2456         -- <Bug 8513167>
2457         -- Call for all document types. Added BLANKET.
2458         if (g_document_subtype IN ('STANDARD','PLANNED','BLANKET')) then
2459          calculate_local(g_document_subtype, 'HEADER', interface.po_header_id);
2460         end if;
2461 
2462         IF g_debug_stmt THEN
2463           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2464                               p_token    => l_progress,
2465                               p_message  => 'After calculate_local');
2466         END IF;
2467 
2468         --<RENEG BLANKET FPI END>
2469 
2470       ELSIF(g_document_subtype='RELEASE')THEN
2471 
2472          l_progress:= '270';
2473          SELECT po_releases_s.nextval
2474            INTO g_po_release_id
2475            FROM sys.dual;
2476 
2477    /*
2478    ** assign the document id to get passed back to the
2479    ** calling module.
2480    */
2481          x_document_id := g_po_release_id;
2482 
2483 /*Bug 1664638
2484   Inserting negative of g_po_release_id as release number to
2485   avoid unique constraint violation
2486 */
2487         l_progress:='280';
2488 
2489         -- Bug 3599251: Assign value to l_document_creation_method and
2490         -- insert it into po_releases_all instead of p_document_creation_method
2491         -- Bug 3648268 Use lookup code instead of hardcoded value
2492         IF g_interface_source_code = 'CONSUMPTION_ADVICE' THEN
2493            l_document_creation_method := 'CREATE_CONSUMPTION';
2494         END IF;
2495 
2496         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2497             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2498                                 p_token    => l_progress,
2499                                 p_message  => 'Before insert into PO_RELEASES');
2500         END IF;
2501 
2502          INSERT INTO po_releases_all  --<Shared Proc FPJ>
2503              (po_release_id,
2504               last_update_date,
2505               last_updated_by,
2506               po_header_id,
2507               release_num,
2508               agent_id,
2509               release_date,
2510               creation_date,
2511               created_by,
2512               last_update_login,
2513               revision_num,
2514               approved_flag,
2515               authorization_status,
2516               print_count,
2517               release_type,
2518               pay_on_code,
2519               pcard_id,
2520               consigned_consumption_flag,   -- CONSIGNED FPI
2521               shipping_control,    -- <INBOUND LOGISTICS FPJ>
2522               org_id  --<Shared Proc FPJ>
2523         ,document_creation_method --<DBI FPJ>
2524         ,tax_attribute_update_code  --<eTax integration R12>
2525         ,acceptance_required_flag   --Bug 7518967 : Default Acceptance Required Check ER
2526               )
2527        VALUES (g_po_release_id,
2528                interface.last_update_date,
2529                interface.last_updated_by,
2530                interface.po_header_id,
2531                -g_po_release_id, --interface.release_num
2532                interface.agent_id,
2533                nvl(interface.release_date,sysdate),
2534                interface.creation_date,
2535                interface.created_by,
2536                interface.last_update_login,
2537                0,
2538                'N',
2539                'INCOMPLETE',
2540                0,
2541                'BLANKET',
2542                interface.pay_on_code,
2543                interface.pcard_id,
2544                decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'Y',null), -- CONSIGNED FPI
2545                interface.shipping_control,    -- <INBOUND LOGISTICS FPJ>
2546                g_purchasing_ou_id  --<Shared Proc FPJ>
2547          ,l_document_creation_method  --<DBI FPJ> -- Bug 3599251
2548                ,nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax Integration R12>
2549                ,decode(params.acceptance_required_flag,'N','N',   /* Bug 7518967 : Default Acceptance Required Check ER: Geting the default acceptance_required_flag */
2550 	                                               'Y','Y',
2551 						       'D','Y',
2552 						       'S','Y',
2553 						       'N')
2554                );
2555 
2556         l_progress:='290';
2557         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2558             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2559                                 p_token    => l_progress,
2560                                 p_message  => 'After insert into PO_RELEASES');
2561         END IF;
2562        -- Bug 882050: Release header level global attribute
2563 
2564        calculate_local('RELEASE', 'HEADER', g_po_release_id);
2565 
2566       END IF; /* of Standard/Planned */
2567     END IF; /* of NEW/ADD */ --Bug#5024876: Uncommenting the END IF commented by Bug#4886821
2568 
2569     l_progress:='300';
2570     -- <Complex Work R12 Start>
2571     create_line(
2572       x_interface_header_id => x_interface_header_id
2573     , p_is_complex_work_po => l_is_complex_work_po
2574     );
2575     -- <Complex Work R12 End>
2576 
2577     IF g_debug_stmt THEN
2578       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2579                           p_token    => l_progress,
2580                           p_message  => 'After create_line');
2581     END IF;
2582 
2583 
2584     LOOP
2585 
2586         FETCH interface_cursor INTO interface;
2587         EXIT WHEN interface_cursor%notfound;
2588 
2589         -- <Complex Work R12 Start>
2590         create_line(
2591           x_interface_header_id => x_interface_header_id
2592         , p_is_complex_work_po => l_is_complex_work_po
2593         );
2594         -- <Complex Work R12 End>
2595 
2596       IF g_debug_stmt THEN
2597         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2598                             p_token    => l_progress,
2599                             p_message  => 'After create_line (inside complex works loop)');
2600       END IF;
2601 
2602     END LOOP;
2603 
2604     --<Begin Bug# 5365579> After iterating through the cursor we want to reset
2605     --the cursor back to the first record for the rest of the procedure.
2606     CLOSE interface_cursor;
2607     OPEN interface_cursor(x_interface_header_id);
2608     FETCH interface_cursor INTO interface;
2609 
2610     IF interface_cursor%notfound THEN
2611       CLOSE interface_cursor;
2612       RETURN;
2613     END IF;
2614     --<End Bug# 5365579>
2615 
2616     --<Unified Catalog R12 START>
2617     -- Since we have the po_line_id available on po_attr_values_interface and tlp_interface
2618     -- we can move all records from interface to txn tables for all lines of a given blanket
2619     IF ((g_interface_source_code ='SOURCING') AND (g_document_subtype = 'BLANKET')) THEN
2620       IF g_debug_stmt THEN
2621         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2622                             p_token    => l_progress,
2623                             p_message  => 'Calling PO_ATTRIBUTE_VALUES_PVT.transfer_intf_item_attribs');
2624       END IF;
2625       PO_ATTRIBUTE_VALUES_PVT.transfer_intf_item_attribs(x_interface_header_id);
2626     END IF;
2627     -- <Unified Catalog R12 END>
2628 
2629 
2630     IF g_debug_stmt THEN
2631       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2632                           p_token    => l_progress,
2633                           p_message  => 'After PO_ATTRIBUTE_VALUES_PVT.transfer_intf_item_attribs');
2634     END IF;
2635 
2636     l_progress:='310';
2637 /* Bug 1093645:Code added to fix the deadlock issue in autocreate*/
2638     if (g_mode = 'NEW')  then
2639          IF (params.po_num_code='AUTOMATIC') AND
2640             --<SOURCING TO PO FPH>
2641       --modified the if clause to include PA
2642             (g_document_type in ('PO','PA'))         AND
2643 /* Bug 1183082
2644    If emergency po number is mentioned then the interface document number
2645    will have that value and it can be alphanumeric though the po num code
2646    is automatic.
2647    In case of automatic, we populate a dummy value in segment1(in po_headers)
2648    which is negative of po_header_id.
2649    We should be populating the segment1 from unique identifier control
2650    table only if the segment1 is negative of po_header id and
2651    hence the following logic.
2652            (interface.document_num  = to_char((-1* x_document_id))) THEN
2653 */
2654            (interface.document_num  = to_char((-1* x_document_id))) THEN
2655 
2656                l_progress:= '320';
2657 
2658                -- bug5174177
2659                -- Call Centralized API to get the next po number
2660                x_document_num :=
2661                  PO_CORE_SV1.default_po_unique_identifier
2662                  ( p_table_name => 'PO_HEADERS',
2663                    p_org_id     => g_purchasing_ou_id
2664                  );
2665 
2666                IF g_debug_stmt THEN
2667                  PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2668                             p_token    => l_progress,
2669                             p_message  => 'new po num = ' || x_document_num);
2670                END IF;
2671 
2672                l_progress := '325';
2673 
2674                UPDATE po_headers_all  --<Shared Proc FPJ>
2675                   set segment1=x_document_num,
2676                       clm_document_number = x_document_num
2677                where po_header_id=x_document_id;
2678 
2679           END IF;
2680 
2681           --<CONTERMS FPJ START>
2682           --Copy contract terms if sourcing doc had a template attached
2683           IF ((g_interface_source_code ='SOURCING')
2684               AND  (p_conterms_exist_flag= 'Y')) then
2685 
2686               l_progress:= '330';
2687               l_contract_doc_type:= PO_CONTERMS_UTL_GRP.GET_PO_CONTRACT_DOCTYPE(
2688                                   p_sub_doc_type=>g_document_subtype);
2689 
2690                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2691                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2692                                         p_token    => l_progress,
2693                                         p_message  => 'Contracts template attached');
2694                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2695                                         p_progress => l_progress,
2696                                         p_name     => 'x_document_id',
2697                                         p_value    => x_document_id);
2698                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2699                                         p_progress => l_progress,
2700                                         p_name     => 'x_document_num',
2701                                         p_value    => x_document_num);
2702                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2703                                         p_progress => l_progress,
2704                                         p_name     => 'l_contract_doc_type',
2705                                         p_value    => l_contract_doc_type);
2706                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2707                                         p_progress => l_progress,
2708                                         p_name     => 'interface.bid_number',
2709                                         p_value    => interface.bid_number);
2710                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2711                                         p_progress => l_progress,
2712                                         p_name     => 'p_sourcing_k_doc_type',
2713                                         p_value    => p_sourcing_k_doc_type);
2714                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2715                                         p_token    => l_progress,
2716                                         p_message  => 'before call okc_terms_copy_grp.copy_doc');
2717                 END IF;
2718 
2719                 l_progress:= '340';
2720 
2721                 OKC_TERMS_COPY_GRP.copy_doc     (
2722                         p_api_version           => 1.0,
2723                         p_source_doc_type     => p_sourcing_k_doc_type,
2724                         p_source_doc_id         => interface.bid_number,
2725                         p_target_doc_type     => l_contract_doc_type,
2726                         p_target_doc_id         => x_document_id,
2727                         p_keep_version          => 'Y',
2728                         p_article_effective_date=> sysdate,
2729                         p_initialize_status_yn  => 'N',
2730                         p_reset_Fixed_Date_yn   => 'N',
2731                         p_copy_del_attachments_yn=>'Y',
2732                         p_copy_deliverables     => 'Y',
2733                         p_document_number     => x_document_num,
2734                         p_copy_abstract_yn    => 'Y',   -- Bug 4051316
2735                         x_return_status        =>  l_return_status,
2736                         x_msg_data             =>  l_msg_data,
2737                         x_msg_count            =>  l_msg_count
2738                         );
2739 
2740                 l_progress:='350';
2741                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2742                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2743                                         p_token    => l_progress,
2744                                         p_message  => 'after call okc_terms_copy_grp.copy_doc.Return status:'||l_return_status);
2745                 END IF;
2746 
2747                  IF l_return_status <> FND_API.G_RET_STS_SUCCESS then
2748                        RAISE l_Contracts_call_exception;
2749                  END IF; -- Return status from contracts
2750 
2751             END IF; -- if p_conterms_exist_flag and sourcing doc
2752             --<CONTERMS FPJ END>
2753 
2754      l_progress := '360';
2755   /* FPI GA start  Update the terms after the successful completion of PO */
2756 
2757      IF  (g_document_subtype = 'STANDARD') and
2758          (g_interface_source_code <> 'CONSUMPTION_ADVICE')  then  -- CONSIGNED FPI
2759        po_interface_s2.update_terms(x_document_id);
2760      END IF;
2761 
2762    /* FPI GA end */
2763      l_progress := '370';
2764 
2765 /*Bug 1664638
2766   Since while inserting into po_releases , we inserted a negative
2767   number to avoid unique constraint violation, just before
2768   commit we are updating the correct value for release number.
2769 */
2770           IF  (g_document_subtype = 'RELEASE') then
2771 --Added a new loop as a part of 1805397 for fixing unique
2772 --constraint error
2773 --jbalakri
2774            begin
2775             loop
2776               begin
2777                  l_progress := '380';
2778                  select nvl(max(release_num),0) + 1
2779                  into   x_release_num
2780                  from   po_releases_all por  --<Shared Proc FPJ>
2781                  where  por.po_header_id = interface.po_header_id;
2782 /*Bug 1724603
2783   When we are creating a blanket release for the first time then
2784   we end up creating releases with negative release numbers
2785   and hence it required the following lines to be added as an
2786   extension to the fix in 1664638
2787 */
2788 
2789                  if (x_release_num <= 0) then   --Bug 4473796 : added '='
2790                      x_release_num := 1;
2791                  end if;
2792 
2793                  l_progress := '390';
2794                  update po_releases_all  --<Shared Proc FPJ>
2795                  set    release_num = x_release_num
2796                  where  po_releases_all.po_header_id = interface.po_header_id
2797                  and    release_num = -g_po_release_id;
2798                          exit;
2799                exception
2800                 when DUP_VAL_ON_INDEX then
2801                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2802                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2803                                             p_token    => l_progress,
2804                                             p_message  => 'DUP_VAL_ON_INDEX: '||SQLERRM);
2805                     END IF;
2806                  /* Bug 14065497: Comment the RAISE statement so that the loop continues when the DUP_VAL_ON_INDEX exception occurs */
2807                  -- RAISE;
2808                 when others then
2809                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
2810                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
2811                                            p_progress => l_progress);
2812                     END IF;
2813                   RAISE;
2814               end;
2815             end loop;
2816 --end of add for 1805397
2817            end;
2818            END IF;
2819 
2820     END IF;
2821 
2822     l_progress:='400';
2823 
2824     -- Bug 882050: Document level global attribute
2825     -- <Bug 8513167>
2826     -- Make the call for all document types. Added BLANKET.
2827     if (interface.document_subtype IN ('STANDARD','PLANNED','BLANKET')) THEN
2828         calculate_local(interface.document_subtype, 'DOCUMENT',
2829                         interface.po_header_id);
2830     elsif (g_document_subtype='RELEASE') THEN
2831         calculate_local('RELEASE', 'DOCUMENT', g_po_release_id);
2832     end if;
2833 
2834     l_progress := '410';
2835     --<Bug :11071489 REQ_AUTOCREATE Start>--
2836      l_event_name := 'oracle.apps.po.autocreate.pocreated';
2837      l_parameter_list(1).name := 'Interface_Header_ID' ;
2838      l_parameter_list(1).value := x_interface_header_id;
2839      po_core_s4.raise_business_event(l_event_name,l_parameter_list);
2840     --<REQ_AUTOCREATE end>---
2841     wrapup(x_interface_header_id);
2842 
2843     CLOSE interface_cursor;
2844     --
2845     -- <eTax Integration R12 Start>
2846     -- Removed multiple tax calls from procedure
2847     -- create_shipment and placed a single call here for calculating
2848     -- tax for the whole document
2849     --
2850     IF (g_document_subtype in ('STANDARD', 'PLANNED')) THEN
2851        l_progress := '413';
2852        l_return_status := NULL;
2853        -- Bug 5067321. For Add To, x_document_id is null, use
2854        -- interface.po_header_id instead
2855        IF (g_mode = 'ADD') THEN
2856          tax_document_id := interface.po_header_id;
2857        ELSE
2858          tax_document_id := x_document_id;
2859        END IF;
2860 
2861        PO_TAX_INTERFACE_PVT.calculate_tax( x_return_status     => l_return_status,
2862                                            p_po_header_id      => tax_document_id,
2863                                            p_po_release_id     => NULL,
2864                                            p_calling_program   => 'POXBWVRP_PO');
2865        IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
2866          l_progress := '414';
2867          IF g_interface_source_code = 'CONSUMPTION_ADVICE' THEN
2868            ROLLBACK TO TAX_CALCULATION_ERROR;
2869            x_document_id := NULL;
2870            fnd_message.set_name('PO','PO_API_ERROR');
2871            fnd_message.set_token( TOKEN  => 'PROC_CALLER'
2872                                 , VALUE  => 'PO_INTERFACE_S.CREATE_PO');
2873            fnd_message.set_token( TOKEN  => 'PROC_CALLED'
2874                                 , VALUE  => 'PO_TAX_INTERFACE_PVT.CALCULATE_TAX');
2875            fnd_msg_pub.add;
2876            fnd_message.set_name('PO','PO_AP_TAX_ENGINE_FAILED_WARN');
2877            fnd_msg_pub.add;
2878          END IF;
2879        END IF;
2880     ELSIF (g_document_subtype = 'RELEASE') THEN
2881        l_progress := '416';
2882        l_return_status := NULL;
2883        -- Bug 5067321. For Add To, x_document_id is null, use
2884        -- interface.po_header_id instead
2885        IF (g_mode = 'ADD') THEN
2886          tax_document_id := g_po_release_id;
2887        ELSE
2888          tax_document_id := x_document_id;
2889        END IF;
2890 
2891        PO_TAX_INTERFACE_PVT.calculate_tax(x_return_status     => l_return_status,
2892                                           p_po_header_id      => NULL,
2893                                           p_po_release_id     => tax_document_id,
2894                                           p_calling_program   => 'POXBWVRP_PO');
2895        IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
2896          IF g_interface_source_code = 'CONSUMPTION_ADVICE' THEN
2897            ROLLBACK TO TAX_CALCULATION_ERROR;
2898            x_document_id := NULL;
2899            fnd_message.set_name('PO','PO_API_ERROR');
2900            fnd_message.set_token( TOKEN  => 'PROC_CALLER'
2901                                 , VALUE  => 'PO_INTERFACE_S.CREATE_PO');
2902            fnd_message.set_token( TOKEN  => 'PROC_CALLED'
2903                                 , VALUE  => 'PO_TAX_INTERFACE_PVT.CALCULATE_TAX');
2904            fnd_msg_pub.add;
2905            fnd_message.set_name('PO','PO_AP_TAX_ENGINE_FAILED_WARN');
2906            fnd_msg_pub.add;
2907          END IF;
2908          l_progress := '417';
2909        END IF;
2910     END IF;
2911     -- <eTax Integration R12 End>
2912     l_progress := '420';
2913 
2914     --<SOURCING TO PO FPH>
2915     --for sourcing transaction is controlled by the sourcing code.
2916     if g_interface_source_code not in ('SOURCING','CONSUMPTION_ADVICE') then
2917 
2918 /* Bug 2534534 If no records are processed then we should not commit */
2919       if(g_number_records_processed > 0) then
2920          l_progress := '430';
2921          COMMIT;
2922       else
2923          l_progress := '440';
2924          rollback to savepoint create_po; --Bug 4314776
2925       end if;
2926     end if;
2927 
2928     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2929         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
2930     END IF;
2931 EXCEPTION
2932 --<CONTERMS FPJ START>
2933   WHEN l_Contracts_call_exception then
2934        -- put error messages in log
2935         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2936             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2937                                 p_token    => l_progress,
2938                                 p_message  => 'Create_po: Inside l_contracts_call_exception');
2939         END IF;
2940           Fnd_message.set_name('PO','PO_API_ERROR');
2941           Fnd_message.set_token( token  => 'PROC_CALLER'
2942                                , VALUE => 'PO_INTERFACE_S.CREATE_PO');
2943           Fnd_message.set_token( token  => 'PROC_CALLED'
2944                                , VALUE => 'OKC_TERMS_CPOY_GRP.COPY_DOC');
2945           FND_MSG_PUB.Add;
2946 
2947         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2948             l_msg_count := FND_MSG_PUB.Count_Msg;
2949             FOR i IN 1..l_msg_count LOOP
2950                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2951                                     p_token    => l_progress||'_EXCEPTION_'||i,
2952                                     p_message  => FND_MSG_PUB.Get(p_msg_index=>i,p_encoded =>'F'));
2953             END LOOP;
2954         END IF;
2955      IF interface_cursor%ISOPEN then
2956        CLOSE interface_cursor;
2957      END IF;
2958      RAISE;
2959 --<CONTERMS FPJ END>
2960 
2961 /* Bug: 1137860:
2962    Raise exception regardless of error. This will make debuging easier */
2963    WHEN OTHERS THEN
2964     --  wrapup(x_interface_header_id);
2965      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
2966          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
2967                             p_progress => l_progress);
2968      END IF;
2969      po_message_s.sql_error('CREATE_PO',l_progress,sqlcode);
2970      if interface_cursor%isopen then
2971        CLOSE interface_cursor;
2972      end if;
2973      --togeorge 11/20/2001
2974      -- Bug 1349801
2975      -- Added a Rollback when a Exception was raised
2976      -- This Rollbacks all the Changes done when a Exception Condition was raised. This was done to avoid PO's with negative numbers getting created.
2977      --raise;
2978     --<SOURCING TO PO FPH>
2979     --for sourcing transaction is controlled by the sourcing code.
2980     if g_interface_source_code not in  ('SOURCING', 'CONSUMPTION_ADVICE') then
2981       ROLLBACK  to savepoint create_po;  --Bug 4314776
2982        wrapup(x_interface_header_id); --Bug 4314776
2983 
2984      end if;
2985      --
2986     raise;  --<Bug 3336920>
2987 END create_po;
2988 
2989 /* ============================================================================
2990      NAME: CREATE_LINE
2991      DESC: Create/Add to document line
2992      ARGS: IN : x_interface_header_id_id IN number
2993      ALGR:
2994 
2995    ==========================================================================*/
2996 -- <Complex Work R12>: Added parameter p_is_complex_work_po
2997 PROCEDURE create_line(
2998   x_interface_header_id IN NUMBER
2999 , p_is_complex_work_po  IN BOOLEAN
3000 )
3001 IS
3002 x_po_line_id       number;
3003 x_po_line_type_id  number;
3004 x_line_num         po_lines.line_num%type;
3005 x_po_item_id       number;
3006 x_order_type_lookup_code varchar2(25);
3007 l_purchase_basis         PO_LINE_TYPES_B.purchase_basis%TYPE; -- <SERVICES FPJ>
3008 x_po_item_revision po_lines.item_revision%type;
3009 x_po_unit_meas_lookup_code po_lines.unit_meas_lookup_code%type;
3010 x_po_unit_price    number;
3011 x_po_transaction_reason_code po_lines.transaction_reason_code%type;
3012 x_price_break_lookup_code    po_lines.price_break_lookup_code%type;
3013 x_quantity         number := '';
3014 x_requisition_header_id number := ''; /* Used for copying attachments */
3015 
3016 	 --fix 8976669
3017  	 --declared x_amount
3018  	 x_amount number;
3019 
3020 x_line_location_id number := null;
3021 l_line_loc_id_tbl po_tbl_number;
3022 
3023 l_price_break_id  PO_LINE_LOCATIONS_ALL.line_location_id%TYPE;-- <SERVICES FPJ>
3024 
3025 x_quote_header_id number := null;
3026 x_quote_line_id number := null;
3027 x_match_blanket_line varchar2(1) := null;
3028 x_unit_price  po_lines.unit_price%TYPE := null;
3029 l_base_unit_price  po_lines.base_unit_price%TYPE := null; -- <FPJ Advanced Price>
3030 
3031 /* obtain currency info to adjust precision */
3032 x_precision   number :='';
3033 x_ext_precision   number :='';
3034 x_min_unit    number :='';
3035 /* project/task enhancement for RFQ */
3036 x_project_id    number :='';
3037 x_task_id   number :='';
3038 x_req_dist_id   number :='';
3039 --togeorge 11/17/2000
3040 --Bug# 1369049
3041 --Added logic to default tax_name in po_lines
3042    x_tax_id                ap_tax_codes.tax_id%type;
3043    x_tax_type              ap_tax_codes.tax_type%type;
3044    x_description           ap_tax_codes.description%type;
3045    x_allow_tax_code_override_flag  gl_tax_option_accounts.allow_tax_code_override_flag%type;
3046    x_tax_name              po_lines.tax_name%type;
3047    x_ship_to_location_id   number:= 0;
3048    x_ship_to_loc_org_id    mtl_system_items.organization_id%TYPE;
3049    x_ship_org_code         varchar2(3);
3050 
3051 /** <UTF8 FPI> **/
3052 /** tpoon 9/29/2002 **/
3053 /** Changed x_ship_org_name to use %TYPE **/
3054 --   x_ship_org_name         varchar2(60);
3055    x_ship_org_name         hr_all_organization_units.name%TYPE;
3056 --
3057 -- bug# 3345108
3058 -- comment out most of the changes done by bug 2219743.
3059 -- bug# 2219743
3060 /**
3061    x_secondary_qty         po_lines.secondary_quantity%type := NULL;
3062    x_item_number           VARCHAR2(240);
3063    x_process_org           VARCHAR2(1);
3064    x_dummy                 VARCHAR2(240);
3065    x_product               VARCHAR2(3) := 'GMI';
3066    x_opm_installed         VARCHAR2(1);
3067    x_retvar                BOOLEAN;
3068    ic_item_mst_rec IC_ITEM_MST%ROWTYPE;
3069    ic_item_cpg_rec IC_ITEM_CPG%ROWTYPE;
3070    x_order_opm_um  ic_item_mst.item_um%type := NULL;
3071    x_inv_org_id    mtl_system_items.organization_id%TYPE;
3072 **/
3073 l_api_name CONSTANT VARCHAR2(30) := 'create_line';
3074 d_mod CONSTANT VARCHAR2(255) := g_log_head||l_api_name;
3075 -- end of 2219743
3076 
3077     --<SOURCING TO PO FPH START>
3078     x_column1       varchar2(10);
3079     x_result        varchar2(7);
3080     update_req_pool_fail  exception;
3081     x_hazard_class_id   number:=null;
3082     x_un_number_id    number:=null;
3083     x_unit_of_measure   po_line_types.unit_of_measure%type:=null;
3084     --The following flag indicates whether copying the attachments from (all)the
3085     --sourcing entities need to be suppressed due to the grouping of lines.
3086     x_attch_suppress_flag       varchar2(1) :='N';
3087     --<SOURCING TO PO FPH END>
3088 
3089     l_db_quantity   po_lines.quantity%TYPE := null; --bug#2723479
3090 
3091     -- Bug 2735840 START
3092     l_uom_convert varchar2(2) := fnd_profile.value('PO_REQ_BPA_UOM_CONVERT');
3093     l_ga_uom                    PO_LINES.unit_meas_lookup_code%TYPE;
3094     l_quantity_in_ga_uom        PO_LINES_INTERFACE.quantity%TYPE;
3095     l_conversion_rate number :=1;
3096     -- Bug 2735840 END
3097 
3098     -- Bug 2875346.
3099     l_one_time_att_doc_id fnd_attached_documents.attached_document_id%TYPE;
3100 
3101     -- <SERVICES FPJ START>
3102     l_job_long_description  PO_REQUISITION_LINES_ALL.job_long_description%TYPE;
3103     l_who_rec               PO_NEGOTIATIONS_SV2.who_rec_type;
3104 
3105     l_return_status         VARCHAR2(1);
3106 
3107     l_order_type_lookup_code  PO_LINE_TYPES_B.order_type_lookup_code%TYPE;
3108     l_purchase_basis1         PO_LINE_TYPES_B.purchase_basis%TYPE;
3109     l_matching_basis          PO_LINE_TYPES_B.matching_basis%TYPE;
3110     l_category_id             PO_LINE_TYPES_B.category_id%TYPE;
3111     l_unit_meas_lookup_code   PO_LINE_TYPES_B.unit_of_measure%TYPE;
3112     l_unit_price              PO_LINE_TYPES_B.unit_price%TYPE;
3113     l_outside_operation_flag  PO_LINE_TYPES_B.outside_operation_flag%TYPE;
3114     l_receiving_flag          PO_LINE_TYPES_B.receiving_flag%TYPE;
3115     l_receive_close_tolerance PO_LINE_TYPES_B.receive_close_tolerance%TYPE;
3116     -- <SERVICES FPJ END>
3117     l_negotiated_by_preparer_flag po_lines_all.negotiated_by_preparer_flag%type; --<DBI FPJ>
3118     l_type_lookup_code po_headers_all.type_lookup_code%type; --<DBI FPJ>
3119     l_global_agreement_flag po_headers_all.global_agreement_flag%type; --<DBI FPJ>
3120 
3121     -- oneoff 3201308 start
3122     l_needby_prf  varchar2(1);
3123     l_shipto_prf  varchar2(1);
3124     l_min_shipment_num po_line_locations_all.shipment_num%TYPE;
3125     l_ship_to_loc po_line_locations_all.ship_to_location_id%TYPE;
3126     l_ship_to_org po_line_locations_all.ship_to_organization_id%TYPE;
3127     l_need_by_date po_line_locations_all.need_by_date%TYPE;
3128     -- oneoff 3201308 end
3129 
3130     l_contractor_status PO_REQUISITION_LINES_ALL.contractor_status%TYPE;
3131     --<Bug 3353109>
3132 
3133     l_routing_name      RCV_ROUTING_HEADERS.routing_name%TYPE; -- <BUG 3365446>
3134 
3135     l_progress VARCHAR2(3) := '000';                --< Bug 3210331 >
3136     l_manual_price_change_flag po_lines_all.manual_price_change_flag%TYPE := NULL; --bug 3495772
3137     l_from_type_lookup_code PO_HEADERS.type_lookup_code%type;--bug#3612701
3138 
3139     --<INVCONV R12 START>
3140     x_secondary_unit_def  MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
3141     x_secondary_uom       MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
3142     x_secondary_quantity_def  PO_LINES.SECONDARY_QUANTITY%TYPE;
3143     x_preferred_grade_def MTL_GRADES.GRADE_CODE%TYPE;
3144     l_quantity_temp   PO_LINES.QUANTITY%TYPE;
3145     --<INVCONV R12 END>
3146 
3147     l_requesting_ou_id    PO_REQUISITION_LINES_ALL.org_id%TYPE; -- <ACHTML R12>
3148     l_rate_for_req_fields GL_DAILY_RATES.conversion_rate%TYPE; -- <ACHTML R12>
3149 
3150     -- <Unified Catalog R12 START>
3151     l_po_line_id_tbl po_line_id_tbl;
3152     l_interface_header_id_tbl interface_header_id_tbl;
3153     l_interface_line_id_tbl interface_line_id_tbl;
3154     -- <Unified Catalog R12 END>
3155 
3156     l_outsourced_assembly po_line_locations_all.outsourced_assembly%type; --<SHIKYU R12>
3157     l_retainage_rate      PO_VENDOR_SITES_ALL.retainage_rate%type; --bug#5255878
3158 
3159     --<Bug:8598002 Enhanced Pricing Start:>
3160     l_enhanced_pricing_flag po_doc_style_headers.enhanced_pricing_flag%type;
3161     l_pricing_call_src VARCHAR2(5);
3162     --<Enhanced Pricing End>
3163 
3164 BEGIN
3165         l_outsourced_assembly :=2; --<SHIKYU R12>
3166   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3167     PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
3168   END IF;
3169 
3170   -- <ACHTML R12 START>
3171   -- Determine the Requesting OU from the current requisition line.
3172   -- If there is no backing req, take the globally determined Requesting OU.
3173   IF (interface.requisition_line_id IS NOT NULL)
3174   THEN
3175     BEGIN
3176       SELECT prl.org_id
3177       INTO   l_requesting_ou_id
3178       FROM   po_requisition_lines_all prl
3179       WHERE  prl.requisition_line_id = interface.requisition_line_id;
3180     EXCEPTION
3181       WHEN OTHERS
3182       THEN
3183         IF g_debug_unexp
3184         THEN
3185           PO_DEBUG.debug_exc(
3186             p_log_head => g_log_head||l_api_name,
3187             p_progress => l_progress
3188           );
3189         END IF;
3190         wrapup(interface.interface_header_id);
3191         po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
3192         raise;
3193       END;
3194   ELSE
3195     l_requesting_ou_id := g_hdr_requesting_ou_id;
3196   END IF;
3197 
3198   -- Determine the currency conversion rate for the current line.
3199   -- If called from Sourcing, simply use the rate specified in the interface
3200   -- table.
3201   IF (g_interface_source_code <> 'SOURCING'
3202       AND g_purchasing_ou_id <> l_requesting_ou_id
3203       AND interface.document_subtype = 'STANDARD')
3204   THEN
3205     get_rate_for_req_price(
3206       p_requesting_ou_id => l_requesting_ou_id, -- IN
3207       p_purchasing_ou_id => g_purchasing_ou_id, -- IN
3208       p_po_currency_code => interface.h_currency_code, -- IN
3209       p_rate_type        => interface.h_rate_type, -- IN
3210       p_rate_date        => interface.h_rate_date, -- IN
3211       x_rate             => l_rate_for_req_fields -- OUT
3212     );
3213   END IF;
3214 
3215   IF (l_rate_for_req_fields IS NULL)
3216   THEN
3217     l_rate_for_req_fields := nvl(g_rate_for_req_fields, 1);
3218   END IF;
3219   -- <ACHTML R12 END>
3220 
3221    /* initialize values */
3222    x_quantity := interface.quantity;
3223    x_secondary_quantity_def := interface.secondary_quantity; -- Bug 9324837
3224    x_unit_of_measure := interface.unit_meas_lookup_code; -- Bug 2735840
3225 
3226    /* Bug 586033, lpo, 11/25/97
3227    ** When trying to autocreate a release from a req with multiple lines
3228    ** against a blanket and the blanket has lines that match only some
3229    ** (i.e. not all) of the req lines, interface.line_type_id will be null
3230    ** and the following SELECT statement would cause a NO_DATA_FOUND
3231    ** exception. Since the X_match_blanket_line variable hasn't been set
3232    ** to 'N', the exception handlier does a 'raise', causing the COMMIT
3233    ** statement in create_po() to be skipped. Added an if statement below
3234    ** so that it wouldn't raise NO_DATA_FOUND exception until the
3235    ** X_match_blanket_line variable is set to 'N' later in the code.
3236    */
3237    IF (interface.line_type_id IS NOT NULL) THEN  -- Bug 586033, lpo, 11/25/97
3238      l_progress := '010';
3239      SELECT order_type_lookup_code
3240      ,      purchase_basis                                    -- <SERVICES FPJ>
3241      INTO   x_order_type_lookup_code
3242      ,      l_purchase_basis                                  -- <SERVICES FPJ>
3243      FROM   po_line_types
3244      WHERE  line_type_id = interface.line_type_id;
3245    END IF;  -- Bug 586033, lpo, 11/25/97
3246 
3247    l_progress := '020';
3248 
3249    IF interface.h_currency_code IS NOT NULL THEN
3250         fnd_currency.get_info(interface.h_currency_code,
3251                             x_precision,
3252                             x_ext_precision,
3253                               x_min_unit );
3254    END IF;
3255 
3256     /*
3257     ** Check to see if the po line exists
3258     ** Note that we do not need to check if the line exists in the
3259     ** interface table since we are in the process of inserting
3260     ** lines into the po lines table on a record by record basis.
3261     */
3262     IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED' or
3263        g_document_type = 'RFQ'
3264        --<SOURCING TO PO FPH>
3265        --do the select for blanket also
3266        or g_document_subtype = 'BLANKET') THEN
3267 
3268       BEGIN
3269 
3270       l_progress := '030';
3271       SELECT po_line_id,
3272              line_type_id,
3273              line_num,
3274              item_id,
3275              item_revision,
3276              unit_meas_lookup_code,
3277              base_unit_price,   -- <FPJ Advanced Price>
3278              unit_price,
3279              transaction_reason_code,
3280              price_break_lookup_code,
3281              manual_price_change_flag --bug 3495772
3282         INTO x_po_line_id,
3283              x_po_line_type_id,
3284              x_line_num,
3285              x_po_item_id,
3286              x_po_item_revision,
3287              x_po_unit_meas_lookup_code,
3288              l_base_unit_price,   -- <FPJ Advanced Price>
3289              x_po_unit_price,
3290              x_po_transaction_reason_code,
3291              x_price_break_lookup_code,
3292              l_manual_price_change_flag --bug 3495772
3293         FROM PO_LINES_ALL  --<Shared Proc FPJ>
3294        WHERE PO_HEADER_ID = interface.po_header_id
3295          AND LINE_NUM = interface.line_num
3296          FOR UPDATE OF quantity;
3297 
3298        EXCEPTION
3299     WHEN NO_DATA_FOUND then
3300             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3301                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3302                                     p_token    => l_progress,
3303                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3304             END IF;
3305        END;
3306 
3307      ELSIF(g_document_subtype = 'RELEASE')THEN
3308 
3309       l_progress := '040';
3310       X_match_blanket_line := 'N';
3311 
3312 /* Bug 2534534 Reverting the fix done in 1951084 */
3313 --     BEGIN
3314       SELECT po_line_id
3315   INTO x_po_line_id
3316         FROM po_lines_all  --<Shared Proc FPJ>
3317        WHERE po_header_id = interface.po_header_id
3318          AND line_num = interface.line_num
3319          FOR UPDATE OF quantity;
3320 
3321 /*      -- Bug 1951084 : added the exception handler
3322 
3323       EXCEPTION
3324     WHEN NO_DATA_FOUND then null;
3325        END;
3326 */
3327 
3328       X_match_blanket_line := 'Y';
3329 
3330      END IF;
3331 
3332      l_progress := '050';
3333      /*
3334      ** Bug 515985  ecso 10/9/97
3335      **       This procedure should be called even if line is not found
3336      ** when autocreating blanket releases
3337      */
3338 
3339     -- <BUG 3365446 START>
3340     --
3341     RCV_CORE_S.get_receiving_controls
3342     (   p_order_type_lookup_code      => x_order_type_lookup_code
3343     ,   p_purchase_basis              => l_purchase_basis
3344     ,   p_line_location_id            => NULL
3345     ,   p_item_id                     => interface.item_id
3346     ,   p_org_id                      => nvl(interface.destination_organization_id,params.inventory_organization_id)
3347     ,   p_vendor_id                   => interface.vendor_id
3348     ,   p_drop_ship_flag              => interface.drop_ship_flag
3349     ,   x_enforce_ship_to_loc_code    => rc.enforce_ship_to_location_code
3350     ,   x_allow_substitute_receipts   => rc.allow_substitute_receipts_flag
3351     ,   x_routing_id                  => rc.receiving_routing_id
3352     ,   x_routing_name                => l_routing_name
3353     ,   x_qty_rcv_tolerance           => rc.qty_rcv_tolerance
3354     ,   x_qty_rcv_exception_code      => rc.qty_rcv_exception_code
3355     ,   x_days_early_receipt_allowed  => rc.days_early_receipt_allowed
3356     ,   x_days_late_receipt_allowed   => rc.days_late_receipt_allowed
3357     ,   x_receipt_days_exception_code => rc.receipt_days_exception_code
3358     );
3359     -- <BUG 3365446 END>
3360 
3361 -- bug# 3345108 defaults secondary qty /UOM and grade in SETUP_INTERFACE_TABLE.
3362 -- no need to default it again here. comment out this logic.
3363 
3364 /**
3365        --mchandak 02/11/2002
3366        --Bug# 2219743
3367        --Added logic to default secondary qnty,UOM and grade in po_lines
3368        --if common purchasing is installed for OPM dual item
3369        IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED') AND NOT GML_PO_FOR_PROCESS.check_po_for_proc
3370        THEN
3371            x_retvar := FND_INSTALLATION.get_app_info(x_product,x_opm_installed,x_dummy,x_dummy);
3372            BEGIN
3373                 l_progress := '060';
3374                 SELECT inventory_organization_id INTO x_inv_org_id
3375                   FROM financials_system_params_all  --<Shared Proc FPJ>
3376                  WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
3377 
3378                 l_progress := '070';
3379                 SELECT process_enabled_flag INTO x_process_org
3380                 FROM   mtl_parameters
3381                 WHERE  organization_id = x_inv_org_id;
3382            exception
3383            when others
3384            then
3385                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3386                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3387                                         p_token    => l_progress,
3388                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
3389                 END IF;
3390                x_process_org := 'N';
3391            end;
3392 
3393            IF x_opm_installed = 'I' and x_process_org = 'Y' and
3394               interface.item_id is not null
3395            THEN
3396                BEGIN
3397                     l_progress := '080';
3398                     SELECT  segment1
3399                     INTO    x_item_number
3400                     FROM    mtl_system_items
3401                     WHERE
3402                         inventory_item_id = interface.item_id
3403                         AND  organization_id   = x_inv_org_id;
3404 
3405                EXCEPTION
3406                WHEN OTHERS
3407                THEN
3408                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3409                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3410                                         p_token    => l_progress,
3411                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
3412                 END IF;
3413                    x_item_number := NULL;
3414                END;
3415 
3416                l_progress := '090';
3417 
3418                GMIGUTL.GET_ITEM(x_item_number,ic_item_mst_rec,ic_item_cpg_rec);
3419                IF ic_item_mst_rec.item_no is not null
3420                THEN
3421                    interface.preferred_grade := ic_item_mst_rec.qc_grade;
3422 
3423                    IF ic_item_mst_rec.dualum_ind >= 1
3424                    THEN
3425                        interface.secondary_unit_of_measure:= po_gml_db_common.get_apps_uom_code(ic_item_mst_rec.item_um2);
3426                        x_order_opm_um := po_gml_db_common.get_opm_uom_code(interface.unit_meas_lookup_code);
3427                        po_gml_db_common.validate_quantity(
3428                                     ic_item_mst_rec.item_id,
3429                                     ic_item_mst_rec.dualum_ind,
3430                                     x_quantity,
3431                                     x_order_opm_um,
3432                                     ic_item_mst_rec.item_um2,
3433                                     x_secondary_qty);
3434                        interface.secondary_quantity := x_secondary_qty;
3435                    ELSE
3436                        interface.secondary_quantity := null;
3437                        interface.secondary_unit_of_measure := null;
3438                    END IF; -- ic_item_mst_rec.dualum_ind >= 1
3439                ELSE
3440                    interface.secondary_quantity := null;
3441                    interface.preferred_grade    := null;
3442                    interface.secondary_unit_of_measure := null;
3443                END IF; -- ic_item_mst_rec.item_no is not null
3444              ELSE
3445                    interface.secondary_quantity := null;
3446                    interface.preferred_grade    := null;
3447                    interface.secondary_unit_of_measure := null;
3448              END IF;
3449          END IF;
3450 -- end of 2219743
3451 **/
3452 
3453    l_progress := '100';
3454 
3455    -- Bug 2735840 START
3456    -- When autocreating a PO that references a GA, and the req line and
3457    -- GA line have different UOM's, convert to the GA's UOM if the
3458    -- UOM Convert profile is Yes. If UOM Convert is No, do not create
3459    -- this line.
3460    IF (interface.from_line_id IS NOT NULL)
3461       AND (g_document_subtype = 'STANDARD') THEN
3462 
3463      l_progress := '110';
3464      BEGIN
3465 --bug#3612701 modified the sql to fetch type lookup code
3466 --of the source document as well.
3467        SELECT pol.unit_meas_lookup_code,poh.type_lookup_code
3468        INTO l_ga_uom,l_from_type_lookup_code
3469        FROM po_lines_all pol,po_headers_all poh
3470        WHERE pol.po_line_id = interface.from_line_id
3471        and poh.po_header_id=interface.from_header_id
3472        and poh.po_header_id=pol.po_header_id;
3473 --bug#3612701
3474      EXCEPTION
3475        WHEN OTHERS THEN
3476          IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3477              PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3478                                 p_progress => l_progress);
3479          END IF;
3480          po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
3481          wrapup(interface.interface_header_id);
3482          raise;
3483      END;
3484 
3485      l_progress := '120';
3486      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3487         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3488                             p_token    => l_progress,
3489                             p_message  => 'req uom: '||interface.unit_meas_lookup_code||' uom: '||l_ga_uom
3490           ||'document type: ' || l_from_type_lookup_code);
3491      END IF;
3492 
3493 
3494      IF interface.unit_meas_lookup_code <> l_ga_uom THEN
3495        l_progress := '130';
3496 --bug#3612701
3497        IF (nvl(l_uom_convert,'N') = 'Y' or l_from_type_lookup_code='QUOTATION') THEN
3498 --bug#3612701
3499          -- Convert to the GA's UOM
3500          -- Bug 3793360 : use the po_uom_convert procedure and round 15
3501          l_conversion_rate :=  po_uom_s.po_uom_convert(interface.unit_meas_lookup_code,
3502                                                        l_ga_uom,
3503                                                        interface.item_id);
3504 
3505          x_quantity := round(x_quantity * l_conversion_rate , 15);
3506          x_unit_of_measure := l_ga_uom;
3507        ELSE -- UOM Convert is No, so do not create this line.
3508          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3509              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3510                                 p_token    => l_progress,
3511                                 p_message  => 'Create_line: Requisition UOM is different from GA UOM, and the Convert UOM profile is No. This PO line will not be created.');
3512          END IF;
3513          RETURN;
3514        END IF;
3515      END IF; -- interface.unit_meas_lookup_code <> l_ga_uom
3516 
3517    END IF; -- interface.from_line_id IS NOT NULL ...
3518    -- Bug 2735840 END
3519 
3520    --<Bug:8598002 Enhanced Pricing Start: Check if pricing enhanced for the current style and set l_pricing_call_src>
3521    BEGIN
3522      SELECT NVL(SH.enhanced_pricing_flag,'N')
3523      INTO l_enhanced_pricing_flag
3524      FROM po_doc_style_headers SH
3525      WHERE  SH.style_id = interface.style_id;
3526    EXCEPTION
3527      WHEN OTHERS THEN
3528        l_enhanced_pricing_flag := 'N';
3529    END;
3530 
3531    --l_pricing_call_src is used to distinguish pricing calls from auto creation.
3532    --Also it is assumed that
3533    IF (l_enhanced_pricing_flag  = 'Y') THEN
3534      l_pricing_call_src := 'AUTO';
3535    ELSE
3536      l_pricing_call_src := NULL;
3537    END IF;
3538    --<Enhanced Pricing End: >
3539 
3540    /* if line does not exist */
3541 
3542    IF(x_po_line_id is NULL) THEN
3543 
3544        /* If item is not null get list price and taxable flag */
3545 
3546        l_progress:='140';
3547         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3548             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3549                                 p_token    => l_progress,
3550                                 p_message  => 'Create_line: PO line does not exist');
3551         END IF;
3552 
3553 
3554         IF(interface.item_id is not null) THEN
3555 
3556           item.list_price_per_unit := interface.unit_price;
3557 
3558           l_outsourced_assembly := po_core_s.get_outsourced_assembly(interface.item_id,
3559                                                 interface.destination_organization_id);--<SHIKYU R12>
3560 
3561 
3562  /* Bug 919204 */
3563  /* made the receive close and invoice close tolerance to be picked up
3564   * from the lowest existing level by splitting the select.
3565   */
3566 /* Bug 1018048
3567    Prior to the fix we were getting the values of receipt required
3568    flag and inspection required flag of the item/master org to
3569    default in the autocreated document and were not considering the
3570    values defined at item/destination organization.
3571 
3572   Now, we derive the values from the item/destination organization
3573   and if it is not defined at the  item/destination organization
3574   level, then we derive the values from the item/master organization.
3575 */
3576 
3577           l_progress := '150';
3578           begin
3579           SELECT msi.invoice_close_tolerance,
3580                  msi.receive_close_tolerance,
3581                  msi.inspection_required_flag,
3582                  msi.receipt_required_flag
3583             INTO item.invoice_close_tolerance,
3584                  item.receive_close_tolerance,
3585                  item.inspection_required_flag,
3586                  item.receipt_required_flag
3587             FROM mtl_system_items msi
3588            WHERE msi.inventory_item_id = interface.item_id
3589              AND msi.organization_id   = interface.destination_organization_id;
3590 
3591           exception
3592                when no_data_found then
3593                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3594                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3595                                             p_token    => l_progress,
3596                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3597                     END IF;
3598                WHEN OTHERS THEN
3599                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3600                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3601                                            p_progress => l_progress);
3602                     END IF;
3603                     wrapup(x_interface_header_id);
3604                     po_message_s.sql_error('Get Item/Org defaults',l_progress,sqlcode);
3605                     raise;
3606           end;
3607 
3608          l_progress := '160';
3609 
3610          begin
3611           SELECT decode(x_order_type_lookup_code, 'QUANTITY',
3612                         msi.list_price_per_unit/nvl(interface.h_rate,1),
3613                         1), --<Shared Proc FPJ><Bug 3808903>
3614                  decode(x_order_type_lookup_code, 'QUANTITY',
3615                         msi.market_price/nvl(interface.h_rate,1),
3616                         1), --<Shared Proc FPJ><Bug 3808903>
3617                  msi.taxable_flag,
3618                  msi.primary_uom_code,
3619                  nvl(item.inspection_required_flag,msi.inspection_required_flag),
3620                  nvl(item.receipt_required_flag,msi.receipt_required_flag),
3621                  nvl(item.invoice_close_tolerance,msi.invoice_close_tolerance),
3622                  nvl(item.receive_close_tolerance,msi.receive_close_tolerance),
3623                  decode(msi.tracking_quantity_ind,
3624                         g_chktype_TRACKING_QTY_IND,
3625                         msi.secondary_uom_code,NULL),--<INVCONV R12>
3626                  nvl(msi.grade_control_flag,'N') --<INVCONV R12>
3627             INTO item.list_price_per_unit,
3628                  item.market_price,
3629                  item.taxable_flag,
3630                  item.unit_meas_lookup_code,
3631                  item.inspection_required_flag,
3632                  item.receipt_required_flag,
3633                  item.invoice_close_tolerance,
3634                  item.receive_close_tolerance,
3635                  item.secondary_uom_code, --<INVCONV R12>
3636                  item.grade_control_flag  --<INVCONV R12>
3637             FROM mtl_system_items msi
3638            WHERE msi.inventory_item_id = interface.item_id
3639              AND msi.organization_id = params.inventory_organization_id;
3640 
3641          exception
3642                when no_data_found then
3643                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3644                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3645                                             p_token    => l_progress,
3646                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3647                     END IF;
3648                WHEN OTHERS THEN
3649                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3650                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3651                                            p_progress => l_progress);
3652                     END IF;
3653                  wrapup(x_interface_header_id);
3654                  po_message_s.sql_error('Get Item/Master org defaults',l_progress,sqlcode);
3655                     raise;
3656           end;
3657       ELSE  -- added by jbalakri for bug 2348729
3658 /*  this case will reach when the item_id is null */
3659 /* Bug#2674947 We need to initialize market_price also */
3660 /* Bug#3545290 In case of One-time items i.e Item_id is NUll , the
3661                list price needed to be reinitialized.
3662 */
3663           item.market_price := '';
3664           item.taxable_flag := '';
3665           item.unit_meas_lookup_code := '';
3666           item.inspection_required_flag := '';
3667           item.receipt_required_flag := '';
3668           item.invoice_close_tolerance := '';
3669           item.receive_close_tolerance := '';
3670           item.list_price_per_unit := ''; --Bug 3545290
3671           item.secondary_uom_code := '';  --<INVCONV R12>
3672           item.grade_control_flag := '';  --<INVCONV R12>
3673       END IF; -- item id not null   Bug #2102149
3674 
3675       l_progress := '170';
3676 
3677 -- Bug: 1702702 Select receipt required flag also at line type level
3678         begin
3679                SELECT nvl(item.receive_close_tolerance,receipt_close),
3680                       nvl(item.receipt_required_flag,receiving_flag)
3681                INTO item.receive_close_tolerance,
3682                     item.receipt_required_flag
3683                FROM po_line_types_v
3684                WHERE line_type_id = interface.line_type_id;
3685           exception
3686                when no_data_found then
3687                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3688                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3689                                             p_token    => l_progress,
3690                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3691                     END IF;
3692                WHEN OTHERS THEN
3693                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3694                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3695                                            p_progress => l_progress);
3696                     END IF;
3697                     wrapup(x_interface_header_id);
3698                     po_message_s.sql_error('Get Line type default',l_progress,sqlcode);
3699                     raise;
3700           end;
3701 
3702    l_progress := '180';
3703 
3704 /*  Bug: 2106201 Select receipt required flag,inspection required flag
3705                  at vendor level before system option level to complete the
3706                  default logic
3707 */
3708   Begin
3709           select nvl(item.inspection_required_flag,
3710                                 vendor.INSPECTION_REQUIRED_FLAG),
3711                   nvl(item.receipt_required_flag,
3712                                 vendor.RECEIPT_REQUIRED_FLAG)
3713               into item.inspection_required_flag,
3714                   item.receipt_required_flag
3715               from po_vendors vendor
3716           where   vendor.vendor_id = interface.vendor_id;
3717 
3718       Exception
3719           when no_data_found then
3720                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3721                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3722                                         p_token    => l_progress,
3723                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3724                 END IF;
3725           WHEN OTHERS THEN
3726                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3727                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3728                                        p_progress => l_progress);
3729                 END IF;
3730               wrapup(x_interface_header_id);
3731               po_message_s.sql_error('Get vendor default',l_progress,sqlcode);
3732               raise;
3733       End;
3734 
3735    l_progress := '190';
3736 
3737 /* Bug: 1322342 Select receipt required flag,inspection required flag
3738                 receipt close tolerance and insp close tolerance
3739                 also from po system parameters if not defined at above level
3740 */
3741     Begin
3742         select nvl(item.inspection_required_flag,
3743                                 posp.INSPECTION_REQUIRED_FLAG),
3744                 nvl(item.receipt_required_flag,
3745                                 posp.RECEIVING_FLAG),
3746                 nvl(item.invoice_close_tolerance,
3747                                 posp.INVOICE_CLOSE_TOLERANCE),
3748                 nvl(item.receive_close_tolerance,
3749                                 posp.RECEIVE_CLOSE_TOLERANCE)
3750             into    item.inspection_required_flag,
3751                 item.receipt_required_flag,
3752                 item.invoice_close_tolerance,
3753                 item.receive_close_tolerance
3754            FROM po_system_parameters_all posp  --<Shared Proc FPJ>
3755           WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
3756 
3757     Exception
3758         when no_data_found then
3759             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3760                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3761                                     p_token    => l_progress,
3762                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3763             END IF;
3764         WHEN OTHERS THEN
3765             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3766                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3767                                    p_progress => l_progress);
3768             END IF;
3769             wrapup(x_interface_header_id);
3770             po_message_s.sql_error('Get po system default',l_progress,sqlcode);
3771             raise;
3772     End;
3773 -- Bug: 1322342 If not defined at po system option level also then
3774 
3775    l_progress := '200';
3776 
3777         IF (item.inspection_required_flag is NULL) THEN
3778             item.inspection_required_flag := 'N';
3779         END IF;
3780 
3781         IF (item.receipt_required_flag is  NULL) THEN
3782             item.receipt_required_flag := 'N';
3783         END IF;
3784         IF (item.invoice_close_tolerance is NULL) THEN
3785             item.invoice_close_tolerance := '0';
3786         END IF;
3787 
3788         IF (item.receive_close_tolerance is NULL) THEN
3789             item.receive_close_tolerance := '0';
3790         END IF;
3791 
3792        --ELSE Bug #2102149
3793 /* Bug 814174
3794    Prior to the fix, the list_price_per_unit was the same as the unit_price
3795    and not considering the rate factor.
3796    Made the changes to multiply the unit_price by the factor of rate
3797    for quantity based line types.
3798 */
3799           if (x_order_type_lookup_code = 'QUANTITY') then
3800              -- Bug 2715279. Changed interface.unit_price to item.list_price_per_unit
3801              -- on the RHS of the assignment
3802              -- Bug 3276529 change the paranthesis divide the unit price with rate
3803              -- and not the list price as it has already been divided in the select
3804 
3805       --<Shared Proc FPJ>
3806             item.list_price_per_unit := nvl(
3807               item.list_price_per_unit,
3808               (interface.unit_price / l_rate_for_req_fields) -- <ACHTML R12>
3809             );
3810 
3811           -- <SERVICES FPJ START>
3812           --
3813           ELSIF ( x_order_type_lookup_code = 'AMOUNT' ) THEN
3814 
3815               item.list_price_per_unit := 1;
3816 
3817           ELSE -- ( x_order_type_lookup_code IN ('FIXED PRICE','RATE') )
3818 
3819               item.list_price_per_unit := NULL;
3820 
3821           END IF;
3822           --
3823           -- <SERVICES FPJ END>
3824 
3825     -- Bug #2102149
3826     if (interface.item_id is null) then
3827     item.taxable_flag := '';
3828     item.unit_meas_lookup_code := '';
3829     end if;
3830       -- Bug #2102149
3831 
3832       l_progress := '210';
3833       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3834             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3835                                 p_token    => l_progress,
3836                                 p_message  => 'Create_line: line taxable_flag: '||item.taxable_flag);
3837       END IF;
3838 
3839 
3840         -- <Bug 3322948>
3841         -- Perform currency conversion on price/amount/quantity.
3842         PO_INTERFACE_S.do_currency_conversion(
3843           p_order_type_lookup_code => x_order_type_lookup_code,
3844           p_interface_source_code  => g_interface_source_code,
3845           p_rate                   => l_rate_for_req_fields, -- <ACHTML R12>
3846           p_po_currency_code       => interface.h_currency_code,
3847           p_requisition_line_id    => interface.requisition_line_id,
3848           x_quantity               => x_quantity, -- IN/OUT
3849           x_unit_price             => interface.unit_price, -- IN/OUT
3850           x_base_unit_price        => interface.base_unit_price, -- IN/OUT
3851                                    -- <Bug 3401653>
3852           --fix 8976669
3853  	 --modified parameter x_amount as in x_quantity as the procedure was not returning x_amount
3854  	           x_amount                 => x_amount -- IN/OUT
3855         );
3856 
3857 
3858        /* set neg by preparer flag */
3859        interface.negotiated_by_preparer_flag := 'N';
3860 
3861         --<SOURCING TO PO FPH >Bug# 2288408
3862         --sourcing populates the unit price in bidder's currency, so we are
3863         -- not converting the currency. And sourcing does not have
3864   --list_price_per_unit and market price storred in their system,
3865   --so dont do the following for sourcing
3866         if g_interface_source_code <>'SOURCING' then
3867            IF (item.unit_meas_lookup_code=interface.unit_meas_lookup_code) THEN
3868               IF (item.list_price_per_unit <> '') THEN
3869                  IF (item.list_price_per_unit > interface.unit_price) THEN
3870               interface.negotiated_by_preparer_flag := 'Y';
3871                  END IF;
3872               END IF;
3873            END IF;
3874         end if;
3875 
3876 
3877        l_progress:='240';
3878 
3879 
3880        /* Enhancement Request from Proj Manufacturing
3881        ** ecso 10/22/97
3882        ** Conditions:
3883        ** - new RFQ
3884        ** - only one requisition line for the interface_header_id
3885        ** Action:
3886        ** - copy project_id  task_id from first req dist to RFQ line
3887        ** Future enhancement includes:
3888        ** - spliting req lines with multiple dist
3889        ** - group req lines by project/task
3890        */
3891 
3892 /* Bug: 1526641 in order to propagate Project info we don't need the condition
3893         of req lines. It inhibits the situation when req lines are not grouped
3894         and Project info could propagate to the document being created. But
3895         certainly there is a limitation of removing this which is when there are
3896         two req lines and the first line does not have project info and the
3897         second line does then the project info does not propagate. Of course
3898         reason being we are not grouping lines on the basis of Project.
3899         But right now we are going ahead with this little enhancement.
3900 
3901        IF (g_document_type = 'RFQ') AND
3902     (nvl(g_req_lines_to_process,0) = 1)
3903        THEN
3904 */
3905 
3906        IF (g_document_type = 'RFQ') THEN
3907           l_progress := '240';
3908 
3909    BEGIN
3910      SELECT MIN(DISTRIBUTION_ID)
3911      INTO   x_req_dist_id
3912      FROM   PO_REQ_DISTRIBUTIONS_ALL  --<Shared Proc FPJ>
3913      WHERE  REQUISITION_LINE_ID = interface.requisition_line_id
3914            AND    PROJECT_ID IS NOT NULL
3915            AND    TASK_ID    IS NOT NULL;
3916    EXCEPTION
3917     WHEN NO_DATA_FOUND THEN
3918             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3919                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3920                                     p_token    => l_progress,
3921                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3922             END IF;
3923     WHEN OTHERS THEN
3924             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3925                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3926                                    p_progress => l_progress);
3927             END IF;
3928             RAISE;
3929    END;
3930 
3931       -- Bug 5363922 Start
3932       -- Selecting Only Project ID If Task ID Null
3933  	          IF x_req_dist_id IS NULL THEN
3934  	                  BEGIN
3935  	                    SELECT MIN(DISTRIBUTION_ID)
3936  	                    INTO          x_req_dist_id
3937  	                    FROM          PO_REQ_DISTRIBUTIONS_ALL  --<Shared Proc FPJ>
3938  	                    WHERE  REQUISITION_LINE_ID = interface.requisition_line_id
3939  	                    AND    PROJECT_ID IS NOT NULL;
3940  	                  EXCEPTION
3941  	                   WHEN OTHERS THEN
3942  	                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3943  	                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3944  	                                            p_progress => l_progress);
3945  	                     END IF;
3946  	                     RAISE;
3947  	                  END;
3948 
3949  	          END IF;
3950   -- End Bug 5363922
3951 
3952      l_progress := '250';
3953    BEGIN
3954     SELECT project_id
3955      ,task_id
3956     INTO   x_project_id
3957      , x_task_id
3958     FROM   PO_REQ_DISTRIBUTIONS_ALL  --<Shared Proc FPJ>
3959     WHERE  DISTRIBUTION_ID = x_req_dist_id;
3960   EXCEPTION
3961     WHEN NO_DATA_FOUND THEN
3962             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3963                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3964                                     p_token    => l_progress,
3965                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3966             END IF;
3967     WHEN OTHERS THEN
3968             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3969                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3970                                    p_progress => l_progress);
3971             END IF;
3972             RAISE;
3973    END;
3974 
3975        ELSE
3976 
3977    x_project_id := NULL;
3978    x_task_id := NULL;
3979 
3980        END IF;
3981 
3982       l_progress := '260';
3983 
3984        --<SOURCING TO PO FPH START>
3985        --default un_number_id,hazard_class_id from item attributes when
3986        --not backed by a req. Also default UOM for amount based lines for this
3987        --condition.
3988        If g_interface_source_code in ('SOURCING','CONSUMPTION_ADVICE') then -- CONSIGNED FPI
3989     if interface.requisition_line_id is null then
3990        begin
3991               l_progress:='270';
3992               select un_number_id,hazard_class_id
3993           into x_un_number_id,x_hazard_class_id
3994           from mtl_system_items
3995                where inventory_item_id = interface.item_id
3996            and organization_id   =params.inventory_organization_id;
3997               exception
3998          when no_data_found then
3999                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4000                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4001                                             p_token    => l_progress,
4002                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4003                     END IF;
4004                when others then
4005                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4006                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4007                                            p_progress => l_progress);
4008                     END IF;
4009                     po_message_s.sql_error('Get un number,hazard class defaults'
4010           ,l_progress, sqlcode);
4011               raise;
4012        end;
4013 
4014        if x_order_type_lookup_code='AMOUNT' then
4015                 begin
4016                 l_progress:='280';
4017     select unit_of_measure
4018       into x_unit_of_measure
4019       from po_line_types
4020      where line_type_id= interface.line_type_id;
4021     exception
4022                  when others then
4023                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4024                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4025                                            p_progress => l_progress);
4026                     END IF;
4027                   po_message_s.sql_error('Get UOM for amount based lines- defaults', l_progress, sqlcode);
4028             raise;
4029           end;
4030        else
4031                 x_unit_of_measure :=interface.unit_meas_lookup_code;
4032        end if;
4033           else
4034              x_un_number_id := interface.un_number_id;
4035              x_hazard_class_id := interface.hazard_class_id;
4036              x_unit_of_measure :=interface.unit_meas_lookup_code;
4037           end if;
4038        end if;
4039        --<SOURCING TO PO FPH END>
4040 
4041        l_progress := '290';
4042 
4043        IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED' or
4044           --<SOURCING TO PO FPH>
4045     --insert Blankets also
4046           g_document_subtype='BLANKET' or
4047     g_document_type = 'RFQ') THEN
4048 
4049 
4050 
4051          l_progress:='330';
4052 
4053          SELECT po_lines_s.nextval
4054            INTO x_po_line_id
4055            FROM sys.dual;
4056 
4057          l_progress:='340';
4058 
4059          /* GA FPI start */
4060 
4061         -- <SERVICES FPJ>
4062         --
4063         -- Call the Pricing API only when...
4064         --
4065         --    1) Autocreating a Standard PO or a BlANKET and pricing is enhanced for the style selected
4066         --    2) Source Document exists or the pricing is enhanced for the style selected
4067         --    3) Not a Consumption Advice
4068         --    4) Requisition Line's Contractor Status is not 'ASSIGNED'
4069         --       ( if the contractor status is 'ASSIGNED',
4070         --         then we take the price directly from the Requisition Line )
4071         --
4072         --    5) Not a complex work PO  <Complex Work R12>
4073         l_contractor_status := PO_SERVICES_PVT.get_contractor_status(interface.requisition_line_id);  --<Bug 3353109>
4074         --Bug:8598002 Enhanced Pricing: Enable pricing call for BLANKET document subtype if pricing enhanced for the style selected
4075         IF  (   ( g_document_subtype = 'STANDARD' OR
4076                 (g_document_subtype = 'BLANKET' AND l_enhanced_pricing_flag = 'Y'))
4077             AND ( interface.from_line_id IS NOT NULL OR
4078                   -- <FPJ Advanced Price START>
4079                   interface.contract_id IS NOT NULL OR
4080                   l_enhanced_pricing_flag = 'Y') --Enhanced Pricing: Enable pricing call if pricing enhanced for the style selected
4081                   -- <FPJ Advanced Price END>
4082             AND ( g_interface_source_code <> 'CONSUMPTION_ADVICE' )
4083             AND (NOT p_is_complex_work_po) -- <Complex Work R12>
4084             AND ( l_contractor_status IS NULL OR l_contractor_status <> 'ASSIGNED' ) ) -- <BUG 3281227>  --<Bug 3353109>
4085         THEN
4086 
4087             l_progress := '350';
4088             -- <SERVICES FPJ START>
4089             --
4090             PO_SOURCING2_SV.get_break_price
4091             (  p_api_version    => 1.0
4092             ,  p_order_quantity   => x_quantity
4093             ,  p_ship_to_org    => interface.destination_organization_id
4094             ,  p_ship_to_loc    => get_ship_to_loc(interface.deliver_to_location_id)
4095             ,  p_po_line_id   => interface.from_line_id
4096             ,  p_cum_flag   => FALSE
4097             ,  p_need_by_date   => interface.need_by_date
4098             ,  p_line_location_id => NULL
4099             -- <FPJ Advanced Price START>
4100             ,  p_contract_id    => interface.contract_id
4101             ,  p_org_id     => g_purchasing_ou_id
4102             ,  p_supplier_id    => interface.vendor_id
4103             ,  p_supplier_site_id => interface.vendor_site_id
4104             ,  p_creation_date    => interface.creation_date
4105             ,  p_order_header_id  => interface.po_header_id
4106             ,  p_order_line_id    => x_po_line_id
4107             ,  p_line_type_id   => interface.line_type_id
4108             ,  p_item_revision    => interface.item_revision
4109             ,  p_item_id    => interface.item_id
4110             ,  p_category_id    => interface.category_id
4111             ,  p_supplier_item_num  => interface.vendor_product_num
4112             -- Bug 3343892, pass base_unit_price
4113             -- Bug 3417479, Only pass base_unit_price
4114             -- ,  p_in_price    => NVL(interface.base_unit_price, interface.unit_price)
4115             ,  p_in_price   => interface.base_unit_price
4116             ,  p_uom      => x_unit_of_measure
4117             ,  p_currency_code          => interface.h_currency_code  -- Bug 3564863
4118             --<Bug:8598002 Enhanced Pricing Start>
4119             ,  p_pricing_call_src => l_pricing_call_src
4120             --<Enhanced Pricing End>
4121             ,  x_base_unit_price  => l_base_unit_price
4122             -- <FPJ Advanced Price END>
4123             ,  x_price_break_id   => l_price_break_id
4124             ,  x_price      => x_unit_price
4125             ,  x_return_status    => l_return_status
4126             ,  p_req_line_price => interface.unit_price   -- Bug 7154646
4127             );
4128             -- <SERVICES FPJ END>
4129 
4130       -- Bug 3733202 START
4131       -- Treat 0 price as null price
4132       -- Bug 14173355
4133       -- Treating 0 price as null price for contract source document only
4134       IF (x_unit_price = 0 AND interface.from_line_id IS NULL) THEN
4135         x_unit_price := NULL;
4136       END IF;
4137       -- Bug 3733202 END
4138 
4139             -- Bug 3417479
4140             x_unit_price := nvl(x_unit_price, interface.unit_price);
4141             l_base_unit_price := nvl(l_base_unit_price, interface.base_unit_price);
4142 
4143         ELSE
4144 
4145             x_unit_price := interface.unit_price;
4146             -- <FPJ Advanced Price START>
4147             -- Bug 3417479
4148             -- l_base_unit_price := nvl(interface.base_unit_price, x_unit_price);
4149             l_base_unit_price := interface.base_unit_price;
4150             -- <FPJ Advanced Price END>
4151 
4152         END IF;
4153 
4154          /* GA FPI end */
4155         l_progress := '360';
4156 
4157         -- <SERVICES FPJ START> If we are Autocreating a Standard PO,
4158         -- then setup the Interface tables to copy over Price Differentials.
4159         --<Bug 3268483>
4160         -- This functionality is not supported from Sourcing. One cannot
4161         -- create a Standard PO from Sourcing with Temp Labor lines (with price
4162         -- differentials).
4163         IF ( g_document_subtype = 'STANDARD' AND
4164              --<Bug 3268483>
4165              g_interface_source_code not in  ('SOURCING', 'CONSUMPTION_ADVICE')
4166            AND (NOT p_is_complex_work_po)) -- <Complex Work R12>
4167         THEN
4168 
4169             PO_PRICE_DIFFERENTIALS_PVT.setup_interface_table
4170             (   p_entity_type         => 'PO LINE'
4171             ,   p_interface_header_id => interface.interface_header_id
4172             ,   p_interface_line_id   => interface.interface_line_id
4173             ,   p_req_line_id         => interface.requisition_line_id
4174             ,   p_from_line_id        => interface.from_line_id
4175             ,   p_price_break_id      => l_price_break_id
4176             );
4177         END IF;
4178         --
4179         -- <SERVICES FPJ END>
4180 
4181         l_progress := '370';
4182         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4183             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4184                                 p_token    => l_progress,
4185                                 p_message  => 'Create_line: Line id: '||x_po_line_id);
4186             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4187                                 p_token    => l_progress,
4188                                 p_message  => 'Create_line: Header_id : '||interface.po_header_id);
4189             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4190                                 p_token    => l_progress,
4191                                 p_message  => 'Create_line: Line number: '||interface.line_num);
4192             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4193                                 p_token    => l_progress,
4194                                 p_message  => 'Create_line: TRX RSON CODE : '||interface.transaction_reason_code);
4195         END IF;
4196 
4197         l_progress := '380';
4198          -- <SERVICES FPJ START>
4199          -- Retrieve the values for order_type_lookup_code, purchase_basis
4200          -- and matching_basis
4201          PO_LINE_TYPES_SV.get_line_type_def(
4202                           interface.line_type_id,
4203                           l_order_type_lookup_code,
4204                           l_purchase_basis1,
4205                           l_matching_basis,
4206                           l_category_id,
4207                           l_unit_meas_lookup_code,
4208                           l_unit_price,
4209                           l_outside_operation_flag,
4210                           l_receiving_flag,
4211                           l_receive_close_tolerance);
4212          -- <SERVICES FPJ END>
4213 
4214    -- Bug 694504. frkhan 07/07/98. Removed decode for vendor_product_num
4215    -- so it is inserted for RFQs also.
4216 
4217 --<DBI FPJ Start>
4218 BEGIN
4219   IF g_interface_source_code='SOURCING' THEN
4220     l_negotiated_by_preparer_flag := 'Y';
4221   ELSIF interface.from_header_id is not null THEN
4222     l_progress := '390';
4223     SELECT type_lookup_code,global_agreement_flag into l_type_lookup_code,l_global_agreement_flag
4224     FROM po_headers_all
4225     WHERE po_header_id=interface.from_header_id;
4226     -- if the source document is global agreement.
4227     IF l_type_lookup_code='BLANKET' and l_global_agreement_flag='Y' THEN
4228       l_progress := '395';
4229       SELECT negotiated_by_preparer_flag into l_negotiated_by_preparer_flag
4230       FROM po_lines_all
4231       WHERE po_line_id=interface.from_line_id;
4232     --if the source document is quotation.
4233     ELSIF l_type_lookup_code='QUOTATION' THEN
4234       l_negotiated_by_preparer_flag := 'Y';
4235     -- if the source document is contract or otherwise
4236     -- <Bug 5177657> Changed ELSIF to ELSE
4237     ELSE
4238       l_progress := '400';
4239       SELECT negotiated_by_preparer_flag into l_negotiated_by_preparer_flag
4240       FROM po_requisition_lines_all
4241       WHERE requisition_line_id=interface.requisition_line_id;
4242     END IF;
4243   ELSE
4244     l_progress := '410';
4245     SELECT negotiated_by_preparer_flag into l_negotiated_by_preparer_flag
4246     FROM po_requisition_lines_all
4247     WHERE requisition_line_id=interface.requisition_line_id;
4248   END IF;
4249 EXCEPTION
4250   WHEN others THEN
4251     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4252         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4253                             p_token    => l_progress,
4254                             p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
4255     END IF;
4256     l_negotiated_by_preparer_flag:=NULL;
4257 END;
4258 -- <DBI FPJ End>
4259 
4260         l_progress := '420';
4261 
4262 	-- Bug 9324837
4263 	-- Added debug code.
4264 	IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4265             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4266                                 p_token    => l_progress,
4267                                 p_message  => 'g_document_subtype: '||g_document_subtype);
4268             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4269                                 p_token    => l_progress,
4270                                 p_message  => 'interface.item_id : '||interface.item_id);
4271 	    PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4272                                 p_token    => l_progress,
4273                                 p_message  => 'nterface.destination_organization_id: '||interface.destination_organization_id);
4274             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4275                                 p_token    => l_progress,
4276                                 p_message  => 'params.inventory_organization_id : '||params.inventory_organization_id);
4277             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4278                                 p_token    => l_progress,
4279                                 p_message  => 'item.secondary_uom_code : '||item.secondary_uom_code);
4280             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4281                                 p_token    => l_progress,
4282                                 p_message  => 'interface.secondary_quantity : '||interface.secondary_quantity);
4283         END IF;
4284 
4285   --<INVCONV R12 START>
4286   -- IF secondary quantity is null and item is dual uom control , default the secondary qty.
4287   IF (g_document_subtype='STANDARD' OR g_document_subtype='PLANNED' OR g_document_type = 'PA')
4288   THEN
4289     IF interface.item_id is not null THEN
4290        IF item.secondary_uom_code IS NOT NULL THEN
4291           IF (interface.secondary_quantity IS NULL) THEN
4292            -- Bug 9324837
4293            -- Commented out the  OR condition to interface.secondary_quantity IS NULL
4294            -- as this was causing the secondary quantity to be recalculated using std conversion.
4295            -- OR  params.inventory_organization_id <> interface.destination_organization_id ) THEN
4296              PO_UOM_S.get_secondary_uom( interface.item_id,
4297                                          interface.destination_organization_id,
4298                                          x_secondary_uom,
4299                                          x_secondary_unit_def);
4300 
4301              IF g_document_type <> 'PA' THEN
4302                 PO_UOM_S.uom_convert (x_quantity, x_unit_of_measure, interface.item_id,
4303                                       x_secondary_unit_def, x_secondary_quantity_def) ;
4304 
4305                 IF interface.destination_organization_id  = params.inventory_organization_id
4306                 THEN
4307                   interface.secondary_unit_of_measure := x_secondary_unit_def ;
4308                   interface.secondary_quantity := x_secondary_quantity_def ;
4309                 END IF;
4310              ELSE
4311                 x_secondary_quantity_def := null ;
4312              END IF;
4313           ELSE
4314              x_secondary_unit_def := interface.secondary_unit_of_measure;
4315              x_secondary_quantity_def := interface.secondary_quantity;
4316           END IF;
4317        ELSE -- IF item.secondary_uom_code IS NOT NULL
4318           x_secondary_unit_def := null;
4319           x_secondary_quantity_def := null ;
4320        END IF;
4321 
4322        IF item.grade_control_flag = 'N' and interface.preferred_grade IS NOT NULL THEN
4323           x_preferred_grade_def := null ;
4324        ELSE
4325           x_preferred_grade_def := interface.preferred_grade ;
4326        END IF;
4327 
4328     ELSE -- IF interface.item_id is not null
4329        x_secondary_unit_def := null;
4330        x_secondary_quantity_def := null ;
4331        x_preferred_grade_def    := null;
4332     END IF;
4333   ELSE
4334     x_secondary_unit_def := null;
4335     x_secondary_quantity_def := null ;
4336     x_preferred_grade_def    := null;
4337   END IF;
4338   --<INVCONV R12 END>
4339 
4340 	-- Bug 9324837
4341 	-- Added debug code.
4342 	IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4343             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4344                               p_token    => l_progress,
4345                               p_message  => 'x_secondary_unit_def : '||x_secondary_unit_def);
4346             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4347                               p_token    => l_progress,
4348                               p_message  => 'x_secondary_quantity_def : '||x_secondary_quantity_def);
4349         END IF;
4350 
4351 -- bug 4887900 START
4352 -- checking if the user has manually entered a value
4353 -- bug#5255878
4354 -- declared l_retainage_rate
4355 -- bug#5262303 interface.vendor_site_id can be null
4356 -- if the vendor/vendor_site combination is not provided
4357 -- on the autocreate window. We should query only when
4358 -- vendor_site_id is not null.
4359 -- Bug 13556601 Included complex work flag to avoid copying retainage rate for other document types.
4360     IF(interface.vendor_site_id is not null AND p_is_complex_work_po)THEN
4361         SELECT retainage_rate
4362         into l_retainage_rate
4363         FROM po_vendor_sites_all
4364         WHERE vendor_site_id = interface.vendor_site_id;
4365     END IF;
4366 -- bug 4887900 END
4367 
4368      -- Added note_to_vendor - iali 08/26/99
4369 /*Bug 1391523 . Added market price to the INSERT statement */
4370         INSERT INTO po_lines_all  --<Shared Proc FPJ>
4371         (    po_line_id,
4372              last_update_date,
4373              last_updated_by,
4374              po_header_id,
4375              line_num,
4376              creation_date,
4377              created_by,
4378              last_update_login,
4379              item_id,
4380              job_id,                                          -- <SERVICES FPJ>
4381              category_id,
4382              item_description,
4383              unit_meas_lookup_code,
4384              list_price_per_unit,
4385              market_price,
4386              base_unit_price,             -- <FPJ Advanced Price>
4387              unit_price,
4388              quantity,
4389              amount,                                          -- <SERVICES FPJ>
4390              taxable_flag,
4391              type_1099,
4392              negotiated_by_preparer_flag,
4393              closed_code,
4394              item_revision,
4395              un_number_id,
4396              hazard_class_id,
4397              -- contract_num,   -- <GC FPJ>
4398              contract_id,        -- <GC FPJ>
4399              line_type_id,
4400              vendor_product_num,
4401              qty_rcv_tolerance,
4402              over_tolerance_error_flag,
4403              firm_status_lookup_code,
4404              min_release_amount,
4405              price_type_lookup_code,
4406              transaction_reason_code,
4407              from_header_id,
4408              from_line_id,
4409              from_line_location_id,                           -- <SERVICES FPJ>
4410              project_id,
4411              task_id,
4412              note_to_vendor,
4413              --togeorge 09/27/2000
4414              --added oke columns
4415              oke_contract_header_id,
4416              oke_contract_version_id,
4417              --togeorge 11/17/2000
4418              --Bug# 1369049
4419              --Added logic to default tax_name in po_lines
4420              tax_name,
4421              -- start of 1548597
4422              secondary_unit_of_measure,
4423              secondary_quantity,
4424              preferred_grade,
4425              -- end of  1548597
4426              --<SOURCING TO PO FPH START>
4427              auction_header_id,
4428              auction_line_number,
4429              auction_display_number,
4430              bid_number,
4431              bid_line_number,
4432              quantity_committed,    --Bug# 2288408
4433              committed_amount,    --Bug# 2288408
4434              --<SOURCING TO PO FPH END>
4435              --Bug #2715037
4436              price_break_lookup_code,
4437              supplier_ref_number, --<CONFIG_ID FPJ>
4438              org_id,  --<Shared Proc FPJ>
4439              start_date,                                      -- <SERVICES FPJ>
4440              expiration_date,                                 -- <SERVICES FPJ>
4441              contractor_first_name,                           -- <SERVICES FPJ>
4442              contractor_last_name,                            -- <SERVICES FPJ>
4443              order_type_lookup_code,                          -- <SERVICES FPJ>
4444              purchase_basis,                                  -- <SERVICES FPJ>
4445              matching_basis                                   -- <SERVICES FPJ>
4446              -- <Complex Work R12 Start>
4447            , retainage_rate
4448            , max_retainage_amount
4449            , progress_payment_rate
4450            , recoupment_rate             -- <Complex Work R12 End>
4451      ,tax_attribute_update_code --<eTax Integration R12>
4452             , ip_category_id      --Bug#4656615
4453             , supplier_part_auxid --Bug#4656615
4454             , catalog_name        --Bug#4656615
4455 
4456       )
4457     VALUES (x_po_line_id,
4458                         interface.last_update_date,
4459                         interface.last_updated_by,
4460                         interface.po_header_id,
4461                         interface.line_num,
4462                         interface.creation_date,
4463                         interface.created_by,
4464                         interface.last_update_login,
4465                         interface.item_id,
4466                         interface.job_id,                     -- <SERVICES FPJ>
4467                         interface.category_id,
4468                         interface.item_description,
4469                         x_unit_of_measure, -- Bug 2735840
4470         --<SOURCING TO PO FPH >Bug# 2288408
4471         --sourcing populates the unit price in bidder's currency, so we are
4472         -- not converting the currency. And sourcing does not have
4473   --list_price_per_unit and market price stored in their system,
4474   --so dont do the following for sourcing
4475    -- Bug 3472140: Changed precisions to 15 from 5
4476    -- Bug 3808903: Changed rounding to use extended_precision
4477                         decode(g_document_type, 'RFQ', null,
4478       decode(g_interface_source_code,'SOURCING',null,
4479                              ROUND(item.list_price_per_unit,nvl(x_ext_precision,15)))),
4480                              ROUND(item.market_price,nvl(x_ext_precision,15)), ---11781326
4481     --
4482 -- Bug 1353736   use precision in rounding
4483 /* Bug: 2000367  When there is no currency conversion involved we should not
4484                  round at all because it gives rise to inconsistency.
4485                  So removing the ext precision and blind rounding to 5 also as
4486                  this is already done above in case when currency conversion is
4487                  involved.
4488 */
4489                         l_base_unit_price  , --interface.base_unit_price, -- <FPJ Advanced Price>
4490                         x_unit_price  , --interface.unit_price,
4491                         --<SOURCING TO PO FPH>
4492       --quantity sould be null for a blanket
4493                         decode(g_document_type, 'RFQ', 1,'PA',null, x_quantity),
4494                         interface.amount,                     -- <SERVICES FPJ>
4495                         nvl(item.taxable_flag,params.taxable_flag),
4496                         decode(g_document_type, 'RFQ', null,
4497         vendor.type_1099),
4498                         l_negotiated_by_preparer_flag, --<DBI FPJ>
4499                         interface.l_closed_code,
4500                         interface.item_revision,
4501                         --<SOURCING TO PO FPH START>
4502                         decode(g_interface_source_code,'SOURCING',
4503                                x_un_number_id,interface.un_number_id),
4504                         decode(g_interface_source_code,'SOURCING',
4505              x_hazard_class_id,interface.hazard_class_id),
4506                         --<SOURCING TO PO FPH END>
4507                         -- interface.contract_num,  -- <GC FPJ>
4508                         /* Bug11802312 - Retain the document reference for a consigned PO */
4509                         interface.contract_id,       -- <GC FPJ>
4510                         interface.line_type_id,
4511                         interface.vendor_product_num,
4512 
4513 			/*bug 9155693 START-->
4514 			    While autocreating RFQ from Req. receiving controls values were set to NULL
4515 			    which cause receiving controls values reamin NULL in PO, which was created
4516 			    by copying RFQ to Quotation to PO.
4517 			    Hence, setting receving control fields to defaulted values.
4518 
4519 			 decode(g_document_type, 'RFQ', null,
4520 			    rc.qty_rcv_tolerance),
4521 			 decode(g_document_type, 'RFQ', null,
4522 			    rc.qty_rcv_exception_code),
4523 			*/
4524 
4525                         rc.qty_rcv_tolerance,
4526                         rc.qty_rcv_exception_code,
4527 		         --bug 9155693 END
4528 
4529                         interface.l_firm_status_lookup_code,
4530                         interface.l_min_release_amount,
4531                         interface.price_type_lookup_code,
4532                         interface.transaction_reason_code,
4533                         /* Bug11802312 - Retain the document reference for a consigned PO */
4534                         nvl(interface.from_header_id,x_quote_header_id),
4535                         nvl(interface.from_line_id,x_quote_line_id),
4536                        l_price_break_id,                       -- <BUG 3282527>
4537       x_project_id,
4538       x_task_id,
4539                         --<SOURCING TO PO FPH>
4540       --dont copy note to vendor for sourcing this
4541       --would come as attachments from sourcing.
4542       decode(g_interface_source_code,'SOURCING',
4543           null,interface.note_to_vendor),
4544       --interface.note_to_vendor,
4545       --
4546             --togeorge 09/27/2000
4547             --added oke columns
4548             /* Bug11802312 - Retain the document reference for a consigned PO */
4549             interface.oke_contract_header_id,
4550             interface.oke_contract_version_id,
4551             --togeorge 11/17/2000
4552             --Bug# 1369049
4553             --Added logic to default tax_name in po_lines
4554       x_tax_name,
4555 --<INVCONV R12 START>
4556 -- don't insert secondary unit/quantity/grade from interface record.
4557 -- start of 1548597
4558       x_secondary_unit_def,
4559       x_secondary_quantity_def,
4560       x_preferred_grade_def,
4561 -- end of  1548597
4562 --<INVCONV R12 END>
4563                         --<SOURCING TO PO FPH START>
4564                   interface.auction_header_id,
4565                   interface.auction_line_number,
4566             interface.auction_display_number,
4567                   interface.bid_number,
4568                   interface.bid_line_number,
4569                     decode ( g_document_type
4570                            , 'PA' , decode ( x_order_type_lookup_code
4571                                            , 'AMOUNT' , NULL
4572                                            , interface.quantity
4573                                            )
4574                            , NULL
4575                            ),
4576                     decode ( g_document_type
4577                            , 'PA' , decode ( x_order_type_lookup_code
4578                                            , 'QUANTITY' , NULL-- <SERVICES FPJ>
4579                                            , interface.committed_amount
4580                                            )
4581                            , NULL
4582                            ),
4583                         --<SOURCING TO PO FPH END>
4584                         --Bug #2715037
4585                         decode(g_interface_source_code,'SOURCING',
4586                               interface.price_break_lookup_code, null),
4587                         interface.supplier_ref_number, --<CONFIG_ID FPJ>
4588                         g_purchasing_ou_id,  --<Shared Proc FPJ>
4589                         interface.line_effective_date,        -- <SERVICES FPJ>
4590                         interface.line_expiration_date,       -- <SERVICES FPJ>
4591                         interface.contractor_first_name,      -- <SERVICES FPJ>
4592                         interface.contractor_last_name,       -- <SERVICES FPJ>
4593                         l_order_type_lookup_code,             -- <SERVICES FPJ>
4594                         l_purchase_basis1,                    -- <SERVICES FPJ>
4595                         l_matching_basis                      -- <SERVICES FPJ>
4596                         -- <Complex Work R12 Start>
4597                       , nvl(interface.retainage_rate, l_retainage_rate) -- bug 4887900 bug#5255878
4598                       , interface.max_retainage_amount
4599                       , interface.progress_payment_rate
4600                       , interface.recoupment_rate                 -- <Complex Work R12 End>
4601           ,nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax Integration R12>
4602             , interface.ip_category_id      --Bug#4656615
4603             , interface.supplier_part_auxid --Bug#4656615
4604             , interface.catalog_name        --Bug#4656615
4605       );
4606 
4607         l_progress := '430';
4608 
4609         -- <Unified Catalog R12 START>
4610         IF (g_document_subtype = 'BLANKET'  AND g_interface_source_code = 'SOURCING') THEN
4611 
4612           IF g_debug_stmt THEN PO_DEBUG.debug_stmt(d_mod,l_progress,'Storing values of PO_LINE_IDs for the Attribute interface records');END IF;
4613 
4614           l_interface_header_id_tbl(x_po_line_id) := interface.interface_header_id;
4615           l_interface_line_id_tbl(x_po_line_id) := interface.interface_line_id;
4616           l_po_line_id_tbl(x_po_line_id) := x_po_line_id;
4617         END IF;
4618         -- <Unified Catalog R12 END>
4619 
4620 
4621         -- <SERVICES FPJ START> Insert Price Differentials into main table
4622         -- from the interface table.
4623         --
4624         PO_PRICE_DIFFERENTIALS_PVT.create_from_interface
4625         (   p_entity_id         => x_po_line_id
4626         ,   p_interface_line_id => interface.interface_line_id
4627         );
4628         -- <SERVICES FPJ END>
4629 
4630         l_progress := '440';
4631 
4632 /* Bug 2962568 globalization procedure shouldn't be called for Standard RFQ's
4633    as it is not significant for the same.
4634 */
4635             if g_document_type = 'RFQ' then
4636                null;
4637             elsif (interface.document_subtype = 'STANDARD' or
4638                 interface.document_subtype = 'PLANNED'  or
4639                 --<SOURCING TO PO FPH START>
4640                 interface.document_subtype = 'BLANKET'
4641     ) THEN
4642 
4643                 -- Bug 882050: Line level global attribute
4644                 -- <Bug 8513167>
4645                 -- Now passing document_subtype instead of 'PO'
4646                 calculate_local(interface.document_subtype, 'LINE', x_po_line_id);
4647 
4648             end if;
4649 
4650          END IF;
4651 
4652    ELSE /* If line exists */
4653 
4654         l_progress := '450';
4655         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4656             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4657                                 p_token    => l_progress,
4658                                 p_message  => 'Line does exist: '||x_po_line_id);
4659         END IF;
4660 
4661       --<SOURCING TO PO FPH START>
4662       --lines are grouped, so dont copy any attachments from sourcing(copy only
4663       --from the req)
4664       IF g_interface_source_code='SOURCING' then
4665          x_attch_suppress_flag  :='Y';
4666       END IF;
4667       --<SOURCING TO PO FPH END>
4668 
4669       IF(interface.item_id is not null) THEN
4670 
4671    /*
4672     * bug 1009734 : extention of bug 919204
4673     * made the receive close and invoice close tolerance to be picked up
4674     * from the lowest existing level by splitting the select.
4675     * HAD TO DO THE SAME EVEN IF PO LINE ID IS NOT NULL
4676     * ONLY FOR INVOICE CLOSE TOLERANCE AND RECEIVE CLOSE TOLERANCE
4677     */
4678 
4679       l_progress := '460';
4680 /* Bug# 1702702 - RSHAHI:  Start fix
4681     ** Need to do the same even if po line id is not null
4682     ** for receipt_required_flag and inspection_required_flag too
4683 */
4684          begin
4685           SELECT msi.invoice_close_tolerance,
4686                  msi.receive_close_tolerance,
4687                  msi.receipt_required_flag,
4688                  msi.inspection_required_flag
4689             INTO item.invoice_close_tolerance,
4690                  item.receive_close_tolerance,
4691                  item.receipt_required_flag,
4692                  item.inspection_required_flag
4693             FROM mtl_system_items msi
4694            WHERE msi.inventory_item_id = interface.item_id
4695              AND msi.organization_id   = interface.destination_organization_id;
4696 
4697           exception
4698                when no_data_found then
4699                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4700                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4701                                             p_token    => l_progress,
4702                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4703                     END IF;
4704                WHEN OTHERS THEN
4705                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4706                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4707                                            p_progress => l_progress);
4708                     END IF;
4709                     wrapup(x_interface_header_id);
4710                     po_message_s.sql_error('Get Item/Org defaults',l_progress,sqlcode);
4711                     raise;
4712           end;
4713       l_progress := '470';
4714 -- Bug: 1702702
4715          begin
4716           SELECT nvl(item.invoice_close_tolerance,msi.invoice_close_tolerance),
4717                  nvl(item.receive_close_tolerance,msi.receive_close_tolerance),
4718                  nvl(item.receipt_required_flag,msi.receipt_required_flag),
4719                  nvl(item.inspection_required_flag,msi.inspection_required_flag),
4720                  decode(msi.tracking_quantity_ind,
4721                         g_chktype_TRACKING_QTY_IND,
4722                         msi.secondary_uom_code,NULL) --<INVCONV R12>
4723             INTO item.invoice_close_tolerance,
4724                  item.receive_close_tolerance,
4725                  item.receipt_required_flag,
4726                  item.inspection_required_flag,
4727                  item.secondary_uom_code --<INVCONV R12>
4728             FROM mtl_system_items msi
4729            WHERE msi.inventory_item_id = interface.item_id
4730              AND msi.organization_id = params.inventory_organization_id;
4731           exception
4732                when no_data_found then
4733                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4734                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4735                                             p_token    => l_progress,
4736                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4737                     END IF;
4738                WHEN OTHERS THEN
4739                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4740                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4741                                            p_progress => l_progress);
4742                     END IF;
4743                     wrapup(x_interface_header_id);
4744                     po_message_s.sql_error('Get Item/Master org defaults',l_progress,sqlcode);
4745                     raise;
4746           end;
4747       ELSE  -- added by jbalakri for bug 2348729
4748 
4749 /* This case will reach when the item_id is null */
4750 /* Bug#2674947 We need to initialize market_price also */
4751           item.market_price := '';
4752           item.invoice_close_tolerance := '';
4753           item.receive_close_tolerance := '';
4754           item.inspection_required_flag := '';
4755           item.receipt_required_flag := '';
4756           item.secondary_uom_code := ''; --<INVCONV R12>
4757 
4758       END IF; -- item id is not null Bug #2102149
4759       l_progress := '480';
4760 -- Bug: 1702702
4761           begin
4762                SELECT nvl(item.receive_close_tolerance,receipt_close),
4763                       nvl(item.receipt_required_flag,receiving_flag)
4764                INTO item.receive_close_tolerance,
4765                     item.receipt_required_flag
4766                FROM po_line_types_v
4767                WHERE line_type_id = interface.line_type_id;
4768           exception
4769                when no_data_found then
4770                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4771                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4772                                             p_token    => l_progress,
4773                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4774                     END IF;
4775                WHEN OTHERS THEN
4776                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4777                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4778                                            p_progress => l_progress);
4779                     END IF;
4780                     wrapup(x_interface_header_id);
4781                     po_message_s.sql_error('Get Line type default',l_progress,sqlcode);
4782                     raise;
4783           end;
4784 
4785       l_progress := '490';
4786 
4787 /*  Bug: 2106201 Select receipt required flag,inspection required flag
4788                  at vendor level before system option level to complete the
4789                  default logic
4790 */
4791   Begin
4792           select nvl(item.inspection_required_flag,
4793                                 vendor.INSPECTION_REQUIRED_FLAG),
4794                   nvl(item.receipt_required_flag,
4795                                 vendor.RECEIPT_REQUIRED_FLAG)
4796               into item.inspection_required_flag,
4797                   item.receipt_required_flag
4798               from po_vendors vendor
4799           where   vendor.vendor_id = interface.vendor_id;
4800 
4801       Exception
4802           when no_data_found then
4803                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4804                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4805                                         p_token    => l_progress,
4806                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4807                 END IF;
4808           WHEN OTHERS THEN
4809                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4810                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4811                                        p_progress => l_progress);
4812                 END IF;
4813               wrapup(x_interface_header_id);
4814               po_message_s.sql_error('Get vendor default',l_progress,sqlcode);
4815               raise;
4816       End;
4817 
4818       l_progress := '500';
4819 
4820 /* Bug: 1322342 Select receipt required flag,inspection required flag
4821                 receipt close tolerance and insp close tolerance
4822                 also from po system parameters if not defined at above level
4823 */
4824     Begin
4825         select nvl(item.inspection_required_flag,
4826                                 posp.INSPECTION_REQUIRED_FLAG),
4827                 nvl(item.receipt_required_flag,
4828                                 posp.RECEIVING_FLAG),
4829                 nvl(item.invoice_close_tolerance,
4830                                 posp.INVOICE_CLOSE_TOLERANCE),
4831                 nvl(item.receive_close_tolerance,
4832                                 posp.RECEIVE_CLOSE_TOLERANCE)
4833             into    item.inspection_required_flag,
4834                 item.receipt_required_flag,
4835                 item.invoice_close_tolerance,
4836                 item.receive_close_tolerance
4837            FROM po_system_parameters_all posp  --<Shared Proc FPJ>
4838           WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
4839 
4840     Exception
4841         when no_data_found then
4842             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4843                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4844                                     p_token    => l_progress,
4845                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4846             END IF;
4847         WHEN OTHERS THEN
4848             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4849                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4850                                    p_progress => l_progress);
4851             END IF;
4852             wrapup(x_interface_header_id);
4853             po_message_s.sql_error('Get po system default',l_progress,sqlcode);
4854             raise;
4855     End;
4856 
4857       l_progress := '510';
4858 -- Bug: 1322342 If not defined at po system option level also then
4859 
4860         IF (item.inspection_required_flag is NULL) THEN
4861             item.inspection_required_flag := 'N';
4862         END IF;
4863 
4864         IF (item.receipt_required_flag is  NULL) THEN
4865             item.receipt_required_flag := 'N';
4866         END IF;
4867         IF (item.invoice_close_tolerance is NULL) THEN
4868             item.invoice_close_tolerance := '0';
4869         END IF;
4870 
4871         IF (item.receive_close_tolerance is NULL) THEN
4872             item.receive_close_tolerance := '0';
4873         END IF;
4874 
4875        --ELSE Bug #2102149
4876   /* Bug #2102149
4877     item.invoice_close_tolerance := '';
4878     item.receive_close_tolerance := '';
4879 -- Bug: 1702702
4880           item.inspection_required_flag := '';
4881           item.receipt_required_flag := '';
4882 
4883        END IF;
4884        */
4885 
4886 -- Bug: End fix 1702702
4887 
4888       IF (g_document_type = 'PO') THEN
4889 
4890          l_progress:='520';
4891         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4892             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4893                                 p_token    => l_progress,
4894                                 p_message  => 'Create_line: Po line exists');
4895         END IF;
4896 
4897         -- <BUG 3322948> Perform currency conversion on price/amount/quantity.
4898         --
4899         PO_INTERFACE_S.do_currency_conversion(
4900           p_order_type_lookup_code => x_order_type_lookup_code,
4901           p_interface_source_code  => g_interface_source_code,
4902           p_rate                   => l_rate_for_req_fields, -- <ACHTML R12>
4903           p_po_currency_code       => interface.h_currency_code,
4904           p_requisition_line_id    => interface.requisition_line_id,
4905           x_quantity               => x_quantity, -- IN/OUT
4906           x_unit_price             => interface.unit_price, -- IN/OUT
4907           x_base_unit_price        => interface.base_unit_price, -- IN/OUT
4908                                                                  -- <Bug 3401653>
4909           x_amount                 => interface.amount -- IN/OUT
4910         );
4911 
4912       l_progress := '530';
4913 
4914          /* handled the null value for quantity in the following update statement.
4915             bug 935866 */
4916          -- update secondary quantity to somevalue only if old or new secondary_quantity is not null else update it
4917          -- to null(for discrete items) - 1548597
4918 
4919          --Bug:8598002
4920          /* GA FPI start : For a standard PO if the source document exists or if the
4921             enhanced pricing style is used then we call the pricing API to get the
4922             correct price for the parameters on the requisition */
4923          IF (g_document_subtype='STANDARD')
4924             AND nvl(l_manual_price_change_flag, 'N') <> 'Y' --bug 3495772
4925             AND (interface.from_line_id IS NOT NULL OR
4926                  -- <FPJ Advanced Price START>
4927                  interface.contract_id IS NOT NULL OR
4928                   l_enhanced_pricing_flag = 'Y') --Enhanced Pricing: Enable pricing call if pricing enhanced for the style selected
4929                  -- <FPJ Advanced Price END>
4930             AND  g_interface_source_code <> 'CONSUMPTION_ADVICE'  THEN
4931             /*bug#2723479 In this case, we will be updating an existing po
4932              *line by adding a req line to it. So we use the combined quantity
4933              *(existing po qty + req qty) when calling the pricing API. */
4934             l_progress := '540';
4935       begin
4936     select pl.quantity
4937         into l_db_quantity
4938         from po_lines_all pl  --<Shared Proc FPJ>
4939         where pl.po_line_id = x_po_line_id;
4940       exception
4941     when others then
4942                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4943                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4944                                         p_token    => l_progress,
4945                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
4946                 END IF;
4947       end;
4948 
4949             l_progress := '550';
4950             -- Bug 3201308
4951             -- We get the pricing criteria from the min shipment if the grouping
4952             -- profiles are set such that multiple shipments get created when
4953             -- need by or ship to info are different on different lines.
4954 
4955             PO_SOURCING2_SV.get_min_shipment_num(x_po_line_id,l_min_shipment_num);
4956 
4957             l_progress := '560';
4958             BEGIN
4959                  select poll.ship_to_location_id,
4960                         poll.ship_to_organization_id,
4961                         poll.need_by_date
4962                  into   l_ship_to_loc,
4963                         l_ship_to_org,
4964                         l_need_by_date
4965                  from   po_line_locations_all poll
4966                  where  poll.po_line_id =  x_po_line_id
4967                  and    poll.shipment_num = l_min_shipment_num;
4968             EXCEPTION
4969                   when others then
4970                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4971                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4972                                             p_token    => l_progress,
4973                                             p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
4974                     END IF;
4975             END;
4976 
4977             -- Get the profile option values to determine grouping criteria
4978 
4979             l_needby_prf := fnd_profile.value('PO_NEED_BY_GROUPING');
4980             l_shipto_prf := fnd_profile.value('PO_SHIPTO_GROUPING');
4981 
4982             IF nvl(l_needby_prf,'Y') = 'Y' THEN
4983                l_need_by_date := interface.need_by_date;
4984             END IF;
4985 
4986             l_progress := '570';
4987 
4988             IF nvl(l_shipto_prf,'Y') = 'Y' THEN
4989                l_ship_to_org :=  interface.destination_organization_id;
4990                l_ship_to_loc :=  get_ship_to_loc(interface.deliver_to_location_id);
4991             END IF;
4992 
4993             l_progress := '580';
4994             -- <FPJ Advanced Price START>
4995             PO_SOURCING2_SV.get_break_price
4996             (  p_api_version       => 1.0
4997             ,  p_order_quantity    => x_quantity + nvl(l_db_quantity,0)
4998             ,  p_ship_to_org       => l_ship_to_org           -- Bug 3201308
4999             ,  p_ship_to_loc       => l_ship_to_loc           -- Bug 3201308
5000             ,  p_po_line_id        => interface.from_line_id
5001             ,  p_cum_flag          => FALSE
5002             ,  p_need_by_date      => l_need_by_date          -- Bug 3201308
5003             ,  p_line_location_id  => NULL
5004             ,  p_contract_id       => interface.contract_id
5005             ,  p_org_id            => g_purchasing_ou_id
5006             ,  p_supplier_id       => interface.vendor_id
5007             ,  p_supplier_site_id  => interface.vendor_site_id
5008             ,  p_creation_date     => interface.creation_date
5009             ,  p_order_header_id   => interface.po_header_id
5010             ,  p_order_line_id     => x_po_line_id
5011             ,  p_line_type_id      => interface.line_type_id
5012             ,  p_item_revision     => interface.item_revision
5013             ,  p_item_id           => interface.item_id
5014             ,  p_category_id       => interface.category_id
5015             ,  p_supplier_item_num => interface.vendor_product_num
5016             -- Bug 3343892, pass base_unit_price
5017             -- Bug 3417479, only pass base_unit_price
5018             -- ,  p_in_price          => NVL(interface.base_unit_price, interface.unit_price)
5019             ,  p_in_price          => interface.base_unit_price
5020             ,  p_uom               => x_unit_of_measure
5021             ,  p_currency_code     => interface.h_currency_code  -- Bug 3564863
5022             --<Bug:8598002 Enhanced Pricing Start>
5023             ,  p_pricing_call_src     => l_pricing_call_src
5024             --<Enhanced Pricing End>
5025             ,  x_base_unit_price   => l_base_unit_price
5026             ,  x_price_break_id    => l_price_break_id
5027             ,  x_price             => x_unit_price
5028             ,  x_return_status     => l_return_status
5029             );
5030             -- <FPJ Advanced Price END>
5031 
5032       -- Bug 3733202 START
5033       -- Treat 0 price as null price
5034       IF (x_unit_price = 0) THEN
5035         x_unit_price := NULL;
5036       END IF;
5037       -- Bug 3733202 END
5038 
5039              -- Bug 2879460 Update the price on the PO only with the price
5040              -- from the pricing API and not with the interface price
5041 
5042             UPDATE po_lines_all
5043             -- Bug 3417479
5044             -- SET   unit_price = x_unit_price,
5045             --       base_unit_price = l_base_unit_price,
5046             SET   unit_price = nvl(x_unit_price, unit_price),
5047                   base_unit_price = nvl(l_base_unit_price, base_unit_price),
5048                   from_line_location_id = l_price_break_id      -- <BUG 3282527>
5049             WHERE po_line_id = x_po_line_id;
5050 
5051             --<Bug 3313010 mbhargav START>
5052             --All the shipments which have been created need to get the
5053             --new price as on the line for Standard POs.
5054             UPDATE po_line_locations_all
5055             -- Bug 3417479
5056             -- SET price_override = x_unit_price
5057             SET price_override = nvl(x_unit_price, price_override)
5058             -- Bug 4902592. Not setting tax_attribute_update_code here because
5059             -- it should be passed as CREATE during tax calculation
5060             WHERE po_line_id = x_po_line_id;
5061             --<Bug 3313010 mbhargav END>
5062 
5063          END IF;
5064 
5065          /* GA FPI end */
5066 
5067        l_progress := '590';
5068        --<BUG 2698737 mbhargav START>
5069        --This update should not happen for RELEASES as this would update the BLANKET with REQ price
5070        -- because x_po_line_id is the blanket line_id for 'Release'
5071        -- Introducing the 'If' statement for checking that its not a release
5072        IF (g_document_subtype <> 'RELEASE') THEN
5073 
5074      /** If FSP org and item combination is dual uom control, update the po lines secondary quantity
5075       with the default conversion based on the PO lines quantity **/
5076 
5077        --<INVCONV R12> update secondary quantity/uom to null
5078 
5079 	-- Bug 9324837
5080         -- Added debug.
5081 	IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5082 
5083           	PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5084                               p_token    => l_progress,
5085                               p_message  => 'interface.secondary_quantity' || interface.secondary_quantity);
5086           	PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5087                               p_token    => l_progress,
5088                               p_message  => ' x_quantity' || x_quantity);
5089            	PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5090                               p_token    => l_progress,
5091                               p_message  => 'x_secondary_quantity_def' || x_secondary_quantity_def);
5092       	END IF;
5093 
5094       	 -- Bug 9324837
5095       	 -- Added update to secondary_quantity and commented the seconday null updates.
5096          UPDATE po_lines_all  --<Shared Proc FPJ>
5097 --fix 8976669
5098 --Added a Decode for the nvl function as quantity should not be set to 0 for Fixed Price Services
5099 	SET quantity = Decode(x_order_type_lookup_code,'FIXED PRICE',NULL,Nvl(quantity,0)) + nvl(x_quantity,0),
5100 	     secondary_quantity = (CASE        -- secondary uom controlled item
5101              			   WHEN g_chktype_TRACKING_QTY_IND = 'PS'
5102              			   THEN  secondary_quantity + x_secondary_quantity_def
5103              			   ELSE NULL
5104             			   END),
5105 --Added update for amount in the line level
5106 	     amount = Nvl(amount,0) + x_amount,
5107              last_update_date  = interface.last_update_date,
5108              last_updated_by   = interface.last_updated_by,
5109              last_update_login = interface.last_update_login,
5110              closed_code = 'OPEN',
5111              closed_date = NULL,
5112 -- Bug 1199462 Amitabh
5113              closed_by   = NULL
5114              --secondary_quantity = null, --<INVCONV R12>
5115              --secondary_unit_of_measure = null --<INVCONV R12>
5116          WHERE po_line_id = x_po_line_id
5117          RETURNING quantity INTO l_quantity_temp; --<INVCONV R12>
5118 
5119          --<INVCONV R12 START>
5120          IF (item.secondary_uom_code IS NOT NULL
5121              AND l_quantity_temp > 0
5122              AND  x_secondary_quantity_def IS NULL ) THEN -- bug 9324837
5123             SELECT unit_of_measure
5124             INTO   x_secondary_unit_def
5125             FROM   mtl_units_of_measure
5126             WHERE  uom_code = item.secondary_uom_code ;
5127 
5128             PO_UOM_S.uom_convert (l_quantity_temp,
5129                                   x_unit_of_measure,
5130                                   interface.item_id,
5131                                   x_secondary_unit_def,
5132                                   x_secondary_quantity_def) ;
5133 
5134             UPDATE po_lines_all
5135             SET secondary_quantity = x_secondary_quantity_def,
5136                 secondary_unit_of_measure = x_secondary_unit_def
5137             WHERE po_line_id = x_po_line_id ;
5138 
5139          END IF;
5140          --<INVCONV R12 END>
5141 
5142        END IF; --Release check for update
5143        --<BUG 2698737 mbhargav END>
5144 
5145       END IF;
5146    END IF;
5147 
5148      l_progress := '600';
5149 
5150     l_progress := '610';
5151     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5152         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5153                             p_token    => l_progress,
5154                             p_message  => 'Before going to create shipments');
5155     END IF;
5156 
5157    --<RENEG BLANKET FPI START>
5158    /* Create the shipment  or price break*/
5159    -- if the request is coming from Sourcing and document is Blanket
5160    -- then call create_price_break else call create_shipment
5161    IF g_document_subtype = 'BLANKET'
5162    THEN
5163      IF (g_interface_source_code = 'SOURCING'
5164          AND nvl(interface.shipment_type,'NONE') = 'PRICE BREAK')
5165      THEN
5166        create_price_break(x_po_line_id,
5167         x_line_location_id,
5168         l_outsourced_assembly); --<SHIKYU R12>
5169      END IF;
5170    -- <Complex Work R12 Start>
5171    ELSIF (p_is_complex_work_po)
5172    THEN
5173 
5174      -- x_line_location_id will be line_location_id of first actuals pay items.
5175      -- l_line_loc_id_tbl will return ids of all pay items created
5176 
5177      create_payitems(
5178        p_interface_line_id  => interface.interface_line_id
5179      , p_po_line_id         => x_po_line_id
5180      , p_precision          => x_precision
5181      , p_ext_precision      => x_ext_precision
5182      , x_line_location_id   => x_line_location_id
5183      , x_line_loc_id_tbl    => l_line_loc_id_tbl
5184      );
5185 
5186    -- <Complex Work R12 End>
5187    ELSE
5188      create_shipment(
5189        x_po_line_id,
5190        l_rate_for_req_fields, -- <ACHTML R12>
5191        x_line_location_id,
5192        l_outsourced_assembly --<SHIKYU R12>
5193      );
5194    END IF;
5195 
5196   /* Following Code commented as the below stated condition is included in
5197       FPI code above*/
5198    --<SOURCING TO PO FPH>
5199    --No need to create shipments for BLANKETS
5200    /*
5201    if g_document_subtype <>'BLANKET' then
5202    create_shipment(x_po_line_id,
5203                    x_line_location_id);
5204    end if;
5205    */
5206    --<RENEG BLANKET FPI END>
5207 
5208    l_progress:='620';
5209 
5210     -- <SERVICES FPJ START>
5211     --
5212     ---------------------------------------------------------------------------
5213     -- Req Line (TEXT) -> PO Line (Attachment) --------------------------------
5214     ---------------------------------------------------------------------------
5215     -- "Temp Labor" Lines have a Job Long Description, which resides on the
5216     -- Requisition Line as a LONG Text column, but needs to be copied over
5217     -- as an attachment on the PO Line.
5218     --
5219     IF ( l_purchase_basis = 'TEMP LABOR' ) THEN
5220 
5221         -- Get the Job Long Description from the Req Line.
5222         --
5223         l_job_long_description := PO_SERVICES_PVT.get_job_long_description
5224                                   (    p_req_line_id => interface.requisition_line_id
5225                                   );
5226 
5227         -- If Job Long Description exists, convert it to an attachment.
5228         --
5229         IF ( l_job_long_description IS NOT NULL ) THEN
5230 
5231             -- Initialize Standard WHO Columns.
5232             --
5233             l_who_rec.created_by := interface.created_by;
5234             l_who_rec.creation_date := interface.creation_date;
5235             l_who_rec.last_update_login := interface.last_update_login;
5236             l_who_rec.last_updated_by := interface.last_updated_by;
5237             l_who_rec.last_update_date := interface.last_update_date;
5238 
5239             l_progress := '630';
5240 
5241             -- Call Text-to-Attachment Conversion procedure
5242             --
5243             PO_NEGOTIATIONS_SV2.convert_text_to_attachment
5244             (   p_long_text      => l_job_long_description
5245             ,   p_description    => NULL
5246             ,   p_category_id    => 33                    -- To Supplier
5247             ,   p_to_entity_name => 'PO_LINES'
5248             ,   p_to_pk1_value   => x_po_line_id
5249             ,   p_who_rec        => l_who_rec
5250             );
5251 
5252         END IF; -- ( l_job_long_description IS NOT NULL )
5253 
5254     END IF; -- ( l_purchase_basis = 'TEMP LABOR' )
5255     --
5256     -- <SERVICES FPJ END>
5257 
5258 
5259 /*Bug # 712445 smathur*/
5260 /*For Releases copy attachments to PO_SHIPMENTS */
5261 
5262    if (g_document_subtype = 'RELEASE') and g_interface_source_code <> 'CONSUMPTION_ADVICE' then
5263                                                                        -- CONSIGNED FPI
5264 
5265    l_progress := '640';
5266    --  API to copy attachments from requisition line to release shipment
5267    fnd_attached_documents2_pkg.
5268        copy_attachments('REQ_LINES',
5269       interface.requisition_line_id,
5270       '',
5271       '',
5272       '',
5273       '',
5274       'PO_SHIPMENTS',
5275       x_line_location_id,
5276       '',
5277       '',
5278       '',
5279       '',
5280       interface.created_by,
5281       interface.last_update_login,
5282       '',
5283       '',
5284       '');
5285 
5286    l_progress:='650';
5287 
5288    -- Copy of the requisition header attachements to the purchase
5289    -- order line.
5290    SELECT requisition_header_id
5291    INTO   x_requisition_header_id
5292    FROM   po_requisition_lines_all  --<Shared Proc FPJ>
5293    WHERE  requisition_line_id = interface.requisition_line_id;
5294 
5295    l_progress:='660';
5296 
5297    fnd_attached_documents2_pkg.
5298       copy_attachments('REQ_HEADERS',
5299       x_requisition_header_id,
5300       '',
5301       '',
5302       '',
5303       '',
5304       'PO_SHIPMENTS',
5305       x_line_location_id,
5306       '',
5307       '',
5308       '',
5309       '',
5310       interface.created_by,
5311       interface.last_update_login,
5312       '',
5313       '',
5314       '');
5315     else /*smathur*/
5316    --  API to copy attachments from requisition line to po line
5317    --<SOURCING TO PO FPH>
5318 
5319 /* Copying the attachments functionaliy needs to work as following.
5320    when g_interface_source_code='SOURCING'
5321   1.The existing fnd_attched_documents2_pkg.copy_attachments will not
5322     be copying any attachments.
5323     The new API po_negotiations_sv2.handle_sourcing_attachments would
5324     take care of the following.
5325         2.Copy all the attachments from the negotiation line/header
5326     as supplier type attachment to this PO line. For a blanket,
5327     this would suppress all the attachments copied to negotiation
5328     from requisition and copy only the newly created supplier type
5329     attachment(on the negotiation) to the blanket line.
5330   3.All the attachments from the Bid line/Header would be copied to this
5331     PO line/Blanketline as internal to PO type of attachments.
5332         4.Bid attributes would be converted dynamically to a supplier type of
5333     attachment and attached to this PO line/Blanket line.
5334         5.Notes from negotiation header/line and bid header/line
5335     would be copied to po/blanket line as supplier type attachment.
5336         6.Notes from bid header/line
5337     would be copied to po/blanket line as supplier type attachment.
5338 */
5339 
5340     if g_interface_source_code not in ('SOURCING','CONSUMPTION_ADVICE') then   -- CONSIGNED FPI
5341       l_progress := '670';
5342    fnd_attached_documents2_pkg.
5343        copy_attachments('REQ_LINES',
5344       interface.requisition_line_id,
5345       '',
5346       '',
5347       '',
5348       '',
5349       'PO_LINES',
5350       x_po_line_id,
5351       '',
5352       '',
5353       '',
5354       '',
5355       interface.created_by,
5356       interface.last_update_login,
5357       '',
5358       '',
5359       '');
5360 
5361    l_progress:='680';
5362 
5363    -- Copy of the requisition header attachements to the purchase
5364    -- order line.
5365    SELECT requisition_header_id
5366    INTO   x_requisition_header_id
5367    FROM   po_requisition_lines_all  --<Shared Proc FPJ>
5368    WHERE  requisition_line_id = interface.requisition_line_id;
5369 
5370    l_progress:='690';
5371 
5372    fnd_attached_documents2_pkg.
5373       copy_attachments('REQ_HEADERS',
5374       x_requisition_header_id,
5375       '',
5376       '',
5377       '',
5378       '',
5379       'PO_LINES',
5380       x_po_line_id,
5381       '',
5382       '',
5383       '',
5384       '',
5385       interface.created_by,
5386       interface.last_update_login,
5387       '',
5388       '',
5389       '');
5390 
5391     end if;
5392     end if; /*end of changes : smathur*/
5393 
5394     l_progress := '700';
5395     --<SOURCING TO PO FPH START>
5396     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5397         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5398                             p_token    => l_progress,
5399                             p_message  => 'Sourcing to FPH-3 starts');
5400     END IF;
5401 
5402     --copy attachments/notes from negotiation/bid to po/blanket line
5403     if g_interface_source_code = 'SOURCING' then
5404        if interface.document_subtype = 'STANDARD' then
5405           if interface.requisition_line_id is not null then
5406              x_column1:='NEGREQ';
5407              l_progress:='710';
5408          SELECT requisition_header_id
5409            INTO x_requisition_header_id
5410                FROM po_requisition_lines_all  --<Shared Proc FPJ>
5411               WHERE requisition_line_id =interface.requisition_line_id;
5412           else
5413              x_column1:='NEG';
5414           end if;
5415        elsif interface.document_subtype = 'BLANKET' then
5416           x_column1:='NEG';
5417        end if;
5418        if interface.document_subtype in ('BLANKET','STANDARD') then
5419           l_progress:='720';
5420 
5421           po_negotiations_sv2.handle_sourcing_attachments(
5422       interface.auction_header_id,
5423       interface.auction_line_number,
5424       interface.bid_number,
5425       interface.bid_line_number,
5426       x_requisition_header_id,
5427       interface.requisition_line_id,
5428       x_po_line_id,
5429       x_column1,
5430       x_attch_suppress_flag,
5431       interface.created_by,
5432       interface.last_update_login);
5433 
5434        end if;
5435     end if;
5436 
5437     l_progress := '730';
5438     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5439         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5440                             p_token    => l_progress,
5441                             p_message  => 'Sourcing to FPH-3 Ends');
5442     END IF;
5443     --<SOURCING TO PO FPH END>
5444 
5445    -- Bug 2875346 start.
5446    -- If autocreating a SPO or PPO, and the requisition line has a one-time
5447    -- location, move the attachment from the PO line to the PO shipment
5448    IF (g_document_subtype IN ('STANDARD', 'PLANNED')) AND
5449       (has_one_time_location(interface.requisition_line_id))
5450    THEN
5451         -- Bug 2894378. Use BEGIN-EXCEPTION-END for exception handling to
5452         -- support original FPH behavior.
5453         BEGIN
5454 
5455             l_progress := '740';
5456 
5457             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5458                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5459                                     p_token    => l_progress,
5460                                     p_message  => 'Before selecting one-time attachment');
5461             END IF;
5462 
5463             --SQL What: Locate the one-time location attachment currently under
5464             --          the PO_LINES entity by it's unique iP identifier prefix
5465             --SQL Why: Need the attached_document_id to move the attachment
5466 
5467             SELECT fad.attached_document_id
5468             INTO   l_one_time_att_doc_id
5469             FROM   fnd_attached_documents fad,
5470                    fnd_documents_tl fdt
5471             WHERE  fad.entity_name = 'PO_LINES'
5472             AND    fad.pk1_value = to_char(x_po_line_id)
5473             AND    fad.document_id = fdt.document_id
5474             AND    fdt.language = USERENV('LANG')
5475             AND    fdt.description like 'POR:%';  -- iP unique identifier
5476 
5477             l_progress := '750';
5478 
5479             -- Move the attachment from the PO line to the PO shipment
5480             UPDATE fnd_attached_documents
5481             SET    entity_name = 'PO_SHIPMENTS',
5482                    pk1_value = to_char(x_line_location_id),
5483                    pk2_value = 'ONE_TIME_LOCATION'
5484             WHERE  attached_document_id = l_one_time_att_doc_id;
5485 
5486         EXCEPTION
5487             WHEN NO_DATA_FOUND THEN
5488                 -- If cannot locate one-time loc attchmnt, do nothing. This
5489                 -- supports original FPH behavior.
5490                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5491                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5492                                         p_token    => l_progress,
5493                                         p_message  => 'One-time loc attachment missing iP prefix, so do not try to move');
5494                 END IF;
5495         END;
5496    END IF;
5497    -- Bug 2875346 end.
5498 
5499    -- <Complex Work R12 Start> : Copy attachments to payitems
5500    IF (p_is_complex_work_po) THEN
5501 
5502      FOR i IN 1..l_line_loc_id_tbl.COUNT
5503      LOOP
5504 
5505        IF (l_line_loc_id_tbl(i) <> x_line_location_id) THEN
5506          -- Bug 5411781: Check if the one time location exists
5507          -- only then need to copy the one time attachments.
5508            -- copy one-time location from first actual shipment to
5509            -- each payitem.
5510        IF (l_one_time_att_doc_id IS NOT NULL) THEN
5511             fnd_attached_documents2_pkg.copy_attachments(
5512              X_from_entity_name  => 'PO_SHIPMENTS'
5513            , X_from_pk1_value    => x_line_location_id
5514            , X_from_pk2_value    => 'ONE_TIME_LOCATION'
5515            , X_to_entity_name    => 'PO_SHIPMENTS'
5516            , X_to_pk1_value      => l_line_loc_id_tbl(i)
5517            , X_to_pk2_value      => 'ONE_TIME_LOCATION'
5518            , X_created_by        => interface.created_by
5519            , X_last_update_login => interface.last_update_login
5520            );
5521 
5522         END IF;
5523       END IF;  -- if l_line_loc_id_tbl(i) <> x_line_location_id
5524 
5525        -- Bug 4620207: pass more parameters
5526        PO_NEGOTIATIONS_SV2.copy_sourcing_payitem_atts(
5527          p_line_location_id    => l_line_loc_id_tbl(i)
5528        , p_created_by          => interface.created_by
5529        , p_last_update_login   => interface.last_update_login
5530        , p_auction_header_id   => interface.auction_header_id
5531        , p_auction_line_number => interface.auction_line_number
5532        , p_bid_number          => interface.bid_number
5533        , p_bid_line_number     => interface.bid_line_number
5534        );
5535 
5536      END LOOP;
5537 
5538    END IF;  -- is Complex Work PO
5539 
5540    -- <Complex Work R12 End>
5541 
5542    l_progress:='760';
5543 
5544     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5545         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5546                             p_token    => l_progress,
5547                             p_message  => 'Create_line: Before update of po_requisition_lines');
5548     END IF;
5549 
5550    IF (g_document_type = 'PO') THEN
5551    l_progress:='770';
5552       UPDATE po_requisition_lines_all  --<Shared Proc FPJ>
5553          SET line_location_id  = x_line_location_id,
5554        --<CONSUME REQ DEMAND PFI START>
5555        reqs_in_pool_flag = NULL, --<REQINPOOL - changed value from N to NULL>
5556        --<CONSUME REQ DEMAND PFI END>
5557              last_update_date  = interface.last_update_date,
5558              last_updated_by   = interface.last_updated_by,
5559              last_update_login = interface.last_update_login
5560        WHERE requisition_line_id = interface.requisition_line_id;
5561    ELSE
5562       l_progress := '780';
5563       UPDATE po_requisition_lines_all  --<Shared Proc FPJ>
5564          SET on_rfq_flag = 'Y',
5565              last_update_date  = interface.last_update_date,
5566              last_updated_by   = interface.last_updated_by,
5567              last_update_login = interface.last_update_login
5568        WHERE requisition_line_id = interface.requisition_line_id;
5569    END IF;
5570 
5571    l_progress:='790';
5572    g_number_records_processed := g_number_records_processed + 1;
5573 
5574     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5575         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5576                             p_token    => l_progress,
5577                             p_message  => 'num records processed: '||g_number_records_processed);
5578         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
5579     END IF;
5580 
5581   --<Unified Catalog R12 START>
5582   l_progress:='800';
5583   -- For intergration with Sourcing, during blanket creation from Renegotiate flow,
5584   -- we need to import all attributes for each line.
5585   -- to facilitate bulk update, we are storing the newly created po_line on
5586   -- po_attr_values_interface and po_attr_values_interface_tlp
5587   IF (g_document_subtype = 'BLANKET'  AND g_interface_source_code = 'SOURCING') THEN
5588     l_progress:='810';
5589 
5590     IF g_debug_stmt THEN PO_DEBUG.debug_stmt(d_mod,l_progress,'Updating PO_LINE_IDs in attribute interface tables: '||l_po_line_id_tbl.COUNT);END IF;
5591 
5592     --SQL What: Update the PO_LINE_ID on PO_ATTR_VALUES_INTERFACE table
5593     --SQL Why : To facilitate bulk update of attributes, later in the flow
5594     --SQL Join: interface_header_id, interface_line_id
5595     FORALL i IN INDICES OF l_po_line_id_tbl
5596       UPDATE PO_ATTR_VALUES_INTERFACE
5597         SET po_line_id = l_po_line_id_tbl(i),
5598             req_template_name = to_char(g_ATTR_VALUES_NULL_ID),
5599             req_template_line_num = to_char(g_ATTR_VALUES_NULL_ID),
5600             inventory_item_id = nvl(inventory_item_id, g_ATTR_VALUES_NULL_ID)
5601       WHERE po_attr_values_interface.interface_header_id = l_interface_header_id_tbl(i)
5602         AND po_attr_values_interface.interface_line_id = l_interface_line_id_tbl(i);
5603 
5604     IF g_debug_stmt THEN PO_DEBUG.debug_stmt(d_mod,l_progress,'Number of PO_ATTR_VALUES_INTERFACE rows updated='||SQL%rowcount);END IF;
5605 
5606     l_progress:='820';
5607     --SQL What: Update the PO_LINE_ID on PO_ATTR_VALUES_TLP_INTERFACE table
5608     --SQL Why : To facilitate bulk update of attributes, later in the flow
5609     --SQL Join: interface_header_id, interface_line_id
5610     FORALL i IN INDICES OF l_po_line_id_tbl
5611       UPDATE PO_ATTR_VALUES_TLP_INTERFACE
5612         SET po_line_id = l_po_line_id_tbl(i),
5613             req_template_name = to_char(g_ATTR_VALUES_NULL_ID),
5614             req_template_line_num = to_char(g_ATTR_VALUES_NULL_ID),
5615             inventory_item_id = nvl(inventory_item_id, g_ATTR_VALUES_NULL_ID)
5616       WHERE po_attr_values_tlp_interface.interface_header_id = l_interface_header_id_tbl(i)
5617         AND po_attr_values_tlp_interface.interface_line_id = l_interface_line_id_tbl(i);
5618 
5619     IF g_debug_stmt THEN PO_DEBUG.debug_stmt(d_mod,l_progress,'Number of PO_ATTR_VALUES_TLP_INTERFACE rows updated='||SQL%rowcount);END IF;
5620   END IF;
5621   --<Unified Catalog R12 END>
5622 
5623   IF g_debug_stmt THEN PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name); END IF;
5624 EXCEPTION
5625   WHEN NO_DATA_FOUND THEN
5626      IF (X_match_blanket_line = 'N') THEN
5627 
5628         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5629             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5630                                 p_token    => l_progress,
5631                                 p_message  => 'Create_line: Inside No data found : Match blanket line is N');
5632         END IF;
5633         null;
5634      ELSE
5635 
5636         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5637             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5638                                 p_token    => l_progress,
5639                                 p_message  => 'Create_line : Inside No data found : Match blanket line is not N');
5640         END IF;
5641         po_message_s.sql_error('CREATE_LINE', l_progress,sqlcode);
5642         wrapup(x_interface_header_id);
5643         raise;
5644 
5645      END IF;
5646   --handle update_req_pool_fail exception
5647   --<SOURCING TO PO FPH START>
5648   WHEN update_req_pool_fail then
5649        po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
5650         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5651             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5652                                 p_token    => l_progress,
5653                                 p_message  => 'Create_documents: update_req_pool_fail exception : SQLCODE '||sqlcode);
5654         END IF;
5655        raise;
5656 
5657   --<SOURCING TO PO FPH END>
5658   WHEN OTHERS THEN
5659      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
5660          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
5661                             p_progress => l_progress);
5662      END IF;
5663      wrapup(x_interface_header_id);
5664      po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
5665      raise;
5666 
5667 END create_line;
5668 
5669 /* ============================================================================
5670      NAME: CREATE_SHIPMENT
5671      DESC: Create/Add to document shipment
5672      ARGS: IN : x_po_line_id IN number
5673            IN : x_line_location_id IN number
5674      ALGR:
5675 
5676    ==========================================================================*/
5677 PROCEDURE create_shipment(
5678   x_po_line_id IN number,
5679   p_rate_for_req_fields IN NUMBER, -- <ACHTML R12>
5680   x_line_location_id IN OUT NOCOPY number,
5681   p_outsourced_assembly IN NUMBER --<SHIKYU R12>
5682   )
5683 IS
5684 x_ship_to_location_id number:= 0;
5685 x_po_release_id number := g_po_release_id;
5686 x_cumulative_flag boolean; /* used to get release price from PA */
5687 x_price number;              /* used to get release price from PA */
5688 x_price_break_type varchar2(25) := '';
5689 x_doctype varchar2(25) := ''; /* used for call to update close state */
5690 x_return_code varchar2(25) := ''; /* used for call to update close state */
5691 x_item_org_taxable_flag      mtl_system_items.taxable_flag%type := NULL;
5692 x_ship_to_org_taxable_flag   mtl_system_items.taxable_flag%type := NULL;
5693 x_return_taxable_flag        mtl_system_items.taxable_flag%type := NULL;
5694 
5695 /* For converting qty if line_type is not quantity based */
5696 x_order_type_lookup_code  varchar2(25)  :='';
5697 x_quantity      number    :=0;
5698 l_conversion_rate number :=1;
5699 --fix 8976669
5700  	 --declared x_amount
5701  	 x_amount number;
5702 
5703 /* obtain currency info to adjust precision */
5704 x_precision   number :='';
5705 x_ext_precision   number :='';
5706 x_min_unit    number :='';
5707 
5708 /* Additional tax variables for R11 tax defaulting functionality */
5709 x_tax_code_id                   ap_tax_codes.tax_id%type;
5710 x_tax_type                      ap_tax_codes.tax_type%type;
5711 x_description                   ap_tax_codes.description%type;
5712 x_allow_tax_code_override_flag  gl_tax_option_accounts.allow_tax_code_override_flag%type;
5713 
5714 /* Parameters for supporting OE callback for maintaining so_drop_ship_source */
5715 x_p_api_version     number:='';
5716 x_p_return_status   varchar2(1):='';
5717 x_p_msg_count     number:='';
5718 x_p_msg_data      varchar2(2000):='';
5719 x_p_req_header_id   NUMBER:='';
5720 x_p_req_line_id     NUMBER:='';
5721 --x_p_interface_source_code   varchar2(25);
5722 --x_p_interface_source_line_id  number:='';
5723 x_p_po_header_id    number:='';
5724 x_p_po_line_id      number:='';
5725 x_p_line_location_id    number:='';
5726 x_requisition_header_id   number:='';
5727 x_p_po_release_id   number:='';
5728 
5729 /*630638 - SVAIDYAN: Variable to get the qty in the already existing shipment */
5730 x_ship_qty number := 0;
5731 --FRKHAN 12/21/98
5732 x_tax_user_override_flag  VARCHAR2(1);
5733 --FRKHAN 1/12/99
5734 x_country_of_origin_code  VARCHAR2(2);
5735 x_tax_status            VARCHAR2(10);
5736 x_tax_status_indicator          po_requisition_lines.tax_status_indicator%type;
5737 --FRKHAN 12/2/99 BUG 1084816
5738 l_encode VARCHAR2(2000);
5739 x_po_uom  varchar2(25):=null;
5740 x_temp_uom  varchar2(25):=null;
5741 x_temp_item_id  number:=null;
5742 x_closed_reason po_line_locations.closed_reason%TYPE;
5743 x_uom_convert          varchar2(2) := fnd_profile.value('PO_REQ_BPA_UOM_CONVERT');
5744 
5745 --<Bug# 3293109 START>
5746 l_promised_date         DATE            := INTERFACE.PROMISED_DATE;
5747 l_po_promised_def_prf   VARCHAR2(1)     := fnd_profile.value('PO_NEED_BY_PROMISE_DEFAULTING');
5748 --<Bug# 3293109 END>
5749 
5750 l_api_name CONSTANT VARCHAR2(30) := 'create_shipment';
5751 l_progress VARCHAR2(3) := '000';                    --< Bug 3210331 >
5752 l_manual_price_change_flag po_line_locations_all.manual_price_change_flag%TYPE := NULL; --bug 3495772
5753 
5754 -- Bug 5208159
5755 l_from_type_lookup_code po_headers_all.type_lookup_code%TYPE;
5756 
5757 --<INVCONV R12 START>
5758 x_shipment_uom      MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
5759 x_secondary_unit_of_measure MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
5760 x_secondary_quantity    PO_LINES.SECONDARY_QUANTITY%TYPE;
5761 x_secondary_uom_code    MTL_UNITS_OF_MEASURE.UOM_CODE%TYPE;
5762 --<INVCONV R12 END>
5763 
5764 l_matching_basis    PO_LINE_TYPES.matching_basis%TYPE;  -- <Complex Work R12>
5765 l_inspection_required_flag VARCHAR2(1);     --10403047
5766 l_receipt_required_flag VARCHAR2(1);       --10403047
5767 
5768 BEGIN
5769     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5770         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
5771     END IF;
5772 
5773    x_line_location_id:=null;
5774    x_quantity := interface.quantity;
5775 
5776 -- bug 16416508: UOM should be the same between line and shipment,
5777 -- select out the UOM from po line
5778     BEGIN
5779       SELECT pol.unit_meas_lookup_code
5780       INTO x_temp_uom
5781       FROM po_lines_all pol
5782       WHERE po_line_id = x_po_line_id;
5783     EXCEPTION
5784     WHEN NO_DATA_FOUND THEN
5785       x_temp_uom     := interface.unit_meas_lookup_code;
5786     END;
5787 
5788   -- x_temp_uom     := interface.unit_meas_lookup_code;
5789    x_temp_item_id := interface.item_id;
5790 
5791     l_progress := '010';
5792 
5793     -- <SERVICES FPJ START>
5794     -- <Complex Work R12>: Also get matching basis
5795 
5796     SELECT plt.order_type_lookup_code, plt.matching_basis
5797     INTO   x_order_type_lookup_code, l_matching_basis
5798     FROM   po_line_types plt
5799     WHERE  plt.line_type_id = interface.line_type_id;
5800 
5801     --
5802     -- <SERVICES FPJ END>
5803 
5804      IF interface.h_currency_code IS NOT NULL THEN
5805                 fnd_currency.get_info(interface.h_currency_code,
5806                              x_precision,
5807                              x_ext_precision,
5808                              x_min_unit );
5809      END IF;
5810 
5811     -- bug 5208159 : Conversion of req UOM to Quotation UOM should always happen if the
5812     -- source document is a quote and profile 'PO: Convert Requisition UOM to Source Document UOM'
5813     -- should be ignored in that case
5814     IF g_debug_stmt THEN
5815          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5816                              p_token    => l_progress,
5817                              p_message  => 'from line id :'||interface.from_line_id||'from header id:'||interface.from_header_id);
5818     END IF;
5819 
5820     IF (interface.from_line_id IS NOT NULL) AND (g_document_subtype = 'STANDARD') THEN
5821 
5822          l_progress := '015';
5823 
5824          BEGIN
5825 
5826            SELECT poh.type_lookup_code
5827            INTO   l_from_type_lookup_code
5828            FROM   po_headers_all poh
5829            WHERE poh.po_header_id=interface.from_header_id ;
5830 
5831            IF g_debug_stmt THEN
5832                PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5833                                    p_token    => l_progress,
5834                                    p_message  => 'l_from_type_lookup_code :'||l_from_type_lookup_code);
5835            END IF;
5836 
5837 
5838 
5839          EXCEPTION
5840            WHEN OTHERS THEN
5841                IF g_debug_unexp THEN
5842                    PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
5843                                       p_progress => l_progress);
5844                END IF;
5845                po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
5846                wrapup(interface.interface_header_id);
5847                raise;
5848            END;
5849     END IF;
5850 
5851     -- got the source document type, now compare it and if required do the UOM conversion
5852 
5853     IF g_debug_stmt THEN
5854          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5855                              p_token    => l_progress,
5856                              p_message  => 'x_uom_convert:'||x_uom_convert);
5857     END IF;
5858 
5859   IF (nvl(x_uom_convert,'N') = 'Y' OR l_from_type_lookup_code = 'QUOTATION') THEN
5860   -- bug 5208159 : end
5861 
5862    IF (g_document_subtype='RELEASE')
5863      -- Bug 2735840 Convert UOM when autocreating a PO that references a GA
5864      OR ((g_document_subtype='STANDARD')
5865          AND (interface.from_line_id is not null)) THEN
5866 
5867    /* Enh : 1660036
5868     get the uom from the PO . This will be used for uom conversion */
5869 
5870     BEGIN
5871       IF (g_document_subtype='RELEASE') THEN -- Bug 2735840
5872         l_progress := '020';
5873         select unit_meas_lookup_code
5874         into x_po_uom
5875         from po_lines_all pol ,  --<Shared Proc FPJ>
5876              po_headers_all poh  --<Shared Proc FPJ>
5877         where pol.po_header_id = poh.po_header_id
5878         and pol.po_header_id = interface.po_header_id
5879         and pol.line_num = interface.line_num;
5880       -- Bug 2735840 START
5881       ELSE -- Autocreating a PO that references a GA
5882         l_progress := '030';
5883         SELECT unit_meas_lookup_code
5884         INTO x_po_uom
5885         FROM po_lines_all
5886         WHERE po_line_id = interface.from_line_id;
5887       END IF; -- g_document_subtype
5888       -- Bug 2735840 END
5889      EXCEPTION
5890      WHEN OTHERS THEN
5891        IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
5892            PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
5893                               p_progress => l_progress);
5894        END IF;
5895        po_message_s.sql_error('CREATE_SHIPMENTS',l_progress,sqlcode);
5896        wrapup(interface.interface_header_id);
5897        raise;
5898     END;
5899 
5900   /* before inserting the quantity into the shipments table convert the quantity
5901       into the BPA uom if the uom's on the req and BPA are different .
5902       This conversion is done only if the Convert UOM  profile option is set to Yes. */
5903 
5904     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5905         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5906                             p_token    => l_progress,
5907                             p_message  => 'Create_shipment: UOM: '||x_temp_uom);
5908         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5909                             p_token    => l_progress,
5910                             p_message  => 'Create_shipment: item id: '||x_temp_item_id);
5911         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5912                             p_token    => l_progress,
5913                             p_message  => 'Create_shipment: PO UOM: '||x_po_uom);
5914     END IF;
5915 
5916     l_progress := '040';
5917 
5918         IF  (   ( interface.unit_meas_lookup_code <> x_po_uom )
5919             AND ( x_order_type_lookup_code IN ('QUANTITY','AMOUNT') ) ) THEN   -- <SERVICES FPJ>
5920 
5921 
5922             -- Bug 3793360 : use the po_uom_convert procedure and round 15
5923             l_conversion_rate :=  po_uom_s.po_uom_convert(interface.unit_meas_lookup_code,
5924                                                        x_po_uom,
5925                                                        interface.item_id);
5926 
5927             x_quantity := round(x_quantity * l_conversion_rate , 15);
5928             x_shipment_uom := x_po_uom ; --<INVCONV R12>
5929 
5930         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5931             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5932                                 p_token    => l_progress,
5933                                 p_message  => 'Create_shipment: Converted Qty: '||x_quantity);
5934         END IF;
5935 
5936         END IF;
5937 
5938     END IF;
5939   END IF;
5940 
5941     l_progress := '050';
5942    /*
5943    ** Get the ship to location id associated with the
5944    ** deliver to location.  This may then used to
5945    ** get the tax name, if the tax system parameters are
5946    ** set up to retrieve the tax code based on ship-to location.
5947    */
5948 
5949    x_ship_to_location_id := get_ship_to_loc(interface.deliver_to_location_id);  -- FPI
5950 
5951   IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED' or
5952   g_document_type = 'RFQ')THEN
5953     l_progress := '060';
5954     BEGIN
5955       SELECT poll.line_location_id,poll.secondary_unit_of_measure --<INVCONV R12>
5956         INTO x_line_location_id,x_secondary_unit_of_measure
5957         FROM po_line_locations_all poll,  --<Shared Proc FPJ>
5958              po_lines_all pol  --<Shared Proc FPJ>
5959        WHERE poll.po_header_id = interface.po_header_id
5960          AND poll.po_line_id = pol.po_line_id
5961          AND poll.shipment_num = interface.shipment_num
5962          AND pol.line_num = interface.line_num
5963          AND poll.shipment_type in ('STANDARD','PLANNED', 'RFQ');
5964     EXCEPTION
5965      WHEN NO_DATA_FOUND THEN
5966         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5967             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5968                                 p_token    => l_progress,
5969                                 p_message  => 'NO_DATA_FOUND: '||SQLERRM);
5970         END IF;
5971      WHEN OTHERS THEN
5972        IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
5973            PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
5974                               p_progress => l_progress);
5975        END IF;
5976        po_message_s.sql_error('CREATE_SHIPMENTS',l_progress,sqlcode);
5977        wrapup(interface.interface_header_id);
5978        raise;
5979     END;
5980 
5981 
5982   ELSIF(g_document_subtype='RELEASE')THEN
5983     l_progress := '070';
5984     BEGIN
5985       SELECT poll.line_location_id,
5986              poll.manual_price_change_flag, --bug 3495772
5987              poll.secondary_unit_of_measure --<INVCONV R12>
5988         INTO x_line_location_id,
5989              l_manual_price_change_flag, --bug 3495772
5990              x_secondary_unit_of_measure
5991         FROM po_line_locations_all poll,  --<Shared Proc FPJ>
5992              po_lines_all pol,  --<Shared Proc FPJ>
5993              po_releases_all por  --<Shared Proc FPJ>
5994        WHERE poll.po_header_id = interface.po_header_id
5995          AND poll.po_line_id = pol.po_line_id
5996          AND poll.shipment_num = interface.shipment_num
5997          AND pol.line_num = interface.line_num
5998          AND poll.po_release_id=por.po_release_id
5999          AND por.po_release_id=x_po_release_id;
6000 
6001 
6002     EXCEPTION
6003      WHEN NO_DATA_FOUND THEN
6004         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6005             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6006                                 p_token    => l_progress,
6007                                 p_message  => 'NO_DATA_FOUND: '||SQLERRM);
6008         END IF;
6009      WHEN OTHERS THEN
6010        IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
6011            PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
6012                               p_progress => l_progress);
6013        END IF;
6014        po_message_s.sql_error('CREATE_SHIPMENTS',l_progress,sqlcode);
6015        wrapup(interface.interface_header_id);
6016        raise;
6017     END;
6018   END IF;
6019 
6020   l_progress:='080';
6021 
6022   IF(interface.document_subtype = 'RELEASE')  AND
6023     (g_interface_source_code  <> 'CONSUMPTION_ADVICE') THEN  -- Bug 2748933
6024 
6025      IF(nvl(l_manual_price_change_flag, 'N') <> 'Y') THEN -- bug 3495772
6026 
6027          -- Find out if the line is using cumulative or non-cumlative pricing
6028          SELECT decode(price_break_lookup_code, 'CUMULATIVE', 'Y', 'N')
6029          INTO   x_price_break_type
6030          FROM   po_lines_all  --<Shared Proc FPJ>
6031          WHERE  po_line_id = x_po_line_id;
6032 
6033          IF (x_price_break_type = 'Y') THEN
6034              x_cumulative_flag := TRUE;
6035          ELSE
6036              x_cumulative_flag := FALSE;
6037          END IF;
6038 
6039     /* 630638 - SVAIDYAN
6040        If the price break type is not cumulative, then
6041        If there exists a shipment to which this qty will be added, then the
6042        qty to get break price would be already existing shipment quantity +
6043        interface.quantity.
6044 
6045     */
6046 
6047         l_progress := '090';
6048         if (x_line_location_id is not null and x_cumulative_flag = FALSE) then
6049         begin
6050             select nvl(quantity, 0)
6051             into   x_ship_qty
6052             from   po_line_locations_all  --<Shared Proc FPJ>
6053             where  line_location_id = x_line_location_id;
6054         exception
6055             when others THEN
6056                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6057                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6058                                         p_token    => l_progress,
6059                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
6060                 END IF;
6061                 x_ship_qty := 0;
6062         end;
6063         end if;
6064 
6065         l_progress := '100';
6066          x_ship_qty := x_ship_qty + x_quantity;
6067 
6068 
6069          /* <TIMEPHASED FPI> */
6070          /* Changed the parameter sysdate to interface.need_by_date */
6071          x_price := po_sourcing2_sv.get_break_price(
6072           x_ship_qty,
6073           interface.destination_organization_id,
6074                       x_ship_to_location_id,
6075           x_po_line_id,
6076                       x_cumulative_flag,
6077                             interface.need_by_date,
6078  	                             p_req_line_price => INTERFACE.unit_price); --bug 8845486
6079   /* <TIMEPHASED FPI> */
6080 
6081       ELSE --manual_price_change_flag = y, bug 3495772
6082            x_price := NULL; --will preserve whatever price is alredy on shipment
6083                             -- in below update statement
6084       END IF;
6085 
6086   ELSE
6087      /* Bug 486563 ecso 5/13/97
6088       * When mulitple lines with different unit_price are combined, we need
6089       * to ensure that price_override field in shipments are populated with
6090       * the unit_price from the line, not the original one from the req.
6091       */
6092    /* Bug 2748933 */
6093    /* For a consumption advice we take the price as it is populated and not from the BPA */
6094 
6095 
6096       IF (g_interface_source_code  =  'CONSUMPTION_ADVICE') THEN
6097             x_price := interface.unit_price;
6098 
6099       ELSE
6100 
6101        l_progress := '110';
6102        begin
6103          SELECT unit_price
6104          INTO   x_price
6105          FROM   po_lines_all  --<Shared Proc FPJ>
6106          WHERE  po_line_id=x_po_line_id;
6107        exception
6108            when others then
6109               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6110                   PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6111                                       p_token    => l_progress,
6112                                       p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
6113               END IF;
6114               x_price := null;
6115        end;
6116 
6117       END IF;
6118 
6119   END IF;
6120 
6121   IF(x_line_location_id is not null) THEN
6122 
6123      /*
6124      ** Update everything except closed_code
6125      */
6126      l_progress:='120';
6127       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6128           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6129                               p_token    => l_progress,
6130                               p_message  => 'Create_shipment: shipment exist');
6131           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6132                               p_token    => l_progress,
6133                               p_message  => 'Create_shipment: Update PO line locations');
6134       END IF;
6135 
6136       /*Bug 5629398 Start: Quantity conversion for foreign currency was not happening for
6137         amount based lines when we try to add to existing shipment line */
6138         IF   ( x_order_type_lookup_code = 'QUANTITY' ) THEN
6139                   x_quantity := round(x_quantity,15);
6140         ELSIF ( x_order_type_lookup_code = 'AMOUNT' ) THEN
6141              -- Bug 7661419, No conversion for same currency.
6142 	     PO_INTERFACE_S.do_currency_conversion(
6143                       p_order_type_lookup_code => 'AMOUNT',
6144                       p_interface_source_code  => g_interface_source_code,
6145                       p_rate                   => p_rate_for_req_fields, -- <ACHTML R12>
6146                       p_po_currency_code       => interface.h_currency_code,
6147                       p_requisition_line_id    => interface.requisition_line_id,
6148                       x_quantity               => x_quantity, -- IN/OUT
6149                       x_unit_price             => interface.unit_price, -- IN/OUT
6150                       x_base_unit_price        => interface.base_unit_price, -- IN/OUT
6151                       x_amount                 => interface.amount -- IN/OUT
6152                       );
6153 
6154                                             --fix 8976669
6155  	 --The procedure do_currency_conversion was not called for 'FIXED PRICE', added the required call
6156  	         ELSIF ( x_order_type_lookup_code = 'FIXED PRICE') THEN
6157  	              PO_INTERFACE_S.do_currency_conversion(
6158  	                       p_order_type_lookup_code => 'FIXED PRICE',
6159  	                       p_interface_source_code  => g_interface_source_code,
6160  	                       p_rate                   => p_rate_for_req_fields, -- <ACHTML R12>
6161  	                       p_po_currency_code       => interface.h_currency_code,
6162  	                       p_requisition_line_id    => interface.requisition_line_id,
6163  	                       x_quantity               => x_quantity, -- IN/OUT
6164  	                       x_unit_price             => interface.unit_price, -- IN/OUT
6165  	                       x_base_unit_price        => interface.base_unit_price, -- IN/OUT
6166  	                       x_amount                 => x_amount -- IN/OUT
6167  	                       );
6168 	END IF;
6169     /*Bug 5629398 End */
6170 
6171 
6172       --<INVCONV R12 START>
6173       --If item is dual uom control and secondary quantity is NULL, derive it
6174      IF x_secondary_unit_of_measure IS NOT NULL THEN
6175         IF interface.secondary_quantity IS  NULL THEN
6176            PO_UOM_S.uom_convert (x_quantity,
6177                                  nvl(x_shipment_uom, interface.unit_meas_lookup_code),
6178                                  interface.item_id, x_secondary_unit_of_measure ,
6179                                  x_secondary_quantity) ;
6180         ELSE
6181            X_secondary_quantity := interface.secondary_quantity ;
6182         END IF;
6183      ELSE
6184         x_secondary_quantity  := null ;
6185      END IF;
6186      --<INVCONV R12 END>
6187 
6188 
6189      --<INVCONV R12> replace interface.secondary_quantity with x_secondary_quantity
6190 
6191      UPDATE po_line_locations_all  --<Shared Proc FPJ>
6192   SET quantity          = quantity + x_quantity,
6193 -- start of 1548597
6194             secondary_quantity = secondary_quantity + x_secondary_quantity,
6195 -- end of 1548597
6196  --fix 8976669
6197  	 --added update of amount when shipments are created
6198  	             amount = nvl(amount,0) + x_amount,
6199             approved_flag     = DECODE(approved_flag,
6200                                          'N','N', 'R'),
6201             last_update_date  = interface.last_update_date,
6202             last_update_login = interface.last_update_login,
6203             last_updated_by   = interface.last_updated_by,
6204             price_override    = decode(g_document_type, 'RFQ',
6205           price_override, DECODE(
6206           nvl(x_price, -1),
6207                                        -1, price_override,
6208 -- Bug 1353736 use precision in rounding
6209 -- Bug 3472140: Changed precisions to 15
6210                                        ROUND(x_price, nvl(x_ext_precision,15)))),
6211             -- Bug 5067321. Setting tax_attribute_update_code to update for
6212             -- add_to cases.
6213             tax_attribute_update_code = NVL(tax_attribute_update_code,
6214                                             NVL2(g_calculate_tax_flag, 'UPDATE', null))
6215       WHERE line_location_id = x_line_location_id;
6216 
6217       /*
6218       ** 9/10/97 ecso
6219       ** OE Callback function for maintaining so_drop_ship_sources table
6220       */
6221       /* 11/18/97 ecso
6222       ** OE redesign. No Shipments linked to sales order will be combined
6223       ** Therefore, no need to do call back for update shipment
6224       ** Removed oe callback.
6225       */
6226 
6227       /*
6228       ** Prepare to call pocupdate_close: - call auto close.
6229       */
6230       IF (g_document_type = 'PO') THEN
6231        IF (g_mode = 'ADD') THEN
6232         IF (g_document_type = 'PO') THEN
6233          IF (g_document_subtype = 'RELEASE') THEN
6234             x_doctype := 'RELEASE';
6235               /* Bug 4016505 Start */
6236               IF NOT po_actions.close_po(x_po_release_id,
6237                     x_doctype,
6238                     g_document_subtype,
6239                     x_po_line_id,
6240                     x_line_location_id,
6241                     'CLOSE',
6242                     '',
6243                     'PO',
6244                     'N',
6245                     x_return_code,
6246                     'Y') then
6247 
6248                   po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
6249 
6250                END IF;
6251               /* Bug 4016505 End */
6252          ELSE
6253             x_doctype := 'PO';
6254                           /* Bug 4016505 Start */
6255             IF NOT po_actions.close_po(interface.po_header_id,
6256                     x_doctype,
6257                     g_document_subtype,
6258                     x_po_line_id,
6259                     x_line_location_id,
6260                     'CLOSE',
6261                     '',
6262                     'PO',
6263                     'N',
6264                     x_return_code,
6265                     'Y') then
6266 
6267                po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
6268 
6269             END IF;
6270             /* Bug 4016505 End */
6271          END IF;
6272 
6273          l_progress := '130';
6274          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6275              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6276                                  p_token    => l_progress,
6277                                  p_message  => 'Create shipment: Before calling Auto close');
6278          END IF;
6279 	/*bug 12673501 starts: the call to po_actions.po_close is a redundant call
6280 	in the above if conditions it is called with the right parameters.
6281 	This call raises an exception hence commenting it.*/
6282          /*IF NOT po_actions.close_po(interface.po_header_id,
6283                     x_doctype,
6284                     g_document_subtype,
6285                     x_po_line_id,
6286                     x_line_location_id,
6287                     'CLOSE',
6288                     '',
6289                     'PO',
6290                     'N',
6291                     x_return_code,
6292                     'Y') then
6293 
6294             po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
6295 
6296          END IF;*/
6297 	/*bug 12673501 ends*/
6298        END IF;
6299 
6300       END IF;
6301 
6302      END IF;
6303 
6304   ELSIF(x_line_location_id is null) THEN
6305 
6306       l_progress := '140';
6307       IF (g_document_type = 'PO') THEN
6308          /*
6309          ** Prepare to call pocupdate_close: -  call manual close
6310          ** for the line level.
6311          */
6312         IF (g_mode = 'ADD') THEN
6313            IF (g_document_subtype = 'RELEASE') THEN
6314               x_doctype := 'RELEASE';
6315               /* Bug 4016505 Start */
6316                 IF not po_actions.close_po(x_po_release_id,
6317                     x_doctype,
6318                     g_document_subtype,
6319                     x_po_line_id,
6320                     x_line_location_id,
6321                     'CLOSE',
6322                     '',
6323                     'PO',
6324                     'N',
6325                     x_return_code,
6326                     'N') then
6327 
6328                    po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
6329                 END IF;
6330               /* Bug 4016505 End */
6331            ELSE
6332               x_doctype := 'PO';
6333               /* Bug 4016505 Start */
6334               IF not po_actions.close_po(interface.po_header_id,
6335                     x_doctype,
6336                     g_document_subtype,
6337                     x_po_line_id,
6338                     x_line_location_id,
6339                     'CLOSE',
6340                     '',
6341                     'PO',
6342                     'N',
6343                     x_return_code,
6344                     'N') then
6345                po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
6346              END IF;
6347               /* Bug 4016505 End */
6348            END IF;
6349 
6350            l_progress := '150';
6351 	   /*bug 12673501 starts*/
6352          /*  IF not po_actions.close_po(interface.po_header_id,
6353                     x_doctype,
6354                     g_document_subtype,
6355                     x_po_line_id,
6356                     x_line_location_id,
6357                     'CLOSE',
6358                     '',
6359                     'PO',
6360                     'N',
6361                     x_return_code,
6362                     'N') then
6363 
6364               po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
6365 
6366            END IF;*/
6367 	/*bug 12673501 ends*/
6368         END IF;
6369 
6370      END IF;
6371 
6372      l_progress:='160';
6373      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6374          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6375                              p_token    => l_progress,
6376                              p_message  => 'create shipment: Shipment does not exist');
6377      END IF;
6378 
6379      l_progress := '200';
6380 
6381      /* Bug 482648
6382       * Adjust quantity for foreign currecny
6383       */
6384 
6385         IF ( x_order_type_lookup_code = 'QUANTITY' ) THEN     -- <SERVICES FPJ>
6386 
6387 -- added by jbalakri for bug 2372004
6388 -- Bug 3472140: Changed precisions to 15
6389             x_quantity := round(x_quantity,15);
6390 
6391         ELSIF ( x_order_type_lookup_code = 'AMOUNT' ) THEN    -- <SERVICES FPJ>
6392              -- Bug 7661419, No conversion for same currency.
6393              PO_INTERFACE_S.do_currency_conversion(
6394                       p_order_type_lookup_code => 'AMOUNT',
6395                       p_interface_source_code  => g_interface_source_code,
6396                       p_rate                   => p_rate_for_req_fields, -- <ACHTML R12>
6397                       p_po_currency_code       => interface.h_currency_code,
6398                       p_requisition_line_id    => interface.requisition_line_id,
6399                       x_quantity               => x_quantity, -- IN/OUT
6400                       x_unit_price             => interface.unit_price, -- IN/OUT
6401                       x_base_unit_price        => interface.base_unit_price, -- IN/OUT
6402                       x_amount                 => interface.amount -- IN/OUT
6403                       );
6404         END IF;
6405 
6406      /*
6407       **  Create a new shipment.
6408       */
6409      l_progress:='210';
6410     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6411         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6412                             p_token    => l_progress,
6413                             p_message  => 'Create shipment: Create a new shipment');
6414     END IF;
6415 
6416      SELECT po_line_locations_s.nextval
6417        INTO x_line_location_id
6418        FROM sys.dual;
6419 
6420      -- bug: 404191
6421      --      Get the taxable_flag based on the following priority
6422      --      1. preferences (global.po_taxable_flag)
6423      --      2. ship_to_org (x_ship_to_org_taxable_flag)
6424      --      2. item-org    (po_lines.taxable_flag)
6425      --      3. PO default  (po_startup_values.taxable_flag)
6426      --
6427      l_progress:='220';
6428      x_item_org_taxable_flag :=  item.taxable_flag;
6429 
6430 
6431      -- Bug 3935370 START
6432      -- Removed the po_items_sv3.get_taxable_flag procedure because
6433      -- x_return_taxable_flag should be based off of tax_code_id instead.
6434      -- Also removed fix for bug 1651019 because it sets x_return_taxable_flag
6435      -- to Y if x_tax_code_id is not null, which is duplicated in this fix.
6436      -- Added else clause in if statment to make sure x_return_taxable_flag is
6437      -- set appropriately according to tax_code_id.
6438      -- Bug 3935370 END
6439 
6440      --< Bug 3334670 Start >
6441      IF (g_interface_source_code = 'CONSUMPTION_ADVICE') THEN
6442 
6443          -- tax_code_id from the interface table is used for consumption advice
6444          IF (NVL(interface.tax_code_id, -1) = -1) THEN
6445              -- FPI inventory code was populating tax_code_id = -1 in some cases
6446              -- for consumption advice. Never insert -1.
6447              interface.tax_code_id := NULL;
6448              x_return_taxable_flag := 'N';
6449          ELSE
6450              x_return_taxable_flag := 'Y';
6451          END IF;
6452      --< Bug 3334670 End >
6453      -- Bug 3935370 START
6454      ELSE
6455        IF (x_tax_code_id is not null) then
6456          x_return_taxable_flag := 'Y';
6457        ELSE
6458          x_return_taxable_flag := 'N';
6459        END IF;
6460      -- Bug 3935370 END
6461      END IF;
6462 
6463      l_progress:='230';
6464 
6465 --FRKHAN 1/12/99 Get default country of origin
6466      po_coo_s.get_default_country_of_origin(
6467       interface.item_id,
6468       interface.destination_organization_id,
6469       interface.vendor_id,
6470       interface.vendor_site_id,
6471       x_country_of_origin_code);
6472 
6473 /*Bug no 781929
6474   Last accept date is also inserted into po_line_locations table.
6475   last_accept_date = interface.need_by_date+rc.days_late_receipt_allowed.
6476   Purposely , null handling has not been done, since even if either
6477   need_by_date or days_late_received_allowed is null then the last_accept_date
6478   should be null.
6479 */
6480 
6481 -- Bug 1353736 Call fnd_currency.get_info to get the precision
6482 --added by jbalakri for 1805397
6483         IF interface.h_currency_code IS NOT NULL THEN
6484                    fnd_currency.get_info(interface.h_currency_code,
6485                                          x_precision,
6486                                          x_ext_precision,
6487                                          x_min_unit );
6488         end if;
6489 --end of add for 1805397
6490 
6491         l_progress := '240';
6492         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6493             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6494                                 p_token    => l_progress,
6495                                 p_message  => 'Create shipment: Before insert into po line locations');
6496         END IF;
6497 
6498      /* CONSIGNED FPI start : Set the closed reason for consigned */
6499         IF interface.consigned_flag = 'Y' THEN
6500            x_closed_reason := fnd_message.get_string('PO', 'PO_SUP_CONS_CLOSED_REASON');
6501         ELSE
6502            x_closed_reason := null;
6503         END IF;
6504 
6505 
6506      /* CONSIGNED FPI End */
6507 
6508      --<Bug# 3293109 START>
6509      if g_document_type <> 'RFQ'
6510          and l_promised_date is null
6511          and nvl(l_po_promised_def_prf, 'N') = 'Y' then
6512 
6513                 l_promised_date := INTERFACE.NEED_BY_DATE;
6514      end if;
6515      --<Bug# 3293109 END>
6516 
6517      -- GA FPI Bug 2750604. Need to insert from_header_id and from_line_id
6518      -- at the shipment level from the interface tables.
6519 
6520      --Bug 2861408:  For consigned items ALWAYS insert 'N' for
6521      --receipt-required flag and inspection-required flag, and
6522      --insert 'P' for match_option.
6523 
6524 
6525     l_progress := '250';
6526     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6527         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6528                             p_token    => l_progress,
6529                             p_message  => 'interface.trxn_flow_header_id='||interface.transaction_flow_header_id);
6530     END IF;
6531 
6532     --<INVCONV R12 START>
6533     -- If item is dual uom control and secondary quantity is NULL, derive it
6534     IF interface.item_id IS NOT NULL THEN
6535       IF interface.secondary_quantity IS NULL THEN
6536           PO_UOM_S.get_secondary_uom( interface.item_id,
6537                                          interface.destination_organization_id,
6538                                          x_secondary_uom_code,
6539                                          x_secondary_unit_of_measure);
6540 
6541          IF x_secondary_unit_of_measure IS NOT NULL and x_quantity > 0 THEN
6542            PO_UOM_S.uom_convert (x_quantity,
6543                                  nvl(x_shipment_uom, interface.unit_meas_lookup_code),
6544                                  interface.item_id,
6545                                  x_secondary_unit_of_measure ,
6546                                  x_secondary_quantity) ;
6547          ELSE
6548            X_secondary_quantity := NULL;
6549          END IF;
6550       ELSE
6551            X_secondary_quantity := interface.secondary_quantity;
6552            X_secondary_unit_of_measure := interface.secondary_unit_of_measure;
6553       END IF;
6554     ELSE
6555        X_secondary_quantity := null;
6556        X_secondary_unit_of_measure := null;
6557     END IF;
6558     --<INVCONV R12 END>
6559 
6560     --Bug 10403047
6561     begin
6562 
6563     select decode(g_interface_source_code,
6564               'CONSUMPTION_ADVICE',
6565               'N', -- CONSIGNED FPI
6566                decode(interface.consigned_flag,
6567                      'Y',
6568                      'N', --bug 2861408
6569                      decode(interface.drop_ship_flag,
6570                             'Y',
6571                             'N', --bug 3330748
6572                             decode(x_order_type_lookup_code,
6573                                    'FIXED PRICE',
6574                                    'N',
6575                                    'RATE',
6576                                    'N', --bug 3483786
6577                                    decode(g_document_type,
6578                                           'RFQ',
6579                                           nvl(item.inspection_required_flag,
6580                                               nvl(params.inspection_required_flag,
6581                                                   'N')),
6582                                           nvl(item.inspection_required_flag,
6583                                               nvl(vendor.inspection_required_flag,
6584                                                   nvl(params.inspection_required_flag,
6585                                                       'N')))))))),
6586        decode(g_interface_source_code,
6587               'CONSUMPTION_ADVICE',
6588               'N', -- CONSIGNED FPI
6589               decode(interface.consigned_flag,
6590                      'Y',
6591                      'N', --bug 2861408
6592                      decode(g_document_type,
6593                             'RFQ',
6594                             nvl(item.receipt_required_flag,
6595                                 nvl(interface.receipt_required_flag,
6596                                     nvl(params.receiving_flag, 'N'))),
6597                             nvl(item.receipt_required_flag,
6598                                 nvl(interface.receipt_required_flag,
6599                                     nvl(vendor.receipt_required_flag,
6600                                         nvl(params.receiving_flag, 'N')))))))
6601   INTO l_inspection_required_flag, l_receipt_required_flag
6602   FROM dual;
6603 
6604   EXCEPTION
6605 
6606   	when others THEN
6607   		   l_progress:='255';
6608     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6609         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6610                             p_token    => l_progress,
6611                             p_message  => 'Error while determing receipt required and inspection required flag for 4 way');
6612     END IF;
6613   	end;
6614 
6615 IF l_inspection_required_flag = 'Y' AND l_receipt_required_flag = 'Y' then
6616 
6617   rc.receiving_routing_id := 2; --Inspection Required
6618 
6619 end if;
6620 
6621     --End Bug 10403047
6622     --Bug11882785-Start
6623 
6624 IF l_inspection_required_flag = 'Y' AND l_receipt_required_flag = 'N' then
6625 
6626   l_inspection_required_flag := 'N';
6627 
6628 end if;
6629 
6630     --Bug11882785-End
6631 
6632 
6633      INSERT INTO po_line_locations_all  --<Shared Proc FPJ>
6634              (line_location_id,
6635               last_update_date,
6636               last_updated_by,
6637               po_header_id,
6638               creation_date,
6639               created_by,
6640               last_update_login,
6641               po_line_id,
6642               quantity,
6643               quantity_received,
6644               quantity_accepted,
6645               quantity_rejected,
6646               quantity_billed,
6647               quantity_cancelled,
6648               amount,                                         -- <SERVICES FPJ>
6649               amount_received,                                -- <SERVICES FPJ>
6650               amount_accepted,                                -- <SERVICES FPJ>
6651               amount_rejected,                                -- <SERVICES FPJ>
6652               amount_billed,                                  -- <SERVICES FPJ>
6653               amount_cancelled,                               -- <SERVICES FPJ>
6654               ship_to_location_id,
6655               need_by_date,
6656               promised_date,
6657               from_header_id,
6658               from_line_id,
6659               --togeorge 09/27/2000
6660         --added note to receiver column
6661         note_to_receiver,
6662               approved_flag,
6663               po_release_id,
6664               closed_code,
6665               closed_reason,
6666               price_override,
6667               encumbered_flag,
6668               shipment_type,
6669               shipment_num,
6670               inspection_required_flag,
6671               receipt_required_flag,
6672               days_early_receipt_allowed,
6673               days_late_receipt_allowed,
6674               enforce_ship_to_location_code,
6675               ship_to_organization_id,
6676               invoice_close_tolerance,
6677               receive_close_tolerance,
6678               accrue_on_receipt_flag,
6679               allow_substitute_receipts_flag,
6680               receiving_routing_id,
6681               qty_rcv_tolerance,
6682               qty_rcv_exception_code,
6683               receipt_days_exception_code,
6684         terms_id,
6685               ship_via_lookup_code,
6686         freight_terms_lookup_code,
6687         fob_lookup_code,
6688         unit_meas_lookup_code,
6689               last_accept_date, -- zxzhang, Mar 04
6690               match_option,   -- bgu, Dec. 7, 98
6691         country_of_origin_code, --frkhan 1/12/99
6692 -- start of 1548597
6693               secondary_unit_of_measure,
6694               secondary_quantity,
6695               preferred_grade,
6696               secondary_quantity_received,
6697               secondary_quantity_accepted,
6698               secondary_quantity_rejected,
6699               secondary_quantity_cancelled,
6700 -- end of 1548597
6701               vmi_flag,  -- VMI FPH
6702               drop_ship_flag,   --  <DropShip FPJ>
6703               consigned_flag,  -- CONSIGNED FPI
6704               transaction_flow_header_id, --<Shared Proc FPJ>
6705               org_id  --<Shared Proc FPJ>
6706               --<DBI Req Fulfillment 11.5.11 Start >
6707               , closed_for_receiving_date
6708               , closed_for_invoice_date
6709               --<DBI Req Fulfillment 11.5.11 End >
6710               -- <Complex Work R12 Start>
6711               , value_basis
6712               , matching_basis
6713               -- <Complex Work R12 End>
6714         , outsourced_assembly --<SHIKYU R12>
6715         ,tax_attribute_update_code --<eTax Integration R12>
6716               )
6717        VALUES (x_line_location_id,
6718                interface.last_update_date,
6719                interface.last_updated_by,
6720                interface.po_header_id,
6721                interface.creation_date,
6722                interface.created_by,
6723                interface.last_update_login,
6724                x_po_line_id,
6725                x_quantity, --interface.quantity,
6726                0,
6727                0,
6728                0,
6729                0,
6730                0,
6731                interface.amount,    -- amount                 -- <SERVICES FPJ>
6732                0,                   -- amount_received        -- <SERVICES FPJ>
6733                0,                   -- amount_accepted        -- <SERVICES FPJ>
6734                0,                   -- amount_rejected        -- <SERVICES FPJ>
6735                0,                   -- amount_billed          -- <SERVICES FPJ>
6736                0,                   -- amount_cancelled       -- <SERVICES FPJ>
6737                x_ship_to_location_id,
6738                interface.need_by_date,
6739                l_promised_date,     --<Bug# 3293109>
6740                /* Bug11802312 - Retain the document reference for a consigned PO */
6741                interface.from_header_id,
6742                interface.from_line_id,
6743                --togeorge 09/27/2000
6744          --added note to receiver column
6745          interface.note_to_receiver,
6746                decode(g_document_type, 'RFQ', '', 'N'),
6747                decode(g_document_subtype,'RELEASE',x_po_release_id,''),
6748                decode(interface.consigned_flag, 'Y', 'CLOSED FOR INVOICE' ,                    -- CONSIGNED FPI
6749                   decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'CLOSED FOR RECEIVING'  ,   -- CONSIGNED FPI
6750                   decode(g_document_type, 'RFQ', '', 'OPEN'))),
6751                x_closed_reason,                                                                  -- CONSIGNED FPI
6752  /* Bug: 2000367 When there is no currency conversion involved we should not
6753                  round at all because it gives rise to inconsistency.
6754                  So removing the ext precision and blind rounding to 5 also as
6755                  this is already done above in case when currency conversion is
6756                  involved.
6757 */
6758                nvl(x_price,interface.unit_price),
6759                decode(g_document_type, 'RFQ', '', 'N'),
6760                decode(g_document_type, 'RFQ', 'RFQ',
6761       Decode(interface.document_subtype,
6762                       'RELEASE','BLANKET',
6763                       interface.document_subtype)),
6764                interface.shipment_num,
6765                 l_inspection_required_flag, -- 10403047
6766               l_receipt_required_flag, -- 10403047
6767 	/*bug 9155693 START-->
6768             While autocreating RFQ from Req. receiving controls values were set to NULL
6769             which cause receiving controls values reamin NULL in PO, which was created
6770             by copying RFQ to Quotation to PO.
6771             Hence, setting receving control fields to defaulted values.
6772 
6773       decode(g_document_type, 'RFQ', '',
6774       rc.days_early_receipt_allowed),
6775                decode(g_document_type, 'RFQ', '',
6776       rc.days_late_receipt_allowed),
6777                decode(g_document_type, 'RFQ', '',
6778       rc.enforce_ship_to_location_code),
6779       */
6780                rc.days_early_receipt_allowed,
6781                rc.days_late_receipt_allowed,
6782                rc.enforce_ship_to_location_code,
6783       -- bug 9155693 END
6784 
6785                interface.destination_organization_id, -- ship to org
6786                decode(interface.consigned_flag, 'Y', 100 , -- CONSIGNED FPI
6787                       (decode(g_document_type, 'RFQ', '',
6788                       (decode(interface.pcard_id, NULL,
6789                               nvl(item.invoice_close_tolerance,
6790                               params.invoice_close_tolerance), 100))))),
6791                decode(g_interface_source_code,'CONSUMPTION_ADVICE', 100 , -- CONSIGNED FPI
6792                      (decode(g_document_type, 'RFQ', '',
6793       nvl(item.receive_close_tolerance,
6794       params.receive_close_tolerance)))),
6795 /** BUG 843414, bgu, Mar. 23, 1999
6796  *  "Accrue on Receipt" should not be allowed for P-card
6797  *  orders because of accounting restrictions.
6798  */
6799               decode(interface.transaction_flow_header_id, NULL,  --<Shared Proc FPJ>
6800                decode(interface.consigned_flag, 'Y', 'N' , -- CONSIGNED FPI
6801                   decode(g_document_type, 'RFQ', '',
6802                     DECODE( interface.pcard_id, NULL,
6803           DECODE(interface.destination_type_code,
6804                       'EXPENSE',DECODE(nvl(item.receipt_required_flag,
6805                                            nvl(interface.receipt_required_flag,
6806              nvl(vendor.receipt_required_flag,
6807              nvl(params.receiving_flag,'N')))),
6808                                         'N', 'N',
6809                                         DECODE(params.expense_accrual_code,
6810                                                'PERIOD END', 'N', 'Y')),
6811                       'Y'),'N'))), 'Y'),    --<Shared Proc FPJ>
6812                decode(g_document_type, 'RFQ','',
6813       rc.allow_substitute_receipts_flag),
6814 
6815      /*bug 9155693 START -->
6816             While autocreating RFQ from Req. receiving controls values were set to NULL
6817             which cause receiving controls values reamin NULL in PO, which was created
6818             by copying RFQ to Quotation to PO.
6819             Hence, setting receving control fields to defaulted values.
6820 
6821        decode(g_document_type, 'RFQ', '',
6822        rc.receiving_routing_id),
6823       */
6824                rc.receiving_routing_id,
6825       -- bug 9155693 END
6826 
6827                rc.qty_rcv_tolerance,
6828                rc.qty_rcv_exception_code,
6829       --bug 9155693 START
6830       /*decode(g_document_type, 'RFQ', '',
6831             rc.receipt_days_exception_code),
6832       */
6833             rc.receipt_days_exception_code,
6834       --bug 9155693 END
6835 
6836          decode(g_document_type, 'RFQ', interface.terms_id, ''),
6837          decode(g_document_type, 'RFQ', interface.ship_via_lookup_code,
6838       ''),
6839          decode(g_document_type, 'RFQ',
6840       interface.freight_terms_lookup_code, ''),
6841          decode(g_document_type, 'RFQ',
6842       interface.fob_lookup_code, ''),
6843          /* Bug 3913683 : we want to import the unit measure lookup code for
6844                           all document types and not just RFQ's so commenting out
6845         below decode. */
6846          /*   decode(g_document_type, 'RFQ',
6847       interface.unit_meas_lookup_code), */
6848       -- bug 5208159
6849       -- bug 16416508
6850       nvl(x_po_uom, x_temp_uom),
6851     -- Bug 3496450. Based the defaulting on promised date going
6852                 --     into the database rather than needby date. Put a to_date
6853                 --     around null so that decode returns date and does not
6854                 --     truncate time information
6855                decode(g_document_type,'RFQ',to_date(null),l_promised_date+rc.days_late_receipt_allowed),
6856                decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'P' , -- CONSIGNED FPI
6857                       decode(interface.consigned_flag, 'Y', 'P', --bug 2861408
6858                              decode(g_document_type, 'RFQ', '',           --bgu, Dec. 7, 98
6859                   vendor.invoice_match_option)
6860                             )
6861                      ),
6862          x_country_of_origin_code,
6863 --<INVCONV R12> replace interface.secondary_unit_of_measure/secondary quantity with variables.
6864 -- also replace in the decode
6865 -- start of 1548597
6866                x_secondary_unit_of_measure,
6867                x_secondary_quantity,
6868                interface.preferred_grade,
6869                decode(x_secondary_unit_of_measure,NULL,NULL,0),
6870                decode(x_secondary_unit_of_measure,NULL,NULL,0),
6871                decode(x_secondary_unit_of_measure,NULL,NULL,0),
6872                decode(x_secondary_unit_of_measure,NULL,NULL,0),
6873 -- end of 1548597
6874                interface.vmi_flag ,  -- VMI FPH
6875                interface.drop_ship_flag,   --  <DropShip FPJ>
6876                interface.consigned_flag,  -- CONSIGNED FPI
6877                interface.transaction_flow_header_id, --<Shared Proc FPJ>
6878                g_purchasing_ou_id            --<Shared Proc FPJ>
6879                --<DBI Req Fulfillment 11.5.11 Start >
6880                , decode(g_interface_source_code,'CONSUMPTION_ADVICE',
6881                         sysdate,null)   --- Closed_for_receiving_date
6882                , decode(interface.consigned_flag, 'Y',
6883                          sysdate,null )  --- Closed_for_invoice_date
6884                --<DBI Req Fulfillment 11.5.11 End >
6885               -- <Complex Work R12 Start>
6886               , x_order_type_lookup_code
6887               , l_matching_basis
6888               -- <Complex Work R12 End>
6889         , p_outsourced_assembly --<SHIKYU R12>
6890         , nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax Integration R12>
6891 );
6892     l_progress := '260';
6893     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6894         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6895                             p_token    => l_progress,
6896                             p_message  => 'Create shipment: After insert into po line locations');
6897     END IF;
6898 
6899    -- Bug 882050: Shipment level global attribute
6900 if g_document_type = 'RFQ' then
6901 null;
6902 -- <Bug 8513167>
6903 -- Make the call for all document types. Added BLANKET
6904 elsif (interface.document_subtype IN ('STANDARD','PLANNED','BLANKET')) THEN
6905         calculate_local(interface.document_subtype, 'SHIPMENT',
6906                         x_line_location_id);
6907    elsif (g_document_subtype='RELEASE') THEN
6908         calculate_local('RELEASE', 'SHIPMENT', x_line_location_id);
6909    end if;
6910 
6911 
6912     l_progress := '270';
6913       /*
6914       ** 9/10/97 ecso
6915       ** OE Callback function for maintaining so_drop_ship_sources table
6916       */
6917    --<SOURCING TO PO FPH>
6918     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6919         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6920                             p_token    => l_progress,
6921                             p_message  => 'Sourcing to FPH-4 starts');
6922     END IF;
6923 
6924    --No need to update oe tables when requisition line id is null,negotiation
6925    --lines would not result in a drop ship PO
6926    if interface.requisition_line_id is not null then
6927    IF (g_document_type = 'PO') THEN
6928   x_p_api_version     := 1.0; -- as requested by OE
6929   x_p_line_location_id    := x_line_location_id;
6930 
6931     l_progress := '280';
6932   BEGIN
6933    SELECT PO_HEADER_ID
6934     ,PO_LINE_ID
6935    INTO x_p_po_header_id
6936     ,x_p_po_line_id
6937    FROM   PO_LINE_LOCATIONS_ALL  --<Shared Proc FPJ>
6938    WHERE  LINE_LOCATION_ID = x_line_location_id;
6939         EXCEPTION
6940                WHEN NO_DATA_FOUND THEN
6941                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6942                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6943                                             p_token    => l_progress,
6944                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
6945                     END IF;
6946          WHEN OTHERS THEN
6947                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6948                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6949                                             p_token    => l_progress,
6950                                             p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
6951                     END IF;
6952         END;
6953 
6954     l_progress := '290';
6955   BEGIN
6956      SELECT requisition_header_id
6957      INTO   x_p_req_header_id
6958      FROM   po_requisition_lines_all  --<Shared Proc FPJ>
6959    WHERE  requisition_line_id = interface.requisition_line_id;
6960         EXCEPTION
6961                WHEN NO_DATA_FOUND THEN
6962                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6963                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6964                                         p_token    => l_progress,
6965                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
6966                 END IF;
6967          WHEN OTHERS THEN
6968                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6969                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6970                                         p_token    => l_progress,
6971                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
6972                 END IF;
6973         END;
6974 
6975   IF g_document_subtype = 'RELEASE' THEN
6976    x_p_po_release_id := g_po_release_id;
6977   ELSE
6978    x_p_po_release_id := '';
6979   END IF;
6980 
6981     l_progress := '300';
6982   oe_drop_ship_grp.update_po_info(x_p_api_version,
6983           x_p_return_status,
6984           x_p_msg_count,
6985           x_p_msg_data,
6986           x_p_req_header_id,
6987           interface.requisition_line_id,
6988           x_p_po_header_id,
6989           x_p_po_line_id,
6990           x_p_line_location_id,
6991           x_p_po_release_id
6992           );
6993 
6994     l_progress := '310';
6995     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6996         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6997                             p_token    => l_progress,
6998                             p_message  => 'Sourcing to FPH-4 ends');
6999     END IF;
7000    --<SOURCING TO PO FPH End>
7001 
7002    END IF; /* end of OE callback for PO */
7003    end if;
7004    --
7005   END IF;
7006 
7007   l_progress := '320';
7008 
7009   IF (g_document_type = 'PO') THEN
7010 
7011     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7012         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7013                             p_token    => l_progress,
7014                             p_message  => 'Create shipment: Before calling create_distribution');
7015     END IF;
7016     create_distributions(
7017       x_po_line_id,
7018       x_line_location_id,
7019       x_po_release_id,
7020       p_rate_for_req_fields -- <ACHTML R12>
7021     );
7022 
7023   END IF;
7024 
7025     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7026         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
7027     END IF;
7028 
7029 EXCEPTION
7030   WHEN OTHERS THEN
7031      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
7032          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
7033                             p_progress => l_progress);
7034      END IF;
7035      wrapup(interface.interface_header_id);
7036      po_message_s.sql_error('CREATE_SHIPMENTS',l_progress,sqlcode);
7037      raise;
7038 END create_shipment;
7039 
7040 /* ============================================================================
7041      NAME: CREATE_DISTRIBUTION
7042      DESC: Create document distribution
7043      ARGS: IN : x_requisition_line_id IN number
7044            IN : x_po_line_id IN number
7045            IN : x_Line_location_id IN number
7046            IN : x_po_release_id IN number
7047      ALGR:
7048 
7049    ==========================================================================*/
7050 PROCEDURE create_distributions(
7051   x_po_line_id IN number,
7052   x_line_location_id IN number,
7053   x_po_release_id IN number,
7054   p_rate_for_req_fields IN NUMBER -- <ACHTML R12>
7055   )
7056 IS
7057 x_distribution_num number;
7058 x_po_distribution_id number;
7059 x_gl_date_option varchar2(25);
7060 x_po_appl_id number;
7061 x_gl_appl_id number;
7062 x_sob_id    number;
7063 /* obtain currency info to adjust precision */
7064 x_precision         number := 2;
7065 x_ext_precision     number := 5;
7066 x_min_unit          number :='';
7067 x_order_type_lookup_code varchar2(15);
7068 
7069 x_kanban_card_id  number:='';
7070 x_accrued_flag          varchar2(1);
7071 x_po_uom                varchar2(25):=null;
7072 x_uom_convert           varchar2(2) := fnd_profile.value('PO_REQ_BPA_UOM_CONVERT');
7073 x_conversion_rate       number := 1;
7074 
7075 -- Bug 7661419, No conversion for same currency.
7076 x_req_rate              PO_REQUISITION_LINES_ALL.rate%TYPE;
7077 x_req_currency_code     PO_REQUISITION_LINES_ALL.currency_code%TYPE;
7078 x_rate                  PO_REQUISITION_LINES_ALL.rate%TYPE;
7079 -- Bug 7661419 end
7080 -- <SERVICES FPJ START>
7081 --
7082 l_uom_conversion_rate        MTL_UOM_CONVERSIONS.conversion_rate%TYPE := 1;
7083 l_currency_conversion_rate   PO_HEADERS_ALL.rate%TYPE := 1;
7084 --
7085 -- <SERVICES FPJ END>
7086 
7087 /* Bug 1030123: cursor to get all the distributions based on the line id */
7088 
7089 l_api_name CONSTANT VARCHAR2(30) := 'create_distributions';
7090 
7091 cursor c_dist is
7092   select po_distribution_id
7093     from po_distributions_all  --<Shared Proc FPJ>
7094    where line_location_id = x_line_location_id;
7095 
7096 --<MRC FPJ Start>
7097 l_key NUMBER;
7098 l_return_status VARCHAR2(1);
7099 l_msg_data VARCHAR2(2000);
7100 l_msg_count NUMBER;
7101 --<MRC FPJ End>
7102 
7103 l_progress VARCHAR2(3) := '000';                    --< Bug 3210331 >
7104 
7105 
7106 l_amount_ordered  NUMBER; --!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
7107 l_drop_ship_flag   po_line_locations.drop_ship_flag%type; --bug#3603067
7108 -- bug 5208159
7109 l_from_type_lookup_code po_headers_all.TYPE_LOOKUP_CODE%type;
7110 
7111 --introduced to hold the value of drop_ship_flag for shipments
7112 BEGIN
7113     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7114         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
7115         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7116                             p_token    => l_progress,
7117                             p_message  => 'Create_distributions: po_line_id: '||x_po_line_id);
7118         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7119                             p_token    => l_progress,
7120                             p_message  => 'Create_distributions: po_line_loc_id: '||x_line_location_id);
7121         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7122                             p_token    => l_progress,
7123                             p_message  => 'Create_distributions: po_release_id: '||x_po_release_id);
7124     END IF;
7125 
7126     /*
7127     ** get previous max distribution number for this shipment
7128     */
7129     l_progress:='010';
7130     SELECT nvl(max(distribution_num), 0)
7131       INTO x_distribution_num
7132       FROM po_distributions_all  --<Shared Proc FPJ>
7133      WHERE line_location_id = x_line_location_id;
7134 
7135     l_progress:='020';
7136     fnd_profile.get('PO_AUTOCREATE_DATE',x_gl_date_option);
7137 
7138      /* Bug 482648 ecso 4/30/97
7139       * Move quantity conversion from setup_interface_tables
7140       * to create_distribution for consistency
7141       */
7142 
7143     l_progress := '030';
7144     SELECT order_type_lookup_code
7145     INTO   x_order_type_lookup_code
7146     FROM   po_line_types
7147     WHERE  line_type_id = interface.line_type_id;
7148 
7149     l_progress := '040';
7150     SELECT set_of_books_id
7151       INTO x_sob_id
7152       FROM financials_system_params_all  --<Shared Proc FPJ>
7153      WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
7154 
7155 
7156     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7157         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7158                             p_token    => l_progress,
7159                             p_message  => 'Create_distributions: Order type: '||x_order_type_lookup_code);
7160     END IF;
7161 
7162     -- <BUG 3422146> Removed IF condition so that we will always get the
7163     -- the precision/extended precision information for the PO currency.
7164     --
7165      -- Bug 4471683: added not null check for currency
7166     IF interface.h_currency_code IS NOT NULL THEN
7167       FND_CURRENCY.get_info ( currency_code => interface.h_currency_code -- IN
7168                           , precision     => x_precision               -- OUT
7169                           , ext_precision => x_ext_precision           -- OUT
7170                           , min_acct_unit => x_min_unit                -- OUT
7171                           );
7172     END IF;
7173 
7174     l_progress := '050';
7175 
7176    /* R11: Enhancement to support Kanban
7177     * ecso 8/29/97
7178     * Kanban_Card_Id is copied from requisition line
7179     * to po_distributions
7180     */
7181   --<SOURCING TO PO FPH>
7182   --Even sourcing need to execute this when backed by a req.
7183     Begin
7184       SELECT KANBAN_CARD_ID
7185       INTO   x_kanban_card_id
7186       FROM   po_requisition_lines_all pol  --<Shared Proc FPJ>
7187       WHERE  pol.REQUISITION_LINE_ID = interface.requisition_line_id;
7188     Exception
7189          WHEN NO_DATA_FOUND THEN
7190      /* Not all req has kanban id */
7191             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7192                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7193                                     p_token    => l_progress,
7194                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
7195             END IF;
7196          WHEN OTHERS THEN
7197             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
7198                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
7199                                    p_progress => l_progress);
7200             END IF;
7201            raise;
7202     End;
7203 
7204 /* 661570 - svaidyan : Use nvl(x_ext_precision,5) for rounding the qty
7205                        if the order type lookup code is not quantity */
7206 
7207 /** BUG 843414,  bgu, Apr. 23, 1999
7208  *  For Pcard PO or release, set the accrued_flag to yes, such that Receipt Accruals
7209  *  - Period-End Process will not accrue pcard related receipts.
7210  */
7211 if(interface.pcard_id is not null) then
7212   x_accrued_flag := 'Y';
7213 else
7214   x_accrued_flag := 'N';
7215 end if;
7216 
7217     l_progress:='060';
7218 
7219 /* 875315 - csheu: if the gl_date_option is not 'REQ GL DATE'
7220             then we need to make sure the period_name is not NULL
7221             even the period may not be opened */
7222 
7223 /* also use fnd_application table to find the application_id */
7224     SELECT application_id
7225     INTO   x_po_appl_id
7226     FROM   fnd_application
7227     WHERE  application_short_name = 'PO';
7228 
7229     l_progress := '070';
7230     SELECT application_id
7231     INTO   x_gl_appl_id
7232     FROM   fnd_application
7233     WHERE  application_short_name = 'SQLGL';
7234 
7235 /* 973348, duplicate of 966370
7236    The following should be done only if the po encumbrance flag is yes
7237 */
7238 
7239     if ((params.po_encumbrance_flag = 'Y') and
7240         (x_gl_date_option <> 'REQ GL DATE') and
7241         (params.period_name IS NULL)) THEN
7242 
7243           l_progress := '080';
7244           SELECT PS1.period_name
7245            INTO   params.period_name
7246            FROM   GL_PERIOD_STATUSES PS1
7247            ,      GL_PERIOD_STATUSES PS2
7248            ,      GL_SETS_OF_BOOKS GSOB
7249            WHERE  PS1.application_id = x_gl_appl_id
7250            AND    PS1.set_of_books_id = params.sob_id
7251            AND    PS1.adjustment_period_flag = 'N'
7252            AND    trunc(sysdate) BETWEEN trunc(PS1.start_date)
7253                                  AND     trunc(PS1.end_date)
7254            AND    ps1.period_year <= gsob.latest_encumbrance_year
7255            AND    gsob.set_of_books_id = params.sob_id
7256            AND    PS1.period_name = PS2.period_name
7257            AND    PS2.application_id = x_po_appl_id
7258            AND    PS2.adjustment_period_flag = 'N'
7259            AND    PS2.set_of_books_id = params.sob_id;
7260     end if;
7261 
7262     /** Bug 1039361
7263      *  bgu, Oct. 22, 1999
7264      *  Port Bug 1030123 in r11 to r115
7265      *  need to put the NEXTVAL inside the insert as there may
7266      *  be more than one distribution.
7267      */
7268 
7269   /* Enh : 1660036 */
7270 
7271   -- bug 5208159 : Conversion of req UOM to Quotation UOM should always happen if the
7272   -- source document is a quote and profile 'PO: Convert Requisition UOM to Source Document UOM'
7273   -- should be ignored in that case
7274   IF (interface.from_line_id IS NOT NULL) AND (g_document_subtype = 'STANDARD') THEN
7275       l_progress := '085';
7276 
7277       BEGIN
7278 
7279         SELECT poh.type_lookup_code
7280         INTO   l_from_type_lookup_code
7281         FROM   po_headers_all poh
7282         WHERE poh.po_header_id=interface.from_header_id ;
7283 
7284       EXCEPTION
7285         WHEN OTHERS THEN
7286             IF g_debug_unexp THEN
7287                  PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
7288                                     p_progress => l_progress);
7289             END IF;
7290             po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
7291             wrapup(interface.interface_header_id);
7292             raise;
7293       END;
7294   END IF;
7295 
7296   IF (nvl(x_uom_convert,'N') = 'Y' OR (l_from_type_lookup_code = 'QUOTATION')) THEN
7297   -- bug 5208159 end
7298 
7299    IF (g_document_subtype='RELEASE')
7300      -- Bug 2735840 Convert UOM when autocreating a PO that references a GA
7301      OR ((g_document_subtype='STANDARD')
7302          AND (interface.from_line_id is not null)) THEN
7303 
7304    /* get the uom from the PO . This will be used for uom conversion */
7305     BEGIN
7306       IF (g_document_subtype='RELEASE') THEN -- Bug 2735840
7307         l_progress := '090';
7308         select unit_meas_lookup_code
7309         into x_po_uom
7310         from po_lines_all pol ,  --<Shared Proc FPJ>
7311              po_headers_all poh  --<Shared Proc FPJ>
7312         where pol.po_header_id = poh.po_header_id
7313         and pol.po_header_id = interface.po_header_id
7314         and pol.line_num = interface.line_num;
7315       -- Bug 2735840 START
7316       ELSE -- Autocreating a PO that references a GA
7317         l_progress := '100';
7318         SELECT unit_meas_lookup_code
7319         INTO x_po_uom
7320         FROM po_lines_all
7321         WHERE po_line_id = interface.from_line_id;
7322       END IF; -- g_document_subtype
7323       -- Bug 2735840 END
7324 
7325         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7326             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7327                                 p_token    => l_progress,
7328                                 p_message  => 'Create_distributions: UOM is: '||x_po_uom);
7329         END IF;
7330      EXCEPTION
7331      WHEN OTHERS THEN
7332         IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
7333             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
7334                                p_progress => l_progress);
7335         END IF;
7336        po_message_s.sql_error('CREATE_DISTRIBUTIONS',l_progress,sqlcode);
7337        wrapup(interface.interface_header_id);
7338        raise;
7339     END;
7340 
7341     l_progress := '110';
7342    /* before inserting into the distributions table get the conversion rate to convert
7343       into the BPA uom if the uom's on the req and BPA are different .
7344       This conversion is done only if the Convert UOM  profile option is set to Yes. */
7345 
7346       if interface.unit_meas_lookup_code <> x_po_uom then
7347 
7348        x_conversion_rate := po_uom_s.po_uom_convert(interface.unit_meas_lookup_code,
7349                                               x_po_uom,
7350                                               interface.item_id);
7351       else
7352 
7353        x_conversion_rate := 1;
7354 
7355       end if;
7356       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7357           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7358                               p_token    => l_progress,
7359                               p_message  => 'Create_distributions: Conversion rate is: '||x_conversion_rate);
7360       END IF;
7361 
7362     END IF;
7363   END IF;
7364 
7365     l_progress := '120';
7366   --<SOURCING TO PO FPH START>
7367   --Dont insert distribution record if the various account_id s are
7368   --not defaulted for negotiation lines which are not backed by req for sourcing
7369     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7370         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7371                             p_token    => l_progress,
7372                             p_message  => 'Sourcing to FPH-5 starts');
7373     END IF;
7374   if (g_interface_source_code in ('SOURCING','CONSUMPTION_ADVICE') and  -- CONSIGNED FPI
7375      (interface.charge_account_id is null or
7376       interface.accrual_account_id is null or
7377       interface.variance_account_id is null or
7378       (interface.encumbered_flag='Y' and
7379        interface.budget_account_id is null))) then
7380       null;
7381   else
7382 
7383     l_uom_conversion_rate := x_conversion_rate;               -- <SERVICES FPJ>
7384     -- <ACHTML R12>
7385     l_currency_conversion_rate := p_rate_for_req_fields; -- <SERVICES FPJ>
7386 
7387     l_progress := '130';
7388 
7389   --<SOURCING TO PO FPH END>
7390 
7391 
7392     l_progress := '150';
7393     --<GRANTS FPJ START>
7394     --SQL WHAT: Update po_distributions_interface table with
7395     --          po_distribution_id's and distribution_num
7396 
7397     UPDATE po_distributions_interface
7398     SET    po_distribution_id = po_distributions_s.NEXTVAL,
7399            distribution_num = x_distribution_num + rownum
7400     WHERE  interface_header_id = interface.interface_header_id
7401            AND interface_line_id = interface.interface_line_id;
7402 
7403     l_progress := '160';
7404     update_award_distributions;
7405 
7406     --<GRANTS FPJ END>
7407 
7408     l_progress := '170';
7409     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7410         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7411                             p_token    => l_progress,
7412                             p_message  => 'Sourcing to FPH-5 ends and insert into distributions');
7413     END IF;
7414 
7415 --!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
7416 --bug#3603067 need to get the value of drop ship flag for the shipment
7417 begin
7418     select nvl(drop_ship_flag,'N') into l_drop_ship_flag
7419     from po_line_locations_all where
7420     line_location_id=x_line_location_id;
7421 exception
7422     when others then
7423   null;
7424 end;
7425 --bug#3603067
7426 
7427 BEGIN
7428 SELECT pdi.amount_ordered
7429 INTO   l_amount_ordered
7430 FROM po_distributions_interface pdi, po_line_locations_all poll
7431            WHERE pdi.interface_header_id = interface.interface_header_id
7432              AND pdi.interface_line_id = interface.interface_line_id
7433              AND poll.line_location_id = x_line_location_id;
7434 
7435 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'l_amount_ordered',l_amount_ordered);
7436 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'x_order_type_lookup_code',x_order_type_lookup_code);
7437 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'l_currency_conversion_rate',l_currency_conversion_rate);
7438 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'l_uom_conversion_rate',l_uom_conversion_rate);
7439 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'x_precision',x_precision);
7440 
7441 
7442 EXCEPTION
7443     WHEN OTHERS THEN
7444         NULL;
7445 END;
7446 
7447 -- Bug 7661419, No conversion for same currency.
7448 BEGIN
7449 SELECT PRL.currency_code,
7450        Nvl(PRL.rate,1)
7451 INTO   x_req_currency_code,
7452        x_req_rate
7453 FROM   po_requisition_lines_all PRL
7454 WHERE  PRL.requisition_line_id = INTERFACE.requisition_line_id;
7455 
7456 EXCEPTION
7457     WHEN OTHERS THEN
7458         NULL;
7459 END;
7460 
7461 IF ( x_req_currency_code = INTERFACE.h_currency_code ) THEN
7462    x_rate:=x_req_rate;
7463 ELSE
7464    x_rate:= p_rate_for_req_fields;
7465 END IF;
7466 
7467 --!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
7468 
7469     INSERT INTO po_distributions_all  --<Shared Proc FPJ>
7470                 (po_distribution_id,
7471                  last_update_date,
7472                  last_updated_by,
7473                  po_header_id,
7474                  creation_date,
7475                  created_by,
7476                  last_update_login,
7477                  po_line_id,
7478                  line_location_id,
7479                  po_release_id,
7480                  req_distribution_id,
7481                  set_of_books_id,
7482                  code_combination_id,
7483                  deliver_to_location_id,
7484                  deliver_to_person_id,
7485                  quantity_ordered,
7486                  quantity_delivered,
7487                  quantity_billed,
7488                  quantity_cancelled,
7489                  amount_ordered,                              -- <SERVICES FPJ>
7490                  amount_delivered,                            -- <SERVICES FPJ>
7491                  amount_cancelled,                            -- <SERVICES FPJ>
7492                  amount_billed,                               -- <SERVICES FPJ>
7493                  rate_date,
7494                  rate,
7495                  accrued_flag,
7496                  encumbered_flag,
7497                  gl_encumbered_date,
7498                  gl_encumbered_period_name,
7499                  distribution_num,
7500                  destination_type_code,
7501                  destination_organization_id,
7502                  destination_subinventory,
7503                  budget_account_id,
7504                  accrual_account_id,
7505                  variance_account_id,
7506 
7507                  --< Shared Proc FPJ Start >
7508                  dest_charge_account_id,
7509                  dest_variance_account_id,
7510                  --< Shared Proc FPJ End >
7511 
7512                  wip_entity_id,
7513                  wip_line_id,
7514                  wip_repetitive_schedule_id,
7515                  wip_operation_seq_num,
7516                  wip_resource_seq_num,
7517                  bom_resource_id,
7518                  prevent_encumbrance_flag,
7519                  project_id,
7520                  task_id,
7521                  end_item_unit_number,
7522                  expenditure_type,
7523                  project_accounting_context,
7524                  destination_context,
7525                  expenditure_organization_id,
7526                  expenditure_item_date,
7527                  accrue_on_receipt_flag,
7528                  kanban_card_id,
7529                  tax_recovery_override_flag,  --<eTax Integration R12>
7530                  recovery_rate,
7531                  award_id,
7532                  --togeorge 09/27/2000
7533                  --added oke columns
7534                  oke_contract_line_id,
7535                  oke_contract_deliverable_id,
7536                  org_id,  --<Shared Proc FPJ>
7537                  distribution_type,  -- <Encumbrance FPJ>
7538                  tax_attribute_update_code,  --<eTax Integration R12>
7539                  interface_distribution_ref --<ECO 5373370>
7540                  )
7541           SELECT pdi.po_distribution_id, --<GRANTS FPJ>
7542                  interface.last_update_date,
7543                  interface.last_updated_by,
7544                  interface.po_header_id,
7545                  interface.creation_date,
7546                  interface.created_by,
7547                  interface.last_update_login,
7548                  x_po_line_id,
7549                  x_line_location_id,
7550                  decode(g_document_subtype,'RELEASE',x_po_release_id,''),
7551                  pdi.req_distribution_id,
7552                  nvl(x_sob_id, pdi.set_of_books_id), --<Bug 3692789>
7553                  pdi.charge_account_id,
7554                  pdi.deliver_to_location_id,
7555      --bug#3603067 if the drop_ship_flag is 'Y' then we
7556      --need to pass null
7557                  decode(l_drop_ship_flag,'Y',NULL,pdi.deliver_to_person_id),
7558 
7559                  -- <SERVICES FPJ START>
7560                  -- Bug 3472140: Changed precisions to 15
7561                  decode(
7562                    x_order_type_lookup_code,
7563                    'QUANTITY',
7564                    round((pdi.quantity_ordered * x_conversion_rate), 15),
7565                    'AMOUNT',
7566                    round(
7567                      (pdi.quantity_ordered
7568                       * x_conversion_rate
7569                       / x_rate), -- <ACHTML R12> -- Bug 7661419
7570                      nvl(x_ext_precision, 15)
7571                    ),
7572                    NULL
7573                  ),
7574                  -- <SERVICES FPJ END>
7575 
7576                  0,
7577                  0,
7578                  0,
7579 
7580                  -- <SERVICES FPJ START>
7581              --bug 16302602,get amount_ordered from REQ_LINE_CURRENCY_AMOUNT
7582 				 --if it has value.
7583                  decode ( x_order_type_lookup_code          -- amount_ordered
7584                         , 'RATE'       ,round ( nvl(prd.REQ_LINE_CURRENCY_AMOUNT,pdi.amount_ordered)
7585                                                   * l_uom_conversion_rate
7586                                               , x_precision )
7587                         , 'FIXED PRICE', nvl(prd.REQ_LINE_CURRENCY_AMOUNT,pdi.amount_ordered)
7588 
7589                                        ,NULL
7590                         ),
7591                  0,                                         -- amount_delivered
7592                  0,                                         -- amount_cancelled
7593                  0,                                         -- amount_billed
7594                  -- <SERVICES FPJ END>
7595 
7596                  pdi.rate_date,
7597                  pdi.rate,
7598      x_accrued_flag,
7599                  'N'
7600 
7601       --<Encumbrance FPJ>
7602       -- If Req encumbrance is on and the profile option requests
7603       -- that the Req's GL date be used, use the Req's GL date.
7604       -- Otherwise, if PO enc is on, use SYSDATE.
7605       --            if PO enc is not on, use NULL.
7606 
7607       -- gl_encumbered_date =
7608       ,  NVL(  DECODE(  params.req_encumbrance_flag
7609                      ,  'Y', DECODE(   x_gl_date_option
7610                                     ,  'REQ GL DATE', pdi.gl_encumbered_date
7611                                     ,  NULL
7612                                     )
7613                      ,  NULL
7614                      )
7615             ,  DECODE(  params.po_encumbrance_flag
7616                      ,  'Y', TRUNC(SYSDATE)
7617                      ,  NULL
7618                      )
7619             )
7620 
7621       -- gl_encumbered_period_name =
7622       ,  NVL(  DECODE(  params.req_encumbrance_flag
7623                      ,  'Y', DECODE(x_gl_date_option
7624                                  ,  'REQ GL DATE', pdi.gl_encumbered_period_name
7625                                  ,  NULL
7626                                  )
7627                      ,  NULL
7628                      )
7629             ,  DECODE(  params.po_encumbrance_flag
7630                      ,  'Y', params.period_name
7631                      ,  NULL
7632                      )
7633             )
7634 
7635              ,   pdi.distribution_num, --<GRANTS FPJ>
7636                  pdi.destination_type_code,
7637                  pdi.destination_organization_id,
7638                  pdi.destination_subinventory,
7639                  pdi.budget_account_id,
7640                  pdi.accrual_account_id,
7641                  pdi.variance_account_id,
7642 
7643                  --< Shared Proc FPJ Start >
7644                  -- Copy the receiving accounts from the interface table to
7645                  -- the PO table.
7646                  pdi.dest_charge_account_id,
7647                  pdi.dest_variance_account_id,
7648                  --< Shared Proc FPJ End >
7649 
7650                  pdi.wip_entity_id,
7651                  pdi.wip_line_id,
7652                  pdi.wip_repetitive_schedule_id,
7653                  pdi.wip_operation_seq_num,
7654                  pdi.wip_resource_seq_num,
7655                  pdi.bom_resource_id
7656                --<ENCUMBRANCE FPJ>
7657                -- prevent_encumbrance_flag =
7658                /*,  DECODE(  pdi.destination_type_code
7659                         ,  g_dest_type_code_SHOP_FLOOR, 'Y'
7660                         ,  'N'
7661                         ) Commented for Encumbrance Project*/
7662                 , DECODE(  pdi.destination_type_code
7663                                                 ,  g_dest_type_code_SHOP_FLOOR
7664                                                                 , decode((select entity_type
7665                                                                           from wip_entities
7666                                                                           where wip_entity_id= pdi.wip_entity_id),6, 'N', 'Y')
7667                         ,  'N'
7668                         )         /* Encumbrance Project - to enable encumbrance for destination type Shop Floor and WIP entity type EAM  */
7669                ,  pdi.project_id,
7670                  pdi.task_id,
7671                  pdi.end_item_unit_number,
7672                  pdi.expenditure_type,
7673                  pdi.project_accounting_context,
7674                  pdi.destination_context,
7675                  pdi.expenditure_organization_id,
7676                  pdi.expenditure_item_date,
7677                  decode(interface.transaction_flow_header_id, NULL, --<Shared Proc FPJ>
7678                         DECODE(interface.destination_type_code,
7679                                'EXPENSE',
7680                                decode(nvl(item.receipt_required_flag,
7681                                           nvl(interface.receipt_required_flag,
7682                                               nvl(vendor.receipt_required_flag,
7683                                                   nvl(params.receiving_flag,'N')))),
7684                                       'N', 'N',
7685                                       decode(params.expense_accrual_code,
7686                                              'PERIOD END', 'N', 'Y')),
7687                                'INVENTORY', 'Y',
7688                                'SHOP FLOOR', 'Y'),
7689                         'Y'), --<Shared Proc FPJ>
7690                  x_kanban_card_id,
7691                  pdi.tax_recovery_override_flag,  --<eTax integration R12>
7692                  decode(pdi.tax_recovery_override_flag, 'Y', pdi.recovery_rate, null),  --<eTax integration R12>
7693                  pdi.award_id,   -- OGM_0.0 changes..
7694                  --togeorge 09/27/2000
7695                  --added oke columns
7696                  interface.oke_contract_line_id,
7697                  interface.oke_contract_deliverable_id,
7698                  g_purchasing_ou_id,  --<Shared Proc FPJ>
7699                  poll.shipment_type,  -- <Encumbrance FPJ: join on poll.line_location_id added>
7700                  nvl2(g_calculate_tax_flag, 'CREATE', null), --<eTax integration R12>
7701                  pdi.interface_distribution_ref --<ECO 5373370>
7702             FROM po_distributions_interface pdi,
7703 			     po_line_locations_all poll,
7704                  po_req_distributions_all prd
7705               --bug 16302602,join table po_req_distributions_all to get REQ_LINE_CURRENCY_AMOUNT
7706            WHERE pdi.interface_header_id = interface.interface_header_id
7707              AND pdi.interface_line_id = interface.interface_line_id
7708              AND poll.line_location_id = x_line_location_id  --<Encumbrance FPJ>
7709              AND prd.DISTRIBUTION_ID(+) =pdi.req_distribution_id;--bug 16871797
7710 
7711 
7712     -- <BUG 3322948> Correct last distribution amount for any conversion and
7713     -- rounding inaccuracies to ensure that the distribution amounts add up
7714     -- to their corresponding shipment amount.
7715     --
7716     PO_INTERFACE_S.calibrate_last_dist_amount(x_line_location_id);
7717 
7718     -- bug 10246022
7719     -- Correct last distribution quantity for any conversion and
7720     -- rounding inaccuracies to ensure that the distribution quantity add up
7721     -- to their corresponding shipment quantity.
7722     PO_INTERFACE_S.calibrate_last_dist_quantity(x_line_location_id);
7723 
7724   end if;
7725     -- Bug 882050: Dist level global attribute
7726 
7727     l_progress := '210';
7728     /* Bug 1030123: Since there may be more than a distribution, we need to
7729        loop thru all the distribution based on the line id */
7730 
7731     begin
7732 
7733       open c_dist;
7734 
7735       loop
7736 
7737         fetch c_dist into x_po_distribution_id;
7738 
7739         exit when c_dist%NOTFOUND;
7740 
7741         -- <Bug 8513167>
7742         -- Make the call for all document types. Added BLANKET
7743         if (interface.document_subtype IN ('STANDARD','PLANNED','BLANKET')) THEN
7744            l_progress := '220';
7745            calculate_local(interface.document_subtype, 'DISTRIBUTION',
7746                            x_po_distribution_id);
7747         elsif (g_document_subtype='RELEASE') THEN
7748             l_progress := '230';
7749             calculate_local('RELEASE', 'DISTRIBUTION', x_po_distribution_id);
7750         end if;
7751       end loop;
7752 
7753       close c_dist;
7754 
7755     exception
7756       when others then
7757         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7758             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7759                                 p_token    => l_progress,
7760                                 p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
7761         END IF;
7762         if c_dist%ISOPEN then
7763           close c_dist;
7764         end if;
7765     end;
7766 
7767      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7768          PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
7769      END IF;
7770 
7771 EXCEPTION
7772   WHEN OTHERS THEN
7773      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
7774          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
7775                             p_progress => l_progress);
7776      END IF;
7777      wrapup(interface.interface_header_id);
7778      po_message_s.sql_error('CREATE_DISTRIBUTIONS',l_progress,sqlcode);
7779      raise;
7780 END create_distributions;
7781 
7782 
7783 ------------------------------------------------------------------<BUG 3322948>
7784 -------------------------------------------------------------------------------
7785 --Start of Comments
7786 --Name: calibrate_last_dist_amount
7787 --Pre-reqs:
7788 --  None.
7789 --Modifies:
7790 --  PO_DISTRIBUTIONS_ALL.AMOUNT_ORDERED
7791 --Locks:
7792 --  None.
7793 --Function:
7794 --  This procedure is used to calibrate the amount of the last distribution
7795 --  belonging to a particular PO Shipment. After going through UOM/currency
7796 --  conversion and rounding, there is a chance that the sum of the distribution
7797 --  amounts will not add up to the shipment amount, causing submission checks
7798 --  to fail. To correct this, we will recalculate the last distribution
7799 --  amount as the difference between the shipment amount and the sum of
7800 --  all other distribution amounts.
7801 --Parameters:
7802 --IN:
7803 --p_line_location_id
7804 --  ID belonging to parent shipment of the distributions which need to be
7805 --  calibrated.
7806 --Testing:
7807 --  None.
7808 --End of Comments
7809 -------------------------------------------------------------------------------
7810 -------------------------------------------------------------------------------
7811 PROCEDURE calibrate_last_dist_amount
7812 (
7813     p_line_location_id   IN   NUMBER
7814 )
7815 IS
7816     l_api_name               VARCHAR2(30) := 'calibrate_last_dist_amount';
7817     l_log_head               VARCHAR2(100) := g_log_head || l_api_name;
7818     l_progress               VARCHAR2(3);
7819 
7820     l_sum_dist_amounts       PO_DISTRIBUTIONS_ALL.amount_ordered%TYPE;
7821     l_last_dist_amount       PO_DISTRIBUTIONS_ALL.amount_ordered%TYPE;
7822     l_last_distribution_id   PO_DISTRIBUTIONS_ALL.po_distribution_id%TYPE;
7823     l_shipment_amount        PO_LINE_LOCATIONS_ALL.amount%TYPE;
7824 
7825 BEGIN
7826 
7827 l_progress:='000'; PO_DEBUG.debug_begin(l_log_head);
7828 l_progress:='010'; PO_DEBUG.debug_var(l_log_head,l_progress,'p_line_location_id',p_line_location_id);
7829 
7830     -- Retrieve Distribution Data =============================================
7831     --
7832     -- Get the sum of all distribution amounts
7833     -- and the ID of the last distribution.
7834     --
7835     SELECT sum(amount_ordered)
7836     ,      max(po_distribution_id)
7837     INTO   l_sum_dist_amounts
7838     ,      l_last_distribution_id
7839     FROM   po_distributions_all
7840     WHERE  line_location_id = p_line_location_id;
7841 
7842 l_progress:='020'; PO_DEBUG.debug_var(l_log_head,l_progress,'l_sum_dist_amounts',l_sum_dist_amounts);
7843 l_progress:='030'; PO_DEBUG.debug_var(l_log_head,l_progress,'l_last_distribution_id',l_last_distribution_id);
7844 
7845 
7846     -- Get the shipment amount ================================================
7847     --
7848     SELECT amount
7849     INTO   l_shipment_amount
7850     FROM   po_line_locations_all
7851     WHERE  line_location_id = p_line_location_id;
7852 
7853 l_progress:='040'; PO_DEBUG.debug_var(l_log_head,l_progress,'l_shipment_amount',l_shipment_amount);
7854 
7855 
7856     -- Correct the last distribution ==========================================
7857     --
7858     -- Set it to the shipment amount minus the sum of all distribution
7859     -- amounts (except the last distribution).
7860     --
7861     UPDATE    po_distributions_all
7862     SET       amount_ordered = l_shipment_amount - (l_sum_dist_amounts - amount_ordered)
7863     WHERE     po_distribution_id = l_last_distribution_id
7864     RETURNING amount_ordered
7865     INTO      l_last_dist_amount;
7866 
7867 l_progress:='050'; PO_DEBUG.debug_var(l_log_head,l_progress,'l_last_dist_amount',l_last_dist_amount);
7868 
7869     --=========================================================================
7870 
7871 l_progress:='060'; PO_DEBUG.debug_end(l_log_head);
7872 
7873 EXCEPTION
7874 
7875     WHEN OTHERS THEN
7876         PO_DEBUG.debug_exc ( p_log_head => l_log_head
7877                            , p_progress => l_progress);
7878         RAISE;
7879 
7880 END calibrate_last_dist_amount;
7881 
7882 -- <Complex Work R12 Start>
7883 -------------------------------------------------------------------------------
7884 --Start of Comments
7885 --Name: calibrate_last_dist_quantity
7886 --Pre-reqs:
7887 --  None.
7888 --Modifies:
7889 --  PO_DISTRIBUTIONS_ALL.QUANTITY_ORDERED
7890 --Locks:
7891 --  None.
7892 --Function:
7893 --  This procedure is used to calibrate the quantity of the last distribution
7894 --  belonging to a particular PO Shipment. After going through UOM/currency
7895 --  conversion and rounding, there is a chance that the sum of the distribution
7896 --  quantitiess will not add up to the shipment qty, causing submission checks
7897 --  to fail. To correct this, we will recalculate the last distribution
7898 --  quantity as the difference between the shipment quantity and the sum of
7899 --  all other distribution quantities.
7900 --Parameters:
7901 --IN:
7902 --p_line_location_id
7903 --  ID belonging to parent shipment of the distributions which need to be
7904 --  calibrated.
7905 --Testing:
7906 --  None.
7907 --End of Comments
7908 -------------------------------------------------------------------------------
7909 -------------------------------------------------------------------------------
7910 PROCEDURE calibrate_last_dist_quantity(
7911    p_line_location_id   IN   NUMBER
7912 )
7913 IS
7914 
7915 d_module   VARCHAR2(70) := 'po.plsql.PO_INTERFACE_S.calibrate_last_dist_quantity';
7916 d_progress NUMBER;
7917 
7918 l_sum_dist_quantities       PO_DISTRIBUTIONS_ALL.quantity_ordered%TYPE;
7919 l_last_dist_id              PO_DISTRIBUTIONS_ALL.po_distribution_id%TYPE;
7920 l_last_dist_qty             PO_DISTRIBUTIONS_ALL.quantity_ordered%TYPE;
7921 l_shipment_quantity         PO_LINE_LOCATIONS_ALL.quantity%TYPE;
7922 
7923 BEGIN
7924 
7925   d_progress := 0;
7926 
7927   IF (PO_LOG.d_proc) THEN
7928     PO_LOG.proc_begin(d_module);
7929     PO_LOG.proc_begin(d_module, 'p_line_location_id', p_line_location_id);
7930   END IF;
7931 
7932   d_progress := 10;
7933 
7934   SELECT sum(pod.quantity_ordered), max(pod.po_distribution_id)
7935   INTO l_sum_dist_quantities, l_last_dist_id
7936   FROM po_distributions_all pod
7937   WHERE pod.line_location_id = p_line_location_id;
7938 
7939   d_progress := 20;
7940 
7941   IF (PO_LOG.d_stmt) THEN
7942     PO_LOG.stmt(d_module, d_progress, 'l_last_dist_id', l_last_dist_id);
7943   END IF;
7944 
7945   SELECT poll.quantity
7946   INTO l_shipment_quantity
7947   FROM po_line_locations_all poll
7948   WHERE poll.line_location_id = p_line_location_id;
7949 
7950   d_progress := 30;
7951 
7952   UPDATE po_distributions_all pod
7953   SET pod.quantity_ordered = l_shipment_quantity -
7954                               (l_sum_dist_quantities - pod.quantity_ordered)
7955   WHERE pod.po_distribution_id = l_last_dist_id
7956   RETURNING pod.quantity_ordered INTO l_last_dist_qty;
7957 
7958   IF (PO_LOG.d_proc) THEN
7959     PO_LOG.proc_end(d_module, 'l_last_dist_qty', l_last_dist_qty);
7960     PO_LOG.proc_end(d_module);
7961   END IF;
7962 
7963 EXCEPTION
7964   WHEN OTHERS THEN
7965     IF (PO_LOG.d_exc) THEN
7966       PO_LOG.exc(d_module, d_progress, SQLCODE||SQLERRM);
7967     END IF;
7968 
7969     RAISE;
7970 
7971 END calibrate_last_dist_quantity;
7972 -- <Complex Work R12 End>
7973 
7974 
7975 /* ============================================================================
7976      NAME: CREATE_RFQ
7977      DESC: Create/Add to RFQ from requisition data in the PO_HEADERS,LINES
7978            and DISTRIBUTION interface tables.
7979      ARGS: IN : x_interface_header_id IN number
7980      ALGR:
7981 
7982    ==========================================================================*/
7983 PROCEDURE create_rfq(x_interface_header_id IN number,
7984          x_document_id IN OUT NOCOPY number) IS
7985 
7986     x_quotation_class_code varchar2(25);
7987     x_document_num po_headers.segment1%type:=null; -- Bug 1093645
7988 
7989 l_api_name CONSTANT VARCHAR2(30) := 'create_documents';
7990 
7991 --<MRC FPJ Start>
7992 l_return_status VARCHAR2(1);
7993 l_msg_data VARCHAR2(2000);
7994 l_msg_count NUMBER;
7995 --<MRC FPJ End>
7996 l_progress VARCHAR2(3) := '000';                --< Bug 3210331 >
7997 
7998 --<Bug :11071489 REQ_AUTOCREATE Start>--
7999 l_parameter_list  PO_CORE_S4.p_parameter_list;
8000 l_event_name VARCHAR2(100);
8001 --<REQ_AUTOCREATE END>--
8002 
8003 BEGIN
8004     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8005         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
8006     END IF;
8007 
8008     get_system_defaults;
8009 
8010     l_progress := '010';
8011     -- populate the interface tables with data from the
8012     -- requisition.
8013     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8014         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8015                             p_token    => l_progress,
8016                             p_message  => 'Create_rfq: Before setup_interface_tables');
8017     END IF;
8018 
8019     -- <Complex Work R12 Start>: Pass in false for p_is_complex_work_po
8020     setup_interface_tables(
8021       x_interface_header_id => x_interface_header_id
8022     , x_document_id => x_document_id
8023     , p_is_complex_work_po => FALSE
8024     );
8025     -- <Complex Work R12 End>
8026 
8027     l_progress := '020';
8028     -- determine which interface lines and shipments should
8029     -- be grouped.
8030     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8031         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8032                             p_token    => l_progress,
8033                             p_message  => 'Create_rfq: Before group_interface_lines');
8034     END IF;
8035 
8036     group_interface_lines(
8037       x_interface_header_id => x_interface_header_id
8038     , p_is_complex_work_po  => FALSE
8039 	, p_group_shipments     => NULL --<Bug 14608120 Autocreate GE ER>
8040     );
8041 
8042     l_progress := '030';
8043     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8044         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8045                             p_token    => l_progress,
8046                             p_message  => 'Create_rfq: interface_hdr id '||x_interface_header_id);
8047     END IF;
8048 
8049     OPEN interface_cursor(x_interface_header_id);
8050 
8051     FETCH interface_cursor INTO interface;
8052 
8053     IF interface_cursor%notfound THEN
8054       CLOSE interface_cursor;
8055       RETURN;
8056     END IF;
8057 
8058     g_rate_for_req_fields := interface.h_rate;   -- <BUG 4895489>
8059 
8060     IF (g_mode = 'ADD') THEN
8061 
8062        l_progress := '040';
8063        UPDATE po_headers_all  --<Shared Proc FPJ>
8064           SET last_update_date  = interface.last_update_date,
8065               last_updated_by   = interface.last_updated_by,
8066               last_update_login = interface.last_update_login,
8067               status_lookup_code = 'I'
8068         WHERE po_header_id = interface.po_header_id;
8069     ELSE /* New */
8070 
8071         l_progress := '050';
8072   SELECT quotation_class_code
8073         INTO   x_quotation_class_code
8074         FROM   po_document_types
8075         WHERE  document_type_code = 'RFQ'
8076   and    document_subtype   = interface.quote_type_lookup_code;
8077 
8078         l_progress := '060';
8079     /** Bug 881882, bgu, Apr. 29, 1999
8080      *  For inserting record into po_headers view, it used
8081      *  to_date(interface.h_rate_date, 'DD/MM/YYYY') for column rate_date.
8082      *  But since the data type of interface.h_rate_date is already date,
8083      *  this is unneccssary and causing problem when system date mask is
8084      *  defined otherwise.
8085      */
8086         INSERT INTO po_headers_all  --<Shared Proc FPJ>
8087                   (po_header_id,
8088                    last_update_date,
8089                    last_updated_by,
8090                    segment1,
8091                    created_by,
8092                    last_update_login,
8093                    summary_flag,
8094                    enabled_flag,
8095                    type_lookup_code,
8096                    agent_id,
8097                    creation_date,
8098                    revision_num,
8099                    ship_to_location_id,
8100                    bill_to_location_id,
8101                    terms_id,
8102                    ship_via_lookup_code,
8103                    fob_lookup_code,
8104                    freight_terms_lookup_code,
8105                    status_lookup_code,
8106                    quotation_class_code,
8107                    quote_type_lookup_code,
8108        approval_required_flag,
8109        currency_code,
8110        rate_type,
8111        rate_date,
8112        rate,
8113                    org_id  --<Shared Proc FPJ>
8114                   ,style_id   --<R12 STYLES PHASE II >
8115                    )
8116             VALUES (interface.po_header_id,
8117                     interface.last_update_date,
8118                     interface.last_updated_by,
8119                     interface.document_num,
8120                     interface.created_by,
8121                     interface.last_update_login,
8122                     'N',
8123                     'Y',
8124                     g_document_type,
8125                     interface.agent_id,
8126                     interface.creation_date,
8127                     0,
8128                     nvl(vendor.ship_to_location_id,
8129                         interface.ship_to_location_id),
8130                     nvl(vendor.bill_to_location_id,
8131                         interface.bill_To_Location_Id),
8132                     nvl(vendor.terms_id,
8133                         interface.terms_id),
8134                     nvl(vendor.ship_via_lookup_code,
8135                         interface.ship_via_lookup_code),
8136                     nvl(vendor.fob_lookup_code,
8137                         interface.fob_lookup_code),
8138                     nvl(vendor.freight_terms_lookup_code,
8139                         interface.freight_terms_lookup_code),
8140                     'I',
8141                     x_quotation_class_code,
8142                     interface.quote_type_lookup_code,
8143         'N',
8144                     interface.h_currency_code,
8145                     interface.h_rate_type,
8146 --                    to_date(interface.h_rate_date, 'DD/MM/YYYY'),
8147         interface.h_rate_date,              -- Bug 881882 , bgu
8148                     interface.h_rate,
8149                     g_purchasing_ou_id  --<Shared Proc FPJ>
8150                     ,interface.style_id   --<R12 STYLES PHASE II >
8151                     );
8152 
8153     IF(interface.vendor_list_header_id is NOT NULL)THEN
8154 
8155         l_progress := '080';
8156 /* Bug 875124 :
8157    Using po_vendor_list_entries_v to insert into po_rfq_vendors
8158    as po_vendor_list_entries_v contains vendor_list with active vendors
8159 */
8160          INSERT INTO po_rfq_vendors
8161                      (po_header_id,
8162                       sequence_num,
8163                       last_update_date,
8164                       last_updated_by,
8165                       last_update_login,
8166                       creation_date,
8167                       created_by,
8168                       vendor_id,
8169                       vendor_site_id,
8170                       vendor_contact_id,
8171                       print_flag,
8172                       print_count)
8173                SELECT interface.po_header_id,
8174                       rownum,
8175                       interface.last_update_date,
8176                       interface.last_updated_by,
8177                       interface.last_update_login,
8178                       interface.creation_date,
8179                       interface.created_by,
8180                       vendor_id,
8181                       vendor_site_id,
8182                       vendor_contact_id,
8183                       'Y',
8184                       0
8185                  FROM po_vendor_list_entries_v
8186                 WHERE vendor_list_header_id = interface.vendor_list_header_id;
8187       END IF;
8188     END IF;/* of New */
8189 
8190     /* DEBUG Create the new lines  */
8191     l_progress:='090';
8192 
8193     -- <Complex Work R12 Start>: Pass in false for p_is_complex_work_po
8194     create_line(
8195       x_interface_header_id => x_interface_header_id
8196     , p_is_complex_work_po => FALSE
8197     );
8198     -- <Complex Work R12 End>
8199 
8200     l_progress := '100';
8201     LOOP
8202 
8203         FETCH interface_cursor INTO interface;
8204         EXIT WHEN interface_cursor%notfound;
8205 
8206         -- <Complex Work R12 Start>: Pass in false for p_is_complex_work_po
8207         create_line(
8208           x_interface_header_id => x_interface_header_id
8209         , p_is_complex_work_po => FALSE
8210         );
8211         -- <Complex Work R12 End>
8212 
8213     END LOOP;
8214 
8215 /* bug 1093645:code added to fix the deadlock issue in autocreate*/
8216     if (g_mode = 'NEW')  then
8217          IF (params.user_defined_rfq_num_code='AUTOMATIC') AND
8218             (g_document_type = 'RFQ') THEN
8219 
8220                l_progress := '110';
8221 
8222                -- bug5174177
8223                x_document_num :=
8224                  PO_CORE_SV1.default_po_unique_identifier
8225                  ( p_table_name => 'PO_HEADERS_RFQ',
8226                    p_org_id     => g_purchasing_ou_id
8227                  );
8228 
8229                IF g_debug_stmt THEN
8230                  PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8231                             p_token    => l_progress,
8232                             p_message  => 'new po num = ' || x_document_num);
8233                END IF;
8234 
8235                l_progress := '130';
8236               UPDATE po_headers set segment1=x_document_num,
8237                                     clm_document_number =x_document_num
8238               where po_header_id=x_document_id;
8239 
8240           END IF;
8241     END IF;
8242 
8243     l_progress := '140';
8244    --<Bug :11071489 REQ_AUTOCREATE Start>--
8245      l_event_name := 'oracle.apps.po.autocreate.rfqcreated';
8246      l_parameter_list(1).name := 'Interface_Header_ID' ;
8247      l_parameter_list(1).value := x_interface_header_id;
8248      po_core_s4.raise_business_event(l_event_name,l_parameter_list);
8249     --<REQ_AUTOCREATE end>---
8250     wrapup(x_interface_header_id);
8251 
8252     l_progress := '150';
8253     CLOSE interface_cursor;
8254 
8255     COMMIT;
8256 
8257     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8258         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
8259     END IF;
8260 
8261 EXCEPTION
8262    WHEN OTHERS THEN
8263      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
8264          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
8265                             p_progress => l_progress);
8266      END IF;
8267      wrapup(x_interface_header_id);
8268 
8269      po_message_s.sql_error('CREATE_RFQ',l_progress,sqlcode);
8270      po_message_s.sql_show_error;
8271      po_message_s.clear;
8272      CLOSE interface_cursor;
8273      --togeorge 11/20/2001
8274      -- Bug 1349801
8275      -- Added a Rollback when a Exception was raised
8276      -- This Rollbacks all the Changes done when a Exception Condition was raised
8277      ROLLBACK;
8278 END create_rfq;
8279 
8280 /* ============================================================================
8281      NAME: GET_SYSTEM_DEFAULTS
8282      DESC: Get system defaults
8283      ARGS: None
8284      ALGR:
8285 
8286    ==========================================================================*/
8287 PROCEDURE get_system_defaults IS
8288 x_date date;
8289 l_api_name CONSTANT VARCHAR2(30) := 'get_system_defaults';  --< Bug 3210331 >
8290 l_progress VARCHAR2(3) := '000';                            --< Bug 3210331 >
8291 BEGIN
8292      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8293          PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
8294      END IF;
8295 
8296     /* Get WHO column values */
8297     who.user_id  := nvl(fnd_global.user_id,0);
8298     who.login_id := nvl(fnd_global.login_id,0);
8299     who.resp_id  := nvl(fnd_global.resp_id,0);
8300 
8301     l_progress:='010';
8302 
8303     /* Get system defaults */
8304     po_core_s.get_po_parameters(params.currency_code,
8305                                 params.coa_id,
8306                                 params.po_encumbrance_flag,
8307                                 params.req_encumbrance_flag,
8308                                 params.sob_id,
8309                                 params.ship_to_location_id,
8310                                 params.bill_to_location_id,
8311                                 params.fob_lookup_code,
8312                                 params.freight_terms_lookup_code,
8313                                 params.terms_id,
8314                                 params.default_rate_type,
8315                                 params.taxable_flag,
8316                                 params.receiving_flag,
8317                                 params.enforce_buyer_name_flag,
8318                                 params.enforce_buyer_auth_flag,
8319                                 params.line_type_id,
8320                                 params.manual_po_num_type,
8321                                 params.po_num_code,
8322                                 params.price_type_lookup_code,
8323                                 params.invoice_close_tolerance,
8324                                 params.receive_close_tolerance,
8325                                 params.security_structure_id,
8326                                 params.expense_accrual_code,
8327                                 params.inventory_organization_id,
8328                                 params.rev_sort_ordering,
8329                                 params.min_rel_amount,
8330                                 params.notify_blanket_flag,
8331                                 params.budgetary_control_flag,
8332                                 params.user_defined_req_num_code,
8333                                 params.rfq_required_flag,
8334                                 params.manual_req_num_type,
8335                                 params.enforce_full_lot_qty,
8336                                 params.disposition_warning_flag,
8337                                 params.reserve_at_completion_flag,
8338                                 params.user_defined_rcpt_num_code,
8339                                 params.manual_rcpt_num_type,
8340               params.use_positions_flag,
8341               params.default_quote_warning_delay,
8342                 params.inspection_required_flag,
8343                 params.user_defined_quote_num_code,
8344                 params.manual_quote_num_type,
8345                 params.user_defined_rfq_num_code,
8346                 params.manual_rfq_num_type,
8347                 params.ship_via_lookup_code,
8348 	        params.qty_rcv_tolerance,
8349 		params.acceptance_required_flag);    /* Bug 7518967 : Default Acceptance Required Check ER */
8350 
8351         l_progress:='020';
8352 
8353         IF(params.po_encumbrance_flag = 'Y') THEN
8354           po_core_s.get_period_name(params.sob_id,params.period_name,x_date);
8355         END IF;
8356 
8357      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8358          PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
8359      END IF;
8360 
8361 EXCEPTION
8362   WHEN OTHERS THEN
8363      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
8364          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
8365                             p_progress => l_progress);
8366      END IF;
8367      wrapup(interface.interface_header_id);
8368      po_message_s.sql_error('GET SYSTEM DEFAULTS',l_progress,sqlcode);
8369      raise;
8370 
8371 END get_system_defaults;
8372 
8373 /* ============================================================================
8374      NAME: GET_INVOICE MATCH OPTION
8375      DESC: Get invoice match option
8376      ARGS: None
8377      ALGR:
8378 
8379    ==========================================================================*/
8380 PROCEDURE get_invoice_match_option(x_vendor_id    IN number,
8381          x_vendor_site_id IN number,
8382          x_invoice_match_option OUT NOCOPY varchar2)
8383  IS
8384 l_progress VARCHAR2(3) := '000';                                --< Bug 3210331 >
8385 l_api_name CONSTANT VARCHAR2(30) := 'get_invoice_match_option'; --< Bug 3210331 >
8386 
8387 BEGIN
8388      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8389          PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
8390      END IF;
8391 
8392    if (X_vendor_site_id is not null) then
8393      l_progress := '010';
8394      /* Retrieve Invoice Match Option from Vendor site*/
8395      SELECT match_option
8396      INTO   x_invoice_match_option
8397      FROM   po_vendor_sites_all  --<Shared Proc FPJ>
8398      WHERE  vendor_site_id = X_vendor_site_id;
8399    end if;
8400 
8401    if(x_invoice_match_option is NULL) then
8402      /* Retrieve Invoice Match Option from Vendor */
8403      if (X_vendor_id is not null) then
8404        l_progress := '020';
8405        SELECT match_option
8406        INTO   x_invoice_match_option
8407        FROM   po_vendors
8408        WHERE  vendor_id = X_vendor_id;
8409      end if;
8410    end if;
8411 
8412    if(x_invoice_match_option is NULL) then
8413      l_progress := '030';
8414      --6057748
8415      -- Get default from ap_product_setup instead of FSP.
8416      SELECT aps.match_option
8417        INTO   x_invoice_match_option
8418        FROM   ap_product_setup aps;
8419 
8420      /* Retrieve Invoice Match Option from Financial System Parameters */
8421 /*
8422      SELECT fsp.match_option
8423        INTO x_invoice_match_option
8424        FROM financials_system_params_all fsp  --<Shared Proc FPJ>
8425       WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>*/
8426    end if;
8427 
8428      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8429          PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
8430      END IF;
8431 EXCEPTION
8432   WHEN OTHERS THEN
8433      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
8434          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
8435                             p_progress => l_progress);
8436      END IF;
8437      wrapup(interface.interface_header_id);
8438      po_message_s.sql_error('GET INVOICE MATCH OPTION',l_progress,sqlcode);
8439      raise;
8440 
8441 END get_invoice_match_option;
8442 
8443 --< Shared Proc FPJ Start >
8444 ---------------------------------------------------------------------------
8445 --Start of Comments
8446 --Name: generate_shared_proc_accounts
8447 --Pre-reqs:
8448 --  The global variables g_document_type, g_document_subtype and params
8449 --  should have been populated correctly.
8450 --Modifies:
8451 --  PO_DISTRIBUTIONS_INTERFACE table. The following columns may get
8452 --  modified:
8453 --       CODE_COMBINATION_ID
8454 --       ACCRUAL_ACCOUNT_ID
8455 --       VARIANCE_ACCOUNT_ID
8456 --       BUDGET_ACCOUNT_ID
8457 --       DEST_CHARGE_ACCOUNT_ID
8458 --       DEST_VARIANCE_ACCOUNT_ID
8459 --Locks:
8460 --  None.
8461 --Function:
8462 --  Generates the accounts for shared procurement scenarios by calling
8463 --  the PO AG workflow. After that, it updates the affected records in
8464 --  PO_DISTRIBUTIONS_INTERFACE table with the new account ID's.
8465 --Parameters:
8466 --IN:
8467 --  p_interface_header_id -- The interface header ID of the document being
8468 --                           processed.
8469 --OUT:
8470 --  None
8471 --Testing:
8472 --End of Comments
8473 ---------------------------------------------------------------------------
8474 PROCEDURE generate_shared_proc_accounts --(
8475 (
8476   p_interface_header_id IN NUMBER
8477 )
8478 IS
8479   l_progress                  VARCHAR2(3) := '000';    --< Bug 3210331 >
8480   l_return_value          BOOLEAN;
8481   l_charge_success              BOOLEAN := TRUE;
8482   l_budget_success              BOOLEAN := TRUE;
8483   l_accrual_success             BOOLEAN := TRUE;
8484   l_variance_success            BOOLEAN := TRUE;
8485   l_charge_account_id           PO_DISTRIBUTIONS_INTERFACE.charge_account_id%TYPE;
8486   l_budget_account_id           PO_DISTRIBUTIONS_INTERFACE.budget_account_id%TYPE;
8487   l_accrual_account_id          PO_DISTRIBUTIONS_INTERFACE.accrual_account_id%TYPE;
8488   l_variance_account_id         PO_DISTRIBUTIONS_INTERFACE.variance_account_id%TYPE;
8489   l_charge_account_flex         VARCHAR2(2000);
8490   l_budget_account_flex         VARCHAR2(2000);
8491   l_accrual_account_flex  VARCHAR2(2000);
8492   l_variance_account_flex       VARCHAR2(2000);
8493   l_charge_account_desc         VARCHAR2(2000);
8494   l_budget_account_desc         VARCHAR2(2000);
8495   l_accrual_account_desc  VARCHAR2(2000);
8496   l_variance_account_desc       VARCHAR2(2000);
8497   l_wf_itemkey              VARCHAR2(80) := NULL;
8498   l_new_ccid_generated          BOOLEAN := FALSE;
8499   l_FB_ERROR_MSG          VARCHAR2(2000);
8500 
8501   l_return_status               VARCHAR2(1);
8502   l_interface_line_id           PO_LINES_INTERFACE.interface_line_id%TYPE;
8503   l_old_interface_line_id       PO_LINES_INTERFACE.interface_line_id%TYPE := -1;
8504   l_interface_distribution_id   PO_DISTRIBUTIONS_INTERFACE.interface_distribution_id%TYPE;
8505   l_item_category_id            PO_LINES_INTERFACE.category_id%TYPE;
8506   l_req_charge_account_id       PO_DISTRIBUTIONS_INTERFACE.charge_account_id%TYPE;
8507   l_req_variance_account_id     PO_DISTRIBUTIONS_INTERFACE.variance_account_id%TYPE;
8508   l_destination_organization_id PO_DISTRIBUTIONS_INTERFACE.destination_organization_id%TYPE;
8509   l_destination_ou_id           PO_HEADERS_ALL.org_id%TYPE;
8510 
8511   l_item_id       PO_LINES_INTERFACE.item_id%TYPE;
8512   l_category_id           PO_LINES_INTERFACE.category_id%TYPE;
8513   l_destination_type_code       PO_DISTRIBUTIONS_ALL.destination_type_code%TYPE;
8514   --l_ship_to_organization_id      NUMBER;
8515   l_ship_to_location_id   PO_DISTRIBUTIONS_INTERFACE.deliver_to_location_id%TYPE;
8516   l_deliver_to_person_id        PO_DISTRIBUTIONS_INTERFACE.deliver_to_person_id%TYPE;
8517   l_line_type_id          PO_LINES_INTERFACE.line_type_id%TYPE;
8518   l_vendor_id       PO_VENDORS.vendor_id%TYPE;
8519   l_agent_id      PO_HEADERS.agent_id%TYPE;
8520   l_expenditure_organization_id PO_DISTRIBUTIONS_INTERFACE.expenditure_organization_id%TYPE;
8521   l_project_id      PO_DISTRIBUTIONS_INTERFACE.project_id%TYPE;
8522   l_task_id       PO_DISTRIBUTIONS_INTERFACE.task_id%TYPE;
8523   l_bom_resource_id     PO_DISTRIBUTIONS_INTERFACE.bom_resource_id%TYPE;
8524   l_wip_entity_id     PO_DISTRIBUTIONS_INTERFACE.wip_entity_id%TYPE;
8525   l_wip_line_id           PO_DISTRIBUTIONS_INTERFACE.wip_line_id%TYPE;
8526   l_wip_repetitive_schedule_id  PO_DISTRIBUTIONS_INTERFACE.wip_repetitive_schedule_id%TYPE;
8527   l_gl_encumbered_date    PO_DISTRIBUTIONS_INTERFACE.gl_encumbered_date%TYPE;
8528   l_destination_subinventory    PO_DISTRIBUTIONS_ALL.destination_subinventory%TYPE;
8529   l_expenditure_type    PO_DISTRIBUTIONS_ALL.expenditure_type%TYPE;
8530   l_expenditure_item_date   PO_DISTRIBUTIONS_INTERFACE.expenditure_item_date%TYPE;
8531   l_wip_operation_seq_num   PO_DISTRIBUTIONS_INTERFACE.wip_operation_seq_num%TYPE;
8532   l_wip_resource_seq_num        PO_DISTRIBUTIONS_INTERFACE.wip_resource_seq_num%TYPE;
8533 
8534 
8535   --< New start_workflow parameters in FPJ End >
8536   l_transaction_flow_header_id  PO_LINE_LOCATIONS.transaction_flow_header_id%TYPE;
8537   l_dest_charge_success         BOOLEAN;
8538   l_dest_variance_success       BOOLEAN;
8539   l_dest_charge_account_id      PO_DISTRIBUTIONS_INTERFACE.dest_charge_account_id%TYPE;
8540   l_dest_variance_account_id    PO_DISTRIBUTIONS_INTERFACE.dest_variance_account_id%TYPE;
8541   l_dest_charge_account_desc    VARCHAR2(2000);
8542   l_dest_variance_account_desc  VARCHAR2(2000);
8543   l_dest_charge_account_flex    VARCHAR2(2000);
8544   l_dest_variance_account_flex  VARCHAR2(2000);
8545   --< New start_workflow parameters in FPJ End >
8546 
8547   -- Bug 3463242 START
8548   l_req_line_id                 PO_LINES_INTERFACE.requisition_line_id%TYPE;
8549   -- <ACHTML R12>
8550   l_requesting_ou_id            PO_REQUISITION_LINES_ALL.org_id%TYPE;
8551   l_unit_price                  PO_LINES_INTERFACE.unit_price%TYPE;
8552   l_base_unit_price             PO_LINES_INTERFACE.base_unit_price%TYPE;
8553   l_amount                      PO_LINES_INTERFACE.amount%TYPE;
8554   l_quantity_dummy              PO_LINES_INTERFACE.quantity%TYPE;
8555   l_order_type_lookup_code      PO_LINE_TYPES_B.order_type_lookup_code%TYPE;
8556   l_po_currency_code            PO_HEADERS_INTERFACE.currency_code%TYPE;
8557   l_req_header_rate_type        PO_HEADERS_INTERFACE.rate_type%TYPE;
8558   l_req_header_rate_date        PO_HEADERS_INTERFACE.rate_date%TYPE;
8559   l_req_header_rate             PO_HEADERS_INTERFACE.rate%TYPE;
8560   l_dist_rate                   PO_DISTRIBUTIONS_INTERFACE.rate%TYPE;
8561   l_rate_for_req_fields         PO_HEADERS_INTERFACE.rate%TYPE;
8562   l_po_func_unit_price          PO_LINES_ALL.unit_price%TYPE;
8563   -- Bug 3463242 END
8564 
8565   l_item_in_linv_pou VARCHAR2(1):= 'Y'; -- Bug 3433867
8566 
8567   --SQL WHAT: All those lines inserted in the PO distributions interface table
8568   --          that have the DOU <> POU.
8569   --SQL WHY:  To call AG Workflow for line that have a Transaction Flow
8570   --          defined between DOU and POU.
8571   CURSOR l_SPS_lines_csr IS
8572     SELECT pdi.interface_distribution_id,
8573            pli.interface_line_id,
8574            pli.category_id,
8575            pdi.charge_account_id,    -- to be copied onto Dest Charge Account
8576            pdi.variance_account_id,  -- to be copied onto Dest Variance Account
8577            pdi.destination_organization_id, -- DINV
8578            TO_NUMBER(hoi.org_information3), -- DOU
8579            pli.item_id,
8580            pli.category_id,
8581            pdi.destination_type_code,
8582            pdi.deliver_to_location_id,
8583            pdi.deliver_to_person_id,
8584            pli.line_type_id,
8585            phi.vendor_id,
8586            phi.agent_id,
8587            pdi.expenditure_organization_id,
8588            pdi.project_id,
8589            pdi.task_id,
8590            pdi.bom_resource_id,
8591            pdi.wip_entity_id,
8592            pdi.wip_line_id,
8593            pdi.wip_repetitive_schedule_id,
8594            pdi.gl_encumbered_date,
8595            pdi.destination_subinventory,
8596            pdi.expenditure_type,
8597            pdi.expenditure_item_date,
8598            pdi.wip_operation_seq_num,
8599            pdi.wip_resource_seq_num,
8600            -- Bug 3463242 START
8601            pli.requisition_line_id,
8602      -- <ACHTML R12>
8603      nvl(prl.org_id, g_hdr_requesting_ou_id) requesting_ou_id,
8604            pli.unit_price,
8605            pli.base_unit_price,
8606            pli.amount,
8607            NVL(plt.order_type_lookup_code,'QUANTITY'),
8608            phi.currency_code,
8609            phi.rate_type,
8610            phi.rate_date,
8611            phi.rate,
8612            pdi.rate
8613            -- Bug 3463242 END
8614     FROM PO_DISTRIBUTIONS_INTERFACE pdi,
8615          PO_LINES_INTERFACE pli,
8616          PO_HEADERS_INTERFACE phi,
8617    PO_REQUISITION_LINES_ALL prl, -- <ACHTML R12>
8618          MTL_PARAMETERS mp,
8619          HR_ORGANIZATION_INFORMATION hoi,
8620          PO_LINE_TYPES_B plt -- Bug 3463242
8621     WHERE phi.interface_header_id = p_interface_header_id
8622       AND pli.interface_header_id = phi.interface_header_id
8623       AND pli.requisition_line_id = prl.requisition_line_id(+) -- <ACHTML R12>
8624       AND pdi.interface_line_id = pli.interface_line_id
8625       AND mp.organization_id = pli.ship_to_organization_id
8626       AND mp.organization_id = hoi.organization_id
8627       AND hoi.org_information_context = 'Accounting Information'
8628       AND hoi.org_information3 <> TO_CHAR(g_purchasing_ou_id)  -- DOU <> POU
8629       AND pli.line_type_id = plt.line_type_id (+) -- Bug 3463242
8630     ORDER BY pli.interface_line_id;
8631   l_api_name VARCHAR2(100) := 'generate_shared_proc_accounts';
8632 BEGIN
8633     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8634         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
8635     END IF;
8636 
8637   -- Ignore for RFQ's and Blankets
8638   IF ( g_document_type <> 'PO' OR
8639        g_document_subtype <> 'STANDARD' ) THEN
8640 
8641     l_progress := '010';
8642     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8643         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8644                             p_token    => l_progress,
8645                             p_message  => 'Ignoring... Type='|| g_document_type|| ' SubType='||g_document_subtype);
8646     END IF;
8647     RETURN;
8648   END IF;
8649 
8650   l_progress := '020';
8651 
8652   OPEN l_SPS_lines_csr;
8653 
8654   l_progress := '030';
8655 
8656   LOOP
8657     FETCH l_SPS_lines_csr
8658     INTO l_interface_distribution_id,
8659          l_interface_line_id,
8660          l_item_category_id,
8661          l_req_charge_account_id,
8662          l_req_variance_account_id,
8663          l_destination_organization_id,
8664          l_destination_ou_id,
8665          l_item_id,
8666          l_category_id,
8667          l_destination_type_code,
8668          l_ship_to_location_id,
8669          l_deliver_to_person_id,
8670          l_line_type_id,
8671          l_vendor_id,
8672          l_agent_id,
8673          l_expenditure_organization_id,
8674          l_project_id,
8675          l_task_id,
8676          l_bom_resource_id,
8677          l_wip_entity_id,
8678          l_wip_line_id,
8679          l_wip_repetitive_schedule_id,
8680          l_gl_encumbered_date,
8681          l_destination_subinventory,
8682          l_expenditure_type,
8683          l_expenditure_item_date,
8684          l_wip_operation_seq_num,
8685          l_wip_resource_seq_num,
8686          -- Bug 3463242 START
8687          l_req_line_id,
8688          l_requesting_ou_id, -- <ACHTML R12>
8689          l_unit_price,
8690          l_base_unit_price,
8691          l_amount,
8692          l_order_type_lookup_code,
8693          l_po_currency_code,
8694          l_req_header_rate_type,
8695          l_req_header_rate_date,
8696          l_req_header_rate,
8697          l_dist_rate;
8698          -- Bug 3463242 END
8699 
8700     l_progress := '040';
8701 
8702     EXIT WHEN l_SPS_lines_csr%NOTFOUND;
8703 
8704     l_progress := '050';
8705 
8706     -- Get the Transaction Flow Header ID from the Inventory API.
8707     -- Use the wrapper API written in PO.
8708     PO_SHARED_PROC_PVT.check_transaction_flow(
8709              p_init_msg_list    => FND_API.G_TRUE,
8710              x_return_status    => l_return_status,  -- OUT NOCOPY VARCHAR2
8711              p_start_ou_id      => g_purchasing_ou_id,
8712              p_end_ou_id        => l_destination_ou_id,
8713              p_ship_to_org_id   => l_destination_organization_id,
8714              p_item_category_id => l_item_category_id,
8715              p_transaction_date => sysdate,
8716              x_transaction_flow_header_id => l_transaction_flow_header_id);
8717                                                           -- OUT NOCOPY NUMBER
8718 
8719     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8720         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8721                             p_token    => l_progress,
8722                             p_message  => 'After calling check_transaction_flow l_transaction_flow_header_id='
8723                                           || to_char(l_transaction_flow_header_id)|| ' l_return_status='
8724                                           ||l_return_status);
8725     END IF;
8726 
8727     l_progress := '060';
8728     IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
8729         APP_EXCEPTION.raise_exception(
8730                 exception_type => 'PO_SHARED_PROC_PVT.check_transaction_flow',
8731                 exception_code => 0,
8732                 exception_text => 'return_status='||l_return_status);
8733     END IF;
8734 
8735     -- Bug 3433867 Start
8736     -- Need to validate the item in the logical inv org of the POU if a
8737     -- valid transaction flow exists and item id is not null
8738 
8739     l_progress := '065';
8740     IF l_transaction_flow_header_id IS NOT NULL AND l_item_id IS NOT NULL THEN
8741        PO_SHARED_PROC_PVT.check_item_in_linv_pou
8742              (x_return_status              => l_return_status,
8743               p_item_id                    => l_item_id,
8744               p_transaction_flow_header_id => l_transaction_flow_header_id,
8745               x_item_in_linv_pou           => l_item_in_linv_pou);
8746        IF l_return_status <> FND_API.g_ret_sts_success THEN
8747           APP_EXCEPTION.raise_exception(
8748                 exception_type => 'PO_SHARED_PROC_PVT.check_item_in_linv_pou',
8749                 exception_code => 0,
8750                 exception_text => 'return_status='||l_return_status);
8751        ELSIF l_return_status = FND_API.g_ret_sts_success AND
8752              (l_item_in_linv_pou <> 'Y') THEN
8753           IF g_debug_stmt THEN
8754              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8755                                  p_token    => l_progress,
8756                                  p_message  => 'After calling check_item_in_linv_pou: Item does not exist in the
8757                                                 logical inv org of the POU'||' l_return_status= '||l_return_status);
8758           END IF;
8759           APP_EXCEPTION.raise_exception(
8760                    exception_type => 'PO_SHARED_PROC_PVT.check_item_in_linv_pou',
8761                    exception_code => 0,
8762                    exception_text => 'Item does not exist in the logical inventory org of POU');
8763        END IF;
8764     END IF;
8765     -- Bug 3433867 End
8766 
8767     l_progress := '070';
8768     -- Call AG Workflow for SPS case
8769     IF (l_transaction_flow_header_id IS NOT NULL) THEN
8770 
8771       l_progress := '080';
8772 
8773       l_charge_account_id        := NULL;
8774       l_variance_account_id      := NULL;
8775       l_accrual_account_id       := NULL;
8776       l_budget_account_id        := NULL;
8777       l_dest_charge_account_id   := l_req_charge_account_id; -- Copied from Req
8778       l_dest_variance_account_id := l_req_variance_account_id;-- Copied from Req
8779 
8780       -- Bug 3463242 START
8781       -- Convert the unit price to the POU functional currency before passing
8782       -- it to the PO account generator workflow.
8783 
8784       IF (l_order_type_lookup_code <> 'AMOUNT') THEN
8785 
8786         IF g_debug_stmt THEN
8787           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8788                               p_token    => l_progress,
8789                               p_message  =>
8790             'unit price in ROU currency: ' || l_unit_price
8791             || ', ROU / requisition rate: ' || l_req_header_rate );
8792         END IF;
8793 
8794         -- Obtain the rate between the ROU currency and the PO currency.
8795         --<Sourcing 11.5.10+> No need to do this if called from Sourcing
8796         IF (g_interface_source_code <> 'SOURCING'
8797       AND g_purchasing_ou_id <> l_requesting_ou_id) -- <ACHTML R12>
8798         THEN
8799           get_rate_for_req_price(
8800             p_requesting_ou_id => l_requesting_ou_id, -- <ACHTML R12>
8801             p_purchasing_ou_id => g_purchasing_ou_id, -- <ACHTML R12>
8802             p_po_currency_code => l_po_currency_code,
8803             p_rate_type => l_req_header_rate_type,
8804             p_rate_date => l_req_header_rate_date,
8805             x_rate => l_rate_for_req_fields
8806           );
8807           IF (l_rate_for_req_fields IS NULL)
8808           THEN
8809             l_rate_for_req_fields := l_req_header_rate;
8810           END IF;
8811         ELSE
8812           l_rate_for_req_fields := l_req_header_rate;
8813         END IF;
8814 
8815         -- First convert from the ROU currency to the PO currency.
8816         PO_INTERFACE_S.do_currency_conversion (
8817           p_order_type_lookup_code => l_order_type_lookup_code,
8818           p_interface_source_code => g_interface_source_code,
8819           p_rate => NVL(l_rate_for_req_fields,1),
8820           p_po_currency_code => l_po_currency_code,
8821           p_requisition_line_id => l_req_line_id,
8822           x_quantity => l_quantity_dummy,
8823           x_unit_price => l_unit_price,
8824           x_base_unit_price => l_base_unit_price,
8825           x_amount => l_amount );
8826 
8827         -- Then convert from the PO currency to the POU currency.
8828         l_po_func_unit_price := l_unit_price * NVL(l_dist_rate,1);
8829 
8830       ELSE -- l_order_type_lookup_code = 'AMOUNT'
8831         l_po_func_unit_price := l_unit_price;
8832       END IF; -- l_order_type_lookup_code
8833       -- Bug 3463242 END
8834 
8835       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8836         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8837                             p_token    => l_progress,
8838                             p_message  => 'Calling AG WF');
8839 
8840         -- Bug 3463242 START
8841         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8842                             p_token    => l_progress,
8843                             p_message  =>
8844           'unit price in PO currency: ' || l_unit_price
8845           || ', ROU / PO rate: ' || l_rate_for_req_fields
8846           || ', POU / PO rate: ' || l_dist_rate
8847           || ', unit price in POU currency (passed to Account Generator): ' || l_po_func_unit_price);
8848         -- Bug 3463242 END
8849       END IF;
8850 
8851      l_progress := '090';
8852 
8853       l_return_value := PO_WF_BUILD_ACCOUNT_INIT.Start_Workflow (
8854 
8855         g_purchasing_ou_id,           -- IN
8856         l_transaction_flow_header_id, -- IN
8857         l_dest_charge_success,        -- IN OUT
8858         l_dest_variance_success,      -- IN OUT
8859         l_dest_charge_account_id,     -- IN OUT
8860         l_dest_variance_account_id,   -- IN OUT
8861         l_dest_charge_account_desc,   -- IN OUT
8862         l_dest_variance_account_desc, -- IN OUT
8863         l_dest_charge_account_flex,   -- IN OUT
8864         l_dest_variance_account_flex, -- IN OUT
8865         l_charge_success,          l_budget_success,
8866       l_accrual_success,         l_variance_success,
8867       l_charge_account_id,         l_budget_account_id,
8868       l_accrual_account_id,        l_variance_account_id,
8869       l_charge_account_flex,         l_budget_account_flex,
8870       l_accrual_account_flex,        l_variance_account_flex,
8871       l_charge_account_desc,         l_budget_account_desc,
8872       l_accrual_account_desc,        l_variance_account_desc,
8873         params.coa_id,
8874         l_bom_resource_id,
8875         NULL, -- p_bom_cost_element_id
8876         l_category_id,                 l_destination_type_code,
8877         l_ship_to_location_id,
8878         l_destination_organization_id, --<Shared Proc FPJ>
8879         l_destination_subinventory,    l_expenditure_type,
8880         l_expenditure_organization_id, l_expenditure_item_date,
8881         l_item_id ,                    l_line_type_id,
8882         NULL, -- PA result billable flag
8883         l_agent_id,
8884         l_project_id,
8885         NULL, -- p_from_type_lookup_code
8886         NULL, -- p_from_header_id
8887         NULL, -- p_from_line_id
8888         l_task_id,                     l_deliver_to_person_id,
8889         g_document_subtype, -- l_type_lookup_code
8890         l_vendor_id,
8891         l_wip_entity_id,
8892         NULL, -- p_wip_entity_type
8893         l_wip_line_id,                 l_wip_repetitive_schedule_id,
8894         l_wip_operation_seq_num,       l_wip_resource_seq_num,
8895         nvl(params.po_encumbrance_flag, 'N'),
8896         l_gl_encumbered_date,
8897 
8898         l_wf_itemkey, l_new_ccid_generated,
8899 
8900         -- 15 Header attributes -- all NULL's
8901         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8902         NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8903         -- 15 Line attributes -- all NULL's
8904         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8905         NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8906         -- 15 Shipment attributes -- all NULL's
8907         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8908         NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8909         -- 15 Distribution attributes -- all NULL's
8910         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8911         NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8912         l_FB_ERROR_MSG,
8913         --<BUG 3407630 START>
8914         NULL,  --x_award_id
8915         NULL,  --x_vendor_site_id
8916         l_po_func_unit_price -- Bug 3463242
8917         --<BUG 3407630 END>
8918         );
8919 
8920       l_progress := '100';
8921 
8922       IF (l_return_value = FALSE) THEN
8923         APP_EXCEPTION.raise_exception(
8924                   exception_type => 'PO_WF_BUILD_ACCOUNT_INIT.Start_Workflow',
8925                   exception_code => 0,
8926                   exception_text => 'Start_workflow returned FALSE');
8927       END IF;
8928 
8929       l_progress := '110';
8930 
8931       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8932           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8933                               p_token    => l_progress,
8934                               p_message  => 'After calling AG WF');
8935           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8936                               p_token    => l_progress,
8937                               p_message  => 'Before updating the interface table with trxflowhdrid l_transaction_flow_header_id='
8938                                             || to_char(l_transaction_flow_header_id)|| ' l_interface_line_id='
8939                                             ||to_char(l_interface_line_id)||' l_old_interface_line_id ='
8940                                             ||to_char(l_old_interface_line_id));
8941       END IF;
8942 
8943       IF l_interface_line_id <> l_old_interface_line_id THEN
8944          l_progress := '120';
8945          UPDATE po_lines_interface
8946             SET transaction_flow_header_id = l_transaction_flow_header_id
8947           WHERE interface_line_id = l_interface_line_id;
8948 
8949          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8950              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8951                                  p_token    => l_progress,
8952                                  p_message  => 'Transaction flow header id updated: SQL%ROWCOUNT = '||SQL%ROWCOUNT);
8953          END IF;
8954 
8955          l_old_interface_line_id := l_interface_line_id;
8956       END IF;
8957 
8958       l_progress := '130';
8959 
8960       -- update the distributions interface table with new account ID's
8961       UPDATE po_distributions_interface
8962       SET charge_account_id        = l_charge_account_id,
8963           variance_account_id      = l_variance_account_id,
8964           accrual_account_id       = l_accrual_account_id,
8965           budget_account_id        = NULL,
8966           dest_charge_account_id   = l_dest_charge_account_id,
8967           dest_variance_account_id = l_dest_variance_account_id
8968       WHERE interface_distribution_id = l_interface_distribution_id;
8969 
8970       l_progress := '140';
8971 
8972     END IF; -- IF (l_transaction_flow_header_id IS NOT NULL)
8973 
8974     l_progress := '150';
8975 
8976   END LOOP;
8977 
8978   l_progress := '160';
8979 
8980   CLOSE l_SPS_lines_csr;
8981 
8982     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8983         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
8984     END IF;
8985 EXCEPTION
8986   WHEN OTHERS THEN
8987     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
8988         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
8989                            p_progress => l_progress);
8990     END IF;
8991     PO_MESSAGE_S.sql_error(l_api_name, l_progress, sqlcode);
8992     RAISE;
8993 END generate_shared_proc_accounts; --)
8994 --< Shared Proc FPJ End >
8995 
8996 
8997 ------------------------------------------------------------------<BUG 3322948>
8998 -------------------------------------------------------------------------------
8999 --Start of Comments
9000 --Name: do_currency_conversion
9001 --Pre-reqs:
9002 --  None.
9003 --Modifies:
9004 --  None.
9005 --Locks:
9006 --  None.
9007 --Function:
9008 --  This procedure performs currency conversion on the input quantity,
9009 --  unit_price, or amount. Which of the previous values to convert depends
9010 --  on the order_type_lookup_code and the interface_source_code.
9011 --
9012 --  If the Req line currency is the same as the new PO currency, we will take
9013 --  the Req's currency_<unit_price/amount> directly so that conversion
9014 --  calculations will not have to be performed again. Otherwise, we will
9015 --  perform the conversion using the input rate.
9016 --
9017 --Parameters:
9018 --IN:
9019 --p_order_type_lookup_code
9020 --  Value Basis of the Requisition/PO line.
9021 --p_interface_source_code
9022 --  Interface Source Code of the current Autocreate session.
9023 --p_rate
9024 --  Currency conversion rate to convert Req Currency to PO Currency.
9025 --p_po_currency_code
9026 --  Currency code of the to-be-created PO.
9027 --p_requisition_line_id
9028 --  Unique ID of the Requisition line being Autocreated.
9029 --  (May be NULL if coming from Sourcing).
9030 --IN OUT:
9031 --x_quantity
9032 --  Quantity to be converted.
9033 --x_unit_price
9034 --  Unit Price to be converted.
9035 --x_base_unit_price
9036 --  Base Unit Price to be converted.
9037 --x_amount
9038 --  Amount to be converted.
9039 --Testing:
9040 --  None.
9041 --End of Comments
9042 -------------------------------------------------------------------------------
9043 -------------------------------------------------------------------------------
9044 PROCEDURE do_currency_conversion
9045 (
9046     p_order_type_lookup_code   IN              VARCHAR2
9047 ,   p_interface_source_code    IN              VARCHAR2
9048 ,   p_rate                     IN              NUMBER
9049 ,   p_po_currency_code         IN              VARCHAR2
9050 ,   p_requisition_line_id      IN              NUMBER
9051 ,   x_quantity                 IN OUT NOCOPY   NUMBER
9052 ,   x_unit_price               IN OUT NOCOPY   NUMBER
9053 ,   x_base_unit_price          IN OUT NOCOPY   NUMBER --bug 3401653
9054 ,   x_amount                   IN OUT NOCOPY   NUMBER
9055 )
9056 IS
9057     l_api_name                VARCHAR2(30) := 'do_currency_conversion';
9058     l_log_head                VARCHAR2(100) := g_log_head || l_api_name;
9059     l_progress                VARCHAR2(3);
9060 
9061     l_precision               FND_CURRENCIES.precision%TYPE;
9062     l_ext_precision           FND_CURRENCIES.extended_precision%TYPE;
9063     l_min_acct_unit           FND_CURRENCIES.minimum_accountable_unit%TYPE;
9064 
9065     l_req_currency_code       PO_REQUISITION_LINES_ALL.currency_code%TYPE;
9066     l_req_ou_currency_code    GL_SETS_OF_BOOKS.currency_code%TYPE; -- Bug 3794198
9067     l_req_unit_price          PO_REQUISITION_LINES_ALL.unit_price%TYPE;
9068     l_req_currency_unit_price PO_REQUISITION_LINES_ALL.currency_unit_price%TYPE;
9069     l_req_amount              PO_REQUISITION_LINES_ALL.amount%TYPE;
9070     l_req_currency_amount     PO_REQUISITION_LINES_ALL.currency_amount%TYPE;
9071     l_req_rate                PO_REQUISITION_LINES_ALL.rate%TYPE; -- Bug 7661419
9072 
9073 BEGIN
9074 
9075 l_progress:='000'; PO_DEBUG.debug_begin(l_log_head);
9076 
9077     -- Initialize Variables ===================================================
9078 
9079     -- Get the precision/extended precision for the PO Currency.
9080     --
9081     -- Bug 4471683: added not null check for currency
9082     IF interface.h_currency_code IS NOT NULL THEN
9083       FND_CURRENCY.get_info ( currency_code => p_po_currency_code
9084                           , precision     => l_precision
9085                           , ext_precision => l_ext_precision
9086                           , min_acct_unit => l_min_acct_unit
9087                           );
9088     END IF;
9089 
9090     -- Convert ================================================================
9091 
9092 l_progress:='010'; PO_DEBUG.debug_var(l_log_head,l_progress,'p_order_type_lookup_code',p_order_type_lookup_code);
9093 
9094     -- For 'Amount' based lines, we need to convert the quantity since
9095     -- quantity acts like amount.
9096     --
9097     IF ( p_order_type_lookup_code = 'AMOUNT' ) THEN
9098 
9099        l_progress:='010';
9100        PO_DEBUG.debug_stmt(l_log_head,l_progress,'Performing currency conversion on quantity.');
9101 
9102        IF ( p_interface_source_code IN ('SOURCING','CONSUMPTION_ADVICE') ) THEN
9103              l_progress:='020';
9104              PO_DEBUG.debug_stmt(l_log_head,l_progress,'p_interface_source_code IN (SOURCING, CONSUMPTION ADVICE) - no currency conversion performed');
9105 
9106        ELSE
9107           -- Bug 7661419, No conversion for same currency.
9108           SELECT PRL.currency_code,
9109                  Nvl(PRL.rate,1)
9110           INTO   l_req_currency_code,
9111                  l_req_rate
9112           FROM   po_requisition_lines_all PRL
9113           WHERE  PRL.requisition_line_id = p_requisition_line_id;
9114 
9115           IF ( l_req_currency_code = p_po_currency_code ) THEN
9116            x_quantity := round ( x_quantity/l_req_rate, nvl(l_ext_precision, 15) );
9117           ELSE
9118            x_quantity := round ( x_quantity/p_rate, nvl(l_ext_precision, 15) );
9119           END IF;
9120        END IF;
9121 
9122     -- For all other line types, convert the Price/Amount.
9123     --
9124     ELSE -- ( p_order_type_lookup_code IN ('QUANTITY','FIXED PRICE','RATE') )
9125 
9126         -- If coming from Sourcing, however, do not perform any conversion as
9127         -- Sourcing already populates converted value in the interface table.
9128         --
9129         IF ( p_interface_source_code IN ('SOURCING','CONSUMPTION_ADVICE') ) THEN
9130 
9131            l_progress:='030';
9132            PO_DEBUG.debug_stmt(l_log_head,l_progress,'p_interface_source_code IN (SOURCING, CONSUMPTION ADVICE) - no currency conversion performed');
9133 
9134         ELSE -- ( p_interface_source_code NOT IN ('SOURCING','CONSUMPTION_ADVICE') )
9135 
9136             -- Retrieve information from the backing Requisition Line.
9137             -- Bug 3794198: Join to financials_system_params_all and gl_sets_of_books to
9138             -- retrieve the value of l_req_ou_currency_code, the functional currency of ROU
9139             SELECT PRL.currency_code
9140             ,      GSB.currency_code
9141             ,      PRL.unit_price
9142             ,      nvl(PRL.currency_unit_price, PRL.unit_price)
9143             ,      PRL.amount
9144             ,      nvl(PRL.currency_amount, PRL.amount)
9145             INTO   l_req_currency_code
9146             ,      l_req_ou_currency_code
9147             ,      l_req_unit_price
9148             ,      l_req_currency_unit_price
9149             ,      l_req_amount
9150             ,      l_req_currency_amount
9151             FROM   po_requisition_lines_all PRL,
9152                    financials_system_params_all FSP,
9153                    gl_sets_of_books GSB
9154             WHERE  PRL.requisition_line_id = p_requisition_line_id
9155             AND    nvl(PRL.org_id, -99) = nvl(FSP.org_id, -99)
9156             AND    FSP.set_of_books_id = GSB.set_of_books_id;
9157 
9158             -- If the Req and PO Currency are the same, then simply take the
9159             -- currency_<unit_price/amount> from the Req to avoid having to
9160             -- perform another conversion.
9161             --
9162             -- Bug 3794198: If the ROU currency and PO Currency are the same, then
9163             -- simply take the unit_price/amount from the Req to avoid conversion
9164             --
9165             -- If the Req and PO Currency are different, then convert the
9166             -- unit_price/amount to the PO Currency using the specified rate.
9167             --
9168             IF ( l_req_currency_code = p_po_currency_code ) THEN
9169 
9170                l_progress:='050';
9171                PO_DEBUG.debug_stmt(l_log_head,l_progress,'Req and PO Currency equivalent (' || p_po_currency_code || ') - taking currency_unit_price/amount directly from the Req Line.');
9172 
9173                 x_unit_price := l_req_currency_unit_price;
9174                 x_amount     := l_req_currency_amount;
9175                 -- bug 12719420
9176                 x_base_unit_price := l_req_currency_unit_price;
9177 
9178             -- Bug 3794198 Start
9179             ELSIF (l_req_ou_currency_code = p_po_currency_code) THEN
9180                l_progress := '060';
9181                PO_DEBUG.debug_stmt(l_log_head,l_progress,'ROU Currency and PO Currency equivalent (' || p_po_currency_code || ') - taking unit_price/amount directory from the Req line');
9182                x_unit_price := l_req_unit_price;
9183                x_amount := l_req_amount;
9184                -- Bug 3794198 End
9185                -- Bug 3472140: Added NVL() around l_ext_precision
9186                x_base_unit_price := round(x_base_unit_price/p_rate, NVL(l_ext_precision, 15)); --bug 3401653
9187 
9188             ELSE
9189 
9190                l_progress:='070';
9191                PO_DEBUG.debug_stmt(l_log_head,l_progress,'Req (' || l_req_currency_code || ')/ ROU (' || l_req_ou_currency_code || ') and PO (' || p_po_currency_code || ') Currency different - performing currency conversion and rounding.');
9192 
9193                 -- Bug 3472140: Added NVL() around l_ext_precision
9194                 x_unit_price := round(l_req_unit_price/p_rate, NVL(l_ext_precision, 15));
9195                 x_amount     := round(l_req_amount/p_rate, l_precision);
9196                 -- Bug 3472140: Added NVL() around l_ext_precision
9197                 x_base_unit_price := round(x_base_unit_price/p_rate, NVL(l_ext_precision, 15)); --bug 3401653
9198 
9199             END IF; -- currency_code
9200             -- Bug 3472140: Added NVL() around l_ext_precision
9201             --x_base_unit_price := round(x_base_unit_price/p_rate, NVL(l_ext_precision, 15)); --bug 3401653
9202 
9203         END IF; -- p_interface_source_code
9204 
9205     END IF; -- p_order_type_lookup_code
9206 
9207 l_progress:='090'; PO_DEBUG.debug_end(l_log_head);
9208 
9209 EXCEPTION
9210 
9211     WHEN OTHERS THEN
9212         PO_DEBUG.debug_exc ( p_log_head => l_log_head
9213                            , p_progress => l_progress);
9214         RAISE;
9215 
9216 END do_currency_conversion;
9217 
9218 
9219 /* ============================================================================
9220      NAME: SETUP_INTERFACE_TABLES
9221      DESC: Setup interface tables
9222      ARGS: x_interface_header_id IN number
9223      ALGR:
9224 
9225    ==========================================================================*/
9226 -- <Complex Work R12>: Add new parameter, p_is_complex_work_po
9227 PROCEDURE setup_interface_tables(
9228   x_interface_header_id  IN             NUMBER
9229 , x_document_id          IN OUT NOCOPY  NUMBER
9230 , p_is_complex_work_po   IN             BOOLEAN
9231 )
9232 IS
9233 
9234 x_po_header_id number := null;
9235 x_document_num po_headers.segment1%type:=null;
9236 x_min_interface_line_id number:= null;
9237 x_order_type_lookup_code varchar2(25) := null;
9238 x_quotation_class_code varchar2(25) := null;
9239 x_count_dist number;
9240 x_item_id number := null;
9241 x_vendor_id number := null;
9242 x_vendor_site_id number := null;
9243 x_rowid varchar2(25) := null;
9244 x_organization_id number := null;
9245 x_asl_id number := null;
9246 x_vendor_product_num varchar2(240) := null;
9247 x_purchasing_uom varchar2(240) := null;
9248 x_pay_on_code varchar2(25) := null;
9249 x_uom_convert          varchar2(2) := fnd_profile.value('PO_REQ_BPA_UOM_CONVERT');
9250 x_old_document_num po_headers.segment1%type:=null; -- Bug 700513, lpo, 07/15/98
9251 
9252 x_employee_id       number;
9253 x_employee_name     varchar2(240);
9254 x_requestor_location_id number;
9255 x_location_code     varchar2(25);
9256 x_employee_is_buyer boolean;
9257 x_is_emp            boolean;
9258 l_shipping_control  PO_RELEASES_ALL.shipping_control%TYPE;    -- <INBOUND LOGISTICS FPJ>
9259 
9260 Cursor C is select pli.rowid,
9261        pli.item_id,
9262        phi.vendor_id,
9263        phi.vendor_site_id,
9264        pdi.destination_organization_id
9265       from   po_lines_interface pli,
9266        po_headers_interface phi,
9267        po_distributions_interface pdi
9268       where  phi.interface_header_id = x_interface_header_id
9269       and    phi.interface_header_id = pli.interface_header_id
9270       and    pdi.interface_distribution_id =
9271         (SELECT min(pdi2.interface_distribution_id)
9272          FROM   po_distributions_interface pdi2
9273                WHERE  pdi2.interface_line_id = pli.interface_line_id)
9274       and    pli.item_id is not null
9275       and    phi.vendor_id is not null
9276       and    pli.vendor_product_num is null;
9277 --default distributions for all negotiation lines which are not backed by
9278 --requisition lines.
9279 Cursor C_default_distribution is
9280        SELECT pli.interface_header_id,
9281               pli.interface_line_id,
9282               pli.item_id,
9283               pli.line_type_id,
9284               pli.quantity,
9285               pli.amount,                                     -- <SERVICES FPJ>
9286               pli.category_id,
9287               pli.ship_to_location_id,
9288               pli.ship_to_organization_id,
9289               phi.vendor_id,
9290               phi.vendor_site_id,
9291               phi.agent_id,
9292               phi.rate,
9293               phi.rate_date,
9294               phi.document_subtype,
9295               pli.unit_price --<BUG 3407630>
9296          FROM po_lines_interface pli,
9297               po_headers_interface phi,
9298         po_line_types plt
9299         WHERE phi.interface_header_id = x_interface_header_id
9300           AND phi.interface_header_id = pli.interface_header_id
9301     AND pli.requisition_line_id is null
9302     AND plt.line_type_id = pli.line_type_id;
9303 
9304 l_api_name CONSTANT VARCHAR2(30) := 'setup_interface_tables';
9305 l_progress VARCHAR2(3) := '000';                --< Bug 3210331 >
9306 
9307 -- bug# 3345108
9308 -- secondary qty and secondary uom not getting populated for requisition lines
9309 -- when requisition is created using IP.
9310 -- default secondary qty and uom if
9311 -- opm is installed.
9312 -- destination org. is process and item is process and item is dual uom control.
9313 
9314 -- bug# 3386353
9315 -- Sourcing when doing overaward creates additional PO line with the extra qty.
9316 -- If the line is OPM item with dual uom control then the shipment corresponding
9317 -- to the extra PO line created by Sourcing does not have secondary uom and
9318 -- secondary quantity with ship to organization as process org.
9319 -- default secondary UOM and secondary quantity in such a case (non req backed lines)
9320 -- the requisition line id would be null in po_lines_interface .
9321 -- need to handle that situation in the default_opm_attributes cursor.
9322 -- in case of non req back lines from sourcing , ship_to_organization_id is NULL.
9323 -- so get it from distribution interface table.
9324 
9325 -- <Complex Work R12 Start>
9326 l_ship_to_org_id  HR_LOCATIONS_ALL.inventory_organization_id%TYPE;
9327 -- <Complex Work R12 End>
9328 
9329 BEGIN
9330     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9331         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
9332     END IF;
9333 
9334     UPDATE po_headers_interface
9335        SET process_code = 'IN PROCESS'
9336      WHERE interface_header_id = x_interface_header_id;
9337 
9338     l_progress := '010';
9339 
9340     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9341         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9342                             p_token    => l_progress,
9343                             p_message  => 'Setup interface:   before select action type');
9344     END IF;
9345 
9346     l_progress := '020';
9347     -- Bug 700513, lpo, 07/15/98
9348     -- Get the document_num as well; needed for later on.
9349 
9350     SELECT min(action),
9351            min(group_code),
9352            min(document_num)
9353       INTO g_mode,
9354            g_group_code,
9355            x_old_document_num
9356       FROM po_headers_interface
9357      WHERE interface_header_id = x_interface_header_id;
9358 
9359     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9360         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9361                             p_token    => l_progress,
9362                             p_message  => 'Setup interface: mode is '||g_mode);
9363     END IF;
9364 
9365     /* Adding a requisition Line to a PO,Release,RFQ */
9366     IF(g_mode = 'ADD') THEN
9367 
9368        /*
9369        ** Find the po_header_id that matches the segment1 value that
9370        ** was loaded into the interface table.
9371        ** document_subtype in in interface table for an RFQ with be RFQ
9372        */
9373 
9374        IF (g_document_type = 'RFQ') THEN
9375          l_progress:='030';
9376          UPDATE po_headers_interface phi
9377             SET po_header_id =
9378               (SELECT ph.po_header_id
9379                  FROM po_headers_all ph  --<Shared Proc FPJ>
9380                 WHERE 'RFQ' = ph.type_lookup_code
9381                   AND phi.document_num = ph.segment1
9382                   AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99))  --<Shared Proc FPJ>
9383              WHERE interface_header_id = x_interface_header_id;
9384 
9385        ELSE
9386          l_progress:='040';
9387          UPDATE po_headers_interface phi
9388             SET po_header_id =
9389               (SELECT ph.po_header_id
9390                  FROM po_headers_all ph  --<Shared Proc FPJ>
9391                 WHERE decode(phi.document_subtype,
9392                              'RELEASE','BLANKET',
9393                              phi.document_subtype) = ph.type_lookup_code
9394                   AND phi.document_num = ph.segment1
9395                   AND NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99))  --<Shared Proc FPJ>
9396           WHERE interface_header_id = x_interface_header_id;
9397 
9398             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9399                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9400                                     p_token    => l_progress,
9401                                     p_message  => 'After update of headers interface');
9402             END IF;
9403 
9404        END IF;
9405 
9406        l_progress:='050';
9407 
9408        /*
9409        ** The values that we are updating in the interface table
9410        ** we need for defaulting to records at the lower levels.
9411        */
9412 
9413        /* Bug 482648 add currecny_code */
9414 
9415        /* Also get the pay_on_code from the document */
9416 
9417        UPDATE po_headers_interface phi
9418        SET (
9419                rate,
9420                rate_type_code,
9421                rate_date,
9422                currency_code) =
9423                  (SELECT
9424                          rate,
9425                          rate_type,
9426                          rate_date,
9427                          currency_code
9428                     FROM po_headers_all ph  --<Shared Proc FPJ>
9429                    WHERE ph.po_header_id = phi.po_header_id)
9430        WHERE interface_header_id = x_interface_header_id;
9431 
9432        IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9433            PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9434                                p_token    => l_progress,
9435                                p_message  => 'After update of headers interfacei rate and etc.');
9436        END IF;
9437 
9438     /* Adding Req Line to New PO/RFQ */
9439     ELSIF(g_mode='NEW') THEN
9440 
9441       IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED'
9442          or g_document_type = 'RFQ'
9443          --<SOURCING TO PO FPH>
9444    or (g_document_subtype='BLANKET' and g_interface_source_code='SOURCING')) THEN
9445          l_progress:='060';
9446 
9447         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9448             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9449                                 p_token    => l_progress,
9450                                 p_message  => 'In std/planned/rfq');
9451         END IF;
9452 
9453          SELECT po_headers_s.nextval
9454            INTO x_po_header_id
9455            FROM sys.dual;
9456 
9457 
9458          /*
9459    ** Assign the document id to get passed back to the calling
9460    ** module.
9461    */
9462          x_document_id := x_po_header_id;
9463 
9464          l_progress:='070';
9465         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9466             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9467                                 p_token    => l_progress,
9468                                 p_message  => 'After select Doc is '||x_po_header_id);
9469         END IF;
9470 
9471    /* If we are using automatic numbering, get segment1
9472    ** from the po_unique_identifier_control table.
9473    ** If we are using manual numbering, segment1
9474    ** should already be loaded into the po_headers_interface table.
9475    ** The checks to verify that a manual po number is unique
9476    ** is done on the client side.
9477    */
9478          /* ecso 4/23/98 emergency requisition enhancement
9479          ** For emergency requisitions, there is a reserved po num
9480          ** even though the document has not been created.
9481          ** Add the case where the document is NEW
9482          ** and there exists a document_num on po_headers_interface
9483          */
9484          --<SOURCING TO PO FPH>
9485    --modified the if condition to include PA
9486    IF (params.po_num_code='AUTOMATIC') AND
9487       (g_document_type in ('PO','PA')) THEN
9488 
9489             -- Bug 700513, lpo, 07/15/98
9490             -- Should check for x_old_document_num instead of
9491             -- interface.document_num which is not defined at this point.
9492 
9493             IF x_old_document_num IS NULL THEN
9494                x_document_num := '-'||x_po_header_id;  --Bug 1093645
9495 
9496 /*Bug 1093645
9497   The following is commented as part of bug fix 958404.
9498   Prior to the fix we were locking the po_unique_identifier_control
9499   table in the beginning of the autocreate process which led to a
9500   deadlock situation.
9501   Fix has been made to assign a dummy (negative of po_header_id-The same
9502   logic followed in the enter po form) value now and then at the
9503   the end of the autocreate process lock the po_unique_identifier control
9504   table to fetch the next document number and assign it appropriately
9505   to avoid the deadlock.
9506 */
9507 
9508              END IF;
9509 
9510    ELSIF (params.user_defined_rfq_num_code='AUTOMATIC') AND
9511       (g_document_type = 'RFQ') THEN
9512 
9513              x_document_num := '-'||x_po_header_id;  --Bug 1093645
9514 
9515 /*Bug 1093645
9516   The following is commented as part of bug fix 958404.
9517   Prior to the fix we were locking the po_unique_identifier_control
9518   table in the beginning of the autocreate process which led to a
9519   deadlock situation.
9520   Fix has been made to assign a dummy (negative of po_header_id-The same
9521   logic followed in the enter po form) value now and then at the
9522   the end of the autocreate process lock the po_unique_identifier control
9523   table to fetch the next document number and assign it appropriately
9524   to avoid the deadlock.
9525 */
9526 
9527    ELSE
9528               x_document_num := interface.document_num;
9529 
9530          END IF;
9531 
9532       ELSIF(g_document_subtype='RELEASE')THEN
9533 
9534           l_progress := '080';
9535           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9536               PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9537                                   p_token    => l_progress,
9538                                   p_message  => 'Setup: In release subtype');
9539           END IF;
9540 
9541   /* Bug 565530 ecso 10/23/97
9542   ** There can be multiple release records
9543   ** in the interface table.
9544   ** Add restriction by interface_header_id
9545   */
9546 
9547           SELECT ph.po_header_id,
9548                  ph.pay_on_code,
9549                  ph.shipping_control    -- <INBOUND LOGISTICS FPJ>
9550             INTO x_po_header_id,
9551                  x_pay_on_code,
9552                  l_shipping_control    -- <INBOUND LOGISTICS FPJ>
9553             FROM po_headers_all ph,  --<Shared Proc FPJ>
9554                  po_headers_interface phi
9555            WHERE phi.interface_header_id = x_interface_header_id
9556        AND ph.segment1 = phi.document_num
9557              AND ph.type_lookup_code='BLANKET'
9558              AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
9559 
9560         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9561             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9562                                 p_token    => l_progress,
9563                                 p_message  => 'Setup: Header id of Blanket:  '||x_po_header_id);
9564         END IF;
9565 
9566       END IF;/* of standard/planned/release */
9567 
9568       l_progress:='090';
9569 
9570        SELECT min(interface_line_id)
9571         INTO x_min_interface_line_id
9572         FROM po_lines_interface pli,
9573              po_headers_interface phi
9574        WHERE phi.interface_header_id=pli.interface_header_id
9575          AND phi.interface_header_id = x_interface_header_id;
9576 
9577       l_progress:='100';
9578       --<SOURCING TO PO FPH>
9579       --modify the following update to default the values for the blanket also.
9580       --track 'PA' for the changes. Also please note that we have added deocode
9581       --for all the terms and conditions.Existing autocreate would not values
9582       --for different terms n condition columns and shipto billto columns in the
9583       --interface tables. But po_headers_interface table would contain values
9584       --for these columns when called from sourcing. So we are not defaulting
9585       --these values from params here but would do this in create_po procedure
9586       --in the order of interface,vendor,params.
9587       /* Bug 2816396
9588          Use the interface table value for pay_on_code when updating the table
9589       */
9590       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9591           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9592                               p_token    => l_progress,
9593                               p_message  => 'Sourcing to FPH-6 starts');
9594       END IF;
9595 
9596       UPDATE po_headers_interface phi
9597               SET (po_header_id,
9598                    last_update_date,
9599                    last_updated_by,
9600                    document_num,
9601              created_by,
9602                    last_update_login,
9603                    agent_id,
9604                    creation_date,
9605                    revision_num,
9606                    print_count,
9607                    closed_code,
9608                    frozen_flag,
9609                    vendor_id,
9610                    vendor_site_id,
9611                    ship_to_location_id,
9612                    bill_to_location_id,
9613                    terms_id,
9614                    freight_carrier,
9615                    fob,
9616                    pay_on_code,
9617                    freight_terms,
9618              confirming_order_flag,
9619                    currency_code,
9620              rate_type_code,
9621                    rate_date,
9622                    rate,
9623                    acceptance_required_flag,
9624                    firm_flag,
9625                    min_release_amount,
9626        document_subtype,
9627                    shipping_control    -- <INBOUND LOGISTICS FPJ>
9628                    ) =
9629             (SELECT x_po_header_id,
9630                     nvl(phi.last_update_date,sysdate),
9631                     nvl(phi.last_updated_by,who.user_id),
9632                     nvl(phi.document_num,x_document_num),
9633                     nvl(phi.created_by,who.user_id),
9634                     nvl(phi.last_update_login,who.login_id),
9635                     phi.agent_id ,
9636                     nvl(phi.creation_date,sysdate),
9637                     decode(g_document_type, 'PO', nvl(phi.revision_num,0),
9638                      'PA', nvl(phi.revision_num,0), phi.revision_num),
9639                     decode(g_document_type, 'PO', nvl(phi.print_count,0),
9640                     'PA', nvl(phi.print_count,0), phi.print_count),
9641                     decode(g_document_type, 'PO', nvl(phi.closed_code,'OPEN'),
9642                     'PA', nvl(phi.closed_code,'OPEN'), phi.closed_code),
9643                     decode(g_document_type, 'PO', nvl(phi.frozen_flag,'N'),
9644                     'PA', nvl(phi.frozen_flag,'N'), phi.frozen_flag),
9645                     phi.vendor_id,
9646                     phi.vendor_site_id,
9647                     decode(g_interface_source_code,'SOURCING',
9648          phi.ship_to_location_id,
9649          nvl(phi.ship_to_location_id,
9650         params.ship_to_location_id)),
9651                     decode(g_interface_source_code,'SOURCING',
9652          phi.bill_to_location_id,
9653                          nvl(phi.bill_To_Location_Id,
9654         params.bill_to_location_id)),
9655                     decode(g_interface_source_code,'SOURCING',phi.terms_id,
9656                            nvl(phi.terms_id,params.terms_id)),
9657                     decode(g_interface_source_code,'SOURCING',
9658                phi.freight_carrier,nvl(phi.freight_carrier,
9659               params.ship_via_lookup_code)),
9660                     decode(g_interface_source_code,'SOURCING',phi.fob,
9661          nvl(phi.fob,params.fob_lookup_code)),
9662                     decode(g_interface_source_code,'CONSUMPTION_ADVICE',phi.pay_on_code,
9663                            x_pay_on_code),
9664                     decode(g_interface_source_code,'SOURCING',phi.freight_terms,
9665                        nvl(phi.freight_terms,
9666         params.freight_terms_lookup_code)),
9667                     decode(g_document_type, 'PO',
9668       nvl(phi.confirming_order_flag,'N'),
9669       'PA',nvl(phi.confirming_order_flag,'N'),
9670       phi.confirming_order_flag),
9671                     phi.currency_code,
9672                     phi.rate_type_code,
9673                     --<SOURCING TO PO FPH>bug# 2430982
9674                     --phi.rate_date,
9675                     nvl(phi.rate_date,decode(g_interface_source_code,'SOURCING',decode(phi.rate_type_code,'User',sysdate),phi.rate_date)),
9676         --
9677                     phi.rate,
9678 	-- bug 8802204: Checking the value of the acceptance_required_flag from po_headers_interface
9679                     decode(g_document_type, 'PO',
9680 			nvl(phi.acceptance_required_flag,nvl(params.acceptance_required_flag,'N')),        /* Bug 7518967 : Default Acceptance Required Check ER: Geting default acceptance_required_flag */
9681 			'PA',nvl(phi.acceptance_required_flag,nvl(params.acceptance_required_flag,'N')),
9682 			params.acceptance_required_flag),
9683                     decode(g_document_type, 'PO',
9684       nvl(phi.firm_flag,'N'),
9685       'PA',nvl(phi.firm_flag,'N'),
9686       phi.firm_flag),
9687                     decode(g_document_type, 'PO',
9688       nvl(phi.min_release_amount,params.min_rel_amount),
9689       'PA',nvl(phi.min_release_amount,params.min_rel_amount),
9690       null),
9691         phi.document_subtype,
9692                     l_shipping_control    -- <INBOUND LOGISTICS FPJ>
9693                FROM po_headers_interface phi2,
9694                     po_lines_interface pli
9695               WHERE phi2.interface_header_id = phi.interface_header_id
9696                 AND pli.interface_header_id=phi2.interface_header_id
9697                 AND pli.interface_line_id = x_min_interface_line_id)
9698          WHERE interface_header_id = x_interface_header_id;
9699 
9700          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9701              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9702                                  p_token    => l_progress,
9703                                  p_message  => 'Sourcing to FPH-6 ends');
9704          END IF;
9705 
9706     END IF;/* of new/add */
9707 
9708     l_progress:='110';
9709 
9710     IF (g_document_subtype = 'RELEASE') THEN
9711 
9712        select po_header_id
9713        into   x_po_header_id
9714        from   po_headers_interface
9715        where  interface_header_id = x_interface_header_id;
9716 
9717         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9718             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9719                                 p_token    => l_progress,
9720                                 p_message  => 'Setup interface:Before release update '||x_po_header_id);
9721         END IF;
9722 
9723        -- Bug 623679, lpo, 02/27/98
9724        -- Added a filter 'phi.interface_header_id = x_interface_header_id'
9725        -- for performance.
9726 /*  Bug no:714303.
9727     The subquery(select stmt) was returning multiple rows
9728     while trying to create release using the manual option
9729     if there are more than one line for the same item
9730     in the referenced blanket agreement.
9731 */
9732 /*Bug 971798
9733   If the blanket agrement has lines which has expired (new feauture in r11)
9734   ,then we should not be considering those lines while matching.
9735 */
9736 
9737     -- Added note_to_vendor - iali 08/26/99
9738 /*Bug 1391523 . Added market price to the update  statement */
9739 
9740    /* Enh : 1660036 - Check the uom convert profile value. If it is set to yes
9741       we do not check if the Req uom is same as BPA uom. We create the release
9742       with the quantity and uom converted to the BPA uom */
9743 
9744  /* CONSIGNED FPI : For consumption PO we do not update the interface table with
9745    requisition values */
9746  IF g_interface_source_code <> 'CONSUMPTION_ADVICE' THEN
9747 
9748      -- Bug 2707576 - In 115.142, removed the IF statement and ELSE clause
9749      -- for x_uom_convert, since UOM checking is now handled in
9750      -- source_blanket_line.
9751 
9752        l_progress:='120';
9753        UPDATE po_lines_interface pli2
9754        SET (
9755             line_num,
9756             item_id,
9757             category_id,
9758             item_description,
9759             unit_of_measure,
9760             list_price_per_unit,
9761       market_price,
9762             base_unit_price,  -- <FPJ Advanced Price>
9763             unit_price,
9764             quantity,
9765             amount,                                           -- <SERVICES FPJ>
9766             taxable_flag,
9767             type_1099,
9768             negotiated_by_preparer_flag,
9769             closed_code,
9770             item_revision,
9771             un_number_id,
9772             hazard_class_id,
9773             -- contract_num,   -- <GC FPJ>
9774             line_type_id,
9775             vendor_product_num,
9776             qty_rcv_tolerance,
9777             over_tolerance_error_flag,
9778             firm_flag,
9779             min_release_amount,
9780             price_type,
9781             transaction_reason_code,
9782             line_location_id,
9783             need_by_date,
9784       --togeorge 09/27/2000
9785       --added note to receiver
9786       note_to_receiver,
9787             from_header_id,
9788             from_line_id,
9789       receipt_required_flag,
9790 --DWR4{
9791             tax_status_indicator,
9792       note_to_vendor,
9793 --DWR4}
9794             --togeorge 09/27/2000
9795       --added oke columns
9796       oke_contract_header_id,
9797       oke_contract_version_id,
9798 -- start of bug 1548597
9799             secondary_unit_of_measure,
9800             secondary_quantity,
9801             preferred_grade,
9802 -- end of bug 1548597
9803             drop_ship_flag,   --  <DropShip FPJ>
9804             vmi_flag  -- VMI FPH
9805       )=
9806        (SELECT
9807             nvl(pli.line_num, pol.line_num),
9808             nvl(pli.item_id,prl.item_id),
9809             nvl(pli.category_id,prl.category_id),
9810             nvl(pli.item_description,prl.item_description),
9811             nvl(pli.unit_of_measure,prl.unit_meas_lookup_code),
9812             pli.list_price_per_unit,
9813       pli.market_price,
9814             nvl(pli.base_unit_price,prl.base_unit_price),     -- <FPJ Advanced Price>
9815             nvl(pli.unit_price,prl.unit_price),
9816             nvl(pli.quantity,prl.quantity),
9817             nvl(pli.amount, prl.amount),                      -- <SERVICES FPJ>
9818             pli.taxable_flag,
9819             pli.type_1099,
9820             nvl(pli.negotiated_by_preparer_flag,'N'),
9821             nvl(pli.closed_code,'OPEN'),
9822             nvl(pli.item_revision,prl.item_revision),
9823             nvl(pli.un_number_id,prl.un_number_id),
9824             nvl(pli.hazard_class_id,prl.hazard_class_id),
9825             -- pli.contract_num,         -- <GC FPJ>
9826             nvl(pli.line_type_id,prl.line_type_id),
9827             nvl(pli.vendor_product_num,prl.suggested_vendor_product_code),
9828             pli.qty_rcv_tolerance,
9829             pli.over_tolerance_error_flag,
9830             nvl(pli.firm_flag,'N'),
9831             nvl(pli.min_release_amount,params.min_rel_amount),
9832             nvl(pli.price_type,params.price_type_lookup_code),
9833             nvl(pli.transaction_reason_code,prl.transaction_reason_code),
9834             pli.line_location_id,
9835             nvl(pli.need_by_date,prl.need_by_date),
9836       --togeorge 09/27/2000
9837       --added note to receiver
9838       nvl(pli.note_to_receiver,prl.note_to_receiver),
9839             pli.from_header_id,
9840             pli.from_line_id,
9841       nvl(pli.receipt_required_flag,plt.receiving_flag),
9842 --DWR4{
9843             prl.tax_status_indicator,
9844       nvl(pli.note_to_vendor, prl.note_to_vendor),
9845 --DWR4}
9846             --togeorge 09/27/2000
9847       --added oke columns
9848       nvl(pli.oke_contract_header_id,prl.oke_contract_header_id),
9849       nvl(pli.oke_contract_version_id,prl.oke_contract_version_id),
9850 -- start of 1548597
9851             nvl(pli.secondary_unit_of_measure,prl.secondary_unit_of_measure),
9852             nvl(pli.secondary_quantity,prl.secondary_quantity),
9853             nvl(pli.preferred_grade,prl.preferred_grade),
9854 -- end of 1548597
9855             prl.drop_ship_flag,   --  <DropShip FPJ>
9856             prl.vmi_flag  -- VMI FPH
9857        FROM po_lines_interface pli,
9858             po_headers_interface phi,
9859             po_requisition_lines_all prl,  --<Shared Proc FPJ>
9860             po_line_types plt,
9861             po_lines_all pol  --<Shared Proc FPJ>
9862       WHERE pli.interface_line_id = pli2.interface_line_id
9863         AND pli.interface_header_id = phi.interface_header_id
9864         AND phi.interface_header_id = x_interface_header_id
9865         AND pli.requisition_line_id = prl.requisition_line_id(+)
9866         AND plt.line_type_id = nvl(prl.line_type_id,pli.line_type_id)
9867   AND pol.po_header_id = x_po_header_id
9868 -- 2082757 : new
9869         AND pol.line_num = po_interface_s.source_blanket_line(
9870                                 x_po_header_id,
9871                                 prl.requisition_line_id,
9872                                 pli.line_num, -- Bug 2707576:
9873                                 NVL(x_uom_convert,'N'),
9874                                 g_purchasing_ou_id  --<Shared Proc FPJ>
9875                            )
9876        )
9877 
9878 /* 2082757: Following logic is now coded in new function source_blanket_line
9879 2082757 */
9880        WHERE pli2.interface_header_id = x_interface_header_id;
9881 
9882  /* CONSIGNED FPI Start */
9883  ELSE  -- CONSIGNED FPI
9884      l_progress:='130';
9885      -- bug 6636486 modified the below update sql to increase the performance.
9886      UPDATE po_lines_interface pli
9887       SET pli.po_header_id = x_po_header_id,
9888             pli.negotiated_by_preparer_flag = nvl(pli.negotiated_by_preparer_flag,'N'),
9889             pli.firm_flag = nvl(pli.firm_flag, 'N')
9890       WHERE pli.interface_header_id = x_interface_header_id;
9891  /*        SET (
9892             po_header_id,
9893             negotiated_by_preparer_flag,
9894             firm_flag
9895       )= */
9896        /*(SELECT
9897             x_po_header_id,
9898             nvl(pli.negotiated_by_preparer_flag,'N'),
9899             nvl(pli.firm_flag,'N')
9900        FROM po_lines_interface pli,
9901             po_headers_interface phi
9902       WHERE pli.interface_line_id = pli2.interface_line_id
9903         AND pli.interface_header_id = phi.interface_header_id
9904         AND phi.interface_header_id = x_interface_header_id);*/
9905 
9906  END IF;
9907  /* CONSIGNED FPI End */
9908 
9909        -- End of fix. Bug 623679, lpo, 02/27/98
9910 
9911         l_progress:='140';
9912         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9913             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9914                                 p_token    => l_progress,
9915                                 p_message  => 'Setup interface: After release update');
9916         END IF;
9917 
9918     ELSE  /* For PO/RFQ/PA */
9919     /*
9920     ** Note:  We do not multiple unit_price or quantity * rate
9921     ** in this statement. This logic is in the create_line stmt.
9922     */
9923     /* Bug 567402 ecso 11/15/97
9924     ** Get the receipt_required_flag from po_line_type table
9925     */
9926 
9927     -- Bug 623679, lpo, 02/27/98
9928     -- Added a filter 'phi.interface_header_id = x_interface_header_id'
9929     -- for performance.
9930 
9931     -- Bug 694504. frkhan 07/07/98. Removed decode for vendor_product_num so
9932     -- it is updated for RFQs also.
9933 
9934     -- Added note_to_vendor - iali 08/26/99
9935 /*Bug 1391523 . Added market price to the update  statement */
9936 
9937     l_progress:='150';
9938     UPDATE po_lines_interface pli2
9939        SET (
9940             line_num,
9941             item_id,
9942             job_id,                                           -- <SERVICES FPJ>
9943             category_id,
9944             item_description,
9945             unit_of_measure,
9946             list_price_per_unit,
9947       market_price,
9948             base_unit_price,  -- <FPJ Advanced Price>
9949             unit_price,
9950             quantity,
9951             amount,                                           -- <SERVICES FPJ>
9952             taxable_flag,
9953             type_1099,
9954             negotiated_by_preparer_flag,
9955             closed_code,
9956             item_revision,
9957             un_number_id,
9958             hazard_class_id,
9959             -- contract_num,       -- <GC FPJ>
9960             line_type_id,
9961             vendor_product_num,
9962             qty_rcv_tolerance,
9963             over_tolerance_error_flag,
9964             firm_flag,
9965             min_release_amount,
9966             price_type,
9967             transaction_reason_code,
9968             line_location_id,
9969             need_by_date,
9970             ship_to_organization_id,
9971       note_to_receiver,
9972             from_header_id,
9973             from_line_id,
9974       receipt_required_flag,
9975             tax_status_indicator,
9976       note_to_vendor,
9977       oke_contract_header_id,
9978       oke_contract_version_id,
9979             secondary_unit_of_measure,
9980             secondary_quantity,
9981             preferred_grade,
9982             drop_ship_flag,   --  <DropShip FPJ>
9983             vmi_flag,      -- bug 2738820
9984             supplier_ref_number, --<CONFIG_ID FPJ>
9985             effective_date,                                   -- <SERVICES FPJ>
9986             expiration_date,                                  -- <SERVICES FPJ>
9987             contractor_first_name,                            -- <SERVICES FPJ>
9988             contractor_last_name                              -- <SERVICES FPJ>
9989             ,supplier_part_auxid                              --13876074
9990       )=
9991     (SELECT
9992             pli.line_num,
9993             nvl(pli.item_id,prl.item_id),
9994             nvl(pli.job_id, prl.job_id),                      -- <SERVICES FPJ>
9995             nvl(pli.category_id,prl.category_id),
9996             nvl(pli.item_description,prl.item_description),
9997             nvl(pli.unit_of_measure,prl.unit_meas_lookup_code),
9998             pli.list_price_per_unit,
9999       pli.market_price,
10000             nvl(pli.base_unit_price,prl.base_unit_price),     -- <FPJ Advanced Price>
10001             nvl(pli.unit_price,prl.unit_price),
10002             --<Bug 3306848 Its possible to have no backing req in which case
10003             --the quantity is taken from interface table.
10004             decode ( prl.order_type_lookup_code          -- <BUG 3275750, 3306848 START>
10005                    , 'FIXED PRICE' , NULL
10006                    , 'RATE'   ,      NULL
10007                    ,                 nvl(pli.quantity,prl.quantity)
10008                    ),                                    -- <BUG 3275750, 3306848 END>
10009             nvl(pli.amount, prl.amount),                      -- <SERVICES FPJ>
10010             pli.taxable_flag,
10011             pli.type_1099,
10012             nvl(pli.negotiated_by_preparer_flag,'N'),
10013             decode(g_document_type, 'PO',
10014     nvl(pli.closed_code,'OPEN'), null),
10015             nvl(pli.item_revision,prl.item_revision),
10016             nvl(pli.un_number_id,prl.un_number_id),
10017             nvl(pli.hazard_class_id,prl.hazard_class_id),
10018             -- pli.contract_num,       -- <GC FPJ>
10019             nvl(pli.line_type_id,prl.line_type_id),
10020             nvl(pli.vendor_product_num,prl.suggested_vendor_product_code),
10021             pli.qty_rcv_tolerance,
10022             pli.over_tolerance_error_flag,
10023             nvl(pli.firm_flag,'N'),
10024             --<SOURCING TO PO FPH>bug# 2438142 added min_release_amount for PA
10025             decode(g_document_type, 'PO',
10026     nvl(pli.min_release_amount,params.min_rel_amount),
10027             'PA',nvl(pli.min_release_amount,params.min_rel_amount),null),
10028             decode(g_document_type, 'PO',
10029             --Bug 14383317 start
10030             --nvl(pli.price_type,params.price_type_lookup_code),null),
10031 			nvl(pol.price_type_lookup_code,params.price_type_lookup_code),null),
10032 			--Bug 14383317 End
10033             nvl(pli.transaction_reason_code,prl.transaction_reason_code),
10034             pli.line_location_id,
10035             nvl(pli.need_by_date,prl.need_by_date),
10036             nvl(pli.ship_to_organization_id,prl.destination_organization_id),
10037       nvl(pli.note_to_receiver,prl.note_to_receiver),
10038             pli.from_header_id,
10039             pli.from_line_id,
10040       nvl(pli.receipt_required_flag,plt.receiving_flag),
10041             prl.tax_status_indicator,
10042       nvl(pli.note_to_vendor, prl.note_to_vendor),
10043             -- 2702892 Added the decode for consigned:
10044             decode(pli.consigned_flag,'Y',null,
10045         nvl(pli.oke_contract_header_id,prl.oke_contract_header_id)),
10046             decode(pli.consigned_flag,'Y',null,
10047         nvl(pli.oke_contract_version_id,prl.oke_contract_version_id)),
10048             nvl(pli.secondary_unit_of_measure,prl.secondary_unit_of_measure),
10049             nvl(pli.secondary_quantity,prl.secondary_quantity),
10050             nvl(pli.preferred_grade,prl.preferred_grade),
10051             prl.drop_ship_flag,   --  <DropShip FPJ>
10052             prl.vmi_flag,   -- bug 2738820
10053             prl.supplier_ref_number, --<CONFIG_ID FPJ>
10054             -- <SERVICES FPJ START>
10055             nvl(pli.effective_date, prl.assignment_start_date),
10056             nvl(pli.expiration_date, prl.assignment_end_date),
10057             nvl(pli.contractor_first_name, prl.candidate_first_name),
10058             nvl(pli.contractor_last_name, prl.candidate_last_name)
10059             -- <SERVICES FPJ END>
10060             ,pol.supplier_part_auxid       --13876074
10061        FROM po_lines_interface pli,
10062             po_headers_interface phi,
10063             po_requisition_lines_all prl,  --<Shared Proc FPJ>
10064             po_line_types plt
10065             ,po_lines_all pol              --13876074
10066       WHERE pli.interface_line_id = pli2.interface_line_id
10067         AND pli.interface_header_id = phi.interface_header_id
10068         AND phi.interface_header_id = x_interface_header_id
10069         AND pli.requisition_line_id = prl.requisition_line_id(+)
10070         AND pli.from_line_id = pol.po_line_id(+)    --13876074
10071         AND plt.line_type_id = nvl(prl.line_type_id,pli.line_type_id))
10072       WHERE pli2.interface_header_id = x_interface_header_id;
10073 
10074       -- End of fix. Bug 623679, lpo, 02/27/98
10075 
10076     END IF;
10077 
10078     l_progress:='160';
10079 
10080     /* RFQs do not have distributions , but we still
10081   do the insert.  We get the deliver to information
10082   from the distribution record. */
10083 
10084 
10085     IF (g_document_type in ('RFQ', 'PO')) THEN
10086 
10087         l_progress:='170';
10088         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10089             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10090                                 p_token    => l_progress,
10091                                 p_message  => 'Before insert into Distribution interface');
10092         END IF;
10093 
10094        INSERT INTO po_distributions_interface
10095           (interface_header_id,
10096            interface_line_id,
10097            interface_distribution_id,
10098            distribution_num,
10099            charge_account_id,
10100            set_of_books_id,
10101            quantity_ordered,
10102            amount_ordered,                                    -- <SERVICES FPJ>
10103            rate,
10104            rate_date,
10105            req_distribution_id,
10106            deliver_to_location_id,
10107            deliver_to_person_id,
10108            encumbered_flag,
10109      gl_encumbered_date,
10110            gl_encumbered_period_name,
10111            destination_type_code,
10112            destination_organization_id,
10113            destination_subinventory,
10114            budget_account_id,
10115            accrual_account_id,
10116            variance_account_id,
10117 
10118            --< Shared Proc FPJ Start >
10119            dest_charge_account_id,
10120            dest_variance_account_id,
10121            --< Shared Proc FPJ End >
10122 
10123            wip_entity_id,
10124            wip_line_id,
10125            wip_repetitive_schedule_id,
10126            wip_operation_seq_num,
10127            wip_resource_seq_num,
10128            bom_resource_id,
10129            prevent_encumbrance_flag,
10130            project_id,
10131            task_id,
10132            end_item_unit_number,
10133            expenditure_type,
10134            project_accounting_context,
10135            destination_context,
10136            expenditure_organization_id,
10137            expenditure_item_date,
10138 --FRKHAN 12/8/98 copy recovery rate and tax amounts
10139           tax_recovery_override_flag, --<eTax Integration R12>
10140      recovery_rate,
10141      recoverable_tax,
10142      nonrecoverable_tax,
10143      -- OGM_0.0 change.
10144      award_id,
10145            --togeorge 09/27/2000
10146      --added oke columns
10147      oke_contract_line_id,
10148      oke_contract_deliverable_id
10149      )
10150        SELECT pli.interface_header_id,
10151            pli.interface_line_id,
10152            po_distributions_interface_s.nextval,
10153            prd.distribution_num,
10154            prd.code_combination_id,
10155            prd.set_of_books_id,
10156            prd.req_line_quantity,
10157            decode ( g_interface_source_code                    -- <BUG 3316071>
10158                   , 'SOURCING' , prd.req_line_amount * pli.amount/prl.amount
10159                   ,              prd.req_line_amount
10160                   ),
10161            phi.rate,
10162            phi.rate_date,
10163            prd.distribution_id,
10164            prl.deliver_to_location_id,
10165            prl.to_person_id,
10166            prd.encumbered_flag,
10167      prd.gl_encumbered_date,
10168            prd.gl_encumbered_period_name,
10169            prl.destination_type_code,
10170            prl.destination_organization_id,
10171            prl.destination_subinventory,
10172            prd.budget_account_id,
10173            prd.accrual_account_id,
10174            prd.variance_account_id,
10175 
10176            --< Shared Proc FPJ Start >
10177            -- For non SPS case (common case), set Destination Accounts to NULL
10178            NULL, -- dest_charge_account_id
10179            NULL, -- dest_variance_account_id
10180            --< Shared Proc FPJ End >
10181 
10182            prl.wip_entity_id,
10183            prl.wip_line_id,
10184            prl.wip_repetitive_schedule_id,
10185            prl.wip_operation_seq_num,
10186            prl.wip_resource_seq_num,
10187            prl.bom_resource_id,
10188            prd.prevent_encumbrance_flag,
10189            prd.project_id,
10190            prd.task_id,
10191            prd.end_item_unit_number,
10192            prd.expenditure_type,
10193            prd.project_accounting_context,
10194            prl.destination_context,
10195            prd.expenditure_organization_id,
10196            prd.expenditure_item_date,
10197      prd.tax_recovery_override_flag,     --<eTax Integration R12>
10198      prd.recovery_rate,
10199      prd.recoverable_tax,
10200      prd.nonrecoverable_tax,
10201      prd.award_id, -- OGM_0.0 change
10202            --togeorge 09/27/2000
10203      --added oke columns
10204            -- 2702892 Added the decode for consigned:
10205            decode(pli.consigned_flag,'Y',null,
10206        prd.oke_contract_line_id),
10207            decode(pli.consigned_flag,'Y',null,
10208        prd.oke_contract_deliverable_id)
10209          FROM po_requisition_lines_all prl,  --<Shared Proc FPJ>
10210            po_req_distributions_all prd,  --<Shared Proc FPJ>
10211            po_lines_interface pli,
10212            po_headers_interface phi
10213         WHERE prd.requisition_line_id = prl.requisition_line_id
10214           AND prl.requisition_line_id  = pli.requisition_line_id -- Bug:1563888
10215           AND pli.interface_header_id = phi.interface_header_id
10216           AND phi.interface_header_id = x_interface_header_id;
10217 
10218           SELECT count(*)
10219           INTO   x_count_dist
10220           FROM  po_distributions_interface
10221     WHERE interface_header_id = x_interface_header_id;
10222 
10223         l_progress:='180';
10224         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10225             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10226                                 p_token    => l_progress,
10227                                 p_message  => 'Count from dist iterface is '||x_count_dist);
10228         END IF;
10229 
10230      END IF;
10231 
10232           --<SOURCING TO PO FPH START>
10233         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10234             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10235                                 p_token    => l_progress,
10236                                 p_message  => 'Sourcing to FPH-7 starts');
10237         END IF;
10238     --default the distribution for non req backing negotiations.The above
10239     --insert only takes care of the interface lines which are backed by
10240     --requisitions.
10241     if g_interface_source_code='SOURCING' then
10242 
10243        IF (PO_LOG.d_stmt) THEN
10244          PO_LOG.stmt(g_log_head || l_api_name, 190, 'Defaulting dists interface for sourcing.');
10245        END IF;
10246 
10247           l_progress:='190';
10248           for i in c_default_distribution
10249         loop
10250 
10251          -- <Complex Work R12 Start>
10252          IF (PO_LOG.d_stmt) THEN
10253            PO_LOG.stmt(g_log_head || l_api_name, 190, 'i.interface_line_id', i.interface_line_id);
10254          END IF;
10255 
10256 
10257          IF (p_is_complex_work_po) THEN
10258 
10259            -- create complex work PO from sourcing
10260 
10261            IF (i.ship_to_organization_id IS NOT NULL) THEN
10262 
10263              l_ship_to_org_id := i.ship_to_organization_id;
10264 
10265            ELSE
10266 
10267              -- SQL WHAT: derive default ship_to_organization_id
10268              -- SQL WHY: the ship_to_organization is optional from sourcing
10269              BEGIN
10270                SELECT hrl.inventory_organization_id
10271                  INTO l_ship_to_org_id
10272                  FROM hr_locations_all hrl
10273                 WHERE hrl.location_id = i.ship_to_location_id
10274                   AND hrl.ship_to_site_flag = 'Y';
10275              EXCEPTION
10276                 WHEN no_data_found THEN
10277                   l_ship_to_org_id := NULL;
10278              END;
10279 
10280              l_ship_to_org_id := NVL(l_ship_to_org_id,
10281                                      params.inventory_organization_id);
10282 
10283            END IF;  -- IF i.ship_to_organization_id IS NOT NULL
10284 
10285            -- SQL WHAT: insert minimal data into po_distributions_interface
10286            -- SQL WHY: this is required because the global interface cursor
10287            -- joins to the distributions interface table and uses
10288            -- some of the following fields for defaulting purposes
10289 
10290            INSERT INTO po_distributions_interface(
10291              interface_header_id
10292            , interface_line_id
10293            , interface_distribution_id
10294            , destination_type_code
10295            , deliver_to_location_id
10296            , destination_organization_id
10297            ) VALUES (
10298              i.interface_header_id
10299            , i.interface_line_id
10300            , PO_DISTRIBUTIONS_INTERFACE_S.nextval
10301            , 'EXPENSE'
10302            , i.ship_to_location_id
10303            , l_ship_to_org_id
10304            );
10305 
10306            IF (PO_LOG.d_stmt) THEN
10307              PO_LOG.stmt(g_log_head || l_api_name, 190, 'Num rows inserted', SQL%ROWCOUNT);
10308            END IF;
10309 
10310          ELSE
10311 
10312            -- non-complex work po from sourcing
10313 
10314            po_negotiations_sv2.default_po_dist_interface(
10315               i.interface_header_id,
10316               i.interface_line_id,
10317               i.item_id,
10318               i.category_id,
10319               i.ship_to_organization_id,
10320               i.ship_to_location_id,
10321               null, --deliver_to_person_id
10322               params.sob_id,
10323               params.coa_id,
10324               i.line_type_id,
10325               i.quantity,
10326               i.amount,  -- <SERVICES FPJ>
10327               i.rate,
10328               i.rate_date,
10329               i.vendor_id,
10330               i.vendor_site_id,
10331               i.agent_id,
10332               nvl(params.po_encumbrance_flag, 'N'),
10333               NULL,
10334               i.document_subtype,
10335               null,
10336               null,
10337               null,
10338               null,
10339               null,
10340               null,
10341               null,
10342               null,
10343               null,
10344               null,
10345               null,
10346               null,
10347               null,
10348               null,
10349               null, --project_accounting_context
10350               g_purchasing_ou_id, --< Shared Proc FPJ >
10351               i.unit_price  --<BUG 3407630>
10352               );
10353          END IF;  -- IF p_is_complex_work_po
10354          -- <Complex Work R12 End>
10355 
10356         end loop;
10357           end if;
10358 
10359         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10360             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10361                                 p_token    => l_progress,
10362                                 p_message  => 'Sourcing to FPH-7 ends');
10363         END IF;
10364           --<SOURCING TO PO FPH END>
10365 
10366 
10367     /* If we do not have a supplier item number, get this
10368        information from the ASL */
10369 
10370     --<SOURCING TO PO FPH>
10371     --for blankets also
10372     IF (g_document_type in ('PO','PA')) THEN
10373 
10374     l_progress:='200';
10375   OPEN C;
10376   LOOP
10377 
10378       Fetch C into x_rowid,
10379          x_item_id,
10380          x_vendor_id,
10381          x_vendor_site_id,
10382          x_organization_id;
10383 --added by jbalakri for 1754916
10384             x_asl_id:=NULL;
10385             x_vendor_product_num:=NULL;
10386             x_purchasing_uom:=NULL;
10387 --end of add for 1754916.
10388 
10389         po_autosource_sv.get_asl_info(x_item_id,
10390      x_vendor_id,
10391      x_vendor_site_id,
10392      x_organization_id,
10393      x_asl_id,
10394      x_vendor_product_num,
10395      x_purchasing_uom);
10396 
10397       if (x_vendor_product_num is not null) then
10398           update po_lines_interface
10399           set    vendor_product_num = x_vendor_product_num
10400     where  rowid = x_rowid;
10401 
10402       end if;
10403 
10404       Exit when C%NOTFOUND;
10405 
10406 
10407   END LOOP;
10408   CLOSE C;
10409 
10410     END IF;
10411 
10412   l_progress:='210';
10413   --< Shared Proc FPJ Start >
10414   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10415       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10416                           p_token    => l_progress,
10417                           p_message  => 'Calling generate_shared_proc_accounts');
10418   END IF;
10419 
10420   -- <Complex Work R12 Start>: Shared proc. not supported with complex work
10421   IF (NOT p_is_complex_work_po) THEN
10422     generate_shared_proc_accounts(x_interface_header_id);
10423   END IF;
10424   -- <Complex Work R12 End>
10425   --< Shared Proc FPJ End >
10426 
10427   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10428       PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
10429   END IF;
10430 
10431 EXCEPTION
10432   WHEN OTHERS THEN
10433      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
10434          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
10435                             p_progress => l_progress);
10436      END IF;
10437      wrapup(x_interface_header_id);
10438      po_message_s.sql_error('SETUP INTERFACE TABLES',l_progress,sqlcode);
10439      raise;
10440 END SETUP_INTERFACE_TABLES;
10441 
10442 
10443 /* ============================================================================
10444      NAME: WRAPUP
10445      DESC: Wrapup
10446      ARGS: x_interface_header_id IN number
10447      ALGR:
10448    ==========================================================================*/
10449 PROCEDURE wrapup(x_interface_header_id IN number) IS
10450 BEGIN
10451     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10452         PO_DEBUG.debug_begin(p_log_head => g_log_head||'wrapup');
10453     END IF;
10454 
10455    DELETE po_distributions_interface
10456    WHERE interface_header_id = x_interface_header_id;
10457 
10458    -- <SERVICES FPJ START>
10459    DELETE po_price_diff_interface
10460    WHERE  interface_header_id = x_interface_header_id;
10461    -- <SERVICES FPJ END>
10462 
10463    -- <Complex Work R12 Start>
10464    DELETE po_line_locations_interface
10465    WHERE interface_header_id = x_interface_header_id;
10466    -- <Complex Work R12 End>
10467 
10468    DELETE po_lines_interface
10469    WHERE interface_header_id = x_interface_header_id;
10470 
10471 
10472    DELETE po_headers_interface
10473    WHERE interface_header_id = x_interface_header_id;
10474 
10475     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10476         PO_DEBUG.debug_end(p_log_head => g_log_head||'wrapup');
10477     END IF;
10478 END wrapup;
10479 
10480 /* ============================================================================
10481      NAME: GROUP_INTERFACE_LINES
10482      DESC: Group interface lines
10483      ARGS: x_interface_header_id IN number
10484      ALGR:
10485    ==========================================================================*/
10486 -- <Complex Work R12>: Added parameter p_is_complex_work_po
10487 
10488 PROCEDURE group_interface_lines(
10489   x_interface_header_id    IN number
10490 , p_is_complex_work_po     IN BOOLEAN
10491 , p_group_shipments        IN VARCHAR2 DEFAULT NULL   --<Bug 14608120 Autocreate GE ER>
10492 )
10493 IS
10494 x_line_num number;
10495 x_shipment_num number;
10496 x_document_num varchar2(30);
10497 x_release_num number;
10498 x_document_type_code varchar2(25);
10499 x_document_subtype varchar2(25);
10500 x_action varchar2(25);
10501 x_requisition_line_id number;
10502 x_interface_line_num number;
10503 x_item_id number;
10504 x_item_description varchar2(240);    -- bgu, Mar. 19, 1999
10505 x_line_type_id number;
10506 x_item_revision varchar2(3);
10507 x_unit_meas_lookup_code varchar2(25);
10508 x_transaction_reason_code varchar2(25);
10509 x_need_by_date date;
10510 --togeorge 09/27/2000
10511 --added note to receiver and oke variables.
10512 x_note_to_receiver po_requisition_lines_all.note_to_receiver%type;
10513 x_oke_contract_header_id number;
10514 x_oke_contract_version_id number;
10515 x_vendor_product_num varchar2(30);  --Bug# 1763933
10516 x_deliver_to_location_id number;
10517 x_destination_org_id number;
10518 x_ship_to_location_id number;
10519 x_po_line_num number;
10520 x_po_line_id number;
10521 x_po_shipment_num number;
10522 x_num_interface_lines number := 1; /* used for incrementing po line number */
10523 x_int_shipment_num number; /* maximum shipment num in interface table */
10524 x_int_line_num number; /* maximum line num in interface table */
10525 -- start of 1548597
10526 x_secondary_unit_of_measure  MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
10527 x_preferred_grade            MTL_GRADES.GRADE_CODE%TYPE; --<INVCONV R12> increased to 150
10528 -- end of 1548597
10529 /* Bug 1949160. x_count variable is used as counter to increment in a
10530     loop */
10531 x_count number := 0;
10532 --<SOURCING TO PO FPH START>
10533 x_bid_number number;
10534 x_bid_line_number number;
10535 x_row_id  varchar2(25) := null;
10536 --<SOURCING TO PO FPH END>
10537 
10538 x_vmi_flag       PO_LINES_INTERFACE.VMI_FLAG%TYPE;  /* VMI FPH */
10539 x_drop_ship_flag PO_LINES_INTERFACE.DROP_SHIP_FLAG%TYPE;  --<DropShip FPJ>
10540 
10541 x_source_doc_id         number;   -- FPI GA
10542 x_source_doc_line_id    number;   -- FPI GA
10543 
10544 x_consigned_flag        VARCHAR2(1) := 'N';  --CONSIGNED FPI
10545 x_create_new_line       VARCHAR2(1) := 'N';   --GA FPI
10546 l_supplier_ref_number   PO_LINES_INTERFACE.supplier_ref_number%TYPE; --<CONFIG_ID FPJ>
10547 
10548 l_contract_id PO_LINES_ALL.contract_id%TYPE;       -- <GC FPJ>
10549 
10550 /* Bug 3201308 start */
10551  l_needby_prf  varchar2(1);
10552  l_shipto_prf  varchar2(1);
10553 /* Bug 3201308 end */
10554 
10555 l_api_name CONSTANT VARCHAR2(30) := 'group_interface_lines';
10556 
10557 /*
10558 ** Order by interface_line_id.
10559 ** The front end will always load the lines in the correct order.
10560 ** The front end will load it either by (item_id, unit_price,
10561 ** need_by_date, requisition_line_id) or by the order in which
10562 ** the user selects.
10563 ** DEBUG.  For now from the front end the users will not be able to
10564 ** determine the order in which they want to lines to be placed.
10565 ** removed order by interface_line_id and replaced it with the
10566 ** above order by.
10567 */
10568 /** bgu, Mar. 19, 1999
10569  *  BUG 853749
10570  *  For one time item, item description will distinguish items.
10571  */
10572 
10573 /* Bug 1949160. Created a cursor to retrieve requisition line-id */
10574 CURSOR interface_lines_temp IS
10575   SELECT pli.requisition_line_id
10576   FROM po_lines_interface pli
10577   WHERE pli.interface_header_id = x_interface_header_id
10578 -- bug 4000047: start: requisition lines should be entered
10579 -- into PO the same order they appear in the requisition
10580   ORDER BY pli.requisition_line_id;
10581 -- bug 4000047: end
10582 
10583 CURSOR interface_lines IS
10584    SELECT pli.action,
10585           pli.requisition_line_id,
10586           pli.line_num,
10587           pli.item_id,
10588           pli.item_description,     -- bgu, Mar. 19, 1999
10589           pli.line_type_id,
10590           pli.item_revision,
10591           pli.unit_of_measure,
10592           pli.transaction_reason_code,
10593           pli.need_by_date,
10594           pli.note_to_receiver,
10595           pli.oke_contract_header_id,
10596           pli.oke_contract_version_id,
10597           pli.vendor_product_num,   -- Bug# 1763933
10598           pld.deliver_to_location_id,
10599           pld.destination_organization_id,
10600           pli.secondary_unit_of_measure,
10601           pli.preferred_grade,
10602           pli.bid_number,
10603           pli.bid_line_number,
10604           pli.rowid,
10605           pli.vmi_flag,   --  VMI FPH
10606           pli.drop_ship_flag,   --  <DropShip FPJ>
10607           pli.from_header_id,   -- FPI GA
10608           pli.from_line_id,      -- FPI GA
10609           pli.consigned_flag,    -- CONSIGNED FPI
10610           pli.contract_id,       -- <GC FPJ>
10611           pli.supplier_ref_number --<CONFIG_ID FPJ>
10612    FROM po_lines_interface pli,
10613         po_distributions_interface pld
10614    WHERE pli.interface_header_id=x_interface_header_id
10615    AND   pli.interface_line_id=pld.interface_line_id
10616    AND   pld.interface_distribution_id =
10617             ( SELECT min(pdi2.interface_distribution_id)
10618               FROM   po_distributions_interface pdi2
10619               WHERE  pdi2.interface_line_id = pli.interface_line_id)
10620    ORDER BY pli.item_id,
10621             pli.item_description,
10622             pli.unit_price,
10623             pli.need_by_date,
10624             pli.requisition_line_id;
10625 
10626   l_progress VARCHAR2(3) := '000';                  --< Bug 3210331 >
10627 
10628   --<INVCONV R12 START>
10629   l_grade_control_flag  MTL_SYSTEM_ITEMS.GRADE_CONTROL_FLAG%TYPE;
10630   l_line_grade    MTL_GRADES.GRADE_CODE%TYPE;
10631   --<INVCONV R12 END>
10632 
10633   l_max_iface_line_num   NUMBER;        -- <Complex Work R12>
10634 
10635 
10636 BEGIN
10637 
10638   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10639       PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
10640   END IF;
10641 
10642   -- Bug 3201308 start
10643   -- Get the profile option values to determine grouping criteria
10644   l_needby_prf := fnd_profile.value('PO_NEED_BY_GROUPING');
10645   l_shipto_prf := fnd_profile.value('PO_SHIPTO_GROUPING');
10646   l_progress := '010';
10647   -- Bug 3201308 end
10648 
10649   SELECT phi.document_num,
10650          phi.document_type_code,
10651          phi.document_subtype,
10652          phi.release_num
10653   INTO x_document_num,
10654        x_document_type_code,
10655        x_document_subtype,
10656        x_release_num
10657   FROM po_headers_interface phi
10658   WHERE phi.interface_header_id = x_interface_header_id;
10659 
10660   IF (g_document_type = 'RFQ') THEN
10661     x_document_subtype := 'RFQ';
10662   END IF;
10663 
10664   l_progress := '020';
10665   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10666       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10667                           p_token    => l_progress,
10668                           p_message  => 'Mode is:'|| g_mode);
10669   END IF;
10670 
10671   --<SOURCING TO PO FPH>
10672   --modify to group blanket lines also
10673 
10674   IF (x_document_type_code IN ('PO', 'PA', 'RFQ')) THEN
10675 
10676     IF (g_group_code = 'REQUISITION') THEN
10677 
10678       IF (g_mode = 'NEW') THEN
10679 
10680 
10681         -- Create a new PO/Release with Req. lines in
10682         -- the same order as on the requisition.
10683         -- The interface table will hold the requisition line id
10684         -- that we need to get the req line number from.
10685         -- We need to update the shipment number to 1.
10686 
10687         l_progress := '030';
10688 
10689 
10690         IF ((x_document_subtype IN ('STANDARD', 'PLANNED')) OR
10691             (g_document_type = 'RFQ'))
10692         THEN
10693 
10694           -- Bug 3825483
10695           -- For Standard and Planned POs and RFQs, the line number
10696           -- will be the same as the req line number if the profile
10697           -- is set to 'Y' otherwise use sequential numbers
10698 
10699           IF (FND_PROFILE.VALUE('PO_USE_REQ_NUM_IN_AUTOCREATE') = 'Y') THEN
10700 
10701             -- use requisition numbers
10702 
10703             l_progress:='035';
10704 
10705             UPDATE po_lines_interface pli
10706             SET pli.shipment_num = 1,
10707                 pli.line_num =
10708                    (
10709                      SELECT prl.line_num
10710                      FROM   po_requisition_lines_all prl  -- Bug 3903445
10711                      WHERE  prl.requisition_line_id = pli.requisition_line_id
10712                    )
10713             WHERE pli.interface_header_id = x_interface_header_id
10714             AND   pli.line_num is null
10715             AND   pli.shipment_num is null;
10716 
10717           ELSE
10718 
10719             -- use sequential numbers
10720 
10721             l_progress := '040';
10722 
10723             OPEN interface_lines_temp;
10724             LOOP
10725 
10726               x_count := x_count + 1;
10727 
10728               FETCH interface_lines_temp into x_requisition_line_id;
10729               EXIT WHEN interface_lines_temp%NOTFOUND;
10730 
10731               l_progress := '050';
10732 
10733               UPDATE po_lines_interface pli
10734               SET pli.line_num = x_count,
10735                   pli.shipment_num = 1
10736               WHERE pli.requisition_line_id = x_requisition_line_id
10737               AND   pli.interface_header_id = x_interface_header_id
10738               AND   pli.line_num IS NULL
10739               AND   pli.shipment_num IS NULL;
10740 
10741             END LOOP;
10742 
10743             CLOSE interface_lines_temp;
10744 
10745           END IF;  -- if fnd_profile.value(PO_USE_REQ_NUM...) = 'Y'
10746 
10747         ELSE
10748 
10749           -- Document is release case
10750 
10751           l_progress:='060';
10752 
10753           OPEN interface_lines;
10754           LOOP
10755 
10756             l_progress:='070';
10757 
10758             FETCH interface_lines INTO
10759               x_action,
10760               x_requisition_line_id,
10761               x_interface_line_num,
10762               x_item_id,
10763               x_item_description,        -- bgu, Mar. 19, 1999
10764               x_line_type_id,
10765               x_item_revision,
10766               x_unit_meas_lookup_code,
10767               x_transaction_reason_code,
10768               x_need_by_date,
10769               x_note_to_receiver,
10770               x_oke_contract_header_id,
10771               x_oke_contract_version_id,
10772               x_vendor_product_num,      --Bug 1763933
10773               x_deliver_to_location_id,
10774               x_destination_org_id,
10775               x_secondary_unit_of_measure,
10776               x_preferred_grade,
10777               x_bid_number,
10778               x_bid_line_number,
10779               x_row_id,
10780               x_vmi_flag,               --  VMI FPH
10781               x_drop_ship_flag,         --  <DropShip FPJ>
10782               x_source_doc_id ,         -- FPI GA
10783               x_source_doc_line_id,     -- FPI GA
10784               x_consigned_flag,         -- CONSIGNED FPI
10785               l_contract_id,            -- <GC FPJ>
10786               l_supplier_ref_number    --<CONFIG_ID FPJ>
10787             ;
10788 
10789             EXIT WHEN interface_lines%NOTFOUND;
10790 
10791             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10792                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10793                                      p_progress => l_progress,
10794                                      p_name     => 'x_deliver_to_location_id',
10795                                      p_value    => x_deliver_to_location_id);
10796                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10797                                      p_progress => l_progress,
10798                                      p_name     => 'x_destination_org_id',
10799                                      p_value    => x_destination_org_id);
10800                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10801                                      p_progress => l_progress,
10802                                      p_name     => 'x_need_by_date',
10803                                      p_value    => x_need_by_date);
10804                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10805                                      p_progress => l_progress,
10806                                      p_name     => 'x_unit_meas_lookup_code',
10807                                      p_value    => x_unit_meas_lookup_code);
10808                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10809                                      p_progress => l_progress,
10810                                      p_name     => 'x_transaction_reason_code',
10811                                      p_value    => x_transaction_reason_code);
10812             END IF;  -- debug logging
10813 
10814             -- The user did not specify the line that they want the
10815             -- requisition line to be associated with.  We need
10816             -- to find a requisition line that matches it.
10817             -- Find a line that matches, if one does not match, skip
10818             -- the record.  If one does match, update the interface
10819             -- table with the correct line number.
10820 
10821             IF (x_action is NULL) THEN
10822 
10823               l_progress := '080';
10824 
10825               BEGIN
10826 
10827                 -- bug# 2564767: don't compare secondary uom
10828 
10829                 SELECT MIN(pli.line_num),
10830                        pli.po_line_id
10831                 INTO x_po_line_num,
10832                      x_po_line_id
10833                 FROM po_lines_interface pli
10834                 WHERE pli.interface_header_id = x_interface_header_id
10835                 AND pli.line_num IS NOT NULL
10836                 AND pli.line_type_id = x_line_type_id
10837                 AND NVL(pli.item_id, -1) = NVL(x_item_id, -1)
10838                 AND NVL(pli.item_description, 'null' ) =
10839                                                  NVL(x_item_description,'null')
10840                 AND (((pli.item_revision IS NULL) AND (x_item_revision IS NULL))
10841                       OR (pli.item_revision = x_item_revision))
10842                 AND pli.unit_of_measure = x_unit_meas_lookup_code
10843                 AND ( pli.transaction_reason_code IS NULL
10844                       OR pli.transaction_reason_code =
10845                            NVL(x_transaction_reason_code,
10846                                   pli.transaction_reason_code))
10847 
10848                 -- togeorge 09/27/2000
10849                 -- added conditions to compare oke contract num and rev.
10850                 -- line num is different if contract info is diff. on the
10851                 -- same item.
10852                 AND   NVL(pli.oke_contract_header_id,-1) =
10853                                                NVL(x_oke_contract_header_id,-1)
10854                 AND   NVL(pli.oke_contract_version_id,-1) =
10855                                                NVL(x_oke_contract_version_id,-1)
10856                 GROUP BY pli.po_line_id;
10857 
10858               EXCEPTION
10859                 WHEN NO_DATA_FOUND THEN
10860                   IF g_debug_stmt THEN
10861                     PO_DEBUG.debug_stmt(
10862                       p_log_head => g_log_head||l_api_name,
10863                       p_token    => l_progress,
10864                       p_message  => 'NO_DATA_FOUND: '||SQLERRM);
10865                     END IF;
10866                     x_po_line_num := -1;
10867               END;
10868 
10869               l_progress := '090';
10870 
10871               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10872                    PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10873                                        p_token    => l_progress,
10874                                        p_message  => 'Line_num is :'|| x_po_line_num);
10875                    PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10876                                        p_token    => l_progress,
10877                                        p_message  => 'Group_interface_lines progress is :'|| l_progress);
10878               END IF;  -- debug logging
10879 
10880               UPDATE po_lines_interface pli
10881               SET pli.line_num = x_po_line_num
10882               WHERE pli.interface_header_id = x_interface_header_id
10883               AND pli.requisition_line_id = x_requisition_line_id;
10884 
10885               x_interface_line_num := x_po_line_num;
10886 
10887             END IF;  -- if x_action is NULL
10888 
10889           END LOOP;
10890           CLOSE interface_lines;
10891 
10892           -- Bug 3825483
10893           -- For Releases, the shipment number will be the same as
10894           -- the req line number if the profile is set, otherwise
10895           -- sequential numbers are used
10896 
10897           IF (FND_PROFILE.VALUE('PO_USE_REQ_NUM_IN_AUTOCREATE')='Y') THEN
10898 
10899             -- use requisition numbers
10900 
10901             l_progress := '100';
10902 
10903             UPDATE po_lines_interface pli
10904             SET pli.shipment_num =
10905                   ( SELECT prl.line_num
10906                     FROM po_requisition_lines_all prl
10907                     WHERE prl.requisition_line_id = pli.requisition_line_id )
10908             WHERE pli.interface_header_id = x_interface_header_id
10909             AND pli.shipment_num IS NULL;
10910 
10911           ELSE
10912 
10913             -- use sequential numbers
10914 
10915             OPEN interface_lines_temp;
10916             LOOP
10917 
10918               x_count := x_count + 1;
10919 
10920               FETCH interface_lines_temp INTO x_requisition_line_id;
10921               EXIT WHEN interface_lines_temp%NOTFOUND;
10922 
10923               l_progress := '110';
10924 
10925               UPDATE po_lines_interface pli
10926               SET pli.shipment_num = x_count
10927               WHERE pli.requisition_line_id = x_requisition_line_id
10928               AND pli.interface_header_id = x_interface_header_id
10929               AND pli.shipment_num IS NULL;
10930 
10931             END LOOP;
10932             CLOSE interface_lines_temp;
10933 
10934           END IF;  -- if fnd_profile.value(PO_USE_REQ_NUM...) = 'Y'
10935 
10936         END IF;  -- release vs. non release case
10937 
10938       ELSE
10939 
10940         -- mode = 'ADD'
10941         -- add to a po/release with the same order as on the req.
10942 
10943         IF ((x_document_subtype IN ('STANDARD', 'PLANNED'))
10944            OR (g_document_type = 'RFQ'))
10945         THEN
10946 
10947           -- The inteface table will hold the requisition line id that we
10948           -- will use to get the line number.  Select the maximum line number
10949           -- that exists on the purchase order.  Update the line number in
10950           -- the interface talbe to be the req. line number + max po line num.
10951           -- Shipment num should be 1.
10952 
10953           l_progress:='120';
10954 
10955           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10956                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10957                                     p_token    => l_progress,
10958                                     p_message  => 'Group_interface_lines: mode is :'|| g_mode);
10959           END IF;
10960 
10961           SELECT NVL(max(pl.line_num),0)
10962           INTO x_line_num
10963           FROM po_headers_all ph,
10964                po_lines_all pl
10965           WHERE pl.po_header_id = ph.po_header_id
10966           AND ph.segment1 = x_document_num
10967           AND ph.type_lookup_code =
10968                 DECODE(g_document_type, 'RFQ', g_document_type, x_document_subtype)
10969           AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99);
10970 
10971           l_progress:='130';
10972 
10973           OPEN interface_lines_temp;
10974           LOOP
10975 
10976             l_progress := '140';
10977             x_count := x_count + 1;
10978 
10979             FETCH interface_lines_temp INTO x_requisition_line_id;
10980             EXIT WHEN interface_lines_temp%NOTFOUND;
10981 
10982             l_progress := '150';
10983 
10984             UPDATE po_lines_interface pli
10985             SET pli.line_num = x_line_num + x_count,
10986                 pli.shipment_num = 1
10987             WHERE pli.requisition_line_id = x_requisition_line_id
10988             AND pli.interface_header_id = x_interface_header_id
10989             AND pli.line_num IS NULL
10990             AND pli.shipment_num IS NULL;
10991 
10992           END LOOP;
10993           CLOSE interface_lines_temp;
10994 
10995         ELSE
10996 
10997           -- Document is release case
10998 
10999           l_progress:='160';
11000           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11001                       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11002                                           p_token    => l_progress,
11003                                           p_message  => 'Before opening interface_lines cursor');
11004           END IF;
11005 
11006           OPEN interface_lines;
11007           LOOP
11008 
11009             l_progress:='170';
11010 
11011             FETCH interface_lines into
11012               x_action,
11013               x_requisition_line_id,
11014               x_interface_line_num,
11015               x_item_id,
11016               x_item_description,     -- bgu, Mar. 19, 1999
11017               x_line_type_id,
11018               x_item_revision,
11019               x_unit_meas_lookup_code,
11020               x_transaction_reason_code,
11021               x_need_by_date,
11022               x_note_to_receiver,
11023               x_oke_contract_header_id,
11024               x_oke_contract_version_id,
11025               x_vendor_product_num,  --Bug# 1763933
11026               x_deliver_to_location_id,
11027               x_destination_org_id,
11028               x_secondary_unit_of_measure,
11029               x_preferred_grade,
11030               x_bid_number,
11031               x_bid_line_number,
11032               x_row_id,
11033               x_vmi_flag,              -- VMI FPH
11034               x_drop_ship_flag,        --  <DropShip FPJ>
11035               x_source_doc_id ,        -- FPI GA
11036               x_source_doc_line_id,    -- FPI GA
11037               x_consigned_flag,        -- CONSIGNED FPI
11038               l_contract_id,           -- GC FPJ
11039               l_supplier_ref_number    --<CONFIG_ID FPJ>
11040             ;
11041 
11042             EXIT WHEN interface_lines%NOTFOUND;
11043 
11044             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11045                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11046                                      p_progress => l_progress,
11047                                      p_name     => 'x_deliver_to_location_id',
11048                                      p_value    => x_deliver_to_location_id);
11049                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11050                                      p_progress => l_progress,
11051                                      p_name     => 'x_destination_org_id',
11052                                      p_value    => x_destination_org_id);
11053                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11054                                      p_progress => l_progress,
11055                                      p_name     => 'x_need_by_date',
11056                                      p_value    => x_need_by_date);
11057                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11058                                      p_progress => l_progress,
11059                                      p_name     => 'x_unit_meas_lookup_code',
11060                                      p_value    => x_unit_meas_lookup_code);
11061                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11062                                      p_progress => l_progress,
11063                                      p_name     => 'x_transaction_reason_code',
11064                                      p_value    => x_transaction_reason_code);
11065             END IF;
11066 
11067             -- The user did not specify the line that they want the
11068             -- requisition line to be associated with.  We need
11069             -- to find a requisition line that matches it.
11070             -- Find a line that matches, if one does not match, skip
11071             -- the record.  If one does match, update the interface
11072             -- table with the correct line number.
11073 
11074             IF (x_action is NULL) THEN
11075 
11076               l_progress := '180';
11077 
11078               BEGIN
11079 
11080                 -- bug# 2564767: don't compare secondary uom
11081 
11082                 SELECT MIN(pli.line_num),
11083                        pli.po_line_id
11084                 INTO x_po_line_num,
11085                      x_po_line_id
11086                 FROM po_lines_interface pli
11087                 WHERE pli.interface_header_id = x_interface_header_id
11088                 AND pli.line_num IS NOT NULL
11089                 AND pli.line_type_id = x_line_type_id
11090                 AND NVL(pli.item_id, -1) = NVL(x_item_id, -1)
11091                 AND NVL(pli.item_description, 'null' ) =
11092                                                  NVL(x_item_description,'null')
11093                 AND (((pli.item_revision IS NULL) AND (x_item_revision IS NULL))
11094                       OR (pli.item_revision = x_item_revision))
11095                 AND pli.unit_of_measure = x_unit_meas_lookup_code
11096                 AND ( pli.transaction_reason_code IS NULL
11097                       OR pli.transaction_reason_code =
11098                            NVL(x_transaction_reason_code,
11099                                   pli.transaction_reason_code))
11100 
11101                 -- togeorge 09/27/2000
11102                 -- added conditions to compare oke contract num and rev.
11103                 -- line num is different if contract info is diff. on the
11104                 -- same item.
11105                 AND   NVL(pli.oke_contract_header_id,-1) =
11106                                                NVL(x_oke_contract_header_id,-1)
11107                 AND   NVL(pli.oke_contract_version_id,-1) =
11108                                                NVL(x_oke_contract_version_id,-1)
11109                 GROUP BY pli.po_line_id;
11110 
11111               EXCEPTION
11112                 WHEN NO_DATA_FOUND THEN
11113                   IF g_debug_stmt THEN
11114                     PO_DEBUG.debug_stmt(
11115                       p_log_head => g_log_head||l_api_name,
11116                       p_token    => l_progress,
11117                       p_message  => 'NO_DATA_FOUND: '||SQLERRM);
11118                     END IF;
11119                     x_po_line_num := -1;
11120               END;
11121 
11122               l_progress := '190';
11123 
11124               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11125                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11126                                             p_token    => l_progress,
11127                                             p_message  => 'Group_interface_lines: Line_num is :'|| x_po_line_num);
11128               END IF;
11129 
11130               UPDATE po_lines_interface pli
11131               SET pli.line_num = x_po_line_num
11132               WHERE pli.interface_header_id = x_interface_header_id
11133               AND pli.requisition_line_id = x_requisition_line_id;
11134 
11135               x_interface_line_num := x_po_line_num;
11136 
11137             END IF;  -- if x_action is null
11138 
11139           END LOOP;
11140           CLOSE interface_lines;
11141 
11142           -- Select the maxmimum shipment number that exists on the
11143           -- release and update the shipment number in the interface
11144           -- table to be the requisition line number + this max
11145 
11146           l_progress:='200';
11147           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11148                       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11149                                           p_token    => l_progress,
11150                                           p_message  => 'Group_interface_lines: before select max ship num');
11151           END IF;
11152 
11153           SELECT nvl(max(poll.shipment_num),0)
11154           INTO x_shipment_num
11155           FROM po_headers_all ph,
11156                po_line_locations_all poll,
11157                po_releases_all pr
11158           WHERE ph.po_header_id = poll.po_header_id
11159           AND ph.segment1 = x_document_num
11160           AND pr.po_header_id = ph.po_header_id
11161           AND pr.release_num = x_release_num
11162           AND ph.type_lookup_code = 'BLANKET'
11163           AND poll.po_release_id = pr.po_release_id
11164           AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
11165           AND NVL(pr.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
11166 
11167           l_progress:='210';
11168           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11169                  PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11170                                      p_token    => l_progress,
11171                                      p_message  => 'Group_interface_lines: after select max ship num');
11172           END IF;
11173 
11174           -- Bug 2841716 Start
11175           -- Prior to this fix, for Releases, the shipment number was
11176           -- derived by adding requisition line number to the current
11177           -- maximum shipment number.  Due to this shipment numbers
11178           -- were getting skipped. Hence commented the following update
11179           -- statement and now updating the po_lines_interface in a loop using
11180           -- a cursor.
11181 
11182           OPEN interface_lines_temp;
11183           LOOP
11184 
11185             x_count := x_count + 1;
11186             FETCH interface_lines_temp INTO x_requisition_line_id;
11187             EXIT WHEN interface_lines_temp%NOTFOUND;
11188 
11189             l_progress := '220';
11190 
11191             UPDATE po_lines_interface pli
11192             SET pli.shipment_num = x_shipment_num + x_count
11193             WHERE pli.requisition_line_id = x_requisition_line_id
11194             AND pli.interface_header_id = x_interface_header_id
11195             AND pli.line_num IS NOT NULL
11196             AND pli.shipment_num IS NULL;
11197 
11198           END LOOP;
11199           CLOSE interface_lines_temp;
11200 
11201           -- Bug 2841716 End
11202 
11203         END IF;  -- doc is not release / release
11204 
11205       END IF;  -- mode is NEW/ADD
11206 
11207     ELSE
11208 
11209       -- group code is DEFAULT
11210 
11211       IF ((x_document_subtype IN ('STANDARD', 'PLANNED', 'BLANKET')) OR
11212            (g_document_type = 'RFQ'))
11213       THEN
11214 
11215         l_progress := '230';
11216 
11217         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11218                   PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11219                                       p_token    => l_progress,
11220                                       p_message  => 'Before open interface: Grouping is default');
11221         END IF;
11222 
11223         -- <Complex Work R12 Start>
11224         -- Get maximum line number in interface table, to be used later
11225 
11226         SELECT NVL(max(pli.line_num), 0)
11227         INTO l_max_iface_line_num
11228         FROM po_lines_interface pli
11229         WHERE pli.interface_header_id = x_interface_header_id;
11230 
11231         -- <Complex Work R12 End>
11232 
11233         OPEN interface_lines;
11234         LOOP
11235 
11236           l_progress := '240';
11237           x_po_line_id := NULL;
11238           x_po_line_num := NULL;
11239 
11240           FETCH interface_lines INTO
11241             x_action,
11242             x_requisition_line_id,
11243             x_interface_line_num,
11244             x_item_id,
11245             x_item_description,     -- bgu, Mar. 19, 1999
11246             x_line_type_id,
11247             x_item_revision,
11248             x_unit_meas_lookup_code,
11249             x_transaction_reason_code,
11250             x_need_by_date,
11251             x_note_to_receiver,
11252             x_oke_contract_header_id,
11253             x_oke_contract_version_id,
11254             x_vendor_product_num, --Bug# 1763933
11255             x_deliver_to_location_id,
11256             x_destination_org_id,
11257             x_secondary_unit_of_measure,
11258             x_preferred_grade,
11259             x_bid_number,
11260             x_bid_line_number,
11261             x_row_id,
11262             x_vmi_flag,  -- VMI FPH
11263             x_drop_ship_flag,   --  <DropShip FPJ>
11264             x_source_doc_id ,        -- FPI GA
11265             x_source_doc_line_id ,    -- FPI GA
11266             x_consigned_flag,         -- CONSIGNED FPI
11267             l_contract_id,            -- <GC FPJ>
11268             l_supplier_ref_number    --<CONFIG_ID FPJ>
11269           ;
11270 
11271           x_po_line_num := x_interface_line_num; --bug 16183038
11272 
11273           EXIT WHEN interface_lines%NOTFOUND;
11274 
11275           -- <Complex Work R12 Start>: Do not group from sourcing
11276 
11277           IF (p_is_complex_work_po) THEN
11278 
11279             -- for complex work, we do not want to group lines.
11280             -- for complex PO's directly from requisitions, the group code
11281             -- will be set to REQUISITION and so lines will not be grouped.
11282             -- when coming from sourcing, however, the group type is set
11283             -- to DEFAULT.
11284 
11285             -- Do not group; simply add 1 to each successive interface line
11286 
11287             UPDATE po_lines_interface pli
11288             SET pli.line_num = l_max_iface_line_num + 1
11289             WHERE pli.rowid = x_row_id
11290             AND pli.line_num IS NULL;
11291 
11292             IF (SQL%ROWCOUNT > 0) THEN
11293               l_max_iface_line_num := l_max_iface_line_num + 1;
11294             END IF;
11295 
11296           -- <Complex Work R12 End>
11297 
11298           ELSIF (x_action = 'NEW') THEN
11299 
11300             -- line number should be loaded into the interface.  In general,
11301             -- the shipment number should be equal to 1.  The only time it
11302             -- will not be is if the user attempts to place two or more
11303             -- req lines to the same po line and the shipments are identical.
11304 
11305             l_progress:='250';
11306             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11307                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11308                                             p_token    => l_progress,
11309                                             p_message  => 'Before get_shipment_num');
11310             END IF;
11311 
11312             get_shipment_num(
11313               x_need_by_date,
11314               x_deliver_to_location_id,
11315               x_destination_org_id,
11316               x_po_line_id,
11317               x_po_line_num,
11318               x_requisition_line_id,
11319               x_interface_header_id,
11320               x_po_shipment_num,
11321               x_note_to_receiver,
11322               x_preferred_grade,
11323               NULL,  -- VMI FPH
11324               x_consigned_flag,
11325               x_drop_ship_flag,     --  <DropShip FPJ>
11326               x_create_new_line, -- FPI GA
11327 			  p_group_shipments --<Bug 14608120 Autocreate GE ER>
11328 			  );
11329 
11330             x_po_line_num := x_interface_line_num;
11331 
11332             l_progress := '260';
11333 
11334             update_shipment(
11335               x_interface_header_id,
11336               x_po_shipment_num,
11337               x_po_line_num,
11338               x_requisition_line_id,
11339               x_po_line_id,
11340               x_document_num,
11341               x_release_num,
11342               x_create_new_line);  -- FPI GA
11343 
11344           ELSIF (x_action = 'ADD') THEN
11345 
11346             -- user wants to add a requisition line to a particular PO line.
11347             -- check if a shipment exists that we can add to, otherwise
11348             -- get the next highest shipment number.
11349 
11350             l_progress:='270';
11351             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11352                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11353                                             p_token    => l_progress,
11354                                             p_message  => 'x_action = '||x_action);
11355             END IF;
11356 
11357             -- Bug 594843: We need to retrieve the po_line_id for the
11358             -- line the user picked in the manual build process.
11359             -- Otherwise we will not be able the shipments
11360             -- Bug 599307: Added an AND condition to match_type_lookup_code
11361             -- Bug 1672940: Passing the value of line_num in x_po_line_num
11362 
11363             IF ((x_interface_line_num IS NOT NULL) AND
11364                   (x_document_num IS NOT NULL))
11365             THEN
11366 
11367               l_progress := '280';
11368 
11369               BEGIN
11370 
11371                 SELECT pol.po_line_id,
11372                        pol.line_num
11373                 INTO x_po_line_id,
11374                      x_po_line_num
11375                 FROM po_lines_all pol,
11376                      po_headers_all poh
11377                 WHERE poh.segment1 = x_document_num
11378                 AND pol.line_num = x_interface_line_num
11379                 AND poh.type_lookup_code =
11380                       DECODE(g_document_type, 'RFQ', g_document_type,x_document_subtype)
11381                 AND poh.po_header_id = pol.po_header_id
11382                 AND NVL(poh.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
11383 
11384                 -- Bug 2708776
11385                 -- In the manual option when a Req. Line is added to the PO
11386                 -- and PO has the same Item, the PO Line is matched and
11387                 -- the line num is defaulted to the Po Line matched in the PO.
11388                 -- If we change the line num defaulted and add a new line to
11389                 -- the PO the shipment# was not populated when the PO was
11390                 -- created. The is because we assume that the line_num
11391                 -- populated will always exist in the PO, which is wrong.
11392                 -- Handling the exception for NO_DATA_FOUND will resolve the
11393                 -- Issue
11394 
11395               EXCEPTION
11396                 WHEN NO_DATA_FOUND THEN
11397                   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11398                                   PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11399                                                       p_token    => l_progress,
11400                                                       p_message  => 'NO_DATA_FOUND: '||SQLERRM);
11401                   END IF;
11402                 WHEN others THEN
11403                   IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11404                                   PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11405                                                      p_progress => l_progress);
11406                   END IF;
11407                   RAISE;
11408               END;
11409 
11410             END IF;  -- if interface_line_num and x_document_num are not null
11411 
11412             l_progress := '290';
11413 
11414             get_shipment_num(
11415               x_need_by_date,
11416               x_deliver_to_location_id,
11417               x_destination_org_id,
11418               x_po_line_id,
11419               x_po_line_num,
11420               x_requisition_line_id,
11421               x_interface_header_id,
11422               x_po_shipment_num,
11423               x_note_to_receiver,
11424               x_preferred_grade,
11425               NULL,  -- VMI FPH
11426               x_consigned_flag,
11427               x_drop_ship_flag,     --  <DropShip FPJ>
11428               x_create_new_line,-- FPI GA
11429 			  p_group_shipments --<Bug 14608120 Autocreate GE ER>
11430 			  );
11431 
11432             l_progress := '300';
11433 
11434             update_shipment(
11435               x_interface_header_id,
11436               x_po_shipment_num,
11437               x_po_line_num,
11438               x_requisition_line_id,
11439               x_po_line_id,
11440               x_document_num,
11441               x_release_num,
11442               x_create_new_line);  -- FPI GA
11443 
11444           ELSE
11445 
11446             -- action = NULL (R10 logic)
11447 
11448             -- Check to see if this line matches another line already on PO
11449             -- If the line matches, update interface line num with PO line num
11450             -- If the shipment matches, update interface table w/ ship. num
11451             -- If the the shipment does not match, update table w/ number = 1
11452             -- If the line does not match, get the next highest line number
11453 
11454             l_progress := '310';
11455 
11456             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11457                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11458                                             p_token    => l_progress,
11459                                             p_message  => 'x_action = '||x_action);
11460             END IF;
11461 
11462             --<SOURCING TO PO FPH>: allow lines grouping for blankets also
11463 
11464             IF (g_document_type IN ('PO', 'PA')) THEN
11465 
11466               --<INVCONV R12 START>
11467               -- Item could have different grade control for FSP and ship to org.
11468               -- If (shipment)grade is present , compare the grade at line level
11469               -- only if item is grade control for the FSP org.
11470               IF x_preferred_grade IS NOT NULL THEN
11471 
11472                 BEGIN
11473                   SELECT grade_control_flag
11474                   INTO l_grade_control_flag
11475                   FROM mtl_system_items
11476                   WHERE inventory_item_id = x_item_id
11477                   and organization_id = params.inventory_organization_id;
11478                 EXCEPTION
11479                   WHEN OTHERS THEN
11480                     l_grade_control_flag := 'N';
11481                 END;
11482 
11483                 IF l_grade_control_flag = 'Y' THEN
11484                   l_line_grade := x_preferred_grade ;
11485                 ELSE
11486                   l_line_grade := null;
11487                 END IF;
11488 
11489               ELSE
11490 
11491                 l_line_grade := null;
11492 
11493               END IF;  -- x_preferred_grade is not null
11494               --<INVCONV R12 END>
11495 
11496               BEGIN
11497 
11498                 l_progress := '320';
11499 
11500                 -- SQL What: Querying for an existing line on the PO
11501                 -- that matches the requisition line that we are trying to add.
11502                 -- SQL Why: Want to group matching lines onto PO documents
11503                 -- SQL Join: business logic for combining two lines
11504 
11505                 SELECT  line_num
11506                 ,       po_line_id
11507                 INTO    x_po_line_num
11508                 ,       x_po_line_id
11509                 FROM    po_lines_all POL2
11510                 ,       po_headers_all POH
11511                 ,       po_line_types_b PLT                 -- <SERVICES FPJ>
11512                 WHERE  POH.segment1 = x_document_num
11513                 AND    POH.po_header_id = POL2.po_header_id
11514                 AND    NVL(poh.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
11515                 AND    POH.type_lookup_code = x_document_subtype
11516                 -- <SERVICES FPJ START> Any new Service line types should
11517                 -- cause the SELECT to fail (i.e. should not be matched).
11518                 --
11519                 AND    POL2.line_type_id = PLT.line_type_id
11520                 AND    PLT.order_type_lookup_code NOT IN ('RATE','FIXED PRICE')
11521                 --
11522                 -- <SERVICES FPJ END>
11523                 AND    pol2.line_num =
11524                            (SELECT /*+ NO_UNNEST */ MIN(line_num)
11525                             FROM  po_lines_all pol  --<Shared Proc FPJ>
11526                             WHERE pol.po_header_id = poh.po_header_id
11527                             AND   NVL(CANCEL_FLAG,'N') = 'N'
11528                             AND   LINE_TYPE_ID = x_line_type_id
11529                             AND   nvl(pol.ITEM_ID, -1) = nvl(x_item_id, -1) -- bgu, For one time item
11530                             AND   nvl(pol.ITEM_DESCRIPTION,'null') = nvl(x_item_description,'null')
11531                             AND
11532                                 ( (     ITEM_REVISION IS NULL
11533                                     AND x_item_revision IS NULL
11534                                    )
11535                                  OR ITEM_REVISION = x_item_revision
11536                                  )
11537                             AND   UNIT_MEAS_LOOKUP_CODE =
11538                                     x_unit_meas_lookup_code
11539 --<INVCONV R12 START>
11540 -- replace x_preferred_grade to l_line_grade and removed secondary unit comparison.
11541                             AND
11542                              (
11543                                ( POL.PREFERRED_GRADE IS NULL
11544                                 AND  l_line_grade IS NULL
11545                                 ) OR
11546                                 (  POL.PREFERRED_GRADE =
11547                                    l_line_grade
11548                                  )
11549                               )
11550 --<INVCONV R12 END>
11551                             AND  /* FPI GA start */
11552                              (
11553                                ( pol.from_header_id IS NULL
11554                                 AND  x_source_doc_id IS NULL
11555                                 ) OR
11556                                 (  pol.from_header_id =
11557                                    x_source_doc_id
11558                                  )
11559                               )
11560                             AND
11561                              (
11562                                ( pol.from_line_id IS NULL
11563                                 AND  x_source_doc_line_id IS NULL
11564                                 ) OR
11565                                 (  pol.from_line_id =
11566                                    x_source_doc_line_id
11567                                  )
11568                               )   /* FPI GA end */
11569                             AND   (TRANSACTION_REASON_CODE IS NULL
11570                                    OR TRANSACTION_REASON_CODE =
11571                                    NVL(x_transaction_reason_code,
11572                                   TRANSACTION_REASON_CODE))
11573                             AND  trunc(nvl(pol.expiration_date,sysdate+1)) >= trunc(sysdate)
11574                             AND  nvl(pol.oke_contract_header_id,-1)=nvl(x_oke_contract_header_id,-1)
11575                             AND  nvl(pol.oke_contract_version_id,-1)=nvl(x_oke_contract_version_id,-1)
11576                             AND  nvl(pol.vendor_product_num,-1)=nvl(x_vendor_product_num,-1)
11577                             AND nvl(pol.bid_number,-1)=nvl(x_bid_number,-1)
11578                             AND nvl(pol.bid_line_number,-1)=nvl(x_bid_line_number,-1)
11579                             -- <GC FPJ START>
11580                             AND
11581                              (
11582                                 ( pol.contract_id IS NULL AND
11583                                   l_contract_id IS NULL )
11584                                 OR
11585                                 ( pol.contract_id = l_contract_id )
11586                              )
11587                             -- <GC FPJ END>
11588                             --<CONFIG_ID FPJ START>
11589                             AND ((pol.supplier_ref_number IS NULL
11590                                   AND l_supplier_ref_number IS NULL)
11591                                  OR (pol.supplier_ref_number = l_supplier_ref_number))
11592                             --<CONFIG_ID FPJ END>
11593                            )
11594                           FOR UPDATE OF QUANTITY;
11595 
11596               EXCEPTION
11597                 WHEN NO_DATA_FOUND THEN
11598                   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11599                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11600                                                     p_token    => l_progress,
11601                                                     p_message  => 'NO_DATA_FOUND: No match to po line: Doc type = '||g_document_type);
11602                   END IF;
11603                   x_po_line_num := -1;
11604                 WHEN OTHERS THEN
11605                   IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11606                                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11607                                                    p_progress => l_progress);
11608                   END IF;
11609                   wrapup(x_interface_header_id);
11610                   RAISE;
11611               END;
11612 
11613             ELSIF (g_document_type = 'RFQ') THEN
11614 
11615               l_progress := '330';
11616 
11617               BEGIN
11618 
11619                 SELECT line_num,
11620                        po_line_id
11621                 INTO   x_po_line_num,
11622                        x_po_line_id
11623                 FROM   po_lines_all POL2,
11624                        po_headers_all POH
11625                 WHERE  POH.segment1 = x_document_num
11626                 AND POH.po_header_id = POL2.po_header_id
11627                 AND NVL(poh.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
11628                 AND POH.type_lookup_code = 'RFQ'
11629                 AND pol2.line_num =
11630                          (
11631                            SELECT /*+ NO_UNNEST */ MIN(line_num)
11632                            FROM  PO_LINES_ALL pol
11633                            WHERE pol.po_header_id = poh.po_header_id
11634                            AND LINE_TYPE_ID = x_line_type_id
11635                            AND nvl(pol.ITEM_ID, -1) = nvl(x_item_id, -1)
11636                            AND nvl(pol.ITEM_DESCRIPTION,'null') =
11637                                            nvl(x_item_description,'null')
11638                            AND
11639                                 ( (     ITEM_REVISION IS NULL
11640                                     AND x_item_revision IS NULL
11641                                    )
11642                                  OR ITEM_REVISION = x_item_revision
11643                                  )
11644                            AND nvl(pol.oke_contract_header_id,-1) =
11645                                      nvl(x_oke_contract_header_id,-1)
11646                            AND nvl(pol.oke_contract_version_id,-1) =
11647                                      nvl(x_oke_contract_version_id,-1)
11648                          )
11649                 FOR UPDATE OF QUANTITY;
11650 
11651               EXCEPTION
11652                 WHEN NO_DATA_FOUND THEN
11653                   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11654                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11655                                                     p_token    => l_progress,
11656                                                     p_message  => 'NO_DATA_FOUND: No match to po line: Doc type RFQ');
11657                   END IF;
11658                   x_po_line_num := -1;
11659                 WHEN OTHERS THEN
11660                   IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11661                                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11662                                                    p_progress => l_progress);
11663                   END IF;
11664                   wrapup(x_interface_header_id);
11665                   RAISE;
11666               END;
11667 
11668             END IF;  -- PO/PA vs. RFQ
11669 
11670             -- Check to see if there is a line in the interface table
11671             -- that matches the line we are attempting to add
11672 
11673             IF (x_po_line_num = -1) THEN
11674 
11675               --<SOURCING TO PO FPH>: allow lines grouping for blankets also
11676 
11677               IF (g_document_type IN ('PO', 'PA')) THEN
11678 
11679                 l_progress := '340';
11680 
11681                 BEGIN
11682 
11683                   x_ship_to_location_id :=
11684                        get_ship_to_loc(x_deliver_to_location_id);
11685 
11686                   l_progress := '350';
11687 
11688                   -- SQL What: Querying for a requisition line in the
11689                   -- interface table that matches the requisition line
11690                   -- that we are trying to add.
11691                   -- SQL Why: Want to group matching lines onto PO documents.
11692                   -- SQL Join: business logic for combining two lines
11693 
11694                   SELECT min(pli.line_num)
11695                   INTO   x_po_line_num
11696                   FROM   po_lines_interface pli
11697                   ,      po_requisition_lines_all prl
11698                   ,      po_line_types_b PLT                -- <SERVICES FPJ>
11699                   WHERE  pli.interface_header_id = x_interface_header_id
11700                   AND pli.line_num is not null
11701                   AND prl.requisition_line_id <> x_requisition_line_id
11702                   AND prl.requisition_line_id = pli.requisition_line_id
11703                   AND pli.line_type_id = x_line_type_id
11704 
11705                   -- <SERVICES FPJ START> Any new Service line types should
11706                   -- cause the SELECT to fail (i.e. should not be matched).
11707                   --
11708                   AND PLI.line_type_id = PLT.line_type_id
11709                   AND PLT.order_type_lookup_code NOT IN ('RATE','FIXED PRICE')
11710                   --
11711                   -- <SERVICES FPJ END>
11712 
11713                   AND nvl(pli.ITEM_ID, -1) = nvl(x_item_id, -1)
11714                   AND nvl(pli.ITEM_DESCRIPTION,'null') =
11715                                         nvl(x_item_description,'null')
11716                   AND ((pli.ITEM_REVISION IS NULL AND x_item_revision IS NULL)
11717                            OR pli.ITEM_REVISION = x_item_revision)
11718                   AND   pli.UNIT_OF_MEASURE = x_unit_meas_lookup_code
11719 
11720                   --<INVCONV R12 START>
11721                   -- replace x_preferred_grade to l_line_grade and
11722                   -- removed secondary unit comparison.
11723                   AND (( pli.PREFERRED_GRADE IS NULL AND l_line_grade IS NULL)
11724                             OR (pli.PREFERRED_GRADE = l_line_grade))
11725                   --<INVCONV R12 END>
11726 
11727                   -- FPI GA start
11728                   AND        (
11729                                ( pli.from_header_id IS NULL
11730                                 AND  x_source_doc_id IS NULL
11731                                 ) OR
11732                                 (  pli.from_header_id =
11733                                    x_source_doc_id
11734                                  )
11735                               )
11736                   AND
11737                              (
11738                                ( pli.from_line_id IS NULL
11739                                 AND  x_source_doc_line_id IS NULL
11740                                 ) OR
11741                                 (  pli.from_line_id =
11742                                    x_source_doc_line_id
11743                                  )
11744                               )
11745                   AND( nvl(l_needby_prf,'Y') = 'N'  -- Bug 3201308
11746                              OR
11747                              (
11748                                ( pli.need_by_date IS NULL
11749                                 AND  x_need_by_date IS NULL
11750                                 ) OR
11751                                 ( to_char(pli.need_by_date-(to_number(substr(to_char(pli.need_by_date,
11752                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
11753                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
11754                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
11755                                  )
11756                               )
11757                               )
11758                   AND ( nvl(l_shipto_prf,'Y') = 'N'  -- Bug 3201308
11759                               OR exists (select 'x'
11760                                      from HR_LOCATIONS HRL
11761                                      where PRL.deliver_to_location_id = HRL.location_id
11762                                      and nvl(HRL.ship_to_location_id, HRL.location_id) = x_ship_to_location_id
11763                                      UNION ALL
11764                                      select 'x'
11765                                      from HZ_LOCATIONS HZ
11766                                      where PRL.deliver_to_location_id = HZ.location_id
11767                                      and HZ.location_id = x_ship_to_location_id)
11768                                )
11769                   AND( nvl(l_shipto_prf,'Y') = 'N'   -- Bug 3201308
11770                               OR
11771                              (
11772                                ( pli.ship_to_organization_id  IS NULL
11773                                 AND  x_destination_org_id IS NULL
11774                                 ) OR
11775                                 (  pli.ship_to_organization_id =
11776                                    x_destination_org_id
11777                                  )
11778                               ) )
11779                   -- FPI GA end
11780 
11781                   -- CONSIGNED FPI start
11782                   AND        (
11783                                ( pli.consigned_flag IS NULL
11784                                 AND  x_consigned_flag IS NULL
11785                                 ) OR
11786                                 (  pli.consigned_flag  =
11787                                    x_consigned_flag
11788                                  )
11789                               )
11790                   -- CONSIGNED FPI End
11791 
11792                   AND   (pli.TRANSACTION_REASON_CODE IS NULL
11793                                    OR pli.TRANSACTION_REASON_CODE =
11794                                    NVL(x_transaction_reason_code,
11795                                   pli.TRANSACTION_REASON_CODE))
11796 
11797                   AND nvl(pli.oke_contract_header_id,-1) =
11798                             nvl(x_oke_contract_header_id,-1)
11799                   AND nvl(pli.oke_contract_version_id,-1) =
11800                             nvl(x_oke_contract_version_id,-1)
11801                   AND nvl(pli.vendor_product_num,-1) =
11802                             nvl(x_vendor_product_num,-1)
11803                   AND nvl(pli.bid_number,-1) = nvl(x_bid_number,-1)
11804                   AND nvl(pli.bid_line_number,-1) = nvl(x_bid_line_number,-1)
11805                   AND nvl(pli.orig_from_req_flag,'Y') <> 'N'
11806 
11807                   -- <GC FPJ START>
11808                   AND
11809                              (
11810                                ( pli.contract_id IS NULL AND
11811                                  l_contract_id IS NULL )
11812                                OR
11813                                ( pli.contract_id = l_contract_id )
11814                              )
11815                   -- <GC FPJ END>
11816 
11817                   --<CONFIG_ID FPJ START>
11818                   AND   ((pli.supplier_ref_number IS NULL
11819                                   AND l_supplier_ref_number IS NULL)
11820                                  OR (pli.supplier_ref_number = l_supplier_ref_number))
11821                   --<CONFIG_ID FPJ END>
11822                   ;
11823 
11824                 EXCEPTION
11825                   WHEN NO_DATA_FOUND THEN
11826                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11827                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11828                                                     p_token    => l_progress,
11829                                                     p_message  => 'NO_DATA_FOUND: No match to po line in Interface- Doc type = '||g_document_type);
11830                     END IF;
11831                     x_po_line_num := -1;
11832                   WHEN OTHERS THEN
11833                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11834                                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11835                                                    p_progress => l_progress);
11836                     END IF;
11837                     wrapup(x_interface_header_id);
11838                     RAISE;
11839                 END;
11840 
11841               ELSIF (g_document_type = 'RFQ') THEN
11842 
11843                 BEGIN
11844 
11845                   l_progress := '360';
11846 
11847                   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11848                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11849                                                   p_token    => l_progress,
11850                                                   p_message  => 'Before select min line_num');
11851                   END IF;
11852 
11853                   SELECT MIN(pli.line_num)
11854                   INTO x_po_line_num
11855                   FROM po_lines_interface pli
11856                   WHERE pli.interface_header_id = x_interface_header_id
11857                   AND pli.line_num is not null
11858                   AND pli.line_type_id = x_line_type_id
11859                   AND nvl(pli.item_id, -1) = nvl(x_item_id, -1)
11860                   AND nvl(pli.item_description,'null') =
11861                                nvl(x_item_description,'null')
11862                   AND ((pli.item_revision IS NULL AND x_item_revision IS NULL)
11863                          OR (pli.item_revision = x_item_revision))
11864                   AND nvl(pli.oke_contract_header_id,-1) =
11865                                    nvl(x_oke_contract_header_id,-1)
11866                   AND nvl(pli.oke_contract_version_id,-1) =
11867                                    nvl(x_oke_contract_version_id,-1)
11868                   ;
11869 
11870                 EXCEPTION
11871                   WHEN NO_DATA_FOUND THEN
11872                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11873                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11874                                                     p_token    => l_progress,
11875                                                     p_message  => 'NO_DATA_FOUND: No match to po line in Interface- Doc type RFQ');
11876                     END IF;
11877                     x_po_line_num := -1;
11878                   WHEN OTHERS THEN
11879                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11880                                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11881                                                    p_progress => l_progress);
11882                     END IF;
11883                     wrapup(x_interface_header_id);
11884                     RAISE;
11885                 END;
11886 
11887               END IF;  -- PO/PA vs. RFQ
11888 
11889             END IF;  -- if x_po_line_num = -1 (interface table)
11890 
11891             IF (x_po_line_num <> -1) THEN
11892 
11893               -- a line matches
11894 
11895               l_progress := '370';
11896 
11897               --<SOURCING TO PO FPH>
11898               -- We need to use get_shipment_num only for those negotiations
11899               -- with backing req.
11900 
11901               IF (x_requisition_line_id IS NOT NULL) THEN
11902 
11903                 -- backing req line exists
11904 
11905                 -- Since get_shipment_num will need it, we update the
11906                 -- line number here.
11907 
11908                 UPDATE po_lines_interface pli
11909                 SET pli.line_num = x_po_line_num
11910                 WHERE pli.interface_header_id = x_interface_header_id
11911                 AND pli.requisition_line_id = x_requisition_line_id;
11912 
11913                 l_progress := '380';
11914 
11915                 -- if a shipment matches, get the shipment number
11916 
11917                 get_shipment_num(
11918                   x_need_by_date,
11919                   x_deliver_to_location_id,
11920                   x_destination_org_id,
11921                   x_po_line_id,
11922                   x_po_line_num,
11923                   x_requisition_line_id,
11924                   x_interface_header_id,
11925                   x_po_shipment_num,
11926                   x_note_to_receiver,
11927                   x_preferred_grade,
11928                   NULL,  -- VMI FPH
11929                   x_consigned_flag,
11930                   x_drop_ship_flag,     --  <DropShip FPJ>
11931                   x_create_new_line,
11932 				  p_group_shipments --<Bug 14608120 Autocreate GE ER>
11933 				  );   -- FPI GA
11934 
11935                 l_progress := '390';
11936 
11937                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11938                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11939                                             p_token    => l_progress,
11940                                             p_message  => 'Before update_shipment');
11941                 END IF;
11942 
11943                 update_shipment(
11944                   x_interface_header_id,
11945                   x_po_shipment_num,
11946                   x_po_line_num,
11947                   x_requisition_line_id,
11948                   x_po_line_id,
11949                   x_document_num,
11950                   x_release_num,
11951                   x_create_new_line);  -- FPI GA
11952 
11953               ELSE
11954 
11955                 -- no backing requisition line
11956 
11957                 --< SOURCING TO PO FPH >
11958                 --Assign max line number+1 from interface table when not backed
11959                 --by a req and the shipment num would be 1. There can't be two
11960                 --similar negotiation lines not backed by a req, having the
11961                 --same bid number and bid line number. If that happens we don't
11962                 --group them to a single line. Also no need to select from
11963                 --po_lines table as we are not supporting add to functionality.
11964 
11965                 l_progress := '400';
11966 
11967                 UPDATE po_lines_interface pli2
11968                 SET (pli2.line_num, pli2.shipment_num) =
11969                       (
11970                         SELECT (NVL(max(pli.line_num), 0) + 1), 1
11971                         FROM po_lines_interface pli
11972                         WHERE pli.interface_header_id = x_interface_header_id
11973                       )
11974                 WHERE pli2.rowid = x_row_id;
11975 
11976               END IF;
11977 
11978             ELSE
11979 
11980               -- a matching line does not exist
11981 
11982               -- Get the max line number on the purchase order and
11983               -- update the interface line number with that number + 1.
11984               -- The shipment number should be 1.
11985 
11986               l_progress := '410';
11987               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11988                            PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11989                                                p_token    => l_progress,
11990                                                p_message  => 'Group_interface_lines: Line does not exist');
11991               END IF;
11992 
11993               SELECT NVL(max(pl.line_num), 0)
11994               INTO x_line_num
11995               FROM po_headers_all ph,
11996                    po_lines_all pl
11997               WHERE pl.po_header_id = ph.po_header_id
11998               AND ph.segment1 = x_document_num
11999               AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99)
12000               AND ph.type_lookup_code =
12001                     DECODE(g_document_type, 'RFQ', g_document_type, x_document_subtype)
12002               ;
12003 
12004               -- Get the max line number already assigne in the interface table
12005 
12006               l_progress:='420';
12007               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12008                            PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12009                                                p_token    => l_progress,
12010                                                p_message  => 'Before select max line_num from po_lines_interface');
12011               END IF;
12012 
12013               SELECT NVL(max(pli.line_num), 0)
12014               INTO x_int_line_num
12015               FROM po_lines_interface pli
12016               WHERE pli.interface_header_id = x_interface_header_id;
12017 
12018               IF (x_line_num >= x_int_line_num) THEN
12019                 x_line_num := x_line_num;
12020               ELSE
12021                 x_line_num := x_int_line_num;
12022               END IF;
12023 
12024               l_progress := '430';
12025               --<SOURCING TO PO FPH>: when req line id is null, use x_row_id
12026 
12027               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12028                        PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12029                                            p_token    => l_progress,
12030                                            p_message  => 'Sourcing to FPH-8 starts');
12031               END IF;
12032 
12033               IF (x_requisition_line_id IS NOT NULL) THEN
12034 
12035                 UPDATE po_lines_interface pli
12036                 SET pli.line_num = x_line_num + 1,
12037                     pli.shipment_num = 1
12038                 WHERE pli.interface_header_id = x_interface_header_id
12039                 AND pli.requisition_line_id = x_requisition_line_id;
12040 
12041               ELSE
12042 
12043                 -- no backing req line; use rowid
12044 
12045                 UPDATE po_lines_interface pli
12046                 SET pli.line_num = x_line_num + 1,
12047                     pli.shipment_num = 1
12048                 WHERE pli.rowid = x_row_id;
12049 
12050               END IF;  -- if x_requisition_id is not null
12051 
12052               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12053                        PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12054                                            p_token    => l_progress,
12055                                            p_message  => 'Sourcing to FPH-8 ends');
12056               END IF;
12057 
12058               x_num_interface_lines := x_num_interface_lines + 1;
12059 
12060             END IF; -- matching line vs. no matching line
12061 
12062            END IF; -- Action Type Code
12063 
12064         END LOOP;
12065         CLOSE interface_lines;
12066 
12067       ELSE
12068 
12069         -- Document is release case
12070 
12071         l_progress:='440';
12072 
12073         OPEN interface_lines;
12074         LOOP
12075 
12076           l_progress:='450';
12077 
12078           FETCH interface_lines INTO
12079             x_action,
12080             x_requisition_line_id,
12081             x_interface_line_num,
12082             x_item_id,
12083             x_item_description,     -- bgu, Mar. 19, 1999
12084             x_line_type_id,
12085             x_item_revision,
12086             x_unit_meas_lookup_code,
12087             x_transaction_reason_code,
12088             x_need_by_date,
12089             x_note_to_receiver,
12090             x_oke_contract_header_id,
12091             x_oke_contract_version_id,
12092             x_vendor_product_num, --Bug# 1763933
12093             x_deliver_to_location_id,
12094             x_destination_org_id,
12095             x_secondary_unit_of_measure,
12096             x_preferred_grade,
12097             x_bid_number,
12098             x_bid_line_number,
12099             x_row_id,
12100             x_vmi_flag,  -- VMI FPH
12101             x_drop_ship_flag,   --  <DropShip FPJ>
12102             x_source_doc_id ,        -- FPI GA
12103             x_source_doc_line_id ,    -- FPI GA
12104             x_consigned_flag,         -- CONSIGNED FPI
12105             l_contract_id,            -- <GC FPJ>
12106             l_supplier_ref_number    --<CONFIG_ID FPJ>
12107           ;
12108 
12109           EXIT WHEN interface_lines%NOTFOUND;
12110 
12111           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12112                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12113                                         p_token    => l_progress,
12114                                         p_message  => 'After fetch interface_lines cursor');
12115           END IF;
12116 
12117 
12118           IF (x_action is NULL) THEN
12119 
12120             -- The user did not specify the line that they want the req line
12121             -- to be associated with.  We need to find a req. line that matches
12122             -- it.  If one does not match, skip the record.  If one does match,
12123             -- update the interface table with the correct line number.
12124 
12125 
12126             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12127                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
12128                                            p_progress => l_progress,
12129                                            p_name     => 'x_line_type_id',
12130                                            p_value    => x_line_type_id);
12131                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
12132                                            p_progress => l_progress,
12133                                            p_name     => 'x_item_id',
12134                                            p_value    => x_item_id);
12135                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
12136                                            p_progress => l_progress,
12137                                            p_name     => 'x_item_revision',
12138                                            p_value    => x_item_revision);
12139                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
12140                                            p_progress => l_progress,
12141                                            p_name     => 'x_unit_meas_lookup_code',
12142                                            p_value    => x_unit_meas_lookup_code);
12143                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
12144                                            p_progress => l_progress,
12145                                            p_name     => 'x_transaction_reason_code',
12146                                            p_value    => x_transaction_reason_code);
12147             END IF;
12148 
12149             l_progress := '460';
12150 
12151             BEGIN
12152 
12153               SELECT min(line_num)
12154               ,      po_line_id
12155               INTO   x_po_line_num
12156               ,      x_po_line_id
12157               FROM   po_lines_interface PLI
12158               ,      po_line_types_b    PLT                 -- <SERVICES FPJ>
12159               WHERE  pli.interface_header_id = x_interface_header_id
12160               AND    pli.line_num is not null
12161               AND    pli.LINE_TYPE_ID = x_line_type_id
12162 
12163               -- <SERVICES FPJ START> Any new Service line types should
12164               -- cause the SELECT to fail (i.e. should not be matched).
12165               --
12166               AND    PLI.line_type_id = PLT.line_type_id
12167               AND    PLT.order_type_lookup_code NOT IN ('RATE','FIXED PRICE')
12168               --
12169               -- <SERVICES FPJ END>
12170 
12171               AND    nvl(pli.ITEM_ID, -1) = nvl(x_item_id, -1)
12172               AND    nvl(pli.ITEM_DESCRIPTION,'null') =
12173                                      nvl(x_item_description,'null')
12174               AND             ( (     pli.ITEM_REVISION IS NULL
12175                                     AND x_item_revision IS NULL
12176                                    )
12177                                   OR pli.ITEM_REVISION = x_item_revision
12178                                   )
12179               AND    pli.UNIT_OF_MEASURE = x_unit_meas_lookup_code
12180               AND    (pli.TRANSACTION_REASON_CODE IS NULL
12181                                    OR pli.TRANSACTION_REASON_CODE =
12182                                    NVL(x_transaction_reason_code,
12183                                   pli.TRANSACTION_REASON_CODE))
12184               AND   nvl(pli.oke_contract_header_id,-1)=nvl(x_oke_contract_header_id,-1)
12185               AND   nvl(pli.oke_contract_version_id,-1)=nvl(x_oke_contract_version_id,-1)
12186               GROUP BY po_line_id;
12187 
12188             EXCEPTION
12189               WHEN NO_DATA_FOUND THEN
12190                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12191                             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12192                                                 p_token    => l_progress,
12193                                                 p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12194                 END IF;
12195                 x_po_line_num := -1;
12196             END;
12197 
12198             l_progress := '470';
12199 
12200             UPDATE po_lines_interface pli
12201             SET pli.line_num = x_po_line_num
12202             WHERE pli.interface_header_id = x_interface_header_id
12203             AND pli.requisition_line_id = x_requisition_line_id;
12204 
12205             x_interface_line_num := x_po_line_num;
12206 
12207             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12208                           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12209                                               p_token    => l_progress,
12210                                               p_message  => 'After update of po_lines_interface line_num');
12211             END IF;
12212 
12213           ELSE
12214 
12215             -- The user did specify the line that they want the
12216             -- requisition line to come from.
12217             -- Note: For a one time item Blanket Release, the user must
12218             -- always specify the action ADD and the line number that
12219             -- that want to release against in the form.
12220 
12221             l_progress := '480';
12222 
12223             BEGIN
12224 
12225               SELECT pol.po_line_id
12226               INTO x_po_line_id
12227               FROM po_lines_all pol,
12228                    po_headers_all poh,
12229                    po_lines_interface pli
12230               WHERE pol.po_header_id = poh.po_header_id
12231               AND poh.segment1 = x_document_num
12232               AND NVL(poh.org_id, -99) = NVL(g_purchasing_ou_id, -99)
12233               AND poh.type_lookup_code = 'BLANKET' -- Bug# 1746943
12234               AND pol.line_num = pli.line_num
12235               AND pli.requisition_line_id = x_requisition_line_id;
12236 
12237             EXCEPTION
12238               WHEN NO_DATA_FOUND THEN
12239                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12240                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12241                                             p_token    => l_progress,
12242                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12243                  END IF;
12244                  x_po_line_num := -1;
12245 
12246             END;
12247           END IF;  -- action code is null vs. not null
12248 
12249           l_progress := '490';
12250 
12251           -- Select the maximum shipment num that exists on the release.
12252           -- Update the shipment num in the interface table to be the
12253           -- requisition line number + this maximum shipment num
12254 
12255 
12256           -- if a shipment matches, get the shipment
12257 
12258           get_shipment_num(
12259              x_need_by_date,
12260              x_deliver_to_location_id,
12261              x_destination_org_id,
12262              x_po_line_id,
12263              x_interface_line_num,
12264              x_requisition_line_id,
12265              x_interface_header_id,
12266              x_po_shipment_num,
12267              x_note_to_receiver,
12268              x_preferred_grade,
12269              x_vmi_flag,  -- VMI FPH
12270              x_consigned_flag,
12271              x_drop_ship_flag,     --  <DropShip FPJ>
12272              x_create_new_line,-- FPI GA
12273 			 p_group_shipments --<Bug 14608120 Autocreate GE ER>
12274 			 );
12275 
12276           update_shipment(
12277             x_interface_header_id,
12278             x_po_shipment_num,
12279             x_po_line_num,
12280             x_requisition_line_id,
12281             x_po_line_id,
12282             x_document_num,
12283             x_release_num,
12284             x_create_new_line, -- FPI GA
12285             x_row_id );
12286 
12287         END LOOP;
12288         CLOSE interface_lines;
12289 
12290       END IF;  -- If STANDARD/PLANNED/RELEASE
12291 
12292     END IF;  -- of same  as REQUISITION mode
12293 
12294   END IF;  -- of PO mode
12295 
12296   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12297         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
12298   END IF;
12299 EXCEPTION
12300   WHEN NO_DATA_FOUND THEN
12301     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12302         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12303                             p_token    => l_progress,
12304                             p_message  => 'Exception block: NO_DATA_FOUND: '||SQLERRM);
12305     END IF;
12306      null;
12307   WHEN OTHERS THEN
12308     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12309         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12310                            p_progress => l_progress||'_main');
12311     END IF;
12312      po_message_s.sql_error('GROUP INTERFACE LINES',l_progress,sqlcode);
12313      wrapup(x_interface_header_id);
12314      raise;
12315 END group_interface_lines;
12316 
12317 
12318 -- Bug 2875346 start.
12319 /**
12320  * Private Function: has_one_time_location
12321  * Effects: Checks if the requisition line p_req_line_id has a one-time
12322  *   location.
12323  * Returns: TRUE if the requisition line has a one-time location
12324  *          FALSE otherwise
12325  */
12326 FUNCTION has_one_time_location(p_req_line_id IN NUMBER)
12327     RETURN BOOLEAN
12328 IS
12329 
12330 l_api_name CONSTANT VARCHAR2(30) := 'has_one_time_location';
12331 l_flag VARCHAR2(1);
12332 l_progress VARCHAR2(3) := '000';                    --< Bug 3210331 >
12333 
12334 BEGIN
12335     l_progress := '000';
12336 
12337     IF (p_req_line_id IS NOT NULL) THEN
12338 
12339         -- Query if this req line has a one-time location attachment, which
12340         -- indicates that the req line is for a one-time location.
12341         SELECT 'Y'
12342           INTO l_flag
12343           FROM fnd_attached_documents
12344          WHERE entity_name = 'REQ_LINES'
12345            AND pk1_value = to_char(p_req_line_id)
12346            AND pk2_value = 'ONE_TIME_LOCATION'
12347            AND rownum = 1;
12348 
12349         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12350             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12351                                 p_token    => l_progress,
12352                                 p_message  => 'Req line '||p_req_line_id||' has one-time attachment');
12353         END IF;
12354 
12355         RETURN TRUE;
12356 
12357     ELSE
12358 
12359         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12360             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12361                                 p_token    => l_progress,
12362                                 p_message  => 'Req line is null');
12363         END IF;
12364         RETURN FALSE;
12365 
12366     END IF;
12367 
12368 EXCEPTION
12369     WHEN NO_DATA_FOUND THEN
12370         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12371             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12372                                 p_token    => l_progress,
12373                                 p_message  => 'NO_DATA_FOUND: No one-time attachment for req line '||p_req_line_id);
12374         END IF;
12375         RETURN FALSE;
12376     WHEN OTHERS THEN
12377         IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12378             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12379                                p_progress => l_progress);
12380         END IF;
12381         RETURN FALSE;
12382 END has_one_time_location;
12383 -- Bug 2875346 end.
12384 
12385 /*
12386  * <Bug 14608120 Autocreate GE ER>
12387  * Private Function: is_wip_enabled
12388  * Effects: Checks if the requisition line p_req_line_id has beed created
12389  *          from work order.
12390  * Returns: TRUE if the requisition line has been created from work order
12391  *          FALSE otherwise.
12392  */
12393 
12394 FUNCTION is_wip_enabled(p_req_line_id IN NUMBER)
12395     RETURN BOOLEAN
12396 IS
12397 
12398 l_api_name CONSTANT VARCHAR2(30) := 'is_wip_enabled';
12399 l_flag VARCHAR2(1);
12400 l_progress VARCHAR2(3) := '000';                    --< Bug 3210331 >
12401 
12402 BEGIN
12403     l_progress := '000';
12404 
12405     IF (p_req_line_id IS NOT NULL) THEN
12406 
12407         -- Check whether the Req has been created from wip.
12408 
12409 		SELECT 'Y'
12410 		  INTO l_flag
12411 		  FROM po_requisition_lines_all
12412 		 WHERE requisition_line_id = p_req_line_id
12413 		 AND wip_entity_id IS NOT NULL;
12414 
12415 
12416         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12417             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12418                                 p_token    => l_progress,
12419                                 p_message  => 'Req line '||p_req_line_id||' is wip enabled');
12420         END IF;
12421 
12422         RETURN TRUE;
12423 
12424     ELSE
12425 
12426         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12427             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12428                                 p_token    => l_progress,
12429                                 p_message  => 'Req line is null');
12430         END IF;
12431         RETURN FALSE;
12432 
12433     END IF;
12434 
12435 EXCEPTION
12436     WHEN NO_DATA_FOUND THEN
12437         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12438             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12439                                 p_token    => l_progress,
12440                                 p_message  => 'NO_DATA_FOUND: No wip entity for req line '||p_req_line_id);
12441         END IF;
12442         RETURN FALSE;
12443     WHEN OTHERS THEN
12444         IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12445             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12446                                p_progress => l_progress);
12447         END IF;
12448         RETURN FALSE;
12449 END is_wip_enabled;
12450 
12451 
12452 /* ============================================================================
12453      NAME: GET_SHIPMENT_NUM
12454      DESC: Get Shipment Number
12455      ARGS: x_interface_header_id IN number
12456      ALGR:
12457    ==========================================================================*/
12458 PROCEDURE get_shipment_num(x_need_by_date IN DATE, x_deliver_to_location_id IN NUMBER,
12459          x_destination_org_id IN NUMBER,
12460          x_po_line_id IN NUMBER,
12461          x_po_line_num IN NUMBER,
12462          x_requisition_line_id IN NUMBER,
12463                x_interface_header_id IN NUMBER,
12464          x_po_shipment_num IN OUT NOCOPY number,
12465                  x_note_to_receiver IN varchar2,
12466                            x_preferred_grade IN VARCHAR2,      -- Bug 1548597
12467                            x_vmi_flag   IN  VARCHAR2 ,         -- VMI FPH
12468                            x_consigned_flag IN VARCHAR2,       -- CONSIGNED FPI
12469                            x_drop_ship_flag IN VARCHAR2,       --  <DropShip FPJ>
12470                            x_create_new_line OUT NOCOPY VARCHAR2,  -- GA FPI
12471 						   x_group_shipments IN VARCHAR2 DEFAULT NULL --<Bug 14608120 Autocreate GE ER>
12472 						   ) IS
12473 
12474  x_ship_to_location_id number;
12475 x_receipt_required_flag varchar2(1);
12476 x_so_line_id number:='';
12477 x_so_line_id_from_shipment number:='';
12478 x_so_line_id_from_req_line number:='';
12479 x_line_location_to_check number:='';
12480 x_req_line_to_check number:='';
12481 
12482 --Added for Bug# 1512955
12483 x_check_doc_sub_type  varchar2(25);
12484 
12485 /* Bug 3201308 start */
12486  l_needby_prf  varchar2(1);
12487  l_shipto_prf  varchar2(1);
12488 /* Bug 3201308 end */
12489 l_api_name CONSTANT VARCHAR2(30) := 'get_shipment_num';     --< Bug 3210331 >
12490 l_progress VARCHAR2(3) := '000';                            --< Bug 3210331 >
12491 
12492 l_po_line_id  NUMBER;  -- bug2788115
12493 
12494 l_group_shipments VARCHAR2(1); --<Bug 14608120 Autocreate GE ER>
12495 
12496 BEGIN
12497    IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12498         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
12499    END IF;
12500 
12501    /* Bug 3201308 start */
12502    /* Get the profile option values to determine grouping criteria */
12503 
12504      l_needby_prf := fnd_profile.value('PO_NEED_BY_GROUPING');
12505      l_shipto_prf := fnd_profile.value('PO_SHIPTO_GROUPING');
12506 
12507    /* Bug 3201308 end */
12508 
12509    /* OE drop ship requirement
12510    ** Do not consolidate any shipments linked to a sales order
12511    ** Neither add them to existing shipments
12512    ** or let other shipments add to them
12513    */
12514 
12515    --<DropShip FPJ Start>
12516    --Removed call to oe_drop_ship_grp.req_line_is_drop_ship, instead use x_drop_ship_flag
12517    --Bug 7312562
12518    --Moving this code to the end of the procedure.
12519    --So that the same logic is used for Drop shipments also.
12520    --Ensuring that two drop shipments are not inserted into same shipment,
12521    --by setting x_po_shipment_num := -1;
12522    /*IF g_document_type = 'PO' AND x_drop_ship_flag = 'Y' THEN
12523      x_po_shipment_num := -1;
12524       x_create_new_line := 'Y';  --Bug 5568899
12525      return;
12526    END IF;*/
12527    --<DropShip FPJ End>
12528 
12529    l_progress := '010';
12530 
12531    -- Bug 2875346. Do not group shipments if the req has a one-time location.
12532    IF (has_one_time_location(x_requisition_line_id)) THEN
12533        x_po_shipment_num := -1;
12534        --Bug 7312562
12535        IF g_document_type = 'PO' AND x_drop_ship_flag = 'Y' THEN
12536           x_create_new_line := 'Y';
12537        END IF;
12538        IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12539             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12540                                 p_token    => l_progress,
12541                                 p_message  => 'One-time location. Shipment num = -1');
12542        END IF;
12543        RETURN;
12544    END IF;
12545    -- Bug 2875346 end.
12546 
12547    x_ship_to_location_id := -1;
12548    l_progress:='020';
12549    x_ship_to_location_id := get_ship_to_loc(x_deliver_to_location_id);  -- FPI
12550 
12551    x_po_shipment_num := -1;
12552 
12553    IF ((g_document_subtype='STANDARD' OR g_document_subtype='PLANNED')
12554   AND g_document_type = 'PO') THEN
12555 
12556       l_progress:='030';
12557 
12558       /* Consigned FPI start : split the following select to determine if a new line
12559          is to be created or just a new shipment */
12560 
12561      -- Bug 3201308 : Further split the select into 3 selects to chenck
12562      -- matching for need by date ,ship to and rest of the information
12563 
12564      -- Bug 2757524 Do not execute this select if x_po_line_id is null
12565 
12566       IF x_po_line_id is not null THEN
12567 
12568       l_progress:='040';
12569       BEGIN
12570 
12571          -- SQL WHAT : compares the existing shipment values with the values from the req
12572          -- SQL WHY : to create a new line if the need by is different based on the profile
12573 
12574          SELECT PLL.shipment_num
12575           ,PLL.line_location_id
12576          INTO   x_po_shipment_num
12577     ,x_line_location_to_check
12578          FROM   PO_LINE_LOCATIONS_ALL    PLL  --<Shared Proc FPJ>
12579          WHERE  PLL.PO_LINE_ID = x_po_line_id
12580 -- bug 4599140 (included the following OR condition so that the SQL works correctly
12581 -- for null need_by_date)
12582          AND    (( to_char(PLL.need_by_date-(to_number(substr(to_char(PLL.need_by_date,
12583                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
12584                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
12585                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
12586                                  )
12587                OR
12588                   (PLL.need_by_date is NULL AND x_need_by_date is NULL)
12589                   )
12590          AND    ROWNUM = 1
12591          FOR UPDATE OF PLL.QUANTITY;
12592 
12593          EXCEPTION
12594             WHEN NO_DATA_FOUND THEN
12595                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12596                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12597                                         p_token    => l_progress,
12598                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12599                 END IF;
12600               x_po_shipment_num := -1;
12601               if nvl(l_needby_prf,'Y') = 'Y' then   -- Bug 3201308
12602                x_create_new_line := 'Y';
12603               end if;
12604             WHEN OTHERS THEN
12605                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12606                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12607                                        p_progress => l_progress);
12608                 END IF;
12609           wrapup(x_interface_header_id);
12610     RAISE;
12611 
12612       END;
12613         -- Bug 3534897 : added nvl to create new line flag
12614         IF x_po_shipment_num <> -1 and nvl(x_create_new_line,'N') <> 'Y' THEN
12615           l_progress:='050';
12616           BEGIN
12617 
12618          -- SQL WHAT : compares the existing shipment values with the values from the req
12619          -- SQL WHY : to create a new line if ship to is different based on the value of the
12620          --           profile
12621 
12622          SELECT PLL.shipment_num
12623           ,PLL.line_location_id
12624          INTO   x_po_shipment_num
12625     ,x_line_location_to_check
12626          FROM   PO_LINE_LOCATIONS_ALL    PLL  --<Shared Proc FPJ>
12627          WHERE  PLL.PO_LINE_ID = x_po_line_id
12628          AND    PLL.SHIP_TO_LOCATION_ID = x_ship_to_location_id
12629          AND    PLL.SHIP_TO_ORGANIZATION_ID =
12630             x_destination_org_id
12631          AND    ROWNUM = 1
12632          FOR UPDATE OF PLL.QUANTITY;
12633 
12634          EXCEPTION
12635             WHEN NO_DATA_FOUND THEN
12636                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12637                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12638                                         p_token    => l_progress,
12639                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12640                 END IF;
12641               x_po_shipment_num := -1;
12642               if nvl(l_shipto_prf,'Y') = 'Y' then  -- Bug 3201308
12643                x_create_new_line := 'Y';
12644               end if;
12645             WHEN OTHERS THEN
12646                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12647                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12648                                        p_progress => l_progress);
12649                 END IF;
12650           wrapup(x_interface_header_id);
12651     RAISE;
12652 
12653           END;
12654         END IF;
12655 
12656         -- Bug 3534897 : added nvl to create new line flag
12657         IF x_po_shipment_num <> -1 and nvl(x_create_new_line,'N') <> 'Y' THEN
12658           l_progress:='060';
12659           BEGIN
12660 
12661          -- SQL WHAT : compares the exixting shipment values with the values from the req
12662          -- SQL WHY : to create a new line if its a drop ship line or consigned flag is
12663          --           different
12664 
12665          SELECT PLL.shipment_num
12666           ,PLL.line_location_id
12667          INTO   x_po_shipment_num
12668     ,x_line_location_to_check
12669          FROM   PO_LINE_LOCATIONS_ALL    PLL  --<Shared Proc FPJ>
12670          WHERE  PLL.PO_LINE_ID = x_po_line_id
12671          AND    nvl(PLL.drop_ship_flag, 'N') <> 'Y' --<DropShip FPJ> cannot add to Drop Ship Shipments
12672          AND   nvl(PLL.CONSIGNED_FLAG,'N') = nvl(x_consigned_flag,'N')
12673          AND    ROWNUM = 1
12674          FOR UPDATE OF PLL.QUANTITY;
12675 
12676          EXCEPTION
12677             WHEN NO_DATA_FOUND THEN
12678                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12679                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12680                                         p_token    => l_progress,
12681                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12682                 END IF;
12683               x_po_shipment_num := -1;
12684 
12685 	      /* Bug 14796195
12686 	      In case of drop shipments flow, the line level grouping
12687 	      should happen based on the profile options value.
12688 	      But the shipments will not be grouped. */
12689 
12690 	      if nvl(l_needby_prf,'Y') = 'Y' or nvl(l_shipto_prf,'Y') = 'Y' then
12691 	        x_create_new_line := 'Y';
12692               end if;
12693 
12694 	      /* Bug 14796195 */
12695 
12696             WHEN OTHERS THEN
12697                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12698                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12699                                        p_progress => l_progress);
12700                 END IF;
12701           wrapup(x_interface_header_id);
12702     RAISE;
12703 
12704           END;
12705         END IF;
12706 
12707       END IF;  -- end of po line id not null check
12708 
12709       IF x_po_shipment_num <> -1 THEN
12710          l_progress:='070';
12711          BEGIN
12712 
12713          -- SQL WHAT : compares the exixting shipment values with the values from the req
12714          -- SQL WHY : if the above values match then we need to determine if we need to create
12715          --           a new shipment or not
12716 
12717          SELECT PLL.shipment_num
12718          INTO   x_po_shipment_num
12719          FROM   PO_LINE_LOCATIONS_ALL    PLL,  --<Shared Proc FPJ>
12720                 PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
12721                 PO_SYSTEM_PARAMETERS_ALL     PSP  --<Shared Proc FPJ>
12722          WHERE  PLL.LINE_LOCATION_ID = x_line_location_to_check
12723          AND    PRL.REQUISITION_LINE_ID = x_requisition_line_id
12724    AND    rtrim(nvl(PLL.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
12725          AND    PLL.SHIPMENT_TYPE in ('STANDARD', 'SCHEDULED',
12726             'BLANKET')
12727          AND    NVL(PLL.ENCUMBERED_FLAG,'N') = 'N'
12728          AND    NVL(PLL.CANCEL_FLAG,'N') = 'N'
12729          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)
12730          AND    PLL.ACCRUE_ON_RECEIPT_FLAG =
12731                 decode(interface.transaction_flow_header_id, NULL,  --<Shared Proc FPJ>
12732                  decode(prl.destination_type_code,'EXPENSE',
12733                      decode(psp.expense_accrual_code,'PERIOD END','N',
12734                             decode(nvl(item.receipt_required_flag,
12735                                    nvl(interface.receipt_required_flag,
12736                                    nvl(vendor.receipt_required_flag,
12737                                    nvl(params.receiving_flag,'N')))),
12738                             'N','N','Y')),'Y'), 'Y')  --<Shared Proc FPJ>
12739 -- start of 1548597
12740          AND
12741                (
12742                 ( PLL.PREFERRED_GRADE IS NULL AND  x_preferred_grade IS NULL )
12743                  OR
12744                 (  PLL.PREFERRED_GRADE = x_preferred_grade )
12745                 )
12746 -- end of 1548597
12747          AND    NVL(PLL.VMI_FLAG, 'N')  =  NVL(x_vmi_flag, 'N')          --  VMI
12748          AND    ROWNUM = 1
12749          FOR UPDATE OF PLL.QUANTITY;
12750 
12751          EXCEPTION
12752             WHEN NO_DATA_FOUND THEN
12753                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12754                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12755                                         p_token    => l_progress,
12756                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12757                 END IF;
12758               x_po_shipment_num := -1;
12759             WHEN OTHERS THEN
12760                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12761                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12762                                        p_progress => l_progress);
12763                 END IF;
12764           wrapup(x_interface_header_id);
12765     RAISE;
12766 
12767       END;
12768       END IF;
12769       /* Consigned FPI end */
12770 
12771       /* OE Drop Ship
12772       ** Make sure not to add to  dropship related shipment.
12773       */
12774       IF x_po_shipment_num <> -1 THEN
12775           l_progress:='080';
12776    x_so_line_id_from_shipment:=
12777           OE_DROP_SHIP_GRP.PO_Line_Location_Is_Drop_Ship(x_line_location_to_check);
12778    IF x_so_line_id_from_shipment IS NOT NULL THEN
12779       x_po_shipment_num := -1;
12780          END IF;
12781       END IF;
12782 
12783    ELSIF (g_document_type = 'RFQ') THEN
12784 
12785       l_progress:='090';
12786       BEGIN
12787 
12788          SELECT PLL.shipment_num
12789          INTO   x_po_shipment_num
12790          FROM   PO_LINE_LOCATIONS_ALL    PLL,  --<Shared Proc FPJ>
12791                 PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
12792                 PO_SYSTEM_PARAMETERS_ALL     PSP  --<Shared Proc FPJ>
12793          WHERE  PLL.PO_LINE_ID = x_po_line_id
12794          AND    PRL.REQUISITION_LINE_ID = x_requisition_line_id
12795          --Bug4599140 (included the following OR condition so that the SQL works correctly
12796          --for null need by date)
12797          AND    ( ( to_char(PLL.need_by_date-(to_number(substr(to_char(PLL.need_by_date,
12798                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
12799                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
12800                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
12801                                  )
12802                   OR
12803                   (PLL.need_by_date is NULL AND x_need_by_date is NULL)
12804                 )
12805    AND    rtrim(nvl(PLL.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
12806          AND    PLL.SHIP_TO_LOCATION_ID = x_ship_to_location_id
12807          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12808          AND    ROWNUM = 1
12809          FOR UPDATE OF PLL.QUANTITY;
12810 
12811          EXCEPTION
12812             WHEN NO_DATA_FOUND THEN
12813                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12814                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12815                                         p_token    => l_progress,
12816                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12817                 END IF;
12818               x_po_shipment_num := -1;
12819             WHEN OTHERS THEN
12820                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12821                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12822                                        p_progress => l_progress);
12823                 END IF;
12824        wrapup(x_interface_header_id);
12825        RAISE;
12826 
12827       END;
12828 
12829    ELSE /* Release */
12830 
12831       l_progress:='100';
12832 
12833       x_po_shipment_num := -1;
12834 
12835       BEGIN
12836 
12837          SELECT por.po_release_id
12838            INTO g_po_release_id
12839            FROM po_releases_all por,  --<Shared Proc FPJ>
12840                 po_headers_interface phi
12841           WHERE phi.interface_header_id = x_interface_header_id
12842             AND phi.release_num = por.release_num
12843             AND phi.po_header_id = por.po_header_id
12844             AND NVL(por.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12845             FOR UPDATE OF por.approved_flag;
12846 
12847          EXCEPTION
12848            WHEN NO_DATA_FOUND THEN
12849 	   --Bug5584718(we need to clear g_po_release_id)
12850                 g_po_release_id := null;
12851                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12852                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12853                                         p_token    => l_progress,
12854                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12855                 END IF;
12856            WHEN OTHERS THEN
12857                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12858                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12859                                        p_progress => l_progress);
12860                 END IF;
12861        wrapup(x_interface_header_id);
12862        RAISE;
12863 
12864       END;
12865 
12866       l_progress := '105';
12867 
12868       -- bug2788115 START
12869       -- Derive po_line_id if only line number is provided
12870 
12871       IF (x_po_line_num <> -1 AND x_po_line_id IS NULL) THEN
12872 
12873           PO_DEBUG.debug_stmt
12874           ( p_log_head => g_log_head || l_api_name,
12875             p_token    => l_progress,
12876             p_message  => 'Derive po_line_id from line num ' || x_po_line_num
12877           );
12878 
12879           SELECT POL.po_line_id
12880           INTO   l_po_line_id
12881           FROM   po_headers_interface PHI,
12882                  po_lines_all POL
12883           WHERE  PHI.interface_header_id = x_interface_header_id
12884           AND    PHI.po_header_id = POL.po_header_id
12885           AND    POL.line_num = x_po_line_num;
12886       ELSE
12887           l_po_line_id := x_po_line_id;
12888       END IF;
12889 
12890       -- bug2788115 END
12891 
12892       l_progress:='110';
12893       BEGIN
12894 
12895     --<bug#5050294 START>
12896     --As per the HLD.
12897     --Only Requisition grouping will be available for the new Service line types.
12898     --That is why we cannot group req lines withe RATE OR FIXED PRICE line types
12899     --onto the same shipment.
12900     --<bug#5050294 END>
12901 
12902          SELECT PLL.shipment_num
12903                ,PLL.line_location_id
12904          INTO   x_po_shipment_num,
12905                 x_line_location_to_check
12906          FROM   PO_LINE_LOCATIONS_ALL    PLL,  --<Shared Proc FPJ>
12907                 PO_LINES_ALL POL, --<bug#5050294>
12908                 PO_LINE_TYPES PLT --<bug#5050294>
12909          WHERE  POL.PO_LINE_ID = l_po_line_id  -- bug2788115
12910          AND    POL.po_line_id = PLL.po_line_id --<bug#5050294>
12911          AND    POL.line_type_id = PLT.line_type_id --<bug#5050294>
12912          AND    PLT.order_type_lookup_code NOT IN ('RATE', 'FIXED PRICE')--<bug#5050294>
12913          AND    PLL.po_release_id = g_po_release_id
12914  --Bug 4599140 (included the following OR condition so that the SQL works correctly
12915  --for null need by date)
12916          AND    ( ( to_char(PLL.need_by_date-(to_number(substr(to_char(PLL.need_by_date,
12917                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
12918                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
12919                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
12920                                  )
12921                   OR
12922                   (PLL.need_by_date is NULL AND x_need_by_date is NULL)
12923                )
12924          AND    nvl(PLL.drop_ship_flag, 'N') <> 'Y' --<DropShip FPJ> cannot add to Drop Ship Shipments
12925          --togeorge 09/27/2000
12926    --added note to receiver
12927    --AND    rtrim(PLL.note_to_receiver) = rtrim(x_note_to_receiver)
12928    --Bug# 1867976,togeorge, 07/06/2001
12929    --added nvl
12930    AND    rtrim(nvl(PLL.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
12931          AND    PLL.SHIP_TO_LOCATION_ID = x_ship_to_location_id
12932          AND    PLL.SHIP_TO_ORGANIZATION_ID =
12933             x_destination_org_id
12934          AND    PLL.SHIPMENT_TYPE in ('STANDARD', 'SCHEDULED',
12935             'BLANKET')
12936          AND    NVL(PLL.ENCUMBERED_FLAG,'N') = 'N'
12937          AND    NVL(PLL.CANCEL_FLAG,'N') = 'N'
12938 -- start of 1548597
12939          AND
12940                (
12941                 ( PLL.PREFERRED_GRADE IS NULL AND  x_preferred_grade IS NULL )
12942                  OR
12943                 (  PLL.PREFERRED_GRADE = x_preferred_grade )
12944                 )
12945 -- end of 1548597
12946          AND    NVL(PLL.VMI_FLAG, 'N')  =  NVL(x_vmi_flag, 'N')          --  VMI FPH
12947          AND    nvl(PLL.CONSIGNED_FLAG,'N') = nvl(x_consigned_flag,'N')  -- CONSIGNED FPI
12948          AND    ROWNUM = 1
12949          FOR UPDATE OF PLL.QUANTITY;
12950 
12951 
12952          EXCEPTION
12953             WHEN NO_DATA_FOUND THEN
12954                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12955                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12956                                         p_token    => l_progress,
12957                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12958                 END IF;
12959               x_po_shipment_num := -1;
12960             WHEN OTHERS THEN
12961                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12962                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12963                                        p_progress => l_progress);
12964                 END IF;
12965        wrapup(x_interface_header_id);
12966        RAISE;
12967 
12968       END;
12969 
12970       IF x_po_shipment_num <> -1 THEN
12971           l_progress:='120';
12972    x_so_line_id_from_shipment:=
12973           OE_DROP_SHIP_GRP.PO_Line_Location_Is_Drop_Ship(x_line_location_to_check);
12974    IF x_so_line_id_from_shipment IS NOT NULL THEN
12975       x_po_shipment_num := -1;
12976          END IF;
12977       END IF;
12978 
12979    END IF;
12980 
12981    IF (x_po_shipment_num = -1) and (g_document_type = 'PO') THEN
12982 
12983       /*
12984       ** Get the receipt required flag that
12985       ** will be inserted for the shipment.
12986       */
12987       l_progress:='130';
12988 
12989       /* Bug No. 1362044. We were not correctly considering the
12990     Accrue on Recepit Flag when grouping the shipments. Modified this logic .
12991     This part of the code gets the current Accrue on Receipt flag which will
12992     be compared with the other records in the interface table to see if
12993     they can be grouped together .
12994     Also added po_requisition_lines to the join to get the destination_type_code
12995     also added the outer join on po_vendors
12996     */
12997     /* Bug # 2224446, Autocreate was not grouping Req. lines when two req.
12998     with the same line details was entered. This happened when they don't
12999     Enter a Item in the lines block. We were not considering that the Item
13000     can be NULL when grouping shipment line. Used outer join on
13001     mtl_system_items when Checking for Item details. */
13002 
13003     --<bug#5050294 START>
13004     --As per the HLD.
13005     --Only Requisition grouping will be available for the new Service line types.
13006     --That is why we cannot group req lines withe RATE OR FIXED PRICE line types
13007     --onto the same shipment.
13008     --<bug#5050294 END>
13009 
13010       BEGIN
13011          SELECT DECODE(PRL.destination_type_code,
13012                       'EXPENSE',
13013                         decode(nvl(msi.receipt_required_flag,
13014                       nvl(plt.receiving_flag,
13015                        nvl(pov.receipt_required_flag,
13016                         nvl(psp.receiving_flag, 'N')))) ,'N','N',
13017                                decode(psp.expense_accrual_code,'PERIOD END', 'N', 'Y')),
13018                        'INVENTORY', 'Y',
13019                        'SHOP FLOOR','Y')
13020          INTO   x_receipt_required_flag
13021          FROM   po_lines_interface pli,
13022                 po_headers_interface phi,
13023                     po_requisition_lines_all prl,  --<Shared Proc FPJ>
13024                 mtl_system_items msi,
13025                 po_line_types plt,
13026                 po_vendors pov,
13027                 po_system_parameters_all psp,  --<Shared Proc FPJ>
13028                 financials_system_params_all fsp  --<Shared Proc FPJ>
13029          WHERE  pli.item_id = msi.inventory_item_id(+)
13030            AND  nvl(msi.organization_id,fsp.inventory_organization_id)=
13031              fsp.inventory_organization_id
13032            AND  pli.line_type_id = plt.line_type_id
13033            AND PLT.order_type_lookup_code NOT IN ('RATE', 'FIXED PRICE')--<bug#5050294>
13034            AND  phi.vendor_id = pov.vendor_id(+)
13035            AND  phi.interface_header_id =
13036         pli.interface_header_id
13037            AND  pli.interface_header_id =
13038                             phi.interface_header_id
13039            AND  prl.requisition_line_id = pli.requisition_line_id
13040            AND  pli.requisition_line_id =
13041                             x_requisition_line_id
13042            AND  NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
13043            AND  NVL(fsp.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
13044 
13045       EXCEPTION
13046            WHEN NO_DATA_FOUND THEN
13047                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13048                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13049                                         p_token    => l_progress,
13050                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
13051                 END IF;
13052            WHEN OTHERS THEN
13053                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13054                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13055                                        p_progress => l_progress);
13056                 END IF;
13057            wrapup(x_interface_header_id);
13058      RAISE;
13059       END;
13060 
13061       l_progress:='140';
13062 
13063       IF (g_document_type = 'PO') THEN
13064 
13065         BEGIN
13066         /*
13067         ** See if a record that has just been inserted into the
13068         ** interface table matches the shipment you are trying to create.
13069         */
13070         /* Bug # 2224446, Added outer join on mtl_system_items */
13071 /* Bug: 2348161.Changed the below SQL and removed the reference to the tables
13072                 HZ_LOCATIONS and HR_LOCATIONS and also the corresponding where
13073                 clause. Instead added a subquery to check for the location_id
13074                 to improve the performance
13075 */
13076 /* Bug 2466578. Changed the UNION to UNION ALL in the sub query to improve the
13077                 performance.
13078 */
13079 
13080         SELECT PLI.shipment_num
13081          ,PLI.requisition_line_id
13082          INTO   x_po_shipment_num
13083     ,x_req_line_to_check
13084          FROM   PO_LINES_INTERFACE   PLI,
13085             PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
13086                 --bug 1942696 hr_location changes to reflect the new view
13087       MTL_SYSTEM_ITEMS     MSI ,
13088                 PO_LINE_TYPES        PLT ,
13089                 PO_SYSTEM_PARAMETERS_ALL PSP ,  --<Shared Proc FPJ>
13090                 FINANCIALS_SYSTEM_PARAMS_ALL FSP,  --<Shared Proc FPJ>
13091                 PO_VENDORS           POV,
13092                 PO_HEADERS_INTERFACE PHI
13093          WHERE  PLI.LINE_NUM = x_po_line_num
13094      AND    PLI.shipment_num is not null
13095          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
13096          AND    NVL(fsp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
13097      AND    PLI.item_id = MSI.inventory_item_id(+)
13098          AND    nvl(MSI.organization_id,FSP.inventory_organization_id)=
13099                     FSP.inventory_organization_id
13100          AND    PLI.line_type_id = PLT.line_type_id
13101          AND    PHI.vendor_id  = POV.vendor_id (+)
13102          AND    PLI.interface_header_id =
13103                     PHI.interface_header_id
13104          AND    PRL.REQUISITION_LINE_ID <>
13105         x_requisition_line_id
13106    AND    PRL.requisition_line_id = PLI.requisition_line_id
13107   --Bug 4599140 (included the following OR condition so that the SQL works correctly
13108 	--for null need by date)
13109          AND   ( ( to_char(PLI.need_by_date-(to_number(substr(to_char(PLI.need_by_date,
13110                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
13111                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
13112                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
13113                                  )
13114                 OR
13115                 (PLI.need_by_date is NULL AND x_need_by_date is NULL)
13116                 )
13117          AND    nvl(PLI.drop_ship_flag, 'N') <> 'Y' --<DropShip FPJ> cannot add to Drop Ship Shipments
13118          --togeorge 09/27/2000
13119    --added note to receiver
13120    --AND    rtrim(PLI.note_to_receiver) = rtrim(x_note_to_receiver)
13121    --Bug# 1867976,togeorge, 07/06/2001
13122    --added nvl
13123    AND    rtrim(nvl(PLI.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
13124          --bug 1942696 hr_location changes to reflect the new view
13125        AND exists (select 'x'
13126                    from HR_LOCATIONS HRL
13127                    where PRL.deliver_to_location_id = HRL.location_id
13128                    and nvl(HRL.ship_to_location_id, HRL.location_id) = x_ship_to_location_id
13129                    UNION ALL
13130                    select 'x'
13131                    from HZ_LOCATIONS HZ
13132                    where PRL.deliver_to_location_id = HZ.location_id
13133                    and HZ.location_id = x_ship_to_location_id)
13134        AND    PRL.destination_organization_id = x_destination_org_id
13135      AND    DECODE(PRL.destination_type_code,
13136         'EXPENSE',
13137                       decode(nvl(msi.receipt_required_flag,
13138                             nvl(plt.receiving_flag,
13139                                  nvl(pov.receipt_required_flag,
13140                                   nvl(psp.receiving_flag,'N')))),'N','N',
13141                    decode(psp.expense_accrual_code, 'PERIOD END', 'N', 'Y')),
13142         'INVENTORY', 'Y',
13143         'SHOP FLOOR', 'Y')
13144           = x_receipt_required_flag
13145 -- start of 1548597
13146          AND
13147                (
13148                 ( PLI.PREFERRED_GRADE IS NULL AND  x_preferred_grade IS NULL )
13149                  OR
13150                 ( PLI.PREFERRED_GRADE = x_preferred_grade )
13151                 )
13152 -- end of 1548597
13153          AND    NVL(PLI.VMI_FLAG, 'N')  =  NVL(x_vmi_flag, 'N')   --  VMI FPH
13154          AND    nvl(PLI.CONSIGNED_FLAG,'N') = nvl(x_consigned_flag,'N')  --CONSIGNED FPI
13155          AND    ROWNUM = 1;
13156 /*Bug 2466578. Removed the ORDER BY Clause as we are using the ROWNUM = 1 condition and
13157                no need to order a single row. This is done to  improve the performance.
13158      ORDER BY shipment_num;
13159 */
13160 
13161      EXCEPTION
13162            WHEN NO_DATA_FOUND THEN
13163                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13164                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13165                                         p_token    => l_progress,
13166                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
13167                 END IF;
13168         x_po_shipment_num := -1;
13169            WHEN OTHERS THEN
13170                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13171                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13172                                        p_progress => l_progress);
13173                 END IF;
13174        wrapup(x_interface_header_id);
13175        RAISE;
13176         END;
13177 
13178         /* Make sure that the potential shipment is related
13179         ** to drop ship
13180         */
13181         IF x_po_shipment_num <> -1 THEN
13182           l_progress:='150';
13183     x_so_line_id_from_req_line:=
13184             OE_DROP_SHIP_GRP.PO_Line_Location_Is_Drop_Ship(x_req_line_to_check);
13185     IF x_so_line_id_from_req_line IS NOT NULL THEN
13186        x_po_shipment_num := -1;
13187           END IF;
13188         END IF;
13189 
13190       ELSE
13191         /* not PO type */
13192 
13193         l_progress:='160';
13194         BEGIN
13195         /*
13196         ** See if a record that has just been inserted into the
13197         ** interface table matches the shipment you are trying to create.
13198         */
13199 /* Bug: 2348161.Changed the below SQL and removed the reference to the tables
13200                 HZ_LOCATIONS and HR_LOCATIONS and also the corresponding where
13201                 clause. Instead added a subquery to check for the location_id
13202                 to improve the performance
13203 */
13204         SELECT PLI.shipment_num
13205          INTO   x_po_shipment_num
13206          FROM   PO_LINES_INTERFACE   PLI,
13207                 PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
13208       MTL_SYSTEM_ITEMS     MSI ,
13209                 PO_LINE_TYPES        PLT ,
13210                 PO_SYSTEM_PARAMETERS_ALL PSP ,  --<Shared Proc FPJ>
13211                 FINANCIALS_SYSTEM_PARAMS_ALL FSP,  --<Shared Proc FPJ>
13212                 PO_VENDORS           POV,
13213                 PO_HEADERS_INTERFACE PHI
13214          WHERE  PLI.LINE_NUM = x_po_line_num
13215      AND    PLI.shipment_num is not null
13216      AND    PLI.item_id = MSI.inventory_item_id
13217          AND    MSI.organization_id=
13218                     FSP.inventory_organization_id
13219          AND    PLI.line_type_id = PLT.line_type_id
13220          AND    PHI.vendor_id  = POV.vendor_id (+)
13221          AND    PLI.interface_header_id =
13222                     PHI.interface_header_id
13223          AND    PRL.REQUISITION_LINE_ID =
13224         x_requisition_line_id
13225          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
13226          AND    NVL(fsp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
13227          --Bug 4599140 (included the following OR condition so that the SQL works correctly
13228          --for null need by date)
13229          AND    ( ( to_char(PLI.need_by_date-(to_number(substr(to_char(PLI.need_by_date,
13230                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
13231                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
13232                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
13233                                  )
13234                    OR
13235                    (PLI.need_by_date is NULL AND x_need_by_date is NULL)
13236                )
13237          AND    nvl(PLI.drop_ship_flag, 'N') <> 'Y' --<DropShip FPJ> cannot add to Drop Ship Shipments
13238          --togeorge 09/27/2000
13239    --added note to receiver
13240    --AND    rtrim(PLI.note_to_receiver) = rtrim(x_note_to_receiver)
13241    --Bug# 1867976,togeorge, 07/06/2001
13242    --added nvl
13243    AND    rtrim(nvl(PLI.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
13244          --bug 1942696 hr_location changes to reflect the new view
13245        AND exists (select 'x'
13246                    from HR_LOCATIONS HRL
13247                    where PRL.deliver_to_location_id = HRL.location_id
13248                    and nvl(HRL.ship_to_location_id, HRL.location_id) = x_ship_to_location_id
13249                    UNION ALL
13250                    select 'x'
13251                    from HZ_LOCATIONS HZ
13252                    where PRL.deliver_to_location_id = HZ.location_id
13253                    and HZ.location_id = x_ship_to_location_id)
13254 -- start of 1548597
13255          AND
13256                (
13257                 ( PLI.PREFERRED_GRADE IS NULL AND  x_preferred_grade IS NULL )
13258                  OR
13259                 ( PLI.PREFERRED_GRADE = x_preferred_grade )
13260                 )
13261 -- end of 1548597
13262          AND    ROWNUM = 1
13263      ORDER BY shipment_num;
13264 
13265      EXCEPTION
13266            WHEN NO_DATA_FOUND THEN
13267                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13268                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13269                                         p_token    => l_progress,
13270                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
13271                 END IF;
13272         x_po_shipment_num := -1;
13273            WHEN OTHERS THEN
13274                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13275                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13276                                        p_progress => l_progress);
13277                 END IF;
13278        wrapup(x_interface_header_id);
13279        RAISE;
13280          END;
13281 
13282       END IF;
13283 
13284 /* Bug# 1512955: kagarwal
13285 ** Forward Fix of bug# 1502551
13286 --Added by jbalakri for  1502551 , RFQ's having multiple lines at the
13287 --shipment level even though requisitions are having same item,need by
13288 --date and ship to location.
13289 */
13290 
13291    ELSIF (x_po_shipment_num=-1) and (g_document_type='RFQ') THEN
13292 
13293      l_progress:='170';
13294      BEGIN
13295         /*
13296         ** See if a record that has just been inserted into the
13297         ** interface table matches the shipment you are trying to create.
13298         */
13299       begin
13300         l_progress:='180';
13301         SELECT document_subtype
13302         into x_check_doc_sub_type
13303         from
13304         PO_HEADERS_INTERFACE
13305         WHERE
13306         INTERFACE_HEADER_ID=x_interface_header_id;
13307       exception
13308       When others then
13309         IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13310             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13311                                p_progress => l_progress);
13312         END IF;
13313         wrapup(x_interface_header_id);
13314           raise;
13315       end;
13316        IF x_check_doc_sub_type='BID' then
13317 
13318 /* Bug: 2348161.Changed the below SQL and removed the reference to the tables
13319                 HZ_LOCATIONS and HR_LOCATIONS and also the corresponding where
13320                 clause. Instead added a subquery to check for the location_id
13321                 to improve the performance
13322 */
13323 
13324     /* Bug # 2286618, Autocreate was not grouping Req. lines when two req.
13325     with the same line details was entered. This happened when they Entered
13326     a One Time Item in the lines block. We were not considering that the Item
13327     can be NULL when grouping shipment line. Used outer join on
13328     mtl_system_items when Checking for Item details. */
13329 
13330          l_progress:='190';
13331          SELECT PLI.shipment_num
13332          INTO   x_po_shipment_num
13333          FROM   PO_LINES_INTERFACE   PLI,
13334                 PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
13335            --bug 1942696 hr_location changes to reflect the new view
13336                 MTL_SYSTEM_ITEMS     MSI ,
13337                 PO_LINE_TYPES        PLT ,
13338                 PO_SYSTEM_PARAMETERS_ALL PSP ,  --<Shared Proc FPJ>
13339                 FINANCIALS_SYSTEM_PARAMS_ALL FSP,  --<Shared Proc FPJ>
13340                 PO_VENDORS           POV,
13341                 PO_HEADERS_INTERFACE PHI
13342          WHERE  PLI.LINE_NUM = x_po_line_num
13343          AND    PLI.shipment_num is not null
13344          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
13345          AND    NVL(fsp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
13346          AND    PLI.item_id = MSI.inventory_item_id(+)
13347          AND    nvl(MSI.organization_id,FSP.inventory_organization_id) =
13348                     FSP.inventory_organization_id
13349          AND    PLI.line_type_id = PLT.line_type_id
13350          AND    PHI.vendor_id  = POV.vendor_id (+)
13351          AND    PLI.interface_header_id =
13352                     PHI.interface_header_id
13353 /* Bug# 1638668, forward fix of 1549754 */
13354 --changed by jbalakri  during testing of 1549754
13355        --AND    PRL.REQUISITION_LINE_ID =
13356        --       x_requisition_line_id
13357          AND    PRL.REQUISITION_LINE_ID <>
13358                         x_requisition_line_id
13359          AND PRL.requisition_line_id=PLI.requisition_line_id
13360 --end of change for 1549754
13361     --Bug 4599140 (included the following OR condition so that the SQL works correctly
13362     --for null need by date)
13363          AND    ( ( to_char(PLI.need_by_date-(to_number(substr(to_char(PLI.need_by_date,
13364                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
13365                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
13366                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
13367                                  )
13368                      OR
13369                      (PLI.need_by_date is NULL AND x_need_by_date is NULL)
13370                 )
13371          --bug 1942696 hr_location changes to reflect the new view
13372          AND exists (select 'x'
13373                      from HR_LOCATIONS HRL
13374                      where PRL.deliver_to_location_id = HRL.location_id
13375                      and nvl(HRL.ship_to_location_id, HRL.location_id) = x_ship_to_location_id
13376                      UNION ALL
13377                      select 'x'
13378                      from HZ_LOCATIONS HZ
13379                      where PRL.deliver_to_location_id = HZ.location_id
13380                      and HZ.location_id = x_ship_to_location_id)
13381          AND    ROWNUM = 1
13382          ORDER BY shipment_num;
13383        END IF;
13384          EXCEPTION
13385            WHEN NO_DATA_FOUND THEN
13386                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13387                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13388                                         p_token    => l_progress,
13389                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
13390                 END IF;
13391                   x_po_shipment_num := -1;
13392            WHEN OTHERS THEN
13393                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13394                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13395                                        p_progress => l_progress);
13396                 END IF;
13397              wrapup(x_interface_header_id);
13398              RAISE;
13399          END;
13400 
13401 --end of change
13402 
13403    END IF; -- end of grouping
13404    --Bug 7312562
13405    --Moving this code to the end of the procedure.
13406    --So that the same logic is used for Drop shipments also.
13407    --Ensuring that two drop shipments are not inserted into same shipment,
13408    --by setting x_po_shipment_num := -1;
13409    IF g_document_type = 'PO' AND x_drop_ship_flag = 'Y' THEN
13410      x_po_shipment_num := -1;
13411    END IF;
13412    /* <Bug 14608120 Autocreate GE ER>
13413     	Do not group shipments if the req is wip enabled.*/
13414 	   IF (is_wip_enabled(x_requisition_line_id)) THEN
13415 	     l_progress := '200';
13416 		 x_po_shipment_num := -1;
13417 		 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13418 		   PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13419 	                                   p_token    => l_progress,
13420 									   p_message  => 'Req is WIP enabled ');
13421 		 END IF;
13422 	   END IF;
13423 
13424      /*<Bug 14608120 Autocreate GE ER>
13425 	 14608120 Do not group shipments if the Group Shipments checkbox is checked.*/
13426 	 l_progress := '210';
13427 
13428 	 IF (x_group_shipments IS NULL) THEN
13429 	     SELECT psp.group_shipments_flag
13430 		 INTO l_group_shipments
13431 		 FROM po_system_parameters_all psp
13432 		 where NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99);
13433 	 ELSE
13434 	     l_group_shipments := x_group_shipments;
13435 	 END IF;
13436 
13437 	 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13438 		   PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13439 	                                   p_token    => l_progress,
13440 									   p_message  => 'l_group_shipments : '||l_group_shipments);
13441      END IF;
13442 
13443      IF (l_group_shipments = 'N' AND
13444 	      ((g_document_type = 'PO' and (g_document_subtype='STANDARD' OR g_document_subtype='PLANNED')) OR
13445 		  (g_document_subtype = 'RELEASE'))) THEN
13446        x_po_shipment_num := -1;
13447 	 END IF;
13448 
13449     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13450         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
13451     END IF;
13452 EXCEPTION
13453   WHEN NO_DATA_FOUND THEN
13454      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13455          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13456                              p_token    => l_progress||'_main',
13457                              p_message  => 'NO_DATA_FOUND: '||SQLERRM);
13458      END IF;
13459   WHEN OTHERS THEN
13460      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13461          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13462                             p_progress => l_progress);
13463      END IF;
13464      po_message_s.sql_error('get_shipment_num',l_progress,sqlcode);
13465      wrapup(x_interface_header_id);
13466      raise;
13467 END get_shipment_num;
13468 
13469 
13470 /* ============================================================================
13471      NAME: UPDATE_SHIPMENT
13472      DESC: Update shipment information in interface table
13473      ARGS: x_interface_header_id IN number
13474      x_po_shipment_num IN number
13475      ALGR:
13476    ==========================================================================*/
13477 PROCEDURE update_shipment(x_interface_header_id IN NUMBER,
13478          x_po_shipment_num IN number,
13479          x_po_line_num IN NUMBER,
13480          x_requisition_line_id IN NUMBER,
13481          x_po_line_id IN NUMBER,
13482                x_document_num IN VARCHAR2,
13483          x_release_num IN NUMBER,
13484                            x_create_new_line IN VARCHAR2,
13485                            x_row_id  IN VARCHAR2) IS
13486 x_shipment_num NUMBER;
13487 x_int_shipment_num NUMBER;
13488 x_line_num NUMBER;
13489 x_int_line_num NUMBER;
13490 l_api_name CONSTANT VARCHAR2(30) := 'update_shipment';      --< Bug 3210331 >
13491 l_progress VARCHAR2(3) := '000';                            --< Bug 3210331 >
13492 
13493 BEGIN
13494     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13495         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
13496     END IF;
13497 
13498       /* Shipment Exists */
13499       IF (x_po_shipment_num <> -1) THEN
13500 
13501          /*
13502          ** Shipment exists.
13503          ** A shipment associated with the purchase order
13504          ** line matches the requisition line information.
13505          */
13506 
13507         if x_requisition_line_id is not null then
13508          l_progress := '010';
13509          update po_lines_interface
13510             set shipment_num= x_po_shipment_num
13511           where interface_header_id=x_interface_header_id
13512             and requisition_line_id=x_requisition_line_id;
13513 
13514         else
13515          l_progress := '015';
13516           update po_lines_interface
13517             set shipment_num= x_po_shipment_num
13518           where interface_header_id=x_interface_header_id
13519             and rowid=x_row_id;
13520         end if;
13521 
13522       ELSE /* Shipment does not exist */
13523 
13524          /*
13525          ** Get the maximum shipment number in the po tables
13526          */
13527          l_progress := '020';
13528 
13529    IF (g_document_subtype = 'STANDARD'
13530     OR g_document_subtype = 'PLANNED' OR
13531              g_document_type = 'RFQ')
13532    THEN
13533 
13534            /* GA FPI start : if create new line parameter is 'Y' then we need to reset
13535               the shipment number and create a new line with one shipment */
13536 
13537             IF nvl(x_create_new_line,'N') = 'Y' and g_document_subtype = 'STANDARD' THEN
13538 
13539                x_int_shipment_num := 0;
13540                x_shipment_num     := 0;
13541 
13542                -- Bug 2757020 START
13543                -- In Add mode, PLI.line_num is set to the existing document
13544                -- line number. We need to generate a new line number.
13545 	       --Bug 6072900
13546 	       -- while Auto Creating PO with req lines with same need by dates from DropShip Sales Order
13547 	       -- the below condition is false for g_mode=NEW ,because of this req lines with same
13548                -- need-by-dates were combined into one line and one shipment .
13549 	       -- So commented the below condition.
13550 
13551                --IF (g_mode = 'ADD') THEN
13552                   -- Set PLI.line_num to the largest line number in use + 1.
13553 
13554                   l_progress := '030';
13555                   select nvl(max(line_num),0)
13556                    into x_line_num
13557                    from po_headers_all ph,  --<Shared Proc FPJ>
13558                         po_lines_all pl  --<Shared Proc FPJ>
13559                   where pl.po_header_id = ph.po_header_id
13560                     and ph.segment1 = x_document_num
13561                     AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
13562 
13563                   l_progress := '040';
13564                   select nvl(max(line_num),0)
13565                    into x_int_line_num
13566                    from po_lines_interface pli
13567                   where pli.interface_header_id = x_interface_header_id;
13568 
13569                   IF (x_line_num >= x_int_line_num) THEN
13570                      x_line_num := x_line_num;
13571                   ELSE
13572                      x_line_num := x_int_line_num;
13573                   END IF;
13574 
13575                   l_progress := '050';
13576                   update po_lines_interface
13577                   set    line_num = x_line_num + 1
13578                   where  interface_header_id = x_interface_header_id
13579                   and    requisition_line_id = x_requisition_line_id;
13580                -- Bug 6072900
13581                --END IF;
13582 
13583                -- Bug 2757020 END
13584 
13585             /* GA FPI end */
13586 
13587             ELSE
13588                l_progress := '060';
13589                select nvl(max(shipment_num),0)
13590                  into x_shipment_num
13591                  from po_line_locations_all poll  --<Shared Proc FPJ>
13592                 where poll.po_line_id = x_po_line_id
13593                   and poll.shipment_type in ('STANDARD', 'PLANNED', 'RFQ');
13594 
13595                -- Bug 605715, lpo, 01/05/98
13596                -- We now check to see if the line_num matches as well by
13597                -- appending an AND condition in the WHERE clause.
13598 
13599                l_progress := '070';
13600                /*
13601                ** Get the max shipment number already
13602                ** assigned in the interface table.
13603                */
13604                select nvl(max(shipment_num),0)
13605                into x_int_shipment_num
13606                from po_lines_interface pli
13607                where pli.interface_header_id = x_interface_header_id
13608                and pli.line_num = x_po_line_num;
13609 
13610               -- End of fix. Bug 605715, lpo, 01/05/98
13611             END IF; -- create new line
13612 
13613         ELSE
13614            l_progress := '080';
13615 
13616          select nvl(max(shipment_num),0)
13617          into   x_shipment_num
13618                from   po_headers_all ph,  --<Shared Proc FPJ>
13619                      po_line_locations_all poll,  --<Shared Proc FPJ>
13620                      po_releases_all pr  --<Shared Proc FPJ>
13621                where  ph.po_header_id = poll.po_header_id
13622                and    ph.segment1 = x_document_num
13623                and    pr.po_header_id = ph.po_header_id
13624                and    pr.release_num = x_release_num
13625                and    ph.type_lookup_code = 'BLANKET'
13626                and    poll.po_release_id=pr.po_release_id
13627                AND    NVL(pr.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
13628                AND    NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
13629 
13630                -- Bug 605715, lpo, 01/05/98
13631                -- For Releases, we don't care about the line_num.
13632 
13633                l_progress := '090';
13634                /*
13635                ** Get the max shipment number already
13636                ** assigned in the interface table.
13637                */
13638                select nvl(max(shipment_num),0)
13639                into x_int_shipment_num
13640                from po_lines_interface pli
13641                where pli.interface_header_id = x_interface_header_id;
13642 
13643                -- End of fix. Bug 605715, lpo, 01/05/98
13644 
13645    END IF;
13646 
13647          l_progress := '100';
13648 
13649          IF (x_shipment_num >= x_int_shipment_num) THEN
13650           x_shipment_num := x_shipment_num;
13651          ELSE
13652           x_shipment_num := x_int_shipment_num;
13653          END IF;
13654 
13655         if x_requisition_line_id is not null then
13656           l_progress := '110';
13657           update po_lines_interface
13658             set shipment_num = x_shipment_num + 1
13659           where interface_header_id=x_interface_header_id
13660             and requisition_line_id=x_requisition_line_id;
13661         else
13662           l_progress := '120';
13663           update po_lines_interface
13664             set shipment_num = x_shipment_num + 1
13665           where interface_header_id=x_interface_header_id
13666             and rowid=x_row_id;
13667         end if;
13668 
13669       END IF; /* Shipment Exists */
13670 
13671     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13672         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
13673     END IF;
13674 EXCEPTION
13675   WHEN NO_DATA_FOUND THEN
13676      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13677          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13678                              p_token    => l_progress||'_main',
13679                              p_message  => 'NO_DATA_FOUND: '||SQLERRM);
13680      END IF;
13681   WHEN OTHERS THEN
13682      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13683          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13684                             p_progress => l_progress);
13685      END IF;
13686      po_message_s.sql_error('update_shipment',l_progress,sqlcode);
13687      wrapup(x_interface_header_id);
13688      raise;
13689 
13690 END update_shipment;
13691 
13692 /* ============================================================================
13693      NAME: CALCULATE_LOCAL
13694      DESC: This procedure serve as a hook to the function of localization team.
13695 
13696    ==========================================================================*/
13697 
13698 PROCEDURE CALCULATE_LOCAL(document_type varchar2,
13699                           level_type    varchar2,
13700                           level_id      number
13701 
13702 ) IS
13703 
13704   l_cursor         integer;
13705   sqlstmt          varchar2(2000);
13706   l_jl_installed   varchar2(30);
13707   l_execute        integer;
13708   l_return         number;
13709   l_progress VARCHAR2(3) := '000';                          --< Bug 3210331 >
13710   l_api_name CONSTANT VARCHAR2(30) := 'calculate_local';    --< Bug 3210331 >
13711 BEGIN
13712  /* Bug4430300 Removed the references to the JL_BR packages */
13713 
13714   -- <Bug 8513167 START>
13715   -- Added call to JG_GLOBE_UTIL_PKG.process_po_globe_event
13716 
13717     IF g_debug_stmt THEN
13718         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
13719     END IF;
13720 
13721     ---------------------------------------------------
13722     -- Check whether the Regional Package is installed
13723     ---------------------------------------------------
13724     SELECT  DISTINCT 'Package Installed'
13725     INTO    l_jl_installed
13726     FROM    user_objects
13727     WHERE   object_name = 'JG_GLOBE_UTIL_PKG'
13728     AND     object_type = 'PACKAGE BODY';
13729 
13730     l_progress := '010';
13731     ---------------------------------------------------
13732     -- Execute dynamically the Regional Procedure
13733     ---------------------------------------------------
13734     sqlstmt := 'BEGIN  JG_GLOBE_UTIL_PKG.process_po_globe_event(:p_document_type,:p_level_type,:p_level_id);  END;';
13735 
13736     -- Create the SQL statement
13737     l_cursor := dbms_sql.open_cursor;
13738 
13739     l_progress := '020';
13740 
13741     -- Parse the SQL statement
13742     dbms_sql.parse (l_cursor, sqlstmt, dbms_sql.native);
13743 
13744     l_progress := '030';
13745     -- Define the variables
13746     dbms_sql.bind_variable(l_cursor, ':p_document_type', document_type);
13747     dbms_sql.bind_variable(l_cursor, ':p_level_type', level_type);
13748     dbms_sql.bind_variable(l_cursor, ':p_level_id', level_id);
13749 
13750     l_progress := '040';
13751     -- Execute the SQL statement
13752     l_execute := dbms_sql.execute(l_cursor);
13753 
13754     -- Get the return value (success)
13755     --  dbms_sql.variable_value(l_cursor, ':b_return', l_return);
13756 
13757     l_progress := '050';
13758     -- Close the cursor
13759     dbms_sql.close_cursor(l_cursor);
13760 
13761     IF g_debug_stmt THEN
13762         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
13763     END IF;
13764   -- <Bug 8513167 END>
13765 EXCEPTION
13766 
13767     WHEN no_data_found THEN
13768 
13769         ----------------------------------------
13770         -- Regional Procedure is not installed
13771         ----------------------------------------
13772         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13773             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13774                                 p_token    => l_progress,
13775                                 p_message  => 'NO_DATA_FOUND: '||SQLERRM);
13776         END IF;
13777 
13778     --<Bug 3336920 START>
13779     WHEN OTHERS THEN
13780 
13781         IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13782            PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13783                                p_progress => l_progress);
13784         END IF;
13785         RAISE;
13786     --<Bug 3336920 END>
13787 END CALCULATE_LOCAL;
13788 
13789 -- 2082757: Added this function:
13790 /* ============================================================================
13791      NAME: SOURCE_BLANKET_LINE
13792      DESC: Return the line number of that BPO line which matches the
13793            sourcing candidature criterion.
13794      ARGS: IN: x_po_header_id NUMBER : header id of source blanket PO
13795            IN: x_requisition_line_id NUMBER : id of the corresponding req line.
13796            IN: x_interface_line_num NUMBER : number from lines interface table
13797            IN: x_allow_different_uoms VARCHAR2 : If not 'Y', require the
13798              matching BPA line to have the same UOM as the requisition line.
13799            IN: p_purchasing_ou_id NUMBER : purchasing operating unit id
13800      ALGR:
13801            - For One-time item, item description of the BPO line should match
13802              that of requisition line.  For others, both item_id and description
13803              should match.
13804            - If there is no BPO line matching the description, then just match
13805              the item_id.
13806            - For any case above, if more than one candidate BPO lines pass the
13807              conditions, then pick the one having the minimum line_num
13808      See Bug 2082757 for details.
13809   ===========================================================================*/
13810 
13811 FUNCTION source_blanket_line(x_po_header_id IN NUMBER,
13812                              x_requisition_line_id IN NUMBER,
13813                              x_interface_line_num IN NUMBER,
13814                              x_allow_different_uoms IN VARCHAR2, -- Bug 2707576
13815                              p_purchasing_ou_id     IN NUMBER  --<Shared Proc FPJ>
13816                             ) RETURN NUMBER IS
13817 
13818     v_line_num NUMBER := null;
13819     x_item_id  number;
13820     x_inv_org_id  number;
13821     x_item_rev_control number := null;
13822 
13823    /* Bug: 2432506 Expriation of document should happen at the end of
13824            the expiration_date */
13825    /* Bug 3828673:Release was not created when the requisition line type is
13826       different from the source document line type.*/
13827 /* Bug 7492597 Added a condition to check for item description and category for one-time item
13828       so that valid GBPA line number is picked up for one-time item req line */
13829 	  /* Bug 9745707 : This bug was introduced because of Bug4541335 fix.
13830 
13831  	      As part of this fix,If the Req is being autocreated to a document/release to which it is already to Sourced to,
13832  	      then the Source Doc line number on Req was matched to the Current Doc line no,
13833  	      because of this, the system was nt picking up the valid blanket line in case the line to which Req was sourced to
13834  	      has expired.
13835 
13836  	      Modified the condition in such a way that If the Req is being autocreated to a document/release to which it is already to Sourced to,
13837  	      then
13838  	      1. take the line from the the Current Doc,which has  expiry date >= sysdate and it is same as the Source Doc line number on Req
13839  	      or
13840  	      2. the expiration date on the line should be greater than the need by date on the Req Line.
13841 
13842  	    */
13843 
13844     CURSOR c1 (p_po_header_id        IN NUMBER,
13845                p_requisition_line_id IN NUMBER,
13846                p_interface_line_num  IN NUMBER,
13847                p_item_rev_control    IN NUMBER,
13848                x_allow_different_uoms IN VARCHAR2 -- Bug 2707576
13849               ) IS
13850                             SELECT MIN(pol.line_num)
13851                             FROM  po_lines_all pol,
13852                                   po_requisition_lines_all prl  --<Shared Proc FPJ>
13853                             WHERE pol.po_header_id = p_po_header_id
13854                             AND   prl.requisition_line_id = p_requisition_line_id
13855                             AND   NVL(pol.cancel_flag,'N') = 'N'
13856                             AND   NVL(pol.closed_code,'OPEN') <> 'FINALLY CLOSED'
13857                             -- Bug 3828673 START
13858                             -- AND   pol.line_type_id = prl.line_type_id
13859                             AND   pol.order_type_lookup_code = prl.order_type_lookup_code
13860                             AND   pol.purchase_basis = prl.purchase_basis
13861                             AND   pol.matching_basis = prl.matching_basis
13862                             -- Bug 3828673 END
13863                             AND   nvl(pol.job_id,-999) = nvl(prl.job_id, -999) -- <SERVICES FPJ>
13864                             AND   ((pol.item_id = prl.item_id                        --bug 7492597
13865                                     and pol.item_description = prl.item_description
13866                                    )
13867                                    or (pol.item_id is null                                --bug 7492597 added for one-time item
13868                                        and prl.item_id is null                            --bug 7492597
13869                                        and pol.item_description = prl.item_description    --bug 7492597
13870                                        and pol.category_id = prl.category_id              --bug 7492597
13871                                        )
13872                                    )
13873                             AND   ((pol.item_revision IS NULL
13874                                    and prl.item_revision IS NULL)
13875                                    or  pol.item_revision = prl.item_revision
13876                                    or  (prl.item_revision is null  and p_item_rev_control = 1))
13877                             AND   (pol.transaction_reason_code IS NULL
13878                                    or pol.transaction_reason_code =
13879                                    NVL(prl.transaction_reason_code,
13880                                                 pol.transaction_reason_code))
13881 
13882          					-- Bug 9745707 starts
13883  	                                   AND   NVL(P_INTERFACE_LINE_NUM,POL.LINE_NUM) =  POL.LINE_NUM
13884  	                              AND ((---  CASE 1 : REQ IS NT SOURCED TO ANY DOC
13885  	                                     ( (PRL.BLANKET_PO_LINE_NUM IS NULL)					--Bug 16013325 : Added extra open-parenthesis
13886  	                                         OR
13887  	                                      ---  CASE 2 : REQ IS  SOURCED TO A DOC OTHER THAN THE CURRENT ONE
13888  	                                     (PRL.BLANKET_PO_LINE_NUM IS NOT NULL AND  PRL.BLANKET_PO_HEADER_ID <> P_PO_HEADER_ID) )  --Bug 16013325 : Added extra close-parenthesis
13889  	                                     -- IN CASE 1 AND 2, VALIDATE THE EXPIRY DATE WITH NEED BY DATE
13890  	                                     AND TRUNC(NVL(POL.EXPIRATION_DATE,SYSDATE + 1)) >= TRUNC(DECODE(POL.EXPIRATION_DATE,NULL,SYSDATE,NVL(PRL.NEED_BY_DATE,SYSDATE)))
13891  	                                     )
13892  	                                     OR
13893  	                                     --- CASE 3 : REQ IS ALREADY SOURCED TO THE DOCUMENT(CUURENT DOC)
13894  	                                     (PRL.BLANKET_PO_LINE_NUM IS NOT NULL AND  PRL.BLANKET_PO_HEADER_ID = P_PO_HEADER_ID
13895  	                                       -- IF THE REQ IS SOURCED TO THE DOC AND THE ALREADY SOURCED LINE IS VALID
13896  	                                     AND ((TRUNC(NVL(POL.EXPIRATION_DATE,SYSDATE + 1)) >= TRUNC(SYSDATE) AND PRL.BLANKET_PO_LINE_NUM = POL.LINE_NUM)
13897  	                                     -- IF THE REQ IS SOURCED TO THE DOC,BUT THE ALREADY SOURCED LINE IS INVALID,THEN TAKE THE OTHER VALID LINE FROM SOURCE DOCUMENT
13898  	                                     --OR TRUNC(NVL(POL.EXPIRATION_DATE,SYSDATE + 1)) >= TRUNC(DECODE(POL.EXPIRATION_DATE,NULL,SYSDATE, NVL(PRL.NEED_BY_DATE,SYSDATE))) ) --13876074
13899                                     --Bug 13876074, ensure to pick another source line
13900                                     --only if the current source line reference is not valid.
13901                                         OR ((NOT EXISTS (SELECT 1 FROM po_lines_all pol2
13902                                                       WHERE pol2.po_header_id = pol.po_header_id
13903                                                         AND TRUNC(NVL(pol2.expiration_date,SYSDATE + 1))
13904                                                             >= TRUNC(SYSDATE)
13905                                                         AND prl.blanket_po_line_num  = pol2.line_num))
13906                                              AND TRUNC(NVL(pol.expiration_date,SYSDATE + 1))
13907                                                  >= TRUNC(DECODE(pol.expiration_date,NULL,SYSDATE,
13908                                                                  NVL(prl.need_by_date,SYSDATE))))
13909                                        ) --end bug 13876074
13910  	                                     )
13911  	                               )
13912 
13913                             /*Bug4541335  AND   nvl(p_interface_line_num,pol.line_num) =
13914                                                                      pol.line_num
13915                             AND   trunc(nvl(pol.expiration_date,sysdate+1))
13916                                                                 >= trunc(sysdate)
13917            Bug4541335 start
13918        AND (p_InterFace_Line_num = pol.Line_num
13919              OR (p_InterFace_Line_num IS NULL
13920                  AND prl.Blanket_po_Header_Id = p_po_Header_Id
13921                  AND prl.Blanket_po_Line_num = pol.Line_num)
13922              OR (p_InterFace_Line_num IS NULL
13923                  AND (prl.Blanket_po_Header_Id <> p_po_Header_Id
13924                        OR prl.Blanket_po_Line_num IS NULL )))
13925        AND (((p_InterFace_Line_num IS NOT NULL
13926                OR (prl.Blanket_po_Header_Id = p_po_Header_Id
13927                    AND prl.Blanket_po_Line_num = pol.Line_num))
13928              AND Trunc(Nvl(pol.Expiration_Date,SYSDATE + 1)) >= Trunc(SYSDATE))
13929              OR ((p_InterFace_Line_num IS NULL
13930                   AND (prl.Blanket_po_Header_Id <> p_po_Header_Id
13931                         OR prl.Blanket_po_Line_num IS NULL ))
13932                  AND Trunc(Nvl(pol.Expiration_Date,SYSDATE + 1)) >= Trunc(DECODE(pol.Expiration_Date,NULL,SYSDATE,
13933                                                                                                      Nvl(prl.Need_By_Date,SYSDATE)))))
13934            Bug4541335 End */
13935 		   -- Bug 9745707 ends
13936 
13937            -- Bug 2707576 Start
13938            -- Require the BPA and req to have the same UOM
13939            -- if x_allow_different_uoms is not 'Y'.
13940         AND   (   (  NVL(POL.unit_meas_lookup_code,chr(0)) =
13941                                          decode ( x_allow_different_uoms,'Y',
13942                                                   NVL(POL.unit_meas_lookup_code,chr(0)),
13943                                                   PRL.unit_meas_lookup_code)
13944                                       )                       -- <SERVICES FPJ>
13945                                   OR  (   ( POL.unit_meas_lookup_code IS NULL )
13946                                       AND ( PRL.unit_meas_lookup_code IS NULL ) )
13947                                   );
13948 
13949                             -- Bug 2707576 End
13950 
13951    /* Bug: 2432506 Expriation of document should happen at the end of
13952            the expiration_date */
13953    /* Bug 3828673:Release was not created when the requisition line type is
13954       different from the source document line type.*/
13955    /* Bug 7492597 Added a condition to check for item description and category for one-time item
13956       so that valid GBPA line number is picked up for one-time item req line */
13957 
13958 	CURSOR c2 (p_po_header_id        IN NUMBER,
13959                p_requisition_line_id IN NUMBER,
13960                p_interface_line_num  IN NUMBER,
13961                p_item_rev_control    IN NUMBER,
13962                x_allow_different_uoms IN VARCHAR2 -- Bug 2707576
13963               ) IS
13964                             SELECT MIN(pol.line_num)
13965                             FROM  po_lines_all pol,
13966                                   po_requisition_lines_all prl  --<Shared Proc FPJ>
13967                             WHERE pol.po_header_id = p_po_header_id
13968                             AND   prl.requisition_line_id = p_requisition_line_id
13969                             AND   NVL(pol.cancel_flag,'N') = 'N'
13970                             AND   NVL(pol.closed_code,'OPEN') <> 'FINALLY CLOSED'
13971                             -- Bug 3828673 START
13972                             -- AND   pol.line_type_id = prl.line_type_id
13973                             AND   pol.order_type_lookup_code = prl.order_type_lookup_code
13974                             AND   pol.purchase_basis = prl.purchase_basis
13975                             AND   pol.matching_basis = prl.matching_basis
13976                             -- Bug 3828673 END
13977                             AND   nvl(pol.job_id,-999) = nvl(prl.job_id, -999) -- <SERVICES FPJ>
13978                             AND   (   ( POL.item_id = PRL.item_id ) -- <SERVICES FPJ>
13979                                   OR  (   ( POL.item_id IS NULL )
13980                                       AND ( PRL.item_id IS NULL )
13981                                       AND ( POL.item_description = PRL.item_description )
13982                                       AND ( POL.category_id = PRL.category_id) )   --bug 7492597
13983                                   )
13984                             AND   ((pol.item_revision IS NULL
13985                                    and prl.item_revision IS NULL)
13986                                    or  pol.item_revision = prl.item_revision
13987                                    or  (prl.item_revision is null  and p_item_rev_control = 1))
13988                             AND   (pol.transaction_reason_code IS NULL
13989                                    or pol.transaction_reason_code =
13990                                    NVL(prl.transaction_reason_code,
13991                                                 pol.transaction_reason_code))
13992 
13993 							-- Bug 9745707 starts
13994  	                        AND   NVL(P_INTERFACE_LINE_NUM,POL.LINE_NUM) =  POL.LINE_NUM
13995 
13996 						    AND ((---  CASE 1 : REQ IS NT SOURCED TO ANY DOC
13997  	                                    ( (PRL.BLANKET_PO_LINE_NUM IS NULL)							--Bug 16013325 : Added extra open-parenthesis
13998  	                                         OR
13999  	                                      ---  CASE 2 : REQ IS  SOURCED TO A DOC OTHER THAN THE CURRENT ONE
14000  	                                     (PRL.BLANKET_PO_LINE_NUM IS NOT NULL AND  PRL.BLANKET_PO_HEADER_ID <> P_PO_HEADER_ID) )	--Bug 16013325 : Added extra close-parenthesis
14001  	                                     -- IN CASE 1 AND 2, VALIDATE THE EXPIRY DATE WITH NEED BY DATE
14002  	                                     AND TRUNC(NVL(POL.EXPIRATION_DATE,SYSDATE + 1)) >= TRUNC(DECODE(POL.EXPIRATION_DATE,NULL,SYSDATE,NVL(PRL.NEED_BY_DATE,SYSDATE)))
14003  	                                     )
14004  	                                     OR
14005  	                                     --- CASE 3 : REQ IS ALREADY SOURCED TO THE DOCUMENT(CUURENT DOC)
14006  	                                     (PRL.BLANKET_PO_LINE_NUM IS NOT NULL AND  PRL.BLANKET_PO_HEADER_ID = P_PO_HEADER_ID
14007  	                                       -- IF THE REQ IS SOURCED TO THE DOC AND THE ALREADY SOURCED LINE IS VALID
14008  	                                     AND ((TRUNC(NVL(POL.EXPIRATION_DATE,SYSDATE + 1)) >= TRUNC(SYSDATE) AND PRL.BLANKET_PO_LINE_NUM = POL.LINE_NUM)
14009  	                                     -- IF THE REQ IS SOURCED TO THE DOC,BUT THE ALREADY SOURCED LINE IS INVALID,THEN TAKE THE OTHER VALID LINE FROM SOURCE DOCUMENT
14010  	                                     --OR TRUNC(NVL(POL.EXPIRATION_DATE,SYSDATE + 1)) >= TRUNC(DECODE(POL.EXPIRATION_DATE,NULL,SYSDATE,NVL(PRL.NEED_BY_DATE,SYSDATE))) ) --13876074
14011                                     --Bug 13876074, ensure to pick another source line
14012                                     --only if the current source line reference is not valid.
14013                                         OR ((NOT EXISTS (SELECT 1 FROM po_lines_all pol2
14014                                                       WHERE pol2.po_header_id = pol.po_header_id
14015                                                         AND TRUNC(NVL(pol2.expiration_date,SYSDATE + 1))
14016                                                             >= TRUNC(SYSDATE)
14017                                                         AND prl.blanket_po_line_num  = pol2.line_num))
14018                                              AND TRUNC(NVL(pol.expiration_date,SYSDATE + 1))
14019                                                  >= TRUNC(DECODE(pol.expiration_date,NULL,SYSDATE,
14020                                                                  NVL(prl.need_by_date,SYSDATE))))
14021                                        ) --end bug 13876074
14022  	                                     )
14023  	                             )
14024 
14025 
14026                             /*Bug4541335  AND   nvl(p_interface_line_num,pol.line_num) =
14027                                                                      pol.line_num
14028                             AND   trunc(nvl(pol.expiration_date,sysdate+1))
14029                                                                 >= trunc(sysdate)
14030            Bug4541335 start
14031        AND (p_InterFace_Line_num = pol.Line_num
14032              OR (p_InterFace_Line_num IS NULL
14033                  AND prl.Blanket_po_Header_Id = p_po_Header_Id
14034                  AND prl.Blanket_po_Line_num = pol.Line_num)
14035              OR (p_InterFace_Line_num IS NULL
14036                  AND (prl.Blanket_po_Header_Id <> p_po_Header_Id
14037                        OR prl.Blanket_po_Line_num IS NULL )))
14038        AND (((p_InterFace_Line_num IS NOT NULL
14039                OR (prl.Blanket_po_Header_Id = p_po_Header_Id
14040                    AND prl.Blanket_po_Line_num = pol.Line_num))
14041              AND Trunc(Nvl(pol.Expiration_Date,SYSDATE + 1)) >= Trunc(SYSDATE))
14042              OR ((p_InterFace_Line_num IS NULL
14043                   AND (prl.Blanket_po_Header_Id <> p_po_Header_Id
14044                         OR prl.Blanket_po_Line_num IS NULL ))
14045                  AND Trunc(Nvl(pol.Expiration_Date,SYSDATE + 1)) >= Trunc(DECODE(pol.Expiration_Date,NULL,SYSDATE,
14046                                                                                                      Nvl(prl.Need_By_Date,SYSDATE)))))
14047            Bug4541335 End */
14048 		   -- Bug 9745707 ends
14049                             -- Bug 2707576 Start
14050                             -- Require the BPA and req to have the same UOM
14051                             -- if x_allow_different_uoms is not 'Y'.
14052                             AND   (   (  NVL(POL.unit_meas_lookup_code,chr(0)) =
14053                                          decode ( x_allow_different_uoms,'Y',
14054                                                   NVL(POL.unit_meas_lookup_code,chr(0)),
14055                                                   PRL.unit_meas_lookup_code)
14056                                       )                       -- <SERVICES FPJ>
14057                                   OR  (   ( POL.unit_meas_lookup_code IS NULL )
14058                                       AND ( PRL.unit_meas_lookup_code IS NULL ) )
14059                                   );
14060                             -- Bug 2707576 End
14061 
14062 BEGIN
14063 
14064      /* bug 2315931 : when creating a release , if the requisition does not
14065        have a revision and the item is not revision controlled then we can
14066        match it to the blanket with a revision. For this added the additional
14067        clause in the cursors for the item revision matching */
14068 
14069       begin
14070        SELECT   inventory_organization_id
14071        INTO     x_inv_org_id
14072          FROM   financials_system_params_all  --<Shared Proc FPJ>
14073         WHERE   NVL(org_id, -99) = NVL(p_purchasing_ou_id, -99);  --<Shared Proc FPJ>
14074 
14075        select item_id
14076        into x_item_id
14077        from po_requisition_lines_all  --<Shared Proc FPJ>
14078        where requisition_line_id = x_requisition_line_id;
14079 
14080      if x_item_id is not null then
14081        SELECT   msi.revision_qty_control_code
14082        INTO     x_item_rev_control
14083        FROM     mtl_system_items msi
14084        WHERE    msi.inventory_item_id = x_item_id
14085        AND      msi.organization_id = x_inv_org_id;
14086      end if;
14087 
14088       exception
14089        when no_data_found then
14090          null;
14091      end;
14092         -- Get the first BPO line having the same item_id AND description
14093         -- as that of requisition line.
14094         OPEN c1(x_po_header_id, x_requisition_line_id, x_interface_line_num,x_item_rev_control,
14095                 x_allow_different_uoms -- Bug 2707576
14096                );
14097 
14098         FETCH c1 INTO v_line_num;
14099 
14100         IF c1%NOTFOUND  OR v_line_num IS NULL THEN
14101                 -- Get the first BPO line having the same item_id as
14102                 -- that of requisition line, ignoring the description.
14103                 OPEN  c2(x_po_header_id,
14104                          x_requisition_line_id,
14105                          x_interface_line_num,
14106                          x_item_rev_control,
14107                          x_allow_different_uoms -- Bug 2707576
14108                         );
14109                 FETCH c2 INTO v_line_num;
14110                 CLOSE c2;
14111         END IF;
14112         CLOSE c1;
14113         RETURN v_line_num;
14114 
14115 EXCEPTION
14116         WHEN OTHERS THEN RETURN -1;
14117 
14118 END source_blanket_line;
14119 
14120 --<RENEG BLANKET FPI START>
14121 /*============================================================================
14122 Name      :     CREATE_PRICE_BREAK
14123 Type      :     Private
14124 Function  :     This procedure is called from 'create_line'. This procedure inserts
14125                 records from po_lines_interface table to po_line_locations_all table
14126                 for the price break information.
14127 Pre-req   :     None
14128 Parameters:
14129 IN        :     p_po_line_id            IN      NUMBER  REQUIRED
14130 OUT       :     x_line_location_id      OUT     NOCOPY
14131 ==============================================================================*/
14132 PROCEDURE CREATE_PRICE_BREAK(p_po_line_id IN number,
14133                              x_line_location_id OUT NOCOPY number,
14134                  p_outsourced_assembly IN NUMBER --<SHIKYU R12>
14135 ) IS
14136 
14137 l_row_id            varchar2(18) := NULL;
14138 l_progress          varchar2(3) := '000';            --< Bug 3210331 >
14139 l_api_name VARCHAR2(30) := 'create_price_break';      --< Bug 3210331, 3336920 >
14140 unexpected_create_pb_err   EXCEPTION;
14141 
14142 l_ship_org_id_line  mtl_system_items.organization_id%type;
14143 l_ship_org_code       varchar2(3);
14144 l_ship_org_name     varchar2(60);
14145 
14146 l_value_basis   PO_LINES_ALL.order_type_lookup_code%TYPE; -- <Complex Work R12>
14147 
14148 BEGIN
14149     -- Standard start of API savepoint
14150     SAVEPOINT       create_price_break_pvt;
14151 
14152     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
14153         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
14154     END IF;
14155 
14156     begin
14157        SELECT po_line_locations_s.nextval
14158           INTO x_line_location_id
14159           FROM sys.dual;
14160     exception
14161         when others then
14162             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
14163                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
14164                                    p_progress => l_progress);
14165             END IF;
14166             po_message_s.sql_error('Exception of create_price_break()', l_progress,sqlcode);
14167             FND_MSG_PUB.Add;
14168             RAISE unexpected_create_pb_err;
14169     end;
14170 
14171     l_progress := '010';
14172     -- Check that price break ship_to_organization_id and ship_to_location_id match
14173     -- (if both are provided)
14174     if (interface.line_ship_to_org_id is not NULL and
14175         interface.line_ship_to_loc_id is not NULL and params.sob_id is not NULL) then
14176         po_locations_s.get_loc_org(interface.line_ship_to_loc_id,
14177                                    params.sob_id,
14178                                    l_ship_org_id_line,
14179                                    l_ship_org_code,
14180                                    l_ship_org_name);
14181         -- if the orgs do match raise an error
14182   if (l_ship_org_id_line <> interface.line_ship_to_org_id) then
14183             --Create an error code 4 for price break ship_to_loc and ship_to_org do not match
14184             g_sourcing_errorcode := 3;
14185            -- raise;
14186         end if;
14187     end if; /*check ship_loc and ship_org */
14188 
14189     l_progress := '020';
14190     --Call the row handler for po_line_location9in file POXP1PSB.pls to insert the row
14191 
14192     -- <Complex Work R12 Start>
14193     -- Get value basis from line
14194 
14195     SELECT pol.order_type_lookup_code
14196     INTO l_value_basis
14197     FROM po_lines_all pol
14198     WHERE pol.po_line_id = p_po_line_id;
14199 
14200     l_progress := '025';
14201 
14202     -- <Complex Work R12 End>
14203 
14204 
14205     begin
14206       po_line_locations_pkg_s0.insert_row(
14207                        l_row_id,
14208                        x_Line_Location_Id,
14209                        interface.last_update_date,
14210                        interface.last_updated_by,
14211                        interface.Po_Header_Id,
14212                        p_po_Line_Id,
14213                        interface.Last_Update_Login,
14214                        interface.creation_Date,
14215                        interface.created_By,
14216                        interface.quantity,
14217                        0, --quantity_received
14218                        0, --Quantity_Accepted
14219                        0, --Quantity_Rejected
14220                        0, --Quantity_Billed
14221                        0, --Quantity_Cancelled,
14222                        interface.unit_meas_lookup_code, --unit of measure
14223                        NULL, -- release_id
14224                        interface.line_Ship_To_Loc_Id,
14225                        interface.Ship_Via_Lookup_Code,
14226                        NULL, --Need_By_Date
14227                        NULL, --Promised_Date
14228                        NULL, --Last_Accept_Date
14229            interface.unit_price, --Price_override
14230                        'N', --Encumbered flag
14231                        NULL, --Encumbered_Date
14232                        NULL, --Fob_Lookup_Code
14233                        NULL, --Freight_Terms_Lookup_Code
14234                        'N', --Taxable_Flag
14235                        NULL, --Tax_Code_Id
14236                        'N', --Tax_User_Override_Flag
14237                        NULL, --Calculate_Tax_Flag
14238                        NULL, --X_From_Header_Id
14239                        NULL, --X_From_Line_Id
14240                        NULL, --X_From_Line_Location_Id
14241                        interface.line_effective_date, --X_Start_Date
14242                        interface.line_expiration_date, --X_End_Date
14243                        NULL, --X_Lead_Time,
14244                        NULL, --X_Lead_Time_Unit,
14245                        interface.Price_Discount,
14246                        interface.Terms_Id,
14247                        NULL, --X_Approved_Flag,
14248                        NULL, --X_Approved_Date,
14249                        'N', --X_Closed_Flag,
14250                        'N', --X_Cancel_Flag,
14251                        NULL, --X_Cancelled_By,
14252                        NULL, --X_Cancel_Date,
14253                        NULL, --X_Cancel_Reason,
14254                        'N', --X_Firm_Status_Lookup_Code,
14255                        NULL, --X_Attribute_Category,
14256                        NULL, --X_Attribute1,
14257                        NULL, --X_Attribute2,
14258                        NULL, --X_Attribute3,
14259                        NULL, --X_Attribute4,
14260                        NULL, --X_Attribute5,
14261                        NULL, --X_Attribute6,
14262                        NULL, --X_Attribute7,
14263                        NULL, --X_Attribute8,
14264                        NULL, --X_Attribute9,
14265                        NULL, --X_Attribute10,
14266                        NULL, --X_Attribute11,
14267                        NULL, --X_Attribute12,
14268                        NULL, --X_Attribute13,
14269                        NULL, --X_Attribute14,
14270                        NULL, --X_Attribute15,
14271                        'N', --X_Inspection_Required_Flag,
14272                        'N', --X_Receipt_Required_Flag,
14273                        NULL, --X_Qty_Rcv_Tolerance,
14274                        NULL, --X_Qty_Rcv_Exception_Code,
14275                        'NONE', --X_Enforce_Ship_To_Location,
14276                        NULL, --X_Allow_Substitute_Receipts,
14277                        NULL, --X_Days_Early_Receipt_Allowed,
14278                        NULL, --X_Days_Late_Receipt_Allowed,
14279                        NULL, --X_Receipt_Days_Exception_Code,
14280                        NULL, --X_Invoice_Close_Tolerance,
14281                        NULL, --X_Receive_Close_Tolerance,
14282                        interface.line_Ship_To_Org_Id,
14283                        interface.Shipment_Num,
14284                        NULL, --X_Source_Shipment_Id,
14285                        interface.Shipment_Type,
14286                        'OPEN', --X_Closed_Code,
14287                        NULL, --
14288                        NULL, --X_Government_Context,
14289                        NULL, --X_Receiving_Routing_Id,
14290                        NULL, --X_Accrue_On_Receipt_Flag,
14291                        NULL, --X_Closed_Reason,
14292                        NULL, --X_Closed_Date,
14293                        NULL, --X_Closed_By,
14294                        NULL, --X_Global_Attribute_Category,
14295                        NULL, --X_Global_Attribute1,
14296                        NULL, --X_Global_Attribute2,
14297                        NULL, --X_Global_Attribute3,
14298                        NULL, --X_Global_Attribute4,
14299                        NULL, --X_Global_Attribute5,
14300                        NULL, --X_Global_Attribute6,
14301                        NULL, --X_Global_Attribute7,
14302                        NULL, --X_Global_Attribute8,
14303                        NULL, --X_Global_Attribute9,
14304                        NULL, --X_Global_Attribute10,
14305                        NULL, --X_Global_Attribute11,
14306                        NULL, --X_Global_Attribute12,
14307                        NULL, --X_Global_Attribute13,
14308                        NULL, --X_Global_Attribute14,
14309                        NULL, --X_Global_Attribute15,
14310                        NULL, --X_Global_Attribute16,
14311                        NULL, --X_Global_Attribute17,
14312                        NULL, --X_Global_Attribute18,
14313                        NULL, --X_Global_Attribute19,
14314                        NULL, --X_Global_Attribute20,
14315                        NULL, --X_Country_of_Origin_Code,
14316                        'P', --invoice option
14317                        l_value_basis,   -- <Complex Work R12>
14318                        NULL,            -- <Complex Work R12>: matching basis
14319                        NULL, --X_note_to_receiver,
14320                        NULL, --X_Secondary_Unit_Of_Measure,
14321                        NULL, --X_Secondary_Quantity,
14322                        NULL, --X_Preferred_Grade,
14323                        NULL, --X_Secondary_Quantity_Received,
14324                        NULL, --X_Secondary_Quantity_Accepted,
14325                        NULL, --X_Secondary_Quantity_Rejected,
14326                        NULL, --X_Secondary_Quantity_Cancelled,
14327                        NULL,            --X_Consigned_Flag    -- <SERVICES FPJ>
14328                        interface.amount, --X_Amount            -- <SERVICES FPJ>
14329                        NULL, -- p_transaction_flow_header_id
14330                        NULL, -- p_manual_price_change_flag
14331            interface.org_id                      -- <R12 MOAC>
14332            ,p_outsourced_assembly --<SHIKYU R12>
14333                        );
14334 
14335         l_progress := '030';
14336         -- <SERVICES FPJ START> Insert Price Break Price Differentials into
14337         -- main table from the interface table.
14338         --
14339         PO_PRICE_DIFFERENTIALS_PVT.create_from_interface
14340         (   p_entity_id         => x_line_location_id
14341         ,   p_interface_line_id => interface.interface_line_id
14342         );
14343         -- <SERVICES FPJ END>
14344 
14345       exception
14346         when others then
14347             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
14348                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
14349                                    p_progress => l_progress);
14350             END IF;
14351             po_message_s.sql_error('Exception of create_price_break()', l_progress, sqlcode);
14352             FND_MSG_PUB.Add;
14353             RAISE unexpected_create_pb_err;
14354       end;
14355 
14356     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
14357         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
14358     END IF;
14359 EXCEPTION
14360         when unexpected_create_pb_err then
14361             RAISE; --Bug 3336920
14362             --ROLLBACK to create_price_break_pvt;
14363         when others then
14364             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
14365                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
14366                                    p_progress => l_progress);
14367             END IF;
14368             --ROLLBACK to create_price_break_pvt;
14369             RAISE; --Bug 3336920
14370 END CREATE_PRICE_BREAK;
14371 --<RENEG BLANKET FPI END>
14372 
14373 -- <Complex Work R12 Start>: Added logging; cleaned tabbing.
14374 FUNCTION get_ship_to_loc(p_deliver_to_loc_id IN NUMBER)
14375 RETURN NUMBER
14376 IS
14377 
14378   l_ship_to_location_id  NUMBER;
14379   l_found BOOLEAN := FALSE;
14380 
14381   d_module VARCHAR2(70) := 'po.plsql.PO_INTERFACE_S.get_ship_to_loc';
14382   d_progress NUMBER;
14383 
14384 BEGIN
14385 
14386   d_progress := 0;
14387 
14388   IF (PO_LOG.d_proc) THEN
14389     PO_LOG.proc_begin(d_module);
14390     PO_LOG.proc_begin(d_module, 'p_deliver_to_loc_id', p_deliver_to_loc_id);
14391   END IF;
14392 
14393   d_progress := 10;
14394 
14395   BEGIN
14396     /*Bug 8763609 : When HR: Business Group is set to some value and
14397     HR Cross business Group is set to Y, then autocreate was failing
14398     because the 2 sqls below were returning no rows.Instead of using the
14399     views , we need to use _all tables to get the ship to location id.  */
14400 
14401     SELECT NVL(hrl.ship_to_location_id, hrl.location_id)
14402     INTO l_ship_to_location_id
14403     FROM hr_locations_all hrl--bug 8763609
14404     WHERE hrl.location_id = p_deliver_to_loc_id;
14405 
14406     l_found := TRUE;
14407 
14408   EXCEPTION
14409     WHEN NO_DATA_FOUND THEN
14410       IF (PO_LOG.d_stmt) THEN
14411         PO_LOG.stmt(d_module, d_progress, 'No data found in hr_locations.');
14412       END IF;
14413   END;
14414 
14415   d_progress := 20;
14416 
14417   IF (NOT l_found) THEN
14418 
14419     BEGIN
14420 
14421       SELECT hzl.location_id
14422       INTO l_ship_to_location_id
14423       FROM hz_locations hzl
14424       WHERE hzl.location_id = p_deliver_to_loc_id;
14425 
14426       l_found := TRUE;
14427 
14428     EXCEPTION
14429       WHEN NO_DATA_FOUND THEN
14430         IF (PO_LOG.d_stmt) THEN
14431           PO_LOG.stmt(d_module, d_progress, 'No data found in hz_locations.');
14432         END IF;
14433     END;
14434 
14435   END IF;  -- if not l_found
14436 
14437   IF (NOT l_found) THEN
14438     RAISE NO_DATA_FOUND;
14439   END IF;
14440 
14441   IF (PO_LOG.d_proc) THEN
14442     PO_LOG.proc_return(d_module, l_ship_to_location_id);
14443     PO_LOG.proc_end(d_module);
14444   END IF;
14445 
14446   RETURN l_ship_to_location_id;
14447 
14448 EXCEPTION
14449   WHEN OTHERS THEN
14450     IF (PO_LOG.d_exc) THEN
14451       PO_LOG.exc(d_module, d_progress, SQLCODE || SQLERRM);
14452     END IF;
14453     wrapup(interface.interface_header_id);
14454     RAISE;
14455 END;
14456 -- <Complex Work R12 End>
14457 
14458 --<CONFIG_ID FPJ START>
14459 
14460 ----------------------------------------------------------------------------
14461 --Start of Comments
14462 --Name: validate_interface_records
14463 --Pre-reqs:
14464 --  None
14465 --Modifies:
14466 --  None
14467 --Locks:
14468 --  None
14469 --Function:
14470 --  Performs various validations on the interface records.
14471 --Parameters:
14472 --IN:
14473 --p_interface_header_id
14474 --  header ID of the interface records to check
14475 --Returns:
14476 --  TRUE if the interface records pass all the validations;
14477 --  FALSE otherwise.
14478 --Testing:
14479 --  None
14480 --End of Comments
14481 ----------------------------------------------------------------------------
14482 
14483 FUNCTION validate_interface_records (
14484   p_interface_header_id IN PO_HEADERS_INTERFACE.interface_header_id%TYPE
14485 ) RETURN BOOLEAN IS
14486 
14487   l_api_name CONSTANT VARCHAR2(30) := 'validate_interface_records';
14488   l_pass_validations BOOLEAN;
14489 
14490 BEGIN
14491 
14492   l_pass_validations := validate_config_id(p_interface_header_id);
14493   RETURN l_pass_validations;
14494 
14495 END validate_interface_records;
14496 
14497 
14498 ----------------------------------------------------------------------------
14499 --Start of Comments
14500 --Name: validate_config_id
14501 --Pre-reqs:
14502 --  g_document_type and g_document_subtype should have been set.
14503 --Modifies:
14504 --  None
14505 --Locks:
14506 --  None
14507 --Function: Verifies that Config ID lines are only placed on the Standard PO
14508 --  document type.
14509 --Parameters:
14510 --IN:
14511 --p_interface_header_id
14512 --  header ID of the interface records to check
14513 --Returns:
14514 --  TRUE if the document type is Standard PO, or if none of the lines have
14515 --  Config ID; FALSE otherwise.
14516 --Testing:
14517 --  None
14518 --End of Comments
14519 ----------------------------------------------------------------------------
14520 
14521 FUNCTION validate_config_id (
14522   p_interface_header_id IN PO_HEADERS_INTERFACE.interface_header_id%TYPE
14523 ) RETURN BOOLEAN IS
14524 
14525   l_api_name CONSTANT VARCHAR2(30) := 'validate_config_id';
14526   l_num_config_id_lines NUMBER;
14527   l_progress VARCHAR2(3) := '000';              --< Bug 3210331 >
14528 
14529 BEGIN
14530 
14531   IF (g_document_type = 'PO' AND g_document_subtype = 'STANDARD') THEN
14532     RETURN TRUE; -- The lines are being placed on a Standard PO.
14533   END IF;
14534 
14535   SELECT count(*)
14536   INTO l_num_config_id_lines
14537   FROM po_lines_interface PLI, po_requisition_lines PRL
14538   WHERE PLI.interface_header_id = p_interface_header_id
14539   AND PLI.requisition_line_id = PRL.requisition_line_id -- JOIN
14540   AND PRL.supplier_ref_number IS NOT NULL;
14541 
14542   IF (l_num_config_id_lines = 0) THEN
14543     RETURN TRUE; -- None of the lines have Config ID.
14544   ELSE
14545     l_progress := '010';
14546     -- We do not allow req lines with Config ID to be placed on any document type
14547     -- other than Standard PO.
14548     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
14549         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
14550                             p_token    => l_progress,
14551                             p_message  => FND_MESSAGE.get_string('PO','PO_CONFIG_ID_ONLY_ON_STD_PO'));
14552     END IF;
14553     RETURN FALSE;
14554   END IF;
14555 
14556 EXCEPTION
14557 
14558   WHEN OTHERS THEN
14559     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
14560         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
14561                            p_progress => l_progress);
14562     END IF;
14563     wrapup(p_interface_header_id);
14564     RAISE;
14565 
14566 END validate_config_id;
14567 
14568 --<CONFIG_ID FPJ END>
14569 
14570 
14571 --<GRANTS FPJ START>
14572 ----------------------------------------------------------------------------
14573 --Start of Comments
14574 --Name: update_award_distributions
14575 --Pre-reqs:
14576 --  None
14577 --Modifies:
14578 --  PO_DISTRIBUTIONS_INTERFACE
14579 --  GMS_AWARD_DISTRIBUTIONS
14580 --Locks:
14581 --  None
14582 --Function:
14583 --  Calls Grants Accounting API to create new award distributions lines
14584 --  when a requisition with distributions that reference awards is
14585 --  autocreated into a PO.
14586 --Parameters:
14587 --  <Complex Work R12>: Add p_table_type and p_po_line_id
14588 --  p_table_type
14589 --    'INTERFACE' - query/update interface tables (default)
14590 --    'ALL - query/update _ALL tables
14591 --  p_po_line_id
14592 --    Only necessary if p_table_type = 'ALL', this is the line for
14593 --    which to update the award distributions for.
14594 --Returns:
14595 --  None
14596 --Testing:
14597 --  None
14598 --End of Comments
14599 ----------------------------------------------------------------------------
14600 
14601 PROCEDURE update_award_distributions(
14602   p_table_type   IN   VARCHAR2   DEFAULT 'INTERFACE'
14603 , p_po_line_id   IN   NUMBER     DEFAULT NULL
14604 )
14605 IS
14606 
14607   l_api_name     CONSTANT VARCHAR(30) := 'update_award_distributions';
14608   l_return_status        VARCHAR2(1);
14609   l_progress           VARCHAR2(4) := '000';              --< Bug 3210331 >
14610   l_gms_po_interface_obj gms_po_interface_type;
14611   l_msg_count          NUMBER;
14612   l_msg_data           VARCHAR2(2000);
14613   l_msg_buf              VARCHAR2(2000);
14614 
14615 BEGIN
14616     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
14617         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
14618     END IF;
14619 
14620     -- <Complex Work R12 Start>
14621     IF (p_table_type = 'ALL') THEN
14622 
14623       --SQL WHAT: For distributions with award_id references, select
14624       --          the columns that Grants needs from the
14625       --          po_distributions_all table
14626       --SQL WHY : Needed to call GMS API to update award distribution
14627       --          lines table.
14628 
14629       SELECT pod.po_distribution_id,
14630              pod.distribution_num,
14631              pod.project_id,
14632              pod.task_id,
14633              pod.award_id,
14634              NULL
14635       BULK COLLECT INTO
14636              l_gms_po_interface_obj.distribution_id,
14637              l_gms_po_interface_obj.distribution_num,
14638              l_gms_po_interface_obj.project_id,
14639              l_gms_po_interface_obj.task_id,
14640              l_gms_po_interface_obj.award_set_id_in,
14641              l_gms_po_interface_obj.award_set_id_out
14642       FROM po_distributions_all pod
14643       WHERE pod.po_line_id = p_po_line_id
14644         AND pod.award_id IS NOT NULL;
14645 
14646     ELSE
14647 
14648       --SQL WHAT: For distributions with award_id references, select
14649       --          the columns that Grants needs from the
14650       --          po_distributions_interface table
14651       --SQL WHY : Need to call GMS API to update award distribution
14652       --          lines table.
14653 
14654       SELECT po_distribution_id,
14655              distribution_num,
14656              project_id,
14657              task_id,
14658              award_id,
14659              NULL
14660       BULK COLLECT INTO
14661              l_gms_po_interface_obj.distribution_id,
14662              l_gms_po_interface_obj.distribution_num,
14663              l_gms_po_interface_obj.project_id,
14664              l_gms_po_interface_obj.task_id,
14665              l_gms_po_interface_obj.award_set_id_in,
14666              l_gms_po_interface_obj.award_set_id_out
14667       FROM PO_DISTRIBUTIONS_INTERFACE
14668       WHERE interface_header_id = interface.interface_header_id
14669             AND interface_line_id = interface.interface_line_id
14670             AND award_id IS NOT NULL;
14671 
14672     END IF;  -- if p_table_type = 'ALL'
14673     -- <Complex Work R12 End>
14674 
14675     IF SQL%NOTFOUND THEN
14676       RETURN;
14677     END IF;
14678 
14679 
14680     l_progress := '010';
14681 
14682     --Create new award distribution lines in GMS_AWARDS_DISTRIBUTIONS table
14683     PO_GMS_INTEGRATION_PVT.maintain_adl (
14684           p_api_version           => 1.0,
14685           x_return_status         => l_return_status,
14686           x_msg_count             => l_msg_count,
14687           x_msg_data              => l_msg_data,
14688           p_caller                => 'AUTOCREATE',
14689           x_po_gms_interface_obj  => l_gms_po_interface_obj);
14690 
14691     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
14692       RAISE FND_API.G_EXC_ERROR;
14693     END IF;
14694 
14695     l_progress := '020';
14696 
14697     -- <Complex Work R12 Start>
14698     IF (p_table_type = 'ALL') THEN
14699 
14700       --SQL WHAT: Update po_distributions_all table with the new
14701       --          award_id's
14702       --SQL WHY : award_id's in PO tables need to be synchronized with
14703       --          award_id's in GMS tables.
14704 
14705       FORALL i IN 1..l_gms_po_interface_obj.distribution_id.COUNT
14706           UPDATE po_distributions_all
14707           SET award_id =
14708                 l_gms_po_interface_obj.award_set_id_out(i)
14709           WHERE po_distribution_id =
14710                 l_gms_po_interface_obj.distribution_id(i);
14711 
14712     ELSE
14713 
14714       --SQL WHAT: Update po_distributions_interface table with the new
14715       --          award_id's
14716       --SQL WHY : award_id's in PO tables need to be synchronized with
14717       --          award_id's in GMS tables.
14718 
14719       FORALL i IN 1..l_gms_po_interface_obj.distribution_id.COUNT
14720           UPDATE po_distributions_interface
14721           SET award_id = l_gms_po_interface_obj.award_set_id_out(i)
14722           WHERE po_distribution_id = l_gms_po_interface_obj.distribution_id(i);
14723 
14724     END IF; -- if p_table_type = 'ALL'
14725     -- <Complex Work R12 End>
14726 
14727     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
14728         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
14729     END IF;
14730 EXCEPTION
14731 
14732   WHEN FND_API.G_EXC_ERROR THEN
14733     IF FND_MSG_PUB.check_msg_level(
14734          p_message_level => FND_MSG_PUB.g_msg_lvl_unexp_error) THEN
14735       FND_MSG_PUB.add_exc_msg( p_pkg_name => G_PKG_NAME,
14736                                p_procedure_name => l_api_name);
14737     END IF;
14738 
14739     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
14740 
14741        FOR i IN 1..FND_MSG_PUB.count_msg LOOP
14742           l_msg_buf := SUBSTRB(FND_MSG_PUB.get(p_msg_index => i,
14743                                                p_encoded   => FND_API.G_FALSE),
14744                                1, 2000);
14745           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
14746                               p_token    => l_progress,
14747                               p_message  => 'EXCEPTION: '|| l_msg_buf);
14748        END LOOP;
14749 
14750     END IF;
14751     RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
14752 
14753   WHEN OTHERS THEN
14754     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
14755         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
14756                            p_progress => l_progress);
14757     END IF;
14758     IF FND_MSG_PUB.check_msg_level(
14759          p_message_level => FND_MSG_PUB.g_msg_lvl_unexp_error) THEN
14760       FND_MSG_PUB.add_exc_msg( p_pkg_name => G_PKG_NAME,
14761                                p_procedure_name => l_api_name);
14762     END IF;
14763 
14764     RAISE;
14765 
14766 END update_award_distributions;
14767 
14768 --<GRANTS FPJ END>
14769 
14770 --<Shared Proc FPJ START>
14771 -------------------------------------------------------------------------------
14772 --Start of Comments
14773 --Name: GET_RATE_FOR_REQ_PRICE
14774 --Pre-reqs:
14775 --   None
14776 --Modifies:
14777 --  None
14778 --Locks:
14779 --  None.
14780 --Function:
14781 --  Get the conversion rate between PO Currency and Req Functional Currency for
14782 --  Default Rate type of Purchasing Org
14783 --Parameters:
14784 --  IN:
14785 --  p_requesting_ou_id: Requesting Operating Unit <ACHTML R12>
14786 --  p_purchasing_ou_id: Purchasing Operating Unit <ACHTML R12>
14787 --  p_po_currency_code: The currency in which PO will be cut
14788 --  p_rate_type: The default rate type of Purchasing Operating Unit
14789 --  p_rate_date: The date used to derive rate between PO and POU functional currency
14790 --  OUT:
14791 --  x_rate: The rate between PO currency and Requisition raising Operating Unit's functional currency
14792 --          Returns NULL if POU and ROU are in same Set Of Books (implying same functional currency)
14793 --Notes:
14794 --  None
14795 --Testing:
14796 --  None
14797 --End of Comments
14798 -------------------------------------------------------------------------------
14799 PROCEDURE get_rate_for_req_price(
14800   p_requesting_ou_id IN NUMBER, -- <ACHTML R12>
14801   p_purchasing_ou_id IN NUMBER, -- <ACHTML R12>
14802   p_po_currency_code IN VARCHAR2,
14803   p_rate_type        IN VARCHAR2,
14804   p_rate_date        IN DATE,
14805   x_rate             OUT NOCOPY NUMBER
14806 )
14807 IS
14808 
14809 l_req_ou_sob_id              GL_SETS_OF_BOOKS.set_of_books_id%TYPE;
14810 l_po_ou_sob_id               GL_SETS_OF_BOOKS.set_of_books_id%TYPE;
14811 l_inverse_rate_display_flag  VARCHAR2(1) := 'N';
14812 l_display_rate               NUMBER;
14813 l_progress                   VARCHAR2(3) := '000';
14814 l_rate_type                  PO_HEADERS_INTERFACE.rate_type%TYPE;
14815 l_api_name CONSTANT VARCHAR2(30) := 'get_rate_for_req_price';  --< Bug 3210331 >
14816 
14817 BEGIN
14818     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
14819         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
14820     END IF;
14821 
14822    select req_fsp.set_of_books_id
14823    into l_req_ou_sob_id
14824    from financials_system_params_all req_fsp
14825    where req_fsp.org_id = p_requesting_ou_id; -- <ACHTML R12>
14826 
14827    l_progress := '010';
14828    select po_fsp.set_of_books_id
14829    into l_po_ou_sob_id
14830    from financials_system_params_all po_fsp
14831    where po_fsp.org_id = p_purchasing_ou_id; -- <ACHTML R12>
14832 
14833    IF l_req_ou_sob_id = l_po_ou_sob_id THEN
14834       x_rate := NULL;
14835       return;
14836    END IF;
14837 
14838    IF p_rate_type is NULL THEN
14839       l_progress := '020';
14840       select default_rate_type
14841       into  l_rate_type
14842       from  po_system_parameters_all psp
14843       where psp.org_id = p_purchasing_ou_id; -- <ACHTML R12>
14844    ELSE
14845      l_rate_type := p_rate_type;
14846    END IF;
14847 
14848    l_progress := '030';
14849 
14850    po_currency_sv.get_rate(l_req_ou_sob_id,
14851                               p_po_currency_code,
14852                               l_rate_type,
14853                               p_rate_date,
14854                               l_inverse_rate_display_flag,
14855                               x_rate,
14856                               l_display_rate);
14857 
14858     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
14859         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
14860     END IF;
14861 EXCEPTION
14862   WHEN OTHERS THEN
14863       IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
14864           PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
14865                              p_progress => l_progress);
14866       END IF;
14867       po_message_s.sql_error('GET_RATE_FOR_REQ_PRICE',l_progress,sqlcode);
14868 END get_rate_for_req_price;
14869 --<Shared Proc FPJ END>
14870 
14871 
14872 -- <Complex Work R12 Start>
14873 -------------------------------------------------------------------------------
14874 --Start of Comments
14875 --Name: create_payitems
14876 --Pre-reqs:
14877 --   PO Line has been created.
14878 --Modifies:
14879 --  PO_LINE_LOCATIONS_ALL
14880 --Locks:
14881 --  None.
14882 --Function:
14883 --  Create all payitems for a PO Line.  If PO_LINE_LOCATIONS_INTERFACE is
14884 --  populated, use that information.  Otherwise, create a default
14885 --  payitem.  Also create DELIVERY and ADVANCE payitems as necessary.
14886 --Parameters:
14887 --  IN:
14888 --    p_interface_line_id:  id of the line in po_lines_interface
14889 --    p_po_line_id: id of the line in po_lines_all
14890 --    p_precision: precision of the currency desired.  Used to round amounts.
14891 --    p_ext_precision: extended precision of the currency desired.
14892 --                     Used to round prices
14893 --  OUT:
14894 --    x_line_location_id: id of the first actuals (STANDARD) payitem
14895 --                        in po_line_locations_all
14896 --    x_line_loc_id_tbl: ids of all payitems created in po_line_locations_all
14897 --Notes:
14898 --  None
14899 --Testing:
14900 --  None
14901 --End of Comments
14902 -------------------------------------------------------------------------------
14903 PROCEDURE create_payitems(
14904   p_interface_line_id IN         NUMBER
14905 , p_po_line_id        IN         NUMBER
14906 , p_precision         IN         NUMBER
14907 , p_ext_precision     IN         NUMBER
14908 , x_line_location_id  OUT NOCOPY NUMBER
14909 , x_line_loc_id_tbl   OUT NOCOPY po_tbl_number
14910 )
14911 IS
14912 
14913 d_progress  NUMBER;
14914 d_module    VARCHAR2(70) := 'po.plsql.PO_INTERFACE_S.create_payitems';
14915 
14916 l_po_header_id         PO_LINES_ALL.po_header_id%TYPE;
14917 l_line_value_basis     PO_LINES_ALL.order_type_lookup_code%TYPE;
14918 l_line_matching_basis  PO_LINES_ALL.matching_basis%TYPE;
14919 l_line_unit_price      PO_LINES_ALL.unit_price%TYPE;
14920 l_line_quantity        PO_LINES_ALL.quantity%TYPE;
14921 l_line_amount          PO_LINES_ALL.amount%TYPE;
14922 l_line_purchase_basis  PO_LINES_ALL.purchase_basis%TYPE;
14923 
14924 l_payment_type       PO_LINE_LOCATIONS_ALL.payment_type%TYPE;
14925 l_shipment_type      PO_LINE_LOCATIONS_ALL.shipment_type%TYPE;
14926 l_payitem_quantity   PO_LINE_LOCATIONS_ALL.quantity%TYPE;
14927 l_payitem_amount     PO_LINE_LOCATIONS_ALL.amount%TYPE;
14928 l_payitem_price      PO_LINE_LOCATIONS_ALL.price_override%TYPE;
14929 
14930 l_req_tax_code_id    PO_REQUISITION_LINES_ALL.tax_code_id%TYPE;
14931 l_req_tax_user_override_flag    PO_REQUISITION_LINES_ALL.tax_user_override_flag%TYPE;
14932 l_req_tax_status_indicator PO_REQUISITION_LINES_ALL.tax_status_indicator%TYPE;
14933 
14934 l_tax_name                      AP_TAX_CODES.name%TYPE;
14935 l_tax_code_id                   AP_TAX_CODES.tax_id%TYPE;
14936 l_tax_type                      AP_TAX_CODES.tax_type%TYPE;
14937 l_tax_description               AP_TAX_CODES.description%TYPE;
14938 l_allow_tax_code_override_flag  GL_TAX_OPTION_ACCOUNTS.allow_tax_code_override_flag%TYPE;
14939 
14940 l_isFinancing          BOOLEAN;
14941 l_ship_to_location_id  NUMBER;
14942 
14943 l_payitem_tax_code_id_tbl   po_tbl_number;
14944 l_payitems_created          NUMBER;
14945 
14946 l_routing_name   RCV_ROUTING_HEADERS.routing_name%TYPE;
14947 l_line_loc_id    PO_LINE_LOCATIONS_ALL.line_location_id%TYPE;
14948 
14949 l_po_promised_def_prf   VARCHAR2(1) := FND_PROFILE.value('PO_NEED_BY_PROMISE_DEFAULTING');
14950 l_country_of_origin_code VARCHAR2(2);
14951 l_tax_status             VARCHAR2(10);
14952 l_encoded_msg            VARCHAR2(2000);
14953 
14954 l_advance_desc           VARCHAR2(240);
14955 --<eTax integration R12 Start >
14956 l_return_status             VARCHAR2(1);
14957 l_msg_count                 NUMBER;
14958 l_msg_data                  VARCHAR2(2000);
14959 --<eTax integration R12 End>
14960 
14961 CURSOR poll_interface_cursor(p_interface_line_id NUMBER)
14962 IS
14963   SELECT polli.interface_line_location_id,
14964          polli.quantity,
14965          polli.amount,
14966          polli.ship_to_location_id,
14967          polli.need_by_date,
14968          polli.promised_date,
14969          polli.price_override,
14970          polli.shipment_type,
14971          polli.shipment_num,
14972          polli.ship_to_organization_id,
14973          polli.value_basis,
14974          polli.matching_basis,
14975          polli.payment_type,
14976          polli.description,
14977          polli.work_approver_id,
14978          polli.bid_payment_id,
14979          polli.unit_of_measure
14980   FROM po_line_locations_interface polli
14981   WHERE polli.interface_line_id = p_interface_line_id
14982   ORDER BY polli.shipment_num;
14983 
14984 line_location_rec     poll_interface_cursor%ROWTYPE;
14985 payitem_rcv_ctl_rec   rcv_controls_type;
14986 
14987 BEGIN
14988 
14989   d_progress := 0;
14990   IF (PO_LOG.d_proc) THEN
14991     PO_LOG.proc_begin(d_module);
14992     PO_LOG.proc_begin(d_module, 'p_interface_line_id', p_interface_line_id);
14993     PO_LOG.proc_begin(d_module, 'p_po_line_id', p_po_line_id);
14994   END IF;
14995 
14996   d_progress := 10;
14997 
14998   SELECT pol.order_type_lookup_code
14999        , pol.matching_basis
15000        , pol.po_header_id
15001        , pol.unit_price
15002        , pol.quantity
15003        , pol.amount
15004        , pol.purchase_basis
15005   INTO l_line_value_basis
15006      , l_line_matching_basis
15007      , l_po_header_id
15008      , l_line_unit_price
15009      , l_line_quantity
15010      , l_line_amount
15011      , l_line_purchase_basis
15012   FROM po_lines_all pol
15013   WHERE pol.po_line_id = p_po_line_id;
15014 
15015   d_progress := 20;
15016 
15017   l_isFinancing := PO_COMPLEX_WORK_PVT.is_financing_po(
15018                      p_po_header_id => l_po_header_id
15019                    );
15020 
15021   IF (PO_LOG.d_stmt) THEN
15022     PO_LOG.stmt(d_module, d_progress, 'l_isFinancing', l_isFinancing);
15023   END IF;
15024 
15025   d_progress := 30;
15026 
15027   IF (interface.poll_interface_pop_flag = 'N') THEN
15028 
15029     d_progress := 40;
15030 
15031     -- If line locations interface is not populated, then we are either
15032     -- autocreating from requisition or there are no payitems negotiated
15033     -- in sourcing for this line.  We need to populate data for the default
15034     -- payitem in the interface tables.
15035 
15036     PO_COMPLEX_WORK_PVT.get_default_payitem_info(
15037       p_po_header_id          => l_po_header_id
15038     , p_po_line_id            => p_po_line_id
15039     , p_line_value_basis      => l_line_value_basis
15040     , p_line_matching_basis   => l_line_matching_basis
15041     , p_line_qty      => ROUND(l_line_quantity, 15)
15042     , p_line_amt      => l_line_amount
15043     , p_line_price    => l_line_unit_price
15044     , x_payment_type  => l_payment_type
15045     , x_payitem_qty   => l_payitem_quantity
15046     , x_payitem_amt   => l_payitem_amount
15047     , x_payitem_price => l_payitem_price
15048     );
15049 
15050     d_progress := 50;
15051 
15052     --SQL WHAT: Insert information for default payitem into
15053     -- po_line_locations interface table
15054     --SQL WHY : We will use line_locations_interface as a
15055     -- common entry point for payitems - whether they come from
15056     -- sourcing or we default them from scratch here.
15057 
15058     INSERT INTO po_line_locations_interface
15059     (
15060       interface_line_location_id
15061     , interface_header_id
15062     , interface_line_id
15063     , quantity
15064     , amount
15065     , price_override
15066     , shipment_type
15067     , payment_type
15068     , shipment_num
15069     , need_by_date
15070     , promised_date
15071     )
15072     VALUES
15073     (
15074       PO_LINE_LOCATIONS_INTERFACE_S.NEXTVAL
15075     , interface.interface_header_id
15076     , p_interface_line_id
15077     , l_payitem_quantity
15078     , l_payitem_amount
15079     , l_payitem_price
15080     , NULL
15081     , l_payment_type
15082     , 1
15083     , interface.need_by_date
15084     , interface.promised_date                             ----Bug11655669
15085     );
15086 
15087   END IF;  -- interface.poll_interface_pop_flag = 'N'
15088 
15089   d_progress := 60;
15090 
15091   IF (l_isFinancing) THEN
15092 
15093     d_progress := 70;
15094 
15095     -- if financing case, create actual delivery payitem
15096     -- this payitem has a shipment_type of STANDARD and payment_type of DELIVERY
15097 
15098     --SQL WHAT: Insert information for delivery payitem into
15099     -- po_line_locations_interface table
15100     --SQL WHY : We will use line_locations_interface as a
15101     -- common entry point for payitems, including ones we create
15102     -- behind the scenes
15103 
15104     INSERT INTO po_line_locations_interface
15105     (
15106       interface_line_location_id
15107     , interface_header_id
15108     , interface_line_id
15109     , quantity
15110     , amount
15111     , price_override
15112     , payment_type
15113     , shipment_type
15114     , description
15115     , shipment_num
15116     , need_by_date
15117     , promised_date
15118     )
15119     VALUES
15120     (
15121       PO_LINE_LOCATIONS_INTERFACE_S.NEXTVAL
15122     , interface.interface_header_id
15123     , p_interface_line_id
15124     , l_line_quantity
15125     , l_line_amount
15126     , l_line_unit_price
15127     , 'DELIVERY'
15128     , 'STANDARD'
15129     , interface.item_description
15130     , 1
15131     , interface.need_by_date
15132     , interface.promised_date            --Bug5532424
15133     );
15134 
15135   END IF;  -- if l_isFinancing
15136 
15137   d_progress := 80;
15138 
15139   IF (PO_LOG.d_stmt) THEN
15140     PO_LOG.stmt(d_module, d_progress, 'interface.has_advance_flag', interface.has_advance_flag);
15141   END IF;
15142 
15143   IF (interface.has_advance_flag = 'Y') THEN
15144 
15145     d_progress := 90;
15146 
15147     -- if line has advance, create financing payitem to represent it.
15148     -- the payitem has shipment_type of PREPAYMENT and payment_type of ADVANCE
15149 
15150     -- get default advance description
15151     FND_MESSAGE.set_name('PO', 'PO_CWPUI_ADVANCE_DESC_PREFIX');
15152     FND_MESSAGE.set_token(token => 'LINE_DESC',
15153                           value => interface.item_description);
15154     l_advance_desc := substrb(FND_MESSAGE.get, 1, 240);
15155 
15156     --SQL WHAT: Insert information for advance payitem into
15157     -- po_line_locations_interface table
15158     --SQL WHY : We will use line_locations_interface as a
15159     -- common entry point for payitems, including ones we create
15160     -- behind the scenes
15161 
15162     INSERT INTO po_line_locations_interface
15163     (
15164       interface_line_location_id
15165     , interface_header_id
15166     , interface_line_id
15167     , quantity
15168     , amount
15169     , price_override
15170     , payment_type
15171     , shipment_type
15172     , description
15173     , shipment_num
15174     , need_by_date
15175     )
15176     VALUES
15177     (
15178       PO_LINE_LOCATIONS_INTERFACE_S.NEXTVAL
15179     , interface.interface_header_id
15180     , p_interface_line_id
15181     , NULL
15182     , interface.advance_amount
15183     , NULL
15184     , 'ADVANCE'
15185     , 'PREPAYMENT'
15186     , l_advance_desc
15187     , 0
15188     , NULL
15189     );
15190 
15191   END IF;  -- if interface.has_advance_flag = 'Y'
15192 
15193   d_progress := 100;
15194 
15195   -- at this point, line_locations_interface has been populated with
15196   -- all necessary payitems - whether they come from sourcing or were
15197   -- created above from line information.
15198 
15199   -- we now update all rows in the line interface, filling in
15200   -- columns as necessary.  Some columns may have already been filled in;
15201   -- for those columns, we do a NULL check first (using NVL).
15202 
15203   l_ship_to_location_id := get_ship_to_loc(interface.deliver_to_location_id);
15204 
15205   IF (l_isFinancing) THEN
15206     l_shipment_type := 'PREPAYMENT';
15207   ELSE
15208     l_shipment_type := 'STANDARD';
15209   END IF;
15210 
15211   d_progress := 110;
15212 
15213   --SQL WHAT: Default/update values for scratch payitems in interface table
15214   --SQL WHY : This allows us to update all new payitems' values at once,
15215   -- including payitems from sourcing or ones we've created in autocreate
15216 
15217   UPDATE po_line_locations_interface polli
15218   SET polli.value_basis =
15219           DECODE(polli.payment_type,
15220                    'RATE', 'QUANTITY',
15221                    'LUMPSUM', 'FIXED PRICE',
15222                    'MILESTONE', l_line_value_basis,
15223                    'ADVANCE', 'FIXED PRICE',
15224                    'DELIVERY', l_line_value_basis,
15225                     polli.value_basis),
15226       polli.matching_basis =
15227           DECODE(polli.payment_type,
15228                    'RATE', 'QUANTITY',
15229                    'LUMPSUM', 'AMOUNT',
15230                    'MILESTONE', l_line_matching_basis,
15231                    'ADVANCE', 'AMOUNT',
15232                    'DELIVERY', l_line_matching_basis,
15233                     polli.matching_basis),
15234       polli.ship_to_location_id =
15235                     NVL(polli.ship_to_location_id, l_ship_to_location_id),
15236       polli.ship_to_organization_id =
15237                     NVL(polli.ship_to_organization_id,
15238                                    interface.destination_organization_id),
15239       polli.promised_date =
15240           NVL(polli.promised_date,
15241             DECODE(NVL(l_po_promised_def_prf, 'N'), 'Y', polli.need_by_date,
15242                                                          polli.promised_date)),
15243       polli.shipment_type = NVL(polli.shipment_type, l_shipment_type),
15244       polli.description = NVL(polli.description, interface.item_description),
15245       polli.unit_of_measure = NVL(polli.unit_of_measure, interface.unit_meas_lookup_code)
15246     WHERE polli.interface_line_id = p_interface_line_id;
15247 
15248   d_progress := 120;
15249 
15250   IF (interface.requisition_line_id IS NOT NULL) THEN
15251 
15252     d_progress := 130;
15253 
15254     SELECT prl.tax_code_id
15255         ,  nvl(prl.tax_user_override_flag,'N')
15256         ,  nvl(prl.tax_status_indicator,'SYSTEM')
15257         ,  nvl(prl.org_id, g_hdr_requesting_ou_id)
15258     INTO l_req_tax_code_id
15259       ,  l_req_tax_user_override_flag
15260       ,  l_req_tax_status_indicator
15261       ,  g_line_requesting_ou_id
15262     FROM po_requisition_lines_all prl
15263     WHERE prl.requisition_line_id = interface.requisition_line_id;
15264 
15265     l_tax_code_id := l_req_tax_code_id;
15266 
15267   ELSE
15268 
15269     d_progress := 140;
15270     l_req_tax_status_indicator := 'SYSTEM';
15271     g_line_requesting_ou_id := g_hdr_requesting_ou_id;
15272 
15273   END IF;  -- if interface.requisition_line_id IS NOT NULL
15274 
15275   d_progress := 150;
15276   x_line_loc_id_tbl := po_tbl_number();
15277   l_payitem_tax_code_id_tbl := po_tbl_number();
15278   l_payitems_created := 0;
15279 
15280   -- now iterate over the rows in the interface table
15281   -- for each row, get the default tax, receiving controls, and country of
15282   -- origin before inserting a new row into po_line_locations_all
15283 
15284   OPEN poll_interface_cursor(p_interface_line_id);
15285   LOOP
15286 
15287     FETCH poll_interface_cursor INTO line_location_rec;
15288     EXIT WHEN poll_interface_cursor%NOTFOUND;
15289 
15290     d_progress := 160;
15291 
15292     IF (PO_LOG.d_stmt) THEN
15293       PO_LOG.stmt(d_module, d_progress, 'Getting receiving controls.');
15294     END IF;
15295 
15296     RCV_CORE_S.get_receiving_controls(
15297       p_order_type_lookup_code => line_location_rec.value_basis
15298     , p_purchase_basis         => l_line_purchase_basis
15299     , p_line_location_id       => NULL
15300     , p_item_id                => interface.item_id
15301     , p_org_id                 => line_location_rec.ship_to_organization_id
15302     , p_vendor_id              => interface.vendor_id
15303     , p_drop_ship_flag         => interface.drop_ship_flag
15304     , p_payment_type           => line_location_rec.payment_type
15305     , x_enforce_ship_to_loc_code => payitem_rcv_ctl_rec.enforce_ship_to_location_code
15306     , x_allow_substitute_receipts => payitem_rcv_ctl_rec.allow_substitute_receipts_flag
15307     , x_routing_id => payitem_rcv_ctl_rec.receiving_routing_id
15308     , x_routing_name => l_routing_name
15309     , x_qty_rcv_tolerance => payitem_rcv_ctl_rec.qty_rcv_tolerance
15310     , x_qty_rcv_exception_code => payitem_rcv_ctl_rec.qty_rcv_exception_code
15311     , x_days_early_receipt_allowed => payitem_rcv_ctl_rec.days_early_receipt_allowed
15312     , x_days_late_receipt_allowed => payitem_rcv_ctl_rec.days_late_receipt_allowed
15313     , x_receipt_days_exception_code => payitem_rcv_ctl_rec.receipt_days_exception_code
15314     );
15315 
15316     d_progress := 200;
15317     IF (PO_LOG.d_stmt) THEN
15318       PO_LOG.stmt(d_module, d_progress, 'Getting default country of origin');
15319     END IF;
15320 
15321     po_coo_s.get_default_country_of_origin(
15322       x_item_id           => interface.item_id
15323     , x_ship_to_org_id    => line_location_rec.ship_to_organization_id
15324     , x_vendor_id         => interface.vendor_id
15325     , x_vendor_site_id    => interface.vendor_site_id
15326     , x_country_of_origin => l_country_of_origin_code
15327     );
15328 
15329     d_progress := 210;
15330     IF (PO_LOG.d_stmt) THEN
15331       PO_LOG.stmt(d_module, d_progress, 'Inserting payitem into po_line_locations_all');
15332     END IF;
15333 
15334     -- insert payitem into po_line_locations_all
15335 
15336     --SQL WHAT: Insert payitem, using info in po_line_locations_interface
15337     --SQL WHY : This allows us to insert all payitems in one location.
15338 
15339     INSERT INTO po_line_locations_all
15340     (
15341       line_location_id
15342     , last_update_date
15343     , last_updated_by
15344     , po_header_id
15345     , creation_date
15346     , created_by
15347     , last_update_login
15348     , po_line_id
15349     , quantity
15350     , quantity_received
15351     , quantity_accepted
15352     , quantity_rejected
15353     , quantity_billed
15354     , quantity_cancelled
15355     , quantity_financed
15356     , amount
15357     , amount_received
15358     , amount_accepted
15359     , amount_rejected
15360     , amount_billed
15361     , amount_cancelled
15362     , amount_financed
15363     , ship_to_location_id
15364     , need_by_date
15365     , promised_date
15366     , from_header_id
15367     , from_line_id
15368     , note_to_receiver
15369     , approved_flag
15370     , po_release_id
15371     , closed_code
15372     , closed_reason
15373     , price_override
15374     , encumbered_flag
15375     , taxable_flag
15376     , tax_code_id
15377     , tax_user_override_flag
15378     , shipment_type
15379     , shipment_num
15380     , inspection_required_flag
15381     , receipt_required_flag
15382     , days_early_receipt_allowed
15383     , days_late_receipt_allowed
15384     , enforce_ship_to_location_code
15385     , ship_to_organization_id
15386     , invoice_close_tolerance
15387     , receive_close_tolerance
15388     , accrue_on_receipt_flag
15389     , allow_substitute_receipts_flag
15390     , receiving_routing_id
15391     , qty_rcv_tolerance
15392     , qty_rcv_exception_code
15393     , receipt_days_exception_code
15394     , terms_id
15395     , ship_via_lookup_code
15396     , freight_terms_lookup_code
15397     , fob_lookup_code
15398     , unit_meas_lookup_code
15399     , last_accept_date
15400     , match_option
15401     , country_of_origin_code
15402     , vmi_flag
15403     , drop_ship_flag
15404     , consigned_flag
15405     , transaction_flow_header_id
15406     , org_id
15407     , closed_for_receiving_date
15408     , closed_for_invoice_date
15409     , value_basis
15410     , matching_basis
15411     , payment_type
15412     , description
15413     , work_approver_id
15414     , bid_payment_id
15415     , outsourced_assembly
15416     ,tax_attribute_update_code --<eTax Integration R12>
15417     )
15418     VALUES
15419     (
15420       PO_LINE_LOCATIONS_S.nextval
15421     , interface.last_update_date
15422     , interface.last_updated_by
15423     , interface.po_header_id
15424     , interface.creation_date
15425     , interface.created_by
15426     , interface.last_update_login
15427     , p_po_line_id
15428     , line_location_rec.quantity   -- quantity
15429     , 0                            -- quantity_received
15430     , 0                            -- quantity_accepted
15431     , 0                            -- quantity_rejected
15432     , 0                            -- quantity_billed
15433     , 0                            -- quantity_cancelled
15434     , 0                            -- quantity_financed
15435     , line_location_rec.amount     -- amount
15436     , 0                            -- amount_received
15437     , 0                            -- amount_accepted
15438     , 0                            -- amount_rejected
15439     , 0                            -- amount_billed
15440     , 0                            -- amount_cancelled
15441     , 0                            -- amount_financed
15442     , line_location_rec.ship_to_location_id
15443     , line_location_rec.need_by_date
15444     , line_location_rec.promised_date
15445    /* Bug11802312 - Retain the document reference for a consigned PO */
15446     , interface.from_header_id
15447     , interface.from_line_id
15448     , interface.note_to_receiver
15449     , 'N'                          -- approved_flag
15450     , NULL                         -- po_release_d
15451     , 'OPEN'                       -- closed_code
15452     , NULL                         -- closed_reason
15453     , line_location_rec.price_override
15454     , 'N'                            -- encumbered_flag
15455     , NVL2(l_tax_code_id, 'Y', 'N')  -- taxable_flag
15456     , l_tax_code_id
15457     , l_req_tax_user_override_flag
15458     , line_location_rec.shipment_type
15459     , line_location_rec.shipment_num
15460     , 'N'                           -- inspection_required_flag
15461     , DECODE(line_location_rec.value_basis,    -- receipt_required_flag
15462                'FIXED_PRICE', 'N',
15463                coalesce(item.receipt_required_flag,
15464                         vendor.receipt_required_flag,
15465                         params.receiving_flag,
15466                         'N'))
15467     , payitem_rcv_ctl_rec.days_early_receipt_allowed
15468     , payitem_rcv_ctl_rec.days_late_receipt_allowed
15469     , payitem_rcv_ctl_rec.enforce_ship_to_location_code
15470     , line_location_rec.ship_to_organization_id
15471     , coalesce(item.invoice_close_tolerance, params.invoice_close_tolerance, 100)
15472     , DECODE(line_location_rec.payment_type,
15473                'MILESTONE', 0,
15474                coalesce(item.receive_close_tolerance,
15475                         params.receive_close_tolerance,
15476                         100))
15477     , DECODE(line_location_rec.shipment_type,   -- acrrue_on_receipt_flag
15478               'PREPAYMENT', 'N',
15479               DECODE(coalesce(item.receipt_required_flag,
15480                               interface.receipt_required_flag,
15481                               vendor.receipt_required_flag,
15482                               params.receiving_flag,
15483                               'N'),
15484                       'N', 'N',
15485                       DECODE(params.expense_accrual_code,
15486                                 'PERIOD END', 'N', 'Y')))
15487     , payitem_rcv_ctl_rec.allow_substitute_receipts_flag
15488     , payitem_rcv_ctl_rec.receiving_routing_id
15489     , payitem_rcv_ctl_rec.qty_rcv_tolerance
15490     , payitem_rcv_ctl_rec.qty_rcv_exception_code
15491     , payitem_rcv_ctl_rec.receipt_days_exception_code
15492     , NULL     -- terms_id
15493     , NULL     -- ship_via_lookup_code
15494     , NULL     -- freight_terms_lookup_code
15495     , NULL     -- fob_lookup_code
15496     , line_location_rec.unit_of_measure   -- unit_meas_lookup_code
15497     , line_location_rec.promised_date     -- last_accept_date
15498             + payitem_rcv_ctl_rec.days_late_receipt_allowed
15499     , vendor.invoice_match_option
15500     , l_country_of_origin_code
15501     , NULL                -- vmi_flag
15502     , NULL                -- drop_ship_flag
15503     , NULL                -- consigned_flag
15504     , interface.transaction_flow_header_id
15505     , g_purchasing_ou_id
15506     , NULL       -- closed_for_receiving_date
15507     , NULL       -- closed_for_invoice_date
15508     , line_location_rec.value_basis
15509     , line_location_rec.matching_basis
15510     , line_location_rec.payment_type
15511     , line_location_rec.description
15512     , line_location_rec.work_approver_id
15513     , line_location_rec.bid_payment_id
15514     , 2                                 -- outsourced_assembly
15515     ,nvl2(g_calculate_tax_flag, 'CREATE', null)  --<eTax Integration R12>
15516 
15517     )
15518     RETURNING line_location_id INTO l_line_loc_id;
15519 
15520     d_progress := 220;
15521     IF (PO_LOG.d_stmt) THEN
15522       PO_LOG.stmt(d_module, d_progress, 'Inserted payitem.');
15523       PO_LOG.stmt(d_module, d_progress, 'l_line_loc_id', l_line_loc_id);
15524     END IF;
15525 
15526     d_progress := 230;
15527 
15528     -- create link between interface row and transaction row
15529     UPDATE po_line_locations_interface polli
15530     SET polli.line_location_id = l_line_loc_id
15531     WHERE polli.interface_line_location_id =
15532                          line_location_rec.interface_line_location_id;
15533 
15534     d_progress := 240;
15535 
15536     calculate_local('PO', 'SHIPMENT', l_line_loc_id);
15537 
15538     d_progress := 250;
15539     l_payitems_created := l_payitems_created + 1;
15540     x_line_loc_id_tbl.EXTEND;
15541     x_line_loc_id_tbl(l_payitems_created) := l_line_loc_id;
15542     l_payitem_tax_code_id_tbl.EXTEND;
15543     l_payitem_tax_code_id_tbl(l_payitems_created) := l_tax_code_id;
15544 
15545     -- set x_line_location_id to id of first actual (STANDARD) payitem
15546     IF ((x_line_location_id IS NULL)
15547         AND (line_location_rec.shipment_type = 'STANDARD')) THEN
15548       x_line_location_id := l_line_loc_id;
15549     END IF;
15550 
15551   END LOOP;  -- poll_interface_cursor loop
15552   CLOSE poll_interface_cursor;
15553 
15554   d_progress := 300;
15555 
15556   -- call create_payitem_dists to create distributions for all new payitems
15557   IF (PO_LOG.d_stmt) THEN
15558     PO_LOG.stmt(d_module, d_progress, 'Ready to call create_payitem_dists');
15559   END IF;
15560 
15561   create_payitem_dists(
15562     p_po_line_id        => p_po_line_id
15563   , p_req_line_id       => interface.requisition_line_id
15564   , p_interface_line_id => p_interface_line_id
15565   , p_precision         => p_precision
15566   , p_ext_precision     => p_ext_precision
15567   );
15568 
15569   d_progress := 310;
15570 
15571   IF (PO_LOG.d_stmt) THEN
15572     PO_LOG.stmt(d_module, d_progress, 'Done calling create_payitem dists');
15573   END IF;
15574 
15575   d_progress := 400;
15576 
15577  IF (PO_LOG.d_stmt) THEN
15578       PO_LOG.stmt(d_module, d_progress, 'calling tax api ');
15579  END IF;
15580 
15581  d_progress := 1420;
15582 
15583   IF (PO_LOG.d_proc) THEN
15584     PO_LOG.proc_end(d_module, 'x_line_location_id', x_line_location_id);
15585     PO_LOG.proc_end(d_module, 'x_line_loc_id_tbl',  x_line_loc_id_tbl);
15586     PO_LOG.proc_end(d_module);
15587   END IF;
15588 
15589 EXCEPTION
15590   WHEN OTHERS THEN
15591 
15592     IF (PO_LOG.d_exc) THEN
15593       PO_LOG.exc(d_module, d_progress, SQLCODE || SQLERRM);
15594     END IF;
15595 
15596     IF (poll_interface_cursor%ISOPEN) THEN
15597       CLOSE poll_interface_cursor;
15598     END IF;
15599 
15600     wrapup(interface.interface_header_id);
15601     RAISE;
15602 END create_payitems;
15603 
15604 
15605 -------------------------------------------------------------------------------
15606 --Start of Comments
15607 --Name: create_payitem_dists
15608 --Pre-reqs:
15609 --   PO Payitems have all been created.
15610 --Modifies:
15611 --  PO_DISTRIBUTIONS_ALL
15612 --Locks:
15613 --  None.
15614 --Function:
15615 --  Create all distributions for all payitems for a PO Line.
15616 --Parameters:
15617 --  IN:
15618 --    p_req_line_id: id of the requisition line that is the source of
15619 --                   the po line; null if no backing req.
15620 --    p_po_line_id: id of the line in po_lines_all
15621 --    p_interface_line_id: id of the line in po_lines_interface
15622 --    p_precision: precision of the currency desired.  Used to round amounts.
15623 --    p_ext_precision: extended precision of the currency desired.
15624 --                     Used to round prices
15625 --  OUT:
15626 --    None.
15627 --Notes:
15628 --  None
15629 --Testing:
15630 --  None
15631 --End of Comments
15632 -------------------------------------------------------------------------------
15633 PROCEDURE create_payitem_dists(
15634   p_po_line_id         IN NUMBER
15635 , p_req_line_id        IN NUMBER
15636 , p_interface_line_id  IN NUMBER
15637 , p_precision          IN NUMBER
15638 , p_ext_precision      IN NUMBER
15639 )
15640 IS
15641 
15642 d_progress   NUMBER;
15643 d_module     VARCHAR2(70) := 'po.plsql.PO_INTERFACE_S.create_payitem_dists';
15644 
15645 CURSOR payitem_acct_gen_cursor(p_po_line_id NUMBER)
15646 IS
15647   SELECT pod.po_distribution_id
15648        , pod.project_id
15649        , pod.task_id
15650        , pod.award_id
15651        , pod.expenditure_type
15652        , pod.expenditure_item_date
15653        , pod.expenditure_organization_id
15654        , pod.destination_type_code
15655        , pod.destination_organization_id
15656        , pod.destination_subinventory
15657        , pod.deliver_to_location_id
15658        , pod.deliver_to_person_id
15659        , pod.gl_encumbered_date
15660        , poll.price_override
15661        , poll.payment_type
15662        , pod.distribution_type
15663        , pod.rate
15664   FROM po_distributions_all pod,
15665        po_line_locations_all poll
15666   WHERE poll.po_line_id = p_po_line_id
15667     AND pod.line_location_id = poll.line_location_id
15668     AND pod.req_distribution_id IS NULL;
15669 
15670 payitem_acct_rec      payitem_acct_gen_cursor%ROWTYPE;
15671 
15672 l_line_loc_id_tbl              po_tbl_number;
15673 l_line_loc_value_basis_tbl     po_tbl_varchar30;
15674 l_dist_id_tbl                  po_tbl_number;
15675 
15676 l_return_status       VARCHAR2(1);
15677 l_msg_count           NUMBER;
15678 l_msg_data            VARCHAR2(2000);
15679 l_gl_date_option      VARCHAR2(25);
15680 l_sob_id              PO_REQ_DISTRIBUTIONS_ALL.set_of_books_id%TYPE;
15681 
15682 
15683 -- Acct. Generator Variables Start
15684 l_dest_charge_success          BOOLEAN   := TRUE;
15685 l_dest_variance_success        BOOLEAN   := TRUE;
15686 l_charge_success               BOOLEAN   := TRUE;
15687 l_budget_success               BOOLEAN   := TRUE;
15688 l_accrual_success              BOOLEAN   := TRUE;
15689 l_variance_success             BOOLEAN   := TRUE;
15690 
15691 l_dest_charge_account_id       NUMBER;
15692 l_dest_variance_account_id     NUMBER;
15693 l_code_combination_id          NUMBER;
15694 l_budget_account_id            NUMBER;
15695 l_accrual_account_id           NUMBER;
15696 l_variance_account_id          NUMBER;
15697 
15698 l_dest_charge_account_desc     VARCHAR2(2000);
15699 l_dest_variance_account_desc   VARCHAR2(2000);
15700 l_charge_account_desc          VARCHAR2(2000);
15701 l_budget_account_desc          VARCHAR2(2000);
15702 l_accrual_account_desc         VARCHAR2(2000);
15703 l_variance_account_desc        VARCHAR2(2000);
15704 
15705 l_dest_charge_account_flex     VARCHAR2(2000);
15706 l_dest_variance_account_flex   VARCHAR2(2000);
15707 l_charge_account_flex          VARCHAR2(2000);
15708 l_budget_account_flex          VARCHAR2(2000);
15709 l_accrual_account_flex         VARCHAR2(2000);
15710 l_variance_account_flex        VARCHAR2(2000);
15711 
15712 l_wf_itemkey                   VARCHAR2(80) := NULL;
15713 l_new_combination              BOOLEAN      := FALSE;
15714 l_fb_error_msg                 VARCHAR2(2000);
15715 
15716 l_acct_api_success             BOOLEAN;
15717 -- Acct. Generator Variables End
15718 
15719 
15720 BEGIN
15721 
15722   d_progress := 0;
15723   IF (PO_LOG.d_proc) THEN
15724     PO_LOG.proc_begin(d_module);
15725     PO_LOG.proc_begin(d_module, 'p_po_line_id', p_po_line_id);
15726     PO_LOG.proc_begin(d_module, 'p_req_line_id', p_req_line_id);
15727     PO_LOG.proc_begin(d_module, 'p_interface_line_id', p_interface_line_id);
15728   END IF;
15729 
15730   d_progress := 10;
15731 
15732   IF (p_req_line_id IS NOT NULL) THEN
15733 
15734     -- if backing req exists, use req distributions as base for creating
15735     -- po distributions.
15736 
15737     d_progress := 20;
15738 
15739     FND_PROFILE.GET('PO_AUTOCREATE_DATE', l_gl_date_option);
15740 
15741     IF ((params.po_encumbrance_flag = 'Y')
15742       AND (l_gl_date_option <> 'REQ GL DATE')
15743       AND (params.period_name IS NULL)) THEN
15744 
15745       -- derive period name if it isn't already known
15746 
15747       d_progress := 30;
15748 
15749       SELECT prd.set_of_books_id
15750       INTO l_sob_id
15751       FROM po_req_distributions_all prd
15752       WHERE prd.requisition_line_id = p_req_line_id
15753         AND ROWNUM = 1;
15754 
15755       d_progress := 40;
15756 
15757       PO_PERIODS_SV.get_period_name(
15758         x_sob_id  => l_sob_id
15759       , x_gl_date => SYSDATE
15760       , x_gl_period => params.period_name
15761       );
15762 
15763       IF (params.period_name IS NULL) THEN
15764         d_progress := 50;
15765         IF (PO_LOG.d_exc) THEN
15766           PO_LOG.exc(d_module, d_progress, 'Unable to find period name for SYSDATE');
15767         END IF;
15768         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
15769       END IF;
15770 
15771     END IF;  -- if params.po_encumbrance_flag = 'Y' AND ...
15772 
15773     -- create distributions from req distributions
15774 
15775     d_progress := 60;
15776 
15777     --SQL WHAT: Create payitem distributions from backing req. distributions
15778     --SQL WHY : Create all such payitem distributions in one place
15779 
15780     INSERT INTO po_distributions_all(
15781       po_distribution_id
15782     , last_update_date
15783     , last_updated_by
15784     , last_update_login
15785     , creation_date
15786     , created_by
15787     , po_header_id
15788     , po_line_id
15789     , line_location_id
15790     , distribution_num
15791     , req_distribution_id
15792     , set_of_books_id
15793     , code_combination_id
15794     , deliver_to_location_id
15795     , deliver_to_person_id
15796     , destination_type_code
15797     , destination_organization_id
15798     , destination_subinventory
15799     , project_id
15800     , task_id
15801     , award_id
15802     , end_item_unit_number
15803     , expenditure_type
15804     , project_accounting_context
15805     , destination_context
15806     , expenditure_organization_id
15807     , expenditure_item_date
15808     , rate
15809     , rate_date
15810     , budget_account_id
15811     , accrual_account_id
15812     , variance_account_id
15813     , accrued_flag
15814     , encumbered_flag
15815     , prevent_encumbrance_flag
15816     , gl_encumbered_date
15817     , gl_encumbered_period_name
15818     , recovery_rate
15819     , recoverable_tax
15820     , nonrecoverable_tax
15821     , accrue_on_receipt_flag
15822     , kanban_card_id
15823     , org_id
15824     , distribution_type
15825     , quantity_ordered
15826     , amount_ordered
15827     ,tax_attribute_update_code    --<eTax Integration R12>
15828     )
15829     SELECT
15830       PO_DISTRIBUTIONS_S.NEXTVAL
15831     , interface.last_update_date
15832     , interface.last_updated_by
15833     , interface.last_update_login
15834     , interface.creation_date
15835     , interface.created_by
15836     , interface.po_header_id
15837     , p_po_line_id
15838     , poll.line_location_id
15839     , prd.distribution_num
15840     , prd.distribution_id  --Bug 4744751: these 2 cols were reversed in order
15841     , prd.set_of_books_id  --Bug 4744751: these 2 cols were reversed in order
15842     , prd.code_combination_id
15843     , prl.deliver_to_location_id
15844     , prl.to_person_id
15845     , prl.destination_type_code
15846     , prl.destination_organization_id
15847     , prl.destination_subinventory
15848     , prd.project_id
15849     , prd.task_id
15850     , prd.award_id
15851     , prd.end_item_unit_number
15852     , prd.expenditure_type
15853     , prd.project_accounting_context
15854     , prl.destination_context
15855     , prd.expenditure_organization_id
15856     , prd.expenditure_item_date
15857     , interface.h_rate
15858     , interface.h_rate_date
15859     , DECODE(poll.shipment_type, 'PREPAYMENT', null, prd.budget_account_id)
15860     , prd.accrual_account_id
15861     , prd.variance_account_id
15862     , 'N'         -- accrued_flag
15863     , 'N'         -- encumbered_flag
15864     , DECODE(params.po_encumbrance_flag, 'Y',
15865                DECODE(poll.shipment_type, 'PREPAYMENT', 'Y', 'N'),
15866                null)  -- prevent_encumbrance_flag
15867     , (CASE        -- gl_encumbered_date
15868          WHEN (params.req_encumbrance_flag = 'Y' AND
15869                  l_gl_date_option = 'REQ GL DATE')
15870            THEN prd.gl_encumbered_date
15871          WHEN (params.po_encumbrance_flag = 'Y')
15872            THEN trunc(SYSDATE)
15873          ELSE NULL
15874        END)
15875     , (CASE        -- gl_encumbered_period_name
15876          WHEN (params.req_encumbrance_flag = 'Y' AND
15877                  l_gl_date_option = 'REQ GL DATE')
15878            THEN prd.gl_encumbered_period_name
15879          WHEN (params.po_encumbrance_flag = 'Y')
15880            THEN params.period_name
15881          ELSE NULL
15882        END)
15883     , prd.recovery_rate
15884     , prd.recoverable_tax
15885     , prd.nonrecoverable_tax
15886     , poll.accrue_on_receipt_flag
15887     , prl.kanban_card_id
15888     , g_purchasing_ou_id
15889     , poll.shipment_type
15890     , (CASE                     -- quantity_ordered
15891          WHEN poll.value_basis <> 'QUANTITY'
15892            THEN NULL
15893          WHEN poll.payment_type IN ('MILESTONE', 'DELIVERY')
15894            THEN ROUND((prd.req_line_quantity / prl.quantity) * poll.quantity, 15)
15895          WHEN poll.payment_type = 'RATE'
15896            THEN ROUND((prd.req_line_amount / prl.amount) * poll.quantity, 15)
15897        END)
15898     , (CASE                     -- amount_ordered
15899          WHEN poll.value_basis <> 'FIXED PRICE'
15900            THEN NULL
15901          ELSE ROUND((prd.req_line_amount / prl.amount) * poll.amount, p_precision)
15902        END)
15903        ,nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax integration R12>
15904     FROM po_line_locations_all poll
15905        , po_req_distributions_all prd
15906        , po_requisition_lines_all prl
15907     WHERE poll.po_line_id = p_po_line_id
15908       AND prd.requisition_line_id = p_req_line_id
15909       AND prl.requisition_line_id = prd.requisition_line_id
15910       AND poll.payment_type <> 'ADVANCE';
15911 
15912     d_progress := 70;
15913     IF (PO_LOG.d_stmt) THEN
15914       PO_LOG.stmt(d_module, d_progress, 'Payitems distributions created from requisition distributions.');
15915     END IF;
15916 
15917   ELSE
15918 
15919     -- no backing req exists; create distributions for payitems
15920     -- from scratch.  Accounts are not set here - they will
15921     -- be generated and populated later.
15922 
15923     d_progress := 80;
15924 
15925     IF ((params.po_encumbrance_flag = 'Y')
15926       AND (params.period_name IS NULL)) THEN
15927 
15928       -- derive period name if it isn't already known
15929       d_progress := 90;
15930 
15931       PO_PERIODS_SV.get_period_name(
15932         x_sob_id  => params.sob_id
15933       , x_gl_date => SYSDATE
15934       , x_gl_period => params.period_name
15935       );
15936 
15937       IF (params.period_name IS NULL) THEN
15938         d_progress := 100;
15939         IF (PO_LOG.d_exc) THEN
15940           PO_LOG.exc(d_module, d_progress, 'Unable to find period name for SYSDATE');
15941         END IF;
15942         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
15943       END IF;
15944 
15945     END IF;  -- if params.po_encumbrance_flag = 'Y' AND ...
15946 
15947     d_progress := 110;
15948 
15949     --SQL WHAT: Create payitem distributions in the case of no backing req.
15950     --SQL WHY : Create all such payitem distributions in one place
15951 
15952     INSERT INTO po_distributions_all(
15953       po_distribution_id
15954     , last_update_date
15955     , last_updated_by
15956     , last_update_login
15957     , creation_date
15958     , created_by
15959     , po_header_id
15960     , po_line_id
15961     , line_location_id
15962     , distribution_num
15963     , req_distribution_id
15964     , deliver_to_location_id
15965     , deliver_to_person_id
15966     , destination_type_code
15967     , destination_organization_id
15968     , destination_subinventory
15969     , rate
15970     , rate_date
15971     , accrued_flag
15972     , encumbered_flag
15973     , prevent_encumbrance_flag
15974     , gl_encumbered_date
15975     , gl_encumbered_period_name
15976     , accrue_on_receipt_flag
15977     , org_id
15978     , distribution_type
15979     , project_id
15980     , task_id
15981     , award_id
15982     , end_item_unit_number
15983     , expenditure_type
15984     , project_accounting_context
15985     , destination_context
15986     , expenditure_organization_id
15987     , expenditure_item_date
15988     , quantity_ordered
15989     , amount_ordered
15990     , set_of_books_id
15991     ,tax_attribute_update_code  --<eTax Integration R12>
15992     )
15993     SELECT
15994       PO_DISTRIBUTIONS_S.NEXTVAL
15995     , interface.last_update_date
15996     , interface.last_updated_by
15997     , interface.last_update_login
15998     , interface.creation_date
15999     , interface.created_by
16000     , interface.po_header_id
16001     , p_po_line_id
16002     , poll.line_location_id
16003     , 1                          -- distribution_num
16004     , NULL                       -- req_distribution_id
16005     , poll.ship_to_location_id
16006     , NULL                       -- deliver_to_person_id
16007     , 'EXPENSE'                  -- destination_type_code
16008     , poll.ship_to_organization_id
16009     , NULL                       -- destination_subinventory
16010     , interface.h_rate
16011     , interface.h_rate_date
16012     , 'N'                        -- accrued_flag
16013     , 'N'                        -- encumbered_flag
16014     , DECODE(params.po_encumbrance_flag, 'Y',
16015                DECODE(poll.shipment_type, 'PREPAYMENT', 'Y', 'N'),
16016                null)  -- prevent_encumbrance_flag
16017     , DECODE(params.po_encumbrance_flag, 'Y', trunc(SYSDATE), NULL)
16018     , DECODE(params.po_encumbrance_flag, 'Y', params.period_name, NULL)
16019     , poll.accrue_on_receipt_flag
16020     , g_purchasing_ou_id
16021     , poll.shipment_type
16022     , polli.project_id
16023     , polli.task_id
16024     , polli.award_id
16025     , NULL                       -- end_item_unit_number
16026     , polli.expenditure_type
16027     , NULL                       -- project_accounting_context
16028     , 'EXPENSE'                  -- destination_context
16029     , polli.expenditure_organization_id
16030     , polli.expenditure_item_date
16031     , poll.quantity
16032     , poll.amount
16033     , params.sob_id
16034     ,nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax integration R12>
16035     FROM po_line_locations_all poll
16036        , po_line_locations_interface polli
16037     WHERE poll.po_line_id = p_po_line_id
16038       AND poll.line_location_id = polli.line_location_id
16039       AND poll.payment_type <> 'ADVANCE';
16040 
16041     d_progress := 120;
16042     IF (PO_LOG.d_stmt) THEN
16043       PO_LOG.stmt(d_module, d_progress, 'Payitems distributions created from scratch.');
16044     END IF;
16045 
16046   END IF;  -- if p_req_line_id IS NOT NULL
16047 
16048   d_progress := 130;
16049 
16050   IF (interface.has_advance_flag = 'Y') THEN
16051 
16052     -- create advance distributions
16053     -- logic: copy distributions from first actuals payitem
16054 
16055     d_progress := 140;
16056 
16057     --SQL WHAT: Create payitem distributions for advance payitems
16058     --SQL WHY : Create all such payitem distributions in one place
16059 
16060     INSERT INTO po_distributions_all
16061     (
16062       po_distribution_id
16063     , last_update_date
16064     , last_updated_by
16065     , last_update_login
16066     , creation_date
16067     , created_by
16068     , po_header_id
16069     , po_line_id
16070     , line_location_id
16071     , distribution_num
16072     , req_distribution_id
16073     , deliver_to_location_id
16074     , deliver_to_person_id
16075     , destination_type_code
16076     , destination_organization_id
16077     , destination_subinventory
16078     , rate
16079     , rate_date
16080     , accrued_flag
16081     , encumbered_flag
16082     , prevent_encumbrance_flag
16083     , gl_encumbered_date
16084     , gl_encumbered_period_name
16085     , accrue_on_receipt_flag
16086     , org_id
16087     , distribution_type
16088     , amount_ordered
16089     , quantity_ordered
16090     , project_id
16091     , task_id
16092     , award_id
16093     , end_item_unit_number
16094     , expenditure_type
16095     , project_accounting_context
16096     , destination_context
16097     , expenditure_organization_id
16098     , expenditure_item_date
16099     , set_of_books_id
16100     ,tax_attribute_update_code  --<eTax Integration R12>
16101     )
16102     SELECT
16103       PO_DISTRIBUTIONS_S.NEXTVAL
16104     , interface.last_update_date
16105     , interface.last_updated_by
16106     , interface.last_update_login
16107     , interface.creation_date
16108     , interface.created_by
16109     , interface.po_header_id
16110     , p_po_line_id
16111     , adv.line_location_id
16112     , pod.distribution_num           -- distribution_num
16113     , NULL                           -- req_distribution_id
16114     , pod.deliver_to_location_id
16115     , pod.deliver_to_person_id
16116     , pod.destination_type_code
16117     , pod.destination_organization_id
16118     , pod.destination_subinventory
16119     , pod.rate
16120     , pod.rate_date
16121     , pod.accrued_flag
16122     , pod.encumbered_flag
16123     , DECODE(params.po_encumbrance_flag, 'Y', 'Y', null) --prevent_enc_flag
16124     , NULL                           -- gl_encumbered_date
16125     , NULL                           -- gl_encumbered_period_name
16126     , adv.accrue_on_receipt_flag
16127     , pod.org_id
16128     , adv.shipment_type
16129     , ROUND(                         -- amount_ordered
16130        (NVL(pod.amount_ordered, deliv.price_override * pod.quantity_ordered)
16131         / NVL(deliv.amount, deliv.price_override * deliv.quantity))
16132          * adv.amount, 15)
16133     , NULL                           -- quantity_ordered
16134     , pod.project_id
16135     , pod.task_id
16136     , pod.award_id
16137     , pod.end_item_unit_number
16138     , pod.expenditure_type
16139     , pod.project_accounting_context
16140     , pod.destination_context
16141     , pod.expenditure_organization_id
16142     , pod.expenditure_item_date
16143     , params.sob_id
16144     ,nvl2(g_calculate_tax_flag, 'CREATE', null)  --<eTax integration R12>
16145       FROM po_line_locations_all adv,
16146            po_line_locations_all deliv,
16147            po_distributions_all pod
16148       WHERE adv.po_line_id = p_po_line_id
16149         AND adv.payment_type = 'ADVANCE'
16150         AND deliv.line_location_id =
16151            ( SELECT poll.line_location_id
16152              FROM po_line_locations_all poll
16153              WHERE poll.po_line_id = p_po_line_id
16154                AND poll.shipment_type = 'STANDARD'
16155                AND poll.shipment_num =
16156                     ( SELECT min(poll2.shipment_num)
16157                       FROM po_line_locations_all poll2
16158                       WHERE poll2.po_line_id = poll.po_line_id
16159                         AND poll2.shipment_type = 'STANDARD'))
16160         AND pod.line_location_id = deliv.line_location_id;
16161 
16162     d_progress := 150;
16163     IF (PO_LOG.d_stmt) THEN
16164       PO_LOG.stmt(d_module, d_progress, 'Advance distributions created.');
16165     END IF;
16166 
16167   END IF;  -- if interface.has_advance_flag
16168 
16169   d_progress := 160;
16170 
16171   -- calibrate last distribution for each pay item
16172 
16173   SELECT poll.line_location_id, poll.value_basis
16174   BULK COLLECT INTO l_line_loc_id_tbl, l_line_loc_value_basis_tbl
16175   FROM po_line_locations_all poll
16176   WHERE poll.po_line_id = p_po_line_id;
16177 
16178   FOR i in 1..l_line_loc_id_tbl.COUNT
16179   LOOP
16180 
16181     IF (l_line_loc_value_basis_tbl(i) = 'FIXED PRICE') THEN
16182       calibrate_last_dist_amount(l_line_loc_id_tbl(i));
16183     ELSE
16184       calibrate_last_dist_quantity(l_line_loc_id_tbl(i));
16185     END IF;
16186 
16187   END LOOP;
16188 
16189   d_progress := 170;
16190 
16191   -- now, generate accounts for all distributions that are not
16192   -- tied to a backing req. distribution
16193 
16194   OPEN payitem_acct_gen_cursor(p_po_line_id);
16195   LOOP
16196 
16197     FETCH payitem_acct_gen_cursor INTO payitem_acct_rec;
16198     EXIT WHEN payitem_acct_gen_cursor%NOTFOUND;
16199 
16200     d_progress := 180;
16201     IF (PO_LOG.d_stmt) THEN
16202       PO_LOG.stmt(d_module, d_progress, 'Calling account generator wf method.');
16203       PO_LOG.stmt(d_module, d_progress, 'payitem_acct_rec.po_distribution_id', payitem_acct_rec.po_distribution_id);
16204     END IF;
16205 
16206     l_acct_api_success := PO_WF_BUILD_ACCOUNT_INIT.Start_Workflow(
16207       x_purchasing_ou_id  =>  g_purchasing_ou_id
16208     , x_transaction_flow_header_id  => NULL
16209     , x_dest_charge_success         => l_dest_charge_success
16210     , x_dest_charge_account_id      => l_dest_charge_account_id
16211     , x_dest_charge_account_desc    => l_dest_charge_account_desc
16212     , x_dest_charge_account_flex    => l_dest_charge_account_flex
16213     , x_dest_variance_success       => l_dest_variance_success
16214     , x_dest_variance_account_id    => l_dest_variance_account_id
16215     , x_dest_variance_account_desc  => l_dest_charge_account_desc
16216     , x_dest_variance_account_flex  => l_dest_charge_account_flex
16217     , x_charge_success              => l_charge_success
16218     , x_budget_success              => l_budget_success
16219     , x_accrual_success             => l_accrual_success
16220     , x_variance_success            => l_variance_success
16221     , x_code_combination_id         => l_code_combination_id
16222     , x_budget_account_id           => l_budget_account_id
16223     , x_accrual_account_id          => l_accrual_account_id
16224     , x_variance_account_id         => l_variance_account_id
16225     , x_charge_account_flex         => l_charge_account_flex
16226     , x_budget_account_flex         => l_budget_account_flex
16227     , x_accrual_account_flex        => l_accrual_account_flex
16228     , x_variance_account_flex       => l_variance_account_flex
16229     , x_charge_account_desc         => l_charge_account_desc
16230     , x_budget_account_desc         => l_budget_account_desc
16231     , x_accrual_account_desc        => l_accrual_account_desc
16232     , x_variance_account_desc       => l_variance_account_desc
16233     , x_coa_id                      => params.coa_id
16234     , x_bom_resource_id             => NULL
16235     , x_bom_cost_element_id         => NULL
16236     , x_category_id                 => interface.category_id
16237     , x_item_id                     => interface.item_id
16238     , x_type_lookup_code            => interface.document_subtype
16239     , x_line_type_id                => interface.line_type_id
16240     , x_agent_id                    => interface.agent_id
16241     , x_destination_type_code       => payitem_acct_rec.destination_type_code
16242     , x_deliver_to_location_id      => payitem_acct_rec.deliver_to_location_id
16243     , x_deliver_to_person_id        => payitem_acct_rec.deliver_to_person_id
16244     , x_destination_organization_id => payitem_acct_rec.destination_organization_id
16245     , x_destination_subinventory    => payitem_acct_rec.destination_subinventory
16246     , x_expenditure_type            => payitem_acct_rec.expenditure_type
16247     , x_expenditure_organization_id => payitem_acct_rec.expenditure_organization_id
16248     , x_expenditure_item_date       => payitem_acct_rec.expenditure_item_date
16249     , x_project_id                  => payitem_acct_rec.project_id
16250     , x_task_id                     => payitem_acct_rec.task_id
16251     , x_award_id                    => payitem_acct_rec.award_id
16252     , x_from_type_lookup_code       => NULL
16253     , x_from_header_id              => NULL
16254     , x_from_line_id                => NULL
16255     , x_vendor_id                   => interface.vendor_id
16256     , x_vendor_site_id              => interface.vendor_site_id
16257     , x_wip_entity_id               => NULL
16258     , x_wip_entity_type             => NULL
16259     , x_wip_line_id                 => NULL
16260     , x_wip_repetitive_schedule_id  => NULL
16261     , x_wip_operation_seq_num       => NULL
16262     , x_wip_resource_seq_num        => NULL
16263     , x_po_encumberance_flag        => params.po_encumbrance_flag
16264     , x_gl_encumbered_date          => payitem_acct_rec.gl_encumbered_date
16265     , x_result_billable_flag        => NULL
16266     , wf_itemkey                    => l_wf_itemkey
16267     , x_new_combination             => l_new_combination
16268     , header_att1        => NULL
16269     , header_att2        => NULL
16270     , header_att3        => NULL
16271     , header_att4        => NULL
16272     , header_att5        => NULL
16273     , header_att6        => NULL
16274     , header_att7        => NULL
16275     , header_att8        => NULL
16276     , header_att9        => NULL
16277     , header_att10       => NULL
16278     , header_att11       => NULL
16279     , header_att12       => NULL
16280     , header_att13       => NULL
16281     , header_att14       => NULL
16282     , header_att15       => NULL
16283     , line_att1          => NULL
16284     , line_att2          => NULL
16285     , line_att3          => NULL
16286     , line_att4          => NULL
16287     , line_att5          => NULL
16288     , line_att6          => NULL
16289     , line_att7          => NULL
16290     , line_att8          => NULL
16291     , line_att9          => NULL
16292     , line_att10         => NULL
16293     , line_att11         => NULL
16294     , line_att12         => NULL
16295     , line_att13         => NULL
16296     , line_att14         => NULL
16297     , line_att15         => NULL
16298     , shipment_att1      => NULL
16299     , shipment_att2      => NULL
16300     , shipment_att3      => NULL
16301     , shipment_att4      => NULL
16302     , shipment_att5      => NULL
16303     , shipment_att6      => NULL
16304     , shipment_att7      => NULL
16305     , shipment_att8      => NULL
16306     , shipment_att9      => NULL
16307     , shipment_att10     => NULL
16308     , shipment_att11     => NULL
16309     , shipment_att12     => NULL
16310     , shipment_att13     => NULL
16311     , shipment_att14     => NULL
16312     , shipment_att15     => NULL
16313     , distribution_att1  => NULL
16314     , distribution_att2  => NULL
16315     , distribution_att3  => NULL
16316     , distribution_att4  => NULL
16317     , distribution_att5  => NULL
16318     , distribution_att6  => NULL
16319     , distribution_att7  => NULL
16320     , distribution_att8  => NULL
16321     , distribution_att9  => NULL
16322     , distribution_att10 => NULL
16323     , distribution_att11 => NULL
16324     , distribution_att12 => NULL
16325     , distribution_att13 => NULL
16326     , distribution_att14 => NULL
16327     , distribution_att15 => NULL
16328     , FB_ERROR_MSG       => l_fb_error_msg
16329     , p_func_unit_price  =>
16330         ROUND(payitem_acct_rec.price_override * NVL (payitem_acct_rec.rate, 1),
16331                 NVL(p_ext_precision, 15))
16332     , p_distribution_type    => payitem_acct_rec.distribution_type
16333     , p_payment_type         => payitem_acct_rec.payment_type
16334     );
16335 
16336     d_progress := 190;
16337     IF (PO_LOG.d_stmt) THEN
16338       PO_LOG.stmt(d_module, d_progress, 'Finished account generator call.');
16339       PO_LOG.stmt(d_module, d_progress, 'l_acct_api_success', l_acct_api_success);
16340       PO_LOG.stmt(d_module, d_progress, 'l_charge_success', l_charge_success);
16341       PO_LOG.stmt(d_module, d_progress, 'l_variance_success', l_variance_success);
16342       PO_LOG.stmt(d_module, d_progress, 'l_budget_success', l_budget_success);
16343       PO_LOG.stmt(d_module, d_progress, 'l_accrual_success', l_accrual_success);
16344     END IF;
16345 
16346     -- follow same behavior as with shipment distributions:
16347     -- if account generator failed, do not create distribution
16348 
16349     d_progress := 200;
16350 
16351     IF ( l_acct_api_success AND l_charge_success
16352          --Bug 5645242: Added the check to test if the charge account id generated is null or 0,
16353          --if this is the case, then we should delete the distribution record.
16354          AND  (NVL(l_code_combination_id , 0) <> 0)
16355          AND l_variance_success AND l_accrual_success
16356          AND (l_budget_success OR (NVL(params.po_encumbrance_flag, 'N') <> 'Y')))
16357     THEN
16358 
16359       d_progress := 210;
16360       IF (PO_LOG.d_stmt) THEN
16361         PO_LOG.stmt(d_module, d_progress, 'Updating dist. with acct. info');
16362       END IF;
16363 
16364       --SQL WHAT: Update account information for a po distribution
16365       --SQL WHY : PO Distributions that don't have a backing req need to
16366       --          have account defaulted from account generator.
16367 
16368       UPDATE po_distributions_all pod
16369       SET pod.code_combination_id = l_code_combination_id
16370         , pod.budget_account_id = DECODE(NVL(params.po_encumbrance_flag, 'N'),
16371                                     'Y', l_budget_account_id,
16372                                     NULL)
16373         , pod.accrual_account_id = l_accrual_account_id
16374         , pod.variance_account_id = l_variance_account_id
16375       WHERE pod.po_distribution_id = payitem_acct_rec.po_distribution_id;
16376 
16377     ELSE
16378 
16379       d_progress := 220;
16380       IF (PO_LOG.d_stmt) THEN
16381         PO_LOG.stmt(d_module, d_progress, 'Deleting distribution - acct. gen failure');
16382       END IF;
16383 
16384       DELETE FROM po_distributions_all pod
16385       WHERE pod.po_distribution_id =
16386               payitem_acct_rec.po_distribution_id;
16387 
16388     END IF;  -- if l_acct_api_success AND ...
16389 
16390   END LOOP;  -- payitem_acct_gen_cursor loop
16391   CLOSE payitem_acct_gen_cursor;
16392 
16393   d_progress := 300;
16394   IF (PO_LOG.d_stmt) THEN
16395     PO_LOG.stmt(d_module, d_progress, 'Calling update_award_distributions');
16396   END IF;
16397 
16398   update_award_distributions(
16399     p_table_type => 'ALL'
16400   , p_po_line_id => p_po_line_id
16401   );
16402 
16403   d_progress := 310;
16404 
16405   SELECT pod.po_distribution_id
16406   BULK COLLECT INTO l_dist_id_tbl
16407   FROM po_distributions_all pod
16408   WHERE pod.po_line_id = p_po_line_id;
16409 
16410   d_progress := 320;
16411 
16412   FOR i in 1..l_dist_id_tbl.COUNT
16413   LOOP
16414     calculate_local('PO', 'DISTRIBUTION', l_dist_id_tbl(i));
16415   END LOOP;
16416 
16417   IF (PO_LOG.d_proc) THEN
16418     PO_LOG.proc_end(d_module);
16419   END IF;
16420 
16421 EXCEPTION
16422   WHEN OTHERS THEN
16423     IF (PO_LOG.d_exc) THEN
16424       PO_LOG.exc(d_module, d_progress, SQLCODE || SQLERRM);
16425     END IF;
16426 
16427     IF (payitem_acct_gen_cursor%ISOPEN) THEN
16428       CLOSE payitem_acct_gen_cursor;
16429     END IF;
16430 
16431     wrapup(interface.interface_header_id);
16432     RAISE;
16433 END create_payitem_dists;
16434 
16435 -- <Complex Work R12 End>
16436 
16437 END PO_INTERFACE_S;