DBA Data[Home] [Help]

PACKAGE BODY: APPS.PAAPIMP_PKG

Source


1 PACKAGE BODY PAAPIMP_PKG AS
2 /* $Header: PAAPIMPB.pls 120.133.12020000.8 2013/04/03 11:33:59 ayushsha ship $ */
3 
4 /*------------------Main Procedure-------------------------------------------*/
5 /* Added for Bug # 2138340 */
6 p_trans_import_failed varchar2(1) := 'N';    /* package level var for detecting if trans import ever failed */
7 g_body_debug_mode varchar2(1) := NVL(FND_PROFILE.value('PA_DEBUG_MODE'), 'N');
8 --g_body_debug_mode varchar2(1) := 'Y';
9 
10 /* 3917045 : This variable holds the value of the request parameter 'Interface Supplier Invoices' */
11 G_PROCESS_INVOICES VARCHAR2(1) := 'Y';
12 
13 FUNCTION ReceiptPaAdditionFlag(p_Pa_Addition_Flag      IN VARCHAR2,
14                                p_Po_Distribution_Id    IN NUMBER)
15                               RETURN VARCHAR2 ;
16 
17 PROCEDURE PAAPIMP ( errbuf                  OUT NOCOPY VARCHAR2,
18                     retcode                 OUT NOCOPY VARCHAR2,
19         	    invoice_type            IN  VARCHAR2,
20                     project_id              IN  NUMBER,
21                     batch_name              IN  VARCHAR2,
22                     gl_date_arg             IN  VARCHAR2,
23                     transaction_date_arg    IN  VARCHAR2,
24                     debug_mode              IN  VARCHAR2,
25                     process_invoices        IN  VARCHAR2,
26                     process_receipts        IN  VARCHAR2,
27                     process_discounts       IN  VARCHAR2,
28                     output_type             IN  NUMBER
29                     ) IS
30 
31      result               NUMBER;
32      gl_date              DATE;
33      transaction_date     DATE;
34      lv_method            VARCHAR2(15);
35      completion_status    BOOLEAN; -- Added for Bug # 2114086
36      l_process_invoices   VARCHAR2(1);
37      l_process_receipts   VARCHAR2(1);
38      l_process_discounts  VARCHAR2(1);
39      l_run  VARCHAR2(15);
40 
41 
42 BEGIN
43 
44      write_log(LOG, 'Invoice Type: '||invoice_type);
45      write_log(LOG, 'Project Id: '||to_char(project_id));
46      write_log(LOG, 'GL Date: '||gl_date_arg);
47      write_log(LOG, 'TR date: '||transaction_date_arg);
48      write_log(LOG, 'Debug Mode: '||debug_mode);
49      write_log(LOG, 'Process Invoices: '||process_invoices);
50      write_log(LOG, 'Process Receipts: '||process_receipts);
51      write_log(LOG, 'Process Discounts: '||process_discounts);
52 
53      /* Setting PASSED IN parameters as local variables */
54      l_process_invoices := nvl(process_invoices,'Y');
55      l_process_receipts := nvl(process_receipts,'N');
56      l_process_discounts := nvl(process_discounts,'N');
57      G_PROCESS_INVOICES := l_process_invoices; /* 3917045 */
58 
59      G_err_stage := 'CHANGING VARCHAR2 TO DATE';
60      gl_date := fnd_date.canonical_to_date(gl_date_arg);
61      transaction_date := fnd_date.canonical_to_date(transaction_date_arg);
62 
63      G_err_stage := 'ASSIGNING LOCK NAME';
64      G_LOCK_NAME := 'PAAPIMP';
65 
66      /*
67      -- VI enhancment Check if we're transferring expense report type invoices or vendor invoices.
68      -- Then nitialize global variables accordingly
69      */
70 
71      IF invoice_type = 'EXPENSE REPORT' THEN
72 
73         If g_body_debug_mode = 'Y' Then
74         write_log(LOG, 'This process transfers Invoice Type: Expense Report');
75         End if;
76 
77         Initialize_Global(
78                         p_project_id           => project_id,
79                         p_batch_name           => batch_name,
80                         p_gl_date              => gl_date,
81                         p_transaction_date     => transaction_date,
82                         p_debug_mode           => debug_mode,
83                         p_output               => output_type,
84                         p_invoice_source1      => 'XpenseXpress',
85                         p_invoice_source2      => 'Manual Invoice Entry',
86                         p_invoice_source3      => 'SelfService',
87                         p_invoice_type         => 'EXPENSE REPORT',
88                         p_system_linkage       => 'ER',
89                         p_process_receipts     => l_process_receipts);
90 
91      ELSE
92 
93         If g_body_debug_mode = 'Y' Then
94         write_log(LOG, 'This process transfers Invoice Type: Supplier Invoice');
95         End If;
96 
97         Initialize_Global(
98                          p_project_id => project_id,
99                          p_batch_name => batch_name,
100                          p_gl_date => gl_date,
101                          p_transaction_date => transaction_date,
102                          p_debug_mode => debug_mode,
103                          p_output => output_type,
104                          p_invoice_type => NULL,
105                          p_system_linkage => 'VI',
106                          p_process_receipts => l_process_receipts);
107 
108      END IF; /* expense type = expense report */
109 
110      If g_body_debug_mode = 'Y' Then
111          write_log(LOG,'Process invoices? : ' || l_process_invoices);
112          write_log(LOG,'Process receipts? : ' || l_process_receipts);
113          write_log(LOG,'Process discounts? :' || l_process_discounts);
114      End If;
115 
116      -- Cleanup all the pending transactions in any previous runs.
117 
118      If g_body_debug_mode = 'Y' Then
119          G_err_stage := 'Before calling cleanup';
120          write_log(LOG, G_err_stage);
121      End If;
122 
123      cleanup();
124 
125  --    savepoint paapimp ; /* Added savepoint for 3922679 */
126 
127      If g_body_debug_mode = 'Y' Then
128            write_log(LOG,'Current Org ID is:'||G_ORG_ID);
129      End If;
130 
131      IF l_process_receipts = 'Y' THEN
132        IF PA_UTILS4.get_ledger_cash_basis_flag = 'N' THEN
133 
134         G_err_stage := 'Before calling Net Zero Ad of RCV Transctions';
135         If g_body_debug_mode = 'Y' Then
136                write_log(LOG, G_err_stage);
137         End If;
138 
139         -- Net_Zero_Adj_Po(); This logic is now implemented in PO at the time of receipt creation. Bug#4565757.
140 
141         If g_body_debug_mode = 'Y' Then
142              G_err_stage := 'Before call to mark_RCV_PAflag';
143              write_log(LOG, G_err_stage);
144         End If;
145 
146         Mark_RCV_PAflag();
147 
148         IF (G_RCV_TRANSACTIONS_MARKED_O > 0) THEN
149 
150             G_err_stage :=  'Before calling transfer receipts to pa procedure';
151             If g_body_debug_mode = 'Y' Then
152                  write_log(LOG, 'No rcv transctions to be transferred.');
153             End If;
154 
155             transfer_receipts_to_pa;
156         ELSE
157             G_err_stage :=  'No rcv transctions to be transferred.';
158             If g_body_debug_mode = 'Y' Then
159                  write_log(LOG, G_err_stage);
160             End If;
161             NULL;
162         END IF;
163        ELSE
164         G_err_stage := 'Not pulling Receipts for Cash Basis Accounting ';
165         If g_body_debug_mode = 'Y' Then
166                write_log(LOG, G_err_stage);
167         End If;
168        END IF;  -- get_ledger_cash_basis_flag = N
169      END IF;  -- l_process_receipts = 'Y'
170 
171      --Added for performance improvement. SELECT the value of assets_addition_flag into
172      --a global variable that can be used throughout the program
173 
174      IF G_PROJECT_ID IS NOT NULL AND
175         (l_process_invoices  = 'Y' OR l_process_discounts ='Y') THEN
176 
177         If g_body_debug_mode = 'Y' Then
178         write_log(LOG,'G_Project_ID is not NULL,:'||G_PROJECT_ID||' getting assets_addition_flag.');
179         End If;
180 
181         SELECT decode(PTYPE.Project_Type_Class_Code,'CAPITAL','P','X')
182           INTO G_Assets_Addition_flag
183           FROM pa_project_types_all PTYPE,
184                pa_projects_all PROJ
185          WHERE PTYPE.Project_Type = PROJ.Project_Type
186            AND (PTYPE.org_id = PROJ.org_id OR
187                 PROJ.org_id is null)
188            AND PROJ.Project_Id = G_PROJECT_ID;
189 
190      END IF;
191 
192      --
193      -- Process invoices
194      --
195      IF l_process_invoices = 'Y' THEN
196 
197         /*============================================================*/
198         /* BEGIN AMOUNT VARIANCE PROCESSING                           */
199         /*============================================================*/
200         If g_body_debug_mode = 'Y' Then
201               G_err_stage:= 'Callng mark_inv_var_paflag';
202               write_log(LOG,   G_err_stage);
203         End If;
204 
205         -- Procedure MARK_INV_VAR_PAFLAG will update the inv dist status to either G or W values for both CASH (Historical only) and ACCRUAL
206           -- This procedure will update invoice dist to status W for processing the amount variance into Oracle Projects
207 
208         mark_inv_var_paflag;
209 
210 
211         IF G_NUM_AP_VARIANCE_MARKED_W > 0 THEN
212 
213            transfer_inv_var_to_pa;
214 
215         ELSE
216            If g_body_debug_mode = 'Y' Then
217            write_log(LOG,'No invoice variances to be processed');
218            End If;
219         END IF;
220 
221         /*=================================================================*/
222         /* BEGIN INVOICE PROCESSING FOR CASH (Historical only) AND ACCRUAL */
223         /*=================================================================*/
224         If g_body_debug_mode = 'Y' Then
225         G_err_stage := 'Before calling Net Zero Ad';
226         write_log(LOG, G_err_stage);
227         End If;
228 
229         net_zero_adjustment();
230 
231         If g_body_debug_mode = 'Y' Then
232         G_err_stage := 'Before call to mark_PAFlag_O';
233         write_log(LOG, G_err_stage);
234         End If;
235 
236         -- Procedure MARK_PAFLAG_O will update the inv dist staus to either G or O values for both CASH (Historical only)  and ACCRUAL
237           -- This Procedure will also update valid Invoice Dist to status O for historical invoices for CASH BASED ACCTNG
238           -- This procedure will also update valid Invoice Dist to status O for ACCRUAL BASED ACCTNG
239 
240         mark_PAflag_O();
241 
242         IF (G_DISTRIBUTIONS_MARKED > 0) THEN
243             transfer_inv_to_pa();
244         ELSE
245         If g_body_debug_mode = 'Y' Then
246             write_log(LOG, 'No invoice distribution to be transferred.');
247         End If;
248         END IF;
249 
250         --
251         /*============================================================*/
252         /* BEGIN PAYMENT PROCESSING FOR CASH ACCTNG                   */
253         /*============================================================*/
254         -- For CAsh BAsis process Payments
255 
256         IF G_ACCTNG_METHOD = 'C' THEN
257 
258           If g_body_debug_mode = 'Y' Then
259           G_err_stage := 'Before calling Net Zero Ad for Payments';
260           write_log(LOG, G_err_stage);
261           End If;
262 
263           net_zero_pay_adjustment();
264 
265           If g_body_debug_mode = 'Y' Then
266                G_err_stage := 'Before call to mark_PA_Pay_flag_O';
267                write_log(LOG, G_err_stage);
268           End If;
269 
270           mark_PA_Pay_flag_O();
271 
272           IF (G_PAY_DISTRIBUTIONS_MARKED > 0) THEN
273               transfer_pay_to_pa();
274           ELSE
275            If g_body_debug_mode = 'Y' Then
276               write_log(LOG, 'No Invoice Payment distributions to be transferred.');
277            End If;
278           END IF;
279 
280        END IF;  /* Cash BAsed Acctng */
281 
282      END IF; /* process invoices = 'Y' */
283 
284      If g_body_debug_mode = 'Y' Then
285      G_err_stage := 'after transferring invoices. Begin Discount processing';
286      write_log(LOG, G_err_stage);
287      End If;
288 
289      /*============================================================*/
290      /* BEGIN DISCOUNT PROCESSING                                  */
291      /*============================================================*/
292      -- Process discounts as cost in Cash Basis flow automatically. Bug#5137211.
293      IF (l_process_discounts = 'Y' OR G_ACCTNG_METHOD = 'C' ) THEN
294 
295            --Modified the to_date to fnd_date.canonical_to_date - Bug 4522045
296            G_Profile_Discount_Start_date:=fnd_date.canonical_to_date(return_profile_discount_date);
297 
298            -- Get the discount Method.
299            G_Discount_Method:=PAAPIMP_PKG.return_discount_method;
300 
301            If g_body_debug_mode = 'Y' Then
302            write_log(LOG,'the profile discount start date is:'||to_char(G_Profile_Discount_Start_date));
303            write_log(LOG,'Only transactions after the profile start date will be pulled.');
304            End If;
305 
306            mark_PA_disc_flag_O();
307 
308            IF (G_DISC_DISTRIBUTIONS_MARKED > 0) THEN
309                transfer_disc_to_pa();
310            ELSE
311             If g_body_debug_mode = 'Y' Then
312                write_log(LOG, 'No Discount distributions to be transferred.');
313             End If;
314            END IF;
315 
316            If g_body_debug_mode = 'Y' Then
317            G_err_stage:= 'after transferring discounts';
318            write_log(LOG, G_err_stage);
319            End If;
320 
321      END IF;  /* process discounts */
322 
323      G_err_stage := 'RELEASING LOCK HANDLE';
324      result := dbms_lock.release(G_LOCKHNDL);
325 
326      G_err_stage := 'PRINT STAT AND SUBMIT REPORT';
327      print_stat_and_submit_report();
328 
329      IF p_trans_import_failed = 'Y' THEN
330            write_log(LOG, 'p-trans-import-failed');
331         completion_status  := fnd_concurrent.set_completion_status('ERROR', SQLERRM);
332      END IF;
333      COMMIT; /* Added commit: 3922679 removed intermediate commits*/
334 
335 EXCEPTION
336      WHEN E_DIFFERENT_SOB THEN
337           write_log(LOG, 'Please check your settings.  AP and PA use different set of books.');
338      WHEN OTHERS THEN
339           write_log(LOG,'Error occured in stage: ' || G_err_stage || ', PAAPIMP aborted!');
340           write_log(LOG, substr(SQLERRM, 1, 200));
341 
342           IF (G_err_stage <> 'RELEASING LOCK HANDLE') THEN
343                     result := dbms_lock.release(G_LOCKHNDL);
344           END IF;
345           print_stat_and_submit_report();
346 
347           /* Here the return value (TRUE/FALSE) is not being
348              checked, as the concurrent request calls this main procedure
349              and we are in the when others exception of this procedure. */
350 
351             completion_status := fnd_concurrent.set_completion_status('ERROR', SQLERRM);
352 
353 
354 END PAAPIMP;
355 
356 /*------------------Init Phase-----------------------------------------------*/
357    /* VI enhancements */
358 PROCEDURE Initialize_Global (
359    p_project_id IN NUMBER,
360    p_batch_name IN VARCHAR2,
361    p_gl_date IN DATE,
362    p_transaction_date IN DATE,
363    p_debug_mode IN VARCHAR2,
364    p_output IN NUMBER,
365    /* IC Upgrade: transaction source variables are now initialize after we fetched
366       the record from the cursor
367    P_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
368    p_user_transaction_source IN pa_transaction_interface.user_transaction_source%TYPE,*/
369    p_invoice_source1 IN ap_invoices.source%TYPE,
370    p_invoice_source2 IN ap_invoices.source%TYPE,
371    p_invoice_source3 IN ap_invoices.source%TYPE,
372    p_invoice_type IN ap_invoices.invoice_type_lookup_code%TYPE,
373    p_system_linkage IN pa_transaction_interface.system_linkage%TYPE,
374    p_process_receipts IN VARCHAR2
375    ) IS
376 
377    v_interface_id    NUMBER;
378    v_commit_size    VARCHAR2(20);
379    v_old_stack      VARCHAR2(630);
380    G_AP_SOB         NUMBER;
381    G_PA_SOB         NUMBER;
382    G_PO_SOB         NUMBER;
383    l_process_receipts VARCHAR2(1);
384 
385 BEGIN
386 
387    /* Initialize the type of output procedure to use.*/
388    G_OUTPUT := p_output;
389 
390    If p_debug_mode = 'Y' Then
391    write_log(LOG, '....Entering Init Phase ....');
392    End If;
393 
394    /* Initialize all logging and debugging variables */
395    v_old_stack := G_err_stack;
396    G_err_stack := G_err_stack || '->PAAPIMP_PKG.Initialize_Global';
397    G_err_code := 0;
398 
399    If p_debug_mode = 'Y' Then
400    write_log(LOG, G_err_stack);
401    End If;
402 
403    /* Initialize debug level */
404    IF (p_debug_mode = 'Y') THEN
405 
406       pa_debug.debug_level := pa_debug.DEBUG_LEVEL_TIMING;
407       --ALTER SESSION SET SQL_TRACE = TRUE;
408 
409    END IF;
410 
411    /* MC Upgrade */
412    /* 1.Check if AP and PA have same set of books.
413       2.Get Accounting Currency
414     */
415 
416     G_err_stage := 'Check AP, PO, and PA set of books';
417     SELECT ap.set_of_books_id,
418            pa.set_of_books_id
419       INTO G_AP_SOB,
420            G_PA_SOB
421       FROM ap_system_parameters ap,
422            pa_implementations pa;
423 
424     IF (G_AP_SOB <> G_PA_SOB) THEN
425 
426         raise E_DIFFERENT_SOB;
427 
428     END IF;
429 
430     l_process_receipts:=p_process_receipts;
431    If p_debug_mode = 'Y' Then
432     write_log(LOG,' process receipts?'||l_process_receipts);
433    End If;
434 
435     IF l_process_receipts = 'Y' THEN
436 
437         G_err_stage := ' Check PO and PA set of books';
438 
439         SELECT po.set_of_books_id
440           INTO G_PO_SOB
441           FROM financials_system_parameters po;
442 
443         IF G_PO_SOB <> G_PA_SOB THEN
444 
445            RAISE E_DIFFERENT_SOB;
446 
447         END IF;
448 
449     END IF;
450 
451     G_err_stage := 'Calling Get_acct_currency_code API';
452     G_ACCT_CURRENCY_CODE := pa_multi_currency.get_acct_currency_code();
453 
454    /* ----------------------------------------------------------------------*/
455 
456    /* Initialize global variables from parameters */
457 
458     G_PROJECT_ID          := p_project_id;
459     G_GL_DATE             := p_gl_date;
460     G_TRANSACTION_DATE    := p_transaction_date;
461     G_DEBUG_MODE          := p_debug_mode;
462     G_BODY_DEBUG_MODE     := p_debug_mode;
463     G_INVOICE_SOURCE1     := p_invoice_source1;
464     G_INVOICE_SOURCE2     := p_invoice_source2;
465     G_INVOICE_SOURCE3     := p_invoice_source3;
466 
467     IF   PA_UTILS4.get_ledger_cash_basis_flag = 'N' THEN
468       G_ACCTNG_METHOD := 'A';
469 --write_log(LOG,'Accounting Method is Accrual');
470     ELSE
471       G_ACCTNG_METHOD := 'C';
472 --write_log(LOG,'Accounting Method is CAsh');
473     END IF;
474 
475 
476 
477    -- Bug 2242588
478    -- Populate value of G_request_ID to create batch names
479 
480    G_REQUEST_ID := FND_GLOBAL.CONC_REQUEST_ID();
481 
482    /* Check if user has given a batch name, if yes, use it, otherwise
483       create a new batch name */
484 
485    IF (p_batch_name IS NULL) THEN
486 
487       G_BATCH_NAME := create_new_batch_name();
488 
489       G_NRT_BATCH_NAME := 'APNRT-'||G_UNIQUE_ID;
490 
491   -- Added for AP discounts
492       G_DISC_BATCH_NAME :='APDISC-'||G_UNIQUE_ID;
493 
494    --Added for AP Variance
495       G_AP_VAR_BATCH_NAME   :='APVAR-'||G_UNIQUE_ID;
496 
497    --Added for AP ERV
498       G_AP_ERV_BATCH_NAME   :='APERV-'||G_UNIQUE_ID;
499 
500    --Added for AP Freight
501       G_AP_FRT_BATCH_NAME   :='APFRT-'||G_UNIQUE_ID;  --NEW
502 
503    --Added for Prepay
504      G_PREPAY_BATCH_NAME   :='APPPAY-'||G_UNIQUE_ID;  --NEW
505 
506   -- Added for Receipts
507      G_RCV_BATCH_NAME    := 'RCV-'||G_UNIQUE_ID;
508      G_RCVTAX_BATCH_NAME := 'RCVNRT-'||G_UNIQUE_ID;
509 
510    ELSE
511 
512       G_BATCH_NAME        := p_batch_name;
513       G_NRT_BATCH_NAME    := p_batch_name;
514       G_DISC_BATCH_NAME   := p_batch_name;
515       G_AP_VAR_BATCH_NAME := p_batch_name;
516       G_AP_ERV_BATCH_NAME := p_batch_name;
517       G_AP_FRT_BATCH_NAME := p_batch_name;
518       G_PREPAY_BATCH_NAME := p_batch_name;
519       G_RCV_BATCH_NAME    := p_batch_name;
520       G_RCVTAX_BATCH_NAME := p_batch_name;
521 
522    END IF;
523 
524 
525    write_validate_param_log();
526 
527    /* IC Upgrade
528       We will be initializing transaction source
529       variables in 'insert_into_trans_intf' API */
530 
531    G_INVOICE_TYPE := p_invoice_type;
532 
533    If p_debug_mode = 'Y' Then
534    write_log(LOG,'The invoice type is:' ||G_INVOICE_TYPE);
535    End If;
536 
537    G_SYSTEM_LINKAGE := p_system_linkage;
538 
539    /* Fetch Profile Variables */
540    fetch_pf_var(p_process_receipts => l_process_receipts);
541 
542    G_err_stage := 'GET ORGINAZATION ID';
543    /* SELECT NVL(org_id, -99) commented for bug#2488576,removed nvl */
544      SELECT org_id
545      INTO G_ORG_ID
546      FROM pa_implementations;
547 
548    /* initialize global count variables */
549    G_NUM_BATCHES_PROCESSED := 0;
550    G_NUM_INVOICES_PROCESSED := 0;
551    G_NUM_DISTRIBUTIONS_PROCESSED := 0;
552    G_DISTRIBUTIONS_MARKED := 0;
553    G_SAT_DISTRIBUTIONS_MARKED := 0; /*Bug 13602288:  Self Assessed Tax  */
554    G_PAY_DISTRIBUTIONS_MARKED := 0;
555 
556    -- Added for AP discounts
557    G_NUM_DISCOUNTS_PROCESSED :=0;
558 
559    --Added for AP Variance
560    G_NUM_AP_VARIANCE_MARKED_W    :=0;
561    G_NUM_AP_SAT_VARIANCE_MARKED_W    :=0; /*Bug 13602288:  Self Assessed Tax  */
562    G_NUM_AP_VARIANCE_PROCESSED :=0;
563 
564    --Added for PO RECEIPT
565    G_RCV_TRANSACTIONS_MARKED_O    :=0;
566    G_RCV_TRANSACTIONS_MARKED_J    :=0;
567    G_RCV_TRANSACTIONS_MARKED_NULL :=0;
568    G_RCV_TRANSACTIONS_MARKED_G    :=0;
569    G_NUM_RCV_TXN_PROCESSED        :=0;
570    G_NUM_RCVTAX_PROCESSED         :=0;
571 
572    /* restore the old G_err_stack */
573    G_err_stack := v_old_stack;
574 
575 EXCEPTION
576 
577    WHEN E_DIFFERENT_SOB THEN
578       RAISE;
579 
580    WHEN Others THEN
581 
582       G_err_stack := v_old_stack;
583       G_err_code := SQLCODE;
584       RAISE;
585 
586 END Initialize_Global;
587 
588 PROCEDURE fetch_pf_var(p_process_receipts IN VARCHAR2 ) IS
589 --PROCEDURE fetch_pf_var IS
590 
591    v_old_stack VARCHAR2(630);
592    v_commit_size VARCHAR2(30);
593 
594 BEGIN
595 
596    v_old_stack := G_err_stack;
597    G_err_stack := G_err_stack || '->PAAPIMP_PKG.fetch_pf_var';
598    G_err_stage := 'FETCHING PROFILE VARIABLES';
599 
600    If g_body_debug_mode = 'Y' Then
601    write_log(LOG, G_err_stack);
602    End If;
603 
604    G_USER_ID := FND_GLOBAL.USER_ID();
605    G_REQUEST_ID := FND_GLOBAL.CONC_REQUEST_ID();
606    G_PROG_APPL_ID := FND_GLOBAL.PROG_APPL_ID();
607    G_PROG_ID := FND_GLOBAL.CONC_PROGRAM_ID();
608    G_LOGIN_ID := FND_GLOBAL.CONC_LOGIN_ID();
609 
610    /* Get commit cycle size */
611    /* VI enhancment: Check the G_INVOICE_TYPE variable to see
612       which invoice type we're transferring, then initialize
613       the profile name global variable accordingly */
614 
615    IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
616 
617       G_PROFILE_NAME := 'PA_NUM_WEB_EXP_PER_SET';
618 
619    ELSE
620 
621       G_PROFILE_NAME := 'PA_NUM_EXP_ITEMS_PER_SET';
622 
623    END IF;
624 
625    G_err_stage := 'FETCHING PROFILE OPTION: COMMIT SIZE';
626    fnd_profile.get(G_PROFILE_NAME, v_commit_size);
627 
628    G_COMMIT_SIZE := to_number(v_commit_size);
629 
630    IF (G_COMMIT_SIZE <= 0) THEN
631 
632    If g_body_debug_mode = 'Y' Then
633       write_log(LOG, 'Please verify the value of profile option PA: Web Expense Invoices Per Set.  Current value is: ' || to_char(G_COMMIT_SIZE));
634       write_log(LOG, 'Commit Size set to default value: 500');
635 G_COMMIT_SIZE := 500;
636   End If;
637    END IF;
638 
639    If g_body_debug_mode = 'Y' Then
640     write_log(LOG, 'Expense Invoices Per Set.  Current value is: ' || to_char(G_COMMIT_SIZE));  /* Bug # 2138340 */
641    End If;
642 
643    /* Get the profile option of whether to transfer DFF from AP */
644    G_err_stage := 'FETCHING PROFILE OPTION: TRANS DFF FROM AP';
645 
646    G_PROFILE_NAME := 'PA_TRANSFER_DFF_AP';
647    fnd_profile.get(G_PROFILE_NAME, G_TRANS_DFF_AP);
648    If g_body_debug_mode = 'Y' Then
649    write_log(LOG,'Processing DFFs for AP?'||G_TRANS_DFF_AP);
650    End If;
651    IF p_process_receipts = 'Y' THEN
652 
653      G_PROFILE_NAME := 'PA_TRANSFER_DFF_PO';
654      fnd_profile.get(G_PROFILE_NAME, G_TRANS_DFF_PO);
655    If g_body_debug_mode = 'Y' Then
656      write_log(LOG,'Processing DFFs for PO?'||G_TRANS_DFF_PO);
657    End if;
658    END IF;
659 
660    G_err_stack := v_old_stack;
661 
662 EXCEPTION
663    WHEN Others THEN
664 
665       G_err_stack := v_old_stack;
666       G_err_code := SQLCODE;
667       RAISE;
668 
669 END fetch_pf_var;
670 
671 FUNCTION create_new_batch_name
672    RETURN pa_transaction_interface.batch_name%TYPE IS
673 
674    v_old_stack VARCHAR2(630);
675    v_new_batch_name pa_transaction_interface.batch_name%TYPE;
676    v_interface_id   NUMBER;
677 
678 BEGIN
679 
680    v_old_stack := G_err_stack;
681    G_err_stack := G_err_stack || '->PAAPIMP_PKG.create_new_batch_name';
682    G_err_stage := 'CREATING NEW BATCHNAME';
683 
684    If g_body_debug_mode = 'Y' Then
685    write_log(LOG, G_err_stack);
686    End If;
687 
688    --Getting a unique sequence for batch name from interface_id
689    SELECT pa_interface_id_s.nextval
690      into v_interface_id
691      FROM dual;
692 
693    G_UNIQUE_ID := v_interface_id;
694 
695    v_new_batch_name :=  'AP-' ||G_UNIQUE_ID;
696 
697    If g_body_debug_mode = 'Y' Then
698    write_log(LOG, 'New Batch Name: ' || v_new_batch_name);
699    End If;
700 
701    G_err_stack := v_old_stack;
702 
703    RETURN v_new_batch_name;
704 
705 EXCEPTION
706 
707 WHEN Others THEN
708 
709    G_err_stack := v_old_stack;
710    G_err_code := SQLCODE;
711    RAISE;
712 
713 
714 END create_new_batch_name;
715 
716 
717 PROCEDURE write_validate_param_log IS
718 
719    v_old_stack Varchar2(630);
720 
721 BEGIN
722 
723 	v_old_stack := G_err_stack;
724 	G_err_stack := G_err_stack || '->PAAPIMP_PKG.write_validate_param_log';
725 	G_err_stage := 'WRITE PARAMETERS TO LOG';
726 
727    If g_body_debug_mode = 'Y' Then
728 	pa_debug.debug(G_err_stack);
729    End If;
730 
731    IF (G_OUTPUT = G_OUTPUT_SQLPLUS) THEN
732 			NULL;
733 		ELSIF (G_OUTPUT = G_OUTPUT_SQLPLUS) THEN
734 	If g_body_debug_mode ='Y' Then
735          pa_debug.debug('Validated parameters are as follows:');
736          pa_debug.debug('  Parameter1  - Project ID                   : ' || G_PROJECT_ID);
737 			pa_debug.debug('  Parameter2  - Batch Name                   : ' || G_BATCH_NAME);
738          pa_debug.debug('  Parameter3  - GL Date through              : ' || to_char(G_GL_DATE));
739          pa_debug.debug('  Parameter4  - Transaction Date through     : ' || to_char(G_TRANSACTION_DATE));
740          pa_debug.debug('                     ');
741          pa_debug.debug('Other relevant information:');
742          pa_debug.debug('  User ID          = ' || to_char(G_USER_ID));
743          pa_debug.debug('  Request ID       = ' || to_char(G_REQUEST_ID));
744          pa_debug.debug('  Program ID       = ' || to_char(G_PROG_ID));
745          pa_debug.debug('  Login ID         = ' || to_char(G_LOGIN_ID));
746        End If;
747 		ELSIF (G_OUTPUT = G_OUTPUT_FND) THEN
748 	If g_body_debug_mode ='Y' Then
749          FND_FILE.PUT_LINE(FND_FILE.LOG, 'Validated parameters are as follows:');
750          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Parameter1  - Project ID                   : ' || G_PROJECT_ID);
751 			FND_FILE.PUT_LINE(FND_FILE.LOG, '  Parameter2  - Batch Name                   : ' || G_BATCH_NAME);
752          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Parameter3  - GL Date through              : ' || to_char(G_GL_DATE));
753          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Parameter4  - Transaction Date through     : ' || to_char(G_TRANSACTION_DATE));
754          FND_FILE.NEW_LINE(FND_FILE.LOG, 1);
755          FND_FILE.PUT_LINE(FND_FILE.LOG, 'Other relevant information:');
756          FND_FILE.PUT_LINE(FND_FILE.LOG, '  User ID          = ' || to_char(G_USER_ID));
757          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Request ID       = ' || to_char(G_REQUEST_ID));
758          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Program ID       = ' || to_char(G_PROG_ID));
759          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Login ID         = ' || to_char(G_LOGIN_ID));
760        End If;
761 
762       END IF;
763 
764 	G_err_stack := v_old_stack;
765 
766 EXCEPTION
767 
768    WHEN Others THEN  /* This exception is not fatal, so don't terminate the program. */
769 
770 	G_err_stack := v_old_stack;
771         G_err_code := SQLCODE;
772         If g_body_debug_mode = 'Y' Then
773         write_log(LOG,'Error occured in stage: ' || G_err_stage);
774         write_log(LOG, substr(SQLERRM, 1, 200));
775 	end if;
776 END write_validate_param_log;
777 
778 
779 PROCEDURE write_log (
780    p_message_type IN NUMBER,
781    p_message IN VARCHAR2) IS
782 
783    buffer_overflow EXCEPTION;
784    PRAGMA EXCEPTION_INIT(buffer_overflow, -20000);
785 
786 BEGIN
787 --          dbms_output.put_line(p_message);
788 /*
789    IF (p_message_type = LOG OR g_body_debug_mode = 'Y') THEN
790 
791       IF (G_OUTPUT = G_OUTPUT_SQLPLUS) THEN
792 
793          --dbms_output.put_line(p_message);
794          NULL;
795 
796       ELSIF (G_OUTPUT = G_OUTPUT_PADEBUG) THEN
797 
798          pa_debug.debug(p_message);
799 
800       ELSIF (G_OUTPUT = G_OUTPUT_FND) THEN
801 
802       FND_FILE.PUT_LINE(FND_FILE.LOG,to_char(sysdate,'HH:MI:SS:   ')|| p_message);
803       FND_FILE.NEW_LINE(FND_FILE.LOG, 1);
804 
805       END IF;
806 
807    END IF;
808 */
809       FND_FILE.PUT_LINE(FND_FILE.LOG,to_char(sysdate,'HH:MI:SS:   ')|| p_message);
810       FND_FILE.NEW_LINE(FND_FILE.LOG, 1);
811 EXCEPTION   /* When exception occurs, program needs to be aborted. */
812 
813    WHEN OTHERS THEN
814 
815       raise;
816 
817 END write_log;
818 
819 /*--------------------------Cleanup Phase--------------------------------------*/
820 
821 PROCEDURE cleanup IS
822 
823         CURSOR paapimp_cur IS
824         SELECT 'Y'
825         FROM    fnd_concurrent_requests req,
826                 fnd_concurrent_programs prog,
827                 fnd_executables exe
828         WHERE   req.program_application_id = prog.application_id
829           AND   req.concurrent_program_id = prog.concurrent_program_id
830           AND   req.phase_code = 'R'
831 	  AND	req.request_id <> G_REQUEST_ID
832           AND   prog.executable_application_id = exe.application_id
833           AND   prog.executable_id = exe.executable_id
834           AND   exe.executable_name = 'PAAPIMP';
835 
836         timeout  integer := 0;
837         lockmode integer := 6; /* exclusive lock */
838         lrelease boolean := FALSE; /* Do not release on commit */
839         lstatus   integer;
840         paapimp_running  varchar2(1) := '';
841 	result integer;
842 	v_old_stack VARCHAR2(630);
843 
844       BEGIN
845 
846 	v_old_stack := G_err_stack;
847 	G_err_stack := G_err_stack || '->PAAPIMP_PKG.cleanup';
848 	G_err_code := 0;
849 	G_err_stage := 'ALLOCATING LOCK';
850 
851         If g_body_debug_mode = 'Y' Then
852 	write_log(LOG, G_err_stack);
853        	write_log(LOG, '......Trying to allocate for a lock');
854         end if;
855         /* get lock handle for PAAPIMP user lock */
856 	dbms_lock.allocate_unique(G_LOCK_NAME,G_LOCKHNDL,timeout);
857 
858 	IF (G_LOCKHNDL IS NOT NULL) THEN
859    		If g_body_debug_mode = 'Y' Then
860 		write_log(LOG, '......Lock created, trying to request for lock.');
861 		end if;
862 
863 		G_err_stage := 'REQUESTING LOCK';
864 
865 		/* Get the lock, do not release the lock on commit */
866 		lstatus := dbms_lock.request(G_LOCKHNDL, lockmode, timeout, lrelease);
867 
868           IF ( lstatus = 0 ) then /* Got the lock */
869 		G_err_stage := 'CHECKING IF PAAPIMP IS RUNNING';
870    		If g_body_debug_mode = 'Y' Then
871 		write_log(LOG, '.....Request for lock granted, check if PAAPIMP is running.');
872 		end if;
873             	OPEN paapimp_cur; /* Check if PAAPIMP is running */
874             	FETCH paapimp_cur INTO paapimp_running;
875             	CLOSE paapimp_cur;
876 
877             IF ( nvl(paapimp_running,'N') = 'N' ) THEN
878 
879               /* PAAPIMP is not running, So Clean up */
880 		If g_body_debug_mode = 'Y' Then
881 		write_log(LOG, '......Paapimp is not running, do cleanup');
882 		end if;
883 		G_err_stage := 'UPDATING INVOICE DISTRIBUTIONS';
884 
885 	        UPDATE ap_invoice_distributions_all DIST
886               	SET DIST.pa_addition_flag = 'N'
887                   , DIST.request_id = G_REQUEST_ID
888               	WHERE  DIST.pa_addition_flag IN ('O','W')
889               	AND  DIST.posted_flag= 'Y' -- removed the append  || '' for bug 13599091
890               	AND  DIST.project_id >0
891                 AND  NOT EXISTS ( SELECT 'X'
892                                    FROM pa_expenditure_items_all ei
893 				  WHERE ei.document_header_id = dist.invoice_id   /*Added for bug 6327185 */
894                                     AND ei.document_distribution_id = dist.invoice_distribution_id
895                                     AND ei.transaction_source in ('AP INVOICE','AP VARIANCE','AP NRTAX','AP EXPENSE')) ;
896 
897 
898 		 /*Bug 13602288: Self Assessed Tax Changes -  Marking the SAT Lines also to N in the cleanup*/
899 		 UPDATE ap_self_assessed_tax_dist_all DIST
900               	SET DIST.pa_addition_flag = 'N'
901                   , DIST.request_id = G_REQUEST_ID
902               	WHERE  DIST.pa_addition_flag IN ('O','W')
903               	AND  DIST.posted_flag||''= 'Y'
904               	AND  DIST.project_id >0
905                 AND  NOT EXISTS ( SELECT 'X'
906                                    FROM pa_expenditure_items_all ei
907 				  WHERE ei.document_header_id = dist.invoice_id
908                                     AND ei.document_distribution_id = dist.invoice_distribution_id
909 				    AND ei.document_distribution_type = 'SELF_ASSESSED_TAX'
910                                     AND ei.transaction_source in ('AP INVOICE','AP VARIANCE','AP NRTAX','AP EXPENSE')) ;
911 
912 
913 		If g_body_debug_mode = 'Y' Then
914 		write_log(LOG, 'Number of invoice distributions updated = ' || to_char(SQL%ROWCOUNT));
915 		end if;
916 
917                 UPDATE ap_payment_hist_dists dist
918                 SET    dist.pa_addition_flag = 'N'
919                      , DIST.request_id = G_REQUEST_ID
920                 WHERE  DIST.pa_addition_flag  = 'O'
921                 AND    dist.pay_dist_lookup_code = 'DISCOUNT'
922                 AND    EXISTS (SELECT /*+ push_subq no_unnest */ NULL    /* added hint for BUG 13002753 */
923                              FROM   ap_payment_history_all hist
924                              WHERE  hist.payment_history_id = dist.payment_history_id
925                              AND    hist.posted_flag = 'Y')
926                 AND    NOT EXISTS ( SELECT /*+ push_subq no_unnest */ 'X'   /* added hint for BUG 13002753 */
927                                      FROM pa_expenditure_items_all ei
928                                     WHERE ei.document_distribution_id = dist.invoice_distribution_id
929                                       AND ei.document_payment_id = dist.invoice_payment_id
930                                       AND ei.transaction_source = 'AP DISCOUNTS') ;
931 
932                 If g_body_debug_mode = 'Y' Then
933                 write_log(LOG, 'Number of discount distributions updated = ' || to_char(SQL%ROWCOUNT));
934                 end if;
935 
936 
937                 IF G_ACCTNG_METHOD = 'A' THEN
938 
939                 --added the following for PO RECEIPT processing
940                 UPDATE rcv_receiving_sub_ledger rcv_sub
941                    SET rcv_sub.pa_addition_flag = 'N'
942                       ,rcv_sub.request_id       = G_REQUEST_ID
943                  WHERE rcv_sub.pa_addition_flag = 'O'
944                    AND NOT EXISTS (SELECT 'X'
945                                     FROM pa_expenditure_items_all ei
946                                     WHERE  ei.document_distribution_id = rcv_sub.rcv_transaction_id);
947 
948                 If g_body_debug_mode = 'Y' Then
949 		write_log(LOG, 'Number of rcv txn cleaned up from O:' || to_char(SQL%ROWCOUNT));
950 		end if;
951 
952                 UPDATE rcv_receiving_sub_ledger rcv_sub
953                    SET rcv_sub.pa_addition_flag = 'I'
954                  WHERE rcv_sub.pa_addition_flag = 'J';
955 
956                 If g_body_debug_mode = 'Y' Then
957 		write_log(LOG, 'Number of rcv txn cleaned up from J:' || to_char(SQL%ROWCOUNT));
958 		end if;
959 
960                 ELSE --Accounting method is CASH BASIS
961 
962                 UPDATE ap_payment_hist_dists dist
963                 SET    dist.pa_addition_flag = 'N'
964                      , DIST.request_id = G_REQUEST_ID
965               	WHERE  DIST.pa_addition_flag  = 'O'
966                 AND    dist.pay_dist_lookup_code = 'CASH'
967                 AND    EXISTS (SELECT NULL
968                              FROM   ap_payment_history_all hist
969                              WHERE  hist.payment_history_id = dist.payment_history_id
970                              AND    hist.posted_flag = 'Y')
971                 AND    NOT EXISTS ( SELECT 'X'
972                                      FROM pa_expenditure_items_all ei
973                                     WHERE ei.document_distribution_id = dist.invoice_distribution_id
974                                       AND ei.document_payment_id = dist.invoice_payment_id
975                                       AND ei.transaction_source = 'AP INVOICE') ;
976 
977 		If g_body_debug_mode = 'Y' Then
978 		write_log(LOG, 'Number of payment distributions updated = ' || to_char(SQL%ROWCOUNT));
979 		end if;
980 
981                 UPDATE ap_prepay_app_dists dist
982                 SET    dist.pa_addition_flag = 'N',
983                        request_id = G_REQUEST_ID
984                 WHERE  dist.pa_addition_flag = 'O'
985                 AND    NOT EXISTS ( SELECT 'X'
986                                      FROM pa_expenditure_items_all ei
987                                      WHERE ei.document_distribution_id = dist.invoice_distribution_id
988                                        AND ei.document_payment_id = dist.prepay_app_dist_id
989                                        AND ei.transaction_source in ('AP INVOICE','AP VARIANCE','AP NRTAX','AP EXPENSE')) ;
990 
991 		If g_body_debug_mode = 'Y' Then
992 		write_log(LOG, 'Number of prepayment appl distributions updated = ' || to_char(SQL%ROWCOUNT));
993 		end if;
994 
995                 END IF;
996 
997 		commit;
998 
999             ELSE
1000              	If g_body_debug_mode = 'Y' Then
1001 		write_log(LOG, '......Got Lock,paapimp is running, No Clean Up ');
1002 		end if;
1003             END IF;
1004           ELSE
1005             	If g_body_debug_mode = 'Y' Then
1006 		write_log(LOG, '......Could not get lock, No Clean Up');
1007 		end if;
1008           END IF;
1009 	ELSE
1010 		If g_body_debug_mode = 'Y' Then
1011 		write_log(LOG, '......Did not create unique lock');
1012 		end if;
1013         END IF;
1014 
1015 	G_err_stack := v_old_stack;
1016 
1017 EXCEPTION
1018         WHEN Others THEN
1019 		G_err_stack := v_old_stack;
1020         	G_err_code := SQLCODE;
1021 		raise;
1022 END cleanup;
1023 
1024 
1025 /*-----------------------Populate Transaction Interface Phase---------------------*/
1026 
1027 /*---------------------------- get_mrc_flag --------------------------------------*/
1028 /* This function will return 'Y' or 'N' depending upon whether MRC is used or not */
1029 /* and ot will also populate a PL/SQL table with reporting set of books ids and   */
1030 /* Reporting currencies                                                           */
1031 /*--------------------------------------------------------------------------------*/
1032 
1033 FUNCTION get_mrc_flag RETURN VARCHAR2 IS
1034 
1035 CURSOR c_reporting_sob (p_set_of_books_id IN NUMBER,
1036                         p_org_id          IN NUMBER) IS
1037   SELECT ledger_id, currency_code
1038   FROM   gl_alc_ledger_rships_v
1039   WHERE  source_ledger_id = p_set_of_books_id
1040   AND    application_id = 275
1041 --  AND    org_id = p_org_id commented for bug 9649314
1042   AND    relationship_enabled_flag = 'Y';
1043 
1044    l_sob NUMBER;
1045    l_org_id NUMBER;
1046    i BINARY_INTEGER := 0;
1047    v_old_stack VARCHAR2(630);
1048 
1049 BEGIN
1050 
1051    v_old_stack := G_err_stack;
1052    G_err_stack := G_err_stack || '->PAAPIMP_PKG.get_mrc_flag';
1053    G_err_code := 0;
1054 
1055    If g_body_debug_mode = 'Y' Then
1056    write_log(LOG, G_err_stack);
1057    end if;
1058 
1059    G_err_stage := 'CALLING PA_MC_CURRENCY_PKG.SET_OF_BOOKS FUNCTION';
1060    l_sob      := pa_mc_currency_pkg.set_of_books;
1061 
1062    G_err_stage := 'GET ORG_ID IN GET_MRC_FLAG';
1063    SELECT NVL(org_id,-99)
1064      INTO   l_org_id
1065      FROM pa_implementations;
1066 
1067    If g_body_debug_mode = 'Y' Then
1068    write_log(LOG,'set of book id is:'||l_sob||'org_id is:'||l_org_id);
1069    end if;
1070 
1071    FOR v_rsob IN c_reporting_sob (l_sob, l_org_id) LOOP
1072    BEGIN
1073 
1074     	i := i + 1;
1075         -- Bug 988355: g_rsob_tab is declared in the PA_MC_CURRENCY_PKG
1076        PA_MC_CURRENCY_PKG.g_rsob_tab(i).rsob_id := v_rsob.ledger_id;
1077        	PA_MC_CURRENCY_PKG.g_rsob_tab(i).rcurrency_code := v_rsob.currency_code;
1078 
1079    EXCEPTION
1080       WHEN OTHERS THEN
1081 	G_err_stack := v_old_stack;
1082 	G_err_code := SQLCODE;
1083        	RAISE;
1084    END; -- Cursor END
1085    END LOOP; -- End of Loop for cursor
1086 
1087    G_err_stack := v_old_stack;
1088 
1089    IF i = 0 then
1090      RETURN 'N';
1091    ELSE
1092      RETURN 'Y';
1093    END IF;
1094 
1095 END get_mrc_flag;
1096 
1097 
1098 FUNCTION create_new_org_transref (
1099     p_batch_name IN pa_transaction_interface.batch_name%TYPE,
1100     p_invoice_id IN ap_invoices.invoice_id%TYPE,
1101     p_invoice_distribution_id IN ap_invoice_distributions.invoice_distribution_id%TYPE)
1102       RETURN  pa_transaction_interface.orig_transaction_reference%TYPE IS
1103 
1104 BEGIN
1105 
1106     RETURN p_batch_name || '-' || to_char(p_invoice_id) || '-' || to_char(p_invoice_distribution_id, '099');
1107 
1108 END create_new_org_transref;
1109 
1110 PROCEDURE print_stat_and_submit_report IS
1111 
1112    req_id NUMBER;
1113    v_err_msg VARCHAR2(1000);
1114    v_old_stack VARCHAR2(630);
1115 
1116    l_number_of_copies NUMBER;
1117    l_print_style VARCHAR2(100);
1118    l_printer VARCHAR2(100);
1119    l_save_output_flag VARCHAR2(1);
1120    l_save_op_flag_bool boolean;
1121    result_print boolean;
1122 
1123 
1124 BEGIN
1125 
1126    /* Initialize all logging and debugging variables */
1127    v_old_stack := G_err_stack;
1128    G_err_stack := G_err_stack || '->PAAPIMP_PKG.print_stat_and_submit_report';
1129    G_err_code := 0;
1130    If g_body_debug_mode = 'Y' Then
1131    write_log(LOG, G_err_stack);
1132 
1133    write_log(LOG, 'TOTAL NUMBER OF BATCHES PROCESSED: ' || to_char(G_NUM_BATCHES_PROCESSED));
1134    write_log(LOG, 'TOTAL NUMBER OF INVOICES PROCESSED: ' || to_char(G_NUM_INVOICES_PROCESSED));
1135    write_log(LOG, 'TOTAL NUMBER OF INVOICE DISTRIBUTIONS PROCESSED: ' || to_char(G_NUM_DISTRIBUTIONS_PROCESSED));
1136    write_log(LOG, 'TOTAL NUMBER OF DISCOUNTS PROCESSED: '|| to_char(G_NUM_DISCOUNTS_PROCESSED));
1137    write_log(LOG, 'TOTAL NUMBER OF RECEIPTS PROCESSED: '||to_char(G_NUM_RCV_TXN_PROCESSED));
1138    write_log(LOG, 'TOTAL NUMBER OF RECEIPT TAX PROCESSED:'||to_char(G_NUM_RCVTAX_PROCESSED));
1139    end if;
1140 
1141    IF (G_OUTPUT = G_OUTPUT_FND) THEN
1142       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF INVOICES PROCESSED: ' || to_char(G_NUM_INVOICES_PROCESSED));
1143       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF INVOICE DISTRIBUTIONS PROCESSED: ' || to_char(G_NUM_DISTRIBUTIONS_PROCESSED));
1144       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF DISCOUNTS PROCESSED: '||to_char(G_NUM_DISCOUNTS_PROCESSED));
1145       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF RECEIPTS PROCESSED: '||to_char(G_NUM_RCV_TXN_PROCESSED));
1146       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF RECEIPT TAX PROCESSED: '||to_char(G_NUM_RCVTAX_PROCESSED));
1147 
1148       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, '----------------------------------------------------------------');
1149       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'For detail information of this interface, please review the following report.');
1150    END IF;
1151 
1152       result_print := FND_CONCURRENT.GET_REQUEST_PRINT_OPTIONS(G_REQUEST_ID,l_number_of_copies,l_print_style,l_printer,
1153                       l_save_output_flag);
1154       IF l_save_output_flag = 'Y' THEN
1155          l_save_op_flag_bool := TRUE;
1156       ELSE l_save_op_flag_bool := FALSE;
1157       END IF;
1158       result_print := FND_REQUEST.SET_PRINT_OPTIONS(l_printer,l_print_style,l_number_of_copies,
1159                       l_save_op_flag_bool,'N');
1160 
1161       -- MOAC changes for R12
1162       FND_REQUEST.set_org_id(G_ORG_ID);
1163 
1164       /* submit request to print report */
1165       /* IC Upgrade: Since we may process mutiple transaction source at once, we can not
1166             submit the transaction source parameter */
1167       req_id := FND_REQUEST.SUBMIT_REQUEST('PA', 'PAAPIMPR', '', '', FALSE, '', /*G_TRANSACTION_SOURCE,*/
1168           G_SYSTEM_LINKAGE, '', G_REQUEST_ID);
1169 
1170      IF (req_id = 0) THEN
1171          --FND_MESSAGE.RAISE_ERROR;
1172 	fnd_message.retrieve(v_err_msg);
1173          If g_body_debug_mode = 'Y' Then
1174         WRITE_LOG (LOG, '......Error in submitting request to print report......');
1175 	WRITE_LOG (LOG, 'Error Message: ' || v_err_msg || ' END of message.');
1176 	End if;
1177 	IF (G_OUTPUT = G_OUTPUT_FND) THEN
1178 	FND_FILE.PUT_LINE(FND_FILE.OUTPUT, '...An attempt to submit the status report of the process has failed.');
1179 	END IF;
1180      ELSE
1181          If g_body_debug_mode = 'Y' Then
1182 	 WRITE_LOG( LOG, '......Request to print report submitted, Request ID: '
1183                               || to_char(req_id) || '......');
1184         end if;
1185 		IF (G_OUTPUT = G_OUTPUT_FND) THEN
1186 		FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'A status report of this process has been submitted.  Request ID: '
1187 					|| to_char(req_id));
1188 		END IF;
1189       END IF;
1190 
1191       /* restore the old G_err_stack */
1192       G_err_stack := v_old_stack;
1193 
1194    EXCEPTION
1195       WHEN Others THEN
1196          G_err_stack := v_old_stack;
1197          G_err_code := SQLCODE;
1198          RAISE;
1199 
1200 	END print_stat_and_submit_report;
1201 
1202 
1203 PROCEDURE trans_import (
1204   p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
1205   p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
1206   p_interface_id IN pa_transaction_interface.interface_id%TYPE,
1207   p_user_id IN NUMBER) IS
1208 
1209   v_old_stack VARCHAR2(630);
1210 BEGIN
1211 
1212    v_old_stack := G_err_stack;
1213    G_err_stack := G_err_stack || '->PAAPIMP_PKG.trans_import';
1214    G_err_stage := 'TRANSACTION IMPORT';
1215    G_err_code := 0;
1216 
1217    write_log(LOG, '......Transaction Import Phase For ' || p_transaction_source);
1218    write_log(LOG, G_err_stack);
1219    savepoint import; /*savepoint added for bug 2138340. The data inserted into
1220                      transaction_interface table will be saved for further
1221                      use even if rollback occurs. */
1222 
1223 
1224    write_log(LOG,'log messages from transaction import ---------------------- ');
1225   -- Changed this to IMPORT from IMPORT1 for bug#
1226    PA_TRX_IMPORT.IMPORT(X_transaction_source =>p_transaction_source
1227                         ,X_batch => p_batch_name
1228                         , X_xface_id => p_interface_id
1229                         , X_userid =>p_user_id );
1230 
1231    G_err_stack := v_old_stack;
1232    /* added for bug 2138340 */
1233    write_log(LOG,'transaction import successful');
1234 
1235 
1236    EXCEPTION
1237       WHEN OTHERS THEN
1238          G_err_stack := v_old_stack;
1239          G_err_code := SQLCODE;
1240          write_log(LOG,'transaction import failed with sqlcode = ');
1241          write_log(LOG,   G_err_code);
1242          write_log(LOG, substr(SQLERRM, 1, 200));
1243 
1244         /* start changes for bug 2138340 */
1245 
1246         p_trans_import_failed := 'Y';
1247 
1248         ROLLBACK TO SAVEPOINT import; /* 2138340 - we will rollback whatever has been done by trx import */
1249         UPDATE pa_transaction_interface
1250            SET transaction_status_code = 'R',
1251                transaction_rejection_code = 'TRX_IMPORT_ABORTED'
1252          WHERE interface_id = p_interface_id
1253            AND transaction_status_code = 'P'
1254            AND transaction_source = p_transaction_source
1255            AND batch_name = p_batch_name;
1256 
1257        /* RAISE;   don't raise so that tieback can continue  */
1258 
1259 END trans_import;
1260 
1261 /*==========================================================================*/
1262 --The following section contains procedures for Supplier Inovice and Expense
1263 --Reports processing. The codes have compeletely changed for patchset K.
1264 --Starting from patchset K, all the processing will be performed in PL/SQL
1265 --tables within a certain batch size.
1266 --The logic of Invoice processing can be undestood as:
1267 -- 1) Update PA_addition_flag on AP Invoice distribution lines to 'Z' if sum of lines
1268 --    net to zero
1269 -- 2) Update PA_addition_flag on AP Invoice distribution lines to 'O' to lock the record
1270 -- 3) Transfer_inv_to_pa populates PA transaction_interface table and call trx import
1271 -- 4) Tieback procedure called to update invoice distribution lines after trx import
1272 
1273 /*----------------------Net Zero Adjustment Phase----------------------*/
1274 /*
1275 --
1276 -- This procedure marks the pa_addition_flag of all the invoice distributions
1277 -- to 'Z' if based on the grouping condition their amount net out to zero.
1278 -- The grouping columns used are
1279 --
1280 --  1. project_id
1281 --  2. task_id
1282 --  3. expenditure_type
1283 --  4. expenditure_organization_id
1284 --  5. expenditure_item_date
1285 --  6. dist_code_combination_id
1286 --  7. invoice_id
1287 --  8. accounting_date
1288 --  9. line_type_lookup_code
1289 --
1290 -- Invoice distributions whose pa_addition_flag is marked with 'Z' will not
1291 -- be pulled to Projects.
1292 --
1293 */
1294 
1295 
1296      /*
1297      --
1298      -- VI enhancments Check what type of invoices are we transferring and
1299      -- then do net zero adjustments accordingly.  If transferring expense
1300      -- report type invoices, then do net zero adjustment only for expense
1301      -- report type invoices.  If transferring vendor invoices then do net
1302      -- zero adjustments for all invoice types, like what PAVVIT has been
1303      -- doing.
1304      */
1305 
1306      /*  Bug 4193362
1307      --  Net Zero logic should not consider a line
1308      --  where po_distribution_id is populated and another line which does not have
1309      --  po_distribution_id. When project is enabled for budgetary control, this
1310      --  scenario will lead project commitment balances data corruption.
1311      --  So for grouping Net Zeroing lines, po_distribution_id should be considered.
1312      */
1313 
1314       --
1315       -- Bug 1594498
1316       -- Due to performance reasons the single update statement was
1317       -- broken up into two update statements based on if the program
1318       -- has the value of project id (If the user has given project number
1319       -- as one of the parameters).
1320       --
1321 
1322 
1323 PROCEDURE net_zero_adjustment IS
1324 
1325    v_old_stack       	VARCHAR2(630);
1326    l_assets_add_flag 	VARCHAR2(1);
1327    l_num_dists_updated	NUMBER;
1328 
1329 BEGIN
1330 
1331      v_old_stack := G_err_stack;
1332      G_err_stack := G_err_stack || '->PAAPIMP_PKG.net_zero_adjustment';
1333      G_err_code := 0;
1334      G_err_stage := 'Updating the invoices/expense reports to Z if the distributions are encumbered';
1335 
1336     If g_body_debug_mode = 'Y' Then
1337      write_log(LOG, G_err_stack);
1338     End If;
1339 
1340      IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
1341 
1342          IF G_PROJECT_ID IS NOT NULL THEN
1343 
1344             -- This update is to mark the pa addition flag of all invoice distributions
1345             -- which have encumbered flag of 'R' .
1346             -- If the invoice distribution has a encumbered flag value of 'R' then it is
1347             -- not encumbered and there exist no Budgetery control commitment records
1348             -- for these in PA
1349 
1350 	   If g_body_debug_mode = 'Y' Then
1351              G_err_stage := 'Updating the expense reports to Z for project ';
1352              write_log(LOG, G_err_stage);
1353            End If;
1354             /* Modified the hint on following update statement for bug 6920705 */
1355             UPDATE /*+ index(dist AP_INVOICE_DISTRIBUTIONS_N14) */ ap_invoice_distributions dist
1356                  SET dist.pa_addition_flag 		=	'Z',
1357                      request_id 				=	G_REQUEST_ID,
1358                      last_update_date			=	SYSDATE,  --bug 3905111
1359                      last_updated_by			=	G_USER_ID,
1360                      last_update_login			=	G_USER_ID,
1361                      program_id					=	G_PROG_ID,
1362                      program_application_id		=	G_PROG_APPL_ID,
1363                      program_update_date		=	SYSDATE, --bug 3905111
1364                      dist.assets_addition_flag 	=	decode(G_Assets_Addition_flag,'P','P',
1365                                                    		     dist.assets_addition_flag)
1366      	       WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D', 'I', 'J', 'K', 'M', 'P', 'V', 'X', 'W')
1367                  AND dist.posted_flag = 'Y'  -- removed the append  || '' for bug 13599091
1368                  AND dist.project_id  = G_PROJECT_ID
1369                  /* 12773881 AND   'N' = (select cost_rate_flag
1370                                 from pa_expenditure_types
1371                                where expenditure_type = dist.expenditure_type)*/
1372 
1373 		       --Bug 14320909 starts
1374 	               AND dist.Accounting_Date <= nvl(G_GL_DATE,dist.Accounting_Date)   /*GSCC*/
1375                        AND dist.Expenditure_Item_Date <= NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date)
1376                        --Bug 14320909 ends
1377 
1378                  AND EXISTS (SELECT invoice_id
1379                                FROM AP_INVOICES inv
1380                               WHERE inv.invoice_id = DIST.invoice_id
1381                                 AND inv.invoice_type_lookup_code = 'EXPENSE REPORT')
1382                  AND ( --( nvl(dist.encumbered_flag,'N') = 'R' ) OR /* Coomented for bug#13940879 */
1383 		    (dist.line_type_lookup_code ='NONREC_TAX' AND nvl(dist.base_amount,dist.amount)=0)) /*Added for bug:7622893*/
1384                  AND NOT EXISTS (SELECT NULL
1385                               FROM   ap_invoice_distributions dist1
1386                               WHERE  dist.parent_reversal_id is not null
1387                               AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1388                               AND    dist1.pa_addition_flag = 'T'
1389                               AND    dist1.encumbered_flag = 'R'
1390 			      )
1391                  --Update historical data for Cash Based Acctng
1392                  AND  (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'));
1393 
1394     	   l_num_dists_updated := SQL%ROWCOUNT ;
1395 
1396 	   If g_body_debug_mode = 'Y' Then
1397            	write_log(LOG, 'Updated '||to_char(l_num_dists_updated)|| 'invoice distributions to Z for Encumbrance');
1398            end if;
1399 
1400 /*Bug 13602288: Self Assessed Tax Changes - NetZero Adjustments need to be handled for Expense Reprort SAT Lines as well*/
1401 
1402  UPDATE ap_self_assessed_tax_dist dist
1403                  SET dist.pa_addition_flag 		=	'Z',
1404                      request_id 				=	G_REQUEST_ID,
1405                      last_update_date			=	SYSDATE,
1406                      last_updated_by			=	G_USER_ID,
1407                      last_update_login			=	G_USER_ID,
1408                      program_id					=	G_PROG_ID,
1409                      program_application_id		=	G_PROG_APPL_ID,
1410                      program_update_date		=	SYSDATE,
1411                      dist.assets_addition_flag 	=	decode(G_Assets_Addition_flag,'P','P',dist.assets_addition_flag)
1412      	       WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D', 'I', 'J', 'K', 'M', 'P', 'V', 'X', 'W')
1413                  AND dist.posted_flag||'' = 'Y'
1414                  AND dist.project_id  = G_PROJECT_ID
1415                                  AND EXISTS (SELECT invoice_id
1416                                FROM AP_INVOICES inv
1417                               WHERE inv.invoice_id = DIST.invoice_id
1418                                 AND inv.invoice_type_lookup_code = 'EXPENSE REPORT')
1419                  AND ( -- ( nvl(dist.encumbered_flag,'N') = 'R' ) OR  /* Commented for bug#13940879 */
1420 	            (dist.line_type_lookup_code ='NONREC_TAX' AND nvl(dist.base_amount,dist.amount)=0))
1421                  AND NOT EXISTS (SELECT NULL
1422                               FROM   ap_self_assessed_tax_dist dist1
1423                               WHERE  dist.parent_reversal_id is not null
1424                               AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1425                               AND    dist1.pa_addition_flag = 'T'
1426                               AND    dist1.encumbered_flag = 'R'
1427 			      );
1428 
1429  l_num_dists_updated := l_num_dists_updated + SQL%ROWCOUNT;
1430 
1431   If g_body_debug_mode = 'Y' Then
1432            	write_log(LOG, 'Updated '||to_char(l_num_dists_updated)|| ' total invoice distributions to Z for Encumbrance');
1433            end if;
1434 
1435          ELSE   /* Project Id is not passed */
1436 
1437             -- This update is to mark the pa addition flag of all invoice distributions
1438             -- which have encumbered flag of 'R'
1439             -- If the invoice distribution has a encumbered flag value of 'R' then it is
1440             -- not encumbered and there exist no Budgetery control commitment records
1441             -- for these in PA
1442 
1443 	   If g_body_debug_mode = 'Y' Then
1444              G_err_stage := 'Updating the expense reports to Z for all';
1445              write_log(LOG, G_err_stage);
1446            End If;
1447 
1448 
1449             UPDATE /*+ index(dist AP_INVOICE_DISTRIBUTIONS_N14)*/ ap_invoice_distributions dist /*Added for bug 6327185*/
1450                SET 	dist.pa_addition_flag 		= 	'Z',
1451                 	request_id 					= 	G_REQUEST_ID,
1452                 	last_update_date			=	SYSDATE,  --bug 3905111
1453                 	last_updated_by				= 	G_USER_ID,
1454                 	last_update_login			= 	G_USER_ID,
1455                 	program_id					= 	G_PROG_ID,
1456                 	program_application_id		= 	G_PROG_APPL_ID,
1457                 	program_update_date			=	SYSDATE, --bug 3905111
1458                 	dist.assets_addition_flag 	= 	DECODE(NVL(
1459                                                   (SELECT ptype.project_type_class_code
1460                                                   FROM pa_project_types_all ptype,
1461                                                     pa_projects_all proj
1462                                                   WHERE ptype.project_type = proj.project_type
1463                                                   AND (ptype.org_id        = proj.org_id
1464                                                   OR proj.org_id          IS NULL)
1465                                                   AND proj.project_id      = dist.project_id
1466                                                   ),'ERROR'), 'CAPITAL','P', dist.assets_addition_flag)   ---bug 13834151
1467 	    WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D', 'I', 'J', 'K', 'M', 'P', 'V', 'X', 'W')
1468               AND dist.posted_flag = 'Y' -- removed the append  || '' for bug 13599091
1469               AND dist.project_id > 0
1470 
1471 	               --Bug 14320909 starts
1472 	               AND dist.Accounting_Date <= nvl(G_GL_DATE,dist.Accounting_Date)   /*GSCC*/
1473                        AND dist.Expenditure_Item_Date <= NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date)
1474                        --Bug 14320909 ends
1475 
1476               /* 12773881 AND 'N' = (select cost_rate_flag
1477                            from pa_expenditure_types
1478                           where expenditure_type = dist.expenditure_type) */
1479               AND EXISTS (SELECT invoice_id
1480                               FROM AP_INVOICES inv
1481                              WHERE inv.invoice_id = DIST.invoice_id
1482                                AND inv.invoice_type_lookup_code = 'EXPENSE REPORT')
1483                 AND ( --( nvl(dist.encumbered_flag,'N') = 'R' ) OR  /* Commented for bug#13940879 */
1484 	           (dist.line_type_lookup_code ='NONREC_TAX' AND nvl(dist.base_amount,dist.amount)=0)) /*Added for bug:7622893*/
1485               AND NOT EXISTS (SELECT NULL
1486                               FROM   ap_invoice_distributions dist1
1487                               WHERE  dist.parent_reversal_id is not null
1488                               AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1489                               AND    dist1.pa_addition_flag = 'T'
1490                               AND    dist1.encumbered_flag = 'R'
1491 			     )
1492               --Update historical data for Cash Based Acctng
1493               AND  (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'));
1494 
1495     	   l_num_dists_updated := SQL%ROWCOUNT ;
1496 
1497 	   If g_body_debug_mode = 'Y' Then
1498            	write_log(LOG, 'Updated '||to_char(l_num_dists_updated)|| 'invoice distributions to Z for Encumbrance');
1499            end if;
1500 
1501 
1502 	   /*Bug 13602288: Self Assessed Tax Changes -  Netzero Adjustment to be marked when the */
1503 
1504 	    UPDATE  ap_self_assessed_tax_dist dist
1505                SET 	dist.pa_addition_flag 		= 	'Z',
1506                 	request_id 					= 	G_REQUEST_ID,
1507                 	last_update_date			=	SYSDATE,
1508                 	last_updated_by				= 	G_USER_ID,
1509                 	last_update_login			= 	G_USER_ID,
1510                 	program_id					= 	G_PROG_ID,
1511                 	program_application_id		= 	G_PROG_APPL_ID,
1512                 	program_update_date			=	SYSDATE,
1513                 	dist.assets_addition_flag 	= 	(SELECT decode(ptype.project_type_class_code,
1514                                             				'CAPITAL','P', dist.assets_addition_flag)
1515                            							   FROM pa_project_types_all ptype, pa_projects_all proj
1516                            							  WHERE ptype.project_type = proj.project_type
1517                            								AND (ptype.org_id = proj.org_id
1518 														 OR proj.org_id is null)
1519                            								AND proj.project_id = dist.project_id)
1520 	    WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D', 'I', 'J', 'K', 'M', 'P', 'V', 'X', 'W')
1521               AND dist.posted_flag||'' = 'Y'
1522               AND dist.project_id > 0
1523               AND EXISTS (SELECT invoice_id
1524                               FROM AP_INVOICES inv
1525                              WHERE inv.invoice_id = DIST.invoice_id
1526                                AND inv.invoice_type_lookup_code = 'EXPENSE REPORT')
1527                 AND ( -- ( nvl(dist.encumbered_flag,'N') = 'R' ) OR   /* Commented for bug#13940879 */
1528 	            (dist.line_type_lookup_code ='NONREC_TAX' AND nvl(dist.base_amount,dist.amount)=0))
1529               AND NOT EXISTS (SELECT NULL
1530                               FROM   ap_self_assessed_tax_dist dist1
1531                               WHERE  dist.parent_reversal_id is not null
1532                               AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1533                               AND    dist1.pa_addition_flag = 'T'
1534                               AND    dist1.encumbered_flag = 'R'
1535 			    );
1536 
1537   l_num_dists_updated := l_num_dists_updated + SQL%ROWCOUNT ;
1538 
1539     If g_body_debug_mode = 'Y' Then
1540            	write_log(LOG, 'Updated '||to_char(l_num_dists_updated)|| ' total (SAT + normal) invoice distributions to Z for Encumbrance');
1541            end if;
1542       END IF;
1543       --
1544       -- End of If section checking if G_PROJECT_ID is not null
1545       --
1546 
1547     ELSE
1548       --
1549       -- Bug 1594498
1550       -- Due to performance reasons the single update statement was
1551       -- broken up into two update statements based on if the program
1552       -- has the value of project id (If the user has given project number
1553       -- as one of the parameters).
1554       --
1555 
1556       IF G_PROJECT_ID IS NOT NULL THEN
1557 
1558 /* Restructured the query below for performance bug 3026625 */
1559 
1560         /* Added the following update for bug 3569296 */
1561         -- The program should update the pa_addition_flag for all encumbered lines marked as R to netzero adj flag.
1562         -- R indicates a line to be ignored by encumbrance and validation code because neither the original nor the
1563         -- reversal distributions were looked at and they offset each other so, they can be ignored and marked as Z.
1564         -- (This is set only if the parent one is not validated as well. Otherwise the reversal one will also be encumbered).
1565         -- Since these lines have been not encumbered, there exist no Budgetery control commitment records for these in PA
1566 
1567 	   If g_body_debug_mode = 'Y' Then
1568              G_err_stage := 'Updating invoice distributions to Z for project';
1569              write_log(LOG, G_err_stage);
1570            End If;
1571           /* Modified the hint on following update statement for bug 6920705 */
1572          UPDATE /*+ index(dist AP_INVOICE_DISTRIBUTIONS_N14) */ ap_invoice_distributions dist
1573             SET dist.pa_addition_flag = 'Z',
1574                 request_id = G_REQUEST_ID,
1575                 last_update_date=SYSDATE, --bug 3905111
1576                 last_updated_by= G_USER_ID,
1577                 last_update_login= G_USER_ID,
1578                 program_id= G_PROG_ID,
1579                 program_application_id= G_PROG_APPL_ID,
1580                 program_update_date=SYSDATE, --bug 3905111
1581                 dist.assets_addition_flag = decode(G_Assets_Addition_flag,'P','P',
1582                                                    dist.assets_addition_flag)
1583          WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'P','V', 'X', 'W')
1584            AND dist.posted_flag = 'Y' -- removed the append  || '' for bug 13599091
1585            AND dist.project_id = G_PROJECT_ID
1586 
1587                        --Bug 14320909 starts
1588 	               AND dist.Accounting_Date <= nvl(G_GL_DATE,dist.Accounting_Date)   /*GSCC*/
1589                        AND dist.Expenditure_Item_Date <= NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date)
1590                        --Bug 14320909 ends
1591 
1592            AND ( -- ( nvl(dist.encumbered_flag,'N') = 'R' ) OR  /* Commented for bug#13940879 */
1593 	           (dist.line_type_lookup_code ='NONREC_TAX' AND nvl(dist.base_amount,dist.amount)=0)) /*Added for bug:7622893*/
1594            --Update historical data for Cash Based Acctng
1595            AND  (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
1596            AND NOT EXISTS (SELECT NULL
1597                            FROM   ap_invoice_distributions dist1
1598                            WHERE  dist.parent_reversal_id is not null
1599                            AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1600                            AND    dist1.pa_addition_flag = 'T'
1601                            AND    dist1.encumbered_flag = 'R'
1602 			   )
1603            AND EXISTS (SELECT invoice_id
1604                          FROM AP_INVOICES inv
1605                         WHERE inv.invoice_id = DIST.invoice_id
1606                           AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT');
1607 
1608       	write_log(LOG, 'Updated '||to_char(SQL%ROWCOUNT)|| 'invoice distributions to Z for Encumbrance');
1609 
1610   -- The program should update the pa_addition_flag for all encumbered lines marked as R to netzero adj flag.
1611         -- R indicates a line to be ignored by encumbrance and validation code because neither the original nor the
1612         -- reversal distributions were looked at and they offset each other so, they can be ignored and marked as Z.
1613         -- (This is set only if the parent one is not validated as well. Otherwise the reversal one will also be encumbered).
1614         -- Since these lines have been not encumbered, there exist no Budgetery control commitment records for these in PA
1615 
1616 	   If g_body_debug_mode = 'Y' Then
1617              G_err_stage := 'Updating Self Assessed Tax  invoice distributions to Z for project';
1618              write_log(LOG, G_err_stage);
1619            End If;
1620 
1621 
1622 /*Bug 13602288: Self Assessed Tax Changes*/
1623 UPDATE  AP_SELF_ASSESSED_TAX_DIST dist
1624             SET dist.pa_addition_flag = 'Z',
1625                 request_id = G_REQUEST_ID,
1626                 last_update_date=SYSDATE,
1627                 last_updated_by= G_USER_ID,
1628                 last_update_login= G_USER_ID,
1629                 program_id= G_PROG_ID,
1630                 program_application_id= G_PROG_APPL_ID,
1631                 program_update_date=SYSDATE,
1632                 dist.assets_addition_flag = decode(G_Assets_Addition_flag,'P','P',
1633                                                    dist.assets_addition_flag)
1634          WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'P','V', 'X', 'W')
1635            AND dist.posted_flag||'' = 'Y'
1636            AND dist.project_id = G_PROJECT_ID
1637            AND (  -- ( nvl(dist.encumbered_flag,'N') = 'R' ) OR  /* Commented for bug#13940879 */
1638 	           (dist.line_type_lookup_code ='NONREC_TAX' AND nvl(dist.base_amount,dist.amount)=0))
1639            AND NOT EXISTS (SELECT NULL
1640                            FROM   AP_SELF_ASSESSED_TAX_DIST dist1
1641                            WHERE  dist.parent_reversal_id is not null
1642                            AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1643                            AND    dist1.pa_addition_flag = 'T'
1644                            AND    dist1.encumbered_flag = 'R'
1645 			 )
1646            AND EXISTS (SELECT invoice_id
1647                          FROM AP_INVOICES inv
1648                         WHERE inv.invoice_id = DIST.invoice_id
1649                           AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT');
1650 
1651       	write_log(LOG, 'Updated '||to_char(SQL%ROWCOUNT)|| 'Self Assessed Tax  invoice distributions to Z for Encumbrance');
1652 
1653      ELSE /* G_PROJECT_ID is null */
1654 
1655 
1656             -- This update is to mark the pa addition flag of all invoice distributions
1657             -- which have encumbered flag of 'R' or reversal flag of 'Y' to 'Z'.
1658             -- Encumbrance flag of 'R' or reversal flag of 'Y' indicates that they are
1659             -- exact reversal of another invoice distribution.
1660             -- If the invoice distribution has a encumbered flag value of 'R' then it is
1661             -- not encumbered and there exist no Budgetery control commitment records
1662             -- for these in PA
1663 
1664 	   If g_body_debug_mode = 'Y' Then
1665              G_err_stage := 'Updating invoice distributions to Z for all';
1666              write_log(LOG, G_err_stage);
1667            End If;
1668 
1669             UPDATE /*+ index(dist AP_INVOICE_DISTRIBUTIONS_N14)*/ ap_invoice_distributions dist /*Added for bug 6327185*/
1670                SET 	dist.pa_addition_flag 	= 	'Z',
1671                 	request_id 				= 	G_REQUEST_ID,
1672                 	last_update_date		=	SYSDATE,  --bug 3905111
1673                 	last_updated_by			= 	G_USER_ID,
1674                 	last_update_login		= 	G_USER_ID,
1675                 	program_id				= 	G_PROG_ID,
1676                 	program_application_id	= 	G_PROG_APPL_ID,
1677                 	program_update_date		=	SYSDATE,  --bug 3905111
1678                 	dist.assets_addition_flag = DECODE(NVL(
1679                                                   (SELECT ptype.project_type_class_code
1680                                                   FROM pa_project_types_all ptype,
1681                                                     pa_projects_all proj
1682                                                   WHERE ptype.project_type = proj.project_type
1683                                                   AND (ptype.org_id        = proj.org_id
1684                                                   OR proj.org_id          IS NULL)
1685                                                   AND proj.project_id      = dist.project_id
1686                                                   ),'ERROR'), 'CAPITAL','P', dist.assets_addition_flag)   --- bug 13834151
1687              WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'P','V', 'X', 'W')
1688                AND   dist.posted_flag||'' = 'Y'
1689                AND   dist.project_id > 0
1690 
1691                        --Bug 14320909 starts
1692 	               AND dist.Accounting_Date <= nvl(G_GL_DATE,dist.Accounting_Date)   /*GSCC*/
1693                        AND dist.Expenditure_Item_Date <= NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date)
1694                        --Bug 14320909 ends
1695 
1696                AND ( -- ( nvl(dist.encumbered_flag,'N') = 'R' ) OR  /* Commented for bug#13940879 */
1697 	        (dist.line_type_lookup_code ='NONREC_TAX' AND nvl(dist.base_amount,dist.amount)=0)) /*Added for bug:7622893*/
1698                --Update historical data for Cash Based Acctng
1699                AND  (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
1700                AND NOT EXISTS (SELECT NULL
1701                               FROM   ap_invoice_distributions dist1
1702                               WHERE  dist.parent_reversal_id is not null
1703                               AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1704                               AND    dist1.pa_addition_flag = 'T'
1705                               AND    dist1.encumbered_flag = 'R'
1706 			    )
1707            AND EXISTS (SELECT invoice_id
1708                          FROM AP_INVOICES inv
1709                         WHERE inv.invoice_id = DIST.invoice_id
1710                           AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT');
1711 
1712       	write_log(LOG, 'Updated '||to_char(SQL%ROWCOUNT)|| 'invoice distributions to Z for Encumbrance');
1713 
1714 
1715 	   If g_body_debug_mode = 'Y' Then
1716              G_err_stage := 'Updating Self Assessed Tax  invoice distributions to Z for all';
1717              write_log(LOG, G_err_stage);
1718            End If;
1719 
1720 /*Bug 13602288: Self Assessed Tax Changes*/
1721 UPDATE AP_SELF_ASSESSED_TAX_DIST dist
1722                SET 	dist.pa_addition_flag 	= 	'Z',
1723                 	request_id 				= 	G_REQUEST_ID,
1724                 	last_update_date		=	SYSDATE,
1725                 	last_updated_by			= 	G_USER_ID,
1726                 	last_update_login		= 	G_USER_ID,
1727                 	program_id				= 	G_PROG_ID,
1728                 	program_application_id	= 	G_PROG_APPL_ID,
1729                 	program_update_date		=	SYSDATE,
1730                 	dist.assets_addition_flag = (SELECT decode(ptype.project_type_class_code,
1731                                             			'CAPITAL','P', dist.assets_addition_flag)
1732                            						   FROM pa_project_types_all ptype, pa_projects_all proj
1733                            						  WHERE ptype.project_type = proj.project_type
1734                            						    AND (ptype.org_id = proj.org_id OR
1735                                    						proj.org_id is null)
1736                            						    AND proj.project_id = dist.project_id)
1737              WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'P','V', 'X', 'W')
1738                AND   dist.posted_flag = 'Y'  -- removed the append  || '' for bug 13599091
1739                AND   dist.project_id > 0
1740                AND ( -- ( nvl(dist.encumbered_flag,'N') = 'R' ) OR  /* Commented for bug#13940879 */
1741 	        (dist.line_type_lookup_code ='NONREC_TAX' AND nvl(dist.base_amount,dist.amount)=0))
1742                               AND NOT EXISTS (SELECT NULL
1743                               FROM   AP_SELF_ASSESSED_TAX_DIST dist1
1744                               WHERE  dist.parent_reversal_id is not null
1745                               AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1746                               AND    dist1.pa_addition_flag = 'T'
1747                               AND    dist1.encumbered_flag = 'R'
1748 			     )
1749            AND EXISTS (SELECT invoice_id
1750                          FROM AP_INVOICES inv
1751                         WHERE inv.invoice_id = DIST.invoice_id
1752                           AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT');
1753 
1754       	write_log(LOG, 'Updated '||to_char(SQL%ROWCOUNT)|| 'Self Assessed Tax  invoice distributions to Z for Encumbrance');
1755 
1756      END IF;
1757       --
1758       -- End of If section checking if G_PROJECT_ID is not null
1759       --
1760 
1761      END IF;
1762 G_err_stack := v_old_stack;
1763 
1764 EXCEPTION
1765         WHEN Others THEN
1766                /*
1767                --
1768                -- Exceptions occured in this procedure must be raised by the
1769                -- UPDATE statement, most likely a fatal error like 'rollback
1770                -- segment exceeded' error which should cause the program to
1771                -- terminate
1772                --
1773                */
1774 
1775 	       G_err_stack := v_old_stack;
1776                G_err_code := SQLCODE;
1777 	       raise;
1778 
1779 
1780 END net_zero_adjustment;
1781 
1782 FUNCTION check_prepay_fully_applied(p_prepay_dist_id in NUMBER, is_self_assessed_tax in VARCHAR2)
1783    RETURN VARCHAR2 IS
1784 
1785   l_prepay_rem_amt      NUMBER;
1786 
1787 BEGIN
1788 
1789   If  is_self_assessed_tax = 'N'  then
1790        SELECT prepay_amount_remaining
1791        INTO   l_prepay_rem_amt
1792        FROM   ap_invoice_distributions_All
1793        WHERE  invoice_distribution_id = p_prepay_dist_id;
1794    else
1795 	SELECT prepay_amount_remaining
1796        INTO   l_prepay_rem_amt
1797        FROM   ap_self_assessed_tax_dist_All
1798        WHERE  invoice_distribution_id = p_prepay_dist_id;
1799    end if;
1800    -- ==================================================================================
1801    -- Bug: 5393523
1802    --    : R12.PJ:XB6:QA:APL: STANDARD INVOICES / PREPAYMENTS NOT SHOWN AS COMMITTMENT
1803    --      Unpaid prepayments invoice has NULL prepay_amount_remaining and it should not
1804    --      mislead as fully applied prepayment.
1805    -- ==================================================================================
1806    IF l_prepay_rem_amt is NULL THEN
1807       RETURN 'N' ;
1808    ELSIF l_prepay_rem_amt = 0 THEN
1809       RETURN 'Y';
1810    ELSE
1811       RETURN 'N';
1812    END IF;
1813 
1814 EXCEPTION
1815 
1816 WHEN Others THEN
1817 
1818    write_log(LOG, 'Exception in check_prepay_fully_applied');
1819    G_err_code := SQLCODE;
1820    RAISE;
1821 
1822 END check_prepay_fully_applied;
1823 
1824 /*-----------------------Marking Distribution Phase---------------------*/
1825 
1826 PROCEDURE mark_PAflag_O IS
1827 
1828         v_old_stack VARCHAR2(630);
1829 
1830 BEGIN
1831 
1832      v_old_stack := G_err_stack;
1833      G_err_stack := G_err_stack || '->PAAPIMP_PKG.mark_PAflag_O';
1834      G_err_code := 0;
1835      G_err_stage := 'UPDATING INVOICE DISTRIBUTIONS-Marking Process';
1836 
1837      write_log(LOG, G_err_stack);
1838       /* VI enhancements */
1839 
1840 
1841      IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
1842 
1843                    --
1844                    -- This section is for Expense Reports
1845                    --
1846 
1847           write_log(LOG, 'Marking Expense Report type invoices for processing...');
1848                    --
1849                    -- Due to performance reasons the single update statement was
1850                    -- broken up into two update statements based on if the program
1851                    -- has the value of project id (If the user has given project number
1852                    -- as one of the parameters).
1853                    --
1854 
1855       IF G_PROJECT_ID IS NOT NULL THEN
1856 
1857         -- In Cash Based Accounting all historical Invoices and their adjustments in AP will continue to be interfaced as Invoice distributions
1858         -- and NOT Payment lines
1859 
1860         IF G_ACCTNG_METHOD = 'C' THEN --CAsh BAsed Accounting
1861 
1862           write_log(LOG, 'Marking invoices to O for Historical Data interface in Cash Based Acctng');
1863 --code changes for bug 14769043
1864           UPDATE  AP_Invoice_distributions DIST
1865              SET  DIST.Pa_Addition_Flag ='O',
1866                   request_id = G_REQUEST_ID,
1867                   last_update_date=SYSDATE,
1868                   last_updated_by=G_USER_ID,
1869                   last_update_login= G_USER_ID,
1870                   program_id= G_PROG_ID,
1871                   program_application_id= G_PROG_APPL_ID,
1872                   program_update_date=SYSDATE
1873            WHERE  DIST.Posted_Flag = 'Y' -- removed the append  || '' for bug 13599091
1874              AND  DIST.Pa_Addition_Flag IN
1875                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
1876              AND DIST.project_id > 0
1877              AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
1878              AND ((
1879                   exists (SELECT NULL
1880                            FROM AP_INVOICES inv,
1881                                 AP_Invoice_distributions DIST1,
1882                                 PO_VENDORS vend
1883                           WHERE inv.invoice_id = DIST1.invoice_id
1884                             AND DIST1.invoice_distribution_id = DIST.invoice_distribution_id
1885                             AND INV.payment_status_flag = 'Y'                                   -- Flag indicated FULLY paid inv
1886                             AND DIST1.historical_flag = 'Y'                                     -- process historical dist as invoices in Cash Based Acctng
1887                             AND inv.vendor_id = vend.vendor_id
1888                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
1889                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1890                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
1891                                  OR
1892                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
1893                                  AND inv.source in ('CREDIT CARD','Both Pay')
1894                                   /*   AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0 commented for bug#8977795 */)
1895                                   OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'
1896                                   and exists (
1897                                   select 1 from PER_PEOPLE PPL,
1898                                   PER_ASSIGNMENTS ASGN ,PER_PERSON_TYPES PTYPE  where
1899                                    ASGN.VENDOR_ID = vend.VENDOR_ID
1900                                   and PPL.PERSON_ID = ASGN.PERSON_ID
1901                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
1902                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
1903                                   )))
1904                  OR
1905                   (EXISTS ( SELECT NULL
1906                            FROM  PO_VENDORS vend1,
1907                                  ap_invoices inv1,
1908                                  ap_invoice_distributions dist2
1909                            WHERE inv1.invoice_id = dist2.invoice_id
1910                            AND   inv1.invoice_id = dist.invoice_id
1911                            AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
1912                            AND   dist2.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
1913                            AND   dist2.pa_addition_flag = 'Y'
1914                            AND   inv1.vendor_id = vend1.vendor_id
1915                            AND ((inv1.invoice_type_lookup_code = G_INVOICE_TYPE
1916                                  AND inv1.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1917                                  AND (vend1.employee_id IS NOT NULL or nvl(inv1.paid_on_behalf_employee_id,0) > 0))
1918                                 OR
1919                                 (inv1.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
1920                                  AND inv1.source  in ('CREDIT CARD','Both Pay')
1921                                   /*   AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0 commented for bug#8977795 */)
1922                                   OR  (INV1.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'				/*code changes for bug 14769043*/
1923                                   and exists (
1924                                   select 1 from PER_PEOPLE_F PPL,
1925                                   PER_ASSIGNMENTS_F ASGN ,PER_PERSON_TYPES PTYPE  where
1926                                    ASGN.VENDOR_ID = vend1.VENDOR_ID
1927                                   and PPL.PERSON_ID = ASGN.PERSON_ID
1928                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
1929                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
1930                                   )))
1931                  )
1932              AND DIST.project_id = G_PROJECT_ID
1933              AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date))
1934              AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date));
1935 
1936         G_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
1937         write_log(LOG, 'Number of Historical rows marked to O: ' || to_char(SQL%ROWCOUNT));
1938 
1939 --code changes for bug 14769043
1940 /*Bug 13602288: Self Assessed Tax Changes*/
1941 	UPDATE ap_self_assessed_tax_dist DIST
1942              SET  DIST.Pa_Addition_Flag ='O',
1943                   request_id = G_REQUEST_ID,
1944                   last_update_date=SYSDATE,
1945                   last_updated_by=G_USER_ID,
1946                   last_update_login= G_USER_ID,
1947                   program_id= G_PROG_ID,
1948                   program_application_id= G_PROG_APPL_ID,
1949                   program_update_date=SYSDATE
1950            WHERE  DIST.Posted_Flag||'' = 'Y'
1951              AND  DIST.Pa_Addition_Flag IN
1952                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
1953              AND DIST.project_id > 0
1954              AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
1955              AND ((
1956                   exists (SELECT NULL
1957                            FROM AP_INVOICES inv,
1958                                 ap_self_assessed_tax_dist DIST1,
1959                                 PO_VENDORS vend
1960                           WHERE inv.invoice_id = DIST1.invoice_id
1961                             AND DIST1.invoice_distribution_id = DIST.invoice_distribution_id
1962                             AND INV.payment_status_flag = 'Y'                                   -- Flag indicated FULLY paid inv
1963                             --AND DIST1.historical_flag = 'Y'                                     -- process historical dist as invoices in Cash Based Acctng
1964                             AND inv.vendor_id = vend.vendor_id
1965                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
1966                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1967                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
1968                                  OR
1969                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
1970                                  AND inv.source in ('CREDIT CARD','Both Pay')
1971 				)
1972         OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'		/*code changes for bug 14769043*/
1973                                   and exists (
1974                                   select 1 from PER_PEOPLE_F PPL,
1975                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
1976                                    ASGN.VENDOR_ID = vend.VENDOR_ID
1977                                   and PPL.PERSON_ID = ASGN.PERSON_ID
1978                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
1979                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
1980         )))
1981                  OR
1982                   (EXISTS ( SELECT NULL
1983                            FROM  PO_VENDORS vend1,
1984                                  ap_invoices inv1,
1985                                  ap_self_assessed_tax_dist dist2
1986                            WHERE inv1.invoice_id = dist2.invoice_id
1987                            AND   inv1.invoice_id = dist.invoice_id
1988                            AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
1989                            AND   dist2.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
1990                            AND   dist2.pa_addition_flag = 'Y'
1991                            AND   inv1.vendor_id = vend1.vendor_id
1992                            AND ((inv1.invoice_type_lookup_code = G_INVOICE_TYPE
1993                                  AND inv1.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1994                                  AND (vend1.employee_id IS NOT NULL or nvl(inv1.paid_on_behalf_employee_id,0) > 0))
1995                                 OR
1996                                 (inv1.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
1997                                  and INV1.source  in ('CREDIT CARD','Both Pay')
1998                                 )
1999                                 OR  (INV1.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'			/*code changes for bug 14769043*/
2000                                   and exists (
2001                                   select 1 from PER_PEOPLE_F PPL,
2002                                   PER_ASSIGNMENTS_F ASGN ,PER_PERSON_TYPES PTYPE  where
2003                                    ASGN.VENDOR_ID = vend1.VENDOR_ID
2004                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2005                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2006                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2007                                 )))
2008                  )
2009              AND DIST.project_id = G_PROJECT_ID
2010              AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date))
2011              AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date));
2012 
2013 	G_DISTRIBUTIONS_MARKED :=  nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
2014         write_log(LOG, 'Number of Self Assessed and Historical rows marked to O: ' || to_char(SQL%ROWCOUNT));
2015 
2016 
2017         /* Historical Data Processing for Prepayments */
2018         /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
2019            Pre Rel12 Upgrade should also be brought into Projects */
2020 
2021           write_log(LOG, 'Marking Historical Prepayments for processing...');
2022 
2023             UPDATE ap_invoice_distributions_all dist
2024             SET    dist.pa_addition_flag = 'O',
2025                    request_id = G_REQUEST_ID,
2026                    last_update_date=SYSDATE,
2027                    last_updated_by= G_USER_ID,
2028                    last_update_login= G_USER_ID,
2029                    program_id= G_PROG_ID,
2030                    program_application_id= G_PROG_APPL_ID,
2031                    program_update_date=SYSDATE
2032             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
2033             AND   DIST.project_id > 0
2034             AND   dist.posted_flag = 'Y'
2035             AND   dist.project_id = G_PROJECT_ID
2036             --AND   dist.line_type_lookup_code = 'PREPAY'
2037             AND   dist.line_type_lookup_code <> 'REC_TAX'
2038             AND   dist.prepay_distribution_id is not null
2039             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
2040             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
2041             AND   exists (SELECT NULL
2042                            FROM AP_INVOICES inv,
2043                                 PO_VENDORS vend
2044                           WHERE inv.invoice_id = DIST.invoice_id
2045                             AND inv.vendor_id = vend.vendor_id
2046                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2047                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2048                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2049                                  OR
2050                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
2051                                  AND inv.source in ('CREDIT CARD','Both Pay')
2052                               /*   AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0 commented for bug#8977795 */ )
2053                               OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'					/*code changes for bug 14769043*/
2054                                   and exists (
2055                                   select 1 from PER_PEOPLE_F PPL,
2056                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2057                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2058                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2059                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2060                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2061                               ))
2062             AND   exists(SELECT inv.invoice_id
2063                          FROM    AP_INVOICES inv,
2064                                  AP_Invoice_Distributions_all aid
2065                           WHERE aid.invoice_id = inv.invoice_id
2066                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
2067                             AND aid.historical_flag = 'Y'
2068                             AND aid.pa_addition_flag = 'Y'
2069                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
2070                  );
2071 
2072             G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
2073             write_log(LOG, 'Number of Historical PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2074 
2075 /*Bug 13602288: Self Assessed Tax Changes*/
2076 UPDATE ap_self_assessed_tax_dist_all dist
2077             SET    dist.pa_addition_flag = 'O',
2078                    request_id = G_REQUEST_ID,
2079                    last_update_date=SYSDATE,
2080                    last_updated_by= G_USER_ID,
2081                    last_update_login= G_USER_ID,
2082                    program_id= G_PROG_ID,
2083                    program_application_id= G_PROG_APPL_ID,
2084                    program_update_date=SYSDATE
2085             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
2086             AND   DIST.project_id > 0
2087             AND   dist.posted_flag = 'Y'
2088             AND   dist.project_id = G_PROJECT_ID
2089             --AND   dist.line_type_lookup_code = 'PREPAY'
2090             AND   dist.line_type_lookup_code <> 'REC_TAX'
2091             AND   dist.prepay_distribution_id is not null
2092             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
2093             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
2094             AND   exists (SELECT NULL
2095                            FROM AP_INVOICES inv,
2096                                 PO_VENDORS vend
2097                           WHERE inv.invoice_id = DIST.invoice_id
2098                             AND inv.vendor_id = vend.vendor_id
2099                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2100                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2101                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2102                                  OR
2103                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
2104                                  AND inv.source in ('CREDIT CARD','Both Pay')
2105 				)
2106         OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'				/*code changes for bug 14769043*/
2107                                   and exists (
2108                                   select 1 from PER_PEOPLE_F PPL,
2109                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2110                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2111                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2112                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2113                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))))
2114             AND   exists(SELECT inv.invoice_id
2115                          FROM    AP_INVOICES inv,
2116                                  ap_self_assessed_tax_dist_all aid
2117                           WHERE aid.invoice_id = inv.invoice_id
2118                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
2119                             --aND aid.historical_flag = 'Y'
2120                             AND aid.pa_addition_flag = 'Y'
2121                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
2122                  );
2123 
2124             G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
2125             write_log(LOG, 'Number of Historical SAT PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2126 
2127           ELSE --Accounting Method is Accrual
2128 
2129           write_log(LOG, 'Marking Expense Report type invoices for processing - Accrual Acct');
2130 
2131              UPDATE  AP_Invoice_distributions DIST
2132                 SET  DIST.Pa_Addition_Flag ='O',
2133                      request_id = G_REQUEST_ID,
2134                      last_update_date=SYSDATE,
2135                      last_updated_by=G_USER_ID,
2136                      last_update_login= G_USER_ID,
2137                      program_id= G_PROG_ID,
2138                      program_application_id= G_PROG_APPL_ID,
2139                      program_update_date=SYSDATE
2140               WHERE  DIST.Posted_Flag = 'Y' -- removed the append  || '' for bug 13599091
2141                 AND  DIST.Pa_Addition_Flag IN
2142                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
2143                 AND DIST.project_id > 0
2144                 AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2145                 AND exists (SELECT NULL
2146                               FROM AP_INVOICES inv,
2147                                    PO_VENDORS vend
2148                              WHERE inv.invoice_id = DIST.invoice_id
2149                                AND inv.vendor_id = vend.vendor_id
2150                                AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2151                                      AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2152                                      AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2153                                     OR
2154                                    (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
2155                                     AND inv.source   in ('CREDIT CARD','Both Pay')
2156                                     /*   AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0 commented for bug#8977795 */)
2157                                     OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'					/*code changes for bug 14769043*/
2158                                   and exists (
2159                                   select 1 from PER_PEOPLE_F PPL,
2160                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2161                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2162                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2163                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2164                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2165                                     ))
2166                AND DIST.project_id = G_PROJECT_ID
2167                AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date)) /*GSCC*//* added trunc for the bug 6623163 */
2168                AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date));   /*GSCC*//* added trunc for the bug 6623163 */
2169 
2170                G_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
2171 
2172 
2173 /*Bug 13602288: Self Assessed Tax Changes*/
2174  write_log(LOG, 'Marking Expense Report type invoices sat lines for processing - Accrual Acct');
2175 
2176              UPDATE  ap_self_assessed_tax_dist DIST
2177                 SET  DIST.Pa_Addition_Flag ='O',
2178                      request_id = G_REQUEST_ID,
2179                      last_update_date=SYSDATE,
2180                      last_updated_by=G_USER_ID,
2181                      last_update_login= G_USER_ID,
2182                      program_id= G_PROG_ID,
2183                      program_application_id= G_PROG_APPL_ID,
2184                      program_update_date=SYSDATE
2185               WHERE  DIST.Posted_Flag||'' = 'Y'
2186                 AND  DIST.Pa_Addition_Flag IN
2187                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
2188                 AND DIST.project_id > 0
2189                 AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2190                 AND exists (SELECT NULL
2191                               FROM AP_INVOICES inv,
2192                                    PO_VENDORS vend
2193                              WHERE inv.invoice_id = DIST.invoice_id
2194                                AND inv.vendor_id = vend.vendor_id
2195                                AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2196                                      AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2197                                      AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2198                                     OR
2199                                    (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
2200                                     AND inv.source   in ('CREDIT CARD','Both Pay')
2201 				    )
2202             OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'					/*code changes for bug 14769043*/
2203                                   and exists (
2204                                   select 1 from PER_PEOPLE_F PPL,
2205                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2206                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2207                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2208                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2209                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2210             ))
2211                AND DIST.project_id = G_PROJECT_ID
2212                AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date))
2213                AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date));
2214 
2215                G_DISTRIBUTIONS_MARKED :=  nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
2216 		write_log(LOG, 'Number of SAT Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2217 
2218         End If; --End of CAsh BAsed Accounting
2219 
2220       ELSE /* G_PROJECT_ID IS NULL */
2221 
2222         IF G_ACCTNG_METHOD = 'C' THEN
2223 
2224           write_log(LOG, 'Marking invoices to O for Historical Data interface in Cash Based Acctng');
2225 
2226           UPDATE  AP_Invoice_distributions DIST
2227              SET  DIST.Pa_Addition_Flag ='O',
2228                   request_id = G_REQUEST_ID,
2229                   last_update_date=SYSDATE,
2230                   last_updated_by=G_USER_ID,
2231                   last_update_login= G_USER_ID,
2232                   program_id= G_PROG_ID,
2233                   program_application_id= G_PROG_APPL_ID,
2234                   program_update_date=SYSDATE
2235            WHERE  DIST.Posted_Flag = 'Y' -- removed the append  || '' for bug 13599091
2236              AND  DIST.Pa_Addition_Flag IN
2237                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
2238              AND DIST.project_id > 0
2239              AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2240              AND (
2241                   (exists (SELECT NULL
2242                            FROM AP_INVOICES inv,
2243                                 AP_Invoice_distributions DIST1,
2244                                 PO_VENDORS vend
2245                           WHERE inv.invoice_id = DIST1.invoice_id
2246                             AND DIST1.invoice_distribution_id = DIST.invoice_distribution_id
2247                             AND INV.payment_status_flag = 'Y'                                   -- Flag indicated FULLY paid inv
2248                             AND DIST1.historical_flag = 'Y'                                     --process historical dist as invoices in Cash Based Acctng
2249                             AND inv.vendor_id = vend.vendor_id
2250                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2251                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2252                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2253                                  OR
2254                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
2255                                  AND inv.source    in ('CREDIT CARD','Both Pay')
2256                                  /*   AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0 commented for bug#8977795 */)
2257                                  OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'					/*code changes for bug 14769043*/
2258                                   and exists (
2259                                   select 1 from PER_PEOPLE_F PPL,
2260                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2261                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2262                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2263                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2264                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2265                                  )))
2266                  OR
2267                   (EXISTS ( SELECT NULL
2268                            FROM  PO_VENDORS vend1,
2269                                  ap_invoices inv1, ap_invoice_distributions dist2
2270                            WHERE inv1.invoice_id = dist2.invoice_id
2271                            AND   inv1.invoice_id = dist.invoice_id
2272                            AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
2273                            AND   dist2.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
2274                            AND   dist2.pa_addition_flag = 'Y'
2275                            AND   inv1.vendor_id = vend1.vendor_id
2276                            AND ((inv1.invoice_type_lookup_code = G_INVOICE_TYPE
2277                                  AND inv1.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2278                                  AND (vend1.employee_id IS NOT NULL or nvl(inv1.paid_on_behalf_employee_id,0) > 0))
2279                                 OR
2280                                (inv1.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
2281                                 AND inv1.source in ('CREDIT CARD','Both Pay')
2282                                 /*   AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0 commented for bug#8977795 */)
2283                                 OR  (INV1.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'				/*code changes for bug 14769043*/
2284                                   and exists (
2285                                   select 1 from PER_PEOPLE_F PPL,
2286                                   PER_ASSIGNMENTS_F ASGN ,PER_PERSON_TYPES PTYPE  where
2287                                    ASGN.VENDOR_ID = vend1.VENDOR_ID
2288                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2289                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2290                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2291                                 )))
2292                  )
2293              AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date)) /*GSCC*/
2294              AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date));   /*GSCC*/ /*Bug 7342936. Right parenthesis were missing on left side of expression*/
2295         G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
2296         write_log(LOG, 'Number of Historical rows marked to O: ' || to_char(SQL%ROWCOUNT));
2297 
2298 	/*Bug 13602288: Self Assessed Tax Changes*/
2299           write_log(LOG, 'Marking invoices to O for SAT Data interface in Cash Based Acctng');
2300 
2301           UPDATE ap_self_assessed_tax_dist DIST
2302              SET  DIST.Pa_Addition_Flag ='O',
2303                   request_id = G_REQUEST_ID,
2304                   last_update_date=SYSDATE,
2305                   last_updated_by=G_USER_ID,
2306                   last_update_login= G_USER_ID,
2307                   program_id= G_PROG_ID,
2308                   program_application_id= G_PROG_APPL_ID,
2309                   program_update_date=SYSDATE
2310            WHERE  DIST.Posted_Flag||'' = 'Y'
2311              AND  DIST.Pa_Addition_Flag IN
2312                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
2313              AND DIST.project_id > 0
2314              AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2315              AND (
2316                   (exists (SELECT NULL
2317                            FROM AP_INVOICES inv,
2318                                 AP_self_assessed_tax_dist DIST1,
2319                                 PO_VENDORS vend
2320                           WHERE inv.invoice_id = DIST1.invoice_id
2321                             AND DIST1.invoice_distribution_id = DIST.invoice_distribution_id
2322                             AND INV.payment_status_flag = 'Y'                                   -- Flag indicated FULLY paid inv
2323                             --AND DIST1.historical_flag = 'Y'                                     --process historical dist as invoices in Cash Based Acctng
2324                             AND inv.vendor_id = vend.vendor_id
2325                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2326                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2327                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2328                                  OR
2329                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
2330                                  AND inv.source    in ('CREDIT CARD','Both Pay')
2331                               )
2332                               OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'				/*code changes for bug 14769043*/
2333                                   and exists (
2334                                   select 1 from PER_PEOPLE_F PPL,
2335                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2336                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2337                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2338                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2339                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2340                               )))
2341                  OR
2342                   (EXISTS ( SELECT NULL
2343                            FROM  PO_VENDORS vend1,
2344                                  ap_invoices inv1, ap_invoice_distributions dist2
2345                            WHERE inv1.invoice_id = dist2.invoice_id
2346                            AND   inv1.invoice_id = dist.invoice_id
2347                            AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
2348                            AND   dist2.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
2349                            AND   dist2.pa_addition_flag = 'Y'
2350                            AND   inv1.vendor_id = vend1.vendor_id
2351                            AND ((inv1.invoice_type_lookup_code = G_INVOICE_TYPE
2352                                  AND inv1.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2353                                  AND (vend1.employee_id IS NOT NULL or nvl(inv1.paid_on_behalf_employee_id,0) > 0))
2354                                 OR
2355                                (inv1.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
2356                                 AND inv1.source in ('CREDIT CARD','Both Pay')
2357                                 )
2358                                 OR  (INV1.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'				/*code changes for bug 14769043*/
2359                                   and exists (
2360                                   select 1 from PER_PEOPLE_F PPL,
2361                                   PER_ASSIGNMENTS_F ASGN ,PER_PERSON_TYPES PTYPE  where
2362                                    ASGN.VENDOR_ID = vend1.VENDOR_ID
2363                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2364                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2365                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2366                                 )))
2367                  )
2368              AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date))
2369              AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date));
2370 
2371         G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
2372         write_log(LOG, 'Number of SAT rows marked to O: ' || to_char(SQL%ROWCOUNT));
2373 
2374         /* Historical Data Processing for Prepayments */
2375         /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
2376            Pre Rel12 Upgrade should also be brought into Projects */
2377 
2378           write_log(LOG, 'Marking Historical Prepayments for processing...');
2379 
2380             UPDATE ap_invoice_distributions dist
2381             SET    dist.pa_addition_flag = 'O',
2382                    request_id = G_REQUEST_ID,
2383                    last_update_date=SYSDATE,
2384                    last_updated_by= G_USER_ID,
2385                    last_update_login= G_USER_ID,
2386                    program_id= G_PROG_ID,
2387                    program_application_id= G_PROG_APPL_ID,
2388                    program_update_date=SYSDATE
2389             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
2390             AND   DIST.project_id > 0
2391             AND   dist.posted_flag = 'Y'
2392             --AND   dist.line_type_lookup_code = 'PREPAY'
2393             AND   dist.line_type_lookup_code <> 'REC_TAX'
2394             AND   dist.prepay_distribution_id is not null
2395             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
2396             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
2397             AND   exists (SELECT NULL
2398                            FROM AP_INVOICES_ALL inv,
2399                                 PO_VENDORS vend
2400                           WHERE inv.invoice_id = DIST.invoice_id
2401                             AND inv.vendor_id = vend.vendor_id
2402                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2403                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2404                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2405                                  OR
2406                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
2407                                  AND inv.source  in ('CREDIT CARD','Both Pay')
2408                                  /*   AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0 commented for bug#8977795 */)
2409                                  OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'					/*code changes for bug 14769043*/
2410                                   and exists (
2411                                   select 1 from PER_PEOPLE_F PPL,
2412                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2413                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2414                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2415                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2416                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2417                                  ))
2418             AND   exists(SELECT inv.invoice_id
2419                          FROM    AP_INVOICES_ALL inv,
2420                                  AP_Invoice_Distributions_all aid
2421                           WHERE aid.invoice_id = inv.invoice_id
2422                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
2423                             AND aid.historical_flag = 'Y'
2424                             AND aid.pa_addition_flag = 'Y'
2425                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
2426                   );
2427 
2428             G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
2429             write_log(LOG, 'Number of Historical PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2430 
2431 	    /*Bug 13602288: Self Assessed Tax Changes*/
2432 	UPDATE ap_self_assessed_tax_dist dist
2433             SET    dist.pa_addition_flag = 'O',
2434                    request_id = G_REQUEST_ID,
2435                    last_update_date=SYSDATE,
2436                    last_updated_by= G_USER_ID,
2437                    last_update_login= G_USER_ID,
2438                    program_id= G_PROG_ID,
2439                    program_application_id= G_PROG_APPL_ID,
2440                    program_update_date=SYSDATE
2441             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
2442             AND   DIST.project_id > 0
2443             AND   dist.posted_flag = 'Y'
2444             --AND   dist.line_type_lookup_code = 'PREPAY'
2445             AND   dist.line_type_lookup_code <> 'REC_TAX'
2446             AND   dist.prepay_distribution_id is not null
2447             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
2448             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
2449             AND   exists (SELECT NULL
2450                            FROM AP_INVOICES_ALL inv,
2451                                 PO_VENDORS vend
2452                           WHERE inv.invoice_id = DIST.invoice_id
2453                             AND inv.vendor_id = vend.vendor_id
2454                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2455                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2456                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2457                                  OR
2458                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
2459                                  AND inv.source  in ('CREDIT CARD','Both Pay'))
2460                                  OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'				/*code changes for bug 14769043*/
2461                                   and exists (
2462                                   select 1 from PER_PEOPLE_F PPL,
2463                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2464                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2465                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2466                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2467                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2468                                  ))
2469                                 AND   exists(SELECT inv.invoice_id
2470                          FROM    AP_INVOICES_ALL inv,
2471                                  ap_self_assessed_tax_dist_all aid
2472                           WHERE aid.invoice_id = inv.invoice_id
2473                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
2474                             --AND aid.historical_flag = 'Y'
2475                             AND aid.pa_addition_flag = 'Y'
2476                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
2477                   );
2478 
2479             G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
2480             write_log(LOG, 'Number of SAT PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2481 
2482           ELSE --Accounting Method is Accrual
2483 
2484           write_log(LOG, 'Marking Expense Report type invoices for processing - Accrual Acct');
2485 
2486             UPDATE  /*+ index(DIST AP_INVOICE_DISTRIBUTIONS_N14)*/ AP_Invoice_distributions DIST /*Added for bug 6327185*/
2487                SET  DIST.Pa_Addition_Flag ='O', /*Bug#2168903*/
2488                     request_id = G_REQUEST_ID,
2489                     last_update_date=SYSDATE,  --bug 3905111
2490                     last_updated_by=G_USER_ID,
2491                     last_update_login= G_USER_ID,
2492                     program_id= G_PROG_ID,
2493                     program_application_id= G_PROG_APPL_ID,
2494                     program_update_date=SYSDATE   --bug 3905111
2495              WHERE  DIST.Posted_Flag = 'Y' -- removed the append  || '' for bug 13599091
2496                AND  DIST.Pa_Addition_Flag IN                           /*Bug#1727504*/
2497                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
2498                AND DIST.project_id > 0
2499                AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2500 	       AND exists (SELECT invoice_id
2501                              FROM AP_INVOICES_ALL inv,
2502                                   PO_VENDORS vend
2503                             WHERE inv.invoice_id = DIST.invoice_id
2504                               AND inv.vendor_id = vend.vendor_id
2505                               AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2506                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2507                                     AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2508                                    OR
2509                                   (inv.invoice_type_lookup_code    in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*//*Bug 4099522*/
2510                                    AND inv.source  in ('CREDIT CARD','Both Pay')
2511                                   /* AND nvl(inv.paid_on_behalf_employee_id,0) > 0 commented for bug#8977795 */ )
2512                                   OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'		/*code changes for bug 14769043*/
2513                                   and exists (
2514                                   select 1 from PER_PEOPLE_F PPL,
2515                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2516                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2517                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2518                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2519                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2520                                   ))
2521                AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date)) /*GSCC*//* added trunc for the bug 6623163 */
2522                AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date)); /*GSCC*/
2523 
2524             G_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
2525             write_log(LOG, 'Number of rows marked to O: ' || to_char(SQL%ROWCOUNT));
2526 
2527 /*Bug 13602288: Self Assessed Tax Changes*/
2528             UPDATE ap_self_assessed_tax_dist DIST
2529                SET  DIST.Pa_Addition_Flag ='O',
2530                     request_id = G_REQUEST_ID,
2531                     last_update_date=SYSDATE,
2532                     last_updated_by=G_USER_ID,
2533                     last_update_login= G_USER_ID,
2534                     program_id= G_PROG_ID,
2535                     program_application_id= G_PROG_APPL_ID,
2536                     program_update_date=SYSDATE
2537              WHERE  DIST.Posted_Flag||'' = 'Y'
2538                AND  DIST.Pa_Addition_Flag IN
2539                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
2540                AND DIST.project_id > 0
2541                AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2542 	       AND exists (SELECT invoice_id
2543                              FROM AP_INVOICES_ALL inv,
2544                                   PO_VENDORS vend
2545                             WHERE inv.invoice_id = DIST.invoice_id
2546                               AND inv.vendor_id = vend.vendor_id
2547                               AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
2548                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
2549                                     AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
2550                                    OR
2551                                   (inv.invoice_type_lookup_code    in ('STANDARD','CREDIT','MIXED')
2552                                    AND inv.source  in ('CREDIT CARD','Both Pay')
2553 				  )
2554           OR  (INV.INVOICE_TYPE_LOOKUP_CODE = 'EXPENSE REPORT'		/*code changes for bug 14769043*/
2555                                   and exists (
2556                                   select 1 from PER_PEOPLE_F PPL,
2557                                   PER_ASSIGNMENTS_f ASGN ,PER_PERSON_TYPES PTYPE  where
2558                                    ASGN.VENDOR_ID = vend.VENDOR_ID
2559                                   and PPL.PERSON_ID = ASGN.PERSON_ID
2560                                   and PTYPE.PERSON_TYPE_ID = PPL.PERSON_TYPE_ID
2561                                   and PTYPE.SYSTEM_PERSON_TYPE in ('OTHER','CWK')))
2562           ))
2563                AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date))
2564                AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date));
2565 
2566             G_DISTRIBUTIONS_MARKED :=  nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
2567             write_log(LOG, 'Number of SAT rows marked to O: ' || to_char(SQL%ROWCOUNT));
2568 
2569           END IF; --End of CAsh BAsed Accounting
2570 
2571         END IF; /* END IF Project ID */
2572 
2573      ELSE
2574 
2575 	   write_log(LOG, 'Marking supplier invoices for processing...');
2576 
2577              --
2578              -- Due to performance reasons the single update statement was
2579              -- broken up into two update statements based on if the program
2580              -- has the value of project id (If the user has given project number
2581              -- as one of the parameters).
2582              --
2583 
2584        IF G_PROJECT_ID IS NOT NULL THEN
2585 
2586           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
2587         If g_body_debug_mode = 'Y' Then
2588 	   write_log(LOG, 'Marking supplier invoices for project = '||G_PROJECT_ID);
2589 	   write_log(LOG, 'Marking supplier invoices for G_GL_DATE = '||G_GL_DATE);
2590 	   write_log(LOG, 'Marking supplier invoices for G_TRANSACTION_DATE = '||G_TRANSACTION_DATE);
2591         End If;
2592 
2593          -- For CASH based Accntg we will continue to bring Historical data as Invoices and not Payments
2594          -- Any reversals made to the historical Invoices should also be brought into projects as Invoices and not Payments
2595 
2596          IF G_ACCTNG_METHOD = 'C' THEN
2597 
2598 	   write_log(LOG, 'Marking invoices to O for Historical Data interface in Cash Based Acctng');
2599 
2600            UPDATE AP_Invoice_Distributions DIST
2601               SET DIST.Pa_Addition_Flag = 'O',
2602                   request_id = G_REQUEST_ID,
2603                   last_update_date=SYSDATE,
2604                   last_updated_by=G_USER_ID,
2605                   last_update_login=G_USER_ID,
2606                   program_id=G_PROG_ID,
2607                   program_application_id=G_PROG_APPL_ID,
2608                   program_update_date=SYSDATE
2609             WHERE DIST.Posted_Flag = 'Y'
2610               AND DIST.Pa_Addition_Flag IN
2611                   ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
2612               AND DIST.project_id > 0
2613               AND trunc(DIST.Accounting_Date) <= trunc(nvl(G_GL_DATE,DIST.Accounting_Date))   /*GSCC*//* added trunc for the bug 6623163 */
2614               AND trunc(DIST.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,DIST.Expenditure_Item_Date))       /*GSCC*/ /* added trunc for the bug 6623163 */
2615               AND DIST.project_id = G_PROJECT_ID
2616               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2617               AND (
2618                   EXISTS (
2619                     SELECT NULL
2620                     FROM ap_invoices_all inv,
2621                          po_distributions_all PO,
2622                          ap_invoice_distributions_all dist2
2623                     WHERE inv.invoice_id = dist2.invoice_id
2624                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
2625                     AND dist2.invoice_id = DIST.invoice_id
2626                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
2627                     AND inv.payment_status_flag = 'Y'                                -- Flag indicates that Invoice has been FULLY paid
2628                     AND dist2.historical_flag = 'Y'                                    --Process Historical data as Invoices in Cash based
2629                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
2630                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
2631                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2632                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2633                     AND inv.source not  in ('CREDIT CARD','Both Pay') /* Added for bug 8977795 */
2634                     AND ( nvl(INV.source, 'xx' ) NOT IN (
2635                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS') /* Removed 'Oracle Project Accounting' */
2636 			  or dist2.line_type_lookup_code = 'NONREC_TAX'
2637 			 )
2638                     )
2639                   OR
2640                   EXISTS (
2641                     SELECT NULL
2642                     FROM ap_invoices_all inv1,
2643                          ap_invoice_distributions_all dist3
2644                     WHERE inv1.invoice_id = dist3.invoice_id
2645                     AND   inv1.invoice_id = dist.invoice_id
2646                     AND   inv1.invoice_type_lookup_code <> 'EXPENSE REPORT'
2647                     AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
2648                     AND   dist3.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
2649                     AND   dist3.pa_addition_flag = 'Y')
2650                   )
2651                 /* Bug 6353803: Added the following for this bug. */
2652   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2653                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2654 		    AND NOT EXISTS (SELECT 'X'
2655 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2656 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2657 				    AND pod.po_line_id = pol.po_line_id
2658 				    AND   si.inventory_item_id = pol.item_id
2659 				    AND   si.comms_nl_trackable_flag = 'Y'
2660 				    AND   (si.organization_id = pod.org_id
2661 						OR   /* Added for bug 13714500  */
2662                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
2663                                                  where pll.po_header_id = pod.po_header_id
2664 						              and pll.po_line_id = pod.po_line_id)
2665 						)
2666 				    )
2667 		    AND NOT EXISTS (SELECT 'X'
2668 			      FROM
2669 				ap_invoice_distributions apdist,
2670 				po_distributions pod,
2671 				mtl_system_items si,
2672 				po_lines_all pol
2673 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2674                                     = apdist.INVOICE_DISTRIBUTION_ID
2675 				  and apdist.po_distribution_id = pod.po_distribution_id
2676 				  and pod.po_line_id = pol.po_line_id
2677 				  and si.inventory_item_id = pol.item_id
2678 				  AND   si.comms_nl_trackable_flag = 'Y'
2679 				  AND   (si.organization_id = pod.org_id
2680 						OR /* Added for bug 13714500 */
2681                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
2682                                                  where pll.po_header_id = pod.po_header_id
2683 						              and pll.po_line_id = pod.po_line_id)
2684 						)
2685 					     )
2686 		    )
2687                   )/* Start changes for bug#14320909 */
2688 		        AND NOT EXISTS (select 'X' from rcv_receiving_sub_ledger rcv_sub,
2689 			po_distributions_all po_dist1
2690 			where  po_dist1.CODE_COMBINATION_ID   =rcv_sub.CODE_COMBINATION_ID
2691 			AND    rcv_sub.ACTUAL_FLAG           = 'A'
2692 			and    rcv_sub.pa_addition_flag ='Y'
2693 			AND    to_char(DIST.po_distribution_id) = rcv_sub.reference3
2694 			and    DIST.po_distribution_id = po_dist1.po_distribution_id)
2695 			/* End changes for bug#14320909 */;
2696 
2697               G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
2698               write_log(LOG, 'Number of Historical Invoice Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2699 
2700 
2701         /* Historical Data Processing for Prepayments */
2702         /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
2703            Pre Rel12 Upgrade should also be brought into Projects */
2704 
2705 	   write_log(LOG, 'Marking PREPAYMENT invoices in Cash Based Acctng');
2706 
2707             UPDATE ap_invoice_distributions_all dist
2708             SET    dist.pa_addition_flag = 'O',
2709                    request_id = G_REQUEST_ID,
2710                    last_update_date=SYSDATE,
2711                    last_updated_by= G_USER_ID,
2712                    last_update_login= G_USER_ID,
2713                    program_id= G_PROG_ID,
2714                    program_application_id= G_PROG_APPL_ID,
2715                    program_update_date=SYSDATE
2716             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
2717             AND   DIST.project_id > 0
2718             AND   dist.posted_flag = 'Y'
2719             AND   dist.project_id = G_PROJECT_ID
2720             --AND   dist.line_type_lookup_code = 'PREPAY'
2721             AND   dist.line_type_lookup_code <> 'REC_TAX'
2722             AND   dist.prepay_distribution_id is not null
2723             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
2724             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
2725             AND   EXISTS (
2726                     SELECT NULL
2727                     FROM ap_invoices inv
2728                     WHERE inv.invoice_id = dist.invoice_id
2729                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2730                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2731                     AND inv.source not  in ('CREDIT CARD','Both Pay') /* Added for bug 8977795 */
2732                     AND nvl(INV.source, 'xx' ) NOT IN (
2733                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')  ) /* Removed 'Oracle Project Accounting' */
2734             AND   exists(SELECT inv.invoice_id
2735                            FROM AP_INVOICES inv,
2736                                 AP_Invoice_Distributions_all aid
2737                           WHERE aid.invoice_id = inv.invoice_id
2738                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
2739                             AND aid.historical_flag = 'Y'
2740                             AND aid.pa_addition_flag = 'Y'
2741                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
2742                             AND aid.project_id = G_PROJECT_ID)
2743                 /* Bug 6353803: Added the following for this bug. */
2744   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2745                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2746 		    AND NOT EXISTS (SELECT 'X'
2747 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2748 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2749 				    AND pod.po_line_id = pol.po_line_id
2750 				    AND   si.inventory_item_id = pol.item_id
2751 				    AND   si.comms_nl_trackable_flag = 'Y'
2752 				    AND    (si.organization_id = pod.org_id
2753 						OR /* Added for bug 13714500 */
2754                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
2755                                                  where pll.po_header_id = pod.po_header_id
2756 						              and pll.po_line_id = pod.po_line_id)
2757 						)
2758 				    )
2759 		    AND NOT EXISTS (SELECT 'X'
2760 			      FROM
2761 				ap_invoice_distributions apdist,
2762 				po_distributions pod,
2763 				mtl_system_items si,
2764 				po_lines_all pol
2765 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2766                                     = apdist.INVOICE_DISTRIBUTION_ID
2767 				  and apdist.po_distribution_id = pod.po_distribution_id
2768 				  and pod.po_line_id = pol.po_line_id
2769 				  and si.inventory_item_id = pol.item_id
2770 				  AND   si.comms_nl_trackable_flag = 'Y'
2771 				  AND    (si.organization_id = pod.org_id
2772 						OR /* Added for bug 13714500 */
2773                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
2774                                                  where pll.po_header_id = pod.po_header_id
2775 						              and pll.po_line_id = pod.po_line_id)
2776 						)
2777 					     )
2778 		    )
2779                   );
2780 
2781             G_DISTRIBUTIONS_MARKED :=nvl(G_DISTRIBUTIONS_MARKED ,0) +  SQL%ROWCOUNT;
2782             write_log(LOG, 'Number of Historical PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2783 
2784 
2785 
2786 	    /* Historical Data Processing for Prepayments  --- Bug 13602288: Self Assessed Tax  Changes */
2787         /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
2788            Pre Rel12 Upgrade should also be brought into Projects */
2789 
2790 	   write_log(LOG, 'Marking PREPAYMENT Self Assessed Tax  lines in Cash Based Acctng');
2791 
2792             UPDATE AP_SELF_ASSESSED_TAX_DIST_ALL dist
2793             SET    dist.pa_addition_flag = 'O',
2794                    request_id = G_REQUEST_ID,
2795                    last_update_date=SYSDATE,
2796                    last_updated_by= G_USER_ID,
2797                    last_update_login= G_USER_ID,
2798                    program_id= G_PROG_ID,
2799                    program_application_id= G_PROG_APPL_ID,
2800                    program_update_date=SYSDATE
2801             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
2802             AND   DIST.project_id > 0
2803             AND   dist.posted_flag = 'Y'
2804             AND   dist.project_id = G_PROJECT_ID
2805            AND   dist.line_type_lookup_code <> 'REC_TAX'
2806             AND   dist.prepay_distribution_id is not null
2807             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
2808             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
2809             AND   EXISTS (
2810                     SELECT NULL
2811                     FROM ap_invoices inv
2812                     WHERE inv.invoice_id = dist.invoice_id
2813                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2814                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2815                     AND inv.source not  in ('CREDIT CARD','Both Pay')
2816                     AND nvl(INV.source, 'xx' ) NOT IN (
2817                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')  )
2818             AND   exists(SELECT inv.invoice_id
2819                            FROM AP_INVOICES inv,
2820                                 AP_SELF_ASSESSED_TAX_DIST_ALL aid
2821                           WHERE aid.invoice_id = inv.invoice_id
2822                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
2823                           --  AND aid.historical_flag = 'Y'  /*doubt*/
2824                             AND aid.pa_addition_flag = 'Y'
2825                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id
2826                             AND aid.project_id = G_PROJECT_ID)
2827                        AND   (pa_nl_installed.is_nl_installed = 'N'
2828                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2829 		    AND NOT EXISTS (SELECT 'X'
2830 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2831 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2832 				    AND pod.po_line_id = pol.po_line_id
2833 				    AND   si.inventory_item_id = pol.item_id
2834 				    AND   si.comms_nl_trackable_flag = 'Y'
2835 				    AND   (si.organization_id = pod.org_id
2836 						OR /* Added for bug 13714500 */
2837                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
2838                                                  where pll.po_header_id = pod.po_header_id
2839 						              and pll.po_line_id = pod.po_line_id)
2840 						)
2841 				    )
2842 		    AND NOT EXISTS (SELECT 'X'
2843 			      FROM
2844 				AP_SELF_ASSESSED_TAX_DIST_ALL apdist,
2845 				po_distributions pod,
2846 				mtl_system_items si,
2847 				po_lines_all pol
2848 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2849                                     = apdist.INVOICE_DISTRIBUTION_ID
2850 				  and apdist.po_distribution_id = pod.po_distribution_id
2851 				  and pod.po_line_id = pol.po_line_id
2852 				  and si.inventory_item_id = pol.item_id
2853 				  AND   si.comms_nl_trackable_flag = 'Y'
2854 				  AND   (si.organization_id = pod.org_id
2855 						OR /* Added for bug 13714500 */
2856                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
2857                                                  where pll.po_header_id = pod.po_header_id
2858 						              and pll.po_line_id = pod.po_line_id)
2859 						)
2860 					     )
2861 		    )
2862                   );
2863 
2864             G_DISTRIBUTIONS_MARKED :=nvl(G_DISTRIBUTIONS_MARKED ,0) +  SQL%ROWCOUNT;
2865             write_log(LOG, 'Number of Historical PREPAY Self Assessed Tax  Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2866 
2867 
2868          ELSE -- Accrual BAsed Acctng
2869 
2870 	   write_log(LOG, 'Marking invoices in Accrual based Acctng');
2871 
2872            UPDATE AP_Invoice_Distributions DIST
2873               SET DIST.Pa_Addition_Flag = 'O',
2874                   request_id = G_REQUEST_ID,
2875                   last_update_date=SYSDATE,
2876                   last_updated_by=G_USER_ID,
2877                   last_update_login=G_USER_ID,
2878                   program_id=G_PROG_ID,
2879                   program_application_id=G_PROG_APPL_ID,
2880                   program_update_date=SYSDATE
2881             WHERE DIST.Posted_Flag = 'Y'
2882               AND DIST.Pa_Addition_Flag IN
2883                    ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
2884               AND DIST.project_id > 0
2885               AND trunc(DIST.Accounting_Date) <= trunc(nvl(G_GL_DATE,DIST.Accounting_Date))   /*GSCC*/
2886               AND trunc(DIST.Expenditure_Item_Date) <=
2887                        trunc(NVL(G_TRANSACTION_DATE,DIST.Expenditure_Item_Date))       /*GSCC*/
2888               AND DIST.project_id = G_PROJECT_ID
2889               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2890               AND EXISTS (
2891                   SELECT NULL
2892                     FROM ap_invoices_all inv,
2893                          po_distributions_all PO,
2894                          ap_invoice_distributions_all dist2
2895                     WHERE inv.invoice_id = dist2.invoice_id
2896                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
2897                     AND dist2.invoice_id = DIST.invoice_id
2898                     /*credit card txn enhancement, make sure this update doesn't pick tehm */
2899                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2900                      AND inv.source not  in ('CREDIT CARD','Both Pay') /* Added for bug 8977795 */
2901                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
2902                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
2903                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
2904                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2905                     AND  (
2906 			nvl(INV.source, 'xx' ) NOT IN ( 'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')  /* Removed 'Oracle Project Accounting' */
2907 			or
2908 			 dist2.line_type_lookup_code = 'NONREC_TAX'
2909 			 )
2910                         )
2911                 /* Bug 6353803: Added the following for this bug. */
2912   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2913                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2914 		    AND NOT EXISTS (SELECT 'X'
2915 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2916 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2917 				    AND pod.po_line_id = pol.po_line_id
2918 				    AND   si.inventory_item_id = pol.item_id
2919 				    AND   si.comms_nl_trackable_flag = 'Y'
2920 				    AND   (si.organization_id = pod.org_id
2921 						OR /* Added for bug 13714500 */
2922                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
2923                                                  where pll.po_header_id = pod.po_header_id
2924 						              and pll.po_line_id = pod.po_line_id)
2925 						)
2926 				    )
2927 		    AND NOT EXISTS (SELECT 'X'
2928 			      FROM
2929 				ap_invoice_distributions apdist,
2930 				po_distributions pod,
2931 				mtl_system_items si,
2932 				po_lines_all pol
2933 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2934                                     = apdist.INVOICE_DISTRIBUTION_ID
2935 				  and apdist.po_distribution_id = pod.po_distribution_id
2936 				  and pod.po_line_id = pol.po_line_id
2937 				  and si.inventory_item_id = pol.item_id
2938 				  AND   si.comms_nl_trackable_flag = 'Y'
2939 				  AND   (si.organization_id = pod.org_id
2940 						OR /* Added for bug 13714500 */
2941                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
2942                                                  where pll.po_header_id = pod.po_header_id
2943 						              and pll.po_line_id = pod.po_line_id)
2944 						)
2945 					     )
2946 		    )
2947                   );
2948 
2949 	      G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
2950               write_log(LOG, 'Number of rows marked to O: ' || to_char(SQL%ROWCOUNT));
2951 
2952 
2953 /*Bug 13602288:  Self Assessed Tax  Changes */
2954            UPDATE AP_SELF_ASSESSED_TAX_DIST DIST
2955               SET DIST.Pa_Addition_Flag = 'O',
2956                   request_id = G_REQUEST_ID,
2957                   last_update_date=SYSDATE,
2958                   last_updated_by=G_USER_ID,
2959                   last_update_login=G_USER_ID,
2960                   program_id=G_PROG_ID,
2961                   program_application_id=G_PROG_APPL_ID,
2962                   program_update_date=SYSDATE
2963             WHERE DIST.Posted_Flag = 'Y'
2964               AND DIST.Pa_Addition_Flag IN
2965                    ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
2966               AND DIST.project_id > 0
2967               AND trunc(DIST.Accounting_Date) <= trunc(nvl(G_GL_DATE,DIST.Accounting_Date))   /*GSCC*/
2968               AND trunc(DIST.Expenditure_Item_Date) <=
2969                        trunc(NVL(G_TRANSACTION_DATE,DIST.Expenditure_Item_Date))       /*GSCC*/
2970               AND DIST.project_id = G_PROJECT_ID
2971               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2972               AND EXISTS (
2973                   SELECT NULL
2974                     FROM ap_invoices_all inv,
2975                          po_distributions_all PO,
2976                          AP_SELF_ASSESSED_TAX_DIST dist2
2977                     WHERE inv.invoice_id = dist2.invoice_id
2978                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
2979                     AND dist2.invoice_id = DIST.invoice_id
2980                     /*credit card txn enhancement, make sure this update doesn't pick tehm */
2981                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2982                      AND inv.source not  in ('CREDIT CARD','Both Pay')
2983                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
2984                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
2985                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
2986                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2987                     AND  (
2988 			nvl(INV.source, 'xx' ) NOT IN ( 'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
2989 			or
2990 			 dist2.line_type_lookup_code = 'NONREC_TAX'
2991 			 )
2992                         )
2993   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2994                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2995 		    AND NOT EXISTS (SELECT 'X'
2996 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2997 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2998 				    AND pod.po_line_id = pol.po_line_id
2999 				    AND   si.inventory_item_id = pol.item_id
3000 				    AND   si.comms_nl_trackable_flag = 'Y'
3001 				    AND   (si.organization_id = pod.org_id
3002 						OR /* Added for bug 13714500 */
3003                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3004                                                  where pll.po_header_id = pod.po_header_id
3005 						              and pll.po_line_id = pod.po_line_id)
3006 						)
3007 				    )
3008 		    AND NOT EXISTS (SELECT 'X'
3009 			      FROM
3010 				AP_SELF_ASSESSED_TAX_DIST apdist,
3011 				po_distributions pod,
3012 				mtl_system_items si,
3013 				po_lines_all pol
3014 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
3015                                     = apdist.INVOICE_DISTRIBUTION_ID
3016 				  and apdist.po_distribution_id = pod.po_distribution_id
3017 				  and pod.po_line_id = pol.po_line_id
3018 				  and si.inventory_item_id = pol.item_id
3019 				  AND   si.comms_nl_trackable_flag = 'Y'
3020 				  AND   (si.organization_id = pod.org_id
3021 						OR /* Added for bug 13714500 */
3022                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3023                                                  where pll.po_header_id = pod.po_header_id
3024 						              and pll.po_line_id = pod.po_line_id)
3025 						)
3026 					     )
3027 		    )
3028                   );
3029 
3030 G_DISTRIBUTIONS_MARKED :=nvl(G_DISTRIBUTIONS_MARKED ,0) +  SQL%ROWCOUNT;
3031 write_log(LOG, 'Number of Self Assessed Tax  rows marked to O: ' || to_char(SQL%ROWCOUNT));
3032 
3033          END IF; -- End of Accntg Method is CASH
3034 
3035        ELSE          /* G_PROJECT_ID IS NULL */
3036 
3037 
3038          -- For CASH based Accntg we will continue to bring Historical data as Invoices and not Payments
3039          -- Any reversals made to the historical Invoices should also be brought into projects as Invoices and not Payments
3040 
3041          IF G_ACCTNG_METHOD = 'C' THEN
3042 
3043 	   write_log(LOG, 'Marking invoices to O for Historical Data interface in Cash Based Acctng');
3044 
3045            UPDATE AP_Invoice_Distributions DIST
3046               SET DIST.Pa_Addition_Flag = 'O',
3047                   request_id = G_REQUEST_ID,
3048                   last_update_date=SYSDATE,
3049                   last_updated_by=G_USER_ID,
3050                   last_update_login=G_USER_ID,
3051                   program_id=G_PROG_ID,
3052                   program_application_id=G_PROG_APPL_ID,
3053                   program_update_date=SYSDATE
3054             WHERE DIST.Posted_Flag = 'Y'
3055               AND DIST.Pa_Addition_Flag IN
3056                   ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
3057               AND DIST.project_id > 0
3058               AND trunc(DIST.Accounting_Date) <= trunc(nvl(G_GL_DATE,DIST.Accounting_Date))   /*GSCC*/ /*Added trunc for the bug 6623163 */
3059               AND trunc(DIST.Expenditure_Item_Date) <=
3060                      trunc(NVL(G_TRANSACTION_DATE,DIST.Expenditure_Item_Date))       /*GSCC*/  /*Added trunc for the bug 6623163 */
3061               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
3062               AND (
3063                   EXISTS (
3064                     SELECT NULL
3065                     FROM ap_invoices_all inv,
3066                          po_distributions_all PO,
3067                          ap_invoice_distributions_all dist2
3068                     WHERE inv.invoice_id = dist2.invoice_id
3069                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
3070                     AND dist2.invoice_id = DIST.invoice_id
3071                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
3072                     AND inv.payment_status_flag = 'Y'                                 -- Flag indicates that Invoice has been FULLY paid
3073                     AND dist2.historical_flag = 'Y'                                     --Process Historical data as Invoices in Cash based
3074                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
3075                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
3076                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
3077                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
3078                     AND inv.source not  in ('CREDIT CARD','Both Pay') /* Added for bug 8977795 */
3079                     AND ( nvl(INV.source, 'xx' ) NOT IN (
3080                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')  /* Removed 'Oracle Project Accounting' */
3081                         or dist2.line_type_lookup_code = 'NONREC_TAX')
3082                        )
3083                   OR
3084                   EXISTS (
3085                     SELECT NULL
3086                     FROM ap_invoices inv1,
3087                          ap_invoice_distributions dist3
3088                     WHERE inv1.invoice_id = dist3.invoice_id
3089                     AND   inv1.invoice_id = dist.invoice_id
3090                     AND   inv1.invoice_type_lookup_code <> 'EXPENSE REPORT'
3091                     AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
3092                     AND   dist3.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
3093                     AND   dist3.pa_addition_flag = 'Y')
3094                   )
3095                 /* Bug 6353803: Added the following for this bug. */
3096   	        AND   (pa_nl_installed.is_nl_installed = 'N'
3097                   OR (    pa_nl_installed.is_nl_installed = 'Y'
3098 		    AND NOT EXISTS (SELECT 'X'
3099 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
3100 				    WHERE pod.po_distribution_id = dist.po_distribution_id
3101 				    AND pod.po_line_id = pol.po_line_id
3102 				    AND   si.inventory_item_id = pol.item_id
3103 				    AND   si.comms_nl_trackable_flag = 'Y'
3104 				    AND   (si.organization_id = pod.org_id
3105 						OR /* Added for bug 13714500 */
3106                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3107                                                  where pll.po_header_id = pod.po_header_id
3108 						              and pll.po_line_id = pod.po_line_id)
3109 						)
3110 				    )
3111 		    AND NOT EXISTS (SELECT 'X'
3112 			      FROM
3113 				ap_invoice_distributions apdist,
3114 				po_distributions pod,
3115 				mtl_system_items si,
3116 				po_lines_all pol
3117 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
3118                                     = apdist.INVOICE_DISTRIBUTION_ID
3119 				  and apdist.po_distribution_id = pod.po_distribution_id
3120 				  and pod.po_line_id = pol.po_line_id
3121 				  and si.inventory_item_id = pol.item_id
3122 				  AND   si.comms_nl_trackable_flag = 'Y'
3123 				  AND   (si.organization_id = pod.org_id
3124 						OR /* Added for bug 13714500 */
3125                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3126                                                  where pll.po_header_id = pod.po_header_id
3127 						              and pll.po_line_id = pod.po_line_id)
3128 						)
3129 					     )
3130 		    )
3131                   )/* Start changes for bug#14320909 */
3132 		        AND NOT EXISTS (select 'X' from rcv_receiving_sub_ledger rcv_sub,
3133 			po_distributions_all po_dist1
3134 			where  po_dist1.CODE_COMBINATION_ID   =rcv_sub.CODE_COMBINATION_ID
3135 			AND    rcv_sub.ACTUAL_FLAG           = 'A'
3136 			and    rcv_sub.pa_addition_flag ='Y'
3137 			AND    to_char(DIST.po_distribution_id) = rcv_sub.reference3
3138 			and    DIST.po_distribution_id = po_dist1.po_distribution_id)
3139 			/* End changes for bug#14320909 */;
3140 
3141 
3142               G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
3143               write_log(LOG, 'Number of Historical Inv Dist marked to O: ' || to_char(SQL%ROWCOUNT));
3144 
3145            /* Historical Data Processing for Prepayments */
3146            /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
3147               Pre Rel12 Upgrade should also be brought into Projects */
3148 
3149           write_log(LOG, 'Marking Historical Prepayments for processing...');
3150 
3151             UPDATE ap_invoice_distributions_all dist
3152             SET    dist.pa_addition_flag = 'O',
3153                    request_id = G_REQUEST_ID,
3154                    last_update_date=SYSDATE,
3155                    last_updated_by= G_USER_ID,
3156                    last_update_login= G_USER_ID,
3157                    program_id= G_PROG_ID,
3158                    program_application_id= G_PROG_APPL_ID,
3159                    program_update_date=SYSDATE
3160             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
3161             AND   dist.posted_flag ='Y'
3162             AND   dist.project_id > 0
3163             --AND   dist.line_type_lookup_code = 'PREPAY'
3164             AND   dist.line_type_lookup_code <> 'REC_TAX'
3165             AND   dist.prepay_distribution_id is not null
3166             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
3167             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
3168             AND   EXISTS (
3169                     SELECT NULL
3170                     FROM ap_invoices inv
3171                     WHERE inv.invoice_id = dist.invoice_id
3172                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
3173                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
3174                      AND inv.source not  in ('CREDIT CARD','Both Pay') /* Added for bug 8977795 */
3175                     AND nvl(INV.source, 'xx' ) NOT IN (
3176                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')  ) /* Removed 'Oracle Project Accounting' */
3177             AND   exists(SELECT inv.invoice_id
3178                            FROM AP_INVOICES_all inv,
3179                                 AP_Invoice_Distributions_all aid
3180                           WHERE aid.invoice_id = inv.invoice_id
3181                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
3182                             AND aid.historical_flag = 'Y'
3183                             AND aid.pa_addition_flag = 'Y'
3184                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
3185                             AND aid.project_id > 0 )
3186                 /* Bug 6353803: Added the following for this bug. */
3187   	        AND   (pa_nl_installed.is_nl_installed = 'N'
3188                   OR (    pa_nl_installed.is_nl_installed = 'Y'
3189 		    AND NOT EXISTS (SELECT 'X'
3190 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
3191 				    WHERE pod.po_distribution_id = dist.po_distribution_id
3192 				    AND pod.po_line_id = pol.po_line_id
3193 				    AND   si.inventory_item_id = pol.item_id
3194 				    AND   si.comms_nl_trackable_flag = 'Y'
3195 				    AND    (si.organization_id = pod.org_id
3196 						OR /* Added for bug 13714500 */
3197                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3198                                                  where pll.po_header_id = pod.po_header_id
3199 						              and pll.po_line_id = pod.po_line_id)
3200 						)
3201 				    )
3202 		    AND NOT EXISTS (SELECT 'X'
3203 			      FROM
3204 				ap_invoice_distributions apdist,
3205 				po_distributions pod,
3206 				mtl_system_items si,
3207 				po_lines_all pol
3208 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
3209                                     = apdist.INVOICE_DISTRIBUTION_ID
3210 				  and apdist.po_distribution_id = pod.po_distribution_id
3211 				  and pod.po_line_id = pol.po_line_id
3212 				  and si.inventory_item_id = pol.item_id
3213 				  AND   si.comms_nl_trackable_flag = 'Y'
3214 				  AND    (si.organization_id = pod.org_id
3215 						OR /* Added for bug 13714500 */
3216                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3217                                                  where pll.po_header_id = pod.po_header_id
3218 						              and pll.po_line_id = pod.po_line_id)
3219 						)
3220 					     )
3221 		    )
3222                   );
3223 
3224             G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
3225             write_log(LOG, 'Number of Historical PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
3226 
3227 
3228 	    /* Historical Data Processing for Self Assessed Tax  Prepayments */
3229            /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
3230               Pre Rel12 Upgrade should also be brought into Projects */
3231 
3232           write_log(LOG, 'Marking Historical Self Assessed Tax  Prepayments for processing...');
3233 
3234             UPDATE AP_SELF_ASSESSED_TAX_DIST_ALL dist
3235             SET    dist.pa_addition_flag = 'O',
3236                    request_id = G_REQUEST_ID,
3237                    last_update_date=SYSDATE,
3238                    last_updated_by= G_USER_ID,
3239                    last_update_login= G_USER_ID,
3240                    program_id= G_PROG_ID,
3241                    program_application_id= G_PROG_APPL_ID,
3242                    program_update_date=SYSDATE
3243             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
3244             AND   dist.posted_flag ='Y'
3245             AND   dist.project_id > 0
3246             AND   dist.line_type_lookup_code <> 'REC_TAX'
3247             AND   dist.prepay_distribution_id is not null
3248             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
3249             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
3250             AND   EXISTS (
3251                     SELECT NULL
3252                     FROM ap_invoices inv
3253                     WHERE inv.invoice_id = dist.invoice_id
3254                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
3255                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
3256                      AND inv.source not  in ('CREDIT CARD','Both Pay')
3257                     AND nvl(INV.source, 'xx' ) NOT IN (
3258                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')  )
3259             AND   exists(SELECT inv.invoice_id
3260                            FROM AP_INVOICES_all inv,
3261                                 AP_SELF_ASSESSED_TAX_DIST_ALL aid
3262                           WHERE aid.invoice_id = inv.invoice_id
3263                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
3264                            -- AND aid.historical_flag = 'Y' /*doubt*/
3265                             AND aid.pa_addition_flag = 'Y'
3266                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id
3267                             AND aid.project_id > 0 )
3268                 AND   (pa_nl_installed.is_nl_installed = 'N'
3269                   OR (    pa_nl_installed.is_nl_installed = 'Y'
3270 		    AND NOT EXISTS (SELECT 'X'
3271 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
3272 				    WHERE pod.po_distribution_id = dist.po_distribution_id
3273 				    AND pod.po_line_id = pol.po_line_id
3274 				    AND   si.inventory_item_id = pol.item_id
3275 				    AND   si.comms_nl_trackable_flag = 'Y'
3276 				    AND   (si.organization_id = pod.org_id
3277 						OR /* Added for bug 13714500 */
3278                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3279                                                  where pll.po_header_id = pod.po_header_id
3280 						              and pll.po_line_id = pod.po_line_id)
3281 						)
3282 				    )
3283 		    AND NOT EXISTS (SELECT 'X'
3284 			      FROM
3285 				AP_SELF_ASSESSED_TAX_DIST_ALL apdist,
3286 				po_distributions pod,
3287 				mtl_system_items si,
3288 				po_lines_all pol
3289 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
3290                                     = apdist.INVOICE_DISTRIBUTION_ID
3291 				  and apdist.po_distribution_id = pod.po_distribution_id
3292 				  and pod.po_line_id = pol.po_line_id
3293 				  and si.inventory_item_id = pol.item_id
3294 				  AND   si.comms_nl_trackable_flag = 'Y'
3295 				  AND   (si.organization_id = pod.org_id
3296 						OR /* Added for bug 13714500 */
3297                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3298                                                  where pll.po_header_id = pod.po_header_id
3299 						              and pll.po_line_id = pod.po_line_id)
3300 						)
3301 					     )
3302 		    )
3303                   );
3304 
3305             G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
3306             write_log(LOG, 'Number of Historical Self Assessed Tax  PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
3307 
3308 
3309          ELSE -- Accrual BAsed Acctng
3310 
3311           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
3312 	   write_log(LOG, 'Marking invoices in Accrual based Acctng');
3313 --bug 14489723
3314            UPDATE /*+ index(DIST AP_INVOICE_DISTRIBUTIONS_N14) */ AP_Invoice_Distributions DIST
3315               SET DIST.Pa_Addition_Flag = 'O',
3316                   request_id = G_REQUEST_ID,
3317                   last_update_date=SYSDATE,
3318                   last_updated_by=G_USER_ID,
3319                   last_update_login=G_USER_ID,
3320                   program_id=G_PROG_ID,
3321                   program_application_id=G_PROG_APPL_ID,
3322                   program_update_date=SYSDATE
3323             WHERE DIST.Posted_Flag = 'Y' -- removed the append  || '' for bug 13599091
3324 	    AND DIST.Pa_Addition_Flag IN
3325                   ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
3326               AND DIST.project_id > 0
3327               AND trunc(DIST.Accounting_Date )<= trunc(nvl(G_GL_DATE,DIST.Accounting_Date) )  /*GSCC*/
3328               AND trunc(DIST.Expenditure_Item_Date) <=
3329                      trunc(NVL(G_TRANSACTION_DATE, DIST.Expenditure_Item_Date))          /*GSCC*/
3330               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
3331               AND EXISTS (
3332                   SELECT NULL
3333                     FROM ap_invoices_all inv,
3334                          po_distributions_all PO,
3335                          ap_invoice_distributions_all dist2
3336                     WHERE inv.invoice_id = dist2.invoice_id
3337                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
3338                     AND dist2.invoice_id = DIST.invoice_id
3339                     /* credit card txn enhancement, make sure this update doesn't pick tehm */
3340                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
3341                     AND inv.source not  in ('CREDIT CARD','Both Pay') /* Added for bug 8977795 */
3342                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
3343                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
3344                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
3345                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
3346                     -- IC Upgrade: Do not get Inter-company invoices
3347                     AND ( nvl(INV.source, 'xx' ) NOT IN (
3348                              'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')  /* Removed 'Oracle Project Accounting' */
3349 			    or
3350 			 dist2.line_type_lookup_code = 'NONREC_TAX'
3351 			 )
3352                         )
3353                 /* Bug 6353803: Added the following for this bug. */
3354   	        AND   (pa_nl_installed.is_nl_installed = 'N'
3355                   OR (    pa_nl_installed.is_nl_installed = 'Y'
3356 		    AND NOT EXISTS (SELECT 'X'
3357 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
3358 				    WHERE pod.po_distribution_id = dist.po_distribution_id
3359 				    AND dist.po_distribution_id > 0   /*Added for bug#12922795 */
3360 				    AND pod.po_line_id = pol.po_line_id
3361 				    AND   si.inventory_item_id = pol.item_id
3362 				    AND   si.comms_nl_trackable_flag = 'Y'
3363 				    AND   (si.organization_id = pod.org_id
3364 						OR /* Added for bug 13714500 */
3365                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3366                                                  where pll.po_header_id = pod.po_header_id
3367 						              and pll.po_line_id = pod.po_line_id)
3368 						)
3369 				    )
3370 		    AND NOT EXISTS (SELECT 'X'
3371 			      FROM
3372 				ap_invoice_distributions apdist,
3373 				po_distributions pod,
3374 				mtl_system_items si,
3375 				po_lines_all pol
3376 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
3377                                     = apdist.INVOICE_DISTRIBUTION_ID
3378 				  and apdist.po_distribution_id = pod.po_distribution_id
3379 				  AND apdist.po_distribution_id > 0   /*Added for bug#12922795 */
3380 				  and pod.po_line_id = pol.po_line_id
3381 				  and si.inventory_item_id = pol.item_id
3382 				  AND   si.comms_nl_trackable_flag = 'Y'
3383 				  AND   (si.organization_id = pod.org_id
3384 						OR /* Added for bug 13714500 */
3385                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3386                                                  where pll.po_header_id = pod.po_header_id
3387 						              and pll.po_line_id = pod.po_line_id)
3388 						)
3389 					     )
3390 		    )
3391                   );
3392 
3393 
3394               G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
3395               write_log(LOG, 'Number of rows marked to O: ' || to_char(SQL%ROWCOUNT));
3396 
3397 	      /*Bug 13602288: Self Assessed Tax  Changes*/
3398 
3399               UPDATE AP_SELF_ASSESSED_TAX_DIST DIST
3400               SET DIST.Pa_Addition_Flag = 'O',
3401                   request_id = G_REQUEST_ID,
3402                   last_update_date=SYSDATE,
3403                   last_updated_by=G_USER_ID,
3404                   last_update_login=G_USER_ID,
3405                   program_id=G_PROG_ID,
3406                   program_application_id=G_PROG_APPL_ID,
3407                   program_update_date=SYSDATE
3408             WHERE DIST.Posted_Flag||'' = 'Y'
3409               AND DIST.Pa_Addition_Flag IN
3410                   ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
3411               AND DIST.project_id > 0
3412               AND trunc(DIST.Accounting_Date )<= trunc(nvl(G_GL_DATE,DIST.Accounting_Date) )  /*GSCC*/
3413               AND trunc(DIST.Expenditure_Item_Date) <=
3414                      trunc(NVL(G_TRANSACTION_DATE, DIST.Expenditure_Item_Date))          /*GSCC*/
3415               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
3416               AND EXISTS (
3417                   SELECT NULL
3418                     FROM ap_invoices_all inv,
3419                          po_distributions_all PO,
3420                          AP_SELF_ASSESSED_TAX_DIST dist2
3421                     WHERE inv.invoice_id = dist2.invoice_id
3422                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
3423                     AND dist2.invoice_id = DIST.invoice_id
3424                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
3425                     AND inv.source not  in ('CREDIT CARD','Both Pay')
3426                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
3427                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
3428                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
3429                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
3430                     AND ( nvl(INV.source, 'xx' ) NOT IN (
3431                              'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
3432 			    or
3433 			 dist2.line_type_lookup_code = 'NONREC_TAX'
3434 			 )
3435                         )
3436   	        AND   (pa_nl_installed.is_nl_installed = 'N'
3437                   OR (    pa_nl_installed.is_nl_installed = 'Y'
3438 		    AND NOT EXISTS (SELECT 'X'
3439 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
3440 				    WHERE pod.po_distribution_id = dist.po_distribution_id
3441 				    AND pod.po_line_id = pol.po_line_id
3442 				    AND   si.inventory_item_id = pol.item_id
3443 				    AND   si.comms_nl_trackable_flag = 'Y'
3444 				    AND   (si.organization_id = pod.org_id
3445 						OR /* Added for bug 13714500 */
3446                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3447                                                  where pll.po_header_id = pod.po_header_id
3448 						              and pll.po_line_id = pod.po_line_id)
3449 						)
3450 				    )
3451 		    AND NOT EXISTS (SELECT 'X'
3452 			      FROM
3453 				AP_SELF_ASSESSED_TAX_DIST apdist,
3454 				po_distributions pod,
3455 				mtl_system_items si,
3456 				po_lines_all pol
3457 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
3458                                     = apdist.INVOICE_DISTRIBUTION_ID
3459 				  and apdist.po_distribution_id = pod.po_distribution_id
3460 				  and pod.po_line_id = pol.po_line_id
3461 				  and si.inventory_item_id = pol.item_id
3462 				  AND   si.comms_nl_trackable_flag = 'Y'
3463 				  AND   (si.organization_id = pod.org_id
3464 						OR /* Added for bug 13714500 */
3465                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
3466                                                  where pll.po_header_id = pod.po_header_id
3467 						              and pll.po_line_id = pod.po_line_id)
3468 						)
3469 					     )
3470 		    )
3471                   );
3472 
3473 
3474            END IF; -- End of Acctng method is CASH
3475 
3476          END IF;
3477          --
3478          -- End of If section checking if G_PROJECT_ID is not null
3479          --
3480 
3481      END IF;
3482 
3483      write_log(LOG, 'Total Number of rows marked to O: ' || to_char(G_DISTRIBUTIONS_MARKED));
3484      G_err_stack := v_old_stack;
3485 
3486 EXCEPTION
3487      WHEN Others THEN
3488            -- Marking phase failed, raise exception to main program to terminate the program
3489            --
3490            G_err_stack := v_old_stack;
3491            G_err_code := SQLCODE;
3492            RAISE;
3493 
3494 END mark_PAflag_O;
3495 
3496 PROCEDURE transfer_inv_to_pa  IS
3497 
3498    v_num_invoices_fetched          NUMBER :=0;
3499    v_num_distributions_fetched     NUMBER :=0;
3500    v_prev_invoice_id               NUMBER := 0;
3501    v_prev_vendor_id                NUMBER := 0;
3502    v_old_stack                     VARCHAR2(630);
3503    v_err_message                   VARCHAR2(220);
3504    v_all_done                      NUMBER := 0;
3505    v_prev_invoice_source           ap_invoices.source%TYPE := NULL;
3506    v_prev_transaction_source       pa_transaction_sources.transaction_source%TYPE;
3507    v_num_tax_lines_fetched         NUMBER:=0;
3508    v_num_inv_variance_fetched      NUMBER:=0;    --NEW
3509    v_num_inv_erv_fetched           NUMBER:=0;    --NEW
3510    v_num_inv_frt_fetched           NUMBER:=0;    --NEW
3511    v_last_inv_ER_flag              VARCHAR2(1);
3512 
3513    v_status Number := 0;
3514    v_stage  Number :=0;
3515    v_business_group_id NUMBER := 0;
3516    v_attribute_category VARCHAR2(150);
3517    v_attribute1 VARCHAR2(150);
3518    v_attribute2 VARCHAR2(150);
3519    v_attribute3 VARCHAR2(150);
3520    v_attribute4 VARCHAR2(150);
3521    v_attribute5 VARCHAR2(150);
3522    v_attribute6 VARCHAR2(150);
3523    v_attribute7 VARCHAR2(150);
3524    v_attribute8 VARCHAR2(150);
3525    v_attribute9 VARCHAR2(150);
3526    v_attribute10 VARCHAR2(150);
3527    v_dff_map_status VARCHAR2(30);
3528    dff_map_exception EXCEPTION;
3529 
3530    v_num_last_invoice_processed NUMBER := 0;
3531    v_last_inv_index             NUMBER := 0;
3532    v_num_dist_marked_O          NUMBER := 0;
3533    v_num_dist_remain            NUMBER := 0;
3534    v_max_size                   NUMBER := 0;
3535 
3536    v_inv_batch_size             NUMBER := 0;
3537    v_tax_batch_size             NUMBER := 0;
3538    v_var_batch_size             NUMBER := 0;
3539    v_frt_batch_size             NUMBER := 0;
3540 
3541 -- For PA IP Invoices
3542    L_IP_TRANSACTION_SOURCE         pa_transaction_interface.transaction_source%TYPE;
3543    l_ap_inv_flag                   VARCHAR2(1):= 'N';
3544    l_ip_inv_flag                   VARCHAR2(1):= 'N';
3545 
3546    CURSOR Num_Dist_Marked_O (p_invoice_id IN NUMBER) IS
3547       SELECT count(*) from
3548       (
3549       select 1
3550          FROM ap_invoice_distributions
3551         WHERE invoice_id       = p_invoice_id
3552           AND pa_addition_flag = 'O'
3553 	union
3554 	select 1
3555 	from AP_SELF_ASSESSED_TAX_DIST
3556 	WHERE invoice_id       = p_invoice_id
3557 	 AND pa_addition_flag = 'O'
3558       );  /*Bug 13602288:  Self Assessed Tax  Changes*/
3559 
3560    l_prev_cr_ccid NUMBER;
3561    l_prev_dr_ccid NUMBER;
3562    l_create_adj_recs  VARCHAR2(1) := 'N';
3563 
3564    /* the following sub-procedure is declared here to save lines of code since deleting
3565       plsql tables will be done multiple times within the procedure transfer_inv_to_pa */
3566 
3567    PROCEDURE clear_plsql_tables IS
3568 
3569        l_status1 VARCHAR2(30);
3570 
3571    BEGIN
3572 
3573        G_err_stage := 'within clear_plsql_tables of ransfer_inv_to_pa';
3574        write_log(LOG, G_err_stage);
3575 
3576        l_invoice_id_tbl.delete;
3577        l_created_by_tbl.delete;
3578        --l_dist_line_num_tbl.delete;
3579        l_invoice_dist_id_tbl.delete; --NEW
3580        l_project_id_tbl.delete;
3581        l_task_id_tbl.delete;
3582        l_ln_type_lookup_tbl.delete;
3583        l_exp_type_tbl.delete;
3584        l_ei_date_tbl.delete;
3585        l_amount_tbl.delete;
3586        l_description_tbl.delete;
3587        l_justification_tbl.delete;
3588        l_dist_cc_id_tbl.delete;
3589        l_exp_org_id_tbl.delete;
3590        l_quantity_tbl.delete;
3591        l_acct_pay_cc_id_tbl.delete;
3592        l_gl_date_tbl.delete;
3593        l_attribute_cat_tbl.delete;
3594        l_attribute1_tbl.delete;
3595        l_attribute2_tbl.delete;
3596        l_attribute3_tbl.delete;
3597        l_attribute4_tbl.delete;
3598        l_attribute5_tbl.delete;
3599        l_attribute6_tbl.delete;
3600        l_attribute7_tbl.delete;
3601        l_attribute8_tbl.delete;
3602        l_attribute9_tbl.delete;
3603        l_attribute10_tbl.delete;
3604        l_rec_cur_amt_tbl.delete;
3605        l_rec_cur_code_tbl.delete;
3606        l_rec_conv_rate_tbl.delete;
3607        l_denom_raw_cost_tbl.delete;
3608        l_denom_cur_code_tbl.delete;
3609        l_acct_rate_date_tbl.delete;
3610        l_acct_rate_type_tbl.delete;
3611        l_acct_exch_rate_tbl.delete;
3612        l_job_id_tbl.delete;
3613        l_employee_id_tbl.delete;
3614        l_vendor_id_tbl.delete;
3615        l_inv_type_code_tbl.delete;
3616        l_source_tbl.delete;
3617        l_org_id_tbl.delete;
3618        l_invoice_num_tbl.delete;
3619        l_cdl_sys_ref4_tbl.delete;
3620        l_po_dist_id_tbl.delete;
3621        l_txn_src_tbl.delete;
3622        l_user_txn_src_tbl.delete;
3623        l_batch_name_tbl.delete;
3624        l_interface_id_tbl.delete;
3625        l_exp_end_date_tbl.delete;
3626        l_txn_status_code_tbl.delete;
3627        l_txn_rej_code_tbl.delete;
3628        l_po_dist_id_tbl.delete;
3629        l_bus_grp_id_tbl.delete;
3630        l_paid_emp_id_tbl.delete;
3631        l_sort_var_tbl.delete;
3632        l_reversal_flag_tbl.delete; --NEW
3633        l_cancel_flag_tbl.delete;  --NEW
3634        l_parent_rev_id_tbl.delete; --NEW
3635        l_net_zero_flag_tbl.delete; --NEW
3636        l_sc_xfer_code_tbl.delete; --NEW
3637        l_adj_exp_item_id_tbl.delete; --NEW
3638        l_fc_enabled_tbl.delete; --NEW
3639        l_fc_document_type_tbl.delete; --NEW
3640        l_insert_flag_tbl.delete;
3641        l_rev_parent_dist_id_tbl.delete;
3642        l_rev_child_dist_id_tbl.delete;
3643        l_rev_parent_dist_ind_tbl.delete;
3644        l_si_assts_add_flg_tbl.delete;
3645        l_prepay_dist_id_tbl.delete;
3646        l_hist_flag_tbl.delete;
3647        l_rev_index:=0;
3648        l_is_self_assessed_tax_tbl.delete; -- Bug 13602288: Self Assessed Tax  change
3649 	     l_cbs_element_id_tbl.delete; -- Added for CBS Enhancement Bug 16220146
3650 
3651     END clear_plsql_tables;
3652 
3653    /* the following sub-procedure is declared here to save lines of code since bulk insert
3654       will be done multiple times within the procedure transfer_inv_to_pa */
3655 
3656     PROCEDURE bulk_update_trx_intf IS
3657 
3658      BEGIN
3659 
3660        /* The records with INSERT_FLAG = F indicate that they are fully applied prepayments and the pa-addition-flag
3661           for such records will be updated to G to relieve commitments*/
3662        /* The records with INSERT_FLAG = P indicate that they are partially applied prepayments and the pa-addition-flag
3663           for such records will be updated to N */
3664 
3665        write_log(LOG,'Before bulk update  of prepayment invoices');
3666 
3667        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
3668 
3669          UPDATE ap_invoice_distributions_all dist
3670             SET dist.pa_addition_flag         = decode(l_insert_flag_tbl(i),'F','G','P','N')
3671           WHERE dist.invoice_id               = l_invoice_id_tbl(i)
3672             AND dist.invoice_distribution_id  = l_invoice_dist_id_tbl(i)
3673             AND dist.pa_addition_flag         = 'O'
3674 	    AND l_is_self_assessed_tax_tbl(i) = 'N'  -- Bug 13602288: Self Assessed Tax  Changes
3675             AND l_insert_flag_tbl(i)         in ('P','F');
3676 
3677 	FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
3678          UPDATE AP_SELF_ASSESSED_TAX_DIST dist
3679             SET dist.pa_addition_flag         = decode(l_insert_flag_tbl(i),'F','G','P','N')
3680           WHERE dist.invoice_id               = l_invoice_id_tbl(i)
3681             AND dist.invoice_distribution_id  = l_invoice_dist_id_tbl(i)
3682             AND dist.pa_addition_flag         = 'O'
3683 	    AND l_is_self_assessed_tax_tbl(i) = 'Y'  -- Bug 13602288: Self Assessed Tax  Changes
3684             AND l_insert_flag_tbl(i)         in ('P','F');
3685 
3686 
3687 
3688      EXCEPTION
3689       WHEN OTHERS THEN
3690           write_log(LOG,'Failed during bulk update for prepayment processing');
3691           G_err_code   := SQLCODE;
3692           write_log(LOG, 'Error Code is '||SQLCODE);
3693           write_log(LOG, substr(SQLERRM, 1, 200));
3694           write_log(LOG, substr(SQLERRM, 201, 200));
3695           raise;
3696 
3697     END bulk_update_trx_intf;
3698 
3699     PROCEDURE bulk_insert_trx_intf IS
3700 
3701       l_status2 VARCHAR2(30);
3702 
3703 
3704     BEGIN
3705 
3706        write_log(LOG,'Before bulk insert of supplier invoices');
3707 
3708       If g_body_debug_mode = 'Y' Then
3709        FOR i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST  LOOP
3710           write_log(LOG,   '1:'||   l_txn_src_tbl(i));
3711           write_log(LOG,   '2:'||   l_user_txn_src_tbl(i));
3712           write_log(LOG,   '3:'||   l_batch_name_tbl(i));
3713           write_log(LOG,      '4:'||to_char(l_exp_end_date_tbl(i)));
3714           write_log(LOG,      '6:'||to_char(l_ei_date_tbl(i)));
3715           write_log(LOG,      '7:'||l_exp_type_tbl(i));
3716           write_log(LOG,      '8:'||to_char(l_quantity_tbl(i)));
3717           write_log(LOG,      '9:'||l_description_tbl(i));
3718           write_log(LOG,      '10:'||l_txn_status_code_tbl(i));
3719           write_log(LOG,      '11:'||l_txn_rej_code_tbl(i));
3720           write_log(LOG,      '12:'||to_char(l_interface_id_tbl(i)));
3721           write_log(LOG,      '13:'||to_char(l_dist_cc_id_tbl(i)));
3722           write_log(LOG,      '14:'||to_char(l_acct_pay_cc_id_tbl(i)));
3723           write_log(LOG,      '15:'||to_char(l_vendor_id_tbl(i) ));
3724           write_log(LOG,      '16:'||to_char(l_invoice_id_tbl(i) ));
3725           write_log(LOG,      '17:'||l_cdl_sys_ref4_tbl(i));
3726           write_log(LOG,      '18:'||to_char(l_invoice_dist_id_tbl(i) ));
3727           write_log(LOG,      '19:'||to_char(l_gl_date_tbl(i)));
3728           write_log(LOG,      '20:'||to_char(l_rec_cur_amt_tbl(i)));
3729           write_log(LOG,      '21:'||l_rec_cur_code_tbl(i));
3730           write_log(LOG,      '22:'||l_rec_conv_rate_tbl(i));
3731           write_log(LOG,      '23:'||to_char(l_denom_raw_cost_tbl(i)));
3732           write_log(LOG,      '24:'||l_denom_cur_code_tbl(i));
3733           write_log(LOG,      '25:'||to_char(l_acct_rate_date_tbl(i)));
3734           write_log(LOG,      '26:'||l_acct_rate_type_tbl(i));
3735           write_log(LOG,      '27:'||to_char(l_acct_exch_rate_tbl(i)));
3736           write_log(LOG,      '28:'||to_char(l_amount_tbl(i)));
3737           write_log(LOG,      '29:'||l_attribute_cat_tbl(i));
3738           write_log(LOG,      '30:'||l_attribute1_tbl(i));
3739           write_log(LOG,      '31:'||l_attribute2_tbl(i));
3740           write_log(LOG,      '32:'||l_attribute3_tbl(i));
3741           write_log(LOG,      '33:'||l_attribute4_tbl(i));
3742           write_log(LOG,      '34:'||l_attribute5_tbl(i));
3743           write_log(LOG,      '35:'||l_attribute6_tbl(i));
3744           write_log(LOG,      '36:'||l_attribute7_tbl(i));
3745           write_log(LOG,      '37:'||l_attribute8_tbl(i));
3746           write_log(LOG,      '38:'||l_attribute9_tbl(i));
3747           write_log(LOG,      '39:'||l_attribute10_tbl(i));
3748           write_log(LOG,      '40:'||to_char(l_invoice_id_tbl(i) ));
3749           write_log(LOG,      '41:'||l_invoice_num_tbl(i));
3750           write_log(LOG,      '42:'||to_char(l_invoice_id_tbl(i) ));
3751           write_log(LOG,      '43:'||to_char(l_employee_id_tbl(i)));
3752           write_log(LOG,      '44:'||to_char(l_org_id_tbl(i)));
3753           write_log(LOG,      '45:'||to_char(l_project_id_tbl(i)));
3754           write_log(LOG,      '46:'||to_char(l_task_id_tbl(i)));
3755           write_log(LOG,      '47:'||to_char(l_vendor_id_tbl(i)));
3756           write_log(LOG,      '48:'||to_char(l_exp_org_id_tbl(i)));
3757           write_log(LOG,      '49:'||to_char(l_bus_grp_id_tbl(i)));
3758           write_log(LOG,      '50:'||to_char(l_adj_exp_item_id_tbl(i) ));
3759           write_log(LOG,      '51:'||l_fc_document_type_tbl(i) );
3760           write_log(LOG,      '52:'||l_inv_type_code_tbl(i));
3761           write_log(LOG,      '53:'||l_ln_type_lookup_tbl(i));
3762           write_log(LOG,      '54:'||l_net_zero_flag_tbl(i));
3763           write_log(LOG,      '55:'||l_si_assts_add_flg_tbl(i));
3764           write_log(LOG,      '56:'||l_cdl_sys_ref3_tbl(i));
3765           write_log(LOG,      '57:'||l_net_zero_flag_tbl(i));
3766           write_log(LOG,      '58:'||l_insert_flag_tbl(i));
3767           write_log(LOG,      '59:'||G_UNIQUE_ID);
3768           write_log(LOG,      '60:'||l_is_self_assessed_tax_tbl(i));   /* Bug 13602288: Self Assessed Tax  changes */
3769           write_log(LOG,      '61:'||l_cbs_element_id_tbl(i)); -- Added for CBS Enhancement Bug 16220146
3770        END LOOP;
3771      End If;
3772 
3773        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
3774 
3775        INSERT INTO pa_transaction_interface_all(
3776                      transaction_source
3777                     , user_transaction_source
3778                     , system_linkage
3779                     , batch_name
3780                     , expenditure_ending_date
3781                     , expenditure_item_date
3782                     , expenditure_type
3783                     , quantity
3784                     , raw_cost_rate
3785                     , expenditure_comment
3786                     , transaction_status_code
3787                     , transaction_rejection_code
3788                     , orig_transaction_reference
3789                     , interface_id
3790                     , dr_code_combination_id
3791                     , cr_code_combination_id
3792                     , cdl_system_reference1
3793                     , cdl_system_reference2
3794                     , cdl_system_reference3
3795                     , cdl_system_reference4
3796                     , cdl_system_reference5 --NEW
3797                     , gl_date
3798                     , org_id
3799                     , unmatched_negative_txn_flag
3800                     , receipt_currency_amount
3801                     , receipt_currency_code
3802                     , receipt_exchange_rate
3803                     , denom_raw_cost
3804                     , denom_currency_code
3805                     , acct_rate_date
3806                     , acct_rate_type
3807                     , acct_exchange_rate
3808                     , acct_raw_cost
3809                     , acct_exchange_rounding_limit
3810                     , attribute_category
3811                     , attribute1
3812                     , attribute2
3813                     , attribute3
3814                     , attribute4
3815                     , attribute5
3816                     , attribute6
3817                     , attribute7
3818                     , attribute8
3819                     , attribute9
3820                     , attribute10
3821                     , orig_exp_txn_reference1
3822                     , orig_user_exp_txn_reference
3823                     , orig_exp_txn_reference2
3824                     , orig_exp_txn_reference3
3825                     , last_update_date
3826                     , last_updated_by
3827                     , creation_date
3828                     , created_by
3829                     , person_id
3830                     , organization_id
3831                     , project_id
3832                     , task_id
3833                     , Vendor_id
3834                     , override_to_organization_id
3835                     , person_business_group_id
3836                     , adjusted_expenditure_item_id --NEW
3837                     , fc_document_type  -- NEW
3838                     , document_type
3839                     , document_distribution_type
3840                     , sc_xfer_code
3841                     , si_assets_addition_flag
3842                     , net_zero_adjustment_flag
3843                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
3844                    )
3845                   SELECT
3846                       l_txn_src_tbl(i)
3847                      ,l_user_txn_src_tbl(i)
3848                      ,G_SYSTEM_LINKAGE
3849                      ,l_batch_name_tbl(i)
3850                      ,l_exp_end_date_tbl(i)
3851                      ,l_ei_date_tbl(i)
3852                      ,l_exp_type_tbl(i)
3853                      ,l_quantity_tbl(i)
3854                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
3855                      ,l_description_tbl(i)
3856                      ,l_txn_status_code_tbl(i)
3857                      ,l_txn_rej_code_tbl(i)
3858                      ,G_REQUEST_ID
3859                      ,l_interface_id_tbl(i)
3860                      ,l_dist_cc_id_tbl(i)
3861                      ,l_acct_pay_cc_id_tbl(i)
3862                      ,l_vendor_id_tbl(i) /*sysref1*/
3863                      ,l_invoice_id_tbl(i) /*sysref2*/
3864                      ,l_cdl_sys_ref3_tbl(i)  --NULL /*sysref3*/
3865                      ,l_cdl_sys_ref4_tbl(i)
3866                      ,l_invoice_dist_id_tbl(i) /*sysref5*/ --NEW
3867                      ,l_gl_date_tbl(i)
3868                      ,G_ORG_ID
3869                      ,'Y'
3870                      ,l_rec_cur_amt_tbl(i)
3871                      ,l_rec_cur_code_tbl(i)
3872                      ,l_rec_conv_rate_tbl(i)
3873                      ,l_denom_raw_cost_tbl(i)
3874                      ,l_denom_cur_code_tbl(i)
3875                      ,l_acct_rate_date_tbl(i)
3876                      ,l_acct_rate_type_tbl(i)
3877                      ,l_acct_exch_rate_tbl(i)
3878                      ,l_amount_tbl(i)
3879                      ,1
3880                      ,l_attribute_cat_tbl(i)
3881                      ,l_attribute1_tbl(i)
3882                      ,l_attribute2_tbl(i)
3883                      ,l_attribute3_tbl(i)
3884                      ,l_attribute4_tbl(i)
3885                      ,l_attribute5_tbl(i)
3886                      ,l_attribute6_tbl(i)
3887                      ,l_attribute7_tbl(i)
3888                      ,l_attribute8_tbl(i)
3889                      ,l_attribute9_tbl(i)
3890                      ,l_attribute10_tbl(i)
3891                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
3892                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
3893                      /* bug 2835757*/
3894                      ,DECODE(G_TRANS_DFF_AP,'N',NULL,l_invoice_id_tbl(i)) /*orig_exp_txn_reference2*/
3895                      ,NULL                       /*orig_exp_txn_reference3*/
3896                      ,SYSDATE
3897                      ,-1
3898                      ,SYSDATE
3899                      ,-1
3900                      ,l_employee_id_tbl(i)
3901                      ,l_org_id_tbl(i)
3902                      ,l_project_id_tbl(i)
3903                      ,l_task_id_tbl(i)
3904                      ,l_vendor_id_tbl(i)
3905                      ,l_exp_org_id_tbl(i)
3906                      ,l_bus_grp_id_tbl(i)
3907                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
3908                      ,l_fc_document_type_tbl(i) --NEW for funds check
3909                      ,l_inv_type_code_tbl(i)
3910                      ,l_ln_type_lookup_tbl(i)
3911                      ,l_sc_xfer_code_tbl(i)
3912                      ,l_si_assts_add_flg_tbl(i)
3913                      ,l_net_zero_flag_tbl(i)
3914                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
3915                 FROM dual
3916                 WHERE l_insert_flag_tbl(i) not in ('F', 'P');
3917 
3918               -- Insert the reversal of reversed/cancelled invoice distribution recs from AP.
3919     IF l_create_adj_recs = 'Y' THEN
3920 
3921                 write_log(LOG, 'Inserting adjustment records..');
3922 
3923 
3924        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
3925        INSERT INTO pa_transaction_interface_all(
3926                      transaction_source
3927                     , user_transaction_source
3928                     , system_linkage
3929                     , batch_name
3930                     , expenditure_ending_date
3931                     , expenditure_item_date
3932                     , expenditure_type
3933                     , quantity
3934                     , raw_cost_rate
3935                     , expenditure_comment
3936                     , transaction_status_code
3937                     , transaction_rejection_code
3938                     , orig_transaction_reference
3939                     , interface_id
3940                     , dr_code_combination_id
3941                     , cr_code_combination_id
3942                     , cdl_system_reference1
3943                     , cdl_system_reference2
3944                     , cdl_system_reference3
3945                     , cdl_system_reference4
3946                     , cdl_system_reference5 --NEW
3947                     , gl_date
3948                     , org_id
3949                     , unmatched_negative_txn_flag
3950                     , receipt_currency_amount
3951                     , receipt_currency_code
3952                     , receipt_exchange_rate
3953                     , denom_raw_cost
3954                     , denom_currency_code
3955                     , acct_rate_date
3956                     , acct_rate_type
3957                     , acct_exchange_rate
3958                     , acct_raw_cost
3959                     , acct_exchange_rounding_limit
3960                     , attribute_category
3961                     , attribute1
3962                     , attribute2
3963                     , attribute3
3964                     , attribute4
3965                     , attribute5
3966                     , attribute6
3967                     , attribute7
3968                     , attribute8
3969                     , attribute9
3970                     , attribute10
3971                     , orig_exp_txn_reference1
3972                     , orig_user_exp_txn_reference
3973                     , orig_exp_txn_reference2
3974                     , orig_exp_txn_reference3
3975                     , last_update_date
3976                     , last_updated_by
3977                     , creation_date
3978                     , created_by
3979                     , person_id
3980                     , organization_id
3981                     , project_id
3982                     , task_id
3983                     , Vendor_id
3984                     , override_to_organization_id
3985                     , person_business_group_id
3986                     , adjusted_expenditure_item_id --NEW
3987                     , fc_document_type  -- NEW
3988                     , document_type
3989                     , document_distribution_type
3990                     , adjusted_txn_interface_id
3991                     , sc_xfer_code
3992                     , si_assets_addition_flag
3993                     , net_zero_adjustment_flag
3994                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
3995                    )
3996                   SELECT
3997                       l_txn_src_tbl(i)
3998                      ,l_user_txn_src_tbl(i)
3999                      ,G_SYSTEM_LINKAGE
4000                      ,l_batch_name_tbl(i)
4001                      ,l_exp_end_date_tbl(i)
4002                      ,l_ei_date_tbl(i)
4003                      ,l_exp_type_tbl(i)
4004                      ,-l_quantity_tbl(i)
4005                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
4006                      ,l_description_tbl(i)
4007                      ,l_txn_status_code_tbl(i)
4008                      ,l_txn_rej_code_tbl(i)
4009                      ,G_REQUEST_ID
4010                      ,l_interface_id_tbl(i)
4011                      ,l_dist_cc_id_tbl(i)
4012                      ,l_acct_pay_cc_id_tbl(i)
4013                      ,l_vendor_id_tbl(i) /*sysref1*/
4014                      ,l_invoice_id_tbl(i) /*sysref2*/
4015                      ,l_cdl_sys_ref3_tbl(i)  --NULL /*sysref3*/
4016                      ,l_cdl_sys_ref4_tbl(i)
4017                      ,l_invoice_dist_id_tbl(i) /*sysref5*/ --NEW
4018                      ,l_gl_date_tbl(i)
4019                      ,G_ORG_ID
4020                      ,'Y'
4021                      ,-l_rec_cur_amt_tbl(i)
4022                      ,l_rec_cur_code_tbl(i)
4023                      ,l_rec_conv_rate_tbl(i)
4024                      ,-l_denom_raw_cost_tbl(i)
4025                      ,l_denom_cur_code_tbl(i)
4026                      ,l_acct_rate_date_tbl(i)
4027                      ,l_acct_rate_type_tbl(i)
4028                      ,l_acct_exch_rate_tbl(i)
4029                      ,-l_amount_tbl(i)
4030                      ,1
4031                      ,l_attribute_cat_tbl(i)
4032                      ,l_attribute1_tbl(i)
4033                      ,l_attribute2_tbl(i)
4034                      ,l_attribute3_tbl(i)
4035                      ,l_attribute4_tbl(i)
4036                      ,l_attribute5_tbl(i)
4037                      ,l_attribute6_tbl(i)
4038                      ,l_attribute7_tbl(i)
4039                      ,l_attribute8_tbl(i)
4040                      ,l_attribute9_tbl(i)
4041                      ,l_attribute10_tbl(i)
4042                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
4043                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
4044                      /* bug 2835757*/
4045                      ,DECODE(G_TRANS_DFF_AP,'N',NULL,l_invoice_id_tbl(i)) /*orig_exp_txn_reference2*/
4046                      ,NULL                       /*orig_exp_txn_reference3*/
4047                      ,SYSDATE
4048                      ,-1
4049                      ,SYSDATE
4050                      ,-1
4051                      ,l_employee_id_tbl(i)
4052                      ,l_org_id_tbl(i)
4053                      ,l_project_id_tbl(i)
4054                      ,l_task_id_tbl(i)
4055                      ,l_vendor_id_tbl(i)
4056                      ,l_exp_org_id_tbl(i)
4057                      ,l_bus_grp_id_tbl(i)
4058                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
4059                      ,l_fc_document_type_tbl(i) --NEW for funds check
4060                      ,l_inv_type_code_tbl(i)
4061                      ,l_ln_type_lookup_tbl(i)
4062                      ,(select xface.txn_interface_id
4063                        from   pa_transaction_interface xface
4064                        where  xface.interface_id = l_interface_id_tbl(i)
4065                        and    xface.cdl_system_reference2 = l_invoice_id_tbl(i)
4066                        and    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(i)
4067 		       and    NVL(xface.adjusted_expenditure_item_id,0) = 0 ) -- R12 funds management Uptake
4068                      ,'P' -- sc_xfer_code
4069                      ,'T' -- l_si_assts_add_flg_tbl(i)
4070                      ,l_net_zero_flag_tbl(i)
4071                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
4072                 FROM dual
4073                 WHERE l_insert_flag_tbl(i)= 'A';
4074 
4075                -- Handle both the parent and the reversal getting interfaced into PA
4076                -- in the same run.
4077                 write_log(LOG, 'Updating  adjustment records..');
4078 
4079               IF l_rev_child_dist_id_tbl.exists(1) THEN
4080 
4081                FOR i in l_rev_child_dist_id_tbl.FIRST ..l_rev_child_dist_id_tbl.LAST LOOP
4082 
4083                    IF l_rev_child_dist_id_tbl(i) > 0 THEN
4084 
4085                     UPDATE pa_transaction_interface_all xface
4086                     SET    xface.net_zero_adjustment_flag ='Y',
4087                            xface.adjusted_txn_interface_id =
4088                               (select distinct  xface1.txn_interface_id  /*Added Distinct for bug 9266578 */
4089                                from   pa_transaction_interface xface1
4090                                where  xface1.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
4091                                and    xface1.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
4092                                and    xface1.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
4093                                )
4094                       WHERE  xface.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
4095                       AND    xface.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
4096                       AND    xface.cdl_system_reference5 = l_rev_child_dist_id_tbl(i);
4097 
4098                    END IF;
4099 
4100                END LOOP;
4101 
4102               END IF;
4103     END IF;
4104 
4105    EXCEPTION
4106       WHEN OTHERS THEN
4107           write_log(LOG,'Failed during bulk insert for invoice processing');
4108           G_err_code   := SQLCODE;
4109           write_log(LOG, 'Error Code is '||SQLCODE);
4110           write_log(LOG, substr(SQLERRM, 1, 200));
4111           write_log(LOG, substr(SQLERRM, 201, 200));
4112           raise;
4113 
4114    END bulk_insert_trx_intf;
4115 
4116    PROCEDURE process_inv_logic IS
4117 
4118        l_status3 VARCHAR2(30);
4119        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
4120        l_historical_flag VARCHAR2(1);  --NEW
4121        l_process_adjustments    Number := 0 ;
4122        l_prepay_hist_flag VARCHAR2(1);
4123 	   -- Start: Added for CBS Enhancement Bug 16220146
4124 	   l_actual_task_id       NUMBER := 0;
4125 	   l_cbs_element_id       NUMBER := 0;
4126 	   -- End: Added for CBS Enhancement Bug 16220146
4127 
4128    BEGIN
4129 
4130        G_err_stage := ('Within Calling process logic of transfer_inv_to_pa');
4131        write_log(LOG, G_err_stage);
4132 
4133        /* Initializing global variables here to reduce code lines */
4134        G_NRT_TRANSACTION_SOURCE      := 'AP NRTAX' ;
4135        G_NRT_USER_TRANSACTION_SOURCE := 'Non-Recoverable Tax From Payables';
4136 
4137        G_AP_VAR_TRANSACTION_SOURCE  := 'AP VARIANCE';                                --NEW
4138        G_AP_VAR_USER_TXN_SOURCE     := 'Oracle Payables Invoice Variance';           --NEW
4139 
4140        G_AP_ERV_TRANSACTION_SOURCE  := 'AP ERV';                                --NEW
4141        G_AP_ERV_USER_TXN_SOURCE     := 'Oracle Payables Supplier Cost Exchange Rate Variance';           --NEW
4142 
4143        j := v_last_inv_index; -- initialize j to the total invoice distributions fetched in the PLSQL array
4144 
4145        FOR i IN  l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST  LOOP
4146 
4147            write_log(LOG,'Processing invoice id:  '||l_invoice_id_tbl(i)|| 'dist id:  '||l_invoice_dist_id_tbl(i));  --NEW
4148 
4149            /* We need to lock the corresponding receipts right away for each invoice distribution*/
4150            IF l_po_dist_id_tbl(i) IS NOT NULL
4151               -- Below clause added so that rcv trx not updated to status G for variance processing   /*Bug 13602288: Self Assessed Tax  Changes*/
4152               and l_ln_type_lookup_tbl(i) IN ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX','SELF_ASSESSED_TAX')  THEN
4153               lock_rcv_txn(l_po_dist_id_tbl(i));
4154            END IF;
4155 
4156            G_TRANSACTION_REJECTION_CODE := '';
4157 
4158            IF l_source_tbl(i) in ('CREDIT CARD','Both Pay') THEN
4159 
4160               write_log(LOG,'This is a credit card txn, setting emp id to paid_emp_id.');
4161               l_employee_id_tbl(i)   := l_paid_emp_id_tbl(i);
4162               l_inv_type_code_tbl(i) := 'EXPENSE REPORT';
4163 
4164            ELSIF l_inv_type_code_tbl(i) = 'EXPENSE REPORT' and l_employee_id_tbl(i) is null THEN
4165               write_log(LOG,'This is a CWK Exp Report, setting emp id to paid_emp_id.');
4166               l_employee_id_tbl(i)   := l_paid_emp_id_tbl(i);
4167 
4168            END IF;
4169 
4170 		   -- Start: Added for CBS Enhancement Bug 16220146
4171 		   IF l_project_id_tbl(i) is not null and l_task_id_tbl(i) IS NOT NULL THEN
4172 
4173 			  IF PA_ALTERNATE_TASK_PVT.Is_Cbs_Enabled(l_project_id_tbl(i)) = 'Y' THEN
4174 
4175 			     BEGIN
4176 
4177 				    SELECT PROJ_ELEMENT_ID, CBS_ELEMENT_ID
4178 					INTO l_actual_task_id, l_cbs_element_id
4179 					FROM PA_ALTERNATE_TASKS
4180 					WHERE alt_task_id = l_task_id_tbl(i);
4181 
4182 				EXCEPTION
4183 				   WHEN OTHERS THEN
4184 				      l_cbs_element_id_tbl(i) := NULL;
4185 				      RAISE;
4186 				END;
4187 
4188 				l_task_id_tbl(i) := l_actual_task_id;
4189 				l_cbs_element_id_tbl(i) := l_cbs_element_id;
4190 			  ELSE
4191 			     l_cbs_element_id_tbl(i) := NULL;
4192 			  END IF;
4193 		   ELSE
4194 		      l_cbs_element_id_tbl(i) := NULL;
4195 		   END IF;
4196 		   -- End: Added for CBS Enhancement Bug 16220146
4197 
4198            /* The following will be executed if the distribution being fetched belongs to a new invoice */
4199            IF (l_invoice_id_tbl(i) <> v_prev_invoice_id) THEN
4200 
4201                G_err_stage := ('New invoice being processed.New invoice _id is:'||l_invoice_id_tbl(i));
4202                write_log(LOG, G_err_stage);
4203 
4204                /* Update the previous invoice id and vendor id*/
4205                v_prev_invoice_id := l_invoice_id_tbl(i);
4206                v_prev_vendor_id  := l_vendor_id_tbl(i);
4207 
4208                /* Increment the counter for invoices */
4209               v_num_invoices_fetched := v_num_invoices_fetched + 1;  --uncommented for bug:7692973
4210 
4211                IF nvl(v_prev_invoice_source,l_source_tbl(i)||'111') <> l_source_tbl(i) THEN
4212 
4213                   /* First update the v_prev_invoice_source */
4214                   G_err_stage := 'New source encountered';
4215                   write_log(LOG, G_err_stage);
4216                   v_prev_invoice_source := l_source_tbl(i);
4217 
4218 
4219                   IF l_source_tbl(i) = 'PA_IP_INVOICES' THEN
4220 
4221                      G_err_stage := 'Invoice source is Inter-Company Invoice';
4222                      write_log(LOG, G_err_stage);
4223                      G_TRANSACTION_SOURCE      := 'INTERPROJECT_AP_INVOICES';
4224                      v_prev_transaction_source := G_TRANSACTION_SOURCE;
4225                      G_USER_TRANSACTION_SOURCE := 'Oracle Inter-Project Invoices';
4226 
4227                      L_IP_TRANSACTION_SOURCE      := 'INTERPROJECT_AP_INVOICES';
4228                      l_ip_inv_flag                := 'Y' ;
4229 
4230                   ELSIF (l_source_tbl(i)        = 'XpenseXpress' OR
4231                          /* if its a Credit card txn, treat like expense report*/
4232                          l_source_tbl(i) in ('CREDIT CARD','Both Pay') OR
4233                         (l_source_tbl(i)        = 'Manual Invoice Entry' AND
4234                          l_inv_type_code_tbl(i) = 'EXPENSE REPORT') OR
4235                          l_source_tbl(i)        = 'SelfService') THEN
4236 
4237                       G_err_stage := 'Invoice source is Expense Reports';
4238                       write_log(LOG, G_err_stage);
4239                       G_TRANSACTION_SOURCE      := 'AP EXPENSE';
4240                       v_prev_transaction_source := G_TRANSACTION_SOURCE;
4241                       G_USER_TRANSACTION_SOURCE := 'ORACLE PAYABLES';
4242 
4243                   ELSE
4244 
4245                       G_err_stage := 'Invoice source is AP Invoice';
4246                       write_log(LOG, G_err_stage);
4247                       G_TRANSACTION_SOURCE             := 'AP INVOICE';
4248                       v_prev_transaction_source := G_TRANSACTION_SOURCE;
4249 
4250                       G_USER_TRANSACTION_SOURCE        := 'AP INVOICE';
4251                       l_ap_inv_flag                    := 'Y' ;
4252 
4253                   END IF;
4254 
4255                END IF; /* invoice source <> v_prev_tranasction_source */
4256 
4257                 /* For new invoice, initialize the transaction status code to 'P' */
4258                 G_TRANSACTION_STATUS_CODE := 'P';
4259 
4260                 G_err_stage := 'GET MAX EXPENDITURE ENDING DATE';
4261                 write_log(LOG, G_err_stage);
4262                 SELECT pa_utils.getweekending(MAX(expenditure_item_date))
4263                   INTO G_EXPENDITURE_ENDING_DATE
4264                   FROM ap_invoice_distributions
4265                  WHERE invoice_id = l_invoice_id_tbl(i);
4266 
4267                 G_err_stage := ('Getting bus group id');
4268                 write_log(LOG, G_err_stage);
4269 
4270                 BEGIN
4271 
4272                    IF l_employee_id_tbl(i) <> 0 THEN
4273 		   Begin
4274                       write_log(LOG,'getting bus group id with emp id of :  '||l_employee_id_tbl(i));
4275 
4276                       SELECT emp.business_group_id
4277                         INTO G_PER_BUS_GRP_ID
4278                         FROM per_all_people_f emp
4279                        WHERE emp.person_id = l_employee_id_tbl(i)
4280                           AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and trunc(emp.effective_end_date);
4281 
4282 			EXCEPTION
4283 			   WHEN NO_DATA_FOUND THEN
4284 			      l_txn_status_code_tbl(i)     := 'R';
4285 			      G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
4286 			      write_log(LOG, 'As no data found for Employee, Rejecting invoice'||l_invoice_id_tbl(i)  );
4287  		    End;
4288 		   Else
4289 		    Begin
4290 
4291 			    select org2.business_group_id
4292 			      into G_PER_BUS_GRP_ID
4293 			      from hr_organization_units org1,
4294 				   hr_organization_units org2
4295 			     Where org1.organization_id = l_exp_org_id_tbl(i)
4296 			       and org1.business_group_id = org2.organization_id ;
4297 
4298 			    Exception
4299 			      When no_data_found Then
4300 				G_TRANSACTION_STATUS_CODE := 'R';
4301 				G_TRANSACTION_REJECTION_CODE := 'INVALID_ORGANIZATION';
4302 				write_log(LOG,'As no data found for Organization,Rejecting invoice '||l_invoice_id_tbl(i)  );
4303 		     End;
4304         	END IF;   /* IF l_employee_id_tbl(i) <> 0 THEN  */
4305 
4306                 END;
4307 
4308            END IF; /* end of check for different invoice_id from previous invoice_id */
4309 
4310 
4311            /* The following will be executed when the distribution belongs to the same
4312               invoice or not the same invoice */
4313 
4314            v_num_distributions_fetched := v_num_distributions_fetched + 1;
4315            write_log(LOG,'Num of distributions fetched:'||v_num_distributions_fetched);
4316 
4317            /*Update counter of how many distributions of the last invoice of the batch has been processed*/
4318 
4319            IF l_invoice_id_tbl(i) = l_invoice_id_tbl(v_last_inv_index) THEN
4320               v_num_last_invoice_processed := v_num_last_invoice_processed +1;
4321 
4322               IF l_inv_type_code_tbl(i) = 'EXPENSE REPORT' THEN
4323                  v_last_inv_ER_flag := 'Y';
4324               ELSE
4325                  v_last_inv_ER_flag := 'N';
4326               END IF;
4327 
4328            END IF;
4329 
4330            -- FC Doc Type
4331             IF l_fc_enabled_tbl(i) = 'N' THEN
4332              l_fc_document_type_tbl(i) := 'NOT';
4333             END IF;
4334 
4335            /* if the invoice is an expense report from self-service we need to use the column of justification as the description */
4336            IF (l_inv_type_code_tbl(i) = 'EXPENSE REPORT' AND
4337                l_source_tbl(i)        in ('SelfService','XpenseXpress') ) THEN
4338                l_description_tbl(i) := l_justification_tbl(i);
4339            END IF;
4340 
4341            IF l_ln_type_lookup_tbl(i)  in ('NONREC_TAX','TRV','TIPV','SELF_ASSESSED_TAX') THEN  /*Bug 13602288: Self Assessed Tax  Changes*/
4342 
4343               /* Update counter for number of tax lines fetched */
4344               v_num_tax_lines_fetched := v_num_tax_lines_fetched +1;
4345 
4346   	      l_quantity_tbl(i)     := 0; --for bug 9979559
4347 
4348               l_cdl_sys_ref4_tbl(i) := l_ln_type_lookup_tbl(i);
4349               l_txn_src_tbl(i)      := G_NRT_TRANSACTION_SOURCE;
4350               l_user_txn_src_tbl(i) := G_NRT_USER_TRANSACTION_SOURCE;
4351               l_batch_name_tbl(i)   := G_NRT_BATCH_NAME;
4352               l_interface_id_tbl(i) := G_NRT_INTERFACE_ID;
4353 
4354            ELSIF l_ln_type_lookup_tbl(i) = 'IPV' THEN
4355 
4356               /* Update counter for number of variance lines fetched */
4357               v_num_inv_variance_fetched :=  v_num_inv_variance_fetched +1;
4358 
4359               l_quantity_tbl(i)     := 0; --l_denom_raw_cost_tbl(i); --for bug 9979559
4360 
4361               l_cdl_sys_ref4_tbl(i) := l_ln_type_lookup_tbl(i);
4362 
4363               l_txn_src_tbl(i)      := G_AP_VAR_TRANSACTION_SOURCE;
4364               l_user_txn_src_tbl(i) := G_AP_VAR_USER_TXN_SOURCE;
4365               l_batch_name_tbl(i)   := G_AP_VAR_BATCH_NAME;
4366               l_interface_id_tbl(i) := G_AP_VAR_INTERFACE_ID;
4367 
4368            ELSIF l_ln_type_lookup_tbl(i) in ('ERV','TERV') THEN
4369 
4370               /* Update counter for number of variance lines fetched */
4371               v_num_inv_erv_fetched :=  v_num_inv_erv_fetched +1;
4372 
4373               l_quantity_tbl(i)     := 0; --l_denom_raw_cost_tbl(i); --for bug 9979559
4374 
4375               l_cdl_sys_ref4_tbl(i) := l_ln_type_lookup_tbl(i);
4376 
4377               l_txn_src_tbl(i)      := G_AP_ERV_TRANSACTION_SOURCE;
4378               l_user_txn_src_tbl(i) := G_AP_ERV_USER_TXN_SOURCE;
4379               l_batch_name_tbl(i)   := G_AP_ERV_BATCH_NAME;
4380               l_interface_id_tbl(i) := G_AP_ERV_INTERFACE_ID;
4381 
4382 
4383            ELSIF  l_ln_type_lookup_tbl(i) in ('FREIGHT','MISCELLANEOUS') THEN
4384               /* Update counter for number of frt and misc lines fetched */
4385               v_num_inv_frt_fetched :=  v_num_inv_frt_fetched +1;
4386 
4387               l_cdl_sys_ref4_tbl(i) := l_ln_type_lookup_tbl(i);
4388               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
4389               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
4390               l_batch_name_tbl(i)   := G_AP_FRT_BATCH_NAME;
4391               l_interface_id_tbl(i) := G_AP_FRT_INTERFACE_ID;
4392 
4393            ELSE -- Other distribution types like ITEM,ACCRUAL,PREPAY etc
4394 
4395               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
4396               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
4397               l_batch_name_tbl(i)   := G_BATCH_NAME;
4398               l_interface_id_tbl(i) := G_INTERFACE_ID;
4399 
4400            END IF ;
4401 
4402            G_TRANSACTION_REJECTION_CODE := '';
4403 
4404            /*Setting values according to global variables*/
4405            l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
4406            l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
4407            l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
4408            l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
4409 
4410            write_log(LOG,'Value of l_txn_src_tbl:'||l_txn_src_tbl(i) ||'batch name:'||l_batch_name_tbl(i));
4411 
4412            /*-----------------------------------------------------------------------*/
4413            /*         PREPAYMENT PROCESSING */
4414            /*-----------------------------------------------------------------------*/
4415            /* In Rel12 we will not interface any R12 PREPAYMENT invoice or PREPAY applications to Oracle Projects */
4416            /* Howver we will still continue to interface reversals or prepayment application related to 11i PREPAYENT invoices */
4417            --
4418            /* The records with INSERT_FLAG = F indicate that they are fully applied prepayments and the pa-addition-flag
4419               for such records will be updated to G to relieve commitments*/
4420            /* The records with INSERT_FLAG = P indicate that they are partially applied prepayments and the pa-addition-flag
4421               for such records will be updated to N */
4422 
4423            l_prepay_hist_flag := 'X'; --initialize
4424 
4425            IF nvl(l_hist_flag_tbl(i),'N') = 'Y' THEN
4426 
4427               l_prepay_hist_flag := 'Y';
4428 
4429            ELSE
4430 
4431              IF (l_prepay_dist_id_tbl(i) is not null OR l_ln_type_lookup_tbl(i) = 'PREPAY' OR --Bug#5219683
4432                  l_inv_type_code_tbl(i) = 'PREPAYMENT' ) THEN --Bug#5444174
4433 
4434               l_prepay_hist_flag := 'N';
4435 
4436                BEGIN
4437 
4438               If g_body_debug_mode = 'Y' Then
4439                 write_log(LOG, 'Checking if the prepay application or prepayment inv reversal belongs to historical prepayment inv');
4440                 write_log(LOG, 'Historical prepayment dist id is '||to_char(l_prepay_dist_id_tbl(i)));
4441                 write_log(LOG, 'Parent Prepayment dist id of reversal dist id is '||to_char(l_parent_rev_id_tbl(i)));
4442               End If;
4443 
4444               IF l_prepay_dist_id_tbl(i) is not null THEN
4445 
4446 	      IF l_is_self_assessed_tax_tbl(i) = 'N' then  --Bug 13602288: Self Assessed Tax Changes
4447                 SELECT nvl(historical_flag,'N')
4448                 INTO   l_prepay_hist_flag
4449                 FROM   ap_invoice_distributions_all
4450                 WHERE  invoice_distribution_id = l_prepay_dist_id_tbl(i);
4451 		ELSE
4452 		l_prepay_hist_flag := 'N';
4453 		END IF;
4454 
4455               ELSIF  l_parent_rev_id_tbl(i) is not null THEN --Bug#5444174
4456 
4457 	      IF l_is_self_assessed_tax_tbl(i) = 'N' then   --Bug 13602288: Self Assessed Tax Changes
4458                 SELECT nvl(historical_flag,'N')
4459                 INTO   l_prepay_hist_flag
4460                 FROM   ap_invoice_distributions_all
4461                 WHERE  invoice_distribution_id = l_parent_rev_id_tbl(i);
4462 	     ELSE
4463 	     l_prepay_hist_flag := 'N';
4464 	     END IF;
4465               END IF;
4466 
4467                 EXCEPTION
4468                 WHEN NO_DATA_FOUND THEN
4469                    l_txn_status_code_tbl(i) := 'R';
4470                    G_TRANSACTION_REJECTION_CODE := 'INVALID_INVOICE';
4471                    write_log(LOG, 'As no data found for parent distribution, Rejecting invoice dist Id'||l_invoice_dist_id_tbl(i));
4472                 WHEN OTHERS THEN
4473                    write_log(LOG, 'Error Code is  '||SQLCODE);
4474                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 1, 200));
4475                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 201, 200));
4476                    RAISE;
4477 
4478                 END;
4479 
4480              END IF;
4481            END IF;
4482 
4483            /* If the PREPAYMENT invoice was created pre-upgrade then the prepayment invoice and its
4484               application should be interfaced to PA else both should be prevented from interfacing to PA*/
4485 
4486            IF l_prepay_hist_flag = 'N' THEN
4487               IF (l_ln_type_lookup_tbl(i) = 'PREPAY' OR l_prepay_dist_id_tbl(i) IS NOT NULL ) THEN -- Bug#5444174
4488 
4489 write_log(LOG,'l_prepay_hist_flag '||l_prepay_hist_flag||' l_ln_type_lookup_tbl(i) '||l_ln_type_lookup_tbl(i)||' l_prepay_dist_id_tbl '||l_prepay_dist_id_tbl(i)||' l_is_self_assessed_tax_tbl '||l_is_self_assessed_tax_tbl(i));
4490 
4491                 IF check_prepay_fully_applied(l_prepay_dist_id_tbl(i),l_is_self_assessed_tax_tbl(i)) = 'Y' THEN   --Bug 13602288: Self Assessed Tax Changes
4492                    l_insert_flag_tbl(i) := 'F';
4493 		   write_log(LOG,' l_insert_flag_tbl '||l_insert_flag_tbl(i)||' check_prepay_fully_applied is Y');
4494                 ELSE
4495                    l_insert_flag_tbl(i) := 'P';
4496    		   write_log(LOG,' l_insert_flag_tbl '||l_insert_flag_tbl(i)||' check_prepay_fully_applied is N');
4497                 END IF;
4498 
4499               ELSIF l_inv_type_code_tbl(i) = 'PREPAYMENT' THEN -- bug5444174
4500 
4501 write_log(LOG,'l_prepay_hist_flag '||l_prepay_hist_flag||' l_ln_type_lookup_tbl(i) '||l_ln_type_lookup_tbl(i)||' l_prepay_dist_id_tbl '||l_prepay_dist_id_tbl(i)||' l_is_self_assessed_tax_tbl '||l_is_self_assessed_tax_tbl(i));
4502 
4503                 IF check_prepay_fully_applied(l_invoice_dist_id_tbl(i),l_is_self_assessed_tax_tbl(i)) = 'Y' THEN    --Bug 13602288: Self Assessed Tax Changes
4504                    l_insert_flag_tbl(i) := 'F';
4505 		   write_log(LOG,' l_insert_flag_tbl '||l_insert_flag_tbl(i)||' check_prepay_fully_applied is Y');
4506                 ELSE
4507                    l_insert_flag_tbl(i) := 'P';
4508    		   write_log(LOG,' l_insert_flag_tbl '||l_insert_flag_tbl(i)||' check_prepay_fully_applied is N');
4509                 END IF;
4510 
4511               END IF; --End of PREPAY AND PREPAYMENT inv
4512 
4513            ELSE  -- Distribution is historical data which should be interfaced into projects
4514 
4515            -- REVERSED DISTRIBUTIONS INTERFACE LOGIC
4516            -- If the distribution is a reversal or cancellation then check if the parent reversal distribution
4517            -- was historical data or not. If so, reversal distribution line will be interfaced as is.
4518            -- However if the parent reversal distribution is not historical then the following steps happen:
4519            -- a) Retreive the latest adjusted expenditures from PA against the parent reversal distribution id
4520            -- b) If any of the above latest EI's are not costed, then the reversed distribution will be rejected by the
4521            --    TRX import program
4522            -- c) IF all above adjusted EI's are costed, then insert record into the interface table for each adjusted EI.
4523            --    The project attributes will be copied from the adjusted EI's instead from the AP reversed
4524            --    distribution since these could have changed in PA.
4525            -- d) The interface program will interface the reversed distribution into projects
4526            -- e) The interface program will also insert a reversal of the reversed distribution into Projects. This is
4527            --    required for account reconciliation
4528            --
4529 
4530          -- This logic is to handle both the parent and reversal getting interfaced in the same run.
4531           -- It's a reversed parent record. Bug#4590527
4532           -- If both the parent and child reversing each other are interfaced in the same run, they
4533           -- were not getting interfaced as netzero transactions.
4534 
4535            IF (l_reversal_flag_tbl(i) = 'Y' or l_cancel_flag_tbl(i) = 'Y')
4536                                  AND l_parent_rev_id_tbl(i) IS NULL THEN
4537 
4538                 write_log(LOG, 'Reversal parent record '||l_invoice_dist_id_tbl(i));
4539               l_rev_index := l_rev_index +1;
4540               l_rev_parent_dist_id_tbl(l_rev_index) :=  l_invoice_dist_id_tbl(i);
4541               l_rev_child_dist_id_tbl(l_rev_index) :=  null;
4542               l_rev_parent_dist_ind_tbl(l_rev_index) :=  i; -- store the index of the parent.
4543 
4544            END IF;
4545 
4546            IF (l_reversal_flag_tbl(i) = 'Y' or l_cancel_flag_tbl(i) = 'Y') AND l_parent_rev_id_tbl(i) IS NOT NULL THEN
4547 
4548                 BEGIN
4549 
4550               If g_body_debug_mode = 'Y' Then
4551                 write_log(LOG, 'Checking if the invoice is a historical transaction');
4552                 write_log(LOG, 'Historical Transaction is '||to_char(l_parent_rev_id_tbl(i)));
4553                 write_log(LOG, 'Historical Invoice Id is '||to_char(l_invoice_id_tbl(i)));
4554               End If;
4555 
4556 
4557  /*Bug 13602288: Self Assessed Tax  Changes*/
4558                 if l_is_self_assessed_tax_tbl(i) = 'Y' then
4559 
4560 		l_historical_flag := 'N';
4561 
4562 		else
4563 
4564 		SELECT nvl(historical_flag,'N')
4565                 INTO   l_historical_flag
4566                 FROM   ap_invoice_distributions_all
4567                 WHERE  invoice_id = l_invoice_id_tbl(i)
4568                 AND    invoice_distribution_id = l_parent_rev_id_tbl(i); --check the index on this table
4569 
4570 		end if;
4571 
4572                 EXCEPTION
4573                 WHEN NO_DATA_FOUND THEN
4574                    l_txn_status_code_tbl(i) := 'R';
4575                    G_TRANSACTION_REJECTION_CODE := 'INVALID_INVOICE';
4576                    write_log(LOG, 'As no data found for reversed parent distribution, Rejecting invoice dist Id'||l_invoice_dist_id_tbl(i));
4577                 WHEN OTHERS THEN
4578                    write_log(LOG, 'Error Code is  '||SQLCODE);
4579                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 1, 200));
4580                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 201, 200));
4581                    RAISE;
4582 
4583                 END;
4584 
4585 
4586                 IF l_historical_flag = 'N' THEN
4587 
4588                      G_err_stage := 'Calling Process Adjustments';
4589                      write_log(LOG, G_err_stage);
4590 
4591                      -- Call reversal API
4592                      Process_Adjustments(p_record_type               => 'AP_INVOICE',
4593                                          p_document_header_id        => l_invoice_id_tbl(i),/*Added this for 6945767 */
4594                                          p_document_distribution_id  => l_parent_rev_id_tbl(i),
4595                                          p_current_index             => i,
4596 					 p_last_index                => j);
4597 
4598                      write_log(LOG, 'After calling Process Adjustments');
4599 
4600                       -- Set the create flag for adjustment records
4601                          IF l_insert_flag_tbl(i) in ('A','U') THEN
4602                           l_create_adj_recs := 'Y';
4603                          END IF;
4604 
4605                    If g_body_debug_mode = 'Y' Then
4606                      write_log(LOG, 'l_txn_rej_code_tbl = '||l_txn_rej_code_tbl(i));
4607                      write_log(LOG, 'l_txn_status_code_tbl = '||l_txn_status_code_tbl(i));
4608                    End If;
4609 
4610                 END IF; --End of check for historical Flag
4611 
4612            END IF; --End of check for reversal Distribution
4613 
4614            G_err_stage := ('Value of G_TRANS_DFF_AP:'||G_TRANS_DFF_AP);
4615            write_log(LOG, G_err_stage);
4616 
4617            IF (G_TRANS_DFF_AP = 'Y') THEN
4618 
4619                 v_attribute_category := l_attribute_cat_tbl(i);
4620                 v_attribute1 := l_attribute1_tbl(i);
4621                 v_attribute2 := l_attribute2_tbl(i);
4622                 v_attribute3 := l_attribute3_tbl(i);
4623                 v_attribute4 := l_attribute4_tbl(i);
4624                 v_attribute5 := l_attribute5_tbl(i);
4625                 v_attribute6 := l_attribute6_tbl(i);
4626                 v_attribute7 := l_attribute7_tbl(i);
4627                 v_attribute8 := l_attribute8_tbl(i);
4628                 v_attribute9 := l_attribute9_tbl(i);
4629                 v_attribute10 := l_attribute10_tbl(i);
4630 
4631                 v_dff_map_status := NULL;
4632 
4633                 PA_CLIENT_EXTN_DFFTRANS.DFF_map_segments_PA_and_AP(
4634                    p_calling_module            => 'PAAPIMP',
4635                    p_trx_ref_1                 => l_invoice_id_tbl(i),
4636                    --p_trx_ref_2                 => l_dist_line_num_tbl(i),
4637                    p_trx_ref_2                 => l_invoice_dist_id_tbl(i),  --NEW
4638                    p_trx_type                  => l_inv_type_code_tbl(i),
4639                    p_system_linkage_function   => G_SYSTEM_LINKAGE,
4640                    p_submodule                 => l_source_tbl(i),
4641                    p_expenditure_type          => l_exp_type_tbl(i),
4642                    p_set_of_books_id           => G_AP_SOB,
4643                    p_org_id                    => l_org_id_tbl(i),
4644                    p_attribute_category        => v_attribute_category,
4645                    p_attribute_1               => v_attribute1,
4646                    p_attribute_2               => v_attribute2,
4647                    p_attribute_3               => v_attribute3,
4648                    p_attribute_4               => v_attribute4,
4649                    p_attribute_5               => v_attribute5,
4650                    p_attribute_6               => v_attribute6,
4651                    p_attribute_7               => v_attribute7,
4652                    p_attribute_8               => v_attribute8,
4653                    p_attribute_9               => v_attribute9,
4654                    p_attribute_10              => v_attribute10,
4655                    x_status_code               => v_dff_map_status);
4656 
4657                    IF (v_dff_map_status IS NOT NULL) THEN
4658 
4659                        write_log(LOG, 'Error in DFF_map_segments_PA_and_AP, Error Code: ' || v_dff_map_status);
4660                        raise dff_map_exception;
4661 
4662                    END IF;
4663 
4664                    l_attribute_cat_tbl(i) := v_attribute_category;
4665                    l_attribute1_tbl(i) := v_attribute1;
4666                    l_attribute2_tbl(i) := v_attribute2;
4667                    l_attribute3_tbl(i) := v_attribute3;
4668                    l_attribute4_tbl(i) := v_attribute4;
4669                    l_attribute5_tbl(i) := v_attribute5;
4670                    l_attribute6_tbl(i) := v_attribute6;
4671                    l_attribute7_tbl(i) := v_attribute7;
4672                    l_attribute8_tbl(i) := v_attribute8;
4673                    l_attribute9_tbl(i) := v_attribute9;
4674                    l_attribute10_tbl(i) := v_attribute10;
4675 
4676 	   ElSE /* if DFF profile is No. Added for Bug 3105153*/
4677                    l_attribute_cat_tbl(i) := NULL;     --Bug#3856390
4678                    l_attribute1_tbl(i) := NULL;
4679                    l_attribute2_tbl(i) := NULL;
4680                    l_attribute3_tbl(i) := NULL;
4681                    l_attribute4_tbl(i) := NULL;
4682                    l_attribute5_tbl(i) := NULL;
4683                    l_attribute6_tbl(i) := NULL;
4684                    l_attribute7_tbl(i) := NULL;
4685                    l_attribute8_tbl(i) := NULL;
4686                    l_attribute9_tbl(i) := NULL;
4687                    l_attribute10_tbl(i) := NULL;
4688 
4689 	   END IF; /* if DFF profile is Yes */
4690 
4691         END IF; /* if prepay is fully applied */
4692 
4693       END LOOP; /* End of looping through each record in plsql table */
4694 
4695    EXCEPTION
4696       WHEN OTHERS THEN
4697           write_log(LOG,'Failed during process_inv_logic');
4698           G_err_code   := SQLCODE;
4699           raise;
4700 
4701    END process_inv_logic;
4702 
4703    BEGIN
4704    /* Main Procedure Logic starts here */
4705 
4706    G_err_stage := 'Within main procedure of transfer_inv_to_pa';
4707    write_log(LOG, G_err_stage);
4708 
4709      write_log(LOG, '......Result of G_TRANSACTION_SOURCE: ' || G_TRANSACTION_SOURCE);
4710 
4711      v_max_size := nvl(G_COMMIT_SIZE,200);
4712 
4713      -- Create a new interface ID for the first session
4714 
4715      OPEN Invoice_Cur;
4716 
4717      G_err_stage := 'After opening Invoice_Cur within transfer_inv_to_pa';
4718      write_log(LOG, G_err_stage);
4719 
4720      WHILE (v_all_done = 0) LOOP
4721 
4722        clear_plsql_tables;
4723 
4724        --Creating new interface ID every time this is called
4725        G_err_stage := 'CREATING NEW INTERFACE ID';
4726        write_log(LOG, G_err_stage);
4727 
4728        SELECT pa_interface_id_s.nextval
4729          INTO G_INTERFACE_ID
4730          FROM dual;
4731 
4732        G_err_stage := 'CREATING NEW NRT INTERFACE ID';
4733        SELECT pa_interface_id_s.nextval
4734          into G_NRT_INTERFACE_ID
4735          FROM dual;
4736 
4737 --new
4738        G_err_stage := 'CREATING NEW FRT INTERFACE ID';
4739        SELECT pa_interface_id_s.nextval
4740          into G_AP_FRT_INTERFACE_ID
4741          FROM dual;
4742 
4743 --new
4744        G_err_stage := 'CREATING NEW VARIANCE INTERFACE ID';
4745        SELECT pa_interface_id_s.nextval
4746          into G_AP_VAR_INTERFACE_ID
4747          FROM dual;
4748 --new
4749        G_err_stage := 'CREATING NEW VARIANCE INTERFACE ID';
4750        SELECT pa_interface_id_s.nextval
4751          into G_AP_ERV_INTERFACE_ID
4752          FROM dual;
4753 
4754           FETCH Invoice_Cur BULK COLLECT INTO
4755              l_invoice_id_tbl
4756 			,l_created_by_tbl
4757 			,l_invoice_dist_id_tbl --NEW
4758             ,l_cdl_sys_ref3_tbl
4759 			,l_project_id_tbl
4760 			,l_task_id_tbl
4761 			,l_ln_type_lookup_tbl
4762 			,l_exp_type_tbl
4763 			,l_ei_date_tbl
4764 			,l_amount_tbl
4765 			,l_description_tbl
4766 			,l_justification_tbl
4767 			,l_dist_cc_id_tbl
4768 			,l_exp_org_id_tbl
4769 			,l_quantity_tbl
4770 			,l_acct_pay_cc_id_tbl
4771 			,l_gl_date_tbl
4772 			,l_attribute_cat_tbl
4773 			,l_attribute1_tbl
4774 			,l_attribute2_tbl
4775 			,l_attribute3_tbl
4776 			,l_attribute4_tbl
4777 			,l_attribute5_tbl
4778 			,l_attribute6_tbl
4779 			,l_attribute7_tbl
4780 			,l_attribute8_tbl
4781 			,l_attribute9_tbl
4782 			,l_attribute10_tbl
4783 			,l_rec_cur_amt_tbl
4784 			,l_rec_cur_code_tbl
4785 			,l_rec_conv_rate_tbl
4786 			,l_denom_raw_cost_tbl
4787 			,l_denom_cur_code_tbl
4788 			,l_acct_rate_date_tbl
4789 			,l_acct_rate_type_tbl
4790 			,l_acct_exch_rate_tbl
4791 			,l_job_id_tbl
4792 			,l_employee_id_tbl
4793 			,l_vendor_id_tbl
4794 			,l_inv_type_code_tbl
4795 			,l_source_tbl
4796 			,l_org_id_tbl
4797 			,l_invoice_num_tbl
4798 			,l_cdl_sys_ref4_tbl
4799 			,l_po_dist_id_tbl
4800             ,l_txn_src_tbl
4801             ,l_user_txn_src_tbl
4802             ,l_batch_name_tbl
4803             ,l_interface_id_tbl
4804             ,l_exp_end_date_tbl
4805             ,l_txn_status_code_tbl
4806             ,l_txn_rej_code_tbl
4807             ,l_bus_grp_id_tbl
4808             ,l_paid_emp_id_tbl
4809             ,l_sort_var_tbl
4810             ,l_reversal_flag_tbl --NEW
4811             ,l_cancel_flag_tbl  --NEW
4812             ,l_parent_rev_id_tbl --NEW
4813             ,l_net_zero_flag_tbl --NEw
4814             ,l_sc_xfer_code_tbl
4815             ,l_adj_exp_item_id_tbl --NEW
4816             ,l_fc_enabled_tbl  --NEW
4817             ,l_mrc_exchange_date_tbl
4818             ,l_fc_document_type_tbl
4819             ,l_si_assts_add_flg_tbl
4820             ,l_insert_flag_tbl
4821             ,l_hist_flag_tbl
4822             ,l_prepay_dist_id_tbl
4823 	    ,l_is_self_assessed_tax_tbl -- Bug 13602288: Self Assessed Tax  Changes
4824             LIMIT v_max_size;
4825 
4826          G_err_stage := 'After fetching Invoice_Cur within transfer_inv_to_pa';
4827          write_log(LOG, G_err_stage);
4828 
4829          IF l_invoice_id_tbl.COUNT <> 0 THEN
4830 
4831             /* get the index of the last invoice being processed within the batch*/
4832             v_last_inv_index := l_invoice_id_tbl.LAST;
4833 
4834             G_err_stage := 'calling process_inv_logic within transfer_inv_to_pa';
4835             write_log(LOG, G_err_stage);
4836 
4837             process_inv_logic;
4838 
4839             -- Added below process to update the inv distributions to either G or N for prepayment procsssing
4840             G_err_stage := 'calling bulk_update_trx_intf within transfer_inv_to_pa';
4841             write_log(LOG, G_err_stage);
4842 
4843             bulk_update_trx_intf;
4844 
4845             G_err_stage := 'calling bulk_insert_trx_intf within transfer_inv_to_pa';
4846             write_log(LOG, G_err_stage);
4847 
4848             bulk_insert_trx_intf;
4849 
4850             G_err_stage := 'After calling bulk_insert_trx_intf within transfer_inv_to_pa';
4851             write_log(LOG, G_err_stage);
4852 
4853             OPEN Num_Dist_Marked_O(l_invoice_id_tbl(v_last_inv_index));
4854 
4855             G_err_stage := 'After opening cursor Num_Dist_Marked_O within transfer_inv_to_pa';
4856             write_log(LOG, G_err_stage);
4857 
4858             FETCH Num_Dist_Marked_O INTO
4859                   v_num_dist_marked_O;
4860 
4861             G_err_stage := 'After fetching cursor Num_Dist_Marked_O within transfer_inv_to_pa';
4862             write_log(LOG, G_err_stage);
4863 
4864             v_num_dist_remain := v_num_dist_marked_O - v_num_last_invoice_processed;
4865             write_log(LOG,'Number of last invoice processed:  '||v_num_last_invoice_processed||
4866                           'Number of last invoice remaining:  '||v_num_dist_remain);
4867 
4868             write_log(LOG,'Is the last invoice an expense report?  '||v_last_inv_ER_flag);
4869 
4870             IF (v_num_dist_remain  > 0 AND
4871                 v_last_inv_ER_flag = 'Y') THEN
4872 
4873                G_err_stage := 'Within condition of v_num_dist_remain>0 of transfer_inv_to_pa';
4874                write_log(LOG, G_err_stage);
4875 
4876                clear_plsql_tables;
4877 
4878                FETCH Invoice_Cur BULK COLLECT INTO
4879                   l_invoice_id_tbl,
4880                   l_created_by_tbl,
4881                   l_invoice_dist_id_tbl, --NEW
4882                   l_cdl_sys_ref3_tbl,
4883                   l_project_id_tbl,
4884                   l_task_id_tbl,
4885                   l_ln_type_lookup_tbl,
4886                   l_exp_type_tbl,
4887                   l_ei_date_tbl,
4888                   l_amount_tbl,
4889                   l_description_tbl,
4890                   l_justification_tbl,
4891                   l_dist_cc_id_tbl,
4892                   l_exp_org_id_tbl,
4893                   l_quantity_tbl,
4894                   l_acct_pay_cc_id_tbl,
4895                   l_gl_date_tbl,
4896                   l_attribute_cat_tbl,
4897                   l_attribute1_tbl,
4898              l_attribute2_tbl,
4899              l_attribute3_tbl,
4900              l_attribute4_tbl,
4901              l_attribute5_tbl,
4902              l_attribute6_tbl,
4903              l_attribute7_tbl,
4904              l_attribute8_tbl,
4905              l_attribute9_tbl,
4906              l_attribute10_tbl,
4907              l_rec_cur_amt_tbl,
4908              l_rec_cur_code_tbl,
4909              l_rec_conv_rate_tbl,
4910              l_denom_raw_cost_tbl,
4911              l_denom_cur_code_tbl,
4912              l_acct_rate_date_tbl,
4913              l_acct_rate_type_tbl,
4914              l_acct_exch_rate_tbl,
4915              l_job_id_tbl,
4916              l_employee_id_tbl,
4917              l_vendor_id_tbl,
4918              l_inv_type_code_tbl,
4919              l_source_tbl,
4920              l_org_id_tbl,
4921              l_invoice_num_tbl,
4922              l_cdl_sys_ref4_tbl,
4923              l_po_dist_id_tbl
4924              ,l_txn_src_tbl
4925              ,l_user_txn_src_tbl
4926              ,l_batch_name_tbl
4927              ,l_interface_id_tbl
4928              ,l_exp_end_date_tbl
4929               ,l_txn_status_code_tbl
4930               ,l_txn_rej_code_tbl
4931               ,l_bus_grp_id_tbl
4932               ,l_paid_emp_id_tbl
4933               ,l_sort_var_tbl
4934               ,l_reversal_flag_tbl --NEW
4935               ,l_cancel_flag_tbl  --NEW
4936               ,l_parent_rev_id_tbl --NEW
4937               ,l_net_zero_flag_tbl --NEW
4938               ,l_sc_xfer_code_tbl
4939               ,l_adj_exp_item_id_tbl --NEW
4940               ,l_fc_enabled_tbl --NEW
4941               ,l_mrc_exchange_date_tbl
4942               ,l_fc_document_type_tbl
4943               ,l_si_assts_add_flg_tbl
4944               ,l_insert_flag_tbl
4945               ,l_hist_flag_tbl
4946               ,l_prepay_dist_id_tbl
4947 	      ,l_is_self_assessed_tax_tbl -- Bug 13602288: Self Assessed Tax  Changes
4948             LIMIT v_num_dist_remain;
4949 
4950             G_err_stage := 'After second fetch of Invoice_Cur within transfer_inv_to_pa';
4951             write_log(LOG, G_err_stage);
4952 
4953                IF l_invoice_id_tbl.COUNT <> 0 THEN
4954 
4955                   G_err_stage := 'Before 2nd call of process_inv_logic  within transfer_inv_to_pa';
4956                   write_log(LOG, G_err_stage);
4957 
4958                   /* Set the index of the last invoice being processed within the batch*/
4959                   v_last_inv_index := l_invoice_id_tbl.LAST;
4960 
4961                   process_inv_logic;
4962 
4963                  -- Added below process to update the inv distributions to either G or N for prepayment procsssing
4964                   G_err_stage := 'calling bulk_update_trx_intf within transfer_inv_to_pa';
4965                   write_log(LOG, G_err_stage);
4966 
4967                   bulk_update_trx_intf;
4968 
4969                   G_err_stage := 'Before 2nd call of bulk_insert_trx_intf within transfer_inv_to_pa';
4970                   write_log(LOG, G_err_stage);
4971 
4972                   bulk_insert_trx_intf;
4973 
4974               END IF; /* l_invoice_id_tbl.COUNT = 0 */
4975 
4976            END IF; /* IF v_num_dist_remain > 0 */
4977 
4978            CLOSE Num_Dist_Marked_O;
4979 
4980 
4981            G_err_stage := 'Before calling transaction import and tiebacks within transfer_inv_to_pa';
4982            write_log(LOG, G_err_stage);
4983 
4984            IF (v_num_distributions_fetched > 0) THEN
4985 
4986                v_inv_batch_size           := v_num_distributions_fetched - v_num_tax_lines_fetched -
4987                                              v_num_inv_variance_fetched - v_num_inv_frt_fetched;
4988 
4989               write_log(LOG,'Before calling trx_import for invoices with interface_id:'||G_INTERFACE_ID);
4990               --Logic to handle IP and AP INVOICES getting interfaced in the same run.Bug#4764470.
4991 
4992              IF (l_ap_inv_flag ='Y' ) THEN
4993 
4994               write_log(LOG,'Before calling trx_import for AP invoices');
4995               trans_import('AP INVOICE', G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
4996               tieback_AP_ER('AP INVOICE', G_BATCH_NAME, G_INTERFACE_ID);
4997 
4998              END IF;
4999 
5000              IF (l_ip_inv_flag ='Y' ) THEN
5001 
5002               write_log(LOG,'Before calling trx_import for IP invoices');
5003               trans_import(L_IP_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
5004               tieback_AP_ER(L_IP_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID);
5005 
5006              ELSIF (l_ap_inv_flag ='N') THEN
5007 
5008               write_log(LOG,'Before calling trx_import for trx src ='||G_TRANSACTION_SOURCE);
5009               trans_import(G_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
5010               tieback_AP_ER(G_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID);
5011 
5012              END IF;
5013               --End of logic to handle IP and AP INVOICES getting interfaced in the same run.Bug#4764470.
5014 
5015 
5016               IF (nvl(v_num_tax_lines_fetched,0) > 0 AND
5017                      (G_INVOICE_TYPE IS NULL OR G_INVOICE_TYPE = 'EXPENSE REPORT')) THEN
5018 
5019                   write_log(LOG,'Before calling trx_import for NRTAX for interface_id:'||G_NRT_INTERFACE_ID);
5020                   v_tax_batch_size           := v_num_tax_lines_fetched;
5021 
5022                   trans_import(G_NRT_TRANSACTION_SOURCE, G_NRT_BATCH_NAME, G_NRT_INTERFACE_ID, G_USER_ID);
5023                   tieback_AP_ER(G_NRT_TRANSACTION_SOURCE, G_NRT_BATCH_NAME, G_NRT_INTERFACE_ID);
5024 
5025               END IF; /* IF (nvl(v_num_tax_lines_fetched,0) > 0*/
5026 
5027               IF nvl(v_num_inv_variance_fetched,0) > 0 THEN
5028 
5029                   write_log(LOG,'Before calling trx_import for Variance for interface_id:'||G_AP_VAR_INTERFACE_ID);
5030                   v_var_batch_size           := v_num_inv_variance_fetched;
5031 
5032                   trans_import(G_AP_VAR_TRANSACTION_SOURCE, G_AP_VAR_BATCH_NAME, G_AP_VAR_INTERFACE_ID, G_USER_ID);
5033                   tieback_AP_ER(G_AP_VAR_TRANSACTION_SOURCE, G_AP_VAR_BATCH_NAME, G_AP_VAR_INTERFACE_ID);
5034 
5035               END IF; /* IF (nvl(v_num_inv_variance_lines_fetched,0) > 0*/
5036 
5037               IF nvl(v_num_inv_erv_fetched,0) > 0 THEN
5038 
5039                   write_log(LOG,'Before calling trx_import for AP ERV for interface_id:'||G_AP_ERV_INTERFACE_ID);
5040                   v_var_batch_size           := v_num_inv_variance_fetched;
5041 
5042                   trans_import(G_AP_ERV_TRANSACTION_SOURCE, G_AP_ERV_BATCH_NAME, G_AP_ERV_INTERFACE_ID, G_USER_ID);
5043                   tieback_AP_ER(G_AP_ERV_TRANSACTION_SOURCE, G_AP_ERV_BATCH_NAME, G_AP_ERV_INTERFACE_ID);
5044 
5045               END IF; /* IF (nvl(v_num_inv_erv_lines_fetched,0) > 0*/
5046 
5047               IF nvl(v_num_inv_frt_fetched,0) > 0 THEN
5048 
5049                   write_log(LOG,'Before calling trx_import for Frt and Misc for interface_id:'||G_AP_FRT_INTERFACE_ID);
5050                   v_frt_batch_size           := v_num_inv_frt_fetched;
5051 
5052                   trans_import(G_TRANSACTION_SOURCE, G_AP_FRT_BATCH_NAME, G_AP_FRT_INTERFACE_ID, G_USER_ID);
5053                   tieback_AP_ER(G_TRANSACTION_SOURCE, G_AP_FRT_BATCH_NAME, G_AP_FRT_INTERFACE_ID);
5054 
5055               END IF; /* IF (nvl(v_num_inv_frt_lines_fetched,0) > 0*/
5056 
5057               write_log(LOG,'Calling tieback for locked RCV transactions');
5058               tieback_locked_rcvtxn;
5059 
5060 /*** Commented 3922679  *
5061               G_err_stage := 'Before calling commit';
5062               write_log(LOG, G_err_stage);
5063               COMMIT;
5064 *** Commented 3922679  End*/
5065 
5066               G_err_stage := 'Before updating the total number of invoices processed';
5067               write_log(LOG, G_err_stage);
5068 
5069               G_NUM_BATCHES_PROCESSED       := G_NUM_BATCHES_PROCESSED + 1;
5070               G_NUM_INVOICES_PROCESSED      :=  G_NUM_INVOICES_PROCESSED + v_num_invoices_fetched;
5071               G_NUM_DISTRIBUTIONS_PROCESSED :=  G_NUM_DISTRIBUTIONS_PROCESSED + v_num_distributions_fetched;
5072               write_log(LOG,'G_NUM_BATCHES_PROCESSED:'||G_NUM_BATCHES_PROCESSED);
5073               write_log(LOG,'G_NUM_INVOICES_PROCESSED:'||G_NUM_INVOICES_PROCESSED);
5074               write_log(LOG,'G_NUM_DISTRIBUTIONS_PROCESSED:'||G_NUM_DISTRIBUTIONS_PROCESSED);
5075 
5076         END IF; /* IF (v_num_distributions_fetched > 0) */
5077 
5078         G_err_stage := 'After calling transaction import and tiebacks within transfer_inv_to_pa';
5079         write_log(LOG, G_err_stage);
5080 
5081         clear_plsql_tables;
5082 
5083         v_num_invoices_fetched       :=0;
5084         v_num_distributions_fetched  :=0;
5085         v_num_tax_lines_fetched      :=0;
5086         v_inv_batch_size             :=0;
5087         v_tax_batch_size             :=0;
5088         v_var_batch_size             :=0;
5089         v_frt_batch_size             :=0;
5090         v_num_dist_remain            :=0;
5091         v_num_dist_marked_O          :=0;
5092         v_num_last_invoice_processed :=0;
5093         v_last_inv_ER_flag           := 'N';
5094 
5095         G_err_stage:='Before exiting when Invoice_Cur is NOTFOUND';
5096         write_log(LOG,   G_err_stage);
5097 
5098       ELSE
5099 
5100           G_err_stage:='Cursor fetched zero rows into plsql tables. Exiting';
5101           write_log(LOG,   G_err_stage);
5102           EXIT;
5103       END IF; /* l_invoice_id_tbl.COUNT = 0 */
5104 
5105       G_err_stage:='Cursor fetched no more rows. Exiting';
5106       write_log(LOG,   G_err_stage);
5107       EXIT WHEN Invoice_Cur%NOTFOUND;
5108 
5109    END LOOP; /* While more rows to process is true */
5110 
5111    CLOSE Invoice_Cur;
5112 
5113 EXCEPTION
5114     WHEN OTHERS THEN
5115 
5116          G_err_stack := v_old_stack;
5117          IF invoice_cur%ISOPEN THEN
5118            CLOSE Invoice_Cur;
5119          END IF ;
5120 
5121          G_err_code := SQLCODE;
5122          RAISE;
5123 
5124 END transfer_inv_to_pa;
5125 
5126 /*---------------------------Tieback to AP Phase----------------------------*/
5127 PROCEDURE tieback_AP_ER(
5128    p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
5129    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
5130    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
5131 
5132    l_assets_addflag          VARCHAR2(1):=NULL;
5133    l_prev_assets_addflag     VARCHAR2(1):=NULL;
5134    l_project_id             NUMBER :=0;
5135    l_pa_addflag             VARCHAR2(1):=NULL;
5136    l_prev_proj_id           NUMBER :=0;
5137 
5138    l_sys_ref1_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
5139    l_sys_ref2_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
5140 --   l_sys_ref3_tbl           PA_PLSQL_DATATYPES.Char15TabTyp; --NEW
5141 --   l_sys_ref4_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
5142    l_sys_ref5_tbl           PA_PLSQL_DATATYPES.IdTabTyp;    --NEW --check with Ajay if its declared as number type
5143    l_txn_src_tbl            PA_PLSQL_DATATYPES.Char30TabTyp;
5144    l_batch_name_tbl         PA_PLSQL_DATATYPES.Char50TabTyp;
5145    l_interface_id_tbl       PA_PLSQL_DATATYPES.IdTabTyp;
5146    l_txn_status_code_tbl    PA_PLSQL_DATATYPES.Char2TabTyp;
5147    l_project_id_tbl            PA_PLSQL_DATATYPES.IdTabTyp;
5148    l_pa_addflag_tbl         PA_PLSQL_DATATYPES.CHAR1TabTyp;
5149    l_assets_addflag_tbl     PA_PLSQL_DATATYPES.CHAR1TabTyp;
5150    l_document_dist_type_tbl   PA_PLSQL_DATATYPES.Char30TabTyp;	/*Bug 13602288: Self Assessed Tax  Changes*/
5151 
5152 
5153    CURSOR txn_intf_rec (p_txn_src       IN VARCHAR2,
5154                         p_batch_name    IN VARCHAR2,
5155                         p_interface_id  IN NUMBER) IS
5156       SELECT cdl_system_reference1
5157             ,cdl_system_reference2
5158          --   ,cdl_system_reference3  --NEW
5159          --   ,cdl_system_reference4
5160             ,cdl_system_reference5 --NEW
5161             ,transaction_source
5162             ,batch_name
5163             ,interface_id
5164             ,transaction_status_code
5165             ,project_id
5166             ,l_pa_addflag
5167             ,l_assets_addflag
5168 	    ,document_distribution_type                       /*Bug 13602288: Self Assessed Tax  Changes*/
5169         FROM pa_transaction_interface_all txnintf
5170        WHERE txnintf.transaction_source = p_txn_src
5171          AND txnintf.batch_name         = p_batch_name
5172          AND txnintf.interface_id       = p_interface_id;
5173 
5174    PROCEDURE clear_plsql_tables IS
5175 
5176       v_status   VARCHAR2(15);
5177 
5178    BEGIN
5179 
5180       G_err_stage:='Clearing PLSQL tables in invoice tieback';
5181       write_log(LOG,   G_err_stage);
5182 
5183       l_sys_ref1_tbl.delete;
5184       l_sys_ref2_tbl.delete;
5185    --   l_sys_ref3_tbl.delete; --NEW
5186    --   l_sys_ref4_tbl.delete; --NEW
5187       l_sys_ref5_tbl.delete; --NEW
5188       l_txn_src_tbl.delete;
5189       l_batch_name_tbl.delete;
5190       l_interface_id_tbl.delete;
5191       l_txn_status_code_tbl.delete;
5192       l_project_id_tbl.delete;
5193       l_pa_addflag_tbl.delete;
5194       l_assets_addflag_tbl.delete;
5195       l_document_dist_type_tbl.delete;   /*Bug 13602288: Self Assessed Tax  Changes*/
5196 
5197    END clear_plsql_tables;
5198 
5199    PROCEDURE process_tieback IS
5200 
5201       v_status   VARCHAR2(15);
5202 
5203    BEGIN
5204 
5205       G_err_stage:='Within process_tieback of invoice tieback';
5206       write_log(LOG,   G_err_stage);
5207 
5208       FOR i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST LOOP
5209 
5210          /* If transaction import stamps the record to be 'A' then
5211             update pa_addition_flag of invoice distribution to 'Y'.
5212             If transaction import leaves the record to be 'P' then
5213             update pa_addition_flag of invoice distribution to 'N'.
5214             If transaction import stamps the record to be 'R' then
5215             update pa_addition_flag of invoice distribution to 'N'.*/
5216 
5217          write_log(LOG,'Tying invoice_id: '||l_sys_ref2_tbl(i)||
5218                        --'dist num:  '||l_sys_ref3_tbl(i)||  --NEW
5219                        'dist id:  '||l_sys_ref5_tbl(i)||  --NEW
5220                        'trc src:   '||l_txn_src_tbl(i));
5221 
5222          IF l_txn_status_code_tbl(i) = 'A' THEN
5223                l_pa_addflag_tbl(i) := 'Y';
5224          ELSIF l_txn_status_code_tbl(i) = 'P' THEN
5225                l_pa_addflag_tbl(i) :='N';
5226          ELSIF l_txn_status_code_tbl(i) = 'R' THEN
5227                l_pa_addflag_tbl(i) := 'N';
5228          END IF;
5229 
5230          IF G_PROJECT_ID IS NOT NULL THEN
5231 
5232             IF G_Assets_Addition_flag = 'P' THEN
5233                l_assets_addflag_tbl(i) := 'P';
5234             ELSE
5235                l_assets_addflag_tbl(i) := 'X';
5236             END IF;
5237 
5238          ELSIF G_PROJECT_ID IS NULL THEN
5239 
5240             IF l_project_id_tbl(i) <> l_prev_proj_id THEN
5241 
5242                G_err_stage:='Selecting assets addition flag within invoice tieback';
5243                write_log(LOG,   G_err_stage);
5244 
5245                SELECT decode(PTYPE.Project_Type_Class_Code,'CAPITAL','P','X')
5246                  INTO l_assets_addflag_tbl(i)
5247                  FROM pa_project_types_all PTYPE,
5248                       pa_projects_all PROJ
5249                 WHERE PTYPE.Project_Type = PROJ.Project_Type
5250                   AND (PTYPE.org_id = PROJ.org_id OR
5251                        PROJ.org_id is null)
5252                   AND PROJ.Project_Id = l_project_id_tbl(i);
5253 
5254                 l_prev_proj_id := l_project_id_tbl(i);
5255 		l_prev_assets_addflag := l_assets_addflag_tbl(i);
5256 
5257             ELSE
5258                l_assets_addflag_tbl(i) := l_prev_assets_addflag;
5259             END IF;
5260 
5261          END IF;
5262 
5263       END LOOP;
5264 
5265    EXCEPTION
5266       WHEN OTHERS THEN
5267          G_err_stage:= 'Failed during process tieback of invoice tieback';
5268          write_log(LOG,   G_err_stage);
5269          G_err_code   := SQLCODE;
5270          raise;
5271 
5272    END process_tieback;
5273 
5274    PROCEDURE bulk_update_txn_intf IS
5275 
5276       v_status VARCHAR2(15);
5277 
5278    BEGIN
5279 
5280       G_err_stage:=('Within bulk update of invoice tieback');
5281       write_log(LOG,   G_err_stage);
5282 
5283       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
5284 
5285          UPDATE ap_invoice_distributions_all dist
5286             SET dist.pa_addition_flag         = l_pa_addflag_tbl(i)
5287                ,dist.assets_addition_flag      = decode(l_assets_addflag_tbl(i),'P','P',dist.assets_addition_flag)
5288           WHERE dist.invoice_id               = l_sys_ref2_tbl(i)
5289             AND dist.invoice_distribution_id  = l_sys_ref5_tbl(i)
5290             AND dist.pa_addition_flag         = 'O'
5291 	    AND l_document_dist_type_tbl(i) <> 'SELF_ASSESSED_TAX';  /*Bug 13602288: Self Assessed Tax  Changes*/
5292 
5293 
5294   /*Bug 13602288: Self Assessed Tax  Changes*/
5295 	FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
5296 
5297          UPDATE ap_self_assessed_tax_dist_all dist
5298             SET dist.pa_addition_flag         = l_pa_addflag_tbl(i)
5299                ,dist.assets_addition_flag      = decode(l_assets_addflag_tbl(i),'P','P',dist.assets_addition_flag)
5300           WHERE dist.invoice_id               = l_sys_ref2_tbl(i)
5301             AND dist.invoice_distribution_id  = l_sys_ref5_tbl(i)
5302             AND dist.pa_addition_flag         = 'O'
5303 	    AND l_document_dist_type_tbl(i) = 'SELF_ASSESSED_TAX';
5304 
5305 
5306       /* Bug 5440548 fix to update expenditure data with historical flag for historical AP data */
5307       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
5308 
5309          UPDATE pa_expenditure_items_all exp1
5310             SET historical_flag = 'Y'
5311          WHERE  document_header_id = l_sys_ref2_tbl(i)
5312            AND  document_distribution_id = l_sys_ref5_tbl(i)
5313 	   AND document_distribution_type <> 'SELF_ASSESSED_TAX'    /*Bug 13602288: Self Assessed Tax  Changes*/
5314            AND  exists (select 'exist'
5315                         from   ap_invoice_distributions_all dist
5316                         where  dist.invoice_id =l_sys_ref2_tbl(i)
5317                         and    dist.invoice_distribution_id = l_sys_ref5_tbl(i)
5318                         and    dist.pa_addition_flag = 'Y'
5319                         and    dist.historical_flag = 'Y');
5320 
5321          /* If the accounting method is CASH BASIS then the payment lines associated with historical invoices should be updated to G
5322             since such invoice distributions will be not be interfaced as PAYMENTS but as INVOICES */
5323 
5324          IF G_ACCTNG_METHOD = 'C' THEN
5325 
5326            FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
5327 
5328            UPDATE ap_payment_hist_dists dist
5329               SET    dist.pa_addition_flag = 'G',
5330                      request_id = G_REQUEST_ID,
5331                      last_update_date=SYSDATE,
5332                      last_updated_by= G_USER_ID,
5333                      last_update_login= G_USER_ID,
5334                      program_id= G_PROG_ID,
5335                      program_application_id= G_PROG_APPL_ID,
5336                      program_update_date=SYSDATE
5337               WHERE  dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
5338               AND   dist.pay_dist_lookup_code = 'CASH'
5339               AND EXISTS (SELECT NULL
5340                           FROM   ap_payment_history_all hist
5341                           WHERE  hist.payment_history_id = dist.payment_history_id
5342                           AND    hist.posted_flag = 'Y')
5343               AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
5344                              FROM AP_INVOICES_ALL inv,
5345                                   AP_Invoice_Distributions_all aid,
5346                                   ap_invoice_payments_all aip
5347                             WHERE inv.invoice_id              = aip.invoice_id
5348                               AND aid.invoice_id              = inv.invoice_id
5349                               AND aip.invoice_payment_id      = dist.invoice_payment_id
5350                               AND aid.invoice_distribution_id = dist.invoice_distribution_id
5351                               AND inv.org_id = G_ORG_ID
5352                               AND aip.invoice_id              = l_sys_ref2_tbl(i)
5353                               AND aid.invoice_distribution_id = l_sys_ref5_tbl(i));
5354 
5355          END IF;
5356    EXCEPTION
5357       WHEN OTHERS THEN
5358          G_err_stage:= 'Failed during bulk update of invoice tieback';
5359          write_log(LOG,   G_err_stage);
5360          G_err_code   := SQLCODE;
5361          raise;
5362 
5363    END bulk_update_txn_intf;
5364 
5365    BEGIN
5366 
5367       /* Main logic of tieback starts here */
5368       G_err_stage:='Within main logic of tieback';
5369       write_log(LOG,   G_err_stage);
5370 
5371       clear_plsql_tables;
5372 
5373       G_err_stage:='Opening txn_intf_rec';
5374       write_log(LOG,   G_err_stage);
5375 
5376       OPEN txn_intf_rec(p_transaction_source
5377                        ,p_batch_name
5378                        ,p_interface_id);
5379 
5380       G_err_stage:='Fetching txn_intf_rec';
5381       write_log(LOG,   G_err_stage);
5382 
5383       FETCH txn_intf_rec BULK COLLECT INTO
5384           l_sys_ref1_tbl
5385          ,l_sys_ref2_tbl
5386          --,l_sys_ref3_tbl --NEW
5387          --,l_sys_ref4_tbl --NEW
5388          ,l_sys_ref5_tbl  --NEW
5389          ,l_txn_src_tbl
5390          ,l_batch_name_tbl
5391          ,l_interface_id_tbl
5392          ,l_txn_status_code_tbl
5393          ,l_project_id_tbl
5394          ,l_pa_addflag_tbl
5395          ,l_assets_addflag_tbl
5396 	 ,l_document_dist_type_tbl;  /* Bug 13602288: Self assessed tax */
5397 
5398       IF l_sys_ref1_tbl.COUNT <> 0 THEN
5399 
5400          process_tieback;
5401 
5402          bulk_update_txn_intf;
5403 
5404          clear_plsql_tables;
5405 
5406       END IF;
5407 
5408       CLOSE txn_intf_rec;
5409 
5410 EXCEPTION
5411    WHEN OTHERS THEN
5412 
5413       IF txn_intf_rec%ISOPEN THEN
5414          CLOSE txn_intf_rec;
5415       END IF;
5416 
5417       G_err_code := SQLCODE;
5418       RAISE;
5419 
5420 END tieback_AP_ER;
5421 
5422 
5423 PROCEDURE lock_rcv_txn (p_po_distribution_id IN ap_invoice_distributions.po_distribution_id%TYPE) IS
5424 
5425    l_num_rows   NUMBER;
5426 
5427 BEGIN
5428 
5429    G_err_stage := 'Within calling lock_rcv_txn';
5430    write_log(LOG, G_err_stage);
5431 
5432 --pricing changes, updating sub_ledger instead of rcv_transactions
5433 -- Modified this update for bug 6825742
5434 
5435 UPDATE rcv_receiving_sub_ledger rcv_sub
5436 SET rcv_sub.pa_addition_flag = 'L'
5437 WHERE rcv_sub.pa_addition_flag = 'N'
5438 and reference3 = TO_CHAR(p_po_distribution_id) and exists (
5439 select 1 from po_distributions_all pod
5440 where po_distribution_id = TO_NUMBER(rcv_sub.reference3)
5441 and   po_distribution_id = p_po_distribution_id
5442 and code_combination_id = rcv_sub.code_combination_id
5443 and accrue_on_receipt_flag = 'Y');
5444 
5445    /* UPDATE rcv_receiving_sub_ledger rcv_sub
5446       SET rcv_sub.pa_addition_flag   = 'L'
5447     WHERE rcv_sub.pa_addition_flag   = 'N'
5448     AND EXISTS (SELECT transaction_id
5449 		FROM rcv_transactions rcv_txn
5450 		WHERE rcv_txn.transaction_id = rcv_sub.rcv_transaction_id
5451 		AND rcv_txn.po_distribution_id = p_po_distribution_id ); commented for bug 6825742*/
5452 
5453    l_num_rows := SQL%ROWCOUNT;
5454 
5455    write_log(LOG,'number of RCV transactions locked:'||l_num_rows);
5456 
5457 EXCEPTION
5458    WHEN NO_DATA_FOUND THEN
5459       NULL;
5460 
5461    WHEN OTHERS THEN
5462      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
5463      G_err_code := SQLCODE;
5464      RAISE;
5465 
5466 END lock_rcv_txn;
5467 
5468 PROCEDURE tieback_locked_rcvtxn IS
5469 
5470    l_num_rows NUMBER;
5471 
5472 BEGIN
5473 
5474    G_err_stage := 'Within calling tieback_locked_rcvtxn';
5475    write_log(LOG, G_err_stage);
5476 
5477    UPDATE rcv_receiving_sub_ledger rcv_sub
5478       SET rcv_sub.pa_addition_flag = 'G'
5479     WHERE rcv_sub.pa_addition_flag = 'L';
5480 
5481    l_num_rows := SQL%ROWCOUNT;
5482 
5483    write_log(LOG,'number of RCV transactions unlocked:'||l_num_rows);
5484 
5485 EXCEPTION
5486    WHEN NO_DATA_FOUND THEN
5487        NULL;
5488 
5489    WHEN OTHERS THEN
5490 
5491      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
5492      G_err_code := SQLCODE;
5493      RAISE;
5494 END tieback_locked_rcvtxn;
5495 
5496    Function get_cdl_ccid(p_expenditure_item_id IN NUMBER, ccid_flag IN varchar2)
5497    RETURN NUMBER is
5498 
5499    l_cr_ccid NUMBER;
5500    l_dr_ccid NUMBER;
5501 
5502    begin
5503 
5504        IF p_expenditure_item_id <> l_prev_exp_item_id THEN
5505 
5506        G_err_stage := 'Selecting Adjustment account: get_cdl_ccid';
5507        write_log(LOG, G_err_stage);
5508 
5509        SELECT cr_code_combination_id, dr_code_combination_id
5510        INTO   l_cr_ccid, l_dr_ccid
5511        FROm   pa_cost_distribution_lines_all cdl
5512        WHERE  cdl.expenditure_item_id = p_expenditure_item_id
5513        AND    cdl.line_num in (select max(line_num)
5514                                from pa_cost_distribution_lines_all cdl2
5515                                where  cdl2.expenditure_item_id = cdl.expenditure_item_id
5516                                and    line_type ='R');
5517 
5518        l_prev_exp_item_id := p_expenditure_item_id;
5519        l_prev_cr_ccid := l_cr_ccid;
5520        l_prev_dr_ccid := l_dr_ccid;
5521 
5522 
5523        END IF;
5524 
5525        IF ccid_flag = 'C' THEN
5526          return l_prev_cr_ccid;
5527        ELSE
5528          return l_prev_dr_ccid;
5529        END IF;
5530 
5531 
5532        EXCEPTION WHEN NO_DATA_FOUND THEN
5533          return null;
5534    End;
5535 
5536 
5537 /*==========================================================================*/
5538 --The following section contains procedures for Supplier Invoice Discounts
5539 --The logic of doscount processing can be undestood as:
5540 -- 1) Update PA_addition_flag on Discount payment lines to 'O' to lock the record
5541 -- 3) Transfer_disc_to_pa populates PA transaction_interface table and call trx import
5542 -- 4) Tieback procedure called to update discount payment lines after trx import
5543 /*==========================================================================*/
5544 
5545 /*-----Function checks the profile setup of cutoff date for which discounts to be pulled----*/
5546 FUNCTION return_profile_discount_date
5547     RETURN VARCHAR2 IS
5548 
5549    v_discount_start_date VARCHAR2(15);
5550 
5551 BEGIN
5552 
5553     select nvl(fnd_profile.value_specific('PA_DISC_PULL_START_DATE'),'2051/01/01')  --bug4474213.
5554       INTO v_discount_start_date
5555       from DUAL;
5556     RETURN v_discount_start_date;
5557 
5558 END return_profile_discount_date;
5559 
5560 /*-----Function checks what method of discount is used by system-----*/
5561 FUNCTION return_discount_method
5562      RETURN VARCHAR2 IS
5563 
5564      v_method VARCHAR2(15);
5565 
5566 BEGIN
5567 
5568      SELECT discount_distribution_method
5569         INTO v_method
5570         FROM AP_SYSTEM_PARAMETERS;
5571       RETURN v_method;
5572 
5573 END return_discount_method;
5574 
5575 /*-----------------------Marking Distribution Phase---------------------*/
5576 
5577 PROCEDURE mark_PA_disc_flag_O IS
5578 
5579         v_old_stack VARCHAR2(630);
5580 
5581 BEGIN
5582 
5583      v_old_stack := G_err_stack;
5584      G_err_stack := G_err_stack || '->PAAPIMP_PKG.mark_PA_Disc_flag_O';
5585      G_err_code := 0;
5586      G_err_stage := 'UPDATING DISCOUNT DISTRIBUTIONS-Marking Process';
5587 
5588      write_log(LOG, G_err_stack);
5589 
5590      IF G_PROJECT_ID is not NULL THEN
5591 
5592           -- Mark all Discount lines associated with PREPAYMENT payment to G to prevent interface into Projects
5593           -- In Rel12, we will only bring in Prepayment application lines (AP_PREPAY_APP_DISTS) into Projects for Cash Based Acctng
5594 
5595             UPDATE ap_payment_hist_dists dist
5596             SET    dist.pa_addition_flag = 'G',
5597                    request_id = G_REQUEST_ID,
5598                    last_update_date=SYSDATE,
5599                    last_updated_by= G_USER_ID,
5600                    last_update_login= G_USER_ID,
5601                    program_id= G_PROG_ID,
5602                    program_application_id= G_PROG_APPL_ID,
5603                    program_update_date=SYSDATE
5604             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
5605             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
5606             AND EXISTS (SELECT NULL
5607                         FROM   ap_payment_history_all hist
5608                         WHERE  hist.payment_history_id = dist.payment_history_id
5609                         AND    hist.posted_flag = 'Y')
5610             AND   exists(SELECT inv.invoice_id -- 11658939 hint del no_unnest
5611                            FROM AP_INVOICES_ALL inv,
5612                                 AP_Invoice_Distributions_all aid,
5613                                 ap_invoice_payments_all aip
5614                           WHERE inv.invoice_id = aip.invoice_id
5615                             AND aid.invoice_id = inv.invoice_id
5616                             AND aip.invoice_payment_id = dist.invoice_payment_id
5617                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
5618                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'         --Prevent prepayment payments from being transferred to Projects
5619                             AND aid.project_id = G_PROJECT_ID
5620                             AND aid.invoice_id = aip.invoice_id
5621                             AND inv.org_id = G_ORG_ID
5622                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
5623                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
5624 
5625         If g_body_debug_mode = 'Y' Then
5626           write_log(LOG, 'Number of Discount prepayments  marked to G: ' || to_char(SQL%ROWCOUNT));
5627           write_log(LOG, 'cash basis: ' || G_ACCTNG_METHOD);
5628           write_log(LOG, 'cash basis2: ' || to_char(G_Profile_Discount_Start_date,'DD-MON-RR'));
5629         End If;
5630 
5631           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
5632 
5633             UPDATE ap_payment_hist_dists dist
5634             SET    dist.pa_addition_flag = 'O',
5635                    request_id = G_REQUEST_ID,
5636                    last_update_date=SYSDATE,
5637                    last_updated_by= G_USER_ID,
5638                    last_update_login= G_USER_ID,
5639                    program_id= G_PROG_ID,
5640                    program_application_id= G_PROG_APPL_ID,
5641                    program_update_date=SYSDATE
5642             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
5643             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
5644             AND EXISTS (SELECT NULL
5645                         FROM   ap_payment_history_all hist
5646                         WHERE  hist.payment_history_id = dist.payment_history_id
5647 			and    hist.accounting_event_id = dist.accounting_event_id  /*Bug# 9266578 */
5648 			-- commented as part of Bug 10626450 and    hist.transaction_type = 'PAYMENT CLEARING'  /*Bug# 9266578 */
5649                         and    hist.transaction_type in ( 'PAYMENT CREATED','PAYMENT CANCELLED') /* 'PAYMENT CREATED' Added as part of Bug 10626450 ,'PAYMENT CANCELLED' as part of 11703565 */
5650 			AND    hist.posted_flag = 'Y')
5651             AND   exists(SELECT inv.invoice_id -- 11658939 hint del no_unnest
5652                            FROM AP_INVOICES_ALL inv,
5653                                 PO_Distributions_all PO,
5654                                 AP_Invoice_Distributions_all aid,
5655                                 ap_invoice_payments_all aip
5656                           WHERE inv.invoice_id = aip.invoice_id
5657                             AND aid.invoice_id = inv.invoice_id
5658                             AND aip.invoice_payment_id = dist.invoice_payment_id
5659                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
5660                             AND aid.po_distribution_id = PO.po_distribution_id (+)
5661                             AND aid.line_type_lookup_code not in ('TERV', 'REC_TAX') -- Bug#5441030 to avoid zero dollar lines for TERV
5662                             AND inv.org_id = G_ORG_ID
5663                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
5664                             AND inv.paid_on_behalf_employee_id IS NULL
5665                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
5666                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
5667                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
5668                             AND aid.project_id = G_PROJECT_ID
5669                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
5670                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
5671                             AND ( (aid.expenditure_item_date  >=G_Profile_Discount_Start_date
5672                                  AND G_ACCTNG_METHOD = 'A'
5673                                  AND G_discount_Method IN ('TAX','EXPENSE'))
5674                                 OR --CAsh basis
5675                                 (( (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  < G_Profile_Discount_Start_date
5676                                     AND nvl(aid.pa_addition_flag,'N') <> 'Y') ---bug 5516855
5677                                    OR (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  >=  G_Profile_Discount_Start_date
5678                                     AND aid.pa_addition_flag = 'Y')  --bug 5516855 Added to allow disounts interface for historical data
5679                                    OR (G_discount_Method = 'TAX' AND AID.line_type_lookup_code <> 'NONREC_TAX'
5680                                         AND aid.expenditure_item_date  >=G_Profile_Discount_Start_date )  --Bug#5189187
5681                                    OR G_Discount_Method = 'SYSTEM') AND G_ACCTNG_METHOD = 'C')
5682                                 ) --See bug#4941454 for logic
5683                            );
5684 
5685 
5686       G_DISC_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
5687       write_log(LOG, 'Number of Discount rows marked to O: ' || to_char(SQL%ROWCOUNT));
5688 
5689       -- Bug 11775600 added the following update statement to mark pa_addition_flag to G for
5690       -- ap_payment_history_all.transaction_type not in ( 'PAYMENT CREATED','PAYMENT CANCELLED') transactions
5691 
5692       UPDATE ap_payment_hist_dists dist
5693             SET    dist.pa_addition_flag = 'G',
5694                    request_id = G_REQUEST_ID,
5695                    last_update_date=SYSDATE,
5696                    last_updated_by= G_USER_ID,
5697                    last_update_login= G_USER_ID,
5698                    program_id= G_PROG_ID,
5699                    program_application_id= G_PROG_APPL_ID,
5700                    program_update_date=SYSDATE
5701             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
5702             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
5703             AND EXISTS (SELECT NULL
5704                         FROM   ap_payment_history_all hist
5705                         WHERE  hist.payment_history_id = dist.payment_history_id
5706 			and    hist.accounting_event_id = dist.accounting_event_id  /*Bug# 9266578 */
5707 			-- commented as part of Bug 10626450 and    hist.transaction_type = 'PAYMENT CLEARING'  /*Bug# 9266578 */
5708                         and    hist.transaction_type not in ( 'PAYMENT CREATED','PAYMENT CANCELLED') /* 'PAYMENT CREATED' Added as part of Bug 10626450 ,'PAYMENT CANCELLED' as part of 11703565 */
5709 			AND    hist.posted_flag = 'Y')
5710             AND   exists(SELECT inv.invoice_id -- 11658939 hint del no_unnest
5711                            FROM AP_INVOICES_ALL inv,
5712                                 PO_Distributions_all PO,
5713                                 AP_Invoice_Distributions_all aid,
5714                                 ap_invoice_payments_all aip
5715                           WHERE inv.invoice_id = aip.invoice_id
5716                             AND aid.invoice_id = inv.invoice_id
5717                             AND aip.invoice_payment_id = dist.invoice_payment_id
5718                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
5719                             AND aid.po_distribution_id = PO.po_distribution_id (+)
5720                             AND aid.line_type_lookup_code not in ('TERV', 'REC_TAX') -- Bug#5441030 to avoid zero dollar lines for TERV
5721                             AND inv.org_id = G_ORG_ID
5722                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
5723                             AND inv.paid_on_behalf_employee_id IS NULL
5724                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
5725                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
5726                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
5727                             AND aid.project_id = G_PROJECT_ID
5728                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
5729                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
5730                             AND ( (aid.expenditure_item_date  >=G_Profile_Discount_Start_date
5731                                  AND G_ACCTNG_METHOD = 'A'
5732                                  AND G_discount_Method IN ('TAX','EXPENSE'))
5733                                 OR --CAsh basis
5734                                 (( (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  < G_Profile_Discount_Start_date
5735                                     AND nvl(aid.pa_addition_flag,'N') <> 'Y') ---bug 5516855
5736                                    OR (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  >=  G_Profile_Discount_Start_date
5737                                     AND aid.pa_addition_flag = 'Y')  --bug 5516855 Added to allow disounts interface for historical data
5738                                    OR (G_discount_Method = 'TAX' AND AID.line_type_lookup_code <> 'NONREC_TAX'
5739                                         AND aid.expenditure_item_date  >=G_Profile_Discount_Start_date )  --Bug#5189187
5740                                    OR G_Discount_Method = 'SYSTEM') AND G_ACCTNG_METHOD = 'C')
5741                                 ) --See bug#4941454 for logic
5742                            );
5743 
5744       -- G_DISC_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT; -- Commented for the bug 13360198
5745       write_log(LOG, 'Number of Discount rows marked to G: ' || to_char(SQL%ROWCOUNT));
5746 
5747      ELSE -- G_PRoject_id is null
5748 
5749           -- Mark all Discount lines associated with PREPAYMENT payment to G to prevent interface into Projects
5750           -- In Rel12, we will only bring in Prepayment application lines (AP_PREPAY_APP_DISTS) into Projects for Cash Based Acctng
5751 
5752             UPDATE ap_payment_hist_dists dist
5753             SET    dist.pa_addition_flag = 'G',
5754                    request_id = G_REQUEST_ID,
5755                    last_update_date=SYSDATE,
5756                    last_updated_by= G_USER_ID,
5757                    last_update_login= G_USER_ID,
5758                    program_id= G_PROG_ID,
5759                    program_application_id= G_PROG_APPL_ID,
5760                    program_update_date=SYSDATE
5761             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
5762             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
5763             AND EXISTS (SELECT NULL
5764                         FROM   ap_payment_history_all hist
5765                         WHERE  hist.payment_history_id = dist.payment_history_id
5766                         AND    hist.posted_flag = 'Y')
5767             AND   exists(SELECT inv.invoice_id -- 11658939 hint del no_unnest
5768                            FROM AP_INVOICES_ALL inv,
5769                                 AP_Invoice_Distributions_all aid,
5770                                 ap_invoice_payments_all aip
5771                           WHERE inv.invoice_id = aip.invoice_id
5772                             AND aid.invoice_id = inv.invoice_id
5773                             AND aip.invoice_payment_id = dist.invoice_payment_id
5774                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
5775                             AND inv.org_id = G_ORG_ID
5776                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'         --Prevent prepayment payments from being transferred to Projects
5777                             AND aid.project_id > 0
5778                             AND aid.invoice_id = aip.invoice_id
5779                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
5780                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
5781 
5782           write_log(LOG, 'Number of Discount prepayments  marked to G: ' || to_char(SQL%ROWCOUNT));
5783 
5784           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
5785 
5786             UPDATE ap_payment_hist_dists dist
5787             SET    dist.pa_addition_flag = 'O',
5788                    request_id = G_REQUEST_ID,
5789                    last_update_date=SYSDATE,
5790                    last_updated_by= G_USER_ID,
5791                    last_update_login= G_USER_ID,
5792                    program_id= G_PROG_ID,
5793                    program_application_id= G_PROG_APPL_ID,
5794                    program_update_date=SYSDATE
5795             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
5796             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
5797             AND EXISTS (SELECT NULL
5798                         FROM   ap_payment_history_all hist
5799                         WHERE  hist.payment_history_id = dist.payment_history_id
5800 			and    hist.accounting_event_id = dist.accounting_event_id  /*Bug# 9266578 */
5801 			-- commented as part of Bug 10626450 and    hist.transaction_type = 'PAYMENT CLEARING'  /*Bug# 9266578 */
5802                         and    hist.transaction_type in ( 'PAYMENT CREATED','PAYMENT CANCELLED') /* 'PAYMENT CREATED' Added as part of Bug 10626450 ,'PAYMENT CANCELLED' as part of 11703565 */
5803 			AND    hist.posted_flag = 'Y')
5804             AND   exists(SELECT inv.invoice_id -- 11658939 hint del no_unnest
5805                            FROM AP_INVOICES_ALL inv,
5806                                 PO_Distributions_all PO,
5807                                 AP_Invoice_Distributions_all aid,
5808                                 ap_invoice_payments_all aip
5809                           WHERE inv.invoice_id = aip.invoice_id
5810                             AND aid.invoice_id = inv.invoice_id
5811                             AND aip.invoice_payment_id = dist.invoice_payment_id
5812                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
5813                             AND inv.org_id = G_ORG_ID
5814                             AND aid.po_distribution_id = PO.po_distribution_id (+)
5815                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
5816                             AND inv.paid_on_behalf_employee_id IS NULL
5817                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
5818                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
5819                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
5820                             AND aid.project_id > 0
5821                             AND aid.line_type_lookup_code not in ('TERV', 'REC_TAX') -- Bug#5441030 to avoid zero dollar lines for TERV
5822                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
5823                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
5824                             AND ( (aid.expenditure_item_date  >=G_Profile_Discount_Start_date
5825                                  AND G_ACCTNG_METHOD = 'A'
5826                                  AND G_discount_Method IN ('TAX','EXPENSE'))
5827                                 OR --CAsh basis
5828                                 (( (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  < G_Profile_Discount_Start_date
5829                                     AND nvl(aid.pa_addition_flag,'N') <> 'Y') ---bug 5516855
5830                                    OR (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  >=  G_Profile_Discount_Start_date
5831                                     AND aid.pa_addition_flag = 'Y')  --bug 5516855 Added to allow disounts interface for historical data
5832                                    OR (G_discount_Method = 'TAX' AND AID.line_type_lookup_code <> 'NONREC_TAX'
5833                                         AND aid.expenditure_item_date  >=G_Profile_Discount_Start_date )  --Bug#5189187
5834                                    OR G_Discount_Method = 'SYSTEM') AND G_ACCTNG_METHOD = 'C')
5835                                 ) --See bug#4941454 for logic
5836                            );
5837 
5838       G_DISC_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
5839       write_log(LOG, 'Number of Discount rows marked to O: ' || to_char(SQL%ROWCOUNT));
5840 
5841       -- Bug 11775600 added the following update statement to mark pa_addition_flag to G for
5842       -- ap_payment_history_all.transaction_type not in ( 'PAYMENT CREATED','PAYMENT CANCELLED') transactions
5843 
5844        UPDATE ap_payment_hist_dists dist
5845             SET    dist.pa_addition_flag = 'G',
5846                    request_id = G_REQUEST_ID,
5847                    last_update_date=SYSDATE,
5848                    last_updated_by= G_USER_ID,
5849                    last_update_login= G_USER_ID,
5850                    program_id= G_PROG_ID,
5851                    program_application_id= G_PROG_APPL_ID,
5852                    program_update_date=SYSDATE
5853             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
5854             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
5855             AND EXISTS (SELECT NULL
5856                         FROM   ap_payment_history_all hist
5857                         WHERE  hist.payment_history_id = dist.payment_history_id
5858 			and    hist.accounting_event_id = dist.accounting_event_id  /*Bug# 9266578 */
5859 			-- commented as part of Bug 10626450 and    hist.transaction_type = 'PAYMENT CLEARING'  /*Bug# 9266578 */
5860                         and    hist.transaction_type  not in ( 'PAYMENT CREATED','PAYMENT CANCELLED') /* 'PAYMENT CREATED' Added as part of Bug 10626450 ,'PAYMENT CANCELLED' as part of 11703565 */
5861 			AND    hist.posted_flag = 'Y')
5862             AND   exists(SELECT inv.invoice_id -- 11658939 hint del no_unnest
5863                            FROM AP_INVOICES_ALL inv,
5864                                 PO_Distributions_all PO,
5865                                 AP_Invoice_Distributions_all aid,
5866                                 ap_invoice_payments_all aip
5867                           WHERE inv.invoice_id = aip.invoice_id
5868                             AND aid.invoice_id = inv.invoice_id
5869                             AND aip.invoice_payment_id = dist.invoice_payment_id
5870                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
5871                             AND inv.org_id = G_ORG_ID
5872                             AND aid.po_distribution_id = PO.po_distribution_id (+)
5873                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
5874                             AND inv.paid_on_behalf_employee_id IS NULL
5875                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
5876                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
5877                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
5878                             AND aid.project_id > 0
5879                             AND aid.line_type_lookup_code not in ('TERV', 'REC_TAX') -- Bug#5441030 to avoid zero dollar lines for TERV
5880                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
5881                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
5882                             AND ( (aid.expenditure_item_date  >=G_Profile_Discount_Start_date
5883                                  AND G_ACCTNG_METHOD = 'A'
5884                                  AND G_discount_Method IN ('TAX','EXPENSE'))
5885                                 OR --CAsh basis
5886                                 (( (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  < G_Profile_Discount_Start_date
5887                                     AND nvl(aid.pa_addition_flag,'N') <> 'Y') ---bug 5516855
5888                                    OR (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  >=  G_Profile_Discount_Start_date
5889                                     AND aid.pa_addition_flag = 'Y')  --bug 5516855 Added to allow disounts interface for historical data
5890                                    OR (G_discount_Method = 'TAX' AND AID.line_type_lookup_code <> 'NONREC_TAX'
5891                                         AND aid.expenditure_item_date  >=G_Profile_Discount_Start_date )  --Bug#5189187
5892                                    OR G_Discount_Method = 'SYSTEM') AND G_ACCTNG_METHOD = 'C')
5893                                 ) --See bug#4941454 for logic
5894                            );
5895 
5896         -- G_DISC_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT; -- Commented for the bug 13360198
5897       write_log(LOG, 'Number of Discount rows marked to G: ' || to_char(SQL%ROWCOUNT));
5898 
5899       END IF;  -- End of If section checking if G_PROJECT_ID is not null
5900 
5901 
5902       G_err_stack := v_old_stack;
5903 
5904 EXCEPTION
5905      WHEN Others THEN
5906            -- Marking phase failed, raise exception to main program to terminate the program
5907            --
5908            G_err_stack := v_old_stack;
5909            G_err_code := SQLCODE;
5910            RAISE;
5911 
5912 END mark_PA_disc_flag_O;
5913 
5914 /*-------------------------------------*/
5915 
5916 PROCEDURE transfer_disc_to_pa IS
5917 
5918    v_old_stack                     VARCHAR2(630);
5919    v_err_message                   VARCHAR2(220);
5920    v_all_done                      NUMBER := 0;
5921    v_status                        VARCHAR2(30);
5922    v_stage                         Number :=0;
5923    v_max_size                      NUMBER :=0;
5924 
5925    v_num_discounts_fetched         NUMBER :=0;
5926    v_num_payments_fetched          NUMBER :=0;
5927 
5928    v_method                        VARCHAR(15);
5929    v_prev_inv_pay_id               NUMBER:=0;
5930 
5931    v_disc_code_combination_id      NUMBER(15);
5932    v_denom_raw_cost                NUMBER :=0;
5933    v_acct_raw_cost                 NUMBER :=0;
5934    v_denom_currency_code           VARCHAR2(30);
5935    v_acct_rate_type                VARCHAR2(30);
5936    v_acct_rate_date                DATE;
5937    v_acct_exchange_rate            NUMBER(15);
5938    v_last_disc_index               NUMBER := 0;
5939 
5940    v_attribute_category VARCHAR2(150);
5941    v_attribute1 VARCHAR2(150);
5942    v_attribute2 VARCHAR2(150);
5943    v_attribute3 VARCHAR2(150);
5944    v_attribute4 VARCHAR2(150);
5945    v_attribute5 VARCHAR2(150);
5946    v_attribute6 VARCHAR2(150);
5947    v_attribute7 VARCHAR2(150);
5948    v_attribute8 VARCHAR2(150);
5949    v_attribute9 VARCHAR2(150);
5950    v_attribute10 VARCHAR2(150);
5951    v_dff_map_status VARCHAR2(30);
5952    dff_map_exception EXCEPTION;
5953    l_create_adj_recs     VARCHAR2(1) := 'N' ;-- NEW
5954    l_ap_inv_disc_flag    VARCHAR2(1):= 'N'; -- Flag to indicate Discounts exist for ITEM lines in Cash Basis flow.
5955    l_ap_nrt_disc_flag    VARCHAR2(1):= 'N'; -- Flag to indicate Discounts exist for NRTAX lines in Cash Basis flow.
5956    l_ap_hist_disc_flag    VARCHAR2(1):= 'N'; -- Flag to indicate Discounts exist for historicqal inv lines in Cash Basis flow.
5957 
5958    PROCEDURE clear_plsql_tables IS
5959 
5960        l_status1 VARCHAR2(30);
5961 
5962    BEGIN
5963 
5964        l_inv_pay_id_tbl.delete;
5965        l_invoice_id_tbl.delete;
5966        l_invoice_dist_id_tbl.delete;
5967        l_project_id_tbl.delete;
5968        l_task_id_tbl.delete;
5969        l_employee_id_tbl.delete;
5970        l_exp_type_tbl.delete;
5971        l_ei_date_tbl.delete;
5972        l_vendor_id_tbl.delete;
5973        l_created_by_tbl.delete;
5974        l_exp_org_id_tbl.delete;
5975        l_quantity_tbl.delete;
5976        l_job_id_tbl.delete;
5977        l_description_tbl.delete;
5978        l_dist_cc_id_tbl.delete;
5979        l_acct_pay_cc_id_tbl.delete;
5980        l_gl_date_tbl.delete;
5981        l_attribute_cat_tbl.delete;
5982        l_attribute1_tbl.delete;
5983        l_attribute2_tbl.delete;
5984        l_attribute3_tbl.delete;
5985        l_attribute4_tbl.delete;
5986        l_attribute5_tbl.delete;
5987        l_attribute6_tbl.delete;
5988        l_attribute7_tbl.delete;
5989        l_attribute8_tbl.delete;
5990        l_attribute9_tbl.delete;
5991        l_attribute10_tbl.delete;
5992        l_inv_type_code_tbl.delete;
5993        l_org_id_tbl.delete;
5994        l_invoice_num_tbl.delete;
5995        l_ln_type_lookup_tbl.delete;
5996        l_source_tbl.delete;
5997        l_denom_raw_cost_tbl.delete;
5998        l_amount_tbl.delete;
5999        l_denom_cur_code_tbl.delete;
6000        l_acct_rate_date_tbl.delete;
6001        l_acct_rate_type_tbl.delete;
6002        l_acct_exch_rate_tbl.delete;
6003        l_cdl_sys_ref4_tbl.delete;
6004        l_cdl_sys_ref3_tbl.delete;
6005        l_txn_src_tbl.delete;
6006        l_user_txn_src_tbl.delete;
6007        l_batch_name_tbl.delete;
6008        l_interface_id_tbl.delete;
6009        l_exp_end_date_tbl.delete;
6010        l_txn_status_code_tbl.delete;
6011        l_txn_rej_code_tbl.delete;
6012        l_bus_grp_id_tbl.delete;
6013        l_reversal_flag_tbl.delete; --NEW
6014        l_net_zero_flag_tbl.delete; --NEW
6015        l_sc_xfer_code_tbl.delete; --NEW
6016        l_parent_pmt_id_tbl.delete; --NEW
6017        l_fc_enabled_tbl.delete; --NEW
6018        l_rev_parent_dist_id_tbl.delete;
6019        l_rev_child_dist_id_tbl.delete;
6020        l_rev_parent_dist_ind_tbl.delete;
6021        l_si_assts_add_flg_tbl.delete;
6022        l_pay_hist_id_tbl.delete;
6023        l_pa_add_flag_tbl.delete;
6024        l_cbs_element_id_tbl.delete; -- Added for CBS Enhancement Bug 16220146
6025        l_rev_index:=0;
6026 
6027     END clear_plsql_tables;
6028 
6029     PROCEDURE bulk_insert_trx_intf IS
6030 
6031       l_status2 VARCHAR2(30);
6032 
6033     BEGIN
6034 
6035        --FORALL i IN l_inv_pay_id_tbl.FIRST..l_inv_pay_id_tbl.LAST
6036        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
6037 
6038        INSERT INTO pa_transaction_interface_all(
6039                      transaction_source
6040                     , user_transaction_source
6041                     , system_linkage
6042                     , batch_name
6043                     , expenditure_ending_date
6044                     , expenditure_item_date
6045                     , expenditure_type
6046                     , quantity
6047                     , raw_cost_rate
6048                     , expenditure_comment
6049                     , transaction_status_code
6050                     , transaction_rejection_code
6051                     , orig_transaction_reference
6052                     , interface_id
6053                     , dr_code_combination_id
6054                     , cr_code_combination_id
6055                     , cdl_system_reference1
6056                     , cdl_system_reference2
6057                     , cdl_system_reference3
6058                     , cdl_system_reference4
6059                     , cdl_system_reference5 --NEW
6060                     , gl_date
6061                     , org_id
6062                     , unmatched_negative_txn_flag
6063                     , denom_raw_cost
6064                     , denom_currency_code
6065                     , acct_rate_date
6066                     , acct_rate_type
6067                     , acct_exchange_rate
6068                     , acct_raw_cost
6069                     , acct_exchange_rounding_limit
6070                     , attribute_category
6071                     , attribute1
6072                     , attribute2
6073                     , attribute3
6074                     , attribute4
6075                     , attribute5
6076                     , attribute6
6077                     , attribute7
6078                     , attribute8
6079                     , attribute9
6080                     , attribute10
6081                     , orig_exp_txn_reference1
6082                     , orig_user_exp_txn_reference
6083                     , orig_exp_txn_reference2
6084                     , orig_exp_txn_reference3
6085                     , last_update_date
6086                     , last_updated_by
6087                     , creation_date
6088                     , created_by
6089                     , person_id
6090                     , organization_id
6091                     , project_id
6092                     , task_id
6093                     , Vendor_id
6094                     , override_to_organization_id
6095                     , person_business_group_id
6096                     , adjusted_expenditure_item_id
6097                     , fc_document_type
6098                     , document_type
6099                     , document_distribution_type
6100                     , si_assets_addition_flag
6101                     , sc_xfer_code
6102                     ,net_zero_adjustment_flag
6103                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
6104                    )
6105              SELECT   l_txn_src_tbl(i)
6106                      ,l_user_txn_src_tbl(i)
6107                      ,G_SYSTEM_LINKAGE
6108                      ,l_batch_name_tbl(i)
6109                      ,l_exp_end_date_tbl(i)
6110                      ,l_ei_date_tbl(i)
6111                      ,l_exp_type_tbl(i)
6112                      ,l_quantity_tbl(i)
6113                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
6114                      ,l_description_tbl(i)
6115                      ,l_txn_status_code_tbl(i)
6116                      ,l_txn_rej_code_tbl(i)
6117                      ,G_REQUEST_ID
6118                      ,l_interface_id_tbl(i)
6119                      ,l_dist_cc_id_tbl(i)
6120                      ,l_acct_pay_cc_id_tbl(i)
6121                      ,l_pay_hist_id_tbl(i) --cdl_ref1
6122                      ,l_invoice_id_tbl(i)
6123                      ,l_cdl_sys_ref3_tbl(i)
6124                      ,l_inv_pay_id_tbl(i)
6125                      ,l_invoice_dist_id_tbl(i) --NEW
6126                      ,l_gl_date_tbl(i)
6127                      ,G_ORG_ID
6128                      ,'Y'
6129                      ,l_denom_raw_cost_tbl(i)
6130                      ,l_denom_cur_code_tbl(i)
6131                      ,l_acct_rate_date_tbl(i)
6132                      ,l_acct_rate_type_tbl(i)
6133                      ,l_acct_exch_rate_tbl(i)
6134                      ,l_amount_tbl(i)
6135                      ,1
6136                      ,l_attribute_cat_tbl(i)
6137                      ,l_attribute1_tbl(i)
6138                      ,l_attribute2_tbl(i)
6139                      ,l_attribute3_tbl(i)
6140                      ,l_attribute4_tbl(i)
6141                      ,l_attribute5_tbl(i)
6142                      ,l_attribute6_tbl(i)
6143                      ,l_attribute7_tbl(i)
6144                      ,l_attribute8_tbl(i)
6145                      ,l_attribute9_tbl(i)
6146                      ,l_attribute10_tbl(i)
6147                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
6148                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
6149                      ,NULL                       /*orig_exp_txn_reference2*/
6150                      ,NULL                       /*orig_exp_txn_reference3*/
6151                      ,SYSDATE
6152                      ,-1
6153                      ,SYSDATE
6154                      ,-1
6155                      ,l_employee_id_tbl(i)
6156                      ,l_org_id_tbl(i)
6157                      ,l_project_id_tbl(i)
6158                      ,l_task_id_tbl(i)
6159                      ,l_vendor_id_tbl(i)
6160                      ,l_exp_org_id_tbl(i)
6161                      ,l_bus_grp_id_tbl(i)
6162                      ,l_adj_exp_item_id_tbl(i)
6163                      ,l_fc_document_type_tbl(i)
6164                      ,l_inv_type_code_tbl(i)
6165                      ,l_ln_type_lookup_tbl(i)
6166                      ,l_si_assts_add_flg_tbl(i)
6167                      ,l_sc_xfer_code_tbl(i)
6168                      ,l_net_zero_flag_tbl(i)
6169                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
6170                   FROM dual;
6171 
6172               -- Insert the reversal of the reversed/cancelled distribution recs from AP.
6173     IF l_create_adj_recs = 'Y' THEN
6174 
6175                 write_log(LOG, 'Inserting adjustment records..');
6176        --FORALL i IN l_inv_pay_id_tbl.FIRST..l_inv_pay_id_tbl.LAST
6177        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
6178 
6179        INSERT INTO pa_transaction_interface_all(
6180                      transaction_source
6181                     , user_transaction_source
6182                     , system_linkage
6183                     , batch_name
6184                     , expenditure_ending_date
6185                     , expenditure_item_date
6186                     , expenditure_type
6187                     , quantity
6188                     , raw_cost_rate
6189                     , expenditure_comment
6190                     , transaction_status_code
6191                     , transaction_rejection_code
6192                     , orig_transaction_reference
6193                     , interface_id
6194                     , dr_code_combination_id
6195                     , cr_code_combination_id
6196                     , cdl_system_reference1
6197                     , cdl_system_reference2
6198                     , cdl_system_reference3
6199                     , cdl_system_reference4
6200                     , cdl_system_reference5 --NEW
6201                     , gl_date
6202                     , org_id
6203                     , unmatched_negative_txn_flag
6204                     , denom_raw_cost
6205                     , denom_currency_code
6206                     , acct_rate_date
6207                     , acct_rate_type
6208                     , acct_exchange_rate
6209                     , acct_raw_cost
6210                     , acct_exchange_rounding_limit
6211                     , attribute_category
6212                     , attribute1
6213                     , attribute2
6214                     , attribute3
6215                     , attribute4
6216                     , attribute5
6217                     , attribute6
6218                     , attribute7
6219                     , attribute8
6220                     , attribute9
6221                     , attribute10
6222                     , orig_exp_txn_reference1
6223                     , orig_user_exp_txn_reference
6224                     , orig_exp_txn_reference2
6225                     , orig_exp_txn_reference3
6226                     , last_update_date
6227                     , last_updated_by
6228                     , creation_date
6229                     , created_by
6230                     , person_id
6231                     , organization_id
6232                     , project_id
6233                     , task_id
6234                     , Vendor_id
6235                     , override_to_organization_id
6236                     , person_business_group_id
6237                     , adjusted_expenditure_item_id
6238                     , fc_document_type
6239                     , document_type
6240                     , document_distribution_type
6241                     , si_assets_addition_flag
6242                     , adjusted_txn_interface_id
6243                     , sc_xfer_code
6244                     ,net_zero_adjustment_flag
6245                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
6246                    )
6247              SELECT   l_txn_src_tbl(i)
6248                      ,l_user_txn_src_tbl(i)
6249                      ,G_SYSTEM_LINKAGE
6250                      ,l_batch_name_tbl(i)
6251                      ,l_exp_end_date_tbl(i)
6252                      ,l_ei_date_tbl(i)
6253                      ,l_exp_type_tbl(i)
6254                      ,-l_quantity_tbl(i)
6255                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
6256                      ,l_description_tbl(i)
6257                      ,l_txn_status_code_tbl(i)
6258                      ,l_txn_rej_code_tbl(i)
6259                      ,G_REQUEST_ID
6260                      ,l_interface_id_tbl(i)
6261                      ,l_dist_cc_id_tbl(i)
6262                      ,l_acct_pay_cc_id_tbl(i)
6263                      ,l_pay_hist_id_tbl(i) --cdl_ref1
6264                      ,l_invoice_id_tbl(i)
6265                      ,l_cdl_sys_ref3_tbl(i)
6266                      ,l_inv_pay_id_tbl(i)
6267                      ,l_invoice_dist_id_tbl(i)
6268                      ,l_gl_date_tbl(i)
6269                      ,G_ORG_ID
6270                      ,'Y'
6271                      ,-l_denom_raw_cost_tbl(i)
6272                      ,l_denom_cur_code_tbl(i)
6273                      ,l_acct_rate_date_tbl(i)
6274                      ,l_acct_rate_type_tbl(i)
6275                      ,l_acct_exch_rate_tbl(i)
6276                      ,-l_amount_tbl(i)
6277                      ,1
6278                      ,l_attribute_cat_tbl(i)
6279                      ,l_attribute1_tbl(i)
6280                      ,l_attribute2_tbl(i)
6281                      ,l_attribute3_tbl(i)
6282                      ,l_attribute4_tbl(i)
6283                      ,l_attribute5_tbl(i)
6284                      ,l_attribute6_tbl(i)
6285                      ,l_attribute7_tbl(i)
6286                      ,l_attribute8_tbl(i)
6287                      ,l_attribute9_tbl(i)
6288                      ,l_attribute10_tbl(i)
6289                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
6290                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
6291                      ,NULL                       /*orig_exp_txn_reference2*/
6292                      ,NULL                       /*orig_exp_txn_reference3*/
6293                      ,SYSDATE
6294                      ,-1
6295                      ,SYSDATE
6296                      ,-1
6297                      ,l_employee_id_tbl(i)
6298                      ,l_org_id_tbl(i)
6299                      ,l_project_id_tbl(i)
6300                      ,l_task_id_tbl(i)
6301                      ,l_vendor_id_tbl(i)
6302                      ,l_exp_org_id_tbl(i)
6303                      ,l_bus_grp_id_tbl(i)
6304                      ,l_adj_exp_item_id_tbl(i)
6305                      ,l_fc_document_type_tbl(i)
6306                      ,l_inv_type_code_tbl(i)
6307                      ,l_ln_type_lookup_tbl(i)
6308                      , 'T' --l_si_assts_add_flg_tbl(i)
6309                      ,(select xface.txn_interface_id
6310                        from   pa_transaction_interface xface
6311                        where  xface.interface_id = l_interface_id_tbl(i)
6312                        and    xface.cdl_system_reference2 = l_invoice_id_tbl(i)
6313                        and    xface.cdl_system_reference4 = to_char(l_inv_pay_id_tbl(i))
6314                        and    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(i)
6315 		       and    NVL(xface.adjusted_expenditure_item_id,0) = 0 ) -- R12 funds management Uptake
6316                      ,'P' -- sc_xfer_code
6317                      ,l_net_zero_flag_tbl(i)
6318                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
6319                    FROM dual
6320                    WHERE l_insert_flag_tbl(i)= 'A';
6321                   --WHERE l_net_zero_flag_tbl(i)= 'Y';
6322 
6323                -- Handle both the parent and the reversal getting interfaced into PA
6324                -- in the same run.
6325                 write_log(LOG, 'Updating  adjustment records..');
6326 
6327               IF l_rev_child_dist_id_tbl.exists(1) THEN
6328                FOR i in l_rev_child_dist_id_tbl.FIRST ..l_rev_child_dist_id_tbl.LAST LOOP
6329 
6330                    IF l_rev_child_dist_id_tbl(i) > 0 THEN
6331 
6332                     UPDATE pa_transaction_interface_all xface
6333                     SET    xface.net_zero_adjustment_flag ='Y',
6334                            xface.adjusted_txn_interface_id =
6335                               (select distinct xface1.txn_interface_id /* bug 9266578 */
6336                                from   pa_transaction_interface xface1
6337                                where  xface1.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
6338                                and    xface1.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
6339                                and    xface1.cdl_system_reference4 = to_char(l_inv_pay_id_tbl(l_rev_parent_dist_ind_tbl(i)))
6340                                and    xface1.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
6341                                )
6342                       WHERE  xface.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
6343                       AND    xface.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
6344                       --AND    xface.cdl_system_reference4 = to_char(l_rev_child_dist_id_tbl(i))
6345                       -- AND    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i));
6346                       AND    -- For voided payments l_rev_child_dist_id_tbl stores the reversed payment id Bug# 5408748
6347                              -- Here the reversal pair will have same inv dist id and diff payment id's
6348                              ((
6349                              xface.cdl_system_reference4     = To_char(l_rev_child_dist_id_tbl(i))
6350                              AND xface.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
6351                              )
6352                       OR     -- For invoice reversal l_rev_child_dist_id_tbl stores the reversed invoice dist id Bug# 5408748
6353                              -- Here the reversal pair will have same payment id and diff inv dist id's
6354                              (
6355                              xface.cdl_system_reference4     = to_char(l_inv_pay_id_tbl(l_rev_parent_dist_ind_tbl(i)))
6356                              AND xface.cdl_system_reference5 = To_char(l_rev_child_dist_id_tbl(i))
6357                              )) ;
6358                     END IF;
6359 
6360               END LOOP;
6361              END IF;
6362     END IF;
6363 
6364    EXCEPTION
6365       WHEN OTHERS THEN
6366           write_log(LOG,'Failed during bulk insert for discount processing');
6367           G_err_code   := SQLCODE;
6368           write_log(LOG, 'Error Code is '||SQLCODE);
6369           write_log(LOG, substr(SQLERRM, 1, 200));
6370           write_log(LOG, substr(SQLERRM, 201, 200));
6371           raise;
6372 
6373    END bulk_insert_trx_intf;
6374 
6375    PROCEDURE process_disc_logic IS
6376 
6377        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
6378        l_status3 VARCHAR2(30);
6379        L_PP_REJECT_FLAG VARCHAR2(1); --Bug 3664528
6380        l_dis_count  NUMBER;  /*start changes for bug#14335609 */
6381 	   -- Start: Added for CBS Enhancement Bug 16220146
6382 	   l_actual_task_id       NUMBER := 0;
6383 	   l_cbs_element_id       NUMBER := 0;
6384 	   -- End: Added for CBS Enhancement Bug 16220146
6385 
6386    BEGIN
6387 
6388 
6389        j :=  v_last_disc_index ;
6390        FOR i IN  l_inv_pay_id_tbl.FIRST..l_inv_pay_id_tbl.LAST  LOOP
6391 
6392          write_log(LOG,'getting discount attributes for inv_pay_id:'||l_inv_pay_id_tbl(i)
6393                       ||'invoice_id:'||l_invoice_id_tbl(i)
6394                       ||'Invoice dist id:'||l_invoice_dist_id_tbl(i));
6395 
6396            l_quantity_tbl(i)       := l_denom_raw_cost_tbl(i);
6397            l_cdl_sys_ref4_tbl(i)   := l_inv_pay_id_tbl(i);
6398 
6399 
6400            G_TRANSACTION_REJECTION_CODE := '';
6401            G_TRANSACTION_STATUS_CODE := 'P';
6402 
6403 		   -- Start: Added for CBS Enhancement Bug 16220146
6404 		   IF l_project_id_tbl(i) is not null and l_task_id_tbl(i) IS NOT NULL THEN
6405 
6406 			  IF PA_ALTERNATE_TASK_PVT.Is_Cbs_Enabled(l_project_id_tbl(i)) = 'Y' THEN
6407 
6408 			     BEGIN
6409 
6410 				    SELECT PROJ_ELEMENT_ID, CBS_ELEMENT_ID
6411 					INTO l_actual_task_id, l_cbs_element_id
6412 					FROM PA_ALTERNATE_TASKS
6413 					WHERE alt_task_id = l_task_id_tbl(i);
6414 
6415 				EXCEPTION
6416 				   WHEN OTHERS THEN
6417 				      l_cbs_element_id_tbl(i) := NULL;
6418 				      RAISE;
6419 				END;
6420 
6421 				l_task_id_tbl(i) := l_actual_task_id;
6422 				l_cbs_element_id_tbl(i) := l_cbs_element_id;
6423 			  ELSE
6424 			     l_cbs_element_id_tbl(i) := NULL;
6425 			  END IF;
6426 		   ELSE
6427 		      l_cbs_element_id_tbl(i) := NULL;
6428 		   END IF;
6429 		   -- End: Added for CBS Enhancement Bug 16220146
6430 
6431            /* For CAsh Basis we process Discounts as SUpplier Invoice */
6432            IF G_ACCTNG_METHOD = 'C' and nvl(l_pa_add_flag_tbl(i),'N') <> 'Y' THEN --Bug# 5516855
6433              -- Added the pa-addition-flag logic for bug 5516855 so that discounts on historical records, that are interfaced as
6434              -- inv dist and have pa-addition-flag as Y , are interfaced as DISCOUNTS source and negitive amount
6435 
6436 
6437              --Added this logic for bug#5122922.
6438 
6439            IF l_ln_type_lookup_tbl(i)  = 'NONREC_TAX' THEN
6440              G_DISC_TRANSACTION_SOURCE      := 'AP NRTAX';
6441              G_DISC_USER_TRANSACTION_SOURCE := 'AP NRTAX';
6442              l_ap_nrt_disc_flag  :='Y';
6443            ELSE
6444              G_DISC_TRANSACTION_SOURCE      := 'AP INVOICE' ;
6445              G_DISC_USER_TRANSACTION_SOURCE := 'AP INVOICE';
6446              l_ap_inv_disc_flag  :='Y';
6447            END IF;
6448 
6449 
6450            ELSE
6451              IF G_ACCTNG_METHOD = 'C' THEN   --To process discounts against historical inv in rel12 in cash env Bug# 5516855
6452                l_ap_hist_disc_flag  :='Y';
6453              END IF;
6454 
6455              G_DISC_TRANSACTION_SOURCE      := 'AP DISCOUNTS' ;
6456              G_DISC_USER_TRANSACTION_SOURCE := 'Supplier Invoice Discounts from Payables';
6457 
6458              l_denom_raw_cost_tbl(i) := -l_denom_raw_cost_tbl(i);   -- for Discounts, amount is interfaced as negitive amount
6459              l_amount_tbl(i)         := -l_amount_tbl(i);
6460              l_quantity_tbl(i)       := -l_quantity_tbl(i);
6461 
6462 
6463 
6464            END IF;
6465 
6466            /* The following will be executed if discount being fetched belongs to a new payment */
6467            IF (l_inv_pay_id_tbl(i) <> v_prev_inv_pay_id) THEN
6468 
6469                write_log(LOG,'New payment processed. inv_pay_id is:'||l_inv_pay_id_tbl(i));
6470 
6471                /* Update the previous invoice payment id*/
6472                v_prev_inv_pay_id := l_inv_pay_id_tbl(i);
6473 
6474                /* Increment the counter for invoices */
6475                v_num_payments_fetched := v_num_payments_fetched + 1;
6476 
6477                /* For new invoice, initialize the transaction status code to 'P' */
6478                L_PP_REJECT_FLAG := 'N';
6479 
6480                G_err_stage := 'GET MAX EXPENDITURE ENDING DATE';
6481                write_log(LOG, G_err_stage);
6482 /* Bug 5051103 - replace expnediture_item_date with l_ei_date_tbl(i) */
6483                SELECT pa_utils.getweekending(MAX(l_ei_date_tbl(i)))
6484                  INTO G_EXPENDITURE_ENDING_DATE
6485                  FROM ap_invoice_distributions
6486                 WHERE invoice_id = l_invoice_id_tbl(i);
6487 
6488                G_err_stage := ('Before getting business group id');
6489                write_log(LOG, G_err_stage);
6490 
6491                BEGIN
6492 
6493                   IF l_employee_id_tbl(i) <> 0 THEN
6494 			Begin
6495 			     SELECT emp.business_group_id
6496                                INTO G_PER_BUS_GRP_ID
6497 			       FROM per_all_people_f emp
6498 			      WHERE emp.person_id = l_employee_id_tbl(i)
6499 				  AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and
6500 							       trunc(emp.effective_end_date);
6501 
6502 		       EXCEPTION
6503 			  WHEN NO_DATA_FOUND THEN
6504                              L_PP_REJECT_FLAG := 'Y' ;
6505 			     G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
6506 			     write_log(LOG, 'no data found for Employee, Rejecting invoice'||l_invoice_id_tbl(i)  );
6507 			End;
6508                     Else
6509                         Begin
6510 
6511                             select org2.business_group_id
6512                               into G_PER_BUS_GRP_ID
6513                               from hr_organization_units org1,
6514                                    hr_organization_units org2
6515                              Where org1.organization_id = l_exp_org_id_tbl(i)
6516                                and org1.business_group_id = org2.organization_id;
6517 
6518                         EXCEPTION
6519                                 WHEN NO_DATA_FOUND THEN
6520                                       L_PP_REJECT_FLAG := 'Y' ;
6521                                       G_TRANSACTION_REJECTION_CODE := 'INVALID_ORGANIZATION';
6522                                       write_log(LOG, 'As no data found for Organization, Rejecting discount invoice ' || l_invoice_id_tbl(i) );
6523                         End;
6524                   END IF; /* IF l_employee_id_tbl(i) <> 0 THEN  */
6525 
6526                END;
6527 
6528            END IF; /* end of check for new invoice_payment_id*/
6529 
6530            v_num_discounts_fetched := v_num_discounts_fetched + 1;
6531            write_log(LOG,'Num of discount lines fetched:'||v_num_discounts_fetched);
6532 
6533           IF L_PP_REJECT_FLAG = 'Y' THEN --Bug 3664528 : Reject all the distributions within prepayment --???????
6534              G_TRANSACTION_STATUS_CODE := 'R';
6535           END IF;
6536 
6537            /*Setting values according to global variables*/
6538 
6539 	   /*start changes for bug#14335609 */
6540 
6541            l_dis_count := 0;
6542 
6543 	   Begin
6544 
6545            select count(1) into l_dis_count from ap_invoice_distributions
6546 	   where invoice_distribution_id = l_invoice_dist_id_tbl(i)
6547 	   and line_type_lookup_code ='NONREC_TAX';
6548 
6549 	   exception
6550 	   when others then
6551              l_dis_count := 0;
6552 	   end;
6553 
6554 		IF G_ACCTNG_METHOD ='A' THEN
6555 
6556 		   IF (l_dis_count > 0) THEN
6557 		   --{
6558 		       l_quantity_tbl(i) :=  0;
6559 		   --}
6560 		   END IF;
6561 
6562 		END IF;
6563 
6564         /*End changes for bug#14335609 */
6565 
6566            l_txn_src_tbl(i)         := G_DISC_TRANSACTION_SOURCE;
6567            l_user_txn_src_tbl(i)    := G_DISC_USER_TRANSACTION_SOURCE;
6568            l_batch_name_tbl(i)      := G_DISC_BATCH_NAME;
6569            l_interface_id_tbl(i)    := G_DISC_INTERFACE_ID;
6570            l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
6571            l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
6572            l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
6573            l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
6574 
6575          -- This logic is to handle both the parent and reversal getting interfaced in the same run.
6576           -- It's a reversed parent record. Bug#4590527
6577           -- If both the parent and child reversing each other are interfaced in the same run, they
6578           -- were not getting interfaced as netzero transactions.
6579 
6580            IF (l_reversal_flag_tbl(i) in ('Y','R') or l_cancel_flag_tbl(i) = 'Y')
6581                                  AND l_parent_pmt_id_tbl(i) IS NULL THEN
6582 
6583               l_rev_index := l_rev_index +1;
6584               IF l_reversal_flag_tbl(i) = 'Y' THEN
6585                 write_log(LOG, 'Reversal parent record '||l_inv_pay_id_tbl(i));
6586                 l_rev_parent_dist_id_tbl(l_rev_index) :=  l_inv_pay_id_tbl(i);
6587               ELSE
6588 
6589                 -- The Reversal flag with value R indicates that the invoice distribution has been reversed
6590                 -- Refer to Bug#5408748
6591 
6592                 write_log(LOG, 'Reversal parent record for Invoice Dist reversals'||l_invoice_dist_id_tbl(i));
6593                 l_rev_parent_dist_id_tbl(l_rev_index) :=  l_invoice_dist_id_tbl(i);
6594               END IF;
6595 
6596               l_rev_child_dist_id_tbl(l_rev_index) :=  null;
6597               l_rev_parent_dist_ind_tbl(l_rev_index) :=  i; -- store the index of the parent.
6598 
6599            END IF;
6600 
6601            IF l_reversal_flag_tbl(i) in ('Y','R')  and l_parent_pmt_id_tbl(i) is not null THEN
6602 
6603                      -- Call reversal API
6604                      Process_Adjustments(p_record_type               => 'AP_DISCOUNTS',
6605                                          p_document_header_id        => l_invoice_id_tbl(i),/*Added this for 6945767 */
6606                                          p_document_distribution_id  => l_invoice_dist_id_tbl(i),
6607                                          p_document_payment_id       => l_parent_pmt_id_tbl(i),
6608                                          p_current_index             => i,
6609 					 p_last_index		     => j);
6610 
6611                       -- Set the create flag for adjustment records
6612                          IF l_insert_flag_tbl(i) in ('A','U') THEN
6613                           l_create_adj_recs := 'Y';
6614                          END IF;
6615 
6616 
6617           END IF; --End of check for reversal Distribution
6618 
6619            -- FC Doc Type
6620             IF l_fc_enabled_tbl(i) = 'N' THEN
6621              l_fc_document_type_tbl(i) := 'NOT';
6622             END IF;
6623 
6624            IF (G_TRANS_DFF_AP = 'Y') THEN
6625 
6626                 v_attribute_category := l_attribute_cat_tbl(i);
6627                 v_attribute1 := l_attribute1_tbl(i);
6628                 v_attribute2 := l_attribute2_tbl(i);
6629                 v_attribute3 := l_attribute3_tbl(i);
6630                 v_attribute4 := l_attribute4_tbl(i);
6631                 v_attribute5 := l_attribute5_tbl(i);
6632                 v_attribute6 := l_attribute6_tbl(i);
6633                 v_attribute7 := l_attribute7_tbl(i);
6634                 v_attribute8 := l_attribute8_tbl(i);
6635                 v_attribute9 := l_attribute9_tbl(i);
6636                 v_attribute10 := l_attribute10_tbl(i);
6637 
6638                 v_dff_map_status := NULL;
6639 
6640                 G_err_stage:='Calling DFF_map_segments_PA_and_AP for discounts';
6641                 write_log(LOG,   G_err_stage);
6642 
6643                 PA_CLIENT_EXTN_DFFTRANS.DFF_map_segments_PA_and_AP(
6644                    p_calling_module            => 'PAAPIMP',
6645                    p_trx_ref_1                 => l_invoice_id_tbl(i),
6646                    p_trx_ref_2                 => l_invoice_dist_id_tbl(i),
6647                    p_trx_type                  => l_inv_type_code_tbl(i),
6648                    p_system_linkage_function   => G_SYSTEM_LINKAGE,
6649                    p_submodule                 => l_source_tbl(i),
6650                    p_expenditure_type          => l_exp_type_tbl(i),
6651                    p_set_of_books_id           => G_AP_SOB,
6652                    p_org_id                    => l_org_id_tbl(i),
6653                    p_attribute_category        => v_attribute_category,
6654                    p_attribute_1               => v_attribute1,
6655                    p_attribute_2               => v_attribute2,
6656                    p_attribute_3               => v_attribute3,
6657                    p_attribute_4               => v_attribute4,
6658                    p_attribute_5               => v_attribute5,
6659                    p_attribute_6               => v_attribute6,
6660                    p_attribute_7               => v_attribute7,
6661                    p_attribute_8               => v_attribute8,
6662                    p_attribute_9               => v_attribute9,
6663                    p_attribute_10              => v_attribute10,
6664                    x_status_code               => v_dff_map_status);
6665 
6666                    IF (v_dff_map_status IS NOT NULL) THEN
6667 
6668                        G_err_stage:=('Error in DFF_map_segments_PA_and_AP, Error Code: ' || v_dff_map_status);
6669                        write_log(LOG,   G_err_stage);
6670                        raise dff_map_exception;
6671 
6672                    END IF;
6673 
6674                    l_attribute_cat_tbl(i) := v_attribute_category;
6675                    l_attribute1_tbl(i) := v_attribute1;
6676                    l_attribute2_tbl(i) := v_attribute2;
6677                    l_attribute3_tbl(i) := v_attribute3;
6678                    l_attribute4_tbl(i) := v_attribute4;
6679                    l_attribute5_tbl(i) := v_attribute5;
6680                    l_attribute6_tbl(i) := v_attribute6;
6681                    l_attribute7_tbl(i) := v_attribute7;
6682                    l_attribute8_tbl(i) := v_attribute8;
6683                    l_attribute9_tbl(i) := v_attribute9;
6684                    l_attribute10_tbl(i) := v_attribute10;
6685 
6686 	   ElSE /* if DFF profile is No. Added for Bug 3105153*/
6687                    l_attribute_cat_tbl(i) := NULL;
6688                    l_attribute1_tbl(i) := NULL;
6689                    l_attribute2_tbl(i) := NULL;
6690                    l_attribute3_tbl(i) := NULL;
6691                    l_attribute4_tbl(i) := NULL;
6692                    l_attribute5_tbl(i) := NULL;
6693                    l_attribute6_tbl(i) := NULL;
6694                    l_attribute7_tbl(i) := NULL;
6695                    l_attribute8_tbl(i) := NULL;
6696                    l_attribute9_tbl(i) := NULL;
6697                    l_attribute10_tbl(i) := NULL;
6698 
6699            END IF; /* if DFF profile is Yes */
6700 
6701       END LOOP; /* End of looping through each record in plsql table */
6702 
6703    EXCEPTION
6704       WHEN OTHERS THEN
6705           write_log(LOG,'Failed during process_disc_logic for discount processing');
6706           G_err_code   := SQLCODE;
6707           raise;
6708 
6709    END process_disc_logic;
6710 
6711    BEGIN
6712    /* Main Procedure Logic starts here */
6713 
6714    G_err_stage := 'Entering main processing logic of transfer_disc_to_pa';
6715    write_log(LOG,   G_err_stage);
6716 
6717      v_max_size := nvl(G_COMMIT_SIZE,200);
6718 
6719       G_err_stage:= 'Opening Discount_cour';
6720       write_log(LOG, G_err_stage);
6721 
6722       OPEN Discount_Cur;
6723 
6724       WHILE (v_all_done = 0) LOOP
6725 
6726           G_err_stage:='Discount Cursor is opened, looping through batches';
6727           write_log(LOG,   G_err_stage);
6728 
6729           clear_plsql_tables;
6730 
6731           G_err_stage := 'CREATING NEW INTERFACE ID';
6732           write_log(LOG, G_err_stage);
6733 
6734           SELECT pa_interface_id_s.nextval
6735             INTO G_DISC_INTERFACE_ID
6736             FROM dual;
6737 
6738           G_err_stage := 'Fetching Discount Cursor';
6739           write_log(LOG, G_err_stage);
6740 
6741           FETCH Discount_Cur BULK COLLECT INTO
6742               l_inv_pay_id_tbl
6743              ,l_invoice_id_tbl
6744              ,l_invoice_dist_id_tbl
6745              ,l_cdl_sys_ref3_tbl
6746              ,l_project_id_tbl
6747              ,l_task_id_tbl
6748              ,l_employee_id_tbl
6749              ,l_exp_type_tbl
6750              ,l_ei_date_tbl
6751              ,l_vendor_id_tbl
6752              ,l_created_by_tbl
6753              ,l_exp_org_id_tbl
6754              ,l_quantity_tbl
6755              ,l_job_id_tbl
6756              ,l_description_tbl
6757              ,l_dist_cc_id_tbl
6758              ,l_acct_pay_cc_id_tbl
6759              ,l_gl_date_tbl
6760              ,l_attribute_cat_tbl
6761              ,l_attribute1_tbl
6762              ,l_attribute2_tbl
6763              ,l_attribute3_tbl
6764              ,l_attribute4_tbl
6765              ,l_attribute5_tbl
6766              ,l_attribute6_tbl
6767              ,l_attribute7_tbl
6768              ,l_attribute8_tbl
6769              ,l_attribute9_tbl
6770              ,l_attribute10_tbl
6771              ,l_inv_type_code_tbl
6772              ,l_org_id_tbl
6773              ,l_invoice_num_tbl
6774              ,l_ln_type_lookup_tbl
6775              ,l_source_tbl
6776              ,l_denom_raw_cost_tbl
6777              ,l_amount_tbl
6778              ,l_denom_cur_code_tbl
6779              ,l_acct_rate_date_tbl
6780              ,l_acct_rate_type_tbl
6781              ,l_acct_exch_rate_tbl
6782              ,l_cdl_sys_ref4_tbl
6783              ,l_txn_src_tbl
6784              ,l_user_txn_src_tbl
6785              ,l_batch_name_tbl
6786              ,l_interface_id_tbl
6787              ,l_exp_end_date_tbl
6788              ,l_txn_status_code_tbl
6789              ,l_txn_rej_code_tbl
6790              ,l_bus_grp_id_tbl
6791              ,l_reversal_flag_tbl
6792              ,l_cancel_flag_tbl
6793              ,l_parent_pmt_id_tbl
6794              ,l_net_zero_flag_tbl
6795              ,l_sc_xfer_code_tbl
6796              ,l_adj_exp_item_id_tbl
6797              ,l_fc_enabled_tbl
6798              ,l_mrc_exchange_date_tbl
6799              ,l_fc_document_type_tbl
6800              ,l_si_assts_add_flg_tbl
6801              ,l_insert_flag_tbl
6802              ,l_pay_hist_id_tbl
6803              ,l_pa_add_flag_tbl
6804             LIMIT v_max_size;
6805 
6806          IF l_inv_pay_id_tbl.COUNT <> 0 THEN
6807 
6808             G_DISC_TRANSACTION_SOURCE      := 'AP DISCOUNTS' ;
6809             G_DISC_USER_TRANSACTION_SOURCE := 'Supplier Invoice Discounts From Payables';
6810 
6811             v_last_disc_index := l_invoice_id_tbl.LAST;
6812             G_err_stage := 'Calling process logic for discount processsing';
6813             write_log(LOG, G_err_stage);
6814 
6815             process_disc_logic;
6816 
6817             G_err_stage := 'Calling Bulk Insert into trx intf for discounts';
6818             write_log(LOG, G_err_stage);
6819 
6820             bulk_insert_trx_intf;
6821 
6822             IF (v_num_discounts_fetched > 0) THEN
6823 
6824                G_err_stage := 'Calling trans import for discounts';
6825                write_log(LOG, G_err_stage);
6826 
6827            IF G_ACCTNG_METHOD = 'C' THEN
6828               IF l_ap_inv_disc_flag = 'Y' THEN
6829                trans_import('AP INVOICE', G_DISC_BATCH_NAME,G_DISC_INTERFACE_ID, G_USER_ID);
6830                tieback_payment_AP_ER('AP INVOICE', G_DISC_BATCH_NAME, 'APDISC',G_DISC_INTERFACE_ID);
6831               END IF;
6832               IF l_ap_nrt_disc_flag = 'Y' THEN
6833                trans_import('AP NRTAX', G_DISC_BATCH_NAME,G_DISC_INTERFACE_ID, G_USER_ID);
6834                tieback_payment_AP_ER('AP NRTAX', G_DISC_BATCH_NAME, 'APDISC',G_DISC_INTERFACE_ID);
6835               END IF;
6836               IF l_ap_hist_disc_flag = 'Y' THEN
6837                trans_import(G_DISC_TRANSACTION_SOURCE, G_DISC_BATCH_NAME,G_DISC_INTERFACE_ID, G_USER_ID);
6838                tieback_payment_AP_ER(G_DISC_TRANSACTION_SOURCE, G_DISC_BATCH_NAME, 'APDISC',G_DISC_INTERFACE_ID);
6839               END IF;
6840            ELSE
6841                trans_import(G_DISC_TRANSACTION_SOURCE, G_DISC_BATCH_NAME,G_DISC_INTERFACE_ID, G_USER_ID);
6842                tieback_payment_AP_ER(G_DISC_TRANSACTION_SOURCE, G_DISC_BATCH_NAME, 'APDISC',G_DISC_INTERFACE_ID);
6843            END IF;
6844 
6845                G_NUM_BATCHES_PROCESSED := G_NUM_BATCHES_PROCESSED + 1;
6846                G_NUM_DISCOUNTS_PROCESSED := G_NUM_DISCOUNTS_PROCESSED + v_num_discounts_fetched;
6847 
6848             END IF; /* IF (v_num_discounts_fetched > 0) */
6849 
6850             clear_plsql_tables;
6851 
6852         ELSE
6853 
6854           G_err_stage := 'plsql table for discounts is empty. Exiting';
6855           write_log(LOG, G_err_stage);
6856 
6857           EXIT; /* Exit if /* l_inv_pay_id_tbl.COUNT = 0 */
6858 
6859         END IF; /* l_inv_pay_id_tbl.COUNT = 0 */
6860 
6861         v_num_discounts_fetched :=0;
6862         v_num_payments_fetched := 0;
6863 
6864         EXIT WHEN Discount_Cur%NOTFOUND;
6865 
6866       END LOOP; /* While v_all_done = 0 */
6867 
6868       G_err_stage := 'Closing Discount cursor';
6869       write_log(LOG, G_err_stage);
6870 
6871       CLOSE Discount_cur;
6872 
6873 EXCEPTION
6874     WHEN OTHERS THEN
6875 
6876          G_err_stack := v_old_stack;
6877          IF Discount_Cur%ISOPEN THEN
6878            CLOSE Discount_Cur;
6879          END IF ;
6880 
6881          G_err_code := SQLCODE;
6882          RAISE;
6883 
6884 END transfer_disc_to_pa;
6885 
6886 
6887 PROCEDURE mark_RCV_PAflag IS
6888 
6889    v_status     VARCHAR2(30);
6890 
6891 BEGIN
6892 
6893    G_err_stack := G_err_stack || '->PAAPIMP_PKG.mark_RCV_PAflag';
6894    write_log(LOG, 'UPDATING RCV_TRANSACTIONS -Marking Process');
6895 
6896    /* mark all the rcv sub ledger records pa_addition_flag to NULL for any rcv transactions
6897       that are non-project related or with a non-EXPENSE destination_type_code,which is not a return or is not actual*/
6898     -- This update has been moved to pa_po_integration_utils.update_pa_addition_flag.
6899 
6900 
6901    /* mark rcv sub ledger records pa_addition_flag to O/J for rcv transactions that are
6902      project related and fit the criteria to be pulled into Projects.
6903      Divided into project_ID IS NULL and NOT NULL section for better performance
6904    */
6905 
6906    IF G_PROJECT_ID IS NOT NULL THEN
6907 
6908    /* Modified the below update statement for better performence bug#7526677
6909    Not commenting and doing the changes because it has already become a mess with these updates
6910    */
6911 
6912 	  UPDATE rcv_receiving_sub_ledger rcv_sub
6913 	      SET rcv_sub.pa_Addition_Flag       = decode(rcv_sub.pa_addition_flag,'N','O','I','J'),
6914 		  rcv_sub.request_id             = G_REQUEST_ID,
6915 		  rcv_sub.last_update_date       = SYSDATE,
6916 		  rcv_sub.last_updated_by        = G_USER_ID,
6917 		  rcv_sub.last_update_login      = G_USER_ID,
6918 		  rcv_sub.program_id             = G_PROG_ID,
6919 		  rcv_sub.program_application_id = G_PROG_APPL_ID,
6920 		  rcv_sub.program_update_date    = SYSDATE
6921 	    WHERE exists
6922 		(SELECT 1 --rcv_sub1.ROWID --Removed /*+ leading(po_dist) */ for Bug5262594
6923                  FROM Rcv_Transactions rcv_txn,
6924                       PO_Distributions po_dist,
6925 					  po_lines_all POL
6926 		WHERE ((rcv_txn.destination_type_code ='EXPENSE' )
6927 		    OR (rcv_txn.destination_type_code = 'RECEIVING'
6928                     AND (rcv_txn.transaction_type IN ('RETURN TO VENDOR','RETURN TO RECEIVING'))))
6929 		AND trunc(rcv_txn.transaction_date)      <= trunc(nvl(G_GL_DATE,rcv_txn.transaction_date))      /*Added trunc for the bug 6623163 */
6930 		AND rcv_txn.PO_DISTRIBUTION_ID    =  po_dist.po_distribution_id
6931 		and po_dist.PO_line_ID            =  POL.po_line_id       --16265673
6932 		AND rcv_sub.code_combination_id   =  po_dist.code_combination_id
6933                 AND nvl(po_dist.distribution_type,'XXX') <> 'PREPAYMENT'   --bug 7192304, added nvl
6934 		AND rcv_sub.rcv_transaction_id    =  rcv_txn.transaction_id
6935 		AND trunc(po_dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,po_dist.expenditure_item_date)) /*Added trunc for the bug 6623163 */
6936 		AND po_dist.project_ID  > 0
6937 		AND po_dist.accrue_on_receipt_flag= 'Y'
6938 		AND nvl(rcv_txn.project_id , po_dist.project_id)  = G_PROJECT_ID  /*Added for bug:7046666*/
6939 		/* Start added for bug#6015451 */
6940 		AND ( (rcv_txn.destination_type_code = 'EXPENSE' AND  /*Starts-code changes  for bug:9196652*/
6941                         (( rcv_txn.transaction_type = 'DELIVER' AND
6942 			   rcv_sub.entered_dr is NOT NULL
6943                           )
6944 						 OR
6945 						 (
6946 						  rcv_txn.transaction_type = 'RETURN TO RECEIVING' AND
6947 						  rcv_sub.entered_cr is NOT NULL
6948 						  )
6949 						 OR
6950 						 (
6951 						  rcv_txn.transaction_type = 'CORRECT' AND
6952 						  (rcv_sub.entered_cr is NOT NULL or rcv_sub.entered_dr is NOT NULL) AND
6953 						  rcv_sub.accounting_line_type='Charge'  and
6954 						  decode(POL.order_type_lookup_code,
6955 						 'RATE' , rcv_txn.amount,
6956 						 'FIXED PRICE', rcv_txn.amount,
6957 						  rcv_txn.primary_quantity) < 0
6958 						  )
6959 						 OR
6960 						 (
6961 						  rcv_txn.transaction_type = 'CORRECT' AND
6962 						  rcv_sub.entered_dr is NOT NULL AND
6963 						  decode(POL.order_type_lookup_code,
6964 						  'RATE' , rcv_txn.amount,
6965 						  'FIXED PRICE', rcv_txn.amount,
6966 						  rcv_txn.primary_quantity) >= 0
6967 						  )
6968 			 )  /*Ends-code changes  for bug:9196652*/
6969 		       /* rcv_txn.transaction_type <> 'RETURN TO RECEIVING' AND rcv_sub.entered_dr is NOT NULL commented for bug:9196652*/
6970 		       ) /*OR
6971 		       ((rcv_txn.destination_type_code = 'RECEIVING' OR
6972 		         rcv_txn.transaction_type = 'RETURN TO RECEIVING') AND rcv_sub.entered_cr is NOT NULL
6973                         ) commented for bug 9196652*/
6974 		     )
6975 		/* Ends added for bug#6015451 */
6976 	  /* Added for bug 14288109 */
6977 		AND (
6978 		PA_PJC_CWK_UTILS.Is_rate_based_line(null, po_dist.po_distribution_id) = 'N'
6979 		OR PA_PJC_CWK_UTILS.Is_CWK_TC_Xface_Allowed(po_dist.project_ID) = 'N'
6980 		OR (PA_PJC_CWK_UTILS.IS_RATE_BASED_LINE(NULL, PO_DIST.PO_DISTRIBUTION_ID) = 'Y' AND NVL(RCV_SUB.ENTERED_NR_TAX,0) <> 0 )/*Added for bug 16562910 */
6981 		) /* Modified for bug 16305848 */
6982 		/* Added for bug 14288109 */
6983     )
6984 	        AND rcv_sub.pa_addition_flag IN ('N','I')
6985 		AND rcv_sub.actual_flag = 'A';
6986 
6987 	     G_RCV_TRANSACTIONS_MARKED_O := SQL%ROWCOUNT;
6988              write_log(LOG, 'Number of rcvtxn marked to O or J:' || to_char(SQL%ROWCOUNT));
6989 
6990 
6991    ELSIF G_PROJECT_ID IS NULL THEN
6992 
6993    /* Modified the below update statement for better performence bug#7526677
6994    Not commenting and doing the changes because it has already become a mess with these updates
6995    */
6996 
6997 	   UPDATE rcv_receiving_sub_ledger rcv_sub
6998 	      SET rcv_sub.pa_Addition_Flag       = decode(rcv_sub.pa_addition_flag,'N','O','I','J'),
6999 		  rcv_sub.request_id             = G_REQUEST_ID,
7000 		  rcv_sub.last_update_date       = SYSDATE,
7001 		  rcv_sub.last_updated_by        = G_USER_ID,
7002 		  rcv_sub.last_update_login      = G_USER_ID,
7003 		  rcv_sub.program_id             = G_PROG_ID,
7004 		  rcv_sub.program_application_id = G_PROG_APPL_ID,
7005 		  rcv_sub.program_update_date    = SYSDATE
7006 	    WHERE exists
7007                (SELECT 1 --rcv_sub1.ROWID --Removed /*+ leading(po_dist) */ for Bug5262594
7008                  FROM Rcv_Transactions rcv_txn,
7009                      PO_Distributions po_dist  ,
7010 			  po_lines_all POL
7011 		WHERE
7012 		((rcv_txn.destination_type_code ='EXPENSE' )
7013 		    OR (rcv_txn.destination_type_code = 'RECEIVING'
7014                     AND (rcv_txn.transaction_type IN ('RETURN TO VENDOR','RETURN TO RECEIVING'))))
7015 		AND trunc(rcv_txn.transaction_date)      <= trunc(nvl(G_GL_DATE,rcv_txn.transaction_date))      /*Added trunc for the bug 6623163 */
7016 		AND rcv_txn.PO_DISTRIBUTION_ID    =  po_dist.po_distribution_id
7017 		and po_dist.PO_line_ID            =  POL.po_line_id                    --16265673
7018 		AND rcv_sub.code_combination_id   =  po_dist.code_combination_id
7019                 AND nvl(po_dist.distribution_type,'XXX') <> 'PREPAYMENT'    -- bug 7192304, added nvl
7020 		AND rcv_sub.rcv_transaction_id    =  rcv_txn.transaction_id
7021 		AND trunc(po_dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,po_dist.expenditure_item_date)) /*Added trunc for the bug 6623163 */
7022 		AND po_dist.project_ID  > 0
7023 		AND po_dist.accrue_on_receipt_flag= 'Y'
7024 		/* Starts added for bug#6015451 */
7025 		AND ( (rcv_txn.destination_type_code = 'EXPENSE'
7026 		    AND /*Starts-code changes  for bug:9196652*/
7027                         (( rcv_txn.transaction_type = 'DELIVER' AND
7028 						rcv_sub.entered_dr is NOT NULL
7029                         )
7030 						 OR
7031 						 (
7032 						  rcv_txn.transaction_type = 'RETURN TO RECEIVING' AND
7033 						  rcv_sub.entered_cr is NOT NULL
7034 						  )
7035 						 OR
7036 						 (
7037 						  rcv_txn.transaction_type = 'CORRECT' AND
7038 						 ( rcv_sub.entered_cr is NOT NULL or rcv_sub.entered_dr is NOT NULL )AND
7039 						  rcv_sub.accounting_line_type='Charge'  and
7040 						  decode(POL.order_type_lookup_code,
7041 						 'RATE' , rcv_txn.amount,
7042 						 'FIXED PRICE', rcv_txn.amount,
7043 						  rcv_txn.primary_quantity) < 0
7044 						  )
7045 						 OR
7046 						 (
7047 						  rcv_txn.transaction_type = 'CORRECT' AND
7048 						  rcv_sub.entered_dr is NOT NULL AND
7049 						  decode(POL.order_type_lookup_code,
7050 						  'RATE' , rcv_txn.amount,
7051 						  'FIXED PRICE', rcv_txn.amount,
7052 						  rcv_txn.primary_quantity) >= 0
7053 						  )
7054 						 )  /*Ends-code changes  for bug:9196652*/
7055                         /*
7056 		        rcv_txn.transaction_type <> 'RETURN TO RECEIVING' AND rcv_sub.entered_dr is NOT NULL commented for bug :9196652*/
7057 		       ) /* OR
7058 		       ((rcv_txn.destination_type_code = 'RECEIVING' OR
7059 		         rcv_txn.transaction_type = 'RETURN TO RECEIVING') AND rcv_sub.entered_cr is NOT NULL
7060                         ) commented for bug:9196652 */
7061 		     )
7062 		/* Ends added for bug#6015451 */
7063 		/* Added for bug 14288109 */
7064 		AND (
7065 		PA_PJC_CWK_UTILS.Is_rate_based_line(null, po_dist.po_distribution_id) = 'N'
7066 		OR PA_PJC_CWK_UTILS.Is_CWK_TC_Xface_Allowed(po_dist.project_ID) = 'N'
7067 		OR (PA_PJC_CWK_UTILS.IS_RATE_BASED_LINE(NULL, PO_DIST.PO_DISTRIBUTION_ID) = 'Y' AND NVL(RCV_SUB.ENTERED_NR_TAX,0) <> 0 )/*Added for bug 16562910 */
7068 		) /* Modified for bug 16305848 */
7069 		/* Added for bug 14288109 */
7070     )
7071 		AND rcv_sub.pa_addition_flag IN ('N','I')
7072                 AND rcv_sub.actual_flag = 'A';
7073 
7074 
7075 	     G_RCV_TRANSACTIONS_MARKED_O := SQL%ROWCOUNT;
7076 	     write_log(LOG, 'Number of rcvtxn marked to O or J:' || to_char(SQL%ROWCOUNT));
7077 
7078     END IF;
7079 
7080 EXCEPTION
7081    WHEN Others THEN
7082       G_err_code := SQLCODE;
7083       RAISE;
7084 
7085 END mark_RCV_PAflag;
7086 
7087 PROCEDURE transfer_receipts_to_pa  IS
7088 
7089    v_total_num_receipts            NUMBER := 0;
7090    v_num_receipts_processed        NUMBER := 0;
7091    v_num_receipt_tax_processed     NUMBER := 0;
7092    l_denom_cost                    NUMBER :=0;
7093    l_acct_cost                     NUMBER :=0;
7094    l_quantity                      NUMBER :=0;
7095    l_record_type                   VARCHAR2(20);
7096 
7097    v_max_size                      NUMBER := 0;
7098 
7099    v_old_stack                     VARCHAR2(630);
7100    v_err_message                   VARCHAR2(220);
7101    v_all_done                      NUMBER := 0;
7102 
7103    v_status Number := 0;
7104    v_stage  Number :=0;
7105 
7106    v_last_rcv_index             NUMBER := 0;
7107    v_prev_po_head_id     NUMBER := 0;
7108    v_prev_po_dist_id     NUMBER := 0;
7109    v_business_group_id   NUMBER := 0;
7110    v_attribute_category  VARCHAR2(150);
7111    v_attribute1 VARCHAR2(150);
7112    v_attribute2 VARCHAR2(150);
7113    v_attribute3 VARCHAR2(150);
7114    v_attribute4 VARCHAR2(150);
7115    v_attribute5 VARCHAR2(150);
7116    v_attribute6 VARCHAR2(150);
7117    v_attribute7 VARCHAR2(150);
7118    v_attribute8 VARCHAR2(150);
7119    v_attribute9 VARCHAR2(150);
7120    v_attribute10 VARCHAR2(150);
7121    v_dff_map_status VARCHAR2(30);
7122    dff_map_exception EXCEPTION;
7123    l_create_adj_recs     VARCHAR2(1) := 'N';
7124 
7125    /* the following sub-procedure is declared here to save lines of code since deleting
7126       plsql tables will be done multiple times within the procedure transfer_receipts_to_pa */
7127 
7128    PROCEDURE clear_plsql_tables IS
7129 
7130        l_status1 VARCHAR2(30);
7131 
7132    BEGIN
7133 
7134        G_err_stage := 'within clear_plsql_tables of transfer_receipts_to_pa';
7135        write_log(LOG, G_err_stage);
7136 
7137    l_rcv_txn_id_tbl.delete;
7138    l_po_dist_id_tbl.delete;
7139    l_po_head_id_tbl.delete;
7140    l_po_num_tbl.delete;
7141    l_quantity_tbl.delete;
7142    l_entered_dr_tbl.delete;
7143    l_entered_cr_tbl.delete;
7144    l_accounted_dr_tbl.delete;
7145    l_accounted_cr_tbl.delete;
7146    l_entered_nr_tax_tbl.delete;
7147    l_accounted_nr_tax_tbl.delete;
7148    l_denom_raw_cost_tbl.delete;
7149    l_acct_raw_cost_tbl.delete;
7150    l_record_type_tbl.delete;
7151    l_dist_cc_id_tbl.delete;
7152    l_denom_cur_code_tbl.delete;
7153    l_acct_rate_date_tbl.delete;
7154    l_acct_rate_type_tbl.delete;
7155    l_acct_exch_rate_tbl.delete;
7156    l_gl_date_tbl.delete;
7157    l_dest_typ_code_tbl.delete;
7158    l_pa_add_flag_tbl.delete;
7159    l_trx_type_tbl.delete;
7160    l_project_id_tbl.delete;
7161    l_task_id_tbl.delete;
7162    l_employee_id_tbl.delete;
7163    l_exp_type_tbl.delete;
7164    l_ei_date_tbl.delete;
7165    l_vendor_id_tbl.delete;
7166    l_exp_org_id_tbl.delete;
7167    l_job_id_tbl.delete;
7168    l_description_tbl.delete;
7169    l_attribute_cat_tbl.delete;
7170    l_attribute1_tbl.delete;
7171    l_attribute2_tbl.delete;
7172    l_attribute3_tbl.delete;
7173    l_attribute4_tbl.delete;
7174    l_attribute5_tbl.delete;
7175    l_attribute6_tbl.delete;
7176    l_attribute7_tbl.delete;
7177    l_attribute8_tbl.delete;
7178    l_attribute9_tbl.delete;
7179    l_attribute10_tbl.delete;
7180    l_org_id_tbl.delete;
7181    l_cdl_sys_ref4_tbl.delete;
7182    l_txn_src_tbl.delete;
7183    l_user_txn_src_tbl.delete;
7184    l_batch_name_tbl.delete;
7185    l_interface_id_tbl.delete;
7186    l_exp_end_date_tbl.delete;
7187    l_txn_status_code_tbl.delete;
7188    l_txn_rej_code_tbl.delete;
7189    l_bus_grp_id_tbl.delete;
7190    l_insert_flag_tbl.delete;
7191    l_rcv_acct_evt_id_tbl.delete; -- pricing changes
7192    l_rcv_acct_evt_typ_tbl.delete; -- pricing changes
7193    l_rcv_acct_rec_tax_tbl.delete; -- pricing changes
7194    l_rcv_ent_rec_tax_tbl.delete; -- pricing changes
7195    l_parent_rcv_id_tbl.delete;   -- NEW --added for full return reversal logic
7196    l_net_zero_flag_tbl.delete;
7197    l_sc_xfer_code_tbl.delete; --NEW
7198    l_adj_exp_item_id_tbl.delete; --NEW
7199    l_fc_enabled_tbl.delete; --NEW
7200    l_fc_document_type_tbl.delete; --NEW
7201    l_rcv_sub_ledger_id_tbl.delete;
7202    l_si_assts_add_flg_tbl.delete;
7203    l_exp_cst_rt_flg_tbl.delete; --NEW
7204    l_po_tax_qty_tbl.delete;
7205    l_cbs_element_id_tbl.delete; -- Added for CBS Enhancement Bug 16220146
7206 
7207    END clear_plsql_tables;
7208 
7209    PROCEDURE bulk_insert_trx_intf IS
7210 
7211      l_status2 VARCHAR2(30);
7212 
7213    BEGIN
7214 
7215       FORALL i IN l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST
7216 
7217        INSERT INTO pa_transaction_interface_all(
7218                      transaction_source
7219                     , user_transaction_source
7220                     , system_linkage
7221                     , batch_name
7222                     , expenditure_ending_date
7223                     , expenditure_item_date
7224                     , expenditure_type
7225                     , quantity
7226                     , raw_cost_rate
7227                     , expenditure_comment
7228                     , transaction_status_code
7229                     , transaction_rejection_code
7230                     , orig_transaction_reference
7231                     , interface_id
7232                     , dr_code_combination_id
7233                     , cr_code_combination_id
7234                     , cdl_system_reference1
7235                     , cdl_system_reference2
7236                     , cdl_system_reference3
7237                     , cdl_system_reference4
7238                     , cdl_system_reference5
7239                     , gl_date
7240                     , org_id
7241                     , unmatched_negative_txn_flag
7242                     , denom_raw_cost
7243                     , denom_currency_code
7244                     , acct_rate_date
7245                     , acct_rate_type
7246                     , acct_exchange_rate
7247                     , acct_raw_cost
7248                     , acct_exchange_rounding_limit
7249                     , attribute_category
7250                     , attribute1
7251                     , attribute2
7252                     , attribute3
7253                     , attribute4
7254                     , attribute5
7255                     , attribute6
7256                     , attribute7
7257                     , attribute8
7258                     , attribute9
7259                     , attribute10
7260                     , orig_exp_txn_reference1
7261                     , orig_user_exp_txn_reference
7262                     ,  orig_exp_txn_reference2
7263                     ,  orig_exp_txn_reference3
7264                     , last_update_date
7265                     , last_updated_by
7266                     , creation_date
7267                     , created_by
7268                     , person_id
7269                     , organization_id
7270                     , project_id
7271                     , task_id
7272                     , Vendor_id
7273                     , override_to_organization_id
7274                     , person_business_group_id
7275                     , adjusted_expenditure_item_id --NEW
7276                     , fc_document_type  -- NEW
7277                     , document_type
7278                     , document_distribution_type
7279                     , sc_xfer_code
7280                     , si_assets_addition_flag
7281                     , net_zero_adjustment_flag
7282                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
7283                    )
7284                SELECT l_txn_src_tbl(i)
7285                      ,l_user_txn_src_tbl(i)
7286                      ,G_SYSTEM_LINKAGE
7287                      ,l_batch_name_tbl(i)
7288                      ,l_exp_end_date_tbl(i)
7289                      ,l_ei_date_tbl(i)
7290                      ,l_exp_type_tbl(i)
7291                      ,l_quantity_tbl(i)
7292                      ,l_acct_raw_cost_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
7293                      ,l_description_tbl(i)
7294                      ,l_txn_status_code_tbl(i)
7295                      ,l_txn_rej_code_tbl(i)
7296                      ,G_REQUEST_ID
7297                      ,l_interface_id_tbl(i)
7298                      ,l_dist_cc_id_tbl(i)
7299                      ,NULL
7300                      ,l_vendor_id_tbl(i)
7301                      ,l_po_head_id_tbl(i)
7302                      ,l_po_dist_id_tbl(i)
7303                      ,l_rcv_txn_id_tbl(i)
7304                      ,l_rcv_sub_ledger_id_tbl(i)
7305                      ,l_gl_date_tbl(i)
7306                      ,G_ORG_ID
7307                      ,'Y'
7308                      ,l_denom_raw_cost_tbl(i)
7309                      ,l_denom_cur_code_tbl(i)
7310                      ,l_acct_rate_date_tbl(i)
7311                      ,l_acct_rate_type_tbl(i)
7312                      ,l_acct_exch_rate_tbl(i)
7313                      ,l_acct_raw_cost_tbl(i)
7314                      ,1
7315                      ,l_attribute_cat_tbl(i)
7316                      ,l_attribute1_tbl(i)
7317                      ,l_attribute2_tbl(i)
7318                      ,l_attribute3_tbl(i)
7319                      ,l_attribute4_tbl(i)
7320                      ,l_attribute5_tbl(i)
7321                      ,l_attribute6_tbl(i)
7322                      ,l_attribute7_tbl(i)
7323                      ,l_attribute8_tbl(i)
7324                      ,l_attribute9_tbl(i)
7325                      ,l_attribute10_tbl(i)
7326                      ,l_po_dist_id_tbl(i)        /*orig_exp_txn_reference1*/
7327                      ,l_rcv_txn_id_tbl(i)        /*user_exp_txn_reference*/
7328                      ,l_rcv_acct_evt_id_tbl(i)   /*orig_exp_txn_reference2*/
7329                      ,NULL                       /*orig_exp_txn_reference3*/
7330                      ,SYSDATE
7331                      ,-1
7332                      ,SYSDATE
7333                      ,-1
7334                      ,l_employee_id_tbl(i)
7335                      ,l_org_id_tbl(i)
7336                      ,l_project_id_tbl(i)
7337                      ,l_task_id_tbl(i)
7338                      ,l_vendor_id_tbl(i)
7339                      ,l_exp_org_id_tbl(i)
7340                      ,l_bus_grp_id_tbl(i)
7341                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
7342                      ,l_fc_document_type_tbl(i) --NEW for funds check
7343                      ,l_dest_typ_code_tbl(i)
7344                      ,l_trx_type_tbl(i)
7345                      ,l_sc_xfer_code_tbl(i)
7346                      ,l_si_assts_add_flg_tbl(i)
7347                      ,l_net_zero_flag_tbl(i)
7348                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
7349                   FROM dual
7350                  WHERE l_insert_flag_tbl(i) in  ('Y','A');
7351 
7352               -- Insert the adjustment recs from AP.
7353     IF l_create_adj_recs = 'Y' THEN
7354 
7355                 write_log(LOG, 'Inserting adjustment records..');
7356 
7357       FORALL i IN l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST
7358 
7359        INSERT INTO pa_transaction_interface_all(
7360                      transaction_source
7361                     , user_transaction_source
7362                     , system_linkage
7363                     , batch_name
7364                     , expenditure_ending_date
7365                     , expenditure_item_date
7366                     , expenditure_type
7367                     , quantity
7368                     , raw_cost_rate
7369                     , expenditure_comment
7370                     , transaction_status_code
7371                     , transaction_rejection_code
7372                     , orig_transaction_reference
7373                     , interface_id
7374                     , dr_code_combination_id
7375                     , cr_code_combination_id
7376                     , cdl_system_reference1
7377                     , cdl_system_reference2
7378                     , cdl_system_reference3
7379                     , cdl_system_reference4
7380                     , cdl_system_reference5
7381                     , gl_date
7382                     , org_id
7383                     , unmatched_negative_txn_flag
7384                     , denom_raw_cost
7385                     , denom_currency_code
7386                     , acct_rate_date
7387                     , acct_rate_type
7388                     , acct_exchange_rate
7389                     , acct_raw_cost
7390                     , acct_exchange_rounding_limit
7391                     , attribute_category
7392                     , attribute1
7393                     , attribute2
7394                     , attribute3
7395                     , attribute4
7396                     , attribute5
7397                     , attribute6
7398                     , attribute7
7399                     , attribute8
7400                     , attribute9
7401                     , attribute10
7402                     , orig_exp_txn_reference1
7403                     , orig_user_exp_txn_reference
7404                     ,  orig_exp_txn_reference2
7405                     ,  orig_exp_txn_reference3
7406                     , last_update_date
7407                     , last_updated_by
7408                     , creation_date
7409                     , created_by
7410                     , person_id
7411                     , organization_id
7412                     , project_id
7413                     , task_id
7414                     , Vendor_id
7415                     , override_to_organization_id
7416                     , person_business_group_id
7417                     , adjusted_expenditure_item_id --NEW
7418                     , fc_document_type  -- NEW
7419                     , document_type
7420                     , document_distribution_type
7421                     , adjusted_txn_interface_id
7422                     , sc_xfer_code
7423                     , si_assets_addition_flag
7424                     , net_zero_adjustment_flag
7425                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
7426                    )
7427                SELECT l_txn_src_tbl(i)
7428                      ,l_user_txn_src_tbl(i)
7429                      ,G_SYSTEM_LINKAGE
7430                      ,l_batch_name_tbl(i)
7431                      ,l_exp_end_date_tbl(i)
7432                      ,l_ei_date_tbl(i)
7433                      ,l_exp_type_tbl(i)
7434                      ,-l_quantity_tbl(i)
7435                      ,l_acct_raw_cost_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
7436                      ,l_description_tbl(i)
7437                      ,l_txn_status_code_tbl(i)
7438                      ,l_txn_rej_code_tbl(i)
7439                      ,G_REQUEST_ID
7440                      ,l_interface_id_tbl(i)
7441                      ,l_dist_cc_id_tbl(i)
7442                      ,NULL
7443                      ,l_vendor_id_tbl(i)
7444                      ,l_po_head_id_tbl(i)
7445                      ,l_po_dist_id_tbl(i)
7446                      ,l_rcv_txn_id_tbl(i)
7447                      ,l_rcv_sub_ledger_id_tbl(i)
7448                      ,l_gl_date_tbl(i)
7449                      ,G_ORG_ID
7450                      ,'Y'
7451                      ,-l_denom_raw_cost_tbl(i)
7452                      ,l_denom_cur_code_tbl(i)
7453                      ,l_acct_rate_date_tbl(i)
7454                      ,l_acct_rate_type_tbl(i)
7455                      ,l_acct_exch_rate_tbl(i)
7456                      ,-l_acct_raw_cost_tbl(i)
7457                      ,1
7458                      ,l_attribute_cat_tbl(i)
7459                      ,l_attribute1_tbl(i)
7460                      ,l_attribute2_tbl(i)
7461                      ,l_attribute3_tbl(i)
7462                      ,l_attribute4_tbl(i)
7463                      ,l_attribute5_tbl(i)
7464                      ,l_attribute6_tbl(i)
7465                      ,l_attribute7_tbl(i)
7466                      ,l_attribute8_tbl(i)
7467                      ,l_attribute9_tbl(i)
7468                      ,l_attribute10_tbl(i)
7469                      ,l_po_dist_id_tbl(i)        /*orig_exp_txn_reference1*/
7470                      ,l_rcv_txn_id_tbl(i)        /*user_exp_txn_reference*/
7471                      ,l_rcv_acct_evt_id_tbl(i)   /*orig_exp_txn_reference2*/
7472                      ,NULL                       /*orig_exp_txn_reference3*/
7473                      ,SYSDATE
7474                      ,-1
7475                      ,SYSDATE
7476                      ,-1
7477                      ,l_employee_id_tbl(i)
7478                      ,l_org_id_tbl(i)
7479                      ,l_project_id_tbl(i)
7480                      ,l_task_id_tbl(i)
7481                      ,l_vendor_id_tbl(i)
7482                      ,l_exp_org_id_tbl(i)
7483                      ,l_bus_grp_id_tbl(i)
7484                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
7485                      ,l_fc_document_type_tbl(i) --NEW for funds check
7486                      ,l_dest_typ_code_tbl(i)
7487                      ,l_trx_type_tbl(i)
7488                      ,(select xface.txn_interface_id
7489                       from   pa_transaction_interface xface
7490                       where  xface.interface_id =  l_interface_id_tbl(i)
7491                       and    xface.transaction_source = l_txn_src_tbl(i)
7492                       and    xface.cdl_system_reference2 = l_po_head_id_tbl(i)
7493                       and    xface.cdl_system_reference3 = l_po_dist_id_tbl(i)
7494                       and    xface.cdl_system_reference4 = to_char(l_rcv_txn_id_tbl(i))
7495 		      and    nVL(xface.adjusted_expenditure_item_id,0) = 0 ) -- R12 funds management Uptake
7496                      ,'P'  -- sc_xfer_code
7497                      ,'T'  -- Si assets flag
7498                      ,l_net_zero_flag_tbl(i)
7499                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
7500                   FROM dual
7501                   WHERE l_insert_flag_tbl(i) = 'A';
7502     END IF;
7503 
7504    EXCEPTION
7505       WHEN OTHERS THEN
7506           write_log(LOG,'Failed during bulk insert for receipt processing');
7507           G_err_code   := SQLCODE;
7508           raise;
7509 
7510    END bulk_insert_trx_intf;
7511 
7512    PROCEDURE process_receipt_logic IS
7513 
7514        l_status_3 VARCHAR2(30);
7515        l_evt_typ_name VARCHAR2(30);
7516        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
7517        l_historical_flag VARCHAR(1);  --NEW
7518        l_process_adjustments    Number := 0 ;
7519 
7520 
7521                          l_primary_quantity     NUMBER;
7522                          l_amount               NUMBER;
7523                          l_exists               VARCHAR2(1);
7524 	   -- Start: Added for CBS Enhancement Bug 16220146
7525 	   l_actual_task_id       NUMBER := 0;
7526 	   l_cbs_element_id       NUMBER := 0;
7527 	   -- End: Added for CBS Enhancement Bug 16220146
7528 
7529    BEGIN
7530 
7531       G_err_stage:='Within process_receipt_logic';
7532       write_log(LOG,   G_err_stage);
7533 
7534       j := v_last_rcv_index; -- initialize j to the total invoice distributions fetched in the PLSQL array
7535       FOR i IN l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST LOOP
7536 
7537           G_err_stage:=('processing receipt of rcvtxn_id:  '||l_rcv_txn_id_tbl(i)||
7538                        'of po_dist_id:  '||l_po_dist_id_tbl(i));
7539           write_log(LOG,   G_err_stage);
7540 
7541           G_err_stage := 'Calling lock_ap_invoice within pa_add_flag is O';
7542           write_log(LOG,   G_err_stage);
7543 
7544           lock_ap_invoice(l_po_dist_id_tbl(i));
7545 
7546           G_TRANSACTION_REJECTION_CODE  :='';
7547           G_TRANSACTION_STATUS_CODE     := 'P';
7548 
7549           /*
7550             When the Receipt Amount is NULL, mark status code as R in
7551             transaction interface table such that the record wont' be interfaceed.
7552           */
7553           write_log(LOG, 'Checking if the Receipt Amount is Null...');
7554 
7555           IF (l_entered_dr_tbl(i)     IS NULL AND
7556               l_entered_nr_tax_tbl(i) IS NULL ) THEN
7557 
7558              G_TRANSACTION_STATUS_CODE := 'R';
7559              G_TRANSACTION_REJECTION_CODE := 'INVALID_AMOUNT';
7560              write_log(LOG, 'As PO Receipt Amount is NULL, Rejecting PO Receipt : '||l_rcv_txn_id_tbl(i));
7561 
7562           END IF;
7563 
7564 		   -- Start: Added for CBS Enhancement Bug 16220146
7565 		   IF l_project_id_tbl(i) is not null and l_task_id_tbl(i) IS NOT NULL THEN
7566 
7567 			  IF PA_ALTERNATE_TASK_PVT.Is_Cbs_Enabled(l_project_id_tbl(i)) = 'Y' THEN
7568 
7569 			     BEGIN
7570 
7571 				    SELECT PROJ_ELEMENT_ID, CBS_ELEMENT_ID
7572 					INTO l_actual_task_id, l_cbs_element_id
7573 					FROM PA_ALTERNATE_TASKS
7574 					WHERE alt_task_id = l_task_id_tbl(i);
7575 
7576 				EXCEPTION
7577 				   WHEN OTHERS THEN
7578 				      l_cbs_element_id_tbl(i) := NULL;
7579 				      RAISE;
7580 				END;
7581 
7582 				l_task_id_tbl(i) := l_actual_task_id;
7583 				l_cbs_element_id_tbl(i) := l_cbs_element_id;
7584 			  ELSE
7585 			     l_cbs_element_id_tbl(i) := NULL;
7586 			  END IF;
7587 		   ELSE
7588 		      l_cbs_element_id_tbl(i) := NULL;
7589 		   END IF;
7590 		   -- End: Added for CBS Enhancement Bug 16220146
7591 
7592           G_err_stage := ('Before getting business group id');
7593           write_log(LOG, G_err_stage);
7594 
7595           IF (nvl(l_po_head_id_tbl(i),0)<>v_prev_po_head_id) THEN
7596 
7597              v_prev_po_head_id := l_po_head_id_tbl(i);
7598 
7599              BEGIN
7600 
7601                IF nvl(l_employee_id_tbl(i),0) <> 0 THEN
7602 
7603                  SELECT emp.business_group_id
7604                    INTO G_PER_BUS_GRP_ID
7605                    FROM per_all_people_f emp
7606                   WHERE emp.person_id = l_employee_id_tbl(i)
7607                           AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and
7608                                                        trunc(emp.effective_end_date);
7609 
7610                END IF;
7611 
7612              EXCEPTION
7613               WHEN NO_DATA_FOUND THEN
7614 
7615                  l_txn_status_code_tbl(i) := 'R';
7616                  G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
7617                  write_log(LOG, 'no data found for Employee, Rejecting receipt'||l_rcv_txn_id_tbl(i)  );
7618 
7619              END;
7620 
7621           END IF;
7622 
7623           IF (nvl(l_po_dist_id_tbl(i),0)<>v_prev_po_dist_id) THEN
7624 
7625              v_prev_po_dist_id := l_po_dist_id_tbl(i);
7626 
7627              G_err_stage := 'GET MAX EXPENDITURE ENDING DATE for Receipt Accruals';
7628              write_log(LOG,   G_err_stage);
7629 
7630              /* Get the weekending date of the maximum expenditure item date of this PO distribution */
7631 
7632 /* Bug 5051103 - replace expnediture_item_date with l_ei_date_tbl(i) */
7633              SELECT pa_utils.getweekending(MAX(l_ei_date_tbl(i)))
7634                INTO G_EXPENDITURE_ENDING_DATE
7635                FROM po_distributions
7636               WHERE po_distribution_id = l_po_dist_id_tbl(i);
7637 
7638           END IF;
7639 
7640          write_log(LOG,'Fetched a po receipt record of destination type:'||
7641                         l_dest_typ_code_tbl(i)||
7642                        'and trx type of:'||l_trx_type_tbl(i));
7643 
7644          v_total_num_receipts := v_total_num_receipts +1 ;
7645          write_log(LOG,'Number of receipts fetched:  '||v_total_num_receipts);
7646 
7647 	     IF (l_rcv_acct_evt_id_tbl(i) IS NULL) THEN
7648 
7649     	        l_txn_src_tbl(i)         := G_RCV_TRANSACTION_SOURCE;
7650 	            l_user_txn_src_tbl(i)    := G_RCV_USER_TRANSACTION_SOURCE;
7651 	     ELSE
7652 
7653         		SELECT event_type_name
7654 	        	INTO l_evt_typ_name
7655         		FROM rcv_accounting_event_types rcv_acct_evt_typ, rcv_accounting_events rcv_acct_evts
7656         		WHERE rcv_acct_evt_typ.event_type_id = rcv_acct_evts.event_type_id
7657         		AND rcv_acct_evts.accounting_event_id = l_rcv_acct_evt_id_tbl(i);
7658 
7659         		IF (l_evt_typ_name in ('ADJUST_DELIVER','ADJUST_RECEIVE')) THEN
7660         			l_txn_src_tbl(i)         := G_RCV_PRC_ADJ_TRX_SRC;
7661         			l_user_txn_src_tbl(i)    := G_RCV_PRC_ADJ_USER_TRX_SRC;
7662                                 l_quantity               := 0;
7663         		ELSE
7664         			l_txn_src_tbl(i)         := G_RCV_TRANSACTION_SOURCE;
7665         			l_user_txn_src_tbl(i)    := G_RCV_USER_TRANSACTION_SOURCE;
7666         		END IF;
7667 
7668 	     END IF;
7669 
7670 	     l_batch_name_tbl(i)      := G_RCV_BATCH_NAME;
7671 	     l_interface_id_tbl(i)    := G_RCV_INTERFACE_ID;
7672 
7673              l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
7674              l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
7675              l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
7676              l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
7677 
7678 
7679          IF l_pa_add_flag_tbl(i) = 'O' THEN
7680 
7681             write_log(LOG,'PA_addition_flag for this RCV transaction has been marked to O');
7682 
7683             /* If the pa_addition_flag is updated to 'O', then it means we would need
7684                to break down the amount of the receipt into two portions. One is the
7685                total minus tax and the other is just the NR Tax portion. This Loop
7686                will process the total minus tax portion.  After inserting this amount
7687                , the next loop will insert the tax portion of the receipt into the
7688                tranasction_interface table */
7689 
7690             v_num_receipts_processed := v_num_receipts_processed + 1;
7691 
7692             /* for the amount that we are selecting, we need to see whether the transaction is an
7693                EXPENSE or RECEIVING transactions. EXPENSE means we take the positive value of dr column
7694                minus the tax amount while RECEIVNG transaction means it is a return, so we take the
7695                negative of the cr column plus the tax amount. If the trasnaction is a RETURN,
7696                then we want the quantity to be a negative quantity */
7697 
7698          -- call the function to check if the txn got interfaced through AP. If Yes, then set the pa_add_flag to G.
7699           IF ReceiptPaAdditionFlag(p_Pa_Addition_Flag     => l_pa_add_flag_tbl(i),
7700                                      p_Po_Distribution_Id   => l_po_dist_id_tbl(i)) = 'G' THEN
7701 
7702 
7703              write_log(LOG,'PA_addition_flag for this RCV transaction should be marked to G');
7704 
7705                           l_insert_flag_tbl(i) := 'N';
7706                           l_pa_add_flag_tbl(i) := 'G';
7707 
7708           ELSE
7709 
7710             l_record_type:= 'RECEIPT';
7711 
7712            /* If the PO Receipt is for Contingent Worker labor type and the CWK timecard is to be processed
7713               as Labor cost in the Project operating unit, then only the non recoverable tax receipt lines
7714               should be pulled from PO, otherwise the entire receipt with tax should be processed from PO */
7715 
7716             IF PA_PJC_CWK_UTILS.Is_rate_based_line(null, l_po_dist_id_tbl(i)) = 'Y'
7717                AND PA_PJC_CWK_UTILS.Is_CWK_TC_Xface_Allowed(l_project_id_tbl(i)) = 'Y' THEN
7718                l_insert_flag_tbl(i) := 'N';
7719 
7720                write_log(LOG, 'Receipt is for CWK timecard PO - Only NRTAX will be processed');
7721 
7722             ELSE
7723 
7724               IF (l_dest_typ_code_tbl(i) = 'EXPENSE'  AND
7725                   l_trx_type_tbl(i)  NOT IN ('CORRECT', 'RETURN TO RECEIVING')) THEN
7726 
7727                 l_denom_cost := l_entered_dr_tbl(i)   - l_entered_nr_tax_tbl(i);
7728                 l_acct_cost  := l_accounted_dr_tbl(i) - l_accounted_nr_tax_tbl(i);
7729                 l_quantity   := l_quantity_tbl(i);
7730 
7731               ELSIF ((l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i)  IN ('CORRECT', 'RETURN TO RECEIVING')) OR
7732                        ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
7733                                                                                         'RETURN TO RECEIVING' ))) THEN
7734                       --
7735                       -- Check if the correction is a complete correction
7736                       --
7737                       DECLARE
7738                          l_primary_quantity     NUMBER;
7739                          l_amount               NUMBER;
7740                          l_exists               VARCHAR2(1):= 'N';  /*bug7168636*/
7741                       BEGIN
7742 
7743                             SELECT primary_quantity, amount
7744                               INTO l_primary_quantity, l_amount
7745                               FROM rcv_transactions
7746                              WHERE transaction_id = l_parent_rcv_id_tbl(i) ;
7747 
7748                                 IF ((( ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = l_quantity_tbl(i)) OR
7749                                       ( l_amount = l_amount_tbl(i)))   AND
7750                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'RETURN TO RECEIVING') OR
7751                                         ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in ('RETURN TO VENDOR',
7752                                                                                                          'RETURN TO RECEIVING' )))) OR
7753                                     ((  ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = -l_quantity_tbl(i)) OR
7754                                       ( l_amount = -l_amount_tbl(i)))   AND /* BUG13566949 */
7755                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'CORRECT')))) THEN
7756 
7757                                   -- Check if the parent has been interfaced to Projects.
7758 				  /*bug7168636 handling no data found */
7759 				  BEGIN
7760                                      SELECT 'Y'
7761                                        INTO l_exists
7762                                        FROM dual
7763                                       WHERE EXISTS (
7764                                                    SELECT pa_addition_flag
7765                                                      FROM rcv_receiving_sub_ledger
7766                                                     WHERE rcv_transaction_id = l_parent_rcv_id_tbl(i)
7767                                                       AND pa_addition_flag in ('Y','I')) ;
7768                                    EXCEPTION
7769                                      WHEN NO_DATA_FOUND THEN
7770                                      NULL;
7771                                    END;
7772 
7773                                       IF l_exists = 'Y' THEN
7774 
7775 
7776                                          -- Call reversal API
7777                                          Process_Adjustments(p_record_type               => 'PO_RECEIPT',
7778                                             p_document_header_id => l_po_head_id_tbl(i),/*Added this for 6945767 */
7779                                             p_document_distribution_id  => l_parent_rcv_id_tbl(i),
7780                                             p_current_index             => i,
7781 					    p_last_index                => j);
7782 
7783                                          -- Set the create flag for adjustment records
7784                                          IF l_insert_flag_tbl(i)= 'A' THEN
7785                                           l_create_adj_recs := 'Y';
7786                                          END IF;
7787 
7788                                      END IF;
7789 
7790                               END IF ; -- l_primary_quantity  = l_quantity
7791 
7792                             IF ( l_dest_typ_code_tbl(i) = 'RECEIVING'  OR l_trx_type_tbl(i) = 'RETURN TO RECEIVING' ) THEN
7793                               l_denom_cost := -l_entered_cr_tbl(i)   + l_entered_nr_tax_tbl(i);
7794                               l_acct_cost  := -l_accounted_cr_tbl(i) + l_accounted_nr_tax_tbl(i);
7795                               l_quantity   := -l_quantity_tbl(i);
7796                            ELSE
7797                               l_denom_cost := l_entered_dr_tbl(i)   - l_entered_nr_tax_tbl(i);
7798                               l_acct_cost  := l_accounted_dr_tbl(i) - l_accounted_nr_tax_tbl(i);
7799                               l_quantity   := l_quantity_tbl(i);
7800                            END IF;
7801 
7802                        EXCEPTION
7803                           WHEN NO_DATA_FOUND THEN
7804                                 NULL;
7805 
7806                           WHEN OTHERS THEN
7807                                RAISE ;
7808                        END ;
7809 
7810               END IF;
7811 
7812                IF l_quantity = 0 THEN   /* for amount based POs setting the pa quantity to be the same as the transaction cost*/
7813                    l_quantity := l_denom_cost;
7814                END IF;
7815 
7816 
7817             END IF; -- End of check for Contingent worker
7818 
7819        END IF; -- ReceiptPaAdditionFlag
7820      ELSIF l_pa_add_flag_tbl(i) = 'J' THEN
7821 
7822             write_log(LOG,'pa_addition_flag for this RCV transaction has been marked to J');
7823                /* If the pa_addition_flag is J, that means we only need to pull in the NR tax portion*/
7824 
7825             IF l_entered_nr_tax_tbl(i) = 0 THEN
7826 
7827                l_insert_flag_tbl(i) := 'N';
7828 
7829             ELSE
7830 
7831                v_num_receipt_tax_processed := v_num_receipt_tax_processed + 1;
7832 
7833                l_record_type:= 'RECEIPT TAX';
7834 
7835                IF (l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) NOT IN ('RETURN TO RECEIVING','CORRECT')) THEN
7836 
7837                   l_denom_cost := l_entered_nr_tax_tbl(i);
7838                   l_acct_cost  := l_accounted_nr_tax_tbl(i);
7839                   l_quantity   := l_quantity_tbl(i);
7840 
7841 
7842                ELSIF ((l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i)  IN ('CORRECT', 'RETURN TO RECEIVING')) OR
7843                        ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
7844                                                                                         'RETURN TO RECEIVING' ))) THEN
7845                       --
7846                       -- Check if the correction is a complete correction
7847                       --
7848                       DECLARE
7849                          l_primary_quantity     NUMBER;
7850                          l_amount               NUMBER;
7851                          l_exists               VARCHAR2(1):= 'N';    /*bug7168636*/
7852                       BEGIN
7853 
7854                             SELECT primary_quantity, amount
7855                               INTO l_primary_quantity, l_amount
7856                               FROM rcv_transactions
7857                              WHERE transaction_id = l_parent_rcv_id_tbl(i) ;
7858 
7859                                 IF ((( ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = l_quantity_tbl(i)) OR
7860                                       ( l_amount = l_amount_tbl(i)))   AND
7861                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'RETURN TO RECEIVING') OR
7862                                         ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
7863                                                                                                          'RETURN TO RECEIVING' )))) OR
7864                                     ((  ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = -l_quantity_tbl(i)) OR
7865                                       ( l_amount = -l_amount_tbl(i)))   AND /* BUG13566949 */
7866                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'CORRECT')))) THEN
7867 
7868                                   -- Check if the parent has been interfaced to Projects.
7869 				  /*bug 7168636 handling no data found*/
7870 				  BEGIN
7871                                      SELECT 'Y'
7872                                        INTO l_exists
7873                                        FROM dual
7874                                       WHERE EXISTS (
7875                                                    SELECT pa_addition_flag
7876                                                      FROM rcv_receiving_sub_ledger
7877                                                     WHERE rcv_transaction_id = l_parent_rcv_id_tbl(i)
7878                                                       AND pa_addition_flag in ('Y','I')) ;
7879                                    EXCEPTION
7880                                      WHEN NO_DATA_FOUND THEN
7881                                      NULL;
7882                                    END;
7883 
7884                                       IF l_exists = 'Y' THEN
7885 
7886 
7887                                          -- Call reversal API
7888                                          Process_Adjustments(p_record_type               => 'PO_RECEIPT_TAX',
7889                                             p_document_header_id  => l_po_head_id_tbl(i),/*Added this for 6945767 */
7890                                             p_document_distribution_id  => l_parent_rcv_id_tbl(i),
7891                                             p_current_index             => i,
7892                                             p_last_index                => j);
7893 
7894                                         -- Set the create flag for adjustment records
7895                                            IF l_insert_flag_tbl(i) = 'A' THEN
7896                                             l_create_adj_recs := 'Y';
7897                                            END IF;
7898 
7899 
7900                                       END IF;
7901 
7902                                 END IF ; -- l_primary_quantity  = l_quantity
7903                             IF ( l_dest_typ_code_tbl(i) = 'RECEIVING'  OR l_trx_type_tbl(i) = 'RETURN TO RECEIVING' ) THEN
7904                               l_denom_cost := -l_entered_nr_tax_tbl(i);
7905                               l_acct_cost  := -l_accounted_nr_tax_tbl(i);
7906                               l_quantity   := -l_quantity_tbl(i);
7907                            ELSE
7908                               l_denom_cost := l_entered_nr_tax_tbl(i);
7909                               l_acct_cost  := l_accounted_nr_tax_tbl(i);
7910                               l_quantity   := l_quantity_tbl(i);
7911                            END IF;
7912 
7913                        EXCEPTION
7914                           WHEN NO_DATA_FOUND THEN
7915                                 NULL;
7916                           WHEN OTHERS THEN
7917                                RAISE ;
7918                        END ;
7919 
7920                 END IF;
7921 
7922                IF l_quantity = 0 THEN   /*for amount based POs setting the pa quantity to be the same as the transaction cost*/
7923                    l_quantity := l_denom_cost;
7924                END IF;
7925 
7926             END IF; /* tax column is zero */
7927 
7928          END IF; /* pa_add_flag O or J*/
7929 
7930          write_log(LOG, 'This is a record type of: '||l_record_type||
7931                         'denom cost for receipt amount:'||l_denom_cost||
7932                         'acct cost:'||l_acct_cost||'quantity is:'||l_quantity);
7933 
7934          l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
7935          l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
7936          l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
7937 
7938          l_record_type_tbl(i)     := l_record_type;
7939          l_denom_raw_cost_tbl(i)  := l_denom_cost;
7940          l_acct_raw_cost_tbl(i)   := l_acct_cost;
7941 
7942          IF l_exp_cst_rt_flg_tbl(i) = 'Y' THEN --Exp Cost Rate Required = Y, stamp the quantity. Bug#5138396.
7943             l_quantity_tbl(i)        := l_quantity;
7944          ELSE
7945             l_quantity_tbl(i)        := l_denom_cost;
7946          END IF;
7947 
7948          IF l_insert_flag_tbl(i) IS NULL THEN
7949             l_insert_flag_tbl(i)     := 'Y';
7950          END IF;
7951 
7952            -- FC Doc Type
7953             IF l_fc_enabled_tbl(i) = 'N' THEN
7954              l_fc_document_type_tbl(i) := 'NOT';
7955             END IF;
7956 
7957          write_log(LOG, 'The value for Insert Flag : '||l_insert_flag_tbl(i)  );
7958 
7959          IF (G_TRANS_DFF_PO = 'Y') THEN
7960 
7961                 v_attribute_category := l_attribute_cat_tbl(i);
7962                 v_attribute1 := l_attribute1_tbl(i);
7963                 v_attribute2 := l_attribute2_tbl(i);
7964                 v_attribute3 := l_attribute3_tbl(i);
7965                 v_attribute4 := l_attribute4_tbl(i);
7966                 v_attribute5 := l_attribute5_tbl(i);
7967                 v_attribute6 := l_attribute6_tbl(i);
7968                 v_attribute7 := l_attribute7_tbl(i);
7969                 v_attribute8 := l_attribute8_tbl(i);
7970                 v_attribute9 := l_attribute9_tbl(i);
7971                 v_attribute10 := l_attribute10_tbl(i);
7972 
7973                 v_dff_map_status := NULL;
7974 
7975                 G_err_stage:='Calling PA_CLINET_EXTN_DFFTRANS to map DFF fields';
7976                 write_log(LOG,   G_err_stage);
7977 
7978                 PA_CLIENT_EXTN_DFFTRANS.DFF_map_segments_PA_and_AP(
7979                    p_calling_module            => 'PAAPIMP',
7980                    p_trx_ref_1                 => l_po_dist_id_tbl(i),
7981                    p_trx_ref_2                 => l_rcv_txn_id_tbl(i),
7982                    p_trx_type                  => l_dest_typ_code_tbl(i),
7983                    p_system_linkage_function   => 'VI',
7984                    p_submodule                 => NULL,
7985                    p_expenditure_type          => l_exp_type_tbl(i),
7986                    p_set_of_books_id           => G_PO_SOB,
7987                    p_org_id                    => l_org_id_tbl(i),
7988                    p_attribute_category        => v_attribute_category,
7989                    p_attribute_1               => v_attribute1,
7990                    p_attribute_2               => v_attribute2,
7991                    p_attribute_3               => v_attribute3,
7992                    p_attribute_4               => v_attribute4,
7993                    p_attribute_5               => v_attribute5,
7994                    p_attribute_6               => v_attribute6,
7995                    p_attribute_7               => v_attribute7,
7996                    p_attribute_8               => v_attribute8,
7997                    p_attribute_9               => v_attribute9,
7998                    p_attribute_10              => v_attribute10,
7999                    x_status_code               => v_dff_map_status);
8000 
8001                    IF (v_dff_map_status IS NOT NULL) THEN
8002 
8003                        G_err_stage := ('Error in DFF_map_segments_PA_and_AP, Error Code: ' || v_dff_map_status);
8004                        write_log(LOG,   G_err_stage);
8005                        raise dff_map_exception;
8006 
8007                    END IF;
8008 
8009                    l_attribute_cat_tbl(i) := v_attribute_category;
8010                    l_attribute1_tbl(i) := v_attribute1;
8011                    l_attribute2_tbl(i) := v_attribute2;
8012                    l_attribute3_tbl(i) := v_attribute3;
8013                    l_attribute4_tbl(i) := v_attribute4;
8014                    l_attribute5_tbl(i) := v_attribute5;
8015                    l_attribute6_tbl(i) := v_attribute6;
8016                    l_attribute7_tbl(i) := v_attribute7;
8017                    l_attribute8_tbl(i) := v_attribute8;
8018                    l_attribute9_tbl(i) := v_attribute9;
8019                    l_attribute10_tbl(i) := v_attribute10;
8020 
8021 	   ElSE /* if DFF profile is No. Added for Bug 3105153*/
8022                    l_attribute_cat_tbl(i) := NULL;     --Bug#3856390
8023                    l_attribute1_tbl(i) := NULL;
8024                    l_attribute2_tbl(i) := NULL;
8025                    l_attribute3_tbl(i) := NULL;
8026                    l_attribute4_tbl(i) := NULL;
8027                    l_attribute5_tbl(i) := NULL;
8028                    l_attribute6_tbl(i) := NULL;
8029                    l_attribute7_tbl(i) := NULL;
8030                    l_attribute8_tbl(i) := NULL;
8031                    l_attribute9_tbl(i) := NULL;
8032                    l_attribute10_tbl(i) := NULL;
8033 
8034            END IF; /* if DFF profile is Yes */
8035 
8036       END LOOP; /* End of looping through each record in plsql table */
8037 
8038    -- Update to set all the transactions that got interfaced through AP to 'G'
8039     FORALL i IN  l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST
8040          UPDATE rcv_receiving_sub_ledger rcv_sub
8041             SET rcv_sub.pa_addition_flag          = decode(l_pa_add_flag_tbl(i),'G','G',pa_addition_flag)
8042           WHERE rcv_sub.rcv_transaction_id        = l_rcv_txn_id_tbl(i)
8043             AND rcv_sub.pa_addition_flag = 'O'
8044             AND  l_insert_flag_tbl(i) = 'N' ;
8045 
8046    EXCEPTION
8047       WHEN OTHERS THEN
8048           write_log(LOG,'Failed during process_receipt_logic for receipt processing');
8049           G_err_code   := SQLCODE;
8050           raise;
8051    END process_receipt_logic;
8052 
8053    PROCEDURE process_receipt_tax_logic IS
8054 
8055      l_status4    VARCHAR2(10);
8056      l_evt_typ_name VARCHAR2(30); -- pricing changes
8057      j NUMBER := 0; --Index variable for creating reversal EI's --NEW
8058 
8059    BEGIN
8060 
8061       /* This procedure is only called after process_receipt_logic. ONLY the records
8062          with pa_addition_flag of 'O' AND the record type of receipt would be
8063          processed here. The reason for this is because when pa_addition_flag is updated
8064          to 'O', it means we need to split the receipt into the receipt amount and the tax
8065          amount. Since we call a bulk insert after calling  process_receipt_logic then
8066          it means the receipt without tax portion should have been inserted into the
8067          txn interface table. The only part that we should now process are the tax portion
8068          of these records. Thus, we will only process these records and nothing else */
8069 
8070       /* Additional Note: Most of the values already stored in the plsql table for these records
8071          can be reused except for the amount columns. Other columns like bus_group_id and DFF
8072          fields are the same for either the receipt amount or just the tax amount */
8073 
8074       G_err_stage:= 'Within process_receipt_logic';
8075       write_log(LOG,   G_err_stage);
8076 
8077       FOR i IN l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST LOOP
8078 
8079          j := l_rcv_txn_id_tbl.LAST;  -- initialize j to the total rcv trans retrieved in the PLSQL array
8080 
8081          IF (l_pa_add_flag_tbl(i) = 'J' OR l_record_type_tbl(i) not in ('RECEIPT','RCVTAX')) THEN
8082 
8083             l_insert_flag_tbl(i) := 'N';
8084 
8085          ELSIF (l_pa_add_flag_tbl(i)       = 'O'       AND
8086                 l_record_type_tbl(i)   = 'RECEIPT' AND
8087                 l_entered_nr_tax_tbl(i) = 0
8088                ) THEN
8089 
8090                 l_insert_flag_tbl(i) := 'N';
8091 
8092          ELSIF (l_pa_add_flag_tbl(i)       = 'O'       AND
8093                 l_record_type_tbl(i)   = 'RECEIPT' AND
8094                 l_entered_nr_tax_tbl(i) <> 0
8095                ) THEN
8096 
8097                v_num_receipt_tax_processed := v_num_receipt_tax_processed + 1;
8098 
8099                G_err_stage := 'Calling lock_ap_invoice within process_receipt_tax_logic';
8100                write_log(LOG,   G_err_stage);
8101 
8102                lock_ap_invoice(l_po_dist_id_tbl(i));
8103 
8104                l_record_type := 'RECEIPT TAX';
8105 
8106                l_insert_flag_tbl(i)     := 'Y';
8107 
8108                IF (l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) NOT IN ( 'RETURN TO RECEIVING','CORRECT')) THEN
8109 
8110                   l_denom_cost := l_entered_nr_tax_tbl(i);
8111                   l_acct_cost  := l_accounted_nr_tax_tbl(i);
8112                   l_quantity   := l_quantity_tbl(i);
8113 
8114                ELSIF ((l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i)  IN ('CORRECT', 'RETURN TO RECEIVING')) OR
8115                        ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
8116                                                                                         'RETURN TO RECEIVING' ))) THEN
8117                       --
8118                       -- Check if the correction is a complete correction
8119                       --
8120                       DECLARE
8121                          l_primary_quantity     NUMBER;
8122                          l_amount               NUMBER;
8123                          l_exists               VARCHAR2(1);
8124                       BEGIN
8125 
8126                             SELECT primary_quantity, nvl(amount,0)
8127                               INTO l_primary_quantity, l_amount
8128                               FROM rcv_transactions
8129                              WHERE transaction_id = l_parent_rcv_id_tbl(i) ;
8130 
8131                                 -- Added a new variable l_po_tax_qty_tbl which will store the original po qty since the l_quantity_tbl
8132                                 -- variable gets overwritten by the raw cost
8133 
8134                                 IF ((( ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = l_po_tax_qty_tbl(i)) OR --bug5465098
8135                                       ( l_amount = l_amount_tbl(i)))   AND
8136                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'RETURN TO RECEIVING') OR
8137                                         ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
8138                                                                                                          'RETURN TO RECEIVING' )))) OR
8139                                     ((  ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = -l_po_tax_qty_tbl(i)) OR
8140                                       ( l_amount = -l_amount_tbl(i)))   AND /* BUG13566949 */
8141                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'CORRECT')))) THEN
8142 
8143                                   -- Check if the parent has been interfaced to Projects.
8144 				  --added exception block to handle exception for the bug 12379537.
8145 				begin
8146                                      SELECT 'Y'
8147                                        INTO l_exists
8148                                        FROM dual
8149                                         WHERE EXISTS (
8150                                                    SELECT pa_addition_flag
8151                                                      FROM rcv_receiving_sub_ledger
8152                                                     WHERE rcv_transaction_id = l_parent_rcv_id_tbl(i)
8153                                                       AND pa_addition_flag in ('Y','I')) ;
8154 				  exception
8155 			           when others then
8156 			           l_exists:='N';
8157 			       end;
8158 
8159 
8160                    -- Should we call this api at all? This api processes the records
8161                     --  where the pa_addition_flag is 'O'- the ones that got processed in
8162                     --  process_receipt_logic api.
8163                                       IF l_exists = 'Y' THEN
8164 
8165                                         -- Set the parent record attributes for adjustment record to copy
8166 		                        l_txn_src_tbl(i)         := G_RCVTAX_TRANSACTION_SOURCE;
8167                            		l_user_txn_src_tbl(i)    := G_RCVTAX_USER_TRX_SOURCE;
8168                                         l_batch_name_tbl(i)      := G_RCVTAX_BATCH_NAME;
8169                                         l_interface_id_tbl(i)    := G_RCVNRT_INTERFACE_ID;
8170 
8171                        -- This api call may not be necessary. Need to verify.
8172                                          -- Call reversal API
8173                          Process_Adjustments(p_record_type               => 'PO_RECEIPT_TAX',
8174                                              p_document_header_id  => l_po_head_id_tbl(i),/*Added this for 6945767 */
8175                                              p_document_distribution_id  => l_parent_rcv_id_tbl(i),
8176                                              p_current_index             => i,
8177                                              p_last_index                => j);
8178 
8179                                         -- Set the create flag for adjustment records
8180                                            IF l_insert_flag_tbl(i) = 'A' THEN
8181                                             l_create_adj_recs := 'Y';
8182                                            END IF;
8183 
8184                                       END IF ;
8185                                 END IF ; -- primary_quantity  = l_quantity
8186 
8187 
8188                             IF ( l_dest_typ_code_tbl(i) = 'RECEIVING'  OR l_trx_type_tbl(i) = 'RETURN TO RECEIVING' ) THEN
8189                               l_denom_cost := -l_entered_nr_tax_tbl(i);
8190                               l_acct_cost  := -l_accounted_nr_tax_tbl(i);
8191                               l_quantity   := -l_quantity_tbl(i);
8192                            ELSE
8193                               l_denom_cost := l_entered_nr_tax_tbl(i);
8194                               l_acct_cost  := l_accounted_nr_tax_tbl(i);
8195                               l_quantity   := l_quantity_tbl(i);
8196                            END IF;
8197 
8198                        EXCEPTION
8199                           WHEN NO_DATA_FOUND THEN
8200                                 NULL;
8201 
8202                           WHEN OTHERS THEN
8203                                RAISE ;
8204                        END ;
8205 
8206                END IF;
8207 
8208                IF l_quantity = 0 THEN   /* bug 3496492 */
8209                    l_quantity := l_denom_cost;
8210                END IF;
8211 
8212                write_log(LOG, 'This is a record type of: '||l_record_type||
8213                         'denom cost for receipt amount:'||l_denom_cost||
8214                         'acct cost:'||l_acct_cost||'quantity is:'||l_quantity);
8215 
8216                l_record_type_tbl(i)     := l_record_type;
8217                l_denom_raw_cost_tbl(i)  := l_denom_cost;
8218                l_acct_raw_cost_tbl(i)   := l_acct_cost;
8219                l_quantity_tbl(i)        := l_quantity;
8220 
8221                l_txn_status_code_tbl(i) := 'P';
8222                l_txn_rej_code_tbl(i)    := '';
8223 
8224 -- pricing changes start
8225 	       IF (l_rcv_acct_evt_id_tbl(i) is NULL) THEN    /* bug 3475571 */
8226 
8227 		l_txn_src_tbl(i)         := G_RCVTAX_TRANSACTION_SOURCE;
8228 		l_user_txn_src_tbl(i)    := G_RCVTAX_USER_TRX_SOURCE;
8229 	       ELSE
8230 
8231 		SELECT event_type_name
8232 		INTO l_evt_typ_name
8233 		FROM rcv_accounting_event_types rcv_acct_evt_typ, rcv_accounting_events rcv_acct_evts
8234 		WHERE rcv_acct_evt_typ.event_type_id = rcv_acct_evts.event_type_id
8235 		AND rcv_acct_evts.accounting_event_id = l_rcv_acct_evt_id_tbl(i);
8236 
8237 		IF (l_evt_typ_name in ('ADJUST_DELIVER','ADJUST_RECEIVE')) THEN
8238 			l_txn_src_tbl(i)         := G_RCVTAX_PRC_ADJ_TRX_SRC;
8239 			l_user_txn_src_tbl(i)    := G_RCVTAX_PRC_ADJ_USER_TRX_SRC;
8240                         l_quantity               := 0;
8241                         l_quantity_tbl(i)        := l_quantity;
8242 		ELSE
8243 			l_txn_src_tbl(i)         := G_RCVTAX_TRANSACTION_SOURCE;
8244 			l_user_txn_src_tbl(i)    := G_RCVTAX_USER_TRX_SOURCE;
8245 		END IF;
8246 
8247 	       END IF;
8248 -- pricing changes end
8249                l_batch_name_tbl(i)      := G_RCVTAX_BATCH_NAME;
8250                l_interface_id_tbl(i)    := G_RCVNRT_INTERFACE_ID;
8251 
8252               -- FC Doc Type
8253                IF l_fc_enabled_tbl(i) = 'N' THEN
8254                 l_fc_document_type_tbl(i) := 'NOT';
8255                END IF;
8256 
8257          END IF; /* pa_add_flag is O or J */
8258 
8259          IF l_exp_cst_rt_flg_tbl(i) = 'Y' THEN --Exp Cost Rate Required = Y, stamp the quantity. Bug#5138396.
8260             l_quantity_tbl(i)        := l_quantity;
8261          ELSE
8262             l_quantity_tbl(i)        := l_denom_cost;
8263          END IF;
8264 
8265       END LOOP;
8266 
8267    EXCEPTION
8268       WHEN OTHERS THEN
8269           write_log(LOG,'Failed during process_receipt_tax_logic for receipt processing');
8270           G_err_code   := SQLCODE;
8271           raise;
8272    END process_receipt_tax_logic;
8273 
8274    BEGIN
8275 
8276       G_err_stage := 'Entering main logic of transfer_receipts_to_pa';
8277       write_log(LOG, G_err_stage);
8278 
8279       /*Call get_mrc_flag function to see if MRC is set up*/
8280 
8281       --G_DO_MRC_FLAG := get_mrc_flag();
8282       --write_log(LOG, '......Result of get_mrc_flag: ' || G_DO_MRC_FLAG);
8283 
8284       v_max_size := nvl(G_COMMIT_SIZE,200);
8285 
8286       G_err_stage:='Opening Receipt Cursor';
8287       write_log(LOG,   G_err_stage);
8288 
8289       G_RCV_TRANSACTION_SOURCE      := 'PO RECEIPT';
8290       G_RCV_USER_TRANSACTION_SOURCE := 'Oracle Purchasing Receipt Accruals';
8291       G_RCVTAX_TRANSACTION_SOURCE   := 'PO RECEIPT NRTAX';
8292       G_RCVTAX_USER_TRX_SOURCE      := 'Non-Recoverable Tax from Purchasing Receipts';
8293 
8294 --pricing changes
8295       G_RCV_PRC_ADJ_TRX_SRC      := 'PO RECEIPT PRICE ADJ';
8296       G_RCV_PRC_ADJ_USER_TRX_SRC := 'Oracle Purchasing Receipt Accrual Price Adjustments';
8297       G_RCVTAX_PRC_ADJ_TRX_SRC   := 'PO RECEIPT NRTAX PRICE ADJ';
8298       G_RCVTAX_PRC_ADJ_USER_TRX_SRC      := 'Non-Recoverable Tax Price Adjustments from Purchasing Receipts';
8299 
8300       OPEN Rcv_Receipts_Cur;
8301 
8302       WHILE (v_all_done = 0) LOOP
8303 
8304          write_log(LOG,'Receipt cursor is opened. Looping through batches.');
8305 
8306          clear_plsql_tables;
8307 
8308          G_err_stage := 'CREATING NEW INTERFACE ID';
8309          write_log(LOG,   G_err_stage);
8310          SELECT pa_interface_id_s.nextval
8311            INTO G_RCV_INTERFACE_ID FROM dual;
8312 
8313          SELECT pa_interface_id_s.nextval
8314            INTO G_RCVNRT_INTERFACE_ID FROM dual;
8315 
8316          G_err_stage:='Fetching Receipts Cursor';
8317          write_log(LOG,   G_err_stage);
8318 
8319          FETCH Rcv_Receipts_cur BULK COLLECT INTO
8320                l_rcv_txn_id_tbl,
8321                l_po_dist_id_tbl,
8322                l_po_head_id_tbl,
8323                l_po_num_tbl,
8324                l_quantity_tbl,
8325                l_po_tax_qty_tbl,
8326                l_entered_dr_tbl,
8327                l_entered_cr_tbl,
8328                l_accounted_dr_tbl,
8329                l_accounted_cr_tbl,
8330                l_entered_nr_tax_tbl,
8331                l_accounted_nr_tax_tbl,
8332                l_denom_raw_cost_tbl,
8333                l_acct_raw_cost_tbl,
8334                l_record_type_tbl,
8335                l_dist_cc_id_tbl,
8336                l_denom_cur_code_tbl,
8337                l_acct_rate_date_tbl,
8338                l_acct_rate_type_tbl,
8339                l_acct_exch_rate_tbl,
8340                l_gl_date_tbl,
8341                l_dest_typ_code_tbl,
8342                l_pa_add_flag_tbl,
8343                l_trx_type_tbl,
8344                l_project_id_tbl,
8345                l_task_id_tbl,
8346                l_employee_id_tbl,
8347                l_exp_type_tbl,
8348                l_ei_date_tbl,
8349                l_vendor_id_tbl,
8350                l_exp_org_id_tbl,
8351                l_job_id_tbl,
8352                l_description_tbl,
8353                l_attribute_cat_tbl,
8354                l_attribute1_tbl,
8355                l_attribute2_tbl,
8356                l_attribute3_tbl,
8357                l_attribute4_tbl,
8358                l_attribute5_tbl,
8359                l_attribute6_tbl,
8360                l_attribute7_tbl,
8361                l_attribute8_tbl,
8362                l_attribute9_tbl,
8363                l_attribute10_tbl,
8364                l_org_id_tbl,
8365                l_cdl_sys_ref4_tbl,
8366                l_txn_src_tbl,
8367                l_user_txn_src_tbl,
8368                l_batch_name_tbl,
8369                l_interface_id_tbl,
8370                l_exp_end_date_tbl,
8371                l_txn_status_code_tbl,
8372                l_txn_rej_code_tbl,
8373                l_bus_grp_id_tbl,
8374                l_insert_flag_tbl,
8375 	       l_rcv_acct_evt_id_tbl, -- pricing changes
8376 	       l_rcv_acct_rec_tax_tbl,
8377 	       l_rcv_ent_rec_tax_tbl,
8378                l_parent_rcv_id_tbl, --NEW
8379                l_net_zero_flag_tbl, -- NEW
8380                l_sc_xfer_code_tbl,
8381                l_amount_tbl,
8382                l_adj_exp_item_id_tbl,
8383                l_fc_enabled_tbl,
8384                l_mrc_exchange_date_tbl,
8385                l_fc_document_type_tbl,
8386                l_si_assts_add_flg_tbl,
8387                l_insert_flag_tbl,
8388                l_rcv_sub_ledger_id_tbl,
8389                l_exp_cst_rt_flg_tbl
8390          LIMIT v_max_size;
8391 
8392          IF l_rcv_txn_id_tbl.COUNT <> 0 THEN
8393 
8394            /*Start by processing the receipt minus tax records or just the tax record.
8395              Explanation:
8396              The Receipt Cursor picks up both records that have  pa_addition_flag updated
8397              to either 'O' or 'J'. for the ones updated 'O', it means we need to split up
8398              the record into receipt minus tax portion and just the tax portion. The call
8399              to process_receipt_logic will insert only the receipt total minus tax portion.
8400              For records updated to 'J', we will only pull the nr_tax portion and insert
8401              into transaction_interface_all table for processing */
8402 
8403              G_err_stage:='Begin processing just the receipt records';
8404              write_log(LOG,   G_err_stage);
8405 
8406              v_last_rcv_index := l_rcv_txn_id_tbl.LAST;
8407 
8408              process_receipt_logic;
8409 
8410              bulk_insert_trx_intf;
8411 
8412             /* The process_receipt_tax_logic applies only to those records that have been updated
8413              to 'O'. After having the total receipt amount minus tax being inserted into txn
8414              interface table, we need to insert the tax portion of these records by calling
8415              process_receipt_tax_logic. The records that have been updated to 'J' would not be
8416              processed here because the tax amount was taken cared of in proceess_receipt_logic
8417              above.
8418             */
8419 
8420             G_err_stage:='Begin processing receipt tax records';
8421             write_log(LOG,   G_err_stage);
8422 
8423             process_receipt_tax_logic;
8424 
8425             bulk_insert_trx_intf;
8426 
8427             IF v_total_num_receipts > 0 THEN
8428 
8429                IF v_num_receipts_processed > 0 THEN
8430 
8431                   G_err_stage:='Calling trx import for receipts with interface_id:  '||G_RCV_INTERFACE_ID;
8432                   write_log(LOG,   G_err_stage);
8433 
8434 --pricing changes
8435 -- calling import for both transaction sources
8436 
8437  		  trans_import(G_RCV_TRANSACTION_SOURCE, G_RCV_BATCH_NAME,
8438                                G_RCV_INTERFACE_ID, G_USER_ID);
8439 		  trans_import(G_RCV_PRC_ADJ_TRX_SRC, G_RCV_BATCH_NAME,
8440                                G_RCV_INTERFACE_ID, G_USER_ID);
8441 
8442 
8443                   G_err_stage:='After trx import for receipts, check for failed receipts';
8444                   write_log(LOG,   G_err_stage);
8445                   check_failed_receipts(G_RCV_BATCH_NAME, G_RCV_INTERFACE_ID);
8446 
8447                END IF;
8448 
8449                IF v_num_receipt_tax_processed > 0 THEN
8450 
8451                   G_err_stage:='Calling trx import for receipt tax with interface_id:  '||G_RCVNRT_INTERFACE_ID;
8452                   write_log(LOG,   G_err_stage);
8453 --pricing changes
8454 -- calling import for both transaction sources
8455 
8456                   trans_import(G_RCVTAX_TRANSACTION_SOURCE, G_RCVTAX_BATCH_NAME,
8457                                G_RCVNRT_INTERFACE_ID,G_USER_ID);
8458 
8459                   trans_import(G_RCVTAX_PRC_ADJ_TRX_SRC, G_RCVTAX_BATCH_NAME,
8460                                G_RCVNRT_INTERFACE_ID,G_USER_ID);
8461 
8462                END IF;
8463 
8464                G_err_stage:='Calling tieback for receipts';
8465                write_log(LOG,   G_err_stage);
8466                tieback_rcv_Txn(G_RCV_TRANSACTION_SOURCE,G_RCV_BATCH_NAME,
8467                                G_RCV_INTERFACE_ID);
8468 --pricing changes
8469 -- calling tieback for both transaction sources
8470                tieback_rcv_Txn(G_RCV_PRC_ADJ_TRX_SRC,G_RCV_BATCH_NAME,
8471                                G_RCV_INTERFACE_ID);
8472 
8473                G_err_stage:='Calling tieback for receipt tax';
8474                write_log(LOG,   G_err_stage);
8475 
8476                tieback_RCV_Txn(G_RCVTAX_TRANSACTION_SOURCE, G_RCVTAX_BATCH_NAME,
8477                                G_RCVNRT_INTERFACE_ID);
8478 --pricing changes
8479 -- calling tieback for both transaction sources
8480                tieback_RCV_Txn(G_RCVTAX_PRC_ADJ_TRX_SRC, G_RCVTAX_BATCH_NAME,
8481                                G_RCVNRT_INTERFACE_ID);
8482 
8483                write_log(LOG, 'After tying back rcv tax, before calling COMMIT');
8484 
8485                tieback_locked_invoice;
8486                /** 3922679 removed intermediate commit
8487                COMMIT;
8488                3922679 End */
8489 
8490                G_NUM_BATCHES_PROCESSED := G_NUM_BATCHES_PROCESSED + 1;
8491                G_NUM_RCV_TXN_PROCESSED := G_NUM_RCV_TXN_PROCESSED + v_num_receipts_processed;
8492                G_NUM_RCVTAX_PROCESSED  := G_NUM_RCVTAX_PROCESSED  + v_num_receipt_tax_processed;
8493 
8494             END IF; /* v_totabl_num_receipts > 0 */
8495 
8496             clear_plsql_tables;
8497 
8498          ELSE
8499 
8500             G_err_stage := 'plsql table for receipts is empty. Exiting';
8501             write_log(LOG, G_err_stage);
8502 
8503             EXIT; /* Exit if l_rcv_txn_id_tbl.COUNT = 0 */
8504 
8505          END IF; /* l_rcv_txn_id_tbl.COUNT = 0 */
8506 
8507          v_total_num_receipts         := 0;
8508          v_num_receipts_processed     := 0;
8509          v_num_receipt_tax_processed  := 0;
8510 
8511          EXIT WHEN Rcv_Receipts_Cur%NOTFOUND;
8512 
8513       END LOOP; /* While v_all_done = 0 */
8514 
8515       G_err_stage := 'Closing Receipts cursor';
8516       write_log(LOG, G_err_stage);
8517 
8518       CLOSE Rcv_Receipts_cur;
8519 
8520 EXCEPTION
8521     WHEN OTHERS THEN
8522 
8523          G_err_stack := v_old_stack;
8524          IF Rcv_Receipts_Cur%ISOPEN THEN
8525            CLOSE Rcv_Receipts_Cur;
8526          END IF ;
8527 
8528          G_err_code := SQLCODE;
8529          RAISE;
8530 
8531 END transfer_receipts_to_pa;
8532 
8533 PROCEDURE tieback_rcv_Txn (
8534    p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
8535    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
8536    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
8537 
8538    l_pa_addflag             VARCHAR2(1):=NULL;
8539    l_rows_tiebacked         NUMBER :=0;
8540 
8541    l_sys_ref1_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
8542    l_sys_ref2_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
8543    l_sys_ref3_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
8544    l_sys_ref4_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
8545    l_txn_src_tbl            PA_PLSQL_DATATYPES.Char30TabTyp;
8546    l_batch_name_tbl         PA_PLSQL_DATATYPES.Char50TabTyp;
8547    l_interface_id_tbl       PA_PLSQL_DATATYPES.IdTabTyp;
8548    l_txn_status_code_tbl    PA_PLSQL_DATATYPES.Char2TabTyp;
8549    l_project_id_tbl            PA_PLSQL_DATATYPES.IdTabTyp;
8550    l_pa_addflag_tbl         PA_PLSQL_DATATYPES.CHAR1TabTyp;
8551    l_rcv_acct_evt_id_tbl        PA_PLSQL_DATATYPES.IdTabTyp; -- pricing changes
8552    l_dr_ccid_tbl		PA_PLSQL_DATATYPES.IdTabTyp; -- pricing changes
8553 
8554    CURSOR txn_intf_rec (p_txn_src       IN VARCHAR2,
8555                         p_batch_name    IN VARCHAR2,
8556                         p_interface_id  IN NUMBER) IS
8557       SELECT cdl_system_reference1
8558             ,cdl_system_reference2
8559             ,cdl_system_reference3
8560             ,cdl_system_reference4
8561             ,transaction_source
8562             ,batch_name
8563             ,interface_id
8564             ,transaction_status_code
8565             ,project_id
8566             ,l_pa_addflag
8567 	    ,orig_exp_txn_reference2 -- pricing changes
8568 	    ,dr_code_combination_id
8569         FROM pa_transaction_interface_all txnintf
8570        WHERE txnintf.transaction_source = p_txn_src
8571          AND txnintf.batch_name         = p_batch_name
8572          AND txnintf.interface_id       = p_interface_id;
8573 
8574   PROCEDURE clear_plsql_tables IS
8575 
8576       v_status   VARCHAR2(15);
8577 
8578    BEGIN
8579 
8580       G_err_stage:='Clearing PLSQL tables in RCV transactions tieback';
8581       write_log(LOG,   G_err_stage);
8582 
8583       l_sys_ref1_tbl.delete;
8584       l_sys_ref2_tbl.delete;
8585       l_sys_ref3_tbl.delete;
8586       l_sys_ref4_tbl.delete;
8587       l_txn_src_tbl.delete;
8588       l_batch_name_tbl.delete;
8589       l_interface_id_tbl.delete;
8590       l_txn_status_code_tbl.delete;
8591       l_project_id_tbl.delete;
8592       l_pa_addflag_tbl.delete;
8593       l_rcv_acct_evt_id_tbl.delete; -- pricing changes
8594       l_dr_ccid_tbl.delete;
8595 
8596    END clear_plsql_tables;
8597 
8598    PROCEDURE process_tieback IS
8599 
8600       v_status   VARCHAR2(15);
8601 
8602    BEGIN
8603 
8604       G_err_stage:='Within process_tieback of RCV Transactions tieback';
8605       write_log(LOG,   G_err_stage);
8606 
8607       FOR i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST LOOP
8608 
8609          /* If transaction import stamps the record to be 'A' then
8610             update pa_addition_flag of RCV transactions to 'Y'.
8611             If transaction import leaves the record to be 'P' then
8612             update pa_addition_flag of RCV transactions to 'N' or 'I'.
8613             If transaction import stamps the record to be 'R' then
8614             update pa_addition_flag of RCV transactions to 'N' or 'I'.*/
8615 
8616          write_log(LOG,'Tying back transaction ID: '||l_sys_ref4_tbl(i)||
8617                        'trc src:   '||l_txn_src_tbl(i));
8618 
8619          IF l_txn_src_tbl(i) IN ('PO RECEIPT', 'PO RECEIPT PRICE ADJ') THEN
8620 
8621             IF l_txn_status_code_tbl(i) = 'A' THEN
8622                   l_pa_addflag_tbl(i) := 'Y';
8623             ELSIF l_txn_status_code_tbl(i) = 'P' THEN
8624                   l_pa_addflag_tbl(i) :='N';
8625             ELSIF l_txn_status_code_tbl(i) = 'R' THEN
8626                   l_pa_addflag_tbl(i) := 'N';
8627             END IF;
8628 
8629          ELSIF l_txn_src_tbl(i) IN ('PO RECEIPT NRTAX', 'PO RECEIPT NRTAX PRICE ADJ') THEN
8630 
8631             /* Transaction status code of T is a newly added status to
8632                denote that the corresponding receipt has been processed
8633                in the same request but got rejected. Therefore, the pa
8634                addition_flag of the corresponding receipt should be
8635                updated to N. If the status code is R then it should be
8636                updated to I such that the program can pick it up in the
8637                next run and interface ONLY the tax portion */
8638 
8639             IF l_txn_status_code_tbl(i) = 'A' THEN
8640                   l_pa_addflag_tbl(i) := 'Y';
8641             ELSIF l_txn_status_code_tbl(i) = 'T' THEN
8642                   l_pa_addflag_tbl(i) :='N';
8643             ELSIF l_txn_status_code_tbl(i) = 'R' THEN
8644                   l_pa_addflag_tbl(i) := 'I';
8645             END IF;
8646 
8647         END IF; /* checking txn source to be PO RECEIPT, PO RECEIPT PRICE ADJ,
8648 	         PO RECEIPT NRTAX, PO RECEIPT NRTAX PRICE ADJ */
8649 
8650       END LOOP;
8651 
8652    END process_tieback;
8653 
8654    PROCEDURE bulk_update_txn_intf IS
8655 
8656       v_status VARCHAR2(15);
8657 
8658    BEGIN
8659 
8660       G_err_stage:=('Within bulk update of RCV transactions tieback');
8661       write_log(LOG,   G_err_stage);
8662 
8663       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
8664 
8665       /* Code combination Id join is required so that the record whichw as earlier updated to X does nto get updated to Y */
8666 
8667          UPDATE rcv_receiving_sub_ledger rcv_sub -- pricing changes
8668             SET rcv_sub.pa_addition_flag              = l_pa_addflag_tbl(i)
8669           WHERE rcv_sub.rcv_transaction_id        = l_sys_ref4_tbl(i)
8670 	  AND (rcv_sub.accounting_event_id = l_rcv_acct_evt_id_tbl(i) OR rcv_sub.accounting_event_id IS NULL)
8671 	  AND rcv_sub.code_combination_id = l_dr_ccid_tbl(i)
8672            /* Start added for bug#6015451 */
8673 	AND EXISTS
8674             (SELECT 1 from rcv_transactions rcv_txn , po_lines_all pol WHERE
8675               rcv_txn.transaction_id = l_sys_ref4_tbl(i)
8676               and rcv_txn.PO_line_ID            =  POL.po_line_id
8677 	      AND ( (rcv_txn.destination_type_code = 'EXPENSE' AND /*Starts-code changes  for bug:9196652 */
8678 			(( rcv_txn.transaction_type = 'DELIVER' AND
8679 						rcv_sub.entered_dr is NOT NULL
8680                           )
8681 						 OR
8682 						 (
8683 						  rcv_txn.transaction_type = 'RETURN TO RECEIVING' AND
8684 						  rcv_sub.entered_cr is NOT NULL
8685 						  )
8686 						 OR
8687 						 (
8688 						  rcv_txn.transaction_type = 'CORRECT' AND
8689 						 ( rcv_sub.entered_cr is NOT NULL or rcv_sub.entered_dr is NOT NULL )AND
8690 						  rcv_sub.accounting_line_type='Charge'  and
8691 						  decode(POL.order_type_lookup_code,
8692 						 'RATE' , rcv_txn.amount,
8693 						 'FIXED PRICE', rcv_txn.amount,
8694 						  rcv_txn.primary_quantity) < 0
8695 						  )
8696 						 OR
8697 						 (
8698 						  rcv_txn.transaction_type = 'CORRECT' AND
8699 						  rcv_sub.entered_dr is NOT NULL AND
8700 						  decode(POL.order_type_lookup_code,
8701 						  'RATE' , rcv_txn.amount,
8702 						  'FIXED PRICE', rcv_txn.amount,
8703 						  rcv_txn.primary_quantity) >= 0
8704 						  )
8705 						 )  /*Ends-code changes  for bug:9196652*/
8706                      /* rcv_txn.transaction_type <> 'RETURN TO RECEIVING' AND rcv_sub.entered_dr is NOT NULL
8707 	            ) OR
8708 	          ((rcv_txn.destination_type_code = 'RECEIVING' OR
8709 	           rcv_txn.transaction_type = 'RETURN TO RECEIVING') AND rcv_sub.entered_cr is NOT NULL
8710                   ) commented for bug:9196652*/
8711                  ))
8712              );
8713 		/* Ends added for bug#6015451 */
8714 
8715 
8716       l_rows_tiebacked := SQL%ROWCOUNT;
8717       write_log(LOG,'Number of RCV transactions tied back:  '||l_rows_tiebacked);
8718 
8719    EXCEPTION
8720       WHEN OTHERS THEN
8721          G_err_stage:= 'Failed during bulk update of RCV transactions tieback';
8722          write_log(LOG,   G_err_stage);
8723          G_err_code   := SQLCODE;
8724          raise;
8725 
8726    END bulk_update_txn_intf;
8727 
8728    BEGIN
8729 
8730       /* Main logic of tieback starts here */
8731       G_err_stage:='Within main logic of tieback';
8732       write_log(LOG,   G_err_stage);
8733 
8734       G_err_stage:='Opening txn_intf_rec';
8735       write_log(LOG,   G_err_stage);
8736 
8737       OPEN txn_intf_rec(p_transaction_source
8738                        ,p_batch_name
8739                        ,p_interface_id);
8740 
8741       G_err_stage:='Fetching txn_intf_rec';
8742       write_log(LOG,   G_err_stage);
8743 
8744       clear_plsql_tables;
8745 
8746       FETCH txn_intf_rec BULK COLLECT INTO
8747           l_sys_ref1_tbl
8748          ,l_sys_ref2_tbl
8749          ,l_sys_ref3_tbl
8750          ,l_sys_ref4_tbl
8751          ,l_txn_src_tbl
8752          ,l_batch_name_tbl
8753          ,l_interface_id_tbl
8754          ,l_txn_status_code_tbl
8755          ,l_project_id_tbl
8756          ,l_pa_addflag_tbl
8757 	 ,l_rcv_acct_evt_id_tbl
8758 	 ,l_dr_ccid_tbl;
8759 
8760       IF l_sys_ref1_tbl.COUNT <> 0 THEN
8761 
8762          process_tieback;
8763 
8764          bulk_update_txn_intf;
8765 
8766          clear_plsql_tables;
8767 
8768       END IF;
8769 
8770       CLOSE txn_intf_rec;
8771 
8772 EXCEPTION
8773 
8774   WHEN OTHERS THEN
8775      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
8776      G_err_code := SQLCODE;
8777      RAISE;
8778 
8779 END tieback_rcv_Txn;
8780 
8781 PROCEDURE check_failed_receipts (
8782    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
8783    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
8784 
8785    v_num_receipts_failed NUMBER:=0;
8786    v_po_head_id   VARCHAR2(35);
8787    v_po_dist_id   VARCHAR2(35);
8788    v_txn_id       VARCHAR2(35);
8789    v_acct_evt_id  NUMBER; -- pricing changes
8790 
8791    CURSOR Failed_Rec (p_batch_name   IN VARCHAR2,
8792                       p_interface_id IN NUMBER) IS
8793       SELECT cdl_system_reference2
8794             ,cdl_system_reference3
8795             ,cdl_system_reference4
8796 	    ,orig_exp_txn_reference2 -- pricing changes
8797        FROM pa_transaction_interface
8798       WHERE transaction_status_code = 'R'
8799         AND transaction_source      IN ('PO RECEIPT', 'PO RECEIPT PRICE ADJ')
8800         AND batch_name              = p_batch_name
8801         AND interface_id            = p_interface_id;
8802 
8803 BEGIN
8804 
8805    G_err_stage := 'Within calling check_failed_receipts';
8806    write_log(LOG, G_err_stage);
8807 
8808    write_log(LOG,'Checking for failed receipts for batch_name:  '||p_batch_name
8809                  ||'interface id:  '||p_interface_id);
8810 
8811    OPEN Failed_Rec(p_batch_name
8812                   ,p_interface_id);
8813 
8814    LOOP
8815 
8816       FETCH Failed_Rec INTO v_po_head_id
8817                            ,v_po_dist_id
8818                            ,v_txn_id
8819 			   ,v_acct_evt_id; -- pricing changes
8820       EXIT WHEN Failed_Rec%NOTFOUND;
8821 
8822       write_log(LOG,'Number of failed receipt fetched:  '||v_num_receipts_failed);
8823 
8824    /* Changed p_batch_name and p_interface_id to G_ globals.
8825       Cursor fetched the batch name and interface id for RECEIPT and not
8826       for NRTAX */
8827 
8828       write_log(LOG,'Batch Name and Interface Id is : '||G_RCVTAX_BATCH_NAME||'  '||G_UNIQUE_ID);
8829 
8830       UPDATE pa_transaction_interface_all
8831         SET transaction_status_code  = 'T'
8832         WHERE batch_name             =  G_RCVTAX_BATCH_NAME /* p_batch_name changed for #2912545 */
8833           AND interface_id           =  G_RCVNRT_INTERFACE_ID /* p_interface_id changed for #2912545 */
8834           AND transaction_source     = 'PO RECEIPT NRTAX' /* PO RECEIPT TAX. changed for #2912545 */
8835           AND cdl_system_reference2  = v_po_head_id
8836           AND cdl_system_reference3  = v_po_dist_id
8837           AND cdl_system_reference4  = v_txn_id;
8838 
8839 -- pricing changes
8840       UPDATE pa_transaction_interface_all
8841         SET transaction_status_code  = 'T'
8842         WHERE batch_name             =  G_RCVTAX_BATCH_NAME /* p_batch_name changed for #2912545 */
8843           AND interface_id           =  G_RCVNRT_INTERFACE_ID /* p_interface_id changed for #2912545 */
8844           AND transaction_source     = 'PO RECEIPT NRTAX PRICE ADJ' /* PO RECEIPT TAX. changed for #2912545 */
8845           AND cdl_system_reference2  = v_po_head_id
8846           AND cdl_system_reference3  = v_po_dist_id
8847           AND cdl_system_reference4  = v_txn_id
8848 	  AND orig_exp_txn_reference2 = v_acct_evt_id;
8849 
8850       v_num_receipts_failed := v_num_receipts_failed +  SQL%ROWCOUNT;
8851 
8852    END LOOP;
8853 
8854    write_log(LOG,'number of receipts failed: '||v_num_receipts_failed);
8855 
8856    CLOSE Failed_Rec;
8857 
8858 EXCEPTION
8859   WHEN OTHERS THEN
8860      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
8861      CLOSE Failed_Rec;
8862      G_err_code := SQLCODE;
8863      RAISE;
8864 
8865 END check_failed_receipts;
8866 
8867 PROCEDURE lock_ap_invoice (p_po_distribution_id IN ap_invoice_distributions.po_distribution_id%TYPE)  IS
8868 
8869   l_num_rows NUMBER;
8870 
8871 BEGIN
8872 
8873    G_err_stage := 'Within calling lock_ap_invoice';
8874    write_log(LOG, G_err_stage);
8875 
8876     UPDATE ap_invoice_distributions_all dist
8877        SET dist.pa_addition_flag   = 'L'
8878      WHERE dist.po_distribution_id = p_po_distribution_id
8879        AND dist.pa_addition_flag   = 'N';
8880 
8881     l_num_rows := SQL%ROWCOUNT;
8882 
8883     write_log(LOG,'number of ap invoices locked:'||l_num_rows);
8884 
8885 EXCEPTION
8886    WHEN NO_DATA_FOUND THEN
8887        NULL;
8888 
8889    WHEN OTHERS THEN
8890 
8891      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
8892      G_err_code := SQLCODE;
8893      RAISE;
8894 END lock_ap_invoice;
8895 
8896 PROCEDURE tieback_locked_invoice IS
8897 
8898   l_num_rows NUMBER;
8899 
8900 BEGIN
8901 
8902    G_err_stage := 'Within calling tieback_locked_invoice';
8903    write_log(LOG, G_err_stage);
8904 
8905    UPDATE ap_invoice_distributions_all dist
8906       SET dist.pa_addition_flag = 'N'
8907     WHERE dist.pa_addition_flag = 'L';
8908 
8909     l_num_rows := SQL%ROWCOUNT;
8910 
8911     write_log(LOG,'number of ap invoices unlocked:'||l_num_rows);
8912 
8913 EXCEPTION
8914    WHEN NO_DATA_FOUND THEN
8915       NULL;
8916 
8917    WHEN OTHERS THEN
8918 
8919      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
8920      G_err_code := SQLCODE;
8921      RAISE;
8922 END tieback_locked_invoice;
8923 
8924 /*==========================================================================*/
8925 --The following section contains procedures for AP Invoice AMount Variance Processing
8926 
8927 --Function that increments the W count, and returns the same flag back.
8928 
8929 FUNCTION increment_W_count(W_flag IN VARCHAR2)
8930    RETURN VARCHAR2 IS
8931 BEGIN
8932    G_NUM_AP_VARIANCE_MARKED_W := G_NUM_AP_VARIANCE_MARKED_W + 1;
8933    RETURN W_flag;
8934 END;
8935 
8936 
8937 
8938 PROCEDURE mark_inv_var_paflag IS
8939 
8940    v_num_empty_lines    NUMBER;
8941 
8942 BEGIN
8943 
8944    G_err_stage:= 'Within mark_inv_var_paflag';
8945    write_log(LOG,   G_err_stage);
8946 
8947    G_err_stage:= 'Updating empty invoice amount varaince lines pa addtion flag to G or W';
8948    write_log(LOG,   G_err_stage);
8949 
8950 
8951    IF G_PROJECT_ID IS NOT NULL THEN
8952 
8953     --
8954     -- Update pa-addition-flag to 'G' for item and nrtax lines if the invoice is matched to PO/RCPT that is
8955     -- accrued-on-rcpt and the PO has never been interfaced as invoice, historically
8956     -- However, such Invoice lines that have amount variance will be marked as W so that these can be processed
8957     -- for relieving the variance commitment
8958     --
8959     -- In rel12, Receipt Accruals along with NRTAX will be interfaced into Projects only from Purchasing
8960     -- However Variance and other related costs like Freight/Misc will still be interfaced from Payables
8961     --
8962         If g_body_debug_mode = 'Y' Then
8963         write_log(LOG, 'Updating empty invoice variance lines pa addtion flag to G for a project');
8964         End if;
8965 
8966    UPDATE ap_invoice_distributions_all apdist
8967       SET apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
8968           request_id = G_REQUEST_ID,
8969           last_update_date=SYSDATE,
8970           last_updated_by=G_USER_ID,
8971           last_update_login= G_USER_ID,
8972           program_id= G_PROG_ID,
8973           program_application_id= G_PROG_APPL_ID,
8974           program_update_date=SYSDATE
8975     WHERE rowid IN (
8976           SELECT dist.rowid
8977           FROM  ap_invoices inv, ap_invoice_distributions_all dist
8978           WHERE inv.invoice_id = dist.invoice_id
8979           AND  (dist.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX')
8980                 OR ( pa_nl_installed.is_nl_installed = 'Y'                 --EIB trackable items
8981                                  AND EXISTS (SELECT 'X'
8982                                               FROM  mtl_system_items si,
8983                                                     po_lines_all pol,
8984                                                     po_distributions_all po_dist1
8985                                               WHERE po_dist1.po_line_id = pol.po_line_id
8986                                               AND   po_dist1.po_distribution_id  = dist.po_distribution_id
8987                                               AND   si.inventory_item_id = pol.item_id
8988                                               AND   po_dist1.project_id IS NOT NULL
8989                                               AND   si.comms_nl_trackable_flag = 'Y'
8990 					      AND   (si.organization_id = po_dist1.org_id
8991 						OR /* Added for bug 13714500 */
8992                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
8993                                                  where pll.po_header_id = po_dist1.po_header_id
8994 						              and pll.po_line_id = po_dist1.po_line_id)
8995 						))
8996                           )
8997                  ) --Bug#5399352. Added this here to take care of IPV/TIPV records matched to EIB item PO.
8998           AND   NOT EXISTS (SELECT NULL
8999                                      FROM ap_invoice_distributions_all apdist2
9000                                     WHERE apdist2.pa_addition_flag   = 'Y'
9001                                       AND apdist2.po_distribution_id = dist.po_distribution_id
9002                                       AND (apdist2.line_type_lookup_code = dist.line_type_lookup_code
9003                                          or (apdist2.historical_flag = 'Y' and
9004                                              dist.line_type_lookup_code = 'ACCRUAL')) /* Modified for bug 14003230 */
9005                                       AND apdist2.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX')
9006                            )
9007           AND  (  EXISTS (SELECT NULL
9008                               FROM ap_invoice_distributions_all apdist1,
9009                                    ap_invoices_all ap1                 /*Changes for bug 7650946 -- Start */
9010                              WHERE apdist1.pa_addition_flag   IN ('F', 'G')
9011                                AND ap1.invoice_id = apdist1.invoice_id	/*Added for bug 	7650946 */
9012                                AND apdist1.po_distribution_id  = dist.po_distribution_id
9013                                 AND ap1.Invoice_Type_lookup_Code <> 'PREPAYMENT'
9014                                AND apdist1.Line_Type_Lookup_Code <> 'PREPAY'  /*Changes for bug 7650946 -- End */
9015                           )
9016                  OR EXISTS (  SELECT rcv_txn.po_distribution_id
9017                                 FROM rcv_transactions rcv_txn
9018                                    , rcv_receiving_sub_ledger rcv_sub
9019                                WHERE rcv_txn.po_distribution_id      = dist.po_distribution_id
9020                                  AND rcv_sub.pa_addition_flag || '' IN ('Y','I')
9021                                  AND rcv_sub.rcv_transaction_id      = rcv_txn.transaction_id
9022                            )
9023                  OR EXISTS (  SELECT  PO.po_distribution_id
9024                                 FROM  po_distributions PO
9025                                WHERE  PO.po_distribution_id = dist.po_distribution_id
9026                                  AND  nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'  -- bug 7192304, added nvl
9027                                  AND  PO.project_id  > 0
9028                                  AND  NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
9029                                  AND  PO.accrue_on_receipt_flag= 'Y'
9030                            )
9031                 )
9032           --AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT' commented for bug16028785
9033           AND   nvl(INV.source, 'xx' ) NOT IN
9034                  ('Oracle Project Accounting','PA_IC_INVOICES')
9035           AND   dist.pa_addition_flag = 'N'
9036           AND   dist.posted_flag = 'Y'
9037           AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
9038           AND   trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date))
9039           AND   dist.project_id = G_PROJECT_ID
9040           -- Process historical distributions for CAsh BAsed Accounting
9041           AND   (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
9042           AND   dist.po_distribution_id > 0 ); /*Removed NVL condition for bug#12922795 */
9043 
9044           write_log(LOG,'Number of inv amount variance lines marked to G:  '||to_char(SQL%ROWCOUNT));
9045           write_log(LOG,'Number of inv amount variance lines marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W);
9046 
9047 /*Commented out for bBug 13602288: Self Assessed Tax Changes
9048 	   UPDATE ap_self_assessed_tax_dist_all apdist
9049       SET apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
9050           request_id = G_REQUEST_ID,
9051           last_update_date=SYSDATE,
9052           last_updated_by=G_USER_ID,
9053           last_update_login= G_USER_ID,
9054           program_id= G_PROG_ID,
9055           program_application_id= G_PROG_APPL_ID,
9056           program_update_date=SYSDATE
9057     WHERE rowid IN (
9058           SELECT dist.rowid
9059           FROM  ap_invoices inv, ap_self_assessed_tax_dist_all dist
9060           WHERE inv.invoice_id = dist.invoice_id
9061           AND  (dist.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX')
9062                 OR ( pa_nl_installed.is_nl_installed = 'Y'                 --EIB trackable items
9063                                  AND EXISTS (SELECT 'X'
9064                                               FROM  mtl_system_items si,
9065                                                     po_lines_all pol,
9066                                                     po_distributions_all po_dist1
9067                                               WHERE po_dist1.po_line_id = pol.po_line_id
9068                                               AND   po_dist1.po_distribution_id  = dist.po_distribution_id
9069                                               AND   si.inventory_item_id = pol.item_id
9070                                               AND   po_dist1.project_id IS NOT NULL
9071                                               AND   si.comms_nl_trackable_flag = 'Y'
9072 					      AND   si.organization_id = po_dist1.org_id)
9073                           )
9074                  ) --Bug#5399352. Added this here to take care of IPV/TIPV records matched to EIB item PO.
9075           AND   NOT EXISTS (SELECT NULL
9076                                      FROM ap_self_assessed_tax_dist_all apdist2
9077                                     WHERE apdist2.pa_addition_flag   = 'Y'
9078                                       AND apdist2.po_distribution_id = dist.po_distribution_id
9079                                       AND apdist2.line_type_lookup_code = dist.line_type_lookup_code
9080                                       AND apdist2.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX')
9081                            )
9082           AND  (  EXISTS (SELECT NULL
9083                               FROM ap_self_assessed_tax_dist_all apdist1,
9084                                    ap_invoices_all ap1                 /*Changes for bug 7650946 -- Start
9085                              WHERE apdist1.pa_addition_flag   IN ('F', 'G')
9086                                AND ap1.invoice_id = apdist1.invoice_id	/*Added for bug 	7650946
9087                                AND apdist1.po_distribution_id  = dist.po_distribution_id
9088                                 AND ap1.Invoice_Type_lookup_Code <> 'PREPAYMENT'
9089                                AND apdist1.Line_Type_Lookup_Code <> 'PREPAY'  /*Changes for bug 7650946 -- End
9090                           )
9091                  OR EXISTS (  SELECT rcv_txn.po_distribution_id
9092                                 FROM rcv_transactions rcv_txn
9093                                    , rcv_receiving_sub_ledger rcv_sub
9094                                WHERE rcv_txn.po_distribution_id      = dist.po_distribution_id
9095                                  AND rcv_sub.pa_addition_flag || '' IN ('Y','I')
9096                                  AND rcv_sub.rcv_transaction_id      = rcv_txn.transaction_id
9097                            )
9098                  OR EXISTS (  SELECT  PO.po_distribution_id
9099                                 FROM  po_distributions PO
9100                                WHERE  PO.po_distribution_id = dist.po_distribution_id
9101                                  AND  nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'  -- bug 7192304, added nvl
9102                                  AND  PO.project_id  > 0
9103                                  AND  NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
9104                                  AND  PO.accrue_on_receipt_flag= 'Y'
9105                            )
9106                 )
9107           AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
9108           AND   nvl(INV.source, 'xx' ) NOT IN
9109                  ('Oracle Project Accounting','PA_IC_INVOICES')
9110           AND   dist.pa_addition_flag = 'N'
9111           AND   dist.posted_flag = 'Y'
9112           AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
9113           AND   trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date))
9114           AND   dist.project_id = G_PROJECT_ID
9115           -- Process historical distributions for CAsh BAsed Accounting
9116           AND   (G_ACCTNG_METHOD = 'A' )
9117           AND   dist.po_distribution_id > 0 ); /*Removed NVL condition for bug#12922795 */
9118 
9119 	  -- write_log(LOG,'Number of inv amount variance SAT lines marked to G:  '||to_char(SQL%ROWCOUNT)); bug 13546835
9120         --  write_log(LOG,'Number of inv amount variance SAT lines marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W); bug 13546835
9121 
9122       /* If the Supplier Invoice is matched to period-end PO for Contingent worker labor fixed rate and the CWK timecard
9123          is to be processed as Labor cost, only non recoverable tax receipt lines, variances and other allocated costs should be
9124          pulled from Payables. The pa_addition_flag for such invoice ITEM distribution lines is updated to G to prevent
9125          further processing into Projects.
9126          However, if there is an amount variance on such invoice, it needs to be processed as W to releive variance commitment  */
9127 
9128            UPDATE ap_invoice_distributions_all apdist
9129            SET    apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
9130                   request_id = G_REQUEST_ID,
9131                   last_update_date=SYSDATE,
9132                   last_updated_by=G_USER_ID,
9133                   last_update_login= G_USER_ID,
9134                   program_id= G_PROG_ID,
9135                   program_application_id= G_PROG_APPL_ID,
9136                   program_update_date=SYSDATE
9137            WHERE  rowid in (
9138                            SELECT dist.rowid
9139                            FROM  ap_invoices inv,
9140                                  po_distributions po,
9141                                  ap_invoice_distributions_all dist
9142                            WHERE inv.invoice_id = dist.invoice_id
9143                            AND   po.po_distribution_id = dist.po_distribution_id
9144 			   AND   dist.po_distribution_id >0  /*Added the condition for bug#12922795 */
9145         		   AND   nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'  -- bug 7192304, added nvl
9146                            AND   NVL(po.destination_type_code, 'EXPENSE') = 'EXPENSE'
9147                            AND   PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(dist.project_ID, 0))= 'Y'
9148                            AND   PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(dist.po_distribution_id,0))= 'Y'
9149                            AND   dist.line_type_lookup_code in ( 'ITEM','ACCRUAL','RETROACCRUAL') --added accrual for historical data
9150                            AND   dist.pa_addition_flag = 'N'
9151                            AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
9152                            AND   nvl(INV.source, 'xx' ) NOT IN
9153                                ('Oracle Project Accounting','PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
9154                            AND   dist.pa_addition_flag = 'N'
9155                            AND   dist.project_id > 0
9156                            AND   dist.posted_flag = 'Y'
9157                            AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date)) /* Added trunc for the bug 6623163 */
9158                            AND   trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date))/* Added trunc for the bug 6623163 */
9159                            AND   dist.project_id = G_PROJECT_ID
9160                            -- Process historical distributions for CAsh BAsed Accounting
9161                            AND   (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
9162                            AND   inv.paid_on_behalf_employee_id is NULL
9163 AND inv.source not  in ('CREDIT CARD','Both Pay') /* Added for bug 8977795 */ );
9164 
9165            write_log(LOG,'Number of inv amount variance lines for CWK marked to G:  '||to_char(SQL%ROWCOUNT));
9166            write_log(LOG,'Number of inv amount variance lines for CWK marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W);
9167 
9168 /* Clearly the above update has only the line type lookup code in ITEM, ACCRUAL and RETRO ACCRUAL , so did not update the same for
9169 Self Assessed Tax  Lines*/
9170 
9171    Else  -- G_PROJECT_ID IS NULL
9172 
9173     --
9174     -- Update pa-addition-flag to 'G' for item and nrtax lines if the invoice is matched to PO/RCPT that is
9175     -- accrued-on-rcpt and the PO has never been interfaced as invoice, historically
9176     -- However, such Invoice lines that have amount variance will be marked as W so that these can be processed
9177     -- for relieving the variance commitment
9178     --
9179     -- In rel12, Receipt Accruals along with NRTAX will be interfaced into Projects only from Purchasing
9180     -- However Variance and other related costs like Freight/Misc will still be interfaced from Payables
9181     --
9182 
9183         If g_body_debug_mode = 'Y' Then
9184         write_log(LOG, 'Updating empty invoice variance lines pa addtion flag to G for all');
9185         End if;
9186 
9187    UPDATE ap_invoice_distributions_all apdist
9188       SET apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
9189           request_id = G_REQUEST_ID,
9190           last_update_date=SYSDATE,
9191           last_updated_by=G_USER_ID,
9192           last_update_login= G_USER_ID,
9193           program_id= G_PROG_ID,
9194           program_application_id= G_PROG_APPL_ID,
9195           program_update_date=SYSDATE
9196     WHERE rowid IN (
9197           SELECT dist.rowid
9198           FROM  ap_invoices inv, ap_invoice_distributions_all dist
9199           WHERE inv.invoice_id = dist.invoice_id
9200           AND  ( dist.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX')
9201                 OR ( pa_nl_installed.is_nl_installed = 'Y'                 --EIB trackable items
9202                                  AND EXISTS (SELECT 'X'
9203                                               FROM  mtl_system_items si,
9204                                                     po_lines_all pol,
9205                                                     po_distributions_all po_dist1
9206                                               WHERE po_dist1.po_line_id = pol.po_line_id
9207                                               AND   po_dist1.po_distribution_id  = dist.po_distribution_id
9208                                               AND   si.inventory_item_id = pol.item_id
9209                                               AND   po_dist1.project_id IS NOT NULL
9210                                               AND   si.comms_nl_trackable_flag = 'Y'
9211 					      AND   (si.organization_id = po_dist1.org_id
9212 						OR /* Added for bug 13714500 */
9213                          si.organization_id in (select nvl(ship_to_organization_id,-9999) from po_line_locations_all pll
9214                                                  where pll.po_header_id = po_dist1.po_header_id
9215 						              and pll.po_line_id = po_dist1.po_line_id)
9216 						))
9217                           )
9218                  ) --Bug#5399352. Added this here to take care of IPV/TIPV records matched to EIB item PO.
9219           AND   NOT EXISTS (SELECT NULL
9220                                      FROM ap_invoice_distributions_all apdist2
9221                                     WHERE apdist2.pa_addition_flag   = 'Y'
9222                                       AND apdist2.po_distribution_id = dist.po_distribution_id
9223                                       AND (apdist2.line_type_lookup_code = dist.line_type_lookup_code
9224                                          or (apdist2.historical_flag = 'Y' and
9225                                              dist.line_type_lookup_code = 'ACCRUAL')) /* Modified for bug 14003230 */
9226                                       AND apdist2.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX')
9227                            )
9228           AND  (  EXISTS (SELECT NULL
9229                               FROM ap_invoice_distributions_all apdist1,
9230                                    ap_invoices_all ap1                   /*Changes for bug 7650946 -- Start */
9231                              WHERE apdist1.pa_addition_flag   IN ('F', 'G')
9232                                AND ap1.invoice_id = apdist1.invoice_id
9233                                AND apdist1.po_distribution_id  = dist.po_distribution_id
9234                                 AND ap1.Invoice_Type_lookup_Code <> 'PREPAYMENT'
9235                                AND apdist1.Line_Type_Lookup_Code <> 'PREPAY'  /*Changes for bug 7650946 -- End */
9236                           )
9237                  OR EXISTS (  SELECT rcv_txn.po_distribution_id
9238                                 FROM rcv_transactions rcv_txn
9239                                    , rcv_receiving_sub_ledger rcv_sub
9240                                WHERE rcv_txn.po_distribution_id      = dist.po_distribution_id
9241                                  AND rcv_sub.pa_addition_flag || '' IN ('Y','I')
9242                                  AND rcv_sub.rcv_transaction_id      = rcv_txn.transaction_id
9243                            )
9244                  OR EXISTS (  SELECT  PO.po_distribution_id
9245                                 FROM  po_distributions PO
9246                                WHERE  PO.po_distribution_id = dist.po_distribution_id
9247                                  AND  nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'  -- bug 7192304, added nvl
9248                                  AND  PO.project_id  > 0
9249                                  AND  NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
9250                                  AND  PO.accrue_on_receipt_flag= 'Y'
9251                            )
9252                 )
9253           --AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT' commented for bug 16028785
9254           AND   nvl(INV.source, 'xx' ) NOT IN
9255                  ('Oracle Project Accounting','PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
9256           AND   dist.pa_addition_flag = 'N'
9257           AND   dist.posted_flag = 'Y'
9258           AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))  /* Added trunc for the bug 6623163 */
9259           AND  trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date)) /* Added trunc for the bug 6623163 */
9260           AND   dist.project_id > 0
9261           -- Process historical distributions for CAsh BAsed Accounting
9262           AND   (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
9263           AND   dist.po_distribution_id > 0 ); /*Removed NVL condition for bug#12922795 */
9264 
9265           write_log(LOG,'Number of inv amount variance lines marked to G:  '||to_char(SQL%ROWCOUNT));
9266           write_log(LOG,'Number of inv amount variance lines marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W);
9267 
9268 
9269 /*Commented for Bug 13602288:  Self Assessed Tax Changes
9270 	     UPDATE ap_self_assessed_tax_dist_all apdist
9271       SET apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
9272           request_id = G_REQUEST_ID,
9273           last_update_date=SYSDATE,
9274           last_updated_by=G_USER_ID,
9275           last_update_login= G_USER_ID,
9276           program_id= G_PROG_ID,
9277           program_application_id= G_PROG_APPL_ID,
9278           program_update_date=SYSDATE
9279     WHERE rowid IN (
9280           SELECT dist.rowid
9281           FROM  ap_invoices inv, ap_self_assessed_tax_dist_all dist
9282           WHERE inv.invoice_id = dist.invoice_id
9283           AND  ( dist.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX')
9284                 OR ( pa_nl_installed.is_nl_installed = 'Y'                 --EIB trackable items
9285                                  AND EXISTS (SELECT 'X'
9286                                               FROM  mtl_system_items si,
9287                                                     po_lines_all pol,
9288                                                     po_distributions_all po_dist1
9289                                               WHERE po_dist1.po_line_id = pol.po_line_id
9290                                               AND   po_dist1.po_distribution_id  = dist.po_distribution_id
9291                                               AND   si.inventory_item_id = pol.item_id
9292                                               AND   po_dist1.project_id IS NOT NULL
9293                                               AND   si.comms_nl_trackable_flag = 'Y'
9294 					      AND   si.organization_id = po_dist1.org_id)
9295                           )
9296                  ) --Bug#5399352. Added this here to take care of IPV/TIPV records matched to EIB item PO.
9297           AND   NOT EXISTS (SELECT NULL
9298                                      FROM ap_self_assessed_tax_dist_all apdist2
9299                                     WHERE apdist2.pa_addition_flag   = 'Y'
9300                                       AND apdist2.po_distribution_id = dist.po_distribution_id
9301                                       AND apdist2.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX')
9302                            )
9303           AND  (  EXISTS (SELECT NULL
9304                               FROM ap_self_assessed_tax_dist_all apdist1,
9305                                    ap_invoices_all ap1                   /*Changes for bug 7650946 -- Start
9306                              WHERE apdist1.pa_addition_flag   IN ('F', 'G')
9307                                AND ap1.invoice_id = apdist1.invoice_id
9308                                AND apdist1.po_distribution_id  = dist.po_distribution_id
9309                                 AND ap1.Invoice_Type_lookup_Code <> 'PREPAYMENT'
9310                                AND apdist1.Line_Type_Lookup_Code <> 'PREPAY'  /*Changes for bug 7650946 -- End
9311                           )
9312                  OR EXISTS (  SELECT rcv_txn.po_distribution_id
9313                                 FROM rcv_transactions rcv_txn
9314                                    , rcv_receiving_sub_ledger rcv_sub
9315                                WHERE rcv_txn.po_distribution_id      = dist.po_distribution_id
9316                                  AND rcv_sub.pa_addition_flag || '' IN ('Y','I')
9317                                  AND rcv_sub.rcv_transaction_id      = rcv_txn.transaction_id
9318                            )
9319                  OR EXISTS (  SELECT  PO.po_distribution_id
9320                                 FROM  po_distributions PO
9321                                WHERE  PO.po_distribution_id = dist.po_distribution_id
9322                                  AND  nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'  -- bug 7192304, added nvl
9323                                  AND  PO.project_id  > 0
9324                                  AND  NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
9325                                  AND  PO.accrue_on_receipt_flag= 'Y'
9326                            )
9327                 )
9328           AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
9329           AND   nvl(INV.source, 'xx' ) NOT IN
9330                  ('Oracle Project Accounting','PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
9331           AND   dist.pa_addition_flag = 'N'
9332           AND   dist.posted_flag = 'Y'
9333           AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))  /* Added trunc for the bug 6623163
9334           AND  trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date)) /* Added trunc for the bug 6623163
9335           AND   dist.project_id > 0
9336           -- Process historical distributions for CAsh BAsed Accounting
9337           AND   (G_ACCTNG_METHOD = 'A' )
9338           AND   dist.po_distribution_id > 0 ); /*Removed NVL condition for bug#12922795 */
9339 
9340        --   write_log(LOG,'Number of inv amount variance SAT lines marked to G:  '||to_char(SQL%ROWCOUNT)); bug 13546835
9341        --   write_log(LOG,'Number of inv amount variance SAT lines marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W); bug 13546835
9342 
9343       /* If the Supplier Invoice is matched to period-end PO for Contingent worker labor fixed rate and the CWK timecard
9344          is to be processed as Labor cost, only non recoverable tax receipt lines, variances and other allocated costs should be
9345          pulled from Payables. The pa_addition_flag for such invoice ITEM distribution lines is updated to G to prevent
9346          further processing into Projects.
9347          However, if there is an amount variance on such invoice, it needs to be processed as W to releive variance commitment  */
9348 
9349            UPDATE ap_invoice_distributions_all apdist
9350            SET    apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
9351                   request_id = G_REQUEST_ID,
9352                   last_update_date=SYSDATE,
9353                   last_updated_by=G_USER_ID,
9354                   last_update_login= G_USER_ID,
9355                   program_id= G_PROG_ID,
9356                   program_application_id= G_PROG_APPL_ID,
9357                   program_update_date=SYSDATE
9358            WHERE  rowid in (
9359                            SELECT dist.rowid
9360                            FROM  ap_invoices inv,
9361                                  po_distributions po,
9362                                  ap_invoice_distributions_all dist
9363                            WHERE inv.invoice_id = dist.invoice_id
9364                            AND   po.po_distribution_id = dist.po_distribution_id
9365 			   AND   dist.po_distribution_id >0  /*Added the condition for bug#12922795 */
9366                            AND   NVL(po.destination_type_code, 'EXPENSE') = 'EXPENSE'
9367                            AND   nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'   -- bug 7192304, added nvl
9368                            AND   PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(dist.project_ID, 0))= 'Y'
9369                            AND   PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(dist.po_distribution_id,0))= 'Y'
9370                            AND   dist.line_type_lookup_code in ( 'ITEM','ACCRUAL','RETROACCRUAL') --added accrual for historical data
9371                            AND   dist.pa_addition_flag = 'N'
9372                            AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
9373                            AND   nvl(INV.source, 'xx' ) NOT IN
9374                                ('Oracle Project Accounting','PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
9375                            AND   dist.pa_addition_flag = 'N'
9376                            AND   dist.posted_flag = 'Y'
9377                            AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date)) /* Added trunc for the bug 6623163 */
9378                            AND   trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date)) /* Added trunc for the bug 6623163 */
9379                            AND   dist.project_id > 0
9380                            -- Process historical distributions for CAsh BAsed Accounting
9381                            AND   (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
9382                            AND   inv.paid_on_behalf_employee_id is NULL
9383                            AND inv.source not  in ('CREDIT CARD','Both Pay') /* Added for bug 8977795 */);
9384 
9385            write_log(LOG,'Number of inv amount variance lines for CWK marked to G:  '||to_char(SQL%ROWCOUNT));
9386            write_log(LOG,'Number of inv amount variance lines for CWK marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W);
9387 
9388    END IF; /* IF G_PROJECT_ID */
9389 
9390 EXCEPTION
9391    WHEN Others THEN
9392       write_log(LOG,'Failed during mark_inv_var_paflag');
9393       G_err_code := SQLCODE;
9394       RAISE;
9395 
9396 END mark_inv_var_paflag;
9397 
9398 PROCEDURE transfer_inv_var_to_pa  IS
9399 
9400    v_num_invoices_fetched          NUMBER :=0;
9401    v_num_distributions_fetched     NUMBER :=0;
9402    v_prev_invoice_id               NUMBER := 0;
9403    v_old_stack                     VARCHAR2(630);
9404    v_err_message                   VARCHAR2(220);
9405    v_all_done                      NUMBER := 0;
9406    v_num_inv_variance_fetched      NUMBER :=0;
9407 
9408    v_status Number := 0;
9409    v_stage  Number :=0;
9410    v_business_group_id NUMBER := 0;
9411    v_attribute_category VARCHAR2(150);
9412    v_attribute1 VARCHAR2(150);
9413    v_attribute2 VARCHAR2(150);
9414    v_attribute3 VARCHAR2(150);
9415    v_attribute4 VARCHAR2(150);
9416    v_attribute5 VARCHAR2(150);
9417    v_attribute6 VARCHAR2(150);
9418    v_attribute7 VARCHAR2(150);
9419    v_attribute8 VARCHAR2(150);
9420    v_attribute9 VARCHAR2(150);
9421    v_attribute10 VARCHAR2(150);
9422    v_dff_map_status VARCHAR2(30);
9423    dff_map_exception EXCEPTION;
9424 
9425    v_last_inv_var_index         NUMBER := 0;
9426    v_max_size                   NUMBER := 0;
9427    l_prev_cr_ccid NUMBER;
9428    l_prev_dr_ccid NUMBER;
9429    l_prev_exp_item_id NUMBER:=0;
9430    l_create_adj_recs  VARCHAR2(1) := 'N';
9431 
9432 
9433    PROCEDURE clear_plsql_tables IS
9434 
9435        l_status1 VARCHAR2(30);
9436 
9437    BEGIN
9438 
9439        G_err_stage := 'within clear_plsql_tables of transfer_inv_var_to_pa';
9440        write_log(LOG, G_err_stage);
9441 
9442        l_invoice_id_tbl.delete;
9443        l_invoice_dist_id_tbl.delete;
9444        l_project_id_tbl.delete;
9445        l_task_id_tbl.delete;
9446        l_ln_type_lookup_tbl.delete;
9447        l_exp_type_tbl.delete;
9448        l_ei_date_tbl.delete;
9449        l_amount_tbl.delete;
9450        l_description_tbl.delete;
9451        l_dist_cc_id_tbl.delete;
9452        l_exp_org_id_tbl.delete;
9453        l_quantity_tbl.delete;
9454        l_gl_date_tbl.delete;
9455        l_attribute_cat_tbl.delete;
9456        l_attribute1_tbl.delete;
9457        l_attribute2_tbl.delete;
9458        l_attribute3_tbl.delete;
9459        l_attribute4_tbl.delete;
9460        l_attribute5_tbl.delete;
9461        l_attribute6_tbl.delete;
9462        l_attribute7_tbl.delete;
9463        l_attribute8_tbl.delete;
9464        l_attribute9_tbl.delete;
9465        l_attribute10_tbl.delete;
9466        l_denom_raw_cost_tbl.delete;
9467        l_denom_cur_code_tbl.delete;
9468        l_acct_rate_date_tbl.delete;
9469        l_acct_rate_type_tbl.delete;
9470        l_acct_exch_rate_tbl.delete;
9471        l_job_id_tbl.delete;
9472        l_employee_id_tbl.delete;
9473        l_vendor_id_tbl.delete;
9474        l_inv_type_code_tbl.delete;
9475        l_source_tbl.delete;
9476        l_org_id_tbl.delete;
9477        l_invoice_num_tbl.delete;
9478        l_cdl_sys_ref3_tbl.delete;
9479        l_cdl_sys_ref4_tbl.delete;
9480        l_txn_src_tbl.delete;
9481        l_user_txn_src_tbl.delete;
9482        l_batch_name_tbl.delete;
9483        l_interface_id_tbl.delete;
9484        l_exp_end_date_tbl.delete;
9485        l_txn_status_code_tbl.delete;
9486        l_txn_rej_code_tbl.delete;
9487        l_bus_grp_id_tbl.delete;
9488 --       l_insert_flag_tbl.delete;
9489        l_reversal_flag_tbl.delete; --NEW
9490        l_net_zero_flag_tbl.delete; --NEW
9491        l_sc_xfer_code_tbl.delete; --NEW
9492        l_cancel_flag_tbl.delete;  --NEW
9493        l_parent_rev_id_tbl.delete; --NEW
9494        l_adj_exp_item_id_tbl.delete; --NEW
9495        l_fc_enabled_tbl.delete;
9496        l_fc_document_type_tbl.delete;
9497        l_cbs_element_id_tbl.delete; -- Added for CBS Enhancement Bug 16220146
9498 
9499     END clear_plsql_tables;
9500 
9501     PROCEDURE bulk_insert_trx_intf IS
9502 
9503       l_status2 VARCHAR2(30);
9504 
9505     BEGIN
9506 
9507        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
9508 
9509        INSERT INTO pa_transaction_interface_all(
9510                      transaction_source
9511                     , user_transaction_source
9512                     , system_linkage
9513                     , batch_name
9514                     , expenditure_ending_date
9515                     , expenditure_item_date
9516                     , expenditure_type
9517                     , quantity
9518                     , raw_cost_rate
9519                     , expenditure_comment
9520                     , transaction_status_code
9521                     , transaction_rejection_code
9522                     , orig_transaction_reference
9523                     , interface_id
9524                     , dr_code_combination_id
9525                     , cr_code_combination_id
9526                     , cdl_system_reference1
9527                     , cdl_system_reference2
9528                     , cdl_system_reference3
9529                     , cdl_system_reference4
9530                     , cdl_system_reference5 --NEW
9531                     , gl_date
9532                     , org_id
9533                     , unmatched_negative_txn_flag
9534                     , receipt_currency_amount
9535                     , receipt_currency_code
9536                     , receipt_exchange_rate
9537                     , denom_raw_cost
9538                     , denom_currency_code
9539                     , acct_rate_date
9540                     , acct_rate_type
9541                     , acct_exchange_rate
9542                     , acct_raw_cost
9543                     , acct_exchange_rounding_limit
9544                     , attribute_category
9545                     , attribute1
9546                     , attribute2
9547                     , attribute3
9548                     , attribute4
9549                     , attribute5
9550                     , attribute6
9551                     , attribute7
9552                     , attribute8
9553                     , attribute9
9554                     , attribute10
9555                     , orig_exp_txn_reference1
9556                     , orig_user_exp_txn_reference
9557                     ,  orig_exp_txn_reference2
9558                     ,  orig_exp_txn_reference3
9559                     , last_update_date
9560                     , last_updated_by
9561                     , creation_date
9562                     , created_by
9563                     , person_id
9564                     , organization_id
9565                     , project_id
9566                     , task_id
9567                     , Vendor_id
9568                     , override_to_organization_id
9569                     , person_business_group_id
9570                     , adjusted_expenditure_item_id --NEW
9571                     , fc_document_type  -- NEW
9572                     , sc_xfer_code
9573                     , si_assets_addition_flag
9574                     , net_zero_adjustment_flag
9575                     , expenditure_item_id
9576                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
9577                    )
9578              SELECT l_txn_src_tbl(i)
9579                      ,l_user_txn_src_tbl(i)
9580                      ,G_SYSTEM_LINKAGE
9581                      ,l_batch_name_tbl(i)
9582                      ,l_exp_end_date_tbl(i)
9583                      ,l_ei_date_tbl(i)
9584                      ,l_exp_type_tbl(i)
9585                      ,l_quantity_tbl(i)
9586                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
9587                      ,l_description_tbl(i)
9588                      ,l_txn_status_code_tbl(i)
9589                      ,l_txn_rej_code_tbl(i)
9590                      ,G_REQUEST_ID
9591                      ,l_interface_id_tbl(i)
9592                      ,l_dist_cc_id_tbl(i)
9593                      ,NULL
9594                      ,l_vendor_id_tbl(i)
9595                      ,l_invoice_id_tbl(i)
9596                      ,l_cdl_sys_ref3_tbl(i)
9597                      ,l_cdl_sys_ref4_tbl(i)
9598                      ,l_invoice_dist_id_tbl(i) --NEW
9599                      ,l_gl_date_tbl(i)
9600                      ,G_ORG_ID
9601                      ,'Y'
9602                      ,NULL
9603                      ,NULL
9604                      ,NULL
9605                      ,l_denom_raw_cost_tbl(i)
9606                      ,l_denom_cur_code_tbl(i)
9607                      ,l_acct_rate_date_tbl(i)
9608                      ,l_acct_rate_type_tbl(i)
9609                      ,l_acct_exch_rate_tbl(i)
9610                      ,l_amount_tbl(i)
9611                      ,1
9612                      ,l_attribute_cat_tbl(i)
9613                      ,l_attribute1_tbl(i)
9614                      ,l_attribute2_tbl(i)
9615                      ,l_attribute3_tbl(i)
9616                      ,l_attribute4_tbl(i)
9617                      ,l_attribute5_tbl(i)
9618                      ,l_attribute6_tbl(i)
9619                      ,l_attribute7_tbl(i)
9620                      ,l_attribute8_tbl(i)
9621                      ,l_attribute9_tbl(i)
9622                      ,l_attribute10_tbl(i)
9623                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
9624                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
9625                      ,NULL                       /*orig_exp_txn_reference2*/
9626                      ,NULL                       /*orig_exp_txn_reference3*/
9627                      ,SYSDATE
9628                      ,-1
9629                      ,SYSDATE
9630                      ,-1
9631                      ,l_employee_id_tbl(i)
9632                      ,l_org_id_tbl(i)
9633                      ,l_project_id_tbl(i)
9634                      ,l_task_id_tbl(i)
9635                      ,l_vendor_id_tbl(i)
9636                      ,l_exp_org_id_tbl(i)
9637                      ,l_bus_grp_id_tbl(i)
9638                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
9639                      ,l_fc_document_type_tbl(i) --NEW for funds checking
9640                      ,l_sc_xfer_code_tbl(i)
9641                      ,l_si_assts_add_flg_tbl(i)
9642                      ,l_net_zero_flag_tbl(i)
9643                      ,0 -- To relieve the cmt. It will not be interfaced from xface in trx imp.
9644                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
9645                 FROM dual;
9646 
9647               -- Insert the reversal of the reversed/cancelled distribution recs from AP.
9648     IF l_create_adj_recs = 'Y' THEN
9649 
9650         If g_body_debug_mode = 'Y' Then
9651                 write_log(LOG, 'Inserting adjustment records..');
9652         End if;
9653 
9654                 FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
9655        INSERT INTO pa_transaction_interface_all(
9656                      transaction_source
9657                     , user_transaction_source
9658                     , system_linkage
9659                     , batch_name
9660                     , expenditure_ending_date
9661                     , expenditure_item_date
9662                     , expenditure_type
9663                     , quantity
9664                     , raw_cost_rate
9665                     , expenditure_comment
9666                     , transaction_status_code
9667                     , transaction_rejection_code
9668                     , orig_transaction_reference
9669                     , interface_id
9670                     , dr_code_combination_id
9671                     , cr_code_combination_id
9672                     , cdl_system_reference1
9673                     , cdl_system_reference2
9674                     , cdl_system_reference3
9675                     , cdl_system_reference4
9676                     , cdl_system_reference5 --NEW
9677                     , gl_date
9678                     , org_id
9679                     , unmatched_negative_txn_flag
9680                     , receipt_currency_amount
9681                     , receipt_currency_code
9682                     , receipt_exchange_rate
9683                     , denom_raw_cost
9684                     , denom_currency_code
9685                     , acct_rate_date
9686                     , acct_rate_type
9687                     , acct_exchange_rate
9688                     , acct_raw_cost
9689                     , acct_exchange_rounding_limit
9690                     , attribute_category
9691                     , attribute1
9692                     , attribute2
9693                     , attribute3
9694                     , attribute4
9695                     , attribute5
9696                     , attribute6
9697                     , attribute7
9698                     , attribute8
9699                     , attribute9
9700                     , attribute10
9701                     , orig_exp_txn_reference1
9702                     , orig_user_exp_txn_reference
9703                     ,  orig_exp_txn_reference2
9704                     ,  orig_exp_txn_reference3
9705                     , last_update_date
9706                     , last_updated_by
9707                     , creation_date
9708                     , created_by
9709                     , person_id
9710                     , organization_id
9711                     , project_id
9712                     , task_id
9713                     , Vendor_id
9714                     , override_to_organization_id
9715                     , person_business_group_id
9716                     , adjusted_expenditure_item_id --NEW
9717                     , fc_document_type  -- NEW
9718                     , adjusted_txn_interface_id --NEW
9719                     , sc_xfer_code
9720                     , si_assets_addition_flag
9721                     , net_zero_adjustment_flag
9722                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
9723                    )
9724              SELECT l_txn_src_tbl(i)
9725                      ,l_user_txn_src_tbl(i)
9726                      ,G_SYSTEM_LINKAGE
9727                      ,l_batch_name_tbl(i)
9728                      ,l_exp_end_date_tbl(i)
9729                      ,l_ei_date_tbl(i)
9730                      ,l_exp_type_tbl(i)
9731                      ,-l_quantity_tbl(i)
9732                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
9733                      ,l_description_tbl(i)
9734                      ,l_txn_status_code_tbl(i)
9735                      ,l_txn_rej_code_tbl(i)
9736                      ,G_REQUEST_ID
9737                      ,l_interface_id_tbl(i)
9738                      ,l_dist_cc_id_tbl(i)
9739                      ,NULL
9740                      ,l_vendor_id_tbl(i)
9741                      ,l_invoice_id_tbl(i)
9742                      ,l_cdl_sys_ref3_tbl(i)
9743                      ,l_cdl_sys_ref4_tbl(i)
9744                      ,l_invoice_dist_id_tbl(i) --NEW
9745                      ,l_gl_date_tbl(i)
9746                      ,G_ORG_ID
9747                      ,'Y'
9748                      ,NULL
9749                      ,NULL
9750                      ,NULL
9751                      ,-l_denom_raw_cost_tbl(i)
9752                      ,l_denom_cur_code_tbl(i)
9753                      ,l_acct_rate_date_tbl(i)
9754                      ,l_acct_rate_type_tbl(i)
9755                      ,l_acct_exch_rate_tbl(i)
9756                      ,-l_amount_tbl(i)
9757                      ,1
9758                      ,l_attribute_cat_tbl(i)
9759                      ,l_attribute1_tbl(i)
9760                      ,l_attribute2_tbl(i)
9761                      ,l_attribute3_tbl(i)
9762                      ,l_attribute4_tbl(i)
9763                      ,l_attribute5_tbl(i)
9764                      ,l_attribute6_tbl(i)
9765                      ,l_attribute7_tbl(i)
9766                      ,l_attribute8_tbl(i)
9767                      ,l_attribute9_tbl(i)
9768                      ,l_attribute10_tbl(i)
9769                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
9770                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
9771                      ,NULL                       /*orig_exp_txn_reference2*/
9772                      ,NULL                       /*orig_exp_txn_reference3*/
9773                      ,SYSDATE
9774                      ,-1
9775                      ,SYSDATE
9776                      ,-1
9777                      ,l_employee_id_tbl(i)
9778                      ,l_org_id_tbl(i)
9779                      ,l_project_id_tbl(i)
9780                      ,l_task_id_tbl(i)
9781                      ,l_vendor_id_tbl(i)
9782                      ,l_exp_org_id_tbl(i)
9783                      ,l_bus_grp_id_tbl(i)
9784                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
9785                      ,l_fc_document_type_tbl(i) --NEW for funds checking
9786                      ,(select xface.txn_interface_id
9787                        from   pa_transaction_interface xface
9788                        where  xface.interface_id = l_interface_id_tbl(i)
9789                        and    xface.cdl_system_reference2 = l_invoice_id_tbl(i)
9790                        and    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(i)
9791 		       and    NVL(xface.adjusted_expenditure_item_id,0) =0 ) -- R12 funds management Uptake
9792                      ,'P' -- sc_xfer_code
9793                      ,l_si_assts_add_flg_tbl(i)
9794                      ,l_net_zero_flag_tbl(i)
9795                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
9796                 FROM dual
9797                 WHERE l_insert_flag_tbl(i)= 'A';
9798                 --WHERE l_net_zero_flag_tbl(i)= 'Y';
9799       END IF;
9800 
9801    EXCEPTION
9802       WHEN Others THEN
9803          write_log(LOG,'Failed during bulk insert of inv var processing');
9804          G_err_code := SQLCODE;
9805          RAISE;
9806 
9807    END bulk_insert_trx_intf;
9808 
9809    PROCEDURE process_inv_var_logic IS
9810 
9811        j   NUMBER := 0;
9812        l_status3 VARCHAR2(30);
9813        l_historical_flag VARCHAR(1);  --NEW
9814 	   -- Start: Added for CBS Enhancement Bug 16220146
9815 	   l_actual_task_id       NUMBER := 0;
9816 	   l_cbs_element_id       NUMBER := 0;
9817 	   -- End: Added for CBS Enhancement Bug 16220146
9818 
9819    BEGIN
9820 
9821        G_err_stage := ('Within Calling process logic of transfer_inv_var_to_pa');
9822        write_log(LOG, G_err_stage);
9823 
9824        j := v_last_inv_var_index ;
9825        FOR i IN  l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST  LOOP
9826 
9827            write_log(LOG,'Processing Invoice Variance for invoice id:  '||l_invoice_id_tbl(i)||
9828                          'Invoice Dist Id :  '||l_invoice_dist_id_tbl(i));
9829 
9830            G_TRANSACTION_REJECTION_CODE := '';
9831 
9832 		   -- Start: Added for CBS Enhancement Bug 16220146
9833 		   IF l_project_id_tbl(i) is not null and l_task_id_tbl(i) IS NOT NULL THEN
9834 
9835 			  IF PA_ALTERNATE_TASK_PVT.Is_Cbs_Enabled(l_project_id_tbl(i)) = 'Y' THEN
9836 
9837 			     BEGIN
9838 
9839 				    SELECT PROJ_ELEMENT_ID, CBS_ELEMENT_ID
9840 					INTO l_actual_task_id, l_cbs_element_id
9841 					FROM PA_ALTERNATE_TASKS
9842 					WHERE alt_task_id = l_task_id_tbl(i);
9843 
9844 				EXCEPTION
9845 				   WHEN OTHERS THEN
9846 				      l_cbs_element_id_tbl(i) := NULL;
9847 				      RAISE;
9848 				END;
9849 
9850 				l_task_id_tbl(i) := l_actual_task_id;
9851 				l_cbs_element_id_tbl(i) := l_cbs_element_id;
9852 			  ELSE
9853 			     l_cbs_element_id_tbl(i) := NULL;
9854 			  END IF;
9855 		   ELSE
9856 		      l_cbs_element_id_tbl(i) := NULL;
9857 		   END IF;
9858 		   -- End: Added for CBS Enhancement Bug 16220146
9859 
9860            /* The following will be executed if the distribution being fetched belongs to a new invoice */
9861            IF (l_invoice_id_tbl(i) <> v_prev_invoice_id) THEN
9862 
9863                G_err_stage := ('New invoice being processed.New invoice _id is:'||l_invoice_id_tbl(i));
9864                write_log(LOG, G_err_stage);
9865 
9866                /* Update the previous invoice id and vendor id*/
9867                v_prev_invoice_id := l_invoice_id_tbl(i);
9868 
9869                /* Increment the counter for invoices */
9870                v_num_invoices_fetched := v_num_invoices_fetched + 1;
9871 
9872                 /* For new invoice, initialize the transaction status code to 'P' */
9873                 G_TRANSACTION_STATUS_CODE := 'P';
9874 
9875                 G_err_stage := 'GET MAX EXPENDITURE ENDING DATE';
9876                 write_log(LOG, G_err_stage);
9877                 SELECT pa_utils.getweekending(MAX(expenditure_item_date))
9878                   INTO G_EXPENDITURE_ENDING_DATE
9879                   FROM ap_invoice_distributions
9880                  WHERE invoice_id = l_invoice_id_tbl(i);
9881 
9882               If g_body_debug_mode = 'Y' Then
9883                 G_err_stage := ('Getting bus group id');
9884                 write_log(LOG, G_err_stage);
9885               End If;
9886 
9887                 BEGIN
9888 
9889 
9890                     IF l_employee_id_tbl(i) <> 0 THEN
9891 			Begin
9892 			       SELECT emp.business_group_id
9893                                  INTO G_PER_BUS_GRP_ID
9894 				 FROM per_all_people_f emp
9895 				WHERE emp.person_id = l_employee_id_tbl(i)
9896 				  AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and
9897 							       trunc(emp.effective_end_date);
9898 
9899 			EXCEPTION
9900 			   WHEN NO_DATA_FOUND THEN
9901 			      l_txn_status_code_tbl(i) := 'R';
9902 			      G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
9903 			      write_log(LOG, 'As no data found for Employee, Rejecting invoice'||l_invoice_id_tbl(i)  );
9904 		        End;
9905 		    Else
9906 			Begin
9907 
9908 			    select org2.business_group_id
9909                             into G_PER_BUS_GRP_ID
9910 			      from hr_organization_units org1,
9911 				   hr_organization_units org2
9912 			     Where org1.organization_id = l_exp_org_id_tbl(i)
9913 			       and org1.business_group_id = org2.organization_id;
9914 
9915 			EXCEPTION
9916 				WHEN NO_DATA_FOUND THEN
9917 				      G_TRANSACTION_STATUS_CODE := 'R';
9918 				      G_TRANSACTION_REJECTION_CODE := 'INVALID_ORGANIZATION';
9919 				      write_log(LOG, 'As no data found for Organization, Rejecting discount invoice ' || l_invoice_id_tbl(i) );
9920 			End;
9921                     END IF; /* IF l_employee_id_tbl(i) <> 0 THEN  */
9922                 END;
9923 
9924            END IF; /* end of check for different invoice_id from previous invoice_id */
9925 
9926            v_num_inv_variance_fetched  := v_num_inv_variance_fetched  + 1;
9927            v_num_distributions_fetched := v_num_distributions_fetched + 1;
9928            write_log(LOG,'Num of distributions fetched:'||v_num_distributions_fetched);
9929 
9930                --l_insert_flag_tbl(i)     := 'Y';
9931 
9932 
9933         If g_body_debug_mode = 'Y' Then
9934            write_log(LOG,'This is a record type of Amount Variance : ' ||
9935                      'denom cost is:  '||l_denom_raw_cost_tbl(i));
9936         End If;
9937 
9938            /*Setting values according to global variables*/
9939            l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
9940            l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
9941            l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
9942            l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
9943 
9944            l_txn_src_tbl(i)         := G_AP_VAR_TRANSACTION_SOURCE;
9945            l_user_txn_src_tbl(i)    := G_AP_VAR_USER_TXN_SOURCE;
9946            l_batch_name_tbl(i)      := G_AP_VAR_BATCH_NAME;
9947            l_interface_id_tbl(i)    := G_AP_VAR_INTERFACE_ID;
9948 
9949            -- FC Doc Type
9950             IF l_fc_enabled_tbl(i) = 'N' THEN
9951              l_fc_document_type_tbl(i) := 'NOT';
9952             END IF;
9953 
9954            -- REVERSED DISTRIBUTIONS INTERFACE LOGIC
9955            -- If the distribution is a reversal or cancellation then check if the parent reversal distribution
9956            -- was historical data or not. If so, reversal distribution line will be interfaced as is.
9957            -- However if the parent reversal distribution is not historical then the following steps happen:
9958            -- a) Retreive the latest adjusted expenditures from PA against the parent reversal distribution id
9959            -- b) If any of the above latest EI's are not costed, then the reversed distribution will be rejected by the
9960            --    TRX import program
9961            -- c) IF all above adjusted EI's are costed, then insert record into the interface table for each adjusted EI.
9962            --    The project attributes will be copied from the adjusted EI's instead from the AP reversed
9963            --    distribution since these could have changed in PA.
9964            -- d) The interface program will interface the reversed distribution into projects
9965            -- e) The interface program will also insert a reversal of the reversed distribution into Projects. This is
9966            --    required for account reconciliation
9967            --
9968 
9969            IF (l_reversal_flag_tbl(i) = 'Y' or l_cancel_flag_tbl(i) = 'Y') and l_parent_rev_id_tbl(i) is not null THEN
9970 
9971                 BEGIN
9972 
9973                 SELECT nvl(historical_flag,'N') --check if this flag can be used
9974                 INTO   l_historical_flag
9975                 FROM   ap_invoice_distributions_all
9976                 WHERE  invoice_id = l_invoice_id_tbl(i)
9977                 AND    invoice_distribution_id = l_parent_rev_id_tbl(i); --check the index on this table
9978 
9979                 EXCEPTION
9980                 WHEN NO_DATA_FOUND THEN
9981                    l_txn_status_code_tbl(i) := 'R';
9982                    G_TRANSACTION_REJECTION_CODE := 'INVALID_INVOICE'; --?????????
9983                    write_log(LOG, 'As no data found for reversed parent distribution, Rejecting invoice dist Id'||l_invoice_dist_id_tbl(i));
9984                 END;
9985 
9986 
9987                 IF l_historical_flag = 'N' THEN
9988 
9989                      -- Call reversal API
9990                      Process_Adjustments(p_record_type               => 'AP_INVOICE',
9991                                          p_document_header_id  => l_invoice_id_tbl(i),/*Added this for 6945767 */
9992                                          p_document_distribution_id  => l_parent_rev_id_tbl(i),
9993                                          p_current_index             => i,
9994 				         p_last_index                => j);
9995 
9996                       -- Set the create flag for adjustment records
9997                          IF l_insert_flag_tbl(i) in ('A','U') THEN
9998                           l_create_adj_recs := 'Y';
9999                          END IF;
10000 
10001                 END IF; --End of check for historical Flag
10002 
10003            END IF; --End of check for reversal Distribution
10004 
10005 
10006 
10007       END LOOP; /* End of looping through each record in plsql table */
10008 
10009    EXCEPTION
10010       WHEN Others THEN
10011          write_log(LOG,'Failed during process_inv_var_logic of inv amt var processing');
10012          G_err_code := SQLCODE;
10013          RAISE;
10014 
10015    END process_inv_var_logic;
10016 
10017    BEGIN
10018    /* Main Procedure Logic starts here */
10019 
10020    G_err_stage := 'Within main procedure of transfer_inv_var_to_pa';
10021    write_log(LOG, G_err_stage);
10022 
10023      v_max_size := nvl(G_COMMIT_SIZE,200);
10024 
10025      G_AP_VAR_TRANSACTION_SOURCE  := 'AP VARIANCE';
10026      G_AP_VAR_USER_TXN_SOURCE     := 'Oracle Payables Invoice Variance';
10027 
10028      OPEN Invoice_Variance_Cur;
10029 
10030      G_err_stage := 'After opening Invoice_Variance_Cur within transfer_inv_var_to_pa';
10031      write_log(LOG, G_err_stage);
10032 
10033      WHILE (v_all_done = 0) LOOP
10034 
10035        clear_plsql_tables;
10036 
10037        --Creating new interface ID every time this is called
10038        G_err_stage := 'CREATING NEW INTERFACE ID';
10039        write_log(LOG, G_err_stage);
10040 
10041        SELECT pa_interface_id_s.nextval
10042          INTO G_AP_VAR_INTERFACE_ID
10043          FROM dual;
10044 
10045           FETCH Invoice_Variance_Cur BULK COLLECT INTO
10046              l_invoice_id_tbl
10047             ,l_invoice_dist_id_tbl --NEW
10048             ,l_cdl_sys_ref3_tbl --Invoice_lie_num
10049             ,l_project_id_tbl
10050             ,l_task_id_tbl
10051             ,l_ln_type_lookup_tbl
10052             ,l_exp_type_tbl
10053             ,l_ei_date_tbl
10054             ,l_amount_tbl
10055             ,l_description_tbl
10056             ,l_dist_cc_id_tbl
10057             ,l_exp_org_id_tbl
10058             ,l_quantity_tbl
10059             ,l_gl_date_tbl
10060             ,l_attribute_cat_tbl
10061             ,l_attribute1_tbl
10062             ,l_attribute2_tbl
10063             ,l_attribute3_tbl
10064             ,l_attribute4_tbl
10065             ,l_attribute5_tbl
10066             ,l_attribute6_tbl
10067             ,l_attribute7_tbl
10068             ,l_attribute8_tbl
10069             ,l_attribute9_tbl
10070             ,l_attribute10_tbl
10071             ,l_denom_raw_cost_tbl
10072             ,l_denom_cur_code_tbl
10073             ,l_acct_rate_date_tbl
10074             ,l_acct_rate_type_tbl
10075             ,l_acct_exch_rate_tbl
10076             ,l_job_id_tbl
10077             ,l_employee_id_tbl
10078             ,l_vendor_id_tbl
10079             ,l_inv_type_code_tbl
10080             ,l_source_tbl
10081             ,l_org_id_tbl
10082             ,l_invoice_num_tbl
10083             ,l_cdl_sys_ref4_tbl
10084             ,l_txn_src_tbl
10085             ,l_user_txn_src_tbl
10086             ,l_batch_name_tbl
10087             ,l_interface_id_tbl
10088             ,l_exp_end_date_tbl
10089             ,l_txn_status_code_tbl
10090             ,l_txn_rej_code_tbl
10091             ,l_bus_grp_id_tbl
10092             ,l_reversal_flag_tbl
10093             ,l_cancel_flag_tbl
10094             ,l_parent_rev_id_tbl
10095             ,l_net_zero_flag_tbl
10096             ,l_sc_xfer_code_tbl
10097             ,l_adj_exp_item_id_tbl
10098             ,l_fc_enabled_tbl
10099             ,l_mrc_exchange_date_tbl
10100             ,l_fc_document_type_tbl
10101             ,l_si_assts_add_flg_tbl
10102             ,l_insert_flag_tbl
10103             LIMIT v_max_size;
10104 
10105          G_err_stage := 'After fetching Cursor within transfer_inv_var_to_pa';
10106          write_log(LOG, G_err_stage);
10107 
10108          IF l_invoice_id_tbl.COUNT <> 0 THEN
10109 
10110             v_last_inv_var_index := l_invoice_id_tbl.LAST ;
10111 
10112             G_err_stage := 'calling process_inv_logic within transfer_inv_var_to_pa';
10113             write_log(LOG, G_err_stage);
10114 
10115             process_inv_var_logic;
10116 
10117             G_err_stage := 'calling bulk_insert_trx_intf within transfer_inv_var_to_pa';
10118             write_log(LOG, G_err_stage);
10119 
10120             bulk_insert_trx_intf;
10121 
10122            G_err_stage := 'Before calling transaction import and tiebacks within transfer_inv_var_to_pa';
10123            write_log(LOG, G_err_stage);
10124 
10125 
10126            IF (v_num_inv_variance_fetched > 0) THEN
10127 
10128               G_err_stage := 'Before calling transaction import and tiebacks within transfer_inv_var_to_pa';
10129               write_log(LOG, G_err_stage);
10130 
10131               trans_import(G_AP_VAR_TRANSACTION_SOURCE,G_AP_VAR_BATCH_NAME,
10132                            G_AP_VAR_INTERFACE_ID,G_USER_ID);
10133               tieback_invoice_variances(G_AP_VAR_TRANSACTION_SOURCE,G_AP_VAR_BATCH_NAME,
10134                            G_AP_VAR_INTERFACE_ID);
10135 
10136               G_err_stage := 'Before updating the total number of invoices processed';
10137               write_log(LOG, G_err_stage);
10138 
10139               G_NUM_BATCHES_PROCESSED       := G_NUM_BATCHES_PROCESSED + 1;
10140               G_NUM_INVOICES_PROCESSED      :=  G_NUM_INVOICES_PROCESSED + v_num_invoices_fetched;
10141               G_NUM_DISTRIBUTIONS_PROCESSED :=  G_NUM_DISTRIBUTIONS_PROCESSED + v_num_distributions_fetched;
10142               G_NUM_AP_VARIANCE_PROCESSED   := G_NUM_AP_VARIANCE_PROCESSED + v_num_inv_variance_fetched;
10143 
10144         END IF; /* IF (v_num_distributions_fetched > 0) */
10145 
10146         G_err_stage := 'After calling transaction import and tiebacks within transfer_inv_var_to_pa';
10147         write_log(LOG, G_err_stage);
10148 
10149         clear_plsql_tables;
10150 
10151         v_num_invoices_fetched       :=0;
10152         v_num_distributions_fetched  :=0;
10153         v_num_inv_variance_fetched   :=0;
10154 
10155         G_err_stage:='Before exiting when Invoice_Variance_Cur is NOTFOUND';
10156         write_log(LOG,   G_err_stage);
10157 
10158       ELSE
10159           EXIT;
10160       END IF; /* l_invoice_id_tbl.COUNT = 0 */
10161 
10162       EXIT WHEN Invoice_Variance_Cur%NOTFOUND;
10163 
10164    END LOOP; /* While more rows to process is true */
10165 
10166    CLOSE Invoice_Variance_Cur;
10167 
10168 EXCEPTION
10169     WHEN OTHERS THEN
10170 
10171          G_err_stack := v_old_stack;
10172          IF Invoice_Variance_Cur%ISOPEN THEN
10173            CLOSE Invoice_Cur;
10174          END IF ;
10175 
10176          G_err_code := SQLCODE;
10177          RAISE;
10178 
10179 END transfer_inv_var_to_pa;
10180 
10181 PROCEDURE tieback_invoice_variances (
10182    p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
10183    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
10184    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
10185 
10186    l_assets_addflag          VARCHAR2(1):=NULL;
10187    l_prev_assets_addflag     VARCHAR2(1):=NULL;
10188    l_project_id             NUMBER :=0;
10189    l_pa_addflag             VARCHAR2(1):=NULL;
10190    l_prev_proj_id           NUMBER :=0;
10191 
10192    l_sys_ref1_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
10193    l_sys_ref2_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
10194    l_sys_ref5_tbl           PA_PLSQL_DATATYPES.IdTabTyp;    --confirm if this is number type in interface table
10195    l_txn_src_tbl            PA_PLSQL_DATATYPES.Char30TabTyp;
10196    l_batch_name_tbl         PA_PLSQL_DATATYPES.Char50TabTyp;
10197    l_interface_id_tbl       PA_PLSQL_DATATYPES.IdTabTyp;
10198    l_txn_status_code_tbl    PA_PLSQL_DATATYPES.Char2TabTyp;
10199    l_project_id_tbl            PA_PLSQL_DATATYPES.IdTabTyp;
10200    l_pa_addflag_tbl         PA_PLSQL_DATATYPES.CHAR1TabTyp;
10201    l_assets_addflag_tbl     PA_PLSQL_DATATYPES.CHAR1TabTyp;
10202    l_exp_item_id_tbl        PA_PLSQL_DATATYPES.IdTabTyp; /* Bug 8709614  */
10203 
10204    CURSOR txn_intf_rec (p_txn_src       IN VARCHAR2,
10205                         p_batch_name    IN VARCHAR2,
10206                         p_interface_id  IN NUMBER) IS
10207       SELECT cdl_system_reference1
10208             ,cdl_system_reference2
10209             ,cdl_system_reference5
10210             ,transaction_source
10211             ,batch_name
10212             ,interface_id
10213             ,transaction_status_code
10214             ,project_id
10215             ,l_pa_addflag
10216             ,l_assets_addflag
10217 	    ,expenditure_item_id /* Bug 8709614  */
10218         FROM pa_transaction_interface_all txnintf
10219        WHERE txnintf.transaction_source = p_txn_src
10220          AND txnintf.batch_name         = p_batch_name
10221          AND txnintf.interface_id       = p_interface_id;
10222 
10223    PROCEDURE clear_plsql_tables IS
10224 
10225       v_status   VARCHAR2(15);
10226 
10227    BEGIN
10228 
10229       G_err_stage:='Clearing PLSQL tables in invoice variance tieback';
10230       write_log(LOG,   G_err_stage);
10231 
10232       l_sys_ref1_tbl.delete;
10233       l_sys_ref2_tbl.delete;
10234       l_sys_ref5_tbl.delete;
10235       l_txn_src_tbl.delete;
10236       l_batch_name_tbl.delete;
10237       l_interface_id_tbl.delete;
10238       l_txn_status_code_tbl.delete;
10239       l_project_id_tbl.delete;
10240       l_pa_addflag_tbl.delete;
10241       l_assets_addflag_tbl.delete;
10242       l_exp_item_id_tbl.delete; /* Bug 8709614  */
10243 
10244    END clear_plsql_tables;
10245 
10246    PROCEDURE process_tieback IS
10247 
10248       v_status   VARCHAR2(15);
10249 
10250    BEGIN
10251 
10252       G_err_stage:='Within process_tieback of invoice variance tieback';
10253       write_log(LOG,   G_err_stage);
10254 
10255       FOR i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST LOOP
10256 
10257          /* If transaction import stamps the record to be 'A' then
10258             update pa_addition_flag of invoice distribution to 'F'.
10259             If transaction import leaves the record to be 'P' then
10260             update pa_addition_flag of invoice distribution to 'N'.
10261             If transaction import stamps the record to be 'R' then
10262             update pa_addition_flag of invoice distribution to 'N'.*/
10263 
10264          write_log(LOG,'Tying invoice_id: '||l_sys_ref2_tbl(i)||
10265                        -- 'dist num:  '||l_sys_ref3_tbl(i)||
10266                        -- 'sys ref 4: '||l_sys_ref4_tbl(i)||
10267                        'trc src:   '||l_txn_src_tbl(i));
10268 
10269          IF (l_txn_status_code_tbl(i) = 'A' OR l_exp_item_id_tbl(i) = 0) THEN /* Modified for bug 8709614  */
10270                l_pa_addflag_tbl(i) := 'F';
10271          ELSIF l_txn_status_code_tbl(i) = 'P' THEN
10272                l_pa_addflag_tbl(i) :='N';
10273          ELSIF l_txn_status_code_tbl(i) = 'R' THEN
10274                l_pa_addflag_tbl(i) := 'N';
10275          END IF;
10276 
10277 
10278          IF G_PROJECT_ID IS NOT NULL THEN
10279 
10280             IF G_Assets_Addition_flag = 'P' THEN
10281                l_assets_addflag_tbl(i) := 'P';
10282             ELSE
10283                l_assets_addflag_tbl(i) := 'X';
10284             END IF;
10285 
10286          ELSIF G_PROJECT_ID IS NULL THEN
10287 
10288             IF l_project_id_tbl(i) <> l_prev_proj_id THEN
10289 
10290                G_err_stage:='Selecting assets addition flag within invoice variance tieback';
10291                write_log(LOG,   G_err_stage);
10292 
10293                SELECT decode(PTYPE.Project_Type_Class_Code,'CAPITAL','P','X')
10294                  INTO l_assets_addflag_tbl(i)
10295                  FROM pa_project_types_all PTYPE,
10296                       pa_projects_all PROJ
10297                 WHERE PTYPE.Project_Type = PROJ.Project_Type
10298                   AND (PTYPE.org_id = PROJ.org_id OR
10299                        PROJ.org_id is null)
10300                   AND PROJ.Project_Id = l_project_id_tbl(i);
10301 
10302                 l_prev_proj_id := l_project_id_tbl(i);
10303 		l_prev_assets_addflag := l_assets_addflag_tbl(i);      /* Bug 3626038 */
10304 
10305             ELSE
10306                l_assets_addflag_tbl(i) := l_prev_assets_addflag;
10307             END IF;
10308 
10309          END IF;
10310 
10311       END LOOP;
10312 
10313    EXCEPTION
10314       WHEN OTHERS THEN
10315          G_err_stage:= 'Failed during process tieback of invoice variance tieback';
10316          write_log(LOG,   G_err_stage);
10317          G_err_code   := SQLCODE;
10318          raise;
10319 
10320    END process_tieback;
10321 
10322    PROCEDURE bulk_update_txn_intf IS
10323 
10324       v_status VARCHAR2(15);
10325 
10326    BEGIN
10327 
10328       G_err_stage:=('Within bulk update of invoice variance  tieback');
10329       write_log(LOG,   G_err_stage);
10330 
10331       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
10332 
10333          UPDATE ap_invoice_distributions_all dist
10334             SET dist.pa_addition_flag         = l_pa_addflag_tbl(i)
10335                ,dist.assets_addition_flag     = decode(l_assets_addflag_tbl(i),'P','P',dist.assets_addition_flag)
10336           WHERE dist.invoice_id               = l_sys_ref2_tbl(i)
10337             AND dist.invoice_distribution_id  = l_sys_ref5_tbl(i)
10338             AND dist.pa_addition_flag         = 'W';
10339 
10340    EXCEPTION
10341       WHEN OTHERS THEN
10342          G_err_stage:= 'Failed during bulk update of invoice variance tieback';
10343          write_log(LOG,   G_err_stage);
10344          G_err_code   := SQLCODE;
10345          raise;
10346 
10347    END bulk_update_txn_intf;
10348 
10349    BEGIN
10350 
10351       /* Main logic of tieback starts here */
10352       G_err_stage:='Within main logic of invoice variance tieback';
10353       write_log(LOG,   G_err_stage);
10354 
10355       clear_plsql_tables;
10356 
10357       G_err_stage:='Opening txn_intf_rec';
10358       write_log(LOG,   G_err_stage);
10359 
10360       OPEN txn_intf_rec(p_transaction_source
10361                        ,p_batch_name
10362                        ,p_interface_id);
10363 
10364       G_err_stage:='Fetching txn_intf_rec';
10365       write_log(LOG,   G_err_stage);
10366 
10367       FETCH txn_intf_rec BULK COLLECT INTO
10368           l_sys_ref1_tbl
10369          ,l_sys_ref2_tbl
10370          ,l_sys_ref5_tbl
10371          ,l_txn_src_tbl
10372          ,l_batch_name_tbl
10373          ,l_interface_id_tbl
10374          ,l_txn_status_code_tbl
10375          ,l_project_id_tbl
10376          ,l_pa_addflag_tbl
10377          ,l_assets_addflag_tbl
10378 	 ,l_exp_item_id_tbl; /* Bug 8709614  */
10379 
10380       IF l_sys_ref1_tbl.COUNT <> 0 THEN
10381 
10382          process_tieback;
10383 
10384          bulk_update_txn_intf;
10385 
10386          clear_plsql_tables;
10387 
10388       END IF;
10389 
10390       CLOSE txn_intf_rec;
10391 
10392 EXCEPTION
10393    WHEN OTHERS THEN
10394 
10395       IF txn_intf_rec%ISOPEN THEN
10396          CLOSE txn_intf_rec;
10397       END IF;
10398 
10399       G_err_stage:='Failed during tieback of invoice variances';
10400       write_log(LOG,   G_err_stage);
10401 
10402       G_err_code := SQLCODE;
10403       RAISE;
10404 
10405 END tieback_invoice_variances;
10406 
10407 
10408 PROCEDURE net_zero_pay_adjustment IS
10409 
10410    v_old_stack       	VARCHAR2(630);
10411    l_assets_add_flag 	VARCHAR2(1);
10412    l_num_dists_updated	NUMBER;
10413 
10414 BEGIN
10415 
10416      v_old_stack := G_err_stack;
10417      G_err_stack := G_err_stack || '->PAAPIMP_PKG.net_zero_pay_adjustment';
10418      G_err_code := 0;
10419      G_err_stage := 'Updating the payments to Z if they sum up to zero';
10420 
10421      write_log(LOG, G_err_stage);
10422      write_log(LOG, G_err_stack);
10423 
10424      IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
10425 
10426          -- Marking the expense reports to 'Z' if summing up to zero
10427 
10428          IF G_PROJECT_ID IS NOT NULL THEN
10429 
10430             -- This update is to mark the pa addition flag of all invoice distributions
10431             -- which have encumbered flag of 'R' or reversal flag of 'Y' to 'Z'.
10432             -- Encumbrance flag of 'R' or reversal flag of 'Y' indicates that they are
10433             -- exact reversal of another invoice distribution.
10434             -- If the invoice distribution has a encumbered flag value of 'R' then it is
10435             -- not encumbered and there exist no Budgetery control commitment records
10436             -- for these in PA
10437 
10438             UPDATE ap_payment_hist_dists dist
10439                 SET dist.pa_addition_flag = 'Z',
10440                     request_id = G_REQUEST_ID,
10441                     last_update_date=SYSDATE,
10442                     last_updated_by= G_USER_ID,
10443                     last_update_login= G_USER_ID,
10444                     program_id= G_PROG_ID,
10445                     program_application_id= G_PROG_APPL_ID,
10446                     program_update_date=SYSDATE
10447             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
10448                AND EXISTS (SELECT NULL
10449                            FROM   ap_payment_history_all hist
10450                            WHERE  hist.payment_history_id = dist.payment_history_id
10451                            AND    hist.posted_flag = 'Y')
10452                AND EXISTS (SELECT invoice_id
10453                              FROM AP_invoice_distributions aid
10454                             WHERE aid.invoice_distribution_id  = dist.invoice_distribution_id
10455                               AND aid.project_id = G_PROJECT_ID
10456                               AND ( nvl(aid.encumbered_flag,'N') = 'R' )
10457 			    ) ;
10458 
10459             write_log(LOG, 'Number of distributions marked for encumbered net zero adjustment: ' || to_char(SQL%ROWCOUNT));
10460 
10461             ELSE   /* Project Id is not passed */
10462 
10463             -- This update is to mark the pa addition flag of all invoice distributions
10464             -- which have encumbered flag of 'R' or reversal flag of 'Y' to 'Z'.
10465             -- Encumbrance flag of 'R' or reversal flag of 'Y' indicates that they are
10466             -- exact reversal of another invoice distribution.
10467             -- If the invoice distribution has a encumbered flag value of 'R' then it is
10468             -- not encumbered and there exist no Budgetery control commitment records
10469             -- for these in PA
10470 
10471 
10472             UPDATE ap_payment_hist_dists dist
10473                 SET dist.pa_addition_flag = 'Z',
10474                     request_id = G_REQUEST_ID,
10475                     last_update_date=SYSDATE,
10476                     last_updated_by= G_USER_ID,
10477                     last_update_login= G_USER_ID,
10478                     program_id= G_PROG_ID,
10479                     program_application_id= G_PROG_APPL_ID,
10480                     program_update_date=SYSDATE
10481             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
10482                AND EXISTS (SELECT NULL
10483                            FROM   ap_payment_history_all hist
10484                            WHERE  hist.payment_history_id = dist.payment_history_id
10485                            AND    hist.posted_flag = 'Y')
10486                AND EXISTS (SELECT aid.invoice_id
10487                              FROM AP_invoice_distributions aid
10488                             WHERE aid.invoice_distribution_id  = dist.invoice_distribution_id
10489                               AND aid.project_id > 0
10490                               AND  nvl(aid.encumbered_flag,'N') = 'R'
10491 			     ) ;
10492 
10493             write_log(LOG, 'Number of distributions marked for encumbered net zero adjustment: ' || to_char(SQL%ROWCOUNT));
10494 
10495       END IF;
10496       --
10497       -- End of If section checking if G_PROJECT_ID is not null
10498       --
10499 
10500     ELSE
10501 
10502        -- Process Invoices
10503 
10504       IF G_PROJECT_ID IS NOT NULL THEN
10505 
10506         -- The program should update the pa_addition_flag for all encumbered lines marked as R to netzero adj flag.
10507         -- R indicates a line to be ignored by encumbrance and validation code because neither the original nor the
10508         -- reversal distributions were looked at and they offset each other so, they can be ignored and marked as Z.
10509         -- (This is set only if the parent one is not validated as well. Otherwise the reversal one will also be encumbered).
10510         -- Since these lines have been not encumbered, there exist no Budgetery control commitment records for these in PA
10511 
10512             UPDATE ap_payment_hist_dists dist
10513                 SET dist.pa_addition_flag = 'Z',
10514                     request_id = G_REQUEST_ID,
10515                     last_update_date=SYSDATE,
10516                     last_updated_by= G_USER_ID,
10517                     last_update_login= G_USER_ID,
10518                     program_id= G_PROG_ID,
10519                     program_application_id= G_PROG_APPL_ID,
10520                     program_update_date=SYSDATE
10521             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
10522                AND EXISTS (SELECT NULL
10523                            FROM   ap_payment_history_all hist
10524                            WHERE  hist.payment_history_id = dist.payment_history_id
10525                            AND    hist.posted_flag = 'Y')
10526                AND EXISTS (SELECT aid.invoice_id
10527                              FROM AP_invoice_distributions aid
10528                             WHERE aid.invoice_distribution_id  = dist.invoice_distribution_id
10529                               AND aid.project_id = G_PROJECT_ID
10530                               AND ( nvl(aid.encumbered_flag,'N') = 'R' )
10531 			     ) ;
10532 
10533             write_log(LOG, 'Number of distributions marked for encumbered net zero adjustment: ' || to_char(SQL%ROWCOUNT));
10534 
10535      ELSE /* G_PROJECT_ID is null */
10536 
10537             -- This update is to mark the pa addition flag of all invoice distributions
10538             -- which have encumbered flag of 'R' or reversal flag of 'Y' to 'Z'.
10539             -- Encumbrance flag of 'R' or reversal flag of 'Y' indicates that they are
10540             -- exact reversal of another invoice distribution.
10541             -- If the invoice distribution has a encumbered flag value of 'R' then it is
10542             -- not encumbered and there exist no Budgetery control commitment records
10543             -- for these in PA
10544 
10545             UPDATE ap_payment_hist_dists dist
10546                 SET dist.pa_addition_flag = 'Z',
10547                     request_id = G_REQUEST_ID,
10548                     last_update_date=SYSDATE,
10549                     last_updated_by= G_USER_ID,
10550                     last_update_login= G_USER_ID,
10551                     program_id= G_PROG_ID,
10552                     program_application_id= G_PROG_APPL_ID,
10553                     program_update_date=SYSDATE
10554             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
10555                AND EXISTS (SELECT NULL
10556                            FROM   ap_payment_history_all hist
10557                            WHERE  hist.payment_history_id = dist.payment_history_id
10558                            AND    hist.posted_flag = 'Y')
10559                AND EXISTS (SELECT aid.invoice_id
10560                              FROM AP_invoice_distributions aid
10561                             WHERE aid.invoice_distribution_id  = dist.invoice_distribution_id
10562                               AND aid.project_id > 0
10563                               AND ( nvl(aid.encumbered_flag,'N') = 'R' )
10564 			    ) ;
10565 
10566      write_log(LOG, 'Number of distributions marked for encumbered net zero adjustment: ' || to_char(SQL%ROWCOUNT));
10567 
10568      END IF;
10569 
10570      END IF;
10571      G_err_stack := v_old_stack;
10572 
10573 EXCEPTION
10574         WHEN Others THEN
10575                /*
10576                --
10577                -- Exceptions occured in this procedure must be raised by the
10578                -- UPDATE statement, most likely a fatal error like 'rollback
10579                -- segment exceeded' error which should cause the program to
10580                -- terminate
10581                --
10582                */
10583 
10584 	       G_err_stack := v_old_stack;
10585                G_err_code := SQLCODE;
10586 	       raise;
10587 
10588 
10589 END net_zero_pay_adjustment;
10590 
10591 /*-----------------------Marking Distribution Phase---------------------*/
10592 
10593 PROCEDURE mark_PA_Pay_flag_O IS
10594 
10595         v_old_stack VARCHAR2(630);
10596 
10597 BEGIN
10598 
10599      v_old_stack := G_err_stack;
10600      G_err_stack := G_err_stack || '->PAAPIMP_PKG.mark_PA_Pay_flag_O';
10601      G_err_code := 0;
10602      G_err_stage := 'UPDATING PAYMENT DISTRIBUTIONS-Marking Process';
10603 
10604      write_log(LOG, G_err_stack);
10605 
10606      IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
10607                    --
10608                    -- This section is for Expense Reports
10609                    --
10610 
10611           write_log(LOG, 'Marking Expense Report type invoices for processing...');
10612                    --
10613           IF G_PROJECT_ID IS NOT NULL THEN
10614 
10615             UPDATE ap_payment_hist_dists dist
10616                 SET dist.pa_addition_flag = 'O',
10617                     request_id = G_REQUEST_ID,
10618                     last_update_date=SYSDATE,
10619                     last_updated_by= G_USER_ID,
10620                     last_update_login= G_USER_ID,
10621                     program_id= G_PROG_ID,
10622                     program_application_id= G_PROG_APPL_ID,
10623                     program_update_date=SYSDATE
10624             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
10625             AND   dist.pay_dist_lookup_code = 'CASH'
10626             AND EXISTS (SELECT NULL
10627                         FROM   ap_payment_history_all hist
10628                         WHERE  hist.payment_history_id = dist.payment_history_id
10629                         AND    hist.posted_flag = 'Y')
10630             AND   exists (SELECT inv.invoice_id
10631                            FROM AP_INVOICES inv,
10632                                 PO_VENDORS vend,
10633                                 AP_Invoice_Distributions_all aid,
10634                                 ap_invoice_payments_all aip
10635                           WHERE inv.invoice_id = aid.invoice_id
10636                             AND inv.vendor_id = vend.vendor_id
10637                             AND aip.invoice_payment_id = dist.invoice_payment_id
10638                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
10639                             AND aid.pa_addition_flag  = 'N'                      --to avoid any historical data to be processed as Payments
10640                             AND nvl(aid.historical_flag,'N') = 'N'
10641                             AND aid.invoice_id = aip.invoice_id
10642                             AND aid.project_id = G_PROJECT_ID
10643                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
10644                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)) /*GSCC*/
10645                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
10646                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2,
10647                                       G_INVOICE_SOURCE3)
10648                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
10649                                  OR
10650                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
10651                                  AND inv.source  in ('CREDIT CARD','Both Pay')
10652                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)));
10653 
10654         G_PAY_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
10655         write_log(LOG, 'Number of Invoice - Payment rows marked to O: ' || to_char(SQL%ROWCOUNT));
10656 
10657         /* For Prepayment Application , we need to interface the prepay application lines created in ap_prepay_app_dists table*/
10658 
10659             UPDATE ap_prepay_app_dists dist
10660             SET    dist.pa_addition_flag = 'O',
10661                    request_id = G_REQUEST_ID,
10662                    last_update_date=SYSDATE,
10663                    last_updated_by= G_USER_ID,
10664                    last_update_login= G_USER_ID,
10665                    program_id= G_PROG_ID,
10666                    program_application_id= G_PROG_APPL_ID,
10667                    program_update_date=SYSDATE
10668             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
10669             AND   dist.amount <>0
10670             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
10671                            FROM AP_INVOICES_ALL inv,
10672                                 PO_VENDORS vend,
10673                                 PO_Distributions_all PO,
10674                                 AP_Invoice_Distributions_all aid, --STD INV DIST LINE
10675                                 AP_Invoice_Distributions_all aid2 -- PREPAY APPL DIST LINE
10676                           WHERE aid.invoice_id = inv.invoice_id
10677                             AND inv.vendor_id = vend.vendor_id
10678                             AND inv.org_id = G_ORG_ID
10679                             AND aid.invoice_distribution_id = dist.invoice_distribution_id  -- Std inv line
10680                             AND aid2.invoice_id = aid.invoice_id
10681                             AND aid2.invoice_distribution_id =  dist.prepay_app_distribution_id --Prepay appl line
10682                             --AND aid2.line_type_lookup_code in ( 'PREPAY', 'NONREC_TAX') -- bug#5514129
10683                             AND aid.line_type_lookup_code  <> 'REC_TAX' -- bug#5514129
10684                             and aid2.prepay_distribution_id is not null
10685                             AND aid2.pa_addition_flag  in ( 'N','E')         --to avoid any historical data to be processed as Payments
10686                              -- pa-addition-flag E to pull in rec tax across which prepay appl is prorated
10687                             AND aid2.posted_flag = 'Y'
10688                             AND aid.project_id = G_PROJECT_ID
10689                             AND trunc(aid2.Accounting_Date) <= trunc(nvl(G_GL_DATE,aid2.Accounting_Date))
10690                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
10691                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
10692                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
10693                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
10694                                  OR
10695                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
10696                                  AND inv.source in ('CREDIT CARD','Both Pay')
10697                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)));
10698 
10699           G_PAY_DISTRIBUTIONS_MARKED := nvl(G_PAY_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
10700           write_log(LOG, 'Number of Prepayment Application Dist rows marked to O: ' || to_char(SQL%ROWCOUNT));
10701 
10702       ELSE /* G_PROJECT_ID IS NULL */
10703 
10704 
10705             UPDATE ap_payment_hist_dists dist
10706                 SET dist.pa_addition_flag = 'O',
10707                     request_id = G_REQUEST_ID,
10708                     last_update_date=SYSDATE,
10709                     last_updated_by= G_USER_ID,
10710                     last_update_login= G_USER_ID,
10711                     program_id= G_PROG_ID,
10712                     program_application_id= G_PROG_APPL_ID,
10713                     program_update_date=SYSDATE
10714             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
10715             AND   dist.pay_dist_lookup_code = 'CASH'
10716             AND EXISTS (SELECT NULL
10717                         FROM   ap_payment_history_all hist
10718                         WHERE  hist.payment_history_id = dist.payment_history_id
10719                         AND    hist.posted_flag = 'Y')
10720             AND  exists (SELECT inv.invoice_id
10721                            FROM AP_INVOICES_ALL inv,
10722                                 PO_VENDORS vend,
10723                                 AP_Invoice_Distributions_all aid,
10724                                 ap_invoice_payments_all aip
10725                           WHERE inv.vendor_id = vend.vendor_id
10726                             AND aid.invoice_id = inv.invoice_id
10727                             AND inv.org_id = G_ORG_ID
10728                             AND aip.invoice_payment_id = dist.invoice_payment_id
10729                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
10730                             AND aid.invoice_id = aip.invoice_id
10731                             AND aid.project_id > 0
10732                             AND aid.pa_addition_flag  = 'N'                      --to avoid any historical data to be processed as Payments
10733                             AND nvl(aid.historical_flag,'N') = 'N'
10734                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
10735                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)) /*GSCC*/
10736                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
10737                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2,
10738                                       G_INVOICE_SOURCE3)
10739                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
10740                                  OR
10741                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
10742                                  AND inv.source  in ('CREDIT CARD','Both Pay')
10743                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)));
10744 
10745         G_PAY_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
10746         write_log(LOG, 'Number of Invoice - Payment rows marked to O: ' || to_char(SQL%ROWCOUNT));
10747 
10748         /* For Prepayment Application , we need to interface the prepay application lines created in ap_prepay_app_dists table*/
10749 
10750             UPDATE ap_prepay_app_dists dist
10751             SET    dist.pa_addition_flag = 'O',
10752                    request_id = G_REQUEST_ID,
10753                    last_update_date=SYSDATE,
10754                    last_updated_by= G_USER_ID,
10755                    last_update_login= G_USER_ID,
10756                    program_id= G_PROG_ID,
10757                    program_application_id= G_PROG_APPL_ID,
10758                    program_update_date=SYSDATE
10759             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
10760             AND   dist.amount <>0
10761             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
10762                            FROM AP_INVOICES_ALL inv,
10763                                 PO_VENDORS vend,
10764                                 PO_Distributions_all PO,
10765                                 AP_Invoice_Distributions_all aid, --STD INV DIST LINE
10766                                 AP_Invoice_Distributions_all aid2 -- PREPAY APPL DIST LINE
10767                           WHERE aid.invoice_id = inv.invoice_id
10768                             AND inv.vendor_id = vend.vendor_id
10769                             AND inv.org_id = G_ORG_ID
10770                             AND aid.invoice_distribution_id = dist.invoice_distribution_id  -- Std inv line
10771                             AND aid2.invoice_id = aid.invoice_id
10772                             AND aid2.invoice_distribution_id =  dist.prepay_app_distribution_id --Prepay appl line
10773                             --AND aid2.line_type_lookup_code in ( 'PREPAY', 'NONREC_TAX') -- bug#5514129
10774                             AND aid.line_type_lookup_code  <> 'REC_TAX' -- bug#5514129
10775                             AND aid2.pa_addition_flag  in ( 'N','E')         --to avoid any historical data to be processed as Payments
10776                              -- pa-addition-flag E to pull in rec tax across which prepay appl is prorated
10777                             and aid2.prepay_distribution_id is not null
10778                             AND aid2.posted_flag = 'Y'
10779                             AND aid.project_id > 0
10780                             AND trunc(aid2.Accounting_Date) <= trunc(nvl(G_GL_DATE,aid2.Accounting_Date))
10781                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
10782                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
10783                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
10784                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
10785                                  OR
10786                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
10787                                  AND inv.source  in ('CREDIT CARD','Both Pay')
10788                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)));
10789 
10790           G_PAY_DISTRIBUTIONS_MARKED := nvl(G_PAY_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
10791           write_log(LOG, 'Number of Prepayment Application Dist rows marked to O: ' || to_char(SQL%ROWCOUNT));
10792 
10793         END IF; /* END IF Project ID */
10794 
10795      ELSE
10796 
10797 	   write_log(LOG, 'Marking Payments - supplier invoices for processing...');
10798 
10799              --
10800              -- Due to performance reasons the single update statement was
10801              -- broken up into two update statements based on if the program
10802              -- has the value of project id (If the user has given project number
10803              -- as one of the parameters).
10804              --
10805 
10806             IF G_PROJECT_ID IS NOT NULL THEN
10807 
10808           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
10809 
10810             UPDATE ap_payment_hist_dists dist
10811             SET    dist.pa_addition_flag = 'O',
10812                    request_id = G_REQUEST_ID,
10813                    last_update_date=SYSDATE,
10814                    last_updated_by= G_USER_ID,
10815                    last_update_login= G_USER_ID,
10816                    program_id= G_PROG_ID,
10817                    program_application_id= G_PROG_APPL_ID,
10818                    program_update_date=SYSDATE
10819             WHERE dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
10820             AND   dist.pay_dist_lookup_code = 'CASH'
10821             AND EXISTS (SELECT NULL
10822                         FROM   ap_payment_history_all hist
10823                         WHERE  hist.payment_history_id = dist.payment_history_id
10824                         AND    hist.posted_flag = 'Y')
10825             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
10826                            FROM AP_INVOICES_ALL inv,
10827                                 PO_Distributions_all PO,
10828                                 AP_Invoice_Distributions_all aid,
10829                                 ap_invoice_payments_all aip
10830                           WHERE inv.invoice_id = aip.invoice_id
10831                             AND aid.invoice_id = inv.invoice_id
10832                             AND inv.org_id = G_ORG_ID
10833                             AND aip.invoice_payment_id = dist.invoice_payment_id
10834                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
10835                             AND aid.line_type_lookup_code <> 'TERV'             -- Bug#5441030 to avoid zero dollar lines for TERV
10836                             AND aid.invoice_id = aip.invoice_id
10837                             AND aid.pa_addition_flag  = 'N'                      --to avoid any historical data to be processed as Payments
10838                             AND nvl(aid.historical_flag,'N') = 'N'
10839                             AND aid.po_distribution_id = PO.po_distribution_id (+)
10840                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
10841                             AND inv.paid_on_behalf_employee_id IS NULL
10842                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
10843                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
10844                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
10845                             AND aid.project_id = G_PROJECT_ID
10846                             AND aid.line_type_lookup_code <> 'REC_TAX'
10847                             AND (((
10848                                PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(aid.project_ID, 0))= 'N'
10849                                OR
10850                                PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(aid.po_distribution_id,0))= 'N' )
10851                             AND aid.line_type_lookup_code IN ('ITEM','ACCRUAL','RETROACCRUAL')) OR
10852                             (aid.line_type_lookup_code NOT IN ('ITEM','ACCRUAL','RETROACCRUAL')))
10853                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
10854                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
10855 
10856           G_PAY_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
10857         write_log(LOG, 'Number of Invoice - Payment rows marked to O: ' || to_char(SQL%ROWCOUNT));
10858 
10859         /* For Prepayment Application , we need to interface the prepay application lines created in ap_prepay_app_dists table*/
10860 
10861             UPDATE ap_prepay_app_dists dist
10862             SET    dist.pa_addition_flag = 'O',
10863                    request_id = G_REQUEST_ID,
10864                    last_update_date=SYSDATE,
10865                    last_updated_by= G_USER_ID,
10866                    last_update_login= G_USER_ID,
10867                    program_id= G_PROG_ID,
10868                    program_application_id= G_PROG_APPL_ID,
10869                    program_update_date=SYSDATE
10870             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
10871             AND   dist.amount <> 0
10872             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
10873                            FROM AP_INVOICES_ALL inv,
10874                                 PO_Distributions_all PO,
10875                                 AP_Invoice_Distributions_all aid, --STD INV DIST LINE
10876                                 AP_Invoice_Distributions_all aid2 -- PREPAY APPL DIST LINE
10877                           WHERE aid.invoice_id = inv.invoice_id
10878                             AND aid.invoice_distribution_id = dist.invoice_distribution_id  -- Std inv line
10879                             AND inv.org_id = G_ORG_ID
10880                             AND aid2.invoice_id = aid.invoice_id
10881                             AND aid2.invoice_distribution_id =  dist.prepay_app_distribution_id --Prepay appl line
10882                             --AND aid2.line_type_lookup_code in ( 'PREPAY', 'NONREC_TAX') -- bug#5514129
10883                             AND aid.line_type_lookup_code  <> 'REC_TAX' -- bug#5514129
10884                             AND aid2.pa_addition_flag  in ( 'N','E')         --to avoid any historical data to be processed as Payments
10885                              -- pa-addition-flag E to pull in rec tax across which prepay appl is prorated
10886                             and aid2.prepay_distribution_id is not null
10887                             AND aid2.posted_flag = 'Y'
10888                             AND aid.po_distribution_id = PO.po_distribution_id (+)
10889                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
10890                             AND inv.paid_on_behalf_employee_id IS NULL
10891                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
10892                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
10893                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
10894                             AND aid.project_id = G_PROJECT_ID
10895                             AND (((
10896                                PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(aid.project_ID, 0))= 'N'
10897                                OR
10898                                PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(aid.po_distribution_id,0))= 'N' )
10899                             AND aid.line_type_lookup_code IN ('ITEM','ACCRUAL','RETROACCRUAL')) OR
10900                             (aid.line_type_lookup_code NOT IN ('ITEM','ACCRUAL','RETROACCRUAL')))
10901                             AND trunc(aid2.Accounting_Date) <= trunc(nvl(G_GL_DATE,aid2.Accounting_Date))
10902                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
10903 
10904           G_PAY_DISTRIBUTIONS_MARKED := nvl(G_PAY_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
10905           write_log(LOG, 'Number of Prepayment Application Dist rows marked to O: ' || to_char(SQL%ROWCOUNT));
10906 
10907         ELSE          /* G_PROJECT_ID IS NULL */
10908 
10909 
10910           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
10911 
10912             UPDATE ap_payment_hist_dists dist
10913             SET    dist.pa_addition_flag = 'O',
10914                    request_id = G_REQUEST_ID,
10915                    last_update_date=SYSDATE,
10916                    last_updated_by= G_USER_ID,
10917                    last_update_login= G_USER_ID,
10918                    program_id= G_PROG_ID,
10919                    program_application_id= G_PROG_APPL_ID,
10920                    program_update_date=SYSDATE
10921             WHERE  dist.pa_addition_flag = 'N' /*Removed NVL statement for bug#14073110 */
10922             AND    dist.pay_dist_lookup_code = 'CASH'
10923             AND EXISTS (SELECT NULL
10924                         FROM   ap_payment_history_all hist
10925                         WHERE  hist.payment_history_id = dist.payment_history_id
10926                         AND    hist.posted_flag = 'Y')
10927             AND    exists(SELECT /*+ no_unnest */ inv.invoice_id
10928                            FROM AP_INVOICES_ALL inv,
10929                                 PO_Distributions_all PO,
10930                                 AP_Invoice_Distributions_all aid,
10931                                 ap_invoice_payments_all aip
10932                           WHERE inv.invoice_id = aip.invoice_id
10933                             AND aid.invoice_id = inv.invoice_id
10934                             AND inv.org_id = G_ORG_ID
10935                             AND aip.invoice_payment_id = dist.invoice_payment_id
10936                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
10937                             AND aid.line_type_lookup_code <> 'TERV'             -- Bug#5441030 to avoid zero dollar lines for TERV
10938                             AND aid.invoice_id = aip.invoice_id
10939                             AND aid.pa_addition_flag  = 'N'                      --to avoid any historical data to be processed as Payments
10940                             AND nvl(aid.historical_flag,'N') = 'N'
10941                             AND aid.po_distribution_id = PO.po_distribution_id (+)
10942                             AND   nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
10943                             AND inv.paid_on_behalf_employee_id IS NULL
10944                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
10945                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
10946                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
10947                             AND aid.project_id > 0
10948                             AND aid.line_type_lookup_code <> 'REC_TAX'
10949                             AND (((
10950                                PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(aid.project_ID, 0))= 'N'
10951                                OR
10952                                PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(aid.po_distribution_id,0))= 'N' )
10953                             AND aid.line_type_lookup_code IN ('ITEM','ACCRUAL','RETROACCRUAL')) OR
10954                             (aid.line_type_lookup_code NOT IN ('ITEM','ACCRUAL','RETROACCRUAL')))
10955                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
10956                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
10957 
10958         G_PAY_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
10959         write_log(LOG, 'Number of Invoice - Payment rows marked to O: ' || to_char(SQL%ROWCOUNT));
10960 
10961         /* For Prepayment Application , we need to interface the prepay application lines created in ap_prepay_app_dists table*/
10962 
10963             UPDATE ap_prepay_app_dists dist
10964             SET    dist.pa_addition_flag = 'O',
10965                    request_id = G_REQUEST_ID,
10966                    last_update_date=SYSDATE,
10967                    last_updated_by= G_USER_ID,
10968                    last_update_login= G_USER_ID,
10969                    program_id= G_PROG_ID,
10970                    program_application_id= G_PROG_APPL_ID,
10971                    program_update_date=SYSDATE
10972             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
10973             AND   dist.amount <> 0
10974             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
10975                            FROM AP_INVOICES_ALL inv,
10976                                 PO_Distributions_all PO,
10977                                 AP_Invoice_Distributions_all aid, --STD INV DIST LINE
10978                                 AP_Invoice_Distributions_all aid2 -- PREPAY APPL DIST LINE
10979                           WHERE aid.invoice_id = inv.invoice_id
10980                             AND inv.org_id = G_ORG_ID
10981                             AND aid.invoice_distribution_id = dist.invoice_distribution_id  -- Std inv line
10982                             AND aid2.invoice_id = aid.invoice_id
10983                             AND aid2.invoice_distribution_id =  dist.prepay_app_distribution_id --Prepay appl line
10984                             --AND aid2.line_type_lookup_code in ( 'PREPAY', 'NONREC_TAX') -- bug#5514129
10985                             AND aid.line_type_lookup_code  <> 'REC_TAX' -- bug#5514129
10986                             AND aid2.pa_addition_flag  in ( 'N','E')         --to avoid any historical data to be processed as Payments
10987                              -- pa-addition-flag E to pull in rec tax across which prepay appl is prorated
10988                             and aid2.prepay_distribution_id is not null
10989                             AND aid2.posted_flag = 'Y'
10990                             AND aid.po_distribution_id = PO.po_distribution_id (+)
10991                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
10992                             AND inv.paid_on_behalf_employee_id IS NULL
10993                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
10994                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
10995                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
10996                             AND aid.project_id> 0
10997                             AND (((
10998                                PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(aid.project_ID, 0))= 'N'
10999                                OR
11000                                PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(aid.po_distribution_id,0))= 'N' )
11001                             AND aid.line_type_lookup_code IN ('ITEM','ACCRUAL','RETROACCRUAL')) OR
11002                             (aid.line_type_lookup_code NOT IN ('ITEM','ACCRUAL','RETROACCRUAL')))
11003                             AND trunc(aid2.Accounting_Date) <= trunc(nvl(G_GL_DATE,aid2.Accounting_Date))
11004                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
11005 
11006         G_PAY_DISTRIBUTIONS_MARKED := nvl(G_PAY_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
11007         write_log(LOG, 'Number of Prepayment Application Dist rows marked to O: ' || to_char(SQL%ROWCOUNT));
11008 
11009 
11010        END IF;
11011          -- End of If section checking if G_PROJECT_ID is not null
11012      END IF; -- End of Invoice Type is Expense Report
11013 
11014      write_log(LOG, 'Total Number of Payment rows marked to O: ' || to_char(G_PAY_DISTRIBUTIONS_MARKED));
11015 
11016      G_err_stack := v_old_stack;
11017 
11018 EXCEPTION
11019      WHEN Others THEN
11020            -- Marking phase failed, raise exception to main program to terminate the program
11021            --
11022            G_err_stack := v_old_stack;
11023            G_err_code := SQLCODE;
11024            RAISE;
11025 
11026 END mark_PA_Pay_flag_O;
11027 
11028 PROCEDURE transfer_pay_to_pa  IS
11029 
11030    v_num_invoices_fetched          NUMBER :=0;
11031    v_num_distributions_fetched     NUMBER :=0;
11032    v_prev_invoice_id               NUMBER := 0;
11033    v_prev_vendor_id                NUMBER := 0;
11034    v_old_stack                     VARCHAR2(630);
11035    v_err_message                   VARCHAR2(220);
11036    v_all_done                      NUMBER := 0;
11037    v_prev_invoice_source           ap_invoices.source%TYPE := NULL;
11038    v_prev_transaction_source       pa_transaction_sources.transaction_source%TYPE;
11039    v_num_tax_lines_fetched         NUMBER:=0;
11040    v_num_inv_variance_fetched      NUMBER:=0;    --NEW
11041    v_num_inv_erv_fetched           NUMBER:=0;    --NEW
11042    v_num_inv_frt_fetched           NUMBER:=0;    --NEW
11043    v_num_inv_prepay_fetched        NUMBER:=0;    --NEW
11044    v_last_inv_ER_flag              VARCHAR2(1);
11045 
11046    v_status Number := 0;
11047    v_stage  Number :=0;
11048    v_business_group_id NUMBER := 0;
11049    v_attribute_category VARCHAR2(150);
11050    v_attribute1 VARCHAR2(150);
11051    v_attribute2 VARCHAR2(150);
11052    v_attribute3 VARCHAR2(150);
11053    v_attribute4 VARCHAR2(150);
11054    v_attribute5 VARCHAR2(150);
11055    v_attribute6 VARCHAR2(150);
11056    v_attribute7 VARCHAR2(150);
11057    v_attribute8 VARCHAR2(150);
11058    v_attribute9 VARCHAR2(150);
11059    v_attribute10 VARCHAR2(150);
11060    v_dff_map_status VARCHAR2(30);
11061    dff_map_exception EXCEPTION;
11062 
11063    v_num_last_invoice_processed NUMBER := 0;
11064    v_last_inv_index             NUMBER := 0;
11065    v_num_dist_marked_O          NUMBER := 0;
11066    v_num_dist_remain            NUMBER := 0;
11067    v_max_size                   NUMBER := 0;
11068 
11069    v_inv_batch_size             NUMBER := 0;
11070    v_tax_batch_size             NUMBER := 0;
11071    v_var_batch_size             NUMBER := 0;
11072    v_frt_batch_size             NUMBER := 0;
11073 
11074 -- For PA IP Invoices
11075    L_IP_TRANSACTION_SOURCE         pa_transaction_interface.transaction_source%TYPE;
11076    l_ap_inv_flag                   VARCHAR2(1):= 'N';
11077    l_ip_inv_flag                   VARCHAR2(1):= 'N';
11078 
11079    l_create_adj_recs  VARCHAR2(1) := 'N';
11080    l_ap_prepay_tax_flag    VARCHAR2(1):= 'N'; -- Flag to indicate tax  exist for prepay appl in Cash Basis flow.
11081    l_ap_prepay_var_flag    VARCHAR2(1):= 'N'; -- Flag to indicate variance exist for prepay appl lines in Cash Basis flow.
11082    l_ap_prepay_erv_flag    VARCHAR2(1):= 'N'; -- Flag to indicate erv exist for prepay appl lines in Cash Basis flow.
11083 
11084    /* the following sub-procedure is declared here to save lines of code since deleting
11085       plsql tables will be done multiple times within the procedure transfer_pay_to_pa */
11086 
11087    PROCEDURE clear_plsql_tables IS
11088 
11089        l_status1 VARCHAR2(30);
11090 
11091    BEGIN
11092 
11093        G_err_stage := 'within clear_plsql_tables of transfer_pay_to_pa';
11094        write_log(LOG, G_err_stage);
11095 
11096        l_invoice_id_tbl.delete;
11097        l_created_by_tbl.delete;
11098        l_invoice_dist_id_tbl.delete; --NEW
11099        l_project_id_tbl.delete;
11100        l_task_id_tbl.delete;
11101        l_ln_type_lookup_tbl.delete;
11102        l_exp_type_tbl.delete;
11103        l_ei_date_tbl.delete;
11104        l_amount_tbl.delete;
11105        l_description_tbl.delete;
11106        l_justification_tbl.delete;
11107        l_dist_cc_id_tbl.delete;
11108        l_exp_org_id_tbl.delete;
11109        l_quantity_tbl.delete;
11110        l_acct_pay_cc_id_tbl.delete;
11111        l_gl_date_tbl.delete;
11112        l_attribute_cat_tbl.delete;
11113        l_attribute1_tbl.delete;
11114        l_attribute2_tbl.delete;
11115        l_attribute3_tbl.delete;
11116        l_attribute4_tbl.delete;
11117        l_attribute5_tbl.delete;
11118        l_attribute6_tbl.delete;
11119        l_attribute7_tbl.delete;
11120        l_attribute8_tbl.delete;
11121        l_attribute9_tbl.delete;
11122        l_attribute10_tbl.delete;
11123        l_rec_cur_amt_tbl.delete;
11124        l_rec_cur_code_tbl.delete;
11125        l_rec_conv_rate_tbl.delete;
11126        l_denom_raw_cost_tbl.delete;
11127        l_denom_cur_code_tbl.delete;
11128        l_acct_rate_date_tbl.delete;
11129        l_acct_rate_type_tbl.delete;
11130        l_acct_exch_rate_tbl.delete;
11131        l_job_id_tbl.delete;
11132        l_employee_id_tbl.delete;
11133        l_vendor_id_tbl.delete;
11134        l_inv_type_code_tbl.delete;
11135        l_source_tbl.delete;
11136        l_org_id_tbl.delete;
11137        l_invoice_num_tbl.delete;
11138        l_cdl_sys_ref3_tbl.delete;
11139        l_cdl_sys_ref4_tbl.delete;
11140        l_po_dist_id_tbl.delete;
11141        l_txn_src_tbl.delete;
11142        l_user_txn_src_tbl.delete;
11143        l_batch_name_tbl.delete;
11144        l_interface_id_tbl.delete;
11145        l_exp_end_date_tbl.delete;
11146        l_txn_status_code_tbl.delete;
11147        l_txn_rej_code_tbl.delete;
11148        l_po_dist_id_tbl.delete;
11149        l_bus_grp_id_tbl.delete;
11150        l_paid_emp_id_tbl.delete;
11151        l_sort_var_tbl.delete;
11152        l_reversal_flag_tbl.delete;
11153        l_cancel_flag_tbl.delete;
11154        l_parent_rev_id_tbl.delete;
11155        l_net_zero_flag_tbl.delete;
11156        l_sc_xfer_code_tbl.delete;
11157        l_adj_exp_item_id_tbl.delete;
11158        l_fc_enabled_tbl.delete;
11159        l_fc_document_type_tbl.delete;
11160        l_rev_parent_dist_id_tbl.delete;
11161        l_rev_child_dist_id_tbl.delete;
11162        l_rev_parent_dist_ind_tbl.delete;
11163        l_si_assts_add_flg_tbl.delete;
11164        l_pay_hist_id_tbl.delete;
11165        l_prepay_dist_id_tbl.delete;
11166        l_cbs_element_id_tbl.delete; -- Added for CBS Enhancement Bug 16220146
11167        l_rev_index:=0;
11168 
11169     END clear_plsql_tables;
11170 
11171    /* the following sub-procedure is declared here to save lines of code since bulk insert
11172       will be done multiple times within the procedure transfer_pay_to_pa */
11173 
11174     PROCEDURE bulk_update_trx_intf IS
11175 
11176      BEGIN
11177 
11178        /* The records with INSERT_FLAG = F indicate that they are fully applied prepayments and the pa-addition-flag
11179           for such records will be updated to G to relieve commitments*/
11180        /* The records with INSERT_FLAG = P indicate that they are partially applied prepayments and the pa-addition-flag
11181           for such records will be updated to N */
11182 
11183        write_log(LOG,'Before bulk update  of prepayment payments');
11184 
11185        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
11186 
11187          UPDATE ap_payment_hist_dists dist
11188             SET dist.pa_addition_flag         = decode(l_insert_flag_tbl(i),'F','G','P','N')
11189           WHERE dist.invoice_payment_id       = l_inv_pay_id_tbl(i)
11190             AND dist.pay_dist_lookup_code     = 'CASH'
11191             AND dist.invoice_distribution_id  = l_invoice_dist_id_tbl(i)
11192             AND dist.pa_addition_flag         = 'O'
11193             AND l_insert_flag_tbl(i)         in ('P','F');
11194 
11195      EXCEPTION
11196       WHEN OTHERS THEN
11197           write_log(LOG,'Failed during bulk update for prepayment processing');
11198           G_err_code   := SQLCODE;
11199           write_log(LOG, 'Error Code is '||SQLCODE);
11200           write_log(LOG, substr(SQLERRM, 1, 200));
11201           write_log(LOG, substr(SQLERRM, 201, 200));
11202           raise;
11203 
11204     END bulk_update_trx_intf;
11205 
11206 
11207     PROCEDURE bulk_insert_trx_intf IS
11208 
11209       l_status2 VARCHAR2(30);
11210 
11211     BEGIN
11212 
11213        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
11214 
11215        INSERT INTO pa_transaction_interface_all(
11216                      transaction_source
11217                     , user_transaction_source
11218                     , system_linkage
11219                     , batch_name
11220                     , expenditure_ending_date
11221                     , expenditure_item_date
11222                     , expenditure_type
11223                     , quantity
11224                     , raw_cost_rate
11225                     , expenditure_comment
11226                     , transaction_status_code
11227                     , transaction_rejection_code
11228                     , orig_transaction_reference
11229                     , interface_id
11230                     , dr_code_combination_id
11231                     , cr_code_combination_id
11232                     , cdl_system_reference1
11233                     , cdl_system_reference2
11234                     , cdl_system_reference3
11235                     , cdl_system_reference4
11236                     , cdl_system_reference5 --NEW
11237                     , gl_date
11238                     , org_id
11239                     , unmatched_negative_txn_flag
11240                     , receipt_currency_amount
11241                     , receipt_currency_code
11242                     , receipt_exchange_rate
11243                     , denom_raw_cost
11244                     , denom_currency_code
11245                     , acct_rate_date
11246                     , acct_rate_type
11247                     , acct_exchange_rate
11248                     , acct_raw_cost
11249                     , acct_exchange_rounding_limit
11250                     , attribute_category
11251                     , attribute1
11252                     , attribute2
11253                     , attribute3
11254                     , attribute4
11255                     , attribute5
11256                     , attribute6
11257                     , attribute7
11258                     , attribute8
11259                     , attribute9
11260                     , attribute10
11261                     , orig_exp_txn_reference1
11262                     , orig_user_exp_txn_reference
11263                     , orig_exp_txn_reference2
11264                     , orig_exp_txn_reference3
11265                     , last_update_date
11266                     , last_updated_by
11267                     , creation_date
11268                     , created_by
11269                     , person_id
11270                     , organization_id
11271                     , project_id
11272                     , task_id
11273                     , Vendor_id
11274                     , override_to_organization_id
11275                     , person_business_group_id
11276                     , adjusted_expenditure_item_id --NEW
11277                     , fc_document_type  -- NEW
11278                     , document_type
11279                     , document_distribution_type
11280                     , sc_xfer_code
11281                     , si_assets_addition_flag
11282                     , net_zero_adjustment_flag
11283                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
11284                    )
11285               SELECT  l_txn_src_tbl(i)
11286                      ,l_user_txn_src_tbl(i)
11287                      ,G_SYSTEM_LINKAGE
11288                      ,l_batch_name_tbl(i)
11289                      ,l_exp_end_date_tbl(i)
11290                      ,l_ei_date_tbl(i)
11291                      ,l_exp_type_tbl(i)
11292                      ,l_quantity_tbl(i)
11293                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
11294                      ,l_description_tbl(i)
11295                      ,l_txn_status_code_tbl(i)
11296                      ,l_txn_rej_code_tbl(i)
11297                      ,G_REQUEST_ID
11298                      ,l_interface_id_tbl(i)
11299                      ,l_dist_cc_id_tbl(i)
11300                      ,l_acct_pay_cc_id_tbl(i)
11301                      ,decode(l_ln_type_lookup_tbl(i),'PREPAY',l_vendor_id_tbl(i),l_pay_hist_id_tbl(i)) /*sysref1*/
11302                      ,l_invoice_id_tbl(i) /*sysref2*/
11303                      ,l_cdl_sys_ref3_tbl(i) /*sysref3*/
11304                      ,l_inv_pay_id_tbl(i) /*sysref4*/
11305                      ,l_invoice_dist_id_tbl(i) /*sysref5*/
11306                      ,l_gl_date_tbl(i)
11307                      ,G_ORG_ID
11308                      ,'Y'
11309                      ,l_rec_cur_amt_tbl(i)
11310                      ,l_rec_cur_code_tbl(i)
11311                      ,l_rec_conv_rate_tbl(i)
11312                      ,l_denom_raw_cost_tbl(i)
11313                      ,l_denom_cur_code_tbl(i)
11314                      ,l_acct_rate_date_tbl(i)
11315                      ,l_acct_rate_type_tbl(i)
11316                      ,l_acct_exch_rate_tbl(i)
11317                      ,l_amount_tbl(i)
11318                      ,1
11319                      ,l_attribute_cat_tbl(i)
11320                      ,l_attribute1_tbl(i)
11321                      ,l_attribute2_tbl(i)
11322                      ,l_attribute3_tbl(i)
11323                      ,l_attribute4_tbl(i)
11324                      ,l_attribute5_tbl(i)
11325                      ,l_attribute6_tbl(i)
11326                      ,l_attribute7_tbl(i)
11327                      ,l_attribute8_tbl(i)
11328                      ,l_attribute9_tbl(i)
11329                      ,l_attribute10_tbl(i)
11330                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
11331                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
11332                      ,DECODE(G_TRANS_DFF_AP,'N',NULL,l_invoice_id_tbl(i)) /*orig_exp_txn_reference2*/
11333                      ,NULL                       /*orig_exp_txn_reference3*/
11334                      ,SYSDATE
11335                      ,-1
11336                      ,SYSDATE
11337                      ,-1
11338                      ,l_employee_id_tbl(i)
11339                      ,l_org_id_tbl(i)
11340                      ,l_project_id_tbl(i)
11341                      ,l_task_id_tbl(i)
11342                      ,l_vendor_id_tbl(i)
11343                      ,l_exp_org_id_tbl(i)
11344                      ,l_bus_grp_id_tbl(i)
11345                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
11346                      ,l_fc_document_type_tbl(i) --NEW for funds check
11347                      ,l_inv_type_code_tbl(i)
11348                      ,l_ln_type_lookup_tbl(i)
11349                      ,l_sc_xfer_code_tbl(i)
11350                      ,l_si_assts_add_flg_tbl(i)
11351                      ,l_net_zero_flag_tbl(i)
11352                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
11353                  FROM DUAL
11354                 WHERE l_insert_flag_tbl(i)     not in ('P','F');
11355 
11356               -- Insert the adjustment recs from AP.
11357     IF l_create_adj_recs = 'Y' THEN
11358 
11359                 write_log(LOG, 'Inserting adjustment records..');
11360 
11361        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
11362 
11363        INSERT INTO pa_transaction_interface_all(
11364                      transaction_source
11365                     , user_transaction_source
11366                     , system_linkage
11367                     , batch_name
11368                     , expenditure_ending_date
11369                     , expenditure_item_date
11370                     , expenditure_type
11371                     , quantity
11372                     , raw_cost_rate
11373                     , expenditure_comment
11374                     , transaction_status_code
11375                     , transaction_rejection_code
11376                     , orig_transaction_reference
11377                     , interface_id
11378                     , dr_code_combination_id
11379                     , cr_code_combination_id
11380                     , cdl_system_reference1
11381                     , cdl_system_reference2
11382                     , cdl_system_reference3
11383                     , cdl_system_reference4
11384                     , cdl_system_reference5 --NEW
11385                     , gl_date
11386                     , org_id
11387                     , unmatched_negative_txn_flag
11388                     , receipt_currency_amount
11389                     , receipt_currency_code
11390                     , receipt_exchange_rate
11391                     , denom_raw_cost
11392                     , denom_currency_code
11393                     , acct_rate_date
11394                     , acct_rate_type
11395                     , acct_exchange_rate
11396                     , acct_raw_cost
11397                     , acct_exchange_rounding_limit
11398                     , attribute_category
11399                     , attribute1
11400                     , attribute2
11401                     , attribute3
11402                     , attribute4
11403                     , attribute5
11404                     , attribute6
11405                     , attribute7
11406                     , attribute8
11407                     , attribute9
11408                     , attribute10
11409                     , orig_exp_txn_reference1
11410                     , orig_user_exp_txn_reference
11411                     , orig_exp_txn_reference2
11412                     , orig_exp_txn_reference3
11413                     , last_update_date
11414                     , last_updated_by
11415                     , creation_date
11416                     , created_by
11417                     , person_id
11418                     , organization_id
11419                     , project_id
11420                     , task_id
11421                     , Vendor_id
11422                     , override_to_organization_id
11423                     , person_business_group_id
11424                     , adjusted_expenditure_item_id --NEW
11425                     , fc_document_type  -- NEW
11426                     , document_type
11427                     , document_distribution_type
11428                     , adjusted_txn_interface_id --NEW
11429                     , sc_xfer_code
11430                     , si_assets_addition_flag
11431                     , net_zero_adjustment_flag
11432                     , cbs_element_id -- Added for CBS Enhancement Bug 16220146
11433                    )
11434                   SELECT
11435                       l_txn_src_tbl(i)
11436                      ,l_user_txn_src_tbl(i)
11437                      ,G_SYSTEM_LINKAGE
11438                      ,l_batch_name_tbl(i)
11439                      ,l_exp_end_date_tbl(i)
11440                      ,l_ei_date_tbl(i)
11441                      ,l_exp_type_tbl(i)
11442                      ,-l_quantity_tbl(i)
11443                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
11444                      ,l_description_tbl(i)
11445                      ,l_txn_status_code_tbl(i)
11446                      ,l_txn_rej_code_tbl(i)
11447                      ,G_REQUEST_ID
11448                      ,l_interface_id_tbl(i)
11449                      ,l_dist_cc_id_tbl(i)
11450                      ,l_acct_pay_cc_id_tbl(i)
11451                      --,l_vendor_id_tbl(i) /*sysref1*/
11452                      ,decode(l_ln_type_lookup_tbl(i),'PREPAY',l_vendor_id_tbl(i),l_pay_hist_id_tbl(i)) /*sysref1*/
11453                      ,l_invoice_id_tbl(i) /*sysref2*/
11454                      ,l_cdl_sys_ref3_tbl(i)/*sysref3*/
11455                      ,l_inv_pay_id_tbl(i)  /*sysref4*/
11456                      ,l_invoice_dist_id_tbl(i) /*sysref5*/ --NEW
11457                      ,l_gl_date_tbl(i)
11458                      ,G_ORG_ID
11459                      ,'Y'
11460                      ,-l_rec_cur_amt_tbl(i)
11461                      ,l_rec_cur_code_tbl(i)
11462                      ,l_rec_conv_rate_tbl(i)
11463                      ,-l_denom_raw_cost_tbl(i)
11464                      ,l_denom_cur_code_tbl(i)
11465                      ,l_acct_rate_date_tbl(i)
11466                      ,l_acct_rate_type_tbl(i)
11467                      ,l_acct_exch_rate_tbl(i)
11468                      ,-l_amount_tbl(i)
11469                      ,1
11470                      ,l_attribute_cat_tbl(i)
11471                      ,l_attribute1_tbl(i)
11472                      ,l_attribute2_tbl(i)
11473                      ,l_attribute3_tbl(i)
11474                      ,l_attribute4_tbl(i)
11475                      ,l_attribute5_tbl(i)
11476                      ,l_attribute6_tbl(i)
11477                      ,l_attribute7_tbl(i)
11478                      ,l_attribute8_tbl(i)
11479                      ,l_attribute9_tbl(i)
11480                      ,l_attribute10_tbl(i)
11481                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
11482                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
11483                      /* bug 2835757*/
11484                      ,DECODE(G_TRANS_DFF_AP,'N',NULL,l_invoice_id_tbl(i)) /*orig_exp_txn_reference2*/
11485                      ,NULL                       /*orig_exp_txn_reference3*/
11486                      ,SYSDATE
11487                      ,-1
11488                      ,SYSDATE
11489                      ,-1
11490                      ,l_employee_id_tbl(i)
11491                      ,l_org_id_tbl(i)
11492                      ,l_project_id_tbl(i)
11493                      ,l_task_id_tbl(i)
11494                      ,l_vendor_id_tbl(i)
11495                      ,l_exp_org_id_tbl(i)
11496                      ,l_bus_grp_id_tbl(i)
11497                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
11498                      ,l_fc_document_type_tbl(i) --NEW for funds check
11499                      ,l_inv_type_code_tbl(i)
11500                      ,l_ln_type_lookup_tbl(i)
11501                      ,(select xface.txn_interface_id
11502                        from   pa_transaction_interface xface
11503                        where  xface.interface_id = l_interface_id_tbl(i)
11504                        and    xface.cdl_system_reference2 = l_invoice_id_tbl(i)
11505                        and    xface.cdl_system_reference4 = to_char(l_inv_pay_id_tbl(i))
11506                        and    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(i)
11507 		       and    NVL(xface.adjusted_expenditure_item_id,0) = 0 ) -- R12 funds management Uptake
11508                      ,'P'
11509                      ,'T' -- l_si_assts_add_flg_tbl(i)
11510                      ,l_net_zero_flag_tbl(i)
11511                      ,l_cbs_element_id_tbl(i) -- Added for CBS Enhancement Bug 16220146
11512                 FROM dual
11513                 WHERE l_insert_flag_tbl(i)= 'A';
11514                -- WHERE l_net_zero_flag_tbl(i)= 'Y';
11515 
11516                -- Handle both the parent and the reversal getting interfaced into PA
11517                -- in the same run.
11518                 write_log(LOG, 'Updating  adjustment records..');
11519               IF l_rev_child_dist_id_tbl.exists(1) THEN
11520                FOR i in l_rev_child_dist_id_tbl.FIRST ..l_rev_child_dist_id_tbl.LAST LOOP
11521                    IF l_rev_child_dist_id_tbl(i) > 0 THEN
11522                     UPDATE pa_transaction_interface_all xface
11523                     SET    xface.net_zero_adjustment_flag ='Y',
11524                            xface.adjusted_txn_interface_id =
11525                               (select distinct  xface1.txn_interface_id /* bug 9266578 */
11526                                from   pa_transaction_interface xface1
11527                                where  xface1.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
11528                                and    xface1.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
11529                                and    xface1.cdl_system_reference4 = to_char(l_inv_pay_id_tbl(l_rev_parent_dist_ind_tbl(i)))
11530                                and    xface1.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
11531                                )
11532                       WHERE  xface.interface_id          = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
11533                       AND    xface.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
11534                       AND    -- For voided payments l_rev_child_dist_id_tbl stores the reversed payment id Bug# 5408748
11535                              -- Here the reversal pair will have same inv dist id and diff payment id's
11536                              ((
11537                              xface.cdl_system_reference4     = To_char(l_rev_child_dist_id_tbl(i))
11538                              AND xface.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
11539                              )
11540                       OR     -- For invoice reversal l_rev_child_dist_id_tbl stores the reversed invoice dist id Bug# 5408748
11541                              -- Here the reversal pair will have same payment id and diff inv dist id's
11542                              (
11543                              xface.cdl_system_reference4     = to_char(l_inv_pay_id_tbl(l_rev_parent_dist_ind_tbl(i)))
11544                              AND xface.cdl_system_reference5 = To_char(l_rev_child_dist_id_tbl(i))
11545                              )) ;
11546                    END IF;
11547                END LOOP;
11548               END IF;
11549 
11550     END IF;
11551    EXCEPTION
11552       WHEN OTHERS THEN
11553           write_log(LOG,'Failed during bulk insert for payment processing');
11554           G_err_code   := SQLCODE;
11555           raise;
11556 
11557    END bulk_insert_trx_intf;
11558 
11559    PROCEDURE process_pay_logic IS
11560 
11561        l_status3 VARCHAR2(30);
11562        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
11563        l_historical_flag VARCHAR(1);  --NEW
11564        l_process_adjustments    Number := 0 ;
11565 	   -- Start: Added for CBS Enhancement Bug 16220146
11566 	   l_actual_task_id       NUMBER := 0;
11567 	   l_cbs_element_id       NUMBER := 0;
11568 	   -- End: Added for CBS Enhancement Bug 16220146
11569 
11570    BEGIN
11571 
11572        G_err_stage := ('Within Calling process logic of transfer_pay_to_pa');
11573        write_log(LOG, G_err_stage);
11574 
11575        /* Initializing global variables here to reduce code lines */
11576        G_NRT_TRANSACTION_SOURCE      := 'AP NRTAX' ;
11577        G_NRT_USER_TRANSACTION_SOURCE := 'Non-Recoverable Tax From Payables';
11578 
11579        G_AP_VAR_TRANSACTION_SOURCE  := 'AP VARIANCE';
11580        G_AP_VAR_USER_TXN_SOURCE     := 'Oracle Payables Invoice Variance';
11581 
11582 
11583        G_AP_ERV_TRANSACTION_SOURCE  := 'AP ERV';         --NEW bug 5372603
11584        G_AP_ERV_USER_TXN_SOURCE     := 'Oracle Payables Supplier Cost Exchange Rate Variance';  --NEW bug 5372603
11585 
11586 
11587        j := v_last_inv_index; -- initialize j to the total invoice distributions fetched in the PLSQL array
11588 
11589 
11590        FOR i IN  l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST  LOOP
11591 
11592            write_log(LOG,'Processing invoice id:  '||l_invoice_id_tbl(i)|| 'dist id:  '||l_invoice_dist_id_tbl(i));
11593 
11594            G_TRANSACTION_REJECTION_CODE := '';
11595 
11596            IF l_source_tbl(i) in ('CREDIT CARD','Both Pay') THEN
11597 
11598               write_log(LOG,'This is a credit card txn, setting emp id to paid_emp_id.');
11599               l_employee_id_tbl(i)   := l_paid_emp_id_tbl(i);
11600               l_inv_type_code_tbl(i) := 'EXPENSE REPORT';
11601 
11602            ELSIF l_inv_type_code_tbl(i) = 'EXPENSE REPORT' and l_employee_id_tbl(i) is null THEN
11603               write_log(LOG,'This is a CWK Exp Report, setting emp id to paid_emp_id.');
11604               l_employee_id_tbl(i)   := l_paid_emp_id_tbl(i);
11605 
11606            END IF;
11607 
11608 		   -- Start: Added for CBS Enhancement Bug 16220146
11609 		   IF l_project_id_tbl(i) is not null and l_task_id_tbl(i) IS NOT NULL THEN
11610 
11611 			  IF PA_ALTERNATE_TASK_PVT.Is_Cbs_Enabled(l_project_id_tbl(i)) = 'Y' THEN
11612 
11613 			     BEGIN
11614 
11615 				    SELECT PROJ_ELEMENT_ID, CBS_ELEMENT_ID
11616 					INTO l_actual_task_id, l_cbs_element_id
11617 					FROM PA_ALTERNATE_TASKS
11618 					WHERE alt_task_id = l_task_id_tbl(i);
11619 
11620 				EXCEPTION
11621 				   WHEN OTHERS THEN
11622 				      l_cbs_element_id_tbl(i) := NULL;
11623 				      RAISE;
11624 				END;
11625 
11626 				l_task_id_tbl(i) := l_actual_task_id;
11627 				l_cbs_element_id_tbl(i) := l_cbs_element_id;
11628 			  ELSE
11629 			     l_cbs_element_id_tbl(i) := NULL;
11630 			  END IF;
11631 		   ELSE
11632 		      l_cbs_element_id_tbl(i) := NULL;
11633 		   END IF;
11634 		   -- End: Added for CBS Enhancement Bug 16220146
11635 
11636            /* The following will be executed if the distribution being fetched belongs to a new invoice */
11637            IF (l_invoice_id_tbl(i) <> v_prev_invoice_id) THEN
11638 
11639                G_err_stage := ('New invoice being processed.New invoice _id is:'||l_invoice_id_tbl(i));
11640                write_log(LOG, G_err_stage);
11641 
11642                /* Update the previous invoice id and vendor id*/
11643                v_prev_invoice_id := l_invoice_id_tbl(i);
11644                v_prev_vendor_id  := l_vendor_id_tbl(i);
11645 
11646                /* Increment the counter for invoices */
11647                v_num_invoices_fetched := v_num_invoices_fetched + 1;
11648 
11649                IF nvl(v_prev_invoice_source,l_source_tbl(i)||'111') <> l_source_tbl(i) THEN
11650 
11651                   /* First update the v_prev_invoice_source */
11652                   G_err_stage := 'New source encountered';
11653                   write_log(LOG, G_err_stage);
11654                   v_prev_invoice_source := l_source_tbl(i);
11655 
11656 
11657                   IF l_source_tbl(i) = 'PA_IP_INVOICES' THEN
11658 
11659                      G_err_stage := 'Invoice source is Inter-Company Invoice';
11660                      write_log(LOG, G_err_stage);
11661                      G_TRANSACTION_SOURCE      := 'INTERPROJECT_AP_INVOICES';
11662                      v_prev_transaction_source := G_TRANSACTION_SOURCE;
11663                      G_USER_TRANSACTION_SOURCE := 'Oracle Inter-Project Invoices';
11664 
11665                      L_IP_TRANSACTION_SOURCE      := 'INTERPROJECT_AP_INVOICES';
11666                      l_ip_inv_flag                    := 'Y' ;
11667 
11668                   ELSIF (l_source_tbl(i)        = 'XpenseXpress' OR
11669                          /* if its a Credit card txn, treat like expense report*/
11670                          l_source_tbl(i) in ('CREDIT CARD','Both Pay') OR
11671                         (l_source_tbl(i)        = 'Manual Invoice Entry' AND
11672                          l_inv_type_code_tbl(i) = 'EXPENSE REPORT') OR
11673                          l_source_tbl(i)        = 'SelfService') THEN
11674 
11675                       G_err_stage := 'Invoice source is Expense Reports';
11676                       write_log(LOG, G_err_stage);
11677                       G_TRANSACTION_SOURCE      := 'AP EXPENSE';
11678                       v_prev_transaction_source := G_TRANSACTION_SOURCE;
11679                       G_USER_TRANSACTION_SOURCE := 'ORACLE PAYABLES';
11680 
11681                   ELSE
11682 
11683                       G_err_stage := 'Invoice source is AP Invoice';
11684                       write_log(LOG, G_err_stage);
11685                       G_TRANSACTION_SOURCE             := 'AP INVOICE';
11686                       v_prev_transaction_source := G_TRANSACTION_SOURCE;
11687 
11688                       G_USER_TRANSACTION_SOURCE        := 'AP INVOICE';
11689                       l_ap_inv_flag                    := 'Y' ;
11690 
11691                   END IF;
11692 
11693                END IF; /* invoice source <> v_prev_tranasction_source */
11694 
11695                 /* For new invoice, initialize the transaction status code to 'P' */
11696                 G_TRANSACTION_STATUS_CODE := 'P';
11697 
11698                 G_err_stage := 'GET MAX EXPENDITURE ENDING DATE';
11699                 write_log(LOG, G_err_stage);
11700 /* Bug 5051103 - replace expnediture_item_date with l_ei_date_tbl(i) */
11701                 SELECT pa_utils.getweekending(MAX(l_ei_date_tbl(i)))
11702                   INTO G_EXPENDITURE_ENDING_DATE
11703                   FROM ap_invoice_distributions
11704                  WHERE invoice_id = l_invoice_id_tbl(i);
11705 
11706                 G_err_stage := ('Getting bus group id');
11707                 write_log(LOG, G_err_stage);
11708 
11709                 BEGIN
11710 
11711                    IF l_employee_id_tbl(i) <> 0 THEN
11712             		   Begin
11713                                   write_log(LOG,'getting bus group id with emp id of :  '||l_employee_id_tbl(i));
11714 
11715                                   SELECT emp.business_group_id
11716                                     INTO G_PER_BUS_GRP_ID
11717                                     FROM per_all_people_f emp
11718                                    WHERE emp.person_id = l_employee_id_tbl(i)
11719                                       AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and trunc(emp.effective_end_date);
11720 
11721             			EXCEPTION
11722             			   WHEN NO_DATA_FOUND THEN
11723             			      l_txn_status_code_tbl(i)     := 'R';
11724             			      G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
11725             			      write_log(LOG, 'As no data found for Employee, Rejecting invoice'||l_invoice_id_tbl(i)  );
11726              		    End;
11727 		            Else
11728 		    Begin
11729 
11730 			    select org2.business_group_id
11731                               into G_PER_BUS_GRP_ID
11732 			      from hr_organization_units org1,
11733 				   hr_organization_units org2
11734 			     Where org1.organization_id = l_exp_org_id_tbl(i)
11735 			       and org1.business_group_id = org2.organization_id ;
11736 
11737 			    Exception
11738 			      When no_data_found Then
11739 				G_TRANSACTION_STATUS_CODE := 'R';
11740 				G_TRANSACTION_REJECTION_CODE := 'INVALID_ORGANIZATION';
11741 				write_log(LOG,'As no data found for Organization,Rejecting invoice '||l_invoice_id_tbl(i)  );
11742 		     End;
11743         	END IF;   /* IF l_employee_id_tbl(i) <> 0 THEN  */
11744 
11745                 END;
11746 
11747            END IF; /* end of check for different invoice_id from previous invoice_id */
11748 
11749 
11750            /* The following will be executed when the distribution belongs to the same
11751               invoice or not the same invoice */
11752 
11753            v_num_distributions_fetched := v_num_distributions_fetched + 1;
11754            write_log(LOG,'Num of distributions fetched:'||v_num_distributions_fetched);
11755 
11756            /*Update counter of how many distributions of the last invoice of the batch has been processed*/
11757 
11758            IF l_invoice_id_tbl(i) = l_invoice_id_tbl(v_last_inv_index) THEN
11759               v_num_last_invoice_processed := v_num_last_invoice_processed +1;
11760 
11761               IF l_inv_type_code_tbl(i) = 'EXPENSE REPORT' THEN
11762                  v_last_inv_ER_flag := 'Y';
11763               ELSE
11764                  v_last_inv_ER_flag := 'N';
11765               END IF;
11766 
11767            END IF;
11768 
11769 
11770            -- FC Doc Type
11771 
11772             IF l_fc_enabled_tbl(i) = 'N' THEN
11773              l_fc_document_type_tbl(i) := 'NOT';
11774             END IF;
11775 
11776            /* if the invoice is an expense report from self-service we need to use the column of justification as the description */
11777            IF (l_inv_type_code_tbl(i) = 'EXPENSE REPORT' AND
11778                l_source_tbl(i)        in ('SelfService','XpenseXpress') ) THEN
11779                l_description_tbl(i) := l_justification_tbl(i);
11780            END IF;
11781 
11782            IF l_ln_type_lookup_tbl(i)  in ('NONREC_TAX','TRV','TIPV') THEN
11783 
11784               /* Update counter for number of tax lines fetched */
11785               v_num_tax_lines_fetched := v_num_tax_lines_fetched +1;
11786 
11787         	l_quantity_tbl(i)     := 0;   --for bug 9979559
11788 
11789               l_txn_src_tbl(i)      := G_NRT_TRANSACTION_SOURCE;
11790               l_user_txn_src_tbl(i) := G_NRT_USER_TRANSACTION_SOURCE;
11791 
11792               IF l_prepay_dist_id_tbl(i) is not null THEN -- tax associated with prepay application Bug#5514129
11793                 l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
11794                 l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
11795                 l_ap_prepay_tax_flag := 'Y';
11796               ELSE
11797                 l_batch_name_tbl(i)   := G_NRT_BATCH_NAME;
11798                 l_interface_id_tbl(i) := G_NRT_INTERFACE_ID;
11799               END IF;
11800 
11801            ELSIF l_ln_type_lookup_tbl(i) = 'IPV' THEN
11802 
11803               /* Update counter for number of variance lines fetched */
11804               v_num_inv_variance_fetched :=  v_num_inv_variance_fetched +1;
11805 
11806               l_quantity_tbl(i)     := 0; --l_denom_raw_cost_tbl(i); --for bug 9979559
11807 
11808               l_txn_src_tbl(i)      := G_AP_VAR_TRANSACTION_SOURCE;
11809               l_user_txn_src_tbl(i) := G_AP_VAR_USER_TXN_SOURCE;
11810 
11811               IF l_prepay_dist_id_tbl(i) is not null THEN -- associated with prepay application Bug#5514129
11812                 l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
11813                 l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
11814                 l_ap_prepay_var_flag := 'Y';
11815               ELSE
11816                 l_batch_name_tbl(i)   := G_AP_VAR_BATCH_NAME;
11817                 l_interface_id_tbl(i) := G_AP_VAR_INTERFACE_ID;
11818               END IF;
11819 
11820            ELSIF l_ln_type_lookup_tbl(i) in ('ERV','TERV') THEN
11821               /* Update counter for number of variance lines fetched */
11822               v_num_inv_erv_fetched :=  v_num_inv_erv_fetched +1;
11823 
11824               l_quantity_tbl(i)     := 0; --l_denom_raw_cost_tbl(i); --for bug 9979559
11825               l_txn_src_tbl(i)      := G_AP_ERV_TRANSACTION_SOURCE;
11826               l_user_txn_src_tbl(i) := G_AP_ERV_USER_TXN_SOURCE;
11827 
11828               IF l_prepay_dist_id_tbl(i) is not null THEN -- associated with prepay application Bug#5514129
11829                 l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
11830                 l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
11831                 l_ap_prepay_erv_flag := 'Y';
11832               ELSE
11833                 l_batch_name_tbl(i)   := G_AP_ERV_BATCH_NAME;
11834                 l_interface_id_tbl(i) := G_AP_ERV_INTERFACE_ID;
11835               END IF;
11836 
11837            ELSIF  l_ln_type_lookup_tbl(i) in ('FREIGHT','MISCELLANEOUS') THEN
11838               /* Update counter for number of frt and misc lines fetched */
11839               v_num_inv_frt_fetched :=  v_num_inv_frt_fetched +1;
11840 
11841               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
11842               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
11843               IF l_prepay_dist_id_tbl(i) is not null THEN -- associated with prepay application Bug#5514129
11844                 l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
11845                 l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
11846               ELSE
11847                 l_batch_name_tbl(i)   := G_AP_FRT_BATCH_NAME;
11848                 l_interface_id_tbl(i) := G_AP_FRT_INTERFACE_ID;
11849               END IF;
11850 
11851            ELSIF  l_ln_type_lookup_tbl(i) in ('PREPAY') THEN
11852 
11853               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
11854               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
11855               l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
11856               l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
11857 
11858            ELSE -- Other distribution types like ITEM,ACCRUAL etc
11859 
11860               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
11861               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
11862               l_batch_name_tbl(i)   := G_BATCH_NAME;
11863               l_interface_id_tbl(i) := G_INTERFACE_ID;
11864 
11865            END IF ;
11866 
11867            G_TRANSACTION_REJECTION_CODE := '';
11868 
11869            /*Setting values according to global variables*/
11870            l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
11871            l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
11872            l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
11873            l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
11874 
11875            write_log(LOG,'Value of l_txn_src_tbl:'||l_txn_src_tbl(i) ||'batch name:'||l_batch_name_tbl(i));
11876 
11877            /* In Rel12 we will not interface any PREPAYMENT PAYMENTS to Oracle Projects */
11878            --
11879            /* The records with INSERT_FLAG = F indicate that they are fully applied prepayments and the pa-addition-flag
11880               for such records will be updated to G to relieve commitments*/
11881            /* The records with INSERT_FLAG = P indicate that they are partially applied prepayments and the pa-addition-flag
11882               for such records will be updated to N */
11883 
11884            IF (l_inv_type_code_tbl(i) = 'PREPAYMENT' ) THEN
11885 
11886 write_log(LOG,' l_ln_type_lookup_tbl(i) '||l_ln_type_lookup_tbl(i)||' l_prepay_dist_id_tbl '||l_prepay_dist_id_tbl(i)||' l_is_self_assessed_tax_tbl '||l_is_self_assessed_tax_tbl(i));
11887 
11888               IF check_prepay_fully_applied(l_invoice_dist_id_tbl(i), l_is_self_assessed_tax_tbl(i)) = 'Y' THEN -- Bug 13602288: Self Assessed Tax Changes
11889                  l_insert_flag_tbl(i) := 'F';
11890               ELSE
11891                  l_insert_flag_tbl(i) := 'P';
11892               END IF;
11893 
11894            ELSE
11895 
11896            -- REVERSED DISTRIBUTIONS INTERFACE LOGIC
11897            -- If the distribution is a reversal or cancellation then check if the parent reversal distribution
11898            -- was historical data or not. If data is historical, reversal distribution line will be interfaced as is.
11899            --
11900            -- However if the parent reversal distribution is not historical then the following steps happen:
11901            -- a) Retreive the latest adjusted expenditures from PA against the parent reversal distribution id
11902            -- b) If any of the above latest EI's are not costed, then the reversed distribution will be rejected by the
11903            --    TRX import program
11904            -- c) IF all above adjusted EI's are costed, then insert record into the interface table for each adjusted EI.
11905            --    The project attributes will be copied from the adjusted EI's instead from the AP reversed
11906            --    distribution since these could have changed in PA.
11907            -- d) The interface program will interface the reversed distribution into projects
11908            -- e) The interface program will also insert a reversal of the reversed distribution into Projects. This is
11909            --    required for account reconciliation
11910            --
11911 
11912          -- This logic is to handle both the parent and reversal getting interfaced in the same run.
11913           -- It's a reversed parent record. Bug#4590527
11914           -- If both the parent and child reversing each other are interfaced in the same run, they
11915           -- were not getting interfaced as netzero transactions.
11916 
11917            IF (l_reversal_flag_tbl(i) in ('Y','R') or l_cancel_flag_tbl(i) = 'Y')
11918                                  AND l_parent_pmt_id_tbl(i) IS NULL THEN
11919 
11920               l_rev_index := l_rev_index +1;
11921               IF l_reversal_flag_tbl(i) = 'Y' THEN
11922                 write_log(LOG, 'Reversal parent record '||l_inv_pay_id_tbl(i));
11923                 l_rev_parent_dist_id_tbl(l_rev_index) :=  l_inv_pay_id_tbl(i);
11924               ELSE
11925 
11926                 -- The Reversal flag with value R indicates that the invoice distribution has been reversed
11927                 -- Refer to Bug#5408748
11928 
11929                 write_log(LOG, 'Reversal parent record for Invoice Dist reversals'||l_invoice_dist_id_tbl(i));
11930                 l_rev_parent_dist_id_tbl(l_rev_index) :=  l_invoice_dist_id_tbl(i);
11931               END IF;
11932 
11933               l_rev_child_dist_id_tbl(l_rev_index) :=  null;
11934               l_rev_parent_dist_ind_tbl(l_rev_index) :=  i; -- store the index of the parent.
11935 
11936            END IF;
11937 
11938            IF l_reversal_flag_tbl(i) in ('Y','R')  and l_parent_pmt_id_tbl(i) is not null THEN
11939 
11940 -- check if reversal flag is populated for prepayment appl
11941 
11942                   -- Call reversal API
11943                   Process_Adjustments(p_record_type  => 'AP_PAYMENT',
11944                                       p_document_header_id  => l_invoice_id_tbl(i) ,/*Added this for 6945767 */
11945                                       p_document_distribution_id  => l_invoice_dist_id_tbl(i),
11946                                       p_document_payment_id       => l_parent_pmt_id_tbl(i),
11947                                       p_current_index             => i,
11948 				      p_last_index                => j);
11949 
11950                       -- Set the create flag for adjustment records
11951                          IF l_insert_flag_tbl(i) in ('A','U') THEN
11952                           l_create_adj_recs := 'Y';
11953                          END IF;
11954 
11955            END IF; --End of check for reversal Distribution
11956 
11957            G_err_stage := ('Value of G_TRANS_DFF_AP:'||G_TRANS_DFF_AP);
11958            write_log(LOG, G_err_stage);
11959 
11960            IF (G_TRANS_DFF_AP = 'Y') THEN
11961 
11962                 v_attribute_category := l_attribute_cat_tbl(i);
11963                 v_attribute1 := l_attribute1_tbl(i);
11964                 v_attribute2 := l_attribute2_tbl(i);
11965                 v_attribute3 := l_attribute3_tbl(i);
11966                 v_attribute4 := l_attribute4_tbl(i);
11967                 v_attribute5 := l_attribute5_tbl(i);
11968                 v_attribute6 := l_attribute6_tbl(i);
11969                 v_attribute7 := l_attribute7_tbl(i);
11970                 v_attribute8 := l_attribute8_tbl(i);
11971                 v_attribute9 := l_attribute9_tbl(i);
11972                 v_attribute10 := l_attribute10_tbl(i);
11973 
11974                 v_dff_map_status := NULL;
11975 
11976                 PA_CLIENT_EXTN_DFFTRANS.DFF_map_segments_PA_and_AP(
11977                    p_calling_module            => 'PAAPIMP',
11978                    p_trx_ref_1                 => l_invoice_id_tbl(i),
11979                    --p_trx_ref_2                 => l_dist_line_num_tbl(i),
11980                    p_trx_ref_2                 => l_invoice_dist_id_tbl(i),  --NEW
11981                    p_trx_type                  => l_inv_type_code_tbl(i),
11982                    p_system_linkage_function   => G_SYSTEM_LINKAGE,
11983                    p_submodule                 => l_source_tbl(i),
11984                    p_expenditure_type          => l_exp_type_tbl(i),
11985                    p_set_of_books_id           => G_AP_SOB,
11986                    p_org_id                    => l_org_id_tbl(i),
11987                    p_attribute_category        => v_attribute_category,
11988                    p_attribute_1               => v_attribute1,
11989                    p_attribute_2               => v_attribute2,
11990                    p_attribute_3               => v_attribute3,
11991                    p_attribute_4               => v_attribute4,
11992                    p_attribute_5               => v_attribute5,
11993                    p_attribute_6               => v_attribute6,
11994                    p_attribute_7               => v_attribute7,
11995                    p_attribute_8               => v_attribute8,
11996                    p_attribute_9               => v_attribute9,
11997                    p_attribute_10              => v_attribute10,
11998                    x_status_code               => v_dff_map_status);
11999 
12000                    IF (v_dff_map_status IS NOT NULL) THEN
12001 
12002                        write_log(LOG, 'Error in DFF_map_segments_PA_and_AP, Error Code: ' || v_dff_map_status);
12003                        raise dff_map_exception;
12004 
12005                    END IF;
12006 
12007                    l_attribute_cat_tbl(i) := v_attribute_category;
12008                    l_attribute1_tbl(i) := v_attribute1;
12009                    l_attribute2_tbl(i) := v_attribute2;
12010                    l_attribute3_tbl(i) := v_attribute3;
12011                    l_attribute4_tbl(i) := v_attribute4;
12012                    l_attribute5_tbl(i) := v_attribute5;
12013                    l_attribute6_tbl(i) := v_attribute6;
12014                    l_attribute7_tbl(i) := v_attribute7;
12015                    l_attribute8_tbl(i) := v_attribute8;
12016                    l_attribute9_tbl(i) := v_attribute9;
12017                    l_attribute10_tbl(i) := v_attribute10;
12018 
12019 	   ElSE /* if DFF profile is No. Added for Bug 3105153*/
12020                    l_attribute_cat_tbl(i) := NULL;     --Bug#3856390
12021                    l_attribute1_tbl(i) := NULL;
12022                    l_attribute2_tbl(i) := NULL;
12023                    l_attribute3_tbl(i) := NULL;
12024                    l_attribute4_tbl(i) := NULL;
12025                    l_attribute5_tbl(i) := NULL;
12026                    l_attribute6_tbl(i) := NULL;
12027                    l_attribute7_tbl(i) := NULL;
12028                    l_attribute8_tbl(i) := NULL;
12029                    l_attribute9_tbl(i) := NULL;
12030                    l_attribute10_tbl(i) := NULL;
12031 
12032 	   END IF; /* if DFF profile is Yes */
12033 
12034         END IF; /* if inv type is PREPAYMENT */
12035 
12036       END LOOP; /* End of looping through each record in plsql table */
12037 
12038    EXCEPTION
12039       WHEN OTHERS THEN
12040           write_log(LOG,'Failed during process_pay_logic');
12041           G_err_code   := SQLCODE;
12042           raise;
12043 
12044    END process_pay_logic;
12045 
12046    BEGIN
12047    /* Main Procedure Logic starts here */
12048 
12049    G_err_stage := 'Within main procedure of transfer_pay_to_pa';
12050    write_log(LOG, G_err_stage);
12051 
12052      write_log(LOG, '......Result of G_TRANSACTION_SOURCE: ' || G_TRANSACTION_SOURCE);
12053 
12054      v_max_size := nvl(G_COMMIT_SIZE,200);
12055 
12056      -- Create a new interface ID for the first session
12057 
12058      OPEN Payments_Cur;
12059 
12060      G_err_stage := 'After opening Payments_Cur within transfer_pay_to_pa';
12061      write_log(LOG, G_err_stage);
12062 
12063      WHILE (v_all_done = 0) LOOP
12064 
12065        clear_plsql_tables;
12066 
12067        --Creating new interface ID every time this is called
12068        G_err_stage := 'CREATING NEW INTERFACE ID';
12069        write_log(LOG, G_err_stage);
12070 
12071        SELECT pa_interface_id_s.nextval
12072          INTO G_INTERFACE_ID
12073          FROM dual;
12074 
12075        G_err_stage := 'CREATING NEW NRT INTERFACE ID';
12076        SELECT pa_interface_id_s.nextval
12077          into G_NRT_INTERFACE_ID
12078          FROM dual;
12079 
12080        G_err_stage := 'CREATING NEW FRT INTERFACE ID';
12081        SELECT pa_interface_id_s.nextval
12082          into G_AP_FRT_INTERFACE_ID
12083          FROM dual;
12084 
12085        G_err_stage := 'CREATING NEW VARIANCE INTERFACE ID';
12086        SELECT pa_interface_id_s.nextval
12087          into G_AP_VAR_INTERFACE_ID
12088          FROM dual;
12089 
12090        G_err_stage := 'CREATING NEW ERV VARIANCE INTERFACE ID';
12091        SELECT pa_interface_id_s.nextval
12092          into G_AP_ERV_INTERFACE_ID
12093          FROM dual;
12094 
12095           FETCH Payments_Cur BULK COLLECT INTO
12096              l_inv_pay_id_tbl,
12097              l_invoice_id_tbl,
12098              l_created_by_tbl,
12099              l_invoice_dist_id_tbl,
12100              l_cdl_sys_ref3_tbl,
12101              l_project_id_tbl,
12102              l_task_id_tbl,
12103              l_ln_type_lookup_tbl,
12104              l_exp_type_tbl,
12105              l_ei_date_tbl,
12106              l_amount_tbl,
12107              l_description_tbl,
12108              l_justification_tbl,
12109              l_dist_cc_id_tbl,
12110              l_exp_org_id_tbl,
12111              l_quantity_tbl,
12112              l_acct_pay_cc_id_tbl,
12113              l_gl_date_tbl,
12114              l_attribute_cat_tbl,
12115              l_attribute1_tbl,
12116              l_attribute2_tbl,
12117              l_attribute3_tbl,
12118              l_attribute4_tbl,
12119              l_attribute5_tbl,
12120              l_attribute6_tbl,
12121              l_attribute7_tbl,
12122              l_attribute8_tbl,
12123              l_attribute9_tbl,
12124              l_attribute10_tbl,
12125              l_rec_cur_amt_tbl,
12126              l_rec_cur_code_tbl,
12127              l_rec_conv_rate_tbl,
12128              l_denom_raw_cost_tbl,
12129              l_denom_cur_code_tbl,
12130              l_acct_rate_date_tbl,
12131              l_acct_rate_type_tbl,
12132              l_acct_exch_rate_tbl,
12133              l_job_id_tbl,
12134              l_employee_id_tbl,
12135              l_vendor_id_tbl,
12136              l_inv_type_code_tbl,
12137              l_source_tbl,
12138              l_org_id_tbl,
12139              l_invoice_num_tbl,
12140              l_cdl_sys_ref4_tbl,
12141              l_po_dist_id_tbl
12142             ,l_txn_src_tbl
12143             ,l_user_txn_src_tbl
12144             ,l_batch_name_tbl
12145             ,l_interface_id_tbl
12146             ,l_exp_end_date_tbl
12147             ,l_txn_status_code_tbl
12148             ,l_txn_rej_code_tbl
12149             ,l_bus_grp_id_tbl
12150             ,l_paid_emp_id_tbl
12151             ,l_sort_var_tbl
12152             ,l_reversal_flag_tbl --NEW
12153             ,l_cancel_flag_tbl --NEW
12154             ,l_parent_pmt_id_tbl --NEW
12155             ,l_net_zero_flag_tbl  --NEW
12156             ,l_sc_xfer_code_tbl
12157             ,l_adj_exp_item_id_tbl --NEW
12158             ,l_fc_enabled_tbl  --NEW
12159             ,l_mrc_exchange_date_tbl
12160             ,l_fc_document_type_tbl
12161             ,l_payment_status_flag_tbl
12162             ,l_si_assts_add_flg_tbl
12163             ,l_insert_flag_tbl
12164             ,l_pay_hist_id_tbl
12165             ,l_prepay_dist_id_tbl   --bug#5514129
12166             LIMIT v_max_size;
12167 
12168          G_err_stage := 'After fetching Payments_Cur within transfer_pay_to_pa';
12169          write_log(LOG, G_err_stage);
12170 
12171          IF l_invoice_id_tbl.COUNT <> 0 THEN
12172 
12173             /* get the index of the last invoice being processed within the batch*/
12174             v_last_inv_index := l_invoice_id_tbl.LAST;
12175 
12176             G_err_stage := 'calling process_pay_logic within transfer_pay_to_pa';
12177             write_log(LOG, G_err_stage);
12178 
12179             process_pay_logic;
12180 
12181             G_err_stage := 'calling bulk_update_trx_intf within transfer_pay_to_pa';
12182             write_log(LOG, G_err_stage);
12183 
12184             bulk_update_trx_intf; --Update Prepayment trx
12185 
12186             G_err_stage := 'calling bulk_insert_trx_intf within transfer_pay_to_pa';
12187             write_log(LOG, G_err_stage);
12188 
12189             bulk_insert_trx_intf;
12190 
12191             G_err_stage := 'After calling bulk_insert_trx_intf within transfer_pay_to_pa';
12192             write_log(LOG, G_err_stage);
12193 
12194             G_err_stage := 'Before calling transaction import and tiebacks within transfer_pay_to_pa';
12195             write_log(LOG, G_err_stage);
12196 
12197             IF (v_num_distributions_fetched > 0) THEN
12198 
12199                v_inv_batch_size           := v_num_distributions_fetched - v_num_tax_lines_fetched -
12200                                              v_num_inv_variance_fetched - v_num_inv_frt_fetched;
12201 
12202               write_log(LOG,'Before calling trx_import for invoices with interface_id:'||G_INTERFACE_ID);
12203               --Logic to handle IP and AP INVOICES getting interfaced in the same run.Bug#4764470.
12204 
12205              IF (l_ap_inv_flag ='Y' ) THEN
12206 
12207               trans_import('AP INVOICE', G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
12208               tieback_payment_AP_ER('AP INVOICE', G_BATCH_NAME,'PAY', G_INTERFACE_ID);
12209 
12210              END IF;
12211 
12212              IF (l_ip_inv_flag ='Y' ) THEN
12213 
12214               trans_import(L_IP_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
12215               tieback_payment_AP_ER(L_IP_TRANSACTION_SOURCE, G_BATCH_NAME,'PAY', G_INTERFACE_ID);
12216 
12217              ELSIF (l_ap_inv_flag ='N') THEN
12218 
12219               trans_import(G_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
12220               tieback_payment_AP_ER(G_TRANSACTION_SOURCE, G_BATCH_NAME,'PAY', G_INTERFACE_ID);
12221 
12222              END IF;
12223               --End of logic to handle IP and AP INVOICES getting interfaced in the same run.Bug#4764470.
12224 
12225               IF (nvl(v_num_tax_lines_fetched,0) > 0 AND
12226                      (G_INVOICE_TYPE IS NULL OR G_INVOICE_TYPE = 'EXPENSE REPORT')) THEN
12227 
12228                   write_log(LOG,'Before calling trx_import for NRTAX for interface_id:'||G_NRT_INTERFACE_ID);
12229                   v_tax_batch_size           := v_num_tax_lines_fetched;
12230 
12231                   trans_import(G_NRT_TRANSACTION_SOURCE, G_NRT_BATCH_NAME, G_NRT_INTERFACE_ID, G_USER_ID);
12232                   tieback_payment_AP_ER(G_NRT_TRANSACTION_SOURCE, G_NRT_BATCH_NAME,'PAY', G_NRT_INTERFACE_ID);
12233 
12234               END IF; /* IF (nvl(v_num_tax_lines_fetched,0) > 0*/
12235 
12236               IF (nvl(v_num_inv_variance_fetched,0) > 0) THEN
12237 
12238                   write_log(LOG,'Before calling trx_import for Variance for interface_id:'||G_AP_VAR_INTERFACE_ID);
12239                   v_var_batch_size           := v_num_inv_variance_fetched;
12240 
12241                   trans_import(G_AP_VAR_TRANSACTION_SOURCE, G_AP_VAR_BATCH_NAME, G_AP_VAR_INTERFACE_ID, G_USER_ID);
12242                   tieback_payment_AP_ER(G_AP_VAR_TRANSACTION_SOURCE, G_AP_VAR_BATCH_NAME,'PAY', G_AP_VAR_INTERFACE_ID);
12243 
12244               END IF; /* IF (nvl(v_num_inv_variance_lines_fetched,0) > 0*/
12245 
12246               IF (nvl(v_num_inv_erv_fetched,0) > 0) THEN
12247 
12248                   write_log(LOG,'Before calling trx_import for ERV for interface_id:'||G_AP_VAR_INTERFACE_ID);
12249                   v_var_batch_size           := v_num_inv_erv_fetched;
12250 
12251                   trans_import(G_AP_ERV_TRANSACTION_SOURCE, G_AP_ERV_BATCH_NAME, G_AP_ERV_INTERFACE_ID, G_USER_ID);
12252                   tieback_payment_AP_ER(G_AP_ERV_TRANSACTION_SOURCE, G_AP_ERV_BATCH_NAME,'PAY', G_AP_ERV_INTERFACE_ID);
12253 
12254               END IF; /* IF (nvl(v_num_inv_erv_lines_fetched,0) > 0*/
12255 
12256               IF (nvl(v_num_inv_frt_fetched,0) > 0) THEN
12257 
12258                   write_log(LOG,'Before calling trx_import for Frt and Misc for interface_id:'||G_AP_FRT_INTERFACE_ID);
12259                   v_frt_batch_size           := v_num_inv_frt_fetched;
12260 
12261                   trans_import(G_TRANSACTION_SOURCE, G_AP_FRT_BATCH_NAME, G_AP_FRT_INTERFACE_ID, G_USER_ID);
12262                   tieback_payment_AP_ER(G_TRANSACTION_SOURCE, G_AP_FRT_BATCH_NAME, 'PAY',G_AP_FRT_INTERFACE_ID);
12263 
12264               END IF; /* IF (nvl(v_num_inv_frt_lines_fetched,0) > 0*/
12265 
12266               G_err_stage := 'Before updating the total number of payments processed';
12267               write_log(LOG, G_err_stage);
12268 
12269               G_NUM_BATCHES_PROCESSED       := G_NUM_BATCHES_PROCESSED + 1;
12270               G_NUM_INVOICES_PROCESSED      :=  G_NUM_INVOICES_PROCESSED + v_num_invoices_fetched;
12271               G_NUM_DISTRIBUTIONS_PROCESSED :=  G_NUM_DISTRIBUTIONS_PROCESSED + v_num_distributions_fetched;
12272               write_log(LOG,'G_NUM_BATCHES_PROCESSED:'||G_NUM_BATCHES_PROCESSED);
12273               write_log(LOG,'G_NUM_INVOICES_PROCESSED:'||G_NUM_INVOICES_PROCESSED);
12274               write_log(LOG,'G_NUM_DISTRIBUTIONS_PROCESSED:'||G_NUM_DISTRIBUTIONS_PROCESSED);
12275 
12276         END IF; /* IF (v_num_distributions_fetched > 0) */
12277 
12278         G_err_stage := 'After calling transaction import and tiebacks within transfer_pay_to_pa';
12279         write_log(LOG, G_err_stage);
12280 
12281         clear_plsql_tables;
12282 
12283         v_num_invoices_fetched       :=0;
12284         v_num_distributions_fetched  :=0;
12285         v_num_tax_lines_fetched      :=0;
12286         v_inv_batch_size             :=0;
12287         v_tax_batch_size             :=0;
12288         v_var_batch_size             :=0;
12289         v_frt_batch_size             :=0;
12290         v_num_dist_remain            :=0;
12291         v_num_dist_marked_O          :=0;
12292         v_num_last_invoice_processed :=0;
12293         v_last_inv_ER_flag           := 'N';
12294 
12295         G_err_stage:='Before exiting when Payments_Cur is NOTFOUND';
12296         write_log(LOG,   G_err_stage);
12297 
12298       ELSE
12299 
12300           G_err_stage:='Payments Cursor fetched zero rows into plsql tables. Exiting';
12301           write_log(LOG,   G_err_stage);
12302           EXIT;
12303       END IF; /* l_invoice_id_tbl.COUNT = 0 */
12304 
12305       G_err_stage:='Cursor fetched no more rows. Exiting';
12306       write_log(LOG,   G_err_stage);
12307       EXIT WHEN Payments_Cur%NOTFOUND;
12308 
12309    END LOOP; /* While more rows to process is true */
12310 
12311    CLOSE Payments_Cur;
12312 
12313 
12314      /*=====================================================*/
12315      /* PRocess Prepayment Application */
12316      /*=====================================================*/
12317 
12318      -- Create a new interface ID for the first session
12319 
12320      G_err_stage := 'Before  opening Prepay_Cur within transfer_pay_to_pa';
12321      write_log(LOG, G_err_stage);
12322 
12323      OPEN Prepay_Cur;
12324 
12325      G_err_stage := 'After opening Prepay_Cur within transfer_pay_to_pa';
12326      write_log(LOG, G_err_stage);
12327 
12328      WHILE (v_all_done = 0) LOOP
12329 
12330        clear_plsql_tables;
12331 
12332        G_err_stage := 'CREATING NEW PREPAYMENT INTERFACE ID';
12333        SELECT pa_interface_id_s.nextval
12334          into G_PREPAY_INTERFACE_ID
12335          FROM dual;
12336 
12337        G_err_stage := 'Before Fetching records for prepayment application within transfer_pay_to_pa';
12338        write_log(LOG, G_err_stage);
12339 
12340           FETCH Prepay_Cur BULK COLLECT INTO
12341              l_invoice_id_tbl,
12342              l_created_by_tbl,
12343              l_invoice_dist_id_tbl,
12344              l_cdl_sys_ref3_tbl,
12345              l_project_id_tbl,
12346              l_task_id_tbl,
12347              l_ln_type_lookup_tbl,
12348              l_exp_type_tbl,
12349              l_ei_date_tbl,
12350              l_amount_tbl,
12351              l_description_tbl,
12352              l_justification_tbl,
12353              l_dist_cc_id_tbl,
12354              l_exp_org_id_tbl,
12355              l_quantity_tbl,
12356              l_acct_pay_cc_id_tbl,
12357              l_gl_date_tbl,
12358              l_attribute_cat_tbl,
12359              l_attribute1_tbl,
12360              l_attribute2_tbl,
12361              l_attribute3_tbl,
12362              l_attribute4_tbl,
12363              l_attribute5_tbl,
12364              l_attribute6_tbl,
12365              l_attribute7_tbl,
12366              l_attribute8_tbl,
12367              l_attribute9_tbl,
12368              l_attribute10_tbl,
12369              l_rec_cur_amt_tbl,
12370              l_rec_cur_code_tbl,
12371              l_rec_conv_rate_tbl,
12372              l_denom_raw_cost_tbl,
12373              l_denom_cur_code_tbl,
12374              l_acct_rate_date_tbl,
12375              l_acct_rate_type_tbl,
12376              l_acct_exch_rate_tbl,
12377              l_job_id_tbl,
12378              l_employee_id_tbl,
12379              l_vendor_id_tbl,
12380              l_inv_type_code_tbl,
12381              l_source_tbl,
12382              l_org_id_tbl,
12383              l_invoice_num_tbl,
12384              l_inv_pay_id_tbl,  --l_cdl_sys_ref4_tbl
12385              l_po_dist_id_tbl
12386             ,l_txn_src_tbl
12387             ,l_user_txn_src_tbl
12388             ,l_batch_name_tbl
12389             ,l_interface_id_tbl
12390             ,l_exp_end_date_tbl
12391             ,l_txn_status_code_tbl
12392             ,l_txn_rej_code_tbl
12393             ,l_bus_grp_id_tbl
12394             ,l_paid_emp_id_tbl
12395             ,l_sort_var_tbl
12396             ,l_reversal_flag_tbl --NEW
12397             ,l_cancel_flag_tbl --NEW
12398             ,l_parent_pmt_id_tbl --NEW
12399             ,l_net_zero_flag_tbl  --NEW
12400             ,l_sc_xfer_code_tbl
12401             ,l_adj_exp_item_id_tbl --NEW
12402             ,l_fc_enabled_tbl  --NEW
12403             ,l_mrc_exchange_date_tbl
12404             ,l_fc_document_type_tbl
12405             ,l_si_assts_add_flg_tbl
12406             ,l_insert_flag_tbl
12407             ,l_pay_hist_id_tbl
12408             ,l_prepay_dist_id_tbl   --bug#5514129
12409             LIMIT v_max_size;
12410 
12411 
12412          G_err_stage := 'After fetching Prepay_Cur within transfer_pay_to_pa';
12413          write_log(LOG, G_err_stage);
12414 
12415          IF l_invoice_id_tbl.COUNT <> 0 THEN
12416 
12417             /* get the index of the last invoice being processed within the batch*/
12418             v_last_inv_index := l_invoice_id_tbl.LAST;
12419 
12420             G_err_stage := 'calling process_pay_logic for PREPAYMENTS within transfer_pay_to_pa';
12421             write_log(LOG, G_err_stage);
12422 
12423             process_pay_logic;
12424 
12425             G_err_stage := 'calling bulk_insert_trx_intf within transfer_pay_to_pa';
12426             write_log(LOG, G_err_stage);
12427 
12428             bulk_insert_trx_intf;
12429 
12430             G_err_stage := 'After calling bulk_insert_trx_intf within transfer_pay_to_pa';
12431             write_log(LOG, G_err_stage);
12432 
12433             G_err_stage := 'Before calling transaction import and tiebacks within transfer_pay_to_pa';
12434             write_log(LOG, G_err_stage);
12435 
12436             IF (v_num_distributions_fetched > 0) THEN
12437 
12438               write_log(LOG,'Before calling trx_import for Prepayment appl inv with interface_id:'||G_PREPAY_INTERFACE_ID);
12439               trans_import(G_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME, G_PREPAY_INTERFACE_ID, G_USER_ID);
12440 
12441               IF l_ap_prepay_tax_flag ='Y' THEN
12442                 trans_import(G_NRT_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME, G_PREPAY_INTERFACE_ID, G_USER_ID);
12443               END IF;
12444 
12445               IF l_ap_prepay_var_flag ='Y' THEN
12446                 trans_import(G_AP_VAR_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME, G_PREPAY_INTERFACE_ID, G_USER_ID);
12447               END IF;
12448               IF l_ap_prepay_erv_flag ='Y' THEN
12449                 trans_import(G_AP_ERV_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME, G_PREPAY_INTERFACE_ID, G_USER_ID);
12450               END IF;
12451 
12452               tieback_payment_AP_ER(G_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME,'APPPAY', G_PREPAY_INTERFACE_ID);
12453               IF l_ap_prepay_tax_flag ='Y' THEN
12454                 tieback_payment_AP_ER(G_NRT_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME,'APPPAY', G_PREPAY_INTERFACE_ID);
12455               END IF;
12456               IF l_ap_prepay_var_flag ='Y' THEN
12457                 tieback_payment_AP_ER(G_AP_VAR_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME,'APPPAY', G_PREPAY_INTERFACE_ID);
12458               END IF;
12459               IF l_ap_prepay_erv_flag ='Y' THEN
12460                 tieback_payment_AP_ER(G_AP_ERV_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME,'APPPAY', G_PREPAY_INTERFACE_ID);
12461               END IF;
12462 
12463               G_err_stage := 'Before updating the total number of prepayment appl processed';
12464               write_log(LOG, G_err_stage);
12465 
12466               G_NUM_BATCHES_PROCESSED       := G_NUM_BATCHES_PROCESSED + 1;
12467               G_NUM_INVOICES_PROCESSED      :=  G_NUM_INVOICES_PROCESSED + v_num_invoices_fetched;
12468               G_NUM_DISTRIBUTIONS_PROCESSED :=  G_NUM_DISTRIBUTIONS_PROCESSED + v_num_distributions_fetched;
12469               write_log(LOG,'G_NUM_BATCHES_PROCESSED:'||G_NUM_BATCHES_PROCESSED);
12470               write_log(LOG,'G_NUM_INVOICES_PROCESSED:'||G_NUM_INVOICES_PROCESSED);
12471               write_log(LOG,'G_NUM_DISTRIBUTIONS_PROCESSED:'||G_NUM_DISTRIBUTIONS_PROCESSED);
12472 
12473            END IF; /* IF (v_num_distributions_fetched > 0) */
12474 
12475            G_err_stage := 'After calling transaction import and tiebacks within transfer_pay_to_pa';
12476            write_log(LOG, G_err_stage);
12477 
12478            clear_plsql_tables;
12479 
12480            v_num_invoices_fetched       :=0;
12481            v_num_distributions_fetched  :=0;
12482 
12483            G_err_stage:='Before exiting when Prepay_Cur is NOTFOUND';
12484            write_log(LOG,   G_err_stage);
12485 
12486          ELSE
12487 
12488           G_err_stage:='Prepay Cursor fetched zero rows into plsql tables. Exiting';
12489           write_log(LOG,   G_err_stage);
12490           EXIT;
12491          END IF; /* l_invoice_id_tbl.COUNT = 0 */
12492 
12493          G_err_stage:='Cursor fetched no more rows. Exiting';
12494          write_log(LOG,   G_err_stage);
12495          EXIT WHEN Prepay_Cur%NOTFOUND;
12496 
12497       END LOOP; /* While more rows to process is true */
12498 
12499       CLOSE Prepay_Cur;
12500 
12501 
12502 EXCEPTION
12503     WHEN OTHERS THEN
12504 
12505          G_err_stack := v_old_stack;
12506          IF Payments_cur%ISOPEN THEN
12507            CLOSE Invoice_Cur;
12508          END IF ;
12509 
12510          IF Prepay_cur%ISOPEN THEN
12511            CLOSE Prepay_Cur;
12512          END IF ;
12513 
12514          G_err_code := SQLCODE;
12515          RAISE;
12516 
12517 END transfer_pay_to_pa;
12518 
12519 /*---------------------------Tieback to AP Phase----------------------------*/
12520 PROCEDURE tieback_payment_AP_ER(
12521    p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
12522    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
12523    p_batch_type  IN VARCHAR2,
12524    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
12525 
12526    l_assets_addflag          VARCHAR2(1):=NULL;
12527    l_prev_assets_addflag     VARCHAR2(1):=NULL;
12528    l_project_id             NUMBER :=0;
12529    l_pa_addflag             VARCHAR2(1):=NULL;
12530    l_prev_proj_id           NUMBER :=0;
12531 
12532    l_sys_ref1_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
12533    l_sys_ref2_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
12534    l_sys_ref4_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
12535    l_sys_ref5_tbl           PA_PLSQL_DATATYPES.IdTabTyp;
12536    l_txn_src_tbl            PA_PLSQL_DATATYPES.Char30TabTyp;
12537    l_batch_name_tbl         PA_PLSQL_DATATYPES.Char50TabTyp;
12538    l_interface_id_tbl       PA_PLSQL_DATATYPES.IdTabTyp;
12539    l_txn_status_code_tbl    PA_PLSQL_DATATYPES.Char2TabTyp;
12540    l_project_id_tbl            PA_PLSQL_DATATYPES.IdTabTyp;
12541    l_pa_addflag_tbl         PA_PLSQL_DATATYPES.CHAR1TabTyp;
12542    l_assets_addflag_tbl     PA_PLSQL_DATATYPES.CHAR1TabTyp;
12543 
12544    CURSOR txn_intf_rec (p_txn_src       IN VARCHAR2,
12545                         p_batch_name    IN VARCHAR2,
12546                         p_interface_id  IN NUMBER) IS
12547       SELECT cdl_system_reference1
12548             ,cdl_system_reference2
12549             ,cdl_system_reference4
12550             ,cdl_system_reference5
12551             ,transaction_source
12552             ,batch_name
12553             ,interface_id
12554             ,transaction_status_code
12555             ,project_id
12556             ,l_pa_addflag
12557             ,l_assets_addflag
12558         FROM pa_transaction_interface_all txnintf
12559        WHERE txnintf.transaction_source = p_txn_src
12560          AND txnintf.batch_name         = p_batch_name
12561          AND txnintf.interface_id       = p_interface_id;
12562 
12563    PROCEDURE clear_plsql_tables IS
12564 
12565       v_status   VARCHAR2(15);
12566 
12567    BEGIN
12568 
12569       G_err_stage:='Clearing PLSQL tables in payment tieback';
12570       write_log(LOG,   G_err_stage);
12571 
12572       l_sys_ref1_tbl.delete;
12573       l_sys_ref2_tbl.delete;
12574       l_sys_ref4_tbl.delete;
12575       l_sys_ref5_tbl.delete;
12576       l_txn_src_tbl.delete;
12577       l_batch_name_tbl.delete;
12578       l_interface_id_tbl.delete;
12579       l_txn_status_code_tbl.delete;
12580       l_project_id_tbl.delete;
12581       l_pa_addflag_tbl.delete;
12582       l_assets_addflag_tbl.delete;
12583 
12584    END clear_plsql_tables;
12585 
12586    PROCEDURE process_tieback IS
12587 
12588       v_status   VARCHAR2(15);
12589 
12590    BEGIN
12591 
12592       G_err_stage:='Within process_tieback of payment tieback';
12593       write_log(LOG,   G_err_stage);
12594 
12595       FOR i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST LOOP
12596 
12597          /* If transaction import stamps the record to be 'A' then
12598             update pa_addition_flag of invoice distribution to 'Y'.
12599             If transaction import leaves the record to be 'P' then
12600             update pa_addition_flag of invoice distribution to 'N'.
12601             If transaction import stamps the record to be 'R' then
12602             update pa_addition_flag of invoice distribution to 'N'.*/
12603 
12604          write_log(LOG,'Tying invoice_id: '||l_sys_ref2_tbl(i)||
12605                        'Payment Id:  '||l_sys_ref4_tbl(i)||
12606                        'dist id:  '||l_sys_ref5_tbl(i)||
12607                        'trc src:   '||l_txn_src_tbl(i));
12608 
12609          IF l_txn_status_code_tbl(i) = 'A' THEN
12610                l_pa_addflag_tbl(i) := 'Y';
12611          ELSIF l_txn_status_code_tbl(i) = 'P' THEN
12612                l_pa_addflag_tbl(i) :='N';
12613          ELSIF l_txn_status_code_tbl(i) = 'R' THEN
12614                l_pa_addflag_tbl(i) := 'N';
12615          END IF;
12616 
12617          IF G_PROJECT_ID IS NOT NULL THEN
12618 
12619             IF G_Assets_Addition_flag = 'P' THEN
12620                l_assets_addflag_tbl(i) := 'P';
12621             ELSE
12622                l_assets_addflag_tbl(i) := 'X';
12623             END IF;
12624 
12625          ELSIF G_PROJECT_ID IS NULL THEN
12626 
12627             IF l_project_id_tbl(i) <> l_prev_proj_id THEN
12628 
12629                G_err_stage:='Selecting assets addition flag within payment tieback';
12630                write_log(LOG,   G_err_stage);
12631 
12632                SELECT decode(PTYPE.Project_Type_Class_Code,'CAPITAL','P','X')
12633                  INTO l_assets_addflag_tbl(i)
12634                  FROM pa_project_types_all PTYPE,
12635                       pa_projects_all PROJ
12636                 WHERE PTYPE.Project_Type = PROJ.Project_Type
12637                   AND (PTYPE.org_id = PROJ.org_id OR
12638                        PROJ.org_id is null)
12639                   AND PROJ.Project_Id = l_project_id_tbl(i);
12640 
12641                 l_prev_proj_id := l_project_id_tbl(i);
12642 		l_prev_assets_addflag := l_assets_addflag_tbl(i);
12643 
12644             ELSE
12645                l_assets_addflag_tbl(i) := l_prev_assets_addflag;
12646             END IF;
12647 
12648          END IF;
12649 
12650       END LOOP;
12651 
12652    EXCEPTION
12653       WHEN OTHERS THEN
12654          G_err_stage:= 'Failed during process tieback of payment tieback';
12655          write_log(LOG,   G_err_stage);
12656          G_err_code   := SQLCODE;
12657          raise;
12658 
12659    END process_tieback;
12660 
12661 
12662    PROCEDURE bulk_update_txn_intf(l_batch in VARCHAR2) IS
12663 
12664      v_status VARCHAR2(15);
12665 
12666    BEGIN
12667 
12668       G_err_stage:=('Within bulk update of payment tieback');
12669       write_log(LOG,   G_err_stage);
12670 
12671      IF l_batch = 'APPPAY' THEN --Prepayment Appl batch
12672 
12673       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
12674          UPDATE ap_prepay_app_dists dist
12675             SET dist.pa_addition_flag         = l_pa_addflag_tbl(i)
12676           WHERE dist.prepay_app_dist_id       = l_sys_ref4_tbl(i)
12677             AND dist.invoice_distribution_id  = l_sys_ref5_tbl(i)
12678             AND dist.pa_addition_flag         = 'O';
12679 
12680      ELSE
12681 
12682       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
12683          UPDATE ap_payment_hist_dists paydist
12684             SET paydist.pa_addition_flag         = l_pa_addflag_tbl(i)
12685           WHERE paydist.invoice_payment_id       = l_sys_ref4_tbl(i)
12686             AND paydist.invoice_distribution_id  = l_sys_ref5_tbl(i)
12687             AND paydist.pa_addition_flag         = 'O';
12688 
12689 
12690       IF l_batch <> 'APDISC' THEN --Payment Discount batch
12691 
12692         FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
12693            UPDATE ap_invoice_distributions_all dist
12694               SET dist.assets_addition_flag      = decode(l_assets_addflag_tbl(i),'P','P',dist.assets_addition_flag)
12695             WHERE dist.invoice_distribution_id = l_sys_ref5_tbl(i) ;
12696        END IF;
12697 
12698      END IF;
12699 
12700    EXCEPTION
12701       WHEN OTHERS THEN
12702          G_err_stage:= 'Failed during bulk update of payment tieback';
12703          write_log(LOG,   G_err_stage);
12704          G_err_code   := SQLCODE;
12705          raise;
12706 
12707    END bulk_update_txn_intf;
12708 
12709    BEGIN
12710 
12711       /* Main logic of tieback starts here */
12712       G_err_stage:='Within main logic of tieback';
12713       write_log(LOG,   G_err_stage);
12714 
12715       clear_plsql_tables;
12716 
12717       G_err_stage:='Opening txn_intf_rec';
12718       write_log(LOG,   G_err_stage);
12719 
12720       OPEN txn_intf_rec(p_transaction_source
12721                        ,p_batch_name
12722                        ,p_interface_id);
12723 
12724       G_err_stage:='Fetching txn_intf_rec';
12725       write_log(LOG,   G_err_stage);
12726 
12727       FETCH txn_intf_rec BULK COLLECT INTO
12728           l_sys_ref1_tbl
12729          ,l_sys_ref2_tbl
12730          ,l_sys_ref4_tbl
12731          ,l_sys_ref5_tbl
12732          ,l_txn_src_tbl
12733          ,l_batch_name_tbl
12734          ,l_interface_id_tbl
12735          ,l_txn_status_code_tbl
12736          ,l_project_id_tbl
12737          ,l_pa_addflag_tbl
12738          ,l_assets_addflag_tbl;
12739 
12740       IF l_sys_ref1_tbl.COUNT <> 0 THEN
12741 
12742          process_tieback;
12743 
12744          bulk_update_txn_intf(p_batch_type);
12745 
12746          clear_plsql_tables;
12747 
12748       END IF;
12749 
12750       CLOSE txn_intf_rec;
12751 
12752 EXCEPTION
12753    WHEN OTHERS THEN
12754 
12755       IF txn_intf_rec%ISOPEN THEN
12756          CLOSE txn_intf_rec;
12757       END IF;
12758 
12759       G_err_code := SQLCODE;
12760       RAISE;
12761 
12762 END tieback_payment_AP_ER;
12763 
12764 
12765    PROCEDURE process_adjustments (p_record_type                 IN Varchar2,
12766                                   p_document_header_id          IN number,/*Added this for 6945767 */
12767                                   p_document_distribution_id    IN number,
12768                                   p_document_payment_id         IN number DEFAULT NULL,
12769                                   p_current_index               IN number,
12770 			  	  p_last_index			IN OUT NOCOPY number) IS
12771        l_status3 VARCHAR2(30);
12772        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
12773        l_xface_rec_exists_flg VARCHAR(1):='N';  --NEW
12774        l_fc_enabled   VARCHAR2(1) ;
12775        l_process_adjustments    Number := 0 ;
12776        l_all_reversed_cnt       Number := 0 ;
12777        l_not_reversed_cnt       Number := 0 ;
12778 
12779 
12780        CURSOR c_get_latest_ei IS
12781               SELECT ei.expenditure_item_id
12782                     , ei.project_id project_id
12783                     , ei.task_id  task_id
12784                     , ei.expenditure_item_date expenditure_item_date
12785                     , ei.expenditure_type expenditure_type
12786                     , ei.quantity quantity
12787                     , ei.raw_cost raw_cost
12788                     , nvl(ei.cost_distributed_flag,'N') cost_distributed_flag
12789                     , ei.organization_id organization_id
12790                     , ei.override_to_organization_id override_to_organization_id
12791                     , ei.receipt_currency_amount receipt_currency_amount
12792                     , ei.receipt_currency_code receipt_currency_code
12793                     , ei.receipt_exchange_rate receipt_exchange_rate
12794                     , ei.denom_raw_cost denom_raw_cost
12795                     , ei.denom_currency_code denom_currency_code
12796                     , ei.acct_rate_date acct_rate_date
12797                     , ei.acct_rate_type acct_rate_type
12798                     , ei.acct_exchange_rate acct_exchange_rate
12799                     , ei.acct_raw_cost acct_raw_cost
12800                     , ei.acct_exchange_rounding_limit acct_exchange_rounding_limit
12801                     , ei.attribute_category
12802                     , ei.attribute1
12803                     , ei.attribute2
12804                     , ei.attribute3
12805                     , ei.attribute4
12806                     , ei.attribute5
12807                     , ei.attribute6
12808                     , ei.attribute7
12809                     , ei.attribute8
12810                     , ei.attribute9
12811                     , ei.attribute10
12812                     , ei.org_id org_id
12813                     , get_cdl_ccid(ei.expenditure_item_id,'D') dr_code_combination_id
12814                     , get_cdl_ccid(ei.expenditure_item_id,'C') cr_code_combination_id
12815                     , Pa_Funds_Control_Utils.Get_Fnd_Reqd_Flag(ei.project_id,'STD') orig_fc_enabled
12816                     , nvl(cdl.transfer_status_code,'P') transfer_status_code
12817                     ,ei.document_type
12818                     ,ei.document_distribution_type
12819                     ,ei.document_header_id
12820                     ,ei.document_distribution_id
12821                     ,ei.document_payment_id
12822                     ,ei.document_line_number
12823                     ,cdl.system_reference5 cdl_sys_ref5 --to get the rcv_sub_leger_id of parent Rcv txn
12824                     ,ei.cbs_element_id  -- Added for CBS Enhancement Bug 16220146
12825 		  /*  ,nvl(ei.net_zero_adjustment_flag,'N') net_zero_adjustment_flag  -- Added for for bug#12338132 Commented for 13470521 */
12826               FROM   pa_cost_distribution_lines_all cdl,
12827                      pa_expenditure_items_all ei
12828               WHERE  cdl.expenditure_item_id (+) = ei.expenditure_item_id
12829                 AND  nvl(cdl.reversed_flag, 'N') = 'N'
12830                 AND    ei.document_distribution_id = p_document_distribution_id /*Added this for 6945767 */
12831                 AND   ei.system_linkage_function in ('VI','ER')
12832                 AND   ei.document_header_id = p_document_header_id /*Added this for 6945767 */
12833 		AND  nvl(cdl.line_type,'R') = 'R' --Bug 5373272 : 'C' and 'D' lines are incorrectly getting processed
12834                 AND  cdl.line_num_reversed is null
12835                 AND  (( p_record_type  = 'AP_INVOICE'
12836                 AND    ei.transaction_source in ('AP INVOICE','AP VARIANCE','AP EXPENSE','AP NRTAX'))
12837                  OR  ( p_record_type = 'PO_RECEIPT'
12838                 AND    ei.transaction_source IN ('PO RECEIPT', 'PO RECEIPT PRICE ADJ'))
12839                  OR  ( p_record_type = 'PO_RECEIPT_TAX'
12840                 AND    ei.transaction_source in ('PO RECEIPT NRTAX'))
12841                  OR  ( p_record_type = 'AP_DISCOUNTS'
12842                 AND    ei.document_payment_id = p_document_payment_id
12843                 AND    ei.transaction_source in ('AP DISCOUNTS','AP INVOICE','AP NRTAX'))
12844                  OR  ( p_record_type = 'AP_PAYMENT'
12845                 AND    ei.document_payment_id = p_document_payment_id
12846                 AND    ei.transaction_source in ('AP INVOICE','AP EXPENSE','AP NRTAX','AP VARIANCE')))
12847                 AND    nvl(ei.net_zero_adjustment_flag,'N') <> 'Y'  /*--Commeted the line for bug#12338132 Reverted the fix of 12338132 for 13470521 */
12848               ORDER BY  ei.cost_distributed_flag, ei.expenditure_item_id;
12849 
12850 
12851    BEGIN
12852 
12853                   write_log(LOG, 'In Process Adjustments');
12854                   write_log(LOG, 'p_current_index = '||p_current_index);
12855                   write_log(LOG, 'p_last_index = '||p_last_index);
12856 
12857                   FOR c_latest_ei_rec in c_get_latest_ei LOOP
12858                       l_xface_rec_exists_flg:= 'Y'; -- Parent is in projects
12859 
12860                       write_log(LOG, 'For each record in the cursor');
12861 
12862                       IF  ( c_latest_ei_rec.cost_distributed_flag = 'N' AND
12863                            l_process_adjustments = 0) THEN
12864 
12865                               -- Reversal will not be interfaced since adjusted parent EI's have not been cost distributed
12866                               write_log(LOG, 'Adjustment not cost distributed in Projects');
12867                               l_txn_status_code_tbl(p_current_index) := 'R';
12868                               l_txn_rej_code_tbl(p_current_index) := 'PA_EI_NOT_COST_DISTRIBUTED';
12869 
12870                               EXIT;
12871 
12872                       ELSIF  c_latest_ei_rec.transfer_status_code = 'V' THEN
12873 
12874                           l_adj_exp_item_id_tbl(p_current_index):= c_latest_ei_rec.expenditure_item_id;
12875 
12876 			/* Reverted the changes for bug 13470521
12877                              start changes for for bug#12338132
12878 
12879 			  IF (c_latest_ei_rec.net_zero_adjustment_flag ='Y') THEN
12880 			  --{
12881 				l_adj_exp_item_id_tbl(p_current_index):= null;
12882                                 l_net_zero_flag_tbl(p_current_index) := 'N';
12883 			  --}
12884 			  END IF;
12885 
12886 			   End changes for for bug#12338132 Ends reverting for 13470521*/
12887 
12888                           /* Bug 8984546 -- Commented following line
12889                           l_ei_date_tbl(p_current_index) := c_latest_ei_rec.expenditure_item_date; */ -- copy the source ei date
12890 
12891                               EXIT ;
12892 
12893 
12894                      ELSE
12895                           -- This indicates that there are multiple EI adjustments for the reversed distribution lines
12896                           -- This could happen if the EI was SPLIT across different projects
12897                           -- Incase there are multiple EI adjustments for single distribution we will insert multiple
12898                           -- records in the interface table each corresponding to the adjusted EI.
12899                           --
12900                           -- The following section will insert new table records at the end of the fetched table array
12901                           -- example : If bulk fetch populates 200 rows in PLSQL table array, the following section
12902                           --           will insert record in the PLSQL array from 201+ onwards
12903 
12904                           write_log(LOG, 'There are many adjustments that needs to be reversed in projects');
12905                       -- Set the net_zero_flag and the create adj record flag
12906                          l_net_zero_flag_tbl(p_current_index) := 'Y';
12907                          l_insert_flag_tbl(p_current_index)   := 'A';
12908                          l_fc_document_type_tbl(p_current_index) := 'NOT';
12909                          l_adj_exp_item_id_tbl(p_current_index):= 0; -- Skip the EI Date validation in Trx Imp.
12910                     -- Set the sc_xfer_code column on the xface table.
12911 
12912                           IF l_process_adjustments = 0 THEN
12913 
12914                                 j := p_last_index+1;
12915                           ELSE
12916 
12917                                 j := j + 1;
12918                           END IF;
12919 
12920                   write_log(LOG, 'j = '||j);
12921                           l_txn_src_tbl(j)        := l_txn_src_tbl(p_current_index);
12922                           l_user_txn_src_tbl(j)   := l_user_txn_src_tbl(p_current_index);
12923                           l_batch_name_tbl(j)     := l_batch_name_tbl(p_current_index);
12924                           l_project_id_tbl(j)     := c_latest_ei_rec.project_id;
12925                           l_task_id_tbl(j)        := c_latest_ei_rec.task_id;
12926                           l_exp_type_tbl(j)       := c_latest_ei_rec.expenditure_type;
12927                           l_exp_end_date_tbl(j)   := l_exp_end_date_tbl(p_current_index);
12928                           l_ei_date_tbl(j)        := c_latest_ei_rec.expenditure_item_date;
12929                           l_amount_tbl(j)         := c_latest_ei_rec.acct_raw_cost * -1;
12930                           l_quantity_tbl(j)       := nvl(c_latest_ei_rec.quantity,0) * -1;
12931                           l_description_tbl(j)    := l_description_tbl(p_current_index) ;
12932                           l_dist_cc_id_tbl(j)     := c_latest_ei_rec.dr_code_combination_id;
12933                           l_acct_pay_cc_id_tbl(j) := c_latest_ei_rec.cr_code_combination_id;
12934                           l_rec_cur_amt_tbl(j)    := c_latest_ei_rec.receipt_currency_amount * -1;
12935                           l_rec_cur_code_tbl(j)   := c_latest_ei_rec.receipt_currency_code;
12936                           l_rec_conv_rate_tbl(j)  := c_latest_ei_rec.receipt_exchange_rate;
12937                           l_denom_raw_cost_tbl(j) := c_latest_ei_rec.denom_raw_cost * -1;
12938                           l_denom_cur_code_tbl(j) := c_latest_ei_rec.denom_currency_code;
12939                           l_acct_rate_date_tbl(j) := c_latest_ei_rec.acct_rate_date;
12940                           l_acct_rate_type_tbl(j) := c_latest_ei_rec.acct_rate_type;
12941                           l_acct_exch_rate_tbl(j) := c_latest_ei_rec.acct_exchange_rate;
12942                           l_attribute_cat_tbl(j)  := c_latest_ei_rec.attribute_category;
12943                           l_attribute1_tbl(j)     := c_latest_ei_rec.attribute1;
12944                           l_attribute2_tbl(j)     := c_latest_ei_rec.attribute2;
12945                           l_attribute3_tbl(j)     := c_latest_ei_rec.attribute3;
12946                           l_attribute4_tbl(j)     := c_latest_ei_rec.attribute4;
12947                           l_attribute5_tbl(j)     := c_latest_ei_rec.attribute5;
12948                           l_attribute6_tbl(j)     := c_latest_ei_rec.attribute6;
12949                           l_attribute7_tbl(j)     := c_latest_ei_rec.attribute7;
12950                           l_attribute8_tbl(j)     := c_latest_ei_rec.attribute8;
12951                           l_attribute9_tbl(j)     := c_latest_ei_rec.attribute9;
12952                           l_attribute10_tbl(j)    := c_latest_ei_rec.attribute10;
12953                           l_org_id_tbl(j)         := nvl(c_latest_ei_rec.organization_id,c_latest_ei_rec.override_to_organization_id);
12954                           l_exp_org_id_tbl(j)     := c_latest_ei_rec.override_to_organization_id;
12955                           l_vendor_id_tbl(j)      := l_vendor_id_tbl(p_current_index);
12956                           l_cbs_element_id_tbl(j) := c_latest_ei_rec.cbs_element_id; -- Added for CBS Enhancement Bug 16220146
12957 
12958                           IF p_record_type like 'PO_RECEIPT%' THEN
12959                             l_po_head_id_tbl(j)        := c_latest_ei_rec.document_header_id;
12960                             l_po_dist_id_tbl(j)        := c_latest_ei_rec.document_line_number;
12961                             l_rcv_txn_id_tbl(j)        := c_latest_ei_rec.document_distribution_id;
12962                             l_rcv_sub_ledger_id_tbl(j) := to_number(c_latest_ei_rec.cdl_sys_ref5);
12963                             l_dest_typ_code_tbl(j)     := c_latest_ei_rec.document_type;
12964                             l_trx_type_tbl(j)          := c_latest_ei_rec.document_distribution_type;
12965                             l_rcv_acct_evt_id_tbl(j)   := l_rcv_acct_evt_id_tbl(p_current_index);
12966                             l_acct_raw_cost_tbl(j)     := c_latest_ei_rec.acct_raw_cost * -1;
12967                             l_exp_cst_rt_flg_tbl(j)    := l_exp_cst_rt_flg_tbl(p_current_index); -- Was outside if causing 1403 error for Inv.#5351431
12968                             IF p_record_type =  'PO_RECEIPT' THEN
12969                               l_record_type_tbl(j)       := 'RECEIPT';
12970                             ELSE
12971                               l_record_type_tbl(j)       := 'RCVTAX';
12972                             END IF;
12973                               l_entered_nr_tax_tbl(j)    := 0;
12974                               l_pa_add_flag_tbl(j)       := 'O';
12975                           ELSE
12976                             l_invoice_id_tbl(j)     := l_invoice_id_tbl(p_current_index);
12977                             l_invoice_dist_id_tbl(j):= l_invoice_dist_id_tbl(p_current_index); -- R12 funds management Uptake
12978 			    l_is_self_assessed_tax_tbl(j) :=   l_is_self_assessed_tax_tbl(p_current_index);  -- for bug 13919706
12979                             l_cdl_sys_ref4_tbl(j)   := l_cdl_sys_ref4_tbl(p_current_index);
12980                             l_cdl_sys_ref3_tbl(j)   := l_cdl_sys_ref3_tbl(p_current_index);
12981                             l_invoice_num_tbl(j)    := l_invoice_num_tbl(p_current_index);
12982                             l_inv_type_code_tbl(j)  := c_latest_ei_rec.document_type;
12983                             l_ln_type_lookup_tbl(j) := c_latest_ei_rec.document_distribution_type;
12984                           END IF;
12985 
12986                           IF p_record_type in ('AP_DISCOUNTS','AP_PAYMENT')  THEN
12987                             l_inv_pay_id_tbl(j)     := c_latest_ei_rec.document_payment_id;
12988                             l_pay_hist_id_tbl(j)    := c_latest_ei_rec.cdl_sys_ref5;
12989                           END IF;
12990 
12991                           l_gl_date_tbl(j)        := l_gl_date_tbl(p_current_index);
12992                           l_employee_id_tbl(j)    := l_employee_id_tbl(p_current_index);
12993                           l_bus_grp_id_tbl(j)     := l_bus_grp_id_tbl(p_current_index);
12994                           l_txn_status_code_tbl(j):= l_txn_status_code_tbl(p_current_index);
12995                           l_txn_rej_code_tbl(j)   := l_txn_rej_code_tbl(p_current_index);
12996                           l_interface_id_tbl(j)   := l_interface_id_tbl(p_current_index);
12997                           l_adj_exp_item_id_tbl(j):= c_latest_ei_rec.expenditure_item_id;
12998                           l_net_zero_flag_tbl(j)  := 'N';
12999                           l_sc_xfer_code_tbl(j)   := 'P';
13000                           l_si_assts_add_flg_tbl(j) := 'T'; --For Adjustments done in PA
13001                           l_insert_flag_tbl(j)   := 'Y';
13002 
13003                           write_log(LOG, 'Adjustment records populated into the PL/SQL table');
13004 
13005                           --
13006                           -- This section is to ensure that the commitments are relieved and actuals
13007                           -- are funds checked.
13008                           --
13009                           If l_fc_enabled_tbl(p_current_index) = 'Y' AND   c_latest_ei_rec.orig_fc_enabled = 'N' THEN
13010                               l_fc_document_type_tbl(j) := 'CMT';
13011                           ELSIF l_fc_enabled_tbl(p_current_index) = 'Y' AND   c_latest_ei_rec.orig_fc_enabled = 'Y' THEN
13012                               l_fc_document_type_tbl(j) := 'ALL';
13013                           ELSIF l_fc_enabled_tbl(p_current_index) = 'N' AND   c_latest_ei_rec.orig_fc_enabled = 'N' THEN
13014                               l_fc_document_type_tbl(j) := 'NOT';
13015                           ELSIF l_fc_enabled_tbl(p_current_index) = 'N' AND   c_latest_ei_rec.orig_fc_enabled = 'Y' THEN
13016                               l_fc_document_type_tbl(j) := 'ACT';
13017                           END IF ;
13018 
13019                           l_process_adjustments  := 1 ;
13020 
13021                   write_log(LOG, 'p_current_index = '||p_current_index);
13022                     END IF; --End of rowcount=0
13023                     write_log(LOG, 'Done with processing reversals');
13024 
13025                  END LOOP; --End of cursor c_get_latest_ei
13026 
13027                  IF j>= p_last_index THEN
13028 
13029                  -- Some adjustments were created.
13030                  p_last_index := j;
13031                  write_log(LOG, 'p_last_index = '||p_last_index);
13032 
13033                  ELSIF l_xface_rec_exists_flg = 'N' THEN --Parent is not in PA/or All the adjustments got reversed.
13034 
13035                 write_log(LOG, 'Setting the netzero flag  adjustment records..');
13036                    -- Logic for interfacing both the parent and the child (netzero) in the same run.
13037 
13038                   IF l_rev_parent_dist_id_tbl.exists(1) THEN
13039                     FOR i in l_rev_parent_dist_id_tbl.first..l_rev_parent_dist_id_tbl.last LOOP
13040 
13041                       IF (l_rev_parent_dist_id_tbl(i) = p_document_distribution_id OR
13042                         l_rev_parent_dist_id_tbl(i) = p_document_payment_id) THEN
13043 
13044                        IF l_inv_pay_id_tbl.EXISTS(p_current_index) THEN
13045                         IF l_reversal_flag_tbl(p_current_index) = 'R' THEN
13046                         -- If the reversal is for invoice distributions then store the reversed child inv dist id ..Bug# 5408748
13047                           l_rev_child_dist_id_tbl(i):= l_invoice_dist_id_tbl(p_current_index);
13048                         ELSE
13049                         -- If the reversal is for payment distributions then store the reversed child payment id ..Bug# 5408748
13050                           l_rev_child_dist_id_tbl(i):= l_inv_pay_id_tbl(p_current_index);
13051                         END IF;
13052 
13053                        ELSE
13054                         l_rev_child_dist_id_tbl(i):= l_invoice_dist_id_tbl(p_current_index);
13055                        END IF;
13056                         l_net_zero_flag_tbl(l_rev_parent_dist_ind_tbl(i)) := 'Y'; -- Set the parent netzero_flag
13057                         l_insert_flag_tbl(p_current_index)   := 'U';  -- update adjustment record
13058                         l_ei_date_tbl(p_current_index) := l_ei_date_tbl(l_rev_parent_dist_ind_tbl(i)); -- Set the reversal dist ei date same as parent's.
13059                         write_log(LOG, 'Parent dist ='||l_rev_parent_dist_id_tbl(i)||' Child dist = '||l_rev_child_dist_id_tbl(i));
13060                         /*Start changes for bug#15974243 */
13061 			SELECT pa_utils.getweekending(l_ei_date_tbl(p_current_index))
13062 			INTO l_exp_end_date_tbl(p_current_index)
13063 			FROM dual;
13064 			/*End changes for bug#15974243 */
13065 
13066                       END IF;
13067 
13068                     END LOOP;
13069                  END IF;
13070 
13071          -- Handle the corner case where the project adjustments got reversed in an earlier run, but the ap reversal was rejected.
13072          -- This section brings in the ap reversal as a netzero pair rather than a standalone reversal.Bug#5064930.
13073 
13074             IF l_insert_flag_tbl(p_current_index) <> 'U' THEN
13075 
13076                  write_log(LOG, 'Selecting the count of adjusted expenditures');
13077 
13078                  SELECT  sum(decode(ei.net_zero_adjustment_flag,'N',1,0)),count(*)
13079                  INTO   l_not_reversed_cnt,l_all_reversed_cnt
13080                  FROM   pa_expenditure_items_all ei
13081                  /*Added this for 6945767 */
13082                  WHERE  ei.document_distribution_id = p_document_distribution_id
13083                  AND   ei.document_header_id = p_document_header_id /*Added this for 6945767 */
13084                  AND  (( p_record_type  = 'AP_INVOICE'
13085                  -- AND    ei.document_distribution_id = p_document_distribution_id
13086                  AND    ei.transaction_source in ('AP INVOICE','AP VARIANCE','AP EXPENSE','AP NRTAX'))
13087                   OR  ( p_record_type = 'PO_RECEIPT'
13088                  --AND    ei.document_distribution_id = p_document_distribution_id
13089                  AND    ei.transaction_source IN ('PO RECEIPT', 'PO RECEIPT PRICE ADJ'))
13090                   OR  ( p_record_type = 'PO_RECEIPT_TAX'
13091                  --AND    ei.document_distribution_id = p_document_distribution_id
13092                  AND    ei.transaction_source in ('PO RECEIPT NRTAX'))
13093                   OR  ( p_record_type = 'AP_DISCOUNTS'
13094                  --AND    ei.document_distribution_id = p_document_distribution_id
13095                  AND    ei.document_payment_id = p_document_payment_id
13096                  AND    ei.transaction_source in ('AP DISCOUNTS','AP INVOICE','AP NRTAX'))
13097                   OR  ( p_record_type = 'AP_PAYMENT'
13098                  --AND    ei.document_distribution_id = p_document_distribution_id
13099                  AND    ei.document_payment_id = p_document_payment_id
13100                  AND    ei.transaction_source in ('AP INVOICE','AP EXPENSE','AP VARIANCE','AP NRTAX')))
13101                  /* Added below code for 13470521 */
13102                  AND EXISTS (SELECT 1 FROM pa_expenditure_items_all adj_ei
13103                         WHERE adj_ei.adjusted_expenditure_item_id = ei.expenditure_item_id
13104                           AND adj_ei.net_zero_adjustment_flag = 'Y'
13105                           AND adj_ei.document_header_id = ei.document_header_id
13106                           AND adj_ei.document_distribution_id = ei.document_distribution_id);
13107 
13108                IF (l_all_reversed_cnt > 0 and l_not_reversed_cnt = 0 ) THEN
13109 
13110                  write_log(LOG, 'Setting the netzero pair logic for the reversal distribution ='||p_document_distribution_id);
13111                       -- Set the net_zero_flag and the create adj record flag
13112                          l_net_zero_flag_tbl(p_current_index) := 'Y';
13113                          l_insert_flag_tbl(p_current_index)   := 'A';
13114 
13115                END IF;
13116 
13117             END IF;
13118           END IF;
13119 
13120    EXCEPTION
13121       WHEN OTHERS THEN
13122           write_log(LOG,'Failed reversal processing');
13123           G_err_code   := SQLCODE;
13124                    write_log(LOG, 'Error Code is  '||SQLCODE);
13125                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 1, 200));
13126                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 201, 200));
13127           raise;
13128    END;
13129 
13130 FUNCTION ReceiptPaAdditionFlag(p_Pa_Addition_Flag      IN VARCHAR2,
13131                                p_Po_Distribution_Id    IN NUMBER)
13132                               RETURN VARCHAR2 IS
13133 
13134    l_Dummy              VARCHAR2(1);
13135    l_Pa_Addition_Flag   VARCHAR2(1);
13136 
13137 BEGIN
13138  write_log(LOG,'Inside ReceiptPaAdditionFlag');
13139 
13140 l_Pa_Addition_Flag:=p_Pa_Addition_Flag;
13141 
13142   SELECT 'X'
13143   INTO l_Dummy
13144   FROM DUAL
13145   WHERE EXISTS ( SELECT NULL
13146                  FROM   rcv_transactions rcv_txn2
13147                        ,rcv_receiving_sub_ledger rcv_sub2
13148                  WHERE  rcv_sub2.rcv_transaction_id    = rcv_txn2.transaction_id
13149                  AND    rcv_txn2.po_distribution_id    = P_Po_Distribution_Id
13150                  AND    rcv_sub2.pa_addition_flag      = 'G'
13151                   UNION ALL
13152                  SELECT  null
13153                  FROM    ap_invoice_distributions apdist
13154                  WHERE   apdist.po_distribution_id = P_Po_Distribution_Id
13155 --                 AND     apdist.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX') --Modified as below for the bug13984115
13156                  AND     apdist.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL')
13157                  AND     apdist.pa_addition_flag         = 'Y'  /*Bug 13602288: Self Assessed Tax Changes*/
13158 /*		 UNION ALL   /*Bug 13602288: Self Assessed Tax Changes*/
13159 /*		 SELECT  null
13160                  FROM    ap_self_assessed_tax_dist apdist
13161                  WHERE   apdist.po_distribution_id = P_Po_Distribution_Id
13162                  AND     apdist.line_type_lookup_code in ('ITEM','ACCRUAL','RETROACCRUAL','NONREC_TAX')
13163                  AND     apdist.pa_addition_flag         = 'Y'    Removed the union for the bug 13984115*/
13164 		 );
13165 
13166    If l_Dummy = 'X' THEN
13167        write_log(LOG,'ReceiptPaAdditionFlag:l_Dummy is X');
13168       RETURN 'G';
13169    ELSE
13170        write_log(LOG,'ReceiptPaAdditonFlag:l_pa_addition_flag'||l_Pa_Addition_Flag);
13171       RETURN l_Pa_Addition_Flag;
13172    END IF;
13173 
13174 EXCEPTION
13175 WHEN NO_DATA_FOUND THEN
13176     write_log(LOG,'ReceiptPaAdditonFlag NDF:l_pa_addition_flag'||l_Pa_Addition_Flag);
13177     RETURN l_Pa_Addition_Flag;
13178 
13179 WHEN Others THEN
13180    G_err_code := SQLCODE;
13181    RAISE;
13182 
13183 END ReceiptPaAdditionFlag;
13184 
13185 END PAAPIMP_PKG;