DBA Data[Home] [Help]

PACKAGE BODY: APPS.PO_INTERFACE_S

Source


1 PACKAGE BODY PO_INTERFACE_S AS
2 /* $Header: POXBWP1B.pls 120.73.12010000.5 2009/01/06 06:37:38 adbharga 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.ship_to_location_id ship_to_location_id,
168               phi.bill_to_location_id bill_to_location_id,
169               phi.terms_id terms_id,
170               phi.freight_carrier ship_via_lookup_code,
171               phi.fob fob_lookup_code,
172               phi.pay_on_code pay_on_code,
173               phi.freight_terms freight_terms_lookup_code,
174               phi.creation_date creation_date,
175               phi.created_by created_by,
176               phi.last_update_date last_update_date,
177               phi.last_updated_by last_updated_by,
178               phi.last_update_login last_update_login,
179               phi.revision_num revision_num,
180               phi.print_count print_count,
181               phi.closed_code h_closed_code,
182               phi.frozen_flag frozen_flag,
183               phi.firm_flag h_firm_status_lookup_code,
184               pli.firm_flag l_firm_status_lookup_code,
185               phi.confirming_order_flag confirming_order_flag,
186               phi.acceptance_required_flag acceptance_required_flag,
187               phi.currency_code h_currency_code,
188               phi.rate_type_code h_rate_type,
189               phi.rate_date h_rate_date,
190               phi.rate h_rate,
191               phi.min_release_amount h_min_release_amount,
192               pli.min_release_amount l_min_release_amount,
193               phi.release_date release_date,
194               phi.document_subtype quote_type_lookup_code,
195               phi.vendor_list_header_id vendor_list_header_id,
196 --DPCARD{
197               phi.pcard_id,
198 --DPCARD}
199               pli.interface_line_id interface_line_id,
200               pli.line_num line_num,
201               pli.shipment_num shipment_num,
202               pli.line_location_id line_location_id,
203               pli.requisition_line_id requisition_line_id,
204               pli.line_type_id line_type_id,
205               pli.item_id item_id,
206               pli.category_id category_id,
207               pli.item_revision item_revision,
208               pli.item_description item_description,
209               -- <FPJ Advanced Price START>
210               pli.base_unit_price base_unit_price,
211               -- <FPJ Advanced Price END>
212               pli.unit_price unit_price,
213               pli.price_type price_type_lookup_code,
214               pli.unit_of_measure unit_meas_lookup_code,
215               pli.un_number_id un_number_id,
216               pli.hazard_class_id hazard_class_id,
217               -- pli.contract_num contract_num,   -- <GC FPJ>
218               pli.contract_id contract_id,         -- <GC FPJ>
219               pli.vendor_product_num vendor_product_num,
220               pli.type_1099 type_1099,
221               pli.need_by_date need_by_date,
222               pli.quantity quantity,
223               pli.amount,                                     -- <SERVICES FPJ>
224               pli.negotiated_by_preparer_flag negotiated_by_preparer_flag,
225               pli.closed_code l_closed_code,
226               pli.transaction_reason_code transaction_reason_code,
227               pli.from_header_id from_header_id,
228               pli.from_line_id from_line_id,
229               pli.from_line_location_id from_line_location_id,-- <SERVICES FPJ>
230               pli.receipt_required_flag receipt_required_flag,
231 --DWR4{
232               pli.tax_status_indicator,
233 --DWR4}
234               pli.tax_code_id,
235         pli.note_to_vendor,
236         --togeorge 09/27/2000
237         --Bug#1433282
238         --added note to receiver and oke columns
239         pli.note_to_receiver,
240         pli.oke_contract_header_id,
241         pli.oke_contract_version_id,
242         pdi.oke_contract_line_id,
243         pdi.oke_contract_deliverable_id,
244 -- adding process related columns
245 -- start of 1548597
246               pli.secondary_unit_of_measure,
247               pli.secondary_quantity,
248               pli.preferred_grade,
249 -- end of 1548597
250         --<SOURCING TO PO FPH START>
251         phi.amount_agreed,          --Bug# 2288408
252         phi.effective_date,         --Bug# 2288408
253         phi.expiration_date,        --Bug# 2288408
254               pli.committed_amount,     --Bug# 2288408
255               pli.promised_date promised_date,
256               pli.auction_header_id,
257               pli.auction_line_number,
258         pli.auction_display_number,
259               pli.bid_number,
260               pli.bid_line_number,
261         pli.orig_from_req_flag,
262             pdi.charge_account_id,
263         pdi.accrual_account_id,
264         pdi.variance_account_id,
265         pdi.encumbered_flag,
266         pdi.budget_account_id,
267         --<SOURCING TO PO FPH END>
268         --<RENEG BLANKET FPI START>
269         phi.amount_limit,
270               phi.global_agreement_flag,
271               pli.ship_to_location_id line_ship_to_loc_id,
272               pli.ship_to_organization_id line_ship_to_org_id,
273               pli.price_discount,
274               pli.effective_date line_effective_date,
275               pli.expiration_date line_expiration_date,
276               pli.shipment_type,
277               --Bug #2715037 :Need to capture this coming from Sourcing
278               pli.price_break_lookup_code,
279               --<RENEG BLANKET FPI END>
280         pdi.destination_type_code destination_type_code,
281         pdi.deliver_to_location_id deliver_to_location_id,
282         pdi.destination_organization_id destination_organization_id,
283               pli.vmi_flag,   --  VMI FPH
284               pli.drop_ship_flag,   --  <DropShip FPJ>
285         --<CONSUME REQ DEMAND FPI>
286         phi.consume_req_demand_flag,
287               pli.consigned_flag,      -- CONSIGNED FPI
288               phi.shipping_control,    -- <INBOUND LOGISTICS FPJ>
289               pli.supplier_ref_number, --<CONFIG_ID FPJ>
290               pli.job_id,                                     -- <SERVICES FPJ>
291               pli.contractor_first_name,                      -- <SERVICES FPJ>
292               pli.contractor_last_name,                       -- <SERVICES FPJ>
293         pli.transaction_flow_header_id,                 -- <Shared Proc. FPJ>
294         phi.org_id                                      -- <R12 MOAC>
295               --<Complex Work R12 Start>
296             , phi.style_id              style_id
297             , pli.retainage_rate        retainage_rate
298             , pli.max_retainage_amount  max_retainage_amount
299             , pli.progress_payment_rate progress_payment_rate
300             , pli.recoupment_rate       recoupment_rate
301             , pli.advance_amount        advance_amount
302             , NVL(pli.line_loc_populated_flag, 'N') poll_interface_pop_flag
303             , NVL2(pli.advance_amount, 'Y', 'N') has_advance_flag
304               --<Complex Work R12 End>
305               --<Unified Catalog R12 Begin: Bug#4656615>
306             , phi.created_language    created_language
307             , phi.cpa_reference       cpa_reference
308             , pli.ip_category_id      ip_category_id
309             , pli.supplier_part_auxid supplier_part_auxid
310             , pli.catalog_name        catalog_name
311               --<Unified Catalog R12 End>
312          FROM po_headers_interface phi,
313               po_lines_interface pli,
314         po_distributions_interface pdi
315         WHERE phi.interface_header_id = pli.interface_header_id
316     AND pli.interface_line_id = pdi.interface_line_id
317           AND phi.interface_header_id = x_interface_header_id
318     AND pdi.interface_distribution_id =
319     (SELECT min(pdi2.interface_distribution_id)
320            FROM   po_distributions_interface pdi2
321            WHERE  pdi2.interface_line_id = pli.interface_line_id)
322      ORDER BY pli.line_num,
323         --<RENEG BLANKET FPI>
324               nvl(pli.shipment_num,0),
325               pli.unit_price;
326 
327 /* Global variable declarations */
328 who who_record_type;
329 
330 vendor vendor_defaults_type;
331 
332 item item_defaults_type;
333 
334 params system_parameters_type;
335 
336 rc rcv_controls_type;
337 
338 interface interface_cursor%rowtype;
339 --<SOURCING TO PO FPH START>
340 g_sourcing_errorcode number;
341 g_interface_source_code varchar2(25);
342 --<SOURCING TO PO FPH END>
343 
344 g_mode              po_headers_interface.action%type := null;
345 g_group_code        po_headers_interface.group_code%type := null;
346 g_document_subtype  po_headers_interface.document_subtype%type := null;
347 g_po_release_id     number := null;
348 g_document_type     varchar2(25) := null;
349 g_number_records_processed number;
350 g_purchasing_ou_id  PO_HEADERS_ALL.org_id%TYPE;  --<Shared Proc FPJ>
351 g_hdr_requesting_ou_id  PO_HEADERS_ALL.org_id%TYPE;  --<Shared Proc FPJ>
352 g_rate_for_req_fields NUMBER;  --<Shared Proc FPJ>
353 g_line_requesting_ou_id PO_REQUISITION_LINES_ALL.org_id%TYPE; --<Sourcing 11.5.10+>
354 
355 /* Global variable to hold number of req lines
356 ** in the po_lines_interface table. Thie determines
357 ** if we copy project_id, task_id from req to rfq
358 */
359 g_req_lines_to_process  number:=0;
360 
361 -- Bug 2875346 start.
362 --< Bug 3210331 Start >
363 -- Debugging booleans used to bypass logging when turned off
364 g_debug_stmt  CONSTANT BOOLEAN := PO_DEBUG.is_debug_stmt_on;
365 g_debug_unexp CONSTANT BOOLEAN := PO_DEBUG.is_debug_unexp_on;
366 --< Bug 3210331 End >
367 
368 g_calculate_tax_flag VARCHAR2(1); --<eTax Integration Enhancement R12>
369 
370 /*===========================================================================*/
371 /*======================== SPECIFICATIONS (PRIVATE) =========================*/
372 /*===========================================================================*/
373 
374 -- Private function to check if a req line has a one-time location
375 FUNCTION has_one_time_location(p_req_line_id IN NUMBER)
376     RETURN BOOLEAN;
377 
378 -- Bug 2875346 end.
379 
380 /* Private Procedure prototypes */
381 PROCEDURE get_system_defaults;
382 
383 /* bgu, Dec. 10, 98 */
384 PROCEDURE get_invoice_match_option(x_vendor_id    IN number,
385          x_vendor_site_id IN number,
386          x_invoice_match_option OUT NOCOPY varchar2);
387 
388 PROCEDURE wrapup(x_interface_header_id IN number);
389 
390 PROCEDURE update_shipment(x_interface_header_id IN NUMBER,
391         x_po_shipment_num IN NUMBER,
392         x_po_line_num IN NUMBER,
393         x_requisition_line_id IN NUMBER,
394         x_po_line_id IN NUMBER,
395         x_document_num IN VARCHAR2,
396         x_release_num IN NUMBER,
397                           x_create_new_line IN VARCHAR2,  -- GA FPI
398                           x_row_id IN VARCHAR2 default null);
399 
400 PROCEDURE group_interface_lines(
401   x_interface_header_id IN number
402 , p_is_complex_work_po  IN BOOLEAN
403 );
404 
405 -- <Complex Work R12>: Added p_is_complex_work_po parameter
406 PROCEDURE setup_interface_tables(
407   x_interface_header_id  IN             NUMBER
408 , x_document_id          IN OUT NOCOPY  NUMBER
409 , p_is_complex_work_po   IN             BOOLEAN
410 );
411 
412 -- <Complex Work R12>: Added p_is_complex_work_po parameter
413 PROCEDURE create_line(
414   x_interface_header_id IN NUMBER
415 , p_is_complex_work_po  IN BOOLEAN
416 );
417 
418 PROCEDURE create_shipment(
419   x_po_line_id IN number,
420   p_rate_for_req_fields IN NUMBER, -- <ACHTML R12>
421   x_line_location_id IN OUT NOCOPY number,
422   p_outsourced_assembly IN NUMBER --<SHIKYU R12>
423 );
424 
425 PROCEDURE create_distributions(
426   x_po_line_id IN number,
427   x_line_location_id IN number,
428   x_po_release_id IN number,
429   p_rate_for_req_fields IN NUMBER --<ACHTML R12>
430 );
431 
432 -- <Complex Work R12 Start>
433 PROCEDURE create_payitems(
434   p_interface_line_id IN         NUMBER
435 , p_po_line_id        IN         NUMBER
436 , p_precision         IN         NUMBER
437 , p_ext_precision     IN         NUMBER
438 , x_line_location_id  OUT NOCOPY NUMBER
439 , x_line_loc_id_tbl   OUT NOCOPY po_tbl_number
440 );
441 
442 PROCEDURE create_payitem_dists(
443   p_po_line_id         IN NUMBER
444 , p_req_line_id        IN NUMBER
445 , p_interface_line_id  IN NUMBER
446 , p_precision          IN NUMBER
447 , p_ext_precision      IN NUMBER
448 );
449 
450 PROCEDURE calibrate_last_dist_quantity (
451   p_line_location_id   IN   NUMBER
452 );
453 
454 -- <Complex Work R12 End>
455 
456 PROCEDURE calibrate_last_dist_amount                           -- <BUG 3322948>
457 (   p_line_location_id       IN       NUMBER
458 );
459 
460 PROCEDURE create_po(x_interface_header_id IN number,
461         x_document_id IN OUT NOCOPY number
462            ,p_sourcing_k_doc_type  IN VARCHAR2 DEFAULT NULL --<CONTERMS FPJ>
463            ,p_conterms_exist_flag  IN VARCHAR2 DEFAULT 'N'  --<CONTERMS FPJ>
464      ,p_document_creation_method IN VARCHAR2 DEFAULT NULL--<DBI FPJ>
465          );
466 
467 PROCEDURE create_rfq(x_interface_header_id IN number,
468          x_document_id IN OUT NOCOPY number);
469 
470 PROCEDURE get_shipment_num(x_need_by_date IN DATE,
471          x_deliver_to_location_id IN NUMBER,
472          x_destination_org_id IN NUMBER,
473          x_po_line_id IN NUMBER,
474          x_po_line_num IN NUMBER,
475          x_requisition_line_id IN NUMBER,
476                x_interface_header_id IN NUMBER,
477          x_po_shipment_num IN OUT NOCOPY NUMBER,
478          --togeorge 09/27/2000
479          x_note_to_receiver IN varchar2,
480 -- start of 1548597
481                            x_preferred_grade IN VARCHAR2,
482 -- end of 15485097
483                            x_vmi_flag        IN VARCHAR2,         --  VMI FPH
484                            x_consigned_flag IN VARCHAR2   ,       -- CONSIGNED FPI
485                            x_drop_ship_flag IN VARCHAR2,          --  <DropShip FPJ>
486                            x_create_new_line OUT NOCOPY VARCHAR2 ) ;     -- GA FPI
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: 'PO', '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 -- <Complex Work R12>: Add parameters p_table_type, p_po_line_id
522 PROCEDURE update_award_distributions(
523   p_table_type     IN    VARCHAR2   DEFAULT 'INTERFACE'
524 , p_po_line_id     IN    NUMBER     DEFAULT NULL
525 ); --<GRANTS FPJ>
526 
527 --<Shared Proc FPJ START>
528 PROCEDURE get_rate_for_req_price(
529   p_requesting_ou_id IN NUMBER, -- <ACHTML R12>
530   p_purchasing_ou_id IN NUMBER, -- <ACHTML R12>
531   p_po_currency_code IN VARCHAR2,
532   p_rate_type        IN VARCHAR2,
533   p_rate_date        IN DATE,
534   x_rate             OUT NOCOPY NUMBER
535 );
536 --<Shared Proc FPJ END>
537 
538 PROCEDURE do_currency_conversion                               -- <BUG 3322948>
539 (   p_order_type_lookup_code   IN              VARCHAR2
540 ,   p_interface_source_code    IN              VARCHAR2
541 ,   p_rate                     IN              NUMBER
542 ,   p_po_currency_code         IN              VARCHAR2
543 ,   p_requisition_line_id      IN              NUMBER
544 ,   x_quantity                 IN OUT NOCOPY   NUMBER
545 ,   x_unit_price               IN OUT NOCOPY   NUMBER
546 ,   x_base_unit_price          IN OUT NOCOPY   NUMBER --bug 3401653
547 ,   x_amount                   IN OUT NOCOPY   NUMBER
548 );
549 
550 /*===========================================================================*/
551 /*============================ BODY (PUBLIC) ================================*/
552 /*===========================================================================*/
553 
554 --<SOURCING TO PO FPH START>
555 PROCEDURE create_documents(x_batch_id     IN     number,
556          x_document_id  IN OUT NOCOPY number,
557          x_number_lines   IN OUT NOCOPY number,
558          p_document_creation_method IN VARCHAR2,  --<DBI FPJ>
559          p_orig_org_id                IN               NUMBER DEFAULT NULL    -- <R12 MOAC>
560 ) IS
561   x_document_number po_headers.segment1%type;
562   x_errorcode   number;
563   l_progress VARCHAR2(3) := '000';                          --< Bug 3210331 >
564   l_api_name VARCHAR2(30) := 'create_documents(wrapper1)';  --< Bug 3210331 >
565 BEGIN
566   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
567       PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
568   END IF;
569 
570   create_documents(x_batch_id => x_batch_id,
571        x_document_id => x_document_id,
572        x_number_lines => x_number_lines,
573        x_document_number => x_document_number,
574        x_errorcode => x_errorcode,
575        p_document_creation_method => p_document_creation_method, --<DBI FPJ>
576                    p_orig_org_id => p_orig_org_id                 -- <R12 MOAC>
577        );
578 
579   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
580       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
581                           p_token    => l_progress,
582                           p_message  => 'error code: '||x_errorcode);
583       PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
584   END IF;
585 
586 EXCEPTION
587   WHEN OTHERS THEN
588      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
589          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
590                             p_progress => l_progress);
591      END IF;
592      po_message_s.sql_error('CREATE_DOCUMENTS wrapper',l_progress,sqlcode);
593      raise;
594 END create_documents;
595 --<SOURCING TO PO FPH END>
596 
597 /*============================================================================
598      Name: CREATE_DOCUMENTS
599      DESC: Create/Add to document from requisition data in the PO_HEADERS,LINES
600            and DISTRIBUTION interface tables.
601      ARGS: IN : x_batch_id IN number
602 --<CONTERMS FPJ START>
603            IN: p_sourcing_k_doc_type   IN   VARCHAR2 - The document type that Sourcing
604                              has seeded in Contracts.
605                              Deafault null
606           IN: p_conterms_exist_flag   IN    VARCHAR2 - Whether the sourcing document
607                               has contract template attached.
608                               Deafult - N
609 --<CONTERMS FPJ END>
610      ALGR:
611 
612    ==========================================================================*/
613 PROCEDURE create_documents(x_batch_id     IN     number,
614          x_document_id  IN OUT NOCOPY number,
615          x_number_lines   IN OUT NOCOPY number,
616          --<SOURCING TO PO FPH>
617          x_document_number  IN OUT NOCOPY    varchar2,
618          x_errorcode      OUT NOCOPY    number
619               ,p_sourcing_k_doc_type  IN VARCHAR2 --<CONTERMS FPJ>
620               ,p_conterms_exist_flag  IN VARCHAR2 --<CONTERMS FPJ>
621          ,p_document_creation_method IN VARCHAR2 --<DBI FPJ>
622               ,p_orig_org_id                IN               NUMBER DEFAULT NULL    -- <R12 MOAC>
623      ) IS
624 --<Shared Proc FPJ Start>
625 l_api_name                  VARCHAR2(30) := 'create_documents(wrapper2)'; --< Bug 3210331 >
626 l_return_status             VARCHAR2(1);
627 l_msg_count                 NUMBER;
628 l_msg_data                  VARCHAR2(2000);
629 l_req_operating_unit_id     PO_SYSTEM_PARAMETERS_ALL.org_id%TYPE;
630 l_purch_operating_unit_id   PO_SYSTEM_PARAMETERS_ALL.org_id%TYPE;
631 l_progress VARCHAR2(3) := '000';                            --< Bug 3210331 >
632 
633 BEGIN
634     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
635         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
636     END IF;
637 
638     create_documents (p_api_version             => 1.0,
639                       x_return_status           => l_return_status,
640                       x_msg_count               => l_msg_count,
641                       x_msg_data                => l_msg_data,
642                       p_batch_id                => x_batch_id,
643                       p_req_operating_unit_id   => l_req_operating_unit_id,
644                       p_purch_operating_unit_id => l_purch_operating_unit_id,
645                       x_document_id             => x_document_id,
646                       x_number_lines            => x_number_lines,
647                       x_document_number         => x_document_number
648                      ,p_sourcing_k_doc_type     => p_sourcing_k_doc_type--<CONTERMS FPJ>
649                      ,p_conterms_exist_flag     => p_conterms_exist_flag--<CONTERMS FPJ>
650          ,p_document_creation_method => p_document_creation_method --<DBI FPJ>
651                      ,p_orig_org_id              => p_orig_org_id                 -- <R12 MOAC>
652     );
653 
654     IF (l_return_status = FND_API.g_ret_sts_success
655         AND x_number_lines >0 AND x_document_id is NOT NULL) --<Bug 3268483>
656     THEN
657          x_errorcode := 1;
658     ELSIF g_sourcing_errorcode = 2 THEN
659          x_errorcode := 2;
660     ELSE
661          x_errorcode := 3;
662     END IF;
663 
664     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
665         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
666                             p_token    => l_progress,
667                             p_message  => 'error code: '||x_errorcode);
668         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
669     END IF;
670 
671 EXCEPTION
672     WHEN OTHERS THEN
673         IF g_debug_unexp THEN          --< Bug 3210331: use proper debugging >
674             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
675                                p_progress => l_progress);
676         END IF;
677         PO_MESSAGE_S.sql_error (routine    => 'CREATE_DOCUMENTS',
678                                 location   => l_progress,
679                                 error_code => SQLCODE
680         );
681         RAISE;
682 
683 END create_documents;
684 
685 
686 
687 -------------------------------------------------------------------------------
688 --Start of Comments
689 --Name: create_documents
690 --Pre-reqs:
691 --  None
692 --Modifies:
693 --  Transaction tables for the requested document
694 --Locks:
695 --  None.
696 --Function:
697 --  Creates/Adds To a Document. Can create Purchase Orders, Blankets, Global Agreements,
698 --  RFQs, Consumption Advice among others
699 --Parameters:
700 --IN:
701 --p_api_version
702 --  API standard IN parameter
703 --p_batch_id
704 --  The id that will be used to identify the rows in the interface table. The unique identifier
705 --  for the all the documents to be created. It will be the same as interface_header_id
706 --  as we always create 1 doc at a time.
707 --p_req_operating_unit_id
708 --   The Operating Unit of Requisition raising Operating Unit, or the current Operating Unit
709 --   of the environment if called from Oracle Sourcing 11.5.10+ and beyond
710 --p_purch_operating_unit_id
711 --   The Operating Unit where the PO is being created
712 --p_sourcing_k_doc_type   --<CONTERMS FPJ>
713 --   The document type that Sourcing has seeded in Contracts. --<CONTERMS FPJ>
714 --   Valid only When called from Sourcing --<CONTERMS FPJ>
715 --   Default value Null  --<CONTERMS FPJ>
716 --p_conterms_exist_flag   --<CONTERMS FPJ>
717 --   Whether the sourcing document has contract template attached. --<CONTERMS FPJ>
718 --   Valid only When called from Sourcing--<CONTERMS FPJ>
719 --   Default value N  --<CONTERMS FPJ>
720 --INOUT:
721 --x_document_id
722 --   Used as IN  for document id to ADD to N/A for sourcing.
723 --   Used as OUT for returning the id of the document created.
724 --OUT:
725 --x_return_status
726 --   The standard OUT parameter giving return status of the API call.
727 --x_msg_count
728 --   The count of number of messages added to the message list in this call
729 --x_msg_data
730 --   If the count is 1 then x_msg_data contains the message returned
731 --x_number_lines
732 --   Returns the number of interface records processed
733 --x_document_number
734 --   Returns the PO/Blanket number when for sourcing, null for existing autocreate.
735 --Notes:
736 --   None
737 --Testing:
738 --  None
739 --End of Comments
740 -------------------------------------------------------------------------------
741 PROCEDURE create_documents (
742     p_api_version                IN               NUMBER,
743     x_return_status              OUT    NOCOPY    VARCHAR2,
744     x_msg_count                  OUT    NOCOPY    NUMBER,
745     x_msg_data                   OUT    NOCOPY    VARCHAR2,
746     p_batch_id                   IN               NUMBER,
747     p_req_operating_unit_id      IN               NUMBER,
748     p_purch_operating_unit_id    IN               NUMBER,
749     x_document_id                IN OUT NOCOPY    NUMBER,
750     x_number_lines               OUT    NOCOPY    NUMBER,
751     x_document_number            OUT    NOCOPY    VARCHAR2
752    ,p_sourcing_k_doc_type        IN               VARCHAR2 --<CONTERMS FPJ>
753    ,p_conterms_exist_flag        IN               VARCHAR2 --<CONTERMS FPJ>
754    ,p_document_creation_method   IN               VARCHAR2 --<DBI FPJ>
755    ,p_orig_org_id                IN               NUMBER DEFAULT NULL    -- <R12 MOAC>
756 ) IS
757 --<Shared Proc FPJ End>
758     x_errorcode NUMBER;  --<temp added>
759     x_interface_header_id number:= 0;
760     x_unique_document_num boolean;
761     x_release_number  number;   -- CONSIGNED FPI
762 
763     l_api_name    CONSTANT VARCHAR2(30) := 'create_documents';
764     --<Shared Proc FPJ Start>
765     l_api_version     CONSTANT NUMBER := 1.0;
766     l_original_operating_unit_id    NUMBER;
767     l_org_context_changed    VARCHAR2(1) := 'N';
768     l_req_operating_unit_id     PO_SYSTEM_PARAMETERS_ALL.org_id%TYPE;
769     l_purch_operating_unit_id   PO_SYSTEM_PARAMETERS_ALL.org_id%TYPE;
770 
771     --<Shared Proc FPJ End>
772     l_progress VARCHAR2(3) := '000';            --< Bug 3210331 >
773 
774 BEGIN
775     --<Shared Proc FPJ Start>
776       -- Standard Start of API savepoint
777       SAVEPOINT create_documents_pvt;
778 
779     -- Standard call to check for call compatibility.
780     IF NOT FND_API.compatible_api_call (
781                p_current_version_number => l_api_version,
782                p_caller_version_number  => p_api_version,
783                p_api_name               => l_api_name,
784                p_pkg_name               => g_pkg_name
785            )
786     THEN
787         RAISE FND_API.g_exc_unexpected_error;
788     END IF;
789 
790     l_progress := '010';
791     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
792         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
793     END IF;
794 
795     -- Bug 4778867:If p_orig_org_id is not specified get the current
796     -- Operating Unit Info from the Environment
797     --<R12 MOAC START>
798     IF p_orig_org_id IS NOT NULL THEN
799       l_original_operating_unit_id := p_orig_org_id;
800     ELSE
801       l_original_operating_unit_id := po_moac_utils_pvt.get_current_org_id;
802     END IF;
803     --<R12 MOAC END>
804 
805     l_progress := '020';
806 
807     -- If requesting Org ID is not passed set it to  current operating unit id
808     IF (p_req_operating_unit_id IS NULL) THEN
809         l_req_operating_unit_id := l_original_operating_unit_id;
810     ELSE
811         l_req_operating_unit_id := p_req_operating_unit_id;
812     END IF;
813 
814     -- If purchasing Org ID is not passed then create PO in Req raising Operating Unit
815     IF (p_purch_operating_unit_id IS NULL) THEN
816         l_purch_operating_unit_id := l_req_operating_unit_id;
817     ELSE
818         l_purch_operating_unit_id := p_purch_operating_unit_id;
819     END IF;
820 
821     --Set the context of Purchasing Operating Unit
822     -- <ACHTML R12 START>
823     -- Modified if condition to also return true if l_purch_operating_unit_id
824     -- is not null but l_req_operating_unit_id is null.
825     IF (l_purch_operating_unit_id IS NOT NULL
826   AND (l_req_operating_unit_id IS NULL
827        OR l_purch_operating_unit_id <> l_req_operating_unit_id))
828     THEN
829         l_org_context_changed := 'Y';
830         PO_MOAC_UTILS_PVT.set_org_context(l_purch_operating_unit_id) ;       -- <R12 MOAC>
831     END IF;
832 
833     -- Initialize API return status to success
834     x_return_status := FND_API.G_RET_STS_SUCCESS;
835 
836     -- Initialize the Operating Units
837     g_purchasing_ou_id := l_purch_operating_unit_id;
838     g_hdr_requesting_ou_id := l_req_operating_unit_id;
839 
840     --<Shared Proc FPJ End>
841 
842     g_number_records_processed := 0;
843     g_req_lines_to_process:=0;
844 
845     l_progress:='030';
846 
847     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
848         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
849                             p_token    => l_progress,
850                             p_message  => 'Before select min interface header for batch_id: '||p_batch_id);
851     END IF;
852 
853     /* For now a batch has only one header, so get the document header id */
854        SELECT min(interface_header_id)
855        INTO x_interface_header_id
856        FROM po_headers_interface
857        WHERE batch_id = p_batch_id;  --<Shared Proc FPJ>
858 
859     l_progress:='040';
860     --<SOURCING TO PO FPH>
861     /* determine whether the document to be created is a PO,PA or an RFQ */
862     --<CONFIG_ID FPJ>
863     --Modified the select statement to select document_subtype as well.
864     SELECT document_type_code,document_subtype,nvl(interface_source_code,'NOCODE')
865       INTO g_document_type,g_document_subtype,g_interface_source_code
866       FROM po_headers_interface
867      WHERE interface_header_id = x_interface_header_id;
868 
869      --<eTax Integration R12> Populate global variable to indicate whether
870      -- tax is calculated for this document type
871 
872      IF (g_document_type = 'PO' and
873         g_document_subtype in ('STANDARD', 'PLANNED', 'RELEASE')) THEN
874         g_calculate_tax_flag := 'Y';
875      END IF;
876 
877 
878     l_progress := '050';
879     --<SOURCING TO PO FPH START>
880     --Check for the uniqueness of the document number if manual numbering.
881     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
882         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
883                             p_token    => l_progress,
884                             p_message  => 'Document type is :'||g_document_type);
885         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
886                             p_token    => l_progress,
887                             p_message  => 'Sourcing to FPH-1 starts');
888     END IF;
889 
890     if g_interface_source_code='SOURCING' then
891        --Since we allowe cancellation and finally close of reqs it's possible
892        --that the requistion reference sourcing passed to interface tables
893        --are already cancelled or finally closed.
894        --So we update the requisition line ids of such interface line
895        --records before starting the process. And treat them as non req
896        --backing negotiations.
897 
898        --<CONSUME REQ DEMAND FPI>
899        --In FPI sourcing places the reqs back to pool at the time of splitting.
900        --By the time if some one has place these reqs on another PO document
901        --or sourcing doc autocreate should treat it as not backed by a req.
902        --Included the where clause
903        --a."prl.line_location_id is not null"
904        --b."(prl.auction_header_id<>pli.auction_header_id
905        --     and prl.auction_line_number<>pli.auction_line_number)" in the
906        --following sql.
907 
908        l_progress:='060';
909        update po_lines_interface pli
910           set pli.requisition_line_id= null
911         where pli.interface_header_id= x_interface_header_id
912           and exists
913    (select requisition_line_id
914             from po_requisition_lines_all prl  --<Shared Proc FPJ>
915      where prl.requisition_line_id= pli.requisition_line_id
916        and (prl.line_location_id is not null
917             or prl.cancel_flag='Y'
918       or prl.closed_code='FINALLY CLOSED'
919       or (prl.auction_header_id<>pli.auction_header_id
920            and prl.auction_line_number<>pli.auction_line_number
921          )
922      )
923    );
924 
925        l_progress := '070';
926        --bug#2729465, with drawn req lines are deleted from po_requisition_lines
927        --table. Hence require a separate update.
928        IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
929            PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
930                                p_token    => l_progress,
931                                p_message  => 'Sourcing to PO FPH-1: before the update for withdrawn reqs');
932        END IF;
933 
934        UPDATE po_lines_interface pli
935           SET pli.requisition_line_id= null
936         WHERE pli.interface_header_id= x_interface_header_id
937           AND NOT EXISTS
938    (SELECT requisition_line_id
939             FROM po_requisition_lines_all prl  --<Shared Proc FPJ>
940      WHERE prl.requisition_line_id= pli.requisition_line_id);
941 
942     end if;
943 
944     l_progress := '080';
945     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
946         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
947                             p_token    => l_progress,
948                             p_message  => 'Sourcing to FPH-1 Ends');
949     END IF;
950     --<SOURCING TO PO FPH END>
951 
952 
953 
954     /* Enhancement Request from Proj Manufacturing ecso 10/22/97
955      * Count number of req lines in the line interface table
956      * This is used to determine whether we will copy
957      * project/task reference from RFQ to Quote
958      */
959     SELECT count(*)
960       INTO g_req_lines_to_process
961       FROM po_lines_interface
962      WHERE interface_header_id = x_interface_header_id;
963 
964     l_progress:='090';
965 
966     -- <CONFIG_ID FPJ>
967     IF ( validate_interface_records(x_interface_header_id) ) THEN
968       -- Only create the document if the interface records pass the validations.
969 
970       /* Call the appropriate function based on the document type */
971       --<SOURCING TO PO FPH>
972       --We are modifying the procedure create_po to create Blanket also.
973       --So Modify the following IF clause accordingly.
974       --IF(g_document_type = 'PO') THEN
975       IF(g_document_type in ('PO','PA')) THEN
976 
977         l_progress := '100';
978         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
979             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
980                                 p_token    => l_progress,
981                                 p_message  => 'Before create_po:');
982         END IF;
983 
984         create_po(x_interface_header_id, x_document_id
985                  ,p_sourcing_k_doc_type --<CONTERMS FPJ>
986                  ,p_conterms_exist_flag --<CONTERMS FPJ>
987      ,p_document_creation_method --<DBI FPJ>
988                  );
989 
990 
991       ELSE
992 
993         l_progress := '110';
994         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
995             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
996                                 p_token    => l_progress,
997                                 p_message  => 'Before create_rfq:');
998         END IF;
999 
1000         create_rfq(x_interface_header_id, x_document_id);
1001 
1002       END IF;
1003 
1004     END IF; -- <CONFIG_ID FPJ> validate_interface
1005 
1006     -- Copy the number of requisition lines processed back to
1007     -- the client side.
1008     x_number_lines := g_number_records_processed;
1009 
1010     l_progress:='120';
1011     --<SOURCING TO PO FPH>
1012     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1013         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1014                             p_token    => l_progress,
1015                             p_message  => 'Sourcing to FPH -2 starts');
1016     END IF;
1017 
1018     if g_interface_source_code  in ('SOURCING','CONSUMPTION_ADVICE') then   -- CONSIGNED FPI
1019        if x_number_lines>0 and x_document_id is not null then
1020           begin
1021         x_errorcode :=1;  --success.
1022         x_return_status := FND_API.G_RET_STS_SUCCESS ; --<Shared Proc FPJ>
1023 
1024        /* CONSIGNED FPI start : return the release number for the release */
1025        IF g_document_subtype = 'RELEASE' THEN
1026             l_progress:= '130';
1027             select release_num
1028         into x_release_number
1029             from po_releases_all  --<Shared Proc FPJ>
1030             where po_release_id=x_document_id;
1031 
1032          x_document_number := interface.document_num || '-' || to_char(x_release_number);
1033 
1034        ELSE
1035             l_progress:= '140';
1036            select segment1
1037        into x_document_number
1038            from po_headers_all  --<Shared Proc FPJ>
1039            where po_header_id=x_document_id;
1040 
1041        END IF;
1042        /* CONSIGNED FPI end */
1043 
1044           exception
1045            when others then
1046             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
1047                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
1048                                    p_progress => l_progress);
1049             END IF;
1050             wrapup(x_interface_header_id);
1051             --<Shared Proc FPJ Start>
1052             x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1053 
1054             --set the org context back to original one
1055             IF (l_org_context_changed = 'Y') THEN
1056                 PO_MOAC_UTILS_PVT.set_org_context(l_original_operating_unit_id) ;       -- <R12 MOAC>
1057             END IF;
1058             --<Shared Proc FPJ End>
1059             po_message_s.sql_error('CREATE_DOCUMENTS',l_progress,sqlcode);
1060             raise;
1061           end;
1062        else
1063          if g_sourcing_errorcode =2 then
1064             --this will be set to 2 when dup_val_on_idex happen in create_po.
1065             x_errorcode:=2;
1066             x_return_status := PO_INTERFACE_S.G_RET_STS_DUP_DOC_NUM ; --<Shared Proc FPJ>
1067          else
1068             --when 0 lines are created, we assume that there is some erro happened
1069             --which is not related to manual PO numbering.
1070             x_errorcode:=3;
1071             x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ; --<Shared Proc FPJ>
1072          end if;
1073        end if; --Num_line_checked
1074     --<Shared Proc FPJ START>
1075     else --Calls other than Sourcing and Consumption Advice
1076        if x_number_lines>0 and x_document_id is not null then
1077           x_return_status := FND_API.G_RET_STS_SUCCESS ;
1078           -- <ACHTML R12 START>
1079           -- Need to populate document number for autocreate success message
1080           IF g_document_subtype = 'STANDARD' THEN
1081             select segment1
1082             into x_document_number
1083             from po_headers_all
1084             where po_header_id = x_document_id;
1085     END IF;
1086           -- <ACHTML R12 END>
1087        else
1088           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
1089        end if;
1090     end if; --check doc type
1091     --<Shared Proc FPJ END>
1092 
1093     l_progress:= '150';
1094     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1095         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1096                             p_token    => l_progress,
1097                             p_message  => 'Sourcing to FPH-2 Ends');
1098         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1099                             p_token    => l_progress,
1100                             p_message  => 'Create_documents: number of records processed: '||x_number_lines);
1101     END IF;
1102 
1103    /* CONSIGNED FPI Start : A consumption advice PO should always be created in an approved status.
1104       so update the header with 'approved' status and the shipment with the approved flag */
1105 
1106       IF (g_interface_source_code  = 'CONSUMPTION_ADVICE') and
1107          (x_errorcode = 1      )                          THEN
1108 
1109         IF g_document_subtype = 'STANDARD' THEN
1110 
1111           l_progress:= '160';
1112           update po_headers_all
1113           set authorization_status = 'APPROVED',
1114           approved_date = sysdate,
1115           approved_flag = 'Y'
1116           where po_header_id = x_document_id;
1117 
1118           update po_line_locations_all
1119           set approved_flag = 'Y',
1120               approved_date = sysdate
1121           where po_header_id = x_document_id ;
1122 
1123         ELSIF g_document_subtype = 'RELEASE'  THEN
1124 
1125           l_progress:= '170';
1126           update po_releases_all
1127           set authorization_status = 'APPROVED',
1128           approved_date = sysdate,
1129           approved_flag = 'Y'
1130           where po_release_id = x_document_id;
1131 
1132           update po_line_locations_all
1133           set approved_flag = 'Y',
1134               approved_date = sysdate
1135           where po_release_id = x_document_id ;
1136 
1137         END IF;
1138 
1139      END IF;
1140 
1141     /* CONSIGNED FPI END */
1142     l_progress:= '180';
1143 
1144     --<Shared Proc FPJ Start>
1145     --set the org context back to original one
1146     IF (l_org_context_changed = 'Y') THEN
1147         PO_MOAC_UTILS_PVT.set_org_context(l_original_operating_unit_id) ;       -- <R12 MOAC>
1148     END IF;
1149     --<Shared Proc FPJ End>
1150 
1151     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1152         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
1153     END IF;
1154 
1155 EXCEPTION
1156 
1157   WHEN OTHERS THEN
1158      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
1159          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
1160                             p_progress => l_progress);
1161      END IF;
1162      wrapup(x_interface_header_id);
1163 
1164     --<Shared Proc FPJ Start>
1165      x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
1166     --<Bug 3491323 mbhargav START>
1167      x_number_lines :=  g_number_records_processed;
1168      x_document_id := null;
1169      x_document_number := null;
1170     --<Bug 3491323 mbhargav END>
1171 
1172      --set the org context back to original one
1173      IF (l_org_context_changed = 'Y') THEN
1174          PO_MOAC_UTILS_PVT.set_org_context(l_original_operating_unit_id) ;       -- <R12 MOAC>
1175      END IF;
1176     --<Shared Proc FPJ End>
1177 
1178      po_message_s.sql_error('CREATE_DOCUMENTS',l_progress,sqlcode);
1179 
1180      --<Bug 3336920 mbhargav START>
1181      --No need to raise as we are setting the return status and error msg
1182      --raise;
1183      IF FND_MSG_PUB.check_msg_level(FND_MSG_PUB.g_msg_lvl_unexp_error) THEN
1184                FND_MSG_PUB.add_exc_msg(G_PKG_NAME, l_api_name,
1185                      SUBSTRB (SQLERRM , 1 , 200) || ' at location ' || l_progress);
1186      END IF;
1187      x_msg_data := FND_MSG_PUB.GET(p_msg_index => FND_MSG_PUB.G_LAST,
1188             p_encoded => 'F');
1189      --<Bug 3336920 mbhargav END>
1190 
1191     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1192         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
1193     END IF;
1194 
1195 END create_documents;
1196 
1197 
1198 
1199 /*===========================================================================*/
1200 /*============================ BODY (PRIVATE) ===============================*/
1201 /*===========================================================================*/
1202 
1203 /* ============================================================================
1204      NAME: CREATE_PO
1205      DESC: Create/Add to PO from requisition data in the PO_HEADERS,LINES
1206            and DISTRIBUTION interface tables.
1207      ARGS: IN : x_interface_header_id IN number
1208 --<CONTERMS FPJ START>
1209            IN: p_sourcing_k_doc_type   IN   VARCHAR2 - The document type that Sourcing
1210                              has seeded in Contracts.
1211                              Deafault null
1212           IN: p_conterms_exist_flag   IN    VARCHAR2 - Whether the sourcing document
1213                               has contract template attached.
1214                               Deafult - N
1215 --<CONTERMS FPJ END>
1216      ALGR:
1217 
1218    ==========================================================================*/
1219 PROCEDURE create_po(x_interface_header_id IN number,
1220         x_document_id IN OUT NOCOPY number
1221            ,p_sourcing_k_doc_type  IN VARCHAR2 --<CONTERMS FPJ>
1222            ,p_conterms_exist_flag  IN VARCHAR2 --<CONTERMS FPJ>
1223      ,p_document_creation_method IN VARCHAR2 --<DBI FPJ>
1224          ) IS
1225 x_max_revision_num number := null;
1226 
1227 -- Bug 902976, zxzhang, 10/04/99
1228 -- Change REVISED_DATE from VarChar(25) to Date.
1229 -- x_new_revised_date varchar2(25):= null;
1230 x_new_revised_date Date := null;
1231 
1232 X_line_found varchar2(1) := 'N';
1233 x_release_num number;
1234 
1235 x_document_num po_headers.segment1%type:=null; -- Bug 1093645
1236 
1237 l_api_name CONSTANT VARCHAR2(30) := 'create_po';
1238 
1239 x_org_id  number;
1240 /*bug # 2997337 */
1241   x_valid_ship_to po_headers.ship_to_location_id%TYPE;
1242   x_valid_bill_to po_headers.bill_to_location_id%TYPE;
1243   x_is_valid VARCHAR(1) := 'N';
1244 /*bug # 2997337 */
1245 
1246 --<Bug 3054563 mbhargav START>
1247 l_org_assign_rec   po_ga_org_assignments%ROWTYPE;
1248 l_org_row_id       varchar2(30);
1249 l_return_status     varchar2(1);
1250 --<Bug 3054563 mbhargav END>
1251 
1252 --<MRC FPJ Start>
1253 l_msg_data VARCHAR2(2000);
1254 l_msg_count NUMBER;
1255 --<MRC FPJ End>
1256 
1257 --<CONTERMS FPJ START>
1258 l_contracts_call_exception Exception;
1259 --For using %type, dependence on OKC tables. Consider for refactor
1260 l_contract_doc_type    VARCHAR2(150);
1261 --<CONTERMS FPJ END>
1262 l_document_creation_method po_headers_all.document_creation_method%type := p_document_creation_method; --<DBI FPJ>
1263 l_progress VARCHAR2(3) := '000';            --< Bug 3210331 >
1264 
1265 l_terms_id                   PO_HEADERS.terms_id%TYPE;
1266 l_fob_lookup_code            PO_HEADERS.fob_lookup_code%TYPE;
1267 l_freight_lookup_code        PO_HEADERS.freight_terms_lookup_code%TYPE;
1268 l_ship_via_lookup_code       PO_HEADERS_ALL.ship_via_lookup_code%TYPE;
1269 l_vs_terms_id                   PO_HEADERS.terms_id%TYPE;
1270 l_vs_fob_lookup_code            PO_HEADERS.fob_lookup_code%TYPE;
1271 l_vs_freight_lookup_code        PO_HEADERS.freight_terms_lookup_code%TYPE;
1272 l_vs_ship_via_lookup_code       PO_HEADERS_ALL.ship_via_lookup_code%TYPE;
1273 
1274 l_is_complex_work_po         BOOLEAN := FALSE;  -- <Complex Work R12>
1275 l_style_id                   NUMBER;            -- <Complex Work R12>
1276 tax_document_id              NUMBER;
1277 
1278 BEGIN
1279     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1280         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
1281     END IF;
1282     --<R12 eTax Integration Start>
1283     SAVEPOINT TAX_CALCULATION_ERROR;
1284 
1285    /*Bug 4314776:Requisition import errors out with unique constraint voilation
1286    error on po_requsition_header_id when the create_po raises an unhandled exception.
1287    Establishing a savepoint here so that when an exception is raised in create_po
1288    procedure it will be rolled back to  this savepoint */
1289 
1290    savepoint create_po;    --Bug 4314776
1291 
1292     --<R12 eTax Integration End>
1293     get_system_defaults;
1294 
1295     -- <Complex Work R12 Start>
1296     SELECT phi.style_id
1297     INTO l_style_id
1298     FROM po_headers_interface phi
1299     WHERE phi.interface_header_id = x_interface_header_id;
1300 
1301     IF (l_style_id IS NOT NULL) THEN
1302       l_is_complex_work_po := PO_COMPLEX_WORK_PVT.is_complex_work_style(
1303                                 p_style_id => l_style_id
1304                               );
1305     ELSE
1306       l_is_complex_work_po := FALSE;
1307     END IF;
1308     -- <Complex Work R12 End>
1309 
1310     -- populate the interface tables with data from the
1311     -- requisition.
1312 
1313     l_progress := '010';
1314     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1315         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1316                             p_token    => l_progress,
1317                             p_message  => 'Create PO: Before setup interface table');
1318     END IF;
1319 
1320     l_progress:='020';
1321     -- <Complex Work R12 Start>: Pass in l_is_complex_work_po
1322     setup_interface_tables(
1323       x_interface_header_id => x_interface_header_id
1324     , x_document_id => x_document_id
1325     , p_is_complex_work_po => l_is_complex_work_po
1326     );
1327     -- <Complex Work R12 End>: Pass in l_is_complex_work_po
1328 
1329     -- determine which interface lines and shipments should
1330     -- be grouped.
1331     l_progress := '030';
1332     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1333         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1334                             p_token    => l_progress,
1335                             p_message  => 'Create PO: Before Group interface lines');
1336     END IF;
1337 
1338     --<RENEG BLANKET FPI START>
1339     -- DO not do grouping if document is Blanket and request is coming from Sourcing
1340     if (g_document_type <> 'PA') then
1341         group_interface_lines(
1342           x_interface_header_id => x_interface_header_id
1343         , p_is_complex_work_po  => l_is_complex_work_po
1344         );
1345     end if;
1346     --<RENEG BLANKET FPI END>
1347 
1348     l_progress := '040';
1349     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1350         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1351                             p_token    => l_progress,
1352                             p_message  => 'Create PO: After Group interface lines');
1353     END IF;
1354 
1355     -- If the document type is Release, then do not continue
1356     -- processing if there are no lines with a line number
1357     -- This means that none of the requisition lines matched
1358     -- the blanket line.  We do not want to create the release.
1359     IF (g_document_subtype='RELEASE')THEN
1360 
1361        BEGIN
1362 
1363           l_progress := '050';
1364           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1365               PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1366                                   p_token    => l_progress,
1367                                   p_message  => 'Create po: Interface header id is '|| x_interface_header_id);
1368           END IF;
1369 
1370           select distinct 'Y'
1371           into   X_line_found
1372           from   po_lines_interface
1373           where  interface_header_id = x_interface_header_id
1374           and    line_num is not null;
1375 
1376           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1377               PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1378                                   p_token    => l_progress,
1379                                   p_message  => 'Create PO : Line found in po_lines_interfaces');
1380           END IF;
1381 
1382        EXCEPTION
1383           WHEN OTHERS THEN
1384               IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
1385                   PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
1386                                      p_progress => l_progress);
1387               END IF;
1388               wrapup(x_interface_header_id);
1389               RAISE;
1390        END;
1391 
1392     END IF;
1393 
1394     l_progress := '060';
1395     OPEN interface_cursor(x_interface_header_id);
1396 
1397     FETCH interface_cursor INTO interface;
1398 
1399     IF interface_cursor%notfound THEN
1400       CLOSE interface_cursor;
1401       RETURN;
1402     END IF;
1403 
1404 
1405 /* Bug 2786897: Start
1406    Prior the fix the following code was getting executed only when
1407    a new PO was created through autocreate. It should get executed
1408    while adding requisition lines to an existing PO also.  Hence
1409    shifting the following piece of code out of the 'IF' condition
1410    on 'g_mode'
1411 */
1412 
1413     l_progress := '070';
1414     IF(interface.vendor_id is not null) THEN
1415 
1416     /*Bug 5715411 Null out the vendor record details as it is global record type */
1417        vendor.ship_via_lookup_code := null;
1418        vendor.fob_lookup_code := null;
1419        vendor.freight_terms_lookup_code := null;
1420        vendor.terms_id := null;
1421        /*Bug 5715411 end */
1422 
1423           po_vendors_sv.get_vendor_info
1424                            (interface.vendor_id,
1425                             vendor.ship_to_location_id,
1426                             vendor.bill_to_location_id,
1427                             l_ship_via_lookup_code,
1428                             l_fob_lookup_code,
1429                             l_freight_lookup_code,
1430                             l_terms_id,
1431                             vendor.type_1099,
1432                             vendor.hold_flag,
1433                             vendor.invoice_currency_code,
1434                             vendor.receipt_required_flag,
1435                             vendor.num_1099,
1436                             vendor.vat_registration_num,
1437                             vendor.inspection_required_flag);
1438 
1439          IF(interface.vendor_site_id is not null) THEN
1440                   po_vendor_sites_sv.get_vendor_site_info
1441                               (interface.vendor_site_id,
1442                                vendor.ship_to_location_id,
1443                                vendor.bill_to_location_id,
1444                                l_vs_ship_via_lookup_code,
1445                                l_vs_fob_lookup_code,
1446                                vendor.pay_on_code,
1447                                l_vs_freight_lookup_code,
1448                                l_vs_terms_id,
1449                                vendor.invoice_currency_code,
1450                                vendor.shipping_control    -- <INBOUND LOGISTICS FPJ>
1451                               );
1452 
1453                   -- Bug 3807992 start : Do not override the following terms with null
1454                   -- values. If the site has values validate them. If not valid take the
1455                   -- values from the vendor and validate them
1456 
1457                   -- Validate ship via
1458                   if l_vs_ship_via_lookup_code is not null then
1459                      po_vendors_sv.val_freight_carrier(l_vs_ship_via_lookup_code,
1460                                                        params.inventory_organization_id,
1461                                                        vendor.ship_via_lookup_code);
1462                   end if;
1463 
1464                   if vendor.ship_via_lookup_code is null then
1465                      po_vendors_sv.val_freight_carrier(l_ship_via_lookup_code,
1466                                                        params.inventory_organization_id,
1467                                                        vendor.ship_via_lookup_code);
1468                   end if;
1469 
1470                   -- Validate fob code
1471                   if l_vs_fob_lookup_code is not null then
1472                      po_vendors_sv.val_fob(l_vs_fob_lookup_code,vendor.fob_lookup_code);
1473                   end if;
1474 
1475                   if vendor.fob_lookup_code is null then
1476                      po_vendors_sv.val_fob(l_fob_lookup_code,vendor.fob_lookup_code);
1477                   end if;
1478 
1479                   -- Validate freight terms
1480                   if l_vs_freight_lookup_code is not null then
1481                      po_vendors_sv.val_freight_terms(l_vs_freight_lookup_code,
1482                                                      vendor.freight_terms_lookup_code);
1483                   end if;
1484 
1485                   if vendor.freight_terms_lookup_code is null then
1486                      po_vendors_sv.val_freight_terms(l_freight_lookup_code,
1487                                                      vendor.freight_terms_lookup_code);
1488                   end if;
1489 
1490                   -- Validate payment terms
1491                   if l_vs_terms_id is not null then
1492                      po_terms_sv.val_ap_terms(l_vs_terms_id,vendor.terms_id);
1493                   end if;
1494 
1495                   if vendor.terms_id is null then
1496                      po_terms_sv.val_ap_terms(l_terms_id,vendor.terms_id);
1497                   end if;
1498                   -- Bug 3807992 end
1499 
1500                   --  Bug 2816396 START
1501                   --  Default the pay_on_code for a Standard PO based
1502                   --  on the vendor site value.
1503                   if (vendor.pay_on_code = 'RECEIPT_AND_USE') then
1504                      vendor.pay_on_code := 'RECEIPT';
1505                   elsif (vendor.pay_on_code = 'USE') then
1506                      vendor.pay_on_code := null;
1507                   end if;
1508                   -- Bug 2816396 END
1509 
1510          END IF;
1511     END IF;
1512 
1513 /* Bug 2786897: End */
1514     l_progress := '080';
1515 
1516    --<Sourcing 11.5.10+> If called from Sourcing, simply assign interface.h_rate to
1517    -- g_rate_for_req_fields
1518    --<Shared Proc FPJ START>
1519    IF (g_interface_source_code <> 'SOURCING'
1520        AND g_purchasing_ou_id <> g_hdr_requesting_ou_id
1521        AND interface.document_subtype = 'STANDARD')
1522    THEN
1523      get_rate_for_req_price(
1524        p_requesting_ou_id => g_hdr_requesting_ou_id, -- <ACHTML R12>
1525        p_purchasing_ou_id => g_purchasing_ou_id, -- <ACHTML R12>
1526        p_po_currency_code => interface.h_currency_code,
1527        p_rate_type        => interface.h_rate_type,
1528        p_rate_date        => interface.h_rate_date,
1529        x_rate             => g_rate_for_req_fields
1530      );
1531      IF g_rate_for_req_fields IS NULL
1532      THEN
1533        g_rate_for_req_fields := interface.h_rate;
1534      END IF;
1535    ELSE
1536      g_rate_for_req_fields := interface.h_rate;
1537    END IF;
1538    --<Shared Proc FPJ END>
1539 
1540     l_progress := '090';
1541 
1542     IF (g_mode = 'ADD') THEN
1543 /*Bug no 718918:sarunach
1544    The x_new_revised_date was added for bug no 491306 to update
1545    the revised_date.But it was inside the loop for standard and planned
1546    po's only.So the revised_date was Releases was incorrect.
1547    Removed those line and put it here to update the revised date for
1548    Standard,planned and Releases.
1549 */
1550 -- Bug 902976, zxzhang, 10/04/99
1551 -- Change REVISED_DATE from VarChar(25) to Date.
1552 /*
1553           x_new_revised_date := to_char(interface.last_update_date,
1554                                       'DD/MM/YYYY HH24:MI');
1555 */
1556     x_new_revised_date := interface.last_update_date;
1557 
1558        /* Bug# 1734108
1559        * When a line was added to a existing PO the invoice_match_option
1560        * was not Calculated. This resulted in creating shipments with
1561        * invoice_match_option as NULL. Due to this when navigating out of
1562        * Shipment Window we get the Error "FRM-40202:  Field must be
1563        * entered"
1564        * Default invoice match flag in turn from vendor site, vendor and
1565        * Financial system in that Order.
1566        */
1567        if g_interface_source_code  <> 'CONSUMPTION_ADVICE' then   -- bug 2741985
1568            get_invoice_match_option(interface.vendor_id,
1569                  interface.vendor_site_id,
1570                vendor.invoice_match_option);
1571        end if;
1572 
1573        IF(interface.document_subtype = 'STANDARD' or
1574           interface.document_subtype = 'PLANNED') THEN
1575 
1576           l_progress:='100';
1577 
1578           /*
1579           ** Get the max revision that exists in the archive
1580           ** table for this purchase order.  We will compare
1581           ** this against the current revision on the PO
1582           ** to determine if the revision needs to be incremented.
1583           ** If there is not a record in the archive table,
1584           **  the revision will not be incremented.
1585           ** If the po is currently approved and the revision
1586           **  number in the archive table is the same as
1587           **  the revision on the PO, then increment the
1588           **  revision on the PO by one.
1589           */
1590           SELECT max(revision_num)
1591           INTO   x_max_revision_num
1592           FROM   po_headers_archive_all poha  --<Shared Proc FPJ>
1593           WHERE  poha.po_header_id = interface.po_header_id;
1594 
1595          /* Bug 493106 ecso 9/24/97
1596           * Revised date should be updated
1597           * the same time revision is incremented.
1598           * Database field revised_date is defined as varchar(25).
1599           * Use same format as in po_headers_pkg2.check_new_revision
1600           x_new_revised_date := to_char(interface.last_update_date,
1601                                        'DD-MON-YY HH24:MI');
1602           */
1603 
1604           l_progress:='110';
1605           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1606               PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1607                                   p_token    => l_progress,
1608                                   p_message  => 'Update PO_Headers Doc subtype is Std or planned');
1609           END IF;
1610 --Bug 2295672 jbalakri : added 'REJECTED' case in decode statement.
1611 
1612           UPDATE po_headers_all  --<Shared Proc FPJ>
1613              SET approved_flag =
1614                        decode(nvl(approved_flag,'N'),'N','N','F','F','R'),
1615                  authorization_status =
1616                        decode(nvl(authorization_status,'INCOMPLETE'),
1617                               'INCOMPLETE','INCOMPLETE','REJECTED','REJECTED',
1618                               'REQUIRES REAPPROVAL'),
1619                  closed_code = 'OPEN',
1620 -- Bug 1199462 Amitabh
1621                  closed_date = NULL,
1622            revision_num =  decode(x_max_revision_num, '',
1623           revision_num,
1624         decode(nvl(authorization_status,'INCOMPLETE'),
1625                  'APPROVED',
1626            decode(revision_num, x_max_revision_num,
1627             revision_num + 1, revision_num),
1628         revision_num)),
1629                  revised_date =  decode(x_max_revision_num, '',
1630                                        revised_date,
1631                                decode(nvl(authorization_status,'INCOMPLETE'),
1632                                   'APPROVED',
1633                                   decode(revision_num, x_max_revision_num,
1634                                          x_new_revised_date, revised_date),
1635                                revised_date)),
1636                  last_update_date  = interface.last_update_date,
1637                  last_updated_by   = interface.last_updated_by,
1638                  last_update_login = interface.last_update_login
1639            WHERE po_header_id = interface.po_header_id;
1640 
1641        ELSIF (interface.document_subtype = 'RELEASE') THEN
1642 
1643          l_progress:='120';
1644          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1645              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1646                                  p_token    => l_progress,
1647                                  p_message  => 'Update PO_Headers Doc subtype is Release');
1648          END IF;
1649 
1650          UPDATE po_headers_all  --<Shared Proc FPJ>
1651            SET closed_code = 'OPEN',
1652                closed_date = NULL,
1653                last_update_date  = interface.last_update_date,
1654                last_updated_by   = interface.last_updated_by ,
1655                last_update_login = interface.last_update_login
1656          WHERE po_header_id = interface.po_header_id;
1657 
1658         l_progress:='130';
1659 
1660         SELECT po_release_id
1661           INTO g_po_release_id
1662           FROM po_releases_all  --<Shared Proc FPJ>
1663          WHERE release_num = interface.release_num
1664            AND po_header_id = interface.po_header_id
1665            FOR UPDATE OF approved_flag;
1666 
1667         l_progress:='140';
1668 
1669   /*
1670   ** Get max revision num from the archive table to
1671   ** determine if the revision on the release needs to
1672   ** be incremented.
1673   */
1674         SELECT max(revision_num)
1675     INTO x_max_revision_num
1676     FROM po_releases_archive_all  --<Shared Proc FPJ>
1677    WHERE po_release_id = g_po_release_id;
1678 
1679 /*Bug No.1793703:The decode statement below for updating the revision_num
1680                  was not complete.It was updating the revision_num with null
1681                  when the document added to was in 'Requires Re-approval stage'.
1682                  Added the revision_num at the end of the decode statement.*/
1683 
1684         l_progress:='150';
1685         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1686             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1687                                 p_token    => l_progress,
1688                                 p_message  => 'Update PO_Releases Doc subtype is Release');
1689         END IF;
1690 
1691         UPDATE PO_RELEASES_ALL  --<Shared Proc FPJ>
1692            SET last_update_date = interface.last_update_date,
1693                last_updated_by = interface.last_updated_by,
1694                last_update_login = interface.last_update_login,
1695          closed_code = 'OPEN',
1696                approved_flag = DECODE(approved_flag,
1697                                       'N','N','F','F',
1698                                       'R'),
1699                authorization_status = DECODE(authorization_status,
1700                                              'INCOMPLETE','INCOMPLETE','REJECTED','REJECTED',
1701                                              'REQUIRES REAPPROVAL'),
1702          revision_num =  decode(x_max_revision_num, '',
1703           revision_num,
1704             decode(nvl(authorization_status, 'INCOMPLETE'),
1705             'APPROVED',
1706         decode(x_max_revision_num, revision_num,
1707           revision_num+1, revision_num),
1708                                         revision_num)),
1709                revised_date =  decode(x_max_revision_num, '',
1710                                        revised_date,
1711                                decode(nvl(authorization_status,'INCOMPLETE'),
1712                                   'APPROVED',
1713                                   decode(revision_num, x_max_revision_num,
1714                                          x_new_revised_date, revised_date),
1715                                revised_date))
1716          WHERE po_release_id = g_po_release_id;
1717 
1718        END IF; /* of document type */
1719 
1720     ELSIF (g_mode = 'NEW') THEN
1721 
1722        l_progress:='160';
1723 
1724     /* bgu, Dec. 10, 98
1725      * Default invoice match flag in turn from Financial system default,
1726      * vendor, vendor site.
1727      */
1728 
1729     /* bug 2741985 :
1730      * for a consumption advice we do not need to get the match option from the
1731      *  site because we always insert a match type of 'PO' */
1732 
1733     if g_interface_source_code  <> 'CONSUMPTION_ADVICE' then   -- bug 2741985
1734        get_invoice_match_option(interface.vendor_id,
1735                  interface.vendor_site_id,
1736                vendor.invoice_match_option);
1737     end if;
1738 
1739     l_progress:='170';
1740 
1741     /** BUG 873209
1742      *  The date mask on interface.h_rate_date causes this insertion
1743      *  failed on tst115 database.
1744      */
1745     IF(interface.document_subtype = 'STANDARD' or
1746        interface.document_subtype = 'PLANNED'  or
1747        --<SOURCING TO PO FPH>
1748        --Allow to create blanket also
1749        interface.document_subtype = 'BLANKET'
1750        ) THEN
1751       l_progress:= '180';
1752       BEGIN
1753 
1754       if interface.global_agreement_flag = 'N' then
1755           interface.global_agreement_flag := null;
1756       end if;
1757 
1758       -- Bug 2690933
1759       if interface.global_agreement_flag = 'Y' then
1760             interface.h_min_release_amount := null;
1761       end if;
1762 
1763       --<SOURCING TO PO FPH>
1764       --The following insert is modified to take care of defaulting for sourcing
1765       --For more comments please refer to update po_headers_interface phi
1766       --in setup_interface_tables procedure.
1767       /* Bug 2816396
1768          Use the interface table value for pay_on_code when inserting into po_headers.pay_on_code
1769       */
1770 
1771 
1772 /*bug #2997337
1773     validating the ship_to and bill_to locations to check whether they are
1774     active or inactive before inserting into the PO_HEADERS table. If any of them
1775     is found inactive then a null value is inserted in the table in the respective
1776     column*/
1777 
1778      if (g_interface_source_code = 'SOURCING') then
1779        x_valid_ship_to := nvl(interface.ship_to_location_id, nvl(vendor.ship_to_location_id,
1780                                                                      params.ship_to_location_id));
1781        x_valid_bill_to := nvl(interface.bill_to_location_id, nvl(vendor.bill_to_location_id,
1782                                                                params.bill_to_location_id));
1783      else
1784        x_valid_ship_to := nvl(vendor.ship_to_location_id, interface.ship_to_location_id);
1785        x_valid_bill_to := nvl(vendor.bill_to_location_id, interface.bill_to_location_id);
1786      end if;
1787 
1788      l_progress:= '190';
1789      --bug 4229954
1790      --we will validate a location based on Bill-To-Location and Ship-To-Location flags
1791      --of hr_locations_all along with inactive date check
1792      BEGIN
1793         select 'Y' into x_is_valid
1794           from hr_locations_all
1795           where location_id = x_valid_ship_to
1796           and NVL(ship_to_site_flag, 'N') = 'Y' --bug 4229954
1797           and NVL(trunc(inactive_date),trunc(SYSDATE)+1) > trunc(SYSDATE);
1798 
1799      EXCEPTION
1800 
1801          WHEN NO_DATA_FOUND then
1802              IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1803                  PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1804                                      p_token    => l_progress,
1805                                      p_message  => 'NO_DATA_FOUND: '||SQLERRM);
1806              END IF;
1807            x_is_valid:='N';
1808           x_valid_ship_to := NULL;
1809 
1810          WHEN OTHERS  then
1811              IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
1812                  PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
1813                                     p_progress => l_progress);
1814              END IF;
1815           raise;
1816      End;
1817 
1818       l_progress:= '200';
1819  BEGIN
1820           select 'Y' into x_is_valid
1821           from hr_locations_all
1822           where location_id = x_valid_bill_to
1823           and NVL(bill_to_site_flag, 'N') = 'Y'  --bug 4229954
1824           and NVL(trunc(inactive_date),trunc(SYSDATE)+1) > trunc(SYSDATE);
1825 
1826      EXCEPTION
1827 
1828          WHEN NO_DATA_FOUND then
1829             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1830                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1831                                     p_token    => l_progress,
1832                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
1833             END IF;
1834             x_is_valid:='N';
1835             x_valid_bill_to := NULL;
1836 
1837          WHEN OTHERS  then
1838              IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
1839                  PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
1840                                     p_progress => l_progress);
1841              END IF;
1842             raise;
1843      End;
1844   /*end of addition for bug# 2997337 */
1845 
1846 --<DBI FPJ Start>
1847 IF g_interface_source_code = 'CONSUMPTION_ADVICE' THEN
1848   -- Bug 3648268 Use lookup code instead of hardcoded value
1849   l_document_creation_method := 'CREATE_CONSUMPTION';
1850 END IF;
1851 --<DBI FPJ End>
1852 
1853       l_progress:= '210';
1854       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
1855           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
1856                               p_token    => l_progress,
1857                               p_message  => 'Before Insert into PO_headers');
1858       END IF;
1859 
1860       INSERT INTO po_headers_all  --<Shared Proc FPJ>
1861             (po_header_id,
1862                    last_update_date,
1863                    last_updated_by,
1864                    segment1,
1865              created_by,
1866                    last_update_login,
1867              summary_flag,
1868                    enabled_flag,
1869                    type_lookup_code,
1870                    agent_id,
1871                    creation_date,
1872                    revision_num,
1873                    print_count,
1874                    closed_code,
1875                    frozen_flag,
1876                    vendor_id,
1877                    vendor_site_id,
1878        vendor_contact_id,
1879                    ship_to_location_id,
1880                    bill_to_location_id,
1881                    terms_id,
1882                    ship_via_lookup_code,
1883                    fob_lookup_code,
1884                    pay_on_code,
1885                    freight_terms_lookup_code,
1886              confirming_order_flag,
1887                    currency_code,
1888              rate_type,
1889                    rate_date,
1890                    rate,
1891                    acceptance_required_flag,
1892                    firm_status_lookup_code,
1893                    min_release_amount,
1894 --DPCARD{
1895                    pcard_id,
1896 --DPCARD}
1897              --<SOURCING TO PO FPH START>
1898              blanket_total_amount,--Bug# 2288408
1899              start_date,          --Bug# 2288408
1900              end_date,        --Bug# 2288408
1901              --<SOURCING TO PO FPH END>
1902        --<RENEG BLANKET FPI START>
1903        amount_limit,
1904                    global_agreement_flag,
1905        --<RENEG BLANKET FPI END>
1906        --<CONSUME REQ DEMAND FPI>
1907        consume_req_demand_flag,
1908                    consigned_consumption_flag,   -- CONSIGNED FPI
1909                    shipping_control,    -- <INBOUND LOGISTICS FPJ>
1910                    org_id  --<Shared Proc FPJ>
1911                   ,conterms_exist_flag     --<CONTERMS FPJ>
1912       ,document_creation_method --<DBI FPJ>
1913                  ,style_id --<R12 STYLES PHASE II>
1914      ,tax_attribute_update_code   --<eTax Integration R12>
1915             , created_language --<Unified Catalog R12: Bug#4656615>
1916             , cpa_reference    --<Unified Catalog R12: Bug#4656615>
1917        )
1918       VALUES (interface.po_header_id,
1919                     interface.last_update_date,
1920                     interface.last_updated_by,
1921                     interface.document_num,
1922                     interface.created_by,
1923                     interface.last_update_login,
1924               'N',
1925                     'Y',
1926                     interface.document_subtype,
1927                     interface.agent_id,
1928                     interface.creation_date,
1929                     interface.revision_num,
1930                     interface.print_count,
1931                     interface.h_closed_code,
1932                     interface.frozen_flag,
1933                     interface.vendor_id,
1934                     interface.vendor_site_id,
1935         interface.vendor_contact_id,
1936                     x_valid_ship_to,
1937                     x_valid_bill_to,
1938         decode(g_interface_source_code,'SOURCING',
1939           nvl(interface.terms_id,
1940                     nvl(vendor.terms_id,
1941             params.terms_id)),
1942                             nvl(vendor.terms_id,
1943                                 interface.terms_id)),
1944         decode(g_interface_source_code,'SOURCING',
1945                            nvl(interface.ship_via_lookup_code,
1946              nvl(vendor.ship_via_lookup_code,
1947                  params.ship_via_lookup_code)),
1948                            nvl(vendor.ship_via_lookup_code,
1949                                interface.ship_via_lookup_code)),
1950         decode(g_interface_source_code,'SOURCING',
1951                            nvl(interface.fob_lookup_code,
1952              nvl(vendor.fob_lookup_code,
1953            params.fob_lookup_code)),
1954                            nvl(vendor.fob_lookup_code,
1955                                interface.fob_lookup_code)),
1956         decode(g_interface_source_code,'SOURCING',
1957                          nvl(interface.pay_on_code,
1958              vendor.pay_on_code),
1959                            'CONSUMPTION_ADVICE',
1960                            interface.pay_on_code,
1961                            nvl(vendor.pay_on_code,
1962                                interface.pay_on_code)),
1963         decode(g_interface_source_code,'SOURCING',
1964                            nvl(interface.freight_terms_lookup_code,
1965                                nvl(vendor.freight_terms_lookup_code,
1966            params.freight_terms_lookup_code)),
1967                            nvl(vendor.freight_terms_lookup_code,
1968                                interface.freight_terms_lookup_code)),
1969                     interface.confirming_order_flag,
1970                     interface.h_currency_code,
1971                     interface.h_rate_type,
1972 --                    to_date(interface.h_rate_date, 'DD/MM/YYYY'),
1973                     interface.h_rate_date,
1974                     interface.h_rate,
1975                     interface.acceptance_required_flag,
1976                     interface.h_firm_status_lookup_code,
1977                     interface.h_min_release_amount,
1978 --DPCARD{
1979                     interface.pcard_id,
1980 --DPCARD}
1981               --<SOURCING TO PO FPH START>
1982               decode(g_document_type,'PA',interface.amount_agreed,null),
1983               decode(g_document_type,'PA',interface.effective_date,null),
1984               decode(g_document_type,'PA',interface.expiration_date,null),
1985               --<SOURCING TO PO FPH END>
1986         --<RENEG BLANKET FPI START>
1987         decode(g_document_type, 'PA', nvl(interface.amount_limit, interface.amount_agreed), null),
1988                     decode(interface.global_agreement_flag,'N',null,'Y','Y',null),   -- bug 2754954
1989         --<RENEG BLANKET FPI END>
1990         --<CONSUME REQ DEMAND FPI>
1991         interface.consume_req_demand_flag,
1992                     decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'Y',null),
1993                     vendor.shipping_control,    -- <INBOUND LOGISTICS FPJ>
1994                     g_purchasing_ou_id  --<Shared Proc FPJ>
1995                    ,p_conterms_exist_flag     --<CONTERMS FPJ>
1996        ,l_document_creation_method --<DBI FPJ>
1997                    ,decode(g_interface_source_code,'CONSUMPTION_ADVICE',
1998                            PO_DOC_STYLE_GRP.get_standard_doc_style ,interface.style_id)  --<R12 STYLES PHASE II >
1999        ,nvl2(g_calculate_tax_flag, 'CREATE', null)  --<eTax Integration R12>
2000             , interface.created_language --<Unified Catalog R12: Bug#4656615>
2001             , interface.cpa_reference    --<Unified Catalog R12: Bug#4656615>
2002         );
2003     EXCEPTION
2004         WHEN DUP_VAL_ON_INDEX THEN
2005             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2006                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2007                                         p_token    => l_progress,
2008                                         p_message  => 'DUP_VAL_ON_INDEX: '||SQLERRM);
2009             END IF;
2010 
2011             IF g_interface_source_code ='SOURCING' then
2012                 g_sourcing_errorcode:=2; --duplicate document number
2013                 RAISE;
2014             ELSE
2015                 RAISE;
2016             END IF;
2017     END;
2018 
2019     l_progress:= '220';
2020     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2021         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2022                             p_token    => l_progress,
2023                             p_message  => 'After Insert into PO_headers');
2024     END IF;
2025 
2026     --Bug#5024876: Removed the dangling 'END IF' left by Bug#4886821
2027 
2028         -- After insert into po_headers, insert a row into org_assignments for a global agreement
2029            IF nvl(interface.global_agreement_flag, 'N') = 'Y' then
2030              l_progress:= '240';
2031              select org_id
2032              into x_org_id
2033              from po_headers_all
2034              where po_header_id = interface.po_header_id;
2035 
2036                --<Bug 3054563 mbhargav START>
2037                --Replaced the INSERT statement with call to Row Handler.
2038                -- call the GA org assignments table handler to insert a row
2039                -- for the owning org into the org assignments table
2040                l_org_assign_rec.po_header_id      := interface.po_header_id;
2041                l_org_assign_rec.organization_id   := x_org_id;
2042                l_org_assign_rec.purchasing_org_id := l_org_assign_rec.organization_id;
2043                l_org_assign_rec.enabled_flag      := 'Y';
2044                l_org_assign_rec.vendor_site_id    := interface.vendor_site_id;
2045                l_org_assign_rec.last_update_date  := interface.last_update_date;
2046                l_org_assign_rec.last_updated_by   := interface.last_updated_by;
2047                l_org_assign_rec.creation_date     := interface.creation_date;
2048                l_org_assign_rec.created_by        := interface.created_by;
2049                l_org_assign_rec.last_update_login := interface.last_update_login;
2050 
2051                PO_GA_ORG_ASSIGN_PVT.insert_row(p_init_msg_list  => 'T',
2052                                         x_return_status  => l_return_status,
2053                                         p_org_assign_rec => l_org_assign_rec,
2054                                         x_row_id         => l_org_row_id);
2055                --<Bug 3054563 mbhargav END>
2056 
2057               IF g_debug_stmt THEN
2058                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2059                                     p_token    => l_progress,
2060                                     p_message  => 'After inserting into Org Assignments');
2061               END IF;
2062             END IF;
2063 
2064       l_progress:= '250';
2065 
2066    --<RENEG BLANKET FPI START>
2067          --<BUG 2695661>
2068          -- The header level attachments should be copied if the call is coming from Sourcing.
2069          -- irrespective of doc type or subtype. Removing 'Blanket' check.
2070          if (g_interface_source_code ='SOURCING') then
2071 
2072               -- copy attachments from negotiation header to blanket header
2073          po_negotiations_sv2.copy_attachments('PON_AUCTION_HEADERS_ALL',
2074                             interface.auction_header_id,
2075                                 null,
2076                                 null,
2077                                 null,
2078                                 null,
2079                                 'PO_HEADERS',
2080                                 interface.po_header_id,
2081                                 null,
2082                                 null,
2083                                 null,
2084                                 null,
2085                                 interface.created_by,
2086                                 interface.last_update_login,
2087                                 null,
2088                                 null,
2089                                 null,
2090                                 'NEG');
2091 
2092               -- build and attach negotiation header notes as to supplier attachments
2093               -- on po/blanket header.
2094               po_negotiations_sv2.add_attch_dynamic('PON_AUC_SUPPLIER_HEADER_NOTES' ,
2095                         interface.auction_header_id,
2096                         interface.auction_line_number,
2097                         interface.bid_number,
2098                         interface.bid_line_number,
2099                         'PO_HEADERS',
2100                         interface.po_header_id,
2101                         interface.created_by,
2102                         interface.last_update_login ,
2103                         null,
2104                         null,
2105                         null);
2106 
2107               -- Bug# 3207840. build and attach negotiation/bid header
2108         -- attributes as to supplier attachment on po/blanket header
2109         -- from FPJ.
2110               po_negotiations_sv2.add_attch_dynamic('PON_BID_HEADER_ATTRIBUTES' ,
2111                         interface.auction_header_id,
2112                         NULL,
2113                         interface.bid_number,
2114                         NULL,
2115                         'PO_HEADERS',
2116                         interface.po_header_id,
2117                         interface.created_by,
2118                         interface.last_update_login ,
2119                         null,
2120                         null,
2121                         null);
2122 
2123           IF g_debug_stmt THEN
2124             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2125                                 p_token    => l_progress,
2126                                 p_message  => 'After copying attachments from Sourcing');
2127           END IF;
2128         end if; --attachments for header
2129 
2130       l_progress:= '260';
2131    -- the call to procedure calculate_local should happen only for doc_type PO
2132         if (g_document_subtype='STANDARD' or g_document_subtype='PLANNED') then
2133          calculate_local('PO', 'HEADER', interface.po_header_id);
2134         end if;
2135 
2136         IF g_debug_stmt THEN
2137           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2138                               p_token    => l_progress,
2139                               p_message  => 'After calculate_local');
2140         END IF;
2141 
2142         --<RENEG BLANKET FPI END>
2143 
2144       ELSIF(g_document_subtype='RELEASE')THEN
2145 
2146          l_progress:= '270';
2147          SELECT po_releases_s.nextval
2148            INTO g_po_release_id
2149            FROM sys.dual;
2150 
2151    /*
2152    ** assign the document id to get passed back to the
2153    ** calling module.
2154    */
2155          x_document_id := g_po_release_id;
2156 
2157 /*Bug 1664638
2158   Inserting negative of g_po_release_id as release number to
2159   avoid unique constraint violation
2160 */
2161         l_progress:='280';
2162 
2163         -- Bug 3599251: Assign value to l_document_creation_method and
2164         -- insert it into po_releases_all instead of p_document_creation_method
2165         -- Bug 3648268 Use lookup code instead of hardcoded value
2166         IF g_interface_source_code = 'CONSUMPTION_ADVICE' THEN
2167            l_document_creation_method := 'CREATE_CONSUMPTION';
2168         END IF;
2169 
2170         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2171             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2172                                 p_token    => l_progress,
2173                                 p_message  => 'Before insert into PO_RELEASES');
2174         END IF;
2175 
2176          INSERT INTO po_releases_all  --<Shared Proc FPJ>
2177              (po_release_id,
2178               last_update_date,
2179               last_updated_by,
2180               po_header_id,
2181               release_num,
2182               agent_id,
2183               release_date,
2184               creation_date,
2185               created_by,
2186               last_update_login,
2187               revision_num,
2188               approved_flag,
2189               authorization_status,
2190               print_count,
2191               release_type,
2192               pay_on_code,
2193               pcard_id,
2194               consigned_consumption_flag,   -- CONSIGNED FPI
2195               shipping_control,    -- <INBOUND LOGISTICS FPJ>
2196               org_id  --<Shared Proc FPJ>
2197         ,document_creation_method --<DBI FPJ>
2198         ,tax_attribute_update_code  --<eTax integration R12>
2199         ,acceptance_required_flag   --Bug 7518967 : Default Acceptance Required Check ER
2200               )
2201        VALUES (g_po_release_id,
2202                interface.last_update_date,
2203                interface.last_updated_by,
2204                interface.po_header_id,
2205                -g_po_release_id, --interface.release_num
2206                interface.agent_id,
2207                nvl(interface.release_date,sysdate),
2208                interface.creation_date,
2209                interface.created_by,
2210                interface.last_update_login,
2211                0,
2212                'N',
2213                'INCOMPLETE',
2214                0,
2215                'BLANKET',
2216                interface.pay_on_code,
2217                interface.pcard_id,
2218                decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'Y',null), -- CONSIGNED FPI
2219                interface.shipping_control,    -- <INBOUND LOGISTICS FPJ>
2220                g_purchasing_ou_id  --<Shared Proc FPJ>
2221          ,l_document_creation_method  --<DBI FPJ> -- Bug 3599251
2222                ,nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax Integration R12>
2223                ,decode(params.acceptance_required_flag,'N','N',   /* Bug 7518967 : Default Acceptance Required Check ER: Geting the default acceptance_required_flag */
2224 	                                               'Y','Y',
2225 						       'D','Y',
2226 						       'S','Y',
2227 						       'N')
2228                );
2229 
2230         l_progress:='290';
2231         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2232             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2233                                 p_token    => l_progress,
2234                                 p_message  => 'After insert into PO_RELEASES');
2235         END IF;
2236        -- Bug 882050: Release header level global attribute
2237 
2238        calculate_local('RELEASE', 'HEADER', g_po_release_id);
2239 
2240       END IF; /* of Standard/Planned */
2241     END IF; /* of NEW/ADD */ --Bug#5024876: Uncommenting the END IF commented by Bug#4886821
2242 
2243     l_progress:='300';
2244     -- <Complex Work R12 Start>
2245     create_line(
2246       x_interface_header_id => x_interface_header_id
2247     , p_is_complex_work_po => l_is_complex_work_po
2248     );
2249     -- <Complex Work R12 End>
2250 
2251     IF g_debug_stmt THEN
2252       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2253                           p_token    => l_progress,
2254                           p_message  => 'After create_line');
2255     END IF;
2256 
2257 
2258     LOOP
2259 
2260         FETCH interface_cursor INTO interface;
2261         EXIT WHEN interface_cursor%notfound;
2262 
2263         -- <Complex Work R12 Start>
2264         create_line(
2265           x_interface_header_id => x_interface_header_id
2266         , p_is_complex_work_po => l_is_complex_work_po
2267         );
2268         -- <Complex Work R12 End>
2269 
2270       IF g_debug_stmt THEN
2271         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2272                             p_token    => l_progress,
2273                             p_message  => 'After create_line (inside complex works loop)');
2274       END IF;
2275 
2276     END LOOP;
2277 
2278     --<Begin Bug# 5365579> After iterating through the cursor we want to reset
2279     --the cursor back to the first record for the rest of the procedure.
2280     CLOSE interface_cursor;
2281     OPEN interface_cursor(x_interface_header_id);
2282     FETCH interface_cursor INTO interface;
2283 
2284     IF interface_cursor%notfound THEN
2285       CLOSE interface_cursor;
2286       RETURN;
2287     END IF;
2288     --<End Bug# 5365579>
2289 
2290     --<Unified Catalog R12 START>
2291     -- Since we have the po_line_id available on po_attr_values_interface and tlp_interface
2292     -- we can move all records from interface to txn tables for all lines of a given blanket
2293     IF ((g_interface_source_code ='SOURCING') AND (g_document_subtype = 'BLANKET')) THEN
2294       IF g_debug_stmt THEN
2295         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2296                             p_token    => l_progress,
2297                             p_message  => 'Calling PO_ATTRIBUTE_VALUES_PVT.transfer_intf_item_attribs');
2298       END IF;
2299       PO_ATTRIBUTE_VALUES_PVT.transfer_intf_item_attribs(x_interface_header_id);
2300     END IF;
2301     -- <Unified Catalog R12 END>
2302 
2303 
2304     IF g_debug_stmt THEN
2305       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2306                           p_token    => l_progress,
2307                           p_message  => 'After PO_ATTRIBUTE_VALUES_PVT.transfer_intf_item_attribs');
2308     END IF;
2309 
2310     l_progress:='310';
2311 /* Bug 1093645:Code added to fix the deadlock issue in autocreate*/
2312     if (g_mode = 'NEW')  then
2313          IF (params.po_num_code='AUTOMATIC') AND
2314             --<SOURCING TO PO FPH>
2315       --modified the if clause to include PA
2316             (g_document_type in ('PO','PA'))         AND
2317 /* Bug 1183082
2318    If emergency po number is mentioned then the interface document number
2319    will have that value and it can be alphanumeric though the po num code
2320    is automatic.
2321    In case of automatic, we populate a dummy value in segment1(in po_headers)
2322    which is negative of po_header_id.
2323    We should be populating the segment1 from unique identifier control
2324    table only if the segment1 is negative of po_header id and
2325    hence the following logic.
2326            (interface.document_num  = to_char((-1* x_document_id))) THEN
2327 */
2328            (interface.document_num  = to_char((-1* x_document_id))) THEN
2329 
2330                l_progress:= '320';
2331 
2332                -- bug5174177
2333                -- Call Centralized API to get the next po number
2334                x_document_num :=
2335                  PO_CORE_SV1.default_po_unique_identifier
2336                  ( p_table_name => 'PO_HEADERS',
2337                    p_org_id     => g_purchasing_ou_id
2338                  );
2339 
2340                IF g_debug_stmt THEN
2341                  PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2342                             p_token    => l_progress,
2343                             p_message  => 'new po num = ' || x_document_num);
2344                END IF;
2345 
2346                l_progress := '325';
2347 
2348                UPDATE po_headers_all  --<Shared Proc FPJ>
2349                   set segment1=x_document_num
2350                where po_header_id=x_document_id;
2351 
2352           END IF;
2353 
2354           --<CONTERMS FPJ START>
2355           --Copy contract terms if sourcing doc had a template attached
2356           IF ((g_interface_source_code ='SOURCING')
2357               AND  (p_conterms_exist_flag= 'Y')) then
2358 
2359               l_progress:= '330';
2360               l_contract_doc_type:= PO_CONTERMS_UTL_GRP.GET_PO_CONTRACT_DOCTYPE(
2361                                   p_sub_doc_type=>g_document_subtype);
2362 
2363                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2364                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2365                                         p_token    => l_progress,
2366                                         p_message  => 'Contracts template attached');
2367                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2368                                         p_progress => l_progress,
2369                                         p_name     => 'x_document_id',
2370                                         p_value    => x_document_id);
2371                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2372                                         p_progress => l_progress,
2373                                         p_name     => 'x_document_num',
2374                                         p_value    => x_document_num);
2375                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2376                                         p_progress => l_progress,
2377                                         p_name     => 'l_contract_doc_type',
2378                                         p_value    => l_contract_doc_type);
2379                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2380                                         p_progress => l_progress,
2381                                         p_name     => 'interface.bid_number',
2382                                         p_value    => interface.bid_number);
2383                     PO_DEBUG.debug_var (p_log_head => g_log_head||l_api_name,
2384                                         p_progress => l_progress,
2385                                         p_name     => 'p_sourcing_k_doc_type',
2386                                         p_value    => p_sourcing_k_doc_type);
2387                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2388                                         p_token    => l_progress,
2389                                         p_message  => 'before call okc_terms_copy_grp.copy_doc');
2390                 END IF;
2391 
2392                 l_progress:= '340';
2393 
2394                 OKC_TERMS_COPY_GRP.copy_doc     (
2395                         p_api_version           => 1.0,
2396                         p_source_doc_type     => p_sourcing_k_doc_type,
2397                         p_source_doc_id         => interface.bid_number,
2398                         p_target_doc_type     => l_contract_doc_type,
2399                         p_target_doc_id         => x_document_id,
2400                         p_keep_version          => 'Y',
2401                         p_article_effective_date=> sysdate,
2402                         p_initialize_status_yn  => 'N',
2403                         p_reset_Fixed_Date_yn   => 'N',
2404                         p_copy_del_attachments_yn=>'Y',
2405                         p_copy_deliverables     => 'Y',
2406                         p_document_number     => x_document_num,
2407                         p_copy_abstract_yn    => 'Y',   -- Bug 4051316
2408                         x_return_status        =>  l_return_status,
2409                         x_msg_data             =>  l_msg_data,
2410                         x_msg_count            =>  l_msg_count
2411                         );
2412 
2413                 l_progress:='350';
2414                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2415                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2416                                         p_token    => l_progress,
2417                                         p_message  => 'after call okc_terms_copy_grp.copy_doc.Return status:'||l_return_status);
2418                 END IF;
2419 
2420                  IF l_return_status <> FND_API.G_RET_STS_SUCCESS then
2421                        RAISE l_Contracts_call_exception;
2422                  END IF; -- Return status from contracts
2423 
2424             END IF; -- if p_conterms_exist_flag and sourcing doc
2425             --<CONTERMS FPJ END>
2426 
2427      l_progress := '360';
2428   /* FPI GA start  Update the terms after the successful completion of PO */
2429 
2430      IF  (g_document_subtype = 'STANDARD') and
2431          (g_interface_source_code <> 'CONSUMPTION_ADVICE')  then  -- CONSIGNED FPI
2432        po_interface_s2.update_terms(x_document_id);
2433      END IF;
2434 
2435    /* FPI GA end */
2436      l_progress := '370';
2437 
2438 /*Bug 1664638
2439   Since while inserting into po_releases , we inserted a negative
2440   number to avoid unique constraint violation, just before
2441   commit we are updating the correct value for release number.
2442 */
2443           IF  (g_document_subtype = 'RELEASE') then
2444 --Added a new loop as a part of 1805397 for fixing unique
2445 --constraint error
2446 --jbalakri
2447            begin
2448             loop
2449               begin
2450                  l_progress := '380';
2451                  select nvl(max(release_num),0) + 1
2452                  into   x_release_num
2453                  from   po_releases_all por  --<Shared Proc FPJ>
2454                  where  por.po_header_id = interface.po_header_id;
2455 /*Bug 1724603
2456   When we are creating a blanket release for the first time then
2457   we end up creating releases with negative release numbers
2458   and hence it required the following lines to be added as an
2459   extension to the fix in 1664638
2460 */
2461 
2462                  if (x_release_num <= 0) then   --Bug 4473796 : added '='
2463                      x_release_num := 1;
2464                  end if;
2465 
2466                  l_progress := '390';
2467                  update po_releases_all  --<Shared Proc FPJ>
2468                  set    release_num = x_release_num
2469                  where  po_releases_all.po_header_id = interface.po_header_id
2470                  and    release_num = -g_po_release_id;
2471                          exit;
2472                exception
2473                 when DUP_VAL_ON_INDEX then
2474                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2475                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2476                                             p_token    => l_progress,
2477                                             p_message  => 'DUP_VAL_ON_INDEX: '||SQLERRM);
2478                     END IF;
2479                   RAISE;
2480                 when others then
2481                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
2482                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
2483                                            p_progress => l_progress);
2484                     END IF;
2485                   RAISE;
2486               end;
2487             end loop;
2488 --end of add for 1805397
2489            end;
2490            END IF;
2491 
2492     END IF;
2493 
2494     l_progress:='400';
2495 
2496     -- Bug 882050: Document level global attribute
2497 
2498     if (interface.document_subtype = 'STANDARD' or
2499         interface.document_subtype = 'PLANNED') THEN
2500 
2501         calculate_local('PO', 'DOCUMENT', interface.po_header_id);
2502     elsif (g_document_subtype='RELEASE') THEN
2503 
2504         calculate_local('RELEASE', 'DOCUMENT', g_po_release_id);
2505     end if;
2506 
2507     l_progress := '410';
2508     wrapup(x_interface_header_id);
2509 
2510     CLOSE interface_cursor;
2511     --
2512     -- <eTax Integration R12 Start>
2513     -- Removed multiple tax calls from procedure
2514     -- create_shipment and placed a single call here for calculating
2515     -- tax for the whole document
2516     --
2517     IF (g_document_subtype in ('STANDARD', 'PLANNED')) THEN
2518        l_progress := '413';
2519        l_return_status := NULL;
2520        -- Bug 5067321. For Add To, x_document_id is null, use
2521        -- interface.po_header_id instead
2522        IF (g_mode = 'ADD') THEN
2523          tax_document_id := interface.po_header_id;
2524        ELSE
2525          tax_document_id := x_document_id;
2526        END IF;
2527 
2528        PO_TAX_INTERFACE_PVT.calculate_tax( x_return_status     => l_return_status,
2529                                            p_po_header_id      => tax_document_id,
2530                                            p_po_release_id     => NULL,
2531                                            p_calling_program   => 'POXBWVRP_PO');
2532        IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
2533          l_progress := '414';
2534          IF g_interface_source_code = 'CONSUMPTION_ADVICE' THEN
2535            ROLLBACK TO TAX_CALCULATION_ERROR;
2536            x_document_id := NULL;
2537            fnd_message.set_name('PO','PO_API_ERROR');
2538            fnd_message.set_token( TOKEN  => 'PROC_CALLER'
2539                                 , VALUE  => 'PO_INTERFACE_S.CREATE_PO');
2540            fnd_message.set_token( TOKEN  => 'PROC_CALLED'
2541                                 , VALUE  => 'PO_TAX_INTERFACE_PVT.CALCULATE_TAX');
2542            fnd_msg_pub.add;
2543            fnd_message.set_name('PO','PO_AP_TAX_ENGINE_FAILED_WARN');
2544            fnd_msg_pub.add;
2545          END IF;
2546        END IF;
2547     ELSIF (g_document_subtype = 'RELEASE') THEN
2548        l_progress := '416';
2549        l_return_status := NULL;
2550        -- Bug 5067321. For Add To, x_document_id is null, use
2551        -- interface.po_header_id instead
2552        IF (g_mode = 'ADD') THEN
2553          tax_document_id := g_po_release_id;
2554        ELSE
2555          tax_document_id := x_document_id;
2556        END IF;
2557 
2558        PO_TAX_INTERFACE_PVT.calculate_tax(x_return_status     => l_return_status,
2559                                           p_po_header_id      => NULL,
2560                                           p_po_release_id     => tax_document_id,
2561                                           p_calling_program   => 'POXBWVRP_PO');
2562        IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
2563          IF g_interface_source_code = 'CONSUMPTION_ADVICE' THEN
2564            ROLLBACK TO TAX_CALCULATION_ERROR;
2565            x_document_id := NULL;
2566            fnd_message.set_name('PO','PO_API_ERROR');
2567            fnd_message.set_token( TOKEN  => 'PROC_CALLER'
2568                                 , VALUE  => 'PO_INTERFACE_S.CREATE_PO');
2569            fnd_message.set_token( TOKEN  => 'PROC_CALLED'
2570                                 , VALUE  => 'PO_TAX_INTERFACE_PVT.CALCULATE_TAX');
2571            fnd_msg_pub.add;
2572            fnd_message.set_name('PO','PO_AP_TAX_ENGINE_FAILED_WARN');
2573            fnd_msg_pub.add;
2574          END IF;
2575          l_progress := '417';
2576        END IF;
2577     END IF;
2578     -- <eTax Integration R12 End>
2579     l_progress := '420';
2580 
2581     --<SOURCING TO PO FPH>
2582     --for sourcing transaction is controlled by the sourcing code.
2583     if g_interface_source_code not in ('SOURCING','CONSUMPTION_ADVICE') then
2584 
2585 /* Bug 2534534 If no records are processed then we should not commit */
2586       if(g_number_records_processed > 0) then
2587          l_progress := '430';
2588          COMMIT;
2589       else
2590          l_progress := '440';
2591          rollback to savepoint create_po; --Bug 4314776
2592       end if;
2593     end if;
2594 
2595     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2596         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
2597     END IF;
2598 EXCEPTION
2599 --<CONTERMS FPJ START>
2600   WHEN l_Contracts_call_exception then
2601        -- put error messages in log
2602         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2603             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2604                                 p_token    => l_progress,
2605                                 p_message  => 'Create_po: Inside l_contracts_call_exception');
2606         END IF;
2607           Fnd_message.set_name('PO','PO_API_ERROR');
2608           Fnd_message.set_token( token  => 'PROC_CALLER'
2609                                , VALUE => 'PO_INTERFACE_S.CREATE_PO');
2610           Fnd_message.set_token( token  => 'PROC_CALLED'
2611                                , VALUE => 'OKC_TERMS_CPOY_GRP.COPY_DOC');
2612           FND_MSG_PUB.Add;
2613 
2614         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2615             l_msg_count := FND_MSG_PUB.Count_Msg;
2616             FOR i IN 1..l_msg_count LOOP
2617                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2618                                     p_token    => l_progress||'_EXCEPTION_'||i,
2619                                     p_message  => FND_MSG_PUB.Get(p_msg_index=>i,p_encoded =>'F'));
2620             END LOOP;
2621         END IF;
2622      IF interface_cursor%ISOPEN then
2623        CLOSE interface_cursor;
2624      END IF;
2625      RAISE;
2626 --<CONTERMS FPJ END>
2627 
2628 /* Bug: 1137860:
2629    Raise exception regardless of error. This will make debuging easier */
2630    WHEN OTHERS THEN
2631     --  wrapup(x_interface_header_id);
2632      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
2633          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
2634                             p_progress => l_progress);
2635      END IF;
2636      po_message_s.sql_error('CREATE_PO',l_progress,sqlcode);
2637      if interface_cursor%isopen then
2638        CLOSE interface_cursor;
2639      end if;
2640      --togeorge 11/20/2001
2641      -- Bug 1349801
2642      -- Added a Rollback when a Exception was raised
2643      -- This Rollbacks all the Changes done when a Exception Condition was raised. This was done to avoid PO's with negative numbers getting created.
2644      --raise;
2645     --<SOURCING TO PO FPH>
2646     --for sourcing transaction is controlled by the sourcing code.
2647     if g_interface_source_code not in  ('SOURCING', 'CONSUMPTION_ADVICE') then
2648       ROLLBACK  to savepoint create_po;  --Bug 4314776
2649        wrapup(x_interface_header_id); --Bug 4314776
2650 
2651      end if;
2652      --
2653     raise;  --<Bug 3336920>
2654 END create_po;
2655 
2656 /* ============================================================================
2657      NAME: CREATE_LINE
2658      DESC: Create/Add to document line
2659      ARGS: IN : x_interface_header_id_id IN number
2660      ALGR:
2661 
2662    ==========================================================================*/
2663 -- <Complex Work R12>: Added parameter p_is_complex_work_po
2664 PROCEDURE create_line(
2665   x_interface_header_id IN NUMBER
2666 , p_is_complex_work_po  IN BOOLEAN
2667 )
2668 IS
2669 x_po_line_id       number;
2670 x_po_line_type_id  number;
2671 x_line_num         po_lines.line_num%type;
2672 x_po_item_id       number;
2673 x_order_type_lookup_code varchar2(25);
2674 l_purchase_basis         PO_LINE_TYPES_B.purchase_basis%TYPE; -- <SERVICES FPJ>
2675 x_po_item_revision po_lines.item_revision%type;
2676 x_po_unit_meas_lookup_code po_lines.unit_meas_lookup_code%type;
2677 x_po_unit_price    number;
2678 x_po_transaction_reason_code po_lines.transaction_reason_code%type;
2679 x_price_break_lookup_code    po_lines.price_break_lookup_code%type;
2680 x_quantity         number := '';
2681 x_requisition_header_id number := ''; /* Used for copying attachments */
2682 
2683 x_line_location_id number := null;
2684 l_line_loc_id_tbl po_tbl_number;
2685 
2686 l_price_break_id  PO_LINE_LOCATIONS_ALL.line_location_id%TYPE;-- <SERVICES FPJ>
2687 
2688 x_quote_header_id number := null;
2689 x_quote_line_id number := null;
2690 x_match_blanket_line varchar2(1) := null;
2691 x_unit_price  po_lines.unit_price%TYPE := null;
2692 l_base_unit_price  po_lines.base_unit_price%TYPE := null; -- <FPJ Advanced Price>
2693 
2694 /* obtain currency info to adjust precision */
2695 x_precision   number :='';
2696 x_ext_precision   number :='';
2697 x_min_unit    number :='';
2698 /* project/task enhancement for RFQ */
2699 x_project_id    number :='';
2700 x_task_id   number :='';
2701 x_req_dist_id   number :='';
2702 --togeorge 11/17/2000
2703 --Bug# 1369049
2704 --Added logic to default tax_name in po_lines
2705    x_tax_id                ap_tax_codes.tax_id%type;
2706    x_tax_type              ap_tax_codes.tax_type%type;
2707    x_description           ap_tax_codes.description%type;
2708    x_allow_tax_code_override_flag  gl_tax_option_accounts.allow_tax_code_override_flag%type;
2709    x_tax_name              po_lines.tax_name%type;
2710    x_ship_to_location_id   number:= 0;
2711    x_ship_to_loc_org_id    mtl_system_items.organization_id%TYPE;
2712    x_ship_org_code         varchar2(3);
2713 
2714 /** <UTF8 FPI> **/
2715 /** tpoon 9/29/2002 **/
2716 /** Changed x_ship_org_name to use %TYPE **/
2717 --   x_ship_org_name         varchar2(60);
2718    x_ship_org_name         hr_all_organization_units.name%TYPE;
2719 --
2720 -- bug# 3345108
2721 -- comment out most of the changes done by bug 2219743.
2722 -- bug# 2219743
2723 /**
2724    x_secondary_qty         po_lines.secondary_quantity%type := NULL;
2725    x_item_number           VARCHAR2(240);
2726    x_process_org           VARCHAR2(1);
2727    x_dummy                 VARCHAR2(240);
2728    x_product               VARCHAR2(3) := 'GMI';
2729    x_opm_installed         VARCHAR2(1);
2730    x_retvar                BOOLEAN;
2731    ic_item_mst_rec IC_ITEM_MST%ROWTYPE;
2732    ic_item_cpg_rec IC_ITEM_CPG%ROWTYPE;
2733    x_order_opm_um  ic_item_mst.item_um%type := NULL;
2734    x_inv_org_id    mtl_system_items.organization_id%TYPE;
2735 **/
2736 l_api_name CONSTANT VARCHAR2(30) := 'create_line';
2737 d_mod CONSTANT VARCHAR2(255) := g_log_head||l_api_name;
2738 -- end of 2219743
2739 
2740     --<SOURCING TO PO FPH START>
2741     x_column1       varchar2(10);
2742     x_result        varchar2(7);
2743     update_req_pool_fail  exception;
2744     x_hazard_class_id   number:=null;
2745     x_un_number_id    number:=null;
2746     x_unit_of_measure   po_line_types.unit_of_measure%type:=null;
2747     --The following flag indicates whether copying the attachments from (all)the
2748     --sourcing entities need to be suppressed due to the grouping of lines.
2749     x_attch_suppress_flag       varchar2(1) :='N';
2750     --<SOURCING TO PO FPH END>
2751 
2752     l_db_quantity   po_lines.quantity%TYPE := null; --bug#2723479
2753 
2754     -- Bug 2735840 START
2755     l_uom_convert varchar2(2) := fnd_profile.value('PO_REQ_BPA_UOM_CONVERT');
2756     l_ga_uom                    PO_LINES.unit_meas_lookup_code%TYPE;
2757     l_quantity_in_ga_uom        PO_LINES_INTERFACE.quantity%TYPE;
2758     l_conversion_rate number :=1;
2759     -- Bug 2735840 END
2760 
2761     -- Bug 2875346.
2762     l_one_time_att_doc_id fnd_attached_documents.attached_document_id%TYPE;
2763 
2764     -- <SERVICES FPJ START>
2765     l_job_long_description  PO_REQUISITION_LINES_ALL.job_long_description%TYPE;
2766     l_who_rec               PO_NEGOTIATIONS_SV2.who_rec_type;
2767 
2768     l_return_status         VARCHAR2(1);
2769 
2770     l_order_type_lookup_code  PO_LINE_TYPES_B.order_type_lookup_code%TYPE;
2771     l_purchase_basis1         PO_LINE_TYPES_B.purchase_basis%TYPE;
2772     l_matching_basis          PO_LINE_TYPES_B.matching_basis%TYPE;
2773     l_category_id             PO_LINE_TYPES_B.category_id%TYPE;
2774     l_unit_meas_lookup_code   PO_LINE_TYPES_B.unit_of_measure%TYPE;
2775     l_unit_price              PO_LINE_TYPES_B.unit_price%TYPE;
2776     l_outside_operation_flag  PO_LINE_TYPES_B.outside_operation_flag%TYPE;
2777     l_receiving_flag          PO_LINE_TYPES_B.receiving_flag%TYPE;
2778     l_receive_close_tolerance PO_LINE_TYPES_B.receive_close_tolerance%TYPE;
2779     -- <SERVICES FPJ END>
2780     l_negotiated_by_preparer_flag po_lines_all.negotiated_by_preparer_flag%type; --<DBI FPJ>
2781     l_type_lookup_code po_headers_all.type_lookup_code%type; --<DBI FPJ>
2782     l_global_agreement_flag po_headers_all.global_agreement_flag%type; --<DBI FPJ>
2783 
2784     -- oneoff 3201308 start
2785     l_needby_prf  varchar2(1);
2786     l_shipto_prf  varchar2(1);
2787     l_min_shipment_num po_line_locations_all.shipment_num%TYPE;
2788     l_ship_to_loc po_line_locations_all.ship_to_location_id%TYPE;
2789     l_ship_to_org po_line_locations_all.ship_to_organization_id%TYPE;
2790     l_need_by_date po_line_locations_all.need_by_date%TYPE;
2791     -- oneoff 3201308 end
2792 
2793     l_contractor_status PO_REQUISITION_LINES_ALL.contractor_status%TYPE;
2794     --<Bug 3353109>
2795 
2796     l_routing_name      RCV_ROUTING_HEADERS.routing_name%TYPE; -- <BUG 3365446>
2797 
2798     l_progress VARCHAR2(3) := '000';                --< Bug 3210331 >
2799     l_manual_price_change_flag po_lines_all.manual_price_change_flag%TYPE := NULL; --bug 3495772
2800     l_from_type_lookup_code PO_HEADERS.type_lookup_code%type;--bug#3612701
2801 
2802     --<INVCONV R12 START>
2803     x_secondary_unit_def  MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
2804     x_secondary_uom       MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
2805     x_secondary_quantity_def  PO_LINES.SECONDARY_QUANTITY%TYPE;
2806     x_preferred_grade_def MTL_GRADES.GRADE_CODE%TYPE;
2807     l_quantity_temp   PO_LINES.QUANTITY%TYPE;
2808     --<INVCONV R12 END>
2809 
2810     l_requesting_ou_id    PO_REQUISITION_LINES_ALL.org_id%TYPE; -- <ACHTML R12>
2811     l_rate_for_req_fields GL_DAILY_RATES.conversion_rate%TYPE; -- <ACHTML R12>
2812 
2813     -- <Unified Catalog R12 START>
2814     l_po_line_id_tbl po_line_id_tbl;
2815     l_interface_header_id_tbl interface_header_id_tbl;
2816     l_interface_line_id_tbl interface_line_id_tbl;
2817     -- <Unified Catalog R12 END>
2818 
2819     l_outsourced_assembly po_line_locations_all.outsourced_assembly%type; --<SHIKYU R12>
2820     l_retainage_rate      PO_VENDOR_SITES_ALL.retainage_rate%type; --bug#5255878
2821 BEGIN
2822         l_outsourced_assembly :=2; --<SHIKYU R12>
2823   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2824     PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
2825   END IF;
2826 
2827   -- <ACHTML R12 START>
2828   -- Determine the Requesting OU from the current requisition line.
2829   -- If there is no backing req, take the globally determined Requesting OU.
2830   IF (interface.requisition_line_id IS NOT NULL)
2831   THEN
2832     BEGIN
2833       SELECT prl.org_id
2834       INTO   l_requesting_ou_id
2835       FROM   po_requisition_lines_all prl
2836       WHERE  prl.requisition_line_id = interface.requisition_line_id;
2837     EXCEPTION
2838       WHEN OTHERS
2839       THEN
2840         IF g_debug_unexp
2841         THEN
2842           PO_DEBUG.debug_exc(
2843             p_log_head => g_log_head||l_api_name,
2844             p_progress => l_progress
2845           );
2846         END IF;
2847         wrapup(interface.interface_header_id);
2848         po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
2849         raise;
2850       END;
2851   ELSE
2852     l_requesting_ou_id := g_hdr_requesting_ou_id;
2853   END IF;
2854 
2855   -- Determine the currency conversion rate for the current line.
2856   -- If called from Sourcing, simply use the rate specified in the interface
2857   -- table.
2858   IF (g_interface_source_code <> 'SOURCING'
2859       AND g_purchasing_ou_id <> l_requesting_ou_id
2860       AND interface.document_subtype = 'STANDARD')
2861   THEN
2862     get_rate_for_req_price(
2863       p_requesting_ou_id => l_requesting_ou_id, -- IN
2864       p_purchasing_ou_id => g_purchasing_ou_id, -- IN
2865       p_po_currency_code => interface.h_currency_code, -- IN
2866       p_rate_type        => interface.h_rate_type, -- IN
2867       p_rate_date        => interface.h_rate_date, -- IN
2868       x_rate             => l_rate_for_req_fields -- OUT
2869     );
2870   END IF;
2871 
2872   IF (l_rate_for_req_fields IS NULL)
2873   THEN
2874     l_rate_for_req_fields := nvl(g_rate_for_req_fields, 1);
2875   END IF;
2876   -- <ACHTML R12 END>
2877 
2878    /* initialize values */
2879    x_quantity := interface.quantity;
2880    x_unit_of_measure := interface.unit_meas_lookup_code; -- Bug 2735840
2881 
2882    /* Bug 586033, lpo, 11/25/97
2883    ** When trying to autocreate a release from a req with multiple lines
2884    ** against a blanket and the blanket has lines that match only some
2885    ** (i.e. not all) of the req lines, interface.line_type_id will be null
2886    ** and the following SELECT statement would cause a NO_DATA_FOUND
2887    ** exception. Since the X_match_blanket_line variable hasn't been set
2888    ** to 'N', the exception handlier does a 'raise', causing the COMMIT
2889    ** statement in create_po() to be skipped. Added an if statement below
2890    ** so that it wouldn't raise NO_DATA_FOUND exception until the
2891    ** X_match_blanket_line variable is set to 'N' later in the code.
2892    */
2893    IF (interface.line_type_id IS NOT NULL) THEN  -- Bug 586033, lpo, 11/25/97
2894      l_progress := '010';
2895      SELECT order_type_lookup_code
2896      ,      purchase_basis                                    -- <SERVICES FPJ>
2897      INTO   x_order_type_lookup_code
2898      ,      l_purchase_basis                                  -- <SERVICES FPJ>
2899      FROM   po_line_types
2900      WHERE  line_type_id = interface.line_type_id;
2901    END IF;  -- Bug 586033, lpo, 11/25/97
2902 
2903    l_progress := '020';
2904 
2905    IF interface.h_currency_code IS NOT NULL THEN
2906         fnd_currency.get_info(interface.h_currency_code,
2907                             x_precision,
2908                             x_ext_precision,
2909                               x_min_unit );
2910    END IF;
2911 
2912     /*
2913     ** Check to see if the po line exists
2914     ** Note that we do not need to check if the line exists in the
2915     ** interface table since we are in the process of inserting
2916     ** lines into the po lines table on a record by record basis.
2917     */
2918     IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED' or
2919        g_document_type = 'RFQ'
2920        --<SOURCING TO PO FPH>
2921        --do the select for blanket also
2922        or g_document_subtype = 'BLANKET') THEN
2923 
2924       BEGIN
2925 
2926       l_progress := '030';
2927       SELECT po_line_id,
2928              line_type_id,
2929              line_num,
2930              item_id,
2931              item_revision,
2932              unit_meas_lookup_code,
2933              base_unit_price,   -- <FPJ Advanced Price>
2934              unit_price,
2935              transaction_reason_code,
2936              price_break_lookup_code,
2937              manual_price_change_flag --bug 3495772
2938         INTO x_po_line_id,
2939              x_po_line_type_id,
2940              x_line_num,
2941              x_po_item_id,
2942              x_po_item_revision,
2943              x_po_unit_meas_lookup_code,
2944              l_base_unit_price,   -- <FPJ Advanced Price>
2945              x_po_unit_price,
2946              x_po_transaction_reason_code,
2947              x_price_break_lookup_code,
2948              l_manual_price_change_flag --bug 3495772
2949         FROM PO_LINES_ALL  --<Shared Proc FPJ>
2950        WHERE PO_HEADER_ID = interface.po_header_id
2951          AND LINE_NUM = interface.line_num
2952          FOR UPDATE OF quantity;
2953 
2954        EXCEPTION
2955     WHEN NO_DATA_FOUND then
2956             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
2957                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
2958                                     p_token    => l_progress,
2959                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
2960             END IF;
2961        END;
2962 
2963      ELSIF(g_document_subtype = 'RELEASE')THEN
2964 
2965       l_progress := '040';
2966       X_match_blanket_line := 'N';
2967 
2968 /* Bug 2534534 Reverting the fix done in 1951084 */
2969 --     BEGIN
2970       SELECT po_line_id
2971   INTO x_po_line_id
2972         FROM po_lines_all  --<Shared Proc FPJ>
2973        WHERE po_header_id = interface.po_header_id
2974          AND line_num = interface.line_num
2975          FOR UPDATE OF quantity;
2976 
2977 /*      -- Bug 1951084 : added the exception handler
2978 
2979       EXCEPTION
2980     WHEN NO_DATA_FOUND then null;
2981        END;
2982 */
2983 
2984       X_match_blanket_line := 'Y';
2985 
2986      END IF;
2987 
2988      l_progress := '050';
2989      /*
2990      ** Bug 515985  ecso 10/9/97
2991      **       This procedure should be called even if line is not found
2992      ** when autocreating blanket releases
2993      */
2994 
2995     -- <BUG 3365446 START>
2996     --
2997     RCV_CORE_S.get_receiving_controls
2998     (   p_order_type_lookup_code      => x_order_type_lookup_code
2999     ,   p_purchase_basis              => l_purchase_basis
3000     ,   p_line_location_id            => NULL
3001     ,   p_item_id                     => interface.item_id
3002     ,   p_org_id                      => nvl(interface.destination_organization_id,params.inventory_organization_id)
3003     ,   p_vendor_id                   => interface.vendor_id
3004     ,   p_drop_ship_flag              => interface.drop_ship_flag
3005     ,   x_enforce_ship_to_loc_code    => rc.enforce_ship_to_location_code
3006     ,   x_allow_substitute_receipts   => rc.allow_substitute_receipts_flag
3007     ,   x_routing_id                  => rc.receiving_routing_id
3008     ,   x_routing_name                => l_routing_name
3009     ,   x_qty_rcv_tolerance           => rc.qty_rcv_tolerance
3010     ,   x_qty_rcv_exception_code      => rc.qty_rcv_exception_code
3011     ,   x_days_early_receipt_allowed  => rc.days_early_receipt_allowed
3012     ,   x_days_late_receipt_allowed   => rc.days_late_receipt_allowed
3013     ,   x_receipt_days_exception_code => rc.receipt_days_exception_code
3014     );
3015     -- <BUG 3365446 END>
3016 
3017 -- bug# 3345108 defaults secondary qty /UOM and grade in SETUP_INTERFACE_TABLE.
3018 -- no need to default it again here. comment out this logic.
3019 
3020 /**
3021        --mchandak 02/11/2002
3022        --Bug# 2219743
3023        --Added logic to default secondary qnty,UOM and grade in po_lines
3024        --if common purchasing is installed for OPM dual item
3025        IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED') AND NOT GML_PO_FOR_PROCESS.check_po_for_proc
3026        THEN
3027            x_retvar := FND_INSTALLATION.get_app_info(x_product,x_opm_installed,x_dummy,x_dummy);
3028            BEGIN
3029                 l_progress := '060';
3030                 SELECT inventory_organization_id INTO x_inv_org_id
3031                   FROM financials_system_params_all  --<Shared Proc FPJ>
3032                  WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
3033 
3034                 l_progress := '070';
3035                 SELECT process_enabled_flag INTO x_process_org
3036                 FROM   mtl_parameters
3037                 WHERE  organization_id = x_inv_org_id;
3038            exception
3039            when others
3040            then
3041                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3042                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3043                                         p_token    => l_progress,
3044                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
3045                 END IF;
3046                x_process_org := 'N';
3047            end;
3048 
3049            IF x_opm_installed = 'I' and x_process_org = 'Y' and
3050               interface.item_id is not null
3051            THEN
3052                BEGIN
3053                     l_progress := '080';
3054                     SELECT  segment1
3055                     INTO    x_item_number
3056                     FROM    mtl_system_items
3057                     WHERE
3058                         inventory_item_id = interface.item_id
3059                         AND  organization_id   = x_inv_org_id;
3060 
3061                EXCEPTION
3062                WHEN OTHERS
3063                THEN
3064                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3065                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3066                                         p_token    => l_progress,
3067                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
3068                 END IF;
3069                    x_item_number := NULL;
3070                END;
3071 
3072                l_progress := '090';
3073 
3074                GMIGUTL.GET_ITEM(x_item_number,ic_item_mst_rec,ic_item_cpg_rec);
3075                IF ic_item_mst_rec.item_no is not null
3076                THEN
3077                    interface.preferred_grade := ic_item_mst_rec.qc_grade;
3078 
3079                    IF ic_item_mst_rec.dualum_ind >= 1
3080                    THEN
3081                        interface.secondary_unit_of_measure:= po_gml_db_common.get_apps_uom_code(ic_item_mst_rec.item_um2);
3082                        x_order_opm_um := po_gml_db_common.get_opm_uom_code(interface.unit_meas_lookup_code);
3083                        po_gml_db_common.validate_quantity(
3084                                     ic_item_mst_rec.item_id,
3085                                     ic_item_mst_rec.dualum_ind,
3086                                     x_quantity,
3087                                     x_order_opm_um,
3088                                     ic_item_mst_rec.item_um2,
3089                                     x_secondary_qty);
3090                        interface.secondary_quantity := x_secondary_qty;
3091                    ELSE
3092                        interface.secondary_quantity := null;
3093                        interface.secondary_unit_of_measure := null;
3094                    END IF; -- ic_item_mst_rec.dualum_ind >= 1
3095                ELSE
3096                    interface.secondary_quantity := null;
3097                    interface.preferred_grade    := null;
3098                    interface.secondary_unit_of_measure := null;
3099                END IF; -- ic_item_mst_rec.item_no is not null
3100              ELSE
3101                    interface.secondary_quantity := null;
3102                    interface.preferred_grade    := null;
3103                    interface.secondary_unit_of_measure := null;
3104              END IF;
3105          END IF;
3106 -- end of 2219743
3107 **/
3108 
3109    l_progress := '100';
3110 
3111    -- Bug 2735840 START
3112    -- When autocreating a PO that references a GA, and the req line and
3113    -- GA line have different UOM's, convert to the GA's UOM if the
3114    -- UOM Convert profile is Yes. If UOM Convert is No, do not create
3115    -- this line.
3116    IF (interface.from_line_id IS NOT NULL)
3117       AND (g_document_subtype = 'STANDARD') THEN
3118 
3119      l_progress := '110';
3120      BEGIN
3121 --bug#3612701 modified the sql to fetch type lookup code
3122 --of the source document as well.
3123        SELECT pol.unit_meas_lookup_code,poh.type_lookup_code
3124        INTO l_ga_uom,l_from_type_lookup_code
3125        FROM po_lines_all pol,po_headers_all poh
3126        WHERE pol.po_line_id = interface.from_line_id
3127        and poh.po_header_id=interface.from_header_id
3128        and poh.po_header_id=pol.po_header_id;
3129 --bug#3612701
3130      EXCEPTION
3131        WHEN OTHERS THEN
3132          IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3133              PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3134                                 p_progress => l_progress);
3135          END IF;
3136          po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
3137          wrapup(interface.interface_header_id);
3138          raise;
3139      END;
3140 
3141      l_progress := '120';
3142      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3143         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3144                             p_token    => l_progress,
3145                             p_message  => 'req uom: '||interface.unit_meas_lookup_code||' uom: '||l_ga_uom
3146           ||'document type: ' || l_from_type_lookup_code);
3147      END IF;
3148 
3149 
3150      IF interface.unit_meas_lookup_code <> l_ga_uom THEN
3151        l_progress := '130';
3152 --bug#3612701
3153        IF (nvl(l_uom_convert,'N') = 'Y' or l_from_type_lookup_code='QUOTATION') THEN
3154 --bug#3612701
3155          -- Convert to the GA's UOM
3156          -- Bug 3793360 : use the po_uom_convert procedure and round 15
3157          l_conversion_rate :=  po_uom_s.po_uom_convert(interface.unit_meas_lookup_code,
3158                                                        l_ga_uom,
3159                                                        interface.item_id);
3160 
3161          x_quantity := round(x_quantity * l_conversion_rate , 15);
3162          x_unit_of_measure := l_ga_uom;
3163        ELSE -- UOM Convert is No, so do not create this line.
3164          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3165              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3166                                 p_token    => l_progress,
3167                                 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.');
3168          END IF;
3169          RETURN;
3170        END IF;
3171      END IF; -- interface.unit_meas_lookup_code <> l_ga_uom
3172 
3173    END IF; -- interface.from_line_id IS NOT NULL ...
3174    -- Bug 2735840 END
3175 
3176    /* if line does not exist */
3177 
3178    IF(x_po_line_id is NULL) THEN
3179 
3180        /* If item is not null get list price and taxable flag */
3181 
3182        l_progress:='140';
3183         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3184             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3185                                 p_token    => l_progress,
3186                                 p_message  => 'Create_line: PO line does not exist');
3187         END IF;
3188 
3189 
3190         IF(interface.item_id is not null) THEN
3191 
3192           item.list_price_per_unit := interface.unit_price;
3193 
3194           l_outsourced_assembly := po_core_s.get_outsourced_assembly(interface.item_id,
3195                                                 interface.destination_organization_id);--<SHIKYU R12>
3196 
3197 
3198  /* Bug 919204 */
3199  /* made the receive close and invoice close tolerance to be picked up
3200   * from the lowest existing level by splitting the select.
3201   */
3202 /* Bug 1018048
3203    Prior to the fix we were getting the values of receipt required
3204    flag and inspection required flag of the item/master org to
3205    default in the autocreated document and were not considering the
3206    values defined at item/destination organization.
3207 
3208   Now, we derive the values from the item/destination organization
3209   and if it is not defined at the  item/destination organization
3210   level, then we derive the values from the item/master organization.
3211 */
3212 
3213           l_progress := '150';
3214           begin
3215           SELECT msi.invoice_close_tolerance,
3216                  msi.receive_close_tolerance,
3217                  msi.inspection_required_flag,
3218                  msi.receipt_required_flag
3219             INTO item.invoice_close_tolerance,
3220                  item.receive_close_tolerance,
3221                  item.inspection_required_flag,
3222                  item.receipt_required_flag
3223             FROM mtl_system_items msi
3224            WHERE msi.inventory_item_id = interface.item_id
3225              AND msi.organization_id   = interface.destination_organization_id;
3226 
3227           exception
3228                when no_data_found then
3229                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3230                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3231                                             p_token    => l_progress,
3232                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3233                     END IF;
3234                WHEN OTHERS THEN
3235                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3236                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3237                                            p_progress => l_progress);
3238                     END IF;
3239                     wrapup(x_interface_header_id);
3240                     po_message_s.sql_error('Get Item/Org defaults',l_progress,sqlcode);
3241                     raise;
3242           end;
3243 
3244          l_progress := '160';
3245 
3246          begin
3247           SELECT decode(x_order_type_lookup_code, 'QUANTITY',
3248                         msi.list_price_per_unit/nvl(interface.h_rate,1),
3249                         1), --<Shared Proc FPJ><Bug 3808903>
3250                  decode(x_order_type_lookup_code, 'QUANTITY',
3251                         msi.market_price/nvl(interface.h_rate,1),
3252                         1), --<Shared Proc FPJ><Bug 3808903>
3253                  msi.taxable_flag,
3254                  msi.primary_uom_code,
3255                  nvl(item.inspection_required_flag,msi.inspection_required_flag),
3256                  nvl(item.receipt_required_flag,msi.receipt_required_flag),
3257                  nvl(item.invoice_close_tolerance,msi.invoice_close_tolerance),
3258                  nvl(item.receive_close_tolerance,msi.receive_close_tolerance),
3259                  decode(msi.tracking_quantity_ind,
3260                         g_chktype_TRACKING_QTY_IND,
3261                         msi.secondary_uom_code,NULL),--<INVCONV R12>
3262                  nvl(msi.grade_control_flag,'N') --<INVCONV R12>
3263             INTO item.list_price_per_unit,
3264                  item.market_price,
3265                  item.taxable_flag,
3266                  item.unit_meas_lookup_code,
3267                  item.inspection_required_flag,
3268                  item.receipt_required_flag,
3269                  item.invoice_close_tolerance,
3270                  item.receive_close_tolerance,
3271                  item.secondary_uom_code, --<INVCONV R12>
3272                  item.grade_control_flag  --<INVCONV R12>
3273             FROM mtl_system_items msi
3274            WHERE msi.inventory_item_id = interface.item_id
3275              AND msi.organization_id = params.inventory_organization_id;
3276 
3277          exception
3278                when no_data_found then
3279                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3280                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3281                                             p_token    => l_progress,
3282                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3283                     END IF;
3284                WHEN OTHERS THEN
3285                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3286                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3287                                            p_progress => l_progress);
3288                     END IF;
3289                  wrapup(x_interface_header_id);
3290                  po_message_s.sql_error('Get Item/Master org defaults',l_progress,sqlcode);
3291                     raise;
3292           end;
3293       ELSE  -- added by jbalakri for bug 2348729
3294 /*  this case will reach when the item_id is null */
3295 /* Bug#2674947 We need to initialize market_price also */
3296 /* Bug#3545290 In case of One-time items i.e Item_id is NUll , the
3297                list price needed to be reinitialized.
3298 */
3299           item.market_price := '';
3300           item.taxable_flag := '';
3301           item.unit_meas_lookup_code := '';
3302           item.inspection_required_flag := '';
3303           item.receipt_required_flag := '';
3304           item.invoice_close_tolerance := '';
3305           item.receive_close_tolerance := '';
3306           item.list_price_per_unit := ''; --Bug 3545290
3307           item.secondary_uom_code := '';  --<INVCONV R12>
3308           item.grade_control_flag := '';  --<INVCONV R12>
3309       END IF; -- item id not null   Bug #2102149
3310 
3311       l_progress := '170';
3312 
3313 -- Bug: 1702702 Select receipt required flag also at line type level
3314         begin
3315                SELECT nvl(item.receive_close_tolerance,receipt_close),
3316                       nvl(item.receipt_required_flag,receiving_flag)
3317                INTO item.receive_close_tolerance,
3318                     item.receipt_required_flag
3319                FROM po_line_types_v
3320                WHERE line_type_id = interface.line_type_id;
3321           exception
3322                when no_data_found then
3323                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3324                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3325                                             p_token    => l_progress,
3326                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3327                     END IF;
3328                WHEN OTHERS THEN
3329                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3330                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3331                                            p_progress => l_progress);
3332                     END IF;
3333                     wrapup(x_interface_header_id);
3334                     po_message_s.sql_error('Get Line type default',l_progress,sqlcode);
3335                     raise;
3336           end;
3337 
3338    l_progress := '180';
3339 
3340 /*  Bug: 2106201 Select receipt required flag,inspection required flag
3341                  at vendor level before system option level to complete the
3342                  default logic
3343 */
3344   Begin
3345           select nvl(item.inspection_required_flag,
3346                                 vendor.INSPECTION_REQUIRED_FLAG),
3347                   nvl(item.receipt_required_flag,
3348                                 vendor.RECEIPT_REQUIRED_FLAG)
3349               into item.inspection_required_flag,
3350                   item.receipt_required_flag
3351               from po_vendors vendor
3352           where   vendor.vendor_id = interface.vendor_id;
3353 
3354       Exception
3355           when no_data_found then
3356                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3357                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3358                                         p_token    => l_progress,
3359                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3360                 END IF;
3361           WHEN OTHERS THEN
3362                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3363                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3364                                        p_progress => l_progress);
3365                 END IF;
3366               wrapup(x_interface_header_id);
3367               po_message_s.sql_error('Get vendor default',l_progress,sqlcode);
3368               raise;
3369       End;
3370 
3371    l_progress := '190';
3372 
3373 /* Bug: 1322342 Select receipt required flag,inspection required flag
3374                 receipt close tolerance and insp close tolerance
3375                 also from po system parameters if not defined at above level
3376 */
3377     Begin
3378         select nvl(item.inspection_required_flag,
3379                                 posp.INSPECTION_REQUIRED_FLAG),
3380                 nvl(item.receipt_required_flag,
3381                                 posp.RECEIVING_FLAG),
3382                 nvl(item.invoice_close_tolerance,
3383                                 posp.INVOICE_CLOSE_TOLERANCE),
3384                 nvl(item.receive_close_tolerance,
3385                                 posp.RECEIVE_CLOSE_TOLERANCE)
3386             into    item.inspection_required_flag,
3387                 item.receipt_required_flag,
3388                 item.invoice_close_tolerance,
3389                 item.receive_close_tolerance
3390            FROM po_system_parameters_all posp  --<Shared Proc FPJ>
3391           WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
3392 
3393     Exception
3394         when no_data_found then
3395             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3396                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3397                                     p_token    => l_progress,
3398                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3399             END IF;
3400         WHEN OTHERS THEN
3401             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3402                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3403                                    p_progress => l_progress);
3404             END IF;
3405             wrapup(x_interface_header_id);
3406             po_message_s.sql_error('Get po system default',l_progress,sqlcode);
3407             raise;
3408     End;
3409 -- Bug: 1322342 If not defined at po system option level also then
3410 
3411    l_progress := '200';
3412 
3413         IF (item.inspection_required_flag is NULL) THEN
3414             item.inspection_required_flag := 'N';
3415         END IF;
3416 
3417         IF (item.receipt_required_flag is  NULL) THEN
3418             item.receipt_required_flag := 'N';
3419         END IF;
3420         IF (item.invoice_close_tolerance is NULL) THEN
3421             item.invoice_close_tolerance := '0';
3422         END IF;
3423 
3424         IF (item.receive_close_tolerance is NULL) THEN
3425             item.receive_close_tolerance := '0';
3426         END IF;
3427 
3428        --ELSE Bug #2102149
3429 /* Bug 814174
3430    Prior to the fix, the list_price_per_unit was the same as the unit_price
3431    and not considering the rate factor.
3432    Made the changes to multiply the unit_price by the factor of rate
3433    for quantity based line types.
3434 */
3435           if (x_order_type_lookup_code = 'QUANTITY') then
3436              -- Bug 2715279. Changed interface.unit_price to item.list_price_per_unit
3437              -- on the RHS of the assignment
3438              -- Bug 3276529 change the paranthesis divide the unit price with rate
3439              -- and not the list price as it has already been divided in the select
3440 
3441       --<Shared Proc FPJ>
3442             item.list_price_per_unit := nvl(
3443               item.list_price_per_unit,
3444               (interface.unit_price / l_rate_for_req_fields) -- <ACHTML R12>
3445             );
3446 
3447           -- <SERVICES FPJ START>
3448           --
3449           ELSIF ( x_order_type_lookup_code = 'AMOUNT' ) THEN
3450 
3451               item.list_price_per_unit := 1;
3452 
3453           ELSE -- ( x_order_type_lookup_code IN ('FIXED PRICE','RATE') )
3454 
3455               item.list_price_per_unit := NULL;
3456 
3457           END IF;
3458           --
3459           -- <SERVICES FPJ END>
3460 
3461     -- Bug #2102149
3462     if (interface.item_id is null) then
3463     item.taxable_flag := '';
3464     item.unit_meas_lookup_code := '';
3465     end if;
3466       -- Bug #2102149
3467 
3468       l_progress := '210';
3469       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3470             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3471                                 p_token    => l_progress,
3472                                 p_message  => 'Create_line: line taxable_flag: '||item.taxable_flag);
3473       END IF;
3474 
3475 
3476         -- <Bug 3322948>
3477         -- Perform currency conversion on price/amount/quantity.
3478         PO_INTERFACE_S.do_currency_conversion(
3479           p_order_type_lookup_code => x_order_type_lookup_code,
3480           p_interface_source_code  => g_interface_source_code,
3481           p_rate                   => l_rate_for_req_fields, -- <ACHTML R12>
3482           p_po_currency_code       => interface.h_currency_code,
3483           p_requisition_line_id    => interface.requisition_line_id,
3484           x_quantity               => x_quantity, -- IN/OUT
3485           x_unit_price             => interface.unit_price, -- IN/OUT
3486           x_base_unit_price        => interface.base_unit_price, -- IN/OUT
3487                                    -- <Bug 3401653>
3488           x_amount                 => interface.amount -- IN/OUT
3489         );
3490 
3491 
3492        /* set neg by preparer flag */
3493        interface.negotiated_by_preparer_flag := 'N';
3494 
3495         --<SOURCING TO PO FPH >Bug# 2288408
3496         --sourcing populates the unit price in bidder's currency, so we are
3497         -- not converting the currency. And sourcing does not have
3498   --list_price_per_unit and market price storred in their system,
3499   --so dont do the following for sourcing
3500         if g_interface_source_code <>'SOURCING' then
3501            IF (item.unit_meas_lookup_code=interface.unit_meas_lookup_code) THEN
3502               IF (item.list_price_per_unit <> '') THEN
3503                  IF (item.list_price_per_unit > interface.unit_price) THEN
3504               interface.negotiated_by_preparer_flag := 'Y';
3505                  END IF;
3506               END IF;
3507            END IF;
3508         end if;
3509 
3510 
3511        l_progress:='240';
3512 
3513 
3514        /* Enhancement Request from Proj Manufacturing
3515        ** ecso 10/22/97
3516        ** Conditions:
3517        ** - new RFQ
3518        ** - only one requisition line for the interface_header_id
3519        ** Action:
3520        ** - copy project_id  task_id from first req dist to RFQ line
3521        ** Future enhancement includes:
3522        ** - spliting req lines with multiple dist
3523        ** - group req lines by project/task
3524        */
3525 
3526 /* Bug: 1526641 in order to propagate Project info we don't need the condition
3527         of req lines. It inhibits the situation when req lines are not grouped
3528         and Project info could propagate to the document being created. But
3529         certainly there is a limitation of removing this which is when there are
3530         two req lines and the first line does not have project info and the
3531         second line does then the project info does not propagate. Of course
3532         reason being we are not grouping lines on the basis of Project.
3533         But right now we are going ahead with this little enhancement.
3534 
3535        IF (g_document_type = 'RFQ') AND
3536     (nvl(g_req_lines_to_process,0) = 1)
3537        THEN
3538 */
3539 
3540        IF (g_document_type = 'RFQ') THEN
3541           l_progress := '240';
3542 
3543    BEGIN
3544      SELECT MIN(DISTRIBUTION_ID)
3545      INTO   x_req_dist_id
3546      FROM   PO_REQ_DISTRIBUTIONS_ALL  --<Shared Proc FPJ>
3547      WHERE  REQUISITION_LINE_ID = interface.requisition_line_id
3548            AND    PROJECT_ID IS NOT NULL
3549            AND    TASK_ID    IS NOT NULL;
3550    EXCEPTION
3551     WHEN NO_DATA_FOUND THEN
3552             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3553                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3554                                     p_token    => l_progress,
3555                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3556             END IF;
3557     WHEN OTHERS THEN
3558             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3559                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3560                                    p_progress => l_progress);
3561             END IF;
3562             RAISE;
3563    END;
3564 
3565       -- Bug 5363922 Start
3566       -- Selecting Only Project ID If Task ID Null
3567  	          IF x_req_dist_id IS NULL THEN
3568  	                  BEGIN
3569  	                    SELECT MIN(DISTRIBUTION_ID)
3570  	                    INTO          x_req_dist_id
3571  	                    FROM          PO_REQ_DISTRIBUTIONS_ALL  --<Shared Proc FPJ>
3572  	                    WHERE  REQUISITION_LINE_ID = interface.requisition_line_id
3573  	                    AND    PROJECT_ID IS NOT NULL;
3574  	                  EXCEPTION
3575  	                   WHEN OTHERS THEN
3576  	                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3577  	                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3578  	                                            p_progress => l_progress);
3579  	                     END IF;
3580  	                     RAISE;
3581  	                  END;
3582 
3583  	          END IF;
3584   -- End Bug 5363922
3585 
3586      l_progress := '250';
3587    BEGIN
3588     SELECT project_id
3589      ,task_id
3590     INTO   x_project_id
3591      , x_task_id
3592     FROM   PO_REQ_DISTRIBUTIONS_ALL  --<Shared Proc FPJ>
3593     WHERE  DISTRIBUTION_ID = x_req_dist_id;
3594   EXCEPTION
3595     WHEN NO_DATA_FOUND THEN
3596             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3597                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3598                                     p_token    => l_progress,
3599                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3600             END IF;
3601     WHEN OTHERS THEN
3602             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3603                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3604                                    p_progress => l_progress);
3605             END IF;
3606             RAISE;
3607    END;
3608 
3609        ELSE
3610 
3611    x_project_id := NULL;
3612    x_task_id := NULL;
3613 
3614        END IF;
3615 
3616       l_progress := '260';
3617 
3618        --<SOURCING TO PO FPH START>
3619        --default un_number_id,hazard_class_id from item attributes when
3620        --not backed by a req. Also default UOM for amount based lines for this
3621        --condition.
3622        If g_interface_source_code in ('SOURCING','CONSUMPTION_ADVICE') then -- CONSIGNED FPI
3623     if interface.requisition_line_id is null then
3624        begin
3625               l_progress:='270';
3626               select un_number_id,hazard_class_id
3627           into x_un_number_id,x_hazard_class_id
3628           from mtl_system_items
3629                where inventory_item_id = interface.item_id
3630            and organization_id   =params.inventory_organization_id;
3631               exception
3632          when no_data_found then
3633                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3634                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3635                                             p_token    => l_progress,
3636                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
3637                     END IF;
3638                when others then
3639                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3640                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3641                                            p_progress => l_progress);
3642                     END IF;
3643                     po_message_s.sql_error('Get un number,hazard class defaults'
3644           ,l_progress, sqlcode);
3645               raise;
3646        end;
3647 
3648        if x_order_type_lookup_code='AMOUNT' then
3649                 begin
3650                 l_progress:='280';
3651     select unit_of_measure
3652       into x_unit_of_measure
3653       from po_line_types
3654      where line_type_id= interface.line_type_id;
3655     exception
3656                  when others then
3657                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
3658                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
3659                                            p_progress => l_progress);
3660                     END IF;
3661                   po_message_s.sql_error('Get UOM for amount based lines- defaults', l_progress, sqlcode);
3662             raise;
3663           end;
3664        else
3665                 x_unit_of_measure :=interface.unit_meas_lookup_code;
3666        end if;
3667           else
3668              x_un_number_id := interface.un_number_id;
3669              x_hazard_class_id := interface.hazard_class_id;
3670              x_unit_of_measure :=interface.unit_meas_lookup_code;
3671           end if;
3672        end if;
3673        --<SOURCING TO PO FPH END>
3674 
3675        l_progress := '290';
3676 
3677        IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED' or
3678           --<SOURCING TO PO FPH>
3679     --insert Blankets also
3680           g_document_subtype='BLANKET' or
3681     g_document_type = 'RFQ') THEN
3682 
3683 
3684 
3685          l_progress:='330';
3686 
3687          SELECT po_lines_s.nextval
3688            INTO x_po_line_id
3689            FROM sys.dual;
3690 
3691          l_progress:='340';
3692 
3693          /* GA FPI start */
3694 
3695         -- <SERVICES FPJ>
3696         --
3697         -- Call the Pricing API only when...
3698         --
3699         --    1) Autocreating a Standard PO
3700         --    2) Source Document exists
3701         --    3) Not a Consumption Advice
3702         --    4) Requisition Line's Contractor Status is not 'ASSIGNED'
3703         --       ( if the contractor status is 'ASSIGNED',
3704         --         then we take the price directly from the Requisition Line )
3705         --
3706         --    5) Not a complex work PO  <Complex Work R12>
3707         l_contractor_status := PO_SERVICES_PVT.get_contractor_status(interface.requisition_line_id);  --<Bug 3353109>
3708         IF  (   ( g_document_subtype = 'STANDARD' )
3709             AND ( interface.from_line_id IS NOT NULL OR
3710                   -- <FPJ Advanced Price START>
3711                   interface.contract_id IS NOT NULL)
3712                   -- <FPJ Advanced Price END>
3713             AND ( g_interface_source_code <> 'CONSUMPTION_ADVICE' )
3714             AND (NOT p_is_complex_work_po) -- <Complex Work R12>
3715             AND ( l_contractor_status IS NULL OR l_contractor_status <> 'ASSIGNED' ) ) -- <BUG 3281227>  --<Bug 3353109>
3716         THEN
3717 
3718             l_progress := '350';
3719             -- <SERVICES FPJ START>
3720             --
3721             PO_SOURCING2_SV.get_break_price
3722             (  p_api_version    => 1.0
3723             ,  p_order_quantity   => x_quantity
3724             ,  p_ship_to_org    => interface.destination_organization_id
3725             ,  p_ship_to_loc    => get_ship_to_loc(interface.deliver_to_location_id)
3726             ,  p_po_line_id   => interface.from_line_id
3727             ,  p_cum_flag   => FALSE
3728             ,  p_need_by_date   => interface.need_by_date
3729             ,  p_line_location_id => NULL
3730             -- <FPJ Advanced Price START>
3731             ,  p_contract_id    => interface.contract_id
3732             ,  p_org_id     => g_purchasing_ou_id
3733             ,  p_supplier_id    => interface.vendor_id
3734             ,  p_supplier_site_id => interface.vendor_site_id
3735             ,  p_creation_date    => interface.creation_date
3736             ,  p_order_header_id  => interface.po_header_id
3737             ,  p_order_line_id    => x_po_line_id
3738             ,  p_line_type_id   => interface.line_type_id
3739             ,  p_item_revision    => interface.item_revision
3740             ,  p_item_id    => interface.item_id
3741             ,  p_category_id    => interface.category_id
3742             ,  p_supplier_item_num  => interface.vendor_product_num
3743             -- Bug 3343892, pass base_unit_price
3744             -- Bug 3417479, Only pass base_unit_price
3745             -- ,  p_in_price    => NVL(interface.base_unit_price, interface.unit_price)
3746             ,  p_in_price   => interface.base_unit_price
3747             ,  p_uom      => x_unit_of_measure
3748             ,  p_currency_code          => interface.h_currency_code  -- Bug 3564863
3749             ,  x_base_unit_price  => l_base_unit_price
3750             -- <FPJ Advanced Price END>
3751             ,  x_price_break_id   => l_price_break_id
3752             ,  x_price      => x_unit_price
3753             ,  x_return_status    => l_return_status
3754             ,  p_req_line_price => interface.unit_price   -- Bug 7154646
3755             );
3756             -- <SERVICES FPJ END>
3757 
3758       -- Bug 3733202 START
3759       -- Treat 0 price as null price
3760       IF (x_unit_price = 0) THEN
3761         x_unit_price := NULL;
3762       END IF;
3763       -- Bug 3733202 END
3764 
3765             -- Bug 3417479
3766             x_unit_price := nvl(x_unit_price, interface.unit_price);
3767             l_base_unit_price := nvl(l_base_unit_price, interface.base_unit_price);
3768 
3769         ELSE
3770 
3771             x_unit_price := interface.unit_price;
3772             -- <FPJ Advanced Price START>
3773             -- Bug 3417479
3774             -- l_base_unit_price := nvl(interface.base_unit_price, x_unit_price);
3775             l_base_unit_price := interface.base_unit_price;
3776             -- <FPJ Advanced Price END>
3777 
3778         END IF;
3779 
3780          /* GA FPI end */
3781         l_progress := '360';
3782 
3783         -- <SERVICES FPJ START> If we are Autocreating a Standard PO,
3784         -- then setup the Interface tables to copy over Price Differentials.
3785         --<Bug 3268483>
3786         -- This functionality is not supported from Sourcing. One cannot
3787         -- create a Standard PO from Sourcing with Temp Labor lines (with price
3788         -- differentials).
3789         IF ( g_document_subtype = 'STANDARD' AND
3790              --<Bug 3268483>
3791              g_interface_source_code not in  ('SOURCING', 'CONSUMPTION_ADVICE')
3792            AND (NOT p_is_complex_work_po)) -- <Complex Work R12>
3793         THEN
3794 
3795             PO_PRICE_DIFFERENTIALS_PVT.setup_interface_table
3796             (   p_entity_type         => 'PO LINE'
3797             ,   p_interface_header_id => interface.interface_header_id
3798             ,   p_interface_line_id   => interface.interface_line_id
3799             ,   p_req_line_id         => interface.requisition_line_id
3800             ,   p_from_line_id        => interface.from_line_id
3801             ,   p_price_break_id      => l_price_break_id
3802             );
3803         END IF;
3804         --
3805         -- <SERVICES FPJ END>
3806 
3807         l_progress := '370';
3808         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3809             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3810                                 p_token    => l_progress,
3811                                 p_message  => 'Create_line: Line id: '||x_po_line_id);
3812             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3813                                 p_token    => l_progress,
3814                                 p_message  => 'Create_line: Header_id : '||interface.po_header_id);
3815             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3816                                 p_token    => l_progress,
3817                                 p_message  => 'Create_line: Line number: '||interface.line_num);
3818             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3819                                 p_token    => l_progress,
3820                                 p_message  => 'Create_line: TRX RSON CODE : '||interface.transaction_reason_code);
3821         END IF;
3822 
3823         l_progress := '380';
3824          -- <SERVICES FPJ START>
3825          -- Retrieve the values for order_type_lookup_code, purchase_basis
3826          -- and matching_basis
3827          PO_LINE_TYPES_SV.get_line_type_def(
3828                           interface.line_type_id,
3829                           l_order_type_lookup_code,
3830                           l_purchase_basis1,
3831                           l_matching_basis,
3832                           l_category_id,
3833                           l_unit_meas_lookup_code,
3834                           l_unit_price,
3835                           l_outside_operation_flag,
3836                           l_receiving_flag,
3837                           l_receive_close_tolerance);
3838          -- <SERVICES FPJ END>
3839 
3840    -- Bug 694504. frkhan 07/07/98. Removed decode for vendor_product_num
3841    -- so it is inserted for RFQs also.
3842 
3843 --<DBI FPJ Start>
3844 BEGIN
3845   IF g_interface_source_code='SOURCING' THEN
3846     l_negotiated_by_preparer_flag := 'Y';
3847   ELSIF interface.from_header_id is not null THEN
3848     l_progress := '390';
3849     SELECT type_lookup_code,global_agreement_flag into l_type_lookup_code,l_global_agreement_flag
3850     FROM po_headers_all
3851     WHERE po_header_id=interface.from_header_id;
3852     -- if the source document is global agreement.
3853     IF l_type_lookup_code='BLANKET' and l_global_agreement_flag='Y' THEN
3854       l_progress := '395';
3855       SELECT negotiated_by_preparer_flag into l_negotiated_by_preparer_flag
3856       FROM po_lines_all
3857       WHERE po_line_id=interface.from_line_id;
3858     --if the source document is quotation.
3859     ELSIF l_type_lookup_code='QUOTATION' THEN
3860       l_negotiated_by_preparer_flag := 'Y';
3861     -- if the source document is contract or otherwise
3862     -- <Bug 5177657> Changed ELSIF to ELSE
3863     ELSE
3864       l_progress := '400';
3865       SELECT negotiated_by_preparer_flag into l_negotiated_by_preparer_flag
3866       FROM po_requisition_lines_all
3867       WHERE requisition_line_id=interface.requisition_line_id;
3868     END IF;
3869   ELSE
3870     l_progress := '410';
3871     SELECT negotiated_by_preparer_flag into l_negotiated_by_preparer_flag
3872     FROM po_requisition_lines_all
3873     WHERE requisition_line_id=interface.requisition_line_id;
3874   END IF;
3875 EXCEPTION
3876   WHEN others THEN
3877     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
3878         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
3879                             p_token    => l_progress,
3880                             p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
3881     END IF;
3882     l_negotiated_by_preparer_flag:=NULL;
3883 END;
3884 -- <DBI FPJ End>
3885 
3886         l_progress := '420';
3887 
3888   --<INVCONV R12 START>
3889   -- IF secondary quantity is null and item is dual uom control , default the secondary qty.
3890   IF (g_document_subtype='STANDARD' OR g_document_subtype='PLANNED' OR g_document_type = 'PA')
3891   THEN
3892     IF interface.item_id is not null THEN
3893        IF item.secondary_uom_code IS NOT NULL THEN
3894           IF (interface.secondary_quantity IS NULL OR
3895               params.inventory_organization_id <> interface.destination_organization_id )
3896           THEN
3897              PO_UOM_S.get_secondary_uom( interface.item_id,
3898                                          interface.destination_organization_id,
3899                                          x_secondary_uom,
3900                                          x_secondary_unit_def);
3901 
3902              IF g_document_type <> 'PA' THEN
3903                 PO_UOM_S.uom_convert (x_quantity, x_unit_of_measure, interface.item_id,
3904                                       x_secondary_unit_def, x_secondary_quantity_def) ;
3905 
3906                 IF interface.destination_organization_id  = params.inventory_organization_id
3907                 THEN
3908                   interface.secondary_unit_of_measure := x_secondary_unit_def ;
3909                   interface.secondary_quantity := x_secondary_quantity_def ;
3910                 END IF;
3911              ELSE
3912                 x_secondary_quantity_def := null ;
3913              END IF;
3914           ELSE
3915              x_secondary_unit_def := interface.secondary_unit_of_measure;
3916              x_secondary_quantity_def := interface.secondary_quantity;
3917           END IF;
3918        ELSE -- IF item.secondary_uom_code IS NOT NULL
3919           x_secondary_unit_def := null;
3920           x_secondary_quantity_def := null ;
3921        END IF;
3922 
3923        IF item.grade_control_flag = 'N' and interface.preferred_grade IS NOT NULL THEN
3924           x_preferred_grade_def := null ;
3925        ELSE
3926           x_preferred_grade_def := interface.preferred_grade ;
3927        END IF;
3928 
3929     ELSE -- IF interface.item_id is not null
3930        x_secondary_unit_def := null;
3931        x_secondary_quantity_def := null ;
3932        x_preferred_grade_def    := null;
3933     END IF;
3934   ELSE
3935     x_secondary_unit_def := null;
3936     x_secondary_quantity_def := null ;
3937     x_preferred_grade_def    := null;
3938   END IF;
3939   --<INVCONV R12 END>
3940 
3941 -- bug 4887900 START
3942 -- checking if the user has manually entered a value
3943 -- bug#5255878
3944 -- declared l_retainage_rate
3945 -- bug#5262303 interface.vendor_site_id can be null
3946 -- if the vendor/vendor_site combination is not provided
3947 -- on the autocreate window. We should query only when
3948 -- vendor_site_id is not null.
3949     IF(interface.vendor_site_id is not null)THEN
3950         SELECT retainage_rate
3951         into l_retainage_rate
3952         FROM po_vendor_sites_all
3953         WHERE vendor_site_id = interface.vendor_site_id;
3954     END IF;
3955 -- bug 4887900 END
3956 
3957      -- Added note_to_vendor - iali 08/26/99
3958 /*Bug 1391523 . Added market price to the INSERT statement */
3959         INSERT INTO po_lines_all  --<Shared Proc FPJ>
3960         (    po_line_id,
3961              last_update_date,
3962              last_updated_by,
3963              po_header_id,
3964              line_num,
3965              creation_date,
3966              created_by,
3967              last_update_login,
3968              item_id,
3969              job_id,                                          -- <SERVICES FPJ>
3970              category_id,
3971              item_description,
3972              unit_meas_lookup_code,
3973              list_price_per_unit,
3974              market_price,
3975              base_unit_price,             -- <FPJ Advanced Price>
3976              unit_price,
3977              quantity,
3978              amount,                                          -- <SERVICES FPJ>
3979              taxable_flag,
3980              type_1099,
3981              negotiated_by_preparer_flag,
3982              closed_code,
3983              item_revision,
3984              un_number_id,
3985              hazard_class_id,
3986              -- contract_num,   -- <GC FPJ>
3987              contract_id,        -- <GC FPJ>
3988              line_type_id,
3989              vendor_product_num,
3990              qty_rcv_tolerance,
3991              over_tolerance_error_flag,
3992              firm_status_lookup_code,
3993              min_release_amount,
3994              price_type_lookup_code,
3995              transaction_reason_code,
3996              from_header_id,
3997              from_line_id,
3998              from_line_location_id,                           -- <SERVICES FPJ>
3999              project_id,
4000              task_id,
4001              note_to_vendor,
4002              --togeorge 09/27/2000
4003              --added oke columns
4004              oke_contract_header_id,
4005              oke_contract_version_id,
4006              --togeorge 11/17/2000
4007              --Bug# 1369049
4008              --Added logic to default tax_name in po_lines
4009              tax_name,
4010              -- start of 1548597
4011              secondary_unit_of_measure,
4012              secondary_quantity,
4013              preferred_grade,
4014              -- end of  1548597
4015              --<SOURCING TO PO FPH START>
4016              auction_header_id,
4017              auction_line_number,
4018              auction_display_number,
4019              bid_number,
4020              bid_line_number,
4021              quantity_committed,    --Bug# 2288408
4022              committed_amount,    --Bug# 2288408
4023              --<SOURCING TO PO FPH END>
4024              --Bug #2715037
4025              price_break_lookup_code,
4026              supplier_ref_number, --<CONFIG_ID FPJ>
4027              org_id,  --<Shared Proc FPJ>
4028              start_date,                                      -- <SERVICES FPJ>
4029              expiration_date,                                 -- <SERVICES FPJ>
4030              contractor_first_name,                           -- <SERVICES FPJ>
4031              contractor_last_name,                            -- <SERVICES FPJ>
4032              order_type_lookup_code,                          -- <SERVICES FPJ>
4033              purchase_basis,                                  -- <SERVICES FPJ>
4034              matching_basis                                   -- <SERVICES FPJ>
4035              -- <Complex Work R12 Start>
4036            , retainage_rate
4037            , max_retainage_amount
4038            , progress_payment_rate
4039            , recoupment_rate             -- <Complex Work R12 End>
4040      ,tax_attribute_update_code --<eTax Integration R12>
4041             , ip_category_id      --Bug#4656615
4042             , supplier_part_auxid --Bug#4656615
4043             , catalog_name        --Bug#4656615
4044 
4045       )
4046     VALUES (x_po_line_id,
4047                         interface.last_update_date,
4048                         interface.last_updated_by,
4049                         interface.po_header_id,
4050                         interface.line_num,
4051                         interface.creation_date,
4052                         interface.created_by,
4053                         interface.last_update_login,
4054                         interface.item_id,
4055                         interface.job_id,                     -- <SERVICES FPJ>
4056                         interface.category_id,
4057                         interface.item_description,
4058                         x_unit_of_measure, -- Bug 2735840
4059         --<SOURCING TO PO FPH >Bug# 2288408
4060         --sourcing populates the unit price in bidder's currency, so we are
4061         -- not converting the currency. And sourcing does not have
4062   --list_price_per_unit and market price stored in their system,
4063   --so dont do the following for sourcing
4064    -- Bug 3472140: Changed precisions to 15 from 5
4065    -- Bug 3808903: Changed rounding to use extended_precision
4066                         decode(g_document_type, 'RFQ', null,
4067       decode(g_interface_source_code,'SOURCING',null,
4068                              ROUND(item.list_price_per_unit,nvl(x_ext_precision,15)))),
4069     decode(g_interface_source_code,'SOURCING',null,
4070                              ROUND(item.market_price,nvl(x_ext_precision,15))),
4071     --
4072 -- Bug 1353736   use precision in rounding
4073 /* Bug: 2000367  When there is no currency conversion involved we should not
4074                  round at all because it gives rise to inconsistency.
4075                  So removing the ext precision and blind rounding to 5 also as
4076                  this is already done above in case when currency conversion is
4077                  involved.
4078 */
4079                         l_base_unit_price  , --interface.base_unit_price, -- <FPJ Advanced Price>
4080                         x_unit_price  , --interface.unit_price,
4081                         --<SOURCING TO PO FPH>
4082       --quantity sould be null for a blanket
4083                         decode(g_document_type, 'RFQ', 1,'PA',null, x_quantity),
4084                         interface.amount,                     -- <SERVICES FPJ>
4085                         nvl(item.taxable_flag,params.taxable_flag),
4086                         decode(g_document_type, 'RFQ', null,
4087         vendor.type_1099),
4088                         l_negotiated_by_preparer_flag, --<DBI FPJ>
4089                         interface.l_closed_code,
4090                         interface.item_revision,
4091                         --<SOURCING TO PO FPH START>
4092                         decode(g_interface_source_code,'SOURCING',
4093                                x_un_number_id,interface.un_number_id),
4094                         decode(g_interface_source_code,'SOURCING',
4095              x_hazard_class_id,interface.hazard_class_id),
4096                         --<SOURCING TO PO FPH END>
4097                         -- interface.contract_num,  -- <GC FPJ>
4098                         interface.contract_id,       -- <GC FPJ>
4099                         interface.line_type_id,
4100                         interface.vendor_product_num,
4101                         decode(g_document_type, 'RFQ', null,
4102         rc.qty_rcv_tolerance),
4103                         decode(g_document_type, 'RFQ', null,
4104         rc.qty_rcv_exception_code),
4105                         interface.l_firm_status_lookup_code,
4106                         interface.l_min_release_amount,
4107                         interface.price_type_lookup_code,
4108                         interface.transaction_reason_code,
4109                         nvl(interface.from_header_id,x_quote_header_id),
4110                         nvl(interface.from_line_id,x_quote_line_id),
4111                         l_price_break_id,                       -- <BUG 3282527>
4112       x_project_id,
4113       x_task_id,
4114                         --<SOURCING TO PO FPH>
4115       --dont copy note to vendor for sourcing this
4116       --would come as attachments from sourcing.
4117       decode(g_interface_source_code,'SOURCING',
4118           null,interface.note_to_vendor),
4119       --interface.note_to_vendor,
4120       --
4121             --togeorge 09/27/2000
4122             --added oke columns
4123             interface.oke_contract_header_id,
4124             interface.oke_contract_version_id,
4125             --togeorge 11/17/2000
4126             --Bug# 1369049
4127             --Added logic to default tax_name in po_lines
4128       x_tax_name,
4129 --<INVCONV R12 START>
4130 -- don't insert secondary unit/quantity/grade from interface record.
4131 -- start of 1548597
4132       x_secondary_unit_def,
4133       x_secondary_quantity_def,
4134       x_preferred_grade_def,
4135 -- end of  1548597
4136 --<INVCONV R12 END>
4137                         --<SOURCING TO PO FPH START>
4138                   interface.auction_header_id,
4139                   interface.auction_line_number,
4140             interface.auction_display_number,
4141                   interface.bid_number,
4142                   interface.bid_line_number,
4143                     decode ( g_document_type
4144                            , 'PA' , decode ( x_order_type_lookup_code
4145                                            , 'AMOUNT' , NULL
4146                                            , interface.quantity
4147                                            )
4148                            , NULL
4149                            ),
4150                     decode ( g_document_type
4151                            , 'PA' , decode ( x_order_type_lookup_code
4152                                            , 'QUANTITY' , NULL-- <SERVICES FPJ>
4153                                            , interface.committed_amount
4154                                            )
4155                            , NULL
4156                            ),
4157                         --<SOURCING TO PO FPH END>
4158                         --Bug #2715037
4159                         decode(g_interface_source_code,'SOURCING',
4160                               interface.price_break_lookup_code, null),
4161                         interface.supplier_ref_number, --<CONFIG_ID FPJ>
4162                         g_purchasing_ou_id,  --<Shared Proc FPJ>
4163                         interface.line_effective_date,        -- <SERVICES FPJ>
4164                         interface.line_expiration_date,       -- <SERVICES FPJ>
4165                         interface.contractor_first_name,      -- <SERVICES FPJ>
4166                         interface.contractor_last_name,       -- <SERVICES FPJ>
4167                         l_order_type_lookup_code,             -- <SERVICES FPJ>
4168                         l_purchase_basis1,                    -- <SERVICES FPJ>
4169                         l_matching_basis                      -- <SERVICES FPJ>
4170                         -- <Complex Work R12 Start>
4171                       , nvl(interface.retainage_rate, l_retainage_rate) -- bug 4887900 bug#5255878
4172                       , interface.max_retainage_amount
4173                       , interface.progress_payment_rate
4174                       , interface.recoupment_rate                 -- <Complex Work R12 End>
4175           ,nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax Integration R12>
4176             , interface.ip_category_id      --Bug#4656615
4177             , interface.supplier_part_auxid --Bug#4656615
4178             , interface.catalog_name        --Bug#4656615
4179       );
4180 
4181         l_progress := '430';
4182 
4183         -- <Unified Catalog R12 START>
4184         IF (g_document_subtype = 'BLANKET'  AND g_interface_source_code = 'SOURCING') THEN
4185 
4186           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;
4187 
4188           l_interface_header_id_tbl(x_po_line_id) := interface.interface_header_id;
4189           l_interface_line_id_tbl(x_po_line_id) := interface.interface_line_id;
4190           l_po_line_id_tbl(x_po_line_id) := x_po_line_id;
4191         END IF;
4192         -- <Unified Catalog R12 END>
4193 
4194 
4195         -- <SERVICES FPJ START> Insert Price Differentials into main table
4196         -- from the interface table.
4197         --
4198         PO_PRICE_DIFFERENTIALS_PVT.create_from_interface
4199         (   p_entity_id         => x_po_line_id
4200         ,   p_interface_line_id => interface.interface_line_id
4201         );
4202         -- <SERVICES FPJ END>
4203 
4204         l_progress := '440';
4205 
4206 /* Bug 2962568 globalization procedure shouldn't be called for Standard RFQ's
4207    as it is not significant for the same.
4208 */
4209             if g_document_type = 'RFQ' then
4210                null;
4211             elsif (interface.document_subtype = 'STANDARD' or
4212                 interface.document_subtype = 'PLANNED'  or
4213                 --<SOURCING TO PO FPH START>
4214                 interface.document_subtype = 'BLANKET'
4215     ) THEN
4216 
4217                 -- Bug 882050: Line level global attribute
4218 
4219                 calculate_local('PO', 'LINE', x_po_line_id);
4220 
4221             end if;
4222 
4223          END IF;
4224 
4225    ELSE /* If line exists */
4226 
4227         l_progress := '450';
4228         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4229             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4230                                 p_token    => l_progress,
4231                                 p_message  => 'Line does exist: '||x_po_line_id);
4232         END IF;
4233 
4234       --<SOURCING TO PO FPH START>
4235       --lines are grouped, so dont copy any attachments from sourcing(copy only
4236       --from the req)
4237       IF g_interface_source_code='SOURCING' then
4238          x_attch_suppress_flag  :='Y';
4239       END IF;
4240       --<SOURCING TO PO FPH END>
4241 
4242       IF(interface.item_id is not null) THEN
4243 
4244    /*
4245     * bug 1009734 : extention of bug 919204
4246     * made the receive close and invoice close tolerance to be picked up
4247     * from the lowest existing level by splitting the select.
4248     * HAD TO DO THE SAME EVEN IF PO LINE ID IS NOT NULL
4249     * ONLY FOR INVOICE CLOSE TOLERANCE AND RECEIVE CLOSE TOLERANCE
4250     */
4251 
4252       l_progress := '460';
4253 /* Bug# 1702702 - RSHAHI:  Start fix
4254     ** Need to do the same even if po line id is not null
4255     ** for receipt_required_flag and inspection_required_flag too
4256 */
4257          begin
4258           SELECT msi.invoice_close_tolerance,
4259                  msi.receive_close_tolerance,
4260                  msi.receipt_required_flag,
4261                  msi.inspection_required_flag
4262             INTO item.invoice_close_tolerance,
4263                  item.receive_close_tolerance,
4264                  item.receipt_required_flag,
4265                  item.inspection_required_flag
4266             FROM mtl_system_items msi
4267            WHERE msi.inventory_item_id = interface.item_id
4268              AND msi.organization_id   = interface.destination_organization_id;
4269 
4270           exception
4271                when no_data_found then
4272                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4273                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4274                                             p_token    => l_progress,
4275                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4276                     END IF;
4277                WHEN OTHERS THEN
4278                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4279                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4280                                            p_progress => l_progress);
4281                     END IF;
4282                     wrapup(x_interface_header_id);
4283                     po_message_s.sql_error('Get Item/Org defaults',l_progress,sqlcode);
4284                     raise;
4285           end;
4286       l_progress := '470';
4287 -- Bug: 1702702
4288          begin
4289           SELECT nvl(item.invoice_close_tolerance,msi.invoice_close_tolerance),
4290                  nvl(item.receive_close_tolerance,msi.receive_close_tolerance),
4291                  nvl(item.receipt_required_flag,msi.receipt_required_flag),
4292                  nvl(item.inspection_required_flag,msi.inspection_required_flag),
4293                  decode(msi.tracking_quantity_ind,
4294                         g_chktype_TRACKING_QTY_IND,
4295                         msi.secondary_uom_code,NULL) --<INVCONV R12>
4296             INTO item.invoice_close_tolerance,
4297                  item.receive_close_tolerance,
4298                  item.receipt_required_flag,
4299                  item.inspection_required_flag,
4300                  item.secondary_uom_code --<INVCONV R12>
4301             FROM mtl_system_items msi
4302            WHERE msi.inventory_item_id = interface.item_id
4303              AND msi.organization_id = params.inventory_organization_id;
4304           exception
4305                when no_data_found then
4306                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4307                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4308                                             p_token    => l_progress,
4309                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4310                     END IF;
4311                WHEN OTHERS THEN
4312                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4313                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4314                                            p_progress => l_progress);
4315                     END IF;
4316                     wrapup(x_interface_header_id);
4317                     po_message_s.sql_error('Get Item/Master org defaults',l_progress,sqlcode);
4318                     raise;
4319           end;
4320       ELSE  -- added by jbalakri for bug 2348729
4321 
4322 /* This case will reach when the item_id is null */
4323 /* Bug#2674947 We need to initialize market_price also */
4324           item.market_price := '';
4325           item.invoice_close_tolerance := '';
4326           item.receive_close_tolerance := '';
4327           item.inspection_required_flag := '';
4328           item.receipt_required_flag := '';
4329           item.secondary_uom_code := ''; --<INVCONV R12>
4330 
4331       END IF; -- item id is not null Bug #2102149
4332       l_progress := '480';
4333 -- Bug: 1702702
4334           begin
4335                SELECT nvl(item.receive_close_tolerance,receipt_close),
4336                       nvl(item.receipt_required_flag,receiving_flag)
4337                INTO item.receive_close_tolerance,
4338                     item.receipt_required_flag
4339                FROM po_line_types_v
4340                WHERE line_type_id = interface.line_type_id;
4341           exception
4342                when no_data_found then
4343                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4344                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4345                                             p_token    => l_progress,
4346                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4347                     END IF;
4348                WHEN OTHERS THEN
4349                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4350                         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4351                                            p_progress => l_progress);
4352                     END IF;
4353                     wrapup(x_interface_header_id);
4354                     po_message_s.sql_error('Get Line type default',l_progress,sqlcode);
4355                     raise;
4356           end;
4357 
4358       l_progress := '490';
4359 
4360 /*  Bug: 2106201 Select receipt required flag,inspection required flag
4361                  at vendor level before system option level to complete the
4362                  default logic
4363 */
4364   Begin
4365           select nvl(item.inspection_required_flag,
4366                                 vendor.INSPECTION_REQUIRED_FLAG),
4367                   nvl(item.receipt_required_flag,
4368                                 vendor.RECEIPT_REQUIRED_FLAG)
4369               into item.inspection_required_flag,
4370                   item.receipt_required_flag
4371               from po_vendors vendor
4372           where   vendor.vendor_id = interface.vendor_id;
4373 
4374       Exception
4375           when no_data_found then
4376                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4377                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4378                                         p_token    => l_progress,
4379                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4380                 END IF;
4381           WHEN OTHERS THEN
4382                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4383                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4384                                        p_progress => l_progress);
4385                 END IF;
4386               wrapup(x_interface_header_id);
4387               po_message_s.sql_error('Get vendor default',l_progress,sqlcode);
4388               raise;
4389       End;
4390 
4391       l_progress := '500';
4392 
4393 /* Bug: 1322342 Select receipt required flag,inspection required flag
4394                 receipt close tolerance and insp close tolerance
4395                 also from po system parameters if not defined at above level
4396 */
4397     Begin
4398         select nvl(item.inspection_required_flag,
4399                                 posp.INSPECTION_REQUIRED_FLAG),
4400                 nvl(item.receipt_required_flag,
4401                                 posp.RECEIVING_FLAG),
4402                 nvl(item.invoice_close_tolerance,
4403                                 posp.INVOICE_CLOSE_TOLERANCE),
4404                 nvl(item.receive_close_tolerance,
4405                                 posp.RECEIVE_CLOSE_TOLERANCE)
4406             into    item.inspection_required_flag,
4407                 item.receipt_required_flag,
4408                 item.invoice_close_tolerance,
4409                 item.receive_close_tolerance
4410            FROM po_system_parameters_all posp  --<Shared Proc FPJ>
4411           WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
4412 
4413     Exception
4414         when no_data_found then
4415             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4416                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4417                                     p_token    => l_progress,
4418                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
4419             END IF;
4420         WHEN OTHERS THEN
4421             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
4422                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
4423                                    p_progress => l_progress);
4424             END IF;
4425             wrapup(x_interface_header_id);
4426             po_message_s.sql_error('Get po system default',l_progress,sqlcode);
4427             raise;
4428     End;
4429 
4430       l_progress := '510';
4431 -- Bug: 1322342 If not defined at po system option level also then
4432 
4433         IF (item.inspection_required_flag is NULL) THEN
4434             item.inspection_required_flag := 'N';
4435         END IF;
4436 
4437         IF (item.receipt_required_flag is  NULL) THEN
4438             item.receipt_required_flag := 'N';
4439         END IF;
4440         IF (item.invoice_close_tolerance is NULL) THEN
4441             item.invoice_close_tolerance := '0';
4442         END IF;
4443 
4444         IF (item.receive_close_tolerance is NULL) THEN
4445             item.receive_close_tolerance := '0';
4446         END IF;
4447 
4448        --ELSE Bug #2102149
4449   /* Bug #2102149
4450     item.invoice_close_tolerance := '';
4451     item.receive_close_tolerance := '';
4452 -- Bug: 1702702
4453           item.inspection_required_flag := '';
4454           item.receipt_required_flag := '';
4455 
4456        END IF;
4457        */
4458 
4459 -- Bug: End fix 1702702
4460 
4461       IF (g_document_type = 'PO') THEN
4462 
4463          l_progress:='520';
4464         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4465             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4466                                 p_token    => l_progress,
4467                                 p_message  => 'Create_line: Po line exists');
4468         END IF;
4469 
4470         -- <BUG 3322948> Perform currency conversion on price/amount/quantity.
4471         --
4472         PO_INTERFACE_S.do_currency_conversion(
4473           p_order_type_lookup_code => x_order_type_lookup_code,
4474           p_interface_source_code  => g_interface_source_code,
4475           p_rate                   => l_rate_for_req_fields, -- <ACHTML R12>
4476           p_po_currency_code       => interface.h_currency_code,
4477           p_requisition_line_id    => interface.requisition_line_id,
4478           x_quantity               => x_quantity, -- IN/OUT
4479           x_unit_price             => interface.unit_price, -- IN/OUT
4480           x_base_unit_price        => interface.base_unit_price, -- IN/OUT
4481                                                                  -- <Bug 3401653>
4482           x_amount                 => interface.amount -- IN/OUT
4483         );
4484 
4485       l_progress := '530';
4486 
4487          /* handled the null value for quantity in the following update statement.
4488             bug 935866 */
4489          -- update secondary quantity to somevalue only if old or new secondary_quantity is not null else update it
4490          -- to null(for discrete items) - 1548597
4491 
4492          /* GA FPI start : For a standard PO if the source document exists then we call the pricing
4493             API to get the correct price for the parameters on the requisition */
4494 
4495          IF (g_document_subtype='STANDARD')
4496             AND nvl(l_manual_price_change_flag, 'N') <> 'Y' --bug 3495772
4497             AND (interface.from_line_id IS NOT NULL OR
4498                  -- <FPJ Advanced Price START>
4499                  interface.contract_id IS NOT NULL)
4500                  -- <FPJ Advanced Price END>
4501             AND  g_interface_source_code <> 'CONSUMPTION_ADVICE'  THEN
4502             /*bug#2723479 In this case, we will be updating an existing po
4503              *line by adding a req line to it. So we use the combined quantity
4504              *(existing po qty + req qty) when calling the pricing API. */
4505             l_progress := '540';
4506       begin
4507     select pl.quantity
4508         into l_db_quantity
4509         from po_lines_all pl  --<Shared Proc FPJ>
4510         where pl.po_line_id = x_po_line_id;
4511       exception
4512     when others then
4513                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4514                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4515                                         p_token    => l_progress,
4516                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
4517                 END IF;
4518       end;
4519 
4520             l_progress := '550';
4521             -- Bug 3201308
4522             -- We get the pricing criteria from the min shipment if the grouping
4523             -- profiles are set such that multiple shipments get created when
4524             -- need by or ship to info are different on different lines.
4525 
4526             PO_SOURCING2_SV.get_min_shipment_num(x_po_line_id,l_min_shipment_num);
4527 
4528             l_progress := '560';
4529             BEGIN
4530                  select poll.ship_to_location_id,
4531                         poll.ship_to_organization_id,
4532                         poll.need_by_date
4533                  into   l_ship_to_loc,
4534                         l_ship_to_org,
4535                         l_need_by_date
4536                  from   po_line_locations_all poll
4537                  where  poll.po_line_id =  x_po_line_id
4538                  and    poll.shipment_num = l_min_shipment_num;
4539             EXCEPTION
4540                   when others then
4541                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4542                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4543                                             p_token    => l_progress,
4544                                             p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
4545                     END IF;
4546             END;
4547 
4548             -- Get the profile option values to determine grouping criteria
4549 
4550             l_needby_prf := fnd_profile.value('PO_NEED_BY_GROUPING');
4551             l_shipto_prf := fnd_profile.value('PO_SHIPTO_GROUPING');
4552 
4553             IF nvl(l_needby_prf,'Y') = 'Y' THEN
4554                l_need_by_date := interface.need_by_date;
4555             END IF;
4556 
4557             l_progress := '570';
4558 
4559             IF nvl(l_shipto_prf,'Y') = 'Y' THEN
4560                l_ship_to_org :=  interface.destination_organization_id;
4561                l_ship_to_loc :=  get_ship_to_loc(interface.deliver_to_location_id);
4562             END IF;
4563 
4564             l_progress := '580';
4565             -- <FPJ Advanced Price START>
4566             PO_SOURCING2_SV.get_break_price
4567             (  p_api_version       => 1.0
4568             ,  p_order_quantity    => x_quantity + nvl(l_db_quantity,0)
4569             ,  p_ship_to_org       => l_ship_to_org           -- Bug 3201308
4570             ,  p_ship_to_loc       => l_ship_to_loc           -- Bug 3201308
4571             ,  p_po_line_id        => interface.from_line_id
4572             ,  p_cum_flag          => FALSE
4573             ,  p_need_by_date      => l_need_by_date          -- Bug 3201308
4574             ,  p_line_location_id  => NULL
4575             ,  p_contract_id       => interface.contract_id
4576             ,  p_org_id            => g_purchasing_ou_id
4577             ,  p_supplier_id       => interface.vendor_id
4578             ,  p_supplier_site_id  => interface.vendor_site_id
4579             ,  p_creation_date     => interface.creation_date
4580             ,  p_order_header_id   => interface.po_header_id
4581             ,  p_order_line_id     => x_po_line_id
4582             ,  p_line_type_id      => interface.line_type_id
4583             ,  p_item_revision     => interface.item_revision
4584             ,  p_item_id           => interface.item_id
4585             ,  p_category_id       => interface.category_id
4586             ,  p_supplier_item_num => interface.vendor_product_num
4587             -- Bug 3343892, pass base_unit_price
4588             -- Bug 3417479, only pass base_unit_price
4589             -- ,  p_in_price          => NVL(interface.base_unit_price, interface.unit_price)
4590             ,  p_in_price          => interface.base_unit_price
4591             ,  p_uom               => x_unit_of_measure
4592             ,  p_currency_code     => interface.h_currency_code  -- Bug 3564863
4593             ,  x_base_unit_price   => l_base_unit_price
4594             ,  x_price_break_id    => l_price_break_id
4595             ,  x_price             => x_unit_price
4596             ,  x_return_status     => l_return_status
4597             );
4598             -- <FPJ Advanced Price END>
4599 
4600       -- Bug 3733202 START
4601       -- Treat 0 price as null price
4602       IF (x_unit_price = 0) THEN
4603         x_unit_price := NULL;
4604       END IF;
4605       -- Bug 3733202 END
4606 
4607              -- Bug 2879460 Update the price on the PO only with the price
4608              -- from the pricing API and not with the interface price
4609 
4610             UPDATE po_lines_all
4611             -- Bug 3417479
4612             -- SET   unit_price = x_unit_price,
4613             --       base_unit_price = l_base_unit_price,
4614             SET   unit_price = nvl(x_unit_price, unit_price),
4615                   base_unit_price = nvl(l_base_unit_price, base_unit_price),
4616                   from_line_location_id = l_price_break_id      -- <BUG 3282527>
4617             WHERE po_line_id = x_po_line_id;
4618 
4619             --<Bug 3313010 mbhargav START>
4620             --All the shipments which have been created need to get the
4621             --new price as on the line for Standard POs.
4622             UPDATE po_line_locations_all
4623             -- Bug 3417479
4624             -- SET price_override = x_unit_price
4625             SET price_override = nvl(x_unit_price, price_override)
4626             -- Bug 4902592. Not setting tax_attribute_update_code here because
4627             -- it should be passed as CREATE during tax calculation
4628             WHERE po_line_id = x_po_line_id;
4629             --<Bug 3313010 mbhargav END>
4630 
4631          END IF;
4632 
4633          /* GA FPI end */
4634 
4635        l_progress := '590';
4636        --<BUG 2698737 mbhargav START>
4637        --This update should not happen for RELEASES as this would update the BLANKET with REQ price
4638        -- because x_po_line_id is the blanket line_id for 'Release'
4639        -- Introducing the 'If' statement for checking that its not a release
4640        IF (g_document_subtype <> 'RELEASE') THEN
4641 
4642      /** If FSP org and item combination is dual uom control, update the po lines secondary quantity
4643       with the default conversion based on the PO lines quantity **/
4644 
4645        --<INVCONV R12> update secondary quantity/uom to null
4646 
4647          UPDATE po_lines_all  --<Shared Proc FPJ>
4648          SET quantity = (nvl(quantity,0) + nvl(x_quantity,0)),
4649              last_update_date  = interface.last_update_date,
4650              last_updated_by   = interface.last_updated_by,
4651              last_update_login = interface.last_update_login,
4652              closed_code = 'OPEN',
4653              closed_date = NULL,
4654 -- Bug 1199462 Amitabh
4655              closed_by   = NULL,
4656              secondary_quantity = null, --<INVCONV R12>
4657              secondary_unit_of_measure = null --<INVCONV R12>
4658          WHERE po_line_id = x_po_line_id
4659          RETURNING quantity INTO l_quantity_temp; --<INVCONV R12>
4660 
4661          --<INVCONV R12 START>
4662          IF item.secondary_uom_code IS NOT NULL and l_quantity_temp > 0 THEN
4663             SELECT unit_of_measure
4664             INTO   x_secondary_unit_def
4665             FROM   mtl_units_of_measure
4666             WHERE  uom_code = item.secondary_uom_code ;
4667 
4668             PO_UOM_S.uom_convert (l_quantity_temp,
4669                                   x_unit_of_measure,
4670                                   interface.item_id,
4671                                   x_secondary_unit_def,
4672                                   x_secondary_quantity_def) ;
4673 
4674             UPDATE po_lines_all
4675             SET secondary_quantity = x_secondary_quantity_def,
4676                 secondary_unit_of_measure = x_secondary_unit_def
4677             WHERE po_line_id = x_po_line_id ;
4678 
4679          END IF;
4680          --<INVCONV R12 END>
4681 
4682        END IF; --Release check for update
4683        --<BUG 2698737 mbhargav END>
4684 
4685       END IF;
4686    END IF;
4687 
4688      l_progress := '600';
4689 
4690     l_progress := '610';
4691     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4692         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4693                             p_token    => l_progress,
4694                             p_message  => 'Before going to create shipments');
4695     END IF;
4696 
4697    --<RENEG BLANKET FPI START>
4698    /* Create the shipment  or price break*/
4699    -- if the request is coming from Sourcing and document is Blanket
4700    -- then call create_price_break else call create_shipment
4701    IF g_document_subtype = 'BLANKET'
4702    THEN
4703      IF (g_interface_source_code = 'SOURCING'
4704          AND nvl(interface.shipment_type,'NONE') = 'PRICE BREAK')
4705      THEN
4706        create_price_break(x_po_line_id,
4707         x_line_location_id,
4708         l_outsourced_assembly); --<SHIKYU R12>
4709      END IF;
4710    -- <Complex Work R12 Start>
4711    ELSIF (p_is_complex_work_po)
4712    THEN
4713 
4714      -- x_line_location_id will be line_location_id of first actuals pay items.
4715      -- l_line_loc_id_tbl will return ids of all pay items created
4716 
4717      create_payitems(
4718        p_interface_line_id  => interface.interface_line_id
4719      , p_po_line_id         => x_po_line_id
4720      , p_precision          => x_precision
4721      , p_ext_precision      => x_ext_precision
4722      , x_line_location_id   => x_line_location_id
4723      , x_line_loc_id_tbl    => l_line_loc_id_tbl
4724      );
4725 
4726    -- <Complex Work R12 End>
4727    ELSE
4728      create_shipment(
4729        x_po_line_id,
4730        l_rate_for_req_fields, -- <ACHTML R12>
4731        x_line_location_id,
4732        l_outsourced_assembly --<SHIKYU R12>
4733      );
4734    END IF;
4735 
4736   /* Following Code commented as the below stated condition is included in
4737       FPI code above*/
4738    --<SOURCING TO PO FPH>
4739    --No need to create shipments for BLANKETS
4740    /*
4741    if g_document_subtype <>'BLANKET' then
4742    create_shipment(x_po_line_id,
4743                    x_line_location_id);
4744    end if;
4745    */
4746    --<RENEG BLANKET FPI END>
4747 
4748    l_progress:='620';
4749 
4750     -- <SERVICES FPJ START>
4751     --
4752     ---------------------------------------------------------------------------
4753     -- Req Line (TEXT) -> PO Line (Attachment) --------------------------------
4754     ---------------------------------------------------------------------------
4755     -- "Temp Labor" Lines have a Job Long Description, which resides on the
4756     -- Requisition Line as a LONG Text column, but needs to be copied over
4757     -- as an attachment on the PO Line.
4758     --
4759     IF ( l_purchase_basis = 'TEMP LABOR' ) THEN
4760 
4761         -- Get the Job Long Description from the Req Line.
4762         --
4763         l_job_long_description := PO_SERVICES_PVT.get_job_long_description
4764                                   (    p_req_line_id => interface.requisition_line_id
4765                                   );
4766 
4767         -- If Job Long Description exists, convert it to an attachment.
4768         --
4769         IF ( l_job_long_description IS NOT NULL ) THEN
4770 
4771             -- Initialize Standard WHO Columns.
4772             --
4773             l_who_rec.created_by := interface.created_by;
4774             l_who_rec.creation_date := interface.creation_date;
4775             l_who_rec.last_update_login := interface.last_update_login;
4776             l_who_rec.last_updated_by := interface.last_updated_by;
4777             l_who_rec.last_update_date := interface.last_update_date;
4778 
4779             l_progress := '630';
4780 
4781             -- Call Text-to-Attachment Conversion procedure
4782             --
4783             PO_NEGOTIATIONS_SV2.convert_text_to_attachment
4784             (   p_long_text      => l_job_long_description
4785             ,   p_description    => NULL
4786             ,   p_category_id    => 33                    -- To Supplier
4787             ,   p_to_entity_name => 'PO_LINES'
4788             ,   p_to_pk1_value   => x_po_line_id
4789             ,   p_who_rec        => l_who_rec
4790             );
4791 
4792         END IF; -- ( l_job_long_description IS NOT NULL )
4793 
4794     END IF; -- ( l_purchase_basis = 'TEMP LABOR' )
4795     --
4796     -- <SERVICES FPJ END>
4797 
4798 
4799 /*Bug # 712445 smathur*/
4800 /*For Releases copy attachments to PO_SHIPMENTS */
4801 
4802    if (g_document_subtype = 'RELEASE') and g_interface_source_code <> 'CONSUMPTION_ADVICE' then
4803                                                                        -- CONSIGNED FPI
4804 
4805    l_progress := '640';
4806    --  API to copy attachments from requisition line to release shipment
4807    fnd_attached_documents2_pkg.
4808        copy_attachments('REQ_LINES',
4809       interface.requisition_line_id,
4810       '',
4811       '',
4812       '',
4813       '',
4814       'PO_SHIPMENTS',
4815       x_line_location_id,
4816       '',
4817       '',
4818       '',
4819       '',
4820       interface.created_by,
4821       interface.last_update_login,
4822       '',
4823       '',
4824       '');
4825 
4826    l_progress:='650';
4827 
4828    -- Copy of the requisition header attachements to the purchase
4829    -- order line.
4830    SELECT requisition_header_id
4831    INTO   x_requisition_header_id
4832    FROM   po_requisition_lines_all  --<Shared Proc FPJ>
4833    WHERE  requisition_line_id = interface.requisition_line_id;
4834 
4835    l_progress:='660';
4836 
4837    fnd_attached_documents2_pkg.
4838       copy_attachments('REQ_HEADERS',
4839       x_requisition_header_id,
4840       '',
4841       '',
4842       '',
4843       '',
4844       'PO_SHIPMENTS',
4845       x_line_location_id,
4846       '',
4847       '',
4848       '',
4849       '',
4850       interface.created_by,
4851       interface.last_update_login,
4852       '',
4853       '',
4854       '');
4855     else /*smathur*/
4856    --  API to copy attachments from requisition line to po line
4857    --<SOURCING TO PO FPH>
4858 
4859 /* Copying the attachments functionaliy needs to work as following.
4860    when g_interface_source_code='SOURCING'
4861   1.The existing fnd_attched_documents2_pkg.copy_attachments will not
4862     be copying any attachments.
4863     The new API po_negotiations_sv2.handle_sourcing_attachments would
4864     take care of the following.
4865         2.Copy all the attachments from the negotiation line/header
4866     as supplier type attachment to this PO line. For a blanket,
4867     this would suppress all the attachments copied to negotiation
4868     from requisition and copy only the newly created supplier type
4869     attachment(on the negotiation) to the blanket line.
4870   3.All the attachments from the Bid line/Header would be copied to this
4871     PO line/Blanketline as internal to PO type of attachments.
4872         4.Bid attributes would be converted dynamically to a supplier type of
4873     attachment and attached to this PO line/Blanket line.
4874         5.Notes from negotiation header/line and bid header/line
4875     would be copied to po/blanket line as supplier type attachment.
4876         6.Notes from bid header/line
4877     would be copied to po/blanket line as supplier type attachment.
4878 */
4879 
4880     if g_interface_source_code not in ('SOURCING','CONSUMPTION_ADVICE') then   -- CONSIGNED FPI
4881       l_progress := '670';
4882    fnd_attached_documents2_pkg.
4883        copy_attachments('REQ_LINES',
4884       interface.requisition_line_id,
4885       '',
4886       '',
4887       '',
4888       '',
4889       'PO_LINES',
4890       x_po_line_id,
4891       '',
4892       '',
4893       '',
4894       '',
4895       interface.created_by,
4896       interface.last_update_login,
4897       '',
4898       '',
4899       '');
4900 
4901    l_progress:='680';
4902 
4903    -- Copy of the requisition header attachements to the purchase
4904    -- order line.
4905    SELECT requisition_header_id
4906    INTO   x_requisition_header_id
4907    FROM   po_requisition_lines_all  --<Shared Proc FPJ>
4908    WHERE  requisition_line_id = interface.requisition_line_id;
4909 
4910    l_progress:='690';
4911 
4912    fnd_attached_documents2_pkg.
4913       copy_attachments('REQ_HEADERS',
4914       x_requisition_header_id,
4915       '',
4916       '',
4917       '',
4918       '',
4919       'PO_LINES',
4920       x_po_line_id,
4921       '',
4922       '',
4923       '',
4924       '',
4925       interface.created_by,
4926       interface.last_update_login,
4927       '',
4928       '',
4929       '');
4930 
4931     end if;
4932     end if; /*end of changes : smathur*/
4933 
4934     l_progress := '700';
4935     --<SOURCING TO PO FPH START>
4936     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4937         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4938                             p_token    => l_progress,
4939                             p_message  => 'Sourcing to FPH-3 starts');
4940     END IF;
4941 
4942     --copy attachments/notes from negotiation/bid to po/blanket line
4943     if g_interface_source_code = 'SOURCING' then
4944        if interface.document_subtype = 'STANDARD' then
4945           if interface.requisition_line_id is not null then
4946              x_column1:='NEGREQ';
4947              l_progress:='710';
4948          SELECT requisition_header_id
4949            INTO x_requisition_header_id
4950                FROM po_requisition_lines_all  --<Shared Proc FPJ>
4951               WHERE requisition_line_id =interface.requisition_line_id;
4952           else
4953              x_column1:='NEG';
4954           end if;
4955        elsif interface.document_subtype = 'BLANKET' then
4956           x_column1:='NEG';
4957        end if;
4958        if interface.document_subtype in ('BLANKET','STANDARD') then
4959           l_progress:='720';
4960 
4961           po_negotiations_sv2.handle_sourcing_attachments(
4962       interface.auction_header_id,
4963       interface.auction_line_number,
4964       interface.bid_number,
4965       interface.bid_line_number,
4966       x_requisition_header_id,
4967       interface.requisition_line_id,
4968       x_po_line_id,
4969       x_column1,
4970       x_attch_suppress_flag,
4971       interface.created_by,
4972       interface.last_update_login);
4973 
4974        end if;
4975     end if;
4976 
4977     l_progress := '730';
4978     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4979         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4980                             p_token    => l_progress,
4981                             p_message  => 'Sourcing to FPH-3 Ends');
4982     END IF;
4983     --<SOURCING TO PO FPH END>
4984 
4985    -- Bug 2875346 start.
4986    -- If autocreating a SPO or PPO, and the requisition line has a one-time
4987    -- location, move the attachment from the PO line to the PO shipment
4988    IF (g_document_subtype IN ('STANDARD', 'PLANNED')) AND
4989       (has_one_time_location(interface.requisition_line_id))
4990    THEN
4991         -- Bug 2894378. Use BEGIN-EXCEPTION-END for exception handling to
4992         -- support original FPH behavior.
4993         BEGIN
4994 
4995             l_progress := '740';
4996 
4997             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
4998                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
4999                                     p_token    => l_progress,
5000                                     p_message  => 'Before selecting one-time attachment');
5001             END IF;
5002 
5003             --SQL What: Locate the one-time location attachment currently under
5004             --          the PO_LINES entity by it's unique iP identifier prefix
5005             --SQL Why: Need the attached_document_id to move the attachment
5006 
5007             SELECT fad.attached_document_id
5008             INTO   l_one_time_att_doc_id
5009             FROM   fnd_attached_documents fad,
5010                    fnd_documents_tl fdt
5011             WHERE  fad.entity_name = 'PO_LINES'
5012             AND    fad.pk1_value = to_char(x_po_line_id)
5013             AND    fad.document_id = fdt.document_id
5014             AND    fdt.language = USERENV('LANG')
5015             AND    fdt.description like 'POR:%';  -- iP unique identifier
5016 
5017             l_progress := '750';
5018 
5019             -- Move the attachment from the PO line to the PO shipment
5020             UPDATE fnd_attached_documents
5021             SET    entity_name = 'PO_SHIPMENTS',
5022                    pk1_value = to_char(x_line_location_id),
5023                    pk2_value = 'ONE_TIME_LOCATION'
5024             WHERE  attached_document_id = l_one_time_att_doc_id;
5025 
5026         EXCEPTION
5027             WHEN NO_DATA_FOUND THEN
5028                 -- If cannot locate one-time loc attchmnt, do nothing. This
5029                 -- supports original FPH behavior.
5030                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5031                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5032                                         p_token    => l_progress,
5033                                         p_message  => 'One-time loc attachment missing iP prefix, so do not try to move');
5034                 END IF;
5035         END;
5036    END IF;
5037    -- Bug 2875346 end.
5038 
5039    -- <Complex Work R12 Start> : Copy attachments to payitems
5040    IF (p_is_complex_work_po) THEN
5041 
5042      FOR i IN 1..l_line_loc_id_tbl.COUNT
5043      LOOP
5044 
5045        IF (l_line_loc_id_tbl(i) <> x_line_location_id) THEN
5046          -- Bug 5411781: Check if the one time location exists
5047          -- only then need to copy the one time attachments.
5048            -- copy one-time location from first actual shipment to
5049            -- each payitem.
5050        IF (l_one_time_att_doc_id IS NOT NULL) THEN
5051             fnd_attached_documents2_pkg.copy_attachments(
5052              X_from_entity_name  => 'PO_SHIPMENTS'
5053            , X_from_pk1_value    => x_line_location_id
5054            , X_from_pk2_value    => 'ONE_TIME_LOCATION'
5055            , X_to_entity_name    => 'PO_SHIPMENTS'
5056            , X_to_pk1_value      => l_line_loc_id_tbl(i)
5057            , X_to_pk2_value      => 'ONE_TIME_LOCATION'
5058            , X_created_by        => interface.created_by
5059            , X_last_update_login => interface.last_update_login
5060            );
5061 
5062         END IF;
5063       END IF;  -- if l_line_loc_id_tbl(i) <> x_line_location_id
5064 
5065        -- Bug 4620207: pass more parameters
5066        PO_NEGOTIATIONS_SV2.copy_sourcing_payitem_atts(
5067          p_line_location_id    => l_line_loc_id_tbl(i)
5068        , p_created_by          => interface.created_by
5069        , p_last_update_login   => interface.last_update_login
5070        , p_auction_header_id   => interface.auction_header_id
5071        , p_auction_line_number => interface.auction_line_number
5072        , p_bid_number          => interface.bid_number
5073        , p_bid_line_number     => interface.bid_line_number
5074        );
5075 
5076      END LOOP;
5077 
5078    END IF;  -- is Complex Work PO
5079 
5080    -- <Complex Work R12 End>
5081 
5082    l_progress:='760';
5083 
5084     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5085         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5086                             p_token    => l_progress,
5087                             p_message  => 'Create_line: Before update of po_requisition_lines');
5088     END IF;
5089 
5090    IF (g_document_type = 'PO') THEN
5091    l_progress:='770';
5092       UPDATE po_requisition_lines_all  --<Shared Proc FPJ>
5093          SET line_location_id  = x_line_location_id,
5094        --<CONSUME REQ DEMAND PFI START>
5095        reqs_in_pool_flag = NULL, --<REQINPOOL - changed value from N to NULL>
5096        --<CONSUME REQ DEMAND PFI END>
5097              last_update_date  = interface.last_update_date,
5098              last_updated_by   = interface.last_updated_by,
5099              last_update_login = interface.last_update_login
5100        WHERE requisition_line_id = interface.requisition_line_id;
5101    ELSE
5102       l_progress := '780';
5103       UPDATE po_requisition_lines_all  --<Shared Proc FPJ>
5104          SET on_rfq_flag = 'Y',
5105              last_update_date  = interface.last_update_date,
5106              last_updated_by   = interface.last_updated_by,
5107              last_update_login = interface.last_update_login
5108        WHERE requisition_line_id = interface.requisition_line_id;
5109    END IF;
5110 
5111    l_progress:='790';
5112    g_number_records_processed := g_number_records_processed + 1;
5113 
5114     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5115         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5116                             p_token    => l_progress,
5117                             p_message  => 'num records processed: '||g_number_records_processed);
5118         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
5119     END IF;
5120 
5121   --<Unified Catalog R12 START>
5122   l_progress:='800';
5123   -- For intergration with Sourcing, during blanket creation from Renegotiate flow,
5124   -- we need to import all attributes for each line.
5125   -- to facilitate bulk update, we are storing the newly created po_line on
5126   -- po_attr_values_interface and po_attr_values_interface_tlp
5127   IF (g_document_subtype = 'BLANKET'  AND g_interface_source_code = 'SOURCING') THEN
5128     l_progress:='810';
5129 
5130     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;
5131 
5132     --SQL What: Update the PO_LINE_ID on PO_ATTR_VALUES_INTERFACE table
5133     --SQL Why : To facilitate bulk update of attributes, later in the flow
5134     --SQL Join: interface_header_id, interface_line_id
5135     FORALL i IN INDICES OF l_po_line_id_tbl
5136       UPDATE PO_ATTR_VALUES_INTERFACE
5137         SET po_line_id = l_po_line_id_tbl(i),
5138             req_template_name = to_char(g_ATTR_VALUES_NULL_ID),
5139             req_template_line_num = to_char(g_ATTR_VALUES_NULL_ID),
5140             inventory_item_id = nvl(inventory_item_id, g_ATTR_VALUES_NULL_ID)
5141       WHERE po_attr_values_interface.interface_header_id = l_interface_header_id_tbl(i)
5142         AND po_attr_values_interface.interface_line_id = l_interface_line_id_tbl(i);
5143 
5144     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;
5145 
5146     l_progress:='820';
5147     --SQL What: Update the PO_LINE_ID on PO_ATTR_VALUES_TLP_INTERFACE table
5148     --SQL Why : To facilitate bulk update of attributes, later in the flow
5149     --SQL Join: interface_header_id, interface_line_id
5150     FORALL i IN INDICES OF l_po_line_id_tbl
5151       UPDATE PO_ATTR_VALUES_TLP_INTERFACE
5152         SET po_line_id = l_po_line_id_tbl(i),
5153             req_template_name = to_char(g_ATTR_VALUES_NULL_ID),
5154             req_template_line_num = to_char(g_ATTR_VALUES_NULL_ID),
5155             inventory_item_id = nvl(inventory_item_id, g_ATTR_VALUES_NULL_ID)
5156       WHERE po_attr_values_tlp_interface.interface_header_id = l_interface_header_id_tbl(i)
5157         AND po_attr_values_tlp_interface.interface_line_id = l_interface_line_id_tbl(i);
5158 
5159     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;
5160   END IF;
5161   --<Unified Catalog R12 END>
5162 
5163   IF g_debug_stmt THEN PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name); END IF;
5164 EXCEPTION
5165   WHEN NO_DATA_FOUND THEN
5166      IF (X_match_blanket_line = 'N') THEN
5167 
5168         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5169             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5170                                 p_token    => l_progress,
5171                                 p_message  => 'Create_line: Inside No data found : Match blanket line is N');
5172         END IF;
5173         null;
5174      ELSE
5175 
5176         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5177             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5178                                 p_token    => l_progress,
5179                                 p_message  => 'Create_line : Inside No data found : Match blanket line is not N');
5180         END IF;
5181         po_message_s.sql_error('CREATE_LINE', l_progress,sqlcode);
5182         wrapup(x_interface_header_id);
5183         raise;
5184 
5185      END IF;
5186   --handle update_req_pool_fail exception
5187   --<SOURCING TO PO FPH START>
5188   WHEN update_req_pool_fail then
5189        po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
5190         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5191             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5192                                 p_token    => l_progress,
5193                                 p_message  => 'Create_documents: update_req_pool_fail exception : SQLCODE '||sqlcode);
5194         END IF;
5195        raise;
5196 
5197   --<SOURCING TO PO FPH END>
5198   WHEN OTHERS THEN
5199      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
5200          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
5201                             p_progress => l_progress);
5202      END IF;
5203      wrapup(x_interface_header_id);
5204      po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
5205      raise;
5206 
5207 END create_line;
5208 
5209 /* ============================================================================
5210      NAME: CREATE_SHIPMENT
5211      DESC: Create/Add to document shipment
5212      ARGS: IN : x_po_line_id IN number
5213            IN : x_line_location_id IN number
5214      ALGR:
5215 
5216    ==========================================================================*/
5217 PROCEDURE create_shipment(
5218   x_po_line_id IN number,
5219   p_rate_for_req_fields IN NUMBER, -- <ACHTML R12>
5220   x_line_location_id IN OUT NOCOPY number,
5221   p_outsourced_assembly IN NUMBER --<SHIKYU R12>
5222   )
5223 IS
5224 x_ship_to_location_id number:= 0;
5225 x_po_release_id number := g_po_release_id;
5226 x_cumulative_flag boolean; /* used to get release price from PA */
5227 x_price number;              /* used to get release price from PA */
5228 x_price_break_type varchar2(25) := '';
5229 x_doctype varchar2(25) := ''; /* used for call to update close state */
5230 x_return_code varchar2(25) := ''; /* used for call to update close state */
5231 x_item_org_taxable_flag      mtl_system_items.taxable_flag%type := NULL;
5232 x_ship_to_org_taxable_flag   mtl_system_items.taxable_flag%type := NULL;
5233 x_return_taxable_flag        mtl_system_items.taxable_flag%type := NULL;
5234 
5235 /* For converting qty if line_type is not quantity based */
5236 x_order_type_lookup_code  varchar2(25)  :='';
5237 x_quantity      number    :=0;
5238 l_conversion_rate number :=1;
5239 
5240 /* obtain currency info to adjust precision */
5241 x_precision   number :='';
5242 x_ext_precision   number :='';
5243 x_min_unit    number :='';
5244 
5245 /* Additional tax variables for R11 tax defaulting functionality */
5246 x_tax_code_id                   ap_tax_codes.tax_id%type;
5247 x_tax_type                      ap_tax_codes.tax_type%type;
5248 x_description                   ap_tax_codes.description%type;
5249 x_allow_tax_code_override_flag  gl_tax_option_accounts.allow_tax_code_override_flag%type;
5250 
5251 /* Parameters for supporting OE callback for maintaining so_drop_ship_source */
5252 x_p_api_version     number:='';
5253 x_p_return_status   varchar2(1):='';
5254 x_p_msg_count     number:='';
5255 x_p_msg_data      varchar2(2000):='';
5256 x_p_req_header_id   NUMBER:='';
5257 x_p_req_line_id     NUMBER:='';
5258 --x_p_interface_source_code   varchar2(25);
5259 --x_p_interface_source_line_id  number:='';
5260 x_p_po_header_id    number:='';
5261 x_p_po_line_id      number:='';
5262 x_p_line_location_id    number:='';
5263 x_requisition_header_id   number:='';
5264 x_p_po_release_id   number:='';
5265 
5266 /*630638 - SVAIDYAN: Variable to get the qty in the already existing shipment */
5267 x_ship_qty number := 0;
5268 --FRKHAN 12/21/98
5269 x_tax_user_override_flag  VARCHAR2(1);
5270 --FRKHAN 1/12/99
5271 x_country_of_origin_code  VARCHAR2(2);
5272 x_tax_status            VARCHAR2(10);
5273 x_tax_status_indicator          po_requisition_lines.tax_status_indicator%type;
5274 --FRKHAN 12/2/99 BUG 1084816
5275 l_encode VARCHAR2(2000);
5276 x_po_uom  varchar2(25):=null;
5277 x_temp_uom  varchar2(25):=null;
5278 x_temp_item_id  number:=null;
5279 x_closed_reason po_line_locations.closed_reason%TYPE;
5280 x_uom_convert          varchar2(2) := fnd_profile.value('PO_REQ_BPA_UOM_CONVERT');
5281 
5282 --<Bug# 3293109 START>
5283 l_promised_date         DATE            := INTERFACE.PROMISED_DATE;
5284 l_po_promised_def_prf   VARCHAR2(1)     := fnd_profile.value('PO_NEED_BY_PROMISE_DEFAULTING');
5285 --<Bug# 3293109 END>
5286 
5287 l_api_name CONSTANT VARCHAR2(30) := 'create_shipment';
5288 l_progress VARCHAR2(3) := '000';                    --< Bug 3210331 >
5289 l_manual_price_change_flag po_line_locations_all.manual_price_change_flag%TYPE := NULL; --bug 3495772
5290 
5291 -- Bug 5208159
5292 l_from_type_lookup_code po_headers_all.type_lookup_code%TYPE;
5293 
5294 --<INVCONV R12 START>
5295 x_shipment_uom      MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
5296 x_secondary_unit_of_measure MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
5297 x_secondary_quantity    PO_LINES.SECONDARY_QUANTITY%TYPE;
5298 x_secondary_uom_code    MTL_UNITS_OF_MEASURE.UOM_CODE%TYPE;
5299 --<INVCONV R12 END>
5300 
5301 l_matching_basis    PO_LINE_TYPES.matching_basis%TYPE;  -- <Complex Work R12>
5302 
5303 BEGIN
5304     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5305         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
5306     END IF;
5307 
5308    x_line_location_id:=null;
5309    x_quantity := interface.quantity;
5310 
5311    x_temp_uom     := interface.unit_meas_lookup_code;
5312    x_temp_item_id := interface.item_id;
5313 
5314     l_progress := '010';
5315 
5316     -- <SERVICES FPJ START>
5317     -- <Complex Work R12>: Also get matching basis
5318 
5319     SELECT plt.order_type_lookup_code, plt.matching_basis
5320     INTO   x_order_type_lookup_code, l_matching_basis
5321     FROM   po_line_types plt
5322     WHERE  plt.line_type_id = interface.line_type_id;
5323 
5324     --
5325     -- <SERVICES FPJ END>
5326 
5327      IF interface.h_currency_code IS NOT NULL THEN
5328                 fnd_currency.get_info(interface.h_currency_code,
5329                              x_precision,
5330                              x_ext_precision,
5331                              x_min_unit );
5332      END IF;
5333 
5334     -- bug 5208159 : Conversion of req UOM to Quotation UOM should always happen if the
5335     -- source document is a quote and profile 'PO: Convert Requisition UOM to Source Document UOM'
5336     -- should be ignored in that case
5337     IF g_debug_stmt THEN
5338          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5339                              p_token    => l_progress,
5340                              p_message  => 'from line id :'||interface.from_line_id||'from header id:'||interface.from_header_id);
5341     END IF;
5342 
5343     IF (interface.from_line_id IS NOT NULL) AND (g_document_subtype = 'STANDARD') THEN
5344 
5345          l_progress := '015';
5346 
5347          BEGIN
5348 
5349            SELECT poh.type_lookup_code
5350            INTO   l_from_type_lookup_code
5351            FROM   po_headers_all poh
5352            WHERE poh.po_header_id=interface.from_header_id ;
5353 
5354            IF g_debug_stmt THEN
5355                PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5356                                    p_token    => l_progress,
5357                                    p_message  => 'l_from_type_lookup_code :'||l_from_type_lookup_code);
5358            END IF;
5359 
5360 
5361 
5362          EXCEPTION
5363            WHEN OTHERS THEN
5364                IF g_debug_unexp THEN
5365                    PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
5366                                       p_progress => l_progress);
5367                END IF;
5368                po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
5369                wrapup(interface.interface_header_id);
5370                raise;
5371            END;
5372     END IF;
5373 
5374     -- got the source document type, now compare it and if required do the UOM conversion
5375 
5376     IF g_debug_stmt THEN
5377          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5378                              p_token    => l_progress,
5379                              p_message  => 'x_uom_convert:'||x_uom_convert);
5380     END IF;
5381 
5382   IF (nvl(x_uom_convert,'N') = 'Y' OR l_from_type_lookup_code = 'QUOTATION') THEN
5383   -- bug 5208159 : end
5384 
5385    IF (g_document_subtype='RELEASE')
5386      -- Bug 2735840 Convert UOM when autocreating a PO that references a GA
5387      OR ((g_document_subtype='STANDARD')
5388          AND (interface.from_line_id is not null)) THEN
5389 
5390    /* Enh : 1660036
5391     get the uom from the PO . This will be used for uom conversion */
5392 
5393     BEGIN
5394       IF (g_document_subtype='RELEASE') THEN -- Bug 2735840
5395         l_progress := '020';
5396         select unit_meas_lookup_code
5397         into x_po_uom
5398         from po_lines_all pol ,  --<Shared Proc FPJ>
5399              po_headers_all poh  --<Shared Proc FPJ>
5400         where pol.po_header_id = poh.po_header_id
5401         and pol.po_header_id = interface.po_header_id
5402         and pol.line_num = interface.line_num;
5403       -- Bug 2735840 START
5404       ELSE -- Autocreating a PO that references a GA
5405         l_progress := '030';
5406         SELECT unit_meas_lookup_code
5407         INTO x_po_uom
5408         FROM po_lines_all
5409         WHERE po_line_id = interface.from_line_id;
5410       END IF; -- g_document_subtype
5411       -- Bug 2735840 END
5412      EXCEPTION
5413      WHEN OTHERS THEN
5414        IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
5415            PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
5416                               p_progress => l_progress);
5417        END IF;
5418        po_message_s.sql_error('CREATE_SHIPMENTS',l_progress,sqlcode);
5419        wrapup(interface.interface_header_id);
5420        raise;
5421     END;
5422 
5423   /* before inserting the quantity into the shipments table convert the quantity
5424       into the BPA uom if the uom's on the req and BPA are different .
5425       This conversion is done only if the Convert UOM  profile option is set to Yes. */
5426 
5427     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5428         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5429                             p_token    => l_progress,
5430                             p_message  => 'Create_shipment: UOM: '||x_temp_uom);
5431         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5432                             p_token    => l_progress,
5433                             p_message  => 'Create_shipment: item id: '||x_temp_item_id);
5434         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5435                             p_token    => l_progress,
5436                             p_message  => 'Create_shipment: PO UOM: '||x_po_uom);
5437     END IF;
5438 
5439     l_progress := '040';
5440 
5441         IF  (   ( interface.unit_meas_lookup_code <> x_po_uom )
5442             AND ( x_order_type_lookup_code IN ('QUANTITY','AMOUNT') ) ) THEN   -- <SERVICES FPJ>
5443 
5444 
5445             -- Bug 3793360 : use the po_uom_convert procedure and round 15
5446             l_conversion_rate :=  po_uom_s.po_uom_convert(interface.unit_meas_lookup_code,
5447                                                        x_po_uom,
5448                                                        interface.item_id);
5449 
5450             x_quantity := round(x_quantity * l_conversion_rate , 15);
5451             x_shipment_uom := x_po_uom ; --<INVCONV R12>
5452 
5453         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5454             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5455                                 p_token    => l_progress,
5456                                 p_message  => 'Create_shipment: Converted Qty: '||x_quantity);
5457         END IF;
5458 
5459         END IF;
5460 
5461     END IF;
5462   END IF;
5463 
5464     l_progress := '050';
5465    /*
5466    ** Get the ship to location id associated with the
5467    ** deliver to location.  This may then used to
5468    ** get the tax name, if the tax system parameters are
5469    ** set up to retrieve the tax code based on ship-to location.
5470    */
5471 
5472    x_ship_to_location_id := get_ship_to_loc(interface.deliver_to_location_id);  -- FPI
5473 
5474   IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED' or
5475   g_document_type = 'RFQ')THEN
5476     l_progress := '060';
5477     BEGIN
5478       SELECT poll.line_location_id,poll.secondary_unit_of_measure --<INVCONV R12>
5479         INTO x_line_location_id,x_secondary_unit_of_measure
5480         FROM po_line_locations_all poll,  --<Shared Proc FPJ>
5481              po_lines_all pol  --<Shared Proc FPJ>
5482        WHERE poll.po_header_id = interface.po_header_id
5483          AND poll.po_line_id = pol.po_line_id
5484          AND poll.shipment_num = interface.shipment_num
5485          AND pol.line_num = interface.line_num
5486          AND poll.shipment_type in ('STANDARD','PLANNED', 'RFQ');
5487     EXCEPTION
5488      WHEN NO_DATA_FOUND THEN
5489         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5490             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5491                                 p_token    => l_progress,
5492                                 p_message  => 'NO_DATA_FOUND: '||SQLERRM);
5493         END IF;
5494      WHEN OTHERS THEN
5495        IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
5496            PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
5497                               p_progress => l_progress);
5498        END IF;
5499        po_message_s.sql_error('CREATE_SHIPMENTS',l_progress,sqlcode);
5500        wrapup(interface.interface_header_id);
5501        raise;
5502     END;
5503 
5504 
5505   ELSIF(g_document_subtype='RELEASE')THEN
5506     l_progress := '070';
5507     BEGIN
5508       SELECT poll.line_location_id,
5509              poll.manual_price_change_flag, --bug 3495772
5510              poll.secondary_unit_of_measure --<INVCONV R12>
5511         INTO x_line_location_id,
5512              l_manual_price_change_flag, --bug 3495772
5513              x_secondary_unit_of_measure
5514         FROM po_line_locations_all poll,  --<Shared Proc FPJ>
5515              po_lines_all pol,  --<Shared Proc FPJ>
5516              po_releases_all por  --<Shared Proc FPJ>
5517        WHERE poll.po_header_id = interface.po_header_id
5518          AND poll.po_line_id = pol.po_line_id
5519          AND poll.shipment_num = interface.shipment_num
5520          AND pol.line_num = interface.line_num
5521          AND poll.po_release_id=por.po_release_id
5522          AND por.po_release_id=x_po_release_id;
5523 
5524 
5525     EXCEPTION
5526      WHEN NO_DATA_FOUND THEN
5527         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5528             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5529                                 p_token    => l_progress,
5530                                 p_message  => 'NO_DATA_FOUND: '||SQLERRM);
5531         END IF;
5532      WHEN OTHERS THEN
5533        IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
5534            PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
5535                               p_progress => l_progress);
5536        END IF;
5537        po_message_s.sql_error('CREATE_SHIPMENTS',l_progress,sqlcode);
5538        wrapup(interface.interface_header_id);
5539        raise;
5540     END;
5541   END IF;
5542 
5543   l_progress:='080';
5544 
5545   IF(interface.document_subtype = 'RELEASE')  AND
5546     (g_interface_source_code  <> 'CONSUMPTION_ADVICE') THEN  -- Bug 2748933
5547 
5548      IF(nvl(l_manual_price_change_flag, 'N') <> 'Y') THEN -- bug 3495772
5549 
5550          -- Find out if the line is using cumulative or non-cumlative pricing
5551          SELECT decode(price_break_lookup_code, 'CUMULATIVE', 'Y', 'N')
5552          INTO   x_price_break_type
5553          FROM   po_lines_all  --<Shared Proc FPJ>
5554          WHERE  po_line_id = x_po_line_id;
5555 
5556          IF (x_price_break_type = 'Y') THEN
5557              x_cumulative_flag := TRUE;
5558          ELSE
5559              x_cumulative_flag := FALSE;
5560          END IF;
5561 
5562     /* 630638 - SVAIDYAN
5563        If the price break type is not cumulative, then
5564        If there exists a shipment to which this qty will be added, then the
5565        qty to get break price would be already existing shipment quantity +
5566        interface.quantity.
5567 
5568     */
5569 
5570         l_progress := '090';
5571         if (x_line_location_id is not null and x_cumulative_flag = FALSE) then
5572         begin
5573             select nvl(quantity, 0)
5574             into   x_ship_qty
5575             from   po_line_locations_all  --<Shared Proc FPJ>
5576             where  line_location_id = x_line_location_id;
5577         exception
5578             when others THEN
5579                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5580                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5581                                         p_token    => l_progress,
5582                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
5583                 END IF;
5584                 x_ship_qty := 0;
5585         end;
5586         end if;
5587 
5588         l_progress := '100';
5589          x_ship_qty := x_ship_qty + x_quantity;
5590 
5591 
5592          /* <TIMEPHASED FPI> */
5593          /* Changed the parameter sysdate to interface.need_by_date */
5594          x_price := po_sourcing2_sv.get_break_price(
5595           x_ship_qty,
5596           interface.destination_organization_id,
5597                       x_ship_to_location_id,
5598           x_po_line_id,
5599                       x_cumulative_flag,
5600                             interface.need_by_date);   /* <TIMEPHASED FPI> */
5601 
5602       ELSE --manual_price_change_flag = y, bug 3495772
5603            x_price := NULL; --will preserve whatever price is alredy on shipment
5604                             -- in below update statement
5605       END IF;
5606 
5607   ELSE
5608      /* Bug 486563 ecso 5/13/97
5609       * When mulitple lines with different unit_price are combined, we need
5610       * to ensure that price_override field in shipments are populated with
5611       * the unit_price from the line, not the original one from the req.
5612       */
5613    /* Bug 2748933 */
5614    /* For a consumption advice we take the price as it is populated and not from the BPA */
5615 
5616 
5617       IF (g_interface_source_code  =  'CONSUMPTION_ADVICE') THEN
5618             x_price := interface.unit_price;
5619 
5620       ELSE
5621 
5622        l_progress := '110';
5623        begin
5624          SELECT unit_price
5625          INTO   x_price
5626          FROM   po_lines_all  --<Shared Proc FPJ>
5627          WHERE  po_line_id=x_po_line_id;
5628        exception
5629            when others then
5630               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5631                   PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5632                                       p_token    => l_progress,
5633                                       p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
5634               END IF;
5635               x_price := null;
5636        end;
5637 
5638       END IF;
5639 
5640   END IF;
5641 
5642   IF(x_line_location_id is not null) THEN
5643 
5644      /*
5645      ** Update everything except closed_code
5646      */
5647      l_progress:='120';
5648       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5649           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5650                               p_token    => l_progress,
5651                               p_message  => 'Create_shipment: shipment exist');
5652           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5653                               p_token    => l_progress,
5654                               p_message  => 'Create_shipment: Update PO line locations');
5655       END IF;
5656 
5657       /*Bug 5629398 Start: Quantity conversion for foreign currency was not happening for
5658         amount based lines when we try to add to existing shipment line */
5659         IF   ( x_order_type_lookup_code = 'QUANTITY' ) THEN
5660                   x_quantity := round(x_quantity,15);
5661         ELSIF ( x_order_type_lookup_code = 'AMOUNT' ) THEN
5662              -- Bug 7661419, No conversion for same currency.
5663 	     PO_INTERFACE_S.do_currency_conversion(
5664                       p_order_type_lookup_code => 'AMOUNT',
5665                       p_interface_source_code  => g_interface_source_code,
5666                       p_rate                   => p_rate_for_req_fields, -- <ACHTML R12>
5667                       p_po_currency_code       => interface.h_currency_code,
5668                       p_requisition_line_id    => interface.requisition_line_id,
5669                       x_quantity               => x_quantity, -- IN/OUT
5670                       x_unit_price             => interface.unit_price, -- IN/OUT
5671                       x_base_unit_price        => interface.base_unit_price, -- IN/OUT
5672                       x_amount                 => interface.amount -- IN/OUT
5673                       );
5674 	END IF;
5675     /*Bug 5629398 End */
5676 
5677 
5678       --<INVCONV R12 START>
5679       --If item is dual uom control and secondary quantity is NULL, derive it
5680      IF x_secondary_unit_of_measure IS NOT NULL THEN
5681         IF interface.secondary_quantity IS  NULL THEN
5682            PO_UOM_S.uom_convert (x_quantity,
5683                                  nvl(x_shipment_uom, interface.unit_meas_lookup_code),
5684                                  interface.item_id, x_secondary_unit_of_measure ,
5685                                  x_secondary_quantity) ;
5686         ELSE
5687            X_secondary_quantity := interface.secondary_quantity ;
5688         END IF;
5689      ELSE
5690         x_secondary_quantity  := null ;
5691      END IF;
5692      --<INVCONV R12 END>
5693 
5694 
5695      --<INVCONV R12> replace interface.secondary_quantity with x_secondary_quantity
5696 
5697      UPDATE po_line_locations_all  --<Shared Proc FPJ>
5698   SET quantity          = quantity + x_quantity,
5699 -- start of 1548597
5700             secondary_quantity = secondary_quantity + x_secondary_quantity,
5701 -- end of 1548597
5702             approved_flag     = DECODE(approved_flag,
5703                                          'N','N', 'R'),
5704             last_update_date  = interface.last_update_date,
5705             last_update_login = interface.last_update_login,
5706             last_updated_by   = interface.last_updated_by,
5707             price_override    = decode(g_document_type, 'RFQ',
5708           price_override, DECODE(
5709           nvl(x_price, -1),
5710                                        -1, price_override,
5711 -- Bug 1353736 use precision in rounding
5712 -- Bug 3472140: Changed precisions to 15
5713                                        ROUND(x_price, nvl(x_ext_precision,15)))),
5714             -- Bug 5067321. Setting tax_attribute_update_code to update for
5715             -- add_to cases.
5716             tax_attribute_update_code = NVL(tax_attribute_update_code,
5717                                             NVL2(g_calculate_tax_flag, 'UPDATE', null))
5718       WHERE line_location_id = x_line_location_id;
5719 
5720       /*
5721       ** 9/10/97 ecso
5722       ** OE Callback function for maintaining so_drop_ship_sources table
5723       */
5724       /* 11/18/97 ecso
5725       ** OE redesign. No Shipments linked to sales order will be combined
5726       ** Therefore, no need to do call back for update shipment
5727       ** Removed oe callback.
5728       */
5729 
5730       /*
5731       ** Prepare to call pocupdate_close: - call auto close.
5732       */
5733       IF (g_document_type = 'PO') THEN
5734        IF (g_mode = 'ADD') THEN
5735         IF (g_document_type = 'PO') THEN
5736          IF (g_document_subtype = 'RELEASE') THEN
5737             x_doctype := 'RELEASE';
5738               /* Bug 4016505 Start */
5739               IF NOT po_actions.close_po(x_po_release_id,
5740                     x_doctype,
5741                     g_document_subtype,
5742                     x_po_line_id,
5743                     x_line_location_id,
5744                     'CLOSE',
5745                     '',
5746                     'PO',
5747                     'N',
5748                     x_return_code,
5749                     'Y') then
5750 
5751                   po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
5752 
5753                END IF;
5754               /* Bug 4016505 End */
5755          ELSE
5756             x_doctype := 'PO';
5757                           /* Bug 4016505 Start */
5758             IF NOT po_actions.close_po(interface.po_header_id,
5759                     x_doctype,
5760                     g_document_subtype,
5761                     x_po_line_id,
5762                     x_line_location_id,
5763                     'CLOSE',
5764                     '',
5765                     'PO',
5766                     'N',
5767                     x_return_code,
5768                     'Y') then
5769 
5770                po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
5771 
5772             END IF;
5773             /* Bug 4016505 End */
5774          END IF;
5775 
5776          l_progress := '130';
5777          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5778              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5779                                  p_token    => l_progress,
5780                                  p_message  => 'Create shipment: Before calling Auto close');
5781          END IF;
5782 
5783          IF NOT po_actions.close_po(interface.po_header_id,
5784                     x_doctype,
5785                     g_document_subtype,
5786                     x_po_line_id,
5787                     x_line_location_id,
5788                     'CLOSE',
5789                     '',
5790                     'PO',
5791                     'N',
5792                     x_return_code,
5793                     'Y') then
5794 
5795             po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
5796 
5797          END IF;
5798 
5799        END IF;
5800 
5801       END IF;
5802 
5803      END IF;
5804 
5805   ELSIF(x_line_location_id is null) THEN
5806 
5807       l_progress := '140';
5808       IF (g_document_type = 'PO') THEN
5809          /*
5810          ** Prepare to call pocupdate_close: -  call manual close
5811          ** for the line level.
5812          */
5813         IF (g_mode = 'ADD') THEN
5814            IF (g_document_subtype = 'RELEASE') THEN
5815               x_doctype := 'RELEASE';
5816               /* Bug 4016505 Start */
5817                 IF not po_actions.close_po(x_po_release_id,
5818                     x_doctype,
5819                     g_document_subtype,
5820                     x_po_line_id,
5821                     x_line_location_id,
5822                     'CLOSE',
5823                     '',
5824                     'PO',
5825                     'N',
5826                     x_return_code,
5827                     'N') then
5828 
5829                    po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
5830                 END IF;
5831               /* Bug 4016505 End */
5832            ELSE
5833               x_doctype := 'PO';
5834               /* Bug 4016505 Start */
5835               IF not po_actions.close_po(interface.po_header_id,
5836                     x_doctype,
5837                     g_document_subtype,
5838                     x_po_line_id,
5839                     x_line_location_id,
5840                     'CLOSE',
5841                     '',
5842                     'PO',
5843                     'N',
5844                     x_return_code,
5845                     'N') then
5846                po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
5847              END IF;
5848               /* Bug 4016505 End */
5849            END IF;
5850 
5851            l_progress := '150';
5852            IF not po_actions.close_po(interface.po_header_id,
5853                     x_doctype,
5854                     g_document_subtype,
5855                     x_po_line_id,
5856                     x_line_location_id,
5857                     'CLOSE',
5858                     '',
5859                     'PO',
5860                     'N',
5861                     x_return_code,
5862                     'N') then
5863 
5864               po_message_s.sql_error('CLOSE_PO',l_progress,sqlcode);
5865 
5866            END IF;
5867 
5868         END IF;
5869 
5870      END IF;
5871 
5872      l_progress:='160';
5873      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5874          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5875                              p_token    => l_progress,
5876                              p_message  => 'create shipment: Shipment does not exist');
5877      END IF;
5878 
5879      l_progress := '200';
5880 
5881      /* Bug 482648
5882       * Adjust quantity for foreign currecny
5883       */
5884 
5885         IF ( x_order_type_lookup_code = 'QUANTITY' ) THEN     -- <SERVICES FPJ>
5886 
5887 -- added by jbalakri for bug 2372004
5888 -- Bug 3472140: Changed precisions to 15
5889             x_quantity := round(x_quantity,15);
5890 
5891         ELSIF ( x_order_type_lookup_code = 'AMOUNT' ) THEN    -- <SERVICES FPJ>
5892              -- Bug 7661419, No conversion for same currency.
5893              PO_INTERFACE_S.do_currency_conversion(
5894                       p_order_type_lookup_code => 'AMOUNT',
5895                       p_interface_source_code  => g_interface_source_code,
5896                       p_rate                   => p_rate_for_req_fields, -- <ACHTML R12>
5897                       p_po_currency_code       => interface.h_currency_code,
5898                       p_requisition_line_id    => interface.requisition_line_id,
5899                       x_quantity               => x_quantity, -- IN/OUT
5900                       x_unit_price             => interface.unit_price, -- IN/OUT
5901                       x_base_unit_price        => interface.base_unit_price, -- IN/OUT
5902                       x_amount                 => interface.amount -- IN/OUT
5903                       );
5904         END IF;
5905 
5906      /*
5907       **  Create a new shipment.
5908       */
5909      l_progress:='210';
5910     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5911         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5912                             p_token    => l_progress,
5913                             p_message  => 'Create shipment: Create a new shipment');
5914     END IF;
5915 
5916      SELECT po_line_locations_s.nextval
5917        INTO x_line_location_id
5918        FROM sys.dual;
5919 
5920      -- bug: 404191
5921      --      Get the taxable_flag based on the following priority
5922      --      1. preferences (global.po_taxable_flag)
5923      --      2. ship_to_org (x_ship_to_org_taxable_flag)
5924      --      2. item-org    (po_lines.taxable_flag)
5925      --      3. PO default  (po_startup_values.taxable_flag)
5926      --
5927      l_progress:='220';
5928      x_item_org_taxable_flag :=  item.taxable_flag;
5929 
5930 
5931      -- Bug 3935370 START
5932      -- Removed the po_items_sv3.get_taxable_flag procedure because
5933      -- x_return_taxable_flag should be based off of tax_code_id instead.
5934      -- Also removed fix for bug 1651019 because it sets x_return_taxable_flag
5935      -- to Y if x_tax_code_id is not null, which is duplicated in this fix.
5936      -- Added else clause in if statment to make sure x_return_taxable_flag is
5937      -- set appropriately according to tax_code_id.
5938      -- Bug 3935370 END
5939 
5940      --< Bug 3334670 Start >
5941      IF (g_interface_source_code = 'CONSUMPTION_ADVICE') THEN
5942 
5943          -- tax_code_id from the interface table is used for consumption advice
5944          IF (NVL(interface.tax_code_id, -1) = -1) THEN
5945              -- FPI inventory code was populating tax_code_id = -1 in some cases
5946              -- for consumption advice. Never insert -1.
5947              interface.tax_code_id := NULL;
5948              x_return_taxable_flag := 'N';
5949          ELSE
5950              x_return_taxable_flag := 'Y';
5951          END IF;
5952      --< Bug 3334670 End >
5953      -- Bug 3935370 START
5954      ELSE
5955        IF (x_tax_code_id is not null) then
5956          x_return_taxable_flag := 'Y';
5957        ELSE
5958          x_return_taxable_flag := 'N';
5959        END IF;
5960      -- Bug 3935370 END
5961      END IF;
5962 
5963      l_progress:='230';
5964 
5965 --FRKHAN 1/12/99 Get default country of origin
5966      po_coo_s.get_default_country_of_origin(
5967       interface.item_id,
5968       interface.destination_organization_id,
5969       interface.vendor_id,
5970       interface.vendor_site_id,
5971       x_country_of_origin_code);
5972 
5973 /*Bug no 781929
5974   Last accept date is also inserted into po_line_locations table.
5975   last_accept_date = interface.need_by_date+rc.days_late_receipt_allowed.
5976   Purposely , null handling has not been done, since even if either
5977   need_by_date or days_late_received_allowed is null then the last_accept_date
5978   should be null.
5979 */
5980 
5981 -- Bug 1353736 Call fnd_currency.get_info to get the precision
5982 --added by jbalakri for 1805397
5983         IF interface.h_currency_code IS NOT NULL THEN
5984                    fnd_currency.get_info(interface.h_currency_code,
5985                                          x_precision,
5986                                          x_ext_precision,
5987                                          x_min_unit );
5988         end if;
5989 --end of add for 1805397
5990 
5991         l_progress := '240';
5992         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
5993             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
5994                                 p_token    => l_progress,
5995                                 p_message  => 'Create shipment: Before insert into po line locations');
5996         END IF;
5997 
5998      /* CONSIGNED FPI start : Set the closed reason for consigned */
5999         IF interface.consigned_flag = 'Y' THEN
6000            x_closed_reason := fnd_message.get_string('PO', 'PO_SUP_CONS_CLOSED_REASON');
6001         ELSE
6002            x_closed_reason := null;
6003         END IF;
6004 
6005 
6006      /* CONSIGNED FPI End */
6007 
6008      --<Bug# 3293109 START>
6009      if g_document_type <> 'RFQ'
6010          and l_promised_date is null
6011          and nvl(l_po_promised_def_prf, 'N') = 'Y' then
6012 
6013                 l_promised_date := INTERFACE.NEED_BY_DATE;
6014      end if;
6015      --<Bug# 3293109 END>
6016 
6017      -- GA FPI Bug 2750604. Need to insert from_header_id and from_line_id
6018      -- at the shipment level from the interface tables.
6019 
6020      --Bug 2861408:  For consigned items ALWAYS insert 'N' for
6021      --receipt-required flag and inspection-required flag, and
6022      --insert 'P' for match_option.
6023 
6024 
6025     l_progress := '250';
6026     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6027         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6028                             p_token    => l_progress,
6029                             p_message  => 'interface.trxn_flow_header_id='||interface.transaction_flow_header_id);
6030     END IF;
6031 
6032     --<INVCONV R12 START>
6033     -- If item is dual uom control and secondary quantity is NULL, derive it
6034     IF interface.item_id IS NOT NULL THEN
6035       IF interface.secondary_quantity IS NULL THEN
6036           PO_UOM_S.get_secondary_uom( interface.item_id,
6037                                          interface.destination_organization_id,
6038                                          x_secondary_uom_code,
6039                                          x_secondary_unit_of_measure);
6040 
6041          IF x_secondary_unit_of_measure IS NOT NULL and x_quantity > 0 THEN
6042            PO_UOM_S.uom_convert (x_quantity,
6043                                  nvl(x_shipment_uom, interface.unit_meas_lookup_code),
6044                                  interface.item_id,
6045                                  x_secondary_unit_of_measure ,
6046                                  x_secondary_quantity) ;
6047          ELSE
6048            X_secondary_quantity := NULL;
6049          END IF;
6050       ELSE
6051            X_secondary_quantity := interface.secondary_quantity;
6052            X_secondary_unit_of_measure := interface.secondary_unit_of_measure;
6053       END IF;
6054     ELSE
6055        X_secondary_quantity := null;
6056        X_secondary_unit_of_measure := null;
6057     END IF;
6058     --<INVCONV R12 END>
6059 
6060      INSERT INTO po_line_locations_all  --<Shared Proc FPJ>
6061              (line_location_id,
6062               last_update_date,
6063               last_updated_by,
6064               po_header_id,
6065               creation_date,
6066               created_by,
6067               last_update_login,
6068               po_line_id,
6069               quantity,
6070               quantity_received,
6071               quantity_accepted,
6072               quantity_rejected,
6073               quantity_billed,
6074               quantity_cancelled,
6075               amount,                                         -- <SERVICES FPJ>
6076               amount_received,                                -- <SERVICES FPJ>
6077               amount_accepted,                                -- <SERVICES FPJ>
6078               amount_rejected,                                -- <SERVICES FPJ>
6079               amount_billed,                                  -- <SERVICES FPJ>
6080               amount_cancelled,                               -- <SERVICES FPJ>
6081               ship_to_location_id,
6082               need_by_date,
6083               promised_date,
6084               from_header_id,
6085               from_line_id,
6086               --togeorge 09/27/2000
6087         --added note to receiver column
6088         note_to_receiver,
6089               approved_flag,
6090               po_release_id,
6091               closed_code,
6092               closed_reason,
6093               price_override,
6094               encumbered_flag,
6095               shipment_type,
6096               shipment_num,
6097               inspection_required_flag,
6098               receipt_required_flag,
6099               days_early_receipt_allowed,
6100               days_late_receipt_allowed,
6101               enforce_ship_to_location_code,
6102               ship_to_organization_id,
6103               invoice_close_tolerance,
6104               receive_close_tolerance,
6105               accrue_on_receipt_flag,
6106               allow_substitute_receipts_flag,
6107               receiving_routing_id,
6108               qty_rcv_tolerance,
6109               qty_rcv_exception_code,
6110               receipt_days_exception_code,
6111         terms_id,
6112               ship_via_lookup_code,
6113         freight_terms_lookup_code,
6114         fob_lookup_code,
6115         unit_meas_lookup_code,
6116               last_accept_date, -- zxzhang, Mar 04
6117               match_option,   -- bgu, Dec. 7, 98
6118         country_of_origin_code, --frkhan 1/12/99
6119 -- start of 1548597
6120               secondary_unit_of_measure,
6121               secondary_quantity,
6122               preferred_grade,
6123               secondary_quantity_received,
6124               secondary_quantity_accepted,
6125               secondary_quantity_rejected,
6126               secondary_quantity_cancelled,
6127 -- end of 1548597
6128               vmi_flag,  -- VMI FPH
6129               drop_ship_flag,   --  <DropShip FPJ>
6130               consigned_flag,  -- CONSIGNED FPI
6131               transaction_flow_header_id, --<Shared Proc FPJ>
6132               org_id  --<Shared Proc FPJ>
6133               --<DBI Req Fulfillment 11.5.11 Start >
6134               , closed_for_receiving_date
6135               , closed_for_invoice_date
6136               --<DBI Req Fulfillment 11.5.11 End >
6137               -- <Complex Work R12 Start>
6138               , value_basis
6139               , matching_basis
6140               -- <Complex Work R12 End>
6141         , outsourced_assembly --<SHIKYU R12>
6142         ,tax_attribute_update_code --<eTax Integration R12>
6143               )
6144        VALUES (x_line_location_id,
6145                interface.last_update_date,
6146                interface.last_updated_by,
6147                interface.po_header_id,
6148                interface.creation_date,
6149                interface.created_by,
6150                interface.last_update_login,
6151                x_po_line_id,
6152                x_quantity, --interface.quantity,
6153                0,
6154                0,
6155                0,
6156                0,
6157                0,
6158                interface.amount,    -- amount                 -- <SERVICES FPJ>
6159                0,                   -- amount_received        -- <SERVICES FPJ>
6160                0,                   -- amount_accepted        -- <SERVICES FPJ>
6161                0,                   -- amount_rejected        -- <SERVICES FPJ>
6162                0,                   -- amount_billed          -- <SERVICES FPJ>
6163                0,                   -- amount_cancelled       -- <SERVICES FPJ>
6164                x_ship_to_location_id,
6165                interface.need_by_date,
6166                l_promised_date,     --<Bug# 3293109>
6167                interface.from_header_id,
6168                interface.from_line_id,
6169                --togeorge 09/27/2000
6170          --added note to receiver column
6171          interface.note_to_receiver,
6172                decode(g_document_type, 'RFQ', '', 'N'),
6173                decode(g_document_subtype,'RELEASE',x_po_release_id,''),
6174                decode(interface.consigned_flag, 'Y', 'CLOSED FOR INVOICE' ,                    -- CONSIGNED FPI
6175                   decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'CLOSED FOR RECEIVING'  ,   -- CONSIGNED FPI
6176                   decode(g_document_type, 'RFQ', '', 'OPEN'))),
6177                x_closed_reason,                                                                  -- CONSIGNED FPI
6178  /* Bug: 2000367 When there is no currency conversion involved we should not
6179                  round at all because it gives rise to inconsistency.
6180                  So removing the ext precision and blind rounding to 5 also as
6181                  this is already done above in case when currency conversion is
6182                  involved.
6183 */
6184                nvl(x_price,interface.unit_price),
6185                decode(g_document_type, 'RFQ', '', 'N'),
6186                decode(g_document_type, 'RFQ', 'RFQ',
6187       Decode(interface.document_subtype,
6188                       'RELEASE','BLANKET',
6189                       interface.document_subtype)),
6190                interface.shipment_num,
6191 
6192                decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'N' , -- CONSIGNED FPI
6193                       decode(interface.consigned_flag, 'Y', 'N',  --bug 2861408
6194                         decode(interface.drop_ship_flag, 'Y', 'N',  --bug 3330748
6195                           decode(x_order_type_lookup_code,'FIXED PRICE','N','RATE','N',--bug 3483786
6196                              decode(g_document_type, 'RFQ',
6197                         nvl(item.inspection_required_flag,
6198                    nvl(params.inspection_required_flag,'N')),
6199                         nvl(item.inspection_required_flag,
6200                    nvl(vendor.inspection_required_flag,
6201                     nvl(params.inspection_required_flag,'N')))))
6202                                    )
6203                             )
6204                      ),
6205                decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'N' , -- CONSIGNED FPI
6206                       decode(interface.consigned_flag, 'Y', 'N', --bug 2861408
6207                              decode(g_document_type, 'RFQ',
6208                                     nvl(item.receipt_required_flag,
6209                          nvl(interface.receipt_required_flag,
6210                     nvl(params.receiving_flag,'N'))),
6211                   nvl(item.receipt_required_flag,
6212                          nvl(interface.receipt_required_flag,
6213               nvl(vendor.receipt_required_flag,
6214                nvl(params.receiving_flag,'N'))))
6215                                     )
6216                              )
6217                       ),
6218                decode(g_document_type, 'RFQ', '',
6219       rc.days_early_receipt_allowed),
6220                decode(g_document_type, 'RFQ', '',
6221       rc.days_late_receipt_allowed),
6222                decode(g_document_type, 'RFQ', '',
6223       rc.enforce_ship_to_location_code),
6224                interface.destination_organization_id, -- ship to org
6225                decode(interface.consigned_flag, 'Y', 100 , -- CONSIGNED FPI
6226                       (decode(g_document_type, 'RFQ', '',
6227                       (decode(interface.pcard_id, NULL,
6228                               nvl(item.invoice_close_tolerance,
6229                               params.invoice_close_tolerance), 100))))),
6230                decode(g_interface_source_code,'CONSUMPTION_ADVICE', 100 , -- CONSIGNED FPI
6231                      (decode(g_document_type, 'RFQ', '',
6232       nvl(item.receive_close_tolerance,
6233       params.receive_close_tolerance)))),
6234 /** BUG 843414, bgu, Mar. 23, 1999
6235  *  "Accrue on Receipt" should not be allowed for P-card
6236  *  orders because of accounting restrictions.
6237  */
6238               decode(interface.transaction_flow_header_id, NULL,  --<Shared Proc FPJ>
6239                decode(interface.consigned_flag, 'Y', 'N' , -- CONSIGNED FPI
6240                   decode(g_document_type, 'RFQ', '',
6241                     DECODE( interface.pcard_id, NULL,
6242           DECODE(interface.destination_type_code,
6243                       'EXPENSE',DECODE(nvl(item.receipt_required_flag,
6244                                            nvl(interface.receipt_required_flag,
6245              nvl(vendor.receipt_required_flag,
6246              nvl(params.receiving_flag,'N')))),
6247                                         'N', 'N',
6248                                         DECODE(params.expense_accrual_code,
6249                                                'PERIOD END', 'N', 'Y')),
6250                       'Y'),'N'))), 'Y'),    --<Shared Proc FPJ>
6251                decode(g_document_type, 'RFQ','',
6252       rc.allow_substitute_receipts_flag),
6253                decode(g_document_type, 'RFQ', '',
6254       rc.receiving_routing_id),
6255                rc.qty_rcv_tolerance,
6256                rc.qty_rcv_exception_code,
6257                decode(g_document_type, 'RFQ', '',
6258       rc.receipt_days_exception_code),
6259          decode(g_document_type, 'RFQ', interface.terms_id, ''),
6260          decode(g_document_type, 'RFQ', interface.ship_via_lookup_code,
6261       ''),
6262          decode(g_document_type, 'RFQ',
6263       interface.freight_terms_lookup_code, ''),
6264          decode(g_document_type, 'RFQ',
6265       interface.fob_lookup_code, ''),
6266          /* Bug 3913683 : we want to import the unit measure lookup code for
6267                           all document types and not just RFQ's so commenting out
6268         below decode. */
6269          /*   decode(g_document_type, 'RFQ',
6270       interface.unit_meas_lookup_code), */
6271       -- bug 5208159
6272       nvl(x_po_uom,interface.unit_meas_lookup_code),
6273     -- Bug 3496450. Based the defaulting on promised date going
6274                 --     into the database rather than needby date. Put a to_date
6275                 --     around null so that decode returns date and does not
6276                 --     truncate time information
6277                decode(g_document_type,'RFQ',to_date(null),l_promised_date+rc.days_late_receipt_allowed),
6278                decode(g_interface_source_code,'CONSUMPTION_ADVICE', 'P' , -- CONSIGNED FPI
6279                       decode(interface.consigned_flag, 'Y', 'P', --bug 2861408
6280                              decode(g_document_type, 'RFQ', '',           --bgu, Dec. 7, 98
6281                   vendor.invoice_match_option)
6282                             )
6283                      ),
6284          x_country_of_origin_code,
6285 --<INVCONV R12> replace interface.secondary_unit_of_measure/secondary quantity with variables.
6286 -- also replace in the decode
6287 -- start of 1548597
6288                x_secondary_unit_of_measure,
6289                x_secondary_quantity,
6290                interface.preferred_grade,
6291                decode(x_secondary_unit_of_measure,NULL,NULL,0),
6292                decode(x_secondary_unit_of_measure,NULL,NULL,0),
6293                decode(x_secondary_unit_of_measure,NULL,NULL,0),
6294                decode(x_secondary_unit_of_measure,NULL,NULL,0),
6295 -- end of 1548597
6296                interface.vmi_flag ,  -- VMI FPH
6297                interface.drop_ship_flag,   --  <DropShip FPJ>
6298                interface.consigned_flag,  -- CONSIGNED FPI
6299                interface.transaction_flow_header_id, --<Shared Proc FPJ>
6300                g_purchasing_ou_id            --<Shared Proc FPJ>
6301                --<DBI Req Fulfillment 11.5.11 Start >
6302                , decode(g_interface_source_code,'CONSUMPTION_ADVICE',
6303                         sysdate,null)   --- Closed_for_receiving_date
6304                , decode(interface.consigned_flag, 'Y',
6305                          sysdate,null )  --- Closed_for_invoice_date
6306                --<DBI Req Fulfillment 11.5.11 End >
6307               -- <Complex Work R12 Start>
6308               , x_order_type_lookup_code
6309               , l_matching_basis
6310               -- <Complex Work R12 End>
6311         , p_outsourced_assembly --<SHIKYU R12>
6312         , nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax Integration R12>
6313 );
6314     l_progress := '260';
6315     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6316         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6317                             p_token    => l_progress,
6318                             p_message  => 'Create shipment: After insert into po line locations');
6319     END IF;
6320 
6321    -- Bug 882050: Shipment level global attribute
6322 if g_document_type = 'RFQ' then
6323 null;
6324 elsif (interface.document_subtype = 'STANDARD' or
6325        interface.document_subtype = 'PLANNED') THEN
6326 
6327         calculate_local('PO', 'SHIPMENT', x_line_location_id);
6328    elsif (g_document_subtype='RELEASE') THEN
6329 
6330         calculate_local('RELEASE', 'SHIPMENT', x_line_location_id);
6331    end if;
6332 
6333 
6334     l_progress := '270';
6335       /*
6336       ** 9/10/97 ecso
6337       ** OE Callback function for maintaining so_drop_ship_sources table
6338       */
6339    --<SOURCING TO PO FPH>
6340     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6341         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6342                             p_token    => l_progress,
6343                             p_message  => 'Sourcing to FPH-4 starts');
6344     END IF;
6345 
6346    --No need to update oe tables when requisition line id is null,negotiation
6347    --lines would not result in a drop ship PO
6348    if interface.requisition_line_id is not null then
6349    IF (g_document_type = 'PO') THEN
6350   x_p_api_version     := 1.0; -- as requested by OE
6351   x_p_line_location_id    := x_line_location_id;
6352 
6353     l_progress := '280';
6354   BEGIN
6355    SELECT PO_HEADER_ID
6356     ,PO_LINE_ID
6357    INTO x_p_po_header_id
6358     ,x_p_po_line_id
6359    FROM   PO_LINE_LOCATIONS_ALL  --<Shared Proc FPJ>
6360    WHERE  LINE_LOCATION_ID = x_line_location_id;
6361         EXCEPTION
6362                WHEN NO_DATA_FOUND THEN
6363                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6364                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6365                                             p_token    => l_progress,
6366                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
6367                     END IF;
6368          WHEN OTHERS THEN
6369                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6370                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6371                                             p_token    => l_progress,
6372                                             p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
6373                     END IF;
6374         END;
6375 
6376     l_progress := '290';
6377   BEGIN
6378      SELECT requisition_header_id
6379      INTO   x_p_req_header_id
6380      FROM   po_requisition_lines_all  --<Shared Proc FPJ>
6381    WHERE  requisition_line_id = interface.requisition_line_id;
6382         EXCEPTION
6383                WHEN NO_DATA_FOUND THEN
6384                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6385                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6386                                         p_token    => l_progress,
6387                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
6388                 END IF;
6389          WHEN OTHERS THEN
6390                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6391                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6392                                         p_token    => l_progress,
6393                                         p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
6394                 END IF;
6395         END;
6396 
6397   IF g_document_subtype = 'RELEASE' THEN
6398    x_p_po_release_id := g_po_release_id;
6399   ELSE
6400    x_p_po_release_id := '';
6401   END IF;
6402 
6403     l_progress := '300';
6404   oe_drop_ship_grp.update_po_info(x_p_api_version,
6405           x_p_return_status,
6406           x_p_msg_count,
6407           x_p_msg_data,
6408           x_p_req_header_id,
6409           interface.requisition_line_id,
6410           x_p_po_header_id,
6411           x_p_po_line_id,
6412           x_p_line_location_id,
6413           x_p_po_release_id
6414           );
6415 
6416     l_progress := '310';
6417     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6418         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6419                             p_token    => l_progress,
6420                             p_message  => 'Sourcing to FPH-4 ends');
6421     END IF;
6422    --<SOURCING TO PO FPH End>
6423 
6424    END IF; /* end of OE callback for PO */
6425    end if;
6426    --
6427   END IF;
6428 
6429   l_progress := '320';
6430 
6431   IF (g_document_type = 'PO') THEN
6432 
6433     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6434         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6435                             p_token    => l_progress,
6436                             p_message  => 'Create shipment: Before calling create_distribution');
6437     END IF;
6438     create_distributions(
6439       x_po_line_id,
6440       x_line_location_id,
6441       x_po_release_id,
6442       p_rate_for_req_fields -- <ACHTML R12>
6443     );
6444 
6445   END IF;
6446 
6447     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6448         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
6449     END IF;
6450 
6451 EXCEPTION
6452   WHEN OTHERS THEN
6453      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
6454          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
6455                             p_progress => l_progress);
6456      END IF;
6457      wrapup(interface.interface_header_id);
6458      po_message_s.sql_error('CREATE_SHIPMENTS',l_progress,sqlcode);
6459      raise;
6460 END create_shipment;
6461 
6462 /* ============================================================================
6463      NAME: CREATE_DISTRIBUTION
6464      DESC: Create document distribution
6465      ARGS: IN : x_requisition_line_id IN number
6466            IN : x_po_line_id IN number
6467            IN : x_Line_location_id IN number
6468            IN : x_po_release_id IN number
6469      ALGR:
6470 
6471    ==========================================================================*/
6472 PROCEDURE create_distributions(
6473   x_po_line_id IN number,
6474   x_line_location_id IN number,
6475   x_po_release_id IN number,
6476   p_rate_for_req_fields IN NUMBER -- <ACHTML R12>
6477   )
6478 IS
6479 x_distribution_num number;
6480 x_po_distribution_id number;
6481 x_gl_date_option varchar2(25);
6482 x_po_appl_id number;
6483 x_gl_appl_id number;
6484 x_sob_id    number;
6485 /* obtain currency info to adjust precision */
6486 x_precision         number := 2;
6487 x_ext_precision     number := 5;
6488 x_min_unit          number :='';
6489 x_order_type_lookup_code varchar2(15);
6490 
6491 x_kanban_card_id  number:='';
6492 x_accrued_flag          varchar2(1);
6493 x_po_uom                varchar2(25):=null;
6494 x_uom_convert           varchar2(2) := fnd_profile.value('PO_REQ_BPA_UOM_CONVERT');
6495 x_conversion_rate       number := 1;
6496 
6497 -- Bug 7661419, No conversion for same currency.
6498 x_req_rate              PO_REQUISITION_LINES_ALL.rate%TYPE;
6499 x_req_currency_code     PO_REQUISITION_LINES_ALL.currency_code%TYPE;
6500 x_rate                  PO_REQUISITION_LINES_ALL.rate%TYPE;
6501 -- Bug 7661419 end
6502 -- <SERVICES FPJ START>
6503 --
6504 l_uom_conversion_rate        MTL_UOM_CONVERSIONS.conversion_rate%TYPE := 1;
6505 l_currency_conversion_rate   PO_HEADERS_ALL.rate%TYPE := 1;
6506 --
6507 -- <SERVICES FPJ END>
6508 
6509 /* Bug 1030123: cursor to get all the distributions based on the line id */
6510 
6511 l_api_name CONSTANT VARCHAR2(30) := 'create_distributions';
6512 
6513 cursor c_dist is
6514   select po_distribution_id
6515     from po_distributions_all  --<Shared Proc FPJ>
6516    where line_location_id = x_line_location_id;
6517 
6518 --<MRC FPJ Start>
6519 l_key NUMBER;
6520 l_return_status VARCHAR2(1);
6521 l_msg_data VARCHAR2(2000);
6522 l_msg_count NUMBER;
6523 --<MRC FPJ End>
6524 
6525 l_progress VARCHAR2(3) := '000';                    --< Bug 3210331 >
6526 
6527 
6528 l_amount_ordered  NUMBER; --!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
6529 l_drop_ship_flag   po_line_locations.drop_ship_flag%type; --bug#3603067
6530 -- bug 5208159
6531 l_from_type_lookup_code po_headers_all.TYPE_LOOKUP_CODE%type;
6532 
6533 --introduced to hold the value of drop_ship_flag for shipments
6534 BEGIN
6535     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6536         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
6537         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6538                             p_token    => l_progress,
6539                             p_message  => 'Create_distributions: po_line_id: '||x_po_line_id);
6540         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6541                             p_token    => l_progress,
6542                             p_message  => 'Create_distributions: po_line_loc_id: '||x_line_location_id);
6543         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6544                             p_token    => l_progress,
6545                             p_message  => 'Create_distributions: po_release_id: '||x_po_release_id);
6546     END IF;
6547 
6548     /*
6549     ** get previous max distribution number for this shipment
6550     */
6551     l_progress:='010';
6552     SELECT nvl(max(distribution_num), 0)
6553       INTO x_distribution_num
6554       FROM po_distributions_all  --<Shared Proc FPJ>
6555      WHERE line_location_id = x_line_location_id;
6556 
6557     l_progress:='020';
6558     fnd_profile.get('PO_AUTOCREATE_DATE',x_gl_date_option);
6559 
6560      /* Bug 482648 ecso 4/30/97
6561       * Move quantity conversion from setup_interface_tables
6562       * to create_distribution for consistency
6563       */
6564 
6565     l_progress := '030';
6566     SELECT order_type_lookup_code
6567     INTO   x_order_type_lookup_code
6568     FROM   po_line_types
6569     WHERE  line_type_id = interface.line_type_id;
6570 
6571     l_progress := '040';
6572     SELECT set_of_books_id
6573       INTO x_sob_id
6574       FROM financials_system_params_all  --<Shared Proc FPJ>
6575      WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
6576 
6577 
6578     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6579         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6580                             p_token    => l_progress,
6581                             p_message  => 'Create_distributions: Order type: '||x_order_type_lookup_code);
6582     END IF;
6583 
6584     -- <BUG 3422146> Removed IF condition so that we will always get the
6585     -- the precision/extended precision information for the PO currency.
6586     --
6587      -- Bug 4471683: added not null check for currency
6588     IF interface.h_currency_code IS NOT NULL THEN
6589       FND_CURRENCY.get_info ( currency_code => interface.h_currency_code -- IN
6590                           , precision     => x_precision               -- OUT
6591                           , ext_precision => x_ext_precision           -- OUT
6592                           , min_acct_unit => x_min_unit                -- OUT
6593                           );
6594     END IF;
6595 
6596     l_progress := '050';
6597 
6598    /* R11: Enhancement to support Kanban
6599     * ecso 8/29/97
6600     * Kanban_Card_Id is copied from requisition line
6601     * to po_distributions
6602     */
6603   --<SOURCING TO PO FPH>
6604   --Even sourcing need to execute this when backed by a req.
6605     Begin
6606       SELECT KANBAN_CARD_ID
6607       INTO   x_kanban_card_id
6608       FROM   po_requisition_lines_all pol  --<Shared Proc FPJ>
6609       WHERE  pol.REQUISITION_LINE_ID = interface.requisition_line_id;
6610     Exception
6611          WHEN NO_DATA_FOUND THEN
6612      /* Not all req has kanban id */
6613             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6614                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6615                                     p_token    => l_progress,
6616                                     p_message  => 'NO_DATA_FOUND: '||SQLERRM);
6617             END IF;
6618          WHEN OTHERS THEN
6619             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
6620                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
6621                                    p_progress => l_progress);
6622             END IF;
6623            raise;
6624     End;
6625 
6626 /* 661570 - svaidyan : Use nvl(x_ext_precision,5) for rounding the qty
6627                        if the order type lookup code is not quantity */
6628 
6629 /** BUG 843414,  bgu, Apr. 23, 1999
6630  *  For Pcard PO or release, set the accrued_flag to yes, such that Receipt Accruals
6631  *  - Period-End Process will not accrue pcard related receipts.
6632  */
6633 if(interface.pcard_id is not null) then
6634   x_accrued_flag := 'Y';
6635 else
6636   x_accrued_flag := 'N';
6637 end if;
6638 
6639     l_progress:='060';
6640 
6641 /* 875315 - csheu: if the gl_date_option is not 'REQ GL DATE'
6642             then we need to make sure the period_name is not NULL
6643             even the period may not be opened */
6644 
6645 /* also use fnd_application table to find the application_id */
6646     SELECT application_id
6647     INTO   x_po_appl_id
6648     FROM   fnd_application
6649     WHERE  application_short_name = 'PO';
6650 
6651     l_progress := '070';
6652     SELECT application_id
6653     INTO   x_gl_appl_id
6654     FROM   fnd_application
6655     WHERE  application_short_name = 'SQLGL';
6656 
6657 /* 973348, duplicate of 966370
6658    The following should be done only if the po encumbrance flag is yes
6659 */
6660 
6661     if ((params.po_encumbrance_flag = 'Y') and
6662         (x_gl_date_option <> 'REQ GL DATE') and
6663         (params.period_name IS NULL)) THEN
6664 
6665           l_progress := '080';
6666           SELECT PS1.period_name
6667            INTO   params.period_name
6668            FROM   GL_PERIOD_STATUSES PS1
6669            ,      GL_PERIOD_STATUSES PS2
6670            ,      GL_SETS_OF_BOOKS GSOB
6671            WHERE  PS1.application_id = x_gl_appl_id
6672            AND    PS1.set_of_books_id = params.sob_id
6673            AND    PS1.adjustment_period_flag = 'N'
6674            AND    trunc(sysdate) BETWEEN trunc(PS1.start_date)
6675                                  AND     trunc(PS1.end_date)
6676            AND    ps1.period_year <= gsob.latest_encumbrance_year
6677            AND    gsob.set_of_books_id = params.sob_id
6678            AND    PS1.period_name = PS2.period_name
6679            AND    PS2.application_id = x_po_appl_id
6680            AND    PS2.adjustment_period_flag = 'N'
6681            AND    PS2.set_of_books_id = params.sob_id;
6682     end if;
6683 
6684     /** Bug 1039361
6685      *  bgu, Oct. 22, 1999
6686      *  Port Bug 1030123 in r11 to r115
6687      *  need to put the NEXTVAL inside the insert as there may
6688      *  be more than one distribution.
6689      */
6690 
6691   /* Enh : 1660036 */
6692 
6693   -- bug 5208159 : Conversion of req UOM to Quotation UOM should always happen if the
6694   -- source document is a quote and profile 'PO: Convert Requisition UOM to Source Document UOM'
6695   -- should be ignored in that case
6696   IF (interface.from_line_id IS NOT NULL) AND (g_document_subtype = 'STANDARD') THEN
6697       l_progress := '085';
6698 
6699       BEGIN
6700 
6701         SELECT poh.type_lookup_code
6702         INTO   l_from_type_lookup_code
6703         FROM   po_headers_all poh
6704         WHERE poh.po_header_id=interface.from_header_id ;
6705 
6706       EXCEPTION
6707         WHEN OTHERS THEN
6708             IF g_debug_unexp THEN
6709                  PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
6710                                     p_progress => l_progress);
6711             END IF;
6712             po_message_s.sql_error('CREATE_LINE',l_progress,sqlcode);
6713             wrapup(interface.interface_header_id);
6714             raise;
6715       END;
6716   END IF;
6717 
6718   IF (nvl(x_uom_convert,'N') = 'Y' OR (l_from_type_lookup_code = 'QUOTATION')) THEN
6719   -- bug 5208159 end
6720 
6721    IF (g_document_subtype='RELEASE')
6722      -- Bug 2735840 Convert UOM when autocreating a PO that references a GA
6723      OR ((g_document_subtype='STANDARD')
6724          AND (interface.from_line_id is not null)) THEN
6725 
6726    /* get the uom from the PO . This will be used for uom conversion */
6727     BEGIN
6728       IF (g_document_subtype='RELEASE') THEN -- Bug 2735840
6729         l_progress := '090';
6730         select unit_meas_lookup_code
6731         into x_po_uom
6732         from po_lines_all pol ,  --<Shared Proc FPJ>
6733              po_headers_all poh  --<Shared Proc FPJ>
6734         where pol.po_header_id = poh.po_header_id
6735         and pol.po_header_id = interface.po_header_id
6736         and pol.line_num = interface.line_num;
6737       -- Bug 2735840 START
6738       ELSE -- Autocreating a PO that references a GA
6739         l_progress := '100';
6740         SELECT unit_meas_lookup_code
6741         INTO x_po_uom
6742         FROM po_lines_all
6743         WHERE po_line_id = interface.from_line_id;
6744       END IF; -- g_document_subtype
6745       -- Bug 2735840 END
6746 
6747         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6748             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6749                                 p_token    => l_progress,
6750                                 p_message  => 'Create_distributions: UOM is: '||x_po_uom);
6751         END IF;
6752      EXCEPTION
6753      WHEN OTHERS THEN
6754         IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
6755             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
6756                                p_progress => l_progress);
6757         END IF;
6758        po_message_s.sql_error('CREATE_DISTRIBUTIONS',l_progress,sqlcode);
6759        wrapup(interface.interface_header_id);
6760        raise;
6761     END;
6762 
6763     l_progress := '110';
6764    /* before inserting into the distributions table get the conversion rate to convert
6765       into the BPA uom if the uom's on the req and BPA are different .
6766       This conversion is done only if the Convert UOM  profile option is set to Yes. */
6767 
6768       if interface.unit_meas_lookup_code <> x_po_uom then
6769 
6770        x_conversion_rate := po_uom_s.po_uom_convert(interface.unit_meas_lookup_code,
6771                                               x_po_uom,
6772                                               interface.item_id);
6773       else
6774 
6775        x_conversion_rate := 1;
6776 
6777       end if;
6778       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6779           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6780                               p_token    => l_progress,
6781                               p_message  => 'Create_distributions: Conversion rate is: '||x_conversion_rate);
6782       END IF;
6783 
6784     END IF;
6785   END IF;
6786 
6787     l_progress := '120';
6788   --<SOURCING TO PO FPH START>
6789   --Dont insert distribution record if the various account_id s are
6790   --not defaulted for negotiation lines which are not backed by req for sourcing
6791     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6792         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6793                             p_token    => l_progress,
6794                             p_message  => 'Sourcing to FPH-5 starts');
6795     END IF;
6796   if (g_interface_source_code in ('SOURCING','CONSUMPTION_ADVICE') and  -- CONSIGNED FPI
6797      (interface.charge_account_id is null or
6798       interface.accrual_account_id is null or
6799       interface.variance_account_id is null or
6800       (interface.encumbered_flag='Y' and
6801        interface.budget_account_id is null))) then
6802       null;
6803   else
6804 
6805     l_uom_conversion_rate := x_conversion_rate;               -- <SERVICES FPJ>
6806     -- <ACHTML R12>
6807     l_currency_conversion_rate := p_rate_for_req_fields; -- <SERVICES FPJ>
6808 
6809     l_progress := '130';
6810 
6811   --<SOURCING TO PO FPH END>
6812 
6813 
6814     l_progress := '150';
6815     --<GRANTS FPJ START>
6816     --SQL WHAT: Update po_distributions_interface table with
6817     --          po_distribution_id's and distribution_num
6818 
6819     UPDATE po_distributions_interface
6820     SET    po_distribution_id = po_distributions_s.NEXTVAL,
6821            distribution_num = x_distribution_num + rownum
6822     WHERE  interface_header_id = interface.interface_header_id
6823            AND interface_line_id = interface.interface_line_id;
6824 
6825     l_progress := '160';
6826     update_award_distributions;
6827 
6828     --<GRANTS FPJ END>
6829 
6830     l_progress := '170';
6831     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
6832         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
6833                             p_token    => l_progress,
6834                             p_message  => 'Sourcing to FPH-5 ends and insert into distributions');
6835     END IF;
6836 
6837 --!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
6838 --bug#3603067 need to get the value of drop ship flag for the shipment
6839 begin
6840     select nvl(drop_ship_flag,'N') into l_drop_ship_flag
6841     from po_line_locations_all where
6842     line_location_id=x_line_location_id;
6843 exception
6844     when others then
6845   null;
6846 end;
6847 --bug#3603067
6848 
6849 BEGIN
6850 SELECT pdi.amount_ordered
6851 INTO   l_amount_ordered
6852 FROM po_distributions_interface pdi, po_line_locations_all poll
6853            WHERE pdi.interface_header_id = interface.interface_header_id
6854              AND pdi.interface_line_id = interface.interface_line_id
6855              AND poll.line_location_id = x_line_location_id;
6856 
6857 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'l_amount_ordered',l_amount_ordered);
6858 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'x_order_type_lookup_code',x_order_type_lookup_code);
6859 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'l_currency_conversion_rate',l_currency_conversion_rate);
6860 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'l_uom_conversion_rate',l_uom_conversion_rate);
6861 PO_DEBUG.debug_var(g_log_head||l_api_name, l_progress, 'x_precision',x_precision);
6862 
6863 
6864 EXCEPTION
6865     WHEN OTHERS THEN
6866         NULL;
6867 END;
6868 
6869 -- Bug 7661419, No conversion for same currency.
6870 BEGIN
6871 SELECT PRL.currency_code,
6872        Nvl(PRL.rate,1)
6873 INTO   x_req_currency_code,
6874        x_req_rate
6875 FROM   po_requisition_lines_all PRL
6876 WHERE  PRL.requisition_line_id = INTERFACE.requisition_line_id;
6877 
6878 EXCEPTION
6879     WHEN OTHERS THEN
6880         NULL;
6881 END;
6882 
6883 IF ( x_req_currency_code = INTERFACE.h_currency_code ) THEN
6884    x_rate:=x_req_rate;
6885 ELSE
6886    x_rate:= p_rate_for_req_fields;
6887 END IF;
6888 
6889 --!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
6890 
6891     INSERT INTO po_distributions_all  --<Shared Proc FPJ>
6892                 (po_distribution_id,
6893                  last_update_date,
6894                  last_updated_by,
6895                  po_header_id,
6896                  creation_date,
6897                  created_by,
6898                  last_update_login,
6899                  po_line_id,
6900                  line_location_id,
6901                  po_release_id,
6902                  req_distribution_id,
6903                  set_of_books_id,
6904                  code_combination_id,
6905                  deliver_to_location_id,
6906                  deliver_to_person_id,
6907                  quantity_ordered,
6908                  quantity_delivered,
6909                  quantity_billed,
6910                  quantity_cancelled,
6911                  amount_ordered,                              -- <SERVICES FPJ>
6912                  amount_delivered,                            -- <SERVICES FPJ>
6913                  amount_cancelled,                            -- <SERVICES FPJ>
6914                  amount_billed,                               -- <SERVICES FPJ>
6915                  rate_date,
6916                  rate,
6917                  accrued_flag,
6918                  encumbered_flag,
6919                  gl_encumbered_date,
6920                  gl_encumbered_period_name,
6921                  distribution_num,
6922                  destination_type_code,
6923                  destination_organization_id,
6924                  destination_subinventory,
6925                  budget_account_id,
6926                  accrual_account_id,
6927                  variance_account_id,
6928 
6929                  --< Shared Proc FPJ Start >
6930                  dest_charge_account_id,
6931                  dest_variance_account_id,
6932                  --< Shared Proc FPJ End >
6933 
6934                  wip_entity_id,
6935                  wip_line_id,
6936                  wip_repetitive_schedule_id,
6937                  wip_operation_seq_num,
6938                  wip_resource_seq_num,
6939                  bom_resource_id,
6940                  prevent_encumbrance_flag,
6941                  project_id,
6942                  task_id,
6943                  end_item_unit_number,
6944                  expenditure_type,
6945                  project_accounting_context,
6946                  destination_context,
6947                  expenditure_organization_id,
6948                  expenditure_item_date,
6949                  accrue_on_receipt_flag,
6950                  kanban_card_id,
6951                  tax_recovery_override_flag,  --<eTax Integration R12>
6952                  recovery_rate,
6953                  award_id,
6954                  --togeorge 09/27/2000
6955                  --added oke columns
6956                  oke_contract_line_id,
6957                  oke_contract_deliverable_id,
6958                  org_id,  --<Shared Proc FPJ>
6959                  distribution_type,  -- <Encumbrance FPJ>
6960                  tax_attribute_update_code,  --<eTax Integration R12>
6961                  interface_distribution_ref --<ECO 5373370>
6962                  )
6963           SELECT pdi.po_distribution_id, --<GRANTS FPJ>
6964                  interface.last_update_date,
6965                  interface.last_updated_by,
6966                  interface.po_header_id,
6967                  interface.creation_date,
6968                  interface.created_by,
6969                  interface.last_update_login,
6970                  x_po_line_id,
6971                  x_line_location_id,
6972                  decode(g_document_subtype,'RELEASE',x_po_release_id,''),
6973                  pdi.req_distribution_id,
6974                  nvl(x_sob_id, pdi.set_of_books_id), --<Bug 3692789>
6975                  pdi.charge_account_id,
6976                  pdi.deliver_to_location_id,
6977      --bug#3603067 if the drop_ship_flag is 'Y' then we
6978      --need to pass null
6979                  decode(l_drop_ship_flag,'Y',NULL,pdi.deliver_to_person_id),
6980 
6981                  -- <SERVICES FPJ START>
6982                  -- Bug 3472140: Changed precisions to 15
6983                  decode(
6984                    x_order_type_lookup_code,
6985                    'QUANTITY',
6986                    round((pdi.quantity_ordered * x_conversion_rate), 15),
6987                    'AMOUNT',
6988                    round(
6989                      (pdi.quantity_ordered
6990                       * x_conversion_rate
6991                       / x_rate), -- <ACHTML R12> -- Bug 7661419
6992                      nvl(x_ext_precision, 15)
6993                    ),
6994                    NULL
6995                  ),
6996                  -- <SERVICES FPJ END>
6997 
6998                  0,
6999                  0,
7000                  0,
7001 
7002                  -- <SERVICES FPJ START>
7003                  decode ( x_order_type_lookup_code          -- amount_ordered
7004                         , 'RATE'       ,round (   ( pdi.amount_ordered
7005                                                   * l_uom_conversion_rate
7006                                                   / l_currency_conversion_rate)
7007                                               , x_precision )
7008                         , 'FIXED PRICE',round (   ( pdi.amount_ordered
7009                                                   / l_currency_conversion_rate)
7010                                               , x_precision )
7011                                        ,NULL
7012                         ),
7013                  0,                                         -- amount_delivered
7014                  0,                                         -- amount_cancelled
7015                  0,                                         -- amount_billed
7016                  -- <SERVICES FPJ END>
7017 
7018                  pdi.rate_date,
7019                  pdi.rate,
7020      x_accrued_flag,
7021                  'N'
7022 
7023       --<Encumbrance FPJ>
7024       -- If Req encumbrance is on and the profile option requests
7025       -- that the Req's GL date be used, use the Req's GL date.
7026       -- Otherwise, if PO enc is on, use SYSDATE.
7027       --            if PO enc is not on, use NULL.
7028 
7029       -- gl_encumbered_date =
7030       ,  NVL(  DECODE(  params.req_encumbrance_flag
7031                      ,  'Y', DECODE(   x_gl_date_option
7032                                     ,  'REQ GL DATE', pdi.gl_encumbered_date
7033                                     ,  NULL
7034                                     )
7035                      ,  NULL
7036                      )
7037             ,  DECODE(  params.po_encumbrance_flag
7038                      ,  'Y', TRUNC(SYSDATE)
7039                      ,  NULL
7040                      )
7041             )
7042 
7043       -- gl_encumbered_period_name =
7044       ,  NVL(  DECODE(  params.req_encumbrance_flag
7045                      ,  'Y', DECODE(x_gl_date_option
7046                                  ,  'REQ GL DATE', pdi.gl_encumbered_period_name
7047                                  ,  NULL
7048                                  )
7049                      ,  NULL
7050                      )
7051             ,  DECODE(  params.po_encumbrance_flag
7052                      ,  'Y', params.period_name
7053                      ,  NULL
7054                      )
7055             )
7056 
7057              ,   pdi.distribution_num, --<GRANTS FPJ>
7058                  pdi.destination_type_code,
7059                  pdi.destination_organization_id,
7060                  pdi.destination_subinventory,
7061                  pdi.budget_account_id,
7062                  pdi.accrual_account_id,
7063                  pdi.variance_account_id,
7064 
7065                  --< Shared Proc FPJ Start >
7066                  -- Copy the receiving accounts from the interface table to
7067                  -- the PO table.
7068                  pdi.dest_charge_account_id,
7069                  pdi.dest_variance_account_id,
7070                  --< Shared Proc FPJ End >
7071 
7072                  pdi.wip_entity_id,
7073                  pdi.wip_line_id,
7074                  pdi.wip_repetitive_schedule_id,
7075                  pdi.wip_operation_seq_num,
7076                  pdi.wip_resource_seq_num,
7077                  pdi.bom_resource_id
7078                --<ENCUMBRANCE FPJ>
7079                -- prevent_encumbrance_flag =
7080                ,  DECODE(  pdi.destination_type_code
7081                         ,  g_dest_type_code_SHOP_FLOOR, 'Y'
7082                         ,  'N'
7083                         )
7084                ,  pdi.project_id,
7085                  pdi.task_id,
7086                  pdi.end_item_unit_number,
7087                  pdi.expenditure_type,
7088                  pdi.project_accounting_context,
7089                  pdi.destination_context,
7090                  pdi.expenditure_organization_id,
7091                  pdi.expenditure_item_date,
7092                  decode(interface.transaction_flow_header_id, NULL, --<Shared Proc FPJ>
7093                         DECODE(interface.destination_type_code,
7094                                'EXPENSE',
7095                                decode(nvl(item.receipt_required_flag,
7096                                           nvl(interface.receipt_required_flag,
7097                                               nvl(vendor.receipt_required_flag,
7098                                                   nvl(params.receiving_flag,'N')))),
7099                                       'N', 'N',
7100                                       decode(params.expense_accrual_code,
7101                                              'PERIOD END', 'N', 'Y')),
7102                                'INVENTORY', 'Y',
7103                                'SHOP FLOOR', 'Y'),
7104                         'Y'), --<Shared Proc FPJ>
7105                  x_kanban_card_id,
7106                  pdi.tax_recovery_override_flag,  --<eTax integration R12>
7107                  decode(pdi.tax_recovery_override_flag, 'Y', pdi.recovery_rate, null),  --<eTax integration R12>
7108                  pdi.award_id,   -- OGM_0.0 changes..
7109                  --togeorge 09/27/2000
7110                  --added oke columns
7111                  interface.oke_contract_line_id,
7112                  interface.oke_contract_deliverable_id,
7113                  g_purchasing_ou_id,  --<Shared Proc FPJ>
7114                  poll.shipment_type,  -- <Encumbrance FPJ: join on poll.line_location_id added>
7115                  nvl2(g_calculate_tax_flag, 'CREATE', null), --<eTax integration R12>
7116                  pdi.interface_distribution_ref --<ECO 5373370>
7117             FROM po_distributions_interface pdi, po_line_locations_all poll
7118            WHERE pdi.interface_header_id = interface.interface_header_id
7119              AND pdi.interface_line_id = interface.interface_line_id
7120              AND poll.line_location_id = x_line_location_id;  --<Encumbrance FPJ>
7121 
7122 
7123     -- <BUG 3322948> Correct last distribution amount for any conversion and
7124     -- rounding inaccuracies to ensure that the distribution amounts add up
7125     -- to their corresponding shipment amount.
7126     --
7127     PO_INTERFACE_S.calibrate_last_dist_amount(x_line_location_id);
7128 
7129 
7130   end if;
7131     -- Bug 882050: Dist level global attribute
7132 
7133     l_progress := '210';
7134     /* Bug 1030123: Since there may be more than a distribution, we need to
7135        loop thru all the distribution based on the line id */
7136 
7137     begin
7138 
7139       open c_dist;
7140 
7141       loop
7142 
7143         fetch c_dist into x_po_distribution_id;
7144 
7145         exit when c_dist%NOTFOUND;
7146 
7147         if (interface.document_subtype = 'STANDARD' or
7148             interface.document_subtype = 'PLANNED') THEN
7149 
7150            l_progress := '220';
7151            calculate_local('PO', 'DISTRIBUTION', x_po_distribution_id);
7152         elsif (g_document_subtype='RELEASE') THEN
7153             l_progress := '230';
7154             calculate_local('RELEASE', 'DISTRIBUTION', x_po_distribution_id);
7155         end if;
7156       end loop;
7157 
7158       close c_dist;
7159 
7160     exception
7161       when others then
7162         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7163             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7164                                 p_token    => l_progress,
7165                                 p_message  => 'EXCEPTION caught; SQL Code is '||SQLCODE||'; Error is '||SQLERRM);
7166         END IF;
7167         if c_dist%ISOPEN then
7168           close c_dist;
7169         end if;
7170     end;
7171 
7172      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7173          PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
7174      END IF;
7175 
7176 EXCEPTION
7177   WHEN OTHERS THEN
7178      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
7179          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
7180                             p_progress => l_progress);
7181      END IF;
7182      wrapup(interface.interface_header_id);
7183      po_message_s.sql_error('CREATE_DISTRIBUTIONS',l_progress,sqlcode);
7184      raise;
7185 END create_distributions;
7186 
7187 
7188 ------------------------------------------------------------------<BUG 3322948>
7189 -------------------------------------------------------------------------------
7190 --Start of Comments
7191 --Name: calibrate_last_dist_amount
7192 --Pre-reqs:
7193 --  None.
7194 --Modifies:
7195 --  PO_DISTRIBUTIONS_ALL.AMOUNT_ORDERED
7196 --Locks:
7197 --  None.
7198 --Function:
7199 --  This procedure is used to calibrate the amount of the last distribution
7200 --  belonging to a particular PO Shipment. After going through UOM/currency
7201 --  conversion and rounding, there is a chance that the sum of the distribution
7202 --  amounts will not add up to the shipment amount, causing submission checks
7203 --  to fail. To correct this, we will recalculate the last distribution
7204 --  amount as the difference between the shipment amount and the sum of
7205 --  all other distribution amounts.
7206 --Parameters:
7207 --IN:
7208 --p_line_location_id
7209 --  ID belonging to parent shipment of the distributions which need to be
7210 --  calibrated.
7211 --Testing:
7212 --  None.
7213 --End of Comments
7214 -------------------------------------------------------------------------------
7215 -------------------------------------------------------------------------------
7216 PROCEDURE calibrate_last_dist_amount
7217 (
7218     p_line_location_id   IN   NUMBER
7219 )
7220 IS
7221     l_api_name               VARCHAR2(30) := 'calibrate_last_dist_amount';
7222     l_log_head               VARCHAR2(100) := g_log_head || l_api_name;
7223     l_progress               VARCHAR2(3);
7224 
7225     l_sum_dist_amounts       PO_DISTRIBUTIONS_ALL.amount_ordered%TYPE;
7226     l_last_dist_amount       PO_DISTRIBUTIONS_ALL.amount_ordered%TYPE;
7227     l_last_distribution_id   PO_DISTRIBUTIONS_ALL.po_distribution_id%TYPE;
7228     l_shipment_amount        PO_LINE_LOCATIONS_ALL.amount%TYPE;
7229 
7230 BEGIN
7231 
7232 l_progress:='000'; PO_DEBUG.debug_begin(l_log_head);
7233 l_progress:='010'; PO_DEBUG.debug_var(l_log_head,l_progress,'p_line_location_id',p_line_location_id);
7234 
7235     -- Retrieve Distribution Data =============================================
7236     --
7237     -- Get the sum of all distribution amounts
7238     -- and the ID of the last distribution.
7239     --
7240     SELECT sum(amount_ordered)
7241     ,      max(po_distribution_id)
7242     INTO   l_sum_dist_amounts
7243     ,      l_last_distribution_id
7244     FROM   po_distributions_all
7245     WHERE  line_location_id = p_line_location_id;
7246 
7247 l_progress:='020'; PO_DEBUG.debug_var(l_log_head,l_progress,'l_sum_dist_amounts',l_sum_dist_amounts);
7248 l_progress:='030'; PO_DEBUG.debug_var(l_log_head,l_progress,'l_last_distribution_id',l_last_distribution_id);
7249 
7250 
7251     -- Get the shipment amount ================================================
7252     --
7253     SELECT amount
7254     INTO   l_shipment_amount
7255     FROM   po_line_locations_all
7256     WHERE  line_location_id = p_line_location_id;
7257 
7258 l_progress:='040'; PO_DEBUG.debug_var(l_log_head,l_progress,'l_shipment_amount',l_shipment_amount);
7259 
7260 
7261     -- Correct the last distribution ==========================================
7262     --
7263     -- Set it to the shipment amount minus the sum of all distribution
7264     -- amounts (except the last distribution).
7265     --
7266     UPDATE    po_distributions_all
7267     SET       amount_ordered = l_shipment_amount - (l_sum_dist_amounts - amount_ordered)
7268     WHERE     po_distribution_id = l_last_distribution_id
7269     RETURNING amount_ordered
7270     INTO      l_last_dist_amount;
7271 
7272 l_progress:='050'; PO_DEBUG.debug_var(l_log_head,l_progress,'l_last_dist_amount',l_last_dist_amount);
7273 
7274     --=========================================================================
7275 
7276 l_progress:='060'; PO_DEBUG.debug_end(l_log_head);
7277 
7278 EXCEPTION
7279 
7280     WHEN OTHERS THEN
7281         PO_DEBUG.debug_exc ( p_log_head => l_log_head
7282                            , p_progress => l_progress);
7283         RAISE;
7284 
7285 END calibrate_last_dist_amount;
7286 
7287 -- <Complex Work R12 Start>
7288 -------------------------------------------------------------------------------
7289 --Start of Comments
7290 --Name: calibrate_last_dist_quantity
7291 --Pre-reqs:
7292 --  None.
7293 --Modifies:
7294 --  PO_DISTRIBUTIONS_ALL.QUANTITY_ORDERED
7295 --Locks:
7296 --  None.
7297 --Function:
7298 --  This procedure is used to calibrate the quantity of the last distribution
7299 --  belonging to a particular PO Shipment. After going through UOM/currency
7300 --  conversion and rounding, there is a chance that the sum of the distribution
7301 --  quantitiess will not add up to the shipment qty, causing submission checks
7302 --  to fail. To correct this, we will recalculate the last distribution
7303 --  quantity as the difference between the shipment quantity and the sum of
7304 --  all other distribution quantities.
7305 --Parameters:
7306 --IN:
7307 --p_line_location_id
7308 --  ID belonging to parent shipment of the distributions which need to be
7309 --  calibrated.
7310 --Testing:
7311 --  None.
7312 --End of Comments
7313 -------------------------------------------------------------------------------
7314 -------------------------------------------------------------------------------
7315 PROCEDURE calibrate_last_dist_quantity(
7316    p_line_location_id   IN   NUMBER
7317 )
7318 IS
7319 
7320 d_module   VARCHAR2(70) := 'po.plsql.PO_INTERFACE_S.calibrate_last_dist_quantity';
7321 d_progress NUMBER;
7322 
7323 l_sum_dist_quantities       PO_DISTRIBUTIONS_ALL.quantity_ordered%TYPE;
7324 l_last_dist_id              PO_DISTRIBUTIONS_ALL.po_distribution_id%TYPE;
7325 l_last_dist_qty             PO_DISTRIBUTIONS_ALL.quantity_ordered%TYPE;
7326 l_shipment_quantity         PO_LINE_LOCATIONS_ALL.quantity%TYPE;
7327 
7328 BEGIN
7329 
7330   d_progress := 0;
7331 
7332   IF (PO_LOG.d_proc) THEN
7333     PO_LOG.proc_begin(d_module);
7334     PO_LOG.proc_begin(d_module, 'p_line_location_id', p_line_location_id);
7335   END IF;
7336 
7337   d_progress := 10;
7338 
7339   SELECT sum(pod.quantity_ordered), max(pod.po_distribution_id)
7340   INTO l_sum_dist_quantities, l_last_dist_id
7341   FROM po_distributions_all pod
7342   WHERE pod.line_location_id = p_line_location_id;
7343 
7344   d_progress := 20;
7345 
7346   IF (PO_LOG.d_stmt) THEN
7347     PO_LOG.stmt(d_module, d_progress, 'l_last_dist_id', l_last_dist_id);
7348   END IF;
7349 
7350   SELECT poll.quantity
7351   INTO l_shipment_quantity
7352   FROM po_line_locations_all poll
7353   WHERE poll.line_location_id = p_line_location_id;
7354 
7355   d_progress := 30;
7356 
7357   UPDATE po_distributions_all pod
7358   SET pod.quantity_ordered = l_shipment_quantity -
7359                               (l_sum_dist_quantities - pod.quantity_ordered)
7360   WHERE pod.po_distribution_id = l_last_dist_id
7361   RETURNING pod.quantity_ordered INTO l_last_dist_qty;
7362 
7363   IF (PO_LOG.d_proc) THEN
7364     PO_LOG.proc_end(d_module, 'l_last_dist_qty', l_last_dist_qty);
7365     PO_LOG.proc_end(d_module);
7366   END IF;
7367 
7368 EXCEPTION
7369   WHEN OTHERS THEN
7370     IF (PO_LOG.d_exc) THEN
7371       PO_LOG.exc(d_module, d_progress, SQLCODE||SQLERRM);
7372     END IF;
7373 
7374     RAISE;
7375 
7376 END calibrate_last_dist_quantity;
7377 -- <Complex Work R12 End>
7378 
7379 
7380 /* ============================================================================
7381      NAME: CREATE_RFQ
7382      DESC: Create/Add to RFQ from requisition data in the PO_HEADERS,LINES
7383            and DISTRIBUTION interface tables.
7384      ARGS: IN : x_interface_header_id IN number
7385      ALGR:
7386 
7387    ==========================================================================*/
7388 PROCEDURE create_rfq(x_interface_header_id IN number,
7389          x_document_id IN OUT NOCOPY number) IS
7390 
7391     x_quotation_class_code varchar2(25);
7392     x_document_num po_headers.segment1%type:=null; -- Bug 1093645
7393 
7394 l_api_name CONSTANT VARCHAR2(30) := 'create_documents';
7395 
7396 --<MRC FPJ Start>
7397 l_return_status VARCHAR2(1);
7398 l_msg_data VARCHAR2(2000);
7399 l_msg_count NUMBER;
7400 --<MRC FPJ End>
7401 l_progress VARCHAR2(3) := '000';                --< Bug 3210331 >
7402 
7403 BEGIN
7404     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7405         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
7406     END IF;
7407 
7408     get_system_defaults;
7409 
7410     l_progress := '010';
7411     -- populate the interface tables with data from the
7412     -- requisition.
7413     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7414         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7415                             p_token    => l_progress,
7416                             p_message  => 'Create_rfq: Before setup_interface_tables');
7417     END IF;
7418 
7419     -- <Complex Work R12 Start>: Pass in false for p_is_complex_work_po
7420     setup_interface_tables(
7421       x_interface_header_id => x_interface_header_id
7422     , x_document_id => x_document_id
7423     , p_is_complex_work_po => FALSE
7424     );
7425     -- <Complex Work R12 End>
7426 
7427     l_progress := '020';
7428     -- determine which interface lines and shipments should
7429     -- be grouped.
7430     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7431         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7432                             p_token    => l_progress,
7433                             p_message  => 'Create_rfq: Before group_interface_lines');
7434     END IF;
7435 
7436     group_interface_lines(
7437       x_interface_header_id => x_interface_header_id
7438     , p_is_complex_work_po  => FALSE
7439     );
7440 
7441     l_progress := '030';
7442     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7443         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7444                             p_token    => l_progress,
7445                             p_message  => 'Create_rfq: interface_hdr id '||x_interface_header_id);
7446     END IF;
7447 
7448     OPEN interface_cursor(x_interface_header_id);
7449 
7450     FETCH interface_cursor INTO interface;
7451 
7452     IF interface_cursor%notfound THEN
7453       CLOSE interface_cursor;
7454       RETURN;
7455     END IF;
7456 
7457     g_rate_for_req_fields := interface.h_rate;   -- <BUG 4895489>
7458 
7459     IF (g_mode = 'ADD') THEN
7460 
7461        l_progress := '040';
7462        UPDATE po_headers_all  --<Shared Proc FPJ>
7463           SET last_update_date  = interface.last_update_date,
7464               last_updated_by   = interface.last_updated_by,
7465               last_update_login = interface.last_update_login,
7466               status_lookup_code = 'I'
7467         WHERE po_header_id = interface.po_header_id;
7468     ELSE /* New */
7469 
7470         l_progress := '050';
7471   SELECT quotation_class_code
7472         INTO   x_quotation_class_code
7473         FROM   po_document_types
7474         WHERE  document_type_code = 'RFQ'
7475   and    document_subtype   = interface.quote_type_lookup_code;
7476 
7477         l_progress := '060';
7478     /** Bug 881882, bgu, Apr. 29, 1999
7479      *  For inserting record into po_headers view, it used
7480      *  to_date(interface.h_rate_date, 'DD/MM/YYYY') for column rate_date.
7481      *  But since the data type of interface.h_rate_date is already date,
7482      *  this is unneccssary and causing problem when system date mask is
7483      *  defined otherwise.
7484      */
7485         INSERT INTO po_headers_all  --<Shared Proc FPJ>
7486                   (po_header_id,
7487                    last_update_date,
7488                    last_updated_by,
7489                    segment1,
7490                    created_by,
7491                    last_update_login,
7492                    summary_flag,
7493                    enabled_flag,
7494                    type_lookup_code,
7495                    agent_id,
7496                    creation_date,
7497                    revision_num,
7498                    ship_to_location_id,
7499                    bill_to_location_id,
7500                    terms_id,
7501                    ship_via_lookup_code,
7502                    fob_lookup_code,
7503                    freight_terms_lookup_code,
7504                    status_lookup_code,
7505                    quotation_class_code,
7506                    quote_type_lookup_code,
7507        approval_required_flag,
7508        currency_code,
7509        rate_type,
7510        rate_date,
7511        rate,
7512                    org_id  --<Shared Proc FPJ>
7513                   ,style_id   --<R12 STYLES PHASE II >
7514                    )
7515             VALUES (interface.po_header_id,
7516                     interface.last_update_date,
7517                     interface.last_updated_by,
7518                     interface.document_num,
7519                     interface.created_by,
7520                     interface.last_update_login,
7521                     'N',
7522                     'Y',
7523                     g_document_type,
7524                     interface.agent_id,
7525                     interface.creation_date,
7526                     0,
7527                     nvl(vendor.ship_to_location_id,
7528                         interface.ship_to_location_id),
7529                     nvl(vendor.bill_to_location_id,
7530                         interface.bill_To_Location_Id),
7531                     nvl(vendor.terms_id,
7532                         interface.terms_id),
7533                     nvl(vendor.ship_via_lookup_code,
7534                         interface.ship_via_lookup_code),
7535                     nvl(vendor.fob_lookup_code,
7536                         interface.fob_lookup_code),
7537                     nvl(vendor.freight_terms_lookup_code,
7538                         interface.freight_terms_lookup_code),
7539                     'I',
7540                     x_quotation_class_code,
7541                     interface.quote_type_lookup_code,
7542         'N',
7543                     interface.h_currency_code,
7544                     interface.h_rate_type,
7545 --                    to_date(interface.h_rate_date, 'DD/MM/YYYY'),
7546         interface.h_rate_date,              -- Bug 881882 , bgu
7547                     interface.h_rate,
7548                     g_purchasing_ou_id  --<Shared Proc FPJ>
7549                     ,interface.style_id   --<R12 STYLES PHASE II >
7550                     );
7551 
7552     IF(interface.vendor_list_header_id is NOT NULL)THEN
7553 
7554         l_progress := '080';
7555 /* Bug 875124 :
7556    Using po_vendor_list_entries_v to insert into po_rfq_vendors
7557    as po_vendor_list_entries_v contains vendor_list with active vendors
7558 */
7559          INSERT INTO po_rfq_vendors
7560                      (po_header_id,
7561                       sequence_num,
7562                       last_update_date,
7563                       last_updated_by,
7564                       last_update_login,
7565                       creation_date,
7566                       created_by,
7567                       vendor_id,
7568                       vendor_site_id,
7569                       vendor_contact_id,
7570                       print_flag,
7571                       print_count)
7572                SELECT interface.po_header_id,
7573                       rownum,
7574                       interface.last_update_date,
7575                       interface.last_updated_by,
7576                       interface.last_update_login,
7577                       interface.creation_date,
7578                       interface.created_by,
7579                       vendor_id,
7580                       vendor_site_id,
7581                       vendor_contact_id,
7582                       'Y',
7583                       0
7584                  FROM po_vendor_list_entries_v
7585                 WHERE vendor_list_header_id = interface.vendor_list_header_id;
7586       END IF;
7587     END IF;/* of New */
7588 
7589     /* DEBUG Create the new lines  */
7590     l_progress:='090';
7591 
7592     -- <Complex Work R12 Start>: Pass in false for p_is_complex_work_po
7593     create_line(
7594       x_interface_header_id => x_interface_header_id
7595     , p_is_complex_work_po => FALSE
7596     );
7597     -- <Complex Work R12 End>
7598 
7599     l_progress := '100';
7600     LOOP
7601 
7602         FETCH interface_cursor INTO interface;
7603         EXIT WHEN interface_cursor%notfound;
7604 
7605         -- <Complex Work R12 Start>: Pass in false for p_is_complex_work_po
7606         create_line(
7607           x_interface_header_id => x_interface_header_id
7608         , p_is_complex_work_po => FALSE
7609         );
7610         -- <Complex Work R12 End>
7611 
7612     END LOOP;
7613 
7614 /* bug 1093645:code added to fix the deadlock issue in autocreate*/
7615     if (g_mode = 'NEW')  then
7616          IF (params.user_defined_rfq_num_code='AUTOMATIC') AND
7617             (g_document_type = 'RFQ') THEN
7618 
7619                l_progress := '110';
7620 
7621                -- bug5174177
7622                x_document_num :=
7623                  PO_CORE_SV1.default_po_unique_identifier
7624                  ( p_table_name => 'PO_HEADERS_RFQ',
7625                    p_org_id     => g_purchasing_ou_id
7626                  );
7627 
7628                IF g_debug_stmt THEN
7629                  PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
7630                             p_token    => l_progress,
7631                             p_message  => 'new po num = ' || x_document_num);
7632                END IF;
7633 
7634                l_progress := '130';
7635               UPDATE po_headers set segment1=x_document_num
7636               where po_header_id=x_document_id;
7637 
7638           END IF;
7639     END IF;
7640 
7641     l_progress := '140';
7642 
7643     wrapup(x_interface_header_id);
7644 
7645     l_progress := '150';
7646     CLOSE interface_cursor;
7647 
7648     COMMIT;
7649 
7650     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7651         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
7652     END IF;
7653 
7654 EXCEPTION
7655    WHEN OTHERS THEN
7656      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
7657          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
7658                             p_progress => l_progress);
7659      END IF;
7660      wrapup(x_interface_header_id);
7661 
7662      po_message_s.sql_error('CREATE_RFQ',l_progress,sqlcode);
7663      po_message_s.sql_show_error;
7664      po_message_s.clear;
7665      CLOSE interface_cursor;
7666      --togeorge 11/20/2001
7667      -- Bug 1349801
7668      -- Added a Rollback when a Exception was raised
7669      -- This Rollbacks all the Changes done when a Exception Condition was raised
7670      ROLLBACK;
7671 END create_rfq;
7672 
7673 /* ============================================================================
7674      NAME: GET_SYSTEM_DEFAULTS
7675      DESC: Get system defaults
7676      ARGS: None
7677      ALGR:
7678 
7679    ==========================================================================*/
7680 PROCEDURE get_system_defaults IS
7681 x_date date;
7682 l_api_name CONSTANT VARCHAR2(30) := 'get_system_defaults';  --< Bug 3210331 >
7683 l_progress VARCHAR2(3) := '000';                            --< Bug 3210331 >
7684 BEGIN
7685      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7686          PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
7687      END IF;
7688 
7689     /* Get WHO column values */
7690     who.user_id  := nvl(fnd_global.user_id,0);
7691     who.login_id := nvl(fnd_global.login_id,0);
7692     who.resp_id  := nvl(fnd_global.resp_id,0);
7693 
7694     l_progress:='010';
7695 
7696     /* Get system defaults */
7697     po_core_s.get_po_parameters(params.currency_code,
7698                                 params.coa_id,
7699                                 params.po_encumbrance_flag,
7700                                 params.req_encumbrance_flag,
7701                                 params.sob_id,
7702                                 params.ship_to_location_id,
7703                                 params.bill_to_location_id,
7704                                 params.fob_lookup_code,
7705                                 params.freight_terms_lookup_code,
7706                                 params.terms_id,
7707                                 params.default_rate_type,
7708                                 params.taxable_flag,
7709                                 params.receiving_flag,
7710                                 params.enforce_buyer_name_flag,
7711                                 params.enforce_buyer_auth_flag,
7712                                 params.line_type_id,
7713                                 params.manual_po_num_type,
7714                                 params.po_num_code,
7715                                 params.price_type_lookup_code,
7716                                 params.invoice_close_tolerance,
7717                                 params.receive_close_tolerance,
7718                                 params.security_structure_id,
7719                                 params.expense_accrual_code,
7720                                 params.inventory_organization_id,
7721                                 params.rev_sort_ordering,
7722                                 params.min_rel_amount,
7723                                 params.notify_blanket_flag,
7724                                 params.budgetary_control_flag,
7725                                 params.user_defined_req_num_code,
7726                                 params.rfq_required_flag,
7727                                 params.manual_req_num_type,
7728                                 params.enforce_full_lot_qty,
7729                                 params.disposition_warning_flag,
7730                                 params.reserve_at_completion_flag,
7731                                 params.user_defined_rcpt_num_code,
7732                                 params.manual_rcpt_num_type,
7733               params.use_positions_flag,
7734               params.default_quote_warning_delay,
7735                 params.inspection_required_flag,
7736                 params.user_defined_quote_num_code,
7737                 params.manual_quote_num_type,
7738                 params.user_defined_rfq_num_code,
7739                 params.manual_rfq_num_type,
7740                 params.ship_via_lookup_code,
7741 	        params.qty_rcv_tolerance,
7742 		params.acceptance_required_flag);    /* Bug 7518967 : Default Acceptance Required Check ER */
7743 
7744         l_progress:='020';
7745 
7746         IF(params.po_encumbrance_flag = 'Y') THEN
7747           po_core_s.get_period_name(params.sob_id,params.period_name,x_date);
7748         END IF;
7749 
7750      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7751          PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
7752      END IF;
7753 
7754 EXCEPTION
7755   WHEN OTHERS THEN
7756      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
7757          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
7758                             p_progress => l_progress);
7759      END IF;
7760      wrapup(interface.interface_header_id);
7761      po_message_s.sql_error('GET SYSTEM DEFAULTS',l_progress,sqlcode);
7762      raise;
7763 
7764 END get_system_defaults;
7765 
7766 /* ============================================================================
7767      NAME: GET_INVOICE MATCH OPTION
7768      DESC: Get invoice match option
7769      ARGS: None
7770      ALGR:
7771 
7772    ==========================================================================*/
7773 PROCEDURE get_invoice_match_option(x_vendor_id    IN number,
7774          x_vendor_site_id IN number,
7775          x_invoice_match_option OUT NOCOPY varchar2)
7776  IS
7777 l_progress VARCHAR2(3) := '000';                                --< Bug 3210331 >
7778 l_api_name CONSTANT VARCHAR2(30) := 'get_invoice_match_option'; --< Bug 3210331 >
7779 
7780 BEGIN
7781      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7782          PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
7783      END IF;
7784 
7785    if (X_vendor_site_id is not null) then
7786      l_progress := '010';
7787      /* Retrieve Invoice Match Option from Vendor site*/
7788      SELECT match_option
7789      INTO   x_invoice_match_option
7790      FROM   po_vendor_sites_all  --<Shared Proc FPJ>
7791      WHERE  vendor_site_id = X_vendor_site_id;
7792    end if;
7793 
7794    if(x_invoice_match_option is NULL) then
7795      /* Retrieve Invoice Match Option from Vendor */
7796      if (X_vendor_id is not null) then
7797        l_progress := '020';
7798        SELECT match_option
7799        INTO   x_invoice_match_option
7800        FROM   po_vendors
7801        WHERE  vendor_id = X_vendor_id;
7802      end if;
7803    end if;
7804 
7805    if(x_invoice_match_option is NULL) then
7806      l_progress := '030';
7807      --6057748
7808      -- Get default from ap_product_setup instead of FSP.
7809      SELECT aps.match_option
7810        INTO   x_invoice_match_option
7811        FROM   ap_product_setup aps;
7812 
7813      /* Retrieve Invoice Match Option from Financial System Parameters */
7814 /*
7815      SELECT fsp.match_option
7816        INTO x_invoice_match_option
7817        FROM financials_system_params_all fsp  --<Shared Proc FPJ>
7818       WHERE NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>*/
7819    end if;
7820 
7821      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
7822          PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
7823      END IF;
7824 EXCEPTION
7825   WHEN OTHERS THEN
7826      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
7827          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
7828                             p_progress => l_progress);
7829      END IF;
7830      wrapup(interface.interface_header_id);
7831      po_message_s.sql_error('GET INVOICE MATCH OPTION',l_progress,sqlcode);
7832      raise;
7833 
7834 END get_invoice_match_option;
7835 
7836 --< Shared Proc FPJ Start >
7837 ---------------------------------------------------------------------------
7838 --Start of Comments
7839 --Name: generate_shared_proc_accounts
7840 --Pre-reqs:
7841 --  The global variables g_document_type, g_document_subtype and params
7842 --  should have been populated correctly.
7843 --Modifies:
7844 --  PO_DISTRIBUTIONS_INTERFACE table. The following columns may get
7845 --  modified:
7846 --       CODE_COMBINATION_ID
7847 --       ACCRUAL_ACCOUNT_ID
7848 --       VARIANCE_ACCOUNT_ID
7849 --       BUDGET_ACCOUNT_ID
7850 --       DEST_CHARGE_ACCOUNT_ID
7851 --       DEST_VARIANCE_ACCOUNT_ID
7852 --Locks:
7853 --  None.
7854 --Function:
7855 --  Generates the accounts for shared procurement scenarios by calling
7856 --  the PO AG workflow. After that, it updates the affected records in
7857 --  PO_DISTRIBUTIONS_INTERFACE table with the new account ID's.
7858 --Parameters:
7859 --IN:
7860 --  p_interface_header_id -- The interface header ID of the document being
7861 --                           processed.
7862 --OUT:
7863 --  None
7864 --Testing:
7865 --End of Comments
7866 ---------------------------------------------------------------------------
7867 PROCEDURE generate_shared_proc_accounts --(
7868 (
7869   p_interface_header_id IN NUMBER
7870 )
7871 IS
7872   l_progress                  VARCHAR2(3) := '000';    --< Bug 3210331 >
7873   l_return_value          BOOLEAN;
7874   l_charge_success              BOOLEAN := TRUE;
7875   l_budget_success              BOOLEAN := TRUE;
7876   l_accrual_success             BOOLEAN := TRUE;
7877   l_variance_success            BOOLEAN := TRUE;
7878   l_charge_account_id           PO_DISTRIBUTIONS_INTERFACE.charge_account_id%TYPE;
7879   l_budget_account_id           PO_DISTRIBUTIONS_INTERFACE.budget_account_id%TYPE;
7880   l_accrual_account_id          PO_DISTRIBUTIONS_INTERFACE.accrual_account_id%TYPE;
7881   l_variance_account_id         PO_DISTRIBUTIONS_INTERFACE.variance_account_id%TYPE;
7882   l_charge_account_flex         VARCHAR2(2000);
7883   l_budget_account_flex         VARCHAR2(2000);
7884   l_accrual_account_flex  VARCHAR2(2000);
7885   l_variance_account_flex       VARCHAR2(2000);
7886   l_charge_account_desc         VARCHAR2(2000);
7887   l_budget_account_desc         VARCHAR2(2000);
7888   l_accrual_account_desc  VARCHAR2(2000);
7889   l_variance_account_desc       VARCHAR2(2000);
7890   l_wf_itemkey              VARCHAR2(80) := NULL;
7891   l_new_ccid_generated          BOOLEAN := FALSE;
7892   l_FB_ERROR_MSG          VARCHAR2(2000);
7893 
7894   l_return_status               VARCHAR2(1);
7895   l_interface_line_id           PO_LINES_INTERFACE.interface_line_id%TYPE;
7896   l_old_interface_line_id       PO_LINES_INTERFACE.interface_line_id%TYPE := -1;
7897   l_interface_distribution_id   PO_DISTRIBUTIONS_INTERFACE.interface_distribution_id%TYPE;
7898   l_item_category_id            PO_LINES_INTERFACE.category_id%TYPE;
7899   l_req_charge_account_id       PO_DISTRIBUTIONS_INTERFACE.charge_account_id%TYPE;
7900   l_req_variance_account_id     PO_DISTRIBUTIONS_INTERFACE.variance_account_id%TYPE;
7901   l_destination_organization_id PO_DISTRIBUTIONS_INTERFACE.destination_organization_id%TYPE;
7902   l_destination_ou_id           PO_HEADERS_ALL.org_id%TYPE;
7903 
7904   l_item_id       PO_LINES_INTERFACE.item_id%TYPE;
7905   l_category_id           PO_LINES_INTERFACE.category_id%TYPE;
7906   l_destination_type_code       PO_DISTRIBUTIONS_ALL.destination_type_code%TYPE;
7907   --l_ship_to_organization_id      NUMBER;
7908   l_ship_to_location_id   PO_DISTRIBUTIONS_INTERFACE.deliver_to_location_id%TYPE;
7909   l_deliver_to_person_id        PO_DISTRIBUTIONS_INTERFACE.deliver_to_person_id%TYPE;
7910   l_line_type_id          PO_LINES_INTERFACE.line_type_id%TYPE;
7911   l_vendor_id       PO_VENDORS.vendor_id%TYPE;
7912   l_agent_id      PO_HEADERS.agent_id%TYPE;
7913   l_expenditure_organization_id PO_DISTRIBUTIONS_INTERFACE.expenditure_organization_id%TYPE;
7914   l_project_id      PO_DISTRIBUTIONS_INTERFACE.project_id%TYPE;
7915   l_task_id       PO_DISTRIBUTIONS_INTERFACE.task_id%TYPE;
7916   l_bom_resource_id     PO_DISTRIBUTIONS_INTERFACE.bom_resource_id%TYPE;
7917   l_wip_entity_id     PO_DISTRIBUTIONS_INTERFACE.wip_entity_id%TYPE;
7918   l_wip_line_id           PO_DISTRIBUTIONS_INTERFACE.wip_line_id%TYPE;
7919   l_wip_repetitive_schedule_id  PO_DISTRIBUTIONS_INTERFACE.wip_repetitive_schedule_id%TYPE;
7920   l_gl_encumbered_date    PO_DISTRIBUTIONS_INTERFACE.gl_encumbered_date%TYPE;
7921   l_destination_subinventory    PO_DISTRIBUTIONS_ALL.destination_subinventory%TYPE;
7922   l_expenditure_type    PO_DISTRIBUTIONS_ALL.expenditure_type%TYPE;
7923   l_expenditure_item_date   PO_DISTRIBUTIONS_INTERFACE.expenditure_item_date%TYPE;
7924   l_wip_operation_seq_num   PO_DISTRIBUTIONS_INTERFACE.wip_operation_seq_num%TYPE;
7925   l_wip_resource_seq_num        PO_DISTRIBUTIONS_INTERFACE.wip_resource_seq_num%TYPE;
7926 
7927 
7928   --< New start_workflow parameters in FPJ End >
7929   l_transaction_flow_header_id  PO_LINE_LOCATIONS.transaction_flow_header_id%TYPE;
7930   l_dest_charge_success         BOOLEAN;
7931   l_dest_variance_success       BOOLEAN;
7932   l_dest_charge_account_id      PO_DISTRIBUTIONS_INTERFACE.dest_charge_account_id%TYPE;
7933   l_dest_variance_account_id    PO_DISTRIBUTIONS_INTERFACE.dest_variance_account_id%TYPE;
7934   l_dest_charge_account_desc    VARCHAR2(2000);
7935   l_dest_variance_account_desc  VARCHAR2(2000);
7936   l_dest_charge_account_flex    VARCHAR2(2000);
7937   l_dest_variance_account_flex  VARCHAR2(2000);
7938   --< New start_workflow parameters in FPJ End >
7939 
7940   -- Bug 3463242 START
7941   l_req_line_id                 PO_LINES_INTERFACE.requisition_line_id%TYPE;
7942   -- <ACHTML R12>
7943   l_requesting_ou_id            PO_REQUISITION_LINES_ALL.org_id%TYPE;
7944   l_unit_price                  PO_LINES_INTERFACE.unit_price%TYPE;
7945   l_base_unit_price             PO_LINES_INTERFACE.base_unit_price%TYPE;
7946   l_amount                      PO_LINES_INTERFACE.amount%TYPE;
7947   l_quantity_dummy              PO_LINES_INTERFACE.quantity%TYPE;
7948   l_order_type_lookup_code      PO_LINE_TYPES_B.order_type_lookup_code%TYPE;
7949   l_po_currency_code            PO_HEADERS_INTERFACE.currency_code%TYPE;
7950   l_req_header_rate_type        PO_HEADERS_INTERFACE.rate_type%TYPE;
7951   l_req_header_rate_date        PO_HEADERS_INTERFACE.rate_date%TYPE;
7952   l_req_header_rate             PO_HEADERS_INTERFACE.rate%TYPE;
7953   l_dist_rate                   PO_DISTRIBUTIONS_INTERFACE.rate%TYPE;
7954   l_rate_for_req_fields         PO_HEADERS_INTERFACE.rate%TYPE;
7955   l_po_func_unit_price          PO_LINES_ALL.unit_price%TYPE;
7956   -- Bug 3463242 END
7957 
7958   l_item_in_linv_pou VARCHAR2(1):= 'Y'; -- Bug 3433867
7959 
7960   --SQL WHAT: All those lines inserted in the PO distributions interface table
7961   --          that have the DOU <> POU.
7962   --SQL WHY:  To call AG Workflow for line that have a Transaction Flow
7963   --          defined between DOU and POU.
7964   CURSOR l_SPS_lines_csr IS
7965     SELECT pdi.interface_distribution_id,
7966            pli.interface_line_id,
7967            pli.category_id,
7968            pdi.charge_account_id,    -- to be copied onto Dest Charge Account
7969            pdi.variance_account_id,  -- to be copied onto Dest Variance Account
7970            pdi.destination_organization_id, -- DINV
7971            TO_NUMBER(hoi.org_information3), -- DOU
7972            pli.item_id,
7973            pli.category_id,
7974            pdi.destination_type_code,
7975            pdi.deliver_to_location_id,
7976            pdi.deliver_to_person_id,
7977            pli.line_type_id,
7978            phi.vendor_id,
7979            phi.agent_id,
7980            pdi.expenditure_organization_id,
7981            pdi.project_id,
7982            pdi.task_id,
7983            pdi.bom_resource_id,
7984            pdi.wip_entity_id,
7985            pdi.wip_line_id,
7986            pdi.wip_repetitive_schedule_id,
7987            pdi.gl_encumbered_date,
7988            pdi.destination_subinventory,
7989            pdi.expenditure_type,
7990            pdi.expenditure_item_date,
7991            pdi.wip_operation_seq_num,
7992            pdi.wip_resource_seq_num,
7993            -- Bug 3463242 START
7994            pli.requisition_line_id,
7995      -- <ACHTML R12>
7996      nvl(prl.org_id, g_hdr_requesting_ou_id) requesting_ou_id,
7997            pli.unit_price,
7998            pli.base_unit_price,
7999            pli.amount,
8000            NVL(plt.order_type_lookup_code,'QUANTITY'),
8001            phi.currency_code,
8002            phi.rate_type,
8003            phi.rate_date,
8004            phi.rate,
8005            pdi.rate
8006            -- Bug 3463242 END
8007     FROM PO_DISTRIBUTIONS_INTERFACE pdi,
8008          PO_LINES_INTERFACE pli,
8009          PO_HEADERS_INTERFACE phi,
8010    PO_REQUISITION_LINES_ALL prl, -- <ACHTML R12>
8011          MTL_PARAMETERS mp,
8012          HR_ORGANIZATION_INFORMATION hoi,
8013          PO_LINE_TYPES_B plt -- Bug 3463242
8014     WHERE phi.interface_header_id = p_interface_header_id
8015       AND pli.interface_header_id = phi.interface_header_id
8016       AND pli.requisition_line_id = prl.requisition_line_id(+) -- <ACHTML R12>
8017       AND pdi.interface_line_id = pli.interface_line_id
8018       AND mp.organization_id = pli.ship_to_organization_id
8019       AND mp.organization_id = hoi.organization_id
8020       AND hoi.org_information_context = 'Accounting Information'
8021       AND hoi.org_information3 <> TO_CHAR(g_purchasing_ou_id)  -- DOU <> POU
8022       AND pli.line_type_id = plt.line_type_id (+) -- Bug 3463242
8023     ORDER BY pli.interface_line_id;
8024   l_api_name VARCHAR2(100) := 'generate_shared_proc_accounts';
8025 BEGIN
8026     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8027         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
8028     END IF;
8029 
8030   -- Ignore for RFQ's and Blankets
8031   IF ( g_document_type <> 'PO' OR
8032        g_document_subtype <> 'STANDARD' ) THEN
8033 
8034     l_progress := '010';
8035     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8036         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8037                             p_token    => l_progress,
8038                             p_message  => 'Ignoring... Type='|| g_document_type|| ' SubType='||g_document_subtype);
8039     END IF;
8040     RETURN;
8041   END IF;
8042 
8043   l_progress := '020';
8044 
8045   OPEN l_SPS_lines_csr;
8046 
8047   l_progress := '030';
8048 
8049   LOOP
8050     FETCH l_SPS_lines_csr
8051     INTO l_interface_distribution_id,
8052          l_interface_line_id,
8053          l_item_category_id,
8054          l_req_charge_account_id,
8055          l_req_variance_account_id,
8056          l_destination_organization_id,
8057          l_destination_ou_id,
8058          l_item_id,
8059          l_category_id,
8060          l_destination_type_code,
8061          l_ship_to_location_id,
8062          l_deliver_to_person_id,
8063          l_line_type_id,
8064          l_vendor_id,
8065          l_agent_id,
8066          l_expenditure_organization_id,
8067          l_project_id,
8068          l_task_id,
8069          l_bom_resource_id,
8070          l_wip_entity_id,
8071          l_wip_line_id,
8072          l_wip_repetitive_schedule_id,
8073          l_gl_encumbered_date,
8074          l_destination_subinventory,
8075          l_expenditure_type,
8076          l_expenditure_item_date,
8077          l_wip_operation_seq_num,
8078          l_wip_resource_seq_num,
8079          -- Bug 3463242 START
8080          l_req_line_id,
8081          l_requesting_ou_id, -- <ACHTML R12>
8082          l_unit_price,
8083          l_base_unit_price,
8084          l_amount,
8085          l_order_type_lookup_code,
8086          l_po_currency_code,
8087          l_req_header_rate_type,
8088          l_req_header_rate_date,
8089          l_req_header_rate,
8090          l_dist_rate;
8091          -- Bug 3463242 END
8092 
8093     l_progress := '040';
8094 
8095     EXIT WHEN l_SPS_lines_csr%NOTFOUND;
8096 
8097     l_progress := '050';
8098 
8099     -- Get the Transaction Flow Header ID from the Inventory API.
8100     -- Use the wrapper API written in PO.
8101     PO_SHARED_PROC_PVT.check_transaction_flow(
8102              p_init_msg_list    => FND_API.G_TRUE,
8103              x_return_status    => l_return_status,  -- OUT NOCOPY VARCHAR2
8104              p_start_ou_id      => g_purchasing_ou_id,
8105              p_end_ou_id        => l_destination_ou_id,
8106              p_ship_to_org_id   => l_destination_organization_id,
8107              p_item_category_id => l_item_category_id,
8108              p_transaction_date => sysdate,
8109              x_transaction_flow_header_id => l_transaction_flow_header_id);
8110                                                           -- OUT NOCOPY NUMBER
8111 
8112     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8113         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8114                             p_token    => l_progress,
8115                             p_message  => 'After calling check_transaction_flow l_transaction_flow_header_id='
8116                                           || to_char(l_transaction_flow_header_id)|| ' l_return_status='
8117                                           ||l_return_status);
8118     END IF;
8119 
8120     l_progress := '060';
8121     IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
8122         APP_EXCEPTION.raise_exception(
8123                 exception_type => 'PO_SHARED_PROC_PVT.check_transaction_flow',
8124                 exception_code => 0,
8125                 exception_text => 'return_status='||l_return_status);
8126     END IF;
8127 
8128     -- Bug 3433867 Start
8129     -- Need to validate the item in the logical inv org of the POU if a
8130     -- valid transaction flow exists and item id is not null
8131 
8132     l_progress := '065';
8133     IF l_transaction_flow_header_id IS NOT NULL AND l_item_id IS NOT NULL THEN
8134        PO_SHARED_PROC_PVT.check_item_in_linv_pou
8135              (x_return_status              => l_return_status,
8136               p_item_id                    => l_item_id,
8137               p_transaction_flow_header_id => l_transaction_flow_header_id,
8138               x_item_in_linv_pou           => l_item_in_linv_pou);
8139        IF l_return_status <> FND_API.g_ret_sts_success THEN
8140           APP_EXCEPTION.raise_exception(
8141                 exception_type => 'PO_SHARED_PROC_PVT.check_item_in_linv_pou',
8142                 exception_code => 0,
8143                 exception_text => 'return_status='||l_return_status);
8144        ELSIF l_return_status = FND_API.g_ret_sts_success AND
8145              (l_item_in_linv_pou <> 'Y') THEN
8146           IF g_debug_stmt THEN
8147              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8148                                  p_token    => l_progress,
8149                                  p_message  => 'After calling check_item_in_linv_pou: Item does not exist in the
8150                                                 logical inv org of the POU'||' l_return_status= '||l_return_status);
8151           END IF;
8152           APP_EXCEPTION.raise_exception(
8153                    exception_type => 'PO_SHARED_PROC_PVT.check_item_in_linv_pou',
8154                    exception_code => 0,
8155                    exception_text => 'Item does not exist in the logical inventory org of POU');
8156        END IF;
8157     END IF;
8158     -- Bug 3433867 End
8159 
8160     l_progress := '070';
8161     -- Call AG Workflow for SPS case
8162     IF (l_transaction_flow_header_id IS NOT NULL) THEN
8163 
8164       l_progress := '080';
8165 
8166       l_charge_account_id        := NULL;
8167       l_variance_account_id      := NULL;
8168       l_accrual_account_id       := NULL;
8169       l_budget_account_id        := NULL;
8170       l_dest_charge_account_id   := l_req_charge_account_id; -- Copied from Req
8171       l_dest_variance_account_id := l_req_variance_account_id;-- Copied from Req
8172 
8173       -- Bug 3463242 START
8174       -- Convert the unit price to the POU functional currency before passing
8175       -- it to the PO account generator workflow.
8176 
8177       IF (l_order_type_lookup_code <> 'AMOUNT') THEN
8178 
8179         IF g_debug_stmt THEN
8180           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8181                               p_token    => l_progress,
8182                               p_message  =>
8183             'unit price in ROU currency: ' || l_unit_price
8184             || ', ROU / requisition rate: ' || l_req_header_rate );
8185         END IF;
8186 
8187         -- Obtain the rate between the ROU currency and the PO currency.
8188         --<Sourcing 11.5.10+> No need to do this if called from Sourcing
8189         IF (g_interface_source_code <> 'SOURCING'
8190       AND g_purchasing_ou_id <> l_requesting_ou_id) -- <ACHTML R12>
8191         THEN
8192           get_rate_for_req_price(
8193             p_requesting_ou_id => l_requesting_ou_id, -- <ACHTML R12>
8194             p_purchasing_ou_id => g_purchasing_ou_id, -- <ACHTML R12>
8195             p_po_currency_code => l_po_currency_code,
8196             p_rate_type => l_req_header_rate_type,
8197             p_rate_date => l_req_header_rate_date,
8198             x_rate => l_rate_for_req_fields
8199           );
8200           IF (l_rate_for_req_fields IS NULL)
8201           THEN
8202             l_rate_for_req_fields := l_req_header_rate;
8203           END IF;
8204         ELSE
8205           l_rate_for_req_fields := l_req_header_rate;
8206         END IF;
8207 
8208         -- First convert from the ROU currency to the PO currency.
8209         PO_INTERFACE_S.do_currency_conversion (
8210           p_order_type_lookup_code => l_order_type_lookup_code,
8211           p_interface_source_code => g_interface_source_code,
8212           p_rate => NVL(l_rate_for_req_fields,1),
8213           p_po_currency_code => l_po_currency_code,
8214           p_requisition_line_id => l_req_line_id,
8215           x_quantity => l_quantity_dummy,
8216           x_unit_price => l_unit_price,
8217           x_base_unit_price => l_base_unit_price,
8218           x_amount => l_amount );
8219 
8220         -- Then convert from the PO currency to the POU currency.
8221         l_po_func_unit_price := l_unit_price * NVL(l_dist_rate,1);
8222 
8223       ELSE -- l_order_type_lookup_code = 'AMOUNT'
8224         l_po_func_unit_price := l_unit_price;
8225       END IF; -- l_order_type_lookup_code
8226       -- Bug 3463242 END
8227 
8228       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8229         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8230                             p_token    => l_progress,
8231                             p_message  => 'Calling AG WF');
8232 
8233         -- Bug 3463242 START
8234         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8235                             p_token    => l_progress,
8236                             p_message  =>
8237           'unit price in PO currency: ' || l_unit_price
8238           || ', ROU / PO rate: ' || l_rate_for_req_fields
8239           || ', POU / PO rate: ' || l_dist_rate
8240           || ', unit price in POU currency (passed to Account Generator): ' || l_po_func_unit_price);
8241         -- Bug 3463242 END
8242       END IF;
8243 
8244      l_progress := '090';
8245 
8246       l_return_value := PO_WF_BUILD_ACCOUNT_INIT.Start_Workflow (
8247 
8248         g_purchasing_ou_id,           -- IN
8249         l_transaction_flow_header_id, -- IN
8250         l_dest_charge_success,        -- IN OUT
8251         l_dest_variance_success,      -- IN OUT
8252         l_dest_charge_account_id,     -- IN OUT
8253         l_dest_variance_account_id,   -- IN OUT
8254         l_dest_charge_account_desc,   -- IN OUT
8255         l_dest_variance_account_desc, -- IN OUT
8256         l_dest_charge_account_flex,   -- IN OUT
8257         l_dest_variance_account_flex, -- IN OUT
8258         l_charge_success,          l_budget_success,
8259       l_accrual_success,         l_variance_success,
8260       l_charge_account_id,         l_budget_account_id,
8261       l_accrual_account_id,        l_variance_account_id,
8262       l_charge_account_flex,         l_budget_account_flex,
8263       l_accrual_account_flex,        l_variance_account_flex,
8264       l_charge_account_desc,         l_budget_account_desc,
8265       l_accrual_account_desc,        l_variance_account_desc,
8266         params.coa_id,
8267         l_bom_resource_id,
8268         NULL, -- p_bom_cost_element_id
8269         l_category_id,                 l_destination_type_code,
8270         l_ship_to_location_id,
8271         l_destination_organization_id, --<Shared Proc FPJ>
8272         l_destination_subinventory,    l_expenditure_type,
8273         l_expenditure_organization_id, l_expenditure_item_date,
8274         l_item_id ,                    l_line_type_id,
8275         NULL, -- PA result billable flag
8276         l_agent_id,
8277         l_project_id,
8278         NULL, -- p_from_type_lookup_code
8279         NULL, -- p_from_header_id
8280         NULL, -- p_from_line_id
8281         l_task_id,                     l_deliver_to_person_id,
8282         g_document_subtype, -- l_type_lookup_code
8283         l_vendor_id,
8284         l_wip_entity_id,
8285         NULL, -- p_wip_entity_type
8286         l_wip_line_id,                 l_wip_repetitive_schedule_id,
8287         l_wip_operation_seq_num,       l_wip_resource_seq_num,
8288         nvl(params.po_encumbrance_flag, 'N'),
8289         l_gl_encumbered_date,
8290 
8291         l_wf_itemkey, l_new_ccid_generated,
8292 
8293         -- 15 Header attributes -- all NULL's
8294         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8295         NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8296         -- 15 Line attributes -- all NULL's
8297         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8298         NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8299         -- 15 Shipment attributes -- all NULL's
8300         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8301         NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8302         -- 15 Distribution attributes -- all NULL's
8303         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8304         NULL, NULL, NULL, NULL, NULL, NULL, NULL,
8305         l_FB_ERROR_MSG,
8306         --<BUG 3407630 START>
8307         NULL,  --x_award_id
8308         NULL,  --x_vendor_site_id
8309         l_po_func_unit_price -- Bug 3463242
8310         --<BUG 3407630 END>
8311         );
8312 
8313       l_progress := '100';
8314 
8315       IF (l_return_value = FALSE) THEN
8316         APP_EXCEPTION.raise_exception(
8317                   exception_type => 'PO_WF_BUILD_ACCOUNT_INIT.Start_Workflow',
8318                   exception_code => 0,
8319                   exception_text => 'Start_workflow returned FALSE');
8320       END IF;
8321 
8322       l_progress := '110';
8323 
8324       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8325           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8326                               p_token    => l_progress,
8327                               p_message  => 'After calling AG WF');
8328           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8329                               p_token    => l_progress,
8330                               p_message  => 'Before updating the interface table with trxflowhdrid l_transaction_flow_header_id='
8331                                             || to_char(l_transaction_flow_header_id)|| ' l_interface_line_id='
8332                                             ||to_char(l_interface_line_id)||' l_old_interface_line_id ='
8333                                             ||to_char(l_old_interface_line_id));
8334       END IF;
8335 
8336       IF l_interface_line_id <> l_old_interface_line_id THEN
8337          l_progress := '120';
8338          UPDATE po_lines_interface
8339             SET transaction_flow_header_id = l_transaction_flow_header_id
8340           WHERE interface_line_id = l_interface_line_id;
8341 
8342          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8343              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8344                                  p_token    => l_progress,
8345                                  p_message  => 'Transaction flow header id updated: SQL%ROWCOUNT = '||SQL%ROWCOUNT);
8346          END IF;
8347 
8348          l_old_interface_line_id := l_interface_line_id;
8349       END IF;
8350 
8351       l_progress := '130';
8352 
8353       -- update the distributions interface table with new account ID's
8354       UPDATE po_distributions_interface
8355       SET charge_account_id        = l_charge_account_id,
8356           variance_account_id      = l_variance_account_id,
8357           accrual_account_id       = l_accrual_account_id,
8358           budget_account_id        = NULL,
8359           dest_charge_account_id   = l_dest_charge_account_id,
8360           dest_variance_account_id = l_dest_variance_account_id
8361       WHERE interface_distribution_id = l_interface_distribution_id;
8362 
8363       l_progress := '140';
8364 
8365     END IF; -- IF (l_transaction_flow_header_id IS NOT NULL)
8366 
8367     l_progress := '150';
8368 
8369   END LOOP;
8370 
8371   l_progress := '160';
8372 
8373   CLOSE l_SPS_lines_csr;
8374 
8375     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8376         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
8377     END IF;
8378 EXCEPTION
8379   WHEN OTHERS THEN
8380     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
8381         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
8382                            p_progress => l_progress);
8383     END IF;
8384     PO_MESSAGE_S.sql_error(l_api_name, l_progress, sqlcode);
8385     RAISE;
8386 END generate_shared_proc_accounts; --)
8387 --< Shared Proc FPJ End >
8388 
8389 
8390 ------------------------------------------------------------------<BUG 3322948>
8391 -------------------------------------------------------------------------------
8392 --Start of Comments
8393 --Name: do_currency_conversion
8394 --Pre-reqs:
8395 --  None.
8396 --Modifies:
8397 --  None.
8398 --Locks:
8399 --  None.
8400 --Function:
8401 --  This procedure performs currency conversion on the input quantity,
8402 --  unit_price, or amount. Which of the previous values to convert depends
8403 --  on the order_type_lookup_code and the interface_source_code.
8404 --
8405 --  If the Req line currency is the same as the new PO currency, we will take
8406 --  the Req's currency_<unit_price/amount> directly so that conversion
8407 --  calculations will not have to be performed again. Otherwise, we will
8408 --  perform the conversion using the input rate.
8409 --
8410 --Parameters:
8411 --IN:
8412 --p_order_type_lookup_code
8413 --  Value Basis of the Requisition/PO line.
8414 --p_interface_source_code
8415 --  Interface Source Code of the current Autocreate session.
8416 --p_rate
8417 --  Currency conversion rate to convert Req Currency to PO Currency.
8418 --p_po_currency_code
8419 --  Currency code of the to-be-created PO.
8420 --p_requisition_line_id
8421 --  Unique ID of the Requisition line being Autocreated.
8422 --  (May be NULL if coming from Sourcing).
8423 --IN OUT:
8424 --x_quantity
8425 --  Quantity to be converted.
8426 --x_unit_price
8427 --  Unit Price to be converted.
8428 --x_base_unit_price
8429 --  Base Unit Price to be converted.
8430 --x_amount
8431 --  Amount to be converted.
8432 --Testing:
8433 --  None.
8434 --End of Comments
8435 -------------------------------------------------------------------------------
8436 -------------------------------------------------------------------------------
8437 PROCEDURE do_currency_conversion
8438 (
8439     p_order_type_lookup_code   IN              VARCHAR2
8440 ,   p_interface_source_code    IN              VARCHAR2
8441 ,   p_rate                     IN              NUMBER
8442 ,   p_po_currency_code         IN              VARCHAR2
8443 ,   p_requisition_line_id      IN              NUMBER
8444 ,   x_quantity                 IN OUT NOCOPY   NUMBER
8445 ,   x_unit_price               IN OUT NOCOPY   NUMBER
8446 ,   x_base_unit_price          IN OUT NOCOPY   NUMBER --bug 3401653
8447 ,   x_amount                   IN OUT NOCOPY   NUMBER
8448 )
8449 IS
8450     l_api_name                VARCHAR2(30) := 'do_currency_conversion';
8451     l_log_head                VARCHAR2(100) := g_log_head || l_api_name;
8452     l_progress                VARCHAR2(3);
8453 
8454     l_precision               FND_CURRENCIES.precision%TYPE;
8455     l_ext_precision           FND_CURRENCIES.extended_precision%TYPE;
8456     l_min_acct_unit           FND_CURRENCIES.minimum_accountable_unit%TYPE;
8457 
8458     l_req_currency_code       PO_REQUISITION_LINES_ALL.currency_code%TYPE;
8459     l_req_ou_currency_code    GL_SETS_OF_BOOKS.currency_code%TYPE; -- Bug 3794198
8460     l_req_unit_price          PO_REQUISITION_LINES_ALL.unit_price%TYPE;
8461     l_req_currency_unit_price PO_REQUISITION_LINES_ALL.currency_unit_price%TYPE;
8462     l_req_amount              PO_REQUISITION_LINES_ALL.amount%TYPE;
8463     l_req_currency_amount     PO_REQUISITION_LINES_ALL.currency_amount%TYPE;
8464     l_req_rate                PO_REQUISITION_LINES_ALL.rate%TYPE; -- Bug 7661419
8465 
8466 BEGIN
8467 
8468 l_progress:='000'; PO_DEBUG.debug_begin(l_log_head);
8469 
8470     -- Initialize Variables ===================================================
8471 
8472     -- Get the precision/extended precision for the PO Currency.
8473     --
8474     -- Bug 4471683: added not null check for currency
8475     IF interface.h_currency_code IS NOT NULL THEN
8476       FND_CURRENCY.get_info ( currency_code => p_po_currency_code
8477                           , precision     => l_precision
8478                           , ext_precision => l_ext_precision
8479                           , min_acct_unit => l_min_acct_unit
8480                           );
8481     END IF;
8482 
8483     -- Convert ================================================================
8484 
8485 l_progress:='010'; PO_DEBUG.debug_var(l_log_head,l_progress,'p_order_type_lookup_code',p_order_type_lookup_code);
8486 
8487     -- For 'Amount' based lines, we need to convert the quantity since
8488     -- quantity acts like amount.
8489     --
8490     IF ( p_order_type_lookup_code = 'AMOUNT' ) THEN
8491 
8492        l_progress:='010';
8493        PO_DEBUG.debug_stmt(l_log_head,l_progress,'Performing currency conversion on quantity.');
8494 
8495        -- Bug 7661419, No conversion for same currency.
8496        SELECT PRL.currency_code,
8497               Nvl(PRL.rate,1)
8498        INTO   l_req_currency_code,
8499               l_req_rate
8500        FROM   po_requisition_lines_all PRL
8501        WHERE  PRL.requisition_line_id = p_requisition_line_id;
8502 
8503        IF ( l_req_currency_code = p_po_currency_code ) THEN
8504         x_quantity := round ( x_quantity/l_req_rate, nvl(l_ext_precision, 15) );
8505        ELSE
8506         x_quantity := round ( x_quantity/p_rate, nvl(l_ext_precision, 15) );
8507        END IF;
8508 
8509 
8510     -- For all other line types, convert the Price/Amount.
8511     --
8512     ELSE -- ( p_order_type_lookup_code IN ('QUANTITY','FIXED PRICE','RATE') )
8513 
8514         -- If coming from Sourcing, however, do not perform any conversion as
8515         -- Sourcing already populates converted value in the interface table.
8516         --
8517         IF ( p_interface_source_code IN ('SOURCING','CONSUMPTION_ADVICE') ) THEN
8518 
8519            l_progress:='030';
8520            PO_DEBUG.debug_stmt(l_log_head,l_progress,'p_interface_source_code IN (SOURCING, CONSUMPTION ADVICE) - no currency conversion performed');
8521 
8522         ELSE -- ( p_interface_source_code NOT IN ('SOURCING','CONSUMPTION_ADVICE') )
8523 
8524             -- Retrieve information from the backing Requisition Line.
8525             -- Bug 3794198: Join to financials_system_params_all and gl_sets_of_books to
8526             -- retrieve the value of l_req_ou_currency_code, the functional currency of ROU
8527             SELECT PRL.currency_code
8528             ,      GSB.currency_code
8529             ,      PRL.unit_price
8530             ,      nvl(PRL.currency_unit_price, PRL.unit_price)
8531             ,      PRL.amount
8532             ,      nvl(PRL.currency_amount, PRL.amount)
8533             INTO   l_req_currency_code
8534             ,      l_req_ou_currency_code
8535             ,      l_req_unit_price
8536             ,      l_req_currency_unit_price
8537             ,      l_req_amount
8538             ,      l_req_currency_amount
8539             FROM   po_requisition_lines_all PRL,
8540                    financials_system_params_all FSP,
8541                    gl_sets_of_books GSB
8542             WHERE  PRL.requisition_line_id = p_requisition_line_id
8543             AND    nvl(PRL.org_id, -99) = nvl(FSP.org_id, -99)
8544             AND    FSP.set_of_books_id = GSB.set_of_books_id;
8545 
8546             -- If the Req and PO Currency are the same, then simply take the
8547             -- currency_<unit_price/amount> from the Req to avoid having to
8548             -- perform another conversion.
8549             --
8550             -- Bug 3794198: If the ROU currency and PO Currency are the same, then
8551             -- simply take the unit_price/amount from the Req to avoid conversion
8552             --
8553             -- If the Req and PO Currency are different, then convert the
8554             -- unit_price/amount to the PO Currency using the specified rate.
8555             --
8556             IF ( l_req_currency_code = p_po_currency_code ) THEN
8557 
8558                l_progress:='050';
8559                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.');
8560 
8561                 x_unit_price := l_req_currency_unit_price;
8562                 x_amount     := l_req_currency_amount;
8563 
8564             -- Bug 3794198 Start
8565             ELSIF (l_req_ou_currency_code = p_po_currency_code) THEN
8566                l_progress := '060';
8567                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');
8568                x_unit_price := l_req_unit_price;
8569                x_amount := l_req_amount;
8570             -- Bug 3794198 End
8571 
8572             ELSE
8573 
8574                l_progress:='070';
8575                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.');
8576 
8577                 -- Bug 3472140: Added NVL() around l_ext_precision
8578                 x_unit_price := round(l_req_unit_price/p_rate, NVL(l_ext_precision, 15));
8579                 x_amount     := round(l_req_amount/p_rate, l_precision);
8580 
8581             END IF; -- currency_code
8582             -- Bug 3472140: Added NVL() around l_ext_precision
8583             x_base_unit_price := round(x_base_unit_price/p_rate, NVL(l_ext_precision, 15)); --bug 3401653
8584 
8585         END IF; -- p_interface_source_code
8586 
8587     END IF; -- p_order_type_lookup_code
8588 
8589 l_progress:='090'; PO_DEBUG.debug_end(l_log_head);
8590 
8591 EXCEPTION
8592 
8593     WHEN OTHERS THEN
8594         PO_DEBUG.debug_exc ( p_log_head => l_log_head
8595                            , p_progress => l_progress);
8596         RAISE;
8597 
8598 END do_currency_conversion;
8599 
8600 
8601 /* ============================================================================
8602      NAME: SETUP_INTERFACE_TABLES
8603      DESC: Setup interface tables
8604      ARGS: x_interface_header_id IN number
8605      ALGR:
8606 
8607    ==========================================================================*/
8608 -- <Complex Work R12>: Add new parameter, p_is_complex_work_po
8609 PROCEDURE setup_interface_tables(
8610   x_interface_header_id  IN             NUMBER
8611 , x_document_id          IN OUT NOCOPY  NUMBER
8612 , p_is_complex_work_po   IN             BOOLEAN
8613 )
8614 IS
8615 
8616 x_po_header_id number := null;
8617 x_document_num po_headers.segment1%type:=null;
8618 x_min_interface_line_id number:= null;
8619 x_order_type_lookup_code varchar2(25) := null;
8620 x_quotation_class_code varchar2(25) := null;
8621 x_count_dist number;
8622 x_item_id number := null;
8623 x_vendor_id number := null;
8624 x_vendor_site_id number := null;
8625 x_rowid varchar2(25) := null;
8626 x_organization_id number := null;
8627 x_asl_id number := null;
8628 x_vendor_product_num varchar2(240) := null;
8629 x_purchasing_uom varchar2(240) := null;
8630 x_pay_on_code varchar2(25) := null;
8631 x_uom_convert          varchar2(2) := fnd_profile.value('PO_REQ_BPA_UOM_CONVERT');
8632 x_old_document_num po_headers.segment1%type:=null; -- Bug 700513, lpo, 07/15/98
8633 
8634 x_employee_id       number;
8635 x_employee_name     varchar2(240);
8636 x_requestor_location_id number;
8637 x_location_code     varchar2(25);
8638 x_employee_is_buyer boolean;
8639 x_is_emp            boolean;
8640 l_shipping_control  PO_RELEASES_ALL.shipping_control%TYPE;    -- <INBOUND LOGISTICS FPJ>
8641 
8642 Cursor C is select pli.rowid,
8643        pli.item_id,
8644        phi.vendor_id,
8645        phi.vendor_site_id,
8646        pdi.destination_organization_id
8647       from   po_lines_interface pli,
8648        po_headers_interface phi,
8649        po_distributions_interface pdi
8650       where  phi.interface_header_id = x_interface_header_id
8651       and    phi.interface_header_id = pli.interface_header_id
8652       and    pdi.interface_distribution_id =
8653         (SELECT min(pdi2.interface_distribution_id)
8654          FROM   po_distributions_interface pdi2
8655                WHERE  pdi2.interface_line_id = pli.interface_line_id)
8656       and    pli.item_id is not null
8657       and    phi.vendor_id is not null
8658       and    pli.vendor_product_num is null;
8659 --default distributions for all negotiation lines which are not backed by
8660 --requisition lines.
8661 Cursor C_default_distribution is
8662        SELECT pli.interface_header_id,
8663               pli.interface_line_id,
8664               pli.item_id,
8665               pli.line_type_id,
8666               pli.quantity,
8667               pli.amount,                                     -- <SERVICES FPJ>
8668               pli.category_id,
8669               pli.ship_to_location_id,
8670               pli.ship_to_organization_id,
8671               phi.vendor_id,
8672               phi.vendor_site_id,
8673               phi.agent_id,
8674               phi.rate,
8675               phi.rate_date,
8676               phi.document_subtype,
8677               pli.unit_price --<BUG 3407630>
8678          FROM po_lines_interface pli,
8679               po_headers_interface phi,
8680         po_line_types plt
8681         WHERE phi.interface_header_id = x_interface_header_id
8682           AND phi.interface_header_id = pli.interface_header_id
8683     AND pli.requisition_line_id is null
8684     AND plt.line_type_id = pli.line_type_id;
8685 
8686 l_api_name CONSTANT VARCHAR2(30) := 'setup_interface_tables';
8687 l_progress VARCHAR2(3) := '000';                --< Bug 3210331 >
8688 
8689 -- bug# 3345108
8690 -- secondary qty and secondary uom not getting populated for requisition lines
8691 -- when requisition is created using IP.
8692 -- default secondary qty and uom if
8693 -- opm is installed.
8694 -- destination org. is process and item is process and item is dual uom control.
8695 
8696 -- bug# 3386353
8697 -- Sourcing when doing overaward creates additional PO line with the extra qty.
8698 -- If the line is OPM item with dual uom control then the shipment corresponding
8699 -- to the extra PO line created by Sourcing does not have secondary uom and
8700 -- secondary quantity with ship to organization as process org.
8701 -- default secondary UOM and secondary quantity in such a case (non req backed lines)
8702 -- the requisition line id would be null in po_lines_interface .
8703 -- need to handle that situation in the default_opm_attributes cursor.
8704 -- in case of non req back lines from sourcing , ship_to_organization_id is NULL.
8705 -- so get it from distribution interface table.
8706 
8707 -- <Complex Work R12 Start>
8708 l_ship_to_org_id  HR_LOCATIONS_ALL.inventory_organization_id%TYPE;
8709 -- <Complex Work R12 End>
8710 
8711 BEGIN
8712     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8713         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
8714     END IF;
8715 
8716     UPDATE po_headers_interface
8717        SET process_code = 'IN PROCESS'
8718      WHERE interface_header_id = x_interface_header_id;
8719 
8720     l_progress := '010';
8721 
8722     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8723         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8724                             p_token    => l_progress,
8725                             p_message  => 'Setup interface:   before select action type');
8726     END IF;
8727 
8728     l_progress := '020';
8729     -- Bug 700513, lpo, 07/15/98
8730     -- Get the document_num as well; needed for later on.
8731 
8732     SELECT min(action),
8733            min(group_code),
8734            min(document_num)
8735       INTO g_mode,
8736            g_group_code,
8737            x_old_document_num
8738       FROM po_headers_interface
8739      WHERE interface_header_id = x_interface_header_id;
8740 
8741     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8742         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8743                             p_token    => l_progress,
8744                             p_message  => 'Setup interface: mode is '||g_mode);
8745     END IF;
8746 
8747     /* Adding a requisition Line to a PO,Release,RFQ */
8748     IF(g_mode = 'ADD') THEN
8749 
8750        /*
8751        ** Find the po_header_id that matches the segment1 value that
8752        ** was loaded into the interface table.
8753        ** document_subtype in in interface table for an RFQ with be RFQ
8754        */
8755 
8756        IF (g_document_type = 'RFQ') THEN
8757          l_progress:='030';
8758          UPDATE po_headers_interface phi
8759             SET po_header_id =
8760               (SELECT ph.po_header_id
8761                  FROM po_headers_all ph  --<Shared Proc FPJ>
8762                 WHERE 'RFQ' = ph.type_lookup_code
8763                   AND phi.document_num = ph.segment1
8764                   AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99))  --<Shared Proc FPJ>
8765              WHERE interface_header_id = x_interface_header_id;
8766 
8767        ELSE
8768          l_progress:='040';
8769          UPDATE po_headers_interface phi
8770             SET po_header_id =
8771               (SELECT ph.po_header_id
8772                  FROM po_headers_all ph  --<Shared Proc FPJ>
8773                 WHERE decode(phi.document_subtype,
8774                              'RELEASE','BLANKET',
8775                              phi.document_subtype) = ph.type_lookup_code
8776                   AND phi.document_num = ph.segment1
8777                   AND NVL(org_id, -99) = NVL(g_purchasing_ou_id, -99))  --<Shared Proc FPJ>
8778           WHERE interface_header_id = x_interface_header_id;
8779 
8780             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8781                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8782                                     p_token    => l_progress,
8783                                     p_message  => 'After update of headers interface');
8784             END IF;
8785 
8786        END IF;
8787 
8788        l_progress:='050';
8789 
8790        /*
8791        ** The values that we are updating in the interface table
8792        ** we need for defaulting to records at the lower levels.
8793        */
8794 
8795        /* Bug 482648 add currecny_code */
8796 
8797        /* Also get the pay_on_code from the document */
8798 
8799        UPDATE po_headers_interface phi
8800        SET (
8801                rate,
8802                rate_type_code,
8803                rate_date,
8804                currency_code) =
8805                  (SELECT
8806                          rate,
8807                          rate_type,
8808                          rate_date,
8809                          currency_code
8810                     FROM po_headers_all ph  --<Shared Proc FPJ>
8811                    WHERE ph.po_header_id = phi.po_header_id)
8812        WHERE interface_header_id = x_interface_header_id;
8813 
8814        IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8815            PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8816                                p_token    => l_progress,
8817                                p_message  => 'After update of headers interfacei rate and etc.');
8818        END IF;
8819 
8820     /* Adding Req Line to New PO/RFQ */
8821     ELSIF(g_mode='NEW') THEN
8822 
8823       IF(g_document_subtype='STANDARD' or g_document_subtype='PLANNED'
8824          or g_document_type = 'RFQ'
8825          --<SOURCING TO PO FPH>
8826    or (g_document_subtype='BLANKET' and g_interface_source_code='SOURCING')) THEN
8827          l_progress:='060';
8828 
8829         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8830             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8831                                 p_token    => l_progress,
8832                                 p_message  => 'In std/planned/rfq');
8833         END IF;
8834 
8835          SELECT po_headers_s.nextval
8836            INTO x_po_header_id
8837            FROM sys.dual;
8838 
8839 
8840          /*
8841    ** Assign the document id to get passed back to the calling
8842    ** module.
8843    */
8844          x_document_id := x_po_header_id;
8845 
8846          l_progress:='070';
8847         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8848             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8849                                 p_token    => l_progress,
8850                                 p_message  => 'After select Doc is '||x_po_header_id);
8851         END IF;
8852 
8853    /* If we are using automatic numbering, get segment1
8854    ** from the po_unique_identifier_control table.
8855    ** If we are using manual numbering, segment1
8856    ** should already be loaded into the po_headers_interface table.
8857    ** The checks to verify that a manual po number is unique
8858    ** is done on the client side.
8859    */
8860          /* ecso 4/23/98 emergency requisition enhancement
8861          ** For emergency requisitions, there is a reserved po num
8862          ** even though the document has not been created.
8863          ** Add the case where the document is NEW
8864          ** and there exists a document_num on po_headers_interface
8865          */
8866          --<SOURCING TO PO FPH>
8867    --modified the if condition to include PA
8868    IF (params.po_num_code='AUTOMATIC') AND
8869       (g_document_type in ('PO','PA')) THEN
8870 
8871             -- Bug 700513, lpo, 07/15/98
8872             -- Should check for x_old_document_num instead of
8873             -- interface.document_num which is not defined at this point.
8874 
8875             IF x_old_document_num IS NULL THEN
8876                x_document_num := '-'||x_po_header_id;  --Bug 1093645
8877 
8878 /*Bug 1093645
8879   The following is commented as part of bug fix 958404.
8880   Prior to the fix we were locking the po_unique_identifier_control
8881   table in the beginning of the autocreate process which led to a
8882   deadlock situation.
8883   Fix has been made to assign a dummy (negative of po_header_id-The same
8884   logic followed in the enter po form) value now and then at the
8885   the end of the autocreate process lock the po_unique_identifier control
8886   table to fetch the next document number and assign it appropriately
8887   to avoid the deadlock.
8888 */
8889 
8890              END IF;
8891 
8892    ELSIF (params.user_defined_rfq_num_code='AUTOMATIC') AND
8893       (g_document_type = 'RFQ') THEN
8894 
8895              x_document_num := '-'||x_po_header_id;  --Bug 1093645
8896 
8897 /*Bug 1093645
8898   The following is commented as part of bug fix 958404.
8899   Prior to the fix we were locking the po_unique_identifier_control
8900   table in the beginning of the autocreate process which led to a
8901   deadlock situation.
8902   Fix has been made to assign a dummy (negative of po_header_id-The same
8903   logic followed in the enter po form) value now and then at the
8904   the end of the autocreate process lock the po_unique_identifier control
8905   table to fetch the next document number and assign it appropriately
8906   to avoid the deadlock.
8907 */
8908 
8909    ELSE
8910               x_document_num := interface.document_num;
8911 
8912          END IF;
8913 
8914       ELSIF(g_document_subtype='RELEASE')THEN
8915 
8916           l_progress := '080';
8917           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8918               PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8919                                   p_token    => l_progress,
8920                                   p_message  => 'Setup: In release subtype');
8921           END IF;
8922 
8923   /* Bug 565530 ecso 10/23/97
8924   ** There can be multiple release records
8925   ** in the interface table.
8926   ** Add restriction by interface_header_id
8927   */
8928 
8929           SELECT ph.po_header_id,
8930                  ph.pay_on_code,
8931                  ph.shipping_control    -- <INBOUND LOGISTICS FPJ>
8932             INTO x_po_header_id,
8933                  x_pay_on_code,
8934                  l_shipping_control    -- <INBOUND LOGISTICS FPJ>
8935             FROM po_headers_all ph,  --<Shared Proc FPJ>
8936                  po_headers_interface phi
8937            WHERE phi.interface_header_id = x_interface_header_id
8938        AND ph.segment1 = phi.document_num
8939              AND ph.type_lookup_code='BLANKET'
8940              AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
8941 
8942         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8943             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8944                                 p_token    => l_progress,
8945                                 p_message  => 'Setup: Header id of Blanket:  '||x_po_header_id);
8946         END IF;
8947 
8948       END IF;/* of standard/planned/release */
8949 
8950       l_progress:='090';
8951 
8952        SELECT min(interface_line_id)
8953         INTO x_min_interface_line_id
8954         FROM po_lines_interface pli,
8955              po_headers_interface phi
8956        WHERE phi.interface_header_id=pli.interface_header_id
8957          AND phi.interface_header_id = x_interface_header_id;
8958 
8959       l_progress:='100';
8960       --<SOURCING TO PO FPH>
8961       --modify the following update to default the values for the blanket also.
8962       --track 'PA' for the changes. Also please note that we have added deocode
8963       --for all the terms and conditions.Existing autocreate would not values
8964       --for different terms n condition columns and shipto billto columns in the
8965       --interface tables. But po_headers_interface table would contain values
8966       --for these columns when called from sourcing. So we are not defaulting
8967       --these values from params here but would do this in create_po procedure
8968       --in the order of interface,vendor,params.
8969       /* Bug 2816396
8970          Use the interface table value for pay_on_code when updating the table
8971       */
8972       IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
8973           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
8974                               p_token    => l_progress,
8975                               p_message  => 'Sourcing to FPH-6 starts');
8976       END IF;
8977 
8978       UPDATE po_headers_interface phi
8979               SET (po_header_id,
8980                    last_update_date,
8981                    last_updated_by,
8982                    document_num,
8983              created_by,
8984                    last_update_login,
8985                    agent_id,
8986                    creation_date,
8987                    revision_num,
8988                    print_count,
8989                    closed_code,
8990                    frozen_flag,
8991                    vendor_id,
8992                    vendor_site_id,
8993                    ship_to_location_id,
8994                    bill_to_location_id,
8995                    terms_id,
8996                    freight_carrier,
8997                    fob,
8998                    pay_on_code,
8999                    freight_terms,
9000              confirming_order_flag,
9001                    currency_code,
9002              rate_type_code,
9003                    rate_date,
9004                    rate,
9005                    acceptance_required_flag,
9006                    firm_flag,
9007                    min_release_amount,
9008        document_subtype,
9009                    shipping_control    -- <INBOUND LOGISTICS FPJ>
9010                    ) =
9011             (SELECT x_po_header_id,
9012                     nvl(phi.last_update_date,sysdate),
9013                     nvl(phi.last_updated_by,who.user_id),
9014                     nvl(phi.document_num,x_document_num),
9015                     nvl(phi.created_by,who.user_id),
9016                     nvl(phi.last_update_login,who.login_id),
9017                     phi.agent_id ,
9018                     nvl(phi.creation_date,sysdate),
9019                     decode(g_document_type, 'PO', nvl(phi.revision_num,0),
9020                      'PA', nvl(phi.revision_num,0), phi.revision_num),
9021                     decode(g_document_type, 'PO', nvl(phi.print_count,0),
9022                     'PA', nvl(phi.print_count,0), phi.print_count),
9023                     decode(g_document_type, 'PO', nvl(phi.closed_code,'OPEN'),
9024                     'PA', nvl(phi.closed_code,'OPEN'), phi.closed_code),
9025                     decode(g_document_type, 'PO', nvl(phi.frozen_flag,'N'),
9026                     'PA', nvl(phi.frozen_flag,'N'), phi.frozen_flag),
9027                     phi.vendor_id,
9028                     phi.vendor_site_id,
9029                     decode(g_interface_source_code,'SOURCING',
9030          phi.ship_to_location_id,
9031          nvl(phi.ship_to_location_id,
9032         params.ship_to_location_id)),
9033                     decode(g_interface_source_code,'SOURCING',
9034          phi.bill_to_location_id,
9035                          nvl(phi.bill_To_Location_Id,
9036         params.bill_to_location_id)),
9037                     decode(g_interface_source_code,'SOURCING',phi.terms_id,
9038                            nvl(phi.terms_id,params.terms_id)),
9039                     decode(g_interface_source_code,'SOURCING',
9040                phi.freight_carrier,nvl(phi.freight_carrier,
9041               params.ship_via_lookup_code)),
9042                     decode(g_interface_source_code,'SOURCING',phi.fob,
9043          nvl(phi.fob,params.fob_lookup_code)),
9044                     decode(g_interface_source_code,'CONSUMPTION_ADVICE',phi.pay_on_code,
9045                            x_pay_on_code),
9046                     decode(g_interface_source_code,'SOURCING',phi.freight_terms,
9047                        nvl(phi.freight_terms,
9048         params.freight_terms_lookup_code)),
9049                     decode(g_document_type, 'PO',
9050       nvl(phi.confirming_order_flag,'N'),
9051       'PA',nvl(phi.confirming_order_flag,'N'),
9052       phi.confirming_order_flag),
9053                     phi.currency_code,
9054                     phi.rate_type_code,
9055                     --<SOURCING TO PO FPH>bug# 2430982
9056                     --phi.rate_date,
9057                     nvl(phi.rate_date,decode(g_interface_source_code,'SOURCING',decode(phi.rate_type_code,'User',sysdate),phi.rate_date)),
9058         --
9059                     phi.rate,
9060                     decode(g_document_type, 'PO',
9061 			nvl(params.acceptance_required_flag,'N'),        /* Bug 7518967 : Default Acceptance Required Check ER: Geting default acceptance_required_flag */
9062 			'PA',nvl(params.acceptance_required_flag,'N'),
9063 			params.acceptance_required_flag),
9064                     decode(g_document_type, 'PO',
9065       nvl(phi.firm_flag,'N'),
9066       'PA',nvl(phi.firm_flag,'N'),
9067       phi.firm_flag),
9068                     decode(g_document_type, 'PO',
9069       nvl(phi.min_release_amount,params.min_rel_amount),
9070       'PA',nvl(phi.min_release_amount,params.min_rel_amount),
9071       null),
9072         phi.document_subtype,
9073                     l_shipping_control    -- <INBOUND LOGISTICS FPJ>
9074                FROM po_headers_interface phi2,
9075                     po_lines_interface pli
9076               WHERE phi2.interface_header_id = phi.interface_header_id
9077                 AND pli.interface_header_id=phi2.interface_header_id
9078                 AND pli.interface_line_id = x_min_interface_line_id)
9079          WHERE interface_header_id = x_interface_header_id;
9080 
9081          IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9082              PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9083                                  p_token    => l_progress,
9084                                  p_message  => 'Sourcing to FPH-6 ends');
9085          END IF;
9086 
9087     END IF;/* of new/add */
9088 
9089     l_progress:='110';
9090 
9091     IF (g_document_subtype = 'RELEASE') THEN
9092 
9093        select po_header_id
9094        into   x_po_header_id
9095        from   po_headers_interface
9096        where  interface_header_id = x_interface_header_id;
9097 
9098         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9099             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9100                                 p_token    => l_progress,
9101                                 p_message  => 'Setup interface:Before release update '||x_po_header_id);
9102         END IF;
9103 
9104        -- Bug 623679, lpo, 02/27/98
9105        -- Added a filter 'phi.interface_header_id = x_interface_header_id'
9106        -- for performance.
9107 /*  Bug no:714303.
9108     The subquery(select stmt) was returning multiple rows
9109     while trying to create release using the manual option
9110     if there are more than one line for the same item
9111     in the referenced blanket agreement.
9112 */
9113 /*Bug 971798
9114   If the blanket agrement has lines which has expired (new feauture in r11)
9115   ,then we should not be considering those lines while matching.
9116 */
9117 
9118     -- Added note_to_vendor - iali 08/26/99
9119 /*Bug 1391523 . Added market price to the update  statement */
9120 
9121    /* Enh : 1660036 - Check the uom convert profile value. If it is set to yes
9122       we do not check if the Req uom is same as BPA uom. We create the release
9123       with the quantity and uom converted to the BPA uom */
9124 
9125  /* CONSIGNED FPI : For consumption PO we do not update the interface table with
9126    requisition values */
9127  IF g_interface_source_code <> 'CONSUMPTION_ADVICE' THEN
9128 
9129      -- Bug 2707576 - In 115.142, removed the IF statement and ELSE clause
9130      -- for x_uom_convert, since UOM checking is now handled in
9131      -- source_blanket_line.
9132 
9133        l_progress:='120';
9134        UPDATE po_lines_interface pli2
9135        SET (
9136             line_num,
9137             item_id,
9138             category_id,
9139             item_description,
9140             unit_of_measure,
9141             list_price_per_unit,
9142       market_price,
9143             base_unit_price,  -- <FPJ Advanced Price>
9144             unit_price,
9145             quantity,
9146             amount,                                           -- <SERVICES FPJ>
9147             taxable_flag,
9148             type_1099,
9149             negotiated_by_preparer_flag,
9150             closed_code,
9151             item_revision,
9152             un_number_id,
9153             hazard_class_id,
9154             -- contract_num,   -- <GC FPJ>
9155             line_type_id,
9156             vendor_product_num,
9157             qty_rcv_tolerance,
9158             over_tolerance_error_flag,
9159             firm_flag,
9160             min_release_amount,
9161             price_type,
9162             transaction_reason_code,
9163             line_location_id,
9164             need_by_date,
9165       --togeorge 09/27/2000
9166       --added note to receiver
9167       note_to_receiver,
9168             from_header_id,
9169             from_line_id,
9170       receipt_required_flag,
9171 --DWR4{
9172             tax_status_indicator,
9173       note_to_vendor,
9174 --DWR4}
9175             --togeorge 09/27/2000
9176       --added oke columns
9177       oke_contract_header_id,
9178       oke_contract_version_id,
9179 -- start of bug 1548597
9180             secondary_unit_of_measure,
9181             secondary_quantity,
9182             preferred_grade,
9183 -- end of bug 1548597
9184             drop_ship_flag,   --  <DropShip FPJ>
9185             vmi_flag  -- VMI FPH
9186       )=
9187        (SELECT
9188             nvl(pli.line_num, pol.line_num),
9189             nvl(pli.item_id,prl.item_id),
9190             nvl(pli.category_id,prl.category_id),
9191             nvl(pli.item_description,prl.item_description),
9192             nvl(pli.unit_of_measure,prl.unit_meas_lookup_code),
9193             pli.list_price_per_unit,
9194       pli.market_price,
9195             nvl(pli.base_unit_price,prl.base_unit_price),     -- <FPJ Advanced Price>
9196             nvl(pli.unit_price,prl.unit_price),
9197             nvl(pli.quantity,prl.quantity),
9198             nvl(pli.amount, prl.amount),                      -- <SERVICES FPJ>
9199             pli.taxable_flag,
9200             pli.type_1099,
9201             nvl(pli.negotiated_by_preparer_flag,'N'),
9202             nvl(pli.closed_code,'OPEN'),
9203             nvl(pli.item_revision,prl.item_revision),
9204             nvl(pli.un_number_id,prl.un_number_id),
9205             nvl(pli.hazard_class_id,prl.hazard_class_id),
9206             -- pli.contract_num,         -- <GC FPJ>
9207             nvl(pli.line_type_id,prl.line_type_id),
9208             nvl(pli.vendor_product_num,prl.suggested_vendor_product_code),
9209             pli.qty_rcv_tolerance,
9210             pli.over_tolerance_error_flag,
9211             nvl(pli.firm_flag,'N'),
9212             nvl(pli.min_release_amount,params.min_rel_amount),
9213             nvl(pli.price_type,params.price_type_lookup_code),
9214             nvl(pli.transaction_reason_code,prl.transaction_reason_code),
9215             pli.line_location_id,
9216             nvl(pli.need_by_date,prl.need_by_date),
9217       --togeorge 09/27/2000
9218       --added note to receiver
9219       nvl(pli.note_to_receiver,prl.note_to_receiver),
9220             pli.from_header_id,
9221             pli.from_line_id,
9222       nvl(pli.receipt_required_flag,plt.receiving_flag),
9223 --DWR4{
9224             prl.tax_status_indicator,
9225       nvl(pli.note_to_vendor, prl.note_to_vendor),
9226 --DWR4}
9227             --togeorge 09/27/2000
9228       --added oke columns
9229       nvl(pli.oke_contract_header_id,prl.oke_contract_header_id),
9230       nvl(pli.oke_contract_version_id,prl.oke_contract_version_id),
9231 -- start of 1548597
9232             nvl(pli.secondary_unit_of_measure,prl.secondary_unit_of_measure),
9233             nvl(pli.secondary_quantity,prl.secondary_quantity),
9234             nvl(pli.preferred_grade,prl.preferred_grade),
9235 -- end of 1548597
9236             prl.drop_ship_flag,   --  <DropShip FPJ>
9237             prl.vmi_flag  -- VMI FPH
9238        FROM po_lines_interface pli,
9239             po_headers_interface phi,
9240             po_requisition_lines_all prl,  --<Shared Proc FPJ>
9241             po_line_types plt,
9242             po_lines_all pol  --<Shared Proc FPJ>
9243       WHERE pli.interface_line_id = pli2.interface_line_id
9244         AND pli.interface_header_id = phi.interface_header_id
9245         AND phi.interface_header_id = x_interface_header_id
9246         AND pli.requisition_line_id = prl.requisition_line_id(+)
9247         AND plt.line_type_id = nvl(prl.line_type_id,pli.line_type_id)
9248   AND pol.po_header_id = x_po_header_id
9249 -- 2082757 : new
9250         AND pol.line_num = po_interface_s.source_blanket_line(
9251                                 x_po_header_id,
9252                                 prl.requisition_line_id,
9253                                 pli.line_num, -- Bug 2707576:
9254                                 NVL(x_uom_convert,'N'),
9255                                 g_purchasing_ou_id  --<Shared Proc FPJ>
9256                            )
9257        )
9258 
9259 /* 2082757: Following logic is now coded in new function source_blanket_line
9260 2082757 */
9261        WHERE pli2.interface_header_id = x_interface_header_id;
9262 
9263  /* CONSIGNED FPI Start */
9264  ELSE  -- CONSIGNED FPI
9265      l_progress:='130';
9266      UPDATE po_lines_interface pli2
9267          SET (
9268             po_header_id,
9269             negotiated_by_preparer_flag,
9270             firm_flag
9271       )=
9272        (SELECT
9273             x_po_header_id,
9274             nvl(pli.negotiated_by_preparer_flag,'N'),
9275             nvl(pli.firm_flag,'N')
9276        FROM po_lines_interface pli,
9277             po_headers_interface phi
9278       WHERE pli.interface_line_id = pli2.interface_line_id
9279         AND pli.interface_header_id = phi.interface_header_id
9280         AND phi.interface_header_id = x_interface_header_id);
9281 
9282  END IF;
9283  /* CONSIGNED FPI End */
9284 
9285        -- End of fix. Bug 623679, lpo, 02/27/98
9286 
9287         l_progress:='140';
9288         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9289             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9290                                 p_token    => l_progress,
9291                                 p_message  => 'Setup interface: After release update');
9292         END IF;
9293 
9294     ELSE  /* For PO/RFQ/PA */
9295     /*
9296     ** Note:  We do not multiple unit_price or quantity * rate
9297     ** in this statement. This logic is in the create_line stmt.
9298     */
9299     /* Bug 567402 ecso 11/15/97
9300     ** Get the receipt_required_flag from po_line_type table
9301     */
9302 
9303     -- Bug 623679, lpo, 02/27/98
9304     -- Added a filter 'phi.interface_header_id = x_interface_header_id'
9305     -- for performance.
9306 
9307     -- Bug 694504. frkhan 07/07/98. Removed decode for vendor_product_num so
9308     -- it is updated for RFQs also.
9309 
9310     -- Added note_to_vendor - iali 08/26/99
9311 /*Bug 1391523 . Added market price to the update  statement */
9312 
9313     l_progress:='150';
9314     UPDATE po_lines_interface pli2
9315        SET (
9316             line_num,
9317             item_id,
9318             job_id,                                           -- <SERVICES FPJ>
9319             category_id,
9320             item_description,
9321             unit_of_measure,
9322             list_price_per_unit,
9323       market_price,
9324             base_unit_price,  -- <FPJ Advanced Price>
9325             unit_price,
9326             quantity,
9327             amount,                                           -- <SERVICES FPJ>
9328             taxable_flag,
9329             type_1099,
9330             negotiated_by_preparer_flag,
9331             closed_code,
9332             item_revision,
9333             un_number_id,
9334             hazard_class_id,
9335             -- contract_num,       -- <GC FPJ>
9336             line_type_id,
9337             vendor_product_num,
9338             qty_rcv_tolerance,
9339             over_tolerance_error_flag,
9340             firm_flag,
9341             min_release_amount,
9342             price_type,
9343             transaction_reason_code,
9344             line_location_id,
9345             need_by_date,
9346             ship_to_organization_id,
9347       note_to_receiver,
9348             from_header_id,
9349             from_line_id,
9350       receipt_required_flag,
9351             tax_status_indicator,
9352       note_to_vendor,
9353       oke_contract_header_id,
9354       oke_contract_version_id,
9355             secondary_unit_of_measure,
9356             secondary_quantity,
9357             preferred_grade,
9358             drop_ship_flag,   --  <DropShip FPJ>
9359             vmi_flag,      -- bug 2738820
9360             supplier_ref_number, --<CONFIG_ID FPJ>
9361             effective_date,                                   -- <SERVICES FPJ>
9362             expiration_date,                                  -- <SERVICES FPJ>
9363             contractor_first_name,                            -- <SERVICES FPJ>
9364             contractor_last_name                              -- <SERVICES FPJ>
9365       )=
9366     (SELECT
9367             pli.line_num,
9368             nvl(pli.item_id,prl.item_id),
9369             nvl(pli.job_id, prl.job_id),                      -- <SERVICES FPJ>
9370             nvl(pli.category_id,prl.category_id),
9371             nvl(pli.item_description,prl.item_description),
9372             nvl(pli.unit_of_measure,prl.unit_meas_lookup_code),
9373             pli.list_price_per_unit,
9374       pli.market_price,
9375             nvl(pli.base_unit_price,prl.base_unit_price),     -- <FPJ Advanced Price>
9376             nvl(pli.unit_price,prl.unit_price),
9377             --<Bug 3306848 Its possible to have no backing req in which case
9378             --the quantity is taken from interface table.
9379             decode ( prl.order_type_lookup_code          -- <BUG 3275750, 3306848 START>
9380                    , 'FIXED PRICE' , NULL
9381                    , 'RATE'   ,      NULL
9382                    ,                 nvl(pli.quantity,prl.quantity)
9383                    ),                                    -- <BUG 3275750, 3306848 END>
9384             nvl(pli.amount, prl.amount),                      -- <SERVICES FPJ>
9385             pli.taxable_flag,
9386             pli.type_1099,
9387             nvl(pli.negotiated_by_preparer_flag,'N'),
9388             decode(g_document_type, 'PO',
9389     nvl(pli.closed_code,'OPEN'), null),
9390             nvl(pli.item_revision,prl.item_revision),
9391             nvl(pli.un_number_id,prl.un_number_id),
9392             nvl(pli.hazard_class_id,prl.hazard_class_id),
9393             -- pli.contract_num,       -- <GC FPJ>
9394             nvl(pli.line_type_id,prl.line_type_id),
9395             nvl(pli.vendor_product_num,prl.suggested_vendor_product_code),
9396             pli.qty_rcv_tolerance,
9397             pli.over_tolerance_error_flag,
9398             nvl(pli.firm_flag,'N'),
9399             --<SOURCING TO PO FPH>bug# 2438142 added min_release_amount for PA
9400             decode(g_document_type, 'PO',
9401     nvl(pli.min_release_amount,params.min_rel_amount),
9402             'PA',nvl(pli.min_release_amount,params.min_rel_amount),null),
9403             decode(g_document_type, 'PO',
9404     nvl(pli.price_type,params.price_type_lookup_code),
9405     null),
9406             nvl(pli.transaction_reason_code,prl.transaction_reason_code),
9407             pli.line_location_id,
9408             nvl(pli.need_by_date,prl.need_by_date),
9409             nvl(pli.ship_to_organization_id,prl.destination_organization_id),
9410       nvl(pli.note_to_receiver,prl.note_to_receiver),
9411             pli.from_header_id,
9412             pli.from_line_id,
9413       nvl(pli.receipt_required_flag,plt.receiving_flag),
9414             prl.tax_status_indicator,
9415       nvl(pli.note_to_vendor, prl.note_to_vendor),
9416             -- 2702892 Added the decode for consigned:
9417             decode(pli.consigned_flag,'Y',null,
9418         nvl(pli.oke_contract_header_id,prl.oke_contract_header_id)),
9419             decode(pli.consigned_flag,'Y',null,
9420         nvl(pli.oke_contract_version_id,prl.oke_contract_version_id)),
9421             nvl(pli.secondary_unit_of_measure,prl.secondary_unit_of_measure),
9422             nvl(pli.secondary_quantity,prl.secondary_quantity),
9423             nvl(pli.preferred_grade,prl.preferred_grade),
9424             prl.drop_ship_flag,   --  <DropShip FPJ>
9425             prl.vmi_flag,   -- bug 2738820
9426             prl.supplier_ref_number, --<CONFIG_ID FPJ>
9427             -- <SERVICES FPJ START>
9428             nvl(pli.effective_date, prl.assignment_start_date),
9429             nvl(pli.expiration_date, prl.assignment_end_date),
9430             nvl(pli.contractor_first_name, prl.candidate_first_name),
9431             nvl(pli.contractor_last_name, prl.candidate_last_name)
9432             -- <SERVICES FPJ END>
9433        FROM po_lines_interface pli,
9434             po_headers_interface phi,
9435             po_requisition_lines_all prl,  --<Shared Proc FPJ>
9436             po_line_types plt
9437       WHERE pli.interface_line_id = pli2.interface_line_id
9438         AND pli.interface_header_id = phi.interface_header_id
9439         AND phi.interface_header_id = x_interface_header_id
9440         AND pli.requisition_line_id = prl.requisition_line_id(+)
9441         AND plt.line_type_id = nvl(prl.line_type_id,pli.line_type_id))
9442       WHERE pli2.interface_header_id = x_interface_header_id;
9443 
9444       -- End of fix. Bug 623679, lpo, 02/27/98
9445 
9446     END IF;
9447 
9448     l_progress:='160';
9449 
9450     /* RFQs do not have distributions , but we still
9451   do the insert.  We get the deliver to information
9452   from the distribution record. */
9453 
9454 
9455     IF (g_document_type in ('RFQ', 'PO')) THEN
9456 
9457         l_progress:='170';
9458         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9459             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9460                                 p_token    => l_progress,
9461                                 p_message  => 'Before insert into Distribution interface');
9462         END IF;
9463 
9464        INSERT INTO po_distributions_interface
9465           (interface_header_id,
9466            interface_line_id,
9467            interface_distribution_id,
9468            distribution_num,
9469            charge_account_id,
9470            set_of_books_id,
9471            quantity_ordered,
9472            amount_ordered,                                    -- <SERVICES FPJ>
9473            rate,
9474            rate_date,
9475            req_distribution_id,
9476            deliver_to_location_id,
9477            deliver_to_person_id,
9478            encumbered_flag,
9479      gl_encumbered_date,
9480            gl_encumbered_period_name,
9481            destination_type_code,
9482            destination_organization_id,
9483            destination_subinventory,
9484            budget_account_id,
9485            accrual_account_id,
9486            variance_account_id,
9487 
9488            --< Shared Proc FPJ Start >
9489            dest_charge_account_id,
9490            dest_variance_account_id,
9491            --< Shared Proc FPJ End >
9492 
9493            wip_entity_id,
9494            wip_line_id,
9495            wip_repetitive_schedule_id,
9496            wip_operation_seq_num,
9497            wip_resource_seq_num,
9498            bom_resource_id,
9499            prevent_encumbrance_flag,
9500            project_id,
9501            task_id,
9502            end_item_unit_number,
9503            expenditure_type,
9504            project_accounting_context,
9505            destination_context,
9506            expenditure_organization_id,
9507            expenditure_item_date,
9508 --FRKHAN 12/8/98 copy recovery rate and tax amounts
9509           tax_recovery_override_flag, --<eTax Integration R12>
9510      recovery_rate,
9511      recoverable_tax,
9512      nonrecoverable_tax,
9513      -- OGM_0.0 change.
9514      award_id,
9515            --togeorge 09/27/2000
9516      --added oke columns
9517      oke_contract_line_id,
9518      oke_contract_deliverable_id
9519      )
9520        SELECT pli.interface_header_id,
9521            pli.interface_line_id,
9522            po_distributions_interface_s.nextval,
9523            prd.distribution_num,
9524            prd.code_combination_id,
9525            prd.set_of_books_id,
9526            prd.req_line_quantity,
9527            decode ( g_interface_source_code                    -- <BUG 3316071>
9528                   , 'SOURCING' , prd.req_line_amount * pli.amount/prl.amount
9529                   ,              prd.req_line_amount
9530                   ),
9531            phi.rate,
9532            phi.rate_date,
9533            prd.distribution_id,
9534            prl.deliver_to_location_id,
9535            prl.to_person_id,
9536            prd.encumbered_flag,
9537      prd.gl_encumbered_date,
9538            prd.gl_encumbered_period_name,
9539            prl.destination_type_code,
9540            prl.destination_organization_id,
9541            prl.destination_subinventory,
9542            prd.budget_account_id,
9543            prd.accrual_account_id,
9544            prd.variance_account_id,
9545 
9546            --< Shared Proc FPJ Start >
9547            -- For non SPS case (common case), set Destination Accounts to NULL
9548            NULL, -- dest_charge_account_id
9549            NULL, -- dest_variance_account_id
9550            --< Shared Proc FPJ End >
9551 
9552            prl.wip_entity_id,
9553            prl.wip_line_id,
9554            prl.wip_repetitive_schedule_id,
9555            prl.wip_operation_seq_num,
9556            prl.wip_resource_seq_num,
9557            prl.bom_resource_id,
9558            prd.prevent_encumbrance_flag,
9559            prd.project_id,
9560            prd.task_id,
9561            prd.end_item_unit_number,
9562            prd.expenditure_type,
9563            prd.project_accounting_context,
9564            prl.destination_context,
9565            prd.expenditure_organization_id,
9566            prd.expenditure_item_date,
9567      prd.tax_recovery_override_flag,     --<eTax Integration R12>
9568      prd.recovery_rate,
9569      prd.recoverable_tax,
9570      prd.nonrecoverable_tax,
9571      prd.award_id, -- OGM_0.0 change
9572            --togeorge 09/27/2000
9573      --added oke columns
9574            -- 2702892 Added the decode for consigned:
9575            decode(pli.consigned_flag,'Y',null,
9576        prd.oke_contract_line_id),
9577            decode(pli.consigned_flag,'Y',null,
9578        prd.oke_contract_deliverable_id)
9579          FROM po_requisition_lines_all prl,  --<Shared Proc FPJ>
9580            po_req_distributions_all prd,  --<Shared Proc FPJ>
9581            po_lines_interface pli,
9582            po_headers_interface phi
9583         WHERE prd.requisition_line_id = prl.requisition_line_id
9584           AND prl.requisition_line_id  = pli.requisition_line_id -- Bug:1563888
9585           AND pli.interface_header_id = phi.interface_header_id
9586           AND phi.interface_header_id = x_interface_header_id;
9587 
9588           SELECT count(*)
9589           INTO   x_count_dist
9590           FROM  po_distributions_interface
9591     WHERE interface_header_id = x_interface_header_id;
9592 
9593         l_progress:='180';
9594         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9595             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9596                                 p_token    => l_progress,
9597                                 p_message  => 'Count from dist iterface is '||x_count_dist);
9598         END IF;
9599 
9600      END IF;
9601 
9602           --<SOURCING TO PO FPH START>
9603         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9604             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9605                                 p_token    => l_progress,
9606                                 p_message  => 'Sourcing to FPH-7 starts');
9607         END IF;
9608     --default the distribution for non req backing negotiations.The above
9609     --insert only takes care of the interface lines which are backed by
9610     --requisitions.
9611     if g_interface_source_code='SOURCING' then
9612 
9613        IF (PO_LOG.d_stmt) THEN
9614          PO_LOG.stmt(g_log_head || l_api_name, 190, 'Defaulting dists interface for sourcing.');
9615        END IF;
9616 
9617           l_progress:='190';
9618           for i in c_default_distribution
9619         loop
9620 
9621          -- <Complex Work R12 Start>
9622          IF (PO_LOG.d_stmt) THEN
9623            PO_LOG.stmt(g_log_head || l_api_name, 190, 'i.interface_line_id', i.interface_line_id);
9624          END IF;
9625 
9626 
9627          IF (p_is_complex_work_po) THEN
9628 
9629            -- create complex work PO from sourcing
9630 
9631            IF (i.ship_to_organization_id IS NOT NULL) THEN
9632 
9633              l_ship_to_org_id := i.ship_to_organization_id;
9634 
9635            ELSE
9636 
9637              -- SQL WHAT: derive default ship_to_organization_id
9638              -- SQL WHY: the ship_to_organization is optional from sourcing
9639              BEGIN
9640                SELECT hrl.inventory_organization_id
9641                  INTO l_ship_to_org_id
9642                  FROM hr_locations_all hrl
9643                 WHERE hrl.location_id = i.ship_to_location_id
9644                   AND hrl.ship_to_site_flag = 'Y';
9645              EXCEPTION
9646                 WHEN no_data_found THEN
9647                   l_ship_to_org_id := NULL;
9648              END;
9649 
9650              l_ship_to_org_id := NVL(l_ship_to_org_id,
9651                                      params.inventory_organization_id);
9652 
9653            END IF;  -- IF i.ship_to_organization_id IS NOT NULL
9654 
9655            -- SQL WHAT: insert minimal data into po_distributions_interface
9656            -- SQL WHY: this is required because the global interface cursor
9657            -- joins to the distributions interface table and uses
9658            -- some of the following fields for defaulting purposes
9659 
9660            INSERT INTO po_distributions_interface(
9661              interface_header_id
9662            , interface_line_id
9663            , interface_distribution_id
9664            , destination_type_code
9665            , deliver_to_location_id
9666            , destination_organization_id
9667            ) VALUES (
9668              i.interface_header_id
9669            , i.interface_line_id
9670            , PO_DISTRIBUTIONS_INTERFACE_S.nextval
9671            , 'EXPENSE'
9672            , i.ship_to_location_id
9673            , l_ship_to_org_id
9674            );
9675 
9676            IF (PO_LOG.d_stmt) THEN
9677              PO_LOG.stmt(g_log_head || l_api_name, 190, 'Num rows inserted', SQL%ROWCOUNT);
9678            END IF;
9679 
9680          ELSE
9681 
9682            -- non-complex work po from sourcing
9683 
9684            po_negotiations_sv2.default_po_dist_interface(
9685               i.interface_header_id,
9686               i.interface_line_id,
9687               i.item_id,
9688               i.category_id,
9689               i.ship_to_organization_id,
9690               i.ship_to_location_id,
9691               null, --deliver_to_person_id
9692               params.sob_id,
9693               params.coa_id,
9694               i.line_type_id,
9695               i.quantity,
9696               i.amount,  -- <SERVICES FPJ>
9697               i.rate,
9698               i.rate_date,
9699               i.vendor_id,
9700               i.vendor_site_id,
9701               i.agent_id,
9702               nvl(params.po_encumbrance_flag, 'N'),
9703               NULL,
9704               i.document_subtype,
9705               null,
9706               null,
9707               null,
9708               null,
9709               null,
9710               null,
9711               null,
9712               null,
9713               null,
9714               null,
9715               null,
9716               null,
9717               null,
9718               null,
9719               null, --project_accounting_context
9720               g_purchasing_ou_id, --< Shared Proc FPJ >
9721               i.unit_price  --<BUG 3407630>
9722               );
9723          END IF;  -- IF p_is_complex_work_po
9724          -- <Complex Work R12 End>
9725 
9726         end loop;
9727           end if;
9728 
9729         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9730             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9731                                 p_token    => l_progress,
9732                                 p_message  => 'Sourcing to FPH-7 ends');
9733         END IF;
9734           --<SOURCING TO PO FPH END>
9735 
9736 
9737     /* If we do not have a supplier item number, get this
9738        information from the ASL */
9739 
9740     --<SOURCING TO PO FPH>
9741     --for blankets also
9742     IF (g_document_type in ('PO','PA')) THEN
9743 
9744     l_progress:='200';
9745   OPEN C;
9746   LOOP
9747 
9748       Fetch C into x_rowid,
9749          x_item_id,
9750          x_vendor_id,
9751          x_vendor_site_id,
9752          x_organization_id;
9753 --added by jbalakri for 1754916
9754             x_asl_id:=NULL;
9755             x_vendor_product_num:=NULL;
9756             x_purchasing_uom:=NULL;
9757 --end of add for 1754916.
9758 
9759         po_autosource_sv.get_asl_info(x_item_id,
9760      x_vendor_id,
9761      x_vendor_site_id,
9762      x_organization_id,
9763      x_asl_id,
9764      x_vendor_product_num,
9765      x_purchasing_uom);
9766 
9767       if (x_vendor_product_num is not null) then
9768           update po_lines_interface
9769           set    vendor_product_num = x_vendor_product_num
9770     where  rowid = x_rowid;
9771 
9772       end if;
9773 
9774       Exit when C%NOTFOUND;
9775 
9776 
9777   END LOOP;
9778   CLOSE C;
9779 
9780     END IF;
9781 
9782   l_progress:='210';
9783   --< Shared Proc FPJ Start >
9784   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9785       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
9786                           p_token    => l_progress,
9787                           p_message  => 'Calling generate_shared_proc_accounts');
9788   END IF;
9789 
9790   -- <Complex Work R12 Start>: Shared proc. not supported with complex work
9791   IF (NOT p_is_complex_work_po) THEN
9792     generate_shared_proc_accounts(x_interface_header_id);
9793   END IF;
9794   -- <Complex Work R12 End>
9795   --< Shared Proc FPJ End >
9796 
9797   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9798       PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
9799   END IF;
9800 
9801 EXCEPTION
9802   WHEN OTHERS THEN
9803      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
9804          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
9805                             p_progress => l_progress);
9806      END IF;
9807      wrapup(x_interface_header_id);
9808      po_message_s.sql_error('SETUP INTERFACE TABLES',l_progress,sqlcode);
9809      raise;
9810 END SETUP_INTERFACE_TABLES;
9811 
9812 
9813 /* ============================================================================
9814      NAME: WRAPUP
9815      DESC: Wrapup
9816      ARGS: x_interface_header_id IN number
9817      ALGR:
9818    ==========================================================================*/
9819 PROCEDURE wrapup(x_interface_header_id IN number) IS
9820 BEGIN
9821     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9822         PO_DEBUG.debug_begin(p_log_head => g_log_head||'wrapup');
9823     END IF;
9824 
9825    DELETE po_distributions_interface
9826    WHERE interface_header_id = x_interface_header_id;
9827 
9828    -- <SERVICES FPJ START>
9829    DELETE po_price_diff_interface
9830    WHERE  interface_header_id = x_interface_header_id;
9831    -- <SERVICES FPJ END>
9832 
9833    -- <Complex Work R12 Start>
9834    DELETE po_line_locations_interface
9835    WHERE interface_header_id = x_interface_header_id;
9836    -- <Complex Work R12 End>
9837 
9838    DELETE po_lines_interface
9839    WHERE interface_header_id = x_interface_header_id;
9840 
9841 
9842    DELETE po_headers_interface
9843    WHERE interface_header_id = x_interface_header_id;
9844 
9845     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
9846         PO_DEBUG.debug_end(p_log_head => g_log_head||'wrapup');
9847     END IF;
9848 END wrapup;
9849 
9850 /* ============================================================================
9851      NAME: GROUP_INTERFACE_LINES
9852      DESC: Group interface lines
9853      ARGS: x_interface_header_id IN number
9854      ALGR:
9855    ==========================================================================*/
9856 -- <Complex Work R12>: Added parameter p_is_complex_work_po
9857 
9858 PROCEDURE group_interface_lines(
9859   x_interface_header_id    IN number
9860 , p_is_complex_work_po     IN BOOLEAN
9861 )
9862 IS
9863 x_line_num number;
9864 x_shipment_num number;
9865 x_document_num varchar2(30);
9866 x_release_num number;
9867 x_document_type_code varchar2(25);
9868 x_document_subtype varchar2(25);
9869 x_action varchar2(25);
9870 x_requisition_line_id number;
9871 x_interface_line_num number;
9872 x_item_id number;
9873 x_item_description varchar2(240);    -- bgu, Mar. 19, 1999
9874 x_line_type_id number;
9875 x_item_revision varchar2(3);
9876 x_unit_meas_lookup_code varchar2(25);
9877 x_transaction_reason_code varchar2(25);
9878 x_need_by_date date;
9879 --togeorge 09/27/2000
9880 --added note to receiver and oke variables.
9881 x_note_to_receiver po_requisition_lines_all.note_to_receiver%type;
9882 x_oke_contract_header_id number;
9883 x_oke_contract_version_id number;
9884 x_vendor_product_num varchar2(30);  --Bug# 1763933
9885 x_deliver_to_location_id number;
9886 x_destination_org_id number;
9887 x_ship_to_location_id number;
9888 x_po_line_num number;
9889 x_po_line_id number;
9890 x_po_shipment_num number;
9891 x_num_interface_lines number := 1; /* used for incrementing po line number */
9892 x_int_shipment_num number; /* maximum shipment num in interface table */
9893 x_int_line_num number; /* maximum line num in interface table */
9894 -- start of 1548597
9895 x_secondary_unit_of_measure  MTL_UNITS_OF_MEASURE.UNIT_OF_MEASURE%TYPE;
9896 x_preferred_grade            MTL_GRADES.GRADE_CODE%TYPE; --<INVCONV R12> increased to 150
9897 -- end of 1548597
9898 /* Bug 1949160. x_count variable is used as counter to increment in a
9899     loop */
9900 x_count number := 0;
9901 --<SOURCING TO PO FPH START>
9902 x_bid_number number;
9903 x_bid_line_number number;
9904 x_row_id  varchar2(25) := null;
9905 --<SOURCING TO PO FPH END>
9906 
9907 x_vmi_flag       PO_LINES_INTERFACE.VMI_FLAG%TYPE;  /* VMI FPH */
9908 x_drop_ship_flag PO_LINES_INTERFACE.DROP_SHIP_FLAG%TYPE;  --<DropShip FPJ>
9909 
9910 x_source_doc_id         number;   -- FPI GA
9911 x_source_doc_line_id    number;   -- FPI GA
9912 
9913 x_consigned_flag        VARCHAR2(1) := 'N';  --CONSIGNED FPI
9914 x_create_new_line       VARCHAR2(1) := 'N';   --GA FPI
9915 l_supplier_ref_number   PO_LINES_INTERFACE.supplier_ref_number%TYPE; --<CONFIG_ID FPJ>
9916 
9917 l_contract_id PO_LINES_ALL.contract_id%TYPE;       -- <GC FPJ>
9918 
9919 /* Bug 3201308 start */
9920  l_needby_prf  varchar2(1);
9921  l_shipto_prf  varchar2(1);
9922 /* Bug 3201308 end */
9923 
9924 l_api_name CONSTANT VARCHAR2(30) := 'group_interface_lines';
9925 
9926 /*
9927 ** Order by interface_line_id.
9928 ** The front end will always load the lines in the correct order.
9929 ** The front end will load it either by (item_id, unit_price,
9930 ** need_by_date, requisition_line_id) or by the order in which
9931 ** the user selects.
9932 ** DEBUG.  For now from the front end the users will not be able to
9933 ** determine the order in which they want to lines to be placed.
9934 ** removed order by interface_line_id and replaced it with the
9935 ** above order by.
9936 */
9937 /** bgu, Mar. 19, 1999
9938  *  BUG 853749
9939  *  For one time item, item description will distinguish items.
9940  */
9941 
9942 /* Bug 1949160. Created a cursor to retrieve requisition line-id */
9943 CURSOR interface_lines_temp IS
9944   SELECT pli.requisition_line_id
9945   FROM po_lines_interface pli
9946   WHERE pli.interface_header_id = x_interface_header_id
9947 -- bug 4000047: start: requisition lines should be entered
9948 -- into PO the same order they appear in the requisition
9949   ORDER BY pli.requisition_line_id;
9950 -- bug 4000047: end
9951 
9952 CURSOR interface_lines IS
9953    SELECT pli.action,
9954           pli.requisition_line_id,
9955           pli.line_num,
9956           pli.item_id,
9957           pli.item_description,     -- bgu, Mar. 19, 1999
9958           pli.line_type_id,
9959           pli.item_revision,
9960           pli.unit_of_measure,
9961           pli.transaction_reason_code,
9962           pli.need_by_date,
9963           pli.note_to_receiver,
9964           pli.oke_contract_header_id,
9965           pli.oke_contract_version_id,
9966           pli.vendor_product_num,   -- Bug# 1763933
9967           pld.deliver_to_location_id,
9968           pld.destination_organization_id,
9969           pli.secondary_unit_of_measure,
9970           pli.preferred_grade,
9971           pli.bid_number,
9972           pli.bid_line_number,
9973           pli.rowid,
9974           pli.vmi_flag,   --  VMI FPH
9975           pli.drop_ship_flag,   --  <DropShip FPJ>
9976           pli.from_header_id,   -- FPI GA
9977           pli.from_line_id,      -- FPI GA
9978           pli.consigned_flag,    -- CONSIGNED FPI
9979           pli.contract_id,       -- <GC FPJ>
9980           pli.supplier_ref_number --<CONFIG_ID FPJ>
9981    FROM po_lines_interface pli,
9982         po_distributions_interface pld
9983    WHERE pli.interface_header_id=x_interface_header_id
9984    AND   pli.interface_line_id=pld.interface_line_id
9985    AND   pld.interface_distribution_id =
9986             ( SELECT min(pdi2.interface_distribution_id)
9987               FROM   po_distributions_interface pdi2
9988               WHERE  pdi2.interface_line_id = pli.interface_line_id)
9989    ORDER BY pli.item_id,
9990             pli.item_description,
9991             pli.unit_price,
9992             pli.need_by_date,
9993             pli.requisition_line_id;
9994 
9995   l_progress VARCHAR2(3) := '000';                  --< Bug 3210331 >
9996 
9997   --<INVCONV R12 START>
9998   l_grade_control_flag  MTL_SYSTEM_ITEMS.GRADE_CONTROL_FLAG%TYPE;
9999   l_line_grade    MTL_GRADES.GRADE_CODE%TYPE;
10000   --<INVCONV R12 END>
10001 
10002   l_max_iface_line_num   NUMBER;        -- <Complex Work R12>
10003 
10004 
10005 BEGIN
10006 
10007   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10008       PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
10009   END IF;
10010 
10011   -- Bug 3201308 start
10012   -- Get the profile option values to determine grouping criteria
10013   l_needby_prf := fnd_profile.value('PO_NEED_BY_GROUPING');
10014   l_shipto_prf := fnd_profile.value('PO_SHIPTO_GROUPING');
10015   l_progress := '010';
10016   -- Bug 3201308 end
10017 
10018   SELECT phi.document_num,
10019          phi.document_type_code,
10020          phi.document_subtype,
10021          phi.release_num
10022   INTO x_document_num,
10023        x_document_type_code,
10024        x_document_subtype,
10025        x_release_num
10026   FROM po_headers_interface phi
10027   WHERE phi.interface_header_id = x_interface_header_id;
10028 
10029   IF (g_document_type = 'RFQ') THEN
10030     x_document_subtype := 'RFQ';
10031   END IF;
10032 
10033   l_progress := '020';
10034   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10035       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10036                           p_token    => l_progress,
10037                           p_message  => 'Mode is:'|| g_mode);
10038   END IF;
10039 
10040   --<SOURCING TO PO FPH>
10041   --modify to group blanket lines also
10042 
10043   IF (x_document_type_code IN ('PO', 'PA', 'RFQ')) THEN
10044 
10045     IF (g_group_code = 'REQUISITION') THEN
10046 
10047       IF (g_mode = 'NEW') THEN
10048 
10049 
10050         -- Create a new PO/Release with Req. lines in
10051         -- the same order as on the requisition.
10052         -- The interface table will hold the requisition line id
10053         -- that we need to get the req line number from.
10054         -- We need to update the shipment number to 1.
10055 
10056         l_progress := '030';
10057 
10058 
10059         IF ((x_document_subtype IN ('STANDARD', 'PLANNED')) OR
10060             (g_document_type = 'RFQ'))
10061         THEN
10062 
10063           -- Bug 3825483
10064           -- For Standard and Planned POs and RFQs, the line number
10065           -- will be the same as the req line number if the profile
10066           -- is set to 'Y' otherwise use sequential numbers
10067 
10068           IF (FND_PROFILE.VALUE('PO_USE_REQ_NUM_IN_AUTOCREATE') = 'Y') THEN
10069 
10070             -- use requisition numbers
10071 
10072             l_progress:='035';
10073 
10074             UPDATE po_lines_interface pli
10075             SET pli.shipment_num = 1,
10076                 pli.line_num =
10077                    (
10078                      SELECT prl.line_num
10079                      FROM   po_requisition_lines_all prl  -- Bug 3903445
10080                      WHERE  prl.requisition_line_id = pli.requisition_line_id
10081                    )
10082             WHERE pli.interface_header_id = x_interface_header_id
10083             AND   pli.line_num is null
10084             AND   pli.shipment_num is null;
10085 
10086           ELSE
10087 
10088             -- use sequential numbers
10089 
10090             l_progress := '040';
10091 
10092             OPEN interface_lines_temp;
10093             LOOP
10094 
10095               x_count := x_count + 1;
10096 
10097               FETCH interface_lines_temp into x_requisition_line_id;
10098               EXIT WHEN interface_lines_temp%NOTFOUND;
10099 
10100               l_progress := '050';
10101 
10102               UPDATE po_lines_interface pli
10103               SET pli.line_num = x_count,
10104                   pli.shipment_num = 1
10105               WHERE pli.requisition_line_id = x_requisition_line_id
10106               AND   pli.interface_header_id = x_interface_header_id
10107               AND   pli.line_num IS NULL
10108               AND   pli.shipment_num IS NULL;
10109 
10110             END LOOP;
10111 
10112             CLOSE interface_lines_temp;
10113 
10114           END IF;  -- if fnd_profile.value(PO_USE_REQ_NUM...) = 'Y'
10115 
10116         ELSE
10117 
10118           -- Document is release case
10119 
10120           l_progress:='060';
10121 
10122           OPEN interface_lines;
10123           LOOP
10124 
10125             l_progress:='070';
10126 
10127             FETCH interface_lines INTO
10128               x_action,
10129               x_requisition_line_id,
10130               x_interface_line_num,
10131               x_item_id,
10132               x_item_description,        -- bgu, Mar. 19, 1999
10133               x_line_type_id,
10134               x_item_revision,
10135               x_unit_meas_lookup_code,
10136               x_transaction_reason_code,
10137               x_need_by_date,
10138               x_note_to_receiver,
10139               x_oke_contract_header_id,
10140               x_oke_contract_version_id,
10141               x_vendor_product_num,      --Bug 1763933
10142               x_deliver_to_location_id,
10143               x_destination_org_id,
10144               x_secondary_unit_of_measure,
10145               x_preferred_grade,
10146               x_bid_number,
10147               x_bid_line_number,
10148               x_row_id,
10149               x_vmi_flag,               --  VMI FPH
10150               x_drop_ship_flag,         --  <DropShip FPJ>
10151               x_source_doc_id ,         -- FPI GA
10152               x_source_doc_line_id,     -- FPI GA
10153               x_consigned_flag,         -- CONSIGNED FPI
10154               l_contract_id,            -- <GC FPJ>
10155               l_supplier_ref_number    --<CONFIG_ID FPJ>
10156             ;
10157 
10158             EXIT WHEN interface_lines%NOTFOUND;
10159 
10160             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10161                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10162                                      p_progress => l_progress,
10163                                      p_name     => 'x_deliver_to_location_id',
10164                                      p_value    => x_deliver_to_location_id);
10165                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10166                                      p_progress => l_progress,
10167                                      p_name     => 'x_destination_org_id',
10168                                      p_value    => x_destination_org_id);
10169                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10170                                      p_progress => l_progress,
10171                                      p_name     => 'x_need_by_date',
10172                                      p_value    => x_need_by_date);
10173                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10174                                      p_progress => l_progress,
10175                                      p_name     => 'x_unit_meas_lookup_code',
10176                                      p_value    => x_unit_meas_lookup_code);
10177                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10178                                      p_progress => l_progress,
10179                                      p_name     => 'x_transaction_reason_code',
10180                                      p_value    => x_transaction_reason_code);
10181             END IF;  -- debug logging
10182 
10183             -- The user did not specify the line that they want the
10184             -- requisition line to be associated with.  We need
10185             -- to find a requisition line that matches it.
10186             -- Find a line that matches, if one does not match, skip
10187             -- the record.  If one does match, update the interface
10188             -- table with the correct line number.
10189 
10190             IF (x_action is NULL) THEN
10191 
10192               l_progress := '080';
10193 
10194               BEGIN
10195 
10196                 -- bug# 2564767: don't compare secondary uom
10197 
10198                 SELECT MIN(pli.line_num),
10199                        pli.po_line_id
10200                 INTO x_po_line_num,
10201                      x_po_line_id
10202                 FROM po_lines_interface pli
10203                 WHERE pli.interface_header_id = x_interface_header_id
10204                 AND pli.line_num IS NOT NULL
10205                 AND pli.line_type_id = x_line_type_id
10206                 AND NVL(pli.item_id, -1) = NVL(x_item_id, -1)
10207                 AND NVL(pli.item_description, 'null' ) =
10208                                                  NVL(x_item_description,'null')
10209                 AND (((pli.item_revision IS NULL) AND (x_item_revision IS NULL))
10210                       OR (pli.item_revision = x_item_revision))
10211                 AND pli.unit_of_measure = x_unit_meas_lookup_code
10212                 AND ( pli.transaction_reason_code IS NULL
10213                       OR pli.transaction_reason_code =
10214                            NVL(x_transaction_reason_code,
10215                                   pli.transaction_reason_code))
10216 
10217                 -- togeorge 09/27/2000
10218                 -- added conditions to compare oke contract num and rev.
10219                 -- line num is different if contract info is diff. on the
10220                 -- same item.
10221                 AND   NVL(pli.oke_contract_header_id,-1) =
10222                                                NVL(x_oke_contract_header_id,-1)
10223                 AND   NVL(pli.oke_contract_version_id,-1) =
10224                                                NVL(x_oke_contract_version_id,-1)
10225                 GROUP BY pli.po_line_id;
10226 
10227               EXCEPTION
10228                 WHEN NO_DATA_FOUND THEN
10229                   IF g_debug_stmt THEN
10230                     PO_DEBUG.debug_stmt(
10231                       p_log_head => g_log_head||l_api_name,
10232                       p_token    => l_progress,
10233                       p_message  => 'NO_DATA_FOUND: '||SQLERRM);
10234                     END IF;
10235                     x_po_line_num := -1;
10236               END;
10237 
10238               l_progress := '090';
10239 
10240               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10241                    PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10242                                        p_token    => l_progress,
10243                                        p_message  => 'Line_num is :'|| x_po_line_num);
10244                    PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10245                                        p_token    => l_progress,
10246                                        p_message  => 'Group_interface_lines progress is :'|| l_progress);
10247               END IF;  -- debug logging
10248 
10249               UPDATE po_lines_interface pli
10250               SET pli.line_num = x_po_line_num
10251               WHERE pli.interface_header_id = x_interface_header_id
10252               AND pli.requisition_line_id = x_requisition_line_id;
10253 
10254               x_interface_line_num := x_po_line_num;
10255 
10256             END IF;  -- if x_action is NULL
10257 
10258           END LOOP;
10259           CLOSE interface_lines;
10260 
10261           -- Bug 3825483
10262           -- For Releases, the shipment number will be the same as
10263           -- the req line number if the profile is set, otherwise
10264           -- sequential numbers are used
10265 
10266           IF (FND_PROFILE.VALUE('PO_USE_REQ_NUM_IN_AUTOCREATE')='Y') THEN
10267 
10268             -- use requisition numbers
10269 
10270             l_progress := '100';
10271 
10272             UPDATE po_lines_interface pli
10273             SET pli.shipment_num =
10274                   ( SELECT prl.line_num
10275                     FROM po_requisition_lines_all prl
10276                     WHERE prl.requisition_line_id = pli.requisition_line_id )
10277             WHERE pli.interface_header_id = x_interface_header_id
10278             AND pli.shipment_num IS NULL;
10279 
10280           ELSE
10281 
10282             -- use sequential numbers
10283 
10284             OPEN interface_lines_temp;
10285             LOOP
10286 
10287               x_count := x_count + 1;
10288 
10289               FETCH interface_lines_temp INTO x_requisition_line_id;
10290               EXIT WHEN interface_lines_temp%NOTFOUND;
10291 
10292               l_progress := '110';
10293 
10294               UPDATE po_lines_interface pli
10295               SET pli.shipment_num = x_count
10296               WHERE pli.requisition_line_id = x_requisition_line_id
10297               AND pli.interface_header_id = x_interface_header_id
10298               AND pli.shipment_num IS NULL;
10299 
10300             END LOOP;
10301             CLOSE interface_lines_temp;
10302 
10303           END IF;  -- if fnd_profile.value(PO_USE_REQ_NUM...) = 'Y'
10304 
10305         END IF;  -- release vs. non release case
10306 
10307       ELSE
10308 
10309         -- mode = 'ADD'
10310         -- add to a po/release with the same order as on the req.
10311 
10312         IF ((x_document_subtype IN ('STANDARD', 'PLANNED'))
10313            OR (g_document_type = 'RFQ'))
10314         THEN
10315 
10316           -- The inteface table will hold the requisition line id that we
10317           -- will use to get the line number.  Select the maximum line number
10318           -- that exists on the purchase order.  Update the line number in
10319           -- the interface talbe to be the req. line number + max po line num.
10320           -- Shipment num should be 1.
10321 
10322           l_progress:='120';
10323 
10324           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10325                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10326                                     p_token    => l_progress,
10327                                     p_message  => 'Group_interface_lines: mode is :'|| g_mode);
10328           END IF;
10329 
10330           SELECT NVL(max(pl.line_num),0)
10331           INTO x_line_num
10332           FROM po_headers_all ph,
10333                po_lines_all pl
10334           WHERE pl.po_header_id = ph.po_header_id
10335           AND ph.segment1 = x_document_num
10336           AND ph.type_lookup_code =
10337                 DECODE(g_document_type, 'RFQ', g_document_type, x_document_subtype)
10338           AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99);
10339 
10340           l_progress:='130';
10341 
10342           OPEN interface_lines_temp;
10343           LOOP
10344 
10345             l_progress := '140';
10346             x_count := x_count + 1;
10347 
10348             FETCH interface_lines_temp INTO x_requisition_line_id;
10349             EXIT WHEN interface_lines_temp%NOTFOUND;
10350 
10351             l_progress := '150';
10352 
10353             UPDATE po_lines_interface pli
10354             SET pli.line_num = x_line_num + x_count,
10355                 pli.shipment_num = 1
10356             WHERE pli.requisition_line_id = x_requisition_line_id
10357             AND pli.interface_header_id = x_interface_header_id
10358             AND pli.line_num IS NULL
10359             AND pli.shipment_num IS NULL;
10360 
10361           END LOOP;
10362           CLOSE interface_lines_temp;
10363 
10364         ELSE
10365 
10366           -- Document is release case
10367 
10368           l_progress:='160';
10369           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10370                       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10371                                           p_token    => l_progress,
10372                                           p_message  => 'Before opening interface_lines cursor');
10373           END IF;
10374 
10375           OPEN interface_lines;
10376           LOOP
10377 
10378             l_progress:='170';
10379 
10380             FETCH interface_lines into
10381               x_action,
10382               x_requisition_line_id,
10383               x_interface_line_num,
10384               x_item_id,
10385               x_item_description,     -- bgu, Mar. 19, 1999
10386               x_line_type_id,
10387               x_item_revision,
10388               x_unit_meas_lookup_code,
10389               x_transaction_reason_code,
10390               x_need_by_date,
10391               x_note_to_receiver,
10392               x_oke_contract_header_id,
10393               x_oke_contract_version_id,
10394               x_vendor_product_num,  --Bug# 1763933
10395               x_deliver_to_location_id,
10396               x_destination_org_id,
10397               x_secondary_unit_of_measure,
10398               x_preferred_grade,
10399               x_bid_number,
10400               x_bid_line_number,
10401               x_row_id,
10402               x_vmi_flag,              -- VMI FPH
10403               x_drop_ship_flag,        --  <DropShip FPJ>
10404               x_source_doc_id ,        -- FPI GA
10405               x_source_doc_line_id,    -- FPI GA
10406               x_consigned_flag,        -- CONSIGNED FPI
10407               l_contract_id,           -- GC FPJ
10408               l_supplier_ref_number    --<CONFIG_ID FPJ>
10409             ;
10410 
10411             EXIT WHEN interface_lines%NOTFOUND;
10412 
10413             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10414                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10415                                      p_progress => l_progress,
10416                                      p_name     => 'x_deliver_to_location_id',
10417                                      p_value    => x_deliver_to_location_id);
10418                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10419                                      p_progress => l_progress,
10420                                      p_name     => 'x_destination_org_id',
10421                                      p_value    => x_destination_org_id);
10422                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10423                                      p_progress => l_progress,
10424                                      p_name     => 'x_need_by_date',
10425                                      p_value    => x_need_by_date);
10426                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10427                                      p_progress => l_progress,
10428                                      p_name     => 'x_unit_meas_lookup_code',
10429                                      p_value    => x_unit_meas_lookup_code);
10430                   PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
10431                                      p_progress => l_progress,
10432                                      p_name     => 'x_transaction_reason_code',
10433                                      p_value    => x_transaction_reason_code);
10434             END IF;
10435 
10436             -- The user did not specify the line that they want the
10437             -- requisition line to be associated with.  We need
10438             -- to find a requisition line that matches it.
10439             -- Find a line that matches, if one does not match, skip
10440             -- the record.  If one does match, update the interface
10441             -- table with the correct line number.
10442 
10443             IF (x_action is NULL) THEN
10444 
10445               l_progress := '180';
10446 
10447               BEGIN
10448 
10449                 -- bug# 2564767: don't compare secondary uom
10450 
10451                 SELECT MIN(pli.line_num),
10452                        pli.po_line_id
10453                 INTO x_po_line_num,
10454                      x_po_line_id
10455                 FROM po_lines_interface pli
10456                 WHERE pli.interface_header_id = x_interface_header_id
10457                 AND pli.line_num IS NOT NULL
10458                 AND pli.line_type_id = x_line_type_id
10459                 AND NVL(pli.item_id, -1) = NVL(x_item_id, -1)
10460                 AND NVL(pli.item_description, 'null' ) =
10461                                                  NVL(x_item_description,'null')
10462                 AND (((pli.item_revision IS NULL) AND (x_item_revision IS NULL))
10463                       OR (pli.item_revision = x_item_revision))
10464                 AND pli.unit_of_measure = x_unit_meas_lookup_code
10465                 AND ( pli.transaction_reason_code IS NULL
10466                       OR pli.transaction_reason_code =
10467                            NVL(x_transaction_reason_code,
10468                                   pli.transaction_reason_code))
10469 
10470                 -- togeorge 09/27/2000
10471                 -- added conditions to compare oke contract num and rev.
10472                 -- line num is different if contract info is diff. on the
10473                 -- same item.
10474                 AND   NVL(pli.oke_contract_header_id,-1) =
10475                                                NVL(x_oke_contract_header_id,-1)
10476                 AND   NVL(pli.oke_contract_version_id,-1) =
10477                                                NVL(x_oke_contract_version_id,-1)
10478                 GROUP BY pli.po_line_id;
10479 
10480               EXCEPTION
10481                 WHEN NO_DATA_FOUND THEN
10482                   IF g_debug_stmt THEN
10483                     PO_DEBUG.debug_stmt(
10484                       p_log_head => g_log_head||l_api_name,
10485                       p_token    => l_progress,
10486                       p_message  => 'NO_DATA_FOUND: '||SQLERRM);
10487                     END IF;
10488                     x_po_line_num := -1;
10489               END;
10490 
10491               l_progress := '190';
10492 
10493               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10494                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10495                                             p_token    => l_progress,
10496                                             p_message  => 'Group_interface_lines: Line_num is :'|| x_po_line_num);
10497               END IF;
10498 
10499               UPDATE po_lines_interface pli
10500               SET pli.line_num = x_po_line_num
10501               WHERE pli.interface_header_id = x_interface_header_id
10502               AND pli.requisition_line_id = x_requisition_line_id;
10503 
10504               x_interface_line_num := x_po_line_num;
10505 
10506             END IF;  -- if x_action is null
10507 
10508           END LOOP;
10509           CLOSE interface_lines;
10510 
10511           -- Select the maxmimum shipment number that exists on the
10512           -- release and update the shipment number in the interface
10513           -- table to be the requisition line number + this max
10514 
10515           l_progress:='200';
10516           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10517                       PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10518                                           p_token    => l_progress,
10519                                           p_message  => 'Group_interface_lines: before select max ship num');
10520           END IF;
10521 
10522           SELECT nvl(max(poll.shipment_num),0)
10523           INTO x_shipment_num
10524           FROM po_headers_all ph,
10525                po_line_locations_all poll,
10526                po_releases_all pr
10527           WHERE ph.po_header_id = poll.po_header_id
10528           AND ph.segment1 = x_document_num
10529           AND pr.po_header_id = ph.po_header_id
10530           AND pr.release_num = x_release_num
10531           AND ph.type_lookup_code = 'BLANKET'
10532           AND poll.po_release_id = pr.po_release_id
10533           AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
10534           AND NVL(pr.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
10535 
10536           l_progress:='210';
10537           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10538                  PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10539                                      p_token    => l_progress,
10540                                      p_message  => 'Group_interface_lines: after select max ship num');
10541           END IF;
10542 
10543           -- Bug 2841716 Start
10544           -- Prior to this fix, for Releases, the shipment number was
10545           -- derived by adding requisition line number to the current
10546           -- maximum shipment number.  Due to this shipment numbers
10547           -- were getting skipped. Hence commented the following update
10548           -- statement and now updating the po_lines_interface in a loop using
10549           -- a cursor.
10550 
10551           OPEN interface_lines_temp;
10552           LOOP
10553 
10554             x_count := x_count + 1;
10555             FETCH interface_lines_temp INTO x_requisition_line_id;
10556             EXIT WHEN interface_lines_temp%NOTFOUND;
10557 
10558             l_progress := '220';
10559 
10560             UPDATE po_lines_interface pli
10561             SET pli.shipment_num = x_shipment_num + x_count
10562             WHERE pli.requisition_line_id = x_requisition_line_id
10563             AND pli.interface_header_id = x_interface_header_id
10564             AND pli.line_num IS NOT NULL
10565             AND pli.shipment_num IS NULL;
10566 
10567           END LOOP;
10568           CLOSE interface_lines_temp;
10569 
10570           -- Bug 2841716 End
10571 
10572         END IF;  -- doc is not release / release
10573 
10574       END IF;  -- mode is NEW/ADD
10575 
10576     ELSE
10577 
10578       -- group code is DEFAULT
10579 
10580       IF ((x_document_subtype IN ('STANDARD', 'PLANNED', 'BLANKET')) OR
10581            (g_document_type = 'RFQ'))
10582       THEN
10583 
10584         l_progress := '230';
10585 
10586         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10587                   PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10588                                       p_token    => l_progress,
10589                                       p_message  => 'Before open interface: Grouping is default');
10590         END IF;
10591 
10592         -- <Complex Work R12 Start>
10593         -- Get maximum line number in interface table, to be used later
10594 
10595         SELECT NVL(max(pli.line_num), 0)
10596         INTO l_max_iface_line_num
10597         FROM po_lines_interface pli
10598         WHERE pli.interface_header_id = x_interface_header_id;
10599 
10600         -- <Complex Work R12 End>
10601 
10602         OPEN interface_lines;
10603         LOOP
10604 
10605           l_progress := '240';
10606           x_po_line_id := NULL;
10607           x_po_line_num := NULL;
10608 
10609           FETCH interface_lines INTO
10610             x_action,
10611             x_requisition_line_id,
10612             x_interface_line_num,
10613             x_item_id,
10614             x_item_description,     -- bgu, Mar. 19, 1999
10615             x_line_type_id,
10616             x_item_revision,
10617             x_unit_meas_lookup_code,
10618             x_transaction_reason_code,
10619             x_need_by_date,
10620             x_note_to_receiver,
10621             x_oke_contract_header_id,
10622             x_oke_contract_version_id,
10623             x_vendor_product_num, --Bug# 1763933
10624             x_deliver_to_location_id,
10625             x_destination_org_id,
10626             x_secondary_unit_of_measure,
10627             x_preferred_grade,
10628             x_bid_number,
10629             x_bid_line_number,
10630             x_row_id,
10631             x_vmi_flag,  -- VMI FPH
10632             x_drop_ship_flag,   --  <DropShip FPJ>
10633             x_source_doc_id ,        -- FPI GA
10634             x_source_doc_line_id ,    -- FPI GA
10635             x_consigned_flag,         -- CONSIGNED FPI
10636             l_contract_id,            -- <GC FPJ>
10637             l_supplier_ref_number    --<CONFIG_ID FPJ>
10638           ;
10639 
10640           EXIT WHEN interface_lines%NOTFOUND;
10641 
10642           -- <Complex Work R12 Start>: Do not group from sourcing
10643 
10644           IF (p_is_complex_work_po) THEN
10645 
10646             -- for complex work, we do not want to group lines.
10647             -- for complex PO's directly from requisitions, the group code
10648             -- will be set to REQUISITION and so lines will not be grouped.
10649             -- when coming from sourcing, however, the group type is set
10650             -- to DEFAULT.
10651 
10652             -- Do not group; simply add 1 to each successive interface line
10653 
10654             UPDATE po_lines_interface pli
10655             SET pli.line_num = l_max_iface_line_num + 1
10656             WHERE pli.rowid = x_row_id
10657             AND pli.line_num IS NULL;
10658 
10659             IF (SQL%ROWCOUNT > 0) THEN
10660               l_max_iface_line_num := l_max_iface_line_num + 1;
10661             END IF;
10662 
10663           -- <Complex Work R12 End>
10664 
10665           ELSIF (x_action = 'NEW') THEN
10666 
10667             -- line number should be loaded into the interface.  In general,
10668             -- the shipment number should be equal to 1.  The only time it
10669             -- will not be is if the user attempts to place two or more
10670             -- req lines to the same po line and the shipments are identical.
10671 
10672             l_progress:='250';
10673             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10674                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10675                                             p_token    => l_progress,
10676                                             p_message  => 'Before get_shipment_num');
10677             END IF;
10678 
10679             get_shipment_num(
10680               x_need_by_date,
10681               x_deliver_to_location_id,
10682               x_destination_org_id,
10683               x_po_line_id,
10684               x_po_line_num,
10685               x_requisition_line_id,
10686               x_interface_header_id,
10687               x_po_shipment_num,
10688               x_note_to_receiver,
10689               x_preferred_grade,
10690               NULL,  -- VMI FPH
10691               x_consigned_flag,
10692               x_drop_ship_flag,     --  <DropShip FPJ>
10693               x_create_new_line);   -- FPI GA
10694 
10695             x_po_line_num := x_interface_line_num;
10696 
10697             l_progress := '260';
10698 
10699             update_shipment(
10700               x_interface_header_id,
10701               x_po_shipment_num,
10702               x_po_line_num,
10703               x_requisition_line_id,
10704               x_po_line_id,
10705               x_document_num,
10706               x_release_num,
10707               x_create_new_line);  -- FPI GA
10708 
10709           ELSIF (x_action = 'ADD') THEN
10710 
10711             -- user wants to add a requisition line to a particular PO line.
10712             -- check if a shipment exists that we can add to, otherwise
10713             -- get the next highest shipment number.
10714 
10715             l_progress:='270';
10716             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10717                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10718                                             p_token    => l_progress,
10719                                             p_message  => 'x_action = '||x_action);
10720             END IF;
10721 
10722             -- Bug 594843: We need to retrieve the po_line_id for the
10723             -- line the user picked in the manual build process.
10724             -- Otherwise we will not be able the shipments
10725             -- Bug 599307: Added an AND condition to match_type_lookup_code
10726             -- Bug 1672940: Passing the value of line_num in x_po_line_num
10727 
10728             IF ((x_interface_line_num IS NOT NULL) AND
10729                   (x_document_num IS NOT NULL))
10730             THEN
10731 
10732               l_progress := '280';
10733 
10734               BEGIN
10735 
10736                 SELECT pol.po_line_id,
10737                        pol.line_num
10738                 INTO x_po_line_id,
10739                      x_po_line_num
10740                 FROM po_lines_all pol,
10741                      po_headers_all poh
10742                 WHERE poh.segment1 = x_document_num
10743                 AND pol.line_num = x_interface_line_num
10744                 AND poh.type_lookup_code =
10745                       DECODE(g_document_type, 'RFQ', g_document_type,x_document_subtype)
10746                 AND poh.po_header_id = pol.po_header_id
10747                 AND NVL(poh.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
10748 
10749                 -- Bug 2708776
10750                 -- In the manual option when a Req. Line is added to the PO
10751                 -- and PO has the same Item, the PO Line is matched and
10752                 -- the line num is defaulted to the Po Line matched in the PO.
10753                 -- If we change the line num defaulted and add a new line to
10754                 -- the PO the shipment# was not populated when the PO was
10755                 -- created. The is because we assume that the line_num
10756                 -- populated will always exist in the PO, which is wrong.
10757                 -- Handling the exception for NO_DATA_FOUND will resolve the
10758                 -- Issue
10759 
10760               EXCEPTION
10761                 WHEN NO_DATA_FOUND THEN
10762                   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10763                                   PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10764                                                       p_token    => l_progress,
10765                                                       p_message  => 'NO_DATA_FOUND: '||SQLERRM);
10766                   END IF;
10767                 WHEN others THEN
10768                   IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
10769                                   PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
10770                                                      p_progress => l_progress);
10771                   END IF;
10772                   RAISE;
10773               END;
10774 
10775             END IF;  -- if interface_line_num and x_document_num are not null
10776 
10777             l_progress := '290';
10778 
10779             get_shipment_num(
10780               x_need_by_date,
10781               x_deliver_to_location_id,
10782               x_destination_org_id,
10783               x_po_line_id,
10784               x_po_line_num,
10785               x_requisition_line_id,
10786               x_interface_header_id,
10787               x_po_shipment_num,
10788               x_note_to_receiver,
10789               x_preferred_grade,
10790               NULL,  -- VMI FPH
10791               x_consigned_flag,
10792               x_drop_ship_flag,     --  <DropShip FPJ>
10793               x_create_new_line);   -- FPI GA
10794 
10795             l_progress := '300';
10796 
10797             update_shipment(
10798               x_interface_header_id,
10799               x_po_shipment_num,
10800               x_po_line_num,
10801               x_requisition_line_id,
10802               x_po_line_id,
10803               x_document_num,
10804               x_release_num,
10805               x_create_new_line);  -- FPI GA
10806 
10807           ELSE
10808 
10809             -- action = NULL (R10 logic)
10810 
10811             -- Check to see if this line matches another line already on PO
10812             -- If the line matches, update interface line num with PO line num
10813             -- If the shipment matches, update interface table w/ ship. num
10814             -- If the the shipment does not match, update table w/ number = 1
10815             -- If the line does not match, get the next highest line number
10816 
10817             l_progress := '310';
10818 
10819             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10820                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10821                                             p_token    => l_progress,
10822                                             p_message  => 'x_action = '||x_action);
10823             END IF;
10824 
10825             --<SOURCING TO PO FPH>: allow lines grouping for blankets also
10826 
10827             IF (g_document_type IN ('PO', 'PA')) THEN
10828 
10829               --<INVCONV R12 START>
10830               -- Item could have different grade control for FSP and ship to org.
10831               -- If (shipment)grade is present , compare the grade at line level
10832               -- only if item is grade control for the FSP org.
10833               IF x_preferred_grade IS NOT NULL THEN
10834 
10835                 BEGIN
10836                   SELECT grade_control_flag
10837                   INTO l_grade_control_flag
10838                   FROM mtl_system_items
10839                   WHERE inventory_item_id = x_item_id
10840                   and organization_id = params.inventory_organization_id;
10841                 EXCEPTION
10842                   WHEN OTHERS THEN
10843                     l_grade_control_flag := 'N';
10844                 END;
10845 
10846                 IF l_grade_control_flag = 'Y' THEN
10847                   l_line_grade := x_preferred_grade ;
10848                 ELSE
10849                   l_line_grade := null;
10850                 END IF;
10851 
10852               ELSE
10853 
10854                 l_line_grade := null;
10855 
10856               END IF;  -- x_preferred_grade is not null
10857               --<INVCONV R12 END>
10858 
10859               BEGIN
10860 
10861                 l_progress := '320';
10862 
10863                 -- SQL What: Querying for an existing line on the PO
10864                 -- that matches the requisition line that we are trying to add.
10865                 -- SQL Why: Want to group matching lines onto PO documents
10866                 -- SQL Join: business logic for combining two lines
10867 
10868                 SELECT  line_num
10869                 ,       po_line_id
10870                 INTO    x_po_line_num
10871                 ,       x_po_line_id
10872                 FROM    po_lines_all POL2
10873                 ,       po_headers_all POH
10874                 ,       po_line_types_b PLT                 -- <SERVICES FPJ>
10875                 WHERE  POH.segment1 = x_document_num
10876                 AND    POH.po_header_id = POL2.po_header_id
10877                 AND    NVL(poh.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
10878                 AND    POH.type_lookup_code = x_document_subtype
10879                 -- <SERVICES FPJ START> Any new Service line types should
10880                 -- cause the SELECT to fail (i.e. should not be matched).
10881                 --
10882                 AND    POL2.line_type_id = PLT.line_type_id
10883                 AND    PLT.order_type_lookup_code NOT IN ('RATE','FIXED PRICE')
10884                 --
10885                 -- <SERVICES FPJ END>
10886                 AND    pol2.line_num =
10887                            (SELECT /*+ NO_UNNEST */ MIN(line_num)
10888                             FROM  po_lines_all pol  --<Shared Proc FPJ>
10889                             WHERE pol.po_header_id = poh.po_header_id
10890                             AND   NVL(CANCEL_FLAG,'N') = 'N'
10891                             AND   LINE_TYPE_ID = x_line_type_id
10892                             AND   nvl(pol.ITEM_ID, -1) = nvl(x_item_id, -1) -- bgu, For one time item
10893                             AND   nvl(pol.ITEM_DESCRIPTION,'null') = nvl(x_item_description,'null')
10894                             AND
10895                                 ( (     ITEM_REVISION IS NULL
10896                                     AND x_item_revision IS NULL
10897                                    )
10898                                  OR ITEM_REVISION = x_item_revision
10899                                  )
10900                             AND   UNIT_MEAS_LOOKUP_CODE =
10901                                     x_unit_meas_lookup_code
10902 --<INVCONV R12 START>
10903 -- replace x_preferred_grade to l_line_grade and removed secondary unit comparison.
10904                             AND
10905                              (
10906                                ( POL.PREFERRED_GRADE IS NULL
10907                                 AND  l_line_grade IS NULL
10908                                 ) OR
10909                                 (  POL.PREFERRED_GRADE =
10910                                    l_line_grade
10911                                  )
10912                               )
10913 --<INVCONV R12 END>
10914                             AND  /* FPI GA start */
10915                              (
10916                                ( pol.from_header_id IS NULL
10917                                 AND  x_source_doc_id IS NULL
10918                                 ) OR
10919                                 (  pol.from_header_id =
10920                                    x_source_doc_id
10921                                  )
10922                               )
10923                             AND
10924                              (
10925                                ( pol.from_line_id IS NULL
10926                                 AND  x_source_doc_line_id IS NULL
10927                                 ) OR
10928                                 (  pol.from_line_id =
10929                                    x_source_doc_line_id
10930                                  )
10931                               )   /* FPI GA end */
10932                             AND   (TRANSACTION_REASON_CODE IS NULL
10933                                    OR TRANSACTION_REASON_CODE =
10934                                    NVL(x_transaction_reason_code,
10935                                   TRANSACTION_REASON_CODE))
10936                             AND  trunc(nvl(pol.expiration_date,sysdate+1)) >= trunc(sysdate)
10937                             AND  nvl(pol.oke_contract_header_id,-1)=nvl(x_oke_contract_header_id,-1)
10938                             AND  nvl(pol.oke_contract_version_id,-1)=nvl(x_oke_contract_version_id,-1)
10939                             AND  nvl(pol.vendor_product_num,-1)=nvl(x_vendor_product_num,-1)
10940                             AND nvl(pol.bid_number,-1)=nvl(x_bid_number,-1)
10941                             AND nvl(pol.bid_line_number,-1)=nvl(x_bid_line_number,-1)
10942                             -- <GC FPJ START>
10943                             AND
10944                              (
10945                                 ( pol.contract_id IS NULL AND
10946                                   l_contract_id IS NULL )
10947                                 OR
10948                                 ( pol.contract_id = l_contract_id )
10949                              )
10950                             -- <GC FPJ END>
10951                             --<CONFIG_ID FPJ START>
10952                             AND ((pol.supplier_ref_number IS NULL
10953                                   AND l_supplier_ref_number IS NULL)
10954                                  OR (pol.supplier_ref_number = l_supplier_ref_number))
10955                             --<CONFIG_ID FPJ END>
10956                            )
10957                           FOR UPDATE OF QUANTITY;
10958 
10959               EXCEPTION
10960                 WHEN NO_DATA_FOUND THEN
10961                   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
10962                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
10963                                                     p_token    => l_progress,
10964                                                     p_message  => 'NO_DATA_FOUND: No match to po line: Doc type = '||g_document_type);
10965                   END IF;
10966                   x_po_line_num := -1;
10967                 WHEN OTHERS THEN
10968                   IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
10969                                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
10970                                                    p_progress => l_progress);
10971                   END IF;
10972                   wrapup(x_interface_header_id);
10973                   RAISE;
10974               END;
10975 
10976             ELSIF (g_document_type = 'RFQ') THEN
10977 
10978               l_progress := '330';
10979 
10980               BEGIN
10981 
10982                 SELECT line_num,
10983                        po_line_id
10984                 INTO   x_po_line_num,
10985                        x_po_line_id
10986                 FROM   po_lines_all POL2,
10987                        po_headers_all POH
10988                 WHERE  POH.segment1 = x_document_num
10989                 AND POH.po_header_id = POL2.po_header_id
10990                 AND NVL(poh.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
10991                 AND POH.type_lookup_code = 'RFQ'
10992                 AND pol2.line_num =
10993                          (
10994                            SELECT /*+ NO_UNNEST */ MIN(line_num)
10995                            FROM  PO_LINES_ALL pol
10996                            WHERE pol.po_header_id = poh.po_header_id
10997                            AND LINE_TYPE_ID = x_line_type_id
10998                            AND nvl(pol.ITEM_ID, -1) = nvl(x_item_id, -1)
10999                            AND nvl(pol.ITEM_DESCRIPTION,'null') =
11000                                            nvl(x_item_description,'null')
11001                            AND
11002                                 ( (     ITEM_REVISION IS NULL
11003                                     AND x_item_revision IS NULL
11004                                    )
11005                                  OR ITEM_REVISION = x_item_revision
11006                                  )
11007                            AND nvl(pol.oke_contract_header_id,-1) =
11008                                      nvl(x_oke_contract_header_id,-1)
11009                            AND nvl(pol.oke_contract_version_id,-1) =
11010                                      nvl(x_oke_contract_version_id,-1)
11011                          )
11012                 FOR UPDATE OF QUANTITY;
11013 
11014               EXCEPTION
11015                 WHEN NO_DATA_FOUND THEN
11016                   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11017                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11018                                                     p_token    => l_progress,
11019                                                     p_message  => 'NO_DATA_FOUND: No match to po line: Doc type RFQ');
11020                   END IF;
11021                   x_po_line_num := -1;
11022                 WHEN OTHERS THEN
11023                   IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11024                                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11025                                                    p_progress => l_progress);
11026                   END IF;
11027                   wrapup(x_interface_header_id);
11028                   RAISE;
11029               END;
11030 
11031             END IF;  -- PO/PA vs. RFQ
11032 
11033             -- Check to see if there is a line in the interface table
11034             -- that matches the line we are attempting to add
11035 
11036             IF (x_po_line_num = -1) THEN
11037 
11038               --<SOURCING TO PO FPH>: allow lines grouping for blankets also
11039 
11040               IF (g_document_type IN ('PO', 'PA')) THEN
11041 
11042                 l_progress := '340';
11043 
11044                 BEGIN
11045 
11046                   x_ship_to_location_id :=
11047                        get_ship_to_loc(x_deliver_to_location_id);
11048 
11049                   l_progress := '350';
11050 
11051                   -- SQL What: Querying for a requisition line in the
11052                   -- interface table that matches the requisition line
11053                   -- that we are trying to add.
11054                   -- SQL Why: Want to group matching lines onto PO documents.
11055                   -- SQL Join: business logic for combining two lines
11056 
11057                   SELECT min(pli.line_num)
11058                   INTO   x_po_line_num
11059                   FROM   po_lines_interface pli
11060                   ,      po_requisition_lines_all prl
11061                   ,      po_line_types_b PLT                -- <SERVICES FPJ>
11062                   WHERE  pli.interface_header_id = x_interface_header_id
11063                   AND pli.line_num is not null
11064                   AND prl.requisition_line_id <> x_requisition_line_id
11065                   AND prl.requisition_line_id = pli.requisition_line_id
11066                   AND pli.line_type_id = x_line_type_id
11067 
11068                   -- <SERVICES FPJ START> Any new Service line types should
11069                   -- cause the SELECT to fail (i.e. should not be matched).
11070                   --
11071                   AND PLI.line_type_id = PLT.line_type_id
11072                   AND PLT.order_type_lookup_code NOT IN ('RATE','FIXED PRICE')
11073                   --
11074                   -- <SERVICES FPJ END>
11075 
11076                   AND nvl(pli.ITEM_ID, -1) = nvl(x_item_id, -1)
11077                   AND nvl(pli.ITEM_DESCRIPTION,'null') =
11078                                         nvl(x_item_description,'null')
11079                   AND ((pli.ITEM_REVISION IS NULL AND x_item_revision IS NULL)
11080                            OR pli.ITEM_REVISION = x_item_revision)
11081                   AND   pli.UNIT_OF_MEASURE = x_unit_meas_lookup_code
11082 
11083                   --<INVCONV R12 START>
11084                   -- replace x_preferred_grade to l_line_grade and
11085                   -- removed secondary unit comparison.
11086                   AND (( pli.PREFERRED_GRADE IS NULL AND l_line_grade IS NULL)
11087                             OR (pli.PREFERRED_GRADE = l_line_grade))
11088                   --<INVCONV R12 END>
11089 
11090                   -- FPI GA start
11091                   AND        (
11092                                ( pli.from_header_id IS NULL
11093                                 AND  x_source_doc_id IS NULL
11094                                 ) OR
11095                                 (  pli.from_header_id =
11096                                    x_source_doc_id
11097                                  )
11098                               )
11099                   AND
11100                              (
11101                                ( pli.from_line_id IS NULL
11102                                 AND  x_source_doc_line_id IS NULL
11103                                 ) OR
11104                                 (  pli.from_line_id =
11105                                    x_source_doc_line_id
11106                                  )
11107                               )
11108                   AND( nvl(l_needby_prf,'Y') = 'N'  -- Bug 3201308
11109                              OR
11110                              (
11111                                ( pli.need_by_date IS NULL
11112                                 AND  x_need_by_date IS NULL
11113                                 ) OR
11114                                 ( to_char(pli.need_by_date-(to_number(substr(to_char(pli.need_by_date,
11115                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
11116                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
11117                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
11118                                  )
11119                               )
11120                               )
11121                   AND ( nvl(l_shipto_prf,'Y') = 'N'  -- Bug 3201308
11122                               OR exists (select 'x'
11123                                      from HR_LOCATIONS HRL
11124                                      where PRL.deliver_to_location_id = HRL.location_id
11125                                      and nvl(HRL.ship_to_location_id, HRL.location_id) = x_ship_to_location_id
11126                                      UNION ALL
11127                                      select 'x'
11128                                      from HZ_LOCATIONS HZ
11129                                      where PRL.deliver_to_location_id = HZ.location_id
11130                                      and HZ.location_id = x_ship_to_location_id)
11131                                )
11132                   AND( nvl(l_shipto_prf,'Y') = 'N'   -- Bug 3201308
11133                               OR
11134                              (
11135                                ( pli.ship_to_organization_id  IS NULL
11136                                 AND  x_destination_org_id IS NULL
11137                                 ) OR
11138                                 (  pli.ship_to_organization_id =
11139                                    x_destination_org_id
11140                                  )
11141                               ) )
11142                   -- FPI GA end
11143 
11144                   -- CONSIGNED FPI start
11145                   AND        (
11146                                ( pli.consigned_flag IS NULL
11147                                 AND  x_consigned_flag IS NULL
11148                                 ) OR
11149                                 (  pli.consigned_flag  =
11150                                    x_consigned_flag
11151                                  )
11152                               )
11153                   -- CONSIGNED FPI End
11154 
11155                   AND   (pli.TRANSACTION_REASON_CODE IS NULL
11156                                    OR pli.TRANSACTION_REASON_CODE =
11157                                    NVL(x_transaction_reason_code,
11158                                   pli.TRANSACTION_REASON_CODE))
11159 
11160                   AND nvl(pli.oke_contract_header_id,-1) =
11161                             nvl(x_oke_contract_header_id,-1)
11162                   AND nvl(pli.oke_contract_version_id,-1) =
11163                             nvl(x_oke_contract_version_id,-1)
11164                   AND nvl(pli.vendor_product_num,-1) =
11165                             nvl(x_vendor_product_num,-1)
11166                   AND nvl(pli.bid_number,-1) = nvl(x_bid_number,-1)
11167                   AND nvl(pli.bid_line_number,-1) = nvl(x_bid_line_number,-1)
11168                   AND nvl(pli.orig_from_req_flag,'Y') <> 'N'
11169 
11170                   -- <GC FPJ START>
11171                   AND
11172                              (
11173                                ( pli.contract_id IS NULL AND
11174                                  l_contract_id IS NULL )
11175                                OR
11176                                ( pli.contract_id = l_contract_id )
11177                              )
11178                   -- <GC FPJ END>
11179 
11180                   --<CONFIG_ID FPJ START>
11181                   AND   ((pli.supplier_ref_number IS NULL
11182                                   AND l_supplier_ref_number IS NULL)
11183                                  OR (pli.supplier_ref_number = l_supplier_ref_number))
11184                   --<CONFIG_ID FPJ END>
11185                   ;
11186 
11187                 EXCEPTION
11188                   WHEN NO_DATA_FOUND THEN
11189                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11190                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11191                                                     p_token    => l_progress,
11192                                                     p_message  => 'NO_DATA_FOUND: No match to po line in Interface- Doc type = '||g_document_type);
11193                     END IF;
11194                     x_po_line_num := -1;
11195                   WHEN OTHERS THEN
11196                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11197                                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11198                                                    p_progress => l_progress);
11199                     END IF;
11200                     wrapup(x_interface_header_id);
11201                     RAISE;
11202                 END;
11203 
11204               ELSIF (g_document_type = 'RFQ') THEN
11205 
11206                 BEGIN
11207 
11208                   l_progress := '360';
11209 
11210                   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11211                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11212                                                   p_token    => l_progress,
11213                                                   p_message  => 'Before select min line_num');
11214                   END IF;
11215 
11216                   SELECT MIN(pli.line_num)
11217                   INTO x_po_line_num
11218                   FROM po_lines_interface pli
11219                   WHERE pli.interface_header_id = x_interface_header_id
11220                   AND pli.line_num is not null
11221                   AND pli.line_type_id = x_line_type_id
11222                   AND nvl(pli.item_id, -1) = nvl(x_item_id, -1)
11223                   AND nvl(pli.item_description,'null') =
11224                                nvl(x_item_description,'null')
11225                   AND ((pli.item_revision IS NULL AND x_item_revision IS NULL)
11226                          OR (pli.item_revision = x_item_revision))
11227                   AND nvl(pli.oke_contract_header_id,-1) =
11228                                    nvl(x_oke_contract_header_id,-1)
11229                   AND nvl(pli.oke_contract_version_id,-1) =
11230                                    nvl(x_oke_contract_version_id,-1)
11231                   ;
11232 
11233                 EXCEPTION
11234                   WHEN NO_DATA_FOUND THEN
11235                     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11236                                 PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11237                                                     p_token    => l_progress,
11238                                                     p_message  => 'NO_DATA_FOUND: No match to po line in Interface- Doc type RFQ');
11239                     END IF;
11240                     x_po_line_num := -1;
11241                   WHEN OTHERS THEN
11242                     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11243                                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11244                                                    p_progress => l_progress);
11245                     END IF;
11246                     wrapup(x_interface_header_id);
11247                     RAISE;
11248                 END;
11249 
11250               END IF;  -- PO/PA vs. RFQ
11251 
11252             END IF;  -- if x_po_line_num = -1 (interface table)
11253 
11254             IF (x_po_line_num <> -1) THEN
11255 
11256               -- a line matches
11257 
11258               l_progress := '370';
11259 
11260               --<SOURCING TO PO FPH>
11261               -- We need to use get_shipment_num only for those negotiations
11262               -- with backing req.
11263 
11264               IF (x_requisition_line_id IS NOT NULL) THEN
11265 
11266                 -- backing req line exists
11267 
11268                 -- Since get_shipment_num will need it, we update the
11269                 -- line number here.
11270 
11271                 UPDATE po_lines_interface pli
11272                 SET pli.line_num = x_po_line_num
11273                 WHERE pli.interface_header_id = x_interface_header_id
11274                 AND pli.requisition_line_id = x_requisition_line_id;
11275 
11276                 l_progress := '380';
11277 
11278                 -- if a shipment matches, get the shipment number
11279 
11280                 get_shipment_num(
11281                   x_need_by_date,
11282                   x_deliver_to_location_id,
11283                   x_destination_org_id,
11284                   x_po_line_id,
11285                   x_po_line_num,
11286                   x_requisition_line_id,
11287                   x_interface_header_id,
11288                   x_po_shipment_num,
11289                   x_note_to_receiver,
11290                   x_preferred_grade,
11291                   NULL,  -- VMI FPH
11292                   x_consigned_flag,
11293                   x_drop_ship_flag,     --  <DropShip FPJ>
11294                   x_create_new_line);   -- FPI GA
11295 
11296                 l_progress := '390';
11297 
11298                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11299                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11300                                             p_token    => l_progress,
11301                                             p_message  => 'Before update_shipment');
11302                 END IF;
11303 
11304                 update_shipment(
11305                   x_interface_header_id,
11306                   x_po_shipment_num,
11307                   x_po_line_num,
11308                   x_requisition_line_id,
11309                   x_po_line_id,
11310                   x_document_num,
11311                   x_release_num,
11312                   x_create_new_line);  -- FPI GA
11313 
11314               ELSE
11315 
11316                 -- no backing requisition line
11317 
11318                 --< SOURCING TO PO FPH >
11319                 --Assign max line number+1 from interface table when not backed
11320                 --by a req and the shipment num would be 1. There can't be two
11321                 --similar negotiation lines not backed by a req, having the
11322                 --same bid number and bid line number. If that happens we don't
11323                 --group them to a single line. Also no need to select from
11324                 --po_lines table as we are not supporting add to functionality.
11325 
11326                 l_progress := '400';
11327 
11328                 UPDATE po_lines_interface pli2
11329                 SET (pli2.line_num, pli2.shipment_num) =
11330                       (
11331                         SELECT (NVL(max(pli.line_num), 0) + 1), 1
11332                         FROM po_lines_interface pli
11333                         WHERE pli.interface_header_id = x_interface_header_id
11334                       )
11335                 WHERE pli2.rowid = x_row_id;
11336 
11337               END IF;
11338 
11339             ELSE
11340 
11341               -- a matching line does not exist
11342 
11343               -- Get the max line number on the purchase order and
11344               -- update the interface line number with that number + 1.
11345               -- The shipment number should be 1.
11346 
11347               l_progress := '410';
11348               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11349                            PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11350                                                p_token    => l_progress,
11351                                                p_message  => 'Group_interface_lines: Line does not exist');
11352               END IF;
11353 
11354               SELECT NVL(max(pl.line_num), 0)
11355               INTO x_line_num
11356               FROM po_headers_all ph,
11357                    po_lines_all pl
11358               WHERE pl.po_header_id = ph.po_header_id
11359               AND ph.segment1 = x_document_num
11360               AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99)
11361               AND ph.type_lookup_code =
11362                     DECODE(g_document_type, 'RFQ', g_document_type, x_document_subtype)
11363               ;
11364 
11365               -- Get the max line number already assigne in the interface table
11366 
11367               l_progress:='420';
11368               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11369                            PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11370                                                p_token    => l_progress,
11371                                                p_message  => 'Before select max line_num from po_lines_interface');
11372               END IF;
11373 
11374               SELECT NVL(max(pli.line_num), 0)
11375               INTO x_int_line_num
11376               FROM po_lines_interface pli
11377               WHERE pli.interface_header_id = x_interface_header_id;
11378 
11379               IF (x_line_num >= x_int_line_num) THEN
11380                 x_line_num := x_line_num;
11381               ELSE
11382                 x_line_num := x_int_line_num;
11383               END IF;
11384 
11385               l_progress := '430';
11386               --<SOURCING TO PO FPH>: when req line id is null, use x_row_id
11387 
11388               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11389                        PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11390                                            p_token    => l_progress,
11391                                            p_message  => 'Sourcing to FPH-8 starts');
11392               END IF;
11393 
11394               IF (x_requisition_line_id IS NOT NULL) THEN
11395 
11396                 UPDATE po_lines_interface pli
11397                 SET pli.line_num = x_line_num + 1,
11398                     pli.shipment_num = 1
11399                 WHERE pli.interface_header_id = x_interface_header_id
11400                 AND pli.requisition_line_id = x_requisition_line_id;
11401 
11402               ELSE
11403 
11404                 -- no backing req line; use rowid
11405 
11406                 UPDATE po_lines_interface pli
11407                 SET pli.line_num = x_line_num + 1,
11408                     pli.shipment_num = 1
11409                 WHERE pli.rowid = x_row_id;
11410 
11411               END IF;  -- if x_requisition_id is not null
11412 
11413               IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11414                        PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11415                                            p_token    => l_progress,
11416                                            p_message  => 'Sourcing to FPH-8 ends');
11417               END IF;
11418 
11419               x_num_interface_lines := x_num_interface_lines + 1;
11420 
11421             END IF; -- matching line vs. no matching line
11422 
11423            END IF; -- Action Type Code
11424 
11425         END LOOP;
11426         CLOSE interface_lines;
11427 
11428       ELSE
11429 
11430         -- Document is release case
11431 
11432         l_progress:='440';
11433 
11434         OPEN interface_lines;
11435         LOOP
11436 
11437           l_progress:='450';
11438 
11439           FETCH interface_lines INTO
11440             x_action,
11441             x_requisition_line_id,
11442             x_interface_line_num,
11443             x_item_id,
11444             x_item_description,     -- bgu, Mar. 19, 1999
11445             x_line_type_id,
11446             x_item_revision,
11447             x_unit_meas_lookup_code,
11448             x_transaction_reason_code,
11449             x_need_by_date,
11450             x_note_to_receiver,
11451             x_oke_contract_header_id,
11452             x_oke_contract_version_id,
11453             x_vendor_product_num, --Bug# 1763933
11454             x_deliver_to_location_id,
11455             x_destination_org_id,
11456             x_secondary_unit_of_measure,
11457             x_preferred_grade,
11458             x_bid_number,
11459             x_bid_line_number,
11460             x_row_id,
11461             x_vmi_flag,  -- VMI FPH
11462             x_drop_ship_flag,   --  <DropShip FPJ>
11463             x_source_doc_id ,        -- FPI GA
11464             x_source_doc_line_id ,    -- FPI GA
11465             x_consigned_flag,         -- CONSIGNED FPI
11466             l_contract_id,            -- <GC FPJ>
11467             l_supplier_ref_number    --<CONFIG_ID FPJ>
11468           ;
11469 
11470           EXIT WHEN interface_lines%NOTFOUND;
11471 
11472           IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11473                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11474                                         p_token    => l_progress,
11475                                         p_message  => 'After fetch interface_lines cursor');
11476           END IF;
11477 
11478 
11479           IF (x_action is NULL) THEN
11480 
11481             -- The user did not specify the line that they want the req line
11482             -- to be associated with.  We need to find a req. line that matches
11483             -- it.  If one does not match, skip the record.  If one does match,
11484             -- update the interface table with the correct line number.
11485 
11486 
11487             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11488                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11489                                            p_progress => l_progress,
11490                                            p_name     => 'x_line_type_id',
11491                                            p_value    => x_line_type_id);
11492                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11493                                            p_progress => l_progress,
11494                                            p_name     => 'x_item_id',
11495                                            p_value    => x_item_id);
11496                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11497                                            p_progress => l_progress,
11498                                            p_name     => 'x_item_revision',
11499                                            p_value    => x_item_revision);
11500                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11501                                            p_progress => l_progress,
11502                                            p_name     => 'x_unit_meas_lookup_code',
11503                                            p_value    => x_unit_meas_lookup_code);
11504                         PO_DEBUG.debug_var(p_log_head => g_log_head||l_api_name,
11505                                            p_progress => l_progress,
11506                                            p_name     => 'x_transaction_reason_code',
11507                                            p_value    => x_transaction_reason_code);
11508             END IF;
11509 
11510             l_progress := '460';
11511 
11512             BEGIN
11513 
11514               SELECT min(line_num)
11515               ,      po_line_id
11516               INTO   x_po_line_num
11517               ,      x_po_line_id
11518               FROM   po_lines_interface PLI
11519               ,      po_line_types_b    PLT                 -- <SERVICES FPJ>
11520               WHERE  pli.interface_header_id = x_interface_header_id
11521               AND    pli.line_num is not null
11522               AND    pli.LINE_TYPE_ID = x_line_type_id
11523 
11524               -- <SERVICES FPJ START> Any new Service line types should
11525               -- cause the SELECT to fail (i.e. should not be matched).
11526               --
11527               AND    PLI.line_type_id = PLT.line_type_id
11528               AND    PLT.order_type_lookup_code NOT IN ('RATE','FIXED PRICE')
11529               --
11530               -- <SERVICES FPJ END>
11531 
11532               AND    nvl(pli.ITEM_ID, -1) = nvl(x_item_id, -1)
11533               AND    nvl(pli.ITEM_DESCRIPTION,'null') =
11534                                      nvl(x_item_description,'null')
11535               AND             ( (     pli.ITEM_REVISION IS NULL
11536                                     AND x_item_revision IS NULL
11537                                    )
11538                                   OR pli.ITEM_REVISION = x_item_revision
11539                                   )
11540               AND    pli.UNIT_OF_MEASURE = x_unit_meas_lookup_code
11541               AND    (pli.TRANSACTION_REASON_CODE IS NULL
11542                                    OR pli.TRANSACTION_REASON_CODE =
11543                                    NVL(x_transaction_reason_code,
11544                                   pli.TRANSACTION_REASON_CODE))
11545               AND   nvl(pli.oke_contract_header_id,-1)=nvl(x_oke_contract_header_id,-1)
11546               AND   nvl(pli.oke_contract_version_id,-1)=nvl(x_oke_contract_version_id,-1)
11547               GROUP BY po_line_id;
11548 
11549             EXCEPTION
11550               WHEN NO_DATA_FOUND THEN
11551                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11552                             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11553                                                 p_token    => l_progress,
11554                                                 p_message  => 'NO_DATA_FOUND: '||SQLERRM);
11555                 END IF;
11556                 x_po_line_num := -1;
11557             END;
11558 
11559             l_progress := '470';
11560 
11561             UPDATE po_lines_interface pli
11562             SET pli.line_num = x_po_line_num
11563             WHERE pli.interface_header_id = x_interface_header_id
11564             AND pli.requisition_line_id = x_requisition_line_id;
11565 
11566             x_interface_line_num := x_po_line_num;
11567 
11568             IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11569                           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11570                                               p_token    => l_progress,
11571                                               p_message  => 'After update of po_lines_interface line_num');
11572             END IF;
11573 
11574           ELSE
11575 
11576             -- The user did specify the line that they want the
11577             -- requisition line to come from.
11578             -- Note: For a one time item Blanket Release, the user must
11579             -- always specify the action ADD and the line number that
11580             -- that want to release against in the form.
11581 
11582             l_progress := '480';
11583 
11584             BEGIN
11585 
11586               SELECT pol.po_line_id
11587               INTO x_po_line_id
11588               FROM po_lines_all pol,
11589                    po_headers_all poh,
11590                    po_lines_interface pli
11591               WHERE pol.po_header_id = poh.po_header_id
11592               AND poh.segment1 = x_document_num
11593               AND NVL(poh.org_id, -99) = NVL(g_purchasing_ou_id, -99)
11594               AND poh.type_lookup_code = 'BLANKET' -- Bug# 1746943
11595               AND pol.line_num = pli.line_num
11596               AND pli.requisition_line_id = x_requisition_line_id;
11597 
11598             EXCEPTION
11599               WHEN NO_DATA_FOUND THEN
11600                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11601                         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11602                                             p_token    => l_progress,
11603                                             p_message  => 'NO_DATA_FOUND: '||SQLERRM);
11604                  END IF;
11605                  x_po_line_num := -1;
11606 
11607             END;
11608           END IF;  -- action code is null vs. not null
11609 
11610           l_progress := '490';
11611 
11612           -- Select the maximum shipment num that exists on the release.
11613           -- Update the shipment num in the interface table to be the
11614           -- requisition line number + this maximum shipment num
11615 
11616 
11617           -- if a shipment matches, get the shipment
11618 
11619           get_shipment_num(
11620              x_need_by_date,
11621              x_deliver_to_location_id,
11622              x_destination_org_id,
11623              x_po_line_id,
11624              x_interface_line_num,
11625              x_requisition_line_id,
11626              x_interface_header_id,
11627              x_po_shipment_num,
11628              x_note_to_receiver,
11629              x_preferred_grade,
11630              x_vmi_flag,  -- VMI FPH
11631              x_consigned_flag,
11632              x_drop_ship_flag,     --  <DropShip FPJ>
11633              x_create_new_line);   -- FPI GA
11634 
11635           update_shipment(
11636             x_interface_header_id,
11637             x_po_shipment_num,
11638             x_po_line_num,
11639             x_requisition_line_id,
11640             x_po_line_id,
11641             x_document_num,
11642             x_release_num,
11643             x_create_new_line, -- FPI GA
11644             x_row_id );
11645 
11646         END LOOP;
11647         CLOSE interface_lines;
11648 
11649       END IF;  -- If STANDARD/PLANNED/RELEASE
11650 
11651     END IF;  -- of same  as REQUISITION mode
11652 
11653   END IF;  -- of PO mode
11654 
11655   IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11656         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
11657   END IF;
11658 EXCEPTION
11659   WHEN NO_DATA_FOUND THEN
11660     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11661         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11662                             p_token    => l_progress,
11663                             p_message  => 'Exception block: NO_DATA_FOUND: '||SQLERRM);
11664     END IF;
11665      null;
11666   WHEN OTHERS THEN
11667     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11668         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11669                            p_progress => l_progress||'_main');
11670     END IF;
11671      po_message_s.sql_error('GROUP INTERFACE LINES',l_progress,sqlcode);
11672      wrapup(x_interface_header_id);
11673      raise;
11674 END group_interface_lines;
11675 
11676 
11677 -- Bug 2875346 start.
11678 /**
11679  * Private Function: has_one_time_location
11680  * Effects: Checks if the requisition line p_req_line_id has a one-time
11681  *   location.
11682  * Returns: TRUE if the requisition line has a one-time location
11683  *          FALSE otherwise
11684  */
11685 FUNCTION has_one_time_location(p_req_line_id IN NUMBER)
11686     RETURN BOOLEAN
11687 IS
11688 
11689 l_api_name CONSTANT VARCHAR2(30) := 'has_one_time_location';
11690 l_flag VARCHAR2(1);
11691 l_progress VARCHAR2(3) := '000';                    --< Bug 3210331 >
11692 
11693 BEGIN
11694     l_progress := '000';
11695 
11696     IF (p_req_line_id IS NOT NULL) THEN
11697 
11698         -- Query if this req line has a one-time location attachment, which
11699         -- indicates that the req line is for a one-time location.
11700         SELECT 'Y'
11701           INTO l_flag
11702           FROM fnd_attached_documents
11703          WHERE entity_name = 'REQ_LINES'
11704            AND pk1_value = to_char(p_req_line_id)
11705            AND pk2_value = 'ONE_TIME_LOCATION'
11706            AND rownum = 1;
11707 
11708         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11709             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11710                                 p_token    => l_progress,
11711                                 p_message  => 'Req line '||p_req_line_id||' has one-time attachment');
11712         END IF;
11713 
11714         RETURN TRUE;
11715 
11716     ELSE
11717 
11718         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11719             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11720                                 p_token    => l_progress,
11721                                 p_message  => 'Req line is null');
11722         END IF;
11723         RETURN FALSE;
11724 
11725     END IF;
11726 
11727 EXCEPTION
11728     WHEN NO_DATA_FOUND THEN
11729         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11730             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11731                                 p_token    => l_progress,
11732                                 p_message  => 'NO_DATA_FOUND: No one-time attachment for req line '||p_req_line_id);
11733         END IF;
11734         RETURN FALSE;
11735     WHEN OTHERS THEN
11736         IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11737             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11738                                p_progress => l_progress);
11739         END IF;
11740         RETURN FALSE;
11741 END has_one_time_location;
11742 -- Bug 2875346 end.
11743 
11744 
11745 /* ============================================================================
11746      NAME: GET_SHIPMENT_NUM
11747      DESC: Get Shipment Number
11748      ARGS: x_interface_header_id IN number
11749      ALGR:
11750    ==========================================================================*/
11751 PROCEDURE get_shipment_num(x_need_by_date IN DATE, x_deliver_to_location_id IN NUMBER,
11752          x_destination_org_id IN NUMBER,
11753          x_po_line_id IN NUMBER,
11754          x_po_line_num IN NUMBER,
11755          x_requisition_line_id IN NUMBER,
11756                x_interface_header_id IN NUMBER,
11757          x_po_shipment_num IN OUT NOCOPY number,
11758                  x_note_to_receiver IN varchar2,
11759                            x_preferred_grade IN VARCHAR2,      -- Bug 1548597
11760                            x_vmi_flag   IN  VARCHAR2 ,         -- VMI FPH
11761                            x_consigned_flag IN VARCHAR2,       -- CONSIGNED FPI
11762                            x_drop_ship_flag IN VARCHAR2,       --  <DropShip FPJ>
11763                            x_create_new_line OUT NOCOPY VARCHAR2) IS  -- GA FPI
11764 
11765  x_ship_to_location_id number;
11766 x_receipt_required_flag varchar2(1);
11767 x_so_line_id number:='';
11768 x_so_line_id_from_shipment number:='';
11769 x_so_line_id_from_req_line number:='';
11770 x_line_location_to_check number:='';
11771 x_req_line_to_check number:='';
11772 
11773 --Added for Bug# 1512955
11774 x_check_doc_sub_type  varchar2(25);
11775 
11776 /* Bug 3201308 start */
11777  l_needby_prf  varchar2(1);
11778  l_shipto_prf  varchar2(1);
11779 /* Bug 3201308 end */
11780 l_api_name CONSTANT VARCHAR2(30) := 'get_shipment_num';     --< Bug 3210331 >
11781 l_progress VARCHAR2(3) := '000';                            --< Bug 3210331 >
11782 
11783 l_po_line_id  NUMBER;  -- bug2788115
11784 
11785 BEGIN
11786    IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11787         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
11788    END IF;
11789 
11790    /* Bug 3201308 start */
11791    /* Get the profile option values to determine grouping criteria */
11792 
11793      l_needby_prf := fnd_profile.value('PO_NEED_BY_GROUPING');
11794      l_shipto_prf := fnd_profile.value('PO_SHIPTO_GROUPING');
11795 
11796    /* Bug 3201308 end */
11797 
11798    /* OE drop ship requirement
11799    ** Do not consolidate any shipments linked to a sales order
11800    ** Neither add them to existing shipments
11801    ** or let other shipments add to them
11802    */
11803 
11804    --<DropShip FPJ Start>
11805    --Removed call to oe_drop_ship_grp.req_line_is_drop_ship, instead use x_drop_ship_flag
11806    --Bug 7312562
11807    --Moving this code to the end of the procedure.
11808    --So that the same logic is used for Drop shipments also.
11809    --Ensuring that two drop shipments are not inserted into same shipment,
11810    --by setting x_po_shipment_num := -1;
11811    /*IF g_document_type = 'PO' AND x_drop_ship_flag = 'Y' THEN
11812      x_po_shipment_num := -1;
11813       x_create_new_line := 'Y';  --Bug 5568899
11814      return;
11815    END IF;*/
11816    --<DropShip FPJ End>
11817 
11818    l_progress := '010';
11819 
11820    -- Bug 2875346. Do not group shipments if the req has a one-time location.
11821    IF (has_one_time_location(x_requisition_line_id)) THEN
11822        x_po_shipment_num := -1;
11823        --Bug 7312562
11824        IF g_document_type = 'PO' AND x_drop_ship_flag = 'Y' THEN
11825           x_create_new_line := 'Y';
11826        END IF;
11827        IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11828             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11829                                 p_token    => l_progress,
11830                                 p_message  => 'One-time location. Shipment num = -1');
11831        END IF;
11832        RETURN;
11833    END IF;
11834    -- Bug 2875346 end.
11835 
11836    x_ship_to_location_id := -1;
11837    l_progress:='020';
11838    x_ship_to_location_id := get_ship_to_loc(x_deliver_to_location_id);  -- FPI
11839 
11840    x_po_shipment_num := -1;
11841 
11842    IF ((g_document_subtype='STANDARD' OR g_document_subtype='PLANNED')
11843   AND g_document_type = 'PO') THEN
11844 
11845       l_progress:='030';
11846 
11847       /* Consigned FPI start : split the following select to determine if a new line
11848          is to be created or just a new shipment */
11849 
11850      -- Bug 3201308 : Further split the select into 3 selects to chenck
11851      -- matching for need by date ,ship to and rest of the information
11852 
11853      -- Bug 2757524 Do not execute this select if x_po_line_id is null
11854 
11855       IF x_po_line_id is not null THEN
11856 
11857       l_progress:='040';
11858       BEGIN
11859 
11860          -- SQL WHAT : compares the existing shipment values with the values from the req
11861          -- SQL WHY : to create a new line if the need by is different based on the profile
11862 
11863          SELECT PLL.shipment_num
11864           ,PLL.line_location_id
11865          INTO   x_po_shipment_num
11866     ,x_line_location_to_check
11867          FROM   PO_LINE_LOCATIONS_ALL    PLL  --<Shared Proc FPJ>
11868          WHERE  PLL.PO_LINE_ID = x_po_line_id
11869 -- bug 4599140 (included the following OR condition so that the SQL works correctly
11870 -- for null need_by_date)
11871          AND    (( to_char(PLL.need_by_date-(to_number(substr(to_char(PLL.need_by_date,
11872                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
11873                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
11874                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
11875                                  )
11876                OR
11877                   (PLL.need_by_date is NULL AND x_need_by_date is NULL)
11878                   )
11879          AND    ROWNUM = 1
11880          FOR UPDATE OF PLL.QUANTITY;
11881 
11882          EXCEPTION
11883             WHEN NO_DATA_FOUND THEN
11884                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11885                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11886                                         p_token    => l_progress,
11887                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
11888                 END IF;
11889               x_po_shipment_num := -1;
11890               if nvl(l_needby_prf,'Y') = 'Y' then   -- Bug 3201308
11891                x_create_new_line := 'Y';
11892               end if;
11893             WHEN OTHERS THEN
11894                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11895                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11896                                        p_progress => l_progress);
11897                 END IF;
11898           wrapup(x_interface_header_id);
11899     RAISE;
11900 
11901       END;
11902         -- Bug 3534897 : added nvl to create new line flag
11903         IF x_po_shipment_num <> -1 and nvl(x_create_new_line,'N') <> 'Y' THEN
11904           l_progress:='050';
11905           BEGIN
11906 
11907          -- SQL WHAT : compares the existing shipment values with the values from the req
11908          -- SQL WHY : to create a new line if ship to is different based on the value of the
11909          --           profile
11910 
11911          SELECT PLL.shipment_num
11912           ,PLL.line_location_id
11913          INTO   x_po_shipment_num
11914     ,x_line_location_to_check
11915          FROM   PO_LINE_LOCATIONS_ALL    PLL  --<Shared Proc FPJ>
11916          WHERE  PLL.PO_LINE_ID = x_po_line_id
11917          AND    PLL.SHIP_TO_LOCATION_ID = x_ship_to_location_id
11918          AND    PLL.SHIP_TO_ORGANIZATION_ID =
11919             x_destination_org_id
11920          AND    ROWNUM = 1
11921          FOR UPDATE OF PLL.QUANTITY;
11922 
11923          EXCEPTION
11924             WHEN NO_DATA_FOUND THEN
11925                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11926                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11927                                         p_token    => l_progress,
11928                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
11929                 END IF;
11930               x_po_shipment_num := -1;
11931               if nvl(l_shipto_prf,'Y') = 'Y' then  -- Bug 3201308
11932                x_create_new_line := 'Y';
11933               end if;
11934             WHEN OTHERS THEN
11935                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11936                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11937                                        p_progress => l_progress);
11938                 END IF;
11939           wrapup(x_interface_header_id);
11940     RAISE;
11941 
11942           END;
11943         END IF;
11944 
11945         -- Bug 3534897 : added nvl to create new line flag
11946         IF x_po_shipment_num <> -1 and nvl(x_create_new_line,'N') <> 'Y' THEN
11947           l_progress:='060';
11948           BEGIN
11949 
11950          -- SQL WHAT : compares the exixting shipment values with the values from the req
11951          -- SQL WHY : to create a new line if its a drop ship line or consigned flag is
11952          --           different
11953 
11954          SELECT PLL.shipment_num
11955           ,PLL.line_location_id
11956          INTO   x_po_shipment_num
11957     ,x_line_location_to_check
11958          FROM   PO_LINE_LOCATIONS_ALL    PLL  --<Shared Proc FPJ>
11959          WHERE  PLL.PO_LINE_ID = x_po_line_id
11960          AND    nvl(PLL.drop_ship_flag, 'N') <> 'Y' --<DropShip FPJ> cannot add to Drop Ship Shipments
11961          AND   nvl(PLL.CONSIGNED_FLAG,'N') = nvl(x_consigned_flag,'N')
11962          AND    ROWNUM = 1
11963          FOR UPDATE OF PLL.QUANTITY;
11964 
11965          EXCEPTION
11966             WHEN NO_DATA_FOUND THEN
11967                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
11968                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
11969                                         p_token    => l_progress,
11970                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
11971                 END IF;
11972               x_po_shipment_num := -1;
11973               x_create_new_line := 'Y';
11974             WHEN OTHERS THEN
11975                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
11976                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
11977                                        p_progress => l_progress);
11978                 END IF;
11979           wrapup(x_interface_header_id);
11980     RAISE;
11981 
11982           END;
11983         END IF;
11984 
11985       END IF;  -- end of po line id not null check
11986 
11987       IF x_po_shipment_num <> -1 THEN
11988          l_progress:='070';
11989          BEGIN
11990 
11991          -- SQL WHAT : compares the exixting shipment values with the values from the req
11992          -- SQL WHY : if the above values match then we need to determine if we need to create
11993          --           a new shipment or not
11994 
11995          SELECT PLL.shipment_num
11996          INTO   x_po_shipment_num
11997          FROM   PO_LINE_LOCATIONS_ALL    PLL,  --<Shared Proc FPJ>
11998                 PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
11999                 PO_SYSTEM_PARAMETERS_ALL     PSP  --<Shared Proc FPJ>
12000          WHERE  PLL.LINE_LOCATION_ID = x_line_location_to_check
12001          AND    PRL.REQUISITION_LINE_ID = x_requisition_line_id
12002    AND    rtrim(nvl(PLL.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
12003          AND    PLL.SHIPMENT_TYPE in ('STANDARD', 'SCHEDULED',
12004             'BLANKET')
12005          AND    NVL(PLL.ENCUMBERED_FLAG,'N') = 'N'
12006          AND    NVL(PLL.CANCEL_FLAG,'N') = 'N'
12007          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)
12008          AND    PLL.ACCRUE_ON_RECEIPT_FLAG =
12009                 decode(interface.transaction_flow_header_id, NULL,  --<Shared Proc FPJ>
12010                  decode(prl.destination_type_code,'EXPENSE',
12011                      decode(psp.expense_accrual_code,'PERIOD END','N',
12012                             decode(nvl(item.receipt_required_flag,
12013                                    nvl(interface.receipt_required_flag,
12014                                    nvl(vendor.receipt_required_flag,
12015                                    nvl(params.receiving_flag,'N')))),
12016                             'N','N','Y')),'Y'), 'Y')  --<Shared Proc FPJ>
12017 -- start of 1548597
12018          AND
12019                (
12020                 ( PLL.PREFERRED_GRADE IS NULL AND  x_preferred_grade IS NULL )
12021                  OR
12022                 (  PLL.PREFERRED_GRADE = x_preferred_grade )
12023                 )
12024 -- end of 1548597
12025          AND    NVL(PLL.VMI_FLAG, 'N')  =  NVL(x_vmi_flag, 'N')          --  VMI
12026          AND    ROWNUM = 1
12027          FOR UPDATE OF PLL.QUANTITY;
12028 
12029          EXCEPTION
12030             WHEN NO_DATA_FOUND THEN
12031                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12032                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12033                                         p_token    => l_progress,
12034                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12035                 END IF;
12036               x_po_shipment_num := -1;
12037             WHEN OTHERS THEN
12038                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12039                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12040                                        p_progress => l_progress);
12041                 END IF;
12042           wrapup(x_interface_header_id);
12043     RAISE;
12044 
12045       END;
12046       END IF;
12047       /* Consigned FPI end */
12048 
12049       /* OE Drop Ship
12050       ** Make sure not to add to  dropship related shipment.
12051       */
12052       IF x_po_shipment_num <> -1 THEN
12053           l_progress:='080';
12054    x_so_line_id_from_shipment:=
12055           OE_DROP_SHIP_GRP.PO_Line_Location_Is_Drop_Ship(x_line_location_to_check);
12056    IF x_so_line_id_from_shipment IS NOT NULL THEN
12057       x_po_shipment_num := -1;
12058          END IF;
12059       END IF;
12060 
12061    ELSIF (g_document_type = 'RFQ') THEN
12062 
12063       l_progress:='090';
12064       BEGIN
12065 
12066          SELECT PLL.shipment_num
12067          INTO   x_po_shipment_num
12068          FROM   PO_LINE_LOCATIONS_ALL    PLL,  --<Shared Proc FPJ>
12069                 PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
12070                 PO_SYSTEM_PARAMETERS_ALL     PSP  --<Shared Proc FPJ>
12071          WHERE  PLL.PO_LINE_ID = x_po_line_id
12072          AND    PRL.REQUISITION_LINE_ID = x_requisition_line_id
12073          --Bug4599140 (included the following OR condition so that the SQL works correctly
12074          --for null need by date)
12075          AND    ( ( to_char(PLL.need_by_date-(to_number(substr(to_char(PLL.need_by_date,
12076                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
12077                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
12078                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
12079                                  )
12080                   OR
12081                   (PLL.need_by_date is NULL AND x_need_by_date is NULL)
12082                 )
12083    AND    rtrim(nvl(PLL.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
12084          AND    PLL.SHIP_TO_LOCATION_ID = x_ship_to_location_id
12085          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12086          AND    ROWNUM = 1
12087          FOR UPDATE OF PLL.QUANTITY;
12088 
12089          EXCEPTION
12090             WHEN NO_DATA_FOUND THEN
12091                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12092                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12093                                         p_token    => l_progress,
12094                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12095                 END IF;
12096               x_po_shipment_num := -1;
12097             WHEN OTHERS THEN
12098                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12099                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12100                                        p_progress => l_progress);
12101                 END IF;
12102        wrapup(x_interface_header_id);
12103        RAISE;
12104 
12105       END;
12106 
12107    ELSE /* Release */
12108 
12109       l_progress:='100';
12110 
12111       x_po_shipment_num := -1;
12112 
12113       BEGIN
12114 
12115          SELECT por.po_release_id
12116            INTO g_po_release_id
12117            FROM po_releases_all por,  --<Shared Proc FPJ>
12118                 po_headers_interface phi
12119           WHERE phi.interface_header_id = x_interface_header_id
12120             AND phi.release_num = por.release_num
12121             AND phi.po_header_id = por.po_header_id
12122             AND NVL(por.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12123             FOR UPDATE OF por.approved_flag;
12124 
12125          EXCEPTION
12126            WHEN NO_DATA_FOUND THEN
12127 	   --Bug5584718(we need to clear g_po_release_id)
12128                 g_po_release_id := null;
12129                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12130                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12131                                         p_token    => l_progress,
12132                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12133                 END IF;
12134            WHEN OTHERS THEN
12135                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12136                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12137                                        p_progress => l_progress);
12138                 END IF;
12139        wrapup(x_interface_header_id);
12140        RAISE;
12141 
12142       END;
12143 
12144       l_progress := '105';
12145 
12146       -- bug2788115 START
12147       -- Derive po_line_id if only line number is provided
12148 
12149       IF (x_po_line_num <> -1 AND x_po_line_id IS NULL) THEN
12150 
12151           PO_DEBUG.debug_stmt
12152           ( p_log_head => g_log_head || l_api_name,
12153             p_token    => l_progress,
12154             p_message  => 'Derive po_line_id from line num ' || x_po_line_num
12155           );
12156 
12157           SELECT POL.po_line_id
12158           INTO   l_po_line_id
12159           FROM   po_headers_interface PHI,
12160                  po_lines_all POL
12161           WHERE  PHI.interface_header_id = x_interface_header_id
12162           AND    PHI.po_header_id = POL.po_header_id
12163           AND    POL.line_num = x_po_line_num;
12164       ELSE
12165           l_po_line_id := x_po_line_id;
12166       END IF;
12167 
12168       -- bug2788115 END
12169 
12170       l_progress:='110';
12171       BEGIN
12172 
12173     --<bug#5050294 START>
12174     --As per the HLD.
12175     --Only Requisition grouping will be available for the new Service line types.
12176     --That is why we cannot group req lines withe RATE OR FIXED PRICE line types
12177     --onto the same shipment.
12178     --<bug#5050294 END>
12179 
12180          SELECT PLL.shipment_num
12181                ,PLL.line_location_id
12182          INTO   x_po_shipment_num,
12183                 x_line_location_to_check
12184          FROM   PO_LINE_LOCATIONS_ALL    PLL,  --<Shared Proc FPJ>
12185                 PO_LINES_ALL POL, --<bug#5050294>
12186                 PO_LINE_TYPES PLT --<bug#5050294>
12187          WHERE  POL.PO_LINE_ID = l_po_line_id  -- bug2788115
12188          AND    POL.po_line_id = PLL.po_line_id --<bug#5050294>
12189          AND    POL.line_type_id = PLT.line_type_id --<bug#5050294>
12190          AND    PLT.order_type_lookup_code NOT IN ('RATE', 'FIXED PRICE')--<bug#5050294>
12191          AND    PLL.po_release_id = g_po_release_id
12192  --Bug 4599140 (included the following OR condition so that the SQL works correctly
12193  --for null need by date)
12194          AND    ( ( to_char(PLL.need_by_date-(to_number(substr(to_char(PLL.need_by_date,
12195                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
12196                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
12197                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
12198                                  )
12199                   OR
12200                   (PLL.need_by_date is NULL AND x_need_by_date is NULL)
12201                )
12202          AND    nvl(PLL.drop_ship_flag, 'N') <> 'Y' --<DropShip FPJ> cannot add to Drop Ship Shipments
12203          --togeorge 09/27/2000
12204    --added note to receiver
12205    --AND    rtrim(PLL.note_to_receiver) = rtrim(x_note_to_receiver)
12206    --Bug# 1867976,togeorge, 07/06/2001
12207    --added nvl
12208    AND    rtrim(nvl(PLL.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
12209          AND    PLL.SHIP_TO_LOCATION_ID = x_ship_to_location_id
12210          AND    PLL.SHIP_TO_ORGANIZATION_ID =
12211             x_destination_org_id
12212          AND    PLL.SHIPMENT_TYPE in ('STANDARD', 'SCHEDULED',
12213             'BLANKET')
12214          AND    NVL(PLL.ENCUMBERED_FLAG,'N') = 'N'
12215          AND    NVL(PLL.CANCEL_FLAG,'N') = 'N'
12216 -- start of 1548597
12217          AND
12218                (
12219                 ( PLL.PREFERRED_GRADE IS NULL AND  x_preferred_grade IS NULL )
12220                  OR
12221                 (  PLL.PREFERRED_GRADE = x_preferred_grade )
12222                 )
12223 -- end of 1548597
12224          AND    NVL(PLL.VMI_FLAG, 'N')  =  NVL(x_vmi_flag, 'N')          --  VMI FPH
12225          AND    nvl(PLL.CONSIGNED_FLAG,'N') = nvl(x_consigned_flag,'N')  -- CONSIGNED FPI
12226          AND    ROWNUM = 1
12227          FOR UPDATE OF PLL.QUANTITY;
12228 
12229 
12230          EXCEPTION
12231             WHEN NO_DATA_FOUND THEN
12232                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12233                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12234                                         p_token    => l_progress,
12235                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12236                 END IF;
12237               x_po_shipment_num := -1;
12238             WHEN OTHERS THEN
12239                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12240                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12241                                        p_progress => l_progress);
12242                 END IF;
12243        wrapup(x_interface_header_id);
12244        RAISE;
12245 
12246       END;
12247 
12248       IF x_po_shipment_num <> -1 THEN
12249           l_progress:='120';
12250    x_so_line_id_from_shipment:=
12251           OE_DROP_SHIP_GRP.PO_Line_Location_Is_Drop_Ship(x_line_location_to_check);
12252    IF x_so_line_id_from_shipment IS NOT NULL THEN
12253       x_po_shipment_num := -1;
12254          END IF;
12255       END IF;
12256 
12257    END IF;
12258 
12259    IF (x_po_shipment_num = -1) and (g_document_type = 'PO') THEN
12260 
12261       /*
12262       ** Get the receipt required flag that
12263       ** will be inserted for the shipment.
12264       */
12265       l_progress:='130';
12266 
12267       /* Bug No. 1362044. We were not correctly considering the
12268     Accrue on Recepit Flag when grouping the shipments. Modified this logic .
12269     This part of the code gets the current Accrue on Receipt flag which will
12270     be compared with the other records in the interface table to see if
12271     they can be grouped together .
12272     Also added po_requisition_lines to the join to get the destination_type_code
12273     also added the outer join on po_vendors
12274     */
12275     /* Bug # 2224446, Autocreate was not grouping Req. lines when two req.
12276     with the same line details was entered. This happened when they don't
12277     Enter a Item in the lines block. We were not considering that the Item
12278     can be NULL when grouping shipment line. Used outer join on
12279     mtl_system_items when Checking for Item details. */
12280 
12281     --<bug#5050294 START>
12282     --As per the HLD.
12283     --Only Requisition grouping will be available for the new Service line types.
12284     --That is why we cannot group req lines withe RATE OR FIXED PRICE line types
12285     --onto the same shipment.
12286     --<bug#5050294 END>
12287 
12288       BEGIN
12289          SELECT DECODE(PRL.destination_type_code,
12290                       'EXPENSE',
12291                         decode(nvl(msi.receipt_required_flag,
12292                       nvl(plt.receiving_flag,
12293                        nvl(pov.receipt_required_flag,
12294                         nvl(psp.receiving_flag, 'N')))) ,'N','N',
12295                                decode(psp.expense_accrual_code,'PERIOD END', 'N', 'Y')),
12296                        'INVENTORY', 'Y',
12297                        'SHOP FLOOR','Y')
12298          INTO   x_receipt_required_flag
12299          FROM   po_lines_interface pli,
12300                 po_headers_interface phi,
12301                     po_requisition_lines_all prl,  --<Shared Proc FPJ>
12302                 mtl_system_items msi,
12303                 po_line_types plt,
12304                 po_vendors pov,
12305                 po_system_parameters_all psp,  --<Shared Proc FPJ>
12306                 financials_system_params_all fsp  --<Shared Proc FPJ>
12307          WHERE  pli.item_id = msi.inventory_item_id(+)
12308            AND  nvl(msi.organization_id,fsp.inventory_organization_id)=
12309              fsp.inventory_organization_id
12310            AND  pli.line_type_id = plt.line_type_id
12311            AND PLT.order_type_lookup_code NOT IN ('RATE', 'FIXED PRICE')--<bug#5050294>
12312            AND  phi.vendor_id = pov.vendor_id(+)
12313            AND  phi.interface_header_id =
12314         pli.interface_header_id
12315            AND  pli.interface_header_id =
12316                             phi.interface_header_id
12317            AND  prl.requisition_line_id = pli.requisition_line_id
12318            AND  pli.requisition_line_id =
12319                             x_requisition_line_id
12320            AND  NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12321            AND  NVL(fsp.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
12322 
12323       EXCEPTION
12324            WHEN NO_DATA_FOUND THEN
12325                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12326                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12327                                         p_token    => l_progress,
12328                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12329                 END IF;
12330            WHEN OTHERS THEN
12331                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12332                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12333                                        p_progress => l_progress);
12334                 END IF;
12335            wrapup(x_interface_header_id);
12336      RAISE;
12337       END;
12338 
12339       l_progress:='140';
12340 
12341       IF (g_document_type = 'PO') THEN
12342 
12343         BEGIN
12344         /*
12345         ** See if a record that has just been inserted into the
12346         ** interface table matches the shipment you are trying to create.
12347         */
12348         /* Bug # 2224446, Added outer join on mtl_system_items */
12349 /* Bug: 2348161.Changed the below SQL and removed the reference to the tables
12350                 HZ_LOCATIONS and HR_LOCATIONS and also the corresponding where
12351                 clause. Instead added a subquery to check for the location_id
12352                 to improve the performance
12353 */
12354 /* Bug 2466578. Changed the UNION to UNION ALL in the sub query to improve the
12355                 performance.
12356 */
12357 
12358         SELECT PLI.shipment_num
12359          ,PLI.requisition_line_id
12360          INTO   x_po_shipment_num
12361     ,x_req_line_to_check
12362          FROM   PO_LINES_INTERFACE   PLI,
12363             PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
12364                 --bug 1942696 hr_location changes to reflect the new view
12365       MTL_SYSTEM_ITEMS     MSI ,
12366                 PO_LINE_TYPES        PLT ,
12367                 PO_SYSTEM_PARAMETERS_ALL PSP ,  --<Shared Proc FPJ>
12368                 FINANCIALS_SYSTEM_PARAMS_ALL FSP,  --<Shared Proc FPJ>
12369                 PO_VENDORS           POV,
12370                 PO_HEADERS_INTERFACE PHI
12371          WHERE  PLI.LINE_NUM = x_po_line_num
12372      AND    PLI.shipment_num is not null
12373          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12374          AND    NVL(fsp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12375      AND    PLI.item_id = MSI.inventory_item_id(+)
12376          AND    nvl(MSI.organization_id,FSP.inventory_organization_id)=
12377                     FSP.inventory_organization_id
12378          AND    PLI.line_type_id = PLT.line_type_id
12379          AND    PHI.vendor_id  = POV.vendor_id (+)
12380          AND    PLI.interface_header_id =
12381                     PHI.interface_header_id
12382          AND    PRL.REQUISITION_LINE_ID <>
12383         x_requisition_line_id
12384    AND    PRL.requisition_line_id = PLI.requisition_line_id
12385   --Bug 4599140 (included the following OR condition so that the SQL works correctly
12386 	--for null need by date)
12387          AND   ( ( to_char(PLI.need_by_date-(to_number(substr(to_char(PLI.need_by_date,
12388                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
12389                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
12390                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
12391                                  )
12392                 OR
12393                 (PLI.need_by_date is NULL AND x_need_by_date is NULL)
12394                 )
12395          AND    nvl(PLI.drop_ship_flag, 'N') <> 'Y' --<DropShip FPJ> cannot add to Drop Ship Shipments
12396          --togeorge 09/27/2000
12397    --added note to receiver
12398    --AND    rtrim(PLI.note_to_receiver) = rtrim(x_note_to_receiver)
12399    --Bug# 1867976,togeorge, 07/06/2001
12400    --added nvl
12401    AND    rtrim(nvl(PLI.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
12402          --bug 1942696 hr_location changes to reflect the new view
12403        AND exists (select 'x'
12404                    from HR_LOCATIONS HRL
12405                    where PRL.deliver_to_location_id = HRL.location_id
12406                    and nvl(HRL.ship_to_location_id, HRL.location_id) = x_ship_to_location_id
12407                    UNION ALL
12408                    select 'x'
12409                    from HZ_LOCATIONS HZ
12410                    where PRL.deliver_to_location_id = HZ.location_id
12411                    and HZ.location_id = x_ship_to_location_id)
12412        AND    PRL.destination_organization_id = x_destination_org_id
12413      AND    DECODE(PRL.destination_type_code,
12414         'EXPENSE',
12415                       decode(nvl(msi.receipt_required_flag,
12416                             nvl(plt.receiving_flag,
12417                                  nvl(pov.receipt_required_flag,
12418                                   nvl(psp.receiving_flag,'N')))),'N','N',
12419                    decode(psp.expense_accrual_code, 'PERIOD END', 'N', 'Y')),
12420         'INVENTORY', 'Y',
12421         'SHOP FLOOR', 'Y')
12422           = x_receipt_required_flag
12423 -- start of 1548597
12424          AND
12425                (
12426                 ( PLI.PREFERRED_GRADE IS NULL AND  x_preferred_grade IS NULL )
12427                  OR
12428                 ( PLI.PREFERRED_GRADE = x_preferred_grade )
12429                 )
12430 -- end of 1548597
12431          AND    NVL(PLI.VMI_FLAG, 'N')  =  NVL(x_vmi_flag, 'N')   --  VMI FPH
12432          AND    nvl(PLI.CONSIGNED_FLAG,'N') = nvl(x_consigned_flag,'N')  --CONSIGNED FPI
12433          AND    ROWNUM = 1;
12434 /*Bug 2466578. Removed the ORDER BY Clause as we are using the ROWNUM = 1 condition and
12435                no need to order a single row. This is done to  improve the performance.
12436      ORDER BY shipment_num;
12437 */
12438 
12439      EXCEPTION
12440            WHEN NO_DATA_FOUND THEN
12441                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12442                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12443                                         p_token    => l_progress,
12444                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12445                 END IF;
12446         x_po_shipment_num := -1;
12447            WHEN OTHERS THEN
12448                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12449                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12450                                        p_progress => l_progress);
12451                 END IF;
12452        wrapup(x_interface_header_id);
12453        RAISE;
12454         END;
12455 
12456         /* Make sure that the potential shipment is related
12457         ** to drop ship
12458         */
12459         IF x_po_shipment_num <> -1 THEN
12460           l_progress:='150';
12461     x_so_line_id_from_req_line:=
12462             OE_DROP_SHIP_GRP.PO_Line_Location_Is_Drop_Ship(x_req_line_to_check);
12463     IF x_so_line_id_from_req_line IS NOT NULL THEN
12464        x_po_shipment_num := -1;
12465           END IF;
12466         END IF;
12467 
12468       ELSE
12469         /* not PO type */
12470 
12471         l_progress:='160';
12472         BEGIN
12473         /*
12474         ** See if a record that has just been inserted into the
12475         ** interface table matches the shipment you are trying to create.
12476         */
12477 /* Bug: 2348161.Changed the below SQL and removed the reference to the tables
12478                 HZ_LOCATIONS and HR_LOCATIONS and also the corresponding where
12479                 clause. Instead added a subquery to check for the location_id
12480                 to improve the performance
12481 */
12482         SELECT PLI.shipment_num
12483          INTO   x_po_shipment_num
12484          FROM   PO_LINES_INTERFACE   PLI,
12485                 PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
12486       MTL_SYSTEM_ITEMS     MSI ,
12487                 PO_LINE_TYPES        PLT ,
12488                 PO_SYSTEM_PARAMETERS_ALL PSP ,  --<Shared Proc FPJ>
12489                 FINANCIALS_SYSTEM_PARAMS_ALL FSP,  --<Shared Proc FPJ>
12490                 PO_VENDORS           POV,
12491                 PO_HEADERS_INTERFACE PHI
12492          WHERE  PLI.LINE_NUM = x_po_line_num
12493      AND    PLI.shipment_num is not null
12494      AND    PLI.item_id = MSI.inventory_item_id
12495          AND    MSI.organization_id=
12496                     FSP.inventory_organization_id
12497          AND    PLI.line_type_id = PLT.line_type_id
12498          AND    PHI.vendor_id  = POV.vendor_id (+)
12499          AND    PLI.interface_header_id =
12500                     PHI.interface_header_id
12501          AND    PRL.REQUISITION_LINE_ID =
12502         x_requisition_line_id
12503          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12504          AND    NVL(fsp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12505          --Bug 4599140 (included the following OR condition so that the SQL works correctly
12506          --for null need by date)
12507          AND    ( ( to_char(PLI.need_by_date-(to_number(substr(to_char(PLI.need_by_date,
12508                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
12509                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
12510                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
12511                                  )
12512                    OR
12513                    (PLI.need_by_date is NULL AND x_need_by_date is NULL)
12514                )
12515          AND    nvl(PLI.drop_ship_flag, 'N') <> 'Y' --<DropShip FPJ> cannot add to Drop Ship Shipments
12516          --togeorge 09/27/2000
12517    --added note to receiver
12518    --AND    rtrim(PLI.note_to_receiver) = rtrim(x_note_to_receiver)
12519    --Bug# 1867976,togeorge, 07/06/2001
12520    --added nvl
12521    AND    rtrim(nvl(PLI.note_to_receiver,'99')) = rtrim(nvl(x_note_to_receiver,'99'))
12522          --bug 1942696 hr_location changes to reflect the new view
12523        AND exists (select 'x'
12524                    from HR_LOCATIONS HRL
12525                    where PRL.deliver_to_location_id = HRL.location_id
12526                    and nvl(HRL.ship_to_location_id, HRL.location_id) = x_ship_to_location_id
12527                    UNION ALL
12528                    select 'x'
12529                    from HZ_LOCATIONS HZ
12530                    where PRL.deliver_to_location_id = HZ.location_id
12531                    and HZ.location_id = x_ship_to_location_id)
12532 -- start of 1548597
12533          AND
12534                (
12535                 ( PLI.PREFERRED_GRADE IS NULL AND  x_preferred_grade IS NULL )
12536                  OR
12537                 ( PLI.PREFERRED_GRADE = x_preferred_grade )
12538                 )
12539 -- end of 1548597
12540          AND    ROWNUM = 1
12541      ORDER BY shipment_num;
12542 
12543      EXCEPTION
12544            WHEN NO_DATA_FOUND THEN
12545                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12546                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12547                                         p_token    => l_progress,
12548                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12549                 END IF;
12550         x_po_shipment_num := -1;
12551            WHEN OTHERS THEN
12552                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12553                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12554                                        p_progress => l_progress);
12555                 END IF;
12556        wrapup(x_interface_header_id);
12557        RAISE;
12558          END;
12559 
12560       END IF;
12561 
12562 /* Bug# 1512955: kagarwal
12563 ** Forward Fix of bug# 1502551
12564 --Added by jbalakri for  1502551 , RFQ's having multiple lines at the
12565 --shipment level even though requisitions are having same item,need by
12566 --date and ship to location.
12567 */
12568 
12569    ELSIF (x_po_shipment_num=-1) and (g_document_type='RFQ') THEN
12570 
12571      l_progress:='170';
12572      BEGIN
12573         /*
12574         ** See if a record that has just been inserted into the
12575         ** interface table matches the shipment you are trying to create.
12576         */
12577       begin
12578         l_progress:='180';
12579         SELECT document_subtype
12580         into x_check_doc_sub_type
12581         from
12582         PO_HEADERS_INTERFACE
12583         WHERE
12584         INTERFACE_HEADER_ID=x_interface_header_id;
12585       exception
12586       When others then
12587         IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12588             PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12589                                p_progress => l_progress);
12590         END IF;
12591         wrapup(x_interface_header_id);
12592           raise;
12593       end;
12594        IF x_check_doc_sub_type='BID' then
12595 
12596 /* Bug: 2348161.Changed the below SQL and removed the reference to the tables
12597                 HZ_LOCATIONS and HR_LOCATIONS and also the corresponding where
12598                 clause. Instead added a subquery to check for the location_id
12599                 to improve the performance
12600 */
12601 
12602     /* Bug # 2286618, Autocreate was not grouping Req. lines when two req.
12603     with the same line details was entered. This happened when they Entered
12604     a One Time Item in the lines block. We were not considering that the Item
12605     can be NULL when grouping shipment line. Used outer join on
12606     mtl_system_items when Checking for Item details. */
12607 
12608          l_progress:='190';
12609          SELECT PLI.shipment_num
12610          INTO   x_po_shipment_num
12611          FROM   PO_LINES_INTERFACE   PLI,
12612                 PO_REQUISITION_LINES_ALL PRL,  --<Shared Proc FPJ>
12613            --bug 1942696 hr_location changes to reflect the new view
12614                 MTL_SYSTEM_ITEMS     MSI ,
12615                 PO_LINE_TYPES        PLT ,
12616                 PO_SYSTEM_PARAMETERS_ALL PSP ,  --<Shared Proc FPJ>
12617                 FINANCIALS_SYSTEM_PARAMS_ALL FSP,  --<Shared Proc FPJ>
12618                 PO_VENDORS           POV,
12619                 PO_HEADERS_INTERFACE PHI
12620          WHERE  PLI.LINE_NUM = x_po_line_num
12621          AND    PLI.shipment_num is not null
12622          AND    NVL(psp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12623          AND    NVL(fsp.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12624          AND    PLI.item_id = MSI.inventory_item_id(+)
12625          AND    nvl(MSI.organization_id,FSP.inventory_organization_id) =
12626                     FSP.inventory_organization_id
12627          AND    PLI.line_type_id = PLT.line_type_id
12628          AND    PHI.vendor_id  = POV.vendor_id (+)
12629          AND    PLI.interface_header_id =
12630                     PHI.interface_header_id
12631 /* Bug# 1638668, forward fix of 1549754 */
12632 --changed by jbalakri  during testing of 1549754
12633        --AND    PRL.REQUISITION_LINE_ID =
12634        --       x_requisition_line_id
12635          AND    PRL.REQUISITION_LINE_ID <>
12636                         x_requisition_line_id
12637          AND PRL.requisition_line_id=PLI.requisition_line_id
12638 --end of change for 1549754
12639     --Bug 4599140 (included the following OR condition so that the SQL works correctly
12640     --for null need by date)
12641          AND    ( ( to_char(PLI.need_by_date-(to_number(substr(to_char(PLI.need_by_date,
12642                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS') =
12643                                   to_char(x_need_by_date-(to_number(substr(to_char(x_need_by_date,
12644                                   'DD-MM-YYYY HH24:MI:SS'),18, 2))/86400), 'DD-MM-YYYY HH24:MI:SS')
12645                                  )
12646                      OR
12647                      (PLI.need_by_date is NULL AND x_need_by_date is NULL)
12648                 )
12649          --bug 1942696 hr_location changes to reflect the new view
12650          AND exists (select 'x'
12651                      from HR_LOCATIONS HRL
12652                      where PRL.deliver_to_location_id = HRL.location_id
12653                      and nvl(HRL.ship_to_location_id, HRL.location_id) = x_ship_to_location_id
12654                      UNION ALL
12655                      select 'x'
12656                      from HZ_LOCATIONS HZ
12657                      where PRL.deliver_to_location_id = HZ.location_id
12658                      and HZ.location_id = x_ship_to_location_id)
12659          AND    ROWNUM = 1
12660          ORDER BY shipment_num;
12661        END IF;
12662          EXCEPTION
12663            WHEN NO_DATA_FOUND THEN
12664                 IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12665                     PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12666                                         p_token    => l_progress,
12667                                         p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12668                 END IF;
12669                   x_po_shipment_num := -1;
12670            WHEN OTHERS THEN
12671                 IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12672                     PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12673                                        p_progress => l_progress);
12674                 END IF;
12675              wrapup(x_interface_header_id);
12676              RAISE;
12677          END;
12678 
12679 --end of change
12680 
12681    END IF; -- end of grouping
12682    --Bug 7312562
12683    --Moving this code to the end of the procedure.
12684    --So that the same logic is used for Drop shipments also.
12685    --Ensuring that two drop shipments are not inserted into same shipment,
12686    --by setting x_po_shipment_num := -1;
12687    IF g_document_type = 'PO' AND x_drop_ship_flag = 'Y' THEN
12688      x_po_shipment_num := -1;
12689    END IF;
12690 
12691     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12692         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
12693     END IF;
12694 EXCEPTION
12695   WHEN NO_DATA_FOUND THEN
12696      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12697          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12698                              p_token    => l_progress||'_main',
12699                              p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12700      END IF;
12701   WHEN OTHERS THEN
12702      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12703          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12704                             p_progress => l_progress);
12705      END IF;
12706      po_message_s.sql_error('get_shipment_num',l_progress,sqlcode);
12707      wrapup(x_interface_header_id);
12708      raise;
12709 END get_shipment_num;
12710 
12711 
12712 /* ============================================================================
12713      NAME: UPDATE_SHIPMENT
12714      DESC: Update shipment information in interface table
12715      ARGS: x_interface_header_id IN number
12716      x_po_shipment_num IN number
12717      ALGR:
12718    ==========================================================================*/
12719 PROCEDURE update_shipment(x_interface_header_id IN NUMBER,
12720          x_po_shipment_num IN number,
12721          x_po_line_num IN NUMBER,
12722          x_requisition_line_id IN NUMBER,
12723          x_po_line_id IN NUMBER,
12724                x_document_num IN VARCHAR2,
12725          x_release_num IN NUMBER,
12726                            x_create_new_line IN VARCHAR2,
12727                            x_row_id  IN VARCHAR2) IS
12728 x_shipment_num NUMBER;
12729 x_int_shipment_num NUMBER;
12730 x_line_num NUMBER;
12731 x_int_line_num NUMBER;
12732 l_api_name CONSTANT VARCHAR2(30) := 'update_shipment';      --< Bug 3210331 >
12733 l_progress VARCHAR2(3) := '000';                            --< Bug 3210331 >
12734 
12735 BEGIN
12736     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12737         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
12738     END IF;
12739 
12740       /* Shipment Exists */
12741       IF (x_po_shipment_num <> -1) THEN
12742 
12743          /*
12744          ** Shipment exists.
12745          ** A shipment associated with the purchase order
12746          ** line matches the requisition line information.
12747          */
12748 
12749         if x_requisition_line_id is not null then
12750          l_progress := '010';
12751          update po_lines_interface
12752             set shipment_num= x_po_shipment_num
12753           where interface_header_id=x_interface_header_id
12754             and requisition_line_id=x_requisition_line_id;
12755 
12756         else
12757          l_progress := '015';
12758           update po_lines_interface
12759             set shipment_num= x_po_shipment_num
12760           where interface_header_id=x_interface_header_id
12761             and rowid=x_row_id;
12762         end if;
12763 
12764       ELSE /* Shipment does not exist */
12765 
12766          /*
12767          ** Get the maximum shipment number in the po tables
12768          */
12769          l_progress := '020';
12770 
12771    IF (g_document_subtype = 'STANDARD'
12772     OR g_document_subtype = 'PLANNED' OR
12773              g_document_type = 'RFQ')
12774    THEN
12775 
12776            /* GA FPI start : if create new line parameter is 'Y' then we need to reset
12777               the shipment number and create a new line with one shipment */
12778 
12779             IF nvl(x_create_new_line,'N') = 'Y' and g_document_subtype = 'STANDARD' THEN
12780 
12781                x_int_shipment_num := 0;
12782                x_shipment_num     := 0;
12783 
12784                -- Bug 2757020 START
12785                -- In Add mode, PLI.line_num is set to the existing document
12786                -- line number. We need to generate a new line number.
12787 	       --Bug 6072900
12788 	       -- while Auto Creating PO with req lines with same need by dates from DropShip Sales Order
12789 	       -- the below condition is false for g_mode=NEW ,because of this req lines with same
12790                -- need-by-dates were combined into one line and one shipment .
12791 	       -- So commented the below condition.
12792 
12793                --IF (g_mode = 'ADD') THEN
12794                   -- Set PLI.line_num to the largest line number in use + 1.
12795 
12796                   l_progress := '030';
12797                   select nvl(max(line_num),0)
12798                    into x_line_num
12799                    from po_headers_all ph,  --<Shared Proc FPJ>
12800                         po_lines_all pl  --<Shared Proc FPJ>
12801                   where pl.po_header_id = ph.po_header_id
12802                     and ph.segment1 = x_document_num
12803                     AND NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
12804 
12805                   l_progress := '040';
12806                   select nvl(max(line_num),0)
12807                    into x_int_line_num
12808                    from po_lines_interface pli
12809                   where pli.interface_header_id = x_interface_header_id;
12810 
12811                   IF (x_line_num >= x_int_line_num) THEN
12812                      x_line_num := x_line_num;
12813                   ELSE
12814                      x_line_num := x_int_line_num;
12815                   END IF;
12816 
12817                   l_progress := '050';
12818                   update po_lines_interface
12819                   set    line_num = x_line_num + 1
12820                   where  interface_header_id = x_interface_header_id
12821                   and    requisition_line_id = x_requisition_line_id;
12822                -- Bug 6072900
12823                --END IF;
12824 
12825                -- Bug 2757020 END
12826 
12827             /* GA FPI end */
12828 
12829             ELSE
12830                l_progress := '060';
12831                select nvl(max(shipment_num),0)
12832                  into x_shipment_num
12833                  from po_line_locations_all poll  --<Shared Proc FPJ>
12834                 where poll.po_line_id = x_po_line_id
12835                   and poll.shipment_type in ('STANDARD', 'PLANNED', 'RFQ');
12836 
12837                -- Bug 605715, lpo, 01/05/98
12838                -- We now check to see if the line_num matches as well by
12839                -- appending an AND condition in the WHERE clause.
12840 
12841                l_progress := '070';
12842                /*
12843                ** Get the max shipment number already
12844                ** assigned in the interface table.
12845                */
12846                select nvl(max(shipment_num),0)
12847                into x_int_shipment_num
12848                from po_lines_interface pli
12849                where pli.interface_header_id = x_interface_header_id
12850                and pli.line_num = x_po_line_num;
12851 
12852               -- End of fix. Bug 605715, lpo, 01/05/98
12853             END IF; -- create new line
12854 
12855         ELSE
12856            l_progress := '080';
12857 
12858          select nvl(max(shipment_num),0)
12859          into   x_shipment_num
12860                from   po_headers_all ph,  --<Shared Proc FPJ>
12861                      po_line_locations_all poll,  --<Shared Proc FPJ>
12862                      po_releases_all pr  --<Shared Proc FPJ>
12863                where  ph.po_header_id = poll.po_header_id
12864                and    ph.segment1 = x_document_num
12865                and    pr.po_header_id = ph.po_header_id
12866                and    pr.release_num = x_release_num
12867                and    ph.type_lookup_code = 'BLANKET'
12868                and    poll.po_release_id=pr.po_release_id
12869                AND    NVL(pr.org_id, -99) = NVL(g_purchasing_ou_id, -99)  --<Shared Proc FPJ>
12870                AND    NVL(ph.org_id, -99) = NVL(g_purchasing_ou_id, -99);  --<Shared Proc FPJ>
12871 
12872                -- Bug 605715, lpo, 01/05/98
12873                -- For Releases, we don't care about the line_num.
12874 
12875                l_progress := '090';
12876                /*
12877                ** Get the max shipment number already
12878                ** assigned in the interface table.
12879                */
12880                select nvl(max(shipment_num),0)
12881                into x_int_shipment_num
12882                from po_lines_interface pli
12883                where pli.interface_header_id = x_interface_header_id;
12884 
12885                -- End of fix. Bug 605715, lpo, 01/05/98
12886 
12887    END IF;
12888 
12889          l_progress := '100';
12890 
12891          IF (x_shipment_num >= x_int_shipment_num) THEN
12892           x_shipment_num := x_shipment_num;
12893          ELSE
12894           x_shipment_num := x_int_shipment_num;
12895          END IF;
12896 
12897         if x_requisition_line_id is not null then
12898           l_progress := '110';
12899           update po_lines_interface
12900             set shipment_num = x_shipment_num + 1
12901           where interface_header_id=x_interface_header_id
12902             and requisition_line_id=x_requisition_line_id;
12903         else
12904           l_progress := '120';
12905           update po_lines_interface
12906             set shipment_num = x_shipment_num + 1
12907           where interface_header_id=x_interface_header_id
12908             and rowid=x_row_id;
12909         end if;
12910 
12911       END IF; /* Shipment Exists */
12912 
12913     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12914         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
12915     END IF;
12916 EXCEPTION
12917   WHEN NO_DATA_FOUND THEN
12918      IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12919          PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12920                              p_token    => l_progress||'_main',
12921                              p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12922      END IF;
12923   WHEN OTHERS THEN
12924      IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12925          PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12926                             p_progress => l_progress);
12927      END IF;
12928      po_message_s.sql_error('update_shipment',l_progress,sqlcode);
12929      wrapup(x_interface_header_id);
12930      raise;
12931 
12932 END update_shipment;
12933 
12934 /* ============================================================================
12935      NAME: CALCULATE_LOCAL
12936      DESC: This procedure serve as a hook to the function of localization team.
12937 
12938    ==========================================================================*/
12939 
12940 PROCEDURE CALCULATE_LOCAL(document_type varchar2,
12941                           level_type    varchar2,
12942                           level_id      number
12943 
12944 ) IS
12945 
12946   l_cursor         integer;
12947   sqlstmt          varchar2(2000);
12948   l_jl_installed   varchar2(30);
12949   l_execute        integer;
12950   l_return         number;
12951   l_progress VARCHAR2(3) := '000';                          --< Bug 3210331 >
12952   l_api_name CONSTANT VARCHAR2(30) := 'calculate_local';    --< Bug 3210331 >
12953 BEGIN
12954  /* Bug4430300 Removed the references to the JL_BR packages */
12955 Null;
12956 
12957 
12958 EXCEPTION
12959 
12960     WHEN no_data_found THEN
12961 
12962         ----------------------------------------
12963         -- Regional Procedure is not installed
12964         ----------------------------------------
12965         IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
12966             PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
12967                                 p_token    => l_progress,
12968                                 p_message  => 'NO_DATA_FOUND: '||SQLERRM);
12969         END IF;
12970 
12971     --<Bug 3336920 START>
12972     WHEN OTHERS THEN
12973 
12974         IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
12975            PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
12976                                p_progress => l_progress);
12977         END IF;
12978         RAISE;
12979     --<Bug 3336920 END>
12980 END CALCULATE_LOCAL;
12981 
12982 -- 2082757: Added this function:
12983 /* ============================================================================
12984      NAME: SOURCE_BLANKET_LINE
12985      DESC: Return the line number of that BPO line which matches the
12986            sourcing candidature criterion.
12987      ARGS: IN: x_po_header_id NUMBER : header id of source blanket PO
12988            IN: x_requisition_line_id NUMBER : id of the corresponding req line.
12989            IN: x_interface_line_num NUMBER : number from lines interface table
12990            IN: x_allow_different_uoms VARCHAR2 : If not 'Y', require the
12991              matching BPA line to have the same UOM as the requisition line.
12992            IN: p_purchasing_ou_id NUMBER : purchasing operating unit id
12993      ALGR:
12994            - For One-time item, item description of the BPO line should match
12995              that of requisition line.  For others, both item_id and description
12996              should match.
12997            - If there is no BPO line matching the description, then just match
12998              the item_id.
12999            - For any case above, if more than one candidate BPO lines pass the
13000              conditions, then pick the one having the minimum line_num
13001      See Bug 2082757 for details.
13002   ===========================================================================*/
13003 
13004 FUNCTION source_blanket_line(x_po_header_id IN NUMBER,
13005                              x_requisition_line_id IN NUMBER,
13006                              x_interface_line_num IN NUMBER,
13007                              x_allow_different_uoms IN VARCHAR2, -- Bug 2707576
13008                              p_purchasing_ou_id     IN NUMBER  --<Shared Proc FPJ>
13009                             ) RETURN NUMBER IS
13010 
13011     v_line_num NUMBER := null;
13012     x_item_id  number;
13013     x_inv_org_id  number;
13014     x_item_rev_control number := null;
13015 
13016    /* Bug: 2432506 Expriation of document should happen at the end of
13017            the expiration_date */
13018    /* Bug 3828673:Release was not created when the requisition line type is
13019       different from the source document line type.*/
13020 
13021     CURSOR c1 (p_po_header_id        IN NUMBER,
13022                p_requisition_line_id IN NUMBER,
13023                p_interface_line_num  IN NUMBER,
13024                p_item_rev_control    IN NUMBER,
13025                x_allow_different_uoms IN VARCHAR2 -- Bug 2707576
13026               ) IS
13027                             SELECT MIN(pol.line_num)
13028                             FROM  po_lines_all pol,
13029                                   po_requisition_lines_all prl  --<Shared Proc FPJ>
13030                             WHERE pol.po_header_id = p_po_header_id
13031                             AND   prl.requisition_line_id = p_requisition_line_id
13032                             AND   NVL(pol.cancel_flag,'N') = 'N'
13033                             AND   NVL(pol.closed_code,'OPEN') <> 'FINALLY CLOSED'
13034                             -- Bug 3828673 START
13035                             -- AND   pol.line_type_id = prl.line_type_id
13036                             AND   pol.order_type_lookup_code = prl.order_type_lookup_code
13037                             AND   pol.purchase_basis = prl.purchase_basis
13038                             AND   pol.matching_basis = prl.matching_basis
13039                             -- Bug 3828673 END
13040                             AND   nvl(pol.job_id,-999) = nvl(prl.job_id, -999) -- <SERVICES FPJ>
13041                             AND   (nvl(pol.item_id,-999) = nvl(prl.item_id, -999)
13042                                    and pol.item_description =
13043                                                             prl.item_description)
13044                             AND   ((pol.item_revision IS NULL
13045                                    and prl.item_revision IS NULL)
13046                                    or  pol.item_revision = prl.item_revision
13047                                    or  (prl.item_revision is null  and p_item_rev_control = 1))
13048                             AND   (pol.transaction_reason_code IS NULL
13049                                    or pol.transaction_reason_code =
13050                                    NVL(prl.transaction_reason_code,
13051                                                 pol.transaction_reason_code))
13052                             /*Bug4541335  AND   nvl(p_interface_line_num,pol.line_num) =
13053                                                                      pol.line_num
13054                             AND   trunc(nvl(pol.expiration_date,sysdate+1))
13055                                                                 >= trunc(sysdate) */
13056            /*Bug4541335 start */
13057        AND (p_InterFace_Line_num = pol.Line_num
13058              OR (p_InterFace_Line_num IS NULL
13059                  AND prl.Blanket_po_Header_Id = p_po_Header_Id
13060                  AND prl.Blanket_po_Line_num = pol.Line_num)
13061              OR (p_InterFace_Line_num IS NULL
13062                  AND (prl.Blanket_po_Header_Id <> p_po_Header_Id
13063                        OR prl.Blanket_po_Line_num IS NULL )))
13064        AND (((p_InterFace_Line_num IS NOT NULL
13065                OR (prl.Blanket_po_Header_Id = p_po_Header_Id
13066                    AND prl.Blanket_po_Line_num = pol.Line_num))
13067              AND Trunc(Nvl(pol.Expiration_Date,SYSDATE + 1)) >= Trunc(SYSDATE))
13068              OR ((p_InterFace_Line_num IS NULL
13069                   AND (prl.Blanket_po_Header_Id <> p_po_Header_Id
13070                         OR prl.Blanket_po_Line_num IS NULL ))
13071                  AND Trunc(Nvl(pol.Expiration_Date,SYSDATE + 1)) >= Trunc(DECODE(pol.Expiration_Date,NULL,SYSDATE,
13072                                                                                                      Nvl(prl.Need_By_Date,SYSDATE)))))
13073            /*Bug4541335 End */
13074            -- Bug 2707576 Start
13075            -- Require the BPA and req to have the same UOM
13076            -- if x_allow_different_uoms is not 'Y'.
13077         AND   (   (  NVL(POL.unit_meas_lookup_code,chr(0)) =
13078                                          decode ( x_allow_different_uoms,'Y',
13079                                                   NVL(POL.unit_meas_lookup_code,chr(0)),
13080                                                   PRL.unit_meas_lookup_code)
13081                                       )                       -- <SERVICES FPJ>
13082                                   OR  (   ( POL.unit_meas_lookup_code IS NULL )
13083                                       AND ( PRL.unit_meas_lookup_code IS NULL ) )
13084                                   );
13085 
13086                             -- Bug 2707576 End
13087 
13088    /* Bug: 2432506 Expriation of document should happen at the end of
13089            the expiration_date */
13090    /* Bug 3828673:Release was not created when the requisition line type is
13091       different from the source document line type.*/
13092 
13093     CURSOR c2 (p_po_header_id        IN NUMBER,
13094                p_requisition_line_id IN NUMBER,
13095                p_interface_line_num  IN NUMBER,
13096                p_item_rev_control    IN NUMBER,
13097                x_allow_different_uoms IN VARCHAR2 -- Bug 2707576
13098               ) IS
13099                             SELECT MIN(pol.line_num)
13100                             FROM  po_lines_all pol,
13101                                   po_requisition_lines_all prl  --<Shared Proc FPJ>
13102                             WHERE pol.po_header_id = p_po_header_id
13103                             AND   prl.requisition_line_id = p_requisition_line_id
13104                             AND   NVL(pol.cancel_flag,'N') = 'N'
13105                             AND   NVL(pol.closed_code,'OPEN') <> 'FINALLY CLOSED'
13106                             -- Bug 3828673 START
13107                             -- AND   pol.line_type_id = prl.line_type_id
13108                             AND   pol.order_type_lookup_code = prl.order_type_lookup_code
13109                             AND   pol.purchase_basis = prl.purchase_basis
13110                             AND   pol.matching_basis = prl.matching_basis
13111                             -- Bug 3828673 END
13112                             AND   nvl(pol.job_id,-999) = nvl(prl.job_id, -999) -- <SERVICES FPJ>
13113                             AND   (   ( POL.item_id = PRL.item_id ) -- <SERVICES FPJ>
13114                                   OR  (   ( POL.item_id IS NULL )
13115                                       AND ( PRL.item_id IS NULL ) )
13116                                   )
13117                             AND   ((pol.item_revision IS NULL
13118                                    and prl.item_revision IS NULL)
13119                                    or  pol.item_revision = prl.item_revision
13120                                    or  (prl.item_revision is null  and p_item_rev_control = 1))
13121                             AND   (pol.transaction_reason_code IS NULL
13122                                    or pol.transaction_reason_code =
13123                                    NVL(prl.transaction_reason_code,
13124                                                 pol.transaction_reason_code))
13125                             /*Bug4541335  AND   nvl(p_interface_line_num,pol.line_num) =
13126                                                                      pol.line_num
13127                             AND   trunc(nvl(pol.expiration_date,sysdate+1))
13128                                                                 >= trunc(sysdate) */
13129            /*Bug4541335 start */
13130        AND (p_InterFace_Line_num = pol.Line_num
13131              OR (p_InterFace_Line_num IS NULL
13132                  AND prl.Blanket_po_Header_Id = p_po_Header_Id
13133                  AND prl.Blanket_po_Line_num = pol.Line_num)
13134              OR (p_InterFace_Line_num IS NULL
13135                  AND (prl.Blanket_po_Header_Id <> p_po_Header_Id
13136                        OR prl.Blanket_po_Line_num IS NULL )))
13137        AND (((p_InterFace_Line_num IS NOT NULL
13138                OR (prl.Blanket_po_Header_Id = p_po_Header_Id
13139                    AND prl.Blanket_po_Line_num = pol.Line_num))
13140              AND Trunc(Nvl(pol.Expiration_Date,SYSDATE + 1)) >= Trunc(SYSDATE))
13141              OR ((p_InterFace_Line_num IS NULL
13142                   AND (prl.Blanket_po_Header_Id <> p_po_Header_Id
13143                         OR prl.Blanket_po_Line_num IS NULL ))
13144                  AND Trunc(Nvl(pol.Expiration_Date,SYSDATE + 1)) >= Trunc(DECODE(pol.Expiration_Date,NULL,SYSDATE,
13145                                                                                                      Nvl(prl.Need_By_Date,SYSDATE)))))
13146            /*Bug4541335 End */
13147                             -- Bug 2707576 Start
13148                             -- Require the BPA and req to have the same UOM
13149                             -- if x_allow_different_uoms is not 'Y'.
13150                             AND   (   (  NVL(POL.unit_meas_lookup_code,chr(0)) =
13151                                          decode ( x_allow_different_uoms,'Y',
13152                                                   NVL(POL.unit_meas_lookup_code,chr(0)),
13153                                                   PRL.unit_meas_lookup_code)
13154                                       )                       -- <SERVICES FPJ>
13155                                   OR  (   ( POL.unit_meas_lookup_code IS NULL )
13156                                       AND ( PRL.unit_meas_lookup_code IS NULL ) )
13157                                   );
13158                             -- Bug 2707576 End
13159 
13160 BEGIN
13161 
13162      /* bug 2315931 : when creating a release , if the requisition does not
13163        have a revision and the item is not revision controlled then we can
13164        match it to the blanket with a revision. For this added the additional
13165        clause in the cursors for the item revision matching */
13166 
13167       begin
13168        SELECT   inventory_organization_id
13169        INTO     x_inv_org_id
13170          FROM   financials_system_params_all  --<Shared Proc FPJ>
13171         WHERE   NVL(org_id, -99) = NVL(p_purchasing_ou_id, -99);  --<Shared Proc FPJ>
13172 
13173        select item_id
13174        into x_item_id
13175        from po_requisition_lines_all  --<Shared Proc FPJ>
13176        where requisition_line_id = x_requisition_line_id;
13177 
13178      if x_item_id is not null then
13179        SELECT   msi.revision_qty_control_code
13180        INTO     x_item_rev_control
13181        FROM     mtl_system_items msi
13182        WHERE    msi.inventory_item_id = x_item_id
13183        AND      msi.organization_id = x_inv_org_id;
13184      end if;
13185 
13186       exception
13187        when no_data_found then
13188          null;
13189      end;
13190         -- Get the first BPO line having the same item_id AND description
13191         -- as that of requisition line.
13192         OPEN c1(x_po_header_id, x_requisition_line_id, x_interface_line_num,x_item_rev_control,
13193                 x_allow_different_uoms -- Bug 2707576
13194                );
13195 
13196         FETCH c1 INTO v_line_num;
13197 
13198         IF c1%NOTFOUND  OR v_line_num IS NULL THEN
13199                 -- Get the first BPO line having the same item_id as
13200                 -- that of requisition line, ignoring the description.
13201                 OPEN  c2(x_po_header_id,
13202                          x_requisition_line_id,
13203                          x_interface_line_num,
13204                          x_item_rev_control,
13205                          x_allow_different_uoms -- Bug 2707576
13206                         );
13207                 FETCH c2 INTO v_line_num;
13208                 CLOSE c2;
13209         END IF;
13210         CLOSE c1;
13211         RETURN v_line_num;
13212 
13213 EXCEPTION
13214         WHEN OTHERS THEN RETURN -1;
13215 
13216 END source_blanket_line;
13217 
13218 --<RENEG BLANKET FPI START>
13219 /*============================================================================
13220 Name      :     CREATE_PRICE_BREAK
13221 Type      :     Private
13222 Function  :     This procedure is called from 'create_line'. This procedure inserts
13223                 records from po_lines_interface table to po_line_locations_all table
13224                 for the price break information.
13225 Pre-req   :     None
13226 Parameters:
13227 IN        :     p_po_line_id            IN      NUMBER  REQUIRED
13228 OUT       :     x_line_location_id      OUT     NOCOPY
13229 ==============================================================================*/
13230 PROCEDURE CREATE_PRICE_BREAK(p_po_line_id IN number,
13231                              x_line_location_id OUT NOCOPY number,
13232                  p_outsourced_assembly IN NUMBER --<SHIKYU R12>
13233 ) IS
13234 
13235 l_row_id            varchar2(18) := NULL;
13236 l_progress          varchar2(3) := '000';            --< Bug 3210331 >
13237 l_api_name VARCHAR2(30) := 'create_price_break';      --< Bug 3210331, 3336920 >
13238 unexpected_create_pb_err   EXCEPTION;
13239 
13240 l_ship_org_id_line  mtl_system_items.organization_id%type;
13241 l_ship_org_code       varchar2(3);
13242 l_ship_org_name     varchar2(60);
13243 
13244 l_value_basis   PO_LINES_ALL.order_type_lookup_code%TYPE; -- <Complex Work R12>
13245 
13246 BEGIN
13247     -- Standard start of API savepoint
13248     SAVEPOINT       create_price_break_pvt;
13249 
13250     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13251         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
13252     END IF;
13253 
13254     begin
13255        SELECT po_line_locations_s.nextval
13256           INTO x_line_location_id
13257           FROM sys.dual;
13258     exception
13259         when others then
13260             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13261                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13262                                    p_progress => l_progress);
13263             END IF;
13264             po_message_s.sql_error('Exception of create_price_break()', l_progress,sqlcode);
13265             FND_MSG_PUB.Add;
13266             RAISE unexpected_create_pb_err;
13267     end;
13268 
13269     l_progress := '010';
13270     -- Check that price break ship_to_organization_id and ship_to_location_id match
13271     -- (if both are provided)
13272     if (interface.line_ship_to_org_id is not NULL and
13273         interface.line_ship_to_loc_id is not NULL and params.sob_id is not NULL) then
13274         po_locations_s.get_loc_org(interface.line_ship_to_loc_id,
13275                                    params.sob_id,
13276                                    l_ship_org_id_line,
13277                                    l_ship_org_code,
13278                                    l_ship_org_name);
13279         -- if the orgs do match raise an error
13280   if (l_ship_org_id_line <> interface.line_ship_to_org_id) then
13281             --Create an error code 4 for price break ship_to_loc and ship_to_org do not match
13282             g_sourcing_errorcode := 3;
13283            -- raise;
13284         end if;
13285     end if; /*check ship_loc and ship_org */
13286 
13287     l_progress := '020';
13288     --Call the row handler for po_line_location9in file POXP1PSB.pls to insert the row
13289 
13290     -- <Complex Work R12 Start>
13291     -- Get value basis from line
13292 
13293     SELECT pol.order_type_lookup_code
13294     INTO l_value_basis
13295     FROM po_lines_all pol
13296     WHERE pol.po_line_id = p_po_line_id;
13297 
13298     l_progress := '025';
13299 
13300     -- <Complex Work R12 End>
13301 
13302 
13303     begin
13304       po_line_locations_pkg_s0.insert_row(
13305                        l_row_id,
13306                        x_Line_Location_Id,
13307                        interface.last_update_date,
13308                        interface.last_updated_by,
13309                        interface.Po_Header_Id,
13310                        p_po_Line_Id,
13311                        interface.Last_Update_Login,
13312                        interface.creation_Date,
13313                        interface.created_By,
13314                        interface.quantity,
13315                        0, --quantity_received
13316                        0, --Quantity_Accepted
13317                        0, --Quantity_Rejected
13318                        0, --Quantity_Billed
13319                        0, --Quantity_Cancelled,
13320                        interface.unit_meas_lookup_code, --unit of measure
13321                        NULL, -- release_id
13322                        interface.line_Ship_To_Loc_Id,
13323                        interface.Ship_Via_Lookup_Code,
13324                        NULL, --Need_By_Date
13325                        NULL, --Promised_Date
13326                        NULL, --Last_Accept_Date
13327            interface.unit_price, --Price_override
13328                        'N', --Encumbered flag
13329                        NULL, --Encumbered_Date
13330                        NULL, --Fob_Lookup_Code
13331                        NULL, --Freight_Terms_Lookup_Code
13332                        'N', --Taxable_Flag
13333                        NULL, --Tax_Code_Id
13334                        'N', --Tax_User_Override_Flag
13335                        NULL, --Calculate_Tax_Flag
13336                        NULL, --X_From_Header_Id
13337                        NULL, --X_From_Line_Id
13338                        NULL, --X_From_Line_Location_Id
13339                        interface.line_effective_date, --X_Start_Date
13340                        interface.line_expiration_date, --X_End_Date
13341                        NULL, --X_Lead_Time,
13342                        NULL, --X_Lead_Time_Unit,
13343                        interface.Price_Discount,
13344                        interface.Terms_Id,
13345                        NULL, --X_Approved_Flag,
13346                        NULL, --X_Approved_Date,
13347                        'N', --X_Closed_Flag,
13348                        'N', --X_Cancel_Flag,
13349                        NULL, --X_Cancelled_By,
13350                        NULL, --X_Cancel_Date,
13351                        NULL, --X_Cancel_Reason,
13352                        'N', --X_Firm_Status_Lookup_Code,
13353                        NULL, --X_Attribute_Category,
13354                        NULL, --X_Attribute1,
13355                        NULL, --X_Attribute2,
13356                        NULL, --X_Attribute3,
13357                        NULL, --X_Attribute4,
13358                        NULL, --X_Attribute5,
13359                        NULL, --X_Attribute6,
13360                        NULL, --X_Attribute7,
13361                        NULL, --X_Attribute8,
13362                        NULL, --X_Attribute9,
13363                        NULL, --X_Attribute10,
13364                        NULL, --X_Attribute11,
13365                        NULL, --X_Attribute12,
13366                        NULL, --X_Attribute13,
13367                        NULL, --X_Attribute14,
13368                        NULL, --X_Attribute15,
13369                        'N', --X_Inspection_Required_Flag,
13370                        'N', --X_Receipt_Required_Flag,
13371                        NULL, --X_Qty_Rcv_Tolerance,
13372                        NULL, --X_Qty_Rcv_Exception_Code,
13373                        'NONE', --X_Enforce_Ship_To_Location,
13374                        NULL, --X_Allow_Substitute_Receipts,
13375                        NULL, --X_Days_Early_Receipt_Allowed,
13376                        NULL, --X_Days_Late_Receipt_Allowed,
13377                        NULL, --X_Receipt_Days_Exception_Code,
13378                        NULL, --X_Invoice_Close_Tolerance,
13379                        NULL, --X_Receive_Close_Tolerance,
13380                        interface.line_Ship_To_Org_Id,
13381                        interface.Shipment_Num,
13382                        NULL, --X_Source_Shipment_Id,
13383                        interface.Shipment_Type,
13384                        'OPEN', --X_Closed_Code,
13385                        NULL, --
13386                        NULL, --X_Government_Context,
13387                        NULL, --X_Receiving_Routing_Id,
13388                        NULL, --X_Accrue_On_Receipt_Flag,
13389                        NULL, --X_Closed_Reason,
13390                        NULL, --X_Closed_Date,
13391                        NULL, --X_Closed_By,
13392                        NULL, --X_Global_Attribute_Category,
13393                        NULL, --X_Global_Attribute1,
13394                        NULL, --X_Global_Attribute2,
13395                        NULL, --X_Global_Attribute3,
13396                        NULL, --X_Global_Attribute4,
13397                        NULL, --X_Global_Attribute5,
13398                        NULL, --X_Global_Attribute6,
13399                        NULL, --X_Global_Attribute7,
13400                        NULL, --X_Global_Attribute8,
13401                        NULL, --X_Global_Attribute9,
13402                        NULL, --X_Global_Attribute10,
13403                        NULL, --X_Global_Attribute11,
13404                        NULL, --X_Global_Attribute12,
13405                        NULL, --X_Global_Attribute13,
13406                        NULL, --X_Global_Attribute14,
13407                        NULL, --X_Global_Attribute15,
13408                        NULL, --X_Global_Attribute16,
13409                        NULL, --X_Global_Attribute17,
13410                        NULL, --X_Global_Attribute18,
13411                        NULL, --X_Global_Attribute19,
13412                        NULL, --X_Global_Attribute20,
13413                        NULL, --X_Country_of_Origin_Code,
13414                        'P', --invoice option
13415                        l_value_basis,   -- <Complex Work R12>
13416                        NULL,            -- <Complex Work R12>: matching basis
13417                        NULL, --X_note_to_receiver,
13418                        NULL, --X_Secondary_Unit_Of_Measure,
13419                        NULL, --X_Secondary_Quantity,
13420                        NULL, --X_Preferred_Grade,
13421                        NULL, --X_Secondary_Quantity_Received,
13422                        NULL, --X_Secondary_Quantity_Accepted,
13423                        NULL, --X_Secondary_Quantity_Rejected,
13424                        NULL, --X_Secondary_Quantity_Cancelled,
13425                        NULL,            --X_Consigned_Flag    -- <SERVICES FPJ>
13426                        interface.amount, --X_Amount            -- <SERVICES FPJ>
13427                        NULL, -- p_transaction_flow_header_id
13428                        NULL, -- p_manual_price_change_flag
13429            interface.org_id                      -- <R12 MOAC>
13430            ,p_outsourced_assembly --<SHIKYU R12>
13431                        );
13432 
13433         l_progress := '030';
13434         -- <SERVICES FPJ START> Insert Price Break Price Differentials into
13435         -- main table from the interface table.
13436         --
13437         PO_PRICE_DIFFERENTIALS_PVT.create_from_interface
13438         (   p_entity_id         => x_line_location_id
13439         ,   p_interface_line_id => interface.interface_line_id
13440         );
13441         -- <SERVICES FPJ END>
13442 
13443       exception
13444         when others then
13445             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13446                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13447                                    p_progress => l_progress);
13448             END IF;
13449             po_message_s.sql_error('Exception of create_price_break()', l_progress, sqlcode);
13450             FND_MSG_PUB.Add;
13451             RAISE unexpected_create_pb_err;
13452       end;
13453 
13454     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13455         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
13456     END IF;
13457 EXCEPTION
13458         when unexpected_create_pb_err then
13459             RAISE; --Bug 3336920
13460             --ROLLBACK to create_price_break_pvt;
13461         when others then
13462             IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13463                 PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13464                                    p_progress => l_progress);
13465             END IF;
13466             --ROLLBACK to create_price_break_pvt;
13467             RAISE; --Bug 3336920
13468 END CREATE_PRICE_BREAK;
13469 --<RENEG BLANKET FPI END>
13470 
13471 -- <Complex Work R12 Start>: Added logging; cleaned tabbing.
13472 FUNCTION get_ship_to_loc(p_deliver_to_loc_id IN NUMBER)
13473 RETURN NUMBER
13474 IS
13475 
13476   l_ship_to_location_id  NUMBER;
13477   l_found BOOLEAN := FALSE;
13478 
13479   d_module VARCHAR2(70) := 'po.plsql.PO_INTERFACE_S.get_ship_to_loc';
13480   d_progress NUMBER;
13481 
13482 BEGIN
13483 
13484   d_progress := 0;
13485 
13486   IF (PO_LOG.d_proc) THEN
13487     PO_LOG.proc_begin(d_module);
13488     PO_LOG.proc_begin(d_module, 'p_deliver_to_loc_id', p_deliver_to_loc_id);
13489   END IF;
13490 
13491   d_progress := 10;
13492 
13493   BEGIN
13494 
13495     SELECT NVL(hrl.ship_to_location_id, hrl.location_id)
13496     INTO l_ship_to_location_id
13497     FROM hr_locations hrl
13498     WHERE hrl.location_id = p_deliver_to_loc_id;
13499 
13500     l_found := TRUE;
13501 
13502   EXCEPTION
13503     WHEN NO_DATA_FOUND THEN
13504       IF (PO_LOG.d_stmt) THEN
13505         PO_LOG.stmt(d_module, d_progress, 'No data found in hr_locations.');
13506       END IF;
13507   END;
13508 
13509   d_progress := 20;
13510 
13511   IF (NOT l_found) THEN
13512 
13513     BEGIN
13514 
13515       SELECT hzl.location_id
13516       INTO l_ship_to_location_id
13517       FROM hz_locations hzl
13518       WHERE hzl.location_id = p_deliver_to_loc_id;
13519 
13520       l_found := TRUE;
13521 
13522     EXCEPTION
13523       WHEN NO_DATA_FOUND THEN
13524         IF (PO_LOG.d_stmt) THEN
13525           PO_LOG.stmt(d_module, d_progress, 'No data found in hz_locations.');
13526         END IF;
13527     END;
13528 
13529   END IF;  -- if not l_found
13530 
13531   IF (NOT l_found) THEN
13532     RAISE NO_DATA_FOUND;
13533   END IF;
13534 
13535   IF (PO_LOG.d_proc) THEN
13536     PO_LOG.proc_return(d_module, l_ship_to_location_id);
13537     PO_LOG.proc_end(d_module);
13538   END IF;
13539 
13540   RETURN l_ship_to_location_id;
13541 
13542 EXCEPTION
13543   WHEN OTHERS THEN
13544     IF (PO_LOG.d_exc) THEN
13545       PO_LOG.exc(d_module, d_progress, SQLCODE || SQLERRM);
13546     END IF;
13547     wrapup(interface.interface_header_id);
13548     RAISE;
13549 END;
13550 -- <Complex Work R12 End>
13551 
13552 --<CONFIG_ID FPJ START>
13553 
13554 ----------------------------------------------------------------------------
13555 --Start of Comments
13556 --Name: validate_interface_records
13557 --Pre-reqs:
13558 --  None
13559 --Modifies:
13560 --  None
13561 --Locks:
13562 --  None
13563 --Function:
13564 --  Performs various validations on the interface records.
13565 --Parameters:
13566 --IN:
13567 --p_interface_header_id
13568 --  header ID of the interface records to check
13569 --Returns:
13570 --  TRUE if the interface records pass all the validations;
13571 --  FALSE otherwise.
13572 --Testing:
13573 --  None
13574 --End of Comments
13575 ----------------------------------------------------------------------------
13576 
13577 FUNCTION validate_interface_records (
13578   p_interface_header_id IN PO_HEADERS_INTERFACE.interface_header_id%TYPE
13579 ) RETURN BOOLEAN IS
13580 
13581   l_api_name CONSTANT VARCHAR2(30) := 'validate_interface_records';
13582   l_pass_validations BOOLEAN;
13583 
13584 BEGIN
13585 
13586   l_pass_validations := validate_config_id(p_interface_header_id);
13587   RETURN l_pass_validations;
13588 
13589 END validate_interface_records;
13590 
13591 
13592 ----------------------------------------------------------------------------
13593 --Start of Comments
13594 --Name: validate_config_id
13595 --Pre-reqs:
13596 --  g_document_type and g_document_subtype should have been set.
13597 --Modifies:
13598 --  None
13599 --Locks:
13600 --  None
13601 --Function: Verifies that Config ID lines are only placed on the Standard PO
13602 --  document type.
13603 --Parameters:
13604 --IN:
13605 --p_interface_header_id
13606 --  header ID of the interface records to check
13607 --Returns:
13608 --  TRUE if the document type is Standard PO, or if none of the lines have
13609 --  Config ID; FALSE otherwise.
13610 --Testing:
13611 --  None
13612 --End of Comments
13613 ----------------------------------------------------------------------------
13614 
13615 FUNCTION validate_config_id (
13616   p_interface_header_id IN PO_HEADERS_INTERFACE.interface_header_id%TYPE
13617 ) RETURN BOOLEAN IS
13618 
13619   l_api_name CONSTANT VARCHAR2(30) := 'validate_config_id';
13620   l_num_config_id_lines NUMBER;
13621   l_progress VARCHAR2(3) := '000';              --< Bug 3210331 >
13622 
13623 BEGIN
13624 
13625   IF (g_document_type = 'PO' AND g_document_subtype = 'STANDARD') THEN
13626     RETURN TRUE; -- The lines are being placed on a Standard PO.
13627   END IF;
13628 
13629   SELECT count(*)
13630   INTO l_num_config_id_lines
13631   FROM po_lines_interface PLI, po_requisition_lines PRL
13632   WHERE PLI.interface_header_id = p_interface_header_id
13633   AND PLI.requisition_line_id = PRL.requisition_line_id -- JOIN
13634   AND PRL.supplier_ref_number IS NOT NULL;
13635 
13636   IF (l_num_config_id_lines = 0) THEN
13637     RETURN TRUE; -- None of the lines have Config ID.
13638   ELSE
13639     l_progress := '010';
13640     -- We do not allow req lines with Config ID to be placed on any document type
13641     -- other than Standard PO.
13642     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13643         PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13644                             p_token    => l_progress,
13645                             p_message  => FND_MESSAGE.get_string('PO','PO_CONFIG_ID_ONLY_ON_STD_PO'));
13646     END IF;
13647     RETURN FALSE;
13648   END IF;
13649 
13650 EXCEPTION
13651 
13652   WHEN OTHERS THEN
13653     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13654         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13655                            p_progress => l_progress);
13656     END IF;
13657     wrapup(p_interface_header_id);
13658     RAISE;
13659 
13660 END validate_config_id;
13661 
13662 --<CONFIG_ID FPJ END>
13663 
13664 
13665 --<GRANTS FPJ START>
13666 ----------------------------------------------------------------------------
13667 --Start of Comments
13668 --Name: update_award_distributions
13669 --Pre-reqs:
13670 --  None
13671 --Modifies:
13672 --  PO_DISTRIBUTIONS_INTERFACE
13673 --  GMS_AWARD_DISTRIBUTIONS
13674 --Locks:
13675 --  None
13676 --Function:
13677 --  Calls Grants Accounting API to create new award distributions lines
13678 --  when a requisition with distributions that reference awards is
13679 --  autocreated into a PO.
13680 --Parameters:
13681 --  <Complex Work R12>: Add p_table_type and p_po_line_id
13682 --  p_table_type
13683 --    'INTERFACE' - query/update interface tables (default)
13684 --    'ALL - query/update _ALL tables
13685 --  p_po_line_id
13686 --    Only necessary if p_table_type = 'ALL', this is the line for
13687 --    which to update the award distributions for.
13688 --Returns:
13689 --  None
13690 --Testing:
13691 --  None
13692 --End of Comments
13693 ----------------------------------------------------------------------------
13694 
13695 PROCEDURE update_award_distributions(
13696   p_table_type   IN   VARCHAR2   DEFAULT 'INTERFACE'
13697 , p_po_line_id   IN   NUMBER     DEFAULT NULL
13698 )
13699 IS
13700 
13701   l_api_name     CONSTANT VARCHAR(30) := 'update_award_distributions';
13702   l_return_status        VARCHAR2(1);
13703   l_progress           VARCHAR2(4) := '000';              --< Bug 3210331 >
13704   l_gms_po_interface_obj gms_po_interface_type;
13705   l_msg_count          NUMBER;
13706   l_msg_data           VARCHAR2(2000);
13707   l_msg_buf              VARCHAR2(2000);
13708 
13709 BEGIN
13710     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13711         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
13712     END IF;
13713 
13714     -- <Complex Work R12 Start>
13715     IF (p_table_type = 'ALL') THEN
13716 
13717       --SQL WHAT: For distributions with award_id references, select
13718       --          the columns that Grants needs from the
13719       --          po_distributions_all table
13720       --SQL WHY : Needed to call GMS API to update award distribution
13721       --          lines table.
13722 
13723       SELECT pod.po_distribution_id,
13724              pod.distribution_num,
13725              pod.project_id,
13726              pod.task_id,
13727              pod.award_id,
13728              NULL
13729       BULK COLLECT INTO
13730              l_gms_po_interface_obj.distribution_id,
13731              l_gms_po_interface_obj.distribution_num,
13732              l_gms_po_interface_obj.project_id,
13733              l_gms_po_interface_obj.task_id,
13734              l_gms_po_interface_obj.award_set_id_in,
13735              l_gms_po_interface_obj.award_set_id_out
13736       FROM po_distributions_all pod
13737       WHERE pod.po_line_id = p_po_line_id
13738         AND pod.award_id IS NOT NULL;
13739 
13740     ELSE
13741 
13742       --SQL WHAT: For distributions with award_id references, select
13743       --          the columns that Grants needs from the
13744       --          po_distributions_interface table
13745       --SQL WHY : Need to call GMS API to update award distribution
13746       --          lines table.
13747 
13748       SELECT po_distribution_id,
13749              distribution_num,
13750              project_id,
13751              task_id,
13752              award_id,
13753              NULL
13754       BULK COLLECT INTO
13755              l_gms_po_interface_obj.distribution_id,
13756              l_gms_po_interface_obj.distribution_num,
13757              l_gms_po_interface_obj.project_id,
13758              l_gms_po_interface_obj.task_id,
13759              l_gms_po_interface_obj.award_set_id_in,
13760              l_gms_po_interface_obj.award_set_id_out
13761       FROM PO_DISTRIBUTIONS_INTERFACE
13762       WHERE interface_header_id = interface.interface_header_id
13763             AND interface_line_id = interface.interface_line_id
13764             AND award_id IS NOT NULL;
13765 
13766     END IF;  -- if p_table_type = 'ALL'
13767     -- <Complex Work R12 End>
13768 
13769     IF SQL%NOTFOUND THEN
13770       RETURN;
13771     END IF;
13772 
13773 
13774     l_progress := '010';
13775 
13776     --Create new award distribution lines in GMS_AWARDS_DISTRIBUTIONS table
13777     PO_GMS_INTEGRATION_PVT.maintain_adl (
13778           p_api_version           => 1.0,
13779           x_return_status         => l_return_status,
13780           x_msg_count             => l_msg_count,
13781           x_msg_data              => l_msg_data,
13782           p_caller                => 'AUTOCREATE',
13783           x_po_gms_interface_obj  => l_gms_po_interface_obj);
13784 
13785     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
13786       RAISE FND_API.G_EXC_ERROR;
13787     END IF;
13788 
13789     l_progress := '020';
13790 
13791     -- <Complex Work R12 Start>
13792     IF (p_table_type = 'ALL') THEN
13793 
13794       --SQL WHAT: Update po_distributions_all table with the new
13795       --          award_id's
13796       --SQL WHY : award_id's in PO tables need to be synchronized with
13797       --          award_id's in GMS tables.
13798 
13799       FORALL i IN 1..l_gms_po_interface_obj.distribution_id.COUNT
13800           UPDATE po_distributions_all
13801           SET award_id =
13802                 l_gms_po_interface_obj.award_set_id_out(i)
13803           WHERE po_distribution_id =
13804                 l_gms_po_interface_obj.distribution_id(i);
13805 
13806     ELSE
13807 
13808       --SQL WHAT: Update po_distributions_interface table with the new
13809       --          award_id's
13810       --SQL WHY : award_id's in PO tables need to be synchronized with
13811       --          award_id's in GMS tables.
13812 
13813       FORALL i IN 1..l_gms_po_interface_obj.distribution_id.COUNT
13814           UPDATE po_distributions_interface
13815           SET award_id = l_gms_po_interface_obj.award_set_id_out(i)
13816           WHERE po_distribution_id = l_gms_po_interface_obj.distribution_id(i);
13817 
13818     END IF; -- if p_table_type = 'ALL'
13819     -- <Complex Work R12 End>
13820 
13821     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13822         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
13823     END IF;
13824 EXCEPTION
13825 
13826   WHEN FND_API.G_EXC_ERROR THEN
13827     IF FND_MSG_PUB.check_msg_level(
13828          p_message_level => FND_MSG_PUB.g_msg_lvl_unexp_error) THEN
13829       FND_MSG_PUB.add_exc_msg( p_pkg_name => G_PKG_NAME,
13830                                p_procedure_name => l_api_name);
13831     END IF;
13832 
13833     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13834 
13835        FOR i IN 1..FND_MSG_PUB.count_msg LOOP
13836           l_msg_buf := SUBSTRB(FND_MSG_PUB.get(p_msg_index => i,
13837                                                p_encoded   => FND_API.G_FALSE),
13838                                1, 2000);
13839           PO_DEBUG.debug_stmt(p_log_head => g_log_head||l_api_name,
13840                               p_token    => l_progress,
13841                               p_message  => 'EXCEPTION: '|| l_msg_buf);
13842        END LOOP;
13843 
13844     END IF;
13845     RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
13846 
13847   WHEN OTHERS THEN
13848     IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13849         PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13850                            p_progress => l_progress);
13851     END IF;
13852     IF FND_MSG_PUB.check_msg_level(
13853          p_message_level => FND_MSG_PUB.g_msg_lvl_unexp_error) THEN
13854       FND_MSG_PUB.add_exc_msg( p_pkg_name => G_PKG_NAME,
13855                                p_procedure_name => l_api_name);
13856     END IF;
13857 
13858     RAISE;
13859 
13860 END update_award_distributions;
13861 
13862 --<GRANTS FPJ END>
13863 
13864 --<Shared Proc FPJ START>
13865 -------------------------------------------------------------------------------
13866 --Start of Comments
13867 --Name: GET_RATE_FOR_REQ_PRICE
13868 --Pre-reqs:
13869 --   None
13870 --Modifies:
13871 --  None
13872 --Locks:
13873 --  None.
13874 --Function:
13875 --  Get the conversion rate between PO Currency and Req Functional Currency for
13876 --  Default Rate type of Purchasing Org
13877 --Parameters:
13878 --  IN:
13879 --  p_requesting_ou_id: Requesting Operating Unit <ACHTML R12>
13880 --  p_purchasing_ou_id: Purchasing Operating Unit <ACHTML R12>
13881 --  p_po_currency_code: The currency in which PO will be cut
13882 --  p_rate_type: The default rate type of Purchasing Operating Unit
13883 --  p_rate_date: The date used to derive rate between PO and POU functional currency
13884 --  OUT:
13885 --  x_rate: The rate between PO currency and Requisition raising Operating Unit's functional currency
13886 --          Returns NULL if POU and ROU are in same Set Of Books (implying same functional currency)
13887 --Notes:
13888 --  None
13889 --Testing:
13890 --  None
13891 --End of Comments
13892 -------------------------------------------------------------------------------
13893 PROCEDURE get_rate_for_req_price(
13894   p_requesting_ou_id IN NUMBER, -- <ACHTML R12>
13895   p_purchasing_ou_id IN NUMBER, -- <ACHTML R12>
13896   p_po_currency_code IN VARCHAR2,
13897   p_rate_type        IN VARCHAR2,
13898   p_rate_date        IN DATE,
13899   x_rate             OUT NOCOPY NUMBER
13900 )
13901 IS
13902 
13903 l_req_ou_sob_id              GL_SETS_OF_BOOKS.set_of_books_id%TYPE;
13904 l_po_ou_sob_id               GL_SETS_OF_BOOKS.set_of_books_id%TYPE;
13905 l_inverse_rate_display_flag  VARCHAR2(1) := 'N';
13906 l_display_rate               NUMBER;
13907 l_progress                   VARCHAR2(3) := '000';
13908 l_rate_type                  PO_HEADERS_INTERFACE.rate_type%TYPE;
13909 l_api_name CONSTANT VARCHAR2(30) := 'get_rate_for_req_price';  --< Bug 3210331 >
13910 
13911 BEGIN
13912     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13913         PO_DEBUG.debug_begin(p_log_head => g_log_head||l_api_name);
13914     END IF;
13915 
13916    select req_fsp.set_of_books_id
13917    into l_req_ou_sob_id
13918    from financials_system_params_all req_fsp
13919    where req_fsp.org_id = p_requesting_ou_id; -- <ACHTML R12>
13920 
13921    l_progress := '010';
13922    select po_fsp.set_of_books_id
13923    into l_po_ou_sob_id
13924    from financials_system_params_all po_fsp
13925    where po_fsp.org_id = p_purchasing_ou_id; -- <ACHTML R12>
13926 
13927    IF l_req_ou_sob_id = l_po_ou_sob_id THEN
13928       x_rate := NULL;
13929       return;
13930    END IF;
13931 
13932    IF p_rate_type is NULL THEN
13933       l_progress := '020';
13934       select default_rate_type
13935       into  l_rate_type
13936       from  po_system_parameters_all psp
13937       where psp.org_id = p_purchasing_ou_id; -- <ACHTML R12>
13938    ELSE
13939      l_rate_type := p_rate_type;
13940    END IF;
13941 
13942    l_progress := '030';
13943 
13944    po_currency_sv.get_rate(l_req_ou_sob_id,
13945                               p_po_currency_code,
13946                               l_rate_type,
13947                               p_rate_date,
13948                               l_inverse_rate_display_flag,
13949                               x_rate,
13950                               l_display_rate);
13951 
13952     IF g_debug_stmt THEN    --< Bug 3210331: use proper debugging >
13953         PO_DEBUG.debug_end(p_log_head => g_log_head||l_api_name);
13954     END IF;
13955 EXCEPTION
13956   WHEN OTHERS THEN
13957       IF g_debug_unexp THEN    --< Bug 3210331: use proper debugging >
13958           PO_DEBUG.debug_exc(p_log_head => g_log_head||l_api_name,
13959                              p_progress => l_progress);
13960       END IF;
13961       po_message_s.sql_error('GET_RATE_FOR_REQ_PRICE',l_progress,sqlcode);
13962 END get_rate_for_req_price;
13963 --<Shared Proc FPJ END>
13964 
13965 
13966 -- <Complex Work R12 Start>
13967 -------------------------------------------------------------------------------
13968 --Start of Comments
13969 --Name: create_payitems
13970 --Pre-reqs:
13971 --   PO Line has been created.
13972 --Modifies:
13973 --  PO_LINE_LOCATIONS_ALL
13974 --Locks:
13975 --  None.
13976 --Function:
13977 --  Create all payitems for a PO Line.  If PO_LINE_LOCATIONS_INTERFACE is
13978 --  populated, use that information.  Otherwise, create a default
13979 --  payitem.  Also create DELIVERY and ADVANCE payitems as necessary.
13980 --Parameters:
13981 --  IN:
13982 --    p_interface_line_id:  id of the line in po_lines_interface
13983 --    p_po_line_id: id of the line in po_lines_all
13984 --    p_precision: precision of the currency desired.  Used to round amounts.
13985 --    p_ext_precision: extended precision of the currency desired.
13986 --                     Used to round prices
13987 --  OUT:
13988 --    x_line_location_id: id of the first actuals (STANDARD) payitem
13989 --                        in po_line_locations_all
13990 --    x_line_loc_id_tbl: ids of all payitems created in po_line_locations_all
13991 --Notes:
13992 --  None
13993 --Testing:
13994 --  None
13995 --End of Comments
13996 -------------------------------------------------------------------------------
13997 PROCEDURE create_payitems(
13998   p_interface_line_id IN         NUMBER
13999 , p_po_line_id        IN         NUMBER
14000 , p_precision         IN         NUMBER
14001 , p_ext_precision     IN         NUMBER
14002 , x_line_location_id  OUT NOCOPY NUMBER
14003 , x_line_loc_id_tbl   OUT NOCOPY po_tbl_number
14004 )
14005 IS
14006 
14007 d_progress  NUMBER;
14008 d_module    VARCHAR2(70) := 'po.plsql.PO_INTERFACE_S.create_payitems';
14009 
14010 l_po_header_id         PO_LINES_ALL.po_header_id%TYPE;
14011 l_line_value_basis     PO_LINES_ALL.order_type_lookup_code%TYPE;
14012 l_line_matching_basis  PO_LINES_ALL.matching_basis%TYPE;
14013 l_line_unit_price      PO_LINES_ALL.unit_price%TYPE;
14014 l_line_quantity        PO_LINES_ALL.quantity%TYPE;
14015 l_line_amount          PO_LINES_ALL.amount%TYPE;
14016 l_line_purchase_basis  PO_LINES_ALL.purchase_basis%TYPE;
14017 
14018 l_payment_type       PO_LINE_LOCATIONS_ALL.payment_type%TYPE;
14019 l_shipment_type      PO_LINE_LOCATIONS_ALL.shipment_type%TYPE;
14020 l_payitem_quantity   PO_LINE_LOCATIONS_ALL.quantity%TYPE;
14021 l_payitem_amount     PO_LINE_LOCATIONS_ALL.amount%TYPE;
14022 l_payitem_price      PO_LINE_LOCATIONS_ALL.price_override%TYPE;
14023 
14024 l_req_tax_code_id    PO_REQUISITION_LINES_ALL.tax_code_id%TYPE;
14025 l_req_tax_user_override_flag    PO_REQUISITION_LINES_ALL.tax_user_override_flag%TYPE;
14026 l_req_tax_status_indicator PO_REQUISITION_LINES_ALL.tax_status_indicator%TYPE;
14027 
14028 l_tax_name                      AP_TAX_CODES.name%TYPE;
14029 l_tax_code_id                   AP_TAX_CODES.tax_id%TYPE;
14030 l_tax_type                      AP_TAX_CODES.tax_type%TYPE;
14031 l_tax_description               AP_TAX_CODES.description%TYPE;
14032 l_allow_tax_code_override_flag  GL_TAX_OPTION_ACCOUNTS.allow_tax_code_override_flag%TYPE;
14033 
14034 l_isFinancing          BOOLEAN;
14035 l_ship_to_location_id  NUMBER;
14036 
14037 l_payitem_tax_code_id_tbl   po_tbl_number;
14038 l_payitems_created          NUMBER;
14039 
14040 l_routing_name   RCV_ROUTING_HEADERS.routing_name%TYPE;
14041 l_line_loc_id    PO_LINE_LOCATIONS_ALL.line_location_id%TYPE;
14042 
14043 l_po_promised_def_prf   VARCHAR2(1) := FND_PROFILE.value('PO_NEED_BY_PROMISE_DEFAULTING');
14044 l_country_of_origin_code VARCHAR2(2);
14045 l_tax_status             VARCHAR2(10);
14046 l_encoded_msg            VARCHAR2(2000);
14047 
14048 l_advance_desc           VARCHAR2(240);
14049 --<eTax integration R12 Start >
14050 l_return_status             VARCHAR2(1);
14051 l_msg_count                 NUMBER;
14052 l_msg_data                  VARCHAR2(2000);
14053 --<eTax integration R12 End>
14054 
14055 CURSOR poll_interface_cursor(p_interface_line_id NUMBER)
14056 IS
14057   SELECT polli.interface_line_location_id,
14058          polli.quantity,
14059          polli.amount,
14060          polli.ship_to_location_id,
14061          polli.need_by_date,
14062          polli.promised_date,
14063          polli.price_override,
14064          polli.shipment_type,
14065          polli.shipment_num,
14066          polli.ship_to_organization_id,
14067          polli.value_basis,
14068          polli.matching_basis,
14069          polli.payment_type,
14070          polli.description,
14071          polli.work_approver_id,
14072          polli.bid_payment_id,
14073          polli.unit_of_measure
14074   FROM po_line_locations_interface polli
14075   WHERE polli.interface_line_id = p_interface_line_id
14076   ORDER BY polli.shipment_num;
14077 
14078 line_location_rec     poll_interface_cursor%ROWTYPE;
14079 payitem_rcv_ctl_rec   rcv_controls_type;
14080 
14081 BEGIN
14082 
14083   d_progress := 0;
14084   IF (PO_LOG.d_proc) THEN
14085     PO_LOG.proc_begin(d_module);
14086     PO_LOG.proc_begin(d_module, 'p_interface_line_id', p_interface_line_id);
14087     PO_LOG.proc_begin(d_module, 'p_po_line_id', p_po_line_id);
14088   END IF;
14089 
14090   d_progress := 10;
14091 
14092   SELECT pol.order_type_lookup_code
14093        , pol.matching_basis
14094        , pol.po_header_id
14095        , pol.unit_price
14096        , pol.quantity
14097        , pol.amount
14098        , pol.purchase_basis
14099   INTO l_line_value_basis
14100      , l_line_matching_basis
14101      , l_po_header_id
14102      , l_line_unit_price
14103      , l_line_quantity
14104      , l_line_amount
14105      , l_line_purchase_basis
14106   FROM po_lines_all pol
14107   WHERE pol.po_line_id = p_po_line_id;
14108 
14109   d_progress := 20;
14110 
14111   l_isFinancing := PO_COMPLEX_WORK_PVT.is_financing_po(
14112                      p_po_header_id => l_po_header_id
14113                    );
14114 
14115   IF (PO_LOG.d_stmt) THEN
14116     PO_LOG.stmt(d_module, d_progress, 'l_isFinancing', l_isFinancing);
14117   END IF;
14118 
14119   d_progress := 30;
14120 
14121   IF (interface.poll_interface_pop_flag = 'N') THEN
14122 
14123     d_progress := 40;
14124 
14125     -- If line locations interface is not populated, then we are either
14126     -- autocreating from requisition or there are no payitems negotiated
14127     -- in sourcing for this line.  We need to populate data for the default
14128     -- payitem in the interface tables.
14129 
14130     PO_COMPLEX_WORK_PVT.get_default_payitem_info(
14131       p_po_header_id          => l_po_header_id
14132     , p_po_line_id            => p_po_line_id
14133     , p_line_value_basis      => l_line_value_basis
14134     , p_line_matching_basis   => l_line_matching_basis
14135     , p_line_qty      => ROUND(l_line_quantity, 15)
14136     , p_line_amt      => l_line_amount
14137     , p_line_price    => l_line_unit_price
14138     , x_payment_type  => l_payment_type
14139     , x_payitem_qty   => l_payitem_quantity
14140     , x_payitem_amt   => l_payitem_amount
14141     , x_payitem_price => l_payitem_price
14142     );
14143 
14144     d_progress := 50;
14145 
14146     --SQL WHAT: Insert information for default payitem into
14147     -- po_line_locations interface table
14148     --SQL WHY : We will use line_locations_interface as a
14149     -- common entry point for payitems - whether they come from
14150     -- sourcing or we default them from scratch here.
14151 
14152     INSERT INTO po_line_locations_interface
14153     (
14154       interface_line_location_id
14155     , interface_header_id
14156     , interface_line_id
14157     , quantity
14158     , amount
14159     , price_override
14160     , shipment_type
14161     , payment_type
14162     , shipment_num
14163     , need_by_date
14164     )
14165     VALUES
14166     (
14167       PO_LINE_LOCATIONS_INTERFACE_S.NEXTVAL
14168     , interface.interface_header_id
14169     , p_interface_line_id
14170     , l_payitem_quantity
14171     , l_payitem_amount
14172     , l_payitem_price
14173     , NULL
14174     , l_payment_type
14175     , 1
14176     , interface.need_by_date
14177     );
14178 
14179   END IF;  -- interface.poll_interface_pop_flag = 'N'
14180 
14181   d_progress := 60;
14182 
14183   IF (l_isFinancing) THEN
14184 
14185     d_progress := 70;
14186 
14187     -- if financing case, create actual delivery payitem
14188     -- this payitem has a shipment_type of STANDARD and payment_type of DELIVERY
14189 
14190     --SQL WHAT: Insert information for delivery payitem into
14191     -- po_line_locations_interface table
14192     --SQL WHY : We will use line_locations_interface as a
14193     -- common entry point for payitems, including ones we create
14194     -- behind the scenes
14195 
14196     INSERT INTO po_line_locations_interface
14197     (
14198       interface_line_location_id
14199     , interface_header_id
14200     , interface_line_id
14201     , quantity
14202     , amount
14203     , price_override
14204     , payment_type
14205     , shipment_type
14206     , description
14207     , shipment_num
14208     , need_by_date
14209     , promised_date
14210     )
14211     VALUES
14212     (
14213       PO_LINE_LOCATIONS_INTERFACE_S.NEXTVAL
14214     , interface.interface_header_id
14215     , p_interface_line_id
14216     , l_line_quantity
14217     , l_line_amount
14218     , l_line_unit_price
14219     , 'DELIVERY'
14220     , 'STANDARD'
14221     , interface.item_description
14222     , 1
14223     , interface.need_by_date
14224     , interface.promised_date            --Bug5532424
14225     );
14226 
14227   END IF;  -- if l_isFinancing
14228 
14229   d_progress := 80;
14230 
14231   IF (PO_LOG.d_stmt) THEN
14232     PO_LOG.stmt(d_module, d_progress, 'interface.has_advance_flag', interface.has_advance_flag);
14233   END IF;
14234 
14235   IF (interface.has_advance_flag = 'Y') THEN
14236 
14237     d_progress := 90;
14238 
14239     -- if line has advance, create financing payitem to represent it.
14240     -- the payitem has shipment_type of PREPAYMENT and payment_type of ADVANCE
14241 
14242     -- get default advance description
14243     FND_MESSAGE.set_name('PO', 'PO_CWPUI_ADVANCE_DESC_PREFIX');
14244     FND_MESSAGE.set_token(token => 'LINE_DESC',
14245                           value => interface.item_description);
14246     l_advance_desc := substrb(FND_MESSAGE.get, 1, 240);
14247 
14248     --SQL WHAT: Insert information for advance payitem into
14249     -- po_line_locations_interface table
14250     --SQL WHY : We will use line_locations_interface as a
14251     -- common entry point for payitems, including ones we create
14252     -- behind the scenes
14253 
14254     INSERT INTO po_line_locations_interface
14255     (
14256       interface_line_location_id
14257     , interface_header_id
14258     , interface_line_id
14259     , quantity
14260     , amount
14261     , price_override
14262     , payment_type
14263     , shipment_type
14264     , description
14265     , shipment_num
14266     , need_by_date
14267     )
14268     VALUES
14269     (
14270       PO_LINE_LOCATIONS_INTERFACE_S.NEXTVAL
14271     , interface.interface_header_id
14272     , p_interface_line_id
14273     , NULL
14274     , interface.advance_amount
14275     , NULL
14276     , 'ADVANCE'
14277     , 'PREPAYMENT'
14278     , l_advance_desc
14279     , 0
14280     , NULL
14281     );
14282 
14283   END IF;  -- if interface.has_advance_flag = 'Y'
14284 
14285   d_progress := 100;
14286 
14287   -- at this point, line_locations_interface has been populated with
14288   -- all necessary payitems - whether they come from sourcing or were
14289   -- created above from line information.
14290 
14291   -- we now update all rows in the line interface, filling in
14292   -- columns as necessary.  Some columns may have already been filled in;
14293   -- for those columns, we do a NULL check first (using NVL).
14294 
14295   l_ship_to_location_id := get_ship_to_loc(interface.deliver_to_location_id);
14296 
14297   IF (l_isFinancing) THEN
14298     l_shipment_type := 'PREPAYMENT';
14299   ELSE
14300     l_shipment_type := 'STANDARD';
14301   END IF;
14302 
14303   d_progress := 110;
14304 
14305   --SQL WHAT: Default/update values for scratch payitems in interface table
14306   --SQL WHY : This allows us to update all new payitems' values at once,
14307   -- including payitems from sourcing or ones we've created in autocreate
14308 
14309   UPDATE po_line_locations_interface polli
14310   SET polli.value_basis =
14311           DECODE(polli.payment_type,
14312                    'RATE', 'QUANTITY',
14313                    'LUMPSUM', 'FIXED PRICE',
14314                    'MILESTONE', l_line_value_basis,
14315                    'ADVANCE', 'FIXED PRICE',
14316                    'DELIVERY', l_line_value_basis,
14317                     polli.value_basis),
14318       polli.matching_basis =
14319           DECODE(polli.payment_type,
14320                    'RATE', 'QUANTITY',
14321                    'LUMPSUM', 'AMOUNT',
14322                    'MILESTONE', l_line_matching_basis,
14323                    'ADVANCE', 'AMOUNT',
14324                    'DELIVERY', l_line_matching_basis,
14325                     polli.matching_basis),
14326       polli.ship_to_location_id =
14327                     NVL(polli.ship_to_location_id, l_ship_to_location_id),
14328       polli.ship_to_organization_id =
14329                     NVL(polli.ship_to_organization_id,
14330                                    interface.destination_organization_id),
14331       polli.promised_date =
14332           NVL(polli.promised_date,
14333             DECODE(NVL(l_po_promised_def_prf, 'N'), 'Y', polli.need_by_date,
14334                                                          polli.promised_date)),
14335       polli.shipment_type = NVL(polli.shipment_type, l_shipment_type),
14336       polli.description = NVL(polli.description, interface.item_description),
14337       polli.unit_of_measure = NVL(polli.unit_of_measure, interface.unit_meas_lookup_code)
14338     WHERE polli.interface_line_id = p_interface_line_id;
14339 
14340   d_progress := 120;
14341 
14342   IF (interface.requisition_line_id IS NOT NULL) THEN
14343 
14344     d_progress := 130;
14345 
14346     SELECT prl.tax_code_id
14347         ,  nvl(prl.tax_user_override_flag,'N')
14348         ,  nvl(prl.tax_status_indicator,'SYSTEM')
14349         ,  nvl(prl.org_id, g_hdr_requesting_ou_id)
14350     INTO l_req_tax_code_id
14351       ,  l_req_tax_user_override_flag
14352       ,  l_req_tax_status_indicator
14353       ,  g_line_requesting_ou_id
14354     FROM po_requisition_lines_all prl
14355     WHERE prl.requisition_line_id = interface.requisition_line_id;
14356 
14357     l_tax_code_id := l_req_tax_code_id;
14358 
14359   ELSE
14360 
14361     d_progress := 140;
14362     l_req_tax_status_indicator := 'SYSTEM';
14363     g_line_requesting_ou_id := g_hdr_requesting_ou_id;
14364 
14365   END IF;  -- if interface.requisition_line_id IS NOT NULL
14366 
14367   d_progress := 150;
14368   x_line_loc_id_tbl := po_tbl_number();
14369   l_payitem_tax_code_id_tbl := po_tbl_number();
14370   l_payitems_created := 0;
14371 
14372   -- now iterate over the rows in the interface table
14373   -- for each row, get the default tax, receiving controls, and country of
14374   -- origin before inserting a new row into po_line_locations_all
14375 
14376   OPEN poll_interface_cursor(p_interface_line_id);
14377   LOOP
14378 
14379     FETCH poll_interface_cursor INTO line_location_rec;
14380     EXIT WHEN poll_interface_cursor%NOTFOUND;
14381 
14382     d_progress := 160;
14383 
14384     IF (PO_LOG.d_stmt) THEN
14385       PO_LOG.stmt(d_module, d_progress, 'Getting receiving controls.');
14386     END IF;
14387 
14388     RCV_CORE_S.get_receiving_controls(
14389       p_order_type_lookup_code => line_location_rec.value_basis
14390     , p_purchase_basis         => l_line_purchase_basis
14391     , p_line_location_id       => NULL
14392     , p_item_id                => interface.item_id
14393     , p_org_id                 => line_location_rec.ship_to_organization_id
14394     , p_vendor_id              => interface.vendor_id
14395     , p_drop_ship_flag         => interface.drop_ship_flag
14396     , p_payment_type           => line_location_rec.payment_type
14397     , x_enforce_ship_to_loc_code => payitem_rcv_ctl_rec.enforce_ship_to_location_code
14398     , x_allow_substitute_receipts => payitem_rcv_ctl_rec.allow_substitute_receipts_flag
14399     , x_routing_id => payitem_rcv_ctl_rec.receiving_routing_id
14400     , x_routing_name => l_routing_name
14401     , x_qty_rcv_tolerance => payitem_rcv_ctl_rec.qty_rcv_tolerance
14402     , x_qty_rcv_exception_code => payitem_rcv_ctl_rec.qty_rcv_exception_code
14403     , x_days_early_receipt_allowed => payitem_rcv_ctl_rec.days_early_receipt_allowed
14404     , x_days_late_receipt_allowed => payitem_rcv_ctl_rec.days_late_receipt_allowed
14405     , x_receipt_days_exception_code => payitem_rcv_ctl_rec.receipt_days_exception_code
14406     );
14407 
14408     d_progress := 200;
14409     IF (PO_LOG.d_stmt) THEN
14410       PO_LOG.stmt(d_module, d_progress, 'Getting default country of origin');
14411     END IF;
14412 
14413     po_coo_s.get_default_country_of_origin(
14414       x_item_id           => interface.item_id
14415     , x_ship_to_org_id    => line_location_rec.ship_to_organization_id
14416     , x_vendor_id         => interface.vendor_id
14417     , x_vendor_site_id    => interface.vendor_site_id
14418     , x_country_of_origin => l_country_of_origin_code
14419     );
14420 
14421     d_progress := 210;
14422     IF (PO_LOG.d_stmt) THEN
14423       PO_LOG.stmt(d_module, d_progress, 'Inserting payitem into po_line_locations_all');
14424     END IF;
14425 
14426     -- insert payitem into po_line_locations_all
14427 
14428     --SQL WHAT: Insert payitem, using info in po_line_locations_interface
14429     --SQL WHY : This allows us to insert all payitems in one location.
14430 
14431     INSERT INTO po_line_locations_all
14432     (
14433       line_location_id
14434     , last_update_date
14435     , last_updated_by
14436     , po_header_id
14437     , creation_date
14438     , created_by
14439     , last_update_login
14440     , po_line_id
14441     , quantity
14442     , quantity_received
14443     , quantity_accepted
14444     , quantity_rejected
14445     , quantity_billed
14446     , quantity_cancelled
14447     , quantity_financed
14448     , amount
14449     , amount_received
14450     , amount_accepted
14451     , amount_rejected
14452     , amount_billed
14453     , amount_cancelled
14454     , amount_financed
14455     , ship_to_location_id
14456     , need_by_date
14457     , promised_date
14458     , from_header_id
14459     , from_line_id
14460     , note_to_receiver
14461     , approved_flag
14462     , po_release_id
14463     , closed_code
14464     , closed_reason
14465     , price_override
14466     , encumbered_flag
14467     , taxable_flag
14468     , tax_code_id
14469     , tax_user_override_flag
14470     , shipment_type
14471     , shipment_num
14472     , inspection_required_flag
14473     , receipt_required_flag
14474     , days_early_receipt_allowed
14475     , days_late_receipt_allowed
14476     , enforce_ship_to_location_code
14477     , ship_to_organization_id
14478     , invoice_close_tolerance
14479     , receive_close_tolerance
14480     , accrue_on_receipt_flag
14481     , allow_substitute_receipts_flag
14482     , receiving_routing_id
14483     , qty_rcv_tolerance
14484     , qty_rcv_exception_code
14485     , receipt_days_exception_code
14486     , terms_id
14487     , ship_via_lookup_code
14488     , freight_terms_lookup_code
14489     , fob_lookup_code
14490     , unit_meas_lookup_code
14491     , last_accept_date
14492     , match_option
14493     , country_of_origin_code
14494     , vmi_flag
14495     , drop_ship_flag
14496     , consigned_flag
14497     , transaction_flow_header_id
14498     , org_id
14499     , closed_for_receiving_date
14500     , closed_for_invoice_date
14501     , value_basis
14502     , matching_basis
14503     , payment_type
14504     , description
14505     , work_approver_id
14506     , bid_payment_id
14507     , outsourced_assembly
14508     ,tax_attribute_update_code --<eTax Integration R12>
14509     )
14510     VALUES
14511     (
14512       PO_LINE_LOCATIONS_S.nextval
14513     , interface.last_update_date
14514     , interface.last_updated_by
14515     , interface.po_header_id
14516     , interface.creation_date
14517     , interface.created_by
14518     , interface.last_update_login
14519     , p_po_line_id
14520     , line_location_rec.quantity   -- quantity
14521     , 0                            -- quantity_received
14522     , 0                            -- quantity_accepted
14523     , 0                            -- quantity_rejected
14524     , 0                            -- quantity_billed
14525     , 0                            -- quantity_cancelled
14526     , 0                            -- quantity_financed
14527     , line_location_rec.amount     -- amount
14528     , 0                            -- amount_received
14529     , 0                            -- amount_accepted
14530     , 0                            -- amount_rejected
14531     , 0                            -- amount_billed
14532     , 0                            -- amount_cancelled
14533     , 0                            -- amount_financed
14534     , line_location_rec.ship_to_location_id
14535     , line_location_rec.need_by_date
14536     , line_location_rec.promised_date
14537     , interface.from_header_id
14538     , interface.from_line_id
14539     , interface.note_to_receiver
14540     , 'N'                          -- approved_flag
14541     , NULL                         -- po_release_d
14542     , 'OPEN'                       -- closed_code
14543     , NULL                         -- closed_reason
14544     , line_location_rec.price_override
14545     , 'N'                            -- encumbered_flag
14546     , NVL2(l_tax_code_id, 'Y', 'N')  -- taxable_flag
14547     , l_tax_code_id
14548     , l_req_tax_user_override_flag
14549     , line_location_rec.shipment_type
14550     , line_location_rec.shipment_num
14551     , 'N'                           -- inspection_required_flag
14552     , DECODE(line_location_rec.value_basis,    -- receipt_required_flag
14553                'FIXED_PRICE', 'N',
14554                coalesce(item.receipt_required_flag,
14555                         vendor.receipt_required_flag,
14556                         params.receiving_flag,
14557                         'N'))
14558     , payitem_rcv_ctl_rec.days_early_receipt_allowed
14559     , payitem_rcv_ctl_rec.days_late_receipt_allowed
14560     , payitem_rcv_ctl_rec.enforce_ship_to_location_code
14561     , line_location_rec.ship_to_organization_id
14562     , coalesce(item.invoice_close_tolerance, params.invoice_close_tolerance, 100)
14563     , DECODE(line_location_rec.payment_type,
14564                'MILESTONE', 0,
14565                coalesce(item.receive_close_tolerance,
14566                         params.receive_close_tolerance,
14567                         100))
14568     , DECODE(line_location_rec.shipment_type,   -- acrrue_on_receipt_flag
14569               'PREPAYMENT', 'N',
14570               DECODE(coalesce(item.receipt_required_flag,
14571                               interface.receipt_required_flag,
14572                               vendor.receipt_required_flag,
14573                               params.receiving_flag,
14574                               'N'),
14575                       'N', 'N',
14576                       DECODE(params.expense_accrual_code,
14577                                 'PERIOD END', 'N', 'Y')))
14578     , payitem_rcv_ctl_rec.allow_substitute_receipts_flag
14579     , payitem_rcv_ctl_rec.receiving_routing_id
14580     , payitem_rcv_ctl_rec.qty_rcv_tolerance
14581     , payitem_rcv_ctl_rec.qty_rcv_exception_code
14582     , payitem_rcv_ctl_rec.receipt_days_exception_code
14583     , NULL     -- terms_id
14584     , NULL     -- ship_via_lookup_code
14585     , NULL     -- freight_terms_lookup_code
14586     , NULL     -- fob_lookup_code
14587     , line_location_rec.unit_of_measure   -- unit_meas_lookup_code
14588     , line_location_rec.promised_date     -- last_accept_date
14589             + payitem_rcv_ctl_rec.days_late_receipt_allowed
14590     , vendor.invoice_match_option
14591     , l_country_of_origin_code
14592     , NULL                -- vmi_flag
14593     , NULL                -- drop_ship_flag
14594     , NULL                -- consigned_flag
14595     , interface.transaction_flow_header_id
14596     , g_purchasing_ou_id
14597     , NULL       -- closed_for_receiving_date
14598     , NULL       -- closed_for_invoice_date
14599     , line_location_rec.value_basis
14600     , line_location_rec.matching_basis
14601     , line_location_rec.payment_type
14602     , line_location_rec.description
14603     , line_location_rec.work_approver_id
14604     , line_location_rec.bid_payment_id
14605     , 2                                 -- outsourced_assembly
14606     ,nvl2(g_calculate_tax_flag, 'CREATE', null)  --<eTax Integration R12>
14607 
14608     )
14609     RETURNING line_location_id INTO l_line_loc_id;
14610 
14611     d_progress := 220;
14612     IF (PO_LOG.d_stmt) THEN
14613       PO_LOG.stmt(d_module, d_progress, 'Inserted payitem.');
14614       PO_LOG.stmt(d_module, d_progress, 'l_line_loc_id', l_line_loc_id);
14615     END IF;
14616 
14617     d_progress := 230;
14618 
14619     -- create link between interface row and transaction row
14620     UPDATE po_line_locations_interface polli
14621     SET polli.line_location_id = l_line_loc_id
14622     WHERE polli.interface_line_location_id =
14623                          line_location_rec.interface_line_location_id;
14624 
14625     d_progress := 240;
14626 
14627     calculate_local('PO', 'SHIPMENT', l_line_loc_id);
14628 
14629     d_progress := 250;
14630     l_payitems_created := l_payitems_created + 1;
14631     x_line_loc_id_tbl.EXTEND;
14632     x_line_loc_id_tbl(l_payitems_created) := l_line_loc_id;
14633     l_payitem_tax_code_id_tbl.EXTEND;
14634     l_payitem_tax_code_id_tbl(l_payitems_created) := l_tax_code_id;
14635 
14636     -- set x_line_location_id to id of first actual (STANDARD) payitem
14637     IF ((x_line_location_id IS NULL)
14638         AND (line_location_rec.shipment_type = 'STANDARD')) THEN
14639       x_line_location_id := l_line_loc_id;
14640     END IF;
14641 
14642   END LOOP;  -- poll_interface_cursor loop
14643   CLOSE poll_interface_cursor;
14644 
14645   d_progress := 300;
14646 
14647   -- call create_payitem_dists to create distributions for all new payitems
14648   IF (PO_LOG.d_stmt) THEN
14649     PO_LOG.stmt(d_module, d_progress, 'Ready to call create_payitem_dists');
14650   END IF;
14651 
14652   create_payitem_dists(
14653     p_po_line_id        => p_po_line_id
14654   , p_req_line_id       => interface.requisition_line_id
14655   , p_interface_line_id => p_interface_line_id
14656   , p_precision         => p_precision
14657   , p_ext_precision     => p_ext_precision
14658   );
14659 
14660   d_progress := 310;
14661 
14662   IF (PO_LOG.d_stmt) THEN
14663     PO_LOG.stmt(d_module, d_progress, 'Done calling create_payitem dists');
14664   END IF;
14665 
14666   d_progress := 400;
14667 
14668  IF (PO_LOG.d_stmt) THEN
14669       PO_LOG.stmt(d_module, d_progress, 'calling tax api ');
14670  END IF;
14671 
14672  d_progress := 1420;
14673 
14674   IF (PO_LOG.d_proc) THEN
14675     PO_LOG.proc_end(d_module, 'x_line_location_id', x_line_location_id);
14676     PO_LOG.proc_end(d_module, 'x_line_loc_id_tbl',  x_line_loc_id_tbl);
14677     PO_LOG.proc_end(d_module);
14678   END IF;
14679 
14680 EXCEPTION
14681   WHEN OTHERS THEN
14682 
14683     IF (PO_LOG.d_exc) THEN
14684       PO_LOG.exc(d_module, d_progress, SQLCODE || SQLERRM);
14685     END IF;
14686 
14687     IF (poll_interface_cursor%ISOPEN) THEN
14688       CLOSE poll_interface_cursor;
14689     END IF;
14690 
14691     wrapup(interface.interface_header_id);
14692     RAISE;
14693 END create_payitems;
14694 
14695 
14696 -------------------------------------------------------------------------------
14697 --Start of Comments
14698 --Name: create_payitem_dists
14699 --Pre-reqs:
14700 --   PO Payitems have all been created.
14701 --Modifies:
14702 --  PO_DISTRIBUTIONS_ALL
14703 --Locks:
14704 --  None.
14705 --Function:
14706 --  Create all distributions for all payitems for a PO Line.
14707 --Parameters:
14708 --  IN:
14709 --    p_req_line_id: id of the requisition line that is the source of
14710 --                   the po line; null if no backing req.
14711 --    p_po_line_id: id of the line in po_lines_all
14712 --    p_interface_line_id: id of the line in po_lines_interface
14713 --    p_precision: precision of the currency desired.  Used to round amounts.
14714 --    p_ext_precision: extended precision of the currency desired.
14715 --                     Used to round prices
14716 --  OUT:
14717 --    None.
14718 --Notes:
14719 --  None
14720 --Testing:
14721 --  None
14722 --End of Comments
14723 -------------------------------------------------------------------------------
14724 PROCEDURE create_payitem_dists(
14725   p_po_line_id         IN NUMBER
14726 , p_req_line_id        IN NUMBER
14727 , p_interface_line_id  IN NUMBER
14728 , p_precision          IN NUMBER
14729 , p_ext_precision      IN NUMBER
14730 )
14731 IS
14732 
14733 d_progress   NUMBER;
14734 d_module     VARCHAR2(70) := 'po.plsql.PO_INTERFACE_S.create_payitem_dists';
14735 
14736 CURSOR payitem_acct_gen_cursor(p_po_line_id NUMBER)
14737 IS
14738   SELECT pod.po_distribution_id
14739        , pod.project_id
14740        , pod.task_id
14741        , pod.award_id
14742        , pod.expenditure_type
14743        , pod.expenditure_item_date
14744        , pod.expenditure_organization_id
14745        , pod.destination_type_code
14746        , pod.destination_organization_id
14747        , pod.destination_subinventory
14748        , pod.deliver_to_location_id
14749        , pod.deliver_to_person_id
14750        , pod.gl_encumbered_date
14751        , poll.price_override
14752        , poll.payment_type
14753        , pod.distribution_type
14754        , pod.rate
14755   FROM po_distributions_all pod,
14756        po_line_locations_all poll
14757   WHERE poll.po_line_id = p_po_line_id
14758     AND pod.line_location_id = poll.line_location_id
14759     AND pod.req_distribution_id IS NULL;
14760 
14761 payitem_acct_rec      payitem_acct_gen_cursor%ROWTYPE;
14762 
14763 l_line_loc_id_tbl              po_tbl_number;
14764 l_line_loc_value_basis_tbl     po_tbl_varchar30;
14765 l_dist_id_tbl                  po_tbl_number;
14766 
14767 l_return_status       VARCHAR2(1);
14768 l_msg_count           NUMBER;
14769 l_msg_data            VARCHAR2(2000);
14770 l_gl_date_option      VARCHAR2(25);
14771 l_sob_id              PO_REQ_DISTRIBUTIONS_ALL.set_of_books_id%TYPE;
14772 
14773 
14774 -- Acct. Generator Variables Start
14775 l_dest_charge_success          BOOLEAN   := TRUE;
14776 l_dest_variance_success        BOOLEAN   := TRUE;
14777 l_charge_success               BOOLEAN   := TRUE;
14778 l_budget_success               BOOLEAN   := TRUE;
14779 l_accrual_success              BOOLEAN   := TRUE;
14780 l_variance_success             BOOLEAN   := TRUE;
14781 
14782 l_dest_charge_account_id       NUMBER;
14783 l_dest_variance_account_id     NUMBER;
14784 l_code_combination_id          NUMBER;
14785 l_budget_account_id            NUMBER;
14786 l_accrual_account_id           NUMBER;
14787 l_variance_account_id          NUMBER;
14788 
14789 l_dest_charge_account_desc     VARCHAR2(2000);
14790 l_dest_variance_account_desc   VARCHAR2(2000);
14791 l_charge_account_desc          VARCHAR2(2000);
14792 l_budget_account_desc          VARCHAR2(2000);
14793 l_accrual_account_desc         VARCHAR2(2000);
14794 l_variance_account_desc        VARCHAR2(2000);
14795 
14796 l_dest_charge_account_flex     VARCHAR2(2000);
14797 l_dest_variance_account_flex   VARCHAR2(2000);
14798 l_charge_account_flex          VARCHAR2(2000);
14799 l_budget_account_flex          VARCHAR2(2000);
14800 l_accrual_account_flex         VARCHAR2(2000);
14801 l_variance_account_flex        VARCHAR2(2000);
14802 
14803 l_wf_itemkey                   VARCHAR2(80) := NULL;
14804 l_new_combination              BOOLEAN      := FALSE;
14805 l_fb_error_msg                 VARCHAR2(2000);
14806 
14807 l_acct_api_success             BOOLEAN;
14808 -- Acct. Generator Variables End
14809 
14810 
14811 BEGIN
14812 
14813   d_progress := 0;
14814   IF (PO_LOG.d_proc) THEN
14815     PO_LOG.proc_begin(d_module);
14816     PO_LOG.proc_begin(d_module, 'p_po_line_id', p_po_line_id);
14817     PO_LOG.proc_begin(d_module, 'p_req_line_id', p_req_line_id);
14818     PO_LOG.proc_begin(d_module, 'p_interface_line_id', p_interface_line_id);
14819   END IF;
14820 
14821   d_progress := 10;
14822 
14823   IF (p_req_line_id IS NOT NULL) THEN
14824 
14825     -- if backing req exists, use req distributions as base for creating
14826     -- po distributions.
14827 
14828     d_progress := 20;
14829 
14830     FND_PROFILE.GET('PO_AUTOCREATE_DATE', l_gl_date_option);
14831 
14832     IF ((params.po_encumbrance_flag = 'Y')
14833       AND (l_gl_date_option <> 'REQ GL DATE')
14834       AND (params.period_name IS NULL)) THEN
14835 
14836       -- derive period name if it isn't already known
14837 
14838       d_progress := 30;
14839 
14840       SELECT prd.set_of_books_id
14841       INTO l_sob_id
14842       FROM po_req_distributions_all prd
14843       WHERE prd.requisition_line_id = p_req_line_id
14844         AND ROWNUM = 1;
14845 
14846       d_progress := 40;
14847 
14848       PO_PERIODS_SV.get_period_name(
14849         x_sob_id  => l_sob_id
14850       , x_gl_date => SYSDATE
14851       , x_gl_period => params.period_name
14852       );
14853 
14854       IF (params.period_name IS NULL) THEN
14855         d_progress := 50;
14856         IF (PO_LOG.d_exc) THEN
14857           PO_LOG.exc(d_module, d_progress, 'Unable to find period name for SYSDATE');
14858         END IF;
14859         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
14860       END IF;
14861 
14862     END IF;  -- if params.po_encumbrance_flag = 'Y' AND ...
14863 
14864     -- create distributions from req distributions
14865 
14866     d_progress := 60;
14867 
14868     --SQL WHAT: Create payitem distributions from backing req. distributions
14869     --SQL WHY : Create all such payitem distributions in one place
14870 
14871     INSERT INTO po_distributions_all(
14872       po_distribution_id
14873     , last_update_date
14874     , last_updated_by
14875     , last_update_login
14876     , creation_date
14877     , created_by
14878     , po_header_id
14879     , po_line_id
14880     , line_location_id
14881     , distribution_num
14882     , req_distribution_id
14883     , set_of_books_id
14884     , code_combination_id
14885     , deliver_to_location_id
14886     , deliver_to_person_id
14887     , destination_type_code
14888     , destination_organization_id
14889     , destination_subinventory
14890     , project_id
14891     , task_id
14892     , award_id
14893     , end_item_unit_number
14894     , expenditure_type
14895     , project_accounting_context
14896     , destination_context
14897     , expenditure_organization_id
14898     , expenditure_item_date
14899     , rate
14900     , rate_date
14901     , budget_account_id
14902     , accrual_account_id
14903     , variance_account_id
14904     , accrued_flag
14905     , encumbered_flag
14906     , prevent_encumbrance_flag
14907     , gl_encumbered_date
14908     , gl_encumbered_period_name
14909     , recovery_rate
14910     , recoverable_tax
14911     , nonrecoverable_tax
14912     , accrue_on_receipt_flag
14913     , kanban_card_id
14914     , org_id
14915     , distribution_type
14916     , quantity_ordered
14917     , amount_ordered
14918     ,tax_attribute_update_code    --<eTax Integration R12>
14919     )
14920     SELECT
14921       PO_DISTRIBUTIONS_S.NEXTVAL
14922     , interface.last_update_date
14923     , interface.last_updated_by
14924     , interface.last_update_login
14925     , interface.creation_date
14926     , interface.created_by
14927     , interface.po_header_id
14928     , p_po_line_id
14929     , poll.line_location_id
14930     , prd.distribution_num
14931     , prd.distribution_id  --Bug 4744751: these 2 cols were reversed in order
14932     , prd.set_of_books_id  --Bug 4744751: these 2 cols were reversed in order
14933     , prd.code_combination_id
14934     , prl.deliver_to_location_id
14935     , prl.to_person_id
14936     , prl.destination_type_code
14937     , prl.destination_organization_id
14938     , prl.destination_subinventory
14939     , prd.project_id
14940     , prd.task_id
14941     , prd.award_id
14942     , prd.end_item_unit_number
14943     , prd.expenditure_type
14944     , prd.project_accounting_context
14945     , prl.destination_context
14946     , prd.expenditure_organization_id
14947     , prd.expenditure_item_date
14948     , interface.h_rate
14949     , interface.h_rate_date
14950     , DECODE(poll.shipment_type, 'PREPAYMENT', null, prd.budget_account_id)
14951     , prd.accrual_account_id
14952     , prd.variance_account_id
14953     , 'N'         -- accrued_flag
14954     , 'N'         -- encumbered_flag
14955     , DECODE(params.po_encumbrance_flag, 'Y',
14956                DECODE(poll.shipment_type, 'PREPAYMENT', 'Y', 'N'),
14957                null)  -- prevent_encumbrance_flag
14958     , (CASE        -- gl_encumbered_date
14959          WHEN (params.req_encumbrance_flag = 'Y' AND
14960                  l_gl_date_option = 'REQ GL DATE')
14961            THEN prd.gl_encumbered_date
14962          WHEN (params.po_encumbrance_flag = 'Y')
14963            THEN trunc(SYSDATE)
14964          ELSE NULL
14965        END)
14966     , (CASE        -- gl_encumbered_period_name
14967          WHEN (params.req_encumbrance_flag = 'Y' AND
14968                  l_gl_date_option = 'REQ GL DATE')
14969            THEN prd.gl_encumbered_period_name
14970          WHEN (params.po_encumbrance_flag = 'Y')
14971            THEN params.period_name
14972          ELSE NULL
14973        END)
14974     , prd.recovery_rate
14975     , prd.recoverable_tax
14976     , prd.nonrecoverable_tax
14977     , poll.accrue_on_receipt_flag
14978     , prl.kanban_card_id
14979     , g_purchasing_ou_id
14980     , poll.shipment_type
14981     , (CASE                     -- quantity_ordered
14982          WHEN poll.value_basis <> 'QUANTITY'
14983            THEN NULL
14984          WHEN poll.payment_type IN ('MILESTONE', 'DELIVERY')
14985            THEN ROUND((prd.req_line_quantity / prl.quantity) * poll.quantity, 15)
14986          WHEN poll.payment_type = 'RATE'
14987            THEN ROUND((prd.req_line_amount / prl.amount) * poll.quantity, 15)
14988        END)
14989     , (CASE                     -- amount_ordered
14990          WHEN poll.value_basis <> 'FIXED PRICE'
14991            THEN NULL
14992          ELSE ROUND((prd.req_line_amount / prl.amount) * poll.amount, p_precision)
14993        END)
14994        ,nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax integration R12>
14995     FROM po_line_locations_all poll
14996        , po_req_distributions_all prd
14997        , po_requisition_lines_all prl
14998     WHERE poll.po_line_id = p_po_line_id
14999       AND prd.requisition_line_id = p_req_line_id
15000       AND prl.requisition_line_id = prd.requisition_line_id
15001       AND poll.payment_type <> 'ADVANCE';
15002 
15003     d_progress := 70;
15004     IF (PO_LOG.d_stmt) THEN
15005       PO_LOG.stmt(d_module, d_progress, 'Payitems distributions created from requisition distributions.');
15006     END IF;
15007 
15008   ELSE
15009 
15010     -- no backing req exists; create distributions for payitems
15011     -- from scratch.  Accounts are not set here - they will
15012     -- be generated and populated later.
15013 
15014     d_progress := 80;
15015 
15016     IF ((params.po_encumbrance_flag = 'Y')
15017       AND (params.period_name IS NULL)) THEN
15018 
15019       -- derive period name if it isn't already known
15020       d_progress := 90;
15021 
15022       PO_PERIODS_SV.get_period_name(
15023         x_sob_id  => params.sob_id
15024       , x_gl_date => SYSDATE
15025       , x_gl_period => params.period_name
15026       );
15027 
15028       IF (params.period_name IS NULL) THEN
15029         d_progress := 100;
15030         IF (PO_LOG.d_exc) THEN
15031           PO_LOG.exc(d_module, d_progress, 'Unable to find period name for SYSDATE');
15032         END IF;
15033         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
15034       END IF;
15035 
15036     END IF;  -- if params.po_encumbrance_flag = 'Y' AND ...
15037 
15038     d_progress := 110;
15039 
15040     --SQL WHAT: Create payitem distributions in the case of no backing req.
15041     --SQL WHY : Create all such payitem distributions in one place
15042 
15043     INSERT INTO po_distributions_all(
15044       po_distribution_id
15045     , last_update_date
15046     , last_updated_by
15047     , last_update_login
15048     , creation_date
15049     , created_by
15050     , po_header_id
15051     , po_line_id
15052     , line_location_id
15053     , distribution_num
15054     , req_distribution_id
15055     , deliver_to_location_id
15056     , deliver_to_person_id
15057     , destination_type_code
15058     , destination_organization_id
15059     , destination_subinventory
15060     , rate
15061     , rate_date
15062     , accrued_flag
15063     , encumbered_flag
15064     , prevent_encumbrance_flag
15065     , gl_encumbered_date
15066     , gl_encumbered_period_name
15067     , accrue_on_receipt_flag
15068     , org_id
15069     , distribution_type
15070     , project_id
15071     , task_id
15072     , award_id
15073     , end_item_unit_number
15074     , expenditure_type
15075     , project_accounting_context
15076     , destination_context
15077     , expenditure_organization_id
15078     , expenditure_item_date
15079     , quantity_ordered
15080     , amount_ordered
15081     , set_of_books_id
15082     ,tax_attribute_update_code  --<eTax Integration R12>
15083     )
15084     SELECT
15085       PO_DISTRIBUTIONS_S.NEXTVAL
15086     , interface.last_update_date
15087     , interface.last_updated_by
15088     , interface.last_update_login
15089     , interface.creation_date
15090     , interface.created_by
15091     , interface.po_header_id
15092     , p_po_line_id
15093     , poll.line_location_id
15094     , 1                          -- distribution_num
15095     , NULL                       -- req_distribution_id
15096     , poll.ship_to_location_id
15097     , NULL                       -- deliver_to_person_id
15098     , 'EXPENSE'                  -- destination_type_code
15099     , poll.ship_to_organization_id
15100     , NULL                       -- destination_subinventory
15101     , interface.h_rate
15102     , interface.h_rate_date
15103     , 'N'                        -- accrued_flag
15104     , 'N'                        -- encumbered_flag
15105     , DECODE(params.po_encumbrance_flag, 'Y',
15106                DECODE(poll.shipment_type, 'PREPAYMENT', 'Y', 'N'),
15107                null)  -- prevent_encumbrance_flag
15108     , DECODE(params.po_encumbrance_flag, 'Y', trunc(SYSDATE), NULL)
15109     , DECODE(params.po_encumbrance_flag, 'Y', params.period_name, NULL)
15110     , poll.accrue_on_receipt_flag
15111     , g_purchasing_ou_id
15112     , poll.shipment_type
15113     , polli.project_id
15114     , polli.task_id
15115     , polli.award_id
15116     , NULL                       -- end_item_unit_number
15117     , polli.expenditure_type
15118     , NULL                       -- project_accounting_context
15119     , 'EXPENSE'                  -- destination_context
15120     , polli.expenditure_organization_id
15121     , polli.expenditure_item_date
15122     , poll.quantity
15123     , poll.amount
15124     , params.sob_id
15125     ,nvl2(g_calculate_tax_flag, 'CREATE', null) --<eTax integration R12>
15126     FROM po_line_locations_all poll
15127        , po_line_locations_interface polli
15128     WHERE poll.po_line_id = p_po_line_id
15129       AND poll.line_location_id = polli.line_location_id
15130       AND poll.payment_type <> 'ADVANCE';
15131 
15132     d_progress := 120;
15133     IF (PO_LOG.d_stmt) THEN
15134       PO_LOG.stmt(d_module, d_progress, 'Payitems distributions created from scratch.');
15135     END IF;
15136 
15137   END IF;  -- if p_req_line_id IS NOT NULL
15138 
15139   d_progress := 130;
15140 
15141   IF (interface.has_advance_flag = 'Y') THEN
15142 
15143     -- create advance distributions
15144     -- logic: copy distributions from first actuals payitem
15145 
15146     d_progress := 140;
15147 
15148     --SQL WHAT: Create payitem distributions for advance payitems
15149     --SQL WHY : Create all such payitem distributions in one place
15150 
15151     INSERT INTO po_distributions_all
15152     (
15153       po_distribution_id
15154     , last_update_date
15155     , last_updated_by
15156     , last_update_login
15157     , creation_date
15158     , created_by
15159     , po_header_id
15160     , po_line_id
15161     , line_location_id
15162     , distribution_num
15163     , req_distribution_id
15164     , deliver_to_location_id
15165     , deliver_to_person_id
15166     , destination_type_code
15167     , destination_organization_id
15168     , destination_subinventory
15169     , rate
15170     , rate_date
15171     , accrued_flag
15172     , encumbered_flag
15173     , prevent_encumbrance_flag
15174     , gl_encumbered_date
15175     , gl_encumbered_period_name
15176     , accrue_on_receipt_flag
15177     , org_id
15178     , distribution_type
15179     , amount_ordered
15180     , quantity_ordered
15181     , project_id
15182     , task_id
15183     , award_id
15184     , end_item_unit_number
15185     , expenditure_type
15186     , project_accounting_context
15187     , destination_context
15188     , expenditure_organization_id
15189     , expenditure_item_date
15190     , set_of_books_id
15191     ,tax_attribute_update_code  --<eTax Integration R12>
15192     )
15193     SELECT
15194       PO_DISTRIBUTIONS_S.NEXTVAL
15195     , interface.last_update_date
15196     , interface.last_updated_by
15197     , interface.last_update_login
15198     , interface.creation_date
15199     , interface.created_by
15200     , interface.po_header_id
15201     , p_po_line_id
15202     , adv.line_location_id
15203     , pod.distribution_num           -- distribution_num
15204     , NULL                           -- req_distribution_id
15205     , pod.deliver_to_location_id
15206     , pod.deliver_to_person_id
15207     , pod.destination_type_code
15208     , pod.destination_organization_id
15209     , pod.destination_subinventory
15210     , pod.rate
15211     , pod.rate_date
15212     , pod.accrued_flag
15213     , pod.encumbered_flag
15214     , DECODE(params.po_encumbrance_flag, 'Y', 'Y', null) --prevent_enc_flag
15215     , NULL                           -- gl_encumbered_date
15216     , NULL                           -- gl_encumbered_period_name
15217     , adv.accrue_on_receipt_flag
15218     , pod.org_id
15219     , adv.shipment_type
15220     , ROUND(                         -- amount_ordered
15221        (NVL(pod.amount_ordered, deliv.price_override * pod.quantity_ordered)
15222         / NVL(deliv.amount, deliv.price_override * deliv.quantity))
15223          * adv.amount, 15)
15224     , NULL                           -- quantity_ordered
15225     , pod.project_id
15226     , pod.task_id
15227     , pod.award_id
15228     , pod.end_item_unit_number
15229     , pod.expenditure_type
15230     , pod.project_accounting_context
15231     , pod.destination_context
15232     , pod.expenditure_organization_id
15233     , pod.expenditure_item_date
15234     , params.sob_id
15235     ,nvl2(g_calculate_tax_flag, 'CREATE', null)  --<eTax integration R12>
15236       FROM po_line_locations_all adv,
15237            po_line_locations_all deliv,
15238            po_distributions_all pod
15239       WHERE adv.po_line_id = p_po_line_id
15240         AND adv.payment_type = 'ADVANCE'
15241         AND deliv.line_location_id =
15242            ( SELECT poll.line_location_id
15243              FROM po_line_locations_all poll
15244              WHERE poll.po_line_id = p_po_line_id
15245                AND poll.shipment_type = 'STANDARD'
15246                AND poll.shipment_num =
15247                     ( SELECT min(poll2.shipment_num)
15248                       FROM po_line_locations_all poll2
15249                       WHERE poll2.po_line_id = poll.po_line_id
15250                         AND poll2.shipment_type = 'STANDARD'))
15251         AND pod.line_location_id = deliv.line_location_id;
15252 
15253     d_progress := 150;
15254     IF (PO_LOG.d_stmt) THEN
15255       PO_LOG.stmt(d_module, d_progress, 'Advance distributions created.');
15256     END IF;
15257 
15258   END IF;  -- if interface.has_advance_flag
15259 
15260   d_progress := 160;
15261 
15262   -- calibrate last distribution for each pay item
15263 
15264   SELECT poll.line_location_id, poll.value_basis
15265   BULK COLLECT INTO l_line_loc_id_tbl, l_line_loc_value_basis_tbl
15266   FROM po_line_locations_all poll
15267   WHERE poll.po_line_id = p_po_line_id;
15268 
15269   FOR i in 1..l_line_loc_id_tbl.COUNT
15270   LOOP
15271 
15272     IF (l_line_loc_value_basis_tbl(i) = 'FIXED PRICE') THEN
15273       calibrate_last_dist_amount(l_line_loc_id_tbl(i));
15274     ELSE
15275       calibrate_last_dist_quantity(l_line_loc_id_tbl(i));
15276     END IF;
15277 
15278   END LOOP;
15279 
15280   d_progress := 170;
15281 
15282   -- now, generate accounts for all distributions that are not
15283   -- tied to a backing req. distribution
15284 
15285   OPEN payitem_acct_gen_cursor(p_po_line_id);
15286   LOOP
15287 
15288     FETCH payitem_acct_gen_cursor INTO payitem_acct_rec;
15289     EXIT WHEN payitem_acct_gen_cursor%NOTFOUND;
15290 
15291     d_progress := 180;
15292     IF (PO_LOG.d_stmt) THEN
15293       PO_LOG.stmt(d_module, d_progress, 'Calling account generator wf method.');
15294       PO_LOG.stmt(d_module, d_progress, 'payitem_acct_rec.po_distribution_id', payitem_acct_rec.po_distribution_id);
15295     END IF;
15296 
15297     l_acct_api_success := PO_WF_BUILD_ACCOUNT_INIT.Start_Workflow(
15298       x_purchasing_ou_id  =>  g_purchasing_ou_id
15299     , x_transaction_flow_header_id  => NULL
15300     , x_dest_charge_success         => l_dest_charge_success
15301     , x_dest_charge_account_id      => l_dest_charge_account_id
15302     , x_dest_charge_account_desc    => l_dest_charge_account_desc
15303     , x_dest_charge_account_flex    => l_dest_charge_account_flex
15304     , x_dest_variance_success       => l_dest_variance_success
15305     , x_dest_variance_account_id    => l_dest_variance_account_id
15306     , x_dest_variance_account_desc  => l_dest_charge_account_desc
15307     , x_dest_variance_account_flex  => l_dest_charge_account_flex
15308     , x_charge_success              => l_charge_success
15309     , x_budget_success              => l_budget_success
15310     , x_accrual_success             => l_accrual_success
15311     , x_variance_success            => l_variance_success
15312     , x_code_combination_id         => l_code_combination_id
15313     , x_budget_account_id           => l_budget_account_id
15314     , x_accrual_account_id          => l_accrual_account_id
15315     , x_variance_account_id         => l_variance_account_id
15316     , x_charge_account_flex         => l_charge_account_flex
15317     , x_budget_account_flex         => l_budget_account_flex
15318     , x_accrual_account_flex        => l_accrual_account_flex
15319     , x_variance_account_flex       => l_variance_account_flex
15320     , x_charge_account_desc         => l_charge_account_desc
15321     , x_budget_account_desc         => l_budget_account_desc
15322     , x_accrual_account_desc        => l_accrual_account_desc
15323     , x_variance_account_desc       => l_variance_account_desc
15324     , x_coa_id                      => params.coa_id
15325     , x_bom_resource_id             => NULL
15326     , x_bom_cost_element_id         => NULL
15327     , x_category_id                 => interface.category_id
15328     , x_item_id                     => interface.item_id
15329     , x_type_lookup_code            => interface.document_subtype
15330     , x_line_type_id                => interface.line_type_id
15331     , x_agent_id                    => interface.agent_id
15332     , x_destination_type_code       => payitem_acct_rec.destination_type_code
15333     , x_deliver_to_location_id      => payitem_acct_rec.deliver_to_location_id
15334     , x_deliver_to_person_id        => payitem_acct_rec.deliver_to_person_id
15335     , x_destination_organization_id => payitem_acct_rec.destination_organization_id
15336     , x_destination_subinventory    => payitem_acct_rec.destination_subinventory
15337     , x_expenditure_type            => payitem_acct_rec.expenditure_type
15338     , x_expenditure_organization_id => payitem_acct_rec.expenditure_organization_id
15339     , x_expenditure_item_date       => payitem_acct_rec.expenditure_item_date
15340     , x_project_id                  => payitem_acct_rec.project_id
15341     , x_task_id                     => payitem_acct_rec.task_id
15342     , x_award_id                    => payitem_acct_rec.award_id
15343     , x_from_type_lookup_code       => NULL
15344     , x_from_header_id              => NULL
15345     , x_from_line_id                => NULL
15346     , x_vendor_id                   => interface.vendor_id
15347     , x_vendor_site_id              => interface.vendor_site_id
15348     , x_wip_entity_id               => NULL
15349     , x_wip_entity_type             => NULL
15350     , x_wip_line_id                 => NULL
15351     , x_wip_repetitive_schedule_id  => NULL
15352     , x_wip_operation_seq_num       => NULL
15353     , x_wip_resource_seq_num        => NULL
15354     , x_po_encumberance_flag        => params.po_encumbrance_flag
15355     , x_gl_encumbered_date          => payitem_acct_rec.gl_encumbered_date
15356     , x_result_billable_flag        => NULL
15357     , wf_itemkey                    => l_wf_itemkey
15358     , x_new_combination             => l_new_combination
15359     , header_att1        => NULL
15360     , header_att2        => NULL
15361     , header_att3        => NULL
15362     , header_att4        => NULL
15363     , header_att5        => NULL
15364     , header_att6        => NULL
15365     , header_att7        => NULL
15366     , header_att8        => NULL
15367     , header_att9        => NULL
15368     , header_att10       => NULL
15369     , header_att11       => NULL
15370     , header_att12       => NULL
15371     , header_att13       => NULL
15372     , header_att14       => NULL
15373     , header_att15       => NULL
15374     , line_att1          => NULL
15375     , line_att2          => NULL
15376     , line_att3          => NULL
15377     , line_att4          => NULL
15378     , line_att5          => NULL
15379     , line_att6          => NULL
15380     , line_att7          => NULL
15381     , line_att8          => NULL
15382     , line_att9          => NULL
15383     , line_att10         => NULL
15384     , line_att11         => NULL
15385     , line_att12         => NULL
15386     , line_att13         => NULL
15387     , line_att14         => NULL
15388     , line_att15         => NULL
15389     , shipment_att1      => NULL
15390     , shipment_att2      => NULL
15391     , shipment_att3      => NULL
15392     , shipment_att4      => NULL
15393     , shipment_att5      => NULL
15394     , shipment_att6      => NULL
15395     , shipment_att7      => NULL
15396     , shipment_att8      => NULL
15397     , shipment_att9      => NULL
15398     , shipment_att10     => NULL
15399     , shipment_att11     => NULL
15400     , shipment_att12     => NULL
15401     , shipment_att13     => NULL
15402     , shipment_att14     => NULL
15403     , shipment_att15     => NULL
15404     , distribution_att1  => NULL
15405     , distribution_att2  => NULL
15406     , distribution_att3  => NULL
15407     , distribution_att4  => NULL
15408     , distribution_att5  => NULL
15409     , distribution_att6  => NULL
15410     , distribution_att7  => NULL
15411     , distribution_att8  => NULL
15412     , distribution_att9  => NULL
15413     , distribution_att10 => NULL
15414     , distribution_att11 => NULL
15415     , distribution_att12 => NULL
15416     , distribution_att13 => NULL
15417     , distribution_att14 => NULL
15418     , distribution_att15 => NULL
15419     , FB_ERROR_MSG       => l_fb_error_msg
15420     , p_func_unit_price  =>
15421         ROUND(payitem_acct_rec.price_override * NVL (payitem_acct_rec.rate, 1),
15422                 NVL(p_ext_precision, 15))
15423     , p_distribution_type    => payitem_acct_rec.distribution_type
15424     , p_payment_type         => payitem_acct_rec.payment_type
15425     );
15426 
15427     d_progress := 190;
15428     IF (PO_LOG.d_stmt) THEN
15429       PO_LOG.stmt(d_module, d_progress, 'Finished account generator call.');
15430       PO_LOG.stmt(d_module, d_progress, 'l_acct_api_success', l_acct_api_success);
15431       PO_LOG.stmt(d_module, d_progress, 'l_charge_success', l_charge_success);
15432       PO_LOG.stmt(d_module, d_progress, 'l_variance_success', l_variance_success);
15433       PO_LOG.stmt(d_module, d_progress, 'l_budget_success', l_budget_success);
15434       PO_LOG.stmt(d_module, d_progress, 'l_accrual_success', l_accrual_success);
15435     END IF;
15436 
15437     -- follow same behavior as with shipment distributions:
15438     -- if account generator failed, do not create distribution
15439 
15440     d_progress := 200;
15441 
15442     IF ( l_acct_api_success AND l_charge_success
15443          --Bug 5645242: Added the check to test if the charge account id generated is null or 0,
15444          --if this is the case, then we should delete the distribution record.
15445          AND  (NVL(l_code_combination_id , 0) <> 0)
15446          AND l_variance_success AND l_accrual_success
15447          AND (l_budget_success OR (NVL(params.po_encumbrance_flag, 'N') <> 'Y')))
15448     THEN
15449 
15450       d_progress := 210;
15451       IF (PO_LOG.d_stmt) THEN
15452         PO_LOG.stmt(d_module, d_progress, 'Updating dist. with acct. info');
15453       END IF;
15454 
15455       --SQL WHAT: Update account information for a po distribution
15456       --SQL WHY : PO Distributions that don't have a backing req need to
15457       --          have account defaulted from account generator.
15458 
15459       UPDATE po_distributions_all pod
15460       SET pod.code_combination_id = l_code_combination_id
15461         , pod.budget_account_id = DECODE(NVL(params.po_encumbrance_flag, 'N'),
15462                                     'Y', l_budget_account_id,
15463                                     NULL)
15464         , pod.accrual_account_id = l_accrual_account_id
15465         , pod.variance_account_id = l_variance_account_id
15466       WHERE pod.po_distribution_id = payitem_acct_rec.po_distribution_id;
15467 
15468     ELSE
15469 
15470       d_progress := 220;
15471       IF (PO_LOG.d_stmt) THEN
15472         PO_LOG.stmt(d_module, d_progress, 'Deleting distribution - acct. gen failure');
15473       END IF;
15474 
15475       DELETE FROM po_distributions_all pod
15476       WHERE pod.po_distribution_id =
15477               payitem_acct_rec.po_distribution_id;
15478 
15479     END IF;  -- if l_acct_api_success AND ...
15480 
15481   END LOOP;  -- payitem_acct_gen_cursor loop
15482   CLOSE payitem_acct_gen_cursor;
15483 
15484   d_progress := 300;
15485   IF (PO_LOG.d_stmt) THEN
15486     PO_LOG.stmt(d_module, d_progress, 'Calling update_award_distributions');
15487   END IF;
15488 
15489   update_award_distributions(
15490     p_table_type => 'ALL'
15491   , p_po_line_id => p_po_line_id
15492   );
15493 
15494   d_progress := 310;
15495 
15496   SELECT pod.po_distribution_id
15497   BULK COLLECT INTO l_dist_id_tbl
15498   FROM po_distributions_all pod
15499   WHERE pod.po_line_id = p_po_line_id;
15500 
15501   d_progress := 320;
15502 
15503   FOR i in 1..l_dist_id_tbl.COUNT
15504   LOOP
15505     calculate_local('PO', 'DISTRIBUTION', l_dist_id_tbl(i));
15506   END LOOP;
15507 
15508   IF (PO_LOG.d_proc) THEN
15509     PO_LOG.proc_end(d_module);
15510   END IF;
15511 
15512 EXCEPTION
15513   WHEN OTHERS THEN
15514     IF (PO_LOG.d_exc) THEN
15515       PO_LOG.exc(d_module, d_progress, SQLCODE || SQLERRM);
15516     END IF;
15517 
15518     IF (payitem_acct_gen_cursor%ISOPEN) THEN
15519       CLOSE payitem_acct_gen_cursor;
15520     END IF;
15521 
15522     wrapup(interface.interface_header_id);
15523     RAISE;
15524 END create_payitem_dists;
15525 
15526 -- <Complex Work R12 End>
15527 
15528 END PO_INTERFACE_S;