DBA Data[Home] [Help]

PACKAGE BODY: APPS.PAAPIMP_PKG

Source


1 PACKAGE BODY PAAPIMP_PKG AS
2 /* $Header: PAAPIMPB.pls 120.81.12010000.5 2008/11/27 12:43:18 dlella 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_PAY_DISTRIBUTIONS_MARKED := 0;
554 
555    -- Added for AP discounts
556    G_NUM_DISCOUNTS_PROCESSED :=0;
557 
558    --Added for AP Variance
559    G_NUM_AP_VARIANCE_MARKED_W    :=0;
560    G_NUM_AP_VARIANCE_PROCESSED :=0;
561 
562    --Added for PO RECEIPT
563    G_RCV_TRANSACTIONS_MARKED_O    :=0;
564    G_RCV_TRANSACTIONS_MARKED_J    :=0;
565    G_RCV_TRANSACTIONS_MARKED_NULL :=0;
566    G_RCV_TRANSACTIONS_MARKED_G    :=0;
567    G_NUM_RCV_TXN_PROCESSED        :=0;
568    G_NUM_RCVTAX_PROCESSED         :=0;
569 
570    /* restore the old G_err_stack */
571    G_err_stack := v_old_stack;
572 
573 EXCEPTION
574 
575    WHEN E_DIFFERENT_SOB THEN
576       RAISE;
577 
578    WHEN Others THEN
579 
580       G_err_stack := v_old_stack;
581       G_err_code := SQLCODE;
582       RAISE;
583 
584 END Initialize_Global;
585 
586 PROCEDURE fetch_pf_var(p_process_receipts IN VARCHAR2 ) IS
587 --PROCEDURE fetch_pf_var IS
588 
589    v_old_stack VARCHAR2(630);
590    v_commit_size VARCHAR2(30);
591 
592 BEGIN
593 
594    v_old_stack := G_err_stack;
595    G_err_stack := G_err_stack || '->PAAPIMP_PKG.fetch_pf_var';
596    G_err_stage := 'FETCHING PROFILE VARIABLES';
597 
598    If g_body_debug_mode = 'Y' Then
599    write_log(LOG, G_err_stack);
600    End If;
601 
602    G_USER_ID := FND_GLOBAL.USER_ID();
603    G_REQUEST_ID := FND_GLOBAL.CONC_REQUEST_ID();
604    G_PROG_APPL_ID := FND_GLOBAL.PROG_APPL_ID();
605    G_PROG_ID := FND_GLOBAL.CONC_PROGRAM_ID();
606    G_LOGIN_ID := FND_GLOBAL.CONC_LOGIN_ID();
607 
608    /* Get commit cycle size */
609    /* VI enhancment: Check the G_INVOICE_TYPE variable to see
610       which invoice type we're transferring, then initialize
611       the profile name global variable accordingly */
612 
613    IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
614 
615       G_PROFILE_NAME := 'PA_NUM_WEB_EXP_PER_SET';
616 
617    ELSE
618 
619       G_PROFILE_NAME := 'PA_NUM_EXP_ITEMS_PER_SET';
620 
621    END IF;
622 
623    G_err_stage := 'FETCHING PROFILE OPTION: COMMIT SIZE';
624    fnd_profile.get(G_PROFILE_NAME, v_commit_size);
625 
626    G_COMMIT_SIZE := to_number(v_commit_size);
627 
628    IF (G_COMMIT_SIZE <= 0) THEN
629 
630    If g_body_debug_mode = 'Y' Then
631       write_log(LOG, 'Please verify the value of profile option PA: Web Expense Invoices Per Set.  Current value is: ' || to_char(G_COMMIT_SIZE));
632       write_log(LOG, 'Commit Size set to default value: 500');
633 G_COMMIT_SIZE := 500;
634   End If;
635    END IF;
636 
637    If g_body_debug_mode = 'Y' Then
638     write_log(LOG, 'Expense Invoices Per Set.  Current value is: ' || to_char(G_COMMIT_SIZE));  /* Bug # 2138340 */
639    End If;
640 
641    /* Get the profile option of whether to transfer DFF from AP */
642    G_err_stage := 'FETCHING PROFILE OPTION: TRANS DFF FROM AP';
643 
644    G_PROFILE_NAME := 'PA_TRANSFER_DFF_AP';
645    fnd_profile.get(G_PROFILE_NAME, G_TRANS_DFF_AP);
646    If g_body_debug_mode = 'Y' Then
647    write_log(LOG,'Processing DFFs for AP?'||G_TRANS_DFF_AP);
648    End If;
649    IF p_process_receipts = 'Y' THEN
650 
651      G_PROFILE_NAME := 'PA_TRANSFER_DFF_PO';
652      fnd_profile.get(G_PROFILE_NAME, G_TRANS_DFF_PO);
653    If g_body_debug_mode = 'Y' Then
654      write_log(LOG,'Processing DFFs for PO?'||G_TRANS_DFF_PO);
655    End if;
656    END IF;
657 
658    G_err_stack := v_old_stack;
659 
660 EXCEPTION
661    WHEN Others THEN
662 
663       G_err_stack := v_old_stack;
664       G_err_code := SQLCODE;
665       RAISE;
666 
667 END fetch_pf_var;
668 
669 FUNCTION create_new_batch_name
670    RETURN pa_transaction_interface.batch_name%TYPE IS
671 
672    v_old_stack VARCHAR2(630);
673    v_new_batch_name pa_transaction_interface.batch_name%TYPE;
674    v_interface_id   NUMBER;
675 
676 BEGIN
677 
678    v_old_stack := G_err_stack;
679    G_err_stack := G_err_stack || '->PAAPIMP_PKG.create_new_batch_name';
680    G_err_stage := 'CREATING NEW BATCHNAME';
681 
682    If g_body_debug_mode = 'Y' Then
683    write_log(LOG, G_err_stack);
684    End If;
685 
686    --Getting a unique sequence for batch name from interface_id
687    SELECT pa_interface_id_s.nextval
688      into v_interface_id
689      FROM dual;
690 
691    G_UNIQUE_ID := v_interface_id;
692 
693    v_new_batch_name :=  'AP-' ||G_UNIQUE_ID;
694 
695    If g_body_debug_mode = 'Y' Then
696    write_log(LOG, 'New Batch Name: ' || v_new_batch_name);
697    End If;
698 
699    G_err_stack := v_old_stack;
700 
701    RETURN v_new_batch_name;
702 
703 EXCEPTION
704 
705 WHEN Others THEN
706 
707    G_err_stack := v_old_stack;
708    G_err_code := SQLCODE;
709    RAISE;
710 
711 
712 END create_new_batch_name;
713 
714 
715 PROCEDURE write_validate_param_log IS
716 
717    v_old_stack Varchar2(630);
718 
719 BEGIN
720 
721 	v_old_stack := G_err_stack;
722 	G_err_stack := G_err_stack || '->PAAPIMP_PKG.write_validate_param_log';
723 	G_err_stage := 'WRITE PARAMETERS TO LOG';
724 
725    If g_body_debug_mode = 'Y' Then
726 	pa_debug.debug(G_err_stack);
727    End If;
728 
729    IF (G_OUTPUT = G_OUTPUT_SQLPLUS) THEN
730 			NULL;
731 		ELSIF (G_OUTPUT = G_OUTPUT_SQLPLUS) THEN
732 	If g_body_debug_mode ='Y' Then
733          pa_debug.debug('Validated parameters are as follows:');
734          pa_debug.debug('  Parameter1  - Project ID                   : ' || G_PROJECT_ID);
735 			pa_debug.debug('  Parameter2  - Batch Name                   : ' || G_BATCH_NAME);
736          pa_debug.debug('  Parameter3  - GL Date through              : ' || to_char(G_GL_DATE));
737          pa_debug.debug('  Parameter4  - Transaction Date through     : ' || to_char(G_TRANSACTION_DATE));
738          pa_debug.debug('                     ');
739          pa_debug.debug('Other relevant information:');
740          pa_debug.debug('  User ID          = ' || to_char(G_USER_ID));
741          pa_debug.debug('  Request ID       = ' || to_char(G_REQUEST_ID));
742          pa_debug.debug('  Program ID       = ' || to_char(G_PROG_ID));
743          pa_debug.debug('  Login ID         = ' || to_char(G_LOGIN_ID));
744        End If;
745 		ELSIF (G_OUTPUT = G_OUTPUT_FND) THEN
746 	If g_body_debug_mode ='Y' Then
747          FND_FILE.PUT_LINE(FND_FILE.LOG, 'Validated parameters are as follows:');
748          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Parameter1  - Project ID                   : ' || G_PROJECT_ID);
749 			FND_FILE.PUT_LINE(FND_FILE.LOG, '  Parameter2  - Batch Name                   : ' || G_BATCH_NAME);
750          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Parameter3  - GL Date through              : ' || to_char(G_GL_DATE));
751          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Parameter4  - Transaction Date through     : ' || to_char(G_TRANSACTION_DATE));
752          FND_FILE.NEW_LINE(FND_FILE.LOG, 1);
753          FND_FILE.PUT_LINE(FND_FILE.LOG, 'Other relevant information:');
754          FND_FILE.PUT_LINE(FND_FILE.LOG, '  User ID          = ' || to_char(G_USER_ID));
755          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Request ID       = ' || to_char(G_REQUEST_ID));
756          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Program ID       = ' || to_char(G_PROG_ID));
757          FND_FILE.PUT_LINE(FND_FILE.LOG, '  Login ID         = ' || to_char(G_LOGIN_ID));
758        End If;
759 
760       END IF;
761 
762 	G_err_stack := v_old_stack;
763 
764 EXCEPTION
765 
766    WHEN Others THEN  /* This exception is not fatal, so don't terminate the program. */
767 
768 	G_err_stack := v_old_stack;
769         G_err_code := SQLCODE;
770         If g_body_debug_mode = 'Y' Then
771         write_log(LOG,'Error occured in stage: ' || G_err_stage);
772         write_log(LOG, substr(SQLERRM, 1, 200));
773 	end if;
774 END write_validate_param_log;
775 
776 
777 PROCEDURE write_log (
778    p_message_type IN NUMBER,
779    p_message IN VARCHAR2) IS
780 
781    buffer_overflow EXCEPTION;
782    PRAGMA EXCEPTION_INIT(buffer_overflow, -20000);
783 
784 BEGIN
785 --          dbms_output.put_line(p_message);
786 /*
787    IF (p_message_type = LOG OR g_body_debug_mode = 'Y') THEN
788 
789       IF (G_OUTPUT = G_OUTPUT_SQLPLUS) THEN
790 
791          --dbms_output.put_line(p_message);
792          NULL;
793 
794       ELSIF (G_OUTPUT = G_OUTPUT_PADEBUG) THEN
795 
796          pa_debug.debug(p_message);
797 
798       ELSIF (G_OUTPUT = G_OUTPUT_FND) THEN
799 
800       FND_FILE.PUT_LINE(FND_FILE.LOG,to_char(sysdate,'HH:MI:SS:   ')|| p_message);
801       FND_FILE.NEW_LINE(FND_FILE.LOG, 1);
802 
803       END IF;
804 
805    END IF;
806 */
807       FND_FILE.PUT_LINE(FND_FILE.LOG,to_char(sysdate,'HH:MI:SS:   ')|| p_message);
808       FND_FILE.NEW_LINE(FND_FILE.LOG, 1);
809 EXCEPTION   /* When exception occurs, program needs to be aborted. */
810 
811    WHEN OTHERS THEN
812 
813       raise;
814 
815 END write_log;
816 
817 /*--------------------------Cleanup Phase--------------------------------------*/
818 
819 PROCEDURE cleanup IS
820 
821         CURSOR paapimp_cur IS
822         SELECT 'Y'
823         FROM    fnd_concurrent_requests req,
824                 fnd_concurrent_programs prog,
825                 fnd_executables exe
826         WHERE   req.program_application_id = prog.application_id
827           AND   req.concurrent_program_id = prog.concurrent_program_id
828           AND   req.phase_code = 'R'
829 	  AND	req.request_id <> G_REQUEST_ID
830           AND   prog.executable_application_id = exe.application_id
831           AND   prog.executable_id = exe.executable_id
832           AND   exe.executable_name = 'PAAPIMP';
833 
834         timeout  integer := 0;
835         lockmode integer := 6; /* exclusive lock */
836         lrelease boolean := FALSE; /* Do not release on commit */
837         lstatus   integer;
838         paapimp_running  varchar2(1) := '';
839 	result integer;
840 	v_old_stack VARCHAR2(630);
841 
842       BEGIN
843 
844 	v_old_stack := G_err_stack;
845 	G_err_stack := G_err_stack || '->PAAPIMP_PKG.cleanup';
846 	G_err_code := 0;
847 	G_err_stage := 'ALLOCATING LOCK';
848 
849         If g_body_debug_mode = 'Y' Then
850 	write_log(LOG, G_err_stack);
851        	write_log(LOG, '......Trying to allocate for a lock');
852         end if;
853         /* get lock handle for PAAPIMP user lock */
854 	dbms_lock.allocate_unique(G_LOCK_NAME,G_LOCKHNDL,timeout);
855 
856 	IF (G_LOCKHNDL IS NOT NULL) THEN
857    		If g_body_debug_mode = 'Y' Then
858 		write_log(LOG, '......Lock created, trying to request for lock.');
859 		end if;
860 
861 		G_err_stage := 'REQUESTING LOCK';
862 
863 		/* Get the lock, do not release the lock on commit */
864 		lstatus := dbms_lock.request(G_LOCKHNDL, lockmode, timeout, lrelease);
865 
866           IF ( lstatus = 0 ) then /* Got the lock */
867 		G_err_stage := 'CHECKING IF PAAPIMP IS RUNNING';
868    		If g_body_debug_mode = 'Y' Then
869 		write_log(LOG, '.....Request for lock granted, check if PAAPIMP is running.');
870 		end if;
871             	OPEN paapimp_cur; /* Check if PAAPIMP is running */
872             	FETCH paapimp_cur INTO paapimp_running;
873             	CLOSE paapimp_cur;
874 
875             IF ( nvl(paapimp_running,'N') = 'N' ) THEN
876 
877               /* PAAPIMP is not running, So Clean up */
878 		If g_body_debug_mode = 'Y' Then
879 		write_log(LOG, '......Paapimp is not running, do cleanup');
880 		end if;
881 		G_err_stage := 'UPDATING INVOICE DISTRIBUTIONS';
882 
883 	        UPDATE ap_invoice_distributions_all DIST
884               	SET DIST.pa_addition_flag = 'N'
885                   , DIST.request_id = G_REQUEST_ID
886               	WHERE  DIST.pa_addition_flag IN ('O','W')
887               	AND  DIST.posted_flag||''= 'Y'
888               	AND  DIST.project_id >0
889                 AND  NOT EXISTS ( SELECT 'X'
890                                    FROM pa_expenditure_items_all ei
891 				  WHERE ei.document_header_id = dist.invoice_id   /*Added for bug 6327185 */
892                                     AND ei.document_distribution_id = dist.invoice_distribution_id
893                                     AND ei.transaction_source in ('AP INVOICE','AP VARIANCE','AP NRTAX','AP EXPENSE')) ;
894 
895 		If g_body_debug_mode = 'Y' Then
896 		write_log(LOG, 'Number of invoice distributions updated = ' || to_char(SQL%ROWCOUNT));
897 		end if;
898 
899                 UPDATE ap_payment_hist_dists dist
900                 SET    dist.pa_addition_flag = 'N'
901                      , DIST.request_id = G_REQUEST_ID
902                 WHERE  DIST.pa_addition_flag  = 'O'
903                 AND    dist.pay_dist_lookup_code = 'DISCOUNT'
904                 AND    EXISTS (SELECT NULL
905                              FROM   ap_payment_history_all hist
906                              WHERE  hist.payment_history_id = dist.payment_history_id
907                              AND    hist.posted_flag = 'Y')
908                 AND    NOT EXISTS ( SELECT 'X'
909                                      FROM pa_expenditure_items_all ei
910                                     WHERE ei.document_distribution_id = dist.invoice_distribution_id
911                                       AND ei.document_payment_id = dist.invoice_payment_id
912                                       AND ei.transaction_source = 'AP DISCOUNTS') ;
913 
914                 If g_body_debug_mode = 'Y' Then
915                 write_log(LOG, 'Number of discount distributions updated = ' || to_char(SQL%ROWCOUNT));
916                 end if;
917 
918 
919                 IF G_ACCTNG_METHOD = 'A' THEN
920 
921                 --added the following for PO RECEIPT processing
922                 UPDATE rcv_receiving_sub_ledger rcv_sub
923                    SET rcv_sub.pa_addition_flag = 'N'
924                       ,rcv_sub.request_id       = G_REQUEST_ID
925                  WHERE rcv_sub.pa_addition_flag = 'O'
926                    AND NOT EXISTS (SELECT 'X'
927                                     FROM pa_expenditure_items_all ei
928                                     WHERE  ei.document_distribution_id = rcv_sub.rcv_transaction_id);
929 
930                 If g_body_debug_mode = 'Y' Then
931 		write_log(LOG, 'Number of rcv txn cleaned up from O:' || to_char(SQL%ROWCOUNT));
932 		end if;
933 
934                 UPDATE rcv_receiving_sub_ledger rcv_sub
935                    SET rcv_sub.pa_addition_flag = 'I'
936                  WHERE rcv_sub.pa_addition_flag = 'J';
937 
938                 If g_body_debug_mode = 'Y' Then
939 		write_log(LOG, 'Number of rcv txn cleaned up from J:' || to_char(SQL%ROWCOUNT));
940 		end if;
941 
942                 ELSE --Accounting method is CASH BASIS
943 
944                 UPDATE ap_payment_hist_dists dist
945                 SET    dist.pa_addition_flag = 'N'
946                      , DIST.request_id = G_REQUEST_ID
947               	WHERE  DIST.pa_addition_flag  = 'O'
948                 AND    dist.pay_dist_lookup_code = 'CASH'
949                 AND    EXISTS (SELECT NULL
950                              FROM   ap_payment_history_all hist
951                              WHERE  hist.payment_history_id = dist.payment_history_id
952                              AND    hist.posted_flag = 'Y')
953                 AND    NOT EXISTS ( SELECT 'X'
954                                      FROM pa_expenditure_items_all ei
955                                     WHERE ei.document_distribution_id = dist.invoice_distribution_id
956                                       AND ei.document_payment_id = dist.invoice_payment_id
957                                       AND ei.transaction_source = 'AP INVOICE') ;
958 
959 		If g_body_debug_mode = 'Y' Then
960 		write_log(LOG, 'Number of payment distributions updated = ' || to_char(SQL%ROWCOUNT));
961 		end if;
962 
963                 UPDATE ap_prepay_app_dists dist
964                 SET    dist.pa_addition_flag = 'N',
965                        request_id = G_REQUEST_ID
966                 WHERE  dist.pa_addition_flag = 'O'
967                 AND    NOT EXISTS ( SELECT 'X'
968                                      FROM pa_expenditure_items_all ei
969                                      WHERE ei.document_distribution_id = dist.invoice_distribution_id
970                                        AND ei.document_payment_id = dist.prepay_app_dist_id
971                                        AND ei.transaction_source in ('AP INVOICE','AP VARIANCE','AP NRTAX','AP EXPENSE')) ;
972 
973 		If g_body_debug_mode = 'Y' Then
974 		write_log(LOG, 'Number of prepayment appl distributions updated = ' || to_char(SQL%ROWCOUNT));
975 		end if;
976 
977                 END IF;
978 
979 		commit;
980 
981             ELSE
982              	If g_body_debug_mode = 'Y' Then
983 		write_log(LOG, '......Got Lock,paapimp is running, No Clean Up ');
984 		end if;
985             END IF;
986           ELSE
987             	If g_body_debug_mode = 'Y' Then
988 		write_log(LOG, '......Could not get lock, No Clean Up');
989 		end if;
990           END IF;
991 	ELSE
992 		If g_body_debug_mode = 'Y' Then
993 		write_log(LOG, '......Did not create unique lock');
994 		end if;
995         END IF;
996 
997 	G_err_stack := v_old_stack;
998 
999 EXCEPTION
1000         WHEN Others THEN
1001 		G_err_stack := v_old_stack;
1002         	G_err_code := SQLCODE;
1003 		raise;
1004 END cleanup;
1005 
1006 
1007 /*-----------------------Populate Transaction Interface Phase---------------------*/
1008 
1009 /*---------------------------- get_mrc_flag --------------------------------------*/
1010 /* This function will return 'Y' or 'N' depending upon whether MRC is used or not */
1011 /* and ot will also populate a PL/SQL table with reporting set of books ids and   */
1012 /* Reporting currencies                                                           */
1013 /*--------------------------------------------------------------------------------*/
1014 
1015 FUNCTION get_mrc_flag RETURN VARCHAR2 IS
1016 
1017 CURSOR c_reporting_sob (p_set_of_books_id IN NUMBER,
1018                         p_org_id          IN NUMBER) IS
1019   SELECT ledger_id, currency_code
1020   FROM   gl_alc_ledger_rships_v
1021   WHERE  source_ledger_id = p_set_of_books_id
1022   AND    application_id = 275
1023   AND    org_id = p_org_id
1024   AND    relationship_enabled_flag = 'Y';
1025 
1026    l_sob NUMBER;
1027    l_org_id NUMBER;
1028    i BINARY_INTEGER := 0;
1029    v_old_stack VARCHAR2(630);
1030 
1031 BEGIN
1032 
1033    v_old_stack := G_err_stack;
1034    G_err_stack := G_err_stack || '->PAAPIMP_PKG.get_mrc_flag';
1035    G_err_code := 0;
1036 
1037    If g_body_debug_mode = 'Y' Then
1038    write_log(LOG, G_err_stack);
1039    end if;
1040 
1041    G_err_stage := 'CALLING PA_MC_CURRENCY_PKG.SET_OF_BOOKS FUNCTION';
1042    l_sob      := pa_mc_currency_pkg.set_of_books;
1043 
1044    G_err_stage := 'GET ORG_ID IN GET_MRC_FLAG';
1045    SELECT NVL(org_id,-99)
1046      INTO   l_org_id
1047      FROM pa_implementations;
1048 
1049    If g_body_debug_mode = 'Y' Then
1050    write_log(LOG,'set of book id is:'||l_sob||'org_id is:'||l_org_id);
1051    end if;
1052 
1053    FOR v_rsob IN c_reporting_sob (l_sob, l_org_id) LOOP
1054    BEGIN
1055 
1056     	i := i + 1;
1057         -- Bug 988355: g_rsob_tab is declared in the PA_MC_CURRENCY_PKG
1058        PA_MC_CURRENCY_PKG.g_rsob_tab(i).rsob_id := v_rsob.ledger_id;
1059        	PA_MC_CURRENCY_PKG.g_rsob_tab(i).rcurrency_code := v_rsob.currency_code;
1060 
1061    EXCEPTION
1062       WHEN OTHERS THEN
1063 	G_err_stack := v_old_stack;
1064 	G_err_code := SQLCODE;
1065        	RAISE;
1066    END; -- Cursor END
1067    END LOOP; -- End of Loop for cursor
1068 
1069    G_err_stack := v_old_stack;
1070 
1071    IF i = 0 then
1072      RETURN 'N';
1073    ELSE
1074      RETURN 'Y';
1075    END IF;
1076 
1077 END get_mrc_flag;
1078 
1079 
1080 FUNCTION create_new_org_transref (
1081     p_batch_name IN pa_transaction_interface.batch_name%TYPE,
1082     p_invoice_id IN ap_invoices.invoice_id%TYPE,
1083     p_invoice_distribution_id IN ap_invoice_distributions.invoice_distribution_id%TYPE)
1084       RETURN  pa_transaction_interface.orig_transaction_reference%TYPE IS
1085 
1086 BEGIN
1087 
1088     RETURN p_batch_name || '-' || to_char(p_invoice_id) || '-' || to_char(p_invoice_distribution_id, '099');
1089 
1090 END create_new_org_transref;
1091 
1092 PROCEDURE print_stat_and_submit_report IS
1093 
1094    req_id NUMBER;
1095    v_err_msg VARCHAR2(1000);
1096    v_old_stack VARCHAR2(630);
1097 
1098    l_number_of_copies NUMBER;
1099    l_print_style VARCHAR2(100);
1100    l_printer VARCHAR2(100);
1101    l_save_output_flag VARCHAR2(1);
1102    l_save_op_flag_bool boolean;
1103    result_print boolean;
1104 
1105 
1106 BEGIN
1107 
1108    /* Initialize all logging and debugging variables */
1109    v_old_stack := G_err_stack;
1110    G_err_stack := G_err_stack || '->PAAPIMP_PKG.print_stat_and_submit_report';
1111    G_err_code := 0;
1112    If g_body_debug_mode = 'Y' Then
1113    write_log(LOG, G_err_stack);
1114 
1115    write_log(LOG, 'TOTAL NUMBER OF BATCHES PROCESSED: ' || to_char(G_NUM_BATCHES_PROCESSED));
1116    write_log(LOG, 'TOTAL NUMBER OF INVOICES PROCESSED: ' || to_char(G_NUM_INVOICES_PROCESSED));
1117    write_log(LOG, 'TOTAL NUMBER OF INVOICE DISTRIBUTIONS PROCESSED: ' || to_char(G_NUM_DISTRIBUTIONS_PROCESSED));
1118    write_log(LOG, 'TOTAL NUMBER OF DISCOUNTS PROCESSED: '|| to_char(G_NUM_DISCOUNTS_PROCESSED));
1119    write_log(LOG, 'TOTAL NUMBER OF RECEIPTS PROCESSED: '||to_char(G_NUM_RCV_TXN_PROCESSED));
1120    write_log(LOG, 'TOTAL NUMBER OF RECEIPT TAX PROCESSED:'||to_char(G_NUM_RCVTAX_PROCESSED));
1121    end if;
1122 
1123    IF (G_OUTPUT = G_OUTPUT_FND) THEN
1124       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF INVOICES PROCESSED: ' || to_char(G_NUM_INVOICES_PROCESSED));
1125       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF INVOICE DISTRIBUTIONS PROCESSED: ' || to_char(G_NUM_DISTRIBUTIONS_PROCESSED));
1126       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF DISCOUNTS PROCESSED: '||to_char(G_NUM_DISCOUNTS_PROCESSED));
1127       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF RECEIPTS PROCESSED: '||to_char(G_NUM_RCV_TXN_PROCESSED));
1128       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'TOTAL NUMBER OF RECEIPT TAX PROCESSED: '||to_char(G_NUM_RCVTAX_PROCESSED));
1129 
1130       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, '----------------------------------------------------------------');
1131       FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'For detail information of this interface, please review the following report.');
1132    END IF;
1133 
1134       result_print := FND_CONCURRENT.GET_REQUEST_PRINT_OPTIONS(G_REQUEST_ID,l_number_of_copies,l_print_style,l_printer,
1135                       l_save_output_flag);
1136       IF l_save_output_flag = 'Y' THEN
1137          l_save_op_flag_bool := TRUE;
1138       ELSE l_save_op_flag_bool := FALSE;
1139       END IF;
1140       result_print := FND_REQUEST.SET_PRINT_OPTIONS(l_printer,l_print_style,l_number_of_copies,
1141                       l_save_op_flag_bool,'N');
1142 
1143       -- MOAC changes for R12
1144       FND_REQUEST.set_org_id(G_ORG_ID);
1145 
1146       /* submit request to print report */
1147       /* IC Upgrade: Since we may process mutiple transaction source at once, we can not
1148             submit the transaction source parameter */
1149       req_id := FND_REQUEST.SUBMIT_REQUEST('PA', 'PAAPIMPR', '', '', FALSE, '', /*G_TRANSACTION_SOURCE,*/
1150           G_SYSTEM_LINKAGE, '', G_REQUEST_ID);
1151 
1152      IF (req_id = 0) THEN
1153          --FND_MESSAGE.RAISE_ERROR;
1154 	fnd_message.retrieve(v_err_msg);
1155          If g_body_debug_mode = 'Y' Then
1156         WRITE_LOG (LOG, '......Error in submitting request to print report......');
1157 	WRITE_LOG (LOG, 'Error Message: ' || v_err_msg || ' END of message.');
1158 	End if;
1159 	IF (G_OUTPUT = G_OUTPUT_FND) THEN
1160 	FND_FILE.PUT_LINE(FND_FILE.OUTPUT, '...An attempt to submit the status report of the process has failed.');
1161 	END IF;
1162      ELSE
1163          If g_body_debug_mode = 'Y' Then
1164 	 WRITE_LOG( LOG, '......Request to print report submitted, Request ID: '
1165                               || to_char(req_id) || '......');
1166         end if;
1167 		IF (G_OUTPUT = G_OUTPUT_FND) THEN
1168 		FND_FILE.PUT_LINE(FND_FILE.OUTPUT, 'A status report of this process has been submitted.  Request ID: '
1169 					|| to_char(req_id));
1170 		END IF;
1171       END IF;
1172 
1173       /* restore the old G_err_stack */
1174       G_err_stack := v_old_stack;
1175 
1176    EXCEPTION
1177       WHEN Others THEN
1178          G_err_stack := v_old_stack;
1179          G_err_code := SQLCODE;
1180          RAISE;
1181 
1182 	END print_stat_and_submit_report;
1183 
1184 
1185 PROCEDURE trans_import (
1186   p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
1187   p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
1188   p_interface_id IN pa_transaction_interface.interface_id%TYPE,
1189   p_user_id IN NUMBER) IS
1190 
1191   v_old_stack VARCHAR2(630);
1192 BEGIN
1193 
1194    v_old_stack := G_err_stack;
1195    G_err_stack := G_err_stack || '->PAAPIMP_PKG.trans_import';
1196    G_err_stage := 'TRANSACTION IMPORT';
1197    G_err_code := 0;
1198 
1199    write_log(LOG, '......Transaction Import Phase For ' || p_transaction_source);
1200    write_log(LOG, G_err_stack);
1201    savepoint import; /*savepoint added for bug 2138340. The data inserted into
1202                      transaction_interface table will be saved for further
1203                      use even if rollback occurs. */
1204 
1205 
1206    write_log(LOG,'log messages from transaction import ---------------------- ');
1207   -- Changed this to IMPORT from IMPORT1 for bug#
1208    PA_TRX_IMPORT.IMPORT(X_transaction_source =>p_transaction_source
1209                         ,X_batch => p_batch_name
1210                         , X_xface_id => p_interface_id
1211                         , X_userid =>p_user_id );
1212 
1213    G_err_stack := v_old_stack;
1214    /* added for bug 2138340 */
1215    write_log(LOG,'transaction import successful');
1216 
1217 
1218    EXCEPTION
1219       WHEN OTHERS THEN
1220          G_err_stack := v_old_stack;
1221          G_err_code := SQLCODE;
1222          write_log(LOG,'transaction import failed with sqlcode = ');
1223          write_log(LOG,   G_err_code);
1224          write_log(LOG, substr(SQLERRM, 1, 200));
1225 
1226         /* start changes for bug 2138340 */
1227 
1228         p_trans_import_failed := 'Y';
1229 
1230         ROLLBACK TO SAVEPOINT import; /* 2138340 - we will rollback whatever has been done by trx import */
1231         UPDATE pa_transaction_interface
1232            SET transaction_status_code = 'R',
1233                transaction_rejection_code = 'TRX_IMPORT_ABORTED'
1234          WHERE interface_id = p_interface_id
1235            AND transaction_status_code = 'P'
1236            AND transaction_source = p_transaction_source
1237            AND batch_name = p_batch_name;
1238 
1239        /* RAISE;   don't raise so that tieback can continue  */
1240 
1241 END trans_import;
1242 
1243 /*==========================================================================*/
1244 --The following section contains procedures for Supplier Inovice and Expense
1245 --Reports processing. The codes have compeletely changed for patchset K.
1246 --Starting from patchset K, all the processing will be performed in PL/SQL
1247 --tables within a certain batch size.
1248 --The logic of Invoice processing can be undestood as:
1249 -- 1) Update PA_addition_flag on AP Invoice distribution lines to 'Z' if sum of lines
1250 --    net to zero
1251 -- 2) Update PA_addition_flag on AP Invoice distribution lines to 'O' to lock the record
1252 -- 3) Transfer_inv_to_pa populates PA transaction_interface table and call trx import
1253 -- 4) Tieback procedure called to update invoice distribution lines after trx import
1254 
1255 /*----------------------Net Zero Adjustment Phase----------------------*/
1256 /*
1257 --
1258 -- This procedure marks the pa_addition_flag of all the invoice distributions
1259 -- to 'Z' if based on the grouping condition their amount net out to zero.
1260 -- The grouping columns used are
1261 --
1262 --  1. project_id
1263 --  2. task_id
1264 --  3. expenditure_type
1265 --  4. expenditure_organization_id
1266 --  5. expenditure_item_date
1267 --  6. dist_code_combination_id
1268 --  7. invoice_id
1269 --  8. accounting_date
1270 --  9. line_type_lookup_code
1271 --
1272 -- Invoice distributions whose pa_addition_flag is marked with 'Z' will not
1273 -- be pulled to Projects.
1274 --
1275 */
1276 
1277 
1278      /*
1279      --
1280      -- VI enhancments Check what type of invoices are we transferring and
1281      -- then do net zero adjustments accordingly.  If transferring expense
1282      -- report type invoices, then do net zero adjustment only for expense
1283      -- report type invoices.  If transferring vendor invoices then do net
1284      -- zero adjustments for all invoice types, like what PAVVIT has been
1285      -- doing.
1286      */
1287 
1288      /*  Bug 4193362
1289      --  Net Zero logic should not consider a line
1290      --  where po_distribution_id is populated and another line which does not have
1291      --  po_distribution_id. When project is enabled for budgetary control, this
1292      --  scenario will lead project commitment balances data corruption.
1293      --  So for grouping Net Zeroing lines, po_distribution_id should be considered.
1294      */
1295 
1296       --
1297       -- Bug 1594498
1298       -- Due to performance reasons the single update statement was
1299       -- broken up into two update statements based on if the program
1300       -- has the value of project id (If the user has given project number
1301       -- as one of the parameters).
1302       --
1303 
1304 
1305 PROCEDURE net_zero_adjustment IS
1306 
1307    v_old_stack       	VARCHAR2(630);
1308    l_assets_add_flag 	VARCHAR2(1);
1309    l_num_dists_updated	NUMBER;
1310 
1311 BEGIN
1312 
1313      v_old_stack := G_err_stack;
1314      G_err_stack := G_err_stack || '->PAAPIMP_PKG.net_zero_adjustment';
1315      G_err_code := 0;
1316      G_err_stage := 'Updating the invoices/expense reports to Z if the distributions are encumbered';
1317 
1318     If g_body_debug_mode = 'Y' Then
1319      write_log(LOG, G_err_stack);
1320     End If;
1321 
1322      IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
1323 
1324          IF G_PROJECT_ID IS NOT NULL THEN
1325 
1326             -- This update is to mark the pa addition flag of all invoice distributions
1327             -- which have encumbered flag of 'R' .
1328             -- If the invoice distribution has a encumbered flag value of 'R' then it is
1329             -- not encumbered and there exist no Budgetery control commitment records
1330             -- for these in PA
1331 
1332 	   If g_body_debug_mode = 'Y' Then
1333              G_err_stage := 'Updating the expense reports to Z for project ';
1334              write_log(LOG, G_err_stage);
1335            End If;
1336             /* Modified the hint on following update statement for bug 6920705 */
1337             UPDATE /*+ index(dist AP_INVOICE_DISTRIBUTIONS_N14) */ ap_invoice_distributions dist
1338                  SET dist.pa_addition_flag 		=	'Z',
1339                      request_id 				=	G_REQUEST_ID,
1340                      last_update_date			=	SYSDATE,  --bug 3905111
1341                      last_updated_by			=	G_USER_ID,
1342                      last_update_login			=	G_USER_ID,
1343                      program_id					=	G_PROG_ID,
1344                      program_application_id		=	G_PROG_APPL_ID,
1345                      program_update_date		=	SYSDATE, --bug 3905111
1346                      dist.assets_addition_flag 	=	decode(G_Assets_Addition_flag,'P','P',
1347                                                    		     dist.assets_addition_flag)
1348      	       WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D', 'I', 'J', 'K', 'M', 'P', 'V', 'X', 'W')
1349                  AND dist.posted_flag||'' = 'Y'
1350                  AND dist.project_id  = G_PROJECT_ID
1351                  AND   'N' = (select cost_rate_flag
1352                                 from pa_expenditure_types
1353                                where expenditure_type = dist.expenditure_type)
1354                  AND EXISTS (SELECT invoice_id
1355                                FROM AP_INVOICES inv
1356                               WHERE inv.invoice_id = DIST.invoice_id
1357                                 AND inv.invoice_type_lookup_code = 'EXPENSE REPORT')
1358                  AND   ( nvl(dist.encumbered_flag,'N') = 'R' )
1359                  AND NOT EXISTS (SELECT NULL
1360                               FROM   ap_invoice_distributions dist1
1361                               WHERE  dist.parent_reversal_id is not null
1362                               AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1363                               AND    dist1.pa_addition_flag = 'T'
1364                               AND    dist1.encumbered_flag = 'R')
1365                  --Update historical data for Cash Based Acctng
1366                  AND  (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'));
1367 
1368     	   l_num_dists_updated := SQL%ROWCOUNT ;
1369 
1370 	   If g_body_debug_mode = 'Y' Then
1371            	write_log(LOG, 'Updated '||to_char(l_num_dists_updated)|| 'invoice distributions to Z for Encumbrance');
1372            end if;
1373 
1374 
1375          ELSE   /* Project Id is not passed */
1376 
1377             -- This update is to mark the pa addition flag of all invoice distributions
1378             -- which have encumbered flag of 'R'
1379             -- If the invoice distribution has a encumbered flag value of 'R' then it is
1380             -- not encumbered and there exist no Budgetery control commitment records
1381             -- for these in PA
1382 
1383 	   If g_body_debug_mode = 'Y' Then
1384              G_err_stage := 'Updating the expense reports to Z for all';
1385              write_log(LOG, G_err_stage);
1386            End If;
1387 
1388 
1389             UPDATE /*+ index(dist AP_INVOICE_DISTRIBUTIONS_N14)*/ ap_invoice_distributions dist /*Added for bug 6327185*/
1390                SET 	dist.pa_addition_flag 		= 	'Z',
1391                 	request_id 					= 	G_REQUEST_ID,
1392                 	last_update_date			=	SYSDATE,  --bug 3905111
1393                 	last_updated_by				= 	G_USER_ID,
1394                 	last_update_login			= 	G_USER_ID,
1395                 	program_id					= 	G_PROG_ID,
1396                 	program_application_id		= 	G_PROG_APPL_ID,
1397                 	program_update_date			=	SYSDATE, --bug 3905111
1398                 	dist.assets_addition_flag 	= 	(SELECT decode(ptype.project_type_class_code,
1399                                             				'CAPITAL','P', dist.assets_addition_flag)
1400                            							   FROM pa_project_types_all ptype, pa_projects_all proj
1401                            							  WHERE ptype.project_type = proj.project_type
1402                            								AND (ptype.org_id = proj.org_id
1403 														 OR proj.org_id is null)
1404                            								AND proj.project_id = dist.project_id)
1405 	    WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D', 'I', 'J', 'K', 'M', 'P', 'V', 'X', 'W')
1406               AND dist.posted_flag||'' = 'Y'
1407               AND dist.project_id > 0
1408               AND 'N' = (select cost_rate_flag
1409                            from pa_expenditure_types
1410                           where expenditure_type = dist.expenditure_type)
1411               AND EXISTS (SELECT invoice_id
1412                               FROM AP_INVOICES inv
1413                              WHERE inv.invoice_id = DIST.invoice_id
1414                                AND inv.invoice_type_lookup_code = 'EXPENSE REPORT')
1415               AND   ( nvl(dist.encumbered_flag,'N') = 'R' )
1416               AND NOT EXISTS (SELECT NULL
1417                               FROM   ap_invoice_distributions dist1
1418                               WHERE  dist.parent_reversal_id is not null
1419                               AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1420                               AND    dist1.pa_addition_flag = 'T'
1421                               AND    dist1.encumbered_flag = 'R')
1422               --Update historical data for Cash Based Acctng
1423               AND  (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'));
1424 
1425     	   l_num_dists_updated := SQL%ROWCOUNT ;
1426 
1427 	   If g_body_debug_mode = 'Y' Then
1428            	write_log(LOG, 'Updated '||to_char(l_num_dists_updated)|| 'invoice distributions to Z for Encumbrance');
1429            end if;
1430 
1431       END IF;
1432       --
1433       -- End of If section checking if G_PROJECT_ID is not null
1434       --
1435 
1436     ELSE
1437       --
1438       -- Bug 1594498
1439       -- Due to performance reasons the single update statement was
1440       -- broken up into two update statements based on if the program
1441       -- has the value of project id (If the user has given project number
1442       -- as one of the parameters).
1443       --
1444 
1445       IF G_PROJECT_ID IS NOT NULL THEN
1446 
1447 /* Restructured the query below for performance bug 3026625 */
1448 
1449         /* Added the following update for bug 3569296 */
1450         -- The program should update the pa_addition_flag for all encumbered lines marked as R to netzero adj flag.
1451         -- R indicates a line to be ignored by encumbrance and validation code because neither the original nor the
1452         -- reversal distributions were looked at and they offset each other so, they can be ignored and marked as Z.
1453         -- (This is set only if the parent one is not validated as well. Otherwise the reversal one will also be encumbered).
1454         -- Since these lines have been not encumbered, there exist no Budgetery control commitment records for these in PA
1455 
1456 	   If g_body_debug_mode = 'Y' Then
1457              G_err_stage := 'Updating invoice distributions to Z for project';
1458              write_log(LOG, G_err_stage);
1459            End If;
1460           /* Modified the hint on following update statement for bug 6920705 */
1461          UPDATE /*+ index(dist AP_INVOICE_DISTRIBUTIONS_N14) */ ap_invoice_distributions dist
1462             SET dist.pa_addition_flag = 'Z',
1463                 request_id = G_REQUEST_ID,
1464                 last_update_date=SYSDATE, --bug 3905111
1465                 last_updated_by= G_USER_ID,
1466                 last_update_login= G_USER_ID,
1467                 program_id= G_PROG_ID,
1468                 program_application_id= G_PROG_APPL_ID,
1469                 program_update_date=SYSDATE, --bug 3905111
1470                 dist.assets_addition_flag = decode(G_Assets_Addition_flag,'P','P',
1471                                                    dist.assets_addition_flag)
1472          WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'P','V', 'X', 'W')
1473            AND dist.posted_flag||'' = 'Y'
1474            AND dist.project_id = G_PROJECT_ID
1475            AND ( nvl(dist.encumbered_flag,'N') = 'R' )
1476            --Update historical data for Cash Based Acctng
1477            AND  (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
1478            AND NOT EXISTS (SELECT NULL
1479                            FROM   ap_invoice_distributions dist1
1480                            WHERE  dist.parent_reversal_id is not null
1481                            AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1482                            AND    dist1.pa_addition_flag = 'T'
1483                            AND    dist1.encumbered_flag = 'R')
1484            AND EXISTS (SELECT invoice_id
1485                          FROM AP_INVOICES inv
1486                         WHERE inv.invoice_id = DIST.invoice_id
1487                           AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT');
1488 
1489       	write_log(LOG, 'Updated '||to_char(SQL%ROWCOUNT)|| 'invoice distributions to Z for Encumbrance');
1490 
1491 
1492      ELSE /* G_PROJECT_ID is null */
1493 
1494 
1495             -- This update is to mark the pa addition flag of all invoice distributions
1496             -- which have encumbered flag of 'R' or reversal flag of 'Y' to 'Z'.
1497             -- Encumbrance flag of 'R' or reversal flag of 'Y' indicates that they are
1498             -- exact reversal of another invoice distribution.
1499             -- If the invoice distribution has a encumbered flag value of 'R' then it is
1500             -- not encumbered and there exist no Budgetery control commitment records
1501             -- for these in PA
1502 
1503 	   If g_body_debug_mode = 'Y' Then
1504              G_err_stage := 'Updating invoice distributions to Z for all';
1505              write_log(LOG, G_err_stage);
1506            End If;
1507 
1508             UPDATE /*+ index(dist AP_INVOICE_DISTRIBUTIONS_N14)*/ ap_invoice_distributions dist /*Added for bug 6327185*/
1509                SET 	dist.pa_addition_flag 	= 	'Z',
1510                 	request_id 				= 	G_REQUEST_ID,
1511                 	last_update_date		=	SYSDATE,  --bug 3905111
1512                 	last_updated_by			= 	G_USER_ID,
1513                 	last_update_login		= 	G_USER_ID,
1514                 	program_id				= 	G_PROG_ID,
1515                 	program_application_id	= 	G_PROG_APPL_ID,
1516                 	program_update_date		=	SYSDATE,  --bug 3905111
1517                 	dist.assets_addition_flag = (SELECT decode(ptype.project_type_class_code,
1518                                             			'CAPITAL','P', dist.assets_addition_flag)
1519                            						   FROM pa_project_types_all ptype, pa_projects_all proj
1520                            						  WHERE ptype.project_type = proj.project_type
1521                            						    AND (ptype.org_id = proj.org_id OR
1522                                    						proj.org_id is null)
1523                            						    AND proj.project_id = dist.project_id)
1524              WHERE dist.pa_addition_flag IN ('N', 'S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'P','V', 'X', 'W')
1525                AND   dist.posted_flag||'' = 'Y'
1526                AND   dist.project_id > 0
1527                AND   (nvl(dist.encumbered_flag,'N') = 'R' )
1528                --Update historical data for Cash Based Acctng
1529                AND  (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
1530                AND NOT EXISTS (SELECT NULL
1531                               FROM   ap_invoice_distributions dist1
1532                               WHERE  dist.parent_reversal_id is not null
1533                               AND    dist.parent_reversal_id = dist1.invoice_distribution_id
1534                               AND    dist1.pa_addition_flag = 'T'
1535                               AND    dist1.encumbered_flag = 'R')
1536            AND EXISTS (SELECT invoice_id
1537                          FROM AP_INVOICES inv
1538                         WHERE inv.invoice_id = DIST.invoice_id
1539                           AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT');
1540 
1541       	write_log(LOG, 'Updated '||to_char(SQL%ROWCOUNT)|| 'invoice distributions to Z for Encumbrance');
1542 
1543      END IF;
1544       --
1545       -- End of If section checking if G_PROJECT_ID is not null
1546       --
1547 
1548      END IF;
1549 G_err_stack := v_old_stack;
1550 
1551 EXCEPTION
1552         WHEN Others THEN
1553                /*
1554                --
1555                -- Exceptions occured in this procedure must be raised by the
1556                -- UPDATE statement, most likely a fatal error like 'rollback
1557                -- segment exceeded' error which should cause the program to
1558                -- terminate
1559                --
1560                */
1561 
1562 	       G_err_stack := v_old_stack;
1563                G_err_code := SQLCODE;
1564 	       raise;
1565 
1566 
1567 END net_zero_adjustment;
1568 
1569 FUNCTION check_prepay_fully_applied(p_prepay_dist_id in NUMBER)
1570    RETURN VARCHAR2 IS
1571 
1572   l_prepay_rem_amt      NUMBER;
1573 
1574 BEGIN
1575 
1576        SELECT prepay_amount_remaining
1577        INTO   l_prepay_rem_amt
1578        FROM   ap_invoice_distributions_All
1579        WHERE  invoice_distribution_id = p_prepay_dist_id;
1580 
1581    -- ==================================================================================
1582    -- Bug: 5393523
1583    --    : R12.PJ:XB6:QA:APL: STANDARD INVOICES / PREPAYMENTS NOT SHOWN AS COMMITTMENT
1584    --      Unpaid prepayments invoice has NULL prepay_amount_remaining and it should not
1585    --      mislead as fully applied prepayment.
1586    -- ==================================================================================
1587    IF l_prepay_rem_amt is NULL THEN
1588       RETURN 'N' ;
1589    ELSIF l_prepay_rem_amt = 0 THEN
1590       RETURN 'Y';
1591    ELSE
1592       RETURN 'N';
1593    END IF;
1594 
1595 EXCEPTION
1596 
1597 WHEN Others THEN
1598 
1599    write_log(LOG, 'Exception in check_prepay_fully_applied');
1600    G_err_code := SQLCODE;
1601    RAISE;
1602 
1603 END check_prepay_fully_applied;
1604 
1605 /*-----------------------Marking Distribution Phase---------------------*/
1606 
1607 PROCEDURE mark_PAflag_O IS
1608 
1609         v_old_stack VARCHAR2(630);
1610 
1611 BEGIN
1612 
1613      v_old_stack := G_err_stack;
1614      G_err_stack := G_err_stack || '->PAAPIMP_PKG.mark_PAflag_O';
1615      G_err_code := 0;
1616      G_err_stage := 'UPDATING INVOICE DISTRIBUTIONS-Marking Process';
1617 
1618      write_log(LOG, G_err_stack);
1619       /* VI enhancements */
1620 
1621 
1622      IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
1623 
1624                    --
1625                    -- This section is for Expense Reports
1626                    --
1627 
1628           write_log(LOG, 'Marking Expense Report type invoices for processing...');
1629                    --
1630                    -- Due to performance reasons the single update statement was
1631                    -- broken up into two update statements based on if the program
1632                    -- has the value of project id (If the user has given project number
1633                    -- as one of the parameters).
1634                    --
1635 
1636       IF G_PROJECT_ID IS NOT NULL THEN
1637 
1638         -- In Cash Based Accounting all historical Invoices and their adjustments in AP will continue to be interfaced as Invoice distributions
1639         -- and NOT Payment lines
1640 
1641         IF G_ACCTNG_METHOD = 'C' THEN --CAsh BAsed Accounting
1642 
1643           write_log(LOG, 'Marking invoices to O for Historical Data interface in Cash Based Acctng');
1644 
1645           UPDATE  AP_Invoice_distributions DIST
1646              SET  DIST.Pa_Addition_Flag ='O',
1647                   request_id = G_REQUEST_ID,
1648                   last_update_date=SYSDATE,
1649                   last_updated_by=G_USER_ID,
1650                   last_update_login= G_USER_ID,
1651                   program_id= G_PROG_ID,
1652                   program_application_id= G_PROG_APPL_ID,
1653                   program_update_date=SYSDATE
1654            WHERE  DIST.Posted_Flag||'' = 'Y'
1655              AND  DIST.Pa_Addition_Flag IN
1656                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
1657              AND DIST.project_id > 0
1658              AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
1659              AND ((
1660                   exists (SELECT NULL
1661                            FROM AP_INVOICES inv,
1662                                 AP_Invoice_distributions DIST1,
1663                                 PO_VENDORS vend
1664                           WHERE inv.invoice_id = DIST1.invoice_id
1665                             AND DIST1.invoice_distribution_id = DIST.invoice_distribution_id
1666                             AND INV.payment_status_flag = 'Y'                                   -- Flag indicated FULLY paid inv
1667                             AND DIST1.historical_flag = 'Y'                                     -- process historical dist as invoices in Cash Based Acctng
1668                             AND inv.vendor_id = vend.vendor_id
1669                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
1670                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1671                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
1672                                  OR
1673                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
1674                                  AND inv.source in ('CREDIT CARD','Both Pay')
1675                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0))))
1676                  OR
1677                   (EXISTS ( SELECT NULL
1678                            FROM  PO_VENDORS vend1,
1679                                  ap_invoices inv1,
1680                                  ap_invoice_distributions dist2
1681                            WHERE inv1.invoice_id = dist2.invoice_id
1682                            AND   inv1.invoice_id = dist.invoice_id
1683                            AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
1684                            AND   dist2.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
1685                            AND   dist2.pa_addition_flag = 'Y'
1686                            AND   inv1.vendor_id = vend1.vendor_id
1687                            AND ((inv1.invoice_type_lookup_code = G_INVOICE_TYPE
1688                                  AND inv1.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1689                                  AND (vend1.employee_id IS NOT NULL or nvl(inv1.paid_on_behalf_employee_id,0) > 0))
1690                                 OR
1691                                 (inv1.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED')
1692                                  AND inv1.source  in ('CREDIT CARD','Both Pay')
1693                                  AND nvl(inv1.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0))))
1694                  )
1695              AND DIST.project_id = G_PROJECT_ID
1696              AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date))
1697              AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date));
1698 
1699         G_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
1700         write_log(LOG, 'Number of Historical rows marked to O: ' || to_char(SQL%ROWCOUNT));
1701 
1702         /* Historical Data Processing for Prepayments */
1703         /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
1704            Pre Rel12 Upgrade should also be brought into Projects */
1705 
1706           write_log(LOG, 'Marking Historical Prepayments for processing...');
1707 
1708             UPDATE ap_invoice_distributions_all dist
1709             SET    dist.pa_addition_flag = 'O',
1710                    request_id = G_REQUEST_ID,
1711                    last_update_date=SYSDATE,
1712                    last_updated_by= G_USER_ID,
1713                    last_update_login= G_USER_ID,
1714                    program_id= G_PROG_ID,
1715                    program_application_id= G_PROG_APPL_ID,
1716                    program_update_date=SYSDATE
1717             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
1718             AND   DIST.project_id > 0
1719             AND   dist.posted_flag = 'Y'
1720             AND   dist.project_id = G_PROJECT_ID
1721             --AND   dist.line_type_lookup_code = 'PREPAY'
1722             AND   dist.line_type_lookup_code <> 'REC_TAX'
1723             AND   dist.prepay_distribution_id is not null
1724             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
1725             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
1726             AND   exists (SELECT NULL
1727                            FROM AP_INVOICES inv,
1728                                 PO_VENDORS vend
1729                           WHERE inv.invoice_id = DIST.invoice_id
1730                             AND inv.vendor_id = vend.vendor_id
1731                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
1732                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1733                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
1734                                  OR
1735                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
1736                                  AND inv.source in ('CREDIT CARD','Both Pay')
1737                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)))
1738             AND   exists(SELECT inv.invoice_id
1739                          FROM    AP_INVOICES inv,
1740                                  AP_Invoice_Distributions_all aid
1741                           WHERE aid.invoice_id = inv.invoice_id
1742                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
1743                             AND aid.historical_flag = 'Y'
1744                             AND aid.pa_addition_flag = 'Y'
1745                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
1746                  );
1747 
1748             G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
1749             write_log(LOG, 'Number of Historical PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
1750 
1751           ELSE --Accounting Method is Accrual
1752 
1753           write_log(LOG, 'Marking Expense Report type invoices for processing - Accrual Acct');
1754 
1755              UPDATE  AP_Invoice_distributions DIST
1756                 SET  DIST.Pa_Addition_Flag ='O',
1757                      request_id = G_REQUEST_ID,
1758                      last_update_date=SYSDATE,
1759                      last_updated_by=G_USER_ID,
1760                      last_update_login= G_USER_ID,
1761                      program_id= G_PROG_ID,
1762                      program_application_id= G_PROG_APPL_ID,
1763                      program_update_date=SYSDATE
1764               WHERE  DIST.Posted_Flag||'' = 'Y'
1765                 AND  DIST.Pa_Addition_Flag IN
1766                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
1767                 AND DIST.project_id > 0
1768                 AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
1769                 AND exists (SELECT NULL
1770                               FROM AP_INVOICES inv,
1771                                    PO_VENDORS vend
1772                              WHERE inv.invoice_id = DIST.invoice_id
1773                                AND inv.vendor_id = vend.vendor_id
1774                                AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
1775                                      AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1776                                      AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
1777                                     OR
1778                                    (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
1779                                     AND inv.source   in ('CREDIT CARD','Both Pay')
1780                                     AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)))
1781                AND DIST.project_id = G_PROJECT_ID
1782                AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date)) /*GSCC*//* added trunc for the bug 6623163 */
1783                AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date));   /*GSCC*//* added trunc for the bug 6623163 */
1784 
1785                G_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
1786 
1787         End If; --End of CAsh BAsed Accounting
1788 
1789       ELSE /* G_PROJECT_ID IS NULL */
1790 
1791         IF G_ACCTNG_METHOD = 'C' THEN
1792 
1793           write_log(LOG, 'Marking invoices to O for Historical Data interface in Cash Based Acctng');
1794 
1795           UPDATE  AP_Invoice_distributions DIST
1796              SET  DIST.Pa_Addition_Flag ='O',
1797                   request_id = G_REQUEST_ID,
1798                   last_update_date=SYSDATE,
1799                   last_updated_by=G_USER_ID,
1800                   last_update_login= G_USER_ID,
1801                   program_id= G_PROG_ID,
1802                   program_application_id= G_PROG_APPL_ID,
1803                   program_update_date=SYSDATE
1804            WHERE  DIST.Posted_Flag||'' = 'Y'
1805              AND  DIST.Pa_Addition_Flag IN
1806                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
1807              AND DIST.project_id > 0
1808              AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
1809              AND (
1810                   (exists (SELECT NULL
1811                            FROM AP_INVOICES inv,
1812                                 AP_Invoice_distributions DIST1,
1813                                 PO_VENDORS vend
1814                           WHERE inv.invoice_id = DIST1.invoice_id
1815                             AND DIST1.invoice_distribution_id = DIST.invoice_distribution_id
1816                             AND INV.payment_status_flag = 'Y'                                   -- Flag indicated FULLY paid inv
1817                             AND DIST1.historical_flag = 'Y'                                     --process historical dist as invoices in Cash Based Acctng
1818                             AND inv.vendor_id = vend.vendor_id
1819                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
1820                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1821                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
1822                                  OR
1823                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
1824                                  AND inv.source    in ('CREDIT CARD','Both Pay')
1825                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0))))
1826                  OR
1827                   (EXISTS ( SELECT NULL
1828                            FROM  PO_VENDORS vend1,
1829                                  ap_invoices inv1, ap_invoice_distributions dist2
1830                            WHERE inv1.invoice_id = dist2.invoice_id
1831                            AND   inv1.invoice_id = dist.invoice_id
1832                            AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
1833                            AND   dist2.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
1834                            AND   dist2.pa_addition_flag = 'Y'
1835                            AND   inv1.vendor_id = vend1.vendor_id
1836                            AND ((inv1.invoice_type_lookup_code = G_INVOICE_TYPE
1837                                  AND inv1.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1838                                  AND (vend1.employee_id IS NOT NULL or nvl(inv1.paid_on_behalf_employee_id,0) > 0))
1839                                 OR
1840                                (inv1.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
1841                                 AND inv1.source in ('CREDIT CARD','Both Pay')
1842                                 AND nvl(inv1.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0))))
1843                  )
1844              AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date)) /*GSCC*/
1845              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*/
1846         G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
1847         write_log(LOG, 'Number of Historical rows marked to O: ' || to_char(SQL%ROWCOUNT));
1848 
1849         /* Historical Data Processing for Prepayments */
1850         /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
1851            Pre Rel12 Upgrade should also be brought into Projects */
1852 
1853           write_log(LOG, 'Marking Historical Prepayments for processing...');
1854 
1855             UPDATE ap_invoice_distributions dist
1856             SET    dist.pa_addition_flag = 'O',
1857                    request_id = G_REQUEST_ID,
1858                    last_update_date=SYSDATE,
1859                    last_updated_by= G_USER_ID,
1860                    last_update_login= G_USER_ID,
1861                    program_id= G_PROG_ID,
1862                    program_application_id= G_PROG_APPL_ID,
1863                    program_update_date=SYSDATE
1864             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
1865             AND   DIST.project_id > 0
1866             AND   dist.posted_flag = 'Y'
1867             --AND   dist.line_type_lookup_code = 'PREPAY'
1868             AND   dist.line_type_lookup_code <> 'REC_TAX'
1869             AND   dist.prepay_distribution_id is not null
1870             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
1871             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
1872             AND   exists (SELECT NULL
1873                            FROM AP_INVOICES_ALL inv,
1874                                 PO_VENDORS vend
1875                           WHERE inv.invoice_id = DIST.invoice_id
1876                             AND inv.vendor_id = vend.vendor_id
1877                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
1878                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1879                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
1880                                  OR
1881                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
1882                                  AND inv.source  in ('CREDIT CARD','Both Pay')
1883                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)))
1884             AND   exists(SELECT inv.invoice_id
1885                          FROM    AP_INVOICES_ALL inv,
1886                                  AP_Invoice_Distributions_all aid
1887                           WHERE aid.invoice_id = inv.invoice_id
1888                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
1889                             AND aid.historical_flag = 'Y'
1890                             AND aid.pa_addition_flag = 'Y'
1891                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
1892                   );
1893 
1894             G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
1895             write_log(LOG, 'Number of Historical PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
1896 
1897           ELSE --Accounting Method is Accrual
1898 
1899           write_log(LOG, 'Marking Expense Report type invoices for processing - Accrual Acct');
1900 
1901             UPDATE  /*+ index(DIST AP_INVOICE_DISTRIBUTIONS_N14)*/ AP_Invoice_distributions DIST /*Added for bug 6327185*/
1902                SET  DIST.Pa_Addition_Flag ='O', /*Bug#2168903*/
1903                     request_id = G_REQUEST_ID,
1904                     last_update_date=SYSDATE,  --bug 3905111
1905                     last_updated_by=G_USER_ID,
1906                     last_update_login= G_USER_ID,
1907                     program_id= G_PROG_ID,
1908                     program_application_id= G_PROG_APPL_ID,
1909                     program_update_date=SYSDATE   --bug 3905111
1910              WHERE  DIST.Posted_Flag||'' = 'Y'
1911                AND  DIST.Pa_Addition_Flag IN                           /*Bug#1727504*/
1912                           ('S', 'A', 'B', 'C', 'D', 'I', 'N', 'J', 'K', 'M', 'P','Q', 'V', 'X', 'W')
1913                AND DIST.project_id > 0
1914                AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
1915 	       AND exists (SELECT invoice_id
1916                              FROM AP_INVOICES_ALL inv,
1917                                   PO_VENDORS vend
1918                             WHERE inv.invoice_id = DIST.invoice_id
1919                               AND inv.vendor_id = vend.vendor_id
1920                               AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
1921                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
1922                                     AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
1923                                    OR
1924                                   (inv.invoice_type_lookup_code    in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*//*Bug 4099522*/
1925                                    AND inv.source  in ('CREDIT CARD','Both Pay')
1926                                    AND nvl(inv.paid_on_behalf_employee_id,0) > 0)))
1927                AND trunc(DIST.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,DIST.expenditure_item_date)) /*GSCC*//* added trunc for the bug 6623163 */
1928                AND trunc(DIST.accounting_date) <= trunc(nvl(G_GL_DATE,DIST.accounting_date)); /*GSCC*/
1929 
1930             G_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
1931             write_log(LOG, 'Number of rows marked to O: ' || to_char(SQL%ROWCOUNT));
1932 
1933           END IF; --End of CAsh BAsed Accounting
1934 
1935         END IF; /* END IF Project ID */
1936 
1937      ELSE
1938 
1939 	   write_log(LOG, 'Marking supplier invoices for processing...');
1940 
1941              --
1942              -- Due to performance reasons the single update statement was
1943              -- broken up into two update statements based on if the program
1944              -- has the value of project id (If the user has given project number
1945              -- as one of the parameters).
1946              --
1947 
1948        IF G_PROJECT_ID IS NOT NULL THEN
1949 
1950           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
1951         If g_body_debug_mode = 'Y' Then
1952 	   write_log(LOG, 'Marking supplier invoices for project = '||G_PROJECT_ID);
1953 	   write_log(LOG, 'Marking supplier invoices for G_GL_DATE = '||G_GL_DATE);
1954 	   write_log(LOG, 'Marking supplier invoices for G_TRANSACTION_DATE = '||G_TRANSACTION_DATE);
1955         End If;
1956 
1957          -- For CASH based Accntg we will continue to bring Historical data as Invoices and not Payments
1958          -- Any reversals made to the historical Invoices should also be brought into projects as Invoices and not Payments
1959 
1960          IF G_ACCTNG_METHOD = 'C' THEN
1961 
1962 	   write_log(LOG, 'Marking invoices to O for Historical Data interface in Cash Based Acctng');
1963 
1964            UPDATE AP_Invoice_Distributions DIST
1965               SET DIST.Pa_Addition_Flag = 'O',
1966                   request_id = G_REQUEST_ID,
1967                   last_update_date=SYSDATE,
1968                   last_updated_by=G_USER_ID,
1969                   last_update_login=G_USER_ID,
1970                   program_id=G_PROG_ID,
1971                   program_application_id=G_PROG_APPL_ID,
1972                   program_update_date=SYSDATE
1973             WHERE DIST.Posted_Flag = 'Y'
1974               AND DIST.Pa_Addition_Flag IN
1975                   ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
1976               AND DIST.project_id > 0
1977               AND trunc(DIST.Accounting_Date) <= trunc(nvl(G_GL_DATE,DIST.Accounting_Date))   /*GSCC*//* added trunc for the bug 6623163 */
1978               AND trunc(DIST.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,DIST.Expenditure_Item_Date))       /*GSCC*/ /* added trunc for the bug 6623163 */
1979               AND DIST.project_id = G_PROJECT_ID
1980               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
1981               AND (
1982                   EXISTS (
1983                     SELECT NULL
1984                     FROM ap_invoices_all inv,
1985                          po_distributions_all PO,
1986                          ap_invoice_distributions_all dist2
1987                     WHERE inv.invoice_id = dist2.invoice_id
1988                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
1989                     AND dist2.invoice_id = DIST.invoice_id
1990                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
1991                     AND inv.payment_status_flag = 'Y'                                -- Flag indicates that Invoice has been FULLY paid
1992                     AND dist2.historical_flag = 'Y'                                    --Process Historical data as Invoices in Cash based
1993                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
1994                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
1995                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
1996                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
1997                     AND ( nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting',
1998                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
1999 			  or dist2.line_type_lookup_code = 'NONREC_TAX'
2000 			 )
2001                     )
2002                   OR
2003                   EXISTS (
2004                     SELECT NULL
2005                     FROM ap_invoices_all inv1,
2006                          ap_invoice_distributions_all dist3
2007                     WHERE inv1.invoice_id = dist3.invoice_id
2008                     AND   inv1.invoice_id = dist.invoice_id
2009                     AND   inv1.invoice_type_lookup_code <> 'EXPENSE REPORT'
2010                     AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
2011                     AND   dist3.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
2012                     AND   dist3.pa_addition_flag = 'Y')
2013                   )
2014                 /* Bug 6353803: Added the following for this bug. */
2015   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2016                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2017 		    AND NOT EXISTS (SELECT 'X'
2018 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2019 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2020 				    AND pod.po_line_id = pol.po_line_id
2021 				    AND   si.inventory_item_id = pol.item_id
2022 				    AND   si.comms_nl_trackable_flag = 'Y'
2023 				    AND   si.organization_id = pod.org_id
2024 				    )
2025 		    AND NOT EXISTS (SELECT 'X'
2026 			      FROM
2027 				ap_invoice_distributions apdist,
2028 				po_distributions pod,
2029 				mtl_system_items si,
2030 				po_lines_all pol
2031 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2032                                     = apdist.INVOICE_DISTRIBUTION_ID
2033 				  and apdist.po_distribution_id = pod.po_distribution_id
2034 				  and pod.po_line_id = pol.po_line_id
2035 				  and si.inventory_item_id = pol.item_id
2036 				  AND   si.comms_nl_trackable_flag = 'Y'
2037 				  AND   si.organization_id = pod.org_id
2038 					     )
2039 		    )
2040                   );
2041 
2042               G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
2043               write_log(LOG, 'Number of Historical Invoice Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2044 
2045 
2046         /* Historical Data Processing for Prepayments */
2047         /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
2048            Pre Rel12 Upgrade should also be brought into Projects */
2049 
2050 	   write_log(LOG, 'Marking PREPAYMENT invoices in Cash Based Acctng');
2051 
2052             UPDATE ap_invoice_distributions_all dist
2053             SET    dist.pa_addition_flag = 'O',
2054                    request_id = G_REQUEST_ID,
2055                    last_update_date=SYSDATE,
2056                    last_updated_by= G_USER_ID,
2057                    last_update_login= G_USER_ID,
2058                    program_id= G_PROG_ID,
2059                    program_application_id= G_PROG_APPL_ID,
2060                    program_update_date=SYSDATE
2061             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
2062             AND   DIST.project_id > 0
2063             AND   dist.posted_flag = 'Y'
2064             AND   dist.project_id = G_PROJECT_ID
2065             --AND   dist.line_type_lookup_code = 'PREPAY'
2066             AND   dist.line_type_lookup_code <> 'REC_TAX'
2067             AND   dist.prepay_distribution_id is not null
2068             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
2069             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
2070             AND   EXISTS (
2071                     SELECT NULL
2072                     FROM ap_invoices inv
2073                     WHERE inv.invoice_id = dist.invoice_id
2074                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2075                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2076                     AND nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting',
2077                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')  )
2078             AND   exists(SELECT inv.invoice_id
2079                            FROM AP_INVOICES inv,
2080                                 AP_Invoice_Distributions_all aid
2081                           WHERE aid.invoice_id = inv.invoice_id
2082                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
2083                             AND aid.historical_flag = 'Y'
2084                             AND aid.pa_addition_flag = 'Y'
2085                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
2086                             AND aid.project_id = G_PROJECT_ID)
2087                 /* Bug 6353803: Added the following for this bug. */
2088   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2089                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2090 		    AND NOT EXISTS (SELECT 'X'
2091 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2092 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2093 				    AND pod.po_line_id = pol.po_line_id
2094 				    AND   si.inventory_item_id = pol.item_id
2095 				    AND   si.comms_nl_trackable_flag = 'Y'
2096 				    AND   si.organization_id = pod.org_id
2097 				    )
2098 		    AND NOT EXISTS (SELECT 'X'
2099 			      FROM
2100 				ap_invoice_distributions apdist,
2101 				po_distributions pod,
2102 				mtl_system_items si,
2103 				po_lines_all pol
2104 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2105                                     = apdist.INVOICE_DISTRIBUTION_ID
2106 				  and apdist.po_distribution_id = pod.po_distribution_id
2107 				  and pod.po_line_id = pol.po_line_id
2108 				  and si.inventory_item_id = pol.item_id
2109 				  AND   si.comms_nl_trackable_flag = 'Y'
2110 				  AND   si.organization_id = pod.org_id
2111 					     )
2112 		    )
2113                   );
2114 
2115             G_DISTRIBUTIONS_MARKED :=nvl(G_DISTRIBUTIONS_MARKED ,0) +  SQL%ROWCOUNT;
2116             write_log(LOG, 'Number of Historical PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2117 
2118 
2119          ELSE -- Accrual BAsed Acctng
2120 
2121 	   write_log(LOG, 'Marking invoices in Accrual based Acctng');
2122 
2123            UPDATE AP_Invoice_Distributions DIST
2124               SET DIST.Pa_Addition_Flag = 'O',
2125                   request_id = G_REQUEST_ID,
2126                   last_update_date=SYSDATE,
2127                   last_updated_by=G_USER_ID,
2128                   last_update_login=G_USER_ID,
2129                   program_id=G_PROG_ID,
2130                   program_application_id=G_PROG_APPL_ID,
2131                   program_update_date=SYSDATE
2132             WHERE DIST.Posted_Flag = 'Y'
2133               AND DIST.Pa_Addition_Flag IN
2134                    ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
2135               AND DIST.project_id > 0
2136               AND trunc(DIST.Accounting_Date) <= trunc(nvl(G_GL_DATE,DIST.Accounting_Date))   /*GSCC*/
2137               AND trunc(DIST.Expenditure_Item_Date) <=
2138                        trunc(NVL(G_TRANSACTION_DATE,DIST.Expenditure_Item_Date))       /*GSCC*/
2139               AND DIST.project_id = G_PROJECT_ID
2140               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2141               AND EXISTS (
2142                   SELECT NULL
2143                     FROM ap_invoices_all inv,
2144                          po_distributions_all PO,
2145                          ap_invoice_distributions_all dist2
2146                     WHERE inv.invoice_id = dist2.invoice_id
2147                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
2148                     AND dist2.invoice_id = DIST.invoice_id
2149                     /*credit card txn enhancement, make sure this update doesn't pick tehm */
2150                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2151                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
2152                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
2153                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
2154                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2155                     AND  (
2156 			nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
2157 			or
2158 			 dist2.line_type_lookup_code = 'NONREC_TAX'
2159 			 )
2160                         )
2161                 /* Bug 6353803: Added the following for this bug. */
2162   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2163                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2164 		    AND NOT EXISTS (SELECT 'X'
2165 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2166 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2167 				    AND pod.po_line_id = pol.po_line_id
2168 				    AND   si.inventory_item_id = pol.item_id
2169 				    AND   si.comms_nl_trackable_flag = 'Y'
2170 				    AND   si.organization_id = pod.org_id
2171 				    )
2172 		    AND NOT EXISTS (SELECT 'X'
2173 			      FROM
2174 				ap_invoice_distributions apdist,
2175 				po_distributions pod,
2176 				mtl_system_items si,
2177 				po_lines_all pol
2178 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2179                                     = apdist.INVOICE_DISTRIBUTION_ID
2180 				  and apdist.po_distribution_id = pod.po_distribution_id
2181 				  and pod.po_line_id = pol.po_line_id
2182 				  and si.inventory_item_id = pol.item_id
2183 				  AND   si.comms_nl_trackable_flag = 'Y'
2184 				  AND   si.organization_id = pod.org_id
2185 					     )
2186 		    )
2187                   );
2188 
2189 	      G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
2190               write_log(LOG, 'Number of rows marked to O: ' || to_char(SQL%ROWCOUNT));
2191 
2192          END IF; -- End of Accntg Method is CASH
2193 
2194        ELSE          /* G_PROJECT_ID IS NULL */
2195 
2196 
2197          -- For CASH based Accntg we will continue to bring Historical data as Invoices and not Payments
2198          -- Any reversals made to the historical Invoices should also be brought into projects as Invoices and not Payments
2199 
2200          IF G_ACCTNG_METHOD = 'C' THEN
2201 
2202 	   write_log(LOG, 'Marking invoices to O for Historical Data interface in Cash Based Acctng');
2203 
2204            UPDATE AP_Invoice_Distributions DIST
2205               SET DIST.Pa_Addition_Flag = 'O',
2206                   request_id = G_REQUEST_ID,
2207                   last_update_date=SYSDATE,
2208                   last_updated_by=G_USER_ID,
2209                   last_update_login=G_USER_ID,
2210                   program_id=G_PROG_ID,
2211                   program_application_id=G_PROG_APPL_ID,
2212                   program_update_date=SYSDATE
2213             WHERE DIST.Posted_Flag = 'Y'
2214               AND DIST.Pa_Addition_Flag IN
2215                   ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
2216               AND DIST.project_id > 0
2217               AND trunc(DIST.Accounting_Date) <= trunc(nvl(G_GL_DATE,DIST.Accounting_Date))   /*GSCC*/ /*Added trunc for the bug 6623163 */
2218               AND trunc(DIST.Expenditure_Item_Date) <=
2219                      trunc(NVL(G_TRANSACTION_DATE,DIST.Expenditure_Item_Date))       /*GSCC*/  /*Added trunc for the bug 6623163 */
2220               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2221               AND (
2222                   EXISTS (
2223                     SELECT NULL
2224                     FROM ap_invoices_all inv,
2225                          po_distributions_all PO,
2226                          ap_invoice_distributions_all dist2
2227                     WHERE inv.invoice_id = dist2.invoice_id
2228                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
2229                     AND dist2.invoice_id = DIST.invoice_id
2230                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
2231                     AND inv.payment_status_flag = 'Y'                                 -- Flag indicates that Invoice has been FULLY paid
2232                     AND dist2.historical_flag = 'Y'                                     --Process Historical data as Invoices in Cash based
2233                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
2234                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
2235                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2236                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2237                     AND ( nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting',
2238                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
2239                         or dist2.line_type_lookup_code = 'NONREC_TAX')
2240                        )
2241                   OR
2242                   EXISTS (
2243                     SELECT NULL
2244                     FROM ap_invoices inv1,
2245                          ap_invoice_distributions dist3
2246                     WHERE inv1.invoice_id = dist3.invoice_id
2247                     AND   inv1.invoice_id = dist.invoice_id
2248                     AND   inv1.invoice_type_lookup_code <> 'EXPENSE REPORT'
2249                     AND   (dist.reversal_flag = 'Y' or dist.cancellation_flag = 'Y' )
2250                     AND   dist3.invoice_distribution_id = dist.parent_reversal_id      --Process Historical data reversals as Invoices in Cash based
2251                     AND   dist3.pa_addition_flag = 'Y')
2252                   )
2253                 /* Bug 6353803: Added the following for this bug. */
2254   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2255                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2256 		    AND NOT EXISTS (SELECT 'X'
2257 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2258 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2259 				    AND pod.po_line_id = pol.po_line_id
2260 				    AND   si.inventory_item_id = pol.item_id
2261 				    AND   si.comms_nl_trackable_flag = 'Y'
2262 				    AND   si.organization_id = pod.org_id
2263 				    )
2264 		    AND NOT EXISTS (SELECT 'X'
2265 			      FROM
2266 				ap_invoice_distributions apdist,
2267 				po_distributions pod,
2268 				mtl_system_items si,
2269 				po_lines_all pol
2270 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2271                                     = apdist.INVOICE_DISTRIBUTION_ID
2272 				  and apdist.po_distribution_id = pod.po_distribution_id
2273 				  and pod.po_line_id = pol.po_line_id
2274 				  and si.inventory_item_id = pol.item_id
2275 				  AND   si.comms_nl_trackable_flag = 'Y'
2276 				  AND   si.organization_id = pod.org_id
2277 					     )
2278 		    )
2279                   );
2280 
2281 
2282               G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
2283               write_log(LOG, 'Number of Historical Inv Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2284 
2285            /* Historical Data Processing for Prepayments */
2286            /* All PREPAY application distributions that relate to PREPAYMENT invoice that was already interfaced into PRojects
2287               Pre Rel12 Upgrade should also be brought into Projects */
2288 
2289           write_log(LOG, 'Marking Historical Prepayments for processing...');
2290 
2291             UPDATE ap_invoice_distributions_all dist
2292             SET    dist.pa_addition_flag = 'O',
2293                    request_id = G_REQUEST_ID,
2294                    last_update_date=SYSDATE,
2295                    last_updated_by= G_USER_ID,
2296                    last_update_login= G_USER_ID,
2297                    program_id= G_PROG_ID,
2298                    program_application_id= G_PROG_APPL_ID,
2299                    program_update_date=SYSDATE
2300             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
2301             AND   dist.posted_flag ='Y'
2302             AND   dist.project_id > 0
2303             --AND   dist.line_type_lookup_code = 'PREPAY'
2304             AND   dist.line_type_lookup_code <> 'REC_TAX'
2305             AND   dist.prepay_distribution_id is not null
2306             AND   trunc(dist.Accounting_Date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
2307             AND   trunc(dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,dist.expenditure_item_date))
2308             AND   EXISTS (
2309                     SELECT NULL
2310                     FROM ap_invoices inv
2311                     WHERE inv.invoice_id = dist.invoice_id
2312                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2313                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2314                     AND nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting',
2315                               'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')  )
2316             AND   exists(SELECT inv.invoice_id
2317                            FROM AP_INVOICES_all inv,
2318                                 AP_Invoice_Distributions_all aid
2319                           WHERE aid.invoice_id = inv.invoice_id
2320                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'
2321                             AND aid.historical_flag = 'Y'
2322                             AND aid.pa_addition_flag = 'Y'
2323                             AND aid.invoice_distribution_id =  dist.prepay_distribution_id --Prepayment dist id
2324                             AND aid.project_id > 0 )
2325                 /* Bug 6353803: Added the following for this bug. */
2326   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2327                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2328 		    AND NOT EXISTS (SELECT 'X'
2329 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2330 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2331 				    AND pod.po_line_id = pol.po_line_id
2332 				    AND   si.inventory_item_id = pol.item_id
2333 				    AND   si.comms_nl_trackable_flag = 'Y'
2334 				    AND   si.organization_id = pod.org_id
2335 				    )
2336 		    AND NOT EXISTS (SELECT 'X'
2337 			      FROM
2338 				ap_invoice_distributions apdist,
2339 				po_distributions pod,
2340 				mtl_system_items si,
2341 				po_lines_all pol
2342 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2343                                     = apdist.INVOICE_DISTRIBUTION_ID
2344 				  and apdist.po_distribution_id = pod.po_distribution_id
2345 				  and pod.po_line_id = pol.po_line_id
2346 				  and si.inventory_item_id = pol.item_id
2347 				  AND   si.comms_nl_trackable_flag = 'Y'
2348 				  AND   si.organization_id = pod.org_id
2349 					     )
2350 		    )
2351                   );
2352 
2353             G_DISTRIBUTIONS_MARKED := nvl(G_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
2354             write_log(LOG, 'Number of Historical PREPAY Appl Dist marked to O: ' || to_char(SQL%ROWCOUNT));
2355 
2356 
2357          ELSE -- Accrual BAsed Acctng
2358 
2359           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
2360 	   write_log(LOG, 'Marking invoices in Accrual based Acctng');
2361 
2362            UPDATE AP_Invoice_Distributions DIST
2363               SET DIST.Pa_Addition_Flag = 'O',
2364                   request_id = G_REQUEST_ID,
2365                   last_update_date=SYSDATE,
2366                   last_updated_by=G_USER_ID,
2367                   last_update_login=G_USER_ID,
2368                   program_id=G_PROG_ID,
2369                   program_application_id=G_PROG_APPL_ID,
2370                   program_update_date=SYSDATE
2371             WHERE DIST.Posted_Flag||'' = 'Y'
2372               AND DIST.Pa_Addition_Flag IN
2373                   ('S', 'A', 'B', 'C', 'D','H', 'I', 'J', 'K', 'L', 'M', 'N', 'P','Q', 'V', 'X')
2374               AND DIST.project_id > 0
2375               AND trunc(DIST.Accounting_Date )<= trunc(nvl(G_GL_DATE,DIST.Accounting_Date) )  /*GSCC*/
2376               AND trunc(DIST.Expenditure_Item_Date) <=
2377                      trunc(NVL(G_TRANSACTION_DATE, DIST.Expenditure_Item_Date))          /*GSCC*/
2378               AND dist.line_type_lookup_code <> 'REC_TAX' -- do not proces recoverable tax
2379               AND EXISTS (
2380                   SELECT NULL
2381                     FROM ap_invoices_all inv,
2382                          po_distributions_all PO,
2383                          ap_invoice_distributions_all dist2
2384                     WHERE inv.invoice_id = dist2.invoice_id
2385                     AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
2386                     AND dist2.invoice_id = DIST.invoice_id
2387                     /* credit card txn enhancement, make sure this update doesn't pick tehm */
2388                     AND inv.PAID_ON_BEHALF_EMPLOYEE_ID IS NULL
2389                     AND dist2.invoice_distribution_id = DIST.invoice_distribution_id
2390                     AND dist2.po_distribution_id = PO.po_distribution_id(+)
2391                     AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
2392                     AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
2393                     -- IC Upgrade: Do not get Inter-company invoices
2394                     AND ( nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting',
2395                              'PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
2396 			    or
2397 			 dist2.line_type_lookup_code = 'NONREC_TAX'
2398 			 )
2399                         )
2400                 /* Bug 6353803: Added the following for this bug. */
2401   	        AND   (pa_nl_installed.is_nl_installed = 'N'
2402                   OR (    pa_nl_installed.is_nl_installed = 'Y'
2403 		    AND NOT EXISTS (SELECT 'X'
2404 				    FROM  po_distributions_all pod, mtl_system_items si, po_lines_all pol
2405 				    WHERE pod.po_distribution_id = dist.po_distribution_id
2406 				    AND pod.po_line_id = pol.po_line_id
2407 				    AND   si.inventory_item_id = pol.item_id
2408 				    AND   si.comms_nl_trackable_flag = 'Y'
2409 				    AND   si.organization_id = pod.org_id
2410 				    )
2411 		    AND NOT EXISTS (SELECT 'X'
2412 			      FROM
2413 				ap_invoice_distributions apdist,
2414 				po_distributions pod,
2415 				mtl_system_items si,
2416 				po_lines_all pol
2417 			      where DIST.CHARGE_APPLICABLE_TO_DIST_ID
2418                                     = apdist.INVOICE_DISTRIBUTION_ID
2419 				  and apdist.po_distribution_id = pod.po_distribution_id
2420 				  and pod.po_line_id = pol.po_line_id
2421 				  and si.inventory_item_id = pol.item_id
2422 				  AND   si.comms_nl_trackable_flag = 'Y'
2423 				  AND   si.organization_id = pod.org_id
2424 					     )
2425 		    )
2426                   );
2427 
2428 
2429               G_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
2430               write_log(LOG, 'Number of rows marked to O: ' || to_char(SQL%ROWCOUNT));
2431 
2432            END IF; -- End of Acctng method is CASH
2433 
2434          END IF;
2435          --
2436          -- End of If section checking if G_PROJECT_ID is not null
2437          --
2438 
2439      END IF;
2440 
2441      write_log(LOG, 'Total Number of rows marked to O: ' || to_char(G_DISTRIBUTIONS_MARKED));
2442      G_err_stack := v_old_stack;
2443 
2444 EXCEPTION
2445      WHEN Others THEN
2446            -- Marking phase failed, raise exception to main program to terminate the program
2447            --
2448            G_err_stack := v_old_stack;
2449            G_err_code := SQLCODE;
2450            RAISE;
2451 
2452 END mark_PAflag_O;
2453 
2454 PROCEDURE transfer_inv_to_pa  IS
2455 
2456    v_num_invoices_fetched          NUMBER :=0;
2457    v_num_distributions_fetched     NUMBER :=0;
2458    v_prev_invoice_id               NUMBER := 0;
2459    v_prev_vendor_id                NUMBER := 0;
2460    v_old_stack                     VARCHAR2(630);
2461    v_err_message                   VARCHAR2(220);
2462    v_all_done                      NUMBER := 0;
2463    v_prev_invoice_source           ap_invoices.source%TYPE := NULL;
2464    v_prev_transaction_source       pa_transaction_sources.transaction_source%TYPE;
2465    v_num_tax_lines_fetched         NUMBER:=0;
2466    v_num_inv_variance_fetched      NUMBER:=0;    --NEW
2467    v_num_inv_erv_fetched           NUMBER:=0;    --NEW
2468    v_num_inv_frt_fetched           NUMBER:=0;    --NEW
2469    v_last_inv_ER_flag              VARCHAR2(1);
2470 
2471    v_status Number := 0;
2472    v_stage  Number :=0;
2473    v_business_group_id NUMBER := 0;
2474    v_attribute_category VARCHAR2(150);
2475    v_attribute1 VARCHAR2(150);
2476    v_attribute2 VARCHAR2(150);
2477    v_attribute3 VARCHAR2(150);
2478    v_attribute4 VARCHAR2(150);
2479    v_attribute5 VARCHAR2(150);
2480    v_attribute6 VARCHAR2(150);
2481    v_attribute7 VARCHAR2(150);
2482    v_attribute8 VARCHAR2(150);
2483    v_attribute9 VARCHAR2(150);
2484    v_attribute10 VARCHAR2(150);
2485    v_dff_map_status VARCHAR2(30);
2486    dff_map_exception EXCEPTION;
2487 
2488    v_num_last_invoice_processed NUMBER := 0;
2489    v_last_inv_index             NUMBER := 0;
2490    v_num_dist_marked_O          NUMBER := 0;
2491    v_num_dist_remain            NUMBER := 0;
2492    v_max_size                   NUMBER := 0;
2493 
2494    v_inv_batch_size             NUMBER := 0;
2495    v_tax_batch_size             NUMBER := 0;
2496    v_var_batch_size             NUMBER := 0;
2497    v_frt_batch_size             NUMBER := 0;
2498 
2499 -- For PA IP Invoices
2500    L_IP_TRANSACTION_SOURCE         pa_transaction_interface.transaction_source%TYPE;
2501    l_ap_inv_flag                   VARCHAR2(1):= 'N';
2502    l_ip_inv_flag                   VARCHAR2(1):= 'N';
2503 
2504    CURSOR Num_Dist_Marked_O (p_invoice_id IN NUMBER) IS
2505       SELECT count(*)
2506          FROM ap_invoice_distributions
2507         WHERE invoice_id       = p_invoice_id
2508           AND pa_addition_flag = 'O';
2509 
2510    l_prev_cr_ccid NUMBER;
2511    l_prev_dr_ccid NUMBER;
2512    l_create_adj_recs  VARCHAR2(1) := 'N';
2513 
2514    /* the following sub-procedure is declared here to save lines of code since deleting
2515       plsql tables will be done multiple times within the procedure transfer_inv_to_pa */
2516 
2517    PROCEDURE clear_plsql_tables IS
2518 
2519        l_status1 VARCHAR2(30);
2520 
2521    BEGIN
2522 
2523        G_err_stage := 'within clear_plsql_tables of ransfer_inv_to_pa';
2524        write_log(LOG, G_err_stage);
2525 
2526        l_invoice_id_tbl.delete;
2527        l_created_by_tbl.delete;
2528        --l_dist_line_num_tbl.delete;
2529        l_invoice_dist_id_tbl.delete; --NEW
2530        l_project_id_tbl.delete;
2531        l_task_id_tbl.delete;
2532        l_ln_type_lookup_tbl.delete;
2533        l_exp_type_tbl.delete;
2534        l_ei_date_tbl.delete;
2535        l_amount_tbl.delete;
2536        l_description_tbl.delete;
2537        l_justification_tbl.delete;
2538        l_dist_cc_id_tbl.delete;
2539        l_exp_org_id_tbl.delete;
2540        l_quantity_tbl.delete;
2541        l_acct_pay_cc_id_tbl.delete;
2542        l_gl_date_tbl.delete;
2543        l_attribute_cat_tbl.delete;
2544        l_attribute1_tbl.delete;
2545        l_attribute2_tbl.delete;
2546        l_attribute3_tbl.delete;
2547        l_attribute4_tbl.delete;
2548        l_attribute5_tbl.delete;
2549        l_attribute6_tbl.delete;
2550        l_attribute7_tbl.delete;
2551        l_attribute8_tbl.delete;
2552        l_attribute9_tbl.delete;
2553        l_attribute10_tbl.delete;
2554        l_rec_cur_amt_tbl.delete;
2555        l_rec_cur_code_tbl.delete;
2556        l_rec_conv_rate_tbl.delete;
2557        l_denom_raw_cost_tbl.delete;
2558        l_denom_cur_code_tbl.delete;
2559        l_acct_rate_date_tbl.delete;
2560        l_acct_rate_type_tbl.delete;
2561        l_acct_exch_rate_tbl.delete;
2562        l_job_id_tbl.delete;
2563        l_employee_id_tbl.delete;
2564        l_vendor_id_tbl.delete;
2565        l_inv_type_code_tbl.delete;
2566        l_source_tbl.delete;
2567        l_org_id_tbl.delete;
2568        l_invoice_num_tbl.delete;
2569        l_cdl_sys_ref4_tbl.delete;
2570        l_po_dist_id_tbl.delete;
2571        l_txn_src_tbl.delete;
2572        l_user_txn_src_tbl.delete;
2573        l_batch_name_tbl.delete;
2574        l_interface_id_tbl.delete;
2575        l_exp_end_date_tbl.delete;
2576        l_txn_status_code_tbl.delete;
2577        l_txn_rej_code_tbl.delete;
2578        l_po_dist_id_tbl.delete;
2579        l_bus_grp_id_tbl.delete;
2580        l_paid_emp_id_tbl.delete;
2581        l_sort_var_tbl.delete;
2582        l_reversal_flag_tbl.delete; --NEW
2583        l_cancel_flag_tbl.delete;  --NEW
2584        l_parent_rev_id_tbl.delete; --NEW
2585        l_net_zero_flag_tbl.delete; --NEW
2586        l_sc_xfer_code_tbl.delete; --NEW
2587        l_adj_exp_item_id_tbl.delete; --NEW
2588        l_fc_enabled_tbl.delete; --NEW
2589        l_fc_document_type_tbl.delete; --NEW
2590        l_insert_flag_tbl.delete;
2591        l_rev_parent_dist_id_tbl.delete;
2592        l_rev_child_dist_id_tbl.delete;
2593        l_rev_parent_dist_ind_tbl.delete;
2594        l_si_assts_add_flg_tbl.delete;
2595        l_prepay_dist_id_tbl.delete;
2596        l_hist_flag_tbl.delete;
2597        l_rev_index:=0;
2598 
2599     END clear_plsql_tables;
2600 
2601    /* the following sub-procedure is declared here to save lines of code since bulk insert
2602       will be done multiple times within the procedure transfer_inv_to_pa */
2603 
2604     PROCEDURE bulk_update_trx_intf IS
2605 
2606      BEGIN
2607 
2608        /* The records with INSERT_FLAG = F indicate that they are fully applied prepayments and the pa-addition-flag
2609           for such records will be updated to G to relieve commitments*/
2610        /* The records with INSERT_FLAG = P indicate that they are partially applied prepayments and the pa-addition-flag
2611           for such records will be updated to N */
2612 
2613        write_log(LOG,'Before bulk update  of prepayment invoices');
2614 
2615        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
2616 
2617          UPDATE ap_invoice_distributions_all dist
2618             SET dist.pa_addition_flag         = decode(l_insert_flag_tbl(i),'F','G','P','N')
2619           WHERE dist.invoice_id               = l_invoice_id_tbl(i)
2620             AND dist.invoice_distribution_id  = l_invoice_dist_id_tbl(i)
2621             AND dist.pa_addition_flag         = 'O'
2622             AND l_insert_flag_tbl(i)         in ('P','F');
2623 
2624      EXCEPTION
2625       WHEN OTHERS THEN
2626           write_log(LOG,'Failed during bulk update for prepayment processing');
2627           G_err_code   := SQLCODE;
2628           write_log(LOG, 'Error Code is '||SQLCODE);
2629           write_log(LOG, substr(SQLERRM, 1, 200));
2630           write_log(LOG, substr(SQLERRM, 201, 200));
2631           raise;
2632 
2633     END bulk_update_trx_intf;
2634 
2635     PROCEDURE bulk_insert_trx_intf IS
2636 
2637       l_status2 VARCHAR2(30);
2638 
2639 
2640     BEGIN
2641 
2642        write_log(LOG,'Before bulk insert of supplier invoices');
2643 
2644       If g_body_debug_mode = 'Y' Then
2645        FOR i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST  LOOP
2646           write_log(LOG,   '1:'||   l_txn_src_tbl(i));
2647           write_log(LOG,   '2:'||   l_user_txn_src_tbl(i));
2648           write_log(LOG,   '3:'||   l_batch_name_tbl(i));
2649           write_log(LOG,      '4:'||to_char(l_exp_end_date_tbl(i)));
2650           write_log(LOG,      '6:'||to_char(l_ei_date_tbl(i)));
2651           write_log(LOG,      '7:'||l_exp_type_tbl(i));
2652           write_log(LOG,      '8:'||to_char(l_quantity_tbl(i)));
2653           write_log(LOG,      '9:'||l_description_tbl(i));
2654           write_log(LOG,      '10:'||l_txn_status_code_tbl(i));
2655           write_log(LOG,      '11:'||l_txn_rej_code_tbl(i));
2656           write_log(LOG,      '12:'||to_char(l_interface_id_tbl(i)));
2657           write_log(LOG,      '13:'||to_char(l_dist_cc_id_tbl(i)));
2658           write_log(LOG,      '14:'||to_char(l_acct_pay_cc_id_tbl(i)));
2659           write_log(LOG,      '15:'||to_char(l_vendor_id_tbl(i) ));
2660           write_log(LOG,      '16:'||to_char(l_invoice_id_tbl(i) ));
2661           write_log(LOG,      '17:'||l_cdl_sys_ref4_tbl(i));
2662           write_log(LOG,      '18:'||to_char(l_invoice_dist_id_tbl(i) ));
2663           write_log(LOG,      '19:'||to_char(l_gl_date_tbl(i)));
2664           write_log(LOG,      '20:'||to_char(l_rec_cur_amt_tbl(i)));
2665           write_log(LOG,      '21:'||l_rec_cur_code_tbl(i));
2666           write_log(LOG,      '22:'||l_rec_conv_rate_tbl(i));
2667           write_log(LOG,      '23:'||to_char(l_denom_raw_cost_tbl(i)));
2668           write_log(LOG,      '24:'||l_denom_cur_code_tbl(i));
2669           write_log(LOG,      '25:'||to_char(l_acct_rate_date_tbl(i)));
2670           write_log(LOG,      '26:'||l_acct_rate_type_tbl(i));
2671           write_log(LOG,      '27:'||to_char(l_acct_exch_rate_tbl(i)));
2672           write_log(LOG,      '28:'||to_char(l_amount_tbl(i)));
2673           write_log(LOG,      '29:'||l_attribute_cat_tbl(i));
2674           write_log(LOG,      '30:'||l_attribute1_tbl(i));
2675           write_log(LOG,      '31:'||l_attribute2_tbl(i));
2676           write_log(LOG,      '32:'||l_attribute3_tbl(i));
2677           write_log(LOG,      '33:'||l_attribute4_tbl(i));
2678           write_log(LOG,      '34:'||l_attribute5_tbl(i));
2679           write_log(LOG,      '35:'||l_attribute6_tbl(i));
2680           write_log(LOG,      '36:'||l_attribute7_tbl(i));
2681           write_log(LOG,      '37:'||l_attribute8_tbl(i));
2682           write_log(LOG,      '38:'||l_attribute9_tbl(i));
2683           write_log(LOG,      '39:'||l_attribute10_tbl(i));
2684           write_log(LOG,      '40:'||to_char(l_invoice_id_tbl(i) ));
2685           write_log(LOG,      '41:'||l_invoice_num_tbl(i));
2686           write_log(LOG,      '42:'||to_char(l_invoice_id_tbl(i) ));
2687           write_log(LOG,      '43:'||to_char(l_employee_id_tbl(i)));
2688           write_log(LOG,      '44:'||to_char(l_org_id_tbl(i)));
2689           write_log(LOG,      '45:'||to_char(l_project_id_tbl(i)));
2690           write_log(LOG,      '46:'||to_char(l_task_id_tbl(i)));
2691           write_log(LOG,      '47:'||to_char(l_vendor_id_tbl(i)));
2692           write_log(LOG,      '48:'||to_char(l_exp_org_id_tbl(i)));
2693           write_log(LOG,      '49:'||to_char(l_bus_grp_id_tbl(i)));
2694           write_log(LOG,      '50:'||to_char(l_adj_exp_item_id_tbl(i) ));
2695           write_log(LOG,      '51:'||l_fc_document_type_tbl(i) );
2696           write_log(LOG,      '52:'||l_inv_type_code_tbl(i));
2697           write_log(LOG,      '53:'||l_ln_type_lookup_tbl(i));
2698           write_log(LOG,      '54:'||l_net_zero_flag_tbl(i));
2699           write_log(LOG,      '55:'||l_si_assts_add_flg_tbl(i));
2700           write_log(LOG,      '56:'||l_cdl_sys_ref3_tbl(i));
2701           write_log(LOG,      '57:'||l_net_zero_flag_tbl(i));
2702           write_log(LOG,      '58:'||l_insert_flag_tbl(i));
2703           write_log(LOG,      '59:'||G_UNIQUE_ID);
2704        END LOOP;
2705      End If;
2706 
2707        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
2708 
2709        INSERT INTO pa_transaction_interface_all(
2710                      transaction_source
2711                     , user_transaction_source
2712                     , system_linkage
2713                     , batch_name
2714                     , expenditure_ending_date
2715                     , expenditure_item_date
2716                     , expenditure_type
2717                     , quantity
2718                     , raw_cost_rate
2719                     , expenditure_comment
2720                     , transaction_status_code
2721                     , transaction_rejection_code
2722                     , orig_transaction_reference
2723                     , interface_id
2724                     , dr_code_combination_id
2725                     , cr_code_combination_id
2726                     , cdl_system_reference1
2727                     , cdl_system_reference2
2728                     , cdl_system_reference3
2729                     , cdl_system_reference4
2730                     , cdl_system_reference5 --NEW
2731                     , gl_date
2732                     , org_id
2733                     , unmatched_negative_txn_flag
2734                     , receipt_currency_amount
2735                     , receipt_currency_code
2736                     , receipt_exchange_rate
2737                     , denom_raw_cost
2738                     , denom_currency_code
2739                     , acct_rate_date
2740                     , acct_rate_type
2741                     , acct_exchange_rate
2742                     , acct_raw_cost
2743                     , acct_exchange_rounding_limit
2744                     , attribute_category
2745                     , attribute1
2746                     , attribute2
2747                     , attribute3
2748                     , attribute4
2749                     , attribute5
2750                     , attribute6
2751                     , attribute7
2752                     , attribute8
2753                     , attribute9
2754                     , attribute10
2755                     , orig_exp_txn_reference1
2756                     , orig_user_exp_txn_reference
2757                     , orig_exp_txn_reference2
2758                     , orig_exp_txn_reference3
2759                     , last_update_date
2760                     , last_updated_by
2761                     , creation_date
2762                     , created_by
2763                     , person_id
2764                     , organization_id
2765                     , project_id
2766                     , task_id
2767                     , Vendor_id
2768                     , override_to_organization_id
2769                     , person_business_group_id
2770                     , adjusted_expenditure_item_id --NEW
2771                     , fc_document_type  -- NEW
2772                     , document_type
2773                     , document_distribution_type
2774                     , sc_xfer_code
2775                     , si_assets_addition_flag
2776                     , net_zero_adjustment_flag
2777                    )
2778                   SELECT
2779                       l_txn_src_tbl(i)
2780                      ,l_user_txn_src_tbl(i)
2781                      ,G_SYSTEM_LINKAGE
2782                      ,l_batch_name_tbl(i)
2783                      ,l_exp_end_date_tbl(i)
2784                      ,l_ei_date_tbl(i)
2785                      ,l_exp_type_tbl(i)
2786                      ,l_quantity_tbl(i)
2787                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
2788                      ,l_description_tbl(i)
2789                      ,l_txn_status_code_tbl(i)
2790                      ,l_txn_rej_code_tbl(i)
2791                      ,G_REQUEST_ID
2792                      ,l_interface_id_tbl(i)
2793                      ,l_dist_cc_id_tbl(i)
2794                      ,l_acct_pay_cc_id_tbl(i)
2795                      ,l_vendor_id_tbl(i) /*sysref1*/
2796                      ,l_invoice_id_tbl(i) /*sysref2*/
2797                      ,l_cdl_sys_ref3_tbl(i)  --NULL /*sysref3*/
2798                      ,l_cdl_sys_ref4_tbl(i)
2799                      ,l_invoice_dist_id_tbl(i) /*sysref5*/ --NEW
2800                      ,l_gl_date_tbl(i)
2801                      ,G_ORG_ID
2802                      ,'Y'
2803                      ,l_rec_cur_amt_tbl(i)
2804                      ,l_rec_cur_code_tbl(i)
2805                      ,l_rec_conv_rate_tbl(i)
2806                      ,l_denom_raw_cost_tbl(i)
2807                      ,l_denom_cur_code_tbl(i)
2808                      ,l_acct_rate_date_tbl(i)
2809                      ,l_acct_rate_type_tbl(i)
2810                      ,l_acct_exch_rate_tbl(i)
2811                      ,l_amount_tbl(i)
2812                      ,1
2813                      ,l_attribute_cat_tbl(i)
2814                      ,l_attribute1_tbl(i)
2815                      ,l_attribute2_tbl(i)
2816                      ,l_attribute3_tbl(i)
2817                      ,l_attribute4_tbl(i)
2818                      ,l_attribute5_tbl(i)
2819                      ,l_attribute6_tbl(i)
2820                      ,l_attribute7_tbl(i)
2821                      ,l_attribute8_tbl(i)
2822                      ,l_attribute9_tbl(i)
2823                      ,l_attribute10_tbl(i)
2824                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
2825                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
2826                      /* bug 2835757*/
2827                      ,DECODE(G_TRANS_DFF_AP,'N',NULL,l_invoice_id_tbl(i)) /*orig_exp_txn_reference2*/
2828                      ,NULL                       /*orig_exp_txn_reference3*/
2829                      ,SYSDATE
2830                      ,-1
2831                      ,SYSDATE
2832                      ,-1
2833                      ,l_employee_id_tbl(i)
2834                      ,l_org_id_tbl(i)
2835                      ,l_project_id_tbl(i)
2836                      ,l_task_id_tbl(i)
2837                      ,l_vendor_id_tbl(i)
2838                      ,l_exp_org_id_tbl(i)
2839                      ,l_bus_grp_id_tbl(i)
2840                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
2841                      ,l_fc_document_type_tbl(i) --NEW for funds check
2842                      ,l_inv_type_code_tbl(i)
2843                      ,l_ln_type_lookup_tbl(i)
2844                      ,l_sc_xfer_code_tbl(i)
2845                      ,l_si_assts_add_flg_tbl(i)
2846                      ,l_net_zero_flag_tbl(i)
2847                 FROM dual
2848                 WHERE l_insert_flag_tbl(i) not in ('F', 'P');
2849 
2850               -- Insert the reversal of reversed/cancelled invoice distribution recs from AP.
2851     IF l_create_adj_recs = 'Y' THEN
2852 
2853                 write_log(LOG, 'Inserting adjustment records..');
2854 
2855 
2856        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
2857        INSERT INTO pa_transaction_interface_all(
2858                      transaction_source
2859                     , user_transaction_source
2860                     , system_linkage
2861                     , batch_name
2862                     , expenditure_ending_date
2863                     , expenditure_item_date
2864                     , expenditure_type
2865                     , quantity
2866                     , raw_cost_rate
2867                     , expenditure_comment
2868                     , transaction_status_code
2869                     , transaction_rejection_code
2870                     , orig_transaction_reference
2871                     , interface_id
2872                     , dr_code_combination_id
2873                     , cr_code_combination_id
2874                     , cdl_system_reference1
2875                     , cdl_system_reference2
2876                     , cdl_system_reference3
2877                     , cdl_system_reference4
2878                     , cdl_system_reference5 --NEW
2879                     , gl_date
2880                     , org_id
2881                     , unmatched_negative_txn_flag
2882                     , receipt_currency_amount
2883                     , receipt_currency_code
2884                     , receipt_exchange_rate
2885                     , denom_raw_cost
2886                     , denom_currency_code
2887                     , acct_rate_date
2888                     , acct_rate_type
2889                     , acct_exchange_rate
2890                     , acct_raw_cost
2891                     , acct_exchange_rounding_limit
2892                     , attribute_category
2893                     , attribute1
2894                     , attribute2
2895                     , attribute3
2896                     , attribute4
2897                     , attribute5
2898                     , attribute6
2899                     , attribute7
2900                     , attribute8
2901                     , attribute9
2902                     , attribute10
2903                     , orig_exp_txn_reference1
2904                     , orig_user_exp_txn_reference
2905                     , orig_exp_txn_reference2
2906                     , orig_exp_txn_reference3
2907                     , last_update_date
2908                     , last_updated_by
2909                     , creation_date
2910                     , created_by
2911                     , person_id
2912                     , organization_id
2913                     , project_id
2914                     , task_id
2915                     , Vendor_id
2916                     , override_to_organization_id
2917                     , person_business_group_id
2918                     , adjusted_expenditure_item_id --NEW
2919                     , fc_document_type  -- NEW
2920                     , document_type
2921                     , document_distribution_type
2922                     , adjusted_txn_interface_id
2923                     , sc_xfer_code
2924                     , si_assets_addition_flag
2925                     , net_zero_adjustment_flag
2926                    )
2927                   SELECT
2928                       l_txn_src_tbl(i)
2929                      ,l_user_txn_src_tbl(i)
2930                      ,G_SYSTEM_LINKAGE
2931                      ,l_batch_name_tbl(i)
2932                      ,l_exp_end_date_tbl(i)
2933                      ,l_ei_date_tbl(i)
2934                      ,l_exp_type_tbl(i)
2935                      ,-l_quantity_tbl(i)
2936                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
2937                      ,l_description_tbl(i)
2938                      ,l_txn_status_code_tbl(i)
2939                      ,l_txn_rej_code_tbl(i)
2940                      ,G_REQUEST_ID
2941                      ,l_interface_id_tbl(i)
2942                      ,l_dist_cc_id_tbl(i)
2943                      ,l_acct_pay_cc_id_tbl(i)
2944                      ,l_vendor_id_tbl(i) /*sysref1*/
2945                      ,l_invoice_id_tbl(i) /*sysref2*/
2946                      ,l_cdl_sys_ref3_tbl(i)  --NULL /*sysref3*/
2947                      ,l_cdl_sys_ref4_tbl(i)
2948                      ,l_invoice_dist_id_tbl(i) /*sysref5*/ --NEW
2949                      ,l_gl_date_tbl(i)
2950                      ,G_ORG_ID
2951                      ,'Y'
2952                      ,-l_rec_cur_amt_tbl(i)
2953                      ,l_rec_cur_code_tbl(i)
2954                      ,l_rec_conv_rate_tbl(i)
2955                      ,-l_denom_raw_cost_tbl(i)
2956                      ,l_denom_cur_code_tbl(i)
2957                      ,l_acct_rate_date_tbl(i)
2958                      ,l_acct_rate_type_tbl(i)
2959                      ,l_acct_exch_rate_tbl(i)
2960                      ,-l_amount_tbl(i)
2961                      ,1
2962                      ,l_attribute_cat_tbl(i)
2963                      ,l_attribute1_tbl(i)
2964                      ,l_attribute2_tbl(i)
2965                      ,l_attribute3_tbl(i)
2966                      ,l_attribute4_tbl(i)
2967                      ,l_attribute5_tbl(i)
2968                      ,l_attribute6_tbl(i)
2969                      ,l_attribute7_tbl(i)
2970                      ,l_attribute8_tbl(i)
2971                      ,l_attribute9_tbl(i)
2972                      ,l_attribute10_tbl(i)
2973                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
2974                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
2975                      /* bug 2835757*/
2976                      ,DECODE(G_TRANS_DFF_AP,'N',NULL,l_invoice_id_tbl(i)) /*orig_exp_txn_reference2*/
2977                      ,NULL                       /*orig_exp_txn_reference3*/
2978                      ,SYSDATE
2979                      ,-1
2980                      ,SYSDATE
2981                      ,-1
2982                      ,l_employee_id_tbl(i)
2983                      ,l_org_id_tbl(i)
2984                      ,l_project_id_tbl(i)
2985                      ,l_task_id_tbl(i)
2986                      ,l_vendor_id_tbl(i)
2987                      ,l_exp_org_id_tbl(i)
2988                      ,l_bus_grp_id_tbl(i)
2989                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
2990                      ,l_fc_document_type_tbl(i) --NEW for funds check
2991                      ,l_inv_type_code_tbl(i)
2992                      ,l_ln_type_lookup_tbl(i)
2993                      ,(select xface.txn_interface_id
2994                        from   pa_transaction_interface xface
2995                        where  xface.interface_id = l_interface_id_tbl(i)
2996                        and    xface.cdl_system_reference2 = l_invoice_id_tbl(i)
2997                        and    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(i)
2998 		       and    NVL(xface.adjusted_expenditure_item_id,0) = 0 ) -- R12 funds management Uptake
2999                      ,'P' -- sc_xfer_code
3000                      ,'T' -- l_si_assts_add_flg_tbl(i)
3001                      ,l_net_zero_flag_tbl(i)
3002                 FROM dual
3003                 WHERE l_insert_flag_tbl(i)= 'A';
3004 
3005                -- Handle both the parent and the reversal getting interfaced into PA
3006                -- in the same run.
3007                 write_log(LOG, 'Updating  adjustment records..');
3008 
3009               IF l_rev_child_dist_id_tbl.exists(1) THEN
3010 
3011                FOR i in l_rev_child_dist_id_tbl.FIRST ..l_rev_child_dist_id_tbl.LAST LOOP
3012 
3013                    IF l_rev_child_dist_id_tbl(i) > 0 THEN
3014 
3015                     UPDATE pa_transaction_interface_all xface
3016                     SET    xface.net_zero_adjustment_flag ='Y',
3017                            xface.adjusted_txn_interface_id =
3018                               (select xface1.txn_interface_id
3019                                from   pa_transaction_interface xface1
3020                                where  xface1.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
3021                                and    xface1.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
3022                                and    xface1.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
3023                                )
3024                       WHERE  xface.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
3025                       AND    xface.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
3026                       AND    xface.cdl_system_reference5 = l_rev_child_dist_id_tbl(i);
3027 
3028                    END IF;
3029 
3030                END LOOP;
3031 
3032               END IF;
3033     END IF;
3034 
3035    EXCEPTION
3036       WHEN OTHERS THEN
3037           write_log(LOG,'Failed during bulk insert for invoice processing');
3038           G_err_code   := SQLCODE;
3039           write_log(LOG, 'Error Code is '||SQLCODE);
3040           write_log(LOG, substr(SQLERRM, 1, 200));
3041           write_log(LOG, substr(SQLERRM, 201, 200));
3042           raise;
3043 
3044    END bulk_insert_trx_intf;
3045 
3046    PROCEDURE process_inv_logic IS
3047 
3048        l_status3 VARCHAR2(30);
3049        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
3050        l_historical_flag VARCHAR2(1);  --NEW
3051        l_process_adjustments    Number := 0 ;
3052        l_prepay_hist_flag VARCHAR2(1);
3053 
3054    BEGIN
3055 
3056        G_err_stage := ('Within Calling process logic of transfer_inv_to_pa');
3057        write_log(LOG, G_err_stage);
3058 
3059        /* Initializing global variables here to reduce code lines */
3060        G_NRT_TRANSACTION_SOURCE      := 'AP NRTAX' ;
3061        G_NRT_USER_TRANSACTION_SOURCE := 'Non-Recoverable Tax From Payables';
3062 
3063        G_AP_VAR_TRANSACTION_SOURCE  := 'AP VARIANCE';                                --NEW
3064        G_AP_VAR_USER_TXN_SOURCE     := 'Oracle Payables Invoice Variance';           --NEW
3065 
3066        G_AP_ERV_TRANSACTION_SOURCE  := 'AP ERV';                                --NEW
3067        G_AP_ERV_USER_TXN_SOURCE     := 'Oracle Payables Supplier Cost Exchange Rate Variance';           --NEW
3068 
3069        j := v_last_inv_index; -- initialize j to the total invoice distributions fetched in the PLSQL array
3070 
3071        FOR i IN  l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST  LOOP
3072 
3073            write_log(LOG,'Processing invoice id:  '||l_invoice_id_tbl(i)|| 'dist id:  '||l_invoice_dist_id_tbl(i));  --NEW
3074 
3075            /* We need to lock the corresponding receipts right away for each invoice distribution*/
3076            IF l_po_dist_id_tbl(i) IS NOT NULL
3077               -- Below clause added so that rcv trx not updated to status G for variance processing
3078               and l_ln_type_lookup_tbl(i) IN ('ITEM','ACCRUAL','NONREC_TAX')  THEN
3079               lock_rcv_txn(l_po_dist_id_tbl(i));
3080            END IF;
3081 
3082            G_TRANSACTION_REJECTION_CODE := '';
3083 
3084            IF l_source_tbl(i) in ('CREDIT CARD','Both Pay') THEN
3085 
3086               write_log(LOG,'This is a credit card txn, setting emp id to paid_emp_id.');
3087               l_employee_id_tbl(i)   := l_paid_emp_id_tbl(i);
3088               l_inv_type_code_tbl(i) := 'EXPENSE REPORT';
3089 
3090            ELSIF l_inv_type_code_tbl(i) = 'EXPENSE REPORT' and l_employee_id_tbl(i) is null THEN
3091               write_log(LOG,'This is a CWK Exp Report, setting emp id to paid_emp_id.');
3092               l_employee_id_tbl(i)   := l_paid_emp_id_tbl(i);
3093 
3094            END IF;
3095 
3096            /* The following will be executed if the distribution being fetched belongs to a new invoice */
3097            IF (l_invoice_id_tbl(i) <> v_prev_invoice_id) THEN
3098 
3099                G_err_stage := ('New invoice being processed.New invoice _id is:'||l_invoice_id_tbl(i));
3100                write_log(LOG, G_err_stage);
3101 
3102                /* Update the previous invoice id and vendor id*/
3103                v_prev_invoice_id := l_invoice_id_tbl(i);
3104                v_prev_vendor_id  := l_vendor_id_tbl(i);
3105 
3106                /* Increment the counter for invoices */
3107                v_num_invoices_fetched := v_num_invoices_fetched + 1;
3108 
3109                IF nvl(v_prev_invoice_source,l_source_tbl(i)||'111') <> l_source_tbl(i) THEN
3110 
3111                   /* First update the v_prev_invoice_source */
3112                   G_err_stage := 'New source encountered';
3113                   write_log(LOG, G_err_stage);
3114                   v_prev_invoice_source := l_source_tbl(i);
3115 
3116 
3117                   IF l_source_tbl(i) = 'PA_IP_INVOICES' THEN
3118 
3119                      G_err_stage := 'Invoice source is Inter-Company Invoice';
3120                      write_log(LOG, G_err_stage);
3121                      G_TRANSACTION_SOURCE      := 'INTERPROJECT_AP_INVOICES';
3122                      v_prev_transaction_source := G_TRANSACTION_SOURCE;
3123                      G_USER_TRANSACTION_SOURCE := 'Oracle Inter-Project Invoices';
3124 
3125                      L_IP_TRANSACTION_SOURCE      := 'INTERPROJECT_AP_INVOICES';
3126                      l_ip_inv_flag                := 'Y' ;
3127 
3128                   ELSIF (l_source_tbl(i)        = 'XpenseXpress' OR
3129                          /* if its a Credit card txn, treat like expense report*/
3130                          l_source_tbl(i) in ('CREDIT CARD','Both Pay') OR
3131                         (l_source_tbl(i)        = 'Manual Invoice Entry' AND
3132                          l_inv_type_code_tbl(i) = 'EXPENSE REPORT') OR
3133                          l_source_tbl(i)        = 'SelfService') THEN
3134 
3135                       G_err_stage := 'Invoice source is Expense Reports';
3136                       write_log(LOG, G_err_stage);
3137                       G_TRANSACTION_SOURCE      := 'AP EXPENSE';
3138                       v_prev_transaction_source := G_TRANSACTION_SOURCE;
3139                       G_USER_TRANSACTION_SOURCE := 'ORACLE PAYABLES';
3140 
3141                   ELSE
3142 
3143                       G_err_stage := 'Invoice source is AP Invoice';
3144                       write_log(LOG, G_err_stage);
3145                       G_TRANSACTION_SOURCE             := 'AP INVOICE';
3146                       v_prev_transaction_source := G_TRANSACTION_SOURCE;
3147 
3148                       G_USER_TRANSACTION_SOURCE        := 'AP INVOICE';
3149                       l_ap_inv_flag                    := 'Y' ;
3150 
3151                   END IF;
3152 
3153                END IF; /* invoice source <> v_prev_tranasction_source */
3154 
3155                 /* For new invoice, initialize the transaction status code to 'P' */
3156                 G_TRANSACTION_STATUS_CODE := 'P';
3157 
3158                 G_err_stage := 'GET MAX EXPENDITURE ENDING DATE';
3159                 write_log(LOG, G_err_stage);
3160                 SELECT pa_utils.getweekending(MAX(expenditure_item_date))
3161                   INTO G_EXPENDITURE_ENDING_DATE
3162                   FROM ap_invoice_distributions
3163                  WHERE invoice_id = l_invoice_id_tbl(i);
3164 
3165                 G_err_stage := ('Getting bus group id');
3166                 write_log(LOG, G_err_stage);
3167 
3168                 BEGIN
3169 
3170                    IF l_employee_id_tbl(i) <> 0 THEN
3171 		   Begin
3172                       write_log(LOG,'getting bus group id with emp id of :  '||l_employee_id_tbl(i));
3173 
3174                       SELECT emp.business_group_id
3175                         INTO G_PER_BUS_GRP_ID
3176                         FROM per_all_people_f emp
3177                        WHERE emp.person_id = l_employee_id_tbl(i)
3178                           AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and trunc(emp.effective_end_date);
3179 
3180 			EXCEPTION
3181 			   WHEN NO_DATA_FOUND THEN
3182 			      l_txn_status_code_tbl(i)     := 'R';
3183 			      G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
3184 			      write_log(LOG, 'As no data found for Employee, Rejecting invoice'||l_invoice_id_tbl(i)  );
3185  		    End;
3186 		   Else
3187 		    Begin
3188 
3189 			    select org2.business_group_id
3190 			      into G_PER_BUS_GRP_ID
3191 			      from hr_organization_units org1,
3192 				   hr_organization_units org2
3193 			     Where org1.organization_id = l_exp_org_id_tbl(i)
3194 			       and org1.business_group_id = org2.organization_id ;
3195 
3196 			    Exception
3197 			      When no_data_found Then
3198 				G_TRANSACTION_STATUS_CODE := 'R';
3199 				G_TRANSACTION_REJECTION_CODE := 'INVALID_ORGANIZATION';
3200 				write_log(LOG,'As no data found for Organization,Rejecting invoice '||l_invoice_id_tbl(i)  );
3201 		     End;
3202         	END IF;   /* IF l_employee_id_tbl(i) <> 0 THEN  */
3203 
3204                 END;
3205 
3206            END IF; /* end of check for different invoice_id from previous invoice_id */
3207 
3208 
3209            /* The following will be executed when the distribution belongs to the same
3210               invoice or not the same invoice */
3211 
3212            v_num_distributions_fetched := v_num_distributions_fetched + 1;
3213            write_log(LOG,'Num of distributions fetched:'||v_num_distributions_fetched);
3214 
3215            /*Update counter of how many distributions of the last invoice of the batch has been processed*/
3216 
3217            IF l_invoice_id_tbl(i) = l_invoice_id_tbl(v_last_inv_index) THEN
3218               v_num_last_invoice_processed := v_num_last_invoice_processed +1;
3219 
3220               IF l_inv_type_code_tbl(i) = 'EXPENSE REPORT' THEN
3221                  v_last_inv_ER_flag := 'Y';
3222               ELSE
3223                  v_last_inv_ER_flag := 'N';
3224               END IF;
3225 
3226            END IF;
3227 
3228            -- FC Doc Type
3229             IF l_fc_enabled_tbl(i) = 'N' THEN
3230              l_fc_document_type_tbl(i) := 'NOT';
3231             END IF;
3232 
3233            /* if the invoice is an expense report from self-service we need to use the column of justification as the description */
3234            IF (l_inv_type_code_tbl(i) = 'EXPENSE REPORT' AND
3235                l_source_tbl(i)        in ('SelfService','XpenseXpress') ) THEN
3236                l_description_tbl(i) := l_justification_tbl(i);
3237            END IF;
3238 
3239            IF l_ln_type_lookup_tbl(i)  in ('NONREC_TAX','TRV','TIPV') THEN
3240 
3241               /* Update counter for number of tax lines fetched */
3242               v_num_tax_lines_fetched := v_num_tax_lines_fetched +1;
3243 
3244               l_cdl_sys_ref4_tbl(i) := l_ln_type_lookup_tbl(i);
3245               l_txn_src_tbl(i)      := G_NRT_TRANSACTION_SOURCE;
3246               l_user_txn_src_tbl(i) := G_NRT_USER_TRANSACTION_SOURCE;
3247               l_batch_name_tbl(i)   := G_NRT_BATCH_NAME;
3248               l_interface_id_tbl(i) := G_NRT_INTERFACE_ID;
3249 
3250            ELSIF l_ln_type_lookup_tbl(i) = 'IPV' THEN
3251 
3252               /* Update counter for number of variance lines fetched */
3253               v_num_inv_variance_fetched :=  v_num_inv_variance_fetched +1;
3254 
3255               l_quantity_tbl(i)     := l_denom_raw_cost_tbl(i);
3256               l_cdl_sys_ref4_tbl(i) := l_ln_type_lookup_tbl(i);
3257 
3258               l_txn_src_tbl(i)      := G_AP_VAR_TRANSACTION_SOURCE;
3259               l_user_txn_src_tbl(i) := G_AP_VAR_USER_TXN_SOURCE;
3260               l_batch_name_tbl(i)   := G_AP_VAR_BATCH_NAME;
3261               l_interface_id_tbl(i) := G_AP_VAR_INTERFACE_ID;
3262 
3263            ELSIF l_ln_type_lookup_tbl(i) in ('ERV','TERV') THEN
3264 
3265               /* Update counter for number of variance lines fetched */
3266               v_num_inv_erv_fetched :=  v_num_inv_erv_fetched +1;
3267 
3268               l_quantity_tbl(i)     := l_denom_raw_cost_tbl(i);
3269               l_cdl_sys_ref4_tbl(i) := l_ln_type_lookup_tbl(i);
3270 
3271               l_txn_src_tbl(i)      := G_AP_ERV_TRANSACTION_SOURCE;
3272               l_user_txn_src_tbl(i) := G_AP_ERV_USER_TXN_SOURCE;
3273               l_batch_name_tbl(i)   := G_AP_ERV_BATCH_NAME;
3274               l_interface_id_tbl(i) := G_AP_ERV_INTERFACE_ID;
3275 
3276 
3277            ELSIF  l_ln_type_lookup_tbl(i) in ('FREIGHT','MISCELLANEOUS') THEN
3278               /* Update counter for number of frt and misc lines fetched */
3279               v_num_inv_frt_fetched :=  v_num_inv_frt_fetched +1;
3280 
3281               l_cdl_sys_ref4_tbl(i) := l_ln_type_lookup_tbl(i);
3282               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
3283               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
3284               l_batch_name_tbl(i)   := G_AP_FRT_BATCH_NAME;
3285               l_interface_id_tbl(i) := G_AP_FRT_INTERFACE_ID;
3286 
3287            ELSE -- Other distribution types like ITEM,ACCRUAL,PREPAY etc
3288 
3289               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
3290               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
3291               l_batch_name_tbl(i)   := G_BATCH_NAME;
3292               l_interface_id_tbl(i) := G_INTERFACE_ID;
3293 
3294            END IF ;
3295 
3296            G_TRANSACTION_REJECTION_CODE := '';
3297 
3298            /*Setting values according to global variables*/
3299            l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
3300            l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
3301            l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
3302            l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
3303 
3304            write_log(LOG,'Value of l_txn_src_tbl:'||l_txn_src_tbl(i) ||'batch name:'||l_batch_name_tbl(i));
3305 
3306            /*-----------------------------------------------------------------------*/
3307            /*         PREPAYMENT PROCESSING */
3308            /*-----------------------------------------------------------------------*/
3309            /* In Rel12 we will not interface any R12 PREPAYMENT invoice or PREPAY applications to Oracle Projects */
3310            /* Howver we will still continue to interface reversals or prepayment application related to 11i PREPAYENT invoices */
3311            --
3312            /* The records with INSERT_FLAG = F indicate that they are fully applied prepayments and the pa-addition-flag
3313               for such records will be updated to G to relieve commitments*/
3314            /* The records with INSERT_FLAG = P indicate that they are partially applied prepayments and the pa-addition-flag
3315               for such records will be updated to N */
3316 
3317            l_prepay_hist_flag := 'X'; --initialize
3318 
3319            IF nvl(l_hist_flag_tbl(i),'N') = 'Y' THEN
3320 
3321               l_prepay_hist_flag := 'Y';
3322 
3323            ELSE
3324 
3325              IF (l_prepay_dist_id_tbl(i) is not null OR l_ln_type_lookup_tbl(i) = 'PREPAY' OR --Bug#5219683
3326                  l_inv_type_code_tbl(i) = 'PREPAYMENT' ) THEN --Bug#5444174
3327 
3328               l_prepay_hist_flag := 'N';
3329 
3330                BEGIN
3331 
3332               If g_body_debug_mode = 'Y' Then
3333                 write_log(LOG, 'Checking if the prepay application or prepayment inv reversal belongs to historical prepayment inv');
3334                 write_log(LOG, 'Historical prepayment dist id is '||to_char(l_prepay_dist_id_tbl(i)));
3335                 write_log(LOG, 'Parent Prepayment dist id of reversal dist id is '||to_char(l_parent_rev_id_tbl(i)));
3336               End If;
3337 
3338               IF l_prepay_dist_id_tbl(i) is not null THEN
3339                 SELECT nvl(historical_flag,'N')
3340                 INTO   l_prepay_hist_flag
3341                 FROM   ap_invoice_distributions_all
3342                 WHERE  invoice_distribution_id = l_prepay_dist_id_tbl(i);
3343 
3344               ELSIF  l_parent_rev_id_tbl(i) is not null THEN --Bug#5444174
3345                 SELECT nvl(historical_flag,'N')
3346                 INTO   l_prepay_hist_flag
3347                 FROM   ap_invoice_distributions_all
3348                 WHERE  invoice_distribution_id = l_parent_rev_id_tbl(i);
3349               END IF;
3350 
3351                 EXCEPTION
3352                 WHEN NO_DATA_FOUND THEN
3353                    l_txn_status_code_tbl(i) := 'R';
3354                    G_TRANSACTION_REJECTION_CODE := 'INVALID_INVOICE';
3355                    write_log(LOG, 'As no data found for parent distribution, Rejecting invoice dist Id'||l_invoice_dist_id_tbl(i));
3356                 WHEN OTHERS THEN
3357                    write_log(LOG, 'Error Code is  '||SQLCODE);
3358                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 1, 200));
3359                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 201, 200));
3360                    RAISE;
3361 
3362                 END;
3363 
3364              END IF;
3365            END IF;
3366 
3367            /* If the PREPAYMENT invoice was created pre-upgrade then the prepayment invoice and its
3368               application should be interfaced to PA else both should be prevented from interfacing to PA*/
3369 
3370            IF l_prepay_hist_flag = 'N' THEN
3371               IF (l_ln_type_lookup_tbl(i) = 'PREPAY' OR l_prepay_dist_id_tbl(i) IS NOT NULL ) THEN -- Bug#5444174
3372 
3373                 IF check_prepay_fully_applied(l_prepay_dist_id_tbl(i)) = 'Y' THEN
3374                    l_insert_flag_tbl(i) := 'F';
3375                 ELSE
3376                    l_insert_flag_tbl(i) := 'P';
3377                 END IF;
3378 
3379               ELSIF l_inv_type_code_tbl(i) = 'PREPAYMENT' THEN -- bug5444174
3380 
3381                 IF check_prepay_fully_applied(l_invoice_dist_id_tbl(i)) = 'Y' THEN
3382                    l_insert_flag_tbl(i) := 'F';
3383                 ELSE
3384                    l_insert_flag_tbl(i) := 'P';
3385                 END IF;
3386 
3387               END IF; --End of PREPAY AND PREPAYMENT inv
3388 
3389            ELSE  -- Distribution is historical data which should be interfaced into projects
3390 
3391            -- REVERSED DISTRIBUTIONS INTERFACE LOGIC
3392            -- If the distribution is a reversal or cancellation then check if the parent reversal distribution
3393            -- was historical data or not. If so, reversal distribution line will be interfaced as is.
3394            -- However if the parent reversal distribution is not historical then the following steps happen:
3395            -- a) Retreive the latest adjusted expenditures from PA against the parent reversal distribution id
3396            -- b) If any of the above latest EI's are not costed, then the reversed distribution will be rejected by the
3397            --    TRX import program
3398            -- c) IF all above adjusted EI's are costed, then insert record into the interface table for each adjusted EI.
3399            --    The project attributes will be copied from the adjusted EI's instead from the AP reversed
3400            --    distribution since these could have changed in PA.
3401            -- d) The interface program will interface the reversed distribution into projects
3402            -- e) The interface program will also insert a reversal of the reversed distribution into Projects. This is
3403            --    required for account reconciliation
3404            --
3405 
3406          -- This logic is to handle both the parent and reversal getting interfaced in the same run.
3407           -- It's a reversed parent record. Bug#4590527
3408           -- If both the parent and child reversing each other are interfaced in the same run, they
3409           -- were not getting interfaced as netzero transactions.
3410 
3411            IF (l_reversal_flag_tbl(i) = 'Y' or l_cancel_flag_tbl(i) = 'Y')
3412                                  AND l_parent_rev_id_tbl(i) IS NULL THEN
3413 
3414                 write_log(LOG, 'Reversal parent record '||l_invoice_dist_id_tbl(i));
3415               l_rev_index := l_rev_index +1;
3416               l_rev_parent_dist_id_tbl(l_rev_index) :=  l_invoice_dist_id_tbl(i);
3417               l_rev_child_dist_id_tbl(l_rev_index) :=  null;
3418               l_rev_parent_dist_ind_tbl(l_rev_index) :=  i; -- store the index of the parent.
3419 
3420            END IF;
3421 
3422            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
3423 
3424                 BEGIN
3425 
3426               If g_body_debug_mode = 'Y' Then
3427                 write_log(LOG, 'Checking if the invoice is a historical transaction');
3428                 write_log(LOG, 'Historical Transaction is '||to_char(l_parent_rev_id_tbl(i)));
3429                 write_log(LOG, 'Historical Invoice Id is '||to_char(l_invoice_id_tbl(i)));
3430               End If;
3431 
3432                 SELECT nvl(historical_flag,'N')
3433                 INTO   l_historical_flag
3434                 FROM   ap_invoice_distributions_all
3435                 WHERE  invoice_id = l_invoice_id_tbl(i)
3436                 AND    invoice_distribution_id = l_parent_rev_id_tbl(i); --check the index on this table
3437 
3438                 EXCEPTION
3439                 WHEN NO_DATA_FOUND THEN
3440                    l_txn_status_code_tbl(i) := 'R';
3441                    G_TRANSACTION_REJECTION_CODE := 'INVALID_INVOICE';
3442                    write_log(LOG, 'As no data found for reversed parent distribution, Rejecting invoice dist Id'||l_invoice_dist_id_tbl(i));
3443                 WHEN OTHERS THEN
3444                    write_log(LOG, 'Error Code is  '||SQLCODE);
3445                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 1, 200));
3446                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 201, 200));
3447                    RAISE;
3448 
3449                 END;
3450 
3451 
3452                 IF l_historical_flag = 'N' THEN
3453 
3454                      G_err_stage := 'Calling Process Adjustments';
3455                      write_log(LOG, G_err_stage);
3456 
3457                      -- Call reversal API
3458                      Process_Adjustments(p_record_type               => 'AP_INVOICE',
3459                                          p_document_header_id        => l_invoice_id_tbl(i),/*Added this for 6945767 */
3460                                          p_document_distribution_id  => l_parent_rev_id_tbl(i),
3461                                          p_current_index             => i,
3462 					 p_last_index                => j);
3463 
3464                      write_log(LOG, 'After calling Process Adjustments');
3465 
3466                       -- Set the create flag for adjustment records
3467                          IF l_insert_flag_tbl(i) in ('A','U') THEN
3468                           l_create_adj_recs := 'Y';
3469                          END IF;
3470 
3471                    If g_body_debug_mode = 'Y' Then
3472                      write_log(LOG, 'l_txn_rej_code_tbl = '||l_txn_rej_code_tbl(i));
3473                      write_log(LOG, 'l_txn_status_code_tbl = '||l_txn_status_code_tbl(i));
3474                    End If;
3475 
3476                 END IF; --End of check for historical Flag
3477 
3478            END IF; --End of check for reversal Distribution
3479 
3480            G_err_stage := ('Value of G_TRANS_DFF_AP:'||G_TRANS_DFF_AP);
3481            write_log(LOG, G_err_stage);
3482 
3483            IF (G_TRANS_DFF_AP = 'Y') THEN
3484 
3485                 v_attribute_category := l_attribute_cat_tbl(i);
3486                 v_attribute1 := l_attribute1_tbl(i);
3487                 v_attribute2 := l_attribute2_tbl(i);
3488                 v_attribute3 := l_attribute3_tbl(i);
3489                 v_attribute4 := l_attribute4_tbl(i);
3490                 v_attribute5 := l_attribute5_tbl(i);
3491                 v_attribute6 := l_attribute6_tbl(i);
3492                 v_attribute7 := l_attribute7_tbl(i);
3493                 v_attribute8 := l_attribute8_tbl(i);
3494                 v_attribute9 := l_attribute9_tbl(i);
3495                 v_attribute10 := l_attribute10_tbl(i);
3496 
3497                 v_dff_map_status := NULL;
3498 
3499                 PA_CLIENT_EXTN_DFFTRANS.DFF_map_segments_PA_and_AP(
3500                    p_calling_module            => 'PAAPIMP',
3501                    p_trx_ref_1                 => l_invoice_id_tbl(i),
3502                    --p_trx_ref_2                 => l_dist_line_num_tbl(i),
3503                    p_trx_ref_2                 => l_invoice_dist_id_tbl(i),  --NEW
3504                    p_trx_type                  => l_inv_type_code_tbl(i),
3505                    p_system_linkage_function   => G_SYSTEM_LINKAGE,
3506                    p_submodule                 => l_source_tbl(i),
3507                    p_expenditure_type          => l_exp_type_tbl(i),
3508                    p_set_of_books_id           => G_AP_SOB,
3509                    p_org_id                    => l_org_id_tbl(i),
3510                    p_attribute_category        => v_attribute_category,
3511                    p_attribute_1               => v_attribute1,
3512                    p_attribute_2               => v_attribute2,
3513                    p_attribute_3               => v_attribute3,
3514                    p_attribute_4               => v_attribute4,
3515                    p_attribute_5               => v_attribute5,
3516                    p_attribute_6               => v_attribute6,
3517                    p_attribute_7               => v_attribute7,
3518                    p_attribute_8               => v_attribute8,
3519                    p_attribute_9               => v_attribute9,
3520                    p_attribute_10              => v_attribute10,
3521                    x_status_code               => v_dff_map_status);
3522 
3523                    IF (v_dff_map_status IS NOT NULL) THEN
3524 
3525                        write_log(LOG, 'Error in DFF_map_segments_PA_and_AP, Error Code: ' || v_dff_map_status);
3526                        raise dff_map_exception;
3527 
3528                    END IF;
3529 
3530                    l_attribute_cat_tbl(i) := v_attribute_category;
3531                    l_attribute1_tbl(i) := v_attribute1;
3532                    l_attribute2_tbl(i) := v_attribute2;
3533                    l_attribute3_tbl(i) := v_attribute3;
3534                    l_attribute4_tbl(i) := v_attribute4;
3535                    l_attribute5_tbl(i) := v_attribute5;
3536                    l_attribute6_tbl(i) := v_attribute6;
3537                    l_attribute7_tbl(i) := v_attribute7;
3538                    l_attribute8_tbl(i) := v_attribute8;
3539                    l_attribute9_tbl(i) := v_attribute9;
3540                    l_attribute10_tbl(i) := v_attribute10;
3541 
3542 	   ElSE /* if DFF profile is No. Added for Bug 3105153*/
3543                    l_attribute_cat_tbl(i) := NULL;     --Bug#3856390
3544                    l_attribute1_tbl(i) := NULL;
3545                    l_attribute2_tbl(i) := NULL;
3546                    l_attribute3_tbl(i) := NULL;
3547                    l_attribute4_tbl(i) := NULL;
3548                    l_attribute5_tbl(i) := NULL;
3549                    l_attribute6_tbl(i) := NULL;
3550                    l_attribute7_tbl(i) := NULL;
3551                    l_attribute8_tbl(i) := NULL;
3552                    l_attribute9_tbl(i) := NULL;
3553                    l_attribute10_tbl(i) := NULL;
3554 
3555 	   END IF; /* if DFF profile is Yes */
3556 
3557         END IF; /* if prepay is fully applied */
3558 
3559       END LOOP; /* End of looping through each record in plsql table */
3560 
3561    EXCEPTION
3562       WHEN OTHERS THEN
3563           write_log(LOG,'Failed during process_inv_logic');
3564           G_err_code   := SQLCODE;
3565           raise;
3566 
3567    END process_inv_logic;
3568 
3569    BEGIN
3570    /* Main Procedure Logic starts here */
3571 
3572    G_err_stage := 'Within main procedure of transfer_inv_to_pa';
3573    write_log(LOG, G_err_stage);
3574 
3575      write_log(LOG, '......Result of G_TRANSACTION_SOURCE: ' || G_TRANSACTION_SOURCE);
3576 
3577      v_max_size := nvl(G_COMMIT_SIZE,200);
3578 
3579      -- Create a new interface ID for the first session
3580 
3581      OPEN Invoice_Cur;
3582 
3583      G_err_stage := 'After opening Invoice_Cur within transfer_inv_to_pa';
3584      write_log(LOG, G_err_stage);
3585 
3586      WHILE (v_all_done = 0) LOOP
3587 
3588        clear_plsql_tables;
3589 
3590        --Creating new interface ID every time this is called
3591        G_err_stage := 'CREATING NEW INTERFACE ID';
3592        write_log(LOG, G_err_stage);
3593 
3594        SELECT pa_interface_id_s.nextval
3595          INTO G_INTERFACE_ID
3596          FROM dual;
3597 
3598        G_err_stage := 'CREATING NEW NRT INTERFACE ID';
3599        SELECT pa_interface_id_s.nextval
3600          into G_NRT_INTERFACE_ID
3601          FROM dual;
3602 
3603 --new
3604        G_err_stage := 'CREATING NEW FRT INTERFACE ID';
3605        SELECT pa_interface_id_s.nextval
3606          into G_AP_FRT_INTERFACE_ID
3607          FROM dual;
3608 
3609 --new
3610        G_err_stage := 'CREATING NEW VARIANCE INTERFACE ID';
3611        SELECT pa_interface_id_s.nextval
3612          into G_AP_VAR_INTERFACE_ID
3613          FROM dual;
3614 --new
3615        G_err_stage := 'CREATING NEW VARIANCE INTERFACE ID';
3616        SELECT pa_interface_id_s.nextval
3617          into G_AP_ERV_INTERFACE_ID
3618          FROM dual;
3619 
3620           FETCH Invoice_Cur BULK COLLECT INTO
3621              l_invoice_id_tbl
3622 			,l_created_by_tbl
3623 			,l_invoice_dist_id_tbl --NEW
3624             ,l_cdl_sys_ref3_tbl
3625 			,l_project_id_tbl
3626 			,l_task_id_tbl
3627 			,l_ln_type_lookup_tbl
3628 			,l_exp_type_tbl
3629 			,l_ei_date_tbl
3630 			,l_amount_tbl
3631 			,l_description_tbl
3632 			,l_justification_tbl
3633 			,l_dist_cc_id_tbl
3634 			,l_exp_org_id_tbl
3635 			,l_quantity_tbl
3636 			,l_acct_pay_cc_id_tbl
3637 			,l_gl_date_tbl
3638 			,l_attribute_cat_tbl
3639 			,l_attribute1_tbl
3640 			,l_attribute2_tbl
3641 			,l_attribute3_tbl
3642 			,l_attribute4_tbl
3643 			,l_attribute5_tbl
3644 			,l_attribute6_tbl
3645 			,l_attribute7_tbl
3646 			,l_attribute8_tbl
3647 			,l_attribute9_tbl
3648 			,l_attribute10_tbl
3649 			,l_rec_cur_amt_tbl
3650 			,l_rec_cur_code_tbl
3651 			,l_rec_conv_rate_tbl
3652 			,l_denom_raw_cost_tbl
3653 			,l_denom_cur_code_tbl
3654 			,l_acct_rate_date_tbl
3655 			,l_acct_rate_type_tbl
3656 			,l_acct_exch_rate_tbl
3657 			,l_job_id_tbl
3658 			,l_employee_id_tbl
3659 			,l_vendor_id_tbl
3660 			,l_inv_type_code_tbl
3661 			,l_source_tbl
3662 			,l_org_id_tbl
3663 			,l_invoice_num_tbl
3664 			,l_cdl_sys_ref4_tbl
3665 			,l_po_dist_id_tbl
3666             ,l_txn_src_tbl
3667             ,l_user_txn_src_tbl
3668             ,l_batch_name_tbl
3669             ,l_interface_id_tbl
3670             ,l_exp_end_date_tbl
3671             ,l_txn_status_code_tbl
3672             ,l_txn_rej_code_tbl
3673             ,l_bus_grp_id_tbl
3674             ,l_paid_emp_id_tbl
3675             ,l_sort_var_tbl
3676             ,l_reversal_flag_tbl --NEW
3677             ,l_cancel_flag_tbl  --NEW
3678             ,l_parent_rev_id_tbl --NEW
3679             ,l_net_zero_flag_tbl --NEw
3680             ,l_sc_xfer_code_tbl
3681             ,l_adj_exp_item_id_tbl --NEW
3682             ,l_fc_enabled_tbl  --NEW
3683             ,l_mrc_exchange_date_tbl
3684             ,l_fc_document_type_tbl
3685             ,l_si_assts_add_flg_tbl
3686             ,l_insert_flag_tbl
3687             ,l_hist_flag_tbl
3688             ,l_prepay_dist_id_tbl
3689             LIMIT v_max_size;
3690 
3691          G_err_stage := 'After fetching Invoice_Cur within transfer_inv_to_pa';
3692          write_log(LOG, G_err_stage);
3693 
3694          IF l_invoice_id_tbl.COUNT <> 0 THEN
3695 
3696             /* get the index of the last invoice being processed within the batch*/
3697             v_last_inv_index := l_invoice_id_tbl.LAST;
3698 
3699             G_err_stage := 'calling process_inv_logic within transfer_inv_to_pa';
3700             write_log(LOG, G_err_stage);
3701 
3702             process_inv_logic;
3703 
3704             -- Added below process to update the inv distributions to either G or N for prepayment procsssing
3705             G_err_stage := 'calling bulk_update_trx_intf within transfer_inv_to_pa';
3706             write_log(LOG, G_err_stage);
3707 
3708             bulk_update_trx_intf;
3709 
3710             G_err_stage := 'calling bulk_insert_trx_intf within transfer_inv_to_pa';
3711             write_log(LOG, G_err_stage);
3712 
3713             bulk_insert_trx_intf;
3714 
3715             G_err_stage := 'After calling bulk_insert_trx_intf within transfer_inv_to_pa';
3716             write_log(LOG, G_err_stage);
3717 
3718             OPEN Num_Dist_Marked_O(l_invoice_id_tbl(v_last_inv_index));
3719 
3720             G_err_stage := 'After opening cursor Num_Dist_Marked_O within transfer_inv_to_pa';
3721             write_log(LOG, G_err_stage);
3722 
3723             FETCH Num_Dist_Marked_O INTO
3724                   v_num_dist_marked_O;
3725 
3726             G_err_stage := 'After fetching cursor Num_Dist_Marked_O within transfer_inv_to_pa';
3727             write_log(LOG, G_err_stage);
3728 
3729             v_num_dist_remain := v_num_dist_marked_O - v_num_last_invoice_processed;
3730             write_log(LOG,'Number of last invoice processed:  '||v_num_last_invoice_processed||
3731                           'Number of last invoice remaining:  '||v_num_dist_remain);
3732 
3733             write_log(LOG,'Is the last invoice an expense report?  '||v_last_inv_ER_flag);
3734 
3735             IF (v_num_dist_remain  > 0 AND
3736                 v_last_inv_ER_flag = 'Y') THEN
3737 
3738                G_err_stage := 'Within condition of v_num_dist_remain>0 of transfer_inv_to_pa';
3739                write_log(LOG, G_err_stage);
3740 
3741                clear_plsql_tables;
3742 
3743                FETCH Invoice_Cur BULK COLLECT INTO
3744                   l_invoice_id_tbl,
3745                   l_created_by_tbl,
3746                   l_invoice_dist_id_tbl, --NEW
3747                   l_cdl_sys_ref3_tbl,
3748                   l_project_id_tbl,
3749                   l_task_id_tbl,
3750                   l_ln_type_lookup_tbl,
3751                   l_exp_type_tbl,
3752                   l_ei_date_tbl,
3753                   l_amount_tbl,
3754                   l_description_tbl,
3755                   l_justification_tbl,
3756                   l_dist_cc_id_tbl,
3757                   l_exp_org_id_tbl,
3758                   l_quantity_tbl,
3759                   l_acct_pay_cc_id_tbl,
3760                   l_gl_date_tbl,
3761                   l_attribute_cat_tbl,
3762                   l_attribute1_tbl,
3763              l_attribute2_tbl,
3764              l_attribute3_tbl,
3765              l_attribute4_tbl,
3766              l_attribute5_tbl,
3767              l_attribute6_tbl,
3768              l_attribute7_tbl,
3769              l_attribute8_tbl,
3770              l_attribute9_tbl,
3771              l_attribute10_tbl,
3772              l_rec_cur_amt_tbl,
3773              l_rec_cur_code_tbl,
3774              l_rec_conv_rate_tbl,
3775              l_denom_raw_cost_tbl,
3776              l_denom_cur_code_tbl,
3777              l_acct_rate_date_tbl,
3778              l_acct_rate_type_tbl,
3779              l_acct_exch_rate_tbl,
3780              l_job_id_tbl,
3781              l_employee_id_tbl,
3782              l_vendor_id_tbl,
3783              l_inv_type_code_tbl,
3784              l_source_tbl,
3785              l_org_id_tbl,
3786              l_invoice_num_tbl,
3787              l_cdl_sys_ref4_tbl,
3788              l_po_dist_id_tbl
3789              ,l_txn_src_tbl
3790              ,l_user_txn_src_tbl
3791              ,l_batch_name_tbl
3792              ,l_interface_id_tbl
3793              ,l_exp_end_date_tbl
3794               ,l_txn_status_code_tbl
3795               ,l_txn_rej_code_tbl
3796               ,l_bus_grp_id_tbl
3797               ,l_paid_emp_id_tbl
3798               ,l_sort_var_tbl
3799               ,l_reversal_flag_tbl --NEW
3800               ,l_cancel_flag_tbl  --NEW
3801               ,l_parent_rev_id_tbl --NEW
3802               ,l_net_zero_flag_tbl --NEW
3803               ,l_sc_xfer_code_tbl
3804               ,l_adj_exp_item_id_tbl --NEW
3805               ,l_fc_enabled_tbl --NEW
3806               ,l_mrc_exchange_date_tbl
3807               ,l_fc_document_type_tbl
3808               ,l_si_assts_add_flg_tbl
3809               ,l_insert_flag_tbl
3810               ,l_hist_flag_tbl
3811               ,l_prepay_dist_id_tbl
3812             LIMIT v_num_dist_remain;
3813 
3814             G_err_stage := 'After second fetch of Invoice_Cur within transfer_inv_to_pa';
3815             write_log(LOG, G_err_stage);
3816 
3817                IF l_invoice_id_tbl.COUNT <> 0 THEN
3818 
3819                   G_err_stage := 'Before 2nd call of process_inv_logic  within transfer_inv_to_pa';
3820                   write_log(LOG, G_err_stage);
3821 
3822                   /* Set the index of the last invoice being processed within the batch*/
3823                   v_last_inv_index := l_invoice_id_tbl.LAST;
3824 
3825                   process_inv_logic;
3826 
3827                  -- Added below process to update the inv distributions to either G or N for prepayment procsssing
3828                   G_err_stage := 'calling bulk_update_trx_intf within transfer_inv_to_pa';
3829                   write_log(LOG, G_err_stage);
3830 
3831                   bulk_update_trx_intf;
3832 
3833                   G_err_stage := 'Before 2nd call of bulk_insert_trx_intf within transfer_inv_to_pa';
3834                   write_log(LOG, G_err_stage);
3835 
3836                   bulk_insert_trx_intf;
3837 
3838               END IF; /* l_invoice_id_tbl.COUNT = 0 */
3839 
3840            END IF; /* IF v_num_dist_remain > 0 */
3841 
3842            CLOSE Num_Dist_Marked_O;
3843 
3844 
3845            G_err_stage := 'Before calling transaction import and tiebacks within transfer_inv_to_pa';
3846            write_log(LOG, G_err_stage);
3847 
3848            IF (v_num_distributions_fetched > 0) THEN
3849 
3850                v_inv_batch_size           := v_num_distributions_fetched - v_num_tax_lines_fetched -
3851                                              v_num_inv_variance_fetched - v_num_inv_frt_fetched;
3852 
3853               write_log(LOG,'Before calling trx_import for invoices with interface_id:'||G_INTERFACE_ID);
3854               --Logic to handle IP and AP INVOICES getting interfaced in the same run.Bug#4764470.
3855 
3856              IF (l_ap_inv_flag ='Y' ) THEN
3857 
3858               write_log(LOG,'Before calling trx_import for AP invoices');
3859               trans_import('AP INVOICE', G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
3860               tieback_AP_ER('AP INVOICE', G_BATCH_NAME, G_INTERFACE_ID);
3861 
3862              END IF;
3863 
3864              IF (l_ip_inv_flag ='Y' ) THEN
3865 
3866               write_log(LOG,'Before calling trx_import for IP invoices');
3867               trans_import(L_IP_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
3868               tieback_AP_ER(L_IP_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID);
3869 
3870              ELSIF (l_ap_inv_flag ='N') THEN
3871 
3872               write_log(LOG,'Before calling trx_import for trx src ='||G_TRANSACTION_SOURCE);
3873               trans_import(G_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
3874               tieback_AP_ER(G_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID);
3875 
3876              END IF;
3877               --End of logic to handle IP and AP INVOICES getting interfaced in the same run.Bug#4764470.
3878 
3879 
3880               IF (nvl(v_num_tax_lines_fetched,0) > 0 AND
3881                      (G_INVOICE_TYPE IS NULL OR G_INVOICE_TYPE = 'EXPENSE REPORT')) THEN
3882 
3883                   write_log(LOG,'Before calling trx_import for NRTAX for interface_id:'||G_NRT_INTERFACE_ID);
3884                   v_tax_batch_size           := v_num_tax_lines_fetched;
3885 
3886                   trans_import(G_NRT_TRANSACTION_SOURCE, G_NRT_BATCH_NAME, G_NRT_INTERFACE_ID, G_USER_ID);
3887                   tieback_AP_ER(G_NRT_TRANSACTION_SOURCE, G_NRT_BATCH_NAME, G_NRT_INTERFACE_ID);
3888 
3889               END IF; /* IF (nvl(v_num_tax_lines_fetched,0) > 0*/
3890 
3891               IF nvl(v_num_inv_variance_fetched,0) > 0 THEN
3892 
3893                   write_log(LOG,'Before calling trx_import for Variance for interface_id:'||G_AP_VAR_INTERFACE_ID);
3894                   v_var_batch_size           := v_num_inv_variance_fetched;
3895 
3896                   trans_import(G_AP_VAR_TRANSACTION_SOURCE, G_AP_VAR_BATCH_NAME, G_AP_VAR_INTERFACE_ID, G_USER_ID);
3897                   tieback_AP_ER(G_AP_VAR_TRANSACTION_SOURCE, G_AP_VAR_BATCH_NAME, G_AP_VAR_INTERFACE_ID);
3898 
3899               END IF; /* IF (nvl(v_num_inv_variance_lines_fetched,0) > 0*/
3900 
3901               IF nvl(v_num_inv_erv_fetched,0) > 0 THEN
3902 
3903                   write_log(LOG,'Before calling trx_import for AP ERV for interface_id:'||G_AP_ERV_INTERFACE_ID);
3904                   v_var_batch_size           := v_num_inv_variance_fetched;
3905 
3906                   trans_import(G_AP_ERV_TRANSACTION_SOURCE, G_AP_ERV_BATCH_NAME, G_AP_ERV_INTERFACE_ID, G_USER_ID);
3907                   tieback_AP_ER(G_AP_ERV_TRANSACTION_SOURCE, G_AP_ERV_BATCH_NAME, G_AP_ERV_INTERFACE_ID);
3908 
3909               END IF; /* IF (nvl(v_num_inv_erv_lines_fetched,0) > 0*/
3910 
3911               IF nvl(v_num_inv_frt_fetched,0) > 0 THEN
3912 
3913                   write_log(LOG,'Before calling trx_import for Frt and Misc for interface_id:'||G_AP_FRT_INTERFACE_ID);
3914                   v_frt_batch_size           := v_num_inv_frt_fetched;
3915 
3916                   trans_import(G_TRANSACTION_SOURCE, G_AP_FRT_BATCH_NAME, G_AP_FRT_INTERFACE_ID, G_USER_ID);
3917                   tieback_AP_ER(G_TRANSACTION_SOURCE, G_AP_FRT_BATCH_NAME, G_AP_FRT_INTERFACE_ID);
3918 
3919               END IF; /* IF (nvl(v_num_inv_frt_lines_fetched,0) > 0*/
3920 
3921               write_log(LOG,'Calling tieback for locked RCV transactions');
3922               tieback_locked_rcvtxn;
3923 
3924 /*** Commented 3922679  *
3925               G_err_stage := 'Before calling commit';
3926               write_log(LOG, G_err_stage);
3927               COMMIT;
3928 *** Commented 3922679  End*/
3929 
3930               G_err_stage := 'Before updating the total number of invoices processed';
3931               write_log(LOG, G_err_stage);
3932 
3933               G_NUM_BATCHES_PROCESSED       := G_NUM_BATCHES_PROCESSED + 1;
3934               G_NUM_INVOICES_PROCESSED      :=  G_NUM_INVOICES_PROCESSED + v_num_invoices_fetched;
3935               G_NUM_DISTRIBUTIONS_PROCESSED :=  G_NUM_DISTRIBUTIONS_PROCESSED + v_num_distributions_fetched;
3936               write_log(LOG,'G_NUM_BATCHES_PROCESSED:'||G_NUM_BATCHES_PROCESSED);
3937               write_log(LOG,'G_NUM_INVOICES_PROCESSED:'||G_NUM_INVOICES_PROCESSED);
3938               write_log(LOG,'G_NUM_DISTRIBUTIONS_PROCESSED:'||G_NUM_DISTRIBUTIONS_PROCESSED);
3939 
3940         END IF; /* IF (v_num_distributions_fetched > 0) */
3941 
3942         G_err_stage := 'After calling transaction import and tiebacks within transfer_inv_to_pa';
3943         write_log(LOG, G_err_stage);
3944 
3945         clear_plsql_tables;
3946 
3947         v_num_invoices_fetched       :=0;
3948         v_num_distributions_fetched  :=0;
3949         v_num_tax_lines_fetched      :=0;
3950         v_inv_batch_size             :=0;
3951         v_tax_batch_size             :=0;
3952         v_var_batch_size             :=0;
3953         v_frt_batch_size             :=0;
3954         v_num_dist_remain            :=0;
3955         v_num_dist_marked_O          :=0;
3956         v_num_last_invoice_processed :=0;
3957         v_last_inv_ER_flag           := 'N';
3958 
3959         G_err_stage:='Before exiting when Invoice_Cur is NOTFOUND';
3960         write_log(LOG,   G_err_stage);
3961 
3962       ELSE
3963 
3964           G_err_stage:='Cursor fetched zero rows into plsql tables. Exiting';
3965           write_log(LOG,   G_err_stage);
3966           EXIT;
3967       END IF; /* l_invoice_id_tbl.COUNT = 0 */
3968 
3969       G_err_stage:='Cursor fetched no more rows. Exiting';
3970       write_log(LOG,   G_err_stage);
3971       EXIT WHEN Invoice_Cur%NOTFOUND;
3972 
3973    END LOOP; /* While more rows to process is true */
3974 
3975    CLOSE Invoice_Cur;
3976 
3977 EXCEPTION
3978     WHEN OTHERS THEN
3979 
3980          G_err_stack := v_old_stack;
3981          IF invoice_cur%ISOPEN THEN
3982            CLOSE Invoice_Cur;
3983          END IF ;
3984 
3985          G_err_code := SQLCODE;
3986          RAISE;
3987 
3988 END transfer_inv_to_pa;
3989 
3990 /*---------------------------Tieback to AP Phase----------------------------*/
3991 PROCEDURE tieback_AP_ER(
3992    p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
3993    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
3994    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
3995 
3996    l_assets_addflag          VARCHAR2(1):=NULL;
3997    l_prev_assets_addflag     VARCHAR2(1):=NULL;
3998    l_project_id             NUMBER :=0;
3999    l_pa_addflag             VARCHAR2(1):=NULL;
4000    l_prev_proj_id           NUMBER :=0;
4001 
4002    l_sys_ref1_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
4003    l_sys_ref2_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
4004 --   l_sys_ref3_tbl           PA_PLSQL_DATATYPES.Char15TabTyp; --NEW
4005 --   l_sys_ref4_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
4006    l_sys_ref5_tbl           PA_PLSQL_DATATYPES.IdTabTyp;    --NEW --check with Ajay if its declared as number type
4007    l_txn_src_tbl            PA_PLSQL_DATATYPES.Char30TabTyp;
4008    l_batch_name_tbl         PA_PLSQL_DATATYPES.Char50TabTyp;
4009    l_interface_id_tbl       PA_PLSQL_DATATYPES.IdTabTyp;
4010    l_txn_status_code_tbl    PA_PLSQL_DATATYPES.Char2TabTyp;
4011    l_project_id_tbl            PA_PLSQL_DATATYPES.IdTabTyp;
4012    l_pa_addflag_tbl         PA_PLSQL_DATATYPES.CHAR1TabTyp;
4013    l_assets_addflag_tbl     PA_PLSQL_DATATYPES.CHAR1TabTyp;
4014 
4015    CURSOR txn_intf_rec (p_txn_src       IN VARCHAR2,
4016                         p_batch_name    IN VARCHAR2,
4017                         p_interface_id  IN NUMBER) IS
4018       SELECT cdl_system_reference1
4019             ,cdl_system_reference2
4020          --   ,cdl_system_reference3  --NEW
4021          --   ,cdl_system_reference4
4022             ,cdl_system_reference5 --NEW
4023             ,transaction_source
4024             ,batch_name
4025             ,interface_id
4026             ,transaction_status_code
4027             ,project_id
4028             ,l_pa_addflag
4029             ,l_assets_addflag
4030         FROM pa_transaction_interface_all txnintf
4031        WHERE txnintf.transaction_source = p_txn_src
4032          AND txnintf.batch_name         = p_batch_name
4033          AND txnintf.interface_id       = p_interface_id;
4034 
4035    PROCEDURE clear_plsql_tables IS
4036 
4037       v_status   VARCHAR2(15);
4038 
4039    BEGIN
4040 
4041       G_err_stage:='Clearing PLSQL tables in invoice tieback';
4042       write_log(LOG,   G_err_stage);
4043 
4044       l_sys_ref1_tbl.delete;
4045       l_sys_ref2_tbl.delete;
4046    --   l_sys_ref3_tbl.delete; --NEW
4047    --   l_sys_ref4_tbl.delete; --NEW
4048       l_sys_ref5_tbl.delete; --NEW
4049       l_txn_src_tbl.delete;
4050       l_batch_name_tbl.delete;
4051       l_interface_id_tbl.delete;
4052       l_txn_status_code_tbl.delete;
4053       l_project_id_tbl.delete;
4054       l_pa_addflag_tbl.delete;
4055       l_assets_addflag_tbl.delete;
4056 
4057    END clear_plsql_tables;
4058 
4059    PROCEDURE process_tieback IS
4060 
4061       v_status   VARCHAR2(15);
4062 
4063    BEGIN
4064 
4065       G_err_stage:='Within process_tieback of invoice tieback';
4066       write_log(LOG,   G_err_stage);
4067 
4068       FOR i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST LOOP
4069 
4070          /* If transaction import stamps the record to be 'A' then
4071             update pa_addition_flag of invoice distribution to 'Y'.
4072             If transaction import leaves the record to be 'P' then
4073             update pa_addition_flag of invoice distribution to 'N'.
4074             If transaction import stamps the record to be 'R' then
4075             update pa_addition_flag of invoice distribution to 'N'.*/
4076 
4077          write_log(LOG,'Tying invoice_id: '||l_sys_ref2_tbl(i)||
4078                        --'dist num:  '||l_sys_ref3_tbl(i)||  --NEW
4079                        'dist id:  '||l_sys_ref5_tbl(i)||  --NEW
4080                        'trc src:   '||l_txn_src_tbl(i));
4081 
4082          IF l_txn_status_code_tbl(i) = 'A' THEN
4083                l_pa_addflag_tbl(i) := 'Y';
4084          ELSIF l_txn_status_code_tbl(i) = 'P' THEN
4085                l_pa_addflag_tbl(i) :='N';
4086          ELSIF l_txn_status_code_tbl(i) = 'R' THEN
4087                l_pa_addflag_tbl(i) := 'N';
4088          END IF;
4089 
4090          IF G_PROJECT_ID IS NOT NULL THEN
4091 
4092             IF G_Assets_Addition_flag = 'P' THEN
4093                l_assets_addflag_tbl(i) := 'P';
4094             ELSE
4095                l_assets_addflag_tbl(i) := 'X';
4096             END IF;
4097 
4098          ELSIF G_PROJECT_ID IS NULL THEN
4099 
4100             IF l_project_id_tbl(i) <> l_prev_proj_id THEN
4101 
4102                G_err_stage:='Selecting assets addition flag within invoice tieback';
4103                write_log(LOG,   G_err_stage);
4104 
4105                SELECT decode(PTYPE.Project_Type_Class_Code,'CAPITAL','P','X')
4106                  INTO l_assets_addflag_tbl(i)
4107                  FROM pa_project_types_all PTYPE,
4108                       pa_projects_all PROJ
4109                 WHERE PTYPE.Project_Type = PROJ.Project_Type
4110                   AND (PTYPE.org_id = PROJ.org_id OR
4111                        PROJ.org_id is null)
4112                   AND PROJ.Project_Id = l_project_id_tbl(i);
4113 
4114                 l_prev_proj_id := l_project_id_tbl(i);
4115 		l_prev_assets_addflag := l_assets_addflag_tbl(i);
4116 
4117             ELSE
4118                l_assets_addflag_tbl(i) := l_prev_assets_addflag;
4119             END IF;
4120 
4121          END IF;
4122 
4123       END LOOP;
4124 
4125    EXCEPTION
4126       WHEN OTHERS THEN
4127          G_err_stage:= 'Failed during process tieback of invoice tieback';
4128          write_log(LOG,   G_err_stage);
4129          G_err_code   := SQLCODE;
4130          raise;
4131 
4132    END process_tieback;
4133 
4134    PROCEDURE bulk_update_txn_intf IS
4135 
4136       v_status VARCHAR2(15);
4137 
4138    BEGIN
4139 
4140       G_err_stage:=('Within bulk update of invoice tieback');
4141       write_log(LOG,   G_err_stage);
4142 
4143       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
4144 
4145          UPDATE ap_invoice_distributions_all dist
4146             SET dist.pa_addition_flag         = l_pa_addflag_tbl(i)
4147                ,dist.assets_addition_flag      = decode(l_assets_addflag_tbl(i),'P','P',dist.assets_addition_flag)
4148           WHERE dist.invoice_id               = l_sys_ref2_tbl(i)
4149             AND dist.invoice_distribution_id  = l_sys_ref5_tbl(i)
4150             AND dist.pa_addition_flag         = 'O';
4151 
4152       /* Bug 5440548 fix to update expenditure data with historical flag for historical AP data */
4153       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
4154 
4155          UPDATE pa_expenditure_items_all exp1
4156             SET historical_flag = 'Y'
4157          WHERE  document_header_id = l_sys_ref2_tbl(i)
4158            AND  document_distribution_id = l_sys_ref5_tbl(i)
4159            AND  exists (select 'exist'
4160                         from   ap_invoice_distributions_all dist
4161                         where  dist.invoice_id =l_sys_ref2_tbl(i)
4162                         and    dist.invoice_distribution_id = l_sys_ref5_tbl(i)
4163                         and    dist.pa_addition_flag = 'Y'
4164                         and    dist.historical_flag = 'Y');
4165 
4166          /* If the accounting method is CASH BASIS then the payment lines associated with historical invoices should be updated to G
4167             since such invoice distributions will be not be interfaced as PAYMENTS but as INVOICES */
4168 
4169          IF G_ACCTNG_METHOD = 'C' THEN
4170 
4171            FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
4172 
4173            UPDATE ap_payment_hist_dists dist
4174               SET    dist.pa_addition_flag = 'G',
4175                      request_id = G_REQUEST_ID,
4176                      last_update_date=SYSDATE,
4177                      last_updated_by= G_USER_ID,
4178                      last_update_login= G_USER_ID,
4179                      program_id= G_PROG_ID,
4180                      program_application_id= G_PROG_APPL_ID,
4181                      program_update_date=SYSDATE
4182               WHERE nvl(dist.pa_addition_flag,'N') = 'N'
4183               AND   dist.pay_dist_lookup_code = 'CASH'
4184               AND EXISTS (SELECT NULL
4185                           FROM   ap_payment_history_all hist
4186                           WHERE  hist.payment_history_id = dist.payment_history_id
4187                           AND    hist.posted_flag = 'Y')
4188               AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
4189                              FROM AP_INVOICES_ALL inv,
4190                                   AP_Invoice_Distributions_all aid,
4191                                   ap_invoice_payments_all aip
4192                             WHERE inv.invoice_id              = aip.invoice_id
4193                               AND aid.invoice_id              = inv.invoice_id
4194                               AND aip.invoice_payment_id      = dist.invoice_payment_id
4195                               AND aid.invoice_distribution_id = dist.invoice_distribution_id
4196                               AND inv.org_id = G_ORG_ID
4197                               AND aip.invoice_id              = l_sys_ref2_tbl(i)
4198                               AND aid.invoice_distribution_id = l_sys_ref5_tbl(i));
4199 
4200          END IF;
4201    EXCEPTION
4202       WHEN OTHERS THEN
4203          G_err_stage:= 'Failed during bulk update of invoice tieback';
4204          write_log(LOG,   G_err_stage);
4205          G_err_code   := SQLCODE;
4206          raise;
4207 
4208    END bulk_update_txn_intf;
4209 
4210    BEGIN
4211 
4212       /* Main logic of tieback starts here */
4213       G_err_stage:='Within main logic of tieback';
4214       write_log(LOG,   G_err_stage);
4215 
4216       clear_plsql_tables;
4217 
4218       G_err_stage:='Opening txn_intf_rec';
4219       write_log(LOG,   G_err_stage);
4220 
4221       OPEN txn_intf_rec(p_transaction_source
4222                        ,p_batch_name
4223                        ,p_interface_id);
4224 
4225       G_err_stage:='Fetching txn_intf_rec';
4226       write_log(LOG,   G_err_stage);
4227 
4228       FETCH txn_intf_rec BULK COLLECT INTO
4229           l_sys_ref1_tbl
4230          ,l_sys_ref2_tbl
4231          --,l_sys_ref3_tbl --NEW
4232          --,l_sys_ref4_tbl --NEW
4233          ,l_sys_ref5_tbl  --NEW
4234          ,l_txn_src_tbl
4235          ,l_batch_name_tbl
4236          ,l_interface_id_tbl
4237          ,l_txn_status_code_tbl
4238          ,l_project_id_tbl
4239          ,l_pa_addflag_tbl
4240          ,l_assets_addflag_tbl;
4241 
4242       IF l_sys_ref1_tbl.COUNT <> 0 THEN
4243 
4244          process_tieback;
4245 
4246          bulk_update_txn_intf;
4247 
4248          clear_plsql_tables;
4249 
4250       END IF;
4251 
4252       CLOSE txn_intf_rec;
4253 
4254 EXCEPTION
4255    WHEN OTHERS THEN
4256 
4257       IF txn_intf_rec%ISOPEN THEN
4258          CLOSE txn_intf_rec;
4259       END IF;
4260 
4261       G_err_code := SQLCODE;
4262       RAISE;
4263 
4264 END tieback_AP_ER;
4265 
4266 
4267 PROCEDURE lock_rcv_txn (p_po_distribution_id IN ap_invoice_distributions.po_distribution_id%TYPE) IS
4268 
4269    l_num_rows   NUMBER;
4270 
4271 BEGIN
4272 
4273    G_err_stage := 'Within calling lock_rcv_txn';
4274    write_log(LOG, G_err_stage);
4275 
4276 --pricing changes, updating sub_ledger instead of rcv_transactions
4277 -- Modified this update for bug 6825742
4278 
4279 UPDATE rcv_receiving_sub_ledger rcv_sub
4280 SET rcv_sub.pa_addition_flag = 'L'
4281 WHERE rcv_sub.pa_addition_flag = 'N'
4282 and reference3 = TO_CHAR(p_po_distribution_id) and exists (
4283 select 1 from po_distributions_all pod
4284 where po_distribution_id = TO_NUMBER(rcv_sub.reference3)
4285 and   po_distribution_id = p_po_distribution_id
4286 and code_combination_id = rcv_sub.code_combination_id
4287 and accrue_on_receipt_flag = 'Y');
4288 
4289    /* UPDATE rcv_receiving_sub_ledger rcv_sub
4290       SET rcv_sub.pa_addition_flag   = 'L'
4291     WHERE rcv_sub.pa_addition_flag   = 'N'
4292     AND EXISTS (SELECT transaction_id
4293 		FROM rcv_transactions rcv_txn
4294 		WHERE rcv_txn.transaction_id = rcv_sub.rcv_transaction_id
4295 		AND rcv_txn.po_distribution_id = p_po_distribution_id ); commented for bug 6825742*/
4296 
4297    l_num_rows := SQL%ROWCOUNT;
4298 
4299    write_log(LOG,'number of RCV transactions locked:'||l_num_rows);
4300 
4301 EXCEPTION
4302    WHEN NO_DATA_FOUND THEN
4303       NULL;
4304 
4305    WHEN OTHERS THEN
4306      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
4307      G_err_code := SQLCODE;
4308      RAISE;
4309 
4310 END lock_rcv_txn;
4311 
4312 PROCEDURE tieback_locked_rcvtxn IS
4313 
4314    l_num_rows NUMBER;
4315 
4316 BEGIN
4317 
4318    G_err_stage := 'Within calling tieback_locked_rcvtxn';
4319    write_log(LOG, G_err_stage);
4320 
4321    UPDATE rcv_receiving_sub_ledger rcv_sub
4322       SET rcv_sub.pa_addition_flag = 'G'
4323     WHERE rcv_sub.pa_addition_flag = 'L';
4324 
4325    l_num_rows := SQL%ROWCOUNT;
4326 
4327    write_log(LOG,'number of RCV transactions unlocked:'||l_num_rows);
4328 
4329 EXCEPTION
4330    WHEN NO_DATA_FOUND THEN
4331        NULL;
4332 
4333    WHEN OTHERS THEN
4334 
4335      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
4336      G_err_code := SQLCODE;
4337      RAISE;
4338 END tieback_locked_rcvtxn;
4339 
4340    Function get_cdl_ccid(p_expenditure_item_id IN NUMBER, ccid_flag IN varchar2)
4341    RETURN NUMBER is
4342 
4343    l_cr_ccid NUMBER;
4344    l_dr_ccid NUMBER;
4345 
4346    begin
4347 
4348        IF p_expenditure_item_id <> l_prev_exp_item_id THEN
4349 
4350        G_err_stage := 'Selecting Adjustment account: get_cdl_ccid';
4351        write_log(LOG, G_err_stage);
4352 
4353        SELECT cr_code_combination_id, dr_code_combination_id
4354        INTO   l_cr_ccid, l_dr_ccid
4355        FROm   pa_cost_distribution_lines_all cdl
4356        WHERE  cdl.expenditure_item_id = p_expenditure_item_id
4357        AND    cdl.line_num in (select max(line_num)
4358                                from pa_cost_distribution_lines_all cdl2
4359                                where  cdl2.expenditure_item_id = cdl.expenditure_item_id
4360                                and    line_type ='R');
4361 
4362        l_prev_exp_item_id := p_expenditure_item_id;
4363        l_prev_cr_ccid := l_cr_ccid;
4364        l_prev_dr_ccid := l_dr_ccid;
4365 
4366 
4367        END IF;
4368 
4369        IF ccid_flag = 'C' THEN
4370          return l_prev_cr_ccid;
4371        ELSE
4372          return l_prev_dr_ccid;
4373        END IF;
4374 
4375 
4376        EXCEPTION WHEN NO_DATA_FOUND THEN
4377          return null;
4378    End;
4379 
4380 
4381 /*==========================================================================*/
4382 --The following section contains procedures for Supplier Invoice Discounts
4383 --The logic of doscount processing can be undestood as:
4384 -- 1) Update PA_addition_flag on Discount payment lines to 'O' to lock the record
4385 -- 3) Transfer_disc_to_pa populates PA transaction_interface table and call trx import
4386 -- 4) Tieback procedure called to update discount payment lines after trx import
4387 /*==========================================================================*/
4388 
4389 /*-----Function checks the profile setup of cutoff date for which discounts to be pulled----*/
4390 FUNCTION return_profile_discount_date
4391     RETURN VARCHAR2 IS
4392 
4393    v_discount_start_date VARCHAR2(15);
4394 
4395 BEGIN
4396 
4397     select nvl(fnd_profile.value_specific('PA_DISC_PULL_START_DATE'),'2051/01/01')  --bug4474213.
4398       INTO v_discount_start_date
4399       from DUAL;
4400     RETURN v_discount_start_date;
4401 
4402 END return_profile_discount_date;
4403 
4404 /*-----Function checks what method of discount is used by system-----*/
4405 FUNCTION return_discount_method
4406      RETURN VARCHAR2 IS
4407 
4408      v_method VARCHAR2(15);
4409 
4410 BEGIN
4411 
4412      SELECT discount_distribution_method
4413         INTO v_method
4414         FROM AP_SYSTEM_PARAMETERS;
4415       RETURN v_method;
4416 
4417 END return_discount_method;
4418 
4419 /*-----------------------Marking Distribution Phase---------------------*/
4420 
4421 PROCEDURE mark_PA_disc_flag_O IS
4422 
4423         v_old_stack VARCHAR2(630);
4424 
4425 BEGIN
4426 
4427      v_old_stack := G_err_stack;
4428      G_err_stack := G_err_stack || '->PAAPIMP_PKG.mark_PA_Disc_flag_O';
4429      G_err_code := 0;
4430      G_err_stage := 'UPDATING DISCOUNT DISTRIBUTIONS-Marking Process';
4431 
4432      write_log(LOG, G_err_stack);
4433 
4434      IF G_PROJECT_ID is not NULL THEN
4435 
4436           -- Mark all Discount lines associated with PREPAYMENT payment to G to prevent interface into Projects
4437           -- In Rel12, we will only bring in Prepayment application lines (AP_PREPAY_APP_DISTS) into Projects for Cash Based Acctng
4438 
4439             UPDATE ap_payment_hist_dists dist
4440             SET    dist.pa_addition_flag = 'G',
4441                    request_id = G_REQUEST_ID,
4442                    last_update_date=SYSDATE,
4443                    last_updated_by= G_USER_ID,
4444                    last_update_login= G_USER_ID,
4445                    program_id= G_PROG_ID,
4446                    program_application_id= G_PROG_APPL_ID,
4447                    program_update_date=SYSDATE
4448             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
4449             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
4450             AND EXISTS (SELECT NULL
4451                         FROM   ap_payment_history_all hist
4452                         WHERE  hist.payment_history_id = dist.payment_history_id
4453                         AND    hist.posted_flag = 'Y')
4454             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
4455                            FROM AP_INVOICES_ALL inv,
4456                                 AP_Invoice_Distributions_all aid,
4457                                 ap_invoice_payments_all aip
4458                           WHERE inv.invoice_id = aip.invoice_id
4459                             AND aid.invoice_id = inv.invoice_id
4460                             AND aip.invoice_payment_id = dist.invoice_payment_id
4461                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
4462                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'         --Prevent prepayment payments from being transferred to Projects
4463                             AND aid.project_id = G_PROJECT_ID
4464                             AND aid.invoice_id = aip.invoice_id
4465                             AND inv.org_id = G_ORG_ID
4466                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
4467                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
4468 
4469         If g_body_debug_mode = 'Y' Then
4470           write_log(LOG, 'Number of Discount prepayments  marked to G: ' || to_char(SQL%ROWCOUNT));
4471           write_log(LOG, 'cash basis: ' || G_ACCTNG_METHOD);
4472           write_log(LOG, 'cash basis2: ' || to_char(G_Profile_Discount_Start_date,'DD-MON-RR'));
4473         End If;
4474 
4475           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
4476 
4477             UPDATE ap_payment_hist_dists dist
4478             SET    dist.pa_addition_flag = 'O',
4479                    request_id = G_REQUEST_ID,
4480                    last_update_date=SYSDATE,
4481                    last_updated_by= G_USER_ID,
4482                    last_update_login= G_USER_ID,
4483                    program_id= G_PROG_ID,
4484                    program_application_id= G_PROG_APPL_ID,
4485                    program_update_date=SYSDATE
4486             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
4487             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
4488             AND EXISTS (SELECT NULL
4489                         FROM   ap_payment_history_all hist
4490                         WHERE  hist.payment_history_id = dist.payment_history_id
4491                         AND    hist.posted_flag = 'Y')
4492             AND   exists(SELECT/*+ no_unnest */  inv.invoice_id
4493                            FROM AP_INVOICES_ALL inv,
4494                                 PO_Distributions_all PO,
4495                                 AP_Invoice_Distributions_all aid,
4496                                 ap_invoice_payments_all aip
4497                           WHERE inv.invoice_id = aip.invoice_id
4498                             AND aid.invoice_id = inv.invoice_id
4499                             AND aip.invoice_payment_id = dist.invoice_payment_id
4500                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
4501                             AND aid.po_distribution_id = PO.po_distribution_id (+)
4502                             AND aid.line_type_lookup_code not in ('TERV', 'REC_TAX') -- Bug#5441030 to avoid zero dollar lines for TERV
4503                             AND inv.org_id = G_ORG_ID
4504                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
4505                             AND inv.paid_on_behalf_employee_id IS NULL
4506                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
4507                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
4508                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
4509                             AND aid.project_id = G_PROJECT_ID
4510                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
4511                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
4512                             AND ( (aid.expenditure_item_date  >=G_Profile_Discount_Start_date
4513                                  AND G_ACCTNG_METHOD = 'A'
4514                                  AND G_discount_Method IN ('TAX','EXPENSE'))
4515                                 OR --CAsh basis
4516                                 (( (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  < G_Profile_Discount_Start_date
4517                                     AND nvl(aid.pa_addition_flag,'N') <> 'Y') ---bug 5516855
4518                                    OR (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  >=  G_Profile_Discount_Start_date
4519                                     AND aid.pa_addition_flag = 'Y')  --bug 5516855 Added to allow disounts interface for historical data
4520                                    OR (G_discount_Method = 'TAX' AND AID.line_type_lookup_code <> 'NONREC_TAX'
4521                                         AND aid.expenditure_item_date  >=G_Profile_Discount_Start_date )  --Bug#5189187
4522                                    OR G_Discount_Method = 'SYSTEM') AND G_ACCTNG_METHOD = 'C')
4523                                 ) --See bug#4941454 for logic
4524                            );
4525 
4526 
4527       G_DISC_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
4528       write_log(LOG, 'Number of Discount rows marked to O: ' || to_char(SQL%ROWCOUNT));
4529 
4530      ELSE -- G_PRoject_id is null
4531 
4532           -- Mark all Discount lines associated with PREPAYMENT payment to G to prevent interface into Projects
4533           -- In Rel12, we will only bring in Prepayment application lines (AP_PREPAY_APP_DISTS) into Projects for Cash Based Acctng
4534 
4535             UPDATE ap_payment_hist_dists dist
4536             SET    dist.pa_addition_flag = 'G',
4537                    request_id = G_REQUEST_ID,
4538                    last_update_date=SYSDATE,
4539                    last_updated_by= G_USER_ID,
4540                    last_update_login= G_USER_ID,
4541                    program_id= G_PROG_ID,
4542                    program_application_id= G_PROG_APPL_ID,
4543                    program_update_date=SYSDATE
4544             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
4545             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
4546             AND EXISTS (SELECT NULL
4547                         FROM   ap_payment_history_all hist
4548                         WHERE  hist.payment_history_id = dist.payment_history_id
4549                         AND    hist.posted_flag = 'Y')
4550             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
4551                            FROM AP_INVOICES_ALL inv,
4552                                 AP_Invoice_Distributions_all aid,
4553                                 ap_invoice_payments_all aip
4554                           WHERE inv.invoice_id = aip.invoice_id
4555                             AND aid.invoice_id = inv.invoice_id
4556                             AND aip.invoice_payment_id = dist.invoice_payment_id
4557                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
4558                             AND inv.org_id = G_ORG_ID
4559                             AND inv.invoice_type_lookup_code = 'PREPAYMENT'         --Prevent prepayment payments from being transferred to Projects
4560                             AND aid.project_id > 0
4561                             AND aid.invoice_id = aip.invoice_id
4562                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
4563                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
4564 
4565           write_log(LOG, 'Number of Discount prepayments  marked to G: ' || to_char(SQL%ROWCOUNT));
4566 
4567           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
4568 
4569             UPDATE ap_payment_hist_dists dist
4570             SET    dist.pa_addition_flag = 'O',
4571                    request_id = G_REQUEST_ID,
4572                    last_update_date=SYSDATE,
4573                    last_updated_by= G_USER_ID,
4574                    last_update_login= G_USER_ID,
4575                    program_id= G_PROG_ID,
4576                    program_application_id= G_PROG_APPL_ID,
4577                    program_update_date=SYSDATE
4578             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
4579             AND   dist.pay_dist_lookup_code = 'DISCOUNT'
4580             AND EXISTS (SELECT NULL
4581                         FROM   ap_payment_history_all hist
4582                         WHERE  hist.payment_history_id = dist.payment_history_id
4583                         AND    hist.posted_flag = 'Y')
4584             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
4585                            FROM AP_INVOICES_ALL inv,
4586                                 PO_Distributions_all PO,
4587                                 AP_Invoice_Distributions_all aid,
4588                                 ap_invoice_payments_all aip
4589                           WHERE inv.invoice_id = aip.invoice_id
4590                             AND aid.invoice_id = inv.invoice_id
4591                             AND aip.invoice_payment_id = dist.invoice_payment_id
4592                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
4593                             AND inv.org_id = G_ORG_ID
4594                             AND aid.po_distribution_id = PO.po_distribution_id (+)
4595                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
4596                             AND inv.paid_on_behalf_employee_id IS NULL
4597                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
4598                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
4599                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
4600                             AND aid.project_id > 0
4601                             AND aid.line_type_lookup_code not in ('TERV', 'REC_TAX') -- Bug#5441030 to avoid zero dollar lines for TERV
4602                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
4603                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
4604                             AND ( (aid.expenditure_item_date  >=G_Profile_Discount_Start_date
4605                                  AND G_ACCTNG_METHOD = 'A'
4606                                  AND G_discount_Method IN ('TAX','EXPENSE'))
4607                                 OR --CAsh basis
4608                                 (( (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  < G_Profile_Discount_Start_date
4609                                     AND nvl(aid.pa_addition_flag,'N') <> 'Y') ---bug 5516855
4610                                    OR (G_discount_Method IN ('TAX','EXPENSE') AND aid.expenditure_item_date  >=  G_Profile_Discount_Start_date
4611                                     AND aid.pa_addition_flag = 'Y')  --bug 5516855 Added to allow disounts interface for historical data
4612                                    OR (G_discount_Method = 'TAX' AND AID.line_type_lookup_code <> 'NONREC_TAX'
4613                                         AND aid.expenditure_item_date  >=G_Profile_Discount_Start_date )  --Bug#5189187
4614                                    OR G_Discount_Method = 'SYSTEM') AND G_ACCTNG_METHOD = 'C')
4615                                 ) --See bug#4941454 for logic
4616                            );
4617 
4618       G_DISC_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
4619       write_log(LOG, 'Number of Discount rows marked to O: ' || to_char(SQL%ROWCOUNT));
4620 
4621       END IF;  -- End of If section checking if G_PROJECT_ID is not null
4622 
4623       --
4624       G_err_stack := v_old_stack;
4625 
4626 EXCEPTION
4627      WHEN Others THEN
4628            -- Marking phase failed, raise exception to main program to terminate the program
4629            --
4630            G_err_stack := v_old_stack;
4631            G_err_code := SQLCODE;
4632            RAISE;
4633 
4634 END mark_PA_disc_flag_O;
4635 
4636 /*-------------------------------------*/
4637 
4638 PROCEDURE transfer_disc_to_pa IS
4639 
4640    v_old_stack                     VARCHAR2(630);
4641    v_err_message                   VARCHAR2(220);
4642    v_all_done                      NUMBER := 0;
4643    v_status                        VARCHAR2(30);
4644    v_stage                         Number :=0;
4645    v_max_size                      NUMBER :=0;
4646 
4647    v_num_discounts_fetched         NUMBER :=0;
4648    v_num_payments_fetched          NUMBER :=0;
4649 
4650    v_method                        VARCHAR(15);
4651    v_prev_inv_pay_id               NUMBER:=0;
4652 
4653    v_disc_code_combination_id      NUMBER(15);
4654    v_denom_raw_cost                NUMBER :=0;
4655    v_acct_raw_cost                 NUMBER :=0;
4656    v_denom_currency_code           VARCHAR2(30);
4657    v_acct_rate_type                VARCHAR2(30);
4658    v_acct_rate_date                DATE;
4659    v_acct_exchange_rate            NUMBER(15);
4660    v_last_disc_index               NUMBER := 0;
4661 
4662    v_attribute_category VARCHAR2(150);
4663    v_attribute1 VARCHAR2(150);
4664    v_attribute2 VARCHAR2(150);
4665    v_attribute3 VARCHAR2(150);
4666    v_attribute4 VARCHAR2(150);
4667    v_attribute5 VARCHAR2(150);
4668    v_attribute6 VARCHAR2(150);
4669    v_attribute7 VARCHAR2(150);
4670    v_attribute8 VARCHAR2(150);
4671    v_attribute9 VARCHAR2(150);
4672    v_attribute10 VARCHAR2(150);
4673    v_dff_map_status VARCHAR2(30);
4674    dff_map_exception EXCEPTION;
4675    l_create_adj_recs     VARCHAR2(1) := 'N' ;-- NEW
4676    l_ap_inv_disc_flag    VARCHAR2(1):= 'N'; -- Flag to indicate Discounts exist for ITEM lines in Cash Basis flow.
4677    l_ap_nrt_disc_flag    VARCHAR2(1):= 'N'; -- Flag to indicate Discounts exist for NRTAX lines in Cash Basis flow.
4678    l_ap_hist_disc_flag    VARCHAR2(1):= 'N'; -- Flag to indicate Discounts exist for historicqal inv lines in Cash Basis flow.
4679 
4680    PROCEDURE clear_plsql_tables IS
4681 
4682        l_status1 VARCHAR2(30);
4683 
4684    BEGIN
4685 
4686        l_inv_pay_id_tbl.delete;
4687        l_invoice_id_tbl.delete;
4688        l_invoice_dist_id_tbl.delete;
4689        l_project_id_tbl.delete;
4690        l_task_id_tbl.delete;
4691        l_employee_id_tbl.delete;
4692        l_exp_type_tbl.delete;
4693        l_ei_date_tbl.delete;
4694        l_vendor_id_tbl.delete;
4695        l_created_by_tbl.delete;
4696        l_exp_org_id_tbl.delete;
4697        l_quantity_tbl.delete;
4698        l_job_id_tbl.delete;
4699        l_description_tbl.delete;
4700        l_dist_cc_id_tbl.delete;
4701        l_acct_pay_cc_id_tbl.delete;
4702        l_gl_date_tbl.delete;
4703        l_attribute_cat_tbl.delete;
4704        l_attribute1_tbl.delete;
4705        l_attribute2_tbl.delete;
4706        l_attribute3_tbl.delete;
4707        l_attribute4_tbl.delete;
4708        l_attribute5_tbl.delete;
4709        l_attribute6_tbl.delete;
4710        l_attribute7_tbl.delete;
4711        l_attribute8_tbl.delete;
4712        l_attribute9_tbl.delete;
4713        l_attribute10_tbl.delete;
4714        l_inv_type_code_tbl.delete;
4715        l_org_id_tbl.delete;
4716        l_invoice_num_tbl.delete;
4717        l_ln_type_lookup_tbl.delete;
4718        l_source_tbl.delete;
4719        l_denom_raw_cost_tbl.delete;
4720        l_amount_tbl.delete;
4721        l_denom_cur_code_tbl.delete;
4722        l_acct_rate_date_tbl.delete;
4723        l_acct_rate_type_tbl.delete;
4724        l_acct_exch_rate_tbl.delete;
4725        l_cdl_sys_ref4_tbl.delete;
4726        l_cdl_sys_ref3_tbl.delete;
4727        l_txn_src_tbl.delete;
4728        l_user_txn_src_tbl.delete;
4729        l_batch_name_tbl.delete;
4730        l_interface_id_tbl.delete;
4731        l_exp_end_date_tbl.delete;
4732        l_txn_status_code_tbl.delete;
4733        l_txn_rej_code_tbl.delete;
4734        l_bus_grp_id_tbl.delete;
4735        l_reversal_flag_tbl.delete; --NEW
4736        l_net_zero_flag_tbl.delete; --NEW
4737        l_sc_xfer_code_tbl.delete; --NEW
4738        l_parent_pmt_id_tbl.delete; --NEW
4739        l_fc_enabled_tbl.delete; --NEW
4740        l_rev_parent_dist_id_tbl.delete;
4741        l_rev_child_dist_id_tbl.delete;
4742        l_rev_parent_dist_ind_tbl.delete;
4743        l_si_assts_add_flg_tbl.delete;
4744        l_pay_hist_id_tbl.delete;
4745        l_pa_add_flag_tbl.delete;
4746        l_rev_index:=0;
4747 
4748     END clear_plsql_tables;
4749 
4750     PROCEDURE bulk_insert_trx_intf IS
4751 
4752       l_status2 VARCHAR2(30);
4753 
4754     BEGIN
4755 
4756        --FORALL i IN l_inv_pay_id_tbl.FIRST..l_inv_pay_id_tbl.LAST
4757        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
4758 
4759        INSERT INTO pa_transaction_interface_all(
4760                      transaction_source
4761                     , user_transaction_source
4762                     , system_linkage
4763                     , batch_name
4764                     , expenditure_ending_date
4765                     , expenditure_item_date
4766                     , expenditure_type
4767                     , quantity
4768                     , raw_cost_rate
4769                     , expenditure_comment
4770                     , transaction_status_code
4771                     , transaction_rejection_code
4772                     , orig_transaction_reference
4773                     , interface_id
4774                     , dr_code_combination_id
4775                     , cr_code_combination_id
4776                     , cdl_system_reference1
4777                     , cdl_system_reference2
4778                     , cdl_system_reference3
4779                     , cdl_system_reference4
4780                     , cdl_system_reference5 --NEW
4781                     , gl_date
4782                     , org_id
4783                     , unmatched_negative_txn_flag
4784                     , denom_raw_cost
4785                     , denom_currency_code
4786                     , acct_rate_date
4787                     , acct_rate_type
4788                     , acct_exchange_rate
4789                     , acct_raw_cost
4790                     , acct_exchange_rounding_limit
4791                     , attribute_category
4792                     , attribute1
4793                     , attribute2
4794                     , attribute3
4795                     , attribute4
4796                     , attribute5
4797                     , attribute6
4798                     , attribute7
4799                     , attribute8
4800                     , attribute9
4801                     , attribute10
4802                     , orig_exp_txn_reference1
4803                     , orig_user_exp_txn_reference
4804                     , orig_exp_txn_reference2
4805                     , orig_exp_txn_reference3
4806                     , last_update_date
4807                     , last_updated_by
4808                     , creation_date
4809                     , created_by
4810                     , person_id
4811                     , organization_id
4812                     , project_id
4813                     , task_id
4814                     , Vendor_id
4815                     , override_to_organization_id
4816                     , person_business_group_id
4817                     , adjusted_expenditure_item_id
4818                     , fc_document_type
4819                     , document_type
4820                     , document_distribution_type
4821                     , si_assets_addition_flag
4822                     , sc_xfer_code
4823                     ,net_zero_adjustment_flag
4824                    )
4825              SELECT   l_txn_src_tbl(i)
4826                      ,l_user_txn_src_tbl(i)
4827                      ,G_SYSTEM_LINKAGE
4828                      ,l_batch_name_tbl(i)
4829                      ,l_exp_end_date_tbl(i)
4830                      ,l_ei_date_tbl(i)
4831                      ,l_exp_type_tbl(i)
4832                      ,l_quantity_tbl(i)
4833                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
4834                      ,l_description_tbl(i)
4835                      ,l_txn_status_code_tbl(i)
4836                      ,l_txn_rej_code_tbl(i)
4837                      ,G_REQUEST_ID
4838                      ,l_interface_id_tbl(i)
4839                      ,l_dist_cc_id_tbl(i)
4840                      ,l_acct_pay_cc_id_tbl(i)
4841                      ,l_pay_hist_id_tbl(i) --cdl_ref1
4842                      ,l_invoice_id_tbl(i)
4843                      ,l_cdl_sys_ref3_tbl(i)
4844                      ,l_inv_pay_id_tbl(i)
4845                      ,l_invoice_dist_id_tbl(i) --NEW
4846                      ,l_gl_date_tbl(i)
4847                      ,G_ORG_ID
4848                      ,'Y'
4849                      ,l_denom_raw_cost_tbl(i)
4850                      ,l_denom_cur_code_tbl(i)
4851                      ,l_acct_rate_date_tbl(i)
4852                      ,l_acct_rate_type_tbl(i)
4853                      ,l_acct_exch_rate_tbl(i)
4854                      ,l_amount_tbl(i)
4855                      ,1
4856                      ,l_attribute_cat_tbl(i)
4857                      ,l_attribute1_tbl(i)
4858                      ,l_attribute2_tbl(i)
4859                      ,l_attribute3_tbl(i)
4860                      ,l_attribute4_tbl(i)
4861                      ,l_attribute5_tbl(i)
4862                      ,l_attribute6_tbl(i)
4863                      ,l_attribute7_tbl(i)
4864                      ,l_attribute8_tbl(i)
4865                      ,l_attribute9_tbl(i)
4866                      ,l_attribute10_tbl(i)
4867                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
4868                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
4869                      ,NULL                       /*orig_exp_txn_reference2*/
4870                      ,NULL                       /*orig_exp_txn_reference3*/
4871                      ,SYSDATE
4872                      ,-1
4873                      ,SYSDATE
4874                      ,-1
4875                      ,l_employee_id_tbl(i)
4876                      ,l_org_id_tbl(i)
4877                      ,l_project_id_tbl(i)
4878                      ,l_task_id_tbl(i)
4879                      ,l_vendor_id_tbl(i)
4880                      ,l_exp_org_id_tbl(i)
4881                      ,l_bus_grp_id_tbl(i)
4882                      ,l_adj_exp_item_id_tbl(i)
4883                      ,l_fc_document_type_tbl(i)
4884                      ,l_inv_type_code_tbl(i)
4885                      ,l_ln_type_lookup_tbl(i)
4886                      ,l_si_assts_add_flg_tbl(i)
4887                      ,l_sc_xfer_code_tbl(i)
4888                      ,l_net_zero_flag_tbl(i)
4889                   FROM dual;
4890 
4891               -- Insert the reversal of the reversed/cancelled distribution recs from AP.
4892     IF l_create_adj_recs = 'Y' THEN
4893 
4894                 write_log(LOG, 'Inserting adjustment records..');
4895        --FORALL i IN l_inv_pay_id_tbl.FIRST..l_inv_pay_id_tbl.LAST
4896        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
4897 
4898        INSERT INTO pa_transaction_interface_all(
4899                      transaction_source
4900                     , user_transaction_source
4901                     , system_linkage
4902                     , batch_name
4903                     , expenditure_ending_date
4904                     , expenditure_item_date
4905                     , expenditure_type
4906                     , quantity
4907                     , raw_cost_rate
4908                     , expenditure_comment
4909                     , transaction_status_code
4910                     , transaction_rejection_code
4911                     , orig_transaction_reference
4912                     , interface_id
4913                     , dr_code_combination_id
4914                     , cr_code_combination_id
4915                     , cdl_system_reference1
4916                     , cdl_system_reference2
4917                     , cdl_system_reference3
4918                     , cdl_system_reference4
4919                     , cdl_system_reference5 --NEW
4920                     , gl_date
4921                     , org_id
4922                     , unmatched_negative_txn_flag
4923                     , denom_raw_cost
4924                     , denom_currency_code
4925                     , acct_rate_date
4926                     , acct_rate_type
4927                     , acct_exchange_rate
4928                     , acct_raw_cost
4929                     , acct_exchange_rounding_limit
4930                     , attribute_category
4931                     , attribute1
4932                     , attribute2
4933                     , attribute3
4934                     , attribute4
4935                     , attribute5
4936                     , attribute6
4937                     , attribute7
4938                     , attribute8
4939                     , attribute9
4940                     , attribute10
4941                     , orig_exp_txn_reference1
4942                     , orig_user_exp_txn_reference
4943                     , orig_exp_txn_reference2
4944                     , orig_exp_txn_reference3
4945                     , last_update_date
4946                     , last_updated_by
4947                     , creation_date
4948                     , created_by
4949                     , person_id
4950                     , organization_id
4951                     , project_id
4952                     , task_id
4953                     , Vendor_id
4954                     , override_to_organization_id
4955                     , person_business_group_id
4956                     , adjusted_expenditure_item_id
4957                     , fc_document_type
4958                     , document_type
4959                     , document_distribution_type
4960                     , si_assets_addition_flag
4961                     , adjusted_txn_interface_id
4962                     , sc_xfer_code
4963                     ,net_zero_adjustment_flag
4964                    )
4965              SELECT   l_txn_src_tbl(i)
4966                      ,l_user_txn_src_tbl(i)
4967                      ,G_SYSTEM_LINKAGE
4968                      ,l_batch_name_tbl(i)
4969                      ,l_exp_end_date_tbl(i)
4970                      ,l_ei_date_tbl(i)
4971                      ,l_exp_type_tbl(i)
4972                      ,-l_quantity_tbl(i)
4973                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
4974                      ,l_description_tbl(i)
4975                      ,l_txn_status_code_tbl(i)
4976                      ,l_txn_rej_code_tbl(i)
4977                      ,G_REQUEST_ID
4978                      ,l_interface_id_tbl(i)
4979                      ,l_dist_cc_id_tbl(i)
4980                      ,l_acct_pay_cc_id_tbl(i)
4981                      ,l_pay_hist_id_tbl(i) --cdl_ref1
4982                      ,l_invoice_id_tbl(i)
4983                      ,l_cdl_sys_ref3_tbl(i)
4984                      ,l_inv_pay_id_tbl(i)
4985                      ,l_invoice_dist_id_tbl(i)
4986                      ,l_gl_date_tbl(i)
4987                      ,G_ORG_ID
4988                      ,'Y'
4989                      ,-l_denom_raw_cost_tbl(i)
4990                      ,l_denom_cur_code_tbl(i)
4991                      ,l_acct_rate_date_tbl(i)
4992                      ,l_acct_rate_type_tbl(i)
4993                      ,l_acct_exch_rate_tbl(i)
4994                      ,-l_amount_tbl(i)
4995                      ,1
4996                      ,l_attribute_cat_tbl(i)
4997                      ,l_attribute1_tbl(i)
4998                      ,l_attribute2_tbl(i)
4999                      ,l_attribute3_tbl(i)
5000                      ,l_attribute4_tbl(i)
5001                      ,l_attribute5_tbl(i)
5002                      ,l_attribute6_tbl(i)
5003                      ,l_attribute7_tbl(i)
5004                      ,l_attribute8_tbl(i)
5005                      ,l_attribute9_tbl(i)
5006                      ,l_attribute10_tbl(i)
5007                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
5008                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
5009                      ,NULL                       /*orig_exp_txn_reference2*/
5010                      ,NULL                       /*orig_exp_txn_reference3*/
5011                      ,SYSDATE
5012                      ,-1
5013                      ,SYSDATE
5014                      ,-1
5015                      ,l_employee_id_tbl(i)
5016                      ,l_org_id_tbl(i)
5017                      ,l_project_id_tbl(i)
5018                      ,l_task_id_tbl(i)
5019                      ,l_vendor_id_tbl(i)
5020                      ,l_exp_org_id_tbl(i)
5021                      ,l_bus_grp_id_tbl(i)
5022                      ,l_adj_exp_item_id_tbl(i)
5023                      ,l_fc_document_type_tbl(i)
5024                      ,l_inv_type_code_tbl(i)
5025                      ,l_ln_type_lookup_tbl(i)
5026                      , 'T' --l_si_assts_add_flg_tbl(i)
5027                      ,(select xface.txn_interface_id
5028                        from   pa_transaction_interface xface
5029                        where  xface.interface_id = l_interface_id_tbl(i)
5030                        and    xface.cdl_system_reference2 = l_invoice_id_tbl(i)
5031                        and    xface.cdl_system_reference4 = to_char(l_inv_pay_id_tbl(i))
5032                        and    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(i)
5033 		       and    NVL(xface.adjusted_expenditure_item_id,0) = 0 ) -- R12 funds management Uptake
5034                      ,'P' -- sc_xfer_code
5035                      ,l_net_zero_flag_tbl(i)
5036                    FROM dual
5037                    WHERE l_insert_flag_tbl(i)= 'A';
5038                   --WHERE l_net_zero_flag_tbl(i)= 'Y';
5039 
5040                -- Handle both the parent and the reversal getting interfaced into PA
5041                -- in the same run.
5042                 write_log(LOG, 'Updating  adjustment records..');
5043 
5044               IF l_rev_child_dist_id_tbl.exists(1) THEN
5045                FOR i in l_rev_child_dist_id_tbl.FIRST ..l_rev_child_dist_id_tbl.LAST LOOP
5046 
5047                    IF l_rev_child_dist_id_tbl(i) > 0 THEN
5048 
5049                     UPDATE pa_transaction_interface_all xface
5050                     SET    xface.net_zero_adjustment_flag ='Y',
5051                            xface.adjusted_txn_interface_id =
5052                               (select xface1.txn_interface_id
5053                                from   pa_transaction_interface xface1
5054                                where  xface1.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
5055                                and    xface1.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
5056                                and    xface1.cdl_system_reference4 = to_char(l_inv_pay_id_tbl(l_rev_parent_dist_ind_tbl(i)))
5057                                and    xface1.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
5058                                )
5059                       WHERE  xface.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
5060                       AND    xface.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
5061                       --AND    xface.cdl_system_reference4 = to_char(l_rev_child_dist_id_tbl(i))
5062                       -- AND    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i));
5063                       AND    -- For voided payments l_rev_child_dist_id_tbl stores the reversed payment id Bug# 5408748
5064                              -- Here the reversal pair will have same inv dist id and diff payment id's
5065                              ((
5066                              xface.cdl_system_reference4     = To_char(l_rev_child_dist_id_tbl(i))
5067                              AND xface.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
5068                              )
5069                       OR     -- For invoice reversal l_rev_child_dist_id_tbl stores the reversed invoice dist id Bug# 5408748
5070                              -- Here the reversal pair will have same payment id and diff inv dist id's
5071                              (
5072                              xface.cdl_system_reference4     = to_char(l_inv_pay_id_tbl(l_rev_parent_dist_ind_tbl(i)))
5073                              AND xface.cdl_system_reference5 = To_char(l_rev_child_dist_id_tbl(i))
5074                              )) ;
5075                     END IF;
5076 
5077               END LOOP;
5078              END IF;
5079     END IF;
5080 
5081    EXCEPTION
5082       WHEN OTHERS THEN
5083           write_log(LOG,'Failed during bulk insert for discount processing');
5084           G_err_code   := SQLCODE;
5085           write_log(LOG, 'Error Code is '||SQLCODE);
5086           write_log(LOG, substr(SQLERRM, 1, 200));
5087           write_log(LOG, substr(SQLERRM, 201, 200));
5088           raise;
5089 
5090    END bulk_insert_trx_intf;
5091 
5092    PROCEDURE process_disc_logic IS
5093 
5094        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
5095        l_status3 VARCHAR2(30);
5096        L_PP_REJECT_FLAG VARCHAR2(1); --Bug 3664528
5097 
5098    BEGIN
5099 
5100 
5101        j :=  v_last_disc_index ;
5102        FOR i IN  l_inv_pay_id_tbl.FIRST..l_inv_pay_id_tbl.LAST  LOOP
5103 
5104          write_log(LOG,'getting discount attributes for inv_pay_id:'||l_inv_pay_id_tbl(i)
5105                       ||'invoice_id:'||l_invoice_id_tbl(i)
5106                       ||'Invoice dist id:'||l_invoice_dist_id_tbl(i));
5107 
5108            l_quantity_tbl(i)       := l_denom_raw_cost_tbl(i);
5109            l_cdl_sys_ref4_tbl(i)   := l_inv_pay_id_tbl(i);
5110 
5111 
5112            G_TRANSACTION_REJECTION_CODE := '';
5113            G_TRANSACTION_STATUS_CODE := 'P';
5114 
5115            /* For CAsh Basis we process Discounts as SUpplier Invoice */
5116            IF G_ACCTNG_METHOD = 'C' and nvl(l_pa_add_flag_tbl(i),'N') <> 'Y' THEN --Bug# 5516855
5117              -- Added the pa-addition-flag logic for bug 5516855 so that discounts on historical records, that are interfaced as
5118              -- inv dist and have pa-addition-flag as Y , are interfaced as DISCOUNTS source and negitive amount
5119 
5120 
5121              --Added this logic for bug#5122922.
5122 
5123            IF l_ln_type_lookup_tbl(i)  = 'NONREC_TAX' THEN
5124              G_DISC_TRANSACTION_SOURCE      := 'AP NRTAX';
5125              G_DISC_USER_TRANSACTION_SOURCE := 'AP NRTAX';
5126              l_ap_nrt_disc_flag  :='Y';
5127            ELSE
5128              G_DISC_TRANSACTION_SOURCE      := 'AP INVOICE' ;
5129              G_DISC_USER_TRANSACTION_SOURCE := 'AP INVOICE';
5130              l_ap_inv_disc_flag  :='Y';
5131            END IF;
5132 
5133 
5134            ELSE
5135              IF G_ACCTNG_METHOD = 'C' THEN   --To process discounts against historical inv in rel12 in cash env Bug# 5516855
5136                l_ap_hist_disc_flag  :='Y';
5137              END IF;
5138 
5139              G_DISC_TRANSACTION_SOURCE      := 'AP DISCOUNTS' ;
5140              G_DISC_USER_TRANSACTION_SOURCE := 'Supplier Invoice Discounts from Payables';
5141 
5142              l_denom_raw_cost_tbl(i) := -l_denom_raw_cost_tbl(i);   -- for Discounts, amount is interfaced as negitive amount
5143              l_amount_tbl(i)         := -l_amount_tbl(i);
5144              l_quantity_tbl(i)       := -l_quantity_tbl(i);
5145 
5146            END IF;
5147 
5148            /* The following will be executed if discount being fetched belongs to a new payment */
5149            IF (l_inv_pay_id_tbl(i) <> v_prev_inv_pay_id) THEN
5150 
5151                write_log(LOG,'New payment processed. inv_pay_id is:'||l_inv_pay_id_tbl(i));
5152 
5153                /* Update the previous invoice payment id*/
5154                v_prev_inv_pay_id := l_inv_pay_id_tbl(i);
5155 
5156                /* Increment the counter for invoices */
5157                v_num_payments_fetched := v_num_payments_fetched + 1;
5158 
5159                /* For new invoice, initialize the transaction status code to 'P' */
5160                L_PP_REJECT_FLAG := 'N';
5161 
5162                G_err_stage := 'GET MAX EXPENDITURE ENDING DATE';
5163                write_log(LOG, G_err_stage);
5164 /* Bug 5051103 - replace expnediture_item_date with l_ei_date_tbl(i) */
5165                SELECT pa_utils.getweekending(MAX(l_ei_date_tbl(i)))
5166                  INTO G_EXPENDITURE_ENDING_DATE
5167                  FROM ap_invoice_distributions
5168                 WHERE invoice_id = l_invoice_id_tbl(i);
5169 
5170                G_err_stage := ('Before getting business group id');
5171                write_log(LOG, G_err_stage);
5172 
5173                BEGIN
5174 
5175                   IF l_employee_id_tbl(i) <> 0 THEN
5176 			Begin
5177 			     SELECT emp.business_group_id
5178                                INTO G_PER_BUS_GRP_ID
5179 			       FROM per_all_people_f emp
5180 			      WHERE emp.person_id = l_employee_id_tbl(i)
5181 				  AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and
5182 							       trunc(emp.effective_end_date);
5183 
5184 		       EXCEPTION
5185 			  WHEN NO_DATA_FOUND THEN
5186                              L_PP_REJECT_FLAG := 'Y' ;
5187 			     G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
5188 			     write_log(LOG, 'no data found for Employee, Rejecting invoice'||l_invoice_id_tbl(i)  );
5189 			End;
5190                     Else
5191                         Begin
5192 
5193                             select org2.business_group_id
5194                               into G_PER_BUS_GRP_ID
5195                               from hr_organization_units org1,
5196                                    hr_organization_units org2
5197                              Where org1.organization_id = l_exp_org_id_tbl(i)
5198                                and org1.business_group_id = org2.organization_id;
5199 
5200                         EXCEPTION
5201                                 WHEN NO_DATA_FOUND THEN
5202                                       L_PP_REJECT_FLAG := 'Y' ;
5203                                       G_TRANSACTION_REJECTION_CODE := 'INVALID_ORGANIZATION';
5204                                       write_log(LOG, 'As no data found for Organization, Rejecting discount invoice ' || l_invoice_id_tbl(i) );
5205                         End;
5206                   END IF; /* IF l_employee_id_tbl(i) <> 0 THEN  */
5207 
5208                END;
5209 
5210            END IF; /* end of check for new invoice_payment_id*/
5211 
5212            v_num_discounts_fetched := v_num_discounts_fetched + 1;
5213            write_log(LOG,'Num of discount lines fetched:'||v_num_discounts_fetched);
5214 
5215           IF L_PP_REJECT_FLAG = 'Y' THEN --Bug 3664528 : Reject all the distributions within prepayment --???????
5216              G_TRANSACTION_STATUS_CODE := 'R';
5217           END IF;
5218 
5219            /*Setting values according to global variables*/
5220 
5221 
5222            l_txn_src_tbl(i)         := G_DISC_TRANSACTION_SOURCE;
5223            l_user_txn_src_tbl(i)    := G_DISC_USER_TRANSACTION_SOURCE;
5224            l_batch_name_tbl(i)      := G_DISC_BATCH_NAME;
5225            l_interface_id_tbl(i)    := G_DISC_INTERFACE_ID;
5226            l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
5227            l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
5228            l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
5229            l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
5230 
5231          -- This logic is to handle both the parent and reversal getting interfaced in the same run.
5232           -- It's a reversed parent record. Bug#4590527
5233           -- If both the parent and child reversing each other are interfaced in the same run, they
5234           -- were not getting interfaced as netzero transactions.
5235 
5236            IF (l_reversal_flag_tbl(i) in ('Y','R') or l_cancel_flag_tbl(i) = 'Y')
5237                                  AND l_parent_pmt_id_tbl(i) IS NULL THEN
5238 
5239               l_rev_index := l_rev_index +1;
5240               IF l_reversal_flag_tbl(i) = 'Y' THEN
5241                 write_log(LOG, 'Reversal parent record '||l_inv_pay_id_tbl(i));
5242                 l_rev_parent_dist_id_tbl(l_rev_index) :=  l_inv_pay_id_tbl(i);
5243               ELSE
5244 
5245                 -- The Reversal flag with value R indicates that the invoice distribution has been reversed
5246                 -- Refer to Bug#5408748
5247 
5248                 write_log(LOG, 'Reversal parent record for Invoice Dist reversals'||l_invoice_dist_id_tbl(i));
5249                 l_rev_parent_dist_id_tbl(l_rev_index) :=  l_invoice_dist_id_tbl(i);
5250               END IF;
5251 
5252               l_rev_child_dist_id_tbl(l_rev_index) :=  null;
5253               l_rev_parent_dist_ind_tbl(l_rev_index) :=  i; -- store the index of the parent.
5254 
5255            END IF;
5256 
5257            IF l_reversal_flag_tbl(i) in ('Y','R')  and l_parent_pmt_id_tbl(i) is not null THEN
5258 
5259                      -- Call reversal API
5260                      Process_Adjustments(p_record_type               => 'AP_DISCOUNTS',
5261                                          p_document_header_id        => l_invoice_id_tbl(i),/*Added this for 6945767 */
5262                                          p_document_distribution_id  => l_invoice_dist_id_tbl(i),
5263                                          p_document_payment_id       => l_parent_pmt_id_tbl(i),
5264                                          p_current_index             => i,
5265 					 p_last_index		     => j);
5266 
5267                       -- Set the create flag for adjustment records
5268                          IF l_insert_flag_tbl(i) in ('A','U') THEN
5269                           l_create_adj_recs := 'Y';
5270                          END IF;
5271 
5272 
5273           END IF; --End of check for reversal Distribution
5274 
5275            -- FC Doc Type
5276             IF l_fc_enabled_tbl(i) = 'N' THEN
5277              l_fc_document_type_tbl(i) := 'NOT';
5278             END IF;
5279 
5280            IF (G_TRANS_DFF_AP = 'Y') THEN
5281 
5282                 v_attribute_category := l_attribute_cat_tbl(i);
5283                 v_attribute1 := l_attribute1_tbl(i);
5284                 v_attribute2 := l_attribute2_tbl(i);
5285                 v_attribute3 := l_attribute3_tbl(i);
5286                 v_attribute4 := l_attribute4_tbl(i);
5287                 v_attribute5 := l_attribute5_tbl(i);
5288                 v_attribute6 := l_attribute6_tbl(i);
5289                 v_attribute7 := l_attribute7_tbl(i);
5290                 v_attribute8 := l_attribute8_tbl(i);
5291                 v_attribute9 := l_attribute9_tbl(i);
5292                 v_attribute10 := l_attribute10_tbl(i);
5293 
5294                 v_dff_map_status := NULL;
5295 
5296                 G_err_stage:='Calling DFF_map_segments_PA_and_AP for discounts';
5297                 write_log(LOG,   G_err_stage);
5298 
5299                 PA_CLIENT_EXTN_DFFTRANS.DFF_map_segments_PA_and_AP(
5300                    p_calling_module            => 'PAAPIMP',
5301                    p_trx_ref_1                 => l_invoice_id_tbl(i),
5302                    p_trx_ref_2                 => l_invoice_dist_id_tbl(i),
5303                    p_trx_type                  => l_inv_type_code_tbl(i),
5304                    p_system_linkage_function   => G_SYSTEM_LINKAGE,
5305                    p_submodule                 => l_source_tbl(i),
5306                    p_expenditure_type          => l_exp_type_tbl(i),
5307                    p_set_of_books_id           => G_AP_SOB,
5308                    p_org_id                    => l_org_id_tbl(i),
5309                    p_attribute_category        => v_attribute_category,
5310                    p_attribute_1               => v_attribute1,
5311                    p_attribute_2               => v_attribute2,
5312                    p_attribute_3               => v_attribute3,
5313                    p_attribute_4               => v_attribute4,
5314                    p_attribute_5               => v_attribute5,
5315                    p_attribute_6               => v_attribute6,
5316                    p_attribute_7               => v_attribute7,
5317                    p_attribute_8               => v_attribute8,
5318                    p_attribute_9               => v_attribute9,
5319                    p_attribute_10              => v_attribute10,
5320                    x_status_code               => v_dff_map_status);
5321 
5322                    IF (v_dff_map_status IS NOT NULL) THEN
5323 
5324                        G_err_stage:=('Error in DFF_map_segments_PA_and_AP, Error Code: ' || v_dff_map_status);
5325                        write_log(LOG,   G_err_stage);
5326                        raise dff_map_exception;
5327 
5328                    END IF;
5329 
5330                    l_attribute_cat_tbl(i) := v_attribute_category;
5331                    l_attribute1_tbl(i) := v_attribute1;
5332                    l_attribute2_tbl(i) := v_attribute2;
5333                    l_attribute3_tbl(i) := v_attribute3;
5334                    l_attribute4_tbl(i) := v_attribute4;
5335                    l_attribute5_tbl(i) := v_attribute5;
5336                    l_attribute6_tbl(i) := v_attribute6;
5337                    l_attribute7_tbl(i) := v_attribute7;
5338                    l_attribute8_tbl(i) := v_attribute8;
5339                    l_attribute9_tbl(i) := v_attribute9;
5340                    l_attribute10_tbl(i) := v_attribute10;
5341 
5342 	   ElSE /* if DFF profile is No. Added for Bug 3105153*/
5343                    l_attribute_cat_tbl(i) := NULL;
5344                    l_attribute1_tbl(i) := NULL;
5345                    l_attribute2_tbl(i) := NULL;
5346                    l_attribute3_tbl(i) := NULL;
5347                    l_attribute4_tbl(i) := NULL;
5348                    l_attribute5_tbl(i) := NULL;
5349                    l_attribute6_tbl(i) := NULL;
5350                    l_attribute7_tbl(i) := NULL;
5351                    l_attribute8_tbl(i) := NULL;
5352                    l_attribute9_tbl(i) := NULL;
5353                    l_attribute10_tbl(i) := NULL;
5354 
5355            END IF; /* if DFF profile is Yes */
5356 
5357       END LOOP; /* End of looping through each record in plsql table */
5358 
5359    EXCEPTION
5360       WHEN OTHERS THEN
5361           write_log(LOG,'Failed during process_disc_logic for discount processing');
5362           G_err_code   := SQLCODE;
5363           raise;
5364 
5365    END process_disc_logic;
5366 
5367    BEGIN
5368    /* Main Procedure Logic starts here */
5369 
5370    G_err_stage := 'Entering main processing logic of transfer_disc_to_pa';
5371    write_log(LOG,   G_err_stage);
5372 
5373      v_max_size := nvl(G_COMMIT_SIZE,200);
5374 
5375       G_err_stage:= 'Opening Discount_cour';
5376       write_log(LOG, G_err_stage);
5377 
5378       OPEN Discount_Cur;
5379 
5380       WHILE (v_all_done = 0) LOOP
5381 
5382           G_err_stage:='Discount Cursor is opened, looping through batches';
5383           write_log(LOG,   G_err_stage);
5384 
5385           clear_plsql_tables;
5386 
5387           G_err_stage := 'CREATING NEW INTERFACE ID';
5388           write_log(LOG, G_err_stage);
5389 
5390           SELECT pa_interface_id_s.nextval
5391             INTO G_DISC_INTERFACE_ID
5392             FROM dual;
5393 
5394           G_err_stage := 'Fetching Discount Cursor';
5395           write_log(LOG, G_err_stage);
5396 
5397           FETCH Discount_Cur BULK COLLECT INTO
5398               l_inv_pay_id_tbl
5399              ,l_invoice_id_tbl
5400              ,l_invoice_dist_id_tbl
5401              ,l_cdl_sys_ref3_tbl
5402              ,l_project_id_tbl
5403              ,l_task_id_tbl
5404              ,l_employee_id_tbl
5405              ,l_exp_type_tbl
5406              ,l_ei_date_tbl
5407              ,l_vendor_id_tbl
5408              ,l_created_by_tbl
5409              ,l_exp_org_id_tbl
5410              ,l_quantity_tbl
5411              ,l_job_id_tbl
5412              ,l_description_tbl
5413              ,l_dist_cc_id_tbl
5414              ,l_acct_pay_cc_id_tbl
5415              ,l_gl_date_tbl
5416              ,l_attribute_cat_tbl
5417              ,l_attribute1_tbl
5418              ,l_attribute2_tbl
5419              ,l_attribute3_tbl
5420              ,l_attribute4_tbl
5421              ,l_attribute5_tbl
5422              ,l_attribute6_tbl
5423              ,l_attribute7_tbl
5424              ,l_attribute8_tbl
5425              ,l_attribute9_tbl
5426              ,l_attribute10_tbl
5427              ,l_inv_type_code_tbl
5428              ,l_org_id_tbl
5429              ,l_invoice_num_tbl
5430              ,l_ln_type_lookup_tbl
5431              ,l_source_tbl
5432              ,l_denom_raw_cost_tbl
5433              ,l_amount_tbl
5434              ,l_denom_cur_code_tbl
5435              ,l_acct_rate_date_tbl
5436              ,l_acct_rate_type_tbl
5437              ,l_acct_exch_rate_tbl
5438              ,l_cdl_sys_ref4_tbl
5439              ,l_txn_src_tbl
5440              ,l_user_txn_src_tbl
5441              ,l_batch_name_tbl
5442              ,l_interface_id_tbl
5443              ,l_exp_end_date_tbl
5444              ,l_txn_status_code_tbl
5445              ,l_txn_rej_code_tbl
5446              ,l_bus_grp_id_tbl
5447              ,l_reversal_flag_tbl
5448              ,l_cancel_flag_tbl
5449              ,l_parent_pmt_id_tbl
5450              ,l_net_zero_flag_tbl
5451              ,l_sc_xfer_code_tbl
5452              ,l_adj_exp_item_id_tbl
5453              ,l_fc_enabled_tbl
5454              ,l_mrc_exchange_date_tbl
5455              ,l_fc_document_type_tbl
5456              ,l_si_assts_add_flg_tbl
5457              ,l_insert_flag_tbl
5458              ,l_pay_hist_id_tbl
5459              ,l_pa_add_flag_tbl
5460             LIMIT v_max_size;
5461 
5462          IF l_inv_pay_id_tbl.COUNT <> 0 THEN
5463 
5464             G_DISC_TRANSACTION_SOURCE      := 'AP DISCOUNTS' ;
5465             G_DISC_USER_TRANSACTION_SOURCE := 'Supplier Invoice Discounts From Payables';
5466 
5467             v_last_disc_index := l_invoice_id_tbl.LAST;
5468             G_err_stage := 'Calling process logic for discount processsing';
5469             write_log(LOG, G_err_stage);
5470 
5471             process_disc_logic;
5472 
5473             G_err_stage := 'Calling Bulk Insert into trx intf for discounts';
5474             write_log(LOG, G_err_stage);
5475 
5476             bulk_insert_trx_intf;
5477 
5478             IF (v_num_discounts_fetched > 0) THEN
5479 
5480                G_err_stage := 'Calling trans import for discounts';
5481                write_log(LOG, G_err_stage);
5482 
5483            IF G_ACCTNG_METHOD = 'C' THEN
5484               IF l_ap_inv_disc_flag = 'Y' THEN
5485                trans_import('AP INVOICE', G_DISC_BATCH_NAME,G_DISC_INTERFACE_ID, G_USER_ID);
5486                tieback_payment_AP_ER('AP INVOICE', G_DISC_BATCH_NAME, 'APDISC',G_DISC_INTERFACE_ID);
5487               END IF;
5488               IF l_ap_nrt_disc_flag = 'Y' THEN
5489                trans_import('AP NRTAX', G_DISC_BATCH_NAME,G_DISC_INTERFACE_ID, G_USER_ID);
5490                tieback_payment_AP_ER('AP NRTAX', G_DISC_BATCH_NAME, 'APDISC',G_DISC_INTERFACE_ID);
5491               END IF;
5492               IF l_ap_hist_disc_flag = 'Y' THEN
5493                trans_import(G_DISC_TRANSACTION_SOURCE, G_DISC_BATCH_NAME,G_DISC_INTERFACE_ID, G_USER_ID);
5494                tieback_payment_AP_ER(G_DISC_TRANSACTION_SOURCE, G_DISC_BATCH_NAME, 'APDISC',G_DISC_INTERFACE_ID);
5495               END IF;
5496            ELSE
5497                trans_import(G_DISC_TRANSACTION_SOURCE, G_DISC_BATCH_NAME,G_DISC_INTERFACE_ID, G_USER_ID);
5498                tieback_payment_AP_ER(G_DISC_TRANSACTION_SOURCE, G_DISC_BATCH_NAME, 'APDISC',G_DISC_INTERFACE_ID);
5499            END IF;
5500 
5501                G_NUM_BATCHES_PROCESSED := G_NUM_BATCHES_PROCESSED + 1;
5502                G_NUM_DISCOUNTS_PROCESSED := G_NUM_DISCOUNTS_PROCESSED + v_num_discounts_fetched;
5503 
5504             END IF; /* IF (v_num_discounts_fetched > 0) */
5505 
5506             clear_plsql_tables;
5507 
5508         ELSE
5509 
5510           G_err_stage := 'plsql table for discounts is empty. Exiting';
5511           write_log(LOG, G_err_stage);
5512 
5513           EXIT; /* Exit if /* l_inv_pay_id_tbl.COUNT = 0 */
5514 
5515         END IF; /* l_inv_pay_id_tbl.COUNT = 0 */
5516 
5517         v_num_discounts_fetched :=0;
5518         v_num_payments_fetched := 0;
5519 
5520         EXIT WHEN Discount_Cur%NOTFOUND;
5521 
5522       END LOOP; /* While v_all_done = 0 */
5523 
5524       G_err_stage := 'Closing Discount cursor';
5525       write_log(LOG, G_err_stage);
5526 
5527       CLOSE Discount_cur;
5528 
5529 EXCEPTION
5530     WHEN OTHERS THEN
5531 
5532          G_err_stack := v_old_stack;
5533          IF Discount_Cur%ISOPEN THEN
5534            CLOSE Discount_Cur;
5535          END IF ;
5536 
5537          G_err_code := SQLCODE;
5538          RAISE;
5539 
5540 END transfer_disc_to_pa;
5541 
5542 
5543 PROCEDURE mark_RCV_PAflag IS
5544 
5545    v_status     VARCHAR2(30);
5546 
5547 BEGIN
5548 
5549    G_err_stack := G_err_stack || '->PAAPIMP_PKG.mark_RCV_PAflag';
5550    write_log(LOG, 'UPDATING RCV_TRANSACTIONS -Marking Process');
5551 
5552    /* mark all the rcv sub ledger records pa_addition_flag to NULL for any rcv transactions
5553       that are non-project related or with a non-EXPENSE destination_type_code,which is not a return or is not actual*/
5554     -- This update has been moved to pa_po_integration_utils.update_pa_addition_flag.
5555 
5556 
5557    /* mark rcv sub ledger records pa_addition_flag to O/J for rcv transactions that are
5558      project related and fit the criteria to be pulled into Projects.
5559      Divided into project_ID IS NULL and NOT NULL section for better performance
5560    */
5561 
5562    IF G_PROJECT_ID IS NOT NULL THEN
5563 
5564    /* Modified the below update statement for better performence bug#7526677
5565    Not commenting and doing the changes because it has already become a mess with these updates
5566    */
5567 
5568 	   UPDATE rcv_receiving_sub_ledger rcv_sub
5569 	      SET rcv_sub.pa_Addition_Flag       = decode(rcv_sub.pa_addition_flag,'N','O','I','J'),
5570 		  rcv_sub.request_id             = G_REQUEST_ID,
5571 		  rcv_sub.last_update_date       = SYSDATE,
5572 		  rcv_sub.last_updated_by        = G_USER_ID,
5573 		  rcv_sub.last_update_login      = G_USER_ID,
5574 		  rcv_sub.program_id             = G_PROG_ID,
5575 		  rcv_sub.program_application_id = G_PROG_APPL_ID,
5576 		  rcv_sub.program_update_date    = SYSDATE
5577 	    WHERE exists
5578 		(SELECT 1 --rcv_sub1.ROWID --Removed /*+ leading(po_dist) */ for Bug5262594
5579                  FROM Rcv_Transactions rcv_txn,
5580                       PO_Distributions po_dist
5581 		WHERE ((rcv_txn.destination_type_code ='EXPENSE' )
5582 		    OR (rcv_txn.destination_type_code = 'RECEIVING'
5583                     AND (rcv_txn.transaction_type IN ('RETURN TO VENDOR','RETURN TO RECEIVING'))))
5584 		AND trunc(rcv_txn.transaction_date)      <= trunc(nvl(G_GL_DATE,rcv_txn.transaction_date))      /*Added trunc for the bug 6623163 */
5585 		AND rcv_txn.PO_DISTRIBUTION_ID    =  po_dist.po_distribution_id
5586 		AND rcv_sub.code_combination_id   =  po_dist.code_combination_id
5587                 AND nvl(po_dist.distribution_type,'XXX') <> 'PREPAYMENT'   --bug 7192304, added nvl
5588 		AND rcv_sub.rcv_transaction_id    =  rcv_txn.transaction_id
5589 		AND trunc(po_dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,po_dist.expenditure_item_date)) /*Added trunc for the bug 6623163 */
5590 		AND po_dist.project_ID  > 0
5591 		AND po_dist.accrue_on_receipt_flag= 'Y'
5592 		AND nvl(rcv_txn.project_id , po_dist.project_id)  = G_PROJECT_ID  /*Added for bug:7046666*/
5593 		/* Start added for bug#6015451 */
5594 		AND ( (rcv_txn.destination_type_code = 'EXPENSE' AND
5595 		        rcv_txn.transaction_type <> 'RETURN TO RECEIVING' AND rcv_sub.entered_dr is NOT NULL
5596 		       ) OR
5597 		       ((rcv_txn.destination_type_code = 'RECEIVING' OR
5598 		         rcv_txn.transaction_type = 'RETURN TO RECEIVING') AND rcv_sub.entered_cr is NOT NULL
5599                         )
5600 		     )
5601 		/* Ends added for bug#6015451 */
5602 		)
5603 	    AND rcv_sub.pa_addition_flag IN ('N','I')
5604 		AND rcv_sub.actual_flag = 'A';
5605 
5606 	     G_RCV_TRANSACTIONS_MARKED_O := SQL%ROWCOUNT;
5607              write_log(LOG, 'Number of rcvtxn marked to O or J:' || to_char(SQL%ROWCOUNT));
5608 
5609 
5610    ELSIF G_PROJECT_ID IS NULL THEN
5611 
5612    /* Modified the below update statement for better performence bug#7526677
5613    Not commenting and doing the changes because it has already become a mess with these updates
5614    */
5615 
5616 	   UPDATE rcv_receiving_sub_ledger rcv_sub
5617 	      SET rcv_sub.pa_Addition_Flag       = decode(rcv_sub.pa_addition_flag,'N','O','I','J'),
5618 		  rcv_sub.request_id             = G_REQUEST_ID,
5619 		  rcv_sub.last_update_date       = SYSDATE,
5620 		  rcv_sub.last_updated_by        = G_USER_ID,
5621 		  rcv_sub.last_update_login      = G_USER_ID,
5622 		  rcv_sub.program_id             = G_PROG_ID,
5623 		  rcv_sub.program_application_id = G_PROG_APPL_ID,
5624 		  rcv_sub.program_update_date    = SYSDATE
5625 	    WHERE exists
5626                (SELECT 1 --rcv_sub1.ROWID --Removed /*+ leading(po_dist) */ for Bug5262594
5627                  FROM Rcv_Transactions rcv_txn,
5628                       PO_Distributions po_dist
5629 		WHERE ((rcv_txn.destination_type_code ='EXPENSE' )
5630 		    OR (rcv_txn.destination_type_code = 'RECEIVING'
5631                     AND (rcv_txn.transaction_type IN ('RETURN TO VENDOR','RETURN TO RECEIVING'))))
5632 		AND trunc(rcv_txn.transaction_date)      <= trunc(nvl(G_GL_DATE,rcv_txn.transaction_date))      /*Added trunc for the bug 6623163 */
5633 		AND rcv_txn.PO_DISTRIBUTION_ID    =  po_dist.po_distribution_id
5634 		AND rcv_sub.code_combination_id   =  po_dist.code_combination_id
5635                 AND nvl(po_dist.distribution_type,'XXX') <> 'PREPAYMENT'    -- bug 7192304, added nvl
5636 		AND rcv_sub.rcv_transaction_id    =  rcv_txn.transaction_id
5637 		AND trunc(po_dist.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,po_dist.expenditure_item_date)) /*Added trunc for the bug 6623163 */
5638 		AND po_dist.project_ID  > 0
5639 		AND po_dist.accrue_on_receipt_flag= 'Y'
5640 		/* Starts added for bug#6015451 */
5641 		AND ( (rcv_txn.destination_type_code = 'EXPENSE' AND
5642 		        rcv_txn.transaction_type <> 'RETURN TO RECEIVING' AND rcv_sub.entered_dr is NOT NULL
5643 		       ) OR
5644 		       ((rcv_txn.destination_type_code = 'RECEIVING' OR
5645 		         rcv_txn.transaction_type = 'RETURN TO RECEIVING') AND rcv_sub.entered_cr is NOT NULL
5646                         )
5647 		     )
5648 		/* Ends added for bug#6015451 */
5649 		)
5650 		AND rcv_sub.pa_addition_flag IN ('N','I')
5651         AND rcv_sub.actual_flag = 'A';
5652 
5653 
5654 	     G_RCV_TRANSACTIONS_MARKED_O := SQL%ROWCOUNT;
5655 	     write_log(LOG, 'Number of rcvtxn marked to O or J:' || to_char(SQL%ROWCOUNT));
5656 
5657     END IF;
5658 
5659 EXCEPTION
5660    WHEN Others THEN
5661       G_err_code := SQLCODE;
5662       RAISE;
5663 
5664 END mark_RCV_PAflag;
5665 
5666 PROCEDURE transfer_receipts_to_pa  IS
5667 
5668    v_total_num_receipts            NUMBER := 0;
5669    v_num_receipts_processed        NUMBER := 0;
5670    v_num_receipt_tax_processed     NUMBER := 0;
5671    l_denom_cost                    NUMBER :=0;
5672    l_acct_cost                     NUMBER :=0;
5673    l_quantity                      NUMBER :=0;
5674    l_record_type                   VARCHAR2(20);
5675 
5676    v_max_size                      NUMBER := 0;
5677 
5678    v_old_stack                     VARCHAR2(630);
5679    v_err_message                   VARCHAR2(220);
5680    v_all_done                      NUMBER := 0;
5681 
5682    v_status Number := 0;
5683    v_stage  Number :=0;
5684 
5685    v_last_rcv_index             NUMBER := 0;
5686    v_prev_po_head_id     NUMBER := 0;
5687    v_prev_po_dist_id     NUMBER := 0;
5688    v_business_group_id   NUMBER := 0;
5689    v_attribute_category  VARCHAR2(150);
5690    v_attribute1 VARCHAR2(150);
5691    v_attribute2 VARCHAR2(150);
5692    v_attribute3 VARCHAR2(150);
5693    v_attribute4 VARCHAR2(150);
5694    v_attribute5 VARCHAR2(150);
5695    v_attribute6 VARCHAR2(150);
5696    v_attribute7 VARCHAR2(150);
5697    v_attribute8 VARCHAR2(150);
5698    v_attribute9 VARCHAR2(150);
5699    v_attribute10 VARCHAR2(150);
5700    v_dff_map_status VARCHAR2(30);
5701    dff_map_exception EXCEPTION;
5702    l_create_adj_recs     VARCHAR2(1) := 'N';
5703 
5704    /* the following sub-procedure is declared here to save lines of code since deleting
5705       plsql tables will be done multiple times within the procedure transfer_receipts_to_pa */
5706 
5707    PROCEDURE clear_plsql_tables IS
5708 
5709        l_status1 VARCHAR2(30);
5710 
5711    BEGIN
5712 
5713        G_err_stage := 'within clear_plsql_tables of transfer_receipts_to_pa';
5714        write_log(LOG, G_err_stage);
5715 
5716    l_rcv_txn_id_tbl.delete;
5717    l_po_dist_id_tbl.delete;
5718    l_po_head_id_tbl.delete;
5719    l_po_num_tbl.delete;
5720    l_quantity_tbl.delete;
5721    l_entered_dr_tbl.delete;
5722    l_entered_cr_tbl.delete;
5723    l_accounted_dr_tbl.delete;
5724    l_accounted_cr_tbl.delete;
5725    l_entered_nr_tax_tbl.delete;
5726    l_accounted_nr_tax_tbl.delete;
5727    l_denom_raw_cost_tbl.delete;
5728    l_acct_raw_cost_tbl.delete;
5729    l_record_type_tbl.delete;
5730    l_dist_cc_id_tbl.delete;
5731    l_denom_cur_code_tbl.delete;
5732    l_acct_rate_date_tbl.delete;
5733    l_acct_rate_type_tbl.delete;
5734    l_acct_exch_rate_tbl.delete;
5735    l_gl_date_tbl.delete;
5736    l_dest_typ_code_tbl.delete;
5737    l_pa_add_flag_tbl.delete;
5738    l_trx_type_tbl.delete;
5739    l_project_id_tbl.delete;
5740    l_task_id_tbl.delete;
5741    l_employee_id_tbl.delete;
5742    l_exp_type_tbl.delete;
5743    l_ei_date_tbl.delete;
5744    l_vendor_id_tbl.delete;
5745    l_exp_org_id_tbl.delete;
5746    l_job_id_tbl.delete;
5747    l_description_tbl.delete;
5748    l_attribute_cat_tbl.delete;
5749    l_attribute1_tbl.delete;
5750    l_attribute2_tbl.delete;
5751    l_attribute3_tbl.delete;
5752    l_attribute4_tbl.delete;
5753    l_attribute5_tbl.delete;
5754    l_attribute6_tbl.delete;
5755    l_attribute7_tbl.delete;
5756    l_attribute8_tbl.delete;
5757    l_attribute9_tbl.delete;
5758    l_attribute10_tbl.delete;
5759    l_org_id_tbl.delete;
5760    l_cdl_sys_ref4_tbl.delete;
5761    l_txn_src_tbl.delete;
5762    l_user_txn_src_tbl.delete;
5763    l_batch_name_tbl.delete;
5764    l_interface_id_tbl.delete;
5765    l_exp_end_date_tbl.delete;
5766    l_txn_status_code_tbl.delete;
5767    l_txn_rej_code_tbl.delete;
5768    l_bus_grp_id_tbl.delete;
5769    l_insert_flag_tbl.delete;
5770    l_rcv_acct_evt_id_tbl.delete; -- pricing changes
5771    l_rcv_acct_evt_typ_tbl.delete; -- pricing changes
5772    l_rcv_acct_rec_tax_tbl.delete; -- pricing changes
5773    l_rcv_ent_rec_tax_tbl.delete; -- pricing changes
5774    l_parent_rcv_id_tbl.delete;   -- NEW --added for full return reversal logic
5775    l_net_zero_flag_tbl.delete;
5776    l_sc_xfer_code_tbl.delete; --NEW
5777    l_adj_exp_item_id_tbl.delete; --NEW
5778    l_fc_enabled_tbl.delete; --NEW
5779    l_fc_document_type_tbl.delete; --NEW
5780    l_rcv_sub_ledger_id_tbl.delete;
5781    l_si_assts_add_flg_tbl.delete;
5782    l_exp_cst_rt_flg_tbl.delete; --NEW
5783    l_po_tax_qty_tbl.delete;
5784 
5785    END clear_plsql_tables;
5786 
5787    PROCEDURE bulk_insert_trx_intf IS
5788 
5789      l_status2 VARCHAR2(30);
5790 
5791    BEGIN
5792 
5793       FORALL i IN l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST
5794 
5795        INSERT INTO pa_transaction_interface_all(
5796                      transaction_source
5797                     , user_transaction_source
5798                     , system_linkage
5799                     , batch_name
5800                     , expenditure_ending_date
5801                     , expenditure_item_date
5802                     , expenditure_type
5803                     , quantity
5804                     , raw_cost_rate
5805                     , expenditure_comment
5806                     , transaction_status_code
5807                     , transaction_rejection_code
5808                     , orig_transaction_reference
5809                     , interface_id
5810                     , dr_code_combination_id
5811                     , cr_code_combination_id
5812                     , cdl_system_reference1
5813                     , cdl_system_reference2
5814                     , cdl_system_reference3
5815                     , cdl_system_reference4
5816                     , cdl_system_reference5
5817                     , gl_date
5818                     , org_id
5819                     , unmatched_negative_txn_flag
5820                     , denom_raw_cost
5821                     , denom_currency_code
5822                     , acct_rate_date
5823                     , acct_rate_type
5824                     , acct_exchange_rate
5825                     , acct_raw_cost
5826                     , acct_exchange_rounding_limit
5827                     , attribute_category
5828                     , attribute1
5829                     , attribute2
5830                     , attribute3
5831                     , attribute4
5832                     , attribute5
5833                     , attribute6
5834                     , attribute7
5835                     , attribute8
5836                     , attribute9
5837                     , attribute10
5838                     , orig_exp_txn_reference1
5839                     , orig_user_exp_txn_reference
5840                     ,  orig_exp_txn_reference2
5841                     ,  orig_exp_txn_reference3
5842                     , last_update_date
5843                     , last_updated_by
5844                     , creation_date
5845                     , created_by
5846                     , person_id
5847                     , organization_id
5848                     , project_id
5849                     , task_id
5850                     , Vendor_id
5851                     , override_to_organization_id
5852                     , person_business_group_id
5853                     , adjusted_expenditure_item_id --NEW
5854                     , fc_document_type  -- NEW
5855                     , document_type
5856                     , document_distribution_type
5857                     , sc_xfer_code
5858                     , si_assets_addition_flag
5859                     , net_zero_adjustment_flag
5860                    )
5861                SELECT l_txn_src_tbl(i)
5862                      ,l_user_txn_src_tbl(i)
5863                      ,G_SYSTEM_LINKAGE
5864                      ,l_batch_name_tbl(i)
5865                      ,l_exp_end_date_tbl(i)
5866                      ,l_ei_date_tbl(i)
5867                      ,l_exp_type_tbl(i)
5868                      ,l_quantity_tbl(i)
5869                      ,l_acct_raw_cost_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
5870                      ,l_description_tbl(i)
5871                      ,l_txn_status_code_tbl(i)
5872                      ,l_txn_rej_code_tbl(i)
5873                      ,G_REQUEST_ID
5874                      ,l_interface_id_tbl(i)
5875                      ,l_dist_cc_id_tbl(i)
5876                      ,NULL
5877                      ,l_vendor_id_tbl(i)
5878                      ,l_po_head_id_tbl(i)
5879                      ,l_po_dist_id_tbl(i)
5880                      ,l_rcv_txn_id_tbl(i)
5881                      ,l_rcv_sub_ledger_id_tbl(i)
5882                      ,l_gl_date_tbl(i)
5883                      ,G_ORG_ID
5884                      ,'Y'
5885                      ,l_denom_raw_cost_tbl(i)
5886                      ,l_denom_cur_code_tbl(i)
5887                      ,l_acct_rate_date_tbl(i)
5888                      ,l_acct_rate_type_tbl(i)
5889                      ,l_acct_exch_rate_tbl(i)
5890                      ,l_acct_raw_cost_tbl(i)
5891                      ,1
5892                      ,l_attribute_cat_tbl(i)
5893                      ,l_attribute1_tbl(i)
5894                      ,l_attribute2_tbl(i)
5895                      ,l_attribute3_tbl(i)
5896                      ,l_attribute4_tbl(i)
5897                      ,l_attribute5_tbl(i)
5898                      ,l_attribute6_tbl(i)
5899                      ,l_attribute7_tbl(i)
5900                      ,l_attribute8_tbl(i)
5901                      ,l_attribute9_tbl(i)
5902                      ,l_attribute10_tbl(i)
5903                      ,l_po_dist_id_tbl(i)        /*orig_exp_txn_reference1*/
5904                      ,l_rcv_txn_id_tbl(i)        /*user_exp_txn_reference*/
5905                      ,l_rcv_acct_evt_id_tbl(i)   /*orig_exp_txn_reference2*/
5906                      ,NULL                       /*orig_exp_txn_reference3*/
5907                      ,SYSDATE
5908                      ,-1
5909                      ,SYSDATE
5910                      ,-1
5911                      ,l_employee_id_tbl(i)
5912                      ,l_org_id_tbl(i)
5913                      ,l_project_id_tbl(i)
5914                      ,l_task_id_tbl(i)
5915                      ,l_vendor_id_tbl(i)
5916                      ,l_exp_org_id_tbl(i)
5917                      ,l_bus_grp_id_tbl(i)
5918                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
5919                      ,l_fc_document_type_tbl(i) --NEW for funds check
5920                      ,l_dest_typ_code_tbl(i)
5921                      ,l_trx_type_tbl(i)
5922                      ,l_sc_xfer_code_tbl(i)
5923                      ,l_si_assts_add_flg_tbl(i)
5924                      ,l_net_zero_flag_tbl(i)
5925                   FROM dual
5926                  WHERE l_insert_flag_tbl(i) in  ('Y','A');
5927 
5928               -- Insert the adjustment recs from AP.
5929     IF l_create_adj_recs = 'Y' THEN
5930 
5931                 write_log(LOG, 'Inserting adjustment records..');
5932 
5933       FORALL i IN l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST
5934 
5935        INSERT INTO pa_transaction_interface_all(
5936                      transaction_source
5937                     , user_transaction_source
5938                     , system_linkage
5939                     , batch_name
5940                     , expenditure_ending_date
5941                     , expenditure_item_date
5942                     , expenditure_type
5943                     , quantity
5944                     , raw_cost_rate
5945                     , expenditure_comment
5946                     , transaction_status_code
5947                     , transaction_rejection_code
5948                     , orig_transaction_reference
5949                     , interface_id
5950                     , dr_code_combination_id
5951                     , cr_code_combination_id
5952                     , cdl_system_reference1
5953                     , cdl_system_reference2
5954                     , cdl_system_reference3
5955                     , cdl_system_reference4
5956                     , cdl_system_reference5
5957                     , gl_date
5958                     , org_id
5959                     , unmatched_negative_txn_flag
5960                     , denom_raw_cost
5961                     , denom_currency_code
5962                     , acct_rate_date
5963                     , acct_rate_type
5964                     , acct_exchange_rate
5965                     , acct_raw_cost
5966                     , acct_exchange_rounding_limit
5967                     , attribute_category
5968                     , attribute1
5969                     , attribute2
5970                     , attribute3
5971                     , attribute4
5972                     , attribute5
5973                     , attribute6
5974                     , attribute7
5975                     , attribute8
5976                     , attribute9
5977                     , attribute10
5978                     , orig_exp_txn_reference1
5979                     , orig_user_exp_txn_reference
5980                     ,  orig_exp_txn_reference2
5981                     ,  orig_exp_txn_reference3
5982                     , last_update_date
5983                     , last_updated_by
5984                     , creation_date
5985                     , created_by
5986                     , person_id
5987                     , organization_id
5988                     , project_id
5989                     , task_id
5990                     , Vendor_id
5991                     , override_to_organization_id
5992                     , person_business_group_id
5993                     , adjusted_expenditure_item_id --NEW
5994                     , fc_document_type  -- NEW
5995                     , document_type
5996                     , document_distribution_type
5997                     , adjusted_txn_interface_id
5998                     , sc_xfer_code
5999                     , si_assets_addition_flag
6000                     , net_zero_adjustment_flag
6001                    )
6002                SELECT l_txn_src_tbl(i)
6003                      ,l_user_txn_src_tbl(i)
6004                      ,G_SYSTEM_LINKAGE
6005                      ,l_batch_name_tbl(i)
6006                      ,l_exp_end_date_tbl(i)
6007                      ,l_ei_date_tbl(i)
6008                      ,l_exp_type_tbl(i)
6009                      ,-l_quantity_tbl(i)
6010                      ,l_acct_raw_cost_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
6011                      ,l_description_tbl(i)
6012                      ,l_txn_status_code_tbl(i)
6013                      ,l_txn_rej_code_tbl(i)
6014                      ,G_REQUEST_ID
6015                      ,l_interface_id_tbl(i)
6016                      ,l_dist_cc_id_tbl(i)
6017                      ,NULL
6018                      ,l_vendor_id_tbl(i)
6019                      ,l_po_head_id_tbl(i)
6020                      ,l_po_dist_id_tbl(i)
6021                      ,l_rcv_txn_id_tbl(i)
6022                      ,l_rcv_sub_ledger_id_tbl(i)
6023                      ,l_gl_date_tbl(i)
6024                      ,G_ORG_ID
6025                      ,'Y'
6026                      ,-l_denom_raw_cost_tbl(i)
6027                      ,l_denom_cur_code_tbl(i)
6028                      ,l_acct_rate_date_tbl(i)
6029                      ,l_acct_rate_type_tbl(i)
6030                      ,l_acct_exch_rate_tbl(i)
6031                      ,-l_acct_raw_cost_tbl(i)
6032                      ,1
6033                      ,l_attribute_cat_tbl(i)
6034                      ,l_attribute1_tbl(i)
6035                      ,l_attribute2_tbl(i)
6036                      ,l_attribute3_tbl(i)
6037                      ,l_attribute4_tbl(i)
6038                      ,l_attribute5_tbl(i)
6039                      ,l_attribute6_tbl(i)
6040                      ,l_attribute7_tbl(i)
6041                      ,l_attribute8_tbl(i)
6042                      ,l_attribute9_tbl(i)
6043                      ,l_attribute10_tbl(i)
6044                      ,l_po_dist_id_tbl(i)        /*orig_exp_txn_reference1*/
6045                      ,l_rcv_txn_id_tbl(i)        /*user_exp_txn_reference*/
6046                      ,l_rcv_acct_evt_id_tbl(i)   /*orig_exp_txn_reference2*/
6047                      ,NULL                       /*orig_exp_txn_reference3*/
6048                      ,SYSDATE
6049                      ,-1
6050                      ,SYSDATE
6051                      ,-1
6052                      ,l_employee_id_tbl(i)
6053                      ,l_org_id_tbl(i)
6054                      ,l_project_id_tbl(i)
6055                      ,l_task_id_tbl(i)
6056                      ,l_vendor_id_tbl(i)
6057                      ,l_exp_org_id_tbl(i)
6058                      ,l_bus_grp_id_tbl(i)
6059                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
6060                      ,l_fc_document_type_tbl(i) --NEW for funds check
6061                      ,l_dest_typ_code_tbl(i)
6062                      ,l_trx_type_tbl(i)
6063                      ,(select xface.txn_interface_id
6064                       from   pa_transaction_interface xface
6065                       where  xface.interface_id =  l_interface_id_tbl(i)
6066                       and    xface.transaction_source = l_txn_src_tbl(i)
6067                       and    xface.cdl_system_reference2 = l_po_head_id_tbl(i)
6068                       and    xface.cdl_system_reference3 = l_po_dist_id_tbl(i)
6069                       and    xface.cdl_system_reference4 = to_char(l_rcv_txn_id_tbl(i))
6070 		      and    nVL(xface.adjusted_expenditure_item_id,0) = 0 ) -- R12 funds management Uptake
6071                      ,'P'  -- sc_xfer_code
6072                      ,'T'  -- Si assets flag
6073                      ,l_net_zero_flag_tbl(i)
6074                   FROM dual
6075                   WHERE l_insert_flag_tbl(i) = 'A';
6076     END IF;
6077 
6078    EXCEPTION
6079       WHEN OTHERS THEN
6080           write_log(LOG,'Failed during bulk insert for receipt processing');
6081           G_err_code   := SQLCODE;
6082           raise;
6083 
6084    END bulk_insert_trx_intf;
6085 
6086    PROCEDURE process_receipt_logic IS
6087 
6088        l_status_3 VARCHAR2(30);
6089        l_evt_typ_name VARCHAR2(30);
6090        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
6091        l_historical_flag VARCHAR(1);  --NEW
6092        l_process_adjustments    Number := 0 ;
6093 
6094 
6095                          l_primary_quantity     NUMBER;
6096                          l_amount               NUMBER;
6097                          l_exists               VARCHAR2(1);
6098 
6099    BEGIN
6100 
6101       G_err_stage:='Within process_receipt_logic';
6102       write_log(LOG,   G_err_stage);
6103 
6104       j := v_last_rcv_index; -- initialize j to the total invoice distributions fetched in the PLSQL array
6105       FOR i IN l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST LOOP
6106 
6107           G_err_stage:=('processing receipt of rcvtxn_id:  '||l_rcv_txn_id_tbl(i)||
6108                        'of po_dist_id:  '||l_po_dist_id_tbl(i));
6109           write_log(LOG,   G_err_stage);
6110 
6111           G_err_stage := 'Calling lock_ap_invoice within pa_add_flag is O';
6112           write_log(LOG,   G_err_stage);
6113 
6114           lock_ap_invoice(l_po_dist_id_tbl(i));
6115 
6116           G_TRANSACTION_REJECTION_CODE  :='';
6117           G_TRANSACTION_STATUS_CODE     := 'P';
6118 
6119           /*
6120             When the Receipt Amount is NULL, mark status code as R in
6121             transaction interface table such that the record wont' be interfaceed.
6122           */
6123           write_log(LOG, 'Checking if the Receipt Amount is Null...');
6124 
6125           IF (l_entered_dr_tbl(i)     IS NULL AND
6126               l_entered_nr_tax_tbl(i) IS NULL ) THEN
6127 
6128              G_TRANSACTION_STATUS_CODE := 'R';
6129              G_TRANSACTION_REJECTION_CODE := 'INVALID_AMOUNT';
6130              write_log(LOG, 'As PO Receipt Amount is NULL, Rejecting PO Receipt : '||l_rcv_txn_id_tbl(i));
6131 
6132           END IF;
6133 
6134           G_err_stage := ('Before getting business group id');
6135           write_log(LOG, G_err_stage);
6136 
6137           IF (nvl(l_po_head_id_tbl(i),0)<>v_prev_po_head_id) THEN
6138 
6139              v_prev_po_head_id := l_po_head_id_tbl(i);
6140 
6141              BEGIN
6142 
6143                IF nvl(l_employee_id_tbl(i),0) <> 0 THEN
6144 
6145                  SELECT emp.business_group_id
6146                    INTO G_PER_BUS_GRP_ID
6147                    FROM per_all_people_f emp
6148                   WHERE emp.person_id = l_employee_id_tbl(i)
6149                           AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and
6150                                                        trunc(emp.effective_end_date);
6151 
6152                END IF;
6153 
6154              EXCEPTION
6155               WHEN NO_DATA_FOUND THEN
6156 
6157                  l_txn_status_code_tbl(i) := 'R';
6158                  G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
6159                  write_log(LOG, 'no data found for Employee, Rejecting receipt'||l_rcv_txn_id_tbl(i)  );
6160 
6161              END;
6162 
6163           END IF;
6164 
6165           IF (nvl(l_po_dist_id_tbl(i),0)<>v_prev_po_dist_id) THEN
6166 
6167              v_prev_po_dist_id := l_po_dist_id_tbl(i);
6168 
6169              G_err_stage := 'GET MAX EXPENDITURE ENDING DATE for Receipt Accruals';
6170              write_log(LOG,   G_err_stage);
6171 
6172              /* Get the weekending date of the maximum expenditure item date of this PO distribution */
6173 
6174 /* Bug 5051103 - replace expnediture_item_date with l_ei_date_tbl(i) */
6175              SELECT pa_utils.getweekending(MAX(l_ei_date_tbl(i)))
6176                INTO G_EXPENDITURE_ENDING_DATE
6177                FROM po_distributions
6178               WHERE po_distribution_id = l_po_dist_id_tbl(i);
6179 
6180           END IF;
6181 
6182          write_log(LOG,'Fetched a po receipt record of destination type:'||
6183                         l_dest_typ_code_tbl(i)||
6184                        'and trx type of:'||l_trx_type_tbl(i));
6185 
6186          v_total_num_receipts := v_total_num_receipts +1 ;
6187          write_log(LOG,'Number of receipts fetched:  '||v_total_num_receipts);
6188 
6189 	     IF (l_rcv_acct_evt_id_tbl(i) IS NULL) THEN
6190 
6191     	        l_txn_src_tbl(i)         := G_RCV_TRANSACTION_SOURCE;
6192 	            l_user_txn_src_tbl(i)    := G_RCV_USER_TRANSACTION_SOURCE;
6193 	     ELSE
6194 
6195         		SELECT event_type_name
6196 	        	INTO l_evt_typ_name
6197         		FROM rcv_accounting_event_types rcv_acct_evt_typ, rcv_accounting_events rcv_acct_evts
6198         		WHERE rcv_acct_evt_typ.event_type_id = rcv_acct_evts.event_type_id
6199         		AND rcv_acct_evts.accounting_event_id = l_rcv_acct_evt_id_tbl(i);
6200 
6201         		IF (l_evt_typ_name in ('ADJUST_DELIVER','ADJUST_RECEIVE')) THEN
6202         			l_txn_src_tbl(i)         := G_RCV_PRC_ADJ_TRX_SRC;
6203         			l_user_txn_src_tbl(i)    := G_RCV_PRC_ADJ_USER_TRX_SRC;
6204                                 l_quantity               := 0;
6205         		ELSE
6206         			l_txn_src_tbl(i)         := G_RCV_TRANSACTION_SOURCE;
6207         			l_user_txn_src_tbl(i)    := G_RCV_USER_TRANSACTION_SOURCE;
6208         		END IF;
6209 
6210 	     END IF;
6211 
6212 	     l_batch_name_tbl(i)      := G_RCV_BATCH_NAME;
6213 	     l_interface_id_tbl(i)    := G_RCV_INTERFACE_ID;
6214 
6215              l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
6216              l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
6217              l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
6218              l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
6219 
6220 
6221          IF l_pa_add_flag_tbl(i) = 'O' THEN
6222 
6223             write_log(LOG,'PA_addition_flag for this RCV transaction has been marked to O');
6224 
6225             /* If the pa_addition_flag is updated to 'O', then it means we would need
6226                to break down the amount of the receipt into two portions. One is the
6227                total minus tax and the other is just the NR Tax portion. This Loop
6228                will process the total minus tax portion.  After inserting this amount
6229                , the next loop will insert the tax portion of the receipt into the
6230                tranasction_interface table */
6231 
6232             v_num_receipts_processed := v_num_receipts_processed + 1;
6233 
6234             /* for the amount that we are selecting, we need to see whether the transaction is an
6235                EXPENSE or RECEIVING transactions. EXPENSE means we take the positive value of dr column
6236                minus the tax amount while RECEIVNG transaction means it is a return, so we take the
6237                negative of the cr column plus the tax amount. If the trasnaction is a RETURN,
6238                then we want the quantity to be a negative quantity */
6239 
6240          -- call the function to check if the txn got interfaced through AP. If Yes, then set the pa_add_flag to G.
6241           IF ReceiptPaAdditionFlag(p_Pa_Addition_Flag     => l_pa_add_flag_tbl(i),
6242                                      p_Po_Distribution_Id   => l_po_dist_id_tbl(i)) = 'G' THEN
6243 
6244 
6245              write_log(LOG,'PA_addition_flag for this RCV transaction should be marked to G');
6246 
6247                           l_insert_flag_tbl(i) := 'N';
6248                           l_pa_add_flag_tbl(i) := 'G';
6249 
6250           ELSE
6251 
6252             l_record_type:= 'RECEIPT';
6253 
6254            /* If the PO Receipt is for Contingent Worker labor type and the CWK timecard is to be processed
6255               as Labor cost in the Project operating unit, then only the non recoverable tax receipt lines
6256               should be pulled from PO, otherwise the entire receipt with tax should be processed from PO */
6257 
6258             IF PA_PJC_CWK_UTILS.Is_rate_based_line(null, l_po_dist_id_tbl(i)) = 'Y'
6259                AND PA_PJC_CWK_UTILS.Is_CWK_TC_Xface_Allowed(l_project_id_tbl(i)) = 'Y' THEN
6260                l_insert_flag_tbl(i) := 'N';
6261 
6262                write_log(LOG, 'Receipt is for CWK timecard PO - Only NRTAX will be processed');
6263 
6264             ELSE
6265 
6266               IF (l_dest_typ_code_tbl(i) = 'EXPENSE'  AND
6267                   l_trx_type_tbl(i)  NOT IN ('CORRECT', 'RETURN TO RECEIVING')) THEN
6268 
6269                 l_denom_cost := l_entered_dr_tbl(i)   - l_entered_nr_tax_tbl(i);
6270                 l_acct_cost  := l_accounted_dr_tbl(i) - l_accounted_nr_tax_tbl(i);
6271                 l_quantity   := l_quantity_tbl(i);
6272 
6273               ELSIF ((l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i)  IN ('CORRECT', 'RETURN TO RECEIVING')) OR
6274                        ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
6275                                                                                         'RETURN TO RECEIVING' ))) THEN
6276                       --
6277                       -- Check if the correction is a complete correction
6278                       --
6279                       DECLARE
6280                          l_primary_quantity     NUMBER;
6281                          l_amount               NUMBER;
6282                          l_exists               VARCHAR2(1):= 'N';  /*bug7168636*/
6283                       BEGIN
6284 
6285                             SELECT primary_quantity, amount
6286                               INTO l_primary_quantity, l_amount
6287                               FROM rcv_transactions
6288                              WHERE transaction_id = l_parent_rcv_id_tbl(i) ;
6289 
6290                                 IF ((( ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = l_quantity_tbl(i)) OR
6291                                       ( l_amount = l_amount_tbl(i)))   AND
6292                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'RETURN TO RECEIVING') OR
6293                                         ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in ('RETURN TO VENDOR',
6294                                                                                                          'RETURN TO RECEIVING' )))) OR
6295                                     ((  ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = -l_quantity_tbl(i)) OR
6296                                       ( l_amount = l_amount_tbl(i)))   AND
6297                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'CORRECT')))) THEN
6298 
6299                                   -- Check if the parent has been interfaced to Projects.
6300 				  /*bug7168636 handling no data found */
6301 				  BEGIN
6302                                      SELECT 'Y'
6303                                        INTO l_exists
6304                                        FROM dual
6305                                       WHERE EXISTS (
6306                                                    SELECT pa_addition_flag
6307                                                      FROM rcv_receiving_sub_ledger
6308                                                     WHERE rcv_transaction_id = l_parent_rcv_id_tbl(i)
6309                                                       AND pa_addition_flag in ('Y','I')) ;
6310                                    EXCEPTION
6311                                      WHEN NO_DATA_FOUND THEN
6312                                      NULL;
6313                                    END;
6314 
6315                                       IF l_exists = 'Y' THEN
6316 
6317 
6318                                          -- Call reversal API
6319                                          Process_Adjustments(p_record_type               => 'PO_RECEIPT',
6320                                             p_document_header_id => l_po_head_id_tbl(i),/*Added this for 6945767 */
6321                                             p_document_distribution_id  => l_parent_rcv_id_tbl(i),
6322                                             p_current_index             => i,
6323 					    p_last_index                => j);
6324 
6325                                          -- Set the create flag for adjustment records
6326                                          IF l_insert_flag_tbl(i)= 'A' THEN
6327                                           l_create_adj_recs := 'Y';
6328                                          END IF;
6329 
6330                                      END IF;
6331 
6332                               END IF ; -- l_primary_quantity  = l_quantity
6333 
6334                             IF ( l_dest_typ_code_tbl(i) = 'RECEIVING'  OR l_trx_type_tbl(i) = 'RETURN TO RECEIVING' ) THEN
6335                               l_denom_cost := -l_entered_cr_tbl(i)   + l_entered_nr_tax_tbl(i);
6336                               l_acct_cost  := -l_accounted_cr_tbl(i) + l_accounted_nr_tax_tbl(i);
6337                               l_quantity   := -l_quantity_tbl(i);
6338                            ELSE
6339                               l_denom_cost := l_entered_dr_tbl(i)   - l_entered_nr_tax_tbl(i);
6340                               l_acct_cost  := l_accounted_dr_tbl(i) - l_accounted_nr_tax_tbl(i);
6341                               l_quantity   := l_quantity_tbl(i);
6342                            END IF;
6343 
6344                        EXCEPTION
6345                           WHEN NO_DATA_FOUND THEN
6346                                 NULL;
6347 
6348                           WHEN OTHERS THEN
6349                                RAISE ;
6350                        END ;
6351 
6352               END IF;
6353 
6354                IF l_quantity = 0 THEN   /* for amount based POs setting the pa quantity to be the same as the transaction cost*/
6355                    l_quantity := l_denom_cost;
6356                END IF;
6357 
6358 
6359             END IF; -- End of check for Contingent worker
6360 
6361        END IF; -- ReceiptPaAdditionFlag
6362      ELSIF l_pa_add_flag_tbl(i) = 'J' THEN
6363 
6364             write_log(LOG,'pa_addition_flag for this RCV transaction has been marked to J');
6365                /* If the pa_addition_flag is J, that means we only need to pull in the NR tax portion*/
6366 
6367             IF l_entered_nr_tax_tbl(i) = 0 THEN
6368 
6369                l_insert_flag_tbl(i) := 'N';
6370 
6371             ELSE
6372 
6373                v_num_receipt_tax_processed := v_num_receipt_tax_processed + 1;
6374 
6375                l_record_type:= 'RECEIPT TAX';
6376 
6377                IF (l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) NOT IN ('RETURN TO RECEIVING','CORRECT')) THEN
6378 
6379                   l_denom_cost := l_entered_nr_tax_tbl(i);
6380                   l_acct_cost  := l_accounted_nr_tax_tbl(i);
6381                   l_quantity   := l_quantity_tbl(i);
6382 
6383 
6384                ELSIF ((l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i)  IN ('CORRECT', 'RETURN TO RECEIVING')) OR
6385                        ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
6386                                                                                         'RETURN TO RECEIVING' ))) THEN
6387                       --
6388                       -- Check if the correction is a complete correction
6389                       --
6390                       DECLARE
6391                          l_primary_quantity     NUMBER;
6392                          l_amount               NUMBER;
6393                          l_exists               VARCHAR2(1):= 'N';    /*bug7168636*/
6394                       BEGIN
6395 
6396                             SELECT primary_quantity, amount
6397                               INTO l_primary_quantity, l_amount
6398                               FROM rcv_transactions
6399                              WHERE transaction_id = l_parent_rcv_id_tbl(i) ;
6400 
6401                                 IF ((( ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = l_quantity_tbl(i)) OR
6402                                       ( l_amount = l_amount_tbl(i)))   AND
6403                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'RETURN TO RECEIVING') OR
6404                                         ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
6405                                                                                                          'RETURN TO RECEIVING' )))) OR
6406                                     ((  ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = -l_quantity_tbl(i)) OR
6407                                       ( l_amount = l_amount_tbl(i)))   AND
6408                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'CORRECT')))) THEN
6409 
6410                                   -- Check if the parent has been interfaced to Projects.
6411 				  /*bug 7168636 handling no data found*/
6412 				  BEGIN
6413                                      SELECT 'Y'
6414                                        INTO l_exists
6415                                        FROM dual
6416                                       WHERE EXISTS (
6417                                                    SELECT pa_addition_flag
6418                                                      FROM rcv_receiving_sub_ledger
6419                                                     WHERE rcv_transaction_id = l_parent_rcv_id_tbl(i)
6420                                                       AND pa_addition_flag in ('Y','I')) ;
6421                                    EXCEPTION
6422                                      WHEN NO_DATA_FOUND THEN
6423                                      NULL;
6424                                    END;
6425 
6426                                       IF l_exists = 'Y' THEN
6427 
6428 
6429                                          -- Call reversal API
6430                                          Process_Adjustments(p_record_type               => 'PO_RECEIPT_TAX',
6431                                             p_document_header_id  => l_po_head_id_tbl(i),/*Added this for 6945767 */
6432                                             p_document_distribution_id  => l_parent_rcv_id_tbl(i),
6433                                             p_current_index             => i,
6434                                             p_last_index                => j);
6435 
6436                                         -- Set the create flag for adjustment records
6437                                            IF l_insert_flag_tbl(i) = 'A' THEN
6438                                             l_create_adj_recs := 'Y';
6439                                            END IF;
6440 
6441 
6442                                       END IF;
6443 
6444                                 END IF ; -- l_primary_quantity  = l_quantity
6445                             IF ( l_dest_typ_code_tbl(i) = 'RECEIVING'  OR l_trx_type_tbl(i) = 'RETURN TO RECEIVING' ) THEN
6446                               l_denom_cost := -l_entered_nr_tax_tbl(i);
6447                               l_acct_cost  := -l_accounted_nr_tax_tbl(i);
6448                               l_quantity   := -l_quantity_tbl(i);
6449                            ELSE
6450                               l_denom_cost := l_entered_nr_tax_tbl(i);
6451                               l_acct_cost  := l_accounted_nr_tax_tbl(i);
6452                               l_quantity   := l_quantity_tbl(i);
6453                            END IF;
6454 
6455                        EXCEPTION
6456                           WHEN NO_DATA_FOUND THEN
6457                                 NULL;
6458                           WHEN OTHERS THEN
6459                                RAISE ;
6460                        END ;
6461 
6462                 END IF;
6463 
6464                IF l_quantity = 0 THEN   /*for amount based POs setting the pa quantity to be the same as the transaction cost*/
6465                    l_quantity := l_denom_cost;
6466                END IF;
6467 
6468             END IF; /* tax column is zero */
6469 
6470          END IF; /* pa_add_flag O or J*/
6471 
6472          write_log(LOG, 'This is a record type of: '||l_record_type||
6473                         'denom cost for receipt amount:'||l_denom_cost||
6474                         'acct cost:'||l_acct_cost||'quantity is:'||l_quantity);
6475 
6476          l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
6477          l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
6478          l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
6479 
6480          l_record_type_tbl(i)     := l_record_type;
6481          l_denom_raw_cost_tbl(i)  := l_denom_cost;
6482          l_acct_raw_cost_tbl(i)   := l_acct_cost;
6483 
6484          IF l_exp_cst_rt_flg_tbl(i) = 'Y' THEN --Exp Cost Rate Required = Y, stamp the quantity. Bug#5138396.
6485             l_quantity_tbl(i)        := l_quantity;
6486          ELSE
6487             l_quantity_tbl(i)        := l_denom_cost;
6488          END IF;
6489 
6490          IF l_insert_flag_tbl(i) IS NULL THEN
6491             l_insert_flag_tbl(i)     := 'Y';
6492          END IF;
6493 
6494            -- FC Doc Type
6495             IF l_fc_enabled_tbl(i) = 'N' THEN
6496              l_fc_document_type_tbl(i) := 'NOT';
6497             END IF;
6498 
6499          write_log(LOG, 'The value for Insert Flag : '||l_insert_flag_tbl(i)  );
6500 
6501          IF (G_TRANS_DFF_PO = 'Y') THEN
6502 
6503                 v_attribute_category := l_attribute_cat_tbl(i);
6504                 v_attribute1 := l_attribute1_tbl(i);
6505                 v_attribute2 := l_attribute2_tbl(i);
6506                 v_attribute3 := l_attribute3_tbl(i);
6507                 v_attribute4 := l_attribute4_tbl(i);
6508                 v_attribute5 := l_attribute5_tbl(i);
6509                 v_attribute6 := l_attribute6_tbl(i);
6510                 v_attribute7 := l_attribute7_tbl(i);
6511                 v_attribute8 := l_attribute8_tbl(i);
6512                 v_attribute9 := l_attribute9_tbl(i);
6513                 v_attribute10 := l_attribute10_tbl(i);
6514 
6515                 v_dff_map_status := NULL;
6516 
6517                 G_err_stage:='Calling PA_CLINET_EXTN_DFFTRANS to map DFF fields';
6518                 write_log(LOG,   G_err_stage);
6519 
6520                 PA_CLIENT_EXTN_DFFTRANS.DFF_map_segments_PA_and_AP(
6521                    p_calling_module            => 'PAAPIMP',
6522                    p_trx_ref_1                 => l_po_dist_id_tbl(i),
6523                    p_trx_ref_2                 => l_rcv_txn_id_tbl(i),
6524                    p_trx_type                  => l_dest_typ_code_tbl(i),
6525                    p_system_linkage_function   => 'VI',
6526                    p_submodule                 => NULL,
6527                    p_expenditure_type          => l_exp_type_tbl(i),
6528                    p_set_of_books_id           => G_PO_SOB,
6529                    p_org_id                    => l_org_id_tbl(i),
6530                    p_attribute_category        => v_attribute_category,
6531                    p_attribute_1               => v_attribute1,
6532                    p_attribute_2               => v_attribute2,
6533                    p_attribute_3               => v_attribute3,
6534                    p_attribute_4               => v_attribute4,
6535                    p_attribute_5               => v_attribute5,
6536                    p_attribute_6               => v_attribute6,
6537                    p_attribute_7               => v_attribute7,
6538                    p_attribute_8               => v_attribute8,
6539                    p_attribute_9               => v_attribute9,
6540                    p_attribute_10              => v_attribute10,
6541                    x_status_code               => v_dff_map_status);
6542 
6543                    IF (v_dff_map_status IS NOT NULL) THEN
6544 
6545                        G_err_stage := ('Error in DFF_map_segments_PA_and_AP, Error Code: ' || v_dff_map_status);
6546                        write_log(LOG,   G_err_stage);
6547                        raise dff_map_exception;
6548 
6549                    END IF;
6550 
6551                    l_attribute_cat_tbl(i) := v_attribute_category;
6552                    l_attribute1_tbl(i) := v_attribute1;
6553                    l_attribute2_tbl(i) := v_attribute2;
6554                    l_attribute3_tbl(i) := v_attribute3;
6555                    l_attribute4_tbl(i) := v_attribute4;
6556                    l_attribute5_tbl(i) := v_attribute5;
6557                    l_attribute6_tbl(i) := v_attribute6;
6558                    l_attribute7_tbl(i) := v_attribute7;
6559                    l_attribute8_tbl(i) := v_attribute8;
6560                    l_attribute9_tbl(i) := v_attribute9;
6561                    l_attribute10_tbl(i) := v_attribute10;
6562 
6563 	   ElSE /* if DFF profile is No. Added for Bug 3105153*/
6564                    l_attribute_cat_tbl(i) := NULL;     --Bug#3856390
6565                    l_attribute1_tbl(i) := NULL;
6566                    l_attribute2_tbl(i) := NULL;
6567                    l_attribute3_tbl(i) := NULL;
6568                    l_attribute4_tbl(i) := NULL;
6569                    l_attribute5_tbl(i) := NULL;
6570                    l_attribute6_tbl(i) := NULL;
6571                    l_attribute7_tbl(i) := NULL;
6572                    l_attribute8_tbl(i) := NULL;
6573                    l_attribute9_tbl(i) := NULL;
6574                    l_attribute10_tbl(i) := NULL;
6575 
6576            END IF; /* if DFF profile is Yes */
6577 
6578       END LOOP; /* End of looping through each record in plsql table */
6579 
6580    -- Update to set all the transactions that got interfaced through AP to 'G'
6581     FORALL i IN  l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST
6582          UPDATE rcv_receiving_sub_ledger rcv_sub
6583             SET rcv_sub.pa_addition_flag          = decode(l_pa_add_flag_tbl(i),'G','G',pa_addition_flag)
6584           WHERE rcv_sub.rcv_transaction_id        = l_rcv_txn_id_tbl(i)
6585             AND rcv_sub.pa_addition_flag = 'O'
6586             AND  l_insert_flag_tbl(i) = 'N' ;
6587 
6588    EXCEPTION
6589       WHEN OTHERS THEN
6590           write_log(LOG,'Failed during process_receipt_logic for receipt processing');
6591           G_err_code   := SQLCODE;
6592           raise;
6593    END process_receipt_logic;
6594 
6595    PROCEDURE process_receipt_tax_logic IS
6596 
6597      l_status4    VARCHAR2(10);
6598      l_evt_typ_name VARCHAR2(30); -- pricing changes
6599      j NUMBER := 0; --Index variable for creating reversal EI's --NEW
6600 
6601    BEGIN
6602 
6603       /* This procedure is only called after process_receipt_logic. ONLY the records
6604          with pa_addition_flag of 'O' AND the record type of receipt would be
6605          processed here. The reason for this is because when pa_addition_flag is updated
6606          to 'O', it means we need to split the receipt into the receipt amount and the tax
6607          amount. Since we call a bulk insert after calling  process_receipt_logic then
6608          it means the receipt without tax portion should have been inserted into the
6609          txn interface table. The only part that we should now process are the tax portion
6610          of these records. Thus, we will only process these records and nothing else */
6611 
6612       /* Additional Note: Most of the values already stored in the plsql table for these records
6613          can be reused except for the amount columns. Other columns like bus_group_id and DFF
6614          fields are the same for either the receipt amount or just the tax amount */
6615 
6616       G_err_stage:= 'Within process_receipt_logic';
6617       write_log(LOG,   G_err_stage);
6618 
6619       FOR i IN l_rcv_txn_id_tbl.FIRST..l_rcv_txn_id_tbl.LAST LOOP
6620 
6621          j := l_rcv_txn_id_tbl.LAST;  -- initialize j to the total rcv trans retrieved in the PLSQL array
6622 
6623          IF (l_pa_add_flag_tbl(i) = 'J' OR l_record_type_tbl(i) not in ('RECEIPT','RCVTAX')) THEN
6624 
6625             l_insert_flag_tbl(i) := 'N';
6626 
6627          ELSIF (l_pa_add_flag_tbl(i)       = 'O'       AND
6628                 l_record_type_tbl(i)   = 'RECEIPT' AND
6629                 l_entered_nr_tax_tbl(i) = 0
6630                ) THEN
6631 
6632                 l_insert_flag_tbl(i) := 'N';
6633 
6634          ELSIF (l_pa_add_flag_tbl(i)       = 'O'       AND
6635                 l_record_type_tbl(i)   = 'RECEIPT' AND
6636                 l_entered_nr_tax_tbl(i) <> 0
6637                ) THEN
6638 
6639                v_num_receipt_tax_processed := v_num_receipt_tax_processed + 1;
6640 
6641                G_err_stage := 'Calling lock_ap_invoice within process_receipt_tax_logic';
6642                write_log(LOG,   G_err_stage);
6643 
6644                lock_ap_invoice(l_po_dist_id_tbl(i));
6645 
6646                l_record_type := 'RECEIPT TAX';
6647 
6648                l_insert_flag_tbl(i)     := 'Y';
6649 
6650                IF (l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) NOT IN ( 'RETURN TO RECEIVING','CORRECT')) THEN
6651 
6652                   l_denom_cost := l_entered_nr_tax_tbl(i);
6653                   l_acct_cost  := l_accounted_nr_tax_tbl(i);
6654                   l_quantity   := l_quantity_tbl(i);
6655 
6656                ELSIF ((l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i)  IN ('CORRECT', 'RETURN TO RECEIVING')) OR
6657                        ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
6658                                                                                         'RETURN TO RECEIVING' ))) THEN
6659                       --
6660                       -- Check if the correction is a complete correction
6661                       --
6662                       DECLARE
6663                          l_primary_quantity     NUMBER;
6664                          l_amount               NUMBER;
6665                          l_exists               VARCHAR2(1);
6666                       BEGIN
6667 
6668                             SELECT primary_quantity, nvl(amount,0)
6669                               INTO l_primary_quantity, l_amount
6670                               FROM rcv_transactions
6671                              WHERE transaction_id = l_parent_rcv_id_tbl(i) ;
6672 
6673                                 -- Added a new variable l_po_tax_qty_tbl which will store the original po qty since the l_quantity_tbl
6674                                 -- variable gets overwritten by the raw cost
6675 
6676                                 IF ((( ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = l_po_tax_qty_tbl(i)) OR --bug5465098
6677                                       ( l_amount = l_amount_tbl(i)))   AND
6678                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'RETURN TO RECEIVING') OR
6679                                         ( l_dest_typ_code_tbl(i) = 'RECEIVING'  AND l_trx_type_tbl(i) in('RETURN TO VENDOR',
6680                                                                                                          'RETURN TO RECEIVING' )))) OR
6681                                     ((  ( l_quantity_tbl(i) <> 0 AND l_primary_quantity  = -l_po_tax_qty_tbl(i)) OR
6682                                       ( l_amount = l_amount_tbl(i)))   AND
6683                                        (( l_dest_typ_code_tbl(i) = 'EXPENSE' AND l_trx_type_tbl(i) = 'CORRECT')))) THEN
6684 
6685                                   -- Check if the parent has been interfaced to Projects.
6686 
6687                                      SELECT 'Y'
6688                                        INTO l_exists
6689                                        FROM dual
6690                                       WHERE EXISTS (
6691                                                    SELECT pa_addition_flag
6692                                                      FROM rcv_receiving_sub_ledger
6693                                                     WHERE rcv_transaction_id = l_parent_rcv_id_tbl(i)
6694                                                       AND pa_addition_flag in ('Y','I')) ;
6695 
6696                    -- Should we call this api at all? This api processes the records
6697                     --  where the pa_addition_flag is 'O'- the ones that got processed in
6698                     --  process_receipt_logic api.
6699                                       IF l_exists = 'Y' THEN
6700 
6701                                         -- Set the parent record attributes for adjustment record to copy
6702 		                        l_txn_src_tbl(i)         := G_RCVTAX_TRANSACTION_SOURCE;
6703                            		l_user_txn_src_tbl(i)    := G_RCVTAX_USER_TRX_SOURCE;
6704                                         l_batch_name_tbl(i)      := G_RCVTAX_BATCH_NAME;
6705                                         l_interface_id_tbl(i)    := G_RCVNRT_INTERFACE_ID;
6706 
6707                        -- This api call may not be necessary. Need to verify.
6708                                          -- Call reversal API
6709                          Process_Adjustments(p_record_type               => 'PO_RECEIPT_TAX',
6710                                              p_document_header_id  => l_po_head_id_tbl(i),/*Added this for 6945767 */
6711                                              p_document_distribution_id  => l_parent_rcv_id_tbl(i),
6712                                              p_current_index             => i,
6713                                              p_last_index                => j);
6714 
6715                                         -- Set the create flag for adjustment records
6716                                            IF l_insert_flag_tbl(i) = 'A' THEN
6717                                             l_create_adj_recs := 'Y';
6718                                            END IF;
6719 
6720                                       END IF ;
6721                                 END IF ; -- primary_quantity  = l_quantity
6722 
6723 
6724                             IF ( l_dest_typ_code_tbl(i) = 'RECEIVING'  OR l_trx_type_tbl(i) = 'RETURN TO RECEIVING' ) THEN
6725                               l_denom_cost := -l_entered_nr_tax_tbl(i);
6726                               l_acct_cost  := -l_accounted_nr_tax_tbl(i);
6727                               l_quantity   := -l_quantity_tbl(i);
6728                            ELSE
6729                               l_denom_cost := l_entered_nr_tax_tbl(i);
6730                               l_acct_cost  := l_accounted_nr_tax_tbl(i);
6731                               l_quantity   := l_quantity_tbl(i);
6732                            END IF;
6733 
6734                        EXCEPTION
6735                           WHEN NO_DATA_FOUND THEN
6736                                 NULL;
6737 
6738                           WHEN OTHERS THEN
6739                                RAISE ;
6740                        END ;
6741 
6742                END IF;
6743 
6744                IF l_quantity = 0 THEN   /* bug 3496492 */
6745                    l_quantity := l_denom_cost;
6746                END IF;
6747 
6748                write_log(LOG, 'This is a record type of: '||l_record_type||
6749                         'denom cost for receipt amount:'||l_denom_cost||
6750                         'acct cost:'||l_acct_cost||'quantity is:'||l_quantity);
6751 
6752                l_record_type_tbl(i)     := l_record_type;
6753                l_denom_raw_cost_tbl(i)  := l_denom_cost;
6754                l_acct_raw_cost_tbl(i)   := l_acct_cost;
6755                l_quantity_tbl(i)        := l_quantity;
6756 
6757                l_txn_status_code_tbl(i) := 'P';
6758                l_txn_rej_code_tbl(i)    := '';
6759 
6760 -- pricing changes start
6761 	       IF (l_rcv_acct_evt_id_tbl(i) is NULL) THEN    /* bug 3475571 */
6762 
6763 		l_txn_src_tbl(i)         := G_RCVTAX_TRANSACTION_SOURCE;
6764 		l_user_txn_src_tbl(i)    := G_RCVTAX_USER_TRX_SOURCE;
6765 	       ELSE
6766 
6767 		SELECT event_type_name
6768 		INTO l_evt_typ_name
6769 		FROM rcv_accounting_event_types rcv_acct_evt_typ, rcv_accounting_events rcv_acct_evts
6770 		WHERE rcv_acct_evt_typ.event_type_id = rcv_acct_evts.event_type_id
6771 		AND rcv_acct_evts.accounting_event_id = l_rcv_acct_evt_id_tbl(i);
6772 
6773 		IF (l_evt_typ_name in ('ADJUST_DELIVER','ADJUST_RECEIVE')) THEN
6774 			l_txn_src_tbl(i)         := G_RCVTAX_PRC_ADJ_TRX_SRC;
6775 			l_user_txn_src_tbl(i)    := G_RCVTAX_PRC_ADJ_USER_TRX_SRC;
6776                         l_quantity               := 0;
6777                         l_quantity_tbl(i)        := l_quantity;
6778 		ELSE
6779 			l_txn_src_tbl(i)         := G_RCVTAX_TRANSACTION_SOURCE;
6780 			l_user_txn_src_tbl(i)    := G_RCVTAX_USER_TRX_SOURCE;
6781 		END IF;
6782 
6783 	       END IF;
6784 -- pricing changes end
6785                l_batch_name_tbl(i)      := G_RCVTAX_BATCH_NAME;
6786                l_interface_id_tbl(i)    := G_RCVNRT_INTERFACE_ID;
6787 
6788               -- FC Doc Type
6789                IF l_fc_enabled_tbl(i) = 'N' THEN
6790                 l_fc_document_type_tbl(i) := 'NOT';
6791                END IF;
6792 
6793          END IF; /* pa_add_flag is O or J */
6794 
6795          IF l_exp_cst_rt_flg_tbl(i) = 'Y' THEN --Exp Cost Rate Required = Y, stamp the quantity. Bug#5138396.
6796             l_quantity_tbl(i)        := l_quantity;
6797          ELSE
6798             l_quantity_tbl(i)        := l_denom_cost;
6799          END IF;
6800 
6801       END LOOP;
6802 
6803    EXCEPTION
6804       WHEN OTHERS THEN
6805           write_log(LOG,'Failed during process_receipt_tax_logic for receipt processing');
6806           G_err_code   := SQLCODE;
6807           raise;
6808    END process_receipt_tax_logic;
6809 
6810    BEGIN
6811 
6812       G_err_stage := 'Entering main logic of transfer_receipts_to_pa';
6813       write_log(LOG, G_err_stage);
6814 
6815       /*Call get_mrc_flag function to see if MRC is set up*/
6816 
6817       --G_DO_MRC_FLAG := get_mrc_flag();
6818       --write_log(LOG, '......Result of get_mrc_flag: ' || G_DO_MRC_FLAG);
6819 
6820       v_max_size := nvl(G_COMMIT_SIZE,200);
6821 
6822       G_err_stage:='Opening Receipt Cursor';
6823       write_log(LOG,   G_err_stage);
6824 
6825       G_RCV_TRANSACTION_SOURCE      := 'PO RECEIPT';
6826       G_RCV_USER_TRANSACTION_SOURCE := 'Oracle Purchasing Receipt Accruals';
6827       G_RCVTAX_TRANSACTION_SOURCE   := 'PO RECEIPT NRTAX';
6828       G_RCVTAX_USER_TRX_SOURCE      := 'Non-Recoverable Tax from Purchasing Receipts';
6829 
6830 --pricing changes
6831       G_RCV_PRC_ADJ_TRX_SRC      := 'PO RECEIPT PRICE ADJ';
6832       G_RCV_PRC_ADJ_USER_TRX_SRC := 'Oracle Purchasing Receipt Accrual Price Adjustments';
6833       G_RCVTAX_PRC_ADJ_TRX_SRC   := 'PO RECEIPT NRTAX PRICE ADJ';
6834       G_RCVTAX_PRC_ADJ_USER_TRX_SRC      := 'Non-Recoverable Tax Price Adjustments from Purchasing Receipts';
6835 
6836       OPEN Rcv_Receipts_Cur;
6837 
6838       WHILE (v_all_done = 0) LOOP
6839 
6840          write_log(LOG,'Receipt cursor is opened. Looping through batches.');
6841 
6842          clear_plsql_tables;
6843 
6844          G_err_stage := 'CREATING NEW INTERFACE ID';
6845          write_log(LOG,   G_err_stage);
6846          SELECT pa_interface_id_s.nextval
6847            INTO G_RCV_INTERFACE_ID FROM dual;
6848 
6849          SELECT pa_interface_id_s.nextval
6850            INTO G_RCVNRT_INTERFACE_ID FROM dual;
6851 
6852          G_err_stage:='Fetching Receipts Cursor';
6853          write_log(LOG,   G_err_stage);
6854 
6855          FETCH Rcv_Receipts_cur BULK COLLECT INTO
6856                l_rcv_txn_id_tbl,
6857                l_po_dist_id_tbl,
6858                l_po_head_id_tbl,
6859                l_po_num_tbl,
6860                l_quantity_tbl,
6861                l_po_tax_qty_tbl,
6862                l_entered_dr_tbl,
6863                l_entered_cr_tbl,
6864                l_accounted_dr_tbl,
6865                l_accounted_cr_tbl,
6866                l_entered_nr_tax_tbl,
6867                l_accounted_nr_tax_tbl,
6868                l_denom_raw_cost_tbl,
6869                l_acct_raw_cost_tbl,
6870                l_record_type_tbl,
6871                l_dist_cc_id_tbl,
6872                l_denom_cur_code_tbl,
6873                l_acct_rate_date_tbl,
6874                l_acct_rate_type_tbl,
6875                l_acct_exch_rate_tbl,
6876                l_gl_date_tbl,
6877                l_dest_typ_code_tbl,
6878                l_pa_add_flag_tbl,
6879                l_trx_type_tbl,
6880                l_project_id_tbl,
6881                l_task_id_tbl,
6882                l_employee_id_tbl,
6883                l_exp_type_tbl,
6884                l_ei_date_tbl,
6885                l_vendor_id_tbl,
6886                l_exp_org_id_tbl,
6887                l_job_id_tbl,
6888                l_description_tbl,
6889                l_attribute_cat_tbl,
6890                l_attribute1_tbl,
6891                l_attribute2_tbl,
6892                l_attribute3_tbl,
6893                l_attribute4_tbl,
6894                l_attribute5_tbl,
6895                l_attribute6_tbl,
6896                l_attribute7_tbl,
6897                l_attribute8_tbl,
6898                l_attribute9_tbl,
6899                l_attribute10_tbl,
6900                l_org_id_tbl,
6901                l_cdl_sys_ref4_tbl,
6902                l_txn_src_tbl,
6903                l_user_txn_src_tbl,
6904                l_batch_name_tbl,
6905                l_interface_id_tbl,
6906                l_exp_end_date_tbl,
6907                l_txn_status_code_tbl,
6908                l_txn_rej_code_tbl,
6909                l_bus_grp_id_tbl,
6910                l_insert_flag_tbl,
6911 	       l_rcv_acct_evt_id_tbl, -- pricing changes
6912 	       l_rcv_acct_rec_tax_tbl,
6913 	       l_rcv_ent_rec_tax_tbl,
6914                l_parent_rcv_id_tbl, --NEW
6915                l_net_zero_flag_tbl, -- NEW
6916                l_sc_xfer_code_tbl,
6917                l_amount_tbl,
6918                l_adj_exp_item_id_tbl,
6919                l_fc_enabled_tbl,
6920                l_mrc_exchange_date_tbl,
6921                l_fc_document_type_tbl,
6922                l_si_assts_add_flg_tbl,
6923                l_insert_flag_tbl,
6924                l_rcv_sub_ledger_id_tbl,
6925                l_exp_cst_rt_flg_tbl
6926          LIMIT v_max_size;
6927 
6928          IF l_rcv_txn_id_tbl.COUNT <> 0 THEN
6929 
6930            /*Start by processing the receipt minus tax records or just the tax record.
6931              Explanation:
6932              The Receipt Cursor picks up both records that have  pa_addition_flag updated
6933              to either 'O' or 'J'. for the ones updated 'O', it means we need to split up
6934              the record into receipt minus tax portion and just the tax portion. The call
6935              to process_receipt_logic will insert only the receipt total minus tax portion.
6936              For records updated to 'J', we will only pull the nr_tax portion and insert
6937              into transaction_interface_all table for processing */
6938 
6939              G_err_stage:='Begin processing just the receipt records';
6940              write_log(LOG,   G_err_stage);
6941 
6942              v_last_rcv_index := l_rcv_txn_id_tbl.LAST;
6943 
6944              process_receipt_logic;
6945 
6946              bulk_insert_trx_intf;
6947 
6948             /* The process_receipt_tax_logic applies only to those records that have been updated
6949              to 'O'. After having the total receipt amount minus tax being inserted into txn
6950              interface table, we need to insert the tax portion of these records by calling
6951              process_receipt_tax_logic. The records that have been updated to 'J' would not be
6952              processed here because the tax amount was taken cared of in proceess_receipt_logic
6953              above.
6954             */
6955 
6956             G_err_stage:='Begin processing receipt tax records';
6957             write_log(LOG,   G_err_stage);
6958 
6959             process_receipt_tax_logic;
6960 
6961             bulk_insert_trx_intf;
6962 
6963             IF v_total_num_receipts > 0 THEN
6964 
6965                IF v_num_receipts_processed > 0 THEN
6966 
6967                   G_err_stage:='Calling trx import for receipts with interface_id:  '||G_RCV_INTERFACE_ID;
6968                   write_log(LOG,   G_err_stage);
6969 
6970 --pricing changes
6971 -- calling import for both transaction sources
6972 
6973  		  trans_import(G_RCV_TRANSACTION_SOURCE, G_RCV_BATCH_NAME,
6974                                G_RCV_INTERFACE_ID, G_USER_ID);
6975 		  trans_import(G_RCV_PRC_ADJ_TRX_SRC, G_RCV_BATCH_NAME,
6976                                G_RCV_INTERFACE_ID, G_USER_ID);
6977 
6978 
6979                   G_err_stage:='After trx import for receipts, check for failed receipts';
6980                   write_log(LOG,   G_err_stage);
6981                   check_failed_receipts(G_RCV_BATCH_NAME, G_RCV_INTERFACE_ID);
6982 
6983                END IF;
6984 
6985                IF v_num_receipt_tax_processed > 0 THEN
6986 
6987                   G_err_stage:='Calling trx import for receipt tax with interface_id:  '||G_RCVNRT_INTERFACE_ID;
6988                   write_log(LOG,   G_err_stage);
6989 --pricing changes
6990 -- calling import for both transaction sources
6991 
6992                   trans_import(G_RCVTAX_TRANSACTION_SOURCE, G_RCVTAX_BATCH_NAME,
6993                                G_RCVNRT_INTERFACE_ID,G_USER_ID);
6994 
6995                   trans_import(G_RCVTAX_PRC_ADJ_TRX_SRC, G_RCVTAX_BATCH_NAME,
6996                                G_RCVNRT_INTERFACE_ID,G_USER_ID);
6997 
6998                END IF;
6999 
7000                G_err_stage:='Calling tieback for receipts';
7001                write_log(LOG,   G_err_stage);
7002                tieback_rcv_Txn(G_RCV_TRANSACTION_SOURCE,G_RCV_BATCH_NAME,
7003                                G_RCV_INTERFACE_ID);
7004 --pricing changes
7005 -- calling tieback for both transaction sources
7006                tieback_rcv_Txn(G_RCV_PRC_ADJ_TRX_SRC,G_RCV_BATCH_NAME,
7007                                G_RCV_INTERFACE_ID);
7008 
7009                G_err_stage:='Calling tieback for receipt tax';
7010                write_log(LOG,   G_err_stage);
7011 
7012                tieback_RCV_Txn(G_RCVTAX_TRANSACTION_SOURCE, G_RCVTAX_BATCH_NAME,
7013                                G_RCVNRT_INTERFACE_ID);
7014 --pricing changes
7015 -- calling tieback for both transaction sources
7016                tieback_RCV_Txn(G_RCVTAX_PRC_ADJ_TRX_SRC, G_RCVTAX_BATCH_NAME,
7017                                G_RCVNRT_INTERFACE_ID);
7018 
7019                write_log(LOG, 'After tying back rcv tax, before calling COMMIT');
7020 
7021                tieback_locked_invoice;
7022                /** 3922679 removed intermediate commit
7023                COMMIT;
7024                3922679 End */
7025 
7026                G_NUM_BATCHES_PROCESSED := G_NUM_BATCHES_PROCESSED + 1;
7027                G_NUM_RCV_TXN_PROCESSED := G_NUM_RCV_TXN_PROCESSED + v_num_receipts_processed;
7028                G_NUM_RCVTAX_PROCESSED  := G_NUM_RCVTAX_PROCESSED  + v_num_receipt_tax_processed;
7029 
7030             END IF; /* v_totabl_num_receipts > 0 */
7031 
7032             clear_plsql_tables;
7033 
7034          ELSE
7035 
7036             G_err_stage := 'plsql table for receipts is empty. Exiting';
7037             write_log(LOG, G_err_stage);
7038 
7039             EXIT; /* Exit if l_rcv_txn_id_tbl.COUNT = 0 */
7040 
7041          END IF; /* l_rcv_txn_id_tbl.COUNT = 0 */
7042 
7043          v_total_num_receipts         := 0;
7044          v_num_receipts_processed     := 0;
7045          v_num_receipt_tax_processed  := 0;
7046 
7047          EXIT WHEN Rcv_Receipts_Cur%NOTFOUND;
7048 
7049       END LOOP; /* While v_all_done = 0 */
7050 
7051       G_err_stage := 'Closing Receipts cursor';
7052       write_log(LOG, G_err_stage);
7053 
7054       CLOSE Rcv_Receipts_cur;
7055 
7056 EXCEPTION
7057     WHEN OTHERS THEN
7058 
7059          G_err_stack := v_old_stack;
7060          IF Rcv_Receipts_Cur%ISOPEN THEN
7061            CLOSE Rcv_Receipts_Cur;
7062          END IF ;
7063 
7064          G_err_code := SQLCODE;
7065          RAISE;
7066 
7067 END transfer_receipts_to_pa;
7068 
7069 PROCEDURE tieback_rcv_Txn (
7070    p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
7071    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
7072    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
7073 
7074    l_pa_addflag             VARCHAR2(1):=NULL;
7075    l_rows_tiebacked         NUMBER :=0;
7076 
7077    l_sys_ref1_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
7078    l_sys_ref2_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
7079    l_sys_ref3_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
7080    l_sys_ref4_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
7081    l_txn_src_tbl            PA_PLSQL_DATATYPES.Char30TabTyp;
7082    l_batch_name_tbl         PA_PLSQL_DATATYPES.Char50TabTyp;
7083    l_interface_id_tbl       PA_PLSQL_DATATYPES.IdTabTyp;
7084    l_txn_status_code_tbl    PA_PLSQL_DATATYPES.Char2TabTyp;
7085    l_project_id_tbl            PA_PLSQL_DATATYPES.IdTabTyp;
7086    l_pa_addflag_tbl         PA_PLSQL_DATATYPES.CHAR1TabTyp;
7087    l_rcv_acct_evt_id_tbl        PA_PLSQL_DATATYPES.IdTabTyp; -- pricing changes
7088    l_dr_ccid_tbl		PA_PLSQL_DATATYPES.IdTabTyp; -- pricing changes
7089 
7090    CURSOR txn_intf_rec (p_txn_src       IN VARCHAR2,
7091                         p_batch_name    IN VARCHAR2,
7092                         p_interface_id  IN NUMBER) IS
7093       SELECT cdl_system_reference1
7094             ,cdl_system_reference2
7095             ,cdl_system_reference3
7096             ,cdl_system_reference4
7097             ,transaction_source
7098             ,batch_name
7099             ,interface_id
7100             ,transaction_status_code
7101             ,project_id
7102             ,l_pa_addflag
7103 	    ,orig_exp_txn_reference2 -- pricing changes
7104 	    ,dr_code_combination_id
7105         FROM pa_transaction_interface_all txnintf
7106        WHERE txnintf.transaction_source = p_txn_src
7107          AND txnintf.batch_name         = p_batch_name
7108          AND txnintf.interface_id       = p_interface_id;
7109 
7110   PROCEDURE clear_plsql_tables IS
7111 
7112       v_status   VARCHAR2(15);
7113 
7114    BEGIN
7115 
7116       G_err_stage:='Clearing PLSQL tables in RCV transactions tieback';
7117       write_log(LOG,   G_err_stage);
7118 
7119       l_sys_ref1_tbl.delete;
7120       l_sys_ref2_tbl.delete;
7121       l_sys_ref3_tbl.delete;
7122       l_sys_ref4_tbl.delete;
7123       l_txn_src_tbl.delete;
7124       l_batch_name_tbl.delete;
7125       l_interface_id_tbl.delete;
7126       l_txn_status_code_tbl.delete;
7127       l_project_id_tbl.delete;
7128       l_pa_addflag_tbl.delete;
7129       l_rcv_acct_evt_id_tbl.delete; -- pricing changes
7130       l_dr_ccid_tbl.delete;
7131 
7132    END clear_plsql_tables;
7133 
7134    PROCEDURE process_tieback IS
7135 
7136       v_status   VARCHAR2(15);
7137 
7138    BEGIN
7139 
7140       G_err_stage:='Within process_tieback of RCV Transactions tieback';
7141       write_log(LOG,   G_err_stage);
7142 
7143       FOR i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST LOOP
7144 
7145          /* If transaction import stamps the record to be 'A' then
7146             update pa_addition_flag of RCV transactions to 'Y'.
7147             If transaction import leaves the record to be 'P' then
7148             update pa_addition_flag of RCV transactions to 'N' or 'I'.
7149             If transaction import stamps the record to be 'R' then
7150             update pa_addition_flag of RCV transactions to 'N' or 'I'.*/
7151 
7152          write_log(LOG,'Tying back transaction ID: '||l_sys_ref4_tbl(i)||
7153                        'trc src:   '||l_txn_src_tbl(i));
7154 
7155          IF l_txn_src_tbl(i) IN ('PO RECEIPT', 'PO RECEIPT PRICE ADJ') THEN
7156 
7157             IF l_txn_status_code_tbl(i) = 'A' THEN
7158                   l_pa_addflag_tbl(i) := 'Y';
7159             ELSIF l_txn_status_code_tbl(i) = 'P' THEN
7160                   l_pa_addflag_tbl(i) :='N';
7161             ELSIF l_txn_status_code_tbl(i) = 'R' THEN
7162                   l_pa_addflag_tbl(i) := 'N';
7163             END IF;
7164 
7165          ELSIF l_txn_src_tbl(i) IN ('PO RECEIPT NRTAX', 'PO RECEIPT NRTAX PRICE ADJ') THEN
7166 
7167             /* Transaction status code of T is a newly added status to
7168                denote that the corresponding receipt has been processed
7169                in the same request but got rejected. Therefore, the pa
7170                addition_flag of the corresponding receipt should be
7171                updated to N. If the status code is R then it should be
7172                updated to I such that the program can pick it up in the
7173                next run and interface ONLY the tax portion */
7174 
7175             IF l_txn_status_code_tbl(i) = 'A' THEN
7176                   l_pa_addflag_tbl(i) := 'Y';
7177             ELSIF l_txn_status_code_tbl(i) = 'T' THEN
7178                   l_pa_addflag_tbl(i) :='N';
7179             ELSIF l_txn_status_code_tbl(i) = 'R' THEN
7180                   l_pa_addflag_tbl(i) := 'I';
7181             END IF;
7182 
7183         END IF; /* checking txn source to be PO RECEIPT, PO RECEIPT PRICE ADJ,
7184 	         PO RECEIPT NRTAX, PO RECEIPT NRTAX PRICE ADJ */
7185 
7186       END LOOP;
7187 
7188    END process_tieback;
7189 
7190    PROCEDURE bulk_update_txn_intf IS
7191 
7192       v_status VARCHAR2(15);
7193 
7194    BEGIN
7195 
7196       G_err_stage:=('Within bulk update of RCV transactions tieback');
7197       write_log(LOG,   G_err_stage);
7198 
7199       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
7200 
7201       /* Code combination Id join is required so that the record whichw as earlier updated to X does nto get updated to Y */
7202 
7203          UPDATE rcv_receiving_sub_ledger rcv_sub -- pricing changes
7204             SET rcv_sub.pa_addition_flag              = l_pa_addflag_tbl(i)
7205           WHERE rcv_sub.rcv_transaction_id        = l_sys_ref4_tbl(i)
7206 	  AND (rcv_sub.accounting_event_id = l_rcv_acct_evt_id_tbl(i) OR rcv_sub.accounting_event_id IS NULL)
7207 	  AND rcv_sub.code_combination_id = l_dr_ccid_tbl(i)
7208            /* Start added for bug#6015451 */
7209 	AND EXISTS
7210             (SELECT 1 from rcv_transactions rcv_txn WHERE
7211               rcv_txn.transaction_id = l_sys_ref4_tbl(i)
7212               AND ( (rcv_txn.destination_type_code = 'EXPENSE' AND
7213 	            rcv_txn.transaction_type <> 'RETURN TO RECEIVING' AND rcv_sub.entered_dr is NOT NULL
7214 	            ) OR
7215 	          ((rcv_txn.destination_type_code = 'RECEIVING' OR
7216 	           rcv_txn.transaction_type = 'RETURN TO RECEIVING') AND rcv_sub.entered_cr is NOT NULL
7217                   )
7218                  )
7219              );
7220 		/* Ends added for bug#6015451 */
7221 
7222 
7223       l_rows_tiebacked := SQL%ROWCOUNT;
7224       write_log(LOG,'Number of RCV transactions tied back:  '||l_rows_tiebacked);
7225 
7226    EXCEPTION
7227       WHEN OTHERS THEN
7228          G_err_stage:= 'Failed during bulk update of RCV transactions tieback';
7229          write_log(LOG,   G_err_stage);
7230          G_err_code   := SQLCODE;
7231          raise;
7232 
7233    END bulk_update_txn_intf;
7234 
7235    BEGIN
7236 
7237       /* Main logic of tieback starts here */
7238       G_err_stage:='Within main logic of tieback';
7239       write_log(LOG,   G_err_stage);
7240 
7241       G_err_stage:='Opening txn_intf_rec';
7242       write_log(LOG,   G_err_stage);
7243 
7244       OPEN txn_intf_rec(p_transaction_source
7245                        ,p_batch_name
7246                        ,p_interface_id);
7247 
7248       G_err_stage:='Fetching txn_intf_rec';
7249       write_log(LOG,   G_err_stage);
7250 
7251       clear_plsql_tables;
7252 
7253       FETCH txn_intf_rec BULK COLLECT INTO
7254           l_sys_ref1_tbl
7255          ,l_sys_ref2_tbl
7256          ,l_sys_ref3_tbl
7257          ,l_sys_ref4_tbl
7258          ,l_txn_src_tbl
7259          ,l_batch_name_tbl
7260          ,l_interface_id_tbl
7261          ,l_txn_status_code_tbl
7262          ,l_project_id_tbl
7263          ,l_pa_addflag_tbl
7264 	 ,l_rcv_acct_evt_id_tbl
7265 	 ,l_dr_ccid_tbl;
7266 
7267       IF l_sys_ref1_tbl.COUNT <> 0 THEN
7268 
7269          process_tieback;
7270 
7271          bulk_update_txn_intf;
7272 
7273          clear_plsql_tables;
7274 
7275       END IF;
7276 
7277       CLOSE txn_intf_rec;
7278 
7279 EXCEPTION
7280 
7281   WHEN OTHERS THEN
7282      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
7283      G_err_code := SQLCODE;
7284      RAISE;
7285 
7286 END tieback_rcv_Txn;
7287 
7288 PROCEDURE check_failed_receipts (
7289    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
7290    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
7291 
7292    v_num_receipts_failed NUMBER:=0;
7293    v_po_head_id   VARCHAR2(35);
7294    v_po_dist_id   VARCHAR2(35);
7295    v_txn_id       VARCHAR2(35);
7296    v_acct_evt_id  NUMBER; -- pricing changes
7297 
7298    CURSOR Failed_Rec (p_batch_name   IN VARCHAR2,
7299                       p_interface_id IN NUMBER) IS
7300       SELECT cdl_system_reference2
7301             ,cdl_system_reference3
7302             ,cdl_system_reference4
7303 	    ,orig_exp_txn_reference2 -- pricing changes
7304        FROM pa_transaction_interface
7305       WHERE transaction_status_code = 'R'
7306         AND transaction_source      IN ('PO RECEIPT', 'PO RECEIPT PRICE ADJ')
7307         AND batch_name              = p_batch_name
7308         AND interface_id            = p_interface_id;
7309 
7310 BEGIN
7311 
7312    G_err_stage := 'Within calling check_failed_receipts';
7313    write_log(LOG, G_err_stage);
7314 
7315    write_log(LOG,'Checking for failed receipts for batch_name:  '||p_batch_name
7316                  ||'interface id:  '||p_interface_id);
7317 
7318    OPEN Failed_Rec(p_batch_name
7319                   ,p_interface_id);
7320 
7321    LOOP
7322 
7323       FETCH Failed_Rec INTO v_po_head_id
7324                            ,v_po_dist_id
7325                            ,v_txn_id
7326 			   ,v_acct_evt_id; -- pricing changes
7327       EXIT WHEN Failed_Rec%NOTFOUND;
7328 
7329       write_log(LOG,'Number of failed receipt fetched:  '||v_num_receipts_failed);
7330 
7331    /* Changed p_batch_name and p_interface_id to G_ globals.
7332       Cursor fetched the batch name and interface id for RECEIPT and not
7333       for NRTAX */
7334 
7335       write_log(LOG,'Batch Name and Interface Id is : '||G_RCVTAX_BATCH_NAME||'  '||G_UNIQUE_ID);
7336 
7337       UPDATE pa_transaction_interface_all
7338         SET transaction_status_code  = 'T'
7339         WHERE batch_name             =  G_RCVTAX_BATCH_NAME /* p_batch_name changed for #2912545 */
7340           AND interface_id           =  G_RCVNRT_INTERFACE_ID /* p_interface_id changed for #2912545 */
7341           AND transaction_source     = 'PO RECEIPT NRTAX' /* PO RECEIPT TAX. changed for #2912545 */
7342           AND cdl_system_reference2  = v_po_head_id
7343           AND cdl_system_reference3  = v_po_dist_id
7344           AND cdl_system_reference4  = v_txn_id;
7345 
7346 -- pricing changes
7347       UPDATE pa_transaction_interface_all
7348         SET transaction_status_code  = 'T'
7349         WHERE batch_name             =  G_RCVTAX_BATCH_NAME /* p_batch_name changed for #2912545 */
7350           AND interface_id           =  G_RCVNRT_INTERFACE_ID /* p_interface_id changed for #2912545 */
7351           AND transaction_source     = 'PO RECEIPT NRTAX PRICE ADJ' /* PO RECEIPT TAX. changed for #2912545 */
7352           AND cdl_system_reference2  = v_po_head_id
7353           AND cdl_system_reference3  = v_po_dist_id
7354           AND cdl_system_reference4  = v_txn_id
7355 	  AND orig_exp_txn_reference2 = v_acct_evt_id;
7356 
7357       v_num_receipts_failed := v_num_receipts_failed +  SQL%ROWCOUNT;
7358 
7359    END LOOP;
7360 
7361    write_log(LOG,'number of receipts failed: '||v_num_receipts_failed);
7362 
7363    CLOSE Failed_Rec;
7364 
7365 EXCEPTION
7366   WHEN OTHERS THEN
7367      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
7368      CLOSE Failed_Rec;
7369      G_err_code := SQLCODE;
7370      RAISE;
7371 
7372 END check_failed_receipts;
7373 
7374 PROCEDURE lock_ap_invoice (p_po_distribution_id IN ap_invoice_distributions.po_distribution_id%TYPE)  IS
7375 
7376   l_num_rows NUMBER;
7377 
7378 BEGIN
7379 
7380    G_err_stage := 'Within calling lock_ap_invoice';
7381    write_log(LOG, G_err_stage);
7382 
7383     UPDATE ap_invoice_distributions_all dist
7384        SET dist.pa_addition_flag   = 'L'
7385      WHERE dist.po_distribution_id = p_po_distribution_id
7386        AND dist.pa_addition_flag   = 'N';
7387 
7388     l_num_rows := SQL%ROWCOUNT;
7389 
7390     write_log(LOG,'number of ap invoices locked:'||l_num_rows);
7391 
7392 EXCEPTION
7393    WHEN NO_DATA_FOUND THEN
7394        NULL;
7395 
7396    WHEN OTHERS THEN
7397 
7398      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
7399      G_err_code := SQLCODE;
7400      RAISE;
7401 END lock_ap_invoice;
7402 
7403 PROCEDURE tieback_locked_invoice IS
7404 
7405   l_num_rows NUMBER;
7406 
7407 BEGIN
7408 
7409    G_err_stage := 'Within calling tieback_locked_invoice';
7410    write_log(LOG, G_err_stage);
7411 
7412    UPDATE ap_invoice_distributions_all dist
7413       SET dist.pa_addition_flag = 'N'
7414     WHERE dist.pa_addition_flag = 'L';
7415 
7416     l_num_rows := SQL%ROWCOUNT;
7417 
7418     write_log(LOG,'number of ap invoices unlocked:'||l_num_rows);
7419 
7420 EXCEPTION
7421    WHEN NO_DATA_FOUND THEN
7422       NULL;
7423 
7424    WHEN OTHERS THEN
7425 
7426      PA_TRX_IMPORT.Upd_PktSts_Fatal(G_REQUEST_ID);
7427      G_err_code := SQLCODE;
7428      RAISE;
7429 END tieback_locked_invoice;
7430 
7431 /*==========================================================================*/
7432 --The following section contains procedures for AP Invoice AMount Variance Processing
7433 
7434 --Function that increments the W count, and returns the same flag back.
7435 
7436 FUNCTION increment_W_count(W_flag IN VARCHAR2)
7437    RETURN VARCHAR2 IS
7438 BEGIN
7439    G_NUM_AP_VARIANCE_MARKED_W := G_NUM_AP_VARIANCE_MARKED_W + 1;
7440    RETURN W_flag;
7441 END;
7442 
7443 
7444 
7445 PROCEDURE mark_inv_var_paflag IS
7446 
7447    v_num_empty_lines    NUMBER;
7448 
7449 BEGIN
7450 
7451    G_err_stage:= 'Within mark_inv_var_paflag';
7452    write_log(LOG,   G_err_stage);
7453 
7454    G_err_stage:= 'Updating empty invoice amount varaince lines pa addtion flag to G or W';
7455    write_log(LOG,   G_err_stage);
7456 
7457 
7458    IF G_PROJECT_ID IS NOT NULL THEN
7459 
7460     --
7461     -- Update pa-addition-flag to 'G' for item and nrtax lines if the invoice is matched to PO/RCPT that is
7462     -- accrued-on-rcpt and the PO has never been interfaced as invoice, historically
7463     -- However, such Invoice lines that have amount variance will be marked as W so that these can be processed
7464     -- for relieving the variance commitment
7465     --
7466     -- In rel12, Receipt Accruals along with NRTAX will be interfaced into Projects only from Purchasing
7467     -- However Variance and other related costs like Freight/Misc will still be interfaced from Payables
7468     --
7469         If g_body_debug_mode = 'Y' Then
7470         write_log(LOG, 'Updating empty invoice variance lines pa addtion flag to G for a project');
7471         End if;
7472 
7473    UPDATE ap_invoice_distributions_all apdist
7474       SET apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
7475           request_id = G_REQUEST_ID,
7476           last_update_date=SYSDATE,
7477           last_updated_by=G_USER_ID,
7478           last_update_login= G_USER_ID,
7479           program_id= G_PROG_ID,
7480           program_application_id= G_PROG_APPL_ID,
7481           program_update_date=SYSDATE
7482     WHERE rowid IN (
7483           SELECT dist.rowid
7484           FROM  ap_invoices inv, ap_invoice_distributions_all dist
7485           WHERE inv.invoice_id = dist.invoice_id
7486           AND  (dist.line_type_lookup_code in ('ITEM','ACCRUAL','NONREC_TAX')
7487                 OR ( pa_nl_installed.is_nl_installed = 'Y'                 --EIB trackable items
7488                                  AND EXISTS (SELECT 'X'
7489                                               FROM  mtl_system_items si,
7490                                                     po_lines_all pol,
7491                                                     po_distributions_all po_dist1
7492                                               WHERE po_dist1.po_line_id = pol.po_line_id
7493                                               AND   po_dist1.po_distribution_id  = dist.po_distribution_id
7494                                               AND   si.inventory_item_id = pol.item_id
7495                                               AND   po_dist1.project_id IS NOT NULL
7496                                               AND   si.comms_nl_trackable_flag = 'Y'
7497 					      AND   si.organization_id = po_dist1.org_id)
7498                           )
7499                  ) --Bug#5399352. Added this here to take care of IPV/TIPV records matched to EIB item PO.
7500           AND   NOT EXISTS (SELECT NULL
7501                                      FROM ap_invoice_distributions_all apdist2
7502                                     WHERE apdist2.pa_addition_flag   = 'Y'
7503                                       AND apdist2.po_distribution_id = dist.po_distribution_id
7504                                       AND apdist2.line_type_lookup_code = dist.line_type_lookup_code
7505                                       AND apdist2.line_type_lookup_code in ('ITEM','ACCRUAL','NONREC_TAX')
7506                            )
7507           AND  (  EXISTS (SELECT NULL
7508                               FROM ap_invoice_distributions_all apdist1
7509                              WHERE apdist1.pa_addition_flag   IN ('F', 'G')
7510                                AND apdist1.po_distribution_id  = dist.po_distribution_id
7511                           )
7512                  OR EXISTS (  SELECT rcv_txn.po_distribution_id
7513                                 FROM rcv_transactions rcv_txn
7514                                    , rcv_receiving_sub_ledger rcv_sub
7515                                WHERE rcv_txn.po_distribution_id      = dist.po_distribution_id
7516                                  AND rcv_sub.pa_addition_flag || '' IN ('Y','I')
7517                                  AND rcv_sub.rcv_transaction_id      = rcv_txn.transaction_id
7518                            )
7519                  OR EXISTS (  SELECT  PO.po_distribution_id
7520                                 FROM  po_distributions PO
7521                                WHERE  PO.po_distribution_id = dist.po_distribution_id
7522                                  AND  nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'  -- bug 7192304, added nvl
7523                                  AND  PO.project_id  > 0
7524                                  AND  NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
7525                                  AND  PO.accrue_on_receipt_flag= 'Y'
7526                            )
7527                 )
7528           AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
7529           AND   nvl(INV.source, 'xx' ) NOT IN
7530                  ('Oracle Project Accounting','PA_IC_INVOICES')
7531           AND   dist.pa_addition_flag = 'N'
7532           AND   dist.posted_flag = 'Y'
7533           AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))
7534           AND   trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date))
7535           AND   dist.project_id = G_PROJECT_ID
7536           -- Process historical distributions for CAsh BAsed Accounting
7537           AND   (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
7538           AND   NVL(dist.po_distribution_id,0) > 0 );
7539 
7540           write_log(LOG,'Number of inv amount variance lines marked to G:  '||to_char(SQL%ROWCOUNT));
7541           write_log(LOG,'Number of inv amount variance lines marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W);
7542 
7543       /* If the Supplier Invoice is matched to period-end PO for Contingent worker labor fixed rate and the CWK timecard
7544          is to be processed as Labor cost, only non recoverable tax receipt lines, variances and other allocated costs should be
7545          pulled from Payables. The pa_addition_flag for such invoice ITEM distribution lines is updated to G to prevent
7546          further processing into Projects.
7547          However, if there is an amount variance on such invoice, it needs to be processed as W to releive variance commitment  */
7548 
7549            UPDATE ap_invoice_distributions_all apdist
7550            SET    apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
7551                   request_id = G_REQUEST_ID,
7552                   last_update_date=SYSDATE,
7553                   last_updated_by=G_USER_ID,
7554                   last_update_login= G_USER_ID,
7555                   program_id= G_PROG_ID,
7556                   program_application_id= G_PROG_APPL_ID,
7557                   program_update_date=SYSDATE
7558            WHERE  rowid in (
7559                            SELECT dist.rowid
7560                            FROM  ap_invoices inv,
7561                                  po_distributions po,
7562                                  ap_invoice_distributions_all dist
7563                            WHERE inv.invoice_id = dist.invoice_id
7564                            AND   po.po_distribution_id = dist.po_distribution_id
7565         			       AND   nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'  -- bug 7192304, added nvl
7566                            AND   NVL(po.destination_type_code, 'EXPENSE') = 'EXPENSE'
7567                            AND   PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(dist.project_ID, 0))= 'Y'
7568                            AND   PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(dist.po_distribution_id,0))= 'Y'
7569                            AND   dist.line_type_lookup_code in ( 'ITEM','ACCRUAL') --added accrual for historical data
7570                            AND   dist.pa_addition_flag = 'N'
7571                            AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
7572                            AND   nvl(INV.source, 'xx' ) NOT IN
7573                                ('Oracle Project Accounting','PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
7574                            AND   dist.pa_addition_flag = 'N'
7575                            AND   dist.project_id > 0
7576                            AND   dist.posted_flag = 'Y'
7577                            AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date)) /* Added trunc for the bug 6623163 */
7578                            AND   trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date))/* Added trunc for the bug 6623163 */
7579                            AND   dist.project_id = G_PROJECT_ID
7580                            -- Process historical distributions for CAsh BAsed Accounting
7581                            AND   (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
7582                            AND   inv.paid_on_behalf_employee_id is NULL );
7583 
7584            write_log(LOG,'Number of inv amount variance lines for CWK marked to G:  '||to_char(SQL%ROWCOUNT));
7585            write_log(LOG,'Number of inv amount variance lines for CWK marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W);
7586 
7587    Else  -- G_PROJECT_ID IS NULL
7588 
7589     --
7590     -- Update pa-addition-flag to 'G' for item and nrtax lines if the invoice is matched to PO/RCPT that is
7591     -- accrued-on-rcpt and the PO has never been interfaced as invoice, historically
7592     -- However, such Invoice lines that have amount variance will be marked as W so that these can be processed
7593     -- for relieving the variance commitment
7594     --
7595     -- In rel12, Receipt Accruals along with NRTAX will be interfaced into Projects only from Purchasing
7596     -- However Variance and other related costs like Freight/Misc will still be interfaced from Payables
7597     --
7598 
7599         If g_body_debug_mode = 'Y' Then
7600         write_log(LOG, 'Updating empty invoice variance lines pa addtion flag to G for all');
7601         End if;
7602 
7603    UPDATE ap_invoice_distributions_all apdist
7604       SET apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
7605           request_id = G_REQUEST_ID,
7606           last_update_date=SYSDATE,
7607           last_updated_by=G_USER_ID,
7608           last_update_login= G_USER_ID,
7609           program_id= G_PROG_ID,
7610           program_application_id= G_PROG_APPL_ID,
7611           program_update_date=SYSDATE
7612     WHERE rowid IN (
7613           SELECT dist.rowid
7614           FROM  ap_invoices inv, ap_invoice_distributions_all dist
7615           WHERE inv.invoice_id = dist.invoice_id
7616           AND  ( dist.line_type_lookup_code in ('ITEM','ACCRUAL','NONREC_TAX')
7617                 OR ( pa_nl_installed.is_nl_installed = 'Y'                 --EIB trackable items
7618                                  AND EXISTS (SELECT 'X'
7619                                               FROM  mtl_system_items si,
7620                                                     po_lines_all pol,
7621                                                     po_distributions_all po_dist1
7622                                               WHERE po_dist1.po_line_id = pol.po_line_id
7623                                               AND   po_dist1.po_distribution_id  = dist.po_distribution_id
7624                                               AND   si.inventory_item_id = pol.item_id
7625                                               AND   po_dist1.project_id IS NOT NULL
7626                                               AND   si.comms_nl_trackable_flag = 'Y'
7627 					      AND   si.organization_id = po_dist1.org_id)
7628                           )
7629                  ) --Bug#5399352. Added this here to take care of IPV/TIPV records matched to EIB item PO.
7630           AND   NOT EXISTS (SELECT NULL
7631                                      FROM ap_invoice_distributions_all apdist2
7632                                     WHERE apdist2.pa_addition_flag   = 'Y'
7633                                       AND apdist2.po_distribution_id = dist.po_distribution_id
7634                                       AND apdist2.line_type_lookup_code in ('ITEM','ACCRUAL','NONREC_TAX')
7635                            )
7636           AND  (  EXISTS (SELECT NULL
7637                               FROM ap_invoice_distributions_all apdist1
7638                              WHERE apdist1.pa_addition_flag   IN ('F', 'G')
7639                                AND apdist1.po_distribution_id  = dist.po_distribution_id
7640                           )
7641                  OR EXISTS (  SELECT rcv_txn.po_distribution_id
7642                                 FROM rcv_transactions rcv_txn
7643                                    , rcv_receiving_sub_ledger rcv_sub
7644                                WHERE rcv_txn.po_distribution_id      = dist.po_distribution_id
7645                                  AND rcv_sub.pa_addition_flag || '' IN ('Y','I')
7646                                  AND rcv_sub.rcv_transaction_id      = rcv_txn.transaction_id
7647                            )
7648                  OR EXISTS (  SELECT  PO.po_distribution_id
7649                                 FROM  po_distributions PO
7650                                WHERE  PO.po_distribution_id = dist.po_distribution_id
7651                                  AND  nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'  -- bug 7192304, added nvl
7652                                  AND  PO.project_id  > 0
7653                                  AND  NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
7654                                  AND  PO.accrue_on_receipt_flag= 'Y'
7655                            )
7656                 )
7657           AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
7658           AND   nvl(INV.source, 'xx' ) NOT IN
7659                  ('Oracle Project Accounting','PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
7660           AND   dist.pa_addition_flag = 'N'
7661           AND   dist.posted_flag = 'Y'
7662           AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date))  /* Added trunc for the bug 6623163 */
7663           AND  trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date)) /* Added trunc for the bug 6623163 */
7664           AND   dist.project_id > 0
7665           -- Process historical distributions for CAsh BAsed Accounting
7666           AND   (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
7667           AND   NVL(dist.po_distribution_id,0) > 0 );
7668 
7669           write_log(LOG,'Number of inv amount variance lines marked to G:  '||to_char(SQL%ROWCOUNT));
7670           write_log(LOG,'Number of inv amount variance lines marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W);
7671 
7672       /* If the Supplier Invoice is matched to period-end PO for Contingent worker labor fixed rate and the CWK timecard
7673          is to be processed as Labor cost, only non recoverable tax receipt lines, variances and other allocated costs should be
7674          pulled from Payables. The pa_addition_flag for such invoice ITEM distribution lines is updated to G to prevent
7675          further processing into Projects.
7676          However, if there is an amount variance on such invoice, it needs to be processed as W to releive variance commitment  */
7677 
7678            UPDATE ap_invoice_distributions_all apdist
7679            SET    apdist.pa_addition_flag = DECODE(NVL(apdist.amount_variance,0),0,'G',increment_W_count('W')),
7680                   request_id = G_REQUEST_ID,
7681                   last_update_date=SYSDATE,
7682                   last_updated_by=G_USER_ID,
7683                   last_update_login= G_USER_ID,
7684                   program_id= G_PROG_ID,
7685                   program_application_id= G_PROG_APPL_ID,
7686                   program_update_date=SYSDATE
7687            WHERE  rowid in (
7688                            SELECT dist.rowid
7689                            FROM  ap_invoices inv,
7690                                  po_distributions po,
7691                                  ap_invoice_distributions_all dist
7692                            WHERE inv.invoice_id = dist.invoice_id
7693                            AND   po.po_distribution_id = dist.po_distribution_id
7694                            AND   NVL(po.destination_type_code, 'EXPENSE') = 'EXPENSE'
7695                            AND   nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'   -- bug 7192304, added nvl
7696                            AND   PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(dist.project_ID, 0))= 'Y'
7697                            AND   PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(dist.po_distribution_id,0))= 'Y'
7698                            AND   dist.line_type_lookup_code in ( 'ITEM','ACCRUAL') --added accrual for historical data
7699                            AND   dist.pa_addition_flag = 'N'
7700                            AND   inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
7701                            AND   nvl(INV.source, 'xx' ) NOT IN
7702                                ('Oracle Project Accounting','PA_IC_INVOICES','PA_COST_ADJUSTMENTS')
7703                            AND   dist.pa_addition_flag = 'N'
7704                            AND   dist.posted_flag = 'Y'
7705                            AND   trunc(dist.accounting_date) <= trunc(nvl(G_GL_DATE,dist.Accounting_Date)) /* Added trunc for the bug 6623163 */
7706                            AND   trunc(dist.Expenditure_Item_Date) <= trunc(NVL(G_TRANSACTION_DATE,dist.Expenditure_Item_Date)) /* Added trunc for the bug 6623163 */
7707                            AND   dist.project_id > 0
7708                            -- Process historical distributions for CAsh BAsed Accounting
7709                            AND   (G_ACCTNG_METHOD = 'A' OR (G_ACCTNG_METHOD = 'C' AND dist.historical_flag = 'Y'))
7710                            AND   inv.paid_on_behalf_employee_id is NULL );
7711 
7712            write_log(LOG,'Number of inv amount variance lines for CWK marked to G:  '||to_char(SQL%ROWCOUNT));
7713            write_log(LOG,'Number of inv amount variance lines for CWK marked to W:  '||G_NUM_AP_VARIANCE_MARKED_W);
7714 
7715    END IF; /* IF G_PROJECT_ID */
7716 
7717 EXCEPTION
7718    WHEN Others THEN
7719       write_log(LOG,'Failed during mark_inv_var_paflag');
7720       G_err_code := SQLCODE;
7721       RAISE;
7722 
7723 END mark_inv_var_paflag;
7724 
7725 PROCEDURE transfer_inv_var_to_pa  IS
7726 
7727    v_num_invoices_fetched          NUMBER :=0;
7728    v_num_distributions_fetched     NUMBER :=0;
7729    v_prev_invoice_id               NUMBER := 0;
7730    v_old_stack                     VARCHAR2(630);
7731    v_err_message                   VARCHAR2(220);
7732    v_all_done                      NUMBER := 0;
7733    v_num_inv_variance_fetched      NUMBER :=0;
7734 
7735    v_status Number := 0;
7736    v_stage  Number :=0;
7737    v_business_group_id NUMBER := 0;
7738    v_attribute_category VARCHAR2(150);
7739    v_attribute1 VARCHAR2(150);
7740    v_attribute2 VARCHAR2(150);
7741    v_attribute3 VARCHAR2(150);
7742    v_attribute4 VARCHAR2(150);
7743    v_attribute5 VARCHAR2(150);
7744    v_attribute6 VARCHAR2(150);
7745    v_attribute7 VARCHAR2(150);
7746    v_attribute8 VARCHAR2(150);
7747    v_attribute9 VARCHAR2(150);
7748    v_attribute10 VARCHAR2(150);
7749    v_dff_map_status VARCHAR2(30);
7750    dff_map_exception EXCEPTION;
7751 
7752    v_last_inv_var_index         NUMBER := 0;
7753    v_max_size                   NUMBER := 0;
7754    l_prev_cr_ccid NUMBER;
7755    l_prev_dr_ccid NUMBER;
7756    l_prev_exp_item_id NUMBER:=0;
7757    l_create_adj_recs  VARCHAR2(1) := 'N';
7758 
7759 
7760    PROCEDURE clear_plsql_tables IS
7761 
7762        l_status1 VARCHAR2(30);
7763 
7764    BEGIN
7765 
7766        G_err_stage := 'within clear_plsql_tables of transfer_inv_var_to_pa';
7767        write_log(LOG, G_err_stage);
7768 
7769        l_invoice_id_tbl.delete;
7770        l_invoice_dist_id_tbl.delete;
7771        l_project_id_tbl.delete;
7772        l_task_id_tbl.delete;
7773        l_ln_type_lookup_tbl.delete;
7774        l_exp_type_tbl.delete;
7775        l_ei_date_tbl.delete;
7776        l_amount_tbl.delete;
7777        l_description_tbl.delete;
7778        l_dist_cc_id_tbl.delete;
7779        l_exp_org_id_tbl.delete;
7780        l_quantity_tbl.delete;
7781        l_gl_date_tbl.delete;
7782        l_attribute_cat_tbl.delete;
7783        l_attribute1_tbl.delete;
7784        l_attribute2_tbl.delete;
7785        l_attribute3_tbl.delete;
7786        l_attribute4_tbl.delete;
7787        l_attribute5_tbl.delete;
7788        l_attribute6_tbl.delete;
7789        l_attribute7_tbl.delete;
7790        l_attribute8_tbl.delete;
7791        l_attribute9_tbl.delete;
7792        l_attribute10_tbl.delete;
7793        l_denom_raw_cost_tbl.delete;
7794        l_denom_cur_code_tbl.delete;
7795        l_acct_rate_date_tbl.delete;
7796        l_acct_rate_type_tbl.delete;
7797        l_acct_exch_rate_tbl.delete;
7798        l_job_id_tbl.delete;
7799        l_employee_id_tbl.delete;
7800        l_vendor_id_tbl.delete;
7801        l_inv_type_code_tbl.delete;
7802        l_source_tbl.delete;
7803        l_org_id_tbl.delete;
7804        l_invoice_num_tbl.delete;
7805        l_cdl_sys_ref3_tbl.delete;
7806        l_cdl_sys_ref4_tbl.delete;
7807        l_txn_src_tbl.delete;
7808        l_user_txn_src_tbl.delete;
7809        l_batch_name_tbl.delete;
7810        l_interface_id_tbl.delete;
7811        l_exp_end_date_tbl.delete;
7812        l_txn_status_code_tbl.delete;
7813        l_txn_rej_code_tbl.delete;
7814        l_bus_grp_id_tbl.delete;
7815 --       l_insert_flag_tbl.delete;
7816        l_reversal_flag_tbl.delete; --NEW
7817        l_net_zero_flag_tbl.delete; --NEW
7818        l_sc_xfer_code_tbl.delete; --NEW
7819        l_cancel_flag_tbl.delete;  --NEW
7820        l_parent_rev_id_tbl.delete; --NEW
7821        l_adj_exp_item_id_tbl.delete; --NEW
7822        l_fc_enabled_tbl.delete;
7823        l_fc_document_type_tbl.delete;
7824 
7825     END clear_plsql_tables;
7826 
7827     PROCEDURE bulk_insert_trx_intf IS
7828 
7829       l_status2 VARCHAR2(30);
7830 
7831     BEGIN
7832 
7833        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
7834 
7835        INSERT INTO pa_transaction_interface_all(
7836                      transaction_source
7837                     , user_transaction_source
7838                     , system_linkage
7839                     , batch_name
7840                     , expenditure_ending_date
7841                     , expenditure_item_date
7842                     , expenditure_type
7843                     , quantity
7844                     , raw_cost_rate
7845                     , expenditure_comment
7846                     , transaction_status_code
7847                     , transaction_rejection_code
7848                     , orig_transaction_reference
7849                     , interface_id
7850                     , dr_code_combination_id
7851                     , cr_code_combination_id
7852                     , cdl_system_reference1
7853                     , cdl_system_reference2
7854                     , cdl_system_reference3
7855                     , cdl_system_reference4
7856                     , cdl_system_reference5 --NEW
7857                     , gl_date
7858                     , org_id
7859                     , unmatched_negative_txn_flag
7860                     , receipt_currency_amount
7861                     , receipt_currency_code
7862                     , receipt_exchange_rate
7863                     , denom_raw_cost
7864                     , denom_currency_code
7865                     , acct_rate_date
7866                     , acct_rate_type
7867                     , acct_exchange_rate
7868                     , acct_raw_cost
7869                     , acct_exchange_rounding_limit
7870                     , attribute_category
7871                     , attribute1
7872                     , attribute2
7873                     , attribute3
7874                     , attribute4
7875                     , attribute5
7876                     , attribute6
7877                     , attribute7
7878                     , attribute8
7879                     , attribute9
7880                     , attribute10
7881                     , orig_exp_txn_reference1
7882                     , orig_user_exp_txn_reference
7883                     ,  orig_exp_txn_reference2
7884                     ,  orig_exp_txn_reference3
7885                     , last_update_date
7886                     , last_updated_by
7887                     , creation_date
7888                     , created_by
7889                     , person_id
7890                     , organization_id
7891                     , project_id
7892                     , task_id
7893                     , Vendor_id
7894                     , override_to_organization_id
7895                     , person_business_group_id
7896                     , adjusted_expenditure_item_id --NEW
7897                     , fc_document_type  -- NEW
7898                     , sc_xfer_code
7899                     , si_assets_addition_flag
7900                     , net_zero_adjustment_flag
7901                     , expenditure_item_id
7902                    )
7903              SELECT l_txn_src_tbl(i)
7904                      ,l_user_txn_src_tbl(i)
7905                      ,G_SYSTEM_LINKAGE
7906                      ,l_batch_name_tbl(i)
7907                      ,l_exp_end_date_tbl(i)
7908                      ,l_ei_date_tbl(i)
7909                      ,l_exp_type_tbl(i)
7910                      ,l_quantity_tbl(i)
7911                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
7912                      ,l_description_tbl(i)
7913                      ,l_txn_status_code_tbl(i)
7914                      ,l_txn_rej_code_tbl(i)
7915                      ,G_REQUEST_ID
7916                      ,l_interface_id_tbl(i)
7917                      ,l_dist_cc_id_tbl(i)
7918                      ,NULL
7919                      ,l_vendor_id_tbl(i)
7920                      ,l_invoice_id_tbl(i)
7921                      ,l_cdl_sys_ref3_tbl(i)
7922                      ,l_cdl_sys_ref4_tbl(i)
7923                      ,l_invoice_dist_id_tbl(i) --NEW
7924                      ,l_gl_date_tbl(i)
7925                      ,G_ORG_ID
7926                      ,'Y'
7927                      ,NULL
7928                      ,NULL
7929                      ,NULL
7930                      ,l_denom_raw_cost_tbl(i)
7931                      ,l_denom_cur_code_tbl(i)
7932                      ,l_acct_rate_date_tbl(i)
7933                      ,l_acct_rate_type_tbl(i)
7934                      ,l_acct_exch_rate_tbl(i)
7935                      ,l_amount_tbl(i)
7936                      ,1
7937                      ,l_attribute_cat_tbl(i)
7938                      ,l_attribute1_tbl(i)
7939                      ,l_attribute2_tbl(i)
7940                      ,l_attribute3_tbl(i)
7941                      ,l_attribute4_tbl(i)
7942                      ,l_attribute5_tbl(i)
7943                      ,l_attribute6_tbl(i)
7944                      ,l_attribute7_tbl(i)
7945                      ,l_attribute8_tbl(i)
7946                      ,l_attribute9_tbl(i)
7947                      ,l_attribute10_tbl(i)
7948                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
7949                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
7950                      ,NULL                       /*orig_exp_txn_reference2*/
7951                      ,NULL                       /*orig_exp_txn_reference3*/
7952                      ,SYSDATE
7953                      ,-1
7954                      ,SYSDATE
7955                      ,-1
7956                      ,l_employee_id_tbl(i)
7957                      ,l_org_id_tbl(i)
7958                      ,l_project_id_tbl(i)
7959                      ,l_task_id_tbl(i)
7960                      ,l_vendor_id_tbl(i)
7961                      ,l_exp_org_id_tbl(i)
7962                      ,l_bus_grp_id_tbl(i)
7963                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
7964                      ,l_fc_document_type_tbl(i) --NEW for funds checking
7965                      ,l_sc_xfer_code_tbl(i)
7966                      ,l_si_assts_add_flg_tbl(i)
7967                      ,l_net_zero_flag_tbl(i)
7968                      ,0 -- To relieve the cmt. It will not be interfaced from xface in trx imp.
7969                 FROM dual;
7970 
7971               -- Insert the reversal of the reversed/cancelled distribution recs from AP.
7972     IF l_create_adj_recs = 'Y' THEN
7973 
7974         If g_body_debug_mode = 'Y' Then
7975                 write_log(LOG, 'Inserting adjustment records..');
7976         End if;
7977 
7978                 FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
7979        INSERT INTO pa_transaction_interface_all(
7980                      transaction_source
7981                     , user_transaction_source
7982                     , system_linkage
7983                     , batch_name
7984                     , expenditure_ending_date
7985                     , expenditure_item_date
7986                     , expenditure_type
7987                     , quantity
7988                     , raw_cost_rate
7989                     , expenditure_comment
7990                     , transaction_status_code
7991                     , transaction_rejection_code
7992                     , orig_transaction_reference
7993                     , interface_id
7994                     , dr_code_combination_id
7995                     , cr_code_combination_id
7996                     , cdl_system_reference1
7997                     , cdl_system_reference2
7998                     , cdl_system_reference3
7999                     , cdl_system_reference4
8000                     , cdl_system_reference5 --NEW
8001                     , gl_date
8002                     , org_id
8003                     , unmatched_negative_txn_flag
8004                     , receipt_currency_amount
8005                     , receipt_currency_code
8006                     , receipt_exchange_rate
8007                     , denom_raw_cost
8008                     , denom_currency_code
8009                     , acct_rate_date
8010                     , acct_rate_type
8011                     , acct_exchange_rate
8012                     , acct_raw_cost
8013                     , acct_exchange_rounding_limit
8014                     , attribute_category
8015                     , attribute1
8016                     , attribute2
8017                     , attribute3
8018                     , attribute4
8019                     , attribute5
8020                     , attribute6
8021                     , attribute7
8022                     , attribute8
8023                     , attribute9
8024                     , attribute10
8025                     , orig_exp_txn_reference1
8026                     , orig_user_exp_txn_reference
8027                     ,  orig_exp_txn_reference2
8028                     ,  orig_exp_txn_reference3
8029                     , last_update_date
8030                     , last_updated_by
8031                     , creation_date
8032                     , created_by
8033                     , person_id
8034                     , organization_id
8035                     , project_id
8036                     , task_id
8037                     , Vendor_id
8038                     , override_to_organization_id
8039                     , person_business_group_id
8040                     , adjusted_expenditure_item_id --NEW
8041                     , fc_document_type  -- NEW
8042                     , adjusted_txn_interface_id --NEW
8043                     , sc_xfer_code
8044                     , si_assets_addition_flag
8045                     , net_zero_adjustment_flag
8046                    )
8047              SELECT l_txn_src_tbl(i)
8048                      ,l_user_txn_src_tbl(i)
8049                      ,G_SYSTEM_LINKAGE
8050                      ,l_batch_name_tbl(i)
8051                      ,l_exp_end_date_tbl(i)
8052                      ,l_ei_date_tbl(i)
8053                      ,l_exp_type_tbl(i)
8054                      ,-l_quantity_tbl(i)
8055                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
8056                      ,l_description_tbl(i)
8057                      ,l_txn_status_code_tbl(i)
8058                      ,l_txn_rej_code_tbl(i)
8059                      ,G_REQUEST_ID
8060                      ,l_interface_id_tbl(i)
8061                      ,l_dist_cc_id_tbl(i)
8062                      ,NULL
8063                      ,l_vendor_id_tbl(i)
8064                      ,l_invoice_id_tbl(i)
8065                      ,l_cdl_sys_ref3_tbl(i)
8066                      ,l_cdl_sys_ref4_tbl(i)
8067                      ,l_invoice_dist_id_tbl(i) --NEW
8068                      ,l_gl_date_tbl(i)
8069                      ,G_ORG_ID
8070                      ,'Y'
8071                      ,NULL
8072                      ,NULL
8073                      ,NULL
8074                      ,-l_denom_raw_cost_tbl(i)
8075                      ,l_denom_cur_code_tbl(i)
8076                      ,l_acct_rate_date_tbl(i)
8077                      ,l_acct_rate_type_tbl(i)
8078                      ,l_acct_exch_rate_tbl(i)
8079                      ,-l_amount_tbl(i)
8080                      ,1
8081                      ,l_attribute_cat_tbl(i)
8082                      ,l_attribute1_tbl(i)
8083                      ,l_attribute2_tbl(i)
8084                      ,l_attribute3_tbl(i)
8085                      ,l_attribute4_tbl(i)
8086                      ,l_attribute5_tbl(i)
8087                      ,l_attribute6_tbl(i)
8088                      ,l_attribute7_tbl(i)
8089                      ,l_attribute8_tbl(i)
8090                      ,l_attribute9_tbl(i)
8091                      ,l_attribute10_tbl(i)
8092                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
8093                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
8094                      ,NULL                       /*orig_exp_txn_reference2*/
8095                      ,NULL                       /*orig_exp_txn_reference3*/
8096                      ,SYSDATE
8097                      ,-1
8098                      ,SYSDATE
8099                      ,-1
8100                      ,l_employee_id_tbl(i)
8101                      ,l_org_id_tbl(i)
8102                      ,l_project_id_tbl(i)
8103                      ,l_task_id_tbl(i)
8104                      ,l_vendor_id_tbl(i)
8105                      ,l_exp_org_id_tbl(i)
8106                      ,l_bus_grp_id_tbl(i)
8107                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
8108                      ,l_fc_document_type_tbl(i) --NEW for funds checking
8109                      ,(select xface.txn_interface_id
8110                        from   pa_transaction_interface xface
8111                        where  xface.interface_id = l_interface_id_tbl(i)
8112                        and    xface.cdl_system_reference2 = l_invoice_id_tbl(i)
8113                        and    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(i)
8114 		       and    NVL(xface.adjusted_expenditure_item_id,0) =0 ) -- R12 funds management Uptake
8115                      ,'P' -- sc_xfer_code
8116                      ,l_si_assts_add_flg_tbl(i)
8117                      ,l_net_zero_flag_tbl(i)
8118                 FROM dual
8119                 WHERE l_insert_flag_tbl(i)= 'A';
8120                 --WHERE l_net_zero_flag_tbl(i)= 'Y';
8121       END IF;
8122 
8123    EXCEPTION
8124       WHEN Others THEN
8125          write_log(LOG,'Failed during bulk insert of inv var processing');
8126          G_err_code := SQLCODE;
8127          RAISE;
8128 
8129    END bulk_insert_trx_intf;
8130 
8131    PROCEDURE process_inv_var_logic IS
8132 
8133        j   NUMBER := 0;
8134        l_status3 VARCHAR2(30);
8135        l_historical_flag VARCHAR(1);  --NEW
8136 
8137    BEGIN
8138 
8139        G_err_stage := ('Within Calling process logic of transfer_inv_var_to_pa');
8140        write_log(LOG, G_err_stage);
8141 
8142        j := v_last_inv_var_index ;
8143        FOR i IN  l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST  LOOP
8144 
8145            write_log(LOG,'Processing Invoice Variance for invoice id:  '||l_invoice_id_tbl(i)||
8146                          'Invoice Dist Id :  '||l_invoice_dist_id_tbl(i));
8147 
8148            G_TRANSACTION_REJECTION_CODE := '';
8149 
8150            /* The following will be executed if the distribution being fetched belongs to a new invoice */
8151            IF (l_invoice_id_tbl(i) <> v_prev_invoice_id) THEN
8152 
8153                G_err_stage := ('New invoice being processed.New invoice _id is:'||l_invoice_id_tbl(i));
8154                write_log(LOG, G_err_stage);
8155 
8156                /* Update the previous invoice id and vendor id*/
8157                v_prev_invoice_id := l_invoice_id_tbl(i);
8158 
8159                /* Increment the counter for invoices */
8160                v_num_invoices_fetched := v_num_invoices_fetched + 1;
8161 
8162                 /* For new invoice, initialize the transaction status code to 'P' */
8163                 G_TRANSACTION_STATUS_CODE := 'P';
8164 
8165                 G_err_stage := 'GET MAX EXPENDITURE ENDING DATE';
8166                 write_log(LOG, G_err_stage);
8167                 SELECT pa_utils.getweekending(MAX(expenditure_item_date))
8168                   INTO G_EXPENDITURE_ENDING_DATE
8169                   FROM ap_invoice_distributions
8170                  WHERE invoice_id = l_invoice_id_tbl(i);
8171 
8172               If g_body_debug_mode = 'Y' Then
8173                 G_err_stage := ('Getting bus group id');
8174                 write_log(LOG, G_err_stage);
8175               End If;
8176 
8177                 BEGIN
8178 
8179 
8180                     IF l_employee_id_tbl(i) <> 0 THEN
8181 			Begin
8182 			       SELECT emp.business_group_id
8183                                  INTO G_PER_BUS_GRP_ID
8184 				 FROM per_all_people_f emp
8185 				WHERE emp.person_id = l_employee_id_tbl(i)
8186 				  AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and
8187 							       trunc(emp.effective_end_date);
8188 
8189 			EXCEPTION
8190 			   WHEN NO_DATA_FOUND THEN
8191 			      l_txn_status_code_tbl(i) := 'R';
8192 			      G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
8193 			      write_log(LOG, 'As no data found for Employee, Rejecting invoice'||l_invoice_id_tbl(i)  );
8194 		        End;
8195 		    Else
8196 			Begin
8197 
8198 			    select org2.business_group_id
8199                             into G_PER_BUS_GRP_ID
8200 			      from hr_organization_units org1,
8201 				   hr_organization_units org2
8202 			     Where org1.organization_id = l_exp_org_id_tbl(i)
8203 			       and org1.business_group_id = org2.organization_id;
8204 
8205 			EXCEPTION
8206 				WHEN NO_DATA_FOUND THEN
8207 				      G_TRANSACTION_STATUS_CODE := 'R';
8208 				      G_TRANSACTION_REJECTION_CODE := 'INVALID_ORGANIZATION';
8209 				      write_log(LOG, 'As no data found for Organization, Rejecting discount invoice ' || l_invoice_id_tbl(i) );
8210 			End;
8211                     END IF; /* IF l_employee_id_tbl(i) <> 0 THEN  */
8212                 END;
8213 
8214            END IF; /* end of check for different invoice_id from previous invoice_id */
8215 
8216            v_num_inv_variance_fetched  := v_num_inv_variance_fetched  + 1;
8217            v_num_distributions_fetched := v_num_distributions_fetched + 1;
8218            write_log(LOG,'Num of distributions fetched:'||v_num_distributions_fetched);
8219 
8220                --l_insert_flag_tbl(i)     := 'Y';
8221 
8222 
8223         If g_body_debug_mode = 'Y' Then
8224            write_log(LOG,'This is a record type of Amount Variance : ' ||
8225                      'denom cost is:  '||l_denom_raw_cost_tbl(i));
8226         End If;
8227 
8228            /*Setting values according to global variables*/
8229            l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
8230            l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
8231            l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
8232            l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
8233 
8234            l_txn_src_tbl(i)         := G_AP_VAR_TRANSACTION_SOURCE;
8235            l_user_txn_src_tbl(i)    := G_AP_VAR_USER_TXN_SOURCE;
8236            l_batch_name_tbl(i)      := G_AP_VAR_BATCH_NAME;
8237            l_interface_id_tbl(i)    := G_AP_VAR_INTERFACE_ID;
8238 
8239            -- FC Doc Type
8240             IF l_fc_enabled_tbl(i) = 'N' THEN
8241              l_fc_document_type_tbl(i) := 'NOT';
8242             END IF;
8243 
8244            -- REVERSED DISTRIBUTIONS INTERFACE LOGIC
8245            -- If the distribution is a reversal or cancellation then check if the parent reversal distribution
8246            -- was historical data or not. If so, reversal distribution line will be interfaced as is.
8247            -- However if the parent reversal distribution is not historical then the following steps happen:
8248            -- a) Retreive the latest adjusted expenditures from PA against the parent reversal distribution id
8249            -- b) If any of the above latest EI's are not costed, then the reversed distribution will be rejected by the
8250            --    TRX import program
8251            -- c) IF all above adjusted EI's are costed, then insert record into the interface table for each adjusted EI.
8252            --    The project attributes will be copied from the adjusted EI's instead from the AP reversed
8253            --    distribution since these could have changed in PA.
8254            -- d) The interface program will interface the reversed distribution into projects
8255            -- e) The interface program will also insert a reversal of the reversed distribution into Projects. This is
8256            --    required for account reconciliation
8257            --
8258 
8259            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
8260 
8261                 BEGIN
8262 
8263                 SELECT nvl(historical_flag,'N') --check if this flag can be used
8264                 INTO   l_historical_flag
8265                 FROM   ap_invoice_distributions_all
8266                 WHERE  invoice_id = l_invoice_id_tbl(i)
8267                 AND    invoice_distribution_id = l_parent_rev_id_tbl(i); --check the index on this table
8268 
8269                 EXCEPTION
8270                 WHEN NO_DATA_FOUND THEN
8271                    l_txn_status_code_tbl(i) := 'R';
8272                    G_TRANSACTION_REJECTION_CODE := 'INVALID_INVOICE'; --?????????
8273                    write_log(LOG, 'As no data found for reversed parent distribution, Rejecting invoice dist Id'||l_invoice_dist_id_tbl(i));
8274                 END;
8275 
8276 
8277                 IF l_historical_flag = 'N' THEN
8278 
8279                      -- Call reversal API
8280                      Process_Adjustments(p_record_type               => 'AP_INVOICE',
8281                                          p_document_header_id  => l_invoice_id_tbl(i),/*Added this for 6945767 */
8282                                          p_document_distribution_id  => l_parent_rev_id_tbl(i),
8283                                          p_current_index             => i,
8284 				         p_last_index                => j);
8285 
8286                       -- Set the create flag for adjustment records
8287                          IF l_insert_flag_tbl(i) in ('A','U') THEN
8288                           l_create_adj_recs := 'Y';
8289                          END IF;
8290 
8291                 END IF; --End of check for historical Flag
8292 
8293            END IF; --End of check for reversal Distribution
8294 
8295 
8296 
8297       END LOOP; /* End of looping through each record in plsql table */
8298 
8299    EXCEPTION
8300       WHEN Others THEN
8301          write_log(LOG,'Failed during process_inv_var_logic of inv amt var processing');
8302          G_err_code := SQLCODE;
8303          RAISE;
8304 
8305    END process_inv_var_logic;
8306 
8307    BEGIN
8308    /* Main Procedure Logic starts here */
8309 
8310    G_err_stage := 'Within main procedure of transfer_inv_var_to_pa';
8311    write_log(LOG, G_err_stage);
8312 
8313      v_max_size := nvl(G_COMMIT_SIZE,200);
8314 
8315      G_AP_VAR_TRANSACTION_SOURCE  := 'AP VARIANCE';
8316      G_AP_VAR_USER_TXN_SOURCE     := 'Oracle Payables Invoice Variance';
8317 
8318      OPEN Invoice_Variance_Cur;
8319 
8320      G_err_stage := 'After opening Invoice_Variance_Cur within transfer_inv_var_to_pa';
8321      write_log(LOG, G_err_stage);
8322 
8323      WHILE (v_all_done = 0) LOOP
8324 
8325        clear_plsql_tables;
8326 
8327        --Creating new interface ID every time this is called
8328        G_err_stage := 'CREATING NEW INTERFACE ID';
8329        write_log(LOG, G_err_stage);
8330 
8331        SELECT pa_interface_id_s.nextval
8332          INTO G_AP_VAR_INTERFACE_ID
8333          FROM dual;
8334 
8335           FETCH Invoice_Variance_Cur BULK COLLECT INTO
8336              l_invoice_id_tbl
8337             ,l_invoice_dist_id_tbl --NEW
8338             ,l_cdl_sys_ref3_tbl --Invoice_lie_num
8339             ,l_project_id_tbl
8340             ,l_task_id_tbl
8341             ,l_ln_type_lookup_tbl
8342             ,l_exp_type_tbl
8343             ,l_ei_date_tbl
8344             ,l_amount_tbl
8345             ,l_description_tbl
8346             ,l_dist_cc_id_tbl
8347             ,l_exp_org_id_tbl
8348             ,l_quantity_tbl
8349             ,l_gl_date_tbl
8350             ,l_attribute_cat_tbl
8351             ,l_attribute1_tbl
8352             ,l_attribute2_tbl
8353             ,l_attribute3_tbl
8354             ,l_attribute4_tbl
8355             ,l_attribute5_tbl
8356             ,l_attribute6_tbl
8357             ,l_attribute7_tbl
8358             ,l_attribute8_tbl
8359             ,l_attribute9_tbl
8360             ,l_attribute10_tbl
8361             ,l_denom_raw_cost_tbl
8362             ,l_denom_cur_code_tbl
8363             ,l_acct_rate_date_tbl
8364             ,l_acct_rate_type_tbl
8365             ,l_acct_exch_rate_tbl
8366             ,l_job_id_tbl
8367             ,l_employee_id_tbl
8368             ,l_vendor_id_tbl
8369             ,l_inv_type_code_tbl
8370             ,l_source_tbl
8371             ,l_org_id_tbl
8372             ,l_invoice_num_tbl
8373             ,l_cdl_sys_ref4_tbl
8374             ,l_txn_src_tbl
8375             ,l_user_txn_src_tbl
8376             ,l_batch_name_tbl
8377             ,l_interface_id_tbl
8378             ,l_exp_end_date_tbl
8379             ,l_txn_status_code_tbl
8380             ,l_txn_rej_code_tbl
8381             ,l_bus_grp_id_tbl
8382             ,l_reversal_flag_tbl
8383             ,l_cancel_flag_tbl
8384             ,l_parent_rev_id_tbl
8385             ,l_net_zero_flag_tbl
8386             ,l_sc_xfer_code_tbl
8387             ,l_adj_exp_item_id_tbl
8388             ,l_fc_enabled_tbl
8389             ,l_mrc_exchange_date_tbl
8390             ,l_fc_document_type_tbl
8391             ,l_si_assts_add_flg_tbl
8392             ,l_insert_flag_tbl
8393             LIMIT v_max_size;
8394 
8395          G_err_stage := 'After fetching Cursor within transfer_inv_var_to_pa';
8396          write_log(LOG, G_err_stage);
8397 
8398          IF l_invoice_id_tbl.COUNT <> 0 THEN
8399 
8400             v_last_inv_var_index := l_invoice_id_tbl.LAST ;
8401 
8402             G_err_stage := 'calling process_inv_logic within transfer_inv_var_to_pa';
8403             write_log(LOG, G_err_stage);
8404 
8405             process_inv_var_logic;
8406 
8407             G_err_stage := 'calling bulk_insert_trx_intf within transfer_inv_var_to_pa';
8408             write_log(LOG, G_err_stage);
8409 
8410             bulk_insert_trx_intf;
8411 
8412            G_err_stage := 'Before calling transaction import and tiebacks within transfer_inv_var_to_pa';
8413            write_log(LOG, G_err_stage);
8414 
8415 
8416            IF (v_num_inv_variance_fetched > 0) THEN
8417 
8418               G_err_stage := 'Before calling transaction import and tiebacks within transfer_inv_var_to_pa';
8419               write_log(LOG, G_err_stage);
8420 
8421               trans_import(G_AP_VAR_TRANSACTION_SOURCE,G_AP_VAR_BATCH_NAME,
8422                            G_AP_VAR_INTERFACE_ID,G_USER_ID);
8423               tieback_invoice_variances(G_AP_VAR_TRANSACTION_SOURCE,G_AP_VAR_BATCH_NAME,
8424                            G_AP_VAR_INTERFACE_ID);
8425 
8426               G_err_stage := 'Before updating the total number of invoices processed';
8427               write_log(LOG, G_err_stage);
8428 
8429               G_NUM_BATCHES_PROCESSED       := G_NUM_BATCHES_PROCESSED + 1;
8430               G_NUM_INVOICES_PROCESSED      :=  G_NUM_INVOICES_PROCESSED + v_num_invoices_fetched;
8431               G_NUM_DISTRIBUTIONS_PROCESSED :=  G_NUM_DISTRIBUTIONS_PROCESSED + v_num_distributions_fetched;
8432               G_NUM_AP_VARIANCE_PROCESSED   := G_NUM_AP_VARIANCE_PROCESSED + v_num_inv_variance_fetched;
8433 
8434         END IF; /* IF (v_num_distributions_fetched > 0) */
8435 
8436         G_err_stage := 'After calling transaction import and tiebacks within transfer_inv_var_to_pa';
8437         write_log(LOG, G_err_stage);
8438 
8439         clear_plsql_tables;
8440 
8441         v_num_invoices_fetched       :=0;
8442         v_num_distributions_fetched  :=0;
8443         v_num_inv_variance_fetched   :=0;
8444 
8445         G_err_stage:='Before exiting when Invoice_Variance_Cur is NOTFOUND';
8446         write_log(LOG,   G_err_stage);
8447 
8448       ELSE
8449           EXIT;
8450       END IF; /* l_invoice_id_tbl.COUNT = 0 */
8451 
8452       EXIT WHEN Invoice_Variance_Cur%NOTFOUND;
8453 
8454    END LOOP; /* While more rows to process is true */
8455 
8456    CLOSE Invoice_Variance_Cur;
8457 
8458 EXCEPTION
8459     WHEN OTHERS THEN
8460 
8461          G_err_stack := v_old_stack;
8462          IF Invoice_Variance_Cur%ISOPEN THEN
8463            CLOSE Invoice_Cur;
8464          END IF ;
8465 
8466          G_err_code := SQLCODE;
8467          RAISE;
8468 
8469 END transfer_inv_var_to_pa;
8470 
8471 PROCEDURE tieback_invoice_variances (
8472    p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
8473    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
8474    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
8475 
8476    l_assets_addflag          VARCHAR2(1):=NULL;
8477    l_prev_assets_addflag     VARCHAR2(1):=NULL;
8478    l_project_id             NUMBER :=0;
8479    l_pa_addflag             VARCHAR2(1):=NULL;
8480    l_prev_proj_id           NUMBER :=0;
8481 
8482    l_sys_ref1_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
8483    l_sys_ref2_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
8484    l_sys_ref5_tbl           PA_PLSQL_DATATYPES.IdTabTyp;    --confirm if this is number type in interface table
8485    l_txn_src_tbl            PA_PLSQL_DATATYPES.Char30TabTyp;
8486    l_batch_name_tbl         PA_PLSQL_DATATYPES.Char50TabTyp;
8487    l_interface_id_tbl       PA_PLSQL_DATATYPES.IdTabTyp;
8488    l_txn_status_code_tbl    PA_PLSQL_DATATYPES.Char2TabTyp;
8489    l_project_id_tbl            PA_PLSQL_DATATYPES.IdTabTyp;
8490    l_pa_addflag_tbl         PA_PLSQL_DATATYPES.CHAR1TabTyp;
8491    l_assets_addflag_tbl     PA_PLSQL_DATATYPES.CHAR1TabTyp;
8492 
8493    CURSOR txn_intf_rec (p_txn_src       IN VARCHAR2,
8494                         p_batch_name    IN VARCHAR2,
8495                         p_interface_id  IN NUMBER) IS
8496       SELECT cdl_system_reference1
8497             ,cdl_system_reference2
8498             ,cdl_system_reference5
8499             ,transaction_source
8500             ,batch_name
8501             ,interface_id
8502             ,transaction_status_code
8503             ,project_id
8504             ,l_pa_addflag
8505             ,l_assets_addflag
8506         FROM pa_transaction_interface_all txnintf
8507        WHERE txnintf.transaction_source = p_txn_src
8508          AND txnintf.batch_name         = p_batch_name
8509          AND txnintf.interface_id       = p_interface_id;
8510 
8511    PROCEDURE clear_plsql_tables IS
8512 
8513       v_status   VARCHAR2(15);
8514 
8515    BEGIN
8516 
8517       G_err_stage:='Clearing PLSQL tables in invoice variance tieback';
8518       write_log(LOG,   G_err_stage);
8519 
8520       l_sys_ref1_tbl.delete;
8521       l_sys_ref2_tbl.delete;
8522       l_sys_ref5_tbl.delete;
8523       l_txn_src_tbl.delete;
8524       l_batch_name_tbl.delete;
8525       l_interface_id_tbl.delete;
8526       l_txn_status_code_tbl.delete;
8527       l_project_id_tbl.delete;
8528       l_pa_addflag_tbl.delete;
8529       l_assets_addflag_tbl.delete;
8530 
8531    END clear_plsql_tables;
8532 
8533    PROCEDURE process_tieback IS
8534 
8535       v_status   VARCHAR2(15);
8536 
8537    BEGIN
8538 
8539       G_err_stage:='Within process_tieback of invoice variance tieback';
8540       write_log(LOG,   G_err_stage);
8541 
8542       FOR i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST LOOP
8543 
8544          /* If transaction import stamps the record to be 'A' then
8545             update pa_addition_flag of invoice distribution to 'F'.
8546             If transaction import leaves the record to be 'P' then
8547             update pa_addition_flag of invoice distribution to 'N'.
8548             If transaction import stamps the record to be 'R' then
8549             update pa_addition_flag of invoice distribution to 'N'.*/
8550 
8551          write_log(LOG,'Tying invoice_id: '||l_sys_ref2_tbl(i)||
8552                        -- 'dist num:  '||l_sys_ref3_tbl(i)||
8553                        -- 'sys ref 4: '||l_sys_ref4_tbl(i)||
8554                        'trc src:   '||l_txn_src_tbl(i));
8555 
8556          IF l_txn_status_code_tbl(i) = 'A' THEN
8557                l_pa_addflag_tbl(i) := 'F';
8558          ELSIF l_txn_status_code_tbl(i) = 'P' THEN
8559                l_pa_addflag_tbl(i) :='N';
8560          ELSIF l_txn_status_code_tbl(i) = 'R' THEN
8561                l_pa_addflag_tbl(i) := 'N';
8562          END IF;
8563 
8564 
8565          IF G_PROJECT_ID IS NOT NULL THEN
8566 
8567             IF G_Assets_Addition_flag = 'P' THEN
8568                l_assets_addflag_tbl(i) := 'P';
8569             ELSE
8570                l_assets_addflag_tbl(i) := 'X';
8571             END IF;
8572 
8573          ELSIF G_PROJECT_ID IS NULL THEN
8574 
8575             IF l_project_id_tbl(i) <> l_prev_proj_id THEN
8576 
8577                G_err_stage:='Selecting assets addition flag within invoice variance tieback';
8578                write_log(LOG,   G_err_stage);
8579 
8580                SELECT decode(PTYPE.Project_Type_Class_Code,'CAPITAL','P','X')
8581                  INTO l_assets_addflag_tbl(i)
8582                  FROM pa_project_types_all PTYPE,
8583                       pa_projects_all PROJ
8584                 WHERE PTYPE.Project_Type = PROJ.Project_Type
8585                   AND (PTYPE.org_id = PROJ.org_id OR
8586                        PROJ.org_id is null)
8587                   AND PROJ.Project_Id = l_project_id_tbl(i);
8588 
8589                 l_prev_proj_id := l_project_id_tbl(i);
8590 		l_prev_assets_addflag := l_assets_addflag_tbl(i);      /* Bug 3626038 */
8591 
8592             ELSE
8593                l_assets_addflag_tbl(i) := l_prev_assets_addflag;
8594             END IF;
8595 
8596          END IF;
8597 
8598       END LOOP;
8599 
8600    EXCEPTION
8601       WHEN OTHERS THEN
8602          G_err_stage:= 'Failed during process tieback of invoice variance tieback';
8603          write_log(LOG,   G_err_stage);
8604          G_err_code   := SQLCODE;
8605          raise;
8606 
8607    END process_tieback;
8608 
8609    PROCEDURE bulk_update_txn_intf IS
8610 
8611       v_status VARCHAR2(15);
8612 
8613    BEGIN
8614 
8615       G_err_stage:=('Within bulk update of invoice variance  tieback');
8616       write_log(LOG,   G_err_stage);
8617 
8618       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
8619 
8620          UPDATE ap_invoice_distributions_all dist
8621             SET dist.pa_addition_flag         = l_pa_addflag_tbl(i)
8622                ,dist.assets_addition_flag     = decode(l_assets_addflag_tbl(i),'P','P',dist.assets_addition_flag)
8623           WHERE dist.invoice_id               = l_sys_ref2_tbl(i)
8624             AND dist.invoice_distribution_id  = l_sys_ref5_tbl(i)
8625             AND dist.pa_addition_flag         = 'W';
8626 
8627    EXCEPTION
8628       WHEN OTHERS THEN
8629          G_err_stage:= 'Failed during bulk update of invoice variance tieback';
8630          write_log(LOG,   G_err_stage);
8631          G_err_code   := SQLCODE;
8632          raise;
8633 
8634    END bulk_update_txn_intf;
8635 
8636    BEGIN
8637 
8638       /* Main logic of tieback starts here */
8639       G_err_stage:='Within main logic of invoice variance tieback';
8640       write_log(LOG,   G_err_stage);
8641 
8642       clear_plsql_tables;
8643 
8644       G_err_stage:='Opening txn_intf_rec';
8645       write_log(LOG,   G_err_stage);
8646 
8647       OPEN txn_intf_rec(p_transaction_source
8648                        ,p_batch_name
8649                        ,p_interface_id);
8650 
8651       G_err_stage:='Fetching txn_intf_rec';
8652       write_log(LOG,   G_err_stage);
8653 
8654       FETCH txn_intf_rec BULK COLLECT INTO
8655           l_sys_ref1_tbl
8656          ,l_sys_ref2_tbl
8657          ,l_sys_ref5_tbl
8658          ,l_txn_src_tbl
8659          ,l_batch_name_tbl
8660          ,l_interface_id_tbl
8661          ,l_txn_status_code_tbl
8662          ,l_project_id_tbl
8663          ,l_pa_addflag_tbl
8664          ,l_assets_addflag_tbl;
8665 
8666       IF l_sys_ref1_tbl.COUNT <> 0 THEN
8667 
8668          process_tieback;
8669 
8670          bulk_update_txn_intf;
8671 
8672          clear_plsql_tables;
8673 
8674       END IF;
8675 
8676       CLOSE txn_intf_rec;
8677 
8678 EXCEPTION
8679    WHEN OTHERS THEN
8680 
8681       IF txn_intf_rec%ISOPEN THEN
8682          CLOSE txn_intf_rec;
8683       END IF;
8684 
8685       G_err_stage:='Failed during tieback of invoice variances';
8686       write_log(LOG,   G_err_stage);
8687 
8688       G_err_code := SQLCODE;
8689       RAISE;
8690 
8691 END tieback_invoice_variances;
8692 
8693 
8694 PROCEDURE net_zero_pay_adjustment IS
8695 
8696    v_old_stack       	VARCHAR2(630);
8697    l_assets_add_flag 	VARCHAR2(1);
8698    l_num_dists_updated	NUMBER;
8699 
8700 BEGIN
8701 
8702      v_old_stack := G_err_stack;
8703      G_err_stack := G_err_stack || '->PAAPIMP_PKG.net_zero_pay_adjustment';
8704      G_err_code := 0;
8705      G_err_stage := 'Updating the payments to Z if they sum up to zero';
8706 
8707      write_log(LOG, G_err_stage);
8708      write_log(LOG, G_err_stack);
8709 
8710      IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
8711 
8712          -- Marking the expense reports to 'Z' if summing up to zero
8713 
8714          IF G_PROJECT_ID IS NOT NULL THEN
8715 
8716             -- This update is to mark the pa addition flag of all invoice distributions
8717             -- which have encumbered flag of 'R' or reversal flag of 'Y' to 'Z'.
8718             -- Encumbrance flag of 'R' or reversal flag of 'Y' indicates that they are
8719             -- exact reversal of another invoice distribution.
8720             -- If the invoice distribution has a encumbered flag value of 'R' then it is
8721             -- not encumbered and there exist no Budgetery control commitment records
8722             -- for these in PA
8723 
8724             UPDATE ap_payment_hist_dists dist
8725                 SET dist.pa_addition_flag = 'Z',
8726                     request_id = G_REQUEST_ID,
8727                     last_update_date=SYSDATE,
8728                     last_updated_by= G_USER_ID,
8729                     last_update_login= G_USER_ID,
8730                     program_id= G_PROG_ID,
8731                     program_application_id= G_PROG_APPL_ID,
8732                     program_update_date=SYSDATE
8733             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
8734                AND EXISTS (SELECT NULL
8735                            FROM   ap_payment_history_all hist
8736                            WHERE  hist.payment_history_id = dist.payment_history_id
8737                            AND    hist.posted_flag = 'Y')
8738                AND EXISTS (SELECT invoice_id
8739                              FROM AP_invoice_distributions aid
8740                             WHERE aid.invoice_distribution_id  = dist.invoice_distribution_id
8741                               AND aid.project_id = G_PROJECT_ID
8742                               AND ( nvl(aid.encumbered_flag,'N') = 'R' )) ;
8743 
8744             write_log(LOG, 'Number of distributions marked for encumbered net zero adjustment: ' || to_char(SQL%ROWCOUNT));
8745 
8746             ELSE   /* Project Id is not passed */
8747 
8748             -- This update is to mark the pa addition flag of all invoice distributions
8749             -- which have encumbered flag of 'R' or reversal flag of 'Y' to 'Z'.
8750             -- Encumbrance flag of 'R' or reversal flag of 'Y' indicates that they are
8751             -- exact reversal of another invoice distribution.
8752             -- If the invoice distribution has a encumbered flag value of 'R' then it is
8753             -- not encumbered and there exist no Budgetery control commitment records
8754             -- for these in PA
8755 
8756 
8757             UPDATE ap_payment_hist_dists dist
8758                 SET dist.pa_addition_flag = 'Z',
8759                     request_id = G_REQUEST_ID,
8760                     last_update_date=SYSDATE,
8761                     last_updated_by= G_USER_ID,
8762                     last_update_login= G_USER_ID,
8763                     program_id= G_PROG_ID,
8764                     program_application_id= G_PROG_APPL_ID,
8765                     program_update_date=SYSDATE
8766             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
8767                AND EXISTS (SELECT NULL
8768                            FROM   ap_payment_history_all hist
8769                            WHERE  hist.payment_history_id = dist.payment_history_id
8770                            AND    hist.posted_flag = 'Y')
8771                AND EXISTS (SELECT aid.invoice_id
8772                              FROM AP_invoice_distributions aid
8773                             WHERE aid.invoice_distribution_id  = dist.invoice_distribution_id
8774                               AND aid.project_id > 0
8775                               AND  nvl(aid.encumbered_flag,'N') = 'R' ) ;
8776 
8777             write_log(LOG, 'Number of distributions marked for encumbered net zero adjustment: ' || to_char(SQL%ROWCOUNT));
8778 
8779       END IF;
8780       --
8781       -- End of If section checking if G_PROJECT_ID is not null
8782       --
8783 
8784     ELSE
8785 
8786        -- Process Invoices
8787 
8788       IF G_PROJECT_ID IS NOT NULL THEN
8789 
8790         -- The program should update the pa_addition_flag for all encumbered lines marked as R to netzero adj flag.
8791         -- R indicates a line to be ignored by encumbrance and validation code because neither the original nor the
8792         -- reversal distributions were looked at and they offset each other so, they can be ignored and marked as Z.
8793         -- (This is set only if the parent one is not validated as well. Otherwise the reversal one will also be encumbered).
8794         -- Since these lines have been not encumbered, there exist no Budgetery control commitment records for these in PA
8795 
8796             UPDATE ap_payment_hist_dists dist
8797                 SET dist.pa_addition_flag = 'Z',
8798                     request_id = G_REQUEST_ID,
8799                     last_update_date=SYSDATE,
8800                     last_updated_by= G_USER_ID,
8801                     last_update_login= G_USER_ID,
8802                     program_id= G_PROG_ID,
8803                     program_application_id= G_PROG_APPL_ID,
8804                     program_update_date=SYSDATE
8805             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
8806                AND EXISTS (SELECT NULL
8807                            FROM   ap_payment_history_all hist
8808                            WHERE  hist.payment_history_id = dist.payment_history_id
8809                            AND    hist.posted_flag = 'Y')
8810                AND EXISTS (SELECT aid.invoice_id
8811                              FROM AP_invoice_distributions aid
8812                             WHERE aid.invoice_distribution_id  = dist.invoice_distribution_id
8813                               AND aid.project_id = G_PROJECT_ID
8814                               AND ( nvl(aid.encumbered_flag,'N') = 'R' )) ;
8815 
8816             write_log(LOG, 'Number of distributions marked for encumbered net zero adjustment: ' || to_char(SQL%ROWCOUNT));
8817 
8818      ELSE /* G_PROJECT_ID is null */
8819 
8820             -- This update is to mark the pa addition flag of all invoice distributions
8821             -- which have encumbered flag of 'R' or reversal flag of 'Y' to 'Z'.
8822             -- Encumbrance flag of 'R' or reversal flag of 'Y' indicates that they are
8823             -- exact reversal of another invoice distribution.
8824             -- If the invoice distribution has a encumbered flag value of 'R' then it is
8825             -- not encumbered and there exist no Budgetery control commitment records
8826             -- for these in PA
8827 
8828             UPDATE ap_payment_hist_dists dist
8829                 SET dist.pa_addition_flag = 'Z',
8830                     request_id = G_REQUEST_ID,
8831                     last_update_date=SYSDATE,
8832                     last_updated_by= G_USER_ID,
8833                     last_update_login= G_USER_ID,
8834                     program_id= G_PROG_ID,
8835                     program_application_id= G_PROG_APPL_ID,
8836                     program_update_date=SYSDATE
8837             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
8838                AND EXISTS (SELECT NULL
8839                            FROM   ap_payment_history_all hist
8840                            WHERE  hist.payment_history_id = dist.payment_history_id
8841                            AND    hist.posted_flag = 'Y')
8842                AND EXISTS (SELECT aid.invoice_id
8843                              FROM AP_invoice_distributions aid
8844                             WHERE aid.invoice_distribution_id  = dist.invoice_distribution_id
8845                               AND aid.project_id > 0
8846                               AND ( nvl(aid.encumbered_flag,'N') = 'R' )) ;
8847 
8848      write_log(LOG, 'Number of distributions marked for encumbered net zero adjustment: ' || to_char(SQL%ROWCOUNT));
8849 
8850      END IF;
8851 
8852      END IF;
8853      G_err_stack := v_old_stack;
8854 
8855 EXCEPTION
8856         WHEN Others THEN
8857                /*
8858                --
8859                -- Exceptions occured in this procedure must be raised by the
8860                -- UPDATE statement, most likely a fatal error like 'rollback
8861                -- segment exceeded' error which should cause the program to
8862                -- terminate
8863                --
8864                */
8865 
8866 	       G_err_stack := v_old_stack;
8867                G_err_code := SQLCODE;
8868 	       raise;
8869 
8870 
8871 END net_zero_pay_adjustment;
8872 
8873 /*-----------------------Marking Distribution Phase---------------------*/
8874 
8875 PROCEDURE mark_PA_Pay_flag_O IS
8876 
8877         v_old_stack VARCHAR2(630);
8878 
8879 BEGIN
8880 
8881      v_old_stack := G_err_stack;
8882      G_err_stack := G_err_stack || '->PAAPIMP_PKG.mark_PA_Pay_flag_O';
8883      G_err_code := 0;
8884      G_err_stage := 'UPDATING PAYMENT DISTRIBUTIONS-Marking Process';
8885 
8886      write_log(LOG, G_err_stack);
8887 
8888      IF G_INVOICE_TYPE = 'EXPENSE REPORT' THEN
8889                    --
8890                    -- This section is for Expense Reports
8891                    --
8892 
8893           write_log(LOG, 'Marking Expense Report type invoices for processing...');
8894                    --
8895           IF G_PROJECT_ID IS NOT NULL THEN
8896 
8897             UPDATE ap_payment_hist_dists dist
8898                 SET dist.pa_addition_flag = 'O',
8899                     request_id = G_REQUEST_ID,
8900                     last_update_date=SYSDATE,
8901                     last_updated_by= G_USER_ID,
8902                     last_update_login= G_USER_ID,
8903                     program_id= G_PROG_ID,
8904                     program_application_id= G_PROG_APPL_ID,
8905                     program_update_date=SYSDATE
8906             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
8907             AND   dist.pay_dist_lookup_code = 'CASH'
8908             AND EXISTS (SELECT NULL
8909                         FROM   ap_payment_history_all hist
8910                         WHERE  hist.payment_history_id = dist.payment_history_id
8911                         AND    hist.posted_flag = 'Y')
8912             AND   exists (SELECT inv.invoice_id
8913                            FROM AP_INVOICES inv,
8914                                 PO_VENDORS vend,
8915                                 AP_Invoice_Distributions_all aid,
8916                                 ap_invoice_payments_all aip
8917                           WHERE inv.invoice_id = aid.invoice_id
8918                             AND inv.vendor_id = vend.vendor_id
8919                             AND aip.invoice_payment_id = dist.invoice_payment_id
8920                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
8921                             AND aid.pa_addition_flag  = 'N'                      --to avoid any historical data to be processed as Payments
8922                             AND nvl(aid.historical_flag,'N') = 'N'
8923                             AND aid.invoice_id = aip.invoice_id
8924                             AND aid.project_id = G_PROJECT_ID
8925                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
8926                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)) /*GSCC*/
8927                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
8928                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2,
8929                                       G_INVOICE_SOURCE3)
8930                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
8931                                  OR
8932                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
8933                                  AND inv.source  in ('CREDIT CARD','Both Pay')
8934                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)));
8935 
8936         G_PAY_DISTRIBUTIONS_MARKED := SQL%ROWCOUNT;
8937         write_log(LOG, 'Number of Invoice - Payment rows marked to O: ' || to_char(SQL%ROWCOUNT));
8938 
8939         /* For Prepayment Application , we need to interface the prepay application lines created in ap_prepay_app_dists table*/
8940 
8941             UPDATE ap_prepay_app_dists dist
8942             SET    dist.pa_addition_flag = 'O',
8943                    request_id = G_REQUEST_ID,
8944                    last_update_date=SYSDATE,
8945                    last_updated_by= G_USER_ID,
8946                    last_update_login= G_USER_ID,
8947                    program_id= G_PROG_ID,
8948                    program_application_id= G_PROG_APPL_ID,
8949                    program_update_date=SYSDATE
8950             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
8951             AND   dist.amount <>0
8952             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
8953                            FROM AP_INVOICES_ALL inv,
8954                                 PO_VENDORS vend,
8955                                 PO_Distributions_all PO,
8956                                 AP_Invoice_Distributions_all aid, --STD INV DIST LINE
8957                                 AP_Invoice_Distributions_all aid2 -- PREPAY APPL DIST LINE
8958                           WHERE aid.invoice_id = inv.invoice_id
8959                             AND inv.vendor_id = vend.vendor_id
8960                             AND inv.org_id = G_ORG_ID
8961                             AND aid.invoice_distribution_id = dist.invoice_distribution_id  -- Std inv line
8962                             AND aid2.invoice_id = aid.invoice_id
8963                             AND aid2.invoice_distribution_id =  dist.prepay_app_distribution_id --Prepay appl line
8964                             --AND aid2.line_type_lookup_code in ( 'PREPAY', 'NONREC_TAX') -- bug#5514129
8965                             AND aid.line_type_lookup_code  <> 'REC_TAX' -- bug#5514129
8966                             and aid2.prepay_distribution_id is not null
8967                             AND aid2.pa_addition_flag  in ( 'N','E')         --to avoid any historical data to be processed as Payments
8968                              -- pa-addition-flag E to pull in rec tax across which prepay appl is prorated
8969                             AND aid2.posted_flag = 'Y'
8970                             AND aid.project_id = G_PROJECT_ID
8971                             AND trunc(aid2.Accounting_Date) <= trunc(nvl(G_GL_DATE,aid2.Accounting_Date))
8972                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
8973                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
8974                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
8975                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
8976                                  OR
8977                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
8978                                  AND inv.source in ('CREDIT CARD','Both Pay')
8979                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)));
8980 
8981           G_PAY_DISTRIBUTIONS_MARKED := nvl(G_PAY_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
8982           write_log(LOG, 'Number of Prepayment Application Dist rows marked to O: ' || to_char(SQL%ROWCOUNT));
8983 
8984       ELSE /* G_PROJECT_ID IS NULL */
8985 
8986 
8987             UPDATE ap_payment_hist_dists dist
8988                 SET dist.pa_addition_flag = 'O',
8989                     request_id = G_REQUEST_ID,
8990                     last_update_date=SYSDATE,
8991                     last_updated_by= G_USER_ID,
8992                     last_update_login= G_USER_ID,
8993                     program_id= G_PROG_ID,
8994                     program_application_id= G_PROG_APPL_ID,
8995                     program_update_date=SYSDATE
8996             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
8997             AND   dist.pay_dist_lookup_code = 'CASH'
8998             AND EXISTS (SELECT NULL
8999                         FROM   ap_payment_history_all hist
9000                         WHERE  hist.payment_history_id = dist.payment_history_id
9001                         AND    hist.posted_flag = 'Y')
9002             AND  exists (SELECT inv.invoice_id
9003                            FROM AP_INVOICES_ALL inv,
9004                                 PO_VENDORS vend,
9005                                 AP_Invoice_Distributions_all aid,
9006                                 ap_invoice_payments_all aip
9007                           WHERE inv.vendor_id = vend.vendor_id
9008                             AND aid.invoice_id = inv.invoice_id
9009                             AND inv.org_id = G_ORG_ID
9010                             AND aip.invoice_payment_id = dist.invoice_payment_id
9011                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
9012                             AND aid.invoice_id = aip.invoice_id
9013                             AND aid.project_id > 0
9014                             AND aid.pa_addition_flag  = 'N'                      --to avoid any historical data to be processed as Payments
9015                             AND nvl(aid.historical_flag,'N') = 'N'
9016                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
9017                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)) /*GSCC*/
9018                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
9019                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2,
9020                                       G_INVOICE_SOURCE3)
9021                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
9022                                  OR
9023                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
9024                                  AND inv.source  in ('CREDIT CARD','Both Pay')
9025                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)));
9026 
9027         G_PAY_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
9028         write_log(LOG, 'Number of Invoice - Payment rows marked to O: ' || to_char(SQL%ROWCOUNT));
9029 
9030         /* For Prepayment Application , we need to interface the prepay application lines created in ap_prepay_app_dists table*/
9031 
9032             UPDATE ap_prepay_app_dists dist
9033             SET    dist.pa_addition_flag = 'O',
9034                    request_id = G_REQUEST_ID,
9035                    last_update_date=SYSDATE,
9036                    last_updated_by= G_USER_ID,
9037                    last_update_login= G_USER_ID,
9038                    program_id= G_PROG_ID,
9039                    program_application_id= G_PROG_APPL_ID,
9040                    program_update_date=SYSDATE
9041             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
9042             AND   dist.amount <>0
9043             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
9044                            FROM AP_INVOICES_ALL inv,
9045                                 PO_VENDORS vend,
9046                                 PO_Distributions_all PO,
9047                                 AP_Invoice_Distributions_all aid, --STD INV DIST LINE
9048                                 AP_Invoice_Distributions_all aid2 -- PREPAY APPL DIST LINE
9049                           WHERE aid.invoice_id = inv.invoice_id
9050                             AND inv.vendor_id = vend.vendor_id
9051                             AND inv.org_id = G_ORG_ID
9052                             AND aid.invoice_distribution_id = dist.invoice_distribution_id  -- Std inv line
9053                             AND aid2.invoice_id = aid.invoice_id
9054                             AND aid2.invoice_distribution_id =  dist.prepay_app_distribution_id --Prepay appl line
9055                             --AND aid2.line_type_lookup_code in ( 'PREPAY', 'NONREC_TAX') -- bug#5514129
9056                             AND aid.line_type_lookup_code  <> 'REC_TAX' -- bug#5514129
9057                             AND aid2.pa_addition_flag  in ( 'N','E')         --to avoid any historical data to be processed as Payments
9058                              -- pa-addition-flag E to pull in rec tax across which prepay appl is prorated
9059                             and aid2.prepay_distribution_id is not null
9060                             AND aid2.posted_flag = 'Y'
9061                             AND aid.project_id > 0
9062                             AND trunc(aid2.Accounting_Date) <= trunc(nvl(G_GL_DATE,aid2.Accounting_Date))
9063                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date))
9064                             AND ((inv.invoice_type_lookup_code = G_INVOICE_TYPE
9065                                   AND inv.source IN (G_INVOICE_SOURCE1, G_INVOICE_SOURCE2, G_INVOICE_SOURCE3)
9066                                   AND (vend.employee_id IS NOT NULL or nvl(inv.paid_on_behalf_employee_id,0) > 0))
9067                                  OR
9068                                 (inv.invoice_type_lookup_code   in ('STANDARD','CREDIT','MIXED') /*Bug# 3373933*/ /*Bug 4099522*/
9069                                  AND inv.source  in ('CREDIT CARD','Both Pay')
9070                                  AND nvl(inv.PAID_ON_BEHALF_EMPLOYEE_ID,0) > 0)));
9071 
9072           G_PAY_DISTRIBUTIONS_MARKED := nvl(G_PAY_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
9073           write_log(LOG, 'Number of Prepayment Application Dist rows marked to O: ' || to_char(SQL%ROWCOUNT));
9074 
9075         END IF; /* END IF Project ID */
9076 
9077      ELSE
9078 
9079 	   write_log(LOG, 'Marking Payments - supplier invoices for processing...');
9080 
9081              --
9082              -- Due to performance reasons the single update statement was
9083              -- broken up into two update statements based on if the program
9084              -- has the value of project id (If the user has given project number
9085              -- as one of the parameters).
9086              --
9087 
9088             IF G_PROJECT_ID IS NOT NULL THEN
9089 
9090           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
9091 
9092             UPDATE ap_payment_hist_dists dist
9093             SET    dist.pa_addition_flag = 'O',
9094                    request_id = G_REQUEST_ID,
9095                    last_update_date=SYSDATE,
9096                    last_updated_by= G_USER_ID,
9097                    last_update_login= G_USER_ID,
9098                    program_id= G_PROG_ID,
9099                    program_application_id= G_PROG_APPL_ID,
9100                    program_update_date=SYSDATE
9101             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
9102             AND   dist.pay_dist_lookup_code = 'CASH'
9103             AND EXISTS (SELECT NULL
9104                         FROM   ap_payment_history_all hist
9105                         WHERE  hist.payment_history_id = dist.payment_history_id
9106                         AND    hist.posted_flag = 'Y')
9107             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
9108                            FROM AP_INVOICES_ALL inv,
9109                                 PO_Distributions_all PO,
9110                                 AP_Invoice_Distributions_all aid,
9111                                 ap_invoice_payments_all aip
9112                           WHERE inv.invoice_id = aip.invoice_id
9113                             AND aid.invoice_id = inv.invoice_id
9114                             AND inv.org_id = G_ORG_ID
9115                             AND aip.invoice_payment_id = dist.invoice_payment_id
9116                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
9117                             AND aid.line_type_lookup_code <> 'TERV'             -- Bug#5441030 to avoid zero dollar lines for TERV
9118                             AND aid.invoice_id = aip.invoice_id
9119                             AND aid.pa_addition_flag  = 'N'                      --to avoid any historical data to be processed as Payments
9120                             AND nvl(aid.historical_flag,'N') = 'N'
9121                             AND aid.po_distribution_id = PO.po_distribution_id (+)
9122                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
9123                             AND inv.paid_on_behalf_employee_id IS NULL
9124                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
9125                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
9126                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
9127                             AND aid.project_id = G_PROJECT_ID
9128                             AND aid.line_type_lookup_code <> 'REC_TAX'
9129                             AND (((
9130                                PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(aid.project_ID, 0))= 'N'
9131                                OR
9132                                PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(aid.po_distribution_id,0))= 'N' )
9133                             AND aid.line_type_lookup_code IN ('ITEM','ACCRUAL')) OR
9134                             (aid.line_type_lookup_code NOT IN ('ITEM','ACCRUAL')))
9135                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
9136                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
9137 
9138           G_PAY_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
9139         write_log(LOG, 'Number of Invoice - Payment rows marked to O: ' || to_char(SQL%ROWCOUNT));
9140 
9141         /* For Prepayment Application , we need to interface the prepay application lines created in ap_prepay_app_dists table*/
9142 
9143             UPDATE ap_prepay_app_dists dist
9144             SET    dist.pa_addition_flag = 'O',
9145                    request_id = G_REQUEST_ID,
9146                    last_update_date=SYSDATE,
9147                    last_updated_by= G_USER_ID,
9148                    last_update_login= G_USER_ID,
9149                    program_id= G_PROG_ID,
9150                    program_application_id= G_PROG_APPL_ID,
9151                    program_update_date=SYSDATE
9152             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
9153             AND   dist.amount <> 0
9154             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
9155                            FROM AP_INVOICES_ALL inv,
9156                                 PO_Distributions_all PO,
9157                                 AP_Invoice_Distributions_all aid, --STD INV DIST LINE
9158                                 AP_Invoice_Distributions_all aid2 -- PREPAY APPL DIST LINE
9159                           WHERE aid.invoice_id = inv.invoice_id
9160                             AND aid.invoice_distribution_id = dist.invoice_distribution_id  -- Std inv line
9161                             AND inv.org_id = G_ORG_ID
9162                             AND aid2.invoice_id = aid.invoice_id
9163                             AND aid2.invoice_distribution_id =  dist.prepay_app_distribution_id --Prepay appl line
9164                             --AND aid2.line_type_lookup_code in ( 'PREPAY', 'NONREC_TAX') -- bug#5514129
9165                             AND aid.line_type_lookup_code  <> 'REC_TAX' -- bug#5514129
9166                             AND aid2.pa_addition_flag  in ( 'N','E')         --to avoid any historical data to be processed as Payments
9167                              -- pa-addition-flag E to pull in rec tax across which prepay appl is prorated
9168                             and aid2.prepay_distribution_id is not null
9169                             AND aid2.posted_flag = 'Y'
9170                             AND aid.po_distribution_id = PO.po_distribution_id (+)
9171                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
9172                             AND inv.paid_on_behalf_employee_id IS NULL
9173                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
9174                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
9175                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
9176                             AND aid.project_id = G_PROJECT_ID
9177                             AND (((
9178                                PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(aid.project_ID, 0))= 'N'
9179                                OR
9180                                PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(aid.po_distribution_id,0))= 'N' )
9181                             AND aid.line_type_lookup_code IN ('ITEM','ACCRUAL')) OR
9182                             (aid.line_type_lookup_code NOT IN ('ITEM','ACCRUAL')))
9183                             AND trunc(aid2.Accounting_Date) <= trunc(nvl(G_GL_DATE,aid2.Accounting_Date))
9184                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
9185 
9186           G_PAY_DISTRIBUTIONS_MARKED := nvl(G_PAY_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
9187           write_log(LOG, 'Number of Prepayment Application Dist rows marked to O: ' || to_char(SQL%ROWCOUNT));
9188 
9189         ELSE          /* G_PROJECT_ID IS NULL */
9190 
9191 
9192           -- Update pa-addition-flag to O for all valid ap distributions that should be interfaced to Projects
9193 
9194             UPDATE ap_payment_hist_dists dist
9195             SET    dist.pa_addition_flag = 'O',
9196                    request_id = G_REQUEST_ID,
9197                    last_update_date=SYSDATE,
9198                    last_updated_by= G_USER_ID,
9199                    last_update_login= G_USER_ID,
9200                    program_id= G_PROG_ID,
9201                    program_application_id= G_PROG_APPL_ID,
9202                    program_update_date=SYSDATE
9203             WHERE  nvl(dist.pa_addition_flag,'N') = 'N'
9204             AND    dist.pay_dist_lookup_code = 'CASH'
9205             AND EXISTS (SELECT NULL
9206                         FROM   ap_payment_history_all hist
9207                         WHERE  hist.payment_history_id = dist.payment_history_id
9208                         AND    hist.posted_flag = 'Y')
9209             AND    exists(SELECT /*+ no_unnest */ inv.invoice_id
9210                            FROM AP_INVOICES_ALL inv,
9211                                 PO_Distributions_all PO,
9212                                 AP_Invoice_Distributions_all aid,
9213                                 ap_invoice_payments_all aip
9214                           WHERE inv.invoice_id = aip.invoice_id
9215                             AND aid.invoice_id = inv.invoice_id
9216                             AND inv.org_id = G_ORG_ID
9217                             AND aip.invoice_payment_id = dist.invoice_payment_id
9218                             AND aid.invoice_distribution_id = dist.invoice_distribution_id
9219                             AND aid.line_type_lookup_code <> 'TERV'             -- Bug#5441030 to avoid zero dollar lines for TERV
9220                             AND aid.invoice_id = aip.invoice_id
9221                             AND aid.pa_addition_flag  = 'N'                      --to avoid any historical data to be processed as Payments
9222                             AND nvl(aid.historical_flag,'N') = 'N'
9223                             AND aid.po_distribution_id = PO.po_distribution_id (+)
9224                             AND   nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
9225                             AND inv.paid_on_behalf_employee_id IS NULL
9226                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
9227                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
9228                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
9229                             AND aid.project_id > 0
9230                             AND aid.line_type_lookup_code <> 'REC_TAX'
9231                             AND (((
9232                                PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(aid.project_ID, 0))= 'N'
9233                                OR
9234                                PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(aid.po_distribution_id,0))= 'N' )
9235                             AND aid.line_type_lookup_code IN ('ITEM','ACCRUAL')) OR
9236                             (aid.line_type_lookup_code NOT IN ('ITEM','ACCRUAL')))
9237                             AND trunc(aip.Accounting_Date) <= trunc(nvl(G_GL_DATE,aip.Accounting_Date))
9238                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
9239 
9240         G_PAY_DISTRIBUTIONS_MARKED :=  SQL%ROWCOUNT;
9241         write_log(LOG, 'Number of Invoice - Payment rows marked to O: ' || to_char(SQL%ROWCOUNT));
9242 
9243         /* For Prepayment Application , we need to interface the prepay application lines created in ap_prepay_app_dists table*/
9244 
9245             UPDATE ap_prepay_app_dists dist
9246             SET    dist.pa_addition_flag = 'O',
9247                    request_id = G_REQUEST_ID,
9248                    last_update_date=SYSDATE,
9249                    last_updated_by= G_USER_ID,
9250                    last_update_login= G_USER_ID,
9251                    program_id= G_PROG_ID,
9252                    program_application_id= G_PROG_APPL_ID,
9253                    program_update_date=SYSDATE
9254             WHERE nvl(dist.pa_addition_flag,'N') = 'N'
9255             AND   dist.amount <> 0
9256             AND   exists(SELECT /*+ no_unnest */ inv.invoice_id
9257                            FROM AP_INVOICES_ALL inv,
9258                                 PO_Distributions_all PO,
9259                                 AP_Invoice_Distributions_all aid, --STD INV DIST LINE
9260                                 AP_Invoice_Distributions_all aid2 -- PREPAY APPL DIST LINE
9261                           WHERE aid.invoice_id = inv.invoice_id
9262                             AND inv.org_id = G_ORG_ID
9263                             AND aid.invoice_distribution_id = dist.invoice_distribution_id  -- Std inv line
9264                             AND aid2.invoice_id = aid.invoice_id
9265                             AND aid2.invoice_distribution_id =  dist.prepay_app_distribution_id --Prepay appl line
9266                             --AND aid2.line_type_lookup_code in ( 'PREPAY', 'NONREC_TAX') -- bug#5514129
9267                             AND aid.line_type_lookup_code  <> 'REC_TAX' -- bug#5514129
9268                             AND aid2.pa_addition_flag  in ( 'N','E')         --to avoid any historical data to be processed as Payments
9269                              -- pa-addition-flag E to pull in rec tax across which prepay appl is prorated
9270                             and aid2.prepay_distribution_id is not null
9271                             AND aid2.posted_flag = 'Y'
9272                             AND aid.po_distribution_id = PO.po_distribution_id (+)
9273                             AND nvl(po.distribution_type,'XXX') <> 'PREPAYMENT'
9274                             AND inv.paid_on_behalf_employee_id IS NULL
9275                             AND NVL(PO.destination_type_code, 'EXPENSE') = 'EXPENSE'
9276                             AND inv.invoice_type_lookup_code <> 'EXPENSE REPORT'
9277                             AND  nvl(INV.source, 'xx' ) NOT IN ('Oracle Project Accounting', 'PA_IC_INVOICES')
9278                             AND aid.project_id> 0
9279                             AND (((
9280                                PA_PJC_CWK_UTILS.Is_cwk_tc_xface_allowed(nvl(aid.project_ID, 0))= 'N'
9281                                OR
9282                                PA_PJC_CWK_UTILS.Is_rate_based_line(null,nvl(aid.po_distribution_id,0))= 'N' )
9283                             AND aid.line_type_lookup_code IN ('ITEM','ACCRUAL')) OR
9284                             (aid.line_type_lookup_code NOT IN ('ITEM','ACCRUAL')))
9285                             AND trunc(aid2.Accounting_Date) <= trunc(nvl(G_GL_DATE,aid2.Accounting_Date))
9286                             AND trunc(aid.expenditure_item_date) <= trunc(nvl(G_TRANSACTION_DATE,aid.expenditure_item_date)));
9287 
9288         G_PAY_DISTRIBUTIONS_MARKED := nvl(G_PAY_DISTRIBUTIONS_MARKED,0) + SQL%ROWCOUNT;
9289         write_log(LOG, 'Number of Prepayment Application Dist rows marked to O: ' || to_char(SQL%ROWCOUNT));
9290 
9291 
9292        END IF;
9293          -- End of If section checking if G_PROJECT_ID is not null
9294      END IF; -- End of Invoice Type is Expense Report
9295 
9296      write_log(LOG, 'Total Number of Payment rows marked to O: ' || to_char(G_PAY_DISTRIBUTIONS_MARKED));
9297 
9298      G_err_stack := v_old_stack;
9299 
9300 EXCEPTION
9301      WHEN Others THEN
9302            -- Marking phase failed, raise exception to main program to terminate the program
9303            --
9304            G_err_stack := v_old_stack;
9305            G_err_code := SQLCODE;
9306            RAISE;
9307 
9308 END mark_PA_Pay_flag_O;
9309 
9310 PROCEDURE transfer_pay_to_pa  IS
9311 
9312    v_num_invoices_fetched          NUMBER :=0;
9313    v_num_distributions_fetched     NUMBER :=0;
9314    v_prev_invoice_id               NUMBER := 0;
9315    v_prev_vendor_id                NUMBER := 0;
9316    v_old_stack                     VARCHAR2(630);
9317    v_err_message                   VARCHAR2(220);
9318    v_all_done                      NUMBER := 0;
9319    v_prev_invoice_source           ap_invoices.source%TYPE := NULL;
9320    v_prev_transaction_source       pa_transaction_sources.transaction_source%TYPE;
9321    v_num_tax_lines_fetched         NUMBER:=0;
9322    v_num_inv_variance_fetched      NUMBER:=0;    --NEW
9323    v_num_inv_erv_fetched           NUMBER:=0;    --NEW
9324    v_num_inv_frt_fetched           NUMBER:=0;    --NEW
9325    v_num_inv_prepay_fetched        NUMBER:=0;    --NEW
9326    v_last_inv_ER_flag              VARCHAR2(1);
9327 
9328    v_status Number := 0;
9329    v_stage  Number :=0;
9330    v_business_group_id NUMBER := 0;
9331    v_attribute_category VARCHAR2(150);
9332    v_attribute1 VARCHAR2(150);
9333    v_attribute2 VARCHAR2(150);
9334    v_attribute3 VARCHAR2(150);
9335    v_attribute4 VARCHAR2(150);
9336    v_attribute5 VARCHAR2(150);
9337    v_attribute6 VARCHAR2(150);
9338    v_attribute7 VARCHAR2(150);
9339    v_attribute8 VARCHAR2(150);
9340    v_attribute9 VARCHAR2(150);
9341    v_attribute10 VARCHAR2(150);
9342    v_dff_map_status VARCHAR2(30);
9343    dff_map_exception EXCEPTION;
9344 
9345    v_num_last_invoice_processed NUMBER := 0;
9346    v_last_inv_index             NUMBER := 0;
9347    v_num_dist_marked_O          NUMBER := 0;
9348    v_num_dist_remain            NUMBER := 0;
9349    v_max_size                   NUMBER := 0;
9350 
9351    v_inv_batch_size             NUMBER := 0;
9352    v_tax_batch_size             NUMBER := 0;
9353    v_var_batch_size             NUMBER := 0;
9354    v_frt_batch_size             NUMBER := 0;
9355 
9356 -- For PA IP Invoices
9357    L_IP_TRANSACTION_SOURCE         pa_transaction_interface.transaction_source%TYPE;
9358    l_ap_inv_flag                   VARCHAR2(1):= 'N';
9359    l_ip_inv_flag                   VARCHAR2(1):= 'N';
9360 
9361    l_create_adj_recs  VARCHAR2(1) := 'N';
9362    l_ap_prepay_tax_flag    VARCHAR2(1):= 'N'; -- Flag to indicate tax  exist for prepay appl in Cash Basis flow.
9363    l_ap_prepay_var_flag    VARCHAR2(1):= 'N'; -- Flag to indicate variance exist for prepay appl lines in Cash Basis flow.
9364    l_ap_prepay_erv_flag    VARCHAR2(1):= 'N'; -- Flag to indicate erv exist for prepay appl lines in Cash Basis flow.
9365 
9366    /* the following sub-procedure is declared here to save lines of code since deleting
9367       plsql tables will be done multiple times within the procedure transfer_pay_to_pa */
9368 
9369    PROCEDURE clear_plsql_tables IS
9370 
9371        l_status1 VARCHAR2(30);
9372 
9373    BEGIN
9374 
9375        G_err_stage := 'within clear_plsql_tables of transfer_pay_to_pa';
9376        write_log(LOG, G_err_stage);
9377 
9378        l_invoice_id_tbl.delete;
9379        l_created_by_tbl.delete;
9380        l_invoice_dist_id_tbl.delete; --NEW
9381        l_project_id_tbl.delete;
9382        l_task_id_tbl.delete;
9383        l_ln_type_lookup_tbl.delete;
9384        l_exp_type_tbl.delete;
9385        l_ei_date_tbl.delete;
9386        l_amount_tbl.delete;
9387        l_description_tbl.delete;
9388        l_justification_tbl.delete;
9389        l_dist_cc_id_tbl.delete;
9390        l_exp_org_id_tbl.delete;
9391        l_quantity_tbl.delete;
9392        l_acct_pay_cc_id_tbl.delete;
9393        l_gl_date_tbl.delete;
9394        l_attribute_cat_tbl.delete;
9395        l_attribute1_tbl.delete;
9396        l_attribute2_tbl.delete;
9397        l_attribute3_tbl.delete;
9398        l_attribute4_tbl.delete;
9399        l_attribute5_tbl.delete;
9400        l_attribute6_tbl.delete;
9401        l_attribute7_tbl.delete;
9402        l_attribute8_tbl.delete;
9403        l_attribute9_tbl.delete;
9404        l_attribute10_tbl.delete;
9405        l_rec_cur_amt_tbl.delete;
9406        l_rec_cur_code_tbl.delete;
9407        l_rec_conv_rate_tbl.delete;
9408        l_denom_raw_cost_tbl.delete;
9409        l_denom_cur_code_tbl.delete;
9410        l_acct_rate_date_tbl.delete;
9411        l_acct_rate_type_tbl.delete;
9412        l_acct_exch_rate_tbl.delete;
9413        l_job_id_tbl.delete;
9414        l_employee_id_tbl.delete;
9415        l_vendor_id_tbl.delete;
9416        l_inv_type_code_tbl.delete;
9417        l_source_tbl.delete;
9418        l_org_id_tbl.delete;
9419        l_invoice_num_tbl.delete;
9420        l_cdl_sys_ref3_tbl.delete;
9421        l_cdl_sys_ref4_tbl.delete;
9422        l_po_dist_id_tbl.delete;
9423        l_txn_src_tbl.delete;
9424        l_user_txn_src_tbl.delete;
9425        l_batch_name_tbl.delete;
9426        l_interface_id_tbl.delete;
9427        l_exp_end_date_tbl.delete;
9428        l_txn_status_code_tbl.delete;
9429        l_txn_rej_code_tbl.delete;
9430        l_po_dist_id_tbl.delete;
9431        l_bus_grp_id_tbl.delete;
9432        l_paid_emp_id_tbl.delete;
9433        l_sort_var_tbl.delete;
9434        l_reversal_flag_tbl.delete;
9435        l_cancel_flag_tbl.delete;
9436        l_parent_rev_id_tbl.delete;
9437        l_net_zero_flag_tbl.delete;
9438        l_sc_xfer_code_tbl.delete;
9439        l_adj_exp_item_id_tbl.delete;
9440        l_fc_enabled_tbl.delete;
9441        l_fc_document_type_tbl.delete;
9442        l_rev_parent_dist_id_tbl.delete;
9443        l_rev_child_dist_id_tbl.delete;
9444        l_rev_parent_dist_ind_tbl.delete;
9445        l_si_assts_add_flg_tbl.delete;
9446        l_pay_hist_id_tbl.delete;
9447        l_prepay_dist_id_tbl.delete;
9448        l_rev_index:=0;
9449 
9450     END clear_plsql_tables;
9451 
9452    /* the following sub-procedure is declared here to save lines of code since bulk insert
9453       will be done multiple times within the procedure transfer_pay_to_pa */
9454 
9455     PROCEDURE bulk_update_trx_intf IS
9456 
9457      BEGIN
9458 
9459        /* The records with INSERT_FLAG = F indicate that they are fully applied prepayments and the pa-addition-flag
9460           for such records will be updated to G to relieve commitments*/
9461        /* The records with INSERT_FLAG = P indicate that they are partially applied prepayments and the pa-addition-flag
9462           for such records will be updated to N */
9463 
9464        write_log(LOG,'Before bulk update  of prepayment payments');
9465 
9466        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
9467 
9468          UPDATE ap_payment_hist_dists dist
9469             SET dist.pa_addition_flag         = decode(l_insert_flag_tbl(i),'F','G','P','N')
9470           WHERE dist.invoice_payment_id       = l_inv_pay_id_tbl(i)
9471             AND dist.pay_dist_lookup_code     = 'CASH'
9472             AND dist.invoice_distribution_id  = l_invoice_dist_id_tbl(i)
9473             AND dist.pa_addition_flag         = 'O'
9474             AND l_insert_flag_tbl(i)         in ('P','F');
9475 
9476      EXCEPTION
9477       WHEN OTHERS THEN
9478           write_log(LOG,'Failed during bulk update for prepayment processing');
9479           G_err_code   := SQLCODE;
9480           write_log(LOG, 'Error Code is '||SQLCODE);
9481           write_log(LOG, substr(SQLERRM, 1, 200));
9482           write_log(LOG, substr(SQLERRM, 201, 200));
9483           raise;
9484 
9485     END bulk_update_trx_intf;
9486 
9487 
9488     PROCEDURE bulk_insert_trx_intf IS
9489 
9490       l_status2 VARCHAR2(30);
9491 
9492     BEGIN
9493 
9494        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
9495 
9496        INSERT INTO pa_transaction_interface_all(
9497                      transaction_source
9498                     , user_transaction_source
9499                     , system_linkage
9500                     , batch_name
9501                     , expenditure_ending_date
9502                     , expenditure_item_date
9503                     , expenditure_type
9504                     , quantity
9505                     , raw_cost_rate
9506                     , expenditure_comment
9507                     , transaction_status_code
9508                     , transaction_rejection_code
9509                     , orig_transaction_reference
9510                     , interface_id
9511                     , dr_code_combination_id
9512                     , cr_code_combination_id
9513                     , cdl_system_reference1
9514                     , cdl_system_reference2
9515                     , cdl_system_reference3
9516                     , cdl_system_reference4
9517                     , cdl_system_reference5 --NEW
9518                     , gl_date
9519                     , org_id
9520                     , unmatched_negative_txn_flag
9521                     , receipt_currency_amount
9522                     , receipt_currency_code
9523                     , receipt_exchange_rate
9524                     , denom_raw_cost
9525                     , denom_currency_code
9526                     , acct_rate_date
9527                     , acct_rate_type
9528                     , acct_exchange_rate
9529                     , acct_raw_cost
9530                     , acct_exchange_rounding_limit
9531                     , attribute_category
9532                     , attribute1
9533                     , attribute2
9534                     , attribute3
9535                     , attribute4
9536                     , attribute5
9537                     , attribute6
9538                     , attribute7
9539                     , attribute8
9540                     , attribute9
9541                     , attribute10
9542                     , orig_exp_txn_reference1
9543                     , orig_user_exp_txn_reference
9544                     , orig_exp_txn_reference2
9545                     , orig_exp_txn_reference3
9546                     , last_update_date
9547                     , last_updated_by
9548                     , creation_date
9549                     , created_by
9550                     , person_id
9551                     , organization_id
9552                     , project_id
9553                     , task_id
9554                     , Vendor_id
9555                     , override_to_organization_id
9556                     , person_business_group_id
9557                     , adjusted_expenditure_item_id --NEW
9558                     , fc_document_type  -- NEW
9559                     , document_type
9560                     , document_distribution_type
9561                     , sc_xfer_code
9562                     , si_assets_addition_flag
9563                     , net_zero_adjustment_flag
9564                    )
9565               SELECT  l_txn_src_tbl(i)
9566                      ,l_user_txn_src_tbl(i)
9567                      ,G_SYSTEM_LINKAGE
9568                      ,l_batch_name_tbl(i)
9569                      ,l_exp_end_date_tbl(i)
9570                      ,l_ei_date_tbl(i)
9571                      ,l_exp_type_tbl(i)
9572                      ,l_quantity_tbl(i)
9573                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
9574                      ,l_description_tbl(i)
9575                      ,l_txn_status_code_tbl(i)
9576                      ,l_txn_rej_code_tbl(i)
9577                      ,G_REQUEST_ID
9578                      ,l_interface_id_tbl(i)
9579                      ,l_dist_cc_id_tbl(i)
9580                      ,l_acct_pay_cc_id_tbl(i)
9581                      ,decode(l_ln_type_lookup_tbl(i),'PREPAY',l_vendor_id_tbl(i),l_pay_hist_id_tbl(i)) /*sysref1*/
9582                      ,l_invoice_id_tbl(i) /*sysref2*/
9583                      ,l_cdl_sys_ref3_tbl(i) /*sysref3*/
9584                      ,l_inv_pay_id_tbl(i) /*sysref4*/
9585                      ,l_invoice_dist_id_tbl(i) /*sysref5*/
9586                      ,l_gl_date_tbl(i)
9587                      ,G_ORG_ID
9588                      ,'Y'
9589                      ,l_rec_cur_amt_tbl(i)
9590                      ,l_rec_cur_code_tbl(i)
9591                      ,l_rec_conv_rate_tbl(i)
9592                      ,l_denom_raw_cost_tbl(i)
9593                      ,l_denom_cur_code_tbl(i)
9594                      ,l_acct_rate_date_tbl(i)
9595                      ,l_acct_rate_type_tbl(i)
9596                      ,l_acct_exch_rate_tbl(i)
9597                      ,l_amount_tbl(i)
9598                      ,1
9599                      ,l_attribute_cat_tbl(i)
9600                      ,l_attribute1_tbl(i)
9601                      ,l_attribute2_tbl(i)
9602                      ,l_attribute3_tbl(i)
9603                      ,l_attribute4_tbl(i)
9604                      ,l_attribute5_tbl(i)
9605                      ,l_attribute6_tbl(i)
9606                      ,l_attribute7_tbl(i)
9607                      ,l_attribute8_tbl(i)
9608                      ,l_attribute9_tbl(i)
9609                      ,l_attribute10_tbl(i)
9610                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
9611                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
9612                      ,DECODE(G_TRANS_DFF_AP,'N',NULL,l_invoice_id_tbl(i)) /*orig_exp_txn_reference2*/
9613                      ,NULL                       /*orig_exp_txn_reference3*/
9614                      ,SYSDATE
9615                      ,-1
9616                      ,SYSDATE
9617                      ,-1
9618                      ,l_employee_id_tbl(i)
9619                      ,l_org_id_tbl(i)
9620                      ,l_project_id_tbl(i)
9621                      ,l_task_id_tbl(i)
9622                      ,l_vendor_id_tbl(i)
9623                      ,l_exp_org_id_tbl(i)
9624                      ,l_bus_grp_id_tbl(i)
9625                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
9626                      ,l_fc_document_type_tbl(i) --NEW for funds check
9627                      ,l_inv_type_code_tbl(i)
9628                      ,l_ln_type_lookup_tbl(i)
9629                      ,l_sc_xfer_code_tbl(i)
9630                      ,l_si_assts_add_flg_tbl(i)
9631                      ,l_net_zero_flag_tbl(i)
9632                  FROM DUAL
9633                 WHERE l_insert_flag_tbl(i)     not in ('P','F');
9634 
9635               -- Insert the adjustment recs from AP.
9636     IF l_create_adj_recs = 'Y' THEN
9637 
9638                 write_log(LOG, 'Inserting adjustment records..');
9639 
9640        FORALL i IN l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST
9641 
9642        INSERT INTO pa_transaction_interface_all(
9643                      transaction_source
9644                     , user_transaction_source
9645                     , system_linkage
9646                     , batch_name
9647                     , expenditure_ending_date
9648                     , expenditure_item_date
9649                     , expenditure_type
9650                     , quantity
9651                     , raw_cost_rate
9652                     , expenditure_comment
9653                     , transaction_status_code
9654                     , transaction_rejection_code
9655                     , orig_transaction_reference
9656                     , interface_id
9657                     , dr_code_combination_id
9658                     , cr_code_combination_id
9659                     , cdl_system_reference1
9660                     , cdl_system_reference2
9661                     , cdl_system_reference3
9662                     , cdl_system_reference4
9663                     , cdl_system_reference5 --NEW
9664                     , gl_date
9665                     , org_id
9666                     , unmatched_negative_txn_flag
9667                     , receipt_currency_amount
9668                     , receipt_currency_code
9669                     , receipt_exchange_rate
9670                     , denom_raw_cost
9671                     , denom_currency_code
9672                     , acct_rate_date
9673                     , acct_rate_type
9674                     , acct_exchange_rate
9675                     , acct_raw_cost
9676                     , acct_exchange_rounding_limit
9677                     , attribute_category
9678                     , attribute1
9679                     , attribute2
9680                     , attribute3
9681                     , attribute4
9682                     , attribute5
9683                     , attribute6
9684                     , attribute7
9685                     , attribute8
9686                     , attribute9
9687                     , attribute10
9688                     , orig_exp_txn_reference1
9689                     , orig_user_exp_txn_reference
9690                     , orig_exp_txn_reference2
9691                     , orig_exp_txn_reference3
9692                     , last_update_date
9693                     , last_updated_by
9694                     , creation_date
9695                     , created_by
9696                     , person_id
9697                     , organization_id
9698                     , project_id
9699                     , task_id
9700                     , Vendor_id
9701                     , override_to_organization_id
9702                     , person_business_group_id
9703                     , adjusted_expenditure_item_id --NEW
9704                     , fc_document_type  -- NEW
9705                     , document_type
9706                     , document_distribution_type
9707                     , adjusted_txn_interface_id --NEW
9708                     , sc_xfer_code
9709                     , si_assets_addition_flag
9710                     , net_zero_adjustment_flag
9711                    )
9712                   SELECT
9713                       l_txn_src_tbl(i)
9714                      ,l_user_txn_src_tbl(i)
9715                      ,G_SYSTEM_LINKAGE
9716                      ,l_batch_name_tbl(i)
9717                      ,l_exp_end_date_tbl(i)
9718                      ,l_ei_date_tbl(i)
9719                      ,l_exp_type_tbl(i)
9720                      ,-l_quantity_tbl(i)
9721                      ,l_amount_tbl(i)/decode(nvl(l_quantity_tbl(i),0),0,1,l_quantity_tbl(i))
9722                      ,l_description_tbl(i)
9723                      ,l_txn_status_code_tbl(i)
9724                      ,l_txn_rej_code_tbl(i)
9725                      ,G_REQUEST_ID
9726                      ,l_interface_id_tbl(i)
9727                      ,l_dist_cc_id_tbl(i)
9728                      ,l_acct_pay_cc_id_tbl(i)
9729                      --,l_vendor_id_tbl(i) /*sysref1*/
9730                      ,decode(l_ln_type_lookup_tbl(i),'PREPAY',l_vendor_id_tbl(i),l_pay_hist_id_tbl(i)) /*sysref1*/
9731                      ,l_invoice_id_tbl(i) /*sysref2*/
9732                      ,l_cdl_sys_ref3_tbl(i)/*sysref3*/
9733                      ,l_inv_pay_id_tbl(i)  /*sysref4*/
9734                      ,l_invoice_dist_id_tbl(i) /*sysref5*/ --NEW
9735                      ,l_gl_date_tbl(i)
9736                      ,G_ORG_ID
9737                      ,'Y'
9738                      ,-l_rec_cur_amt_tbl(i)
9739                      ,l_rec_cur_code_tbl(i)
9740                      ,l_rec_conv_rate_tbl(i)
9741                      ,-l_denom_raw_cost_tbl(i)
9742                      ,l_denom_cur_code_tbl(i)
9743                      ,l_acct_rate_date_tbl(i)
9744                      ,l_acct_rate_type_tbl(i)
9745                      ,l_acct_exch_rate_tbl(i)
9746                      ,-l_amount_tbl(i)
9747                      ,1
9748                      ,l_attribute_cat_tbl(i)
9749                      ,l_attribute1_tbl(i)
9750                      ,l_attribute2_tbl(i)
9751                      ,l_attribute3_tbl(i)
9752                      ,l_attribute4_tbl(i)
9753                      ,l_attribute5_tbl(i)
9754                      ,l_attribute6_tbl(i)
9755                      ,l_attribute7_tbl(i)
9756                      ,l_attribute8_tbl(i)
9757                      ,l_attribute9_tbl(i)
9758                      ,l_attribute10_tbl(i)
9759                      ,l_invoice_id_tbl(i)        /*orig_exp_txn_reference1*/
9760                      ,l_invoice_num_tbl(i)       /*user_exp_txn_reference*/
9761                      /* bug 2835757*/
9762                      ,DECODE(G_TRANS_DFF_AP,'N',NULL,l_invoice_id_tbl(i)) /*orig_exp_txn_reference2*/
9763                      ,NULL                       /*orig_exp_txn_reference3*/
9764                      ,SYSDATE
9765                      ,-1
9766                      ,SYSDATE
9767                      ,-1
9768                      ,l_employee_id_tbl(i)
9769                      ,l_org_id_tbl(i)
9770                      ,l_project_id_tbl(i)
9771                      ,l_task_id_tbl(i)
9772                      ,l_vendor_id_tbl(i)
9773                      ,l_exp_org_id_tbl(i)
9774                      ,l_bus_grp_id_tbl(i)
9775                      ,l_adj_exp_item_id_tbl(i) --NEW for reversals
9776                      ,l_fc_document_type_tbl(i) --NEW for funds check
9777                      ,l_inv_type_code_tbl(i)
9778                      ,l_ln_type_lookup_tbl(i)
9779                      ,(select xface.txn_interface_id
9780                        from   pa_transaction_interface xface
9781                        where  xface.interface_id = l_interface_id_tbl(i)
9782                        and    xface.cdl_system_reference2 = l_invoice_id_tbl(i)
9783                        and    xface.cdl_system_reference4 = to_char(l_inv_pay_id_tbl(i))
9784                        and    xface.cdl_system_reference5 = l_invoice_dist_id_tbl(i)
9785 		       and    NVL(xface.adjusted_expenditure_item_id,0) = 0 ) -- R12 funds management Uptake
9786                      ,'P'
9787                      ,'T' -- l_si_assts_add_flg_tbl(i)
9788                      ,l_net_zero_flag_tbl(i)
9789                 FROM dual
9790                 WHERE l_insert_flag_tbl(i)= 'A';
9791                -- WHERE l_net_zero_flag_tbl(i)= 'Y';
9792 
9793                -- Handle both the parent and the reversal getting interfaced into PA
9794                -- in the same run.
9795                 write_log(LOG, 'Updating  adjustment records..');
9796               IF l_rev_child_dist_id_tbl.exists(1) THEN
9797                FOR i in l_rev_child_dist_id_tbl.FIRST ..l_rev_child_dist_id_tbl.LAST LOOP
9798                    IF l_rev_child_dist_id_tbl(i) > 0 THEN
9799                     UPDATE pa_transaction_interface_all xface
9800                     SET    xface.net_zero_adjustment_flag ='Y',
9801                            xface.adjusted_txn_interface_id =
9802                               (select xface1.txn_interface_id
9803                                from   pa_transaction_interface xface1
9804                                where  xface1.interface_id = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
9805                                and    xface1.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
9806                                and    xface1.cdl_system_reference4 = to_char(l_inv_pay_id_tbl(l_rev_parent_dist_ind_tbl(i)))
9807                                and    xface1.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
9808                                )
9809                       WHERE  xface.interface_id          = l_interface_id_tbl(l_rev_parent_dist_ind_tbl(i))
9810                       AND    xface.cdl_system_reference2 = l_invoice_id_tbl(l_rev_parent_dist_ind_tbl(i))
9811                       AND    -- For voided payments l_rev_child_dist_id_tbl stores the reversed payment id Bug# 5408748
9812                              -- Here the reversal pair will have same inv dist id and diff payment id's
9813                              ((
9814                              xface.cdl_system_reference4     = To_char(l_rev_child_dist_id_tbl(i))
9815                              AND xface.cdl_system_reference5 = l_invoice_dist_id_tbl(l_rev_parent_dist_ind_tbl(i))
9816                              )
9817                       OR     -- For invoice reversal l_rev_child_dist_id_tbl stores the reversed invoice dist id Bug# 5408748
9818                              -- Here the reversal pair will have same payment id and diff inv dist id's
9819                              (
9820                              xface.cdl_system_reference4     = to_char(l_inv_pay_id_tbl(l_rev_parent_dist_ind_tbl(i)))
9821                              AND xface.cdl_system_reference5 = To_char(l_rev_child_dist_id_tbl(i))
9822                              )) ;
9823                    END IF;
9824                END LOOP;
9825               END IF;
9826 
9827     END IF;
9828    EXCEPTION
9829       WHEN OTHERS THEN
9830           write_log(LOG,'Failed during bulk insert for payment processing');
9831           G_err_code   := SQLCODE;
9832           raise;
9833 
9834    END bulk_insert_trx_intf;
9835 
9836    PROCEDURE process_pay_logic IS
9837 
9838        l_status3 VARCHAR2(30);
9839        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
9840        l_historical_flag VARCHAR(1);  --NEW
9841        l_process_adjustments    Number := 0 ;
9842 
9843    BEGIN
9844 
9845        G_err_stage := ('Within Calling process logic of transfer_pay_to_pa');
9846        write_log(LOG, G_err_stage);
9847 
9848        /* Initializing global variables here to reduce code lines */
9849        G_NRT_TRANSACTION_SOURCE      := 'AP NRTAX' ;
9850        G_NRT_USER_TRANSACTION_SOURCE := 'Non-Recoverable Tax From Payables';
9851 
9852        G_AP_VAR_TRANSACTION_SOURCE  := 'AP VARIANCE';
9853        G_AP_VAR_USER_TXN_SOURCE     := 'Oracle Payables Invoice Variance';
9854 
9855 
9856        G_AP_ERV_TRANSACTION_SOURCE  := 'AP ERV';         --NEW bug 5372603
9857        G_AP_ERV_USER_TXN_SOURCE     := 'Oracle Payables Supplier Cost Exchange Rate Variance';  --NEW bug 5372603
9858 
9859 
9860        j := v_last_inv_index; -- initialize j to the total invoice distributions fetched in the PLSQL array
9861 
9862 
9863        FOR i IN  l_invoice_id_tbl.FIRST..l_invoice_id_tbl.LAST  LOOP
9864 
9865            write_log(LOG,'Processing invoice id:  '||l_invoice_id_tbl(i)|| 'dist id:  '||l_invoice_dist_id_tbl(i));
9866 
9867            G_TRANSACTION_REJECTION_CODE := '';
9868 
9869            IF l_source_tbl(i) in ('CREDIT CARD','Both Pay') THEN
9870 
9871               write_log(LOG,'This is a credit card txn, setting emp id to paid_emp_id.');
9872               l_employee_id_tbl(i)   := l_paid_emp_id_tbl(i);
9873               l_inv_type_code_tbl(i) := 'EXPENSE REPORT';
9874 
9875            ELSIF l_inv_type_code_tbl(i) = 'EXPENSE REPORT' and l_employee_id_tbl(i) is null THEN
9876               write_log(LOG,'This is a CWK Exp Report, setting emp id to paid_emp_id.');
9877               l_employee_id_tbl(i)   := l_paid_emp_id_tbl(i);
9878 
9879            END IF;
9880 
9881            /* The following will be executed if the distribution being fetched belongs to a new invoice */
9882            IF (l_invoice_id_tbl(i) <> v_prev_invoice_id) THEN
9883 
9884                G_err_stage := ('New invoice being processed.New invoice _id is:'||l_invoice_id_tbl(i));
9885                write_log(LOG, G_err_stage);
9886 
9887                /* Update the previous invoice id and vendor id*/
9888                v_prev_invoice_id := l_invoice_id_tbl(i);
9889                v_prev_vendor_id  := l_vendor_id_tbl(i);
9890 
9891                /* Increment the counter for invoices */
9892                v_num_invoices_fetched := v_num_invoices_fetched + 1;
9893 
9894                IF nvl(v_prev_invoice_source,l_source_tbl(i)||'111') <> l_source_tbl(i) THEN
9895 
9896                   /* First update the v_prev_invoice_source */
9897                   G_err_stage := 'New source encountered';
9898                   write_log(LOG, G_err_stage);
9899                   v_prev_invoice_source := l_source_tbl(i);
9900 
9901 
9902                   IF l_source_tbl(i) = 'PA_IP_INVOICES' THEN
9903 
9904                      G_err_stage := 'Invoice source is Inter-Company Invoice';
9905                      write_log(LOG, G_err_stage);
9906                      G_TRANSACTION_SOURCE      := 'INTERPROJECT_AP_INVOICES';
9907                      v_prev_transaction_source := G_TRANSACTION_SOURCE;
9908                      G_USER_TRANSACTION_SOURCE := 'Oracle Inter-Project Invoices';
9909 
9910                      L_IP_TRANSACTION_SOURCE      := 'INTERPROJECT_AP_INVOICES';
9911                      l_ip_inv_flag                    := 'Y' ;
9912 
9913                   ELSIF (l_source_tbl(i)        = 'XpenseXpress' OR
9914                          /* if its a Credit card txn, treat like expense report*/
9915                          l_source_tbl(i) in ('CREDIT CARD','Both Pay') OR
9916                         (l_source_tbl(i)        = 'Manual Invoice Entry' AND
9917                          l_inv_type_code_tbl(i) = 'EXPENSE REPORT') OR
9918                          l_source_tbl(i)        = 'SelfService') THEN
9919 
9920                       G_err_stage := 'Invoice source is Expense Reports';
9921                       write_log(LOG, G_err_stage);
9922                       G_TRANSACTION_SOURCE      := 'AP EXPENSE';
9923                       v_prev_transaction_source := G_TRANSACTION_SOURCE;
9924                       G_USER_TRANSACTION_SOURCE := 'ORACLE PAYABLES';
9925 
9926                   ELSE
9927 
9928                       G_err_stage := 'Invoice source is AP Invoice';
9929                       write_log(LOG, G_err_stage);
9930                       G_TRANSACTION_SOURCE             := 'AP INVOICE';
9931                       v_prev_transaction_source := G_TRANSACTION_SOURCE;
9932 
9933                       G_USER_TRANSACTION_SOURCE        := 'AP INVOICE';
9934                       l_ap_inv_flag                    := 'Y' ;
9935 
9936                   END IF;
9937 
9938                END IF; /* invoice source <> v_prev_tranasction_source */
9939 
9940                 /* For new invoice, initialize the transaction status code to 'P' */
9941                 G_TRANSACTION_STATUS_CODE := 'P';
9942 
9943                 G_err_stage := 'GET MAX EXPENDITURE ENDING DATE';
9944                 write_log(LOG, G_err_stage);
9945 /* Bug 5051103 - replace expnediture_item_date with l_ei_date_tbl(i) */
9946                 SELECT pa_utils.getweekending(MAX(l_ei_date_tbl(i)))
9947                   INTO G_EXPENDITURE_ENDING_DATE
9948                   FROM ap_invoice_distributions
9949                  WHERE invoice_id = l_invoice_id_tbl(i);
9950 
9951                 G_err_stage := ('Getting bus group id');
9952                 write_log(LOG, G_err_stage);
9953 
9954                 BEGIN
9955 
9956                    IF l_employee_id_tbl(i) <> 0 THEN
9957             		   Begin
9958                                   write_log(LOG,'getting bus group id with emp id of :  '||l_employee_id_tbl(i));
9959 
9960                                   SELECT emp.business_group_id
9961                                     INTO G_PER_BUS_GRP_ID
9962                                     FROM per_all_people_f emp
9963                                    WHERE emp.person_id = l_employee_id_tbl(i)
9964                                       AND l_ei_date_tbl(i) between trunc(emp.effective_start_date) and trunc(emp.effective_end_date);
9965 
9966             			EXCEPTION
9967             			   WHEN NO_DATA_FOUND THEN
9968             			      l_txn_status_code_tbl(i)     := 'R';
9969             			      G_TRANSACTION_REJECTION_CODE := 'INVALID_EMPLOYEE';
9970             			      write_log(LOG, 'As no data found for Employee, Rejecting invoice'||l_invoice_id_tbl(i)  );
9971              		    End;
9972 		            Else
9973 		    Begin
9974 
9975 			    select org2.business_group_id
9976                               into G_PER_BUS_GRP_ID
9977 			      from hr_organization_units org1,
9978 				   hr_organization_units org2
9979 			     Where org1.organization_id = l_exp_org_id_tbl(i)
9980 			       and org1.business_group_id = org2.organization_id ;
9981 
9982 			    Exception
9983 			      When no_data_found Then
9984 				G_TRANSACTION_STATUS_CODE := 'R';
9985 				G_TRANSACTION_REJECTION_CODE := 'INVALID_ORGANIZATION';
9986 				write_log(LOG,'As no data found for Organization,Rejecting invoice '||l_invoice_id_tbl(i)  );
9987 		     End;
9988         	END IF;   /* IF l_employee_id_tbl(i) <> 0 THEN  */
9989 
9990                 END;
9991 
9992            END IF; /* end of check for different invoice_id from previous invoice_id */
9993 
9994 
9995            /* The following will be executed when the distribution belongs to the same
9996               invoice or not the same invoice */
9997 
9998            v_num_distributions_fetched := v_num_distributions_fetched + 1;
9999            write_log(LOG,'Num of distributions fetched:'||v_num_distributions_fetched);
10000 
10001            /*Update counter of how many distributions of the last invoice of the batch has been processed*/
10002 
10003            IF l_invoice_id_tbl(i) = l_invoice_id_tbl(v_last_inv_index) THEN
10004               v_num_last_invoice_processed := v_num_last_invoice_processed +1;
10005 
10006               IF l_inv_type_code_tbl(i) = 'EXPENSE REPORT' THEN
10007                  v_last_inv_ER_flag := 'Y';
10008               ELSE
10009                  v_last_inv_ER_flag := 'N';
10010               END IF;
10011 
10012            END IF;
10013 
10014 
10015            -- FC Doc Type
10016             IF l_fc_enabled_tbl(i) = 'N' THEN
10017              l_fc_document_type_tbl(i) := 'NOT';
10018             END IF;
10019 
10020            /* if the invoice is an expense report from self-service we need to use the column of justification as the description */
10021            IF (l_inv_type_code_tbl(i) = 'EXPENSE REPORT' AND
10022                l_source_tbl(i)        in ('SelfService','XpenseXpress') ) THEN
10023                l_description_tbl(i) := l_justification_tbl(i);
10024            END IF;
10025 
10026            IF l_ln_type_lookup_tbl(i)  in ('NONREC_TAX','TRV','TIPV') THEN
10027 
10028               /* Update counter for number of tax lines fetched */
10029               v_num_tax_lines_fetched := v_num_tax_lines_fetched +1;
10030 
10031               l_txn_src_tbl(i)      := G_NRT_TRANSACTION_SOURCE;
10032               l_user_txn_src_tbl(i) := G_NRT_USER_TRANSACTION_SOURCE;
10033 
10034               IF l_prepay_dist_id_tbl(i) is not null THEN -- tax associated with prepay application Bug#5514129
10035                 l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
10036                 l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
10037                 l_ap_prepay_tax_flag := 'Y';
10038               ELSE
10039                 l_batch_name_tbl(i)   := G_NRT_BATCH_NAME;
10040                 l_interface_id_tbl(i) := G_NRT_INTERFACE_ID;
10041               END IF;
10042 
10043            ELSIF l_ln_type_lookup_tbl(i) = 'IPV' THEN
10044 
10045               /* Update counter for number of variance lines fetched */
10046               v_num_inv_variance_fetched :=  v_num_inv_variance_fetched +1;
10047 
10048               l_quantity_tbl(i)     := l_denom_raw_cost_tbl(i);
10049               l_txn_src_tbl(i)      := G_AP_VAR_TRANSACTION_SOURCE;
10050               l_user_txn_src_tbl(i) := G_AP_VAR_USER_TXN_SOURCE;
10051 
10052               IF l_prepay_dist_id_tbl(i) is not null THEN -- associated with prepay application Bug#5514129
10053                 l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
10054                 l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
10055                 l_ap_prepay_var_flag := 'Y';
10056               ELSE
10057                 l_batch_name_tbl(i)   := G_AP_VAR_BATCH_NAME;
10058                 l_interface_id_tbl(i) := G_AP_VAR_INTERFACE_ID;
10059               END IF;
10060 
10061            ELSIF l_ln_type_lookup_tbl(i) in ('ERV','TERV') THEN
10062               /* Update counter for number of variance lines fetched */
10063               v_num_inv_erv_fetched :=  v_num_inv_erv_fetched +1;
10064 
10065               l_quantity_tbl(i)     := l_denom_raw_cost_tbl(i);
10066               l_txn_src_tbl(i)      := G_AP_ERV_TRANSACTION_SOURCE;
10067               l_user_txn_src_tbl(i) := G_AP_ERV_USER_TXN_SOURCE;
10068 
10069               IF l_prepay_dist_id_tbl(i) is not null THEN -- associated with prepay application Bug#5514129
10070                 l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
10071                 l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
10072                 l_ap_prepay_erv_flag := 'Y';
10073               ELSE
10074                 l_batch_name_tbl(i)   := G_AP_ERV_BATCH_NAME;
10075                 l_interface_id_tbl(i) := G_AP_ERV_INTERFACE_ID;
10076               END IF;
10077 
10078            ELSIF  l_ln_type_lookup_tbl(i) in ('FREIGHT','MISCELLANEOUS') THEN
10079               /* Update counter for number of frt and misc lines fetched */
10080               v_num_inv_frt_fetched :=  v_num_inv_frt_fetched +1;
10081 
10082               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
10083               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
10084               IF l_prepay_dist_id_tbl(i) is not null THEN -- associated with prepay application Bug#5514129
10085                 l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
10086                 l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
10087               ELSE
10088                 l_batch_name_tbl(i)   := G_AP_FRT_BATCH_NAME;
10089                 l_interface_id_tbl(i) := G_AP_FRT_INTERFACE_ID;
10090               END IF;
10091 
10092            ELSIF  l_ln_type_lookup_tbl(i) in ('PREPAY') THEN
10093 
10094               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
10095               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
10096               l_batch_name_tbl(i)   := G_PREPAY_BATCH_NAME;
10097               l_interface_id_tbl(i) := G_PREPAY_INTERFACE_ID;
10098 
10099            ELSE -- Other distribution types like ITEM,ACCRUAL etc
10100 
10101               l_txn_src_tbl(i)      := G_TRANSACTION_SOURCE;
10102               l_user_txn_src_tbl(i) := G_USER_TRANSACTION_SOURCE;
10103               l_batch_name_tbl(i)   := G_BATCH_NAME;
10104               l_interface_id_tbl(i) := G_INTERFACE_ID;
10105 
10106            END IF ;
10107 
10108            G_TRANSACTION_REJECTION_CODE := '';
10109 
10110            /*Setting values according to global variables*/
10111            l_bus_grp_id_tbl(i)      := G_PER_BUS_GRP_ID;
10112            l_exp_end_date_tbl(i)    := G_EXPENDITURE_ENDING_DATE;
10113            l_txn_rej_code_tbl(i)    := G_TRANSACTION_REJECTION_CODE;
10114            l_txn_status_code_tbl(i) := G_TRANSACTION_STATUS_CODE;
10115 
10116            write_log(LOG,'Value of l_txn_src_tbl:'||l_txn_src_tbl(i) ||'batch name:'||l_batch_name_tbl(i));
10117 
10118            /* In Rel12 we will not interface any PREPAYMENT PAYMENTS to Oracle Projects */
10119            --
10120            /* The records with INSERT_FLAG = F indicate that they are fully applied prepayments and the pa-addition-flag
10121               for such records will be updated to G to relieve commitments*/
10122            /* The records with INSERT_FLAG = P indicate that they are partially applied prepayments and the pa-addition-flag
10123               for such records will be updated to N */
10124 
10125            IF (l_inv_type_code_tbl(i) = 'PREPAYMENT' ) THEN
10126 
10127               IF check_prepay_fully_applied(l_invoice_dist_id_tbl(i)) = 'Y' THEN
10128                  l_insert_flag_tbl(i) := 'F';
10129               ELSE
10130                  l_insert_flag_tbl(i) := 'P';
10131               END IF;
10132 
10133            ELSE
10134 
10135            -- REVERSED DISTRIBUTIONS INTERFACE LOGIC
10136            -- If the distribution is a reversal or cancellation then check if the parent reversal distribution
10137            -- was historical data or not. If data is historical, reversal distribution line will be interfaced as is.
10138            --
10139            -- However if the parent reversal distribution is not historical then the following steps happen:
10140            -- a) Retreive the latest adjusted expenditures from PA against the parent reversal distribution id
10141            -- b) If any of the above latest EI's are not costed, then the reversed distribution will be rejected by the
10142            --    TRX import program
10143            -- c) IF all above adjusted EI's are costed, then insert record into the interface table for each adjusted EI.
10144            --    The project attributes will be copied from the adjusted EI's instead from the AP reversed
10145            --    distribution since these could have changed in PA.
10146            -- d) The interface program will interface the reversed distribution into projects
10147            -- e) The interface program will also insert a reversal of the reversed distribution into Projects. This is
10148            --    required for account reconciliation
10149            --
10150 
10151          -- This logic is to handle both the parent and reversal getting interfaced in the same run.
10152           -- It's a reversed parent record. Bug#4590527
10153           -- If both the parent and child reversing each other are interfaced in the same run, they
10154           -- were not getting interfaced as netzero transactions.
10155 
10156            IF (l_reversal_flag_tbl(i) in ('Y','R') or l_cancel_flag_tbl(i) = 'Y')
10157                                  AND l_parent_pmt_id_tbl(i) IS NULL THEN
10158 
10159               l_rev_index := l_rev_index +1;
10160               IF l_reversal_flag_tbl(i) = 'Y' THEN
10161                 write_log(LOG, 'Reversal parent record '||l_inv_pay_id_tbl(i));
10162                 l_rev_parent_dist_id_tbl(l_rev_index) :=  l_inv_pay_id_tbl(i);
10163               ELSE
10164 
10165                 -- The Reversal flag with value R indicates that the invoice distribution has been reversed
10166                 -- Refer to Bug#5408748
10167 
10168                 write_log(LOG, 'Reversal parent record for Invoice Dist reversals'||l_invoice_dist_id_tbl(i));
10169                 l_rev_parent_dist_id_tbl(l_rev_index) :=  l_invoice_dist_id_tbl(i);
10170               END IF;
10171 
10172               l_rev_child_dist_id_tbl(l_rev_index) :=  null;
10173               l_rev_parent_dist_ind_tbl(l_rev_index) :=  i; -- store the index of the parent.
10174 
10175            END IF;
10176 
10177            IF l_reversal_flag_tbl(i) in ('Y','R')  and l_parent_pmt_id_tbl(i) is not null THEN
10178 
10179 -- check if reversal flag is populated for prepayment appl
10180 
10181                   -- Call reversal API
10182                   Process_Adjustments(p_record_type  => 'AP_PAYMENT',
10183                                       p_document_header_id  => l_invoice_id_tbl(i) ,/*Added this for 6945767 */
10184                                       p_document_distribution_id  => l_invoice_dist_id_tbl(i),
10185                                       p_document_payment_id       => l_parent_pmt_id_tbl(i),
10186                                       p_current_index             => i,
10187 				      p_last_index                => j);
10188 
10189                       -- Set the create flag for adjustment records
10190                          IF l_insert_flag_tbl(i) in ('A','U') THEN
10191                           l_create_adj_recs := 'Y';
10192                          END IF;
10193 
10194            END IF; --End of check for reversal Distribution
10195 
10196            G_err_stage := ('Value of G_TRANS_DFF_AP:'||G_TRANS_DFF_AP);
10197            write_log(LOG, G_err_stage);
10198 
10199            IF (G_TRANS_DFF_AP = 'Y') THEN
10200 
10201                 v_attribute_category := l_attribute_cat_tbl(i);
10202                 v_attribute1 := l_attribute1_tbl(i);
10203                 v_attribute2 := l_attribute2_tbl(i);
10204                 v_attribute3 := l_attribute3_tbl(i);
10205                 v_attribute4 := l_attribute4_tbl(i);
10206                 v_attribute5 := l_attribute5_tbl(i);
10207                 v_attribute6 := l_attribute6_tbl(i);
10208                 v_attribute7 := l_attribute7_tbl(i);
10209                 v_attribute8 := l_attribute8_tbl(i);
10210                 v_attribute9 := l_attribute9_tbl(i);
10211                 v_attribute10 := l_attribute10_tbl(i);
10212 
10213                 v_dff_map_status := NULL;
10214 
10215                 PA_CLIENT_EXTN_DFFTRANS.DFF_map_segments_PA_and_AP(
10216                    p_calling_module            => 'PAAPIMP',
10217                    p_trx_ref_1                 => l_invoice_id_tbl(i),
10218                    --p_trx_ref_2                 => l_dist_line_num_tbl(i),
10219                    p_trx_ref_2                 => l_invoice_dist_id_tbl(i),  --NEW
10220                    p_trx_type                  => l_inv_type_code_tbl(i),
10221                    p_system_linkage_function   => G_SYSTEM_LINKAGE,
10222                    p_submodule                 => l_source_tbl(i),
10223                    p_expenditure_type          => l_exp_type_tbl(i),
10224                    p_set_of_books_id           => G_AP_SOB,
10225                    p_org_id                    => l_org_id_tbl(i),
10226                    p_attribute_category        => v_attribute_category,
10227                    p_attribute_1               => v_attribute1,
10228                    p_attribute_2               => v_attribute2,
10229                    p_attribute_3               => v_attribute3,
10230                    p_attribute_4               => v_attribute4,
10231                    p_attribute_5               => v_attribute5,
10232                    p_attribute_6               => v_attribute6,
10233                    p_attribute_7               => v_attribute7,
10234                    p_attribute_8               => v_attribute8,
10235                    p_attribute_9               => v_attribute9,
10236                    p_attribute_10              => v_attribute10,
10237                    x_status_code               => v_dff_map_status);
10238 
10239                    IF (v_dff_map_status IS NOT NULL) THEN
10240 
10241                        write_log(LOG, 'Error in DFF_map_segments_PA_and_AP, Error Code: ' || v_dff_map_status);
10242                        raise dff_map_exception;
10243 
10244                    END IF;
10245 
10246                    l_attribute_cat_tbl(i) := v_attribute_category;
10247                    l_attribute1_tbl(i) := v_attribute1;
10248                    l_attribute2_tbl(i) := v_attribute2;
10249                    l_attribute3_tbl(i) := v_attribute3;
10250                    l_attribute4_tbl(i) := v_attribute4;
10251                    l_attribute5_tbl(i) := v_attribute5;
10252                    l_attribute6_tbl(i) := v_attribute6;
10253                    l_attribute7_tbl(i) := v_attribute7;
10254                    l_attribute8_tbl(i) := v_attribute8;
10255                    l_attribute9_tbl(i) := v_attribute9;
10256                    l_attribute10_tbl(i) := v_attribute10;
10257 
10258 	   ElSE /* if DFF profile is No. Added for Bug 3105153*/
10259                    l_attribute_cat_tbl(i) := NULL;     --Bug#3856390
10260                    l_attribute1_tbl(i) := NULL;
10261                    l_attribute2_tbl(i) := NULL;
10262                    l_attribute3_tbl(i) := NULL;
10263                    l_attribute4_tbl(i) := NULL;
10264                    l_attribute5_tbl(i) := NULL;
10265                    l_attribute6_tbl(i) := NULL;
10266                    l_attribute7_tbl(i) := NULL;
10267                    l_attribute8_tbl(i) := NULL;
10268                    l_attribute9_tbl(i) := NULL;
10269                    l_attribute10_tbl(i) := NULL;
10270 
10271 	   END IF; /* if DFF profile is Yes */
10272 
10273         END IF; /* if inv type is PREPAYMENT */
10274 
10275       END LOOP; /* End of looping through each record in plsql table */
10276 
10277    EXCEPTION
10278       WHEN OTHERS THEN
10279           write_log(LOG,'Failed during process_pay_logic');
10280           G_err_code   := SQLCODE;
10281           raise;
10282 
10283    END process_pay_logic;
10284 
10285    BEGIN
10286    /* Main Procedure Logic starts here */
10287 
10288    G_err_stage := 'Within main procedure of transfer_pay_to_pa';
10289    write_log(LOG, G_err_stage);
10290 
10291      write_log(LOG, '......Result of G_TRANSACTION_SOURCE: ' || G_TRANSACTION_SOURCE);
10292 
10293      v_max_size := nvl(G_COMMIT_SIZE,200);
10294 
10295      -- Create a new interface ID for the first session
10296 
10297      OPEN Payments_Cur;
10298 
10299      G_err_stage := 'After opening Payments_Cur within transfer_pay_to_pa';
10300      write_log(LOG, G_err_stage);
10301 
10302      WHILE (v_all_done = 0) LOOP
10303 
10304        clear_plsql_tables;
10305 
10306        --Creating new interface ID every time this is called
10307        G_err_stage := 'CREATING NEW INTERFACE ID';
10308        write_log(LOG, G_err_stage);
10309 
10310        SELECT pa_interface_id_s.nextval
10311          INTO G_INTERFACE_ID
10312          FROM dual;
10313 
10314        G_err_stage := 'CREATING NEW NRT INTERFACE ID';
10315        SELECT pa_interface_id_s.nextval
10316          into G_NRT_INTERFACE_ID
10317          FROM dual;
10318 
10319        G_err_stage := 'CREATING NEW FRT INTERFACE ID';
10320        SELECT pa_interface_id_s.nextval
10321          into G_AP_FRT_INTERFACE_ID
10322          FROM dual;
10323 
10324        G_err_stage := 'CREATING NEW VARIANCE INTERFACE ID';
10325        SELECT pa_interface_id_s.nextval
10326          into G_AP_VAR_INTERFACE_ID
10327          FROM dual;
10328 
10329        G_err_stage := 'CREATING NEW ERV VARIANCE INTERFACE ID';
10330        SELECT pa_interface_id_s.nextval
10331          into G_AP_ERV_INTERFACE_ID
10332          FROM dual;
10333 
10334           FETCH Payments_Cur BULK COLLECT INTO
10335              l_inv_pay_id_tbl,
10336              l_invoice_id_tbl,
10337              l_created_by_tbl,
10338              l_invoice_dist_id_tbl,
10339              l_cdl_sys_ref3_tbl,
10340              l_project_id_tbl,
10341              l_task_id_tbl,
10342              l_ln_type_lookup_tbl,
10343              l_exp_type_tbl,
10344              l_ei_date_tbl,
10345              l_amount_tbl,
10346              l_description_tbl,
10347              l_justification_tbl,
10348              l_dist_cc_id_tbl,
10349              l_exp_org_id_tbl,
10350              l_quantity_tbl,
10351              l_acct_pay_cc_id_tbl,
10352              l_gl_date_tbl,
10353              l_attribute_cat_tbl,
10354              l_attribute1_tbl,
10355              l_attribute2_tbl,
10356              l_attribute3_tbl,
10357              l_attribute4_tbl,
10358              l_attribute5_tbl,
10359              l_attribute6_tbl,
10360              l_attribute7_tbl,
10361              l_attribute8_tbl,
10362              l_attribute9_tbl,
10363              l_attribute10_tbl,
10364              l_rec_cur_amt_tbl,
10365              l_rec_cur_code_tbl,
10366              l_rec_conv_rate_tbl,
10367              l_denom_raw_cost_tbl,
10368              l_denom_cur_code_tbl,
10369              l_acct_rate_date_tbl,
10370              l_acct_rate_type_tbl,
10371              l_acct_exch_rate_tbl,
10372              l_job_id_tbl,
10373              l_employee_id_tbl,
10374              l_vendor_id_tbl,
10375              l_inv_type_code_tbl,
10376              l_source_tbl,
10377              l_org_id_tbl,
10378              l_invoice_num_tbl,
10379              l_cdl_sys_ref4_tbl,
10380              l_po_dist_id_tbl
10381             ,l_txn_src_tbl
10382             ,l_user_txn_src_tbl
10383             ,l_batch_name_tbl
10384             ,l_interface_id_tbl
10385             ,l_exp_end_date_tbl
10386             ,l_txn_status_code_tbl
10387             ,l_txn_rej_code_tbl
10388             ,l_bus_grp_id_tbl
10389             ,l_paid_emp_id_tbl
10390             ,l_sort_var_tbl
10391             ,l_reversal_flag_tbl --NEW
10392             ,l_cancel_flag_tbl --NEW
10393             ,l_parent_pmt_id_tbl --NEW
10394             ,l_net_zero_flag_tbl  --NEW
10395             ,l_sc_xfer_code_tbl
10396             ,l_adj_exp_item_id_tbl --NEW
10397             ,l_fc_enabled_tbl  --NEW
10398             ,l_mrc_exchange_date_tbl
10399             ,l_fc_document_type_tbl
10400             ,l_payment_status_flag_tbl
10401             ,l_si_assts_add_flg_tbl
10402             ,l_insert_flag_tbl
10403             ,l_pay_hist_id_tbl
10404             ,l_prepay_dist_id_tbl   --bug#5514129
10405             LIMIT v_max_size;
10406 
10407          G_err_stage := 'After fetching Payments_Cur within transfer_pay_to_pa';
10408          write_log(LOG, G_err_stage);
10409 
10410          IF l_invoice_id_tbl.COUNT <> 0 THEN
10411 
10412             /* get the index of the last invoice being processed within the batch*/
10413             v_last_inv_index := l_invoice_id_tbl.LAST;
10414 
10415             G_err_stage := 'calling process_pay_logic within transfer_pay_to_pa';
10416             write_log(LOG, G_err_stage);
10417 
10418             process_pay_logic;
10419 
10420             G_err_stage := 'calling bulk_update_trx_intf within transfer_pay_to_pa';
10421             write_log(LOG, G_err_stage);
10422 
10423             bulk_update_trx_intf; --Update Prepayment trx
10424 
10425             G_err_stage := 'calling bulk_insert_trx_intf within transfer_pay_to_pa';
10426             write_log(LOG, G_err_stage);
10427 
10428             bulk_insert_trx_intf;
10429 
10430             G_err_stage := 'After calling bulk_insert_trx_intf within transfer_pay_to_pa';
10431             write_log(LOG, G_err_stage);
10432 
10433             G_err_stage := 'Before calling transaction import and tiebacks within transfer_pay_to_pa';
10434             write_log(LOG, G_err_stage);
10435 
10436             IF (v_num_distributions_fetched > 0) THEN
10437 
10438                v_inv_batch_size           := v_num_distributions_fetched - v_num_tax_lines_fetched -
10439                                              v_num_inv_variance_fetched - v_num_inv_frt_fetched;
10440 
10441               write_log(LOG,'Before calling trx_import for invoices with interface_id:'||G_INTERFACE_ID);
10442               --Logic to handle IP and AP INVOICES getting interfaced in the same run.Bug#4764470.
10443 
10444              IF (l_ap_inv_flag ='Y' ) THEN
10445 
10446               trans_import('AP INVOICE', G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
10447               tieback_payment_AP_ER('AP INVOICE', G_BATCH_NAME,'PAY', G_INTERFACE_ID);
10448 
10449              END IF;
10450 
10451              IF (l_ip_inv_flag ='Y' ) THEN
10452 
10453               trans_import(L_IP_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
10454               tieback_payment_AP_ER(L_IP_TRANSACTION_SOURCE, G_BATCH_NAME,'PAY', G_INTERFACE_ID);
10455 
10456              ELSIF (l_ap_inv_flag ='N') THEN
10457 
10458               trans_import(G_TRANSACTION_SOURCE, G_BATCH_NAME, G_INTERFACE_ID, G_USER_ID);
10459               tieback_payment_AP_ER(G_TRANSACTION_SOURCE, G_BATCH_NAME,'PAY', G_INTERFACE_ID);
10460 
10461              END IF;
10462               --End of logic to handle IP and AP INVOICES getting interfaced in the same run.Bug#4764470.
10463 
10464               IF (nvl(v_num_tax_lines_fetched,0) > 0 AND
10465                      (G_INVOICE_TYPE IS NULL OR G_INVOICE_TYPE = 'EXPENSE REPORT')) THEN
10466 
10467                   write_log(LOG,'Before calling trx_import for NRTAX for interface_id:'||G_NRT_INTERFACE_ID);
10468                   v_tax_batch_size           := v_num_tax_lines_fetched;
10469 
10470                   trans_import(G_NRT_TRANSACTION_SOURCE, G_NRT_BATCH_NAME, G_NRT_INTERFACE_ID, G_USER_ID);
10471                   tieback_payment_AP_ER(G_NRT_TRANSACTION_SOURCE, G_NRT_BATCH_NAME,'PAY', G_NRT_INTERFACE_ID);
10472 
10473               END IF; /* IF (nvl(v_num_tax_lines_fetched,0) > 0*/
10474 
10475               IF (nvl(v_num_inv_variance_fetched,0) > 0) THEN
10476 
10477                   write_log(LOG,'Before calling trx_import for Variance for interface_id:'||G_AP_VAR_INTERFACE_ID);
10478                   v_var_batch_size           := v_num_inv_variance_fetched;
10479 
10480                   trans_import(G_AP_VAR_TRANSACTION_SOURCE, G_AP_VAR_BATCH_NAME, G_AP_VAR_INTERFACE_ID, G_USER_ID);
10481                   tieback_payment_AP_ER(G_AP_VAR_TRANSACTION_SOURCE, G_AP_VAR_BATCH_NAME,'PAY', G_AP_VAR_INTERFACE_ID);
10482 
10483               END IF; /* IF (nvl(v_num_inv_variance_lines_fetched,0) > 0*/
10484 
10485               IF (nvl(v_num_inv_erv_fetched,0) > 0) THEN
10486 
10487                   write_log(LOG,'Before calling trx_import for ERV for interface_id:'||G_AP_VAR_INTERFACE_ID);
10488                   v_var_batch_size           := v_num_inv_erv_fetched;
10489 
10490                   trans_import(G_AP_ERV_TRANSACTION_SOURCE, G_AP_ERV_BATCH_NAME, G_AP_ERV_INTERFACE_ID, G_USER_ID);
10491                   tieback_payment_AP_ER(G_AP_ERV_TRANSACTION_SOURCE, G_AP_ERV_BATCH_NAME,'PAY', G_AP_ERV_INTERFACE_ID);
10492 
10493               END IF; /* IF (nvl(v_num_inv_erv_lines_fetched,0) > 0*/
10494 
10495               IF (nvl(v_num_inv_frt_fetched,0) > 0) THEN
10496 
10497                   write_log(LOG,'Before calling trx_import for Frt and Misc for interface_id:'||G_AP_FRT_INTERFACE_ID);
10498                   v_frt_batch_size           := v_num_inv_frt_fetched;
10499 
10500                   trans_import(G_TRANSACTION_SOURCE, G_AP_FRT_BATCH_NAME, G_AP_FRT_INTERFACE_ID, G_USER_ID);
10501                   tieback_payment_AP_ER(G_TRANSACTION_SOURCE, G_AP_FRT_BATCH_NAME, 'PAY',G_AP_FRT_INTERFACE_ID);
10502 
10503               END IF; /* IF (nvl(v_num_inv_frt_lines_fetched,0) > 0*/
10504 
10505               G_err_stage := 'Before updating the total number of payments processed';
10506               write_log(LOG, G_err_stage);
10507 
10508               G_NUM_BATCHES_PROCESSED       := G_NUM_BATCHES_PROCESSED + 1;
10509               G_NUM_INVOICES_PROCESSED      :=  G_NUM_INVOICES_PROCESSED + v_num_invoices_fetched;
10510               G_NUM_DISTRIBUTIONS_PROCESSED :=  G_NUM_DISTRIBUTIONS_PROCESSED + v_num_distributions_fetched;
10511               write_log(LOG,'G_NUM_BATCHES_PROCESSED:'||G_NUM_BATCHES_PROCESSED);
10512               write_log(LOG,'G_NUM_INVOICES_PROCESSED:'||G_NUM_INVOICES_PROCESSED);
10513               write_log(LOG,'G_NUM_DISTRIBUTIONS_PROCESSED:'||G_NUM_DISTRIBUTIONS_PROCESSED);
10514 
10515         END IF; /* IF (v_num_distributions_fetched > 0) */
10516 
10517         G_err_stage := 'After calling transaction import and tiebacks within transfer_pay_to_pa';
10518         write_log(LOG, G_err_stage);
10519 
10520         clear_plsql_tables;
10521 
10522         v_num_invoices_fetched       :=0;
10523         v_num_distributions_fetched  :=0;
10524         v_num_tax_lines_fetched      :=0;
10525         v_inv_batch_size             :=0;
10526         v_tax_batch_size             :=0;
10527         v_var_batch_size             :=0;
10528         v_frt_batch_size             :=0;
10529         v_num_dist_remain            :=0;
10530         v_num_dist_marked_O          :=0;
10531         v_num_last_invoice_processed :=0;
10532         v_last_inv_ER_flag           := 'N';
10533 
10534         G_err_stage:='Before exiting when Payments_Cur is NOTFOUND';
10535         write_log(LOG,   G_err_stage);
10536 
10537       ELSE
10538 
10539           G_err_stage:='Payments Cursor fetched zero rows into plsql tables. Exiting';
10540           write_log(LOG,   G_err_stage);
10541           EXIT;
10542       END IF; /* l_invoice_id_tbl.COUNT = 0 */
10543 
10544       G_err_stage:='Cursor fetched no more rows. Exiting';
10545       write_log(LOG,   G_err_stage);
10546       EXIT WHEN Payments_Cur%NOTFOUND;
10547 
10548    END LOOP; /* While more rows to process is true */
10549 
10550    CLOSE Payments_Cur;
10551 
10552 
10553      /*=====================================================*/
10554      /* PRocess Prepayment Application */
10555      /*=====================================================*/
10556 
10557      -- Create a new interface ID for the first session
10558 
10559      G_err_stage := 'Before  opening Prepay_Cur within transfer_pay_to_pa';
10560      write_log(LOG, G_err_stage);
10561 
10562      OPEN Prepay_Cur;
10563 
10564      G_err_stage := 'After opening Prepay_Cur within transfer_pay_to_pa';
10565      write_log(LOG, G_err_stage);
10566 
10567      WHILE (v_all_done = 0) LOOP
10568 
10569        clear_plsql_tables;
10570 
10571        G_err_stage := 'CREATING NEW PREPAYMENT INTERFACE ID';
10572        SELECT pa_interface_id_s.nextval
10573          into G_PREPAY_INTERFACE_ID
10574          FROM dual;
10575 
10576        G_err_stage := 'Before Fetching records for prepayment application within transfer_pay_to_pa';
10577        write_log(LOG, G_err_stage);
10578 
10579           FETCH Prepay_Cur BULK COLLECT INTO
10580              l_invoice_id_tbl,
10581              l_created_by_tbl,
10582              l_invoice_dist_id_tbl,
10583              l_cdl_sys_ref3_tbl,
10584              l_project_id_tbl,
10585              l_task_id_tbl,
10586              l_ln_type_lookup_tbl,
10587              l_exp_type_tbl,
10588              l_ei_date_tbl,
10589              l_amount_tbl,
10590              l_description_tbl,
10591              l_justification_tbl,
10592              l_dist_cc_id_tbl,
10593              l_exp_org_id_tbl,
10594              l_quantity_tbl,
10595              l_acct_pay_cc_id_tbl,
10596              l_gl_date_tbl,
10597              l_attribute_cat_tbl,
10598              l_attribute1_tbl,
10599              l_attribute2_tbl,
10600              l_attribute3_tbl,
10601              l_attribute4_tbl,
10602              l_attribute5_tbl,
10603              l_attribute6_tbl,
10604              l_attribute7_tbl,
10605              l_attribute8_tbl,
10606              l_attribute9_tbl,
10607              l_attribute10_tbl,
10608              l_rec_cur_amt_tbl,
10609              l_rec_cur_code_tbl,
10610              l_rec_conv_rate_tbl,
10611              l_denom_raw_cost_tbl,
10612              l_denom_cur_code_tbl,
10613              l_acct_rate_date_tbl,
10614              l_acct_rate_type_tbl,
10615              l_acct_exch_rate_tbl,
10616              l_job_id_tbl,
10617              l_employee_id_tbl,
10618              l_vendor_id_tbl,
10619              l_inv_type_code_tbl,
10620              l_source_tbl,
10621              l_org_id_tbl,
10622              l_invoice_num_tbl,
10623              l_inv_pay_id_tbl,  --l_cdl_sys_ref4_tbl
10624              l_po_dist_id_tbl
10625             ,l_txn_src_tbl
10626             ,l_user_txn_src_tbl
10627             ,l_batch_name_tbl
10628             ,l_interface_id_tbl
10629             ,l_exp_end_date_tbl
10630             ,l_txn_status_code_tbl
10631             ,l_txn_rej_code_tbl
10632             ,l_bus_grp_id_tbl
10633             ,l_paid_emp_id_tbl
10634             ,l_sort_var_tbl
10635             ,l_reversal_flag_tbl --NEW
10636             ,l_cancel_flag_tbl --NEW
10637             ,l_parent_pmt_id_tbl --NEW
10638             ,l_net_zero_flag_tbl  --NEW
10639             ,l_sc_xfer_code_tbl
10640             ,l_adj_exp_item_id_tbl --NEW
10641             ,l_fc_enabled_tbl  --NEW
10642             ,l_mrc_exchange_date_tbl
10643             ,l_fc_document_type_tbl
10644             ,l_si_assts_add_flg_tbl
10645             ,l_insert_flag_tbl
10646             ,l_pay_hist_id_tbl
10647             ,l_prepay_dist_id_tbl   --bug#5514129
10648             LIMIT v_max_size;
10649 
10650 
10651          G_err_stage := 'After fetching Prepay_Cur within transfer_pay_to_pa';
10652          write_log(LOG, G_err_stage);
10653 
10654          IF l_invoice_id_tbl.COUNT <> 0 THEN
10655 
10656             /* get the index of the last invoice being processed within the batch*/
10657             v_last_inv_index := l_invoice_id_tbl.LAST;
10658 
10659             G_err_stage := 'calling process_pay_logic for PREPAYMENTS within transfer_pay_to_pa';
10660             write_log(LOG, G_err_stage);
10661 
10662             process_pay_logic;
10663 
10664             G_err_stage := 'calling bulk_insert_trx_intf within transfer_pay_to_pa';
10665             write_log(LOG, G_err_stage);
10666 
10667             bulk_insert_trx_intf;
10668 
10669             G_err_stage := 'After calling bulk_insert_trx_intf within transfer_pay_to_pa';
10670             write_log(LOG, G_err_stage);
10671 
10672             G_err_stage := 'Before calling transaction import and tiebacks within transfer_pay_to_pa';
10673             write_log(LOG, G_err_stage);
10674 
10675             IF (v_num_distributions_fetched > 0) THEN
10676 
10677               write_log(LOG,'Before calling trx_import for Prepayment appl inv with interface_id:'||G_PREPAY_INTERFACE_ID);
10678               trans_import(G_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME, G_PREPAY_INTERFACE_ID, G_USER_ID);
10679 
10680               IF l_ap_prepay_tax_flag ='Y' THEN
10681                 trans_import(G_NRT_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME, G_PREPAY_INTERFACE_ID, G_USER_ID);
10682               END IF;
10683 
10684               IF l_ap_prepay_var_flag ='Y' THEN
10685                 trans_import(G_AP_VAR_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME, G_PREPAY_INTERFACE_ID, G_USER_ID);
10686               END IF;
10687               IF l_ap_prepay_erv_flag ='Y' THEN
10688                 trans_import(G_AP_ERV_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME, G_PREPAY_INTERFACE_ID, G_USER_ID);
10689               END IF;
10690 
10691               tieback_payment_AP_ER(G_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME,'APPPAY', G_PREPAY_INTERFACE_ID);
10692               IF l_ap_prepay_tax_flag ='Y' THEN
10693                 tieback_payment_AP_ER(G_NRT_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME,'APPPAY', G_PREPAY_INTERFACE_ID);
10694               END IF;
10695               IF l_ap_prepay_var_flag ='Y' THEN
10696                 tieback_payment_AP_ER(G_AP_VAR_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME,'APPPAY', G_PREPAY_INTERFACE_ID);
10697               END IF;
10698               IF l_ap_prepay_erv_flag ='Y' THEN
10699                 tieback_payment_AP_ER(G_AP_ERV_TRANSACTION_SOURCE, G_PREPAY_BATCH_NAME,'APPPAY', G_PREPAY_INTERFACE_ID);
10700               END IF;
10701 
10702               G_err_stage := 'Before updating the total number of prepayment appl processed';
10703               write_log(LOG, G_err_stage);
10704 
10705               G_NUM_BATCHES_PROCESSED       := G_NUM_BATCHES_PROCESSED + 1;
10706               G_NUM_INVOICES_PROCESSED      :=  G_NUM_INVOICES_PROCESSED + v_num_invoices_fetched;
10707               G_NUM_DISTRIBUTIONS_PROCESSED :=  G_NUM_DISTRIBUTIONS_PROCESSED + v_num_distributions_fetched;
10708               write_log(LOG,'G_NUM_BATCHES_PROCESSED:'||G_NUM_BATCHES_PROCESSED);
10709               write_log(LOG,'G_NUM_INVOICES_PROCESSED:'||G_NUM_INVOICES_PROCESSED);
10710               write_log(LOG,'G_NUM_DISTRIBUTIONS_PROCESSED:'||G_NUM_DISTRIBUTIONS_PROCESSED);
10711 
10712            END IF; /* IF (v_num_distributions_fetched > 0) */
10713 
10714            G_err_stage := 'After calling transaction import and tiebacks within transfer_pay_to_pa';
10715            write_log(LOG, G_err_stage);
10716 
10717            clear_plsql_tables;
10718 
10719            v_num_invoices_fetched       :=0;
10720            v_num_distributions_fetched  :=0;
10721 
10722            G_err_stage:='Before exiting when Prepay_Cur is NOTFOUND';
10723            write_log(LOG,   G_err_stage);
10724 
10725          ELSE
10726 
10727           G_err_stage:='Prepay Cursor fetched zero rows into plsql tables. Exiting';
10728           write_log(LOG,   G_err_stage);
10729           EXIT;
10730          END IF; /* l_invoice_id_tbl.COUNT = 0 */
10731 
10732          G_err_stage:='Cursor fetched no more rows. Exiting';
10733          write_log(LOG,   G_err_stage);
10734          EXIT WHEN Prepay_Cur%NOTFOUND;
10735 
10736       END LOOP; /* While more rows to process is true */
10737 
10738       CLOSE Prepay_Cur;
10739 
10740 
10741 EXCEPTION
10742     WHEN OTHERS THEN
10743 
10744          G_err_stack := v_old_stack;
10745          IF Payments_cur%ISOPEN THEN
10746            CLOSE Invoice_Cur;
10747          END IF ;
10748 
10749          IF Prepay_cur%ISOPEN THEN
10750            CLOSE Prepay_Cur;
10751          END IF ;
10752 
10753          G_err_code := SQLCODE;
10754          RAISE;
10755 
10756 END transfer_pay_to_pa;
10757 
10758 /*---------------------------Tieback to AP Phase----------------------------*/
10759 PROCEDURE tieback_payment_AP_ER(
10760    p_transaction_source IN pa_transaction_interface.transaction_source%TYPE,
10761    p_batch_name  IN pa_transaction_interface.batch_name%TYPE,
10762    p_batch_type  IN VARCHAR2,
10763    p_interface_id IN pa_transaction_interface.interface_id%TYPE) IS
10764 
10765    l_assets_addflag          VARCHAR2(1):=NULL;
10766    l_prev_assets_addflag     VARCHAR2(1):=NULL;
10767    l_project_id             NUMBER :=0;
10768    l_pa_addflag             VARCHAR2(1):=NULL;
10769    l_prev_proj_id           NUMBER :=0;
10770 
10771    l_sys_ref1_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
10772    l_sys_ref2_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
10773    l_sys_ref4_tbl           PA_PLSQL_DATATYPES.Char15TabTyp;
10774    l_sys_ref5_tbl           PA_PLSQL_DATATYPES.IdTabTyp;
10775    l_txn_src_tbl            PA_PLSQL_DATATYPES.Char30TabTyp;
10776    l_batch_name_tbl         PA_PLSQL_DATATYPES.Char50TabTyp;
10777    l_interface_id_tbl       PA_PLSQL_DATATYPES.IdTabTyp;
10778    l_txn_status_code_tbl    PA_PLSQL_DATATYPES.Char2TabTyp;
10779    l_project_id_tbl            PA_PLSQL_DATATYPES.IdTabTyp;
10780    l_pa_addflag_tbl         PA_PLSQL_DATATYPES.CHAR1TabTyp;
10781    l_assets_addflag_tbl     PA_PLSQL_DATATYPES.CHAR1TabTyp;
10782 
10783    CURSOR txn_intf_rec (p_txn_src       IN VARCHAR2,
10784                         p_batch_name    IN VARCHAR2,
10785                         p_interface_id  IN NUMBER) IS
10786       SELECT cdl_system_reference1
10787             ,cdl_system_reference2
10788             ,cdl_system_reference4
10789             ,cdl_system_reference5
10790             ,transaction_source
10791             ,batch_name
10792             ,interface_id
10793             ,transaction_status_code
10794             ,project_id
10795             ,l_pa_addflag
10796             ,l_assets_addflag
10797         FROM pa_transaction_interface_all txnintf
10798        WHERE txnintf.transaction_source = p_txn_src
10799          AND txnintf.batch_name         = p_batch_name
10800          AND txnintf.interface_id       = p_interface_id;
10801 
10802    PROCEDURE clear_plsql_tables IS
10803 
10804       v_status   VARCHAR2(15);
10805 
10806    BEGIN
10807 
10808       G_err_stage:='Clearing PLSQL tables in payment tieback';
10809       write_log(LOG,   G_err_stage);
10810 
10811       l_sys_ref1_tbl.delete;
10812       l_sys_ref2_tbl.delete;
10813       l_sys_ref4_tbl.delete;
10814       l_sys_ref5_tbl.delete;
10815       l_txn_src_tbl.delete;
10816       l_batch_name_tbl.delete;
10817       l_interface_id_tbl.delete;
10818       l_txn_status_code_tbl.delete;
10819       l_project_id_tbl.delete;
10820       l_pa_addflag_tbl.delete;
10821       l_assets_addflag_tbl.delete;
10822 
10823    END clear_plsql_tables;
10824 
10825    PROCEDURE process_tieback IS
10826 
10827       v_status   VARCHAR2(15);
10828 
10829    BEGIN
10830 
10831       G_err_stage:='Within process_tieback of payment tieback';
10832       write_log(LOG,   G_err_stage);
10833 
10834       FOR i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST LOOP
10835 
10836          /* If transaction import stamps the record to be 'A' then
10837             update pa_addition_flag of invoice distribution to 'Y'.
10838             If transaction import leaves the record to be 'P' then
10839             update pa_addition_flag of invoice distribution to 'N'.
10840             If transaction import stamps the record to be 'R' then
10841             update pa_addition_flag of invoice distribution to 'N'.*/
10842 
10843          write_log(LOG,'Tying invoice_id: '||l_sys_ref2_tbl(i)||
10844                        'Payment Id:  '||l_sys_ref4_tbl(i)||
10845                        'dist id:  '||l_sys_ref5_tbl(i)||
10846                        'trc src:   '||l_txn_src_tbl(i));
10847 
10848          IF l_txn_status_code_tbl(i) = 'A' THEN
10849                l_pa_addflag_tbl(i) := 'Y';
10850          ELSIF l_txn_status_code_tbl(i) = 'P' THEN
10851                l_pa_addflag_tbl(i) :='N';
10852          ELSIF l_txn_status_code_tbl(i) = 'R' THEN
10853                l_pa_addflag_tbl(i) := 'N';
10854          END IF;
10855 
10856          IF G_PROJECT_ID IS NOT NULL THEN
10857 
10858             IF G_Assets_Addition_flag = 'P' THEN
10859                l_assets_addflag_tbl(i) := 'P';
10860             ELSE
10861                l_assets_addflag_tbl(i) := 'X';
10862             END IF;
10863 
10864          ELSIF G_PROJECT_ID IS NULL THEN
10865 
10866             IF l_project_id_tbl(i) <> l_prev_proj_id THEN
10867 
10868                G_err_stage:='Selecting assets addition flag within payment tieback';
10869                write_log(LOG,   G_err_stage);
10870 
10871                SELECT decode(PTYPE.Project_Type_Class_Code,'CAPITAL','P','X')
10872                  INTO l_assets_addflag_tbl(i)
10873                  FROM pa_project_types_all PTYPE,
10874                       pa_projects_all PROJ
10875                 WHERE PTYPE.Project_Type = PROJ.Project_Type
10876                   AND (PTYPE.org_id = PROJ.org_id OR
10877                        PROJ.org_id is null)
10878                   AND PROJ.Project_Id = l_project_id_tbl(i);
10879 
10880                 l_prev_proj_id := l_project_id_tbl(i);
10881 		l_prev_assets_addflag := l_assets_addflag_tbl(i);
10882 
10883             ELSE
10884                l_assets_addflag_tbl(i) := l_prev_assets_addflag;
10885             END IF;
10886 
10887          END IF;
10888 
10889       END LOOP;
10890 
10891    EXCEPTION
10892       WHEN OTHERS THEN
10893          G_err_stage:= 'Failed during process tieback of payment tieback';
10894          write_log(LOG,   G_err_stage);
10895          G_err_code   := SQLCODE;
10896          raise;
10897 
10898    END process_tieback;
10899 
10900 
10901    PROCEDURE bulk_update_txn_intf(l_batch in VARCHAR2) IS
10902 
10903      v_status VARCHAR2(15);
10904 
10905    BEGIN
10906 
10907       G_err_stage:=('Within bulk update of payment tieback');
10908       write_log(LOG,   G_err_stage);
10909 
10910      IF l_batch = 'APPPAY' THEN --Prepayment Appl batch
10911 
10912       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
10913          UPDATE ap_prepay_app_dists dist
10914             SET dist.pa_addition_flag         = l_pa_addflag_tbl(i)
10915           WHERE dist.prepay_app_dist_id       = l_sys_ref4_tbl(i)
10916             AND dist.invoice_distribution_id  = l_sys_ref5_tbl(i)
10917             AND dist.pa_addition_flag         = 'O';
10918 
10919      ELSE
10920 
10921       FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
10922          UPDATE ap_payment_hist_dists paydist
10923             SET paydist.pa_addition_flag         = l_pa_addflag_tbl(i)
10924           WHERE paydist.invoice_payment_id       = l_sys_ref4_tbl(i)
10925             AND paydist.invoice_distribution_id  = l_sys_ref5_tbl(i)
10926             AND paydist.pa_addition_flag         = 'O';
10927 
10928 
10929       IF l_batch <> 'APDISC' THEN --Payment Discount batch
10930 
10931         FORALL i IN l_sys_ref1_tbl.FIRST..l_sys_ref1_tbl.LAST
10932            UPDATE ap_invoice_distributions_all dist
10933               SET dist.assets_addition_flag      = decode(l_assets_addflag_tbl(i),'P','P',dist.assets_addition_flag)
10934             WHERE dist.invoice_distribution_id = l_sys_ref5_tbl(i) ;
10935        END IF;
10936 
10937      END IF;
10938 
10939    EXCEPTION
10940       WHEN OTHERS THEN
10941          G_err_stage:= 'Failed during bulk update of payment tieback';
10942          write_log(LOG,   G_err_stage);
10943          G_err_code   := SQLCODE;
10944          raise;
10945 
10946    END bulk_update_txn_intf;
10947 
10948    BEGIN
10949 
10950       /* Main logic of tieback starts here */
10951       G_err_stage:='Within main logic of tieback';
10952       write_log(LOG,   G_err_stage);
10953 
10954       clear_plsql_tables;
10955 
10956       G_err_stage:='Opening txn_intf_rec';
10957       write_log(LOG,   G_err_stage);
10958 
10959       OPEN txn_intf_rec(p_transaction_source
10960                        ,p_batch_name
10961                        ,p_interface_id);
10962 
10963       G_err_stage:='Fetching txn_intf_rec';
10964       write_log(LOG,   G_err_stage);
10965 
10966       FETCH txn_intf_rec BULK COLLECT INTO
10967           l_sys_ref1_tbl
10968          ,l_sys_ref2_tbl
10969          ,l_sys_ref4_tbl
10970          ,l_sys_ref5_tbl
10971          ,l_txn_src_tbl
10972          ,l_batch_name_tbl
10973          ,l_interface_id_tbl
10974          ,l_txn_status_code_tbl
10975          ,l_project_id_tbl
10976          ,l_pa_addflag_tbl
10977          ,l_assets_addflag_tbl;
10978 
10979       IF l_sys_ref1_tbl.COUNT <> 0 THEN
10980 
10981          process_tieback;
10982 
10983          bulk_update_txn_intf(p_batch_type);
10984 
10985          clear_plsql_tables;
10986 
10987       END IF;
10988 
10989       CLOSE txn_intf_rec;
10990 
10991 EXCEPTION
10992    WHEN OTHERS THEN
10993 
10994       IF txn_intf_rec%ISOPEN THEN
10995          CLOSE txn_intf_rec;
10996       END IF;
10997 
10998       G_err_code := SQLCODE;
10999       RAISE;
11000 
11001 END tieback_payment_AP_ER;
11002 
11003 
11004    PROCEDURE process_adjustments (p_record_type                 IN Varchar2,
11005                                   p_document_header_id          IN number,/*Added this for 6945767 */
11006                                   p_document_distribution_id    IN number,
11007                                   p_document_payment_id         IN number DEFAULT NULL,
11008                                   p_current_index               IN number,
11009 			  	  p_last_index			IN OUT NOCOPY number) IS
11010        l_status3 VARCHAR2(30);
11011        j NUMBER := 0; --Index variable for creating reversal EI's --NEW
11012        l_xface_rec_exists_flg VARCHAR(1):='N';  --NEW
11013        l_fc_enabled   VARCHAR2(1) ;
11014        l_process_adjustments    Number := 0 ;
11015        l_all_reversed_cnt       Number := 0 ;
11016        l_not_reversed_cnt       Number := 0 ;
11017 
11018 
11019        CURSOR c_get_latest_ei IS
11020               SELECT ei.expenditure_item_id
11021                     , ei.project_id project_id
11022                     , ei.task_id  task_id
11023                     , ei.expenditure_item_date expenditure_item_date
11024                     , ei.expenditure_type expenditure_type
11025                     , ei.quantity quantity
11026                     , ei.raw_cost raw_cost
11027                     , nvl(ei.cost_distributed_flag,'N') cost_distributed_flag
11028                     , ei.organization_id organization_id
11029                     , ei.override_to_organization_id override_to_organization_id
11030                     , ei.receipt_currency_amount receipt_currency_amount
11031                     , ei.receipt_currency_code receipt_currency_code
11032                     , ei.receipt_exchange_rate receipt_exchange_rate
11033                     , ei.denom_raw_cost denom_raw_cost
11034                     , ei.denom_currency_code denom_currency_code
11035                     , ei.acct_rate_date acct_rate_date
11036                     , ei.acct_rate_type acct_rate_type
11037                     , ei.acct_exchange_rate acct_exchange_rate
11038                     , ei.acct_raw_cost acct_raw_cost
11039                     , ei.acct_exchange_rounding_limit acct_exchange_rounding_limit
11040                     , ei.attribute_category
11041                     , ei.attribute1
11042                     , ei.attribute2
11043                     , ei.attribute3
11044                     , ei.attribute4
11045                     , ei.attribute5
11046                     , ei.attribute6
11047                     , ei.attribute7
11048                     , ei.attribute8
11049                     , ei.attribute9
11050                     , ei.attribute10
11051                     , ei.org_id org_id
11052                     , get_cdl_ccid(ei.expenditure_item_id,'D') dr_code_combination_id
11053                     , get_cdl_ccid(ei.expenditure_item_id,'C') cr_code_combination_id
11054                     , Pa_Funds_Control_Utils.Get_Fnd_Reqd_Flag(ei.project_id,'STD') orig_fc_enabled
11055                     , nvl(cdl.transfer_status_code,'P') transfer_status_code
11056                     ,ei.document_type
11057                     ,ei.document_distribution_type
11058                     ,ei.document_header_id
11059                     ,ei.document_distribution_id
11060                     ,ei.document_payment_id
11061                     ,ei.document_line_number
11062                     ,cdl.system_reference5 cdl_sys_ref5 --to get the rcv_sub_leger_id of parent Rcv txn
11063               FROM   pa_cost_distribution_lines_all cdl,
11064                      pa_expenditure_items_all ei
11065               WHERE  cdl.expenditure_item_id (+) = ei.expenditure_item_id
11066                 AND  nvl(cdl.reversed_flag, 'N') = 'N'
11067                 AND    ei.document_distribution_id = p_document_distribution_id /*Added this for 6945767 */
11068                 AND   ei.system_linkage_function in ('VI','ER')
11069                 AND   ei.document_header_id = p_document_header_id /*Added this for 6945767 */
11070 		AND  nvl(cdl.line_type,'R') = 'R' --Bug 5373272 : 'C' and 'D' lines are incorrectly getting processed
11071                 AND  cdl.line_num_reversed is null
11072                 AND  (( p_record_type  = 'AP_INVOICE'
11073                 AND    ei.transaction_source in ('AP INVOICE','AP VARIANCE','AP EXPENSE','AP NRTAX'))
11074                  OR  ( p_record_type = 'PO_RECEIPT'
11075                 AND    ei.transaction_source IN ('PO RECEIPT', 'PO RECEIPT PRICE ADJ'))
11076                  OR  ( p_record_type = 'PO_RECEIPT_TAX'
11077                 AND    ei.transaction_source in ('PO RECEIPT NRTAX'))
11078                  OR  ( p_record_type = 'AP_DISCOUNTS'
11079                 AND    ei.document_payment_id = p_document_payment_id
11080                 AND    ei.transaction_source in ('AP DISCOUNTS','AP INVOICE','AP NRTAX'))
11081                  OR  ( p_record_type = 'AP_PAYMENT'
11082                 AND    ei.document_payment_id = p_document_payment_id
11083                 AND    ei.transaction_source in ('AP INVOICE','AP EXPENSE','AP NRTAX','AP VARIANCE')))
11084               AND    nvl(ei.net_zero_adjustment_flag,'N') <> 'Y'
11085               ORDER BY  ei.cost_distributed_flag, ei.expenditure_item_id;
11086 
11087 
11088    BEGIN
11089 
11090                   write_log(LOG, 'In Process Adjustments');
11091                   write_log(LOG, 'p_current_index = '||p_current_index);
11092                   write_log(LOG, 'p_last_index = '||p_last_index);
11093 
11094                   FOR c_latest_ei_rec in c_get_latest_ei LOOP
11095                       l_xface_rec_exists_flg:= 'Y'; -- Parent is in projects
11096 
11097                       write_log(LOG, 'For each record in the cursor');
11098 
11099                       IF  ( c_latest_ei_rec.cost_distributed_flag = 'N' AND
11100                            l_process_adjustments = 0) THEN
11101 
11102                               -- Reversal will not be interfaced since adjusted parent EI's have not been cost distributed
11103                               write_log(LOG, 'Adjustment not cost distributed in Projects');
11104                               l_txn_status_code_tbl(p_current_index) := 'R';
11105                               l_txn_rej_code_tbl(p_current_index) := 'PA_EI_NOT_COST_DISTRIBUTED';
11106 
11107                               EXIT;
11108 
11109                       ELSIF  c_latest_ei_rec.transfer_status_code = 'V' THEN
11110 
11111                           l_adj_exp_item_id_tbl(p_current_index):= c_latest_ei_rec.expenditure_item_id;
11112                           l_ei_date_tbl(p_current_index) := c_latest_ei_rec.expenditure_item_date; -- copy the source ei date
11113 
11114                               EXIT ;
11115 
11116 
11117                      ELSE
11118                           -- This indicates that there are multiple EI adjustments for the reversed distribution lines
11119                           -- This could happen if the EI was SPLIT across different projects
11120                           -- Incase there are multiple EI adjustments for single distribution we will insert multiple
11121                           -- records in the interface table each corresponding to the adjusted EI.
11122                           --
11123                           -- The following section will insert new table records at the end of the fetched table array
11124                           -- example : If bulk fetch populates 200 rows in PLSQL table array, the following section
11125                           --           will insert record in the PLSQL array from 201+ onwards
11126 
11127                           write_log(LOG, 'There are many adjustments that needs to be reversed in projects');
11128                       -- Set the net_zero_flag and the create adj record flag
11129                          l_net_zero_flag_tbl(p_current_index) := 'Y';
11130                          l_insert_flag_tbl(p_current_index)   := 'A';
11131                          l_fc_document_type_tbl(p_current_index) := 'NOT';
11132                          l_adj_exp_item_id_tbl(p_current_index):= 0; -- Skip the EI Date validation in Trx Imp.
11133                     -- Set the sc_xfer_code column on the xface table.
11134 
11135                           IF l_process_adjustments = 0 THEN
11136 
11137                                 j := p_last_index+1;
11138                           ELSE
11139 
11140                                 j := j + 1;
11141                           END IF;
11142 
11143                   write_log(LOG, 'j = '||j);
11144                           l_txn_src_tbl(j)        := l_txn_src_tbl(p_current_index);
11145                           l_user_txn_src_tbl(j)   := l_user_txn_src_tbl(p_current_index);
11146                           l_batch_name_tbl(j)     := l_batch_name_tbl(p_current_index);
11147                           l_project_id_tbl(j)     := c_latest_ei_rec.project_id;
11148                           l_task_id_tbl(j)        := c_latest_ei_rec.task_id;
11149                           l_exp_type_tbl(j)       := c_latest_ei_rec.expenditure_type;
11150                           l_exp_end_date_tbl(j)   := l_exp_end_date_tbl(p_current_index);
11151                           l_ei_date_tbl(j)        := c_latest_ei_rec.expenditure_item_date;
11152                           l_amount_tbl(j)         := c_latest_ei_rec.acct_raw_cost * -1;
11153                           l_quantity_tbl(j)       := nvl(c_latest_ei_rec.quantity,0) * -1;
11154                           l_description_tbl(j)    := l_description_tbl(p_current_index) ;
11155                           l_dist_cc_id_tbl(j)     := c_latest_ei_rec.dr_code_combination_id;
11156                           l_acct_pay_cc_id_tbl(j) := c_latest_ei_rec.cr_code_combination_id;
11157                           l_rec_cur_amt_tbl(j)    := c_latest_ei_rec.receipt_currency_amount * -1;
11158                           l_rec_cur_code_tbl(j)   := c_latest_ei_rec.receipt_currency_code;
11159                           l_rec_conv_rate_tbl(j)  := c_latest_ei_rec.receipt_exchange_rate;
11160                           l_denom_raw_cost_tbl(j) := c_latest_ei_rec.denom_raw_cost * -1;
11161                           l_denom_cur_code_tbl(j) := c_latest_ei_rec.denom_currency_code;
11162                           l_acct_rate_date_tbl(j) := c_latest_ei_rec.acct_rate_date;
11163                           l_acct_rate_type_tbl(j) := c_latest_ei_rec.acct_rate_type;
11164                           l_acct_exch_rate_tbl(j) := c_latest_ei_rec.acct_exchange_rate;
11165                           l_attribute_cat_tbl(j)  := c_latest_ei_rec.attribute_category;
11166                           l_attribute1_tbl(j)     := c_latest_ei_rec.attribute1;
11167                           l_attribute2_tbl(j)     := c_latest_ei_rec.attribute2;
11168                           l_attribute3_tbl(j)     := c_latest_ei_rec.attribute3;
11169                           l_attribute4_tbl(j)     := c_latest_ei_rec.attribute4;
11170                           l_attribute5_tbl(j)     := c_latest_ei_rec.attribute5;
11171                           l_attribute6_tbl(j)     := c_latest_ei_rec.attribute6;
11172                           l_attribute7_tbl(j)     := c_latest_ei_rec.attribute7;
11173                           l_attribute8_tbl(j)     := c_latest_ei_rec.attribute8;
11174                           l_attribute9_tbl(j)     := c_latest_ei_rec.attribute9;
11175                           l_attribute10_tbl(j)    := c_latest_ei_rec.attribute10;
11176                           l_org_id_tbl(j)         := nvl(c_latest_ei_rec.organization_id,c_latest_ei_rec.override_to_organization_id);
11177                           l_exp_org_id_tbl(j)     := c_latest_ei_rec.override_to_organization_id;
11178                           l_vendor_id_tbl(j)      := l_vendor_id_tbl(p_current_index);
11179 
11180                           IF p_record_type like 'PO_RECEIPT%' THEN
11181                             l_po_head_id_tbl(j)        := c_latest_ei_rec.document_header_id;
11182                             l_po_dist_id_tbl(j)        := c_latest_ei_rec.document_line_number;
11183                             l_rcv_txn_id_tbl(j)        := c_latest_ei_rec.document_distribution_id;
11184                             l_rcv_sub_ledger_id_tbl(j) := to_number(c_latest_ei_rec.cdl_sys_ref5);
11185                             l_dest_typ_code_tbl(j)     := c_latest_ei_rec.document_type;
11186                             l_trx_type_tbl(j)          := c_latest_ei_rec.document_distribution_type;
11187                             l_rcv_acct_evt_id_tbl(j)   := l_rcv_acct_evt_id_tbl(p_current_index);
11188                             l_acct_raw_cost_tbl(j)     := c_latest_ei_rec.acct_raw_cost * -1;
11189                             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
11190                             IF p_record_type =  'PO_RECEIPT' THEN
11191                               l_record_type_tbl(j)       := 'RECEIPT';
11192                             ELSE
11193                               l_record_type_tbl(j)       := 'RCVTAX';
11194                             END IF;
11195                               l_entered_nr_tax_tbl(j)    := 0;
11196                               l_pa_add_flag_tbl(j)       := 'O';
11197                           ELSE
11198                             l_invoice_id_tbl(j)     := l_invoice_id_tbl(p_current_index);
11199                             l_invoice_dist_id_tbl(j):= l_invoice_dist_id_tbl(p_current_index); -- R12 funds management Uptake
11200                             l_cdl_sys_ref4_tbl(j)   := l_cdl_sys_ref4_tbl(p_current_index);
11201                             l_cdl_sys_ref3_tbl(j)   := l_cdl_sys_ref3_tbl(p_current_index);
11202                             l_invoice_num_tbl(j)    := l_invoice_num_tbl(p_current_index);
11203                             l_inv_type_code_tbl(j)  := c_latest_ei_rec.document_type;
11204                             l_ln_type_lookup_tbl(j) := c_latest_ei_rec.document_distribution_type;
11205                           END IF;
11206 
11207                           IF p_record_type in ('AP_DISCOUNTS','AP_PAYMENT')  THEN
11208                             l_inv_pay_id_tbl(j)     := c_latest_ei_rec.document_payment_id;
11209                             l_pay_hist_id_tbl(j)    := c_latest_ei_rec.cdl_sys_ref5;
11210                           END IF;
11211 
11212                           l_gl_date_tbl(j)        := l_gl_date_tbl(p_current_index);
11213                           l_employee_id_tbl(j)    := l_employee_id_tbl(p_current_index);
11214                           l_bus_grp_id_tbl(j)     := l_bus_grp_id_tbl(p_current_index);
11215                           l_txn_status_code_tbl(j):= l_txn_status_code_tbl(p_current_index);
11216                           l_txn_rej_code_tbl(j)   := l_txn_rej_code_tbl(p_current_index);
11217                           l_interface_id_tbl(j)   := l_interface_id_tbl(p_current_index);
11218                           l_adj_exp_item_id_tbl(j):= c_latest_ei_rec.expenditure_item_id;
11219                           l_net_zero_flag_tbl(j)  := 'N';
11220                           l_sc_xfer_code_tbl(j)   := 'P';
11221                           l_si_assts_add_flg_tbl(j) := 'T'; --For Adjustments done in PA
11222                           l_insert_flag_tbl(j)   := 'Y';
11223 
11224                           write_log(LOG, 'Adjustment records populated into the PL/SQL table');
11225 
11226                           --
11227                           -- This section is to ensure that the commitments are relieved and actuals
11228                           -- are funds checked.
11229                           --
11230                           If l_fc_enabled_tbl(p_current_index) = 'Y' AND   c_latest_ei_rec.orig_fc_enabled = 'N' THEN
11231                               l_fc_document_type_tbl(j) := 'CMT';
11232                           ELSIF l_fc_enabled_tbl(p_current_index) = 'Y' AND   c_latest_ei_rec.orig_fc_enabled = 'Y' THEN
11233                               l_fc_document_type_tbl(j) := 'ALL';
11234                           ELSIF l_fc_enabled_tbl(p_current_index) = 'N' AND   c_latest_ei_rec.orig_fc_enabled = 'N' THEN
11235                               l_fc_document_type_tbl(j) := 'NOT';
11236                           ELSIF l_fc_enabled_tbl(p_current_index) = 'N' AND   c_latest_ei_rec.orig_fc_enabled = 'Y' THEN
11237                               l_fc_document_type_tbl(j) := 'ACT';
11238                           END IF ;
11239 
11240                           l_process_adjustments  := 1 ;
11241 
11242                   write_log(LOG, 'p_current_index = '||p_current_index);
11243                     END IF; --End of rowcount=0
11244                     write_log(LOG, 'Done with processing reversals');
11245 
11246                  END LOOP; --End of cursor c_get_latest_ei
11247 
11248                  IF j>= p_last_index THEN
11249 
11250                  -- Some adjustments were created.
11251                  p_last_index := j;
11252                  write_log(LOG, 'p_last_index = '||p_last_index);
11253 
11254                  ELSIF l_xface_rec_exists_flg = 'N' THEN --Parent is not in PA/or All the adjustments got reversed.
11255 
11256                 write_log(LOG, 'Setting the netzero flag  adjustment records..');
11257                    -- Logic for interfacing both the parent and the child (netzero) in the same run.
11258 
11259                   IF l_rev_parent_dist_id_tbl.exists(1) THEN
11260                     FOR i in l_rev_parent_dist_id_tbl.first..l_rev_parent_dist_id_tbl.last LOOP
11261 
11262                       IF (l_rev_parent_dist_id_tbl(i) = p_document_distribution_id OR
11263                         l_rev_parent_dist_id_tbl(i) = p_document_payment_id) THEN
11264 
11265                        IF l_inv_pay_id_tbl.EXISTS(p_current_index) THEN
11266                         IF l_reversal_flag_tbl(p_current_index) = 'R' THEN
11267                         -- If the reversal is for invoice distributions then store the reversed child inv dist id ..Bug# 5408748
11268                           l_rev_child_dist_id_tbl(i):= l_invoice_dist_id_tbl(p_current_index);
11269                         ELSE
11270                         -- If the reversal is for payment distributions then store the reversed child payment id ..Bug# 5408748
11271                           l_rev_child_dist_id_tbl(i):= l_inv_pay_id_tbl(p_current_index);
11272                         END IF;
11273 
11274                        ELSE
11275                         l_rev_child_dist_id_tbl(i):= l_invoice_dist_id_tbl(p_current_index);
11276                        END IF;
11277                         l_net_zero_flag_tbl(l_rev_parent_dist_ind_tbl(i)) := 'Y'; -- Set the parent netzero_flag
11278                         l_insert_flag_tbl(p_current_index)   := 'U';  -- update adjustment record
11279                         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.
11280                         write_log(LOG, 'Parent dist ='||l_rev_parent_dist_id_tbl(i)||' Child dist = '||l_rev_child_dist_id_tbl(i));
11281 
11282                       END IF;
11283 
11284                     END LOOP;
11285                  END IF;
11286 
11287          -- Handle the corner case where the project adjustments got reversed in an earlier run, but the ap reversal was rejected.
11288          -- This section brings in the ap reversal as a netzero pair rather than a standalone reversal.Bug#5064930.
11289 
11290             IF l_insert_flag_tbl(p_current_index) <> 'U' THEN
11291 
11292                  write_log(LOG, 'Selecting the count of adjusted expenditures');
11293 
11294                  SELECT  sum(decode(ei.net_zero_adjustment_flag,'N',1,0)),count(*)
11295                  INTO   l_not_reversed_cnt,l_all_reversed_cnt
11296                  FROM   pa_expenditure_items_all ei
11297                  /*Added this for 6945767 */
11298                  WHERE  ei.document_distribution_id = p_document_distribution_id
11299                  AND   ei.document_header_id = p_document_header_id /*Added this for 6945767 */
11300                  AND  (( p_record_type  = 'AP_INVOICE'
11301                  -- AND    ei.document_distribution_id = p_document_distribution_id
11302                  AND    ei.transaction_source in ('AP INVOICE','AP VARIANCE','AP EXPENSE','AP NRTAX'))
11303                   OR  ( p_record_type = 'PO_RECEIPT'
11304                  --AND    ei.document_distribution_id = p_document_distribution_id
11305                  AND    ei.transaction_source IN ('PO RECEIPT', 'PO RECEIPT PRICE ADJ'))
11306                   OR  ( p_record_type = 'PO_RECEIPT_TAX'
11307                  --AND    ei.document_distribution_id = p_document_distribution_id
11308                  AND    ei.transaction_source in ('PO RECEIPT NRTAX'))
11309                   OR  ( p_record_type = 'AP_DISCOUNTS'
11310                  --AND    ei.document_distribution_id = p_document_distribution_id
11311                  AND    ei.document_payment_id = p_document_payment_id
11312                  AND    ei.transaction_source in ('AP DISCOUNTS','AP INVOICE','AP NRTAX'))
11313                   OR  ( p_record_type = 'AP_PAYMENT'
11314                  --AND    ei.document_distribution_id = p_document_distribution_id
11315                  AND    ei.document_payment_id = p_document_payment_id
11316                  AND    ei.transaction_source in ('AP INVOICE','AP EXPENSE','AP VARIANCE','AP NRTAX'))) ;
11317 
11318                IF (l_all_reversed_cnt > 0 and l_not_reversed_cnt = 0 ) THEN
11319 
11320                  write_log(LOG, 'Setting the netzero pair logic for the reversal distribution ='||p_document_distribution_id);
11321                       -- Set the net_zero_flag and the create adj record flag
11322                          l_net_zero_flag_tbl(p_current_index) := 'Y';
11323                          l_insert_flag_tbl(p_current_index)   := 'A';
11324 
11325                END IF;
11326 
11327             END IF;
11328           END IF;
11329 
11330    EXCEPTION
11331       WHEN OTHERS THEN
11332           write_log(LOG,'Failed reversal processing');
11333           G_err_code   := SQLCODE;
11334                    write_log(LOG, 'Error Code is  '||SQLCODE);
11335                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 1, 200));
11336                    write_log(LOG, 'Error Message is  '||SUBSTR(SQLERRM, 201, 200));
11337           raise;
11338    END;
11339 
11340 FUNCTION ReceiptPaAdditionFlag(p_Pa_Addition_Flag      IN VARCHAR2,
11341                                p_Po_Distribution_Id    IN NUMBER)
11342                               RETURN VARCHAR2 IS
11343 
11344    l_Dummy              VARCHAR2(1);
11345    l_Pa_Addition_Flag   VARCHAR2(1);
11346 
11347 BEGIN
11348  write_log(LOG,'Inside ReceiptPaAdditionFlag');
11349 
11350 l_Pa_Addition_Flag:=p_Pa_Addition_Flag;
11351 
11352   SELECT 'X'
11353   INTO l_Dummy
11354   FROM DUAL
11355   WHERE EXISTS ( SELECT NULL
11356                  FROM   rcv_transactions rcv_txn2
11357                        ,rcv_receiving_sub_ledger rcv_sub2
11358                  WHERE  rcv_sub2.rcv_transaction_id    = rcv_txn2.transaction_id
11359                  AND    rcv_txn2.po_distribution_id    = P_Po_Distribution_Id
11360                  AND    rcv_sub2.pa_addition_flag      = 'G'
11361                   UNION ALL
11362                  SELECT  null
11363                  FROM    ap_invoice_distributions apdist
11364                  WHERE   apdist.po_distribution_id = P_Po_Distribution_Id
11365                  AND     apdist.line_type_lookup_code in ('ITEM','ACCRUAL','NONREC_TAX')
11366                  AND     apdist.pa_addition_flag         = 'Y');
11367 
11368    If l_Dummy = 'X' THEN
11369        write_log(LOG,'ReceiptPaAdditionFlag:l_Dummy is X');
11370       RETURN 'G';
11371    ELSE
11372        write_log(LOG,'ReceiptPaAdditonFlag:l_pa_addition_flag'||l_Pa_Addition_Flag);
11373       RETURN l_Pa_Addition_Flag;
11374    END IF;
11375 
11376 EXCEPTION
11377 WHEN NO_DATA_FOUND THEN
11378     write_log(LOG,'ReceiptPaAdditonFlag NDF:l_pa_addition_flag'||l_Pa_Addition_Flag);
11379     RETURN l_Pa_Addition_Flag;
11380 
11381 WHEN Others THEN
11382    G_err_code := SQLCODE;
11383    RAISE;
11384 
11385 END ReceiptPaAdditionFlag;
11386 
11387 END PAAPIMP_PKG;