DBA Data[Home] [Help]

PACKAGE BODY: APPS.AP_AUTOSELECT_PKG

Source


1 PACKAGE BODY AP_AUTOSELECT_PKG AS
2 /* $Header: appbselb.pls 120.132.12020000.12 2013/02/28 23:57:39 lnilacan ship $ */
3 
4    G_PKG_NAME          CONSTANT VARCHAR2(30) := 'AP_AUTOSELECT_PKG';
5    G_MSG_UERROR        CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR;
6    G_MSG_ERROR         CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_ERROR;
7   G_MSG_SUCCESS       CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_SUCCESS;
8    G_MSG_HIGH          CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_DEBUG_HIGH;
9    G_MSG_MEDIUM        CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_DEBUG_MEDIUM;
10    G_MSG_LOW           CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_DEBUG_LOW;
11    G_LINES_PER_FETCH   CONSTANT NUMBER       := 1000;
12 
13    G_CURRENT_RUNTIME_LEVEL CONSTANT NUMBER       := FND_LOG.G_CURRENT_RUNTIME_LEVEL;
14    G_LEVEL_UNEXPECTED      CONSTANT NUMBER       := FND_LOG.LEVEL_UNEXPECTED;
15    G_LEVEL_ERROR           CONSTANT NUMBER       := FND_LOG.LEVEL_ERROR;
16    G_LEVEL_EXCEPTION       CONSTANT NUMBER       := FND_LOG.LEVEL_EXCEPTION;
17    G_LEVEL_EVENT           CONSTANT NUMBER       := FND_LOG.LEVEL_EVENT;
18    G_LEVEL_PROCEDURE       CONSTANT NUMBER       := FND_LOG.LEVEL_PROCEDURE;
19    G_LEVEL_STATEMENT       CONSTANT NUMBER       := FND_LOG.LEVEL_STATEMENT;
20    G_MODULE_NAME           CONSTANT VARCHAR2(80) := 'AP.PLSQL.AP_AUTOSELECT_PKG';
21 
22 
23 /* Added for bug#9930653 Start */
24 FUNCTION prorated_awt_gross_amt
25 ( p_invoice_id  NUMBER
26 , p_payment_num NUMBER
27 )
28 RETURN NUMBER IS
29  l_awt_amount     NUMBER;
30  l_schedules_sum  NUMBER;
31  l_gross_amount   NUMBER;
32  l_prorated_awt_gross_amt  NUMBER;
33 
34 BEGIN
35 
36   SELECT nvl(SUM(amount),0)
37     INTO l_awt_amount
38     FROM ap_invoice_distributions_all
39    WHERE invoice_id = p_invoice_id
40      AND awt_invoice_payment_id IS NULL
41      AND line_type_lookup_code = 'AWT';
42 
43   SELECT nvl(SUM(gross_amount),1)
44     INTO l_schedules_sum
45     FROM ap_payment_schedules_all
46    WHERE invoice_id = p_invoice_id;
47 
48   SELECT gross_amount
49     INTO l_gross_amount
50     FROM ap_payment_schedules_all
51    WHERE invoice_id = p_invoice_id
52      AND payment_num = p_payment_num;
53 
54   l_prorated_awt_gross_amt :=
55       l_gross_amount + (l_awt_amount * (l_gross_amount/l_schedules_sum));
56 
57   RETURN l_prorated_awt_gross_amt;
58 
59 EXCEPTION
60   WHEN OTHERS THEN
61   l_prorated_awt_gross_amt := 1;
62 END;
63 /* Added for bug#9930653 End */
64 
65 /* bug 8691645 */
66 PROCEDURE check_ccr_status( p_checkrun_id  varchar2 ,
67                             p_calling_sequence VARCHAR2) IS
68 
69 
70  TYPE invoice_id_t IS TABLE OF AP_INVOICES.INVOICE_ID%TYPE INDEX BY BINARY_INTEGER;
71  TYPE vendor_id_t IS TABLE OF AP_INVOICES.VENDOR_ID%TYPE INDEX BY BINARY_INTEGER;
72  TYPE vendor_site_id_t IS TABLE OF AP_INVOICES.VENDOR_SITE_ID%TYPE INDEX BY BINARY_INTEGER;
73  TYPE remit_to_supplier_site_id_t IS TABLE OF AP_INVOICES.REMIT_TO_SUPPLIER_SITE_ID%TYPE INDEX BY BINARY_INTEGER;
74 
75  TYPE ccr_rec_type IS RECORD (
76      invoice_id_tab                   invoice_id_t
77     ,vendor_id_tab                    vendor_id_t
78     ,vendor_site_id_tab               vendor_site_id_t
79     ,remit_to_supplier_site_id_tab    remit_to_supplier_site_id_t
80    );
81 
82  ccr_rec_info ccr_rec_type;
83  ccr_rec_list ccr_rec_type;
84  l_ind                        NUMBER :=1;
85  l_Vendor_Site_Reg_Expired    VARCHAR2(1) :='N';
86  l_system_user                NUMBER :=5;
87  l_holds                      AP_APPROVAL_PKG.HOLDSARRAY;
88  l_hold_count                 AP_APPROVAL_PKG.COUNTARRAY;
89  l_release_count              AP_APPROVAL_PKG.COUNTARRAY;
90  l_calling_sequence           VARCHAR2(2000);
91  l_debug_info                 varchar2(2000);
92 
93 
94 CURSOR selected_inv(p_checkrun_id  varchar2) IS
95 SELECT asi.invoice_id
96         ,asi.vendor_id
97         ,asi.vendor_site_id
98         ,asi.remit_to_supplier_site_id
99 FROM   ap_selected_invoices_all asi,ap_invoices_all ai
100 WHERE  ai.invoice_id=asi.invoice_id
101 AND    ai.invoice_type_lookup_code in ('STANDARD','PREPAYMENT')
102 AND    AP_UTILITIES_PKG.GET_CCR_STATUS(asi.vendor_id,'S') <> 'F'
103 AND    asi.checkrun_id=p_checkrun_id;
104 
105 BEGIN
106 
107  l_calling_sequence := p_calling_sequence || 'CHECK_CCR_STATUS';
108 
109 
110   l_debug_info := 'Start of check_ccr_status';
111   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
112     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
113   END IF;
114 
115 OPEN  selected_inv(p_checkrun_id);
116 LOOP
117 FETCH selected_inv
118 BULK  COLLECT INTO  ccr_rec_info.invoice_id_tab
119                   ,ccr_rec_info.vendor_id_tab
120                   ,ccr_rec_info.vendor_site_id_tab
121                   ,ccr_rec_info.remit_to_supplier_site_id_tab
122 
123 LIMIT 1000;
124 
125 l_debug_info := 'CALLING AP_APPROVAL_PKG.CHECK_CCR_VENDOR ';
126   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
127     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
128   END IF;
129 
130 for i in 1 .. ccr_rec_info.invoice_id_tab.count loop
131 
132   AP_APPROVAL_PKG.CHECK_CCR_VENDOR(
133               P_INVOICE_ID                => ccr_rec_info.invoice_id_tab(i),
134               P_VENDOR_ID                 => ccr_rec_info.vendor_id_tab(i),
135               P_VENDOR_SITE_ID            => ccr_rec_info.vendor_site_id_tab(i),
136               P_REMIT_TO_SUPPLIER_SITE_ID => ccr_rec_info.remit_to_supplier_site_id_tab(i),
137               P_SYSTEM_USER               => l_system_user ,
138               P_HOLDS                     => l_holds,
139               P_HOLDS_COUNT               => l_hold_count,
140               P_RELEASE_COUNT             => l_release_count,
141               P_VENDOR_SITE_REG_EXPIRED   => l_Vendor_Site_Reg_Expired,
142               P_CALLING_SEQUENCE          => l_calling_sequence);
143 
144    l_debug_info := 'vendor_id '||ccr_rec_info.vendor_id_tab(i)||' returned ccr reg status ' ||l_Vendor_Site_Reg_Expired ;
145    IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
146     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
147    END IF;
148 
149    IF(l_Vendor_Site_Reg_Expired <>'N') then
150      ccr_rec_list.invoice_id_tab(l_ind) := ccr_rec_info.invoice_id_tab(i);
151      ccr_rec_list.vendor_id_tab(l_ind)  := ccr_rec_info.vendor_id_tab(i);
152      ccr_rec_list.vendor_site_id_tab(l_ind) :=ccr_rec_info.vendor_site_id_tab(i);
153      ccr_rec_list.remit_to_supplier_site_id_tab(l_ind) :=ccr_rec_info.remit_to_supplier_site_id_tab(i);
154 
155 
156      l_ind :=l_ind+1;
157 
158    END IF ;
159 
160 END LOOP;
161 
162 
163 
164 if (ccr_rec_list.invoice_id_tab.count >0) then
165 
166  l_debug_info := 'rejecting the invoices of inactive ccr status sites';
167   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
168     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
169   END IF;
170 
171 FORALL i IN ccr_rec_list.invoice_id_tab.first .. ccr_rec_list.invoice_id_tab.LAST
172 UPDATE    Ap_Selected_Invoices_All ASI
173    SET    ASI.ok_to_pay_flag = 'N',
174           ASI.dont_pay_reason_code =  'CCR_REG_EXPIRED'
175  WHERE    ASI.checkrun_id = p_checkrun_id
176    AND    ASI.invoice_id=ccr_rec_list.invoice_id_tab(i);
177 
178 end if ;
179 
180 EXIT WHEN selected_inv%NOTFOUND;
181 END LOOP;
182 CLOSE selected_inv;
183 
184 
185 
186  l_debug_info := 'End of check_ccr_status';
187   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
188     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
189   END IF;
190 
191 EXCEPTION
192 
193 WHEN OTHERS then
194 
195     IF (SQLCODE <> -20001) THEN
196       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
197       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
198       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_calling_sequence );
199       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
200       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_checkrun_id: '||
201                                            to_char(p_checkrun_id));
202 
203     END IF;
204     APP_EXCEPTION.RAISE_EXCEPTION;
205 
206 
207 END check_ccr_status;
208 
209 
210 --Bug6459578
211 
212 PROCEDURE awt_special_rounding(p_checkrun_name in varchar2,p_calling_sequence in varchar2) IS
213 
214 l_debug_info    VARCHAR2(200);
215 l_current_calling_sequence  VARCHAR2(2000);
216 
217 BEGIN
218   -- Update the calling sequence
219 
220      l_current_calling_sequence := p_calling_sequence || '<-awt_special_rounding';
221      l_debug_info := 'Call AP_CUSTOM_WITHHOLDING_PKG.AP_SPECIAL_ROUNDING';
222 
223 
224      AP_CUSTOM_WITHHOLDING_PKG.AP_SPECIAL_ROUNDING(p_checkrun_name);
225 
226 
227 EXCEPTION
228     WHEN OTHERS then
229 
230     IF (SQLCODE <> -20001) THEN
231       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
232       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
233       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
234       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
235       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_checkrun_name: '||
236                                            p_checkrun_name);
237 
238     END IF;
239     APP_EXCEPTION.RAISE_EXCEPTION;
240 
241 END;
242 
243 
244 PROCEDURE calculate_interest (p_checkrun_id in number,
245                               p_checkrun_name in varchar2,
246                               p_check_date in date,
247                               p_calling_sequence in varchar2) is
248 
249 
250 CURSOR interest_cursor IS
251 SELECT   ASI.invoice_id, ASI.payment_num, ASI.vendor_id,
252          ASI.vendor_site_id, ASI.vendor_num, ASI.vendor_name,
253          ASI.vendor_site_code, ASI.address_line1, ASI.address_line2,
254          ASI.address_line3, ASI.address_line4, ASI.city, ASI.state, ASI.zip,
255          ASI.invoice_num, ASI.voucher_num,
256          -- ASI.payment_priority,   -- Bug 5139574
257          nvl(ASI.payment_priority, 99), ASI.province,
258          ASI.country, ASI.withholding_status_lookup_code,
259          ASI.attention_ar_flag, ASI.set_of_books_id,
260          ASI.invoice_exchange_rate, ASI.payment_cross_rate,
261          ASI.customer_num, asi.external_bank_account_id, ASI.ok_to_pay_flag,
262          round(LEAST(TRUNC(P_check_date),ADD_MONTHS(TRUNC(due_date),12))
263                - TRUNC(due_date)), /*Bug 5124784 */
264          /* annual_interest_rate, Bug#12835170 */
265          /* Added for Bug#12835170 Start */
266          (
267           SELECT annual_interest_rate
268             FROM ap_interest_periods aip
269            WHERE trunc(due_date+1) BETWEEN trunc(start_date) AND trunc(end_date)
270          ) annual_interest_rate,
271          /* Added for Bug#12835170 End */
272          AI.invoice_currency_code,
273          ASI.payment_currency_code,
274          /* bug 5233279. For Federal Installation Exclusive payment Flag is required */
275          decode(Ap_Payment_Util_Pkg.is_federal_installed(AI.org_id),
276                 'Y', AI.exclusive_payment_flag, 'N'),
277          asp.interest_accts_pay_ccid,
278          ai.org_id
279 FROM     /* ap_interest_periods, Bug#12835170 */
280          ap_invoices AI, --Bug6040657. Changed from ap_invoices_all to ap_invoices
281          ap_selected_invoices_all ASI,
282          po_vendors pov,
283          ap_system_parameters_all asp
284 WHERE  ASI.checkrun_id = P_checkrun_id
285 AND    ASP.auto_calculate_interest_flag = 'Y'
286 AND    ASP.org_id = asi.org_id
287 AND    TRUNC(P_check_date) > TRUNC(due_date)
288 /* AND    (trunc(due_date)+1) BETWEEN trunc(start_date) AND trunc(end_date)
289 AND    (NVL(payment_amount,0) *
290             POWER(1 + (annual_interest_rate/(12 * 100)),
291                   TRUNC((LEAST(P_check_date,
292                                ADD_MONTHS(due_date,12))
293                         - due_date) / 30))
294             *
295             (1 + ((annual_interest_rate/(360 * 100)) *
296                   MOD((LEAST(P_check_date,
297                              ADD_MONTHS(due_date,12))
298                       - due_date)
299                       , 30))))
300             - NVL(payment_amount,0) >= NVL(asp.interest_tolerance_amount,0) Bug#12835170 */
301 AND    ASI.vendor_id = pov.vendor_id
302 AND    pov.auto_calculate_interest_flag = 'Y'
303 AND    AI.invoice_id = ASI.invoice_id
304 AND    AI.invoice_type_lookup_code <> 'PAYMENT REQUEST';
305 
306 
307   l_address_line1            po_vendor_sites_all.address_line1%TYPE;
308   l_address_line2            po_vendor_sites_all.address_line2%TYPE;
309   l_address_line3            po_vendor_sites_all.address_line3%TYPE;
310   l_address_line4            po_vendor_sites_all.address_line4%TYPE;
311   l_amount_remaining         NUMBER;
312   l_attention_ar_flag        VARCHAR2(1);
313   l_awt_status_lookup_code   VARCHAR2(25);
314   l_city                     ap_selected_invoices_all.city%type; --6708281
315   l_country                  ap_selected_invoices_all.country%type; --6708281
316 --  l_city                     VARCHAR2(25);
317 --  l_country                  VARCHAR2(25);
318   l_current_calling_sequence varchar2(2000);
319   l_customer_num             VARCHAR2(25);
320   l_debug_info               varchar2(200);
321   l_discount_available       NUMBER;
322   l_discount_taken           NUMBER;
323   l_due_date                 date;
324   l_exclusive_payment_flag   VARCHAR2(1);
325   l_existing_interest_count  NUMBER;
326   l_external_bank_account_id number;
327   l_int_invoice_amt          NUMBER;
328   l_int_invoice_days         NUMBER;
329   l_int_invoice_no           varchar2(50);
330   l_int_invoice_num          VARCHAR2(50);
331   l_int_invoice_rate         NUMBER;
332   l_int_vendor_name          po_vendors.vendor_name%TYPE;
333   l_int_vendor_num           VARCHAR2(30);
334   l_interest_ap_ccid         number;
335   l_inv_curr_int_amt         NUMBER;
336   l_invoice_currency_code    VARCHAR2(15);
337   l_invoice_exchange_rate    NUMBER;
338   l_invoice_id               number;
339   l_nls_days                 ap_lookup_codes.displayed_field%TYPE;
340   l_nls_int                  ap_lookup_codes.displayed_field%TYPE;
341   l_nls_interest             ap_lookup_codes.displayed_field%TYPE;
342   l_nls_percent              ap_lookup_codes.displayed_field%TYPE;
343   l_ok_to_pay_flag           VARCHAR2(1);
344   l_org_id                   number;
345   l_pay_currency_code        VARCHAR2(15);
346   l_payment_amount           NUMBER;
347   l_payment_cross_rate       NUMBER;
348   l_payment_num              number;
349   l_payment_priority         NUMBER(2);
350   l_proposed_interest_count  NUMBER;
351   l_province                 VARCHAR2(150);
352   l_set_of_books_id          number;
353   l_site_code                po_vendor_sites_all.vendor_site_code%TYPE;
354   l_site_id                  NUMBER(15);
355   l_state                    VARCHAR2(150);
356   l_vendor_id                number;
357   l_voucher_num              VARCHAR2(50);
358 --  l_zip                      VARCHAR2(20);
359   l_zip                      ap_selected_invoices_all.zip%type;  --6708281
360 
361 
362 BEGIN
363 
364   l_debug_info := 'Perform Interest calculations';
365   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
366     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
367   END IF;
368 
369   l_current_calling_sequence := p_calling_sequence || '<-calculate_interest';
370 
371 
372   SELECT   substrb(l1.displayed_field, 1, 25),
373            substrb(l2.displayed_field, 1, 10),
374            substrb(l3.displayed_field, 1, 5),
375            substrb(l4.displayed_field, 1, 25)
376   INTO     l_nls_interest,
377            l_nls_days,
378            l_nls_percent,
379            l_nls_int
380   FROM     ap_lookup_codes l1,
381            ap_lookup_codes l2,
382            ap_lookup_codes l3,
383            ap_lookup_codes l4
384   WHERE  l1.lookup_type = 'NLS TRANSLATION'
385   AND    l1.lookup_code = 'INTEREST'
386   AND    l2.lookup_type = 'NLS TRANSLATION'
387   AND    l2.lookup_code = 'DAYS'
388   AND    l3.lookup_type = 'NLS TRANSLATION'
389   AND    l3.lookup_code = 'PERCENT'
390   AND    l4.lookup_type = 'NLS TRANSLATION'
391   AND    l4.lookup_code = 'INT';
392 
393 
394 
395 
396 
397 --interest calculations
398 
399   OPEN interest_cursor;
400 
401   LOOP
402 
403     FETCH  interest_cursor
404     INTO     l_invoice_id, l_payment_num, l_vendor_id,
405              l_site_id, l_int_vendor_num, l_int_vendor_name,
406              l_site_code, l_address_line1, l_address_line2,
407              l_address_line3, l_address_line4, l_city, l_state, l_zip, l_int_invoice_num,
408              l_voucher_num, l_payment_priority, l_province,
409              l_country, l_awt_status_lookup_code,
410              l_attention_ar_flag,
411              l_set_of_books_id,
412              l_invoice_exchange_rate,
413              l_payment_cross_rate,
414              l_customer_num,
415              l_external_bank_account_id,
416              l_ok_to_pay_flag,
417              l_int_invoice_days,
418              l_int_invoice_rate,
419              l_invoice_currency_code,
420              l_pay_currency_code,
421              l_exclusive_payment_flag,
422              l_interest_ap_ccid,
423              l_org_id;
424 
425     EXIT WHEN interest_cursor%NOTFOUND or interest_cursor%NOTFOUND is NULL;
426 
427 
428 
429     SELECT nvl(payment_amount,0), nvl(amount_remaining,0),
430            nvl(discount_amount,0),nvl(discount_amount_remaining,0)
431     INTO   l_payment_amount, l_amount_remaining,
432            l_discount_taken, l_discount_available
433     FROM   ap_selected_invoices_all asi
434     WHERE  asi.invoice_id = l_invoice_id
435     AND    asi.payment_num = l_payment_num
436     and    asi.checkrun_id = p_checkrun_id;
437 
438 
439 
440     l_debug_info := 'Calling ap_interest_invoice_pkg';
441     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
442       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
443     END IF;
444 
445 
446 
447     ap_interest_invoice_pkg.ap_calculate_interest(
448          P_INVOICE_ID                    =>l_invoice_id,
449          P_SYS_AUTO_CALC_INT_FLAG        =>'Y',  --should always be "Y" b/c of cursor where clause
450          P_AUTO_CALCULATE_INTEREST_FLAG  =>'Y',  --should always be "Y" b/c of cursor where clause
451          P_CHECK_DATE                    =>P_check_date,
452          P_PAYMENT_NUM                   =>l_payment_num,
453          P_AMOUNT_REMAINING              =>l_amount_remaining,
454          P_DISCOUNT_TAKEN                =>l_discount_taken,
455          P_DISCOUNT_AVAILABLE            =>l_discount_available,
456          P_CURRENCY_CODE                 =>l_pay_currency_code,
457          P_INTEREST_AMOUNT               =>l_int_invoice_amt,
458          P_DUE_DATE                      =>l_due_date,
459          P_INTEREST_INVOICE_NUM          =>l_int_invoice_no,
460          P_PAYMENT_AMOUNT                =>l_payment_amount,
461          P_CALLING_SEQUENCE              =>l_current_calling_sequence);
462 
463     l_debug_info := 'interest invoice amount = '||to_char(l_int_invoice_amt);
464     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
465       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
466     END IF;
467 
468 
469     IF (l_int_invoice_amt <> 0) THEN
470 
471       SELECT count(*)
472       INTO   l_existing_interest_count
473       FROM   ap_invoice_relationships
474       WHERE  original_invoice_id = l_invoice_id;
475 
476 
477       SELECT count(*)
478       INTO   l_proposed_interest_count
479       FROM   ap_selected_invoices
480       WHERE  original_invoice_id = to_char(l_invoice_id); --4388916
481 
482 
483       l_inv_curr_int_amt := ap_utilities_pkg.ap_round_currency(
484                                l_int_invoice_amt / l_payment_cross_rate,
485                                l_invoice_currency_code);
486 
487       INSERT INTO ap_selected_invoices_all
488            (checkrun_name,
489             invoice_id,
490             vendor_id,
491             vendor_site_id,
492             vendor_num,
493             vendor_name,
494             vendor_site_code,
495             address_line1,
496             address_line2,
497             address_line3,
498             address_line4,
499             city,
500             state,
501             zip,
502             invoice_num,
503             voucher_num,
504             ap_ccid,
505             payment_priority,
506             province,
507             country,
508             withholding_status_lookup_code,
509             attention_ar_flag,
510             set_of_books_id,
511             invoice_exchange_rate,
512             payment_cross_rate,
513             customer_num,
514             payment_num,
515             last_update_date,
516             last_updated_by,
517             invoice_date,
518             invoice_amount,
519             amount_remaining,
520             amount_paid,
521             discount_amount_taken,
522             due_date,
523             invoice_description,
524             discount_amount_remaining,
525             payment_amount,
526             proposed_payment_amount,
527             discount_amount,
528             ok_to_pay_flag,
529             always_take_discount_flag,
530             amount_modified_flag,
531             original_invoice_id,
532             original_payment_num,
533             creation_date,
534             created_by,
535             exclusive_payment_flag,
536             org_id,
537             external_bank_account_id,
538             checkrun_id,
539             payment_currency_code,
540             affects_rejection_level)
541       SELECT
542             P_checkrun_name,
543             ap_invoices_s.NEXTVAL,
544             l_vendor_id,
545             l_site_id,
546             l_int_vendor_num,
547             l_int_vendor_name,
548             l_site_code,
549             l_address_line1,
550             l_address_line2,
551             l_address_line3,
552             l_address_line4,
553             l_city,
554             l_state,
555             l_zip,
556             SUBSTRB(SUBSTRB(l_int_invoice_num,
557                      1,(50 - LENGTHB('-' || l_nls_int ||
558                                      TO_CHAR(l_existing_interest_count +
559                                              l_proposed_interest_count + 1))))
560              || '-' || l_nls_int || TO_CHAR(l_existing_interest_count +
561                                             l_proposed_interest_count + 1),1,50),
562             l_voucher_num,
563             l_interest_ap_ccid,
564             l_payment_priority,
565             l_province,
566             l_country,
567             l_awt_status_lookup_code,
568             l_attention_ar_flag,
569             l_set_of_books_id,
570             l_invoice_exchange_rate,
571             l_payment_cross_rate,
572             l_customer_num,
573             1,
574             SYSDATE,
575             -- Bug 7383484 (Base bug 7296715)
576             -- The User Id is hardcoded to 5 (APPSMGR). It is changed to populate correct value.
577             -- '5',
578             FND_GLOBAL.USER_ID,
579             p_check_date,
580             l_inv_curr_int_amt,
581             l_int_invoice_amt,
582             0,
583             0,
584             p_check_date,
585             SUBSTRB(l_nls_interest|| ' ' || to_char(l_int_invoice_days)
586                     || ' ' || l_nls_days || to_char(l_int_invoice_rate)
587                     || l_nls_percent,1,50),
588             0,
589             l_int_invoice_amt,
590             l_int_invoice_amt,
591             0,
592             l_ok_to_pay_flag,
593             'N',
594             'N',
595             l_invoice_id,
596             l_payment_num,
597             SYSDATE,
598             -- Bug 7383484 (Base bug 7296715)
599             --'5',
600             FND_GLOBAL.USER_ID,
601             l_exclusive_payment_flag,
602             l_org_id,
603             l_external_bank_account_id,
604             p_checkrun_id,
605             l_pay_currency_code,
606             'N'
607             --bug12349626
608       FROM sys.dual;
609 
610     END IF;
611 
612   END LOOP;
613 
614   CLOSE interest_cursor;
615 
616 exception
617     WHEN OTHERS then
618 
619     IF (SQLCODE <> -20001) THEN
620       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
621       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
622       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
623       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
624       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_checkrun_id: '||
625                                            to_char(p_checkrun_id));
626 
627     END IF;
628     APP_EXCEPTION.RAISE_EXCEPTION;
629 
630 END;
631 
632 
633 
634 
635 
636 PROCEDURE remove_all_invoices (p_checkrun_id in number,
637                                p_calling_sequence in varchar2) IS
638 l_debug_info varchar2(2000);
639 l_current_calling_sequence varchar2(2000);
640 
641 begin
642 
643   l_current_calling_sequence := p_calling_sequence || '<- remove_all_invoices';
644   l_debug_info := 'delete unselected invoices';
645 
646   delete from ap_unselected_invoices_all
647   where checkrun_id = p_checkrun_id;
648 
649 
650   l_debug_info := 'deleted selected invoices';
651 
652   delete from ap_selected_invoices_all
653   where checkrun_id = p_checkrun_id;
654 
655 
656   l_debug_info := 'update payment schedules';
657 
658   update ap_payment_schedules_all
659   set checkrun_id = null
660   where checkrun_id = p_checkrun_id;
661 
662 
663 exception
664     WHEN OTHERS then
665 
666     IF (SQLCODE <> -20001) THEN
667       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
668       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
669       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
670       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
671       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_checkrun_id: '||
672                                            to_char(p_checkrun_id));
673 
674     END IF;
675     APP_EXCEPTION.RAISE_EXCEPTION;
676 end;
677 
678 
679 
680 
681 
682 
683 
684 PROCEDURE remove_invoices (p_checkrun_id in number,
685                            p_calling_sequence in varchar2) IS
686 
687 cursor c_dont_pay_invoices (p_checkrun_id number) is
688 --make sure we seed dont pay reason codes
689   select invoice_id, payment_num, dont_pay_reason_code, org_id
690   from ap_selected_invoices_all
691   where checkrun_id = p_checkrun_id
692   and ok_to_pay_flag = 'N';
693 
694 l_debug_info varchar2(2000);
695 l_current_calling_sequence varchar2(2000);
696 TYPE r_remove_invoices IS RECORD (invoice_id number(15),
697                                   payment_num number(15),
698                                   dont_pay_reason_code varchar2(25),
699                                   org_id number(15));
700 
701 type t_remove_invoices is table of r_remove_invoices index by binary_integer;
702 l_remove_invoices t_remove_invoices;
703 
704 
705 begin
706 
707 
708 
709   l_current_calling_sequence := p_calling_sequence || '<-remove invoices';
710 
711 
712   l_debug_info := 'Start of remove_invoices';
713   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
714     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
715   END IF;
716 
717 
718 
719   OPEN  c_dont_pay_invoices(p_checkrun_id);
720   FETCH c_dont_pay_invoices BULK COLLECT INTO l_remove_invoices;
721   CLOSE c_dont_pay_invoices;
722 
723 
724 
725 
726   if l_remove_invoices.count > 0 then
727     for i in l_remove_invoices.first .. l_remove_invoices.last loop
728 
729       insert into ap_unselected_invoices_all(
730         checkrun_id,
731         invoice_id,
732         payment_num,
733         dont_pay_reason_code,
734         last_update_date,
735         last_updated_by,
736         created_by,
737         creation_date,
738         org_id)
739       values(
740         p_checkrun_id,
741         l_remove_invoices(i).invoice_id,
742         l_remove_invoices(i).payment_num ,
743         l_remove_invoices(i).dont_pay_reason_code,
744         sysdate,
745         5,
746         5,
747         sysdate,
748         l_remove_invoices(i).org_id);
749 
750 
751 
752       update ap_payment_schedules_all
753       set checkrun_id = null
754       where invoice_id = l_remove_invoices(i).invoice_id
755       and payment_num = l_remove_invoices(i).payment_num
756       and checkrun_id = p_checkrun_id;
757 
758       delete from ap_selected_invoices_all
759       where invoice_id = l_remove_invoices(i).invoice_id
760       and payment_num = l_remove_invoices(i).payment_num
761       and checkrun_id = p_checkrun_id;
762 
763     end loop;
764   end if;
765 exception
766     WHEN OTHERS then
767 
768     IF (SQLCODE <> -20001) THEN
769       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
770       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
771       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
772       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
773       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_checkrun_id: '||
774                                            to_char(p_checkrun_id));
775 
776     END IF;
777     APP_EXCEPTION.RAISE_EXCEPTION;
778 end;
779 
780 
781 
782 
783 -- Bug 12798965.
784 -- Added following 4 additional parameters.
785 -- p_pay_thru_date_char
786 -- p_pay_from_date_char
787 -- p_check_date_char
788 -- p_disc_pay_thru_char
789 
790 
791 PROCEDURE insert_unselected(p_payment_process_request_name   in      VARCHAR2,
792                             p_hi_payment_priority            in      number,
793                             p_low_payment_priority           in      number,
794                             p_invoice_batch_id               in      number,
795                             p_inv_vendor_id                  in      number,
796                             p_inv_exchange_rate_type         in      varchar2,
797                             p_payment_method                 in      varchar2,
798                             p_supplier_type                  in      varchar2,
799                             p_le_group_option                in      varchar2,
800                             p_ou_group_option                in      varchar2,
801                             p_currency_group_option          in      varchar2,
802                             p_pay_group_option               in      varchar2,
803                             p_zero_invoices_allowed          in      varchar2,
804                             p_check_date                     in      date,
805                             p_checkrun_id                    in      number,
806                             p_current_calling_sequence       in      varchar2,
807                             p_party_id                       in      number,
808  	                    p_pay_thru_date_char             in      varchar2,
809  	                    p_pay_from_date_char             in      varchar2,
810  	                    p_check_date_char                in      varchar2,
811  	                    p_disc_pay_thru_char             in      varchar2
812                             ) IS
813 
814 
815 l_invoice_id number;
816 l_payment_num number;
817 l_invoice_status varchar2(50);
818 l_approval_status   varchar2(50);
819 l_ps_hold_flag varchar2(1);
820 l_hold_all_payments_flag varchar2(1);
821 l_current_calling_sequence varchar2(2000);
822 l_debug_info varchar2(2000);
823 l_org_id number(15);
824 l_due_date date;
825 l_discount_amount_available number;
826 l_discount_date date;
827 
828  -- DYNAMIC SQL (bug8637005)
829 l_hint                     VARCHAR2(100);
830 l_sql_stmt                 LONG;
831 TYPE refcurtyp     IS      REF CURSOR;
832 refcur                     REFCURTYP;
833 
834 
835 
836 
837 BEGIN
838 
839 
840   l_current_calling_sequence := p_current_calling_sequence||'<- insert unselected';
841 
842   l_debug_info := 'open unselected_invoices';
843   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
844     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
845   END IF;
846 
847     -- Setting the hint string, bug8637005
848   /* Commented for bug#12773508 Start
849   IF p_pay_group_option <> 'ALL' THEN
850      l_hint := ' / *+ index(ai AP_INVOICES_N3) * / ';
851   ELSE
852      l_hint := ' ';
853   END IF;
854   Commented for bug#12773508 End */
855 
856   /**************************************************************************/
857   /* Bug8637005                                                             */
858   /* -----------                                                            */
859   /* The query for unselected invoices has been made dynamic for            */
860   /* performance improvements, using native dynamic sqls and ref            */
861   /* cursors.                                                               */
862   /*                                                                        */
863   /* Since use of native sql requires a knowledge of the using              */
864   /* clause and hence the number of binds before hand, please make          */
865   /* sure that any modifications to the sql string, ensures that            */
866   /* the number of binds remain constant for all cases of input             */
867   /* parameters (selection criteria)                                        */
868   /*                                                                        */
869   /* Currently this has been achieved using:                                */
870   /*    nvl(bind, -9999) = -9999                                            */
871   /*                                                                        */
872   /* If for some reason it is not feasible to achieve a constant number     */
873   /* for a later change please connsider                                    */
874   /*   a. Eliminating binds, by joing to ap_invoice_selection_criteria_all  */
875   /*   b. Using DBMS_SQL                                                    */
876   /**************************************************************************/
877 
878 
879 
880   l_sql_stmt :=
881         '       SELECT  '||l_hint||' '||
882         '              ai.invoice_id, '||
883         '              ps.payment_num, '||
884         '              ps.hold_flag, '||
885         '              sites.hold_all_payments_flag, '||
886         '              ap_utilities_pkg.get_invoice_status(ai.invoice_id, null), '||
887         '              ai.wfapproval_status, '||
888         '              ai.org_id, '||
889         '              ps.due_date, '||
890         '              ps.discount_amount_available, '||
891         '              ps.discount_date '||
892         '       FROM   ap_supplier_sites_all sites, '||
893         '              ap_invoices ai,  '||       /* inv,  '|| Commented for bug#9182499 GSCC Error File.Sql.6 Bug6040657. Changed from ap_invoices_all to ap_invoices */
894         '              ap_payment_schedules ps, '||
895         '              ap_suppliers suppliers, '||
896         '              hz_parties hz '||
897         '       where  ai.invoice_id = ps.invoice_id '||
898         '       AND    sites.vendor_site_id(+) = ai.vendor_site_id '||
899         '       AND    suppliers.vendor_id(+) = ai.vendor_id '||
900         '       AND    ai.party_id = hz.party_id '||
901         /* '       AND    ps.payment_status_flag BETWEEN ''N'' AND ''P'' '||
902            '       AND    ai.payment_status_flag BETWEEN ''N'' AND ''P'' '|| Commented for bug#11848050 */
903         '       AND    ps.payment_status_flag IN (''N'', ''P'') '|| /* Added for bug#11848050 */
904         '       AND    ai.payment_status_flag IN (''N'', ''P'') '|| /* Added for bug#11848050 */
905         '       AND    NVL(ps.payment_priority, 99) BETWEEN :p_hi_payment_priority '||
906         '                                              AND :p_low_payment_priority '||
907         '       AND    ai.cancelled_date is null ';
908                 -- Bug 5649608
909                 --AND    nvl(inv.batch_id,-99) = nvl(p_invoice_batch_id,-99)
910 
911   IF p_invoice_batch_id IS NOT NULL THEN
912      l_sql_stmt := l_sql_stmt||'              AND  ai.batch_id = :p_inv_batch_id ';
913   ELSE
914      l_sql_stmt := l_sql_stmt||'              AND  nvl(:p_inv_batch_id, -9999) = -9999 ';
915   END IF;
916 
917   IF p_inv_vendor_id IS NOT NULL THEN
918      l_sql_stmt := l_sql_stmt||'       AND    ai.vendor_id = :p_inv_vendor_id  ';
919   ELSE
920      l_sql_stmt := l_sql_stmt||'       AND    nvl(:p_inv_vendor_id, -9999) = -9999 ';
921   END IF;
922 
923   IF p_party_id IS NOT NULL THEN
924      l_sql_stmt := l_sql_stmt||'       AND    ai.party_id = :p_party_id ';
925   ELSE
926      l_sql_stmt := l_sql_stmt||'       AND    nvl(:p_party_id, -9999) = -9999 ';
927   END IF;
928 
929                 -- Bug 5507013 hkaniven start --
930   l_sql_stmt := l_sql_stmt||
931         '       AND    (( :p_inv_exchange_rate_type = ''IS_USER'' AND NVL(ai.exchange_rate_type,''NOT USER'') = ''User'' ) '||
932         '               OR (:p_inv_exchange_rate_type = ''IS_NOT_USER'' AND NVL(ai.exchange_rate_type,''NOT USER'') <> ''User'') '||
933         '               OR (:p_inv_exchange_rate_type IS NULL)) '
934                 -- Bug 5507013 hkaniven end --
935         /* '       AND    ps.payment_method_code = nvl(:p_payment_method, ps.payment_method_code) '||
936            '       AND    nvl(suppliers.vendor_type_lookup_code,-99) = '||
937            '                   nvl(:p_supplier_type, nvl(suppliers.vendor_type_lookup_code,-99)) '||
938         '       AND    (ai.legal_entity_id in (select /*+ push_subq * / legal_entity_id '||
939         '                                       from   ap_le_group '||
940         '                                       where  checkrun_id = :p_checkrun_id) '||
941         '               or :p_le_group_option = ''ALL'') '||
942         '       AND    (ai.org_id in (select /*+ push_subq * / org_id '||
943         '                              from   AP_OU_GROUP '||
944         '                              where  checkrun_id = :p_checkrun_id) '||
945         '               or :p_ou_group_option = ''ALL'') '||
946         '       AND    (ai.payment_currency_code in (select /*+ push_subq * / currency_code '||
947         '                                             from   AP_CURRENCY_GROUP '||
948         '                                             where  checkrun_id = :p_checkrun_id) '||
949         '               or :p_currency_group_option = ''ALL'') 'Commented for Bug#11848050 */  ;
950 
951   /* Code Added for bug#11848050 Start */
952   IF p_payment_method IS NOT NULL THEN
953      l_sql_stmt := l_sql_stmt || '    AND ps.payment_method_code = :p_payment_method ';
954   ELSE
955      l_sql_stmt := l_sql_stmt || '    AND nvl(:p_payment_method, -9999) = -9999';
956   END IF;
957 
958   IF p_supplier_type IS NOT NULL THEN
959      l_sql_stmt := l_sql_stmt || '    AND suppliers.vendor_type_lookup_code = :p_supplier_type ';
960   ELSE
961      l_sql_stmt := l_sql_stmt || '    AND nvl(:p_supplier_type, -9999) = -9999';
962   END IF;
963   /* Code Added for bug#11848050 End */
964 
965   IF p_pay_group_option <> 'ALL' THEN
966      l_sql_stmt := l_sql_stmt||
967          /* Commented for Bug#9182499 Start
968          '       AND    inv.pay_group_lookup_code in (select / *+ leading(apg) cardinality(apg 1) * / vendor_pay_group '||
969          '                                            from   AP_PAY_GROUP apg'||     --bug9087739, added alias for  AP_PAY_GROUP
970          '                                            where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id) ';
971          Commented for Bug#9182499 End */
972          /* Added for Bug#9182499 Start */
973          '       AND (ai.pay_group_lookup_code, ai.org_id) in '||
974          '                       ( select  '|| /* Added for bug#12773508 */
975          /* '                       ( select / *+ leading(apg) cardinality(apg 1) * / '|| Commented for bug#12773508 */
976          '                                apg.vendor_pay_group, mo.ORGANIZATION_ID '||
977          '                           from AP_PAY_GROUP apg, MO_GLOB_ORG_ACCESS_TMP mo '||
978          '                          where checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id '||
979          '                            AND ai.org_id = mo.organization_id) '; /* Added for bug#11848050 */
980          /* Added for Bug#9182499 End */
981 
982   ELSE
983      l_sql_stmt := l_sql_stmt||
984          '       AND    :p_checkrun_id = :p_checkrun_id   ';
985   END IF;
986 
987   /* Added for bug#11848050 Start */
988   IF p_le_group_option <> 'ALL' THEN
989      l_sql_stmt := l_sql_stmt||
990          '       AND  ai.legal_entity_id in '||
991          '               (select /*+ push_subq */ legal_entity_id '||
992          '                  from   ap_le_group                    '||
993          '                 where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id)   ';
994   ELSE
995      l_sql_stmt := l_sql_stmt||
996          '       AND    :p_checkrun_id = :p_checkrun_id   ';
997   END IF;
998 
999   IF p_ou_group_option <> 'ALL' THEN
1000      l_sql_stmt := l_sql_stmt||
1001          '       AND  ai.org_id in '||
1002          '               (select /*+ push_subq */ org_id '||
1003          '                  from   AP_OU_GROUP                    '||
1004          '                 where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id)   ';
1005   ELSE
1006      l_sql_stmt := l_sql_stmt||
1007          '       AND    :p_checkrun_id = :p_checkrun_id   ';
1008   END IF;
1009 
1010   IF p_currency_group_option <> 'ALL' THEN
1011      l_sql_stmt := l_sql_stmt||
1012          '       AND  ai.payment_currency_code in '||
1013          '               (select /*+ push_subq */ currency_code '||
1014          '                  from   AP_CURRENCY_GROUP                    '||
1015          '                 where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id)   ';
1016   ELSE
1017      l_sql_stmt := l_sql_stmt||
1018          '       AND    :p_checkrun_id = :p_checkrun_id   ';
1019   END IF;
1020   /* Added for bug#11848050 End */
1021 
1022   l_sql_stmt := l_sql_stmt||
1023         '       AND    ((:p_zero_invoices_allowed = ''N'' AND ps.amount_remaining <> 0) OR '||
1024         '                :p_zero_invoices_allowed = ''Y'') '||
1025         '       and     ps.checkrun_id is null ';
1026 
1027   -- Bug 12798965. Added due date condition.
1028 
1029   l_sql_stmt := l_sql_stmt||
1030       '       AND ((due_date <= to_date(:p_pay_thru_date, ''DD-MM-YYYY'') +0/24 and  '|| --Bug 8708165
1031       '               due_date >= nvl(to_date(:p_pay_from_date, ''DD-MM-YYYY'') + 0/24,due_date)) '||
1032       '              OR '||
1033       '               DECODE(NVL(sites.pay_date_basis_lookup_code,''DISCOUNT''), '||
1034       '                    ''DISCOUNT'', '||
1035       '                    DECODE(sites.always_take_disc_flag, '||
1036       '                           ''Y'', ps.discount_date, '||
1037       '                           DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
1038       '                                  -NVL(ps.discount_date, '||
1039       '                                       to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
1040       '                                  -1, ps.discount_date, '||
1041       '                                  DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
1042       '                                              -NVL(ps.second_discount_date, '||
1043       '                                                   to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
1044       '                                         -1, ps.second_discount_date, '||
1045       '                                         DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
1046       '                                                     -NVL(ps.third_discount_date, '||
1047       '                                                         to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
1048       '                                                -1, ps.third_discount_date, '||
1049       '                                                TRUNC(ps.due_date))))), '||
1050       '                    TRUNC(due_date)) '||
1051       '                    BETWEEN DECODE(sites.always_take_disc_flag,''Y'', '||
1052       '                                    nvl(to_date(:p_pay_from_date, ''DD-MM-YYYY''), TO_DATE(''1901'',''YYYY'')), '||
1053       '                                    to_date(:p_check_date, ''DD-MM-YYYY'') ) '||
1054       '                            AND to_date(:p_disc_pay_thru_date, ''DD-MM-YYYY'') ) ';
1055 
1056   -- Bug 12798965.
1057   -- Added following new parameters.
1058   -- p_pay_thru_date_char
1059   -- p_pay_from_date_char
1060   -- p_check_date_char
1061   -- p_disc_pay_thru_char
1062 
1063   OPEN refcur FOR l_sql_stmt USING p_hi_payment_priority,
1064                                    p_low_payment_priority,
1065                                    p_invoice_batch_id,
1066                                    p_inv_vendor_id,
1067                                    p_party_id,
1068                                    p_inv_exchange_rate_type,
1069                                    p_inv_exchange_rate_type,
1070                                    p_inv_exchange_rate_type,
1071                                    p_payment_method, /* Modified the sequence */
1072                                    p_supplier_type,  /* Modified the sequence */
1073                                    p_checkrun_id,
1074                                    p_checkrun_id,
1075                                    p_checkrun_id,
1076                                    p_checkrun_id,
1077                                    p_checkrun_id,
1078                                    p_checkrun_id,
1079                                    p_checkrun_id,
1080                                    p_checkrun_id,
1081                                    p_zero_invoices_allowed,
1082                                    p_zero_invoices_allowed,
1083  	                           p_pay_thru_date_char,
1084  	                           p_pay_from_date_char,
1085  	                           p_check_date_char,
1086  	                           p_check_date_char,
1087  	                           p_check_date_char,
1088  	                           p_check_date_char,
1089  	                           p_check_date_char,
1090  	                           p_check_date_char,
1091  	                           p_pay_from_date_char,
1092  	                           p_check_date_char,
1093  	                           p_disc_pay_thru_char;
1094   loop
1095     fetch refcur into l_invoice_id,
1096                                    l_payment_num,
1097                                    l_ps_hold_flag,
1098                                    l_hold_all_payments_flag,
1099                                    l_invoice_status,
1100                                    l_approval_status,
1101                                    l_org_id,
1102                                    l_due_date,
1103                                    l_discount_amount_available,
1104                                    l_discount_date;
1105 
1106 
1107     exit when refcur%notfound;
1108 
1109 
1110     --Needs Invoice Validation
1111     if l_invoice_status in ('NEVER APPROVED', 'UNAPPROVED')  then
1112 
1113       insert into ap_unselected_invoices_all(
1114         checkrun_id,
1115         invoice_id,
1116         payment_num,
1117         dont_pay_reason_code,
1118         last_update_date,
1119         last_updated_by,
1120         created_by,
1121         creation_date,
1122         org_id)
1123       values(
1124         p_checkrun_id,
1125         l_invoice_id,
1126         l_payment_num ,
1127         'NEEDS_INVOICE_VALIDATION',
1128         sysdate,
1129         5,
1130         5,
1131         sysdate,
1132         l_org_id);
1133 
1134     end if;
1135 
1136 
1137     --Failed Invoice Validation
1138     if l_invoice_status = 'NEEDS REAPPROVAL' then
1139 
1140       insert into ap_unselected_invoices(
1141         checkrun_id,
1142         invoice_id,
1143         payment_num,
1144         dont_pay_reason_code,
1145         last_update_date,
1146         last_updated_by,
1147         created_by,
1148         creation_date,
1149         org_id)
1150       values(
1151         p_checkrun_id,
1152         l_invoice_id,
1153         l_payment_num ,
1154         'FAILED_INVOICE_VALIDATION',
1155         sysdate,
1156         5,
1157         5,
1158         sysdate,
1159         l_org_id);
1160 
1161     end if;
1162 
1163 
1164     --Needs Approval
1165     if l_approval_status in ('INITIATED','REQUIRED','NEEDS WFREAPPROVAL') then
1166 
1167 
1168       insert into ap_unselected_invoices(
1169         checkrun_id,
1170         invoice_id,
1171         payment_num,
1172         dont_pay_reason_code,
1173         last_update_date,
1174         last_updated_by,
1175         created_by,
1176         creation_date,
1177         org_id)
1178       values(
1179         p_checkrun_id,
1180         l_invoice_id,
1181         l_payment_num ,
1182         'NEEDS_APPROVAL',
1183         sysdate,
1184         5,
1185         5,
1186         sysdate,
1187         l_org_id);
1188 
1189     end if;
1190 
1191 
1192 
1193 
1194     --Approver Rejected
1195     if l_approval_status = 'REJECTED' then
1196 
1197       insert into ap_unselected_invoices(
1198         checkrun_id,
1199         invoice_id,
1200         payment_num,
1201         dont_pay_reason_code,
1202         last_update_date,
1203         last_updated_by,
1204         created_by,
1205         creation_date,
1206         org_id)
1207       values(
1208         p_checkrun_id,
1209         l_invoice_id,
1210         l_payment_num ,
1211         'APPROVER_REJECTED',
1212         sysdate,
1213         5,
1214         5,
1215         sysdate,
1216         l_org_id);
1217     end if;
1218 
1219     --Scheduled Payment Hold
1220     if l_ps_hold_flag = 'Y' then
1221 
1222       insert into ap_unselected_invoices(
1223         checkrun_id,
1224         invoice_id,
1225         payment_num,
1226         dont_pay_reason_code,
1227         last_update_date,
1228         last_updated_by,
1229         created_by,
1230         creation_date,
1231         org_id)
1232       values(
1233         p_checkrun_id,
1234         l_invoice_id,
1235         l_payment_num ,
1236         'SCHEDULED_PAYMENT_HOLD',
1237         sysdate,
1238         5,
1239         5,
1240         sysdate,
1241         l_org_id);
1242     end if;
1243 
1244 
1245 
1246     --Supplier Site Hold
1247     if l_hold_all_payments_flag = 'Y' then
1248 
1249       insert into ap_unselected_invoices(
1250         checkrun_id,
1251         invoice_id,
1252         payment_num,
1253         dont_pay_reason_code,
1254         last_update_date,
1255         last_updated_by,
1256         created_by,
1257         creation_date,
1258         org_id)
1259       values(
1260         p_checkrun_id,
1261         l_invoice_id,
1262         l_payment_num ,
1263         'SUPPLIER_SITE_HOLD',
1264         sysdate,
1265         5,
1266         5,
1267         sysdate,
1268         l_org_id);
1269     end if;
1270 
1271 
1272     --Discount Rate Too Low
1273       --4745133, can't call the ebd check in the cursor so doing it here.
1274       insert into ap_unselected_invoices(
1275         checkrun_id,
1276         invoice_id,
1277         payment_num,
1278         dont_pay_reason_code,
1279         last_update_date,
1280         last_updated_by,
1281         created_by,
1282         creation_date,
1283         org_id)
1284       select
1285         p_checkrun_id,
1286         l_invoice_id,
1287         l_payment_num ,
1288         'DISCOUNT_RATE_TOO_LOW',
1289         sysdate,
1290         5,
1291         5,
1292         sysdate,
1293         l_org_id
1294       from dual
1295        where fv_econ_benf_disc.ebd_check(p_payment_process_request_name, l_invoice_id,
1296                                          p_check_date, l_due_date, l_discount_amount_available, l_discount_date) = 'N';
1297 
1298 
1299   end loop;
1300 
1301   close refcur;
1302 
1303 
1304 
1305 EXCEPTION
1306   WHEN OTHERS THEN
1307 
1308     IF (SQLCODE <> -20001) THEN
1309       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
1310       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
1311       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
1312       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
1313       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_payment_process_request_name: '||
1314                                            p_payment_process_request_name);
1315 
1316 
1317     END IF;
1318     APP_EXCEPTION.RAISE_EXCEPTION;
1319 
1320 END INSERT_UNSELECTED;
1321 
1322 
1323 
1324 --this procedure groups invoices AP wants to ensure get paid together.
1325 --it follows the grouping logic Oracle Payments currently has
1326 
1327 PROCEDURE group_interest_credits (p_checkrun_id                    IN      VARCHAR2,
1328                                   p_current_calling_sequence       IN      VARCHAR2
1329                                   ) IS
1330 
1331 
1332 
1333 cursor c_documents (p_checkrun_id number) is
1334 	select nvl(asi.exclusive_payment_flag,'N')exclusive_payment_flag,
1335 		   asi.org_id,
1336 		   asi.payment_amount,
1337 		   asi.vendor_site_id,
1338 		   ai.party_id,
1339 		   ai.party_site_id,
1340 		   asi.payment_currency_code,
1341 		   aps.payment_method_code,
1342 		   nvl(aps.external_bank_account_id,-99) external_bank_account_id,
1343 		   -- As per the discussion with Omar/Jayanta, we will only
1344 		   -- have payables payment function and no more employee expenses
1345 		   -- payment function.
1346 		   nvl(ai.payment_function, 'PAYABLES_DISB') payment_function,
1347 		   nvl(ai.pay_proc_trxn_type_code, decode(ai.invoice_type_lookup_code,'EXPENSE REPORT',
1348 											   'EMPLOYEE_EXP','PAYABLES_DOC')) pay_proc_trxn_type_code,
1349 		   asi.invoice_id,
1350 		   asi.payment_num,
1351 		   asi.payment_grouping_number,
1352 		   NVL(asi.ok_to_pay_flag,'Y') ok_to_pay_flag,
1353 		   asi.proposed_payment_amount,
1354 		   fv.beneficiary_party_id,  --5017076
1355 		   ipm.support_bills_payable_flag,   -- Bug 5357689, 5479979
1356 		   (trunc(aps.due_date) + nvl(ipm.maturity_date_offset_days,0)) due_date -- Bug 5357689
1357 									  --Bug 543942 added NVL in the above scenario
1358 	from   ap_selected_invoices_all asi,
1359 		   ap_invoices ai, --Bug6040657. Changed from ap_invoices_all to ap_invoices
1360 		   ap_inv_selection_criteria_all aisc,
1361 		   ap_payment_schedules_all aps,
1362 		   fv_tpp_assignments_v fv, --5017076
1363 		   iby_payment_methods_vl ipm -- Bug 5357689
1364 	where  asi.invoice_id = ai.invoice_id
1365 	and    aps.invoice_id = asi.invoice_id
1366 	and    aps.payment_num = asi.payment_num
1367 	and    asi.checkrun_name = aisc.checkrun_name
1368 	and    nvl(asi.ok_to_pay_flag,'Y') = 'Y'
1369 	and    aisc.checkrun_id= p_checkrun_id
1370 	and    asi.original_invoice_id is null
1371 	and    fv.beneficiary_supplier_id(+) = ai.vendor_id
1372 	and    fv.beneficiary_supplier_site_id(+) = ai.vendor_site_id
1373 	and    ipm.payment_method_code = aps.payment_method_code -- Bug 5357689
1374 	order by nvl(asi.exclusive_payment_flag,'N'),  --bug8440703
1375 		   asi.org_id,
1376 		   asi.vendor_site_id,
1377 		   ai.party_id,
1378 		   ai.party_site_id,
1379 		   asi.payment_currency_code,
1380 		   aps.payment_method_code,
1381 		   aps.external_bank_account_id,
1382 		   payment_function,
1383 		   /* pay_proc_trxn_type_code, Bug 13442182 */
1384 		   fv.beneficiary_party_id,
1385 		   SIGN(asi.invoice_amount) asc,  --this will make credit memos first(Bug 16340312) per group
1386 		   asi.due_date,   -- Bug 5479979, Bug 12740398, Bug 16340312
1387 			 /*  DECODE(SIGN(asi.invoice_amount),
1388 					-1, TO_CHAR(asi.due_date,'YYYYMMDD'),
1389 					asi.invoice_num), */
1390 		   asi.payment_num;
1391 
1392 
1393 TYPE r_documents IS RECORD (exclusive_payment_flag varchar2(1),
1394                             org_id number(15),
1395                             payment_amount number,
1396                             vendor_site_id number(15),
1397                             party_id number(15),
1398                             party_site_id number(15),
1399                             payment_currency_code varchar2(15),
1400                             payment_method varchar2(30),
1401                             external_bank_account_id number(15),
1402                             payment_function varchar2(30),
1403                             pay_proc_trxn_type_code varchar2(30),
1404                             invoice_id number(15),
1405                             payment_num number(15),
1406                             payment_grouping_number number(15),
1407                             ok_to_pay_flag varchar2(1),
1408                             proposed_payment_amount number,
1409                             beneficiary_party_id number,  --5017076
1410                             support_bills_payable_flag varchar2(1),  -- Bug 5357689
1411                             due_date date);  -- Bug 5357689
1412 
1413 type t_documents is table of r_documents index by binary_integer;
1414 l_documents t_documents;
1415 
1416 
1417 l_prev_exclusive_payment_flag varchar2(1);
1418 l_prev_org_id number(15);
1419 l_prev_payment_amount number;
1420 l_prev_vendor_site_id number(15);
1421 l_prev_party_id number(15);
1422 l_prev_party_site_id number(15);
1423 l_prev_payment_currency_code varchar2(15);
1424 l_prev_payment_method varchar2(30);
1425 l_prev_ext_bank_acct_id number(15);
1426 l_prev_payment_function varchar2(30);
1427 l_prev_pay_proc_trxn_type_code varchar2(30);
1428 l_prev_grouping_number number;
1429 l_prev_beneficiary_party_id number;
1430 l_prev_bills_payable_flag varchar2(1);  -- Bug 5357689
1431 l_prev_due_date date;                   -- Bug 5357689
1432 
1433 l_grouping_number number;
1434 l_payment_sum number := 0;
1435 l_remove_cm_flag varchar2(1);
1436 l_current_calling_sequence varchar2(2000);
1437 l_debug_info varchar2(2000);
1438 
1439 l_maximize_credits_flag varchar2(1); --5007819
1440 l_payment_profile_id number; -- Added for bug 9089243
1441 l_group_by_due_date_flag varchar2(1); -- Added for bug 9089243
1442 l_tmp_cm_total NUMBER :=0; --Added for Bug 16340312
1443 l_tmp_pmt_count NUMBER := 0; --Added for Bug 16340312
1444 l_max_index     NUMBER := 0; --Added for Bug 16340312
1445 l_init_cm_appl_date DATE := null; --Added for Bug 16340312
1446 l_cm_set_off_flag VARCHAR2(1) := 'Y'; --Added for Bug 16340312
1447 
1448 BEGIN
1449   l_current_calling_sequence := p_current_calling_sequence||'<-group interest credits';
1450   l_debug_info := 'open c_documents';
1451   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
1452     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
1453   END IF;
1454 
1455   OPEN  c_documents(p_checkrun_id);
1456   FETCH c_documents BULK COLLECT INTO l_documents;
1457   CLOSE c_documents;
1458 
1459   if l_documents.count = 0 then
1460     return;
1461   end if;
1462 
1463   l_grouping_number := 1;
1464   l_remove_cm_flag := 'N';
1465 
1466   --5007819
1467   select nvl(zero_amounts_allowed,'N'), payment_profile_id
1468   into l_maximize_credits_flag, l_payment_profile_id -- Added for bug 9089243
1469   from ap_inv_selection_criteria_all
1470   where checkrun_id = p_checkrun_id;
1471 
1472   -- Added for bug 9089243
1473   if (l_payment_profile_id is not null) then
1474     select nvl(ibcr.group_by_due_date_flag,'N')
1475     into l_group_by_due_date_flag
1476     from  iby_acct_pmt_profiles_b ibpp, IBY_PMT_CREATION_RULES ibcr
1477     where ibpp.system_profile_code = ibcr.system_profile_code
1478     and ibpp.payment_profile_id = l_payment_profile_id;
1479   else
1480     l_group_by_due_date_flag := 'N';
1481   end if;
1482 
1483   l_debug_info := 'Group_by_due_date flag :'||l_group_by_due_date_flag;
1484   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
1485     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
1486   END IF;
1487 
1488   -- Bug 9089243 ends
1489 
1490   l_debug_info := 'group all documents';
1491   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
1492     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
1493   END IF;
1494 
1495   --initialize the previous variables
1496 
1497     l_prev_org_id := l_documents(1).org_id;
1498     l_prev_exclusive_payment_flag := l_documents(1).exclusive_payment_flag;
1499     l_prev_payment_amount := l_documents(1).payment_amount;
1500     l_prev_vendor_site_id := l_documents(1).vendor_site_id;
1501     l_prev_party_id := l_documents(1).party_id;
1502     l_prev_party_site_id := l_documents(1).party_site_id;
1503     l_prev_payment_currency_code := l_documents(1).payment_currency_code;
1504     l_prev_payment_method := l_documents(1).payment_method;
1505     l_prev_ext_bank_acct_id := l_documents(1).external_bank_account_id;
1506     l_prev_payment_function := l_documents(1).payment_function;
1507     l_prev_pay_proc_trxn_type_code := l_documents(1).pay_proc_trxn_type_code;
1508     l_prev_beneficiary_party_id := l_documents(1).beneficiary_party_id;
1509     l_prev_bills_payable_flag   := l_documents(1).support_bills_payable_flag;  -- Bug 5357689
1510     l_prev_due_date  := l_documents(1).due_date;  -- Bug 5357689
1511 
1512   for i in l_documents.first .. l_documents.last loop
1513 
1514 /*
1515 
1516 Bug 16340312
1517 Grouping Credit memos against Standard Invoices.
1518 
1519  In case of Bills Payable, do not increment group number until the payment
1520  amount becomes positive.
1521 
1522 1) First Payment group should hold all the credit memos.
1523 
1524 2) After grouping all Credit memos, We need to keep running total
1525    of the payment amounts of the documents till the Payment Amount .
1526 
1527 3) Once the Payment Becomes Positive, check if all the Standards Invoices
1528    applied for which Credit memos applied and new invoice for which we do
1529    not apply credit memo are of same due date. If they are of same due date,
1530    we do should not increment the grouping number till we encounter the invoice
1531    of different due date.
1532 
1533    NOTE: If Credit Memo sum is applied to mixed due dated invoices, in that case we
1534    would increment the grouping number as soon as payment amount becomes positive.
1535 
1536    Example 1:
1537 
1538    If invoices are as follows, all the invoices should be grouped together
1539    CM1  - 31-JAN-2012  -100
1540    INV1 - 01-JAN-2012   150
1541    INV2 - 01-JAN-2012   100
1542    INV3 - 01-JAN-2012   100
1543 
1544    Example 2:
1545    If invoices are as follows
1546 
1547    CM1  - 31-JAN-2012  -100
1548    INV1 - 01-JAN-2012   150
1549    INV2 - 02-JAN-2012   100
1550    INV3 - 02-JAN-2012   100
1551 
1552    CM1, INV1, INV2 should be grouped together
1553    INV3 should be out of above group
1554 
1555 */
1556 
1557 		if l_documents(i).exclusive_payment_flag = 'Y' or
1558 		   l_prev_exclusive_payment_flag = 'Y' or
1559 		   l_prev_org_id <> l_documents(i).org_id or
1560 		   nvl(l_prev_vendor_site_id,-1) <> nvl(l_documents(i).vendor_site_id,-1) or
1561 		   l_prev_party_id <>l_documents(i).party_id or
1562 		   l_prev_party_site_id <> l_documents(i).party_site_id or
1563 		   l_prev_payment_currency_code <> l_documents(i).payment_currency_code or
1564 		   l_prev_payment_method <> l_documents(i).payment_method or
1565 		   nvl(l_prev_ext_bank_acct_id,-1) <> nvl(l_documents(i).external_bank_account_id,-1) or
1566 		   l_prev_payment_function <> l_documents(i).payment_function or
1567 		   --l_prev_pay_proc_trxn_type_code <> l_documents(i).pay_proc_trxn_type_code or
1568 		   /*Commented by zrehman for bug#7427845 on 17-Oct-2008*/
1569 		   nvl(l_prev_beneficiary_party_id,-1) <> nvl(l_documents(i).beneficiary_party_id,-1) --Modified for Bug 16340312
1570 		then
1571 
1572 			l_grouping_number := l_grouping_number + 1;
1573 			--Bug 16340312 Resetting the initial values
1574 			l_payment_sum := 0;
1575 			l_remove_cm_flag := 'N';
1576 			l_tmp_cm_total := 0;
1577 			l_tmp_pmt_count := 0;
1578 			l_init_cm_appl_date:= null; --Bug 16340312 to maintain credit memo first applied due_date
1579 
1580 			 if (l_documents(i).payment_amount > 0) then
1581 			   l_cm_set_off_flag:= 'Y';  --Bug 16340312 Initializing credit memo set-off flag
1582 			   l_tmp_cm_total := l_tmp_cm_total + l_documents(i).payment_amount;
1583 			 else
1584 			   l_tmp_cm_total := l_tmp_cm_total + l_documents(i).payment_amount;
1585 			   l_cm_set_off_flag:= 'N';  --Bug 16340312 Initializing credit memo set-off flag
1586 			 end if;
1587 			l_documents(i).payment_grouping_number := l_grouping_number;
1588 		 else
1589 			/*
1590 			  Bug 16340312
1591 			  Check if Bills payable and consider grouping by end-date
1592 
1593 			  Group by due-date would be performed in following cases
1594 			  1. Payment method is Bills Payable and PPP is not provided while submitting the PPR
1595 			  2. Payment method is BP and PPP provided at PPP has due date enabled
1596 
1597 			  Group by due-date would not be performed in following cases
1598 			  1. Normal grouping would be done if, Payment method is not Bills payable
1599 			    irrespecive of Due-date enable/disabled on PPP
1600 			*/
1601 
1602 			 IF ((l_documents(i).support_bills_payable_flag = 'Y') and
1603 			 	 (trunc(l_prev_due_date)  <> trunc(l_documents(i).due_date)) and
1604 					((l_group_by_due_date_flag = 'Y') OR (l_payment_profile_id is null)))
1605 
1606 				THEN
1607 
1608 			/*
1609 			   Bug 16340312
1610 			   Grouping on End-date begins once Credit Memos are completely set-off
1611 			   We need to ignore grouping on end-date till Credit Memos are completely setoff
1612 			*/
1613 			 if(l_documents(i).payment_amount < 0) then
1614 				l_tmp_cm_total := l_tmp_cm_total + l_documents(i).payment_amount;
1615 				l_documents(i).payment_grouping_number := l_grouping_number;
1616 				l_cm_set_off_flag := 'N';
1617 			 else
1618 				/*
1619 				  Based on sort order of documents selection, after grouping all the credit memos
1620 				  code will reach here for grouping standard invocies
1621 				*/
1622 				    l_tmp_cm_total  := l_tmp_cm_total + l_documents(i).payment_amount;
1623 				    l_tmp_pmt_count := l_tmp_pmt_count+1;
1624 					if (l_tmp_pmt_count = 1 and l_cm_set_off_flag = 'N') then
1625 					 l_init_cm_appl_date := l_documents(i).due_date;
1626 					end if;
1627 
1628 				  if (l_tmp_cm_total >= 0 and l_cm_set_off_flag  = 'N') then
1629 					 l_cm_set_off_flag := 'Y'; --Credit Memo is completely set-off here
1630 					 l_documents(i).payment_grouping_number := l_grouping_number;
1631 					 if (trunc(l_init_cm_appl_date) <> trunc( l_documents(i).due_date)) then
1632 					   l_grouping_number := l_grouping_number + 1; --Due-date for 1st std inv, CM Applied
1633 					   l_init_cm_appl_date := null;
1634 					 end if;
1635 
1636 					 l_payment_sum := 0;
1637 					 l_remove_cm_flag := 'N';
1638 				  elsif (l_tmp_cm_total >= 0 and l_cm_set_off_flag  = 'Y') then
1639 				     l_grouping_number := l_grouping_number + 1;
1640 				     l_documents(i).payment_grouping_number := l_grouping_number;
1641 
1642 					 l_payment_sum := 0;
1643 					 l_remove_cm_flag := 'N';
1644 					 l_init_cm_appl_date := null;
1645 
1646 				    else
1647 					 l_documents(i).payment_grouping_number := l_grouping_number;
1648 					end if;
1649 
1650 				  end if;
1651 
1652 		  ELSE
1653                /*
1654 			    If we reached here means, due date of earlier invoice is same as current
1655                */
1656 			 if(l_documents(i).payment_amount < 0) then
1657 				l_tmp_cm_total := l_tmp_cm_total + l_documents(i).payment_amount;
1658 				l_documents(i).payment_grouping_number := l_grouping_number;
1659 				l_cm_set_off_flag := 'N';
1660 			 else
1661 				l_tmp_cm_total := l_tmp_cm_total + l_documents(i).payment_amount;
1662 				l_tmp_pmt_count := l_tmp_pmt_count+1;
1663 				if (l_tmp_pmt_count = 1 and l_cm_set_off_flag = 'N') then
1664 					 l_init_cm_appl_date := l_documents(i).due_date;
1665 				end if;
1666 
1667 				if(l_cm_set_off_flag = 'N' and l_tmp_cm_total>=0) then
1668 				     l_cm_set_off_flag := 'Y';
1669 					 l_documents(i).payment_grouping_number := l_grouping_number;
1670 					 if (trunc(l_init_cm_appl_date) <> trunc( l_documents(i).due_date)) then
1671 					   l_grouping_number := l_grouping_number + 1;
1672 					   l_init_cm_appl_date := null;
1673 					 end if;
1674 					 l_payment_sum := 0;
1675 					 l_remove_cm_flag := 'N';
1676 				else
1677 				     l_documents(i).payment_grouping_number := l_grouping_number;
1678 				end if;
1679 			 end if;
1680 		  end if;
1681 		 end if;
1682 
1683 		 l_prev_org_id := l_documents(i).org_id;
1684 		 l_prev_exclusive_payment_flag := l_documents(i).exclusive_payment_flag;
1685 		 l_prev_payment_amount := l_documents(i).payment_amount;
1686 		 l_prev_vendor_site_id := l_documents(i).vendor_site_id;
1687 		 l_prev_party_id := l_documents(i).party_id;
1688 		 l_prev_party_site_id :=  l_documents(i).party_site_id;
1689 		 l_prev_payment_currency_code :=  l_documents(i).payment_currency_code;
1690 		 l_prev_payment_method :=  l_documents(i).payment_method;
1691 		 l_prev_ext_bank_acct_id :=  l_documents(i).external_bank_account_id;
1692 		 l_prev_payment_function :=  l_documents(i).payment_function;
1693 		 l_prev_pay_proc_trxn_type_code := l_documents(i).pay_proc_trxn_type_code;
1694 		 l_prev_beneficiary_party_id := l_documents(i).beneficiary_party_id;
1695 		 l_prev_bills_payable_flag   := l_documents(i).support_bills_payable_flag;  -- Bug 5357689
1696 		 l_prev_due_date  := l_documents(i).due_date; -- Bug 5357689
1697 		 fnd_file.put_line(FND_FILE.LOG,'l_tmp_cm_total'||l_tmp_cm_total);
1698 	  end loop;
1699 
1700   --5007819
1701   if l_maximize_credits_flag = 'Y' then
1702 
1703     l_debug_info := 'reduce credit memo amounts';
1704     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
1705       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
1706     END IF;
1707 
1708     --now everything should be grouped, let's go through and determine which
1709     --credit memos need to be reduced or set to not pay
1710 
1711     --initialize the previous grouping number
1712 		l_prev_grouping_number := l_documents(l_documents.last).payment_grouping_number;
1713 		l_max_index := l_documents.last;
1714 		/*
1715 		 As we changed order of SIGN and DUE_DATE in c_documents,
1716 		 we need to change the Maximize credit application loop
1717 		 from descending to ascending.
1718 		*/
1719 		WHILE (l_max_index > 0) Loop
1720 		  --Bug 7371792 --
1721 		  l_documents(l_max_index).payment_amount := l_documents(l_max_index).proposed_payment_amount;
1722 
1723 		  if l_documents(l_max_index).payment_grouping_number = l_prev_grouping_number then
1724 
1725 			l_payment_sum := l_payment_sum + l_documents(l_max_index).payment_amount;
1726 
1727 			if l_payment_sum < 0 then
1728 			  if l_remove_cm_flag <> 'Y' then
1729 			   --if are here we have a credit memo that just took
1730 			   --the total payment amount below zero
1731 			   --the code below will set the proposed payment amount for the credit memo
1732 			   --so that the total for this grouping_number is zero
1733 			   l_documents(l_max_index).proposed_payment_amount := l_documents(l_max_index).payment_amount - l_payment_sum;
1734 
1735 
1736 			   --4688545 this will handle the case where the very first record
1737 			   --in the pl/sql table is is a credit memo
1738 			   if l_documents(l_max_index).proposed_payment_amount = 0 then
1739 				 l_documents(l_max_index).ok_to_pay_flag := 'N';
1740 			   end if;
1741 
1742 			   l_remove_cm_flag := 'Y';
1743 			   l_payment_sum := 0;
1744 
1745 			  else
1746 				l_documents(l_max_index).ok_to_pay_flag := 'N';
1747 			  end if;
1748 			end if;
1749 
1750 
1751 		  else
1752 			--we are at a new payment, reset the sum
1753 			--and if just a single credit memo then set it's ok to pay flag to 'N'
1754 			l_payment_sum := l_documents(l_max_index).payment_amount;  -- Bug 5479979
1755 
1756 			if l_documents(l_max_index).payment_amount < 0 then
1757 			  l_documents(l_max_index).ok_to_pay_flag := 'N';
1758 			  --bug 8511962 if the first document of the group is a credit
1759 			  --memo, we need to set the l_remove_cm_flag to Y so that if
1760 			  --there are subsequent credit memos in the group they get
1761 			  --removed as well. If this is the only document in the group
1762 			  --the flag will get reset for the next group on the next
1763 			  --iteration in the else immediately following.
1764 			  l_remove_cm_flag := 'Y';
1765 			else
1766 			  --bug 8511962 l_remove_cm_flag needs to be reset for each payment
1767 			  l_remove_cm_flag := 'N';
1768 			end if;
1769 
1770 		  end if;
1771 
1772 		  l_prev_grouping_number := l_documents(l_max_index).payment_grouping_number;
1773 		  l_max_index := l_max_index - 1;
1774 		end loop;
1775 
1776   end if; --5007819
1777 
1778 
1779   l_debug_info := 'update grouping numbers, ok to pay flags, and amounts';
1780   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
1781     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
1782   END IF;
1783 
1784 
1785 
1786 
1787   --IBY isn't using proposed_payment_amount so we need to set the payment
1788   --amount here
1789   -- 7371792 proposed_payment_amount contains original
1790   -- payment_amount. Later we reset the payment_amount
1791 
1792   for i in l_documents.first .. l_documents.last loop
1793     /* Added the hint INDEX(AP_SELECTED_INVOICES_ALL,AP_SELECTED_INVOICES_N1) for bug#8368922 */
1794     update /*+ INDEX(AP_SELECTED_INVOICES_ALL,AP_SELECTED_INVOICES_N1) */ ap_selected_invoices_all
1795     set    payment_grouping_number = l_documents(i).payment_grouping_number,
1796            ok_to_pay_flag = l_documents(i).ok_to_pay_flag,
1797            -- proposed_payment_amount = l_documents(i).proposed_payment_amount, 7371792
1798            payment_amount = l_documents(i).proposed_payment_amount,
1799            dont_pay_reason_code = decode(l_documents(i).ok_to_pay_flag,'N',
1800                                          'CREDIT TOO LOW',null),
1801            last_update_date = sysdate,
1802            -- Bug 7383484 (Base bug 7296715)
1803            -- last_updated_by = 5
1804            last_updated_by = FND_GLOBAL.USER_ID,
1805            due_date = l_documents(i).due_date  -- Bug 5357689
1806     where  invoice_id  = l_documents(i).invoice_id
1807     and    payment_num = l_documents(i).payment_num
1808     and    checkrun_id= p_checkrun_id;
1809   end loop;
1810 
1811 
1812 
1813   --handle interest invoices where federal is not installed
1814   --bug 5233279
1815   /* Bug 10318301
1816    * In a Federal instance, only when the pay alone is used
1817    * should the original invoice and the interest invoice be paid
1818    * separately. In a non Federal instance they should always be
1819    * paid together.  The above processing only operates on invoices
1820    * where original_invoice_id is null so no interest is grouped before
1821    * here.  Thus we will group the interest if Federal = N or
1822    * if Federal = Y and exclusive payment flag = N
1823    * Note in a federal instance the selected invoice row for the
1824    * interest takes its exclusive payment flag from the original invoice.
1825    */
1826   update ap_selected_invoices_all asi
1827   set payment_grouping_number =
1828     (select asi2.payment_grouping_number
1829      from ap_selected_invoices_all asi2
1830      where asi2.invoice_id = asi.original_invoice_id
1831      and asi2.payment_num = asi.original_payment_num
1832      and asi2.checkrun_id = p_checkrun_id)
1833   where asi.checkrun_id = p_checkrun_id
1834   and asi.original_invoice_id is not null
1835   and (Ap_Payment_Util_Pkg.is_federal_installed(asi.org_id) = 'N'
1836       /* following 2 lines added for bug 10318301 */
1837       or (Ap_Payment_Util_Pkg.is_federal_installed(asi.org_id) = 'Y'
1838           and asi.exclusive_payment_flag = 'N'));
1839 
1840 
1841 
1842   --5007819
1843   --Bug 5277604. Selected Invoices will
1844   --will be only unselected table if total payment
1845   --amount goes below zero.
1846   if l_maximize_credits_flag <> 'Y' then
1847     update ap_selected_invoices_all asi
1848     set ok_to_pay_flag = 'N',
1849         dont_pay_reason_code = 'CREDIT TOO LOW',
1850         last_update_date = sysdate,
1851         -- Bug 7383484 (Base bug 7296715)
1852         -- last_updated_by = 5
1853         last_updated_by = FND_GLOBAL.USER_ID
1854     where checkrun_id = p_checkrun_id
1855     and payment_grouping_number in
1856       (select asi2.payment_grouping_number
1857        from ap_selected_invoices_all asi2
1858        where asi2.checkrun_id = p_checkrun_id
1859        group by asi2.payment_grouping_number
1860        having sum(asi2.payment_amount) < 0);
1861   end if;
1862 
1863 
1864  --now remove the grouping numbers where no interest invoice is involved
1865   --or no credit memo is involved
1866   --Bug 8275467 added HASH_AJ hint
1867 
1868   UPDATE Ap_Selected_Invoices_All ASI
1869   SET    payment_grouping_number = null
1870   WHERE  payment_grouping_number NOT IN (
1871     SELECT /*+ HASH_AJ */ payment_grouping_number
1872     FROM   Ap_Selected_Invoices_All ASI2
1873     WHERE  (ASI2.original_invoice_id is not null or
1874             ASI2.payment_amount < 0)
1875     AND    ASI2.ok_to_pay_flag = 'Y'
1876     AND    ASI2.checkrun_id = p_checkrun_id
1877     AND    ASI2.payment_grouping_number IS NOT NULL)
1878   AND  ASI.checkrun_id = p_checkrun_id
1879   AND  ASI.payment_grouping_number IS NOT NULL;
1880 
1881   --Bug 5646890, Following Update is replaed by updated above as per performance team
1882   --now remove the grouping numbers where no interest invoice is involved
1883   --or no credit memo is involved
1884   /*update ap_selected_invoices_all asi
1885   set payment_grouping_number = null
1886   where payment_grouping_number not in (
1887     select payment_grouping_number
1888     from ap_selected_invoices_all asi2
1889     where (asi2.original_invoice_id is not null or
1890            asi2.payment_amount < 0)
1891     and asi2.ok_to_pay_flag = 'Y'
1892     and checkrun_id = p_checkrun_id)
1893   and checkrun_id = p_checkrun_id; */
1894 
1895   --now remove the grouping numbers where  interest invoice is involved
1896   --but federal is installed. Bug 5233279.
1897   -- Bug 5645890, Added extra condition payment_grouping_number is not null
1898 
1899   /* Bug 10318301
1900    * There is no need to remove the payment_grouping_number when
1901    * federal is installed.  In  Federal instance, only when the pay alone is used
1902    * should the original invoice and the interest invoice be paid
1903    * separately.  This happens already (see comment on same bug # above).
1904    * When in place, the update incorrect ungruops credit memos too.
1905    * Thus the following is commented out.
1906 
1907   update ap_selected_invoices_all asi
1908   set payment_grouping_number = null
1909   where  asi.checkrun_id = p_checkrun_id
1910   and    asi.payment_grouping_number is not null
1911   and Ap_Payment_Util_Pkg.is_federal_installed(asi.org_id) = 'Y'
1912   and exists (
1913     select*/ /*+NO_UNNEST *//* NULL
1914     from ap_selected_invoices_all asi2
1915     where asi2.original_invoice_id is not null
1916     and asi2.original_invoice_id = asi.invoice_id
1917     and asi2.ok_to_pay_flag = 'Y'
1918     and asi2.checkrun_id = p_checkrun_id);
1919    */
1920 
1921 
1922   --bug 5233279. Now set the pay alone flag to 'N' for all invoices
1923   --when federal is not installed  and has related interest invoice
1924   -- Bug 5645890, Added the hint
1925   update ap_selected_invoices_all asi
1926   set exclusive_payment_flag = 'N'
1927   where asi.checkrun_id = p_checkrun_id
1928   and Ap_Payment_Util_Pkg.is_federal_installed(asi.org_id) = 'N'
1929   and exists (
1930     select  NULL
1931     from ap_selected_invoices_all asi2
1932     where asi2.original_invoice_id is not null
1933     and asi2.original_invoice_id = asi.invoice_id
1934     and asi2.ok_to_pay_flag = 'Y'
1935     and asi2.checkrun_id = p_checkrun_id);
1936 
1937 
1938 EXCEPTION
1939   WHEN OTHERS THEN
1940 
1941     IF (SQLCODE <> -20001) THEN
1942       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
1943       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
1944     END IF;
1945     APP_EXCEPTION.RAISE_EXCEPTION;
1946 
1947 END GROUP_INTEREST_CREDITS;
1948 
1949 
1950 Procedure create_checkrun   (p_checkrun_id                  out nocopy number,
1951                              p_template_id                  in number,
1952                              p_payment_date                 in date,
1953                              p_pay_thru_date                in date,
1954                              p_pay_from_date                in date,
1955                              p_current_calling_sequence     in varchar2) is
1956 
1957 
1958 
1959   l_current_calling_sequence varchar2(2000);
1960   l_debug_info varchar2(2000);
1961 
1962 begin
1963 
1964   l_current_calling_sequence := p_current_calling_sequence || '<-create_checkrun';
1965 
1966   l_debug_info := 'select checkrun_id';
1967   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
1968     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
1969   END IF;
1970 
1971 
1972   select ap_inv_selection_criteria_s.nextval
1973   into p_checkrun_id
1974   from dual;
1975 
1976 
1977 
1978   l_debug_info := 'insert into ap_inv_selection_criteria_all';
1979   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
1980     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
1981   END IF;
1982 
1983   insert into ap_inv_selection_criteria_all(
1984            check_date,
1985            pay_thru_date,
1986            hi_payment_priority,
1987            low_payment_priority,
1988            pay_only_when_due_flag,
1989            status,
1990            zero_amounts_allowed,  --uncommented for Bug 8899870
1991            zero_invoices_allowed,
1992            vendor_id,
1993            checkrun_id,
1994            pay_from_date,
1995            inv_exchange_rate_type,
1996            exchange_rate_type, --Bug6829191
1997            payment_method_code,
1998            vendor_type_lookup_code,
1999            CREATE_INSTRS_FLAG,
2000            PAYMENT_PROFILE_ID,
2001            bank_account_id,
2002            checkrun_name,
2003            ou_group_option,
2004            le_group_option,
2005            currency_group_option,
2006            pay_group_option,
2007            last_update_date,
2008            last_updated_by,
2009            last_update_login,
2010            creation_date,
2011            created_by,
2012            template_flag,
2013            template_id,
2014            payables_review_settings,
2015            payments_review_settings,
2016            document_rejection_level_code,
2017            payment_rejection_level_code,
2018            party_id,
2019            request_id, --4737467
2020            payment_document_id, --7315136
2021            transfer_priority, --7315136
2022            settlement_priority, --14726060
2023            ATTRIBUTE_CATEGORY, -- begin 8935712
2024            ATTRIBUTE1
2025            ,ATTRIBUTE2
2026            ,ATTRIBUTE3
2027            ,ATTRIBUTE4
2028            ,ATTRIBUTE5
2029            ,ATTRIBUTE6
2030            ,ATTRIBUTE7
2031            ,ATTRIBUTE8
2032            ,ATTRIBUTE9
2033            ,ATTRIBUTE10
2034            ,ATTRIBUTE11
2035            ,ATTRIBUTE12
2036            ,ATTRIBUTE13
2037            ,ATTRIBUTE14
2038            ,ATTRIBUTE15 -- end 8935712
2039            )
2040  select   nvl(p_payment_date,sysdate)+ nvl(addl_payment_days,0) , --4681989 /*Bug 9739226 */
2041            nvl(p_pay_thru_date, sysdate + ADDL_PAY_THRU_DAYS),--4681989
2042            hi_payment_priority,
2043            low_payment_priority,
2044            pay_only_when_due_flag,
2045            'UNSTARTED',
2046            zero_amounts_allowed,  --uncommented for Bug 8899870
2047            ZERO_INV_ALLOWED_FLAG,
2048            vendor_id,
2049            p_checkrun_id,
2050            -- start of bug12403039
2051            --nvl(p_pay_from_date, sysdate - ADDL_PAY_FROM_DAYS), --4681989
2052            nvl(p_pay_from_date, sysdate + ADDL_PAY_FROM_DAYS),
2053            -- end of bug12403039
2054            inv_exchange_rate_type,
2055            payment_exchange_rate_type, --Bug6829191
2056            payment_method_code,
2057            vendor_type_lookup_code,
2058            CREATE_INSTRS_FLAG,
2059            PAYMENT_PROFILE_ID,
2060            BANK_ACCOUNT_ID,
2061            template_name ||'-'||to_char(sysdate, 'DD-MON-RRRR HH24:MI:SS'),
2062            ou_group_option,
2063            le_group_option,
2064            currency_group_option,
2065            pay_group_option,
2066            sysdate,
2067            last_updated_by,
2068            last_update_login,
2069            sysdate,
2070            created_by,
2071            'Y',
2072            p_template_id,
2073            payables_review_settings,
2074            payments_review_settings,
2075            document_rejection_level_code,
2076            payment_rejection_level_code,
2077            party_id,
2078            fnd_global.conc_request_id,  --4737467
2079            payment_document_id, --7315136
2080            transfer_priority, --7315136
2081            settlement_priority, --14726060
2082            ATTRIBUTE_CATEGORY, -- begin 8885918
2083            ATTRIBUTE1
2084            ,ATTRIBUTE2
2085            ,ATTRIBUTE3
2086            ,ATTRIBUTE4
2087            ,ATTRIBUTE5
2088            ,ATTRIBUTE6
2089            ,ATTRIBUTE7
2090            ,ATTRIBUTE8
2091            ,ATTRIBUTE9
2092            ,ATTRIBUTE10
2093            ,ATTRIBUTE11
2094            ,ATTRIBUTE12
2095            ,ATTRIBUTE13
2096            ,ATTRIBUTE14
2097            ,ATTRIBUTE15 -- end 8885918
2098   from     AP_PAYMENT_TEMPLATES
2099   where    template_id = p_template_id;
2100 
2101 
2102   l_debug_info := 'insert into ap_le_group';
2103   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
2104     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
2105   END IF;
2106 
2107   insert into ap_le_group (
2108            legal_entity_id,
2109            checkrun_id,
2110            LE_GROUP_ID,
2111            CREATION_DATE,
2112            CREATED_BY,
2113            LAST_UPDATE_DATE,
2114            LAST_UPDATED_BY)
2115   select   legal_entity_id,
2116            p_checkrun_id,
2117            AP_LE_GROUP_S.nextval,
2118            sysdate,
2119            alg.created_by,
2120            sysdate,
2121            alg.last_updated_by
2122   from     ap_le_group alg,
2123            ap_payment_templates appt
2124   where    alg.template_id = p_template_id
2125   and      alg.template_id = appt.template_id
2126   and      appt.le_group_option = 'SPECIFY';
2127 
2128 
2129   l_debug_info := 'insert into AP_OU_GROUP';
2130   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
2131     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
2132   END IF;
2133 
2134   insert into AP_OU_GROUP (
2135            org_id,
2136            checkrun_id,
2137            OU_GROUP_ID,
2138            CREATION_DATE,
2139            CREATED_BY,
2140            LAST_UPDATE_DATE,
2141            LAST_UPDATED_BY)
2142   select   aog.org_id,
2143            p_checkrun_id,
2144            AP_OU_GROUP_S.nextval,
2145            sysdate,
2146            aog.created_by,
2147            sysdate,
2148            aog.last_updated_by
2149   from     ap_ou_group aog,
2150            ap_payment_templates appt
2151   where    aog.template_id = p_template_id
2152   and      aog.template_id = appt.template_id
2153   and      appt.ou_group_option = 'SPECIFY';
2154 
2155   l_debug_info := 'insert into AP_CURRENCY_GROUP';
2156   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
2157     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
2158   END IF;
2159 
2160 
2161   insert into AP_CURRENCY_GROUP (
2162            currency_code,
2163            checkrun_id,
2164            CURRENCY_GROUP_ID,
2165            CREATION_DATE,
2166            CREATED_BY,
2167            LAST_UPDATE_DATE,
2168            LAST_UPDATED_BY)
2169   select   currency_code,
2170            p_checkrun_id,
2171            AP_CURRENCY_GROUP_S.nextval,
2172            sysdate,
2173            acg.created_by,
2174            sysdate,
2175            acg.last_updated_by
2176   from     AP_CURRENCY_GROUP acg,
2177            ap_payment_templates appt
2178   where    acg.template_id = p_template_id
2179   and      acg.template_id = appt.template_id
2180   and      appt.currency_group_option = 'SPECIFY';--Bug6926344
2181 
2182   l_debug_info := 'insert into AP_PAY_GROUP';
2183   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
2184     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
2185   END IF;
2186 
2187   insert into AP_PAY_GROUP (
2188            vendor_pay_group,
2189            checkrun_id,
2190            PAY_GROUP_ID,
2191            CREATION_DATE,
2192            CREATED_BY,
2193            LAST_UPDATE_DATE,
2194            LAST_UPDATED_BY)
2195   select   vendor_pay_group,
2196            p_checkrun_id,
2197            AP_PAY_GROUP_S.nextval,
2198            sysdate,
2199            apg.created_by,
2200            sysdate,
2201            apg.last_updated_by
2202   from     AP_PAY_GROUP apg,
2203            ap_payment_templates appt
2204   where    apg.template_id = p_template_id
2205   and      apg.template_id = appt.template_id
2206   and      appt.pay_group_option = 'SPECIFY'; --Bug6926344
2207 
2208 
2209 
2210 EXCEPTION
2211   WHEN OTHERS THEN
2212 
2213     IF (SQLCODE <> -20001) THEN
2214       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
2215       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
2216       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
2217       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
2218       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_template_id= '||
2219                                            to_char(p_template_id));
2220 
2221 
2222     END IF;
2223     APP_EXCEPTION.RAISE_EXCEPTION;
2224 
2225 end create_checkrun;
2226 
2227 
2228 
2229 
2230 
2231 
2232 
2233 
2234 
2235 PROCEDURE select_invoices   (errbuf             OUT NOCOPY VARCHAR2,
2236                              retcode            OUT NOCOPY NUMBER,
2237                              p_checkrun_id      in            varchar2,
2238                              P_template_id      in            varchar2,
2239                              p_payment_date     in            varchar2,
2240                              p_pay_thru_date    in            varchar2,
2241                              p_pay_from_date    in            varchar2)  IS
2242 
2243   l_abort                    varchar2(1);
2244   l_api_name                 CONSTANT  VARCHAR2(100) := 'SELECT_INVOICES';
2245   l_base_currency_code       varchar2(15);
2246   l_batch_exchange_rate_type varchar2(30);
2247   l_batch_status             varchar2(30);
2248   l_bank_account_id          number; --4710933
2249   l_check_date               date;
2250   l_check_date_char          VARCHAR2(100);
2251   l_checkrun_id              number;
2252   l_count_inv_selected       number;
2253   l_create_instrs_flag       varchar2(1);
2254   l_currency_group_option    varchar2(10);
2255   l_current_calling_sequence   VARCHAR2(2000);
2256   l_debug_info               VARCHAR2(2000);
2257   l_disc_pay_thru_date       date;
2258   l_disc_pay_thru_char       VARCHAR2(100);
2259   l_doc_rejection_level_code varchar2(30);
2260   l_encumbrance_flag         number;
2261   l_hi_payment_priority      number;
2262   l_inv_exchange_rate_type   varchar2(30);
2263   l_inv_vendor_id            number;
2264   l_invoice_batch_id         number;
2265   l_le_group_option          varchar2(10);
2266   l_log_module               varchar2(240);
2267   l_low_payment_priority     number;
2268   l_max_payment_amount       number;
2269   l_min_check_amount         number;
2270   l_missing_rates_count      number;
2271   l_ou_group_option          varchar2(10);
2272   l_party_id                 number(15);
2273   l_pay_from_date            date;
2274   l_pay_from_date_char       VARCHAR2(100);
2275   l_pay_group_option         varchar2(10);
2276   l_pay_rejection_level_code varchar2(30);
2277   l_pay_review_settings_flag varchar2(1);
2278   l_pay_thru_date            date;
2279   l_pay_thru_date_char       VARCHAR2(100);
2280   l_payables_review_settings varchar2(1);
2281   l_payment_date             date;
2282   l_payment_document_id      number(15); --4939405
2283   l_payment_method           varchar2(30);
2284   l_payment_process_request_name varchar2(240);
2285   l_payment_profile_id       number;
2286   l_req_id                   number;
2287   l_set_of_books_name        varchar2(30);
2288   l_supplier_type            varchar2(30);
2289   l_template_id              number;
2290   l_zero_amounts_allowed     varchar2(1);
2291   l_zero_invoices_allowed    varchar2(1);
2292   SELECTION_FAILURE          EXCEPTION;
2293   l_xml_output               BOOLEAN;
2294   l_iso_language             FND_LANGUAGES.iso_language%TYPE;
2295   l_iso_territory            FND_LANGUAGES.iso_territory%TYPE;
2296   l_template_code       Fnd_Concurrent_Programs.template_code%TYPE; -- Bug 6969710
2297   l_output_format       XDO_TEMPLATES_B.DEFAULT_OUTPUT_TYPE%TYPE; /* Bug#12917747 */
2298   /*bug 7519277*/
2299   l_ATTRIBUTE_CATEGORY       VARCHAR2(150);
2300   l_ATTRIBUTE1               VARCHAR2(150);
2301   l_ATTRIBUTE2               VARCHAR2(150);
2302   l_ATTRIBUTE3               VARCHAR2(150);
2303   l_ATTRIBUTE4               VARCHAR2(150);
2304   l_ATTRIBUTE5               VARCHAR2(150);
2305   l_ATTRIBUTE6               VARCHAR2(150);
2306   l_ATTRIBUTE7               VARCHAR2(150);
2307   l_ATTRIBUTE8               VARCHAR2(150);
2308   l_ATTRIBUTE9               VARCHAR2(150);
2309   l_ATTRIBUTE10              VARCHAR2(150);
2310   l_ATTRIBUTE11              VARCHAR2(150);
2311   l_ATTRIBUTE12              VARCHAR2(150);
2312   l_ATTRIBUTE13              VARCHAR2(150);
2313   l_ATTRIBUTE14              VARCHAR2(150);
2314   l_ATTRIBUTE15              VARCHAR2(150);
2315   /*bug 7519277*/
2316   l_icx_numeric_characters   VARCHAR2(30); --for bug#7435751
2317   l_return_status   boolean; --for bug#7435751
2318   l_inv_awt_exists_flag      VARCHAR2(1); -- Bug 7492768
2319 
2320   -- DYNAMIC SQL (bug8637005)
2321   l_hint                     VARCHAR2(100);
2322   l_sql_stmt                 LONG;
2323   TYPE refcurtyp     IS      REF CURSOR;
2324   refcur                     REFCURTYP;
2325   -- Bug 5646890.  Performance changes
2326     TYPE checkrun_name_t IS TABLE OF AP_SELECTED_INVOICES_ALL.checkrun_name%TYPE INDEX BY BINARY_INTEGER;
2327     TYPE checkrun_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.checkrun_id%TYPE INDEX BY BINARY_INTEGER;
2328     TYPE invoice_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.invoice_id%TYPE INDEX BY BINARY_INTEGER;
2329     TYPE payment_num_t IS TABLE OF  AP_SELECTED_INVOICES_ALL.payment_num%TYPE INDEX BY BINARY_INTEGER;
2330     TYPE last_update_date_t IS TABLE OF AP_SELECTED_INVOICES_ALL.last_update_date%TYPE INDEX BY BINARY_INTEGER;
2331     TYPE last_updated_by_t IS TABLE OF AP_SELECTED_INVOICES_ALL.last_updated_by%TYPE INDEX BY BINARY_INTEGER;
2332     TYPE creation_date_t IS TABLE OF AP_SELECTED_INVOICES_ALL.creation_date%TYPE INDEX BY BINARY_INTEGER;
2333     TYPE created_by_t IS TABLE OF  AP_SELECTED_INVOICES_ALL.created_by%TYPE INDEX BY BINARY_INTEGER;
2334     TYPE last_update_login_t IS TABLE OF AP_SELECTED_INVOICES_ALL.last_update_login%TYPE INDEX BY BINARY_INTEGER;
2335     TYPE vendor_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.vendor_id%TYPE INDEX BY BINARY_INTEGER;
2336     TYPE vendor_site_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.vendor_site_id%TYPE INDEX BY BINARY_INTEGER;
2337     TYPE vendor_num_t IS TABLE OF AP_SELECTED_INVOICES_ALL.vendor_num%TYPE INDEX BY BINARY_INTEGER;
2338     TYPE vendor_name_t IS TABLE OF AP_SELECTED_INVOICES_ALL.vendor_name%TYPE INDEX BY BINARY_INTEGER;
2339     TYPE vendor_site_code_t IS TABLE OF AP_SELECTED_INVOICES_ALL.vendor_site_code%TYPE INDEX BY BINARY_INTEGER;
2340     TYPE address_line1_t IS TABLE OF AP_SELECTED_INVOICES_ALL.address_line1%TYPE INDEX BY BINARY_INTEGER;
2341     TYPE city_t IS TABLE OF AP_SELECTED_INVOICES_ALL.city%TYPE INDEX BY BINARY_INTEGER;
2342     TYPE state_t IS TABLE OF AP_SELECTED_INVOICES_ALL.state%TYPE INDEX BY BINARY_INTEGER;
2343     TYPE zip_t IS TABLE OF AP_SELECTED_INVOICES_ALL.zip%TYPE INDEX BY BINARY_INTEGER;
2344     TYPE province_t IS TABLE OF AP_SELECTED_INVOICES_ALL.province%TYPE INDEX BY BINARY_INTEGER;
2345     TYPE country_t IS TABLE OF AP_SELECTED_INVOICES_ALL.country%TYPE INDEX BY BINARY_INTEGER;
2346     TYPE attention_ar_flag_t IS TABLE OF AP_SELECTED_INVOICES_ALL.attention_ar_flag%TYPE INDEX BY BINARY_INTEGER;
2347     TYPE withholding_status_lookup_t IS TABLE OF AP_SELECTED_INVOICES_ALL.withholding_status_lookup_code%TYPE INDEX BY BINARY_INTEGER;
2348     TYPE invoice_num_t IS TABLE OF AP_SELECTED_INVOICES_ALL.invoice_num%TYPE INDEX BY BINARY_INTEGER;
2349     TYPE invoice_date_t IS TABLE OF AP_SELECTED_INVOICES_ALL.invoice_date%TYPE INDEX BY BINARY_INTEGER;
2350     TYPE voucher_num_t IS TABLE OF AP_SELECTED_INVOICES_ALL.voucher_num%TYPE INDEX BY BINARY_INTEGER;
2351     TYPE ap_ccid_t IS TABLE OF AP_SELECTED_INVOICES_ALL.ap_ccid%TYPE INDEX BY BINARY_INTEGER;
2352     TYPE due_date_t IS TABLE OF AP_SELECTED_INVOICES_ALL.due_date%TYPE INDEX BY BINARY_INTEGER;
2353     TYPE discount_date_t IS TABLE OF AP_SELECTED_INVOICES_ALL.discount_date%TYPE INDEX BY BINARY_INTEGER;
2354     TYPE invoice_description_t IS TABLE OF AP_SELECTED_INVOICES_ALL.invoice_description%TYPE INDEX BY BINARY_INTEGER;
2355     TYPE payment_priority_t IS TABLE OF AP_SELECTED_INVOICES_ALL.payment_priority%TYPE INDEX BY BINARY_INTEGER;
2356     TYPE ok_to_pay_flag_t IS TABLE OF AP_SELECTED_INVOICES_ALL.ok_to_pay_flag%TYPE INDEX BY BINARY_INTEGER;
2357     TYPE always_take_disc_flag_t IS TABLE OF AP_SELECTED_INVOICES_ALL.always_take_discount_flag%TYPE INDEX BY BINARY_INTEGER;
2358     TYPE amount_modified_flag_t IS TABLE OF AP_SELECTED_INVOICES_ALL.amount_modified_flag%TYPE INDEX BY BINARY_INTEGER;
2359     TYPE invoice_amount_t IS TABLE OF  AP_SELECTED_INVOICES_ALL.invoice_amount%TYPE INDEX BY BINARY_INTEGER;
2360     TYPE payment_cross_rate_t IS TABLE OF AP_SELECTED_INVOICES_ALL.payment_cross_rate%TYPE INDEX BY BINARY_INTEGER;
2361     TYPE invoice_exchange_rate_t IS TABLE OF AP_SELECTED_INVOICES_ALL.invoice_exchange_rate%TYPE INDEX BY BINARY_INTEGER;
2362     TYPE set_of_books_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.set_of_books_id%TYPE INDEX BY BINARY_INTEGER;
2363     TYPE customer_num_t IS TABLE OF AP_SELECTED_INVOICES_ALL.customer_num%TYPE INDEX BY BINARY_INTEGER;
2364     TYPE future_pay_due_date_t IS TABLE OF AP_SELECTED_INVOICES_ALL.future_pay_due_date%TYPE INDEX BY BINARY_INTEGER;
2365     TYPE exclusive_payment_flag_t IS TABLE OF AP_SELECTED_INVOICES_ALL.exclusive_payment_flag%TYPE INDEX BY BINARY_INTEGER;
2366     TYPE attribute1_t IS TABLE OF AP_SELECTED_INVOICES_ALL.attribute1%TYPE INDEX BY BINARY_INTEGER;
2367     TYPE attribute_category_t IS TABLE OF AP_SELECTED_INVOICES_ALL.attribute_category%TYPE INDEX BY BINARY_INTEGER;
2368     TYPE org_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.org_id%TYPE INDEX BY BINARY_INTEGER;
2369     TYPE payment_currency_code_t IS TABLE OF AP_SELECTED_INVOICES_ALL.payment_currency_code%TYPE INDEX BY BINARY_INTEGER;
2370     TYPE external_bank_account_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.external_bank_account_id%TYPE INDEX BY BINARY_INTEGER;
2371     TYPE legal_entity_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.legal_entity_id%TYPE INDEX BY BINARY_INTEGER;
2372     TYPE global_attribute1_t IS TABLE OF AP_SELECTED_INVOICES_ALL.global_attribute1%TYPE INDEX BY BINARY_INTEGER;
2373     TYPE global_attribute_category_t IS TABLE OF AP_SELECTED_INVOICES_ALL.global_attribute_category%TYPE  INDEX BY BINARY_INTEGER;
2374     TYPE amount_paid_t IS TABLE OF AP_SELECTED_INVOICES_ALL.amount_paid%TYPE INDEX BY BINARY_INTEGER;
2375     TYPE discount_amount_taken_t IS TABLE OF AP_SELECTED_INVOICES_ALL.discount_amount_taken%TYPE INDEX BY BINARY_INTEGER;
2376     TYPE amount_remaining_t IS TABLE OF AP_SELECTED_INVOICES_ALL.amount_remaining%TYPE INDEX BY BINARY_INTEGER;
2377     TYPE discount_amount_remaining_t IS TABLE OF AP_SELECTED_INVOICES_ALL.discount_amount_remaining%TYPE INDEX BY BINARY_INTEGER;
2378     TYPE payment_amount_t IS TABLE OF AP_SELECTED_INVOICES_ALL.payment_amount%TYPE INDEX BY BINARY_INTEGER;
2379     TYPE discount_amount_t IS TABLE OF AP_SELECTED_INVOICES_ALL.discount_amount%TYPE INDEX BY BINARY_INTEGER;
2380     TYPE sequence_num_t IS TABLE OF AP_SELECTED_INVOICES_ALL.sequence_num%TYPE INDEX BY BINARY_INTEGER;
2381     TYPE dont_pay_reason_code_t IS TABLE OF AP_SELECTED_INVOICES_ALL.dont_pay_reason_code%TYPE INDEX BY BINARY_INTEGER;
2382     TYPE check_number_t IS TABLE OF AP_SELECTED_INVOICES_ALL.check_number%TYPE INDEX BY BINARY_INTEGER;
2383     TYPE bank_account_type_t IS TABLE OF AP_SELECTED_INVOICES_ALL.bank_account_type%TYPE INDEX BY BINARY_INTEGER;
2384     TYPE original_invoice_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.original_invoice_id%TYPE INDEX BY BINARY_INTEGER;
2385     TYPE original_payment_num_t IS TABLE OF AP_SELECTED_INVOICES_ALL.original_payment_num%TYPE INDEX BY BINARY_INTEGER;
2386     TYPE bank_account_num_t IS TABLE OF AP_SELECTED_INVOICES_ALL.bank_account_num%TYPE INDEX BY BINARY_INTEGER;
2387     TYPE bank_num_t IS TABLE OF AP_SELECTED_INVOICES_ALL.bank_num%TYPE INDEX BY BINARY_INTEGER;
2388     TYPE proposed_payment_amount_t IS TABLE OF AP_SELECTED_INVOICES_ALL.proposed_payment_amount%TYPE INDEX BY BINARY_INTEGER;
2389     TYPE pay_selected_check_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.pay_selected_check_id%TYPE INDEX BY BINARY_INTEGER;
2390     TYPE print_selected_check_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.print_selected_check_id%TYPE INDEX BY BINARY_INTEGER;
2391     TYPE withholding_amount_t IS TABLE OF AP_SELECTED_INVOICES_ALL.withholding_amount%TYPE INDEX BY BINARY_INTEGER;
2392     TYPE invoice_payment_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.invoice_payment_id%TYPE INDEX BY BINARY_INTEGER;
2393     TYPE dont_pay_description_t IS TABLE OF AP_SELECTED_INVOICES_ALL.dont_pay_description%TYPE INDEX BY BINARY_INTEGER;
2394     TYPE transfer_priority_t IS TABLE OF AP_SELECTED_INVOICES_ALL.transfer_priority%TYPE INDEX BY BINARY_INTEGER;
2395     TYPE iban_number_t IS TABLE OF AP_SELECTED_INVOICES_ALL.iban_number%TYPE INDEX BY BINARY_INTEGER;
2396     TYPE payment_grouping_number_t IS TABLE OF AP_SELECTED_INVOICES_ALL.payment_grouping_number%TYPE INDEX BY BINARY_INTEGER;
2397     TYPE payment_exchange_rate_t IS TABLE OF AP_SELECTED_INVOICES_ALL.payment_exchange_rate%TYPE INDEX BY BINARY_INTEGER;
2398     TYPE payment_exchange_rate_type_t IS TABLE OF AP_SELECTED_INVOICES_ALL.payment_exchange_rate_type%TYPE INDEX BY BINARY_INTEGER;
2399     TYPE payment_exchange_date_t IS TABLE OF AP_SELECTED_INVOICES_ALL.payment_exchange_date%TYPE INDEX BY BINARY_INTEGER;
2400      -- Start of 8217641
2401     TYPE remit_to_supplier_name_t IS TABLE OF AP_SELECTED_INVOICES_ALL.remit_to_supplier_name%TYPE INDEX BY BINARY_INTEGER;
2402     TYPE remit_to_supplier_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.remit_to_supplier_id%TYPE INDEX BY BINARY_INTEGER;
2403     TYPE remit_to_supplier_site_t IS TABLE OF AP_SELECTED_INVOICES_ALL.remit_to_supplier_site%TYPE INDEX BY BINARY_INTEGER;
2404     TYPE remit_to_supplier_site_id_t IS TABLE OF AP_SELECTED_INVOICES_ALL.remit_to_supplier_site_id%TYPE INDEX BY BINARY_INTEGER;
2405    --End 8217641
2406 
2407 
2408 
2409 
2410   TYPE sel_inv_rec_type IS RECORD (
2411     checkrun_name_l                   checkrun_name_t
2412    ,checkrun_id_l                     checkrun_id_t
2413    ,invoice_id_l                      invoice_id_t
2414    ,payment_num_l                     payment_num_t
2415    ,last_update_date_l                last_update_date_t
2416    ,last_updated_by_l                 last_updated_by_t
2417    ,creation_date_l                   creation_date_t
2418    ,created_by_l                      created_by_t
2419    ,last_update_login_l               last_update_login_t
2420    ,vendor_id_l                       vendor_id_t
2421    ,vendor_site_id_l                  vendor_site_id_t
2422    ,vendor_num_l                      vendor_num_t
2423    ,vendor_name_l                     vendor_name_t
2424    ,vendor_site_code_l                vendor_site_code_t
2425    ,address_line1_l                   address_line1_t
2426    ,address_line2_l                   address_line1_t
2427    ,address_line3_l                   address_line1_t
2428    ,address_line4_l                   address_line1_t
2429    ,city_l                            city_t
2430    ,state_l                           state_t
2431    ,zip_l                             zip_t
2432    ,province_l                        province_t
2433    ,country_l                         country_t
2434    ,attention_ar_flag_l               attention_ar_flag_t
2435    ,withholding_status_lookup_l       withholding_status_lookup_t
2436    ,invoice_num_l                     invoice_num_t
2437    ,invoice_date_l                    invoice_date_t
2438    ,voucher_num_l                     voucher_num_t
2439    ,ap_ccid_l                         ap_ccid_t
2440    ,due_date_l                        due_date_t
2441    ,discount_date_l                   discount_date_t
2442    ,invoice_description_l             invoice_description_t
2443    ,payment_priority_l                payment_priority_t
2444    ,ok_to_pay_flag_l                  ok_to_pay_flag_t
2445    ,always_take_disc_flag_l           always_take_disc_flag_t
2446    ,amount_modified_flag_l            amount_modified_flag_t
2447    ,invoice_amount_l                  invoice_amount_t
2448    ,payment_cross_rate_l              payment_cross_rate_t
2449    ,invoice_exchange_rate_l           invoice_exchange_rate_t
2450    ,set_of_books_id_l                 set_of_books_id_t
2451    ,customer_num_l                    customer_num_t
2452    ,future_pay_due_date_l             future_pay_due_date_t
2453    ,exclusive_payment_flag_l          exclusive_payment_flag_t
2454    ,attribute1_l                      attribute1_t
2455    ,attribute2_l                      attribute1_t
2456    ,attribute3_l                      attribute1_t
2457    ,attribute4_l                      attribute1_t
2458    ,attribute5_l                      attribute1_t
2459    ,attribute6_l                      attribute1_t
2460    ,attribute7_l                      attribute1_t
2461    ,attribute8_l                      attribute1_t
2462    ,attribute9_l                      attribute1_t
2463    ,attribute10_l                     attribute1_t
2464    ,attribute11_l                     attribute1_t
2465    ,attribute12_l                     attribute1_t
2466    ,attribute13_l                     attribute1_t
2467    ,attribute14_l                     attribute1_t
2468    ,attribute15_l                     attribute1_t
2469    ,attribute_category_l              attribute_category_t
2470    ,org_id_l                          org_id_t
2471    ,payment_currency_code_l           payment_currency_code_t
2472    ,external_bank_account_id_l        external_bank_account_id_t
2473    ,legal_entity_id_l                 legal_entity_id_t
2474    ,global_attribute1_l               global_attribute1_t
2475    ,global_attribute2_l               global_attribute1_t
2476    ,global_attribute3_l               global_attribute1_t
2477    ,global_attribute4_l               global_attribute1_t
2478    ,global_attribute5_l               global_attribute1_t
2479    ,global_attribute6_l               global_attribute1_t
2480    ,global_attribute7_l               global_attribute1_t
2481    ,global_attribute8_l               global_attribute1_t
2482    ,global_attribute9_l               global_attribute1_t
2483    ,global_attribute10_l              global_attribute1_t
2484    ,global_attribute11_l              global_attribute1_t
2485    ,global_attribute12_l              global_attribute1_t
2486    ,global_attribute13_l              global_attribute1_t
2487    ,global_attribute14_l              global_attribute1_t
2488    ,global_attribute15_l              global_attribute1_t
2489    ,global_attribute16_l              global_attribute1_t
2490    ,global_attribute17_l              global_attribute1_t
2491    ,global_attribute18_l              global_attribute1_t
2492    ,global_attribute19_l              global_attribute1_t
2493    ,global_attribute20_l              global_attribute1_t
2494    ,global_attribute_category_l       global_attribute_category_t
2495    ,amount_paid_l                     amount_paid_t
2496    ,discount_amount_taken_l           discount_amount_taken_t
2497    ,amount_remaining_l                amount_remaining_t
2498    ,discount_amount_remaining_l       discount_amount_remaining_t
2499    ,payment_amount_l                  payment_amount_t
2500    ,discount_amount_l                 discount_amount_t
2501    ,sequence_num_l                    sequence_num_t
2502    ,dont_pay_reason_code_l            dont_pay_reason_code_t
2503    ,check_number_l                    check_number_t
2504    ,bank_account_type_l               bank_account_type_t
2505    ,original_invoice_id_l             original_invoice_id_t
2506    ,original_payment_num_l            original_payment_num_t
2507    ,bank_account_num_l                bank_account_num_t
2508    ,bank_num_l                        bank_num_t
2509    ,proposed_payment_amount_l         proposed_payment_amount_t
2510    ,pay_selected_check_id_l           pay_selected_check_id_t
2511    ,print_selected_check_id_l         print_selected_check_id_t
2512    ,withhloding_amount_l              withholding_amount_t
2513    ,invoice_payment_id_l              invoice_payment_id_t
2514    ,dont_pay_description_l            dont_pay_description_t
2515    ,transfer_priority_l               transfer_priority_t
2516    ,iban_number_l                     iban_number_t
2517    ,payment_grouping_number_l         payment_grouping_number_t
2518    ,payment_exchange_rate_l           payment_exchange_rate_t
2519    ,payment_exchange_rate_type_l      payment_exchange_rate_type_t
2520    ,payment_exchange_date_l           payment_exchange_date_t
2521     --Start 8217641
2522     ,remit_to_supplier_name_l         remit_to_supplier_name_t
2523     ,remit_to_supplier_id_l           remit_to_supplier_id_t
2524     ,remit_to_supplier_site_l         remit_to_supplier_site_t
2525     ,remit_to_supplier_site_id_l      remit_to_supplier_site_id_t
2526      --End 8217641
2527    );
2528 
2529   sel_inv_list    sel_inv_rec_type;
2530 
2531   /* Added for bug#8461050 Start */
2532   l_schema             VARCHAR2(30);
2533   l_status             VARCHAR2(1);
2534   l_industry           VARCHAR2(1);
2535   /* Added for bug#8461050 End */
2536 
2537   BEGIN
2538 
2539 
2540 
2541   l_current_calling_sequence := 'select invoices';
2542 
2543   l_debug_info := 'Check to see if creating checkrun from template';
2544   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
2545     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
2546   END IF;
2547 
2548   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2549     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
2550   END IF;
2551 
2552 
2553 
2554   ---if this is a repeating request call a procedure to insert into ap_inv_selection_criteria_all
2555   --the hld says to validate the parameters, but this should probably be done
2556   --in the value sets or setup for the pay process request
2557 
2558 
2559   --l_checkrun_id will be assigned from create_checkrun if this is a
2560   --repeating request
2561   l_checkrun_id := to_number(p_checkrun_id);
2562 
2563 
2564   if p_template_id is not null then
2565 
2566     l_template_id  := to_number(p_template_id);
2567     l_payment_date := FND_DATE.CANONICAL_TO_DATE(P_payment_date);
2568     l_pay_thru_date := FND_DATE.CANONICAL_TO_DATE(P_pay_thru_date);
2569     l_pay_from_date  := FND_DATE.CANONICAL_TO_DATE(P_pay_from_date);
2570 
2571     create_checkrun(l_checkrun_id,
2572                     l_template_id,
2573                     L_payment_date,
2574                     L_pay_thru_date,
2575                     L_pay_from_date,
2576                     l_current_calling_sequence);
2577 
2578   end if;
2579 
2580 
2581 
2582   --get data from ap_inv_selection_criteria
2583 
2584 
2585   l_debug_info := 'Select data from ap_invoice_selection_criteria';
2586   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
2587     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
2588   END IF;
2589 
2590   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2591     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
2592   END IF;
2593 
2594 
2595   BEGIN
2596       -- Bug 5460584. Added trun for check_date, pay_thru_date, pay_from_date
2597       --
2598       -- Bug8637005, added a few more columns to fetch date parameters in
2599       -- 'DD-MM-YYYY' format, for dynamic sql binds
2600       --
2601     SELECT
2602         trunc(check_date),
2603         to_char(check_date, 'DD-MM-YYYY'),
2604         trunc(pay_thru_date),
2605         to_char(pay_thru_date, 'DD-MM-YYYY'),
2606         NVL(hi_payment_priority,1),
2607         NVL(low_payment_priority,99),
2608         DECODE(pay_only_when_due_flag,'Y',
2609                   to_date('01/01/80','MM/DD/RR'),
2610                   trunc(pay_thru_date)),
2611         DECODE(pay_only_when_due_flag,'Y',
2612                '01-01-1980',
2613                to_char(pay_thru_date, 'DD-MM-YYYY')),
2614         DECODE(status,'SELECTING','N','Y'),
2615         nvl(zero_amounts_allowed,'N'),
2616         nvl(zero_invoices_allowed,'N'),
2617         invoice_batch_id,
2618         vendor_id,
2619         checkrun_name,
2620         trunc(pay_from_date),
2621         to_char(pay_from_date, 'DD-MM-YYYY'),
2622         inv_exchange_rate_type,
2623         payment_method_code,
2624         vendor_type_lookup_code,
2625         ou_group_option,
2626         le_group_option,
2627         currency_group_option,
2628         pay_group_option,
2629         exchange_rate_type,
2630         payables_review_settings,
2631         bank_account_id, --4710933
2632         payment_profile_id,
2633         max_payment_amount,
2634         min_check_amount,
2635         payments_review_settings,
2636         --decode(payment_profile_id,null,'N',nvl(create_instrs_flag,'N')),
2637 	nvl(create_instrs_flag,'N'),  -- Commented and added for bug 8925444
2638         party_id,
2639         payment_document_id,
2640         /*bug 7519277*/
2641                 ATTRIBUTE_CATEGORY,
2642                 ATTRIBUTE1,
2643                 ATTRIBUTE2,
2644                 ATTRIBUTE3,
2645                 ATTRIBUTE4,
2646                 ATTRIBUTE5,
2647                 ATTRIBUTE6,
2648                 ATTRIBUTE7,
2649                 ATTRIBUTE8,
2650                 ATTRIBUTE9,
2651                 ATTRIBUTE10,
2652                 ATTRIBUTE11,
2653                 ATTRIBUTE12,
2654                 ATTRIBUTE13,
2655                 ATTRIBUTE14,
2656                 ATTRIBUTE15
2657         /*bug 7519277*/
2658     INTO
2659         l_check_date,
2660         l_check_date_char,
2661         l_pay_thru_date,
2662         l_pay_thru_date_char,
2663         l_hi_payment_priority,
2664         l_low_payment_priority,
2665         l_disc_pay_thru_date,
2666         l_disc_pay_thru_char,
2667         l_abort,
2668         l_zero_amounts_allowed,
2669         l_zero_invoices_allowed,
2670         l_invoice_batch_id,
2671         l_inv_vendor_id,
2672         l_payment_process_request_name,
2673         l_pay_from_date,
2674         l_pay_from_date_char,
2675         l_inv_exchange_rate_type,
2676         l_payment_method,
2677         l_supplier_type,
2678         l_ou_group_option,
2679         l_le_group_option,
2680         l_currency_group_option,
2681         l_pay_group_option,
2682         l_batch_exchange_rate_type,
2683         l_payables_review_settings,
2684         l_bank_account_id ,
2685         l_payment_profile_id,
2686         l_max_payment_amount,
2687         l_min_check_amount,
2688         l_pay_review_settings_flag,
2689         l_create_instrs_flag,
2690         l_party_id,
2691         l_payment_document_id,
2692                 /* bug 7519277*/
2693                 l_ATTRIBUTE_CATEGORY,
2694                 l_ATTRIBUTE1,
2695                 l_ATTRIBUTE2,
2696                 l_ATTRIBUTE3,
2697                 l_ATTRIBUTE4,
2698                 l_ATTRIBUTE5,
2699                 l_ATTRIBUTE6,
2700                 l_ATTRIBUTE7,
2701                 l_ATTRIBUTE8,
2702                 l_ATTRIBUTE9,
2703                 l_ATTRIBUTE10,
2704                 l_ATTRIBUTE11,
2705                 l_ATTRIBUTE12,
2706                 l_ATTRIBUTE13,
2707                 l_ATTRIBUTE14,
2708                 l_ATTRIBUTE15
2709     FROM   ap_inv_selection_criteria_all
2710     WHERE  checkrun_id  = l_checkrun_id
2711     AND    status = 'UNSTARTED';
2712 
2713   EXCEPTION
2714      WHEN NO_DATA_FOUND then
2715       l_debug_info := 'Could not find the payment process';
2716       raise SELECTION_FAILURE;
2717   END;
2718 
2719   -- Setting the hint string(bug8637005)
2720   /* Commented for bug#12773508 Start
2721   IF l_pay_group_option <> 'ALL' THEN
2722      l_hint := ' / *+ index(ai AP_INVOICES_N3) * / ';
2723   ELSE
2724      l_hint := ' ';
2725   END IF;
2726   Commented for bug#12773508 End */
2727 
2728   /* Bug 9750106 - updating check_date and pay_thru_date as done in bug6764140 */
2729   UPDATE ap_inv_selection_criteria_all
2730   set status = 'SELECTING',
2731       check_date = TRUNC(check_date),
2732       pay_thru_date = TRUNC(pay_thru_date),
2733       -- Bug 7492768 We need to reset the inv_awt_exists_flag which indicates if the
2734       -- check run contains invoice that has awt.
2735       inv_awt_exists_flag = 'N'
2736   where checkrun_id = l_checkrun_id;
2737 
2738 
2739 
2740   l_debug_info := 'l_checkrun_id = '|| to_char(l_checkrun_id);
2741   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
2742     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
2743   END IF;
2744 
2745   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2746     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
2747   END IF;
2748 
2749 
2750   l_debug_info := 'See if encumbrances are turned on';
2751   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
2752     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
2753   END IF;
2754 
2755   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2756     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
2757   END IF;
2758 
2759   SELECT count(*)
2760   INTO   l_encumbrance_flag
2761   FROM   financials_system_parameters
2762   WHERE  nvl(purch_encumbrance_flag,'N') = 'Y'
2763   AND    (org_id in (select org_id
2764                      from   AP_OU_GROUP
2765                      where  checkrun_id = l_checkrun_id)
2766           or l_ou_group_option = 'ALL')
2767   AND    rownum=1;
2768 
2769 
2770 
2771   -- Bug 5646890. Cursor processing with FORALL to make sure update and insert
2772   -- only do one one pass to the tables
2773   -- Based on encumbrances two different cursor will be opened and data will be
2774   -- processed.
2775   --
2776 
2777   /**************************************************************************/
2778   /* Bug8637005                                                             */
2779   /* -----------                                                            */
2780   /* The selection queries for Autoselect have been made dynamic for        */
2781   /* performance improvements, using native dynamic sqls and ref            */
2782   /* cursors.                                                               */
2783   /*                                                                        */
2784   /* Since use of native sql requires a knowledge of the using              */
2785   /* clause and hence the number of binds before hand, please make          */
2786   /* sure that any modifications to the sql string, ensures that            */
2787   /* the number of binds remain constant for all cases of input             */
2788   /* parameters (selection criteria)                                        */
2789   /*                                                                        */
2790   /* Currently this has been achieved using:                                */
2791   /*    nvl(bind, -9999) = -9999                                            */
2792   /*                                                                        */
2793   /* If for some reason it is not feasible to achieve a constant number     */
2794   /* for a later change please consider                                    */
2795   /*   a. Eliminating binds, by joing to ap_invoice_selection_criteria_all  */
2796   /*   b. Using DBMS_SQL                                                    */
2797   /**************************************************************************/
2798 
2799   if l_encumbrance_flag = 1 then
2800 
2801     l_debug_info := 'Open payment schedules cursor - encumbrances are on';
2802     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
2803       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
2804     END IF;
2805 
2806     l_sql_stmt :=
2807         '   SELECT  '||l_hint||
2808         '         :p_checkrun_name                                             checkrun_name '||
2809         '        ,:p_checkrun_id                                               checkrun_id '||
2810         '        ,ps.invoice_id                                               invoice_id '||
2811         '        ,payment_num                                                 payment_num '||
2812         '        ,SYSDATE                                                     last_update_date '||
2813                  -- Bug 7296715
2814                  -- The User Id is hardcoded to 5 (APPSMGR). It is changed to populate correct value.
2815                  -- ,5                                                           last_updated_by
2816         '        ,FND_GLOBAL.USER_ID                                          last_updated_by     '||
2817         '        ,SYSDATE                                                     creation_date '||
2818                  -- Bug 7296715
2819                  -- ,5                                                           created_by
2820         '        ,FND_GLOBAL.USER_ID                                          created_by '||
2821         '        ,NULL                                                        last_update_login '||
2822         '        ,ai.vendor_id                                               vendor_id '||
2823         '        ,ai.vendor_site_id                                          vendor_site_id '||
2824         '        ,suppliers.segment1                                          vendor_num '||
2825                  /* Bug 5620285, Added the following decode */
2826         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2827         '                hzp.party_name, suppliers.vendor_name)               vendor_name '||
2828         '        ,sites.vendor_site_code                                      vendor_site_code '||
2829         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2830         '                hzl.address1, sites.address_line1)                   address_line1 '||
2831         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2832         '                hzl.address2, sites.address_line2)                   address_line2 '||
2833         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2834         '                hzl.address3, sites.address_line3)                   address_line3 '||
2835         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2836         '                hzl.address4, sites.address_line4)                   address_line4 '||
2837         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2838         '                hzl.city, sites.city)                                city '||
2839         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2840         '                hzl.state, sites.state)                              state '||
2841         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2842         '                hzl.postal_code, sites.zip)                          zip '||
2843         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2844         '                hzl.province, sites.province)                        province '||
2845         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
2846         '                hzl.country, sites.country)                          country '||
2847         '        ,sites.attention_ar_flag                                     attention_ar_flag '||
2848         '        ,suppliers.withholding_status_lookup_code                    withholding_status_lookup_code '||
2849         '        ,ai.invoice_num                                             invoice_num '||
2850         '        ,ai.invoice_date                                            invoice_date '||
2851         '        ,DECODE(ai.doc_sequence_id, '||
2852         '                   '''', ai.voucher_num, '||
2853         '                   ai.doc_sequence_value)                           voucher_num '||
2854         '        ,ai.accts_pay_code_combination_id                           ap_ccid '||
2855         '        ,TRUNC(ps.due_date)                                          due_date '||
2856         '        ,DECODE(sites.always_take_disc_flag, '||
2857         '                   ''Y'', TRUNC(ps.due_date), '||
2858         '                   DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
2859         '                               - NVL(ps.discount_date, '||
2860         '                                     to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
2861         '                          -1, ps.discount_date, '||
2862         '                          DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
2863         '                                      -NVL(ps.second_discount_date, '||
2864         '                                           to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
2865         '                                 -1, ps.second_discount_date, '||
2866         '                                 DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
2867         '                                             -NVL(ps.third_discount_date, '||
2868         '                                                    to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
2869         '                                        -1, ps.third_discount_date, '||
2870         '                                        TRUNC(ps.due_date)))))      discount_date '||
2871         /* Commented and added for bug 12409940 */
2872         /*'        ,SUBSTRB(ai.description,1,50)                              invoice_description '|| */
2873 	'        ,ai.description                                             invoice_description '||
2874         '        ,nvl(ps.payment_priority, 99)                               payment_priority '||
2875         '        ,''Y''                                                        ok_to_pay_flag '||
2876         '        ,sites.always_take_disc_flag                                always_take_discount_flag '||
2877         '        ,''N''                                                        amount_modified_flag '||
2878         '        ,ai.invoice_amount                                         invoice_amount '||
2879         '        ,ai.payment_cross_rate                                     payment_cross_rate '||
2880         '        ,DECODE(ai.exchange_rate, '||
2881         '                   NULL, DECODE(ai.invoice_currency_code, '||
2882         '                                asp.base_currency_code, 1, '||
2883         '                                NULL), '||
2884         '                   ai.exchange_rate)                               invoice_exchange_rate '||
2885         '        ,ai.set_of_books_id                                        set_of_books_id '||
2886         '        ,sites.customer_num                                         customer_num '||
2887         '        ,ps.future_pay_due_date                                     future_pay_due_date '||
2888         '        ,ai.exclusive_payment_flag                                 exclusive_payment_flag '||
2889         '        ,ps.attribute1                                              attribute1 '||
2890         '        ,ps.attribute2                                              attribute2 '||
2891         '        ,ps.attribute3                                              attribute3 '||
2892         '        ,ps.attribute4                                              attribute4 '||
2893         '        ,ps.attribute5                                              attribute5 '||
2894         '        ,ps.attribute6                                              attribute6 '||
2895         '        ,ps.attribute7                                              attribute7 '||
2896         '        ,ps.attribute8                                              attribute8 '||
2897         '        ,ps.attribute9                                              attribute9 '||
2898         '        ,ps.attribute10                                             attribute10 '||
2899         '        ,ps.attribute11                                             attribute11 '||
2900         '        ,ps.attribute12                                             attribute12 '||
2901         '        ,ps.attribute13                                             attribure13 '||
2902         '        ,ps.attribute14                                             attribute14 '||
2903         '        ,ps.attribute15                                             attribute15 '||
2904         '        ,ps.attribute_category                                      attribute_category '||
2905         '        ,ai.org_id                                                 org_id '||
2906         '        ,ai.payment_currency_code                                  payment_currency_code '||
2907         '        ,ps.external_bank_account_id                                external_bank_account_id '||
2908         '        ,ai.legal_entity_id                                        legal_entity_id '||
2909                  /* Bug 5192018 we will insert global attribute values from ap_invoices table */
2910         '        ,ai.global_attribute1                                      global_attribute1 '||
2911         '        ,ai.global_attribute2                                      global_attribute2 '||
2912         '        ,ai.global_attribute3                                      global_attribute3 '||
2913         '        ,ai.global_attribute4                                      global_attribute4 '||
2914         '        ,ai.global_attribute5                                      global_attribute5 '||
2915         '        ,ai.global_attribute6                                      global_attribute6 '||
2916         '        ,ai.global_attribute7                                      global_attribute7 '||
2917         '        ,ai.global_attribute8                                      global_attribute8 '||
2918         '        ,ai.global_attribute9                                      global_attribute9 '||
2919         '        ,ai.global_attribute10                                     global_attribute10 '||
2920         '        ,ai.global_attribute11                                     global_attribute11 '||
2921         '        ,ai.global_attribute12                                     global_attribute12 '||
2922         '        ,ai.global_attribute13                                     global_attribute13 '||
2923         '        ,ai.global_attribute14                                     global_attribute14 '||
2924         '        ,ai.global_attribute15                                     global_attribute15 '||
2925         '        ,ai.global_attribute16                                     global_attribute16 '||
2926         '        ,ai.global_attribute17                                     global_attribute17 '||
2927         '        ,ai.global_attribute18                                     global_attribute18 '||
2928         '        ,ai.global_attribute19                                     global_attribute19 '||
2929         '        ,ai.global_attribute20                                     global_attribute20 '||
2930         '        ,ai.global_attribute_category                              global_attribute_category '||-- end of bug 5192018
2931         '        ,Null                                                       amount_paid '||
2932         '        ,Null                                                       discount_amount_taken '||
2933         '        ,Null                                                       amount_remaining '||
2934         '        ,Null                                                       discount_amount_remaining '||
2935         '        ,Null                                                       payment_amount '||
2936         '        ,Null                                                       discount_amount  '||
2937         '        ,Null                                                       sequence_num    '||
2938         '        ,Null                                                       done_pay_reason_code '||
2939         '        ,Null                                                       check_number   '||
2940         '        ,Null                                                       bank_account_type  '||
2941         '        ,Null                                                       original_invoice_id '||
2942         '        ,Null                                                       original_payment_num '||
2943         '        ,Null                                                       bank_account_num '||
2944         '        ,Null                                                       bank_num '||
2945         '        ,Null                                                       proposed_payment_amount '||
2946         '        ,Null                                                       pay_selected_check_id '||
2947         '        ,Null                                                       print_selected_check_id '||
2948         '        ,Null                                                       withholding_amount '||
2949         '        ,Null                                                       invoice_payment_id '||
2950         '        ,Null                                                       dont_pay_description '||
2951         '        ,Null                                                       transfer_priority '||
2952         '        ,Null                                                       iban_number '||
2953         '        ,Null                                                       payment_grouping_number '||
2954         '        ,Null                                                       payment_exchange_rate '||
2955         '        ,Null                                                       payment_exchange_rate_type '||
2956         '        ,Null                                                       payment_exchange_date '||
2957                   -- Start of 8217641
2958         '        ,ps.remit_to_supplier_name                                  remit_to_supplier_name                      '||
2959         '        ,ps.remit_to_supplier_id                                    remit_to_supplier_id '||
2960         '        ,ps.remit_to_supplier_site                                  remit_to_supplier_site '||
2961         '        ,ps.remit_to_supplier_site_id                               remit_to_supplier_site_id '||
2962                  --End 8217641
2963         '   FROM   ap_supplier_sites_all sites, '||
2964         '          ap_suppliers suppliers, '||
2965         '          ap_invoices ai, '||               /* inv, '||Commented for bug#9182499 --Bug6040657. Changed from ap_invoices_all to ap_invoices */
2966         '          ap_payment_schedules_all ps, '||
2967         '          ap_system_parameters_all asp, '||
2968         '          hz_parties hzp, '||
2969         '          hz_party_sites hzps,          '||-- Bug 5620285
2970         '          hz_locations   hzl            '||-- Bug 5620285
2971         '   WHERE  ps.checkrun_id is null        '||-- Bug 5705276. Regression
2972         '      AND ((due_date <= to_date(:p_pay_thru_date, ''DD-MM-YYYY'') +0/24 and '||--Bug 8708165
2973         '               due_date >= nvl(to_date(:p_pay_from_date, ''DD-MM-YYYY'') + 0/24,due_date)) '||
2974         '              OR '||
2975         '               DECODE(NVL(sites.pay_date_basis_lookup_code,''DISCOUNT''), '||
2976         '                    ''DISCOUNT'', '||
2977         '                    DECODE(sites.always_take_disc_flag, '||
2978         '                           ''Y'', ps.discount_date, '||
2979         '                           DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
2980         '                                  -NVL(ps.discount_date, '||
2981         '                                       to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
2982         '                                  -1, ps.discount_date, '||
2983         '                                  DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
2984         '                                              -NVL(ps.second_discount_date, '||
2985         '                                                   to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
2986         '                                         -1, ps.second_discount_date, '||
2987         '                                         DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
2988         '                                                     -NVL(ps.third_discount_date, '||
2989         '                                                         to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
2990         '                                                -1, ps.third_discount_date, '||
2991         '                                                TRUNC(ps.due_date))))), '||
2992         '                    TRUNC(due_date)) '||
2993         '                    BETWEEN DECODE(sites.always_take_disc_flag,''Y'', '||
2994         '                                    nvl(to_date(:p_pay_from_date, ''DD-MM-YYYY''), TO_DATE(''1901'',''YYYY'')), '||
2995         '                                    to_date(:p_check_date, ''DD-MM-YYYY'')) '||
2996         '                            AND to_date(:p_disc_pay_thru_date, ''DD-MM-YYYY'')) '||
2997         /*'       AND    ps.payment_status_flag BETWEEN ''N'' AND ''P'' '||
2998           '       AND    ai.payment_status_flag BETWEEN ''N'' AND ''P'' '|| Commented for bug#11848050 */
2999         '       AND    ps.payment_status_flag IN (''N'', ''P'') '|| /* Added for bug#11848050 */
3000         '       AND    ai.payment_status_flag IN (''N'', ''P'') '|| /* Added for bug#11848050 */
3001         '       AND    nvl(ai.force_revalidation_flag, ''N'') = ''N''     '||--bug7244642
3002         '       AND    NVL(ps.payment_priority, 99) BETWEEN :p_hi_payment_priority '||
3003         '                                              AND :p_lo_payment_priority '||
3004         '       AND    ai.cancelled_date is null '||
3005                 -- Bug 7167192 Added decode and outer join
3006                 -- hzp and hzps data is required only for Payment Requests.
3007         '       AND    hzp.party_id(+) = decode(ai.invoice_type_lookup_code,  '||
3008         '                                       ''PAYMENT REQUEST'', ai.party_id '||
3009         '                                                        , -99) '||
3010         '       AND    NVL(ps.hold_flag, ''N'') = ''N'' '||
3011         '       AND    NVL(sites.hold_all_payments_flag, ''N'') = ''N'' '||
3012         '       AND    ai.invoice_id = ps.invoice_id '||
3013         '       AND    sites.vendor_id(+) = ai.vendor_id '||
3014         '       AND    sites.vendor_site_id(+) = ai.vendor_site_id '||
3015         '       AND    suppliers.vendor_id(+) = ai.vendor_id '||
3016         '       AND    asp.org_id = ai.org_id '||
3017         '       AND    hzp.party_id = hzps.party_id (+)   '||-- Bug 5620285
3018                 --Bug 5929034: An employee does not have a hz_party_site, modifying query to reflect the same
3019                 --   AND    nvl(hzps.party_site_id,-99)  = decode(suppliers.vendor_type_lookup_code,''EMPLOYEE'',-99,nvl(inv.party_site_id, hzps.party_site_id))  -- Bug 5620285
3020                 -- Bug 6662382
3021                 -- Bug 7167192 - Query condition is now based on whether the Invoice
3022                 --               is a Payment Request. Supplier type does not matter.
3023                 --AND    NVL(hzps.party_site_id,-99)  = DECODE(suppliers.vendor_type_lookup_code,''EMPLOYEE'', COALESCE(inv.party_site_id, hzps.party_site_id,-99),
3024                 --                                             NVL(inv.party_site_id, hzps.party_site_id))
3025         '       AND    NVL(hzps.party_site_id,-99) = NVL(decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', ai.party_site_id, -99), NVL(hzps.party_site_id,-99)) '||
3026                 -- Bug 7167192
3027         '       AND    nvl(hzps.location_id,-99) = hzl.location_id (+) '||-- Bug 5620285
3028                 --End of 5929034
3029         '       AND    fv_econ_benf_disc.ebd_check(:p_checkrun_name, ai.invoice_id, '||
3030         '                                   to_date(:p_check_date, ''DD-MM-YYYY''), due_date, ps.discount_amount_available, ps.discount_date) = ''Y'' ';
3031 
3032                 -- Bug 7265013 starts
3033                 -- AND    AP_INVOICES_PKG.get_wfapproval_status(inv.invoice_id, inv.org_id) in
3034                 --         (''NOT REQUIRED'',''WFAPPROVED'',''MANUALLY APPROVED'')*/
3035                  -- Bug 7265013 ends
3036 
3037      IF l_invoice_batch_id IS NOT NULL THEN
3038           l_sql_stmt := l_sql_stmt||'              AND  ai.batch_id = :p_inv_batch_id ';
3039      ELSE
3040           l_sql_stmt := l_sql_stmt||'              AND  nvl(:p_inv_batch_id, -9999) = -9999 ';
3041      END IF;
3042 
3043      IF l_inv_vendor_id IS NOT NULL THEN
3044           l_sql_stmt := l_sql_stmt||'       AND    ai.vendor_id = :p_inv_vendor_id  ';
3045      ELSE
3046           l_sql_stmt := l_sql_stmt||'       AND    nvl(:p_inv_vendor_id, -9999) = -9999 ';
3047      END IF;
3048 
3049      IF l_party_id IS NOT NULL THEN
3050            l_sql_stmt := l_sql_stmt||'       AND    ai.party_id = :p_party_id ';
3051      ELSE
3052            l_sql_stmt := l_sql_stmt||'       AND    nvl(:p_party_id, -9999) = -9999 ';
3053      END IF;
3054 
3055                 -- Bug 5507013 hkaniven start --
3056      l_sql_stmt := l_sql_stmt||
3057         '       AND    (( :p_inv_exc_rate_type = ''IS_USER'' AND NVL(ai.exchange_rate_type,''NOT USER'') = ''User'' ) '||
3058         '               OR (:p_inv_exc_rate_type = ''IS_NOT_USER'' AND NVL(ai.exchange_rate_type,''NOT USER'') <> ''User'') '||
3059         '               OR (:p_inv_exc_rate_type IS NULL)) '
3060                 -- Bug 5507013 hkaniven end --
3061         /*'       AND    ps.payment_method_code = nvl(:p_payment_method, ps.payment_method_code) '||
3062           '       AND    nvl(suppliers.vendor_type_lookup_code,-99) = '||
3063           '                   nvl(:p_supplier_type, nvl(suppliers.vendor_type_lookup_code,-99)) '||
3064         '       AND    (ai.legal_entity_id in (select /*+ push_subq * / legal_entity_id '||
3065         '                                       from   ap_le_group '||
3066         '                                       where  checkrun_id = :p_checkrun_id) '||
3067         '               or :p_le_group_option = ''ALL'') '||
3068         '       AND    (ai.org_id in (select /*+ push_subq * / org_id '||
3069         '                              from   AP_OU_GROUP '||
3070         '                              where  checkrun_id = :p_checkrun_id) '||
3071         '               or :p_ou_group_option = ''ALL'') '||
3072         '       AND    (ai.payment_currency_code in (select /*+ push_subq * / currency_code '||
3073         '                                            from   AP_CURRENCY_GROUP '||
3074         '                                            where  checkrun_id = :p_checkrun_id) '||
3075         '               or :p_curr_group_option = ''ALL'') '         Commented for bug#11848050 */;
3076 
3077      /* Code Added for bug#11848050 Start */
3078      IF l_payment_method IS NOT NULL THEN
3079         l_sql_stmt := l_sql_stmt || '    AND ps.payment_method_code = :p_payment_method ';
3080      ELSE
3081         l_sql_stmt := l_sql_stmt || '    AND nvl(:p_payment_method, -9999) = -9999';
3082      END IF;
3083 
3084      IF l_supplier_type IS NOT NULL THEN
3085         l_sql_stmt := l_sql_stmt || '    AND suppliers.vendor_type_lookup_code = :p_supplier_type ';
3086      ELSE
3087         l_sql_stmt := l_sql_stmt || '    AND nvl(:p_supplier_type, -9999) = -9999';
3088      END IF;
3089      /* Code Added for bug#11848050 End */
3090 
3091      IF l_pay_group_option <> 'ALL' THEN
3092           l_sql_stmt := l_sql_stmt||
3093             /* Commented for Bug#9182499 Start
3094             '       AND    inv.pay_group_lookup_code in (select / *+ leading(apg) cardinality(apg 1) * / vendor_pay_group '||
3095             '                                            from   AP_PAY_GROUP apg'|| --bug9087739, added alias for  AP_PAY_GROUP
3096             '                                            where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id) ';
3097             Commented for Bug#9182499 End */
3098             /* Added for Bug#9182499 Start */
3099             '       AND (ai.pay_group_lookup_code, ai.org_id) in '||
3100             '                       ( select  '|| /* Added for bug#12773508 */
3101             /* '                       ( select / *+ leading(apg) cardinality(apg 1) * / '|| Commented for bug#12773508 */
3102             '                                apg.vendor_pay_group, mo.ORGANIZATION_ID '||
3103             '                           from AP_PAY_GROUP apg, MO_GLOB_ORG_ACCESS_TMP mo '||
3104             '                          where checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id '||
3105             '                            AND ai.org_id = mo.organization_id ) '; /* Added for bug#11848050 */
3106             /* Added for Bug#9182499 End */
3107      ELSE
3108           l_sql_stmt := l_sql_stmt||
3109             '       AND    :p_checkrun_id = :p_checkrun_id   ';
3110 
3111      END IF;
3112 
3113      /* Added for bug#11848050 Start */
3114      IF l_le_group_option <> 'ALL' THEN
3115         l_sql_stmt := l_sql_stmt||
3116             '       AND  ai.legal_entity_id in '||
3117             '               (select /*+ push_subq */ legal_entity_id '||
3118             '                  from   ap_le_group                    '||
3119             '                 where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id)   ';
3120      ELSE
3121         l_sql_stmt := l_sql_stmt||
3122             '       AND    :p_checkrun_id = :p_checkrun_id   ';
3123      END IF;
3124 
3125      --bug14160441 remove push_subq hint, add no_push_subq and no_unnest
3126      IF l_ou_group_option <> 'ALL' THEN
3127         l_sql_stmt := l_sql_stmt||
3128             '       AND  ai.org_id in '||
3129             '               (select /*+ no_push_subq no_unnest*/ org_id '||
3130             '                  from   AP_OU_GROUP                    '||
3131             '                 where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id)   ';
3132      ELSE
3133         l_sql_stmt := l_sql_stmt||
3134             '       AND    :p_checkrun_id = :p_checkrun_id   ';
3135      END IF;
3136 
3137      --bug14160441 remove push_subq hint, add no_unnest
3138      IF l_currency_group_option <> 'ALL' THEN
3139         l_sql_stmt := l_sql_stmt||
3140             '       AND  ai.payment_currency_code in '||
3141             '               (select /*+ no_unnest */ currency_code '||
3142             '                  from   AP_CURRENCY_GROUP                    '||
3143             '                 where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id)   ';
3144      ELSE
3145         l_sql_stmt := l_sql_stmt||
3146             '       AND    :p_checkrun_id = :p_checkrun_id   ';
3147      END IF;
3148      /* Added for bug#11848050 End */
3149 
3150      l_sql_stmt := l_sql_stmt||
3151         '       AND    ((:p_zero_inv_allowed = ''N'' AND ps.amount_remaining <> 0) OR '||
3152         '                :p_zero_inv_allowed = ''Y'') '||
3153                 --Bug 6342390 Added the clause below.
3154                 --Commented the fix for the bug6342390, bug6365720
3155                  /* AND NOT EXISTS (SELECT ''Invoice is not fully approved''
3156                                 FROM ap_invoice_distributions_all D2
3157                                 WHERE D2.invoice_id = inv.invoice_id
3158                                 AND NVL(D2.match_status_flag, ''N'') in (''N'', ''S''))*/
3159                 --bug6365720
3160                 -- Bug 7265013 starts
3161         /* Bug 13901772
3162 	'       AND EXISTS ( '||
3163         '       SELECT 1 '||
3164         '       FROM   sys.dual '||
3165         '       WHERE  AP_INVOICES_PKG.get_wfapproval_status(ai.invoice_id, ai.org_id) in '||
3166         '               (''NOT REQUIRED'',''WFAPPROVED'',''MANUALLY APPROVED'') '||
3167         '       ) '||
3168 	*/
3169         '      AND ai.wfapproval_status in (''NOT REQUIRED'',''WFAPPROVED'',''MANUALLY APPROVED'')  '||
3170 	'      AND NOT EXISTS (select 1 from ap_invoice_lines_all ail '||
3171 	'                       where ai.invoice_id = ail.invoice_id  '||
3172 	'                         and ail.wfapproval_status in (''NEEDS WFREAPPROVAL'',''REJECTED'',''INITIATED''))  '||
3173                 -- Bug 7265013 ends
3174                 -- Bug 11816573. Removed the push predicates.
3175         '       AND NOT EXISTS (SELECT /*+ no_unnest */ ''Unreleased holds exist'' '|| /* Added hint for bug#12773508 */
3176         '                       FROM ap_holds H '||
3177         '                       WHERE H.invoice_id = ai.invoice_id '||
3178         '                       AND H.release_lookup_code is null) '||
3179 		/* Added for bug 13901772 */
3180 	   '       AND NOT EXISTS (SELECT  ''Invoice is not fully approved'' '||
3181            '                       FROM ap_invoice_distributions_all D2 '||
3182            '                       WHERE D2.invoice_id = ai.invoice_id '||
3183            '                       AND NVL(D2.match_status_flag, ''N'') in (''N'', ''S'', ''T'')) '||
3184            /* Bug 12799362. Start. */
3185  	   '       AND NOT EXISTS (SELECT ''Line without distribution''  '||
3186  	   '                       FROM   ap_invoice_lines_all ail  '||
3187  	   '                       WHERE  ail.invoice_id = ai.invoice_id  '||
3188  	   '                       AND ail.amount <> 0  ' ||
3189  	   '                       AND NOT EXISTS (SELECT ''No Distributions''  '||
3190  	   '                                       FROM   ap_invoice_distributions_all aid '||
3191  	   '                                       WHERE  ail.invoice_id = aid.invoice_id  '||
3192  	   '                                       AND    ail.line_number = aid.invoice_line_number '||
3193  	   '                                       ) '||
3194  	   '                      ) '||
3195         /* Commented for bug 13901772 */
3196         /*'       AND NOT EXISTS (SELECT /*+ no_unnest */ /*''Invoice is not fully approved''  '|| /* Added hint for bug#12773508 */
3197         /*'                       FROM ap_invoices_derived_v AIDV '||
3198         '                       WHERE AIDV.invoice_id = ai.invoice_id '||
3199         '                       AND AIDV.approval_status_lookup_code IN  '||
3200         '                               (''NEVER APPROVED'', ''NEEDS REAPPROVAL'', ''UNAPPROVED'')) '||
3201 	*/
3202                 -- Bug 11816573. Changed hint from push_subq to no_unnest.
3203         '       AND EXISTS (SELECT /*+ no_unnest */ ''Distributions exist'' '||
3204         '                     FROM   ap_invoice_distributions D4 '||
3205 				/* Added FOR UPDATE for bug 13321621 */
3206                         /* Added SKIP LOCKED for bug 14277979 */
3207         '                    WHERE  D4.invoice_id = ai.invoice_id) FOR UPDATE OF ps.checkrun_id SKIP LOCKED';
3208                 -- bug 6456537
3209         /*     AND NOT EXISTS (SELECT ''CCR EXPIRED''
3210                                FROM FV_TPP_ASSIGNMENTS_V TPP
3211                                WHERE TPP.beneficiary_party_id = inv.party_id
3212                                AND TPP.beneficiary_party_site_id = inv.party_site_id
3213                              AND NVL(TPP.fv_tpp_pay_flag, ''Y'') = ''N'') ; bug8691645 */
3214                 -- 6456537 Checking the validity of CCR of the Third Party for
3215                 -- supplier. If the CCR is Invalid then the invoice document
3216                 -- is not consider for the Payment(Auto Select)
3217 
3218     IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3219       FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
3220     END IF;
3221 
3222     OPEN refcur FOR l_sql_stmt USING
3223                                     l_payment_process_request_name,
3224                                     l_checkrun_id,
3225                                     l_check_date_char,
3226                                     l_check_date_char,
3227                                     l_check_date_char,
3228                                     l_check_date_char,
3229                                     l_check_date_char,
3230                                     l_check_date_char,
3231                                     l_pay_thru_date_char,
3232                                     l_pay_from_date_char,
3233                                     l_check_date_char,
3234                                     l_check_date_char,
3235                                     l_check_date_char,
3236                                     l_check_date_char,
3237                                     l_check_date_char,
3238                                     l_check_date_char,
3239                                     l_pay_from_date_char,
3240                                     l_check_date_char,
3241                                     l_disc_pay_thru_char,
3242                                     l_hi_payment_priority,
3243                                     l_low_payment_priority,
3244                                     l_payment_process_request_name,
3245                                     l_check_date_char,
3246                                     l_invoice_batch_id,
3247                                     l_inv_vendor_id,
3248                                     l_party_id,
3249                                     l_inv_exchange_rate_type,
3250                                     l_inv_exchange_rate_type,
3251                                     l_inv_exchange_rate_type,
3252                                     l_payment_method,  /* Changed the sequence for bug#11848050 */
3253                                     l_supplier_type,   /* Changed the sequence for bug#11848050 */
3254                                     l_checkrun_id,
3255                                     l_checkrun_id,
3256                                     l_checkrun_id,
3257                                     l_checkrun_id,
3258                                     l_checkrun_id,
3259                                     l_checkrun_id,
3260                                     l_checkrun_id,
3261                                     l_checkrun_id,
3262                                     l_zero_invoices_allowed,
3263                                     l_zero_invoices_allowed;
3264       LOOP
3265         FETCH refcur
3266         BULK COLLECT INTO
3267                sel_inv_list.checkrun_name_l
3268               ,sel_inv_list.checkrun_id_l
3269               ,sel_inv_list.invoice_id_l
3270               ,sel_inv_list.payment_num_l
3271               ,sel_inv_list.last_update_date_l
3272               ,sel_inv_list.last_updated_by_l
3273               ,sel_inv_list.creation_date_l
3274               ,sel_inv_list.created_by_l
3275               ,sel_inv_list.last_update_login_l
3276               ,sel_inv_list.vendor_id_l
3277               ,sel_inv_list.vendor_site_id_l
3278               ,sel_inv_list.vendor_num_l
3279               ,sel_inv_list.vendor_name_l
3280               ,sel_inv_list.vendor_site_code_l
3281               ,sel_inv_list.address_line1_l
3282               ,sel_inv_list.address_line2_l
3283               ,sel_inv_list.address_line3_l
3284               ,sel_inv_list.address_line4_l
3285               ,sel_inv_list.city_l
3286               ,sel_inv_list.state_l
3287               ,sel_inv_list.zip_l
3288               ,sel_inv_list.province_l
3289               ,sel_inv_list.country_l
3290               ,sel_inv_list.attention_ar_flag_l
3291               ,sel_inv_list.withholding_status_lookup_l
3292               ,sel_inv_list.invoice_num_l
3293               ,sel_inv_list.invoice_date_l
3294               ,sel_inv_list.voucher_num_l
3295               ,sel_inv_list.ap_ccid_l
3296               ,sel_inv_list.due_date_l
3297               ,sel_inv_list.discount_date_l
3298               ,sel_inv_list.invoice_description_l
3299               ,sel_inv_list.payment_priority_l
3300               ,sel_inv_list.ok_to_pay_flag_l
3301               ,sel_inv_list.always_take_disc_flag_l
3302               ,sel_inv_list.amount_modified_flag_l
3303               ,sel_inv_list.invoice_amount_l
3304               ,sel_inv_list.payment_cross_rate_l
3305               ,sel_inv_list.invoice_exchange_rate_l
3306               ,sel_inv_list.set_of_books_id_l
3307               ,sel_inv_list.customer_num_l
3308               ,sel_inv_list.future_pay_due_date_l
3309               ,sel_inv_list.exclusive_payment_flag_l
3310               ,sel_inv_list.attribute1_l
3311               ,sel_inv_list.attribute2_l
3312               ,sel_inv_list.attribute3_l
3313               ,sel_inv_list.attribute4_l
3314               ,sel_inv_list.attribute5_l
3315               ,sel_inv_list.attribute6_l
3316               ,sel_inv_list.attribute7_l
3317               ,sel_inv_list.attribute8_l
3318               ,sel_inv_list.attribute9_l
3319               ,sel_inv_list.attribute10_l
3320               ,sel_inv_list.attribute11_l
3321               ,sel_inv_list.attribute12_l
3322               ,sel_inv_list.attribute13_l
3323               ,sel_inv_list.attribute14_l
3324               ,sel_inv_list.attribute15_l
3325               ,sel_inv_list.attribute_category_l
3326               ,sel_inv_list.org_id_l
3327               ,sel_inv_list.payment_currency_code_l
3328               ,sel_inv_list.external_bank_account_id_l
3329               ,sel_inv_list.legal_entity_id_l
3330               ,sel_inv_list.global_attribute1_l
3331               ,sel_inv_list.global_attribute2_l
3332               ,sel_inv_list.global_attribute3_l
3333               ,sel_inv_list.global_attribute4_l
3334               ,sel_inv_list.global_attribute5_l
3335               ,sel_inv_list.global_attribute6_l
3336               ,sel_inv_list.global_attribute7_l
3337               ,sel_inv_list.global_attribute8_l
3338               ,sel_inv_list.global_attribute9_l
3339               ,sel_inv_list.global_attribute10_l
3340               ,sel_inv_list.global_attribute11_l
3341               ,sel_inv_list.global_attribute12_l
3342               ,sel_inv_list.global_attribute13_l
3343               ,sel_inv_list.global_attribute14_l
3344               ,sel_inv_list.global_attribute15_l
3345               ,sel_inv_list.global_attribute16_l
3346               ,sel_inv_list.global_attribute17_l
3347               ,sel_inv_list.global_attribute18_l
3348               ,sel_inv_list.global_attribute19_l
3349               ,sel_inv_list.global_attribute20_l
3350               ,sel_inv_list.global_attribute_category_l
3351               ,sel_inv_list.amount_paid_l
3352               ,sel_inv_list.discount_amount_taken_l
3353               ,sel_inv_list.amount_remaining_l
3354               ,sel_inv_list.discount_amount_remaining_l
3355               ,sel_inv_list.payment_amount_l
3356               ,sel_inv_list.discount_amount_l
3357               ,sel_inv_list.sequence_num_l
3358               ,sel_inv_list.dont_pay_reason_code_l
3359               ,sel_inv_list.check_number_l
3360               ,sel_inv_list.bank_account_type_l
3361               ,sel_inv_list.original_invoice_id_l
3362               ,sel_inv_list.original_payment_num_l
3363               ,sel_inv_list.bank_account_num_l
3364               ,sel_inv_list.bank_num_l
3365               ,sel_inv_list.proposed_payment_amount_l
3366               ,sel_inv_list.pay_selected_check_id_l
3367               ,sel_inv_list.print_selected_check_id_l
3368               ,sel_inv_list.withhloding_amount_l
3369               ,sel_inv_list.invoice_payment_id_l
3370               ,sel_inv_list.dont_pay_description_l
3371               ,sel_inv_list.transfer_priority_l
3372               ,sel_inv_list.iban_number_l
3373               ,sel_inv_list.payment_grouping_number_l
3374               ,sel_inv_list.payment_exchange_rate_l
3375               ,sel_inv_list.payment_exchange_rate_type_l
3376               ,sel_inv_list.payment_exchange_date_l
3377                --Start of 8217641
3378               ,sel_inv_list.remit_to_supplier_name_l
3379               ,sel_inv_list.remit_to_supplier_id_l
3380               ,sel_inv_list.remit_to_supplier_site_l
3381               ,sel_inv_list.remit_to_supplier_site_id_l
3382               --End 8217641
3383               LIMIT 1000;
3384 
3385 
3386           l_debug_info := 'Update ap_payment_schedules_all: encumbrances are on';
3387           IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
3388             fnd_file.put_line(FND_FILE.LOG,l_debug_info);
3389           END IF;
3390 
3391           IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3392             FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
3393           END IF;
3394 
3395 
3396           FORALL i IN sel_inv_list.invoice_id_l.FIRST .. sel_inv_list.invoice_id_l.LAST
3397             UPDATE Ap_Payment_Schedules_All
3398             SET    checkrun_id = sel_inv_list.checkrun_id_l(i)
3399             WHERE  invoice_id = sel_inv_list.invoice_id_l(i)
3400             AND    payment_num = sel_inv_list.payment_num_l(i)
3401             AND    checkrun_id IS NULL --bug 6788730
3402             ;
3403 
3404 
3405           l_debug_info := 'Insert into ap_selected_invoices_all: encumbrances are on';
3406           IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
3407             fnd_file.put_line(FND_FILE.LOG,l_debug_info);
3408           END IF;
3409 
3410           IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3411             FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
3412           END IF;
3413 
3414 
3415           FORALL i IN sel_inv_list.invoice_id_l.FIRST .. sel_inv_list.invoice_id_l.LAST
3416             INSERT INTO ap_selected_invoices_all
3417               (checkrun_name
3418               ,checkrun_id
3419               ,invoice_id
3420               ,payment_num
3421               ,last_update_date
3422               ,last_updated_by
3423               ,creation_date
3424               ,created_by
3425               ,vendor_id
3426               ,vendor_site_id
3427               ,vendor_num
3428               ,vendor_name
3429               ,vendor_site_code
3430               ,address_line1
3431               ,address_line2
3432               ,address_line3
3433               ,address_line4
3434               ,city
3435               ,state
3436               ,zip
3437               ,province
3438               ,country
3439               ,attention_ar_flag
3440               ,withholding_status_lookup_code
3441               ,invoice_num
3442               ,invoice_date
3443               ,voucher_num
3444               ,ap_ccid
3445               ,due_date
3446               ,discount_date
3447               ,invoice_description
3448               ,payment_priority
3449               ,ok_to_pay_flag
3450               ,always_take_discount_flag
3451               ,amount_modified_flag
3452               ,invoice_amount
3453               ,payment_cross_rate
3454               ,invoice_exchange_rate
3455               ,set_of_books_id
3456               ,customer_num
3457               ,future_pay_due_date
3458               ,exclusive_payment_flag
3459               ,attribute1
3460               ,attribute2
3461               ,attribute3
3462               ,attribute4
3463               ,attribute5
3464               ,attribute6
3465               ,attribute7
3466               ,attribute8
3467               ,attribute9
3468               ,attribute10
3469               ,attribute11
3470               ,attribute12
3471               ,attribute13
3472               ,attribute14
3473               ,attribute15
3474               ,attribute_category
3475               ,org_id
3476               ,payment_currency_code
3477               ,external_bank_account_id
3478               ,legal_entity_id
3479               ,global_attribute1
3480               ,global_attribute2
3481               ,global_attribute3
3482               ,global_attribute4
3483               ,global_attribute5
3484               ,global_attribute6
3485               ,global_attribute7
3486               ,global_attribute8
3487               ,global_attribute9
3488               ,global_attribute10
3489               ,global_attribute11
3490               ,global_attribute12
3491               ,global_attribute13
3492               ,global_attribute14
3493               ,global_attribute15
3494               ,global_attribute16
3495               ,global_attribute17
3496               ,global_attribute18
3497               ,global_attribute19
3498               ,global_attribute20
3499               ,global_attribute_category
3500                 --Start of 8217641
3501               ,remit_to_supplier_name
3502               ,remit_to_supplier_id
3503               ,remit_to_supplier_site
3504               ,remit_to_supplier_site_id
3505               --End 8217641
3506               ,affects_rejection_level
3507               --bug12349626
3508               )
3509             --bug 6788730 Changed this to SELECT
3510             VALUES /* Bug 13321621 Changed back to insert by values */
3511               (
3512 		/* Commented for bug 13321621 */
3513               --SELECT /*+ INDEX(AP_PAYMENT_SCHEDULES_ALL,AP_PAYMENT_SCHEDULES_U1) */
3514                sel_inv_list.checkrun_name_l(i)
3515               ,sel_inv_list.checkrun_id_l(i)
3516               ,sel_inv_list.invoice_id_l(i)
3517               ,sel_inv_list.payment_num_l(i)
3518               ,sel_inv_list.last_update_date_l(i)
3519               ,sel_inv_list.last_updated_by_l(i)
3520               ,sel_inv_list.creation_date_l(i)
3521               ,sel_inv_list.created_by_l(i)
3522               ,sel_inv_list.vendor_id_l(i)
3523               ,sel_inv_list.vendor_site_id_l(i)
3524               ,sel_inv_list.vendor_num_l(i)
3525               ,sel_inv_list.vendor_name_l(i)
3526               ,sel_inv_list.vendor_site_code_l(i)
3527               ,sel_inv_list.address_line1_l(i)
3528               ,sel_inv_list.address_line2_l(i)
3529               ,sel_inv_list.address_line3_l(i)
3530               ,sel_inv_list.address_line4_l(i)
3531               ,sel_inv_list.city_l(i)
3532               ,sel_inv_list.state_l(i)
3533               ,sel_inv_list.zip_l(i)
3534               ,sel_inv_list.province_l(i)
3535               ,sel_inv_list.country_l(i)
3536               ,sel_inv_list.attention_ar_flag_l(i)
3537               ,sel_inv_list.withholding_status_lookup_l(i)
3538               ,sel_inv_list.invoice_num_l(i)
3539               ,sel_inv_list.invoice_date_l(i)
3540               ,sel_inv_list.voucher_num_l(i)
3541               ,sel_inv_list.ap_ccid_l(i)
3542               ,sel_inv_list.due_date_l(i)
3543               ,sel_inv_list.discount_date_l(i)
3544               ,sel_inv_list.invoice_description_l(i)
3545               ,sel_inv_list.payment_priority_l(i)
3546               ,sel_inv_list.ok_to_pay_flag_l(i)
3547               ,sel_inv_list.always_take_disc_flag_l(i)
3548               ,sel_inv_list.amount_modified_flag_l(i)
3549               ,sel_inv_list.invoice_amount_l(i)
3550               ,sel_inv_list.payment_cross_rate_l(i)
3551               ,sel_inv_list.invoice_exchange_rate_l(i)
3552               ,sel_inv_list.set_of_books_id_l(i)
3553               ,sel_inv_list.customer_num_l(i)
3554               ,sel_inv_list.future_pay_due_date_l(i)
3555               ,sel_inv_list.exclusive_payment_flag_l(i)
3556               ,sel_inv_list.attribute1_l(i)
3557               ,sel_inv_list.attribute2_l(i)
3558               ,sel_inv_list.attribute3_l(i)
3559               ,sel_inv_list.attribute4_l(i)
3560               ,sel_inv_list.attribute5_l(i)
3561               ,sel_inv_list.attribute6_l(i)
3562               ,sel_inv_list.attribute7_l(i)
3563               ,sel_inv_list.attribute8_l(i)
3564               ,sel_inv_list.attribute9_l(i)
3565               ,sel_inv_list.attribute10_l(i)
3566               ,sel_inv_list.attribute11_l(i)
3567               ,sel_inv_list.attribute12_l(i)
3568               ,sel_inv_list.attribute13_l(i)
3569               ,sel_inv_list.attribute14_l(i)
3570               ,sel_inv_list.attribute15_l(i)
3571               ,sel_inv_list.attribute_category_l(i)
3572               ,sel_inv_list.org_id_l(i)
3573               ,sel_inv_list.payment_currency_code_l(i)
3574               ,sel_inv_list.external_bank_account_id_l(i)
3575               ,sel_inv_list.legal_entity_id_l(i)
3576               ,sel_inv_list.global_attribute1_l(i)
3577               ,sel_inv_list.global_attribute2_l(i)
3578               ,sel_inv_list.global_attribute3_l(i)
3579               ,sel_inv_list.global_attribute4_l(i)
3580               ,sel_inv_list.global_attribute5_l(i)
3581               ,sel_inv_list.global_attribute6_l(i)
3582               ,sel_inv_list.global_attribute7_l(i)
3583               ,sel_inv_list.global_attribute8_l(i)
3584               ,sel_inv_list.global_attribute9_l(i)
3585               ,sel_inv_list.global_attribute10_l(i)
3586               ,sel_inv_list.global_attribute11_l(i)
3587               ,sel_inv_list.global_attribute12_l(i)
3588               ,sel_inv_list.global_attribute13_l(i)
3589               ,sel_inv_list.global_attribute14_l(i)
3590               ,sel_inv_list.global_attribute15_l(i)
3591               ,sel_inv_list.global_attribute16_l(i)
3592               ,sel_inv_list.global_attribute17_l(i)
3593               ,sel_inv_list.global_attribute18_l(i)
3594               ,sel_inv_list.global_attribute19_l(i)
3595               ,sel_inv_list.global_attribute20_l(i)
3596               ,sel_inv_list.global_attribute_category_l(i)
3597                --Start of 8217641
3598               ,sel_inv_list.remit_to_supplier_name_l(i)
3599               ,sel_inv_list.remit_to_supplier_id_l(i)
3600               ,sel_inv_list.remit_to_supplier_site_l(i)
3601               ,sel_inv_list.remit_to_supplier_site_id_l(i)
3602               --End 8217641
3603               ,'N'
3604               --bug12349626
3605 		/* Commented for bug 13321621
3606             FROM Ap_Payment_Schedules_All
3607             WHERE  invoice_id = sel_inv_list.invoice_id_l(i)
3608             AND    payment_num = sel_inv_list.payment_num_l(i)
3609             AND    checkrun_id = sel_inv_list.checkrun_id_l(i)
3610 		*/
3611             --bug 6788730
3612             );
3613 
3614         EXIT WHEN refcur%NOTFOUND;
3615       END LOOP;
3616 
3617       COMMIT;
3618 
3619     CLOSE refcur;
3620 
3621 
3622   else  --no encumbrances used
3623 
3624     l_debug_info := 'Open payment schedules cursor- encumbrances are off';
3625     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
3626       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
3627     END IF;
3628 
3629     l_sql_stmt :=
3630         '   SELECT '||l_hint||
3631         '         :p_checkrun_name                                            checkrun_name '||
3632         '        ,:p_checkrun_id                                              checkrun_id '||
3633         '        ,ps.invoice_id                                               invoice_id '||
3634         '        ,ps.payment_num                                              payment_num '||
3635         '        ,SYSDATE                                                     last_update_date '||
3636                 -- Bug 7296715
3637                 -- The User Id is hardcoded to 5 (APPSMGR). It is changed to populate correct value.
3638                 -- ,5                                                           last_updated_by
3639         '        ,FND_GLOBAL.USER_ID                                          last_updated_by '||
3640         '        ,SYSDATE                                                     creation_date '||
3641                   -- Bug 7296715
3642                   -- ,5                                                           created_by
3643         '        ,FND_GLOBAL.USER_ID                                          created_by '||
3644         '        ,NULL                                                        last_update_login '||
3645         '        ,ai.vendor_id                                               vendor_id '||
3646         '        ,ai.vendor_site_id                                          vendor_site_id '||
3647         '        ,suppliers.segment1                                          vendor_num '||
3648                  -- Bug 5620285, Added the following decode */
3649         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3650         '                hzp.party_name, suppliers.vendor_name)               vendor_name '||
3651         '        ,sites.vendor_site_code                                      vendor_site_code '||
3652         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3653         '                hzl.address1, sites.address_line1)                   address_line1 '||
3654         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3655         '                hzl.address2, sites.address_line2)                   address_line2 '||
3656         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3657         '                hzl.address3, sites.address_line3)                   address_line3 '||
3658         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3659         '                hzl.address4, sites.address_line4)                   address_line4 '||
3660         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3661         '                hzl.city, sites.city)                                city '||
3662         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3663         '                hzl.state, sites.state)                              state '||
3664         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3665         '                hzl.postal_code, sites.zip)                          zip '||
3666         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3667         '                hzl.province, sites.province)                        province '||
3668         '        ,decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', '||
3669         '                hzl.country, sites.country)                          country '||
3670         '        ,sites.attention_ar_flag                                     attention_ar_flag '||
3671         '        ,suppliers.withholding_status_lookup_code                    withholding_status_lookup_code '||
3672         '        ,ai.invoice_num                                             invoice_num '||
3673         '        ,ai.invoice_date                                            invoice_date '||
3674         '        ,DECODE(ai.doc_sequence_id, '||
3675         '                   '''', ai.voucher_num, '||
3676         '                   ai.doc_sequence_value)                           voucher_num '||
3677         '        ,ai.accts_pay_code_combination_id                           ap_ccid '||
3678         '        ,TRUNC(ps.due_date)                                          due_date '||
3679         '        ,DECODE(sites.always_take_disc_flag, '||
3680         '                   ''Y'', TRUNC(ps.due_date), '||
3681         '                   DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'')  '||
3682         '                               - NVL(ps.discount_date, '||
3683         '                                     to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
3684         '                          -1, ps.discount_date, '||
3685         '                          DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
3686         '                                      -NVL(ps.second_discount_date, '||
3687         '                                           to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
3688         '                                 -1, ps.second_discount_date, '||
3689         '                                 DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
3690         '                                             -NVL(ps.third_discount_date, '||
3691         '                                                    to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
3692         '                                        -1, ps.third_discount_date, '||
3693         '                                        TRUNC(ps.due_date)))))      discount_date '||
3694         /* Commented and added for bug 12409940 */
3695         /*'        ,SUBSTRB(ai.description,1,50)                              invoice_description '|| */
3696 	'        ,ai.description                                              invoice_description '||
3697         '        ,nvl(ps.payment_priority, 99)                               payment_priority '||
3698         '        ,''Y''                                                        ok_to_pay_flag '||
3699         '        ,sites.always_take_disc_flag                                always_take_discount_flag '||
3700         '        ,''N''                                                        amount_modified_flag '||
3701         '        ,ai.invoice_amount                                         invoice_amount '||
3702         '        ,ai.payment_cross_rate                                     payment_cross_rate '||
3703         '        ,DECODE(ai.exchange_rate, '||
3704         '                   NULL, DECODE(ai.invoice_currency_code, '||
3705         '                                asp.base_currency_code, 1, '||
3706         '                                NULL), '||
3707         '                   ai.exchange_rate)                               invoice_exchange_rate '||
3708         '        ,ai.set_of_books_id                                        set_of_books_id '||
3709         '        ,sites.customer_num                                         customer_num '||
3710         '        ,ps.future_pay_due_date                                     future_pay_due_date '||
3711         '        ,ai.exclusive_payment_flag                                 exclusive_payment_flag '||
3712         '        ,ps.attribute1                                              attribute1 '||
3713         '        ,ps.attribute2                                              attribute2 '||
3714         '        ,ps.attribute3                                              attribute3 '||
3715         '        ,ps.attribute4                                              attribute4 '||
3716         '        ,ps.attribute5                                              attribute5 '||
3717         '        ,ps.attribute6                                              attribute6 '||
3718         '        ,ps.attribute7                                              attribute7 '||
3719         '        ,ps.attribute8                                              attribute8 '||
3720         '        ,ps.attribute9                                              attribute9 '||
3721         '        ,ps.attribute10                                             attribute10 '||
3722         '        ,ps.attribute11                                             attribute11 '||
3723         '        ,ps.attribute12                                             attribute12 '||
3724         '        ,ps.attribute13                                             attribure13 '||
3725         '        ,ps.attribute14                                             attribute14 '||
3726         '        ,ps.attribute15                                             attribute15 '||
3727         '        ,ps.attribute_category                                      attribute_category '||
3728         '        ,ai.org_id                                                 org_id '||
3729         '        ,ai.payment_currency_code                                  payment_currency_code '||
3730         '        ,ps.external_bank_account_id                                external_bank_account_id '||
3731         '        ,ai.legal_entity_id                                        legal_entity_id '||
3732                  -- Bug 5192018 we will insert global attribute values from ap_invoices table */
3733         '        ,ai.global_attribute1                                      global_attribute1 '||
3734         '        ,ai.global_attribute2                                      global_attribute2 '||
3735         '        ,ai.global_attribute3                                      global_attribute3 '||
3736         '        ,ai.global_attribute4                                      global_attribute4 '||
3737         '        ,ai.global_attribute5                                      global_attribute5 '||
3738         '        ,ai.global_attribute6                                      global_attribute6 '||
3739         '        ,ai.global_attribute7                                      global_attribute7 '||
3740         '        ,ai.global_attribute8                                      global_attribute8 '||
3741         '        ,ai.global_attribute9                                      global_attribute9 '||
3742         '        ,ai.global_attribute10                                     global_attribute10 '||
3743         '        ,ai.global_attribute11                                     global_attribute11 '||
3744         '        ,ai.global_attribute12                                     global_attribute12 '||
3745         '        ,ai.global_attribute13                                     global_attribute13 '||
3746         '        ,ai.global_attribute14                                     global_attribute14 '||
3747         '        ,ai.global_attribute15                                     global_attribute15 '||
3748         '        ,ai.global_attribute16                                     global_attribute16 '||
3749         '        ,ai.global_attribute17                                     global_attribute17 '||
3750         '        ,ai.global_attribute18                                     global_attribute18 '||
3751         '        ,ai.global_attribute19                                     global_attribute19 '||
3752         '        ,ai.global_attribute20                                     global_attribute20 '||
3753         '        ,ai.global_attribute_category                              global_attribute_category  '|| -- end of bug 5192018
3754         '        ,Null                                                       amount_paid '||
3755         '        ,Null                                                       discount_amount_taken '||
3756         '        ,Null                                                       amount_remaining '||
3757         '        ,Null                                                       discount_amount_remaining '||
3758         '        ,Null                                                       payment_amount '||
3759         '        ,Null                                                       discount_amount '||
3760         '        ,Null                                                       sequence_num '||
3761         '        ,Null                                                       done_pay_reason_code '||
3762         '        ,Null                                                       check_number '||
3763         '        ,Null                                                       bank_account_type '||
3764         '        ,Null                                                       original_invoice_id '||
3765         '        ,Null                                                       original_payment_num '||
3766         '        ,Null                                                       bank_account_num '||
3767         '        ,Null                                                       bank_num '||
3768         '        ,Null                                                       proposed_payment_amount '||
3769         '        ,Null                                                       pay_selected_check_id '||
3770         '        ,Null                                                       print_selected_check_id '||
3771         '        ,Null                                                       withholding_amount '||
3772         '        ,Null                                                       invoice_payment_id '||
3773         '        ,Null                                                       dont_pay_description '||
3774         '        ,Null                                                       transfer_priority '||
3775         '        ,Null                                                       iban_number '||
3776         '        ,Null                                                       payment_grouping_number '||
3777         '        ,Null                                                       payment_exchange_rate '||
3778         '        ,Null                                                       payment_exchange_rate_type '||
3779         '        ,Null                                                       payment_exchange_date '||
3780                  --Start of 8217641
3781         '        ,ps.remit_to_supplier_name                                  remit_to_supplier_name '||
3782         '        ,ps.remit_to_supplier_id                                    remit_to_supplier_id '||
3783         '        ,ps.remit_to_supplier_site                                  remit_to_supplier_site '||
3784         '        ,ps.remit_to_supplier_site_id                               remit_to_supplier_site_id '||
3785                 --End 8217641
3786         '   FROM   ap_supplier_sites_all sites, '||
3787         '          ap_suppliers suppliers, '||
3788         '          ap_invoices ai,  '||             /* inv,  '||  Commented for bug#9182499 GSCC Error File.Sql.6 --Bug6040657. Changed from ap_invoices_all to ap_invoices */
3789         '          ap_payment_schedules_all ps, '||
3790         '          ap_system_parameters_all asp, '||
3791         '          hz_parties hzp, '||
3792         '          hz_party_sites hzps,           '|| -- Bug 5620285
3793         '          hz_locations   hzl             '|| -- Bug 5620285
3794         '   WHERE   ps.checkrun_id is null        '|| -- Bug 5705276. Regression
3795         '       AND ((due_date <= to_date(:p_pay_thru_date, ''DD-MM-YYYY'') +0/24 and  '|| --Bug 8708165
3796         '               due_date >= nvl(to_date(:p_pay_from_date, ''DD-MM-YYYY'') + 0/24,due_date)) '||
3797         '              OR '||
3798         '               DECODE(NVL(sites.pay_date_basis_lookup_code,''DISCOUNT''), '||
3799         '                    ''DISCOUNT'', '||
3800         '                    DECODE(sites.always_take_disc_flag, '||
3801         '                           ''Y'', ps.discount_date, '||
3802         '                           DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
3803         '                                  -NVL(ps.discount_date, '||
3804         '                                       to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
3805         '                                  -1, ps.discount_date, '||
3806         '                                  DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
3807         '                                              -NVL(ps.second_discount_date, '||
3808         '                                                   to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
3809         '                                         -1, ps.second_discount_date, '||
3810         '                                         DECODE(SIGN(to_date(:p_check_date, ''DD-MM-YYYY'') '||
3811         '                                                     -NVL(ps.third_discount_date, '||
3812         '                                                         to_date(:p_check_date, ''DD-MM-YYYY'')+1)-1), '||
3813         '                                                -1, ps.third_discount_date, '||
3814         '                                                TRUNC(ps.due_date))))), '||
3815         '                    TRUNC(due_date)) '||
3816         '                    BETWEEN DECODE(sites.always_take_disc_flag,''Y'', '||
3817         '                                    nvl(to_date(:p_pay_from_date, ''DD-MM-YYYY''), TO_DATE(''1901'',''YYYY'')), '||
3818         '                                    to_date(:p_check_date, ''DD-MM-YYYY'') ) '||
3819         '                            AND to_date(:p_disc_pay_thru_date, ''DD-MM-YYYY'') ) '||
3820         /* '       AND    ps.payment_status_flag BETWEEN ''N'' AND ''P'' '|| Commented for bug#11848050 */
3821         '       AND    nvl(ai.force_revalidation_flag, ''N'') = ''N''  '||  --bug7244642
3822         /* '       AND    ai.payment_status_flag BETWEEN ''N'' AND ''P'' '|| Commented for bug#11848050 */
3823         '       AND    ps.payment_status_flag IN (''N'', ''P'') '|| /* Added for bug#11848050 */
3824         '       AND    ai.payment_status_flag IN (''N'', ''P'') '|| /* Added for bug#11848050 */
3825         '       AND    NVL(ps.payment_priority, 99) BETWEEN :p_hi_payment_priority '||
3826         '                                              AND :p_lo_payment_priority '||
3827         '       AND    ai.cancelled_date is null '||
3828                -- Bug 7167192 Added decode
3829                -- hzp and hzps data is required only for Payment Requests.
3830         '       AND    hzp.party_id(+) = decode(ai.invoice_type_lookup_code, '||
3831         '                                       ''PAYMENT REQUEST'', ai.party_id '||
3832         '                                                        , -99) '||
3833         '       AND    NVL(ps.hold_flag, ''N'') = ''N'' '||
3834         '       AND    NVL(sites.hold_all_payments_flag, ''N'') = ''N'' '||
3835         '       AND    ai.invoice_id = ps.invoice_id '||
3836         '       AND    sites.vendor_id(+) = ai.vendor_id '||
3837         '       AND    sites.vendor_site_id(+) = ai.vendor_site_id '||
3838         '       AND    suppliers.vendor_id(+) = ai.vendor_id '||
3839         '       AND    asp.org_id = ai.org_id '||
3840         '       AND    hzp.party_id = hzps.party_id (+)  '|| -- Bug 5620285
3841                -- Bug  5929034: An employee does not have a hz_party_site changing query to reflect the same
3842                -- AND  nvl(hzps.party_site_id,-99)  = decode(suppliers.vendor_type_lookup_code,'EMPLOYEE',-99,nvl(inv.party_site_id, hzps.party_site_id))  -- Bug 5620285
3843                -- Bug  6662382
3844                -- Bug  7167192 - Query condition is now based on whether the Invoice
3845                --               is a Payment Request. Supplier type does not matter.
3846                -- AND  NVL(hzps.party_site_id,-99)  = DECODE(suppliers.vendor_type_lookup_code,'EMPLOYEE', COALESCE(inv.party_site_id, hzps.party_site_id,-99),
3847                --                                          NVL(inv.party_site_id, hzps.party_site_id))
3848         '       AND    NVL(hzps.party_site_id,-99) = NVL(decode(ai.invoice_type_lookup_code, ''PAYMENT REQUEST'', ai.party_site_id, -99), hzps.party_site_id) '||
3849                -- Bug 7167192
3850         '       AND    nvl(hzps.location_id,-99) = hzl.location_id(+)  '|| -- Bug 5620285
3851                --End Bug 5929034
3852         '       AND    fv_econ_benf_disc.ebd_check(:p_checkrun_name, ai.invoice_id, '||
3853         '                                  to_date(:p_check_date, ''DD-MM-YYYY''), due_date, ps.discount_amount_available, ps.discount_date) = ''Y'' ';
3854                -- Bug 7265013 starts
3855                -- AND    AP_INVOICES_PKG.get_wfapproval_status(inv.invoice_id, inv.org_id) in
3856                --             ('NOT REQUIRED','WFAPPROVED','MANUALLY APPROVED')
3857                -- Bug 7265013 ends
3858 
3859 
3860 
3861         IF l_invoice_batch_id IS NOT NULL THEN
3862           l_sql_stmt := l_sql_stmt||'              AND  ai.batch_id = :p_inv_batch_id ';
3863         ELSE
3864           l_sql_stmt := l_sql_stmt||'              AND  nvl(:p_inv_batch_id, -9999) = -9999 ';
3865         END IF;
3866 
3867         IF l_inv_vendor_id IS NOT NULL THEN
3868           l_sql_stmt := l_sql_stmt||'       AND    ai.vendor_id = :p_inv_vendor_id  ';
3869         ELSE
3870           l_sql_stmt := l_sql_stmt||'       AND    nvl(:p_inv_vendor_id, -9999) = -9999 ';
3871         END IF;
3872 
3873         IF l_party_id IS NOT NULL THEN
3874            l_sql_stmt := l_sql_stmt||'       AND    ai.party_id = :p_party_id ';
3875         ELSE
3876            l_sql_stmt := l_sql_stmt||'       AND    nvl(:p_party_id, -9999) = -9999 ';
3877         END IF;
3878 
3879 
3880                -- Bug 5507013 hkaniven start --
3881         l_sql_stmt := l_sql_stmt||
3882            '       AND    (( :p_inv_exc_rate_type = ''IS_USER'' AND NVL(ai.exchange_rate_type,''NOT USER'') = ''User'' ) '||
3883            '               OR (:p_inv_exc_rate_type = ''IS_NOT_USER'' AND NVL(ai.exchange_rate_type,''NOT USER'') <> ''User'') '||
3884            '               OR (:p_inv_exc_rate_type IS NULL)) '
3885                   -- Bug 5507013 hkaniven end --
3886            /* '       AND    ps.payment_method_code = nvl(:p_payment_method, ps.payment_method_code) '||
3887               '       AND    nvl(suppliers.vendor_type_lookup_code,-99) = '||
3888               '                   nvl(:p_supplier_type, nvl(suppliers.vendor_type_lookup_code,-99)) '||
3889            '       AND    (ai.legal_entity_id in (select /*+ push_subq * / legal_entity_id '||
3890            '                                       from   ap_le_group '||
3891            '                                       where  checkrun_id = :p_checkrun_id) '||
3892            '               or :p_le_group_option = ''ALL'') '||
3893            '       AND    (ai.org_id in (select /*+ push_subq * / org_id '||
3894            '                              from   AP_OU_GROUP '||
3895            '                              where  checkrun_id = :p_checkrun_id) '||
3896            '               or :p_ou_group_option = ''ALL'') '||
3897            '       AND    (ai.payment_currency_code in (select /*+ push_subq * / currency_code '||
3898            '                                            from   AP_CURRENCY_GROUP '||
3899            '                                            where  checkrun_id = :p_checkrun_id) '||
3900            '               or :p_curr_group_option = ''ALL'') '            Commented for bug#11848050 */;
3901 
3902         /* Code Added for bug#11848050 Start */
3903         IF l_payment_method IS NOT NULL THEN
3904            l_sql_stmt := l_sql_stmt || '    AND ps.payment_method_code = :p_payment_method ';
3905         ELSE
3906            l_sql_stmt := l_sql_stmt || '    AND nvl(:p_payment_method, -9999) = -9999';
3907         END IF;
3908 
3909         IF l_supplier_type IS NOT NULL THEN
3910            l_sql_stmt := l_sql_stmt || '    AND suppliers.vendor_type_lookup_code = :p_supplier_type ';
3911         ELSE
3912            l_sql_stmt := l_sql_stmt || '    AND nvl(:p_supplier_type, -9999) = -9999';
3913         END IF;
3914         /* Code Added for bug#11848050 End */
3915 
3916         IF l_pay_group_option <> 'ALL' THEN
3917           l_sql_stmt := l_sql_stmt||
3918             /* Commented for Bug#9182499 Start
3919             '       AND    inv.pay_group_lookup_code in (select / *+ leading(apg) cardinality(apg 1) * / vendor_pay_group '||
3920             '                                            from   AP_PAY_GROUP apg'||   --bug9087739, added alias for  AP_PAY_GROUP
3921             '                                            where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id) ';
3922             Commented for Bug#9182499 End */
3923             /* Added for Bug#9182499 Start */
3924             '       AND (ai.pay_group_lookup_code, ai.org_id) in '||
3925             '                       ( select  '|| /* Added for bug#12773508 */
3926             /* '                       ( select / *+ leading(apg) cardinality(apg 1) * / '|| Commented for bug#12773508 */
3927             '                                apg.vendor_pay_group, mo.ORGANIZATION_ID '||
3928             '                           from AP_PAY_GROUP apg, MO_GLOB_ORG_ACCESS_TMP mo '||
3929             '                          where checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id '||
3930             '                            AND ai.org_id = mo.organization_id ) '; /* Added for bug#11848050 */
3931             /* Added for Bug#9182499 End */
3932 
3933         ELSE
3934           l_sql_stmt := l_sql_stmt||
3935             '       AND    :p_checkrun_id = :p_checkrun_id   ';
3936         END IF;
3937 
3938         /* Added for bug#11848050 Start */
3939         IF l_le_group_option <> 'ALL' THEN
3940            l_sql_stmt := l_sql_stmt||
3941                '       AND  ai.legal_entity_id in '||
3942                '               (select /*+ push_subq */ legal_entity_id '||
3943                '                  from   ap_le_group                    '||
3944                '                 where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id)   ';
3945         ELSE
3946            l_sql_stmt := l_sql_stmt||
3947                '       AND    :p_checkrun_id = :p_checkrun_id   ';
3948         END IF;
3949 
3950         --bug14160441 remove push_subq hint, add no_push_subq and no_unnest
3951         IF l_ou_group_option <> 'ALL' THEN
3952            l_sql_stmt := l_sql_stmt||
3953                '       AND  ai.org_id in '||
3954                '               (select /*+ no_push_subq no_unnest*/ org_id '||
3955                '                  from   AP_OU_GROUP                    '||
3956                '                 where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id)   ';
3957         ELSE
3958            l_sql_stmt := l_sql_stmt||
3959                '       AND    :p_checkrun_id = :p_checkrun_id   ';
3960         END IF;
3961 
3962         --bug14160441 remove push_subq hint, add no_unnest
3963         IF l_currency_group_option <> 'ALL' THEN
3964            l_sql_stmt := l_sql_stmt||
3965                '       AND  ai.payment_currency_code in '||
3966                '               (select /*+ no_unnest */ currency_code '||
3967                '                  from   AP_CURRENCY_GROUP                    '||
3968                '                 where  checkrun_id BETWEEN :p_checkrun_id AND :p_checkrun_id)   ';
3969         ELSE
3970            l_sql_stmt := l_sql_stmt||
3971                '       AND    :p_checkrun_id = :p_checkrun_id   ';
3972         END IF;
3973         /* Added for bug#11848050 End */
3974 
3975         l_sql_stmt := l_sql_stmt||
3976            '       AND    ((:p_zero_inv_allowed = ''N'' AND ps.amount_remaining <> 0) OR '||
3977            '                :p_zero_inv_allowed = ''Y'') '||
3978                   -- Bug 7265013 starts
3979 	   /*'       AND EXISTS ( '||
3980            '         SELECT 1 '||
3981            '         FROM   sys.dual '||
3982            '         WHERE  AP_INVOICES_PKG.get_wfapproval_status(ai.invoice_id, ai.org_id) in '||
3983            '                 (''NOT REQUIRED'',''WFAPPROVED'',''MANUALLY APPROVED'') '||
3984            '       ) '|| */
3985            /* Bug 13901772 */
3986            '      AND ai.wfapproval_status in (''NOT REQUIRED'',''WFAPPROVED'',''MANUALLY APPROVED'')                   '||
3987 	   '      AND NOT EXISTS (select 1 from ap_invoice_lines_all ail                                                '||
3988 	   '                       where ai.invoice_id = ail.invoice_id                                                 '||
3989 	   '                         and ail.wfapproval_status in (''NEEDS WFREAPPROVAL'',''REJECTED'',''INITIATED''))  '||
3990                   -- Bug 7265013 ends
3991                   -- Bug 11816573. Removed the push predicates.
3992            '       AND NOT EXISTS (SELECT  /*+ no_unnest */ ''Unreleased holds exist'' '|| /* Added hint for bug#12773508 */
3993            '                       FROM   ap_holds_all H '||
3994            '                       WHERE  H.invoice_id = ai.invoice_id '||
3995            '                       AND    H.release_lookup_code is null) '||
3996            '       AND NOT EXISTS (SELECT  ''Invoice is not fully approved'' '||
3997            '                       FROM ap_invoice_distributions_all D2 '||
3998            '                       WHERE D2.invoice_id = ai.invoice_id '||
3999            '                       AND NVL(D2.match_status_flag, ''N'') in (''N'', ''S'')) '||
4000            /* Bug 12799362. Start. */
4001  	   '       AND NOT EXISTS (SELECT ''Line without distribution''  '||
4002  	   '                       FROM   ap_invoice_lines_all ail  '||
4003  	   '                       WHERE  ail.invoice_id = ai.invoice_id  '||
4004  	   '                       AND ail.amount <> 0  ' ||
4005  	   '                       AND NOT EXISTS (SELECT ''No Distributions''  '||
4006  	   '                                       FROM   ap_invoice_distributions_all aid '||
4007  	   '                                       WHERE  ail.invoice_id = aid.invoice_id  '||
4008  	   '                                       AND    ail.line_number = aid.invoice_line_number '||
4009  	   '                                       ) '||
4010  	   '                      ) '||
4011  	   /* Bug 12799362. End. */
4012            /*
4013            -- Commented for Bug 12727539.
4014            -- '       AND NOT EXISTS (SELECT ''Invoice is not fully approved''  '||
4015            -- '                       FROM ap_invoices_derived_v AIDV '||
4016            -- '                       WHERE AIDV.invoice_id = ai.invoice_id '||
4017            -- '                       AND AIDV.approval_status_lookup_code IN  '||
4018            -- '                               (''NEVER APPROVED'', ''NEEDS REAPPROVAL'', ''UNAPPROVED'')) '||
4019            */
4020 
4021                   -- Bug 11816573. Changed hint from push_subq to no_unnest.
4022            '       AND EXISTS (SELECT /*+ no_unnest */  ''Distributions exist'' '||
4023            '                   FROM   ap_invoice_distributions_all D4 '||
4024 				/* Added FOR UPDATE for bug 13321621 */
4025                         /* Added SKIP LOCKED for bug 14277979 */
4026            '            WHERE  D4.invoice_id = ai.invoice_id) FOR UPDATE OF ps.checkrun_id SKIP LOCKED';
4027                   -- bug 6456537
4028            /*      AND NOT EXISTS (SELECT ''CCR EXPIRED''
4029                                   FROM FV_TPP_ASSIGNMENTS_V TPP
4030                                   WHERE TPP.beneficiary_party_id = inv.party_id
4031                                   AND TPP.beneficiary_party_site_id = inv.party_site_id
4032                                   AND NVL(TPP.fv_tpp_pay_flag, ''Y'') = ''N'') bug8691645 */
4033         -- 6456537 Checking the validity of CCR of the Third Party for
4034         -- supplier. If the CCR is Invalid then the invoice document
4035         -- is not consider for the Payment(Auto Select)
4036 
4037         IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4038               FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4039         END IF;
4040 
4041         OPEN refcur FOR l_sql_stmt USING
4042                                     l_payment_process_request_name,
4043                                     l_checkrun_id,
4044                                     l_check_date_char,
4045                                     l_check_date_char,
4046                                     l_check_date_char,
4047                                     l_check_date_char,
4048                                     l_check_date_char,
4049                                     l_check_date_char,
4050                                     l_pay_thru_date_char,
4051                                     l_pay_from_date_char,
4052                                     l_check_date_char,
4053                                     l_check_date_char,
4054                                     l_check_date_char,
4055                                     l_check_date_char,
4056                                     l_check_date_char,
4057                                     l_check_date_char,
4058                                     l_pay_from_date_char,
4059                                     l_check_date_char,
4060                                     l_disc_pay_thru_char,
4061                                     l_hi_payment_priority,
4062                                     l_low_payment_priority,
4063                                     l_payment_process_request_name,
4064                                     l_check_date_char,
4065                                     l_invoice_batch_id,
4066                                     l_inv_vendor_id,
4067                                     l_party_id,
4068                                     l_inv_exchange_rate_type,
4069                                     l_inv_exchange_rate_type,
4070                                     l_inv_exchange_rate_type,
4071                                     l_payment_method, /* Changed the sequence for bug#11848050 */
4072                                     l_supplier_type,  /* Changed the sequence for bug#11848050 */
4073                                     l_checkrun_id,
4074                                     l_checkrun_id,
4075                                     l_checkrun_id,
4076                                     l_checkrun_id,
4077                                     l_checkrun_id,
4078                                     l_checkrun_id,
4079                                     l_checkrun_id,
4080                                     l_checkrun_id,
4081                                     l_zero_invoices_allowed,
4082                                     l_zero_invoices_allowed;
4083         LOOP
4084         FETCH refcur BULK COLLECT INTO
4085                sel_inv_list.checkrun_name_l
4086               ,sel_inv_list.checkrun_id_l
4087               ,sel_inv_list.invoice_id_l
4088               ,sel_inv_list.payment_num_l
4089               ,sel_inv_list.last_update_date_l
4090               ,sel_inv_list.last_updated_by_l
4091               ,sel_inv_list.creation_date_l
4092               ,sel_inv_list.created_by_l
4093               ,sel_inv_list.last_update_login_l
4094               ,sel_inv_list.vendor_id_l
4095               ,sel_inv_list.vendor_site_id_l
4096               ,sel_inv_list.vendor_num_l
4097               ,sel_inv_list.vendor_name_l
4098               ,sel_inv_list.vendor_site_code_l
4099               ,sel_inv_list.address_line1_l
4100               ,sel_inv_list.address_line2_l
4101               ,sel_inv_list.address_line3_l
4102               ,sel_inv_list.address_line4_l
4103               ,sel_inv_list.city_l
4104               ,sel_inv_list.state_l
4105               ,sel_inv_list.zip_l
4106               ,sel_inv_list.province_l
4107               ,sel_inv_list.country_l
4108               ,sel_inv_list.attention_ar_flag_l
4109               ,sel_inv_list.withholding_status_lookup_l
4110               ,sel_inv_list.invoice_num_l
4111               ,sel_inv_list.invoice_date_l
4112               ,sel_inv_list.voucher_num_l
4113               ,sel_inv_list.ap_ccid_l
4114               ,sel_inv_list.due_date_l
4115               ,sel_inv_list.discount_date_l
4116               ,sel_inv_list.invoice_description_l
4117               ,sel_inv_list.payment_priority_l
4118               ,sel_inv_list.ok_to_pay_flag_l
4119               ,sel_inv_list.always_take_disc_flag_l
4120               ,sel_inv_list.amount_modified_flag_l
4121               ,sel_inv_list.invoice_amount_l
4122               ,sel_inv_list.payment_cross_rate_l
4123               ,sel_inv_list.invoice_exchange_rate_l
4124               ,sel_inv_list.set_of_books_id_l
4125               ,sel_inv_list.customer_num_l
4126               ,sel_inv_list.future_pay_due_date_l
4127               ,sel_inv_list.exclusive_payment_flag_l
4128               ,sel_inv_list.attribute1_l
4129               ,sel_inv_list.attribute2_l
4130               ,sel_inv_list.attribute3_l
4131               ,sel_inv_list.attribute4_l
4132               ,sel_inv_list.attribute5_l
4133               ,sel_inv_list.attribute6_l
4134               ,sel_inv_list.attribute7_l
4135               ,sel_inv_list.attribute8_l
4136               ,sel_inv_list.attribute9_l
4137               ,sel_inv_list.attribute10_l
4138               ,sel_inv_list.attribute11_l
4139               ,sel_inv_list.attribute12_l
4140               ,sel_inv_list.attribute13_l
4141               ,sel_inv_list.attribute14_l
4142               ,sel_inv_list.attribute15_l
4143               ,sel_inv_list.attribute_category_l
4144               ,sel_inv_list.org_id_l
4145               ,sel_inv_list.payment_currency_code_l
4146               ,sel_inv_list.external_bank_account_id_l
4147               ,sel_inv_list.legal_entity_id_l
4148               ,sel_inv_list.global_attribute1_l
4149               ,sel_inv_list.global_attribute2_l
4150               ,sel_inv_list.global_attribute3_l
4151               ,sel_inv_list.global_attribute4_l
4152               ,sel_inv_list.global_attribute5_l
4153               ,sel_inv_list.global_attribute6_l
4154               ,sel_inv_list.global_attribute7_l
4155               ,sel_inv_list.global_attribute8_l
4156               ,sel_inv_list.global_attribute9_l
4157               ,sel_inv_list.global_attribute10_l
4158               ,sel_inv_list.global_attribute11_l
4159               ,sel_inv_list.global_attribute12_l
4160               ,sel_inv_list.global_attribute13_l
4161               ,sel_inv_list.global_attribute14_l
4162               ,sel_inv_list.global_attribute15_l
4163               ,sel_inv_list.global_attribute16_l
4164               ,sel_inv_list.global_attribute17_l
4165               ,sel_inv_list.global_attribute18_l
4166               ,sel_inv_list.global_attribute19_l
4167               ,sel_inv_list.global_attribute20_l
4168               ,sel_inv_list.global_attribute_category_l
4169               ,sel_inv_list.amount_paid_l
4170               ,sel_inv_list.discount_amount_taken_l
4171               ,sel_inv_list.amount_remaining_l
4172               ,sel_inv_list.discount_amount_remaining_l
4173               ,sel_inv_list.payment_amount_l
4174               ,sel_inv_list.discount_amount_l
4175               ,sel_inv_list.sequence_num_l
4176               ,sel_inv_list.dont_pay_reason_code_l
4177               ,sel_inv_list.check_number_l
4178               ,sel_inv_list.bank_account_type_l
4179               ,sel_inv_list.original_invoice_id_l
4180               ,sel_inv_list.original_payment_num_l
4181               ,sel_inv_list.bank_account_num_l
4182               ,sel_inv_list.bank_num_l
4183               ,sel_inv_list.proposed_payment_amount_l
4184               ,sel_inv_list.pay_selected_check_id_l
4185               ,sel_inv_list.print_selected_check_id_l
4186               ,sel_inv_list.withhloding_amount_l
4187               ,sel_inv_list.invoice_payment_id_l
4188               ,sel_inv_list.dont_pay_description_l
4189               ,sel_inv_list.transfer_priority_l
4190               ,sel_inv_list.iban_number_l
4191               ,sel_inv_list.payment_grouping_number_l
4192               ,sel_inv_list.payment_exchange_rate_l
4193               ,sel_inv_list.payment_exchange_rate_type_l
4194               ,sel_inv_list.payment_exchange_date_l
4195                  --Start of 8217641
4196               ,sel_inv_list.remit_to_supplier_name_l
4197               ,sel_inv_list.remit_to_supplier_id_l
4198               ,sel_inv_list.remit_to_supplier_site_l
4199               ,sel_inv_list.remit_to_supplier_site_id_l
4200               --End 8217641
4201               LIMIT 1000;
4202 
4203           l_debug_info := 'Update ap_payment_schedules_all: encumbrances are off';
4204           IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4205             fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4206           END IF;
4207 
4208           IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4209             FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4210           END IF;
4211 
4212 
4213           FORALL i IN sel_inv_list.invoice_id_l.FIRST .. sel_inv_list.invoice_id_l.LAST
4214             UPDATE Ap_Payment_Schedules_All
4215             SET    checkrun_id = sel_inv_list.checkrun_id_l(i)
4216             WHERE  invoice_id = sel_inv_list.invoice_id_l(i)
4217             AND    payment_num = sel_inv_list.payment_num_l(i)
4218             AND    checkrun_id IS NULL --bug 6788730
4219             ;
4220 
4221 
4222           l_debug_info := 'Insert into ap_selected_invoices_all: encumbrances are off';
4223           IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4224             fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4225           END IF;
4226 
4227           IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4228             FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4229           END IF;
4230 
4231 
4232           FORALL i IN sel_inv_list.invoice_id_l.FIRST .. sel_inv_list.invoice_id_l.LAST
4233             INSERT INTO ap_selected_invoices_all
4234               (checkrun_name
4235               ,checkrun_id
4236               ,invoice_id
4237               ,payment_num
4238               ,last_update_date
4239               ,last_updated_by
4240               ,creation_date
4241               ,created_by
4242               ,vendor_id
4243               ,vendor_site_id
4244               ,vendor_num
4245               ,vendor_name
4246               ,vendor_site_code
4247               ,address_line1
4248               ,address_line2
4249               ,address_line3
4250               ,address_line4
4251               ,city
4252               ,state
4253               ,zip
4254               ,province
4255               ,country
4256               ,attention_ar_flag
4257               ,withholding_status_lookup_code
4258               ,invoice_num
4259               ,invoice_date
4260               ,voucher_num
4261               ,ap_ccid
4262               ,due_date
4263               ,discount_date
4264               ,invoice_description
4265               ,payment_priority
4266               ,ok_to_pay_flag
4267               ,always_take_discount_flag
4268               ,amount_modified_flag
4269               ,invoice_amount
4270               ,payment_cross_rate
4271               ,invoice_exchange_rate
4272               ,set_of_books_id
4273               ,customer_num
4274               ,future_pay_due_date
4275               ,exclusive_payment_flag
4276               ,attribute1
4277               ,attribute2
4278               ,attribute3
4279               ,attribute4
4280               ,attribute5
4281               ,attribute6
4282               ,attribute7
4283               ,attribute8
4284               ,attribute9
4285               ,attribute10
4286               ,attribute11
4287               ,attribute12
4288               ,attribute13
4289               ,attribute14
4290               ,attribute15
4291               ,attribute_category
4292               ,org_id
4293               ,payment_currency_code
4294               ,external_bank_account_id
4295               ,legal_entity_id
4296               ,global_attribute1
4297               ,global_attribute2
4298               ,global_attribute3
4299               ,global_attribute4
4300               ,global_attribute5
4301               ,global_attribute6
4302               ,global_attribute7
4303               ,global_attribute8
4304               ,global_attribute9
4305               ,global_attribute10
4306               ,global_attribute11
4307               ,global_attribute12
4308               ,global_attribute13
4309               ,global_attribute14
4310               ,global_attribute15
4311               ,global_attribute16
4312               ,global_attribute17
4313               ,global_attribute18
4314               ,global_attribute19
4315               ,global_attribute20
4316               ,global_attribute_category
4317               --Start of 8217641
4318               ,remit_to_supplier_name
4319               ,remit_to_supplier_id
4320               ,remit_to_supplier_site
4321               ,remit_to_supplier_site_id
4322               --End 8217641
4323               ,affects_rejection_level
4324               --bug12349626
4325               )
4326         --bug 6788730 Changed this to SELECT
4327         --
4328           VALUES /* Bug 13321621 Changed back to insert by values */
4329               (
4330 		/* Commented for bug 13321621 */
4331               --SELECT /*+ INDEX(AP_PAYMENT_SCHEDULES_ALL,AP_PAYMENT_SCHEDULES_U1) */
4332                sel_inv_list.checkrun_name_l(i)
4333               ,sel_inv_list.checkrun_id_l(i)
4334               ,sel_inv_list.invoice_id_l(i)
4335               ,sel_inv_list.payment_num_l(i)
4336               ,sel_inv_list.last_update_date_l(i)
4337               ,sel_inv_list.last_updated_by_l(i)
4338               ,sel_inv_list.creation_date_l(i)
4339               ,sel_inv_list.created_by_l(i)
4340               ,sel_inv_list.vendor_id_l(i)
4341               ,sel_inv_list.vendor_site_id_l(i)
4342               ,sel_inv_list.vendor_num_l(i)
4343               ,sel_inv_list.vendor_name_l(i)
4344               ,sel_inv_list.vendor_site_code_l(i)
4345               ,sel_inv_list.address_line1_l(i)
4346               ,sel_inv_list.address_line2_l(i)
4347               ,sel_inv_list.address_line3_l(i)
4348               ,sel_inv_list.address_line4_l(i)
4349               ,sel_inv_list.city_l(i)
4350               ,sel_inv_list.state_l(i)
4351               ,sel_inv_list.zip_l(i)
4352               ,sel_inv_list.province_l(i)
4353               ,sel_inv_list.country_l(i)
4354               ,sel_inv_list.attention_ar_flag_l(i)
4355               ,sel_inv_list.withholding_status_lookup_l(i)
4356               ,sel_inv_list.invoice_num_l(i)
4357               ,sel_inv_list.invoice_date_l(i)
4358               ,sel_inv_list.voucher_num_l(i)
4359               ,sel_inv_list.ap_ccid_l(i)
4360               ,sel_inv_list.due_date_l(i)
4361               ,sel_inv_list.discount_date_l(i)
4362               ,sel_inv_list.invoice_description_l(i)
4363               ,sel_inv_list.payment_priority_l(i)
4364               ,sel_inv_list.ok_to_pay_flag_l(i)
4365               ,sel_inv_list.always_take_disc_flag_l(i)
4366               ,sel_inv_list.amount_modified_flag_l(i)
4367               ,sel_inv_list.invoice_amount_l(i)
4368               ,sel_inv_list.payment_cross_rate_l(i)
4369               ,sel_inv_list.invoice_exchange_rate_l(i)
4370               ,sel_inv_list.set_of_books_id_l(i)
4371               ,sel_inv_list.customer_num_l(i)
4372               ,sel_inv_list.future_pay_due_date_l(i)
4373               ,sel_inv_list.exclusive_payment_flag_l(i)
4374               ,sel_inv_list.attribute1_l(i)
4375               ,sel_inv_list.attribute2_l(i)
4376               ,sel_inv_list.attribute3_l(i)
4377               ,sel_inv_list.attribute4_l(i)
4378               ,sel_inv_list.attribute5_l(i)
4379               ,sel_inv_list.attribute6_l(i)
4380               ,sel_inv_list.attribute7_l(i)
4381               ,sel_inv_list.attribute8_l(i)
4382               ,sel_inv_list.attribute9_l(i)
4383               ,sel_inv_list.attribute10_l(i)
4384               ,sel_inv_list.attribute11_l(i)
4385               ,sel_inv_list.attribute12_l(i)
4386               ,sel_inv_list.attribute13_l(i)
4387               ,sel_inv_list.attribute14_l(i)
4388               ,sel_inv_list.attribute15_l(i)
4389               ,sel_inv_list.attribute_category_l(i)
4390               ,sel_inv_list.org_id_l(i)
4391               ,sel_inv_list.payment_currency_code_l(i)
4392               ,sel_inv_list.external_bank_account_id_l(i)
4393               ,sel_inv_list.legal_entity_id_l(i)
4394               ,sel_inv_list.global_attribute1_l(i)
4395               ,sel_inv_list.global_attribute2_l(i)
4396               ,sel_inv_list.global_attribute3_l(i)
4397               ,sel_inv_list.global_attribute4_l(i)
4398               ,sel_inv_list.global_attribute5_l(i)
4399               ,sel_inv_list.global_attribute6_l(i)
4400               ,sel_inv_list.global_attribute7_l(i)
4401               ,sel_inv_list.global_attribute8_l(i)
4402               ,sel_inv_list.global_attribute9_l(i)
4403               ,sel_inv_list.global_attribute10_l(i)
4404               ,sel_inv_list.global_attribute11_l(i)
4405               ,sel_inv_list.global_attribute12_l(i)
4406               ,sel_inv_list.global_attribute13_l(i)
4407               ,sel_inv_list.global_attribute14_l(i)
4408               ,sel_inv_list.global_attribute15_l(i)
4409               ,sel_inv_list.global_attribute16_l(i)
4410               ,sel_inv_list.global_attribute17_l(i)
4411               ,sel_inv_list.global_attribute18_l(i)
4412               ,sel_inv_list.global_attribute19_l(i)
4413               ,sel_inv_list.global_attribute20_l(i)
4414               ,sel_inv_list.global_attribute_category_l(i)
4415                --Start of 8217641
4416               ,sel_inv_list.remit_to_supplier_name_l(i)
4417               ,sel_inv_list.remit_to_supplier_id_l(i)
4418               ,sel_inv_list.remit_to_supplier_site_l(i)
4419               ,sel_inv_list.remit_to_supplier_site_id_l(i)
4420               --End 8217641
4421               ,'N'
4422               --bug12349626
4423 		/* Commented for bug 13321621
4424             FROM Ap_Payment_Schedules_All
4425             WHERE  invoice_id = sel_inv_list.invoice_id_l(i)
4426             AND    payment_num = sel_inv_list.payment_num_l(i)
4427             AND    checkrun_id = sel_inv_list.checkrun_id_l(i)
4428 		*/
4429             --bug 6788730
4430             );
4431 
4432 
4433         EXIT WHEN refcur%NOTFOUND;
4434       END LOOP;
4435 
4436       COMMIT;
4437     CLOSE refcur;
4438 
4439 
4440   end if;
4441 
4442 
4443   --COMMIT;
4444 
4445 
4446   l_debug_info := 'Done Inserting Into Ap_Selected_Invoices_AlL';
4447   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4448      fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4449   END IF;
4450 
4451   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4452     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4453   END IF;
4454 
4455 
4456   -- Bug 5646890. Added l_checkrun_id condition for performance reason
4457   UPDATE Ap_Payment_Schedules_All aps
4458   SET    checkrun_id = null
4459   WHERE  checkrun_id = l_checkrun_id
4460   AND    NOT EXISTS (SELECT /*+HASH_AJ */ 'no row in asi'
4461                      FROM  ap_selected_invoices_all asi
4462                      WHERE asi.invoice_id = aps.invoice_id
4463                      AND   asi.payment_num = aps.payment_num
4464                      AND   asi.checkrun_id = l_checkrun_id);
4465 
4466    --for payment date, reject if itn's not in an open period
4467    --for payment date < system date and allow pre-date payables option is disabled
4468    -- Bug 5646890. Rewrite the following two update as per Performance team
4469    --Bug#8236818 As per the Documentation; Payables does not allow payment entry or
4470    --payment voiding in a Future period.The date must be in an open accounting period.
4471 
4472   UPDATE AP_SELECTED_INVOICES_ALL ASI
4473   SET    OK_TO_PAY_FLAG   = 'N',
4474          DONT_PAY_REASON_CODE = 'PERIOD CLOSED'
4475   WHERE  CHECKRUN_ID          = l_checkrun_id
4476     AND EXISTS
4477         (SELECT  NULL
4478          FROM    AP_SELECTED_INVOICES_ALL ASI2
4479          WHERE   ASI.INVOICE_ID   =ASI2.INVOICE_ID
4480          AND     ASI.PAYMENT_NUM  = ASI2.PAYMENT_NUM
4481          AND     ASI2.CHECKRUN_ID = l_checkrun_id
4482          AND NOT EXISTS
4483          (SELECT  NULL
4484           FROM    GL_PERIOD_STATUSES GLPS
4485           WHERE   TRUNC(l_check_date) BETWEEN GLPS.START_DATE AND GLPS.END_DATE
4486           AND     GLPS.CLOSING_STATUS  = 'O' --For Payment Only Open Periods are allowed
4487           AND     GLPS.APPLICATION_ID  = 200
4488           AND     GLPS.SET_OF_BOOKS_ID = ASI2.SET_OF_BOOKS_ID));
4489 
4490 
4491   /* Added INDEX(ASI2 AP_SELECTED_INVOICES_N1) And if condition for bug#12725493 */
4492   IF trunc(l_check_date) < trunc(sysdate)
4493   THEN
4494     UPDATE Ap_Selected_Invoices_All ASI
4495     SET    ok_to_pay_flag = 'N',
4496            dont_pay_reason_code =  'PRE DATE NOT ALLOWED'
4497     WHERE  checkrun_id = l_checkrun_id
4498     AND    Exists (SELECT /*+NO_UNNEST INDEX(ASI2 AP_SELECTED_INVOICES_N1)*/ NULL
4499                   FROM  Ap_Selected_Invoices_All ASI2,
4500                         Ap_System_Parameters_All ASP
4501                   WHERE ASI.invoice_id = ASI2.invoice_id
4502                   AND   ASI.payment_num = ASI2.payment_num
4503                   AND   ASI2.checkrun_id = l_checkrun_id
4504                   AND   ASI2.org_id    = ASP.org_id
4505                   AND   ASI2.set_of_books_id = ASP.set_of_books_id
4506                   AND   NVL(ASP.post_dated_payments_flag, 'N') = 'N'
4507                   );
4508   END IF;
4509 --Start of 8217641
4510 
4511 UPDATE AP_SELECTED_INVOICES_ALL ASI
4512   SET    OK_TO_PAY_FLAG   = 'N',
4513          DONT_PAY_REASON_CODE = 'INVALID REMIT SUPPLIER'
4514   WHERE  CHECKRUN_ID          = l_checkrun_id
4515     AND EXISTS
4516         (SELECT  NULL
4517          FROM    AP_SELECTED_INVOICES_ALL ASI2
4518          WHERE   ASI.INVOICE_ID   =ASI2.INVOICE_ID
4519          AND     ASI.PAYMENT_NUM  = ASI2.PAYMENT_NUM
4520          AND     ASI2.CHECKRUN_ID = l_checkrun_id
4521          --introduced for 8403042/8404650
4522          AND EXISTS
4523          (SELECT 1
4524           FROM AP_INVOICES_ALL AI
4525           WHERE AI.INVOICE_ID = ASI2.INVOICE_ID
4526            AND   NVL(AI.RELATIONSHIP_ID,-1) <> -1)
4527         --end of 8403042/8404650
4528          AND NOT EXISTS
4529          (SELECT  NULL
4530           FROM  iby_ext_payee_relationships irel
4531           WHERE irel.party_id = (select party_id
4532                                  from ap_suppliers
4533                                                        where vendor_id = ASI2.vendor_id)
4534            AND irel.supplier_site_id =ASI2.vendor_site_id
4535                  AND irel.remit_party_id =  (select party_id
4536                                             from ap_suppliers
4537                                                                     where vendor_id = ASI2.remit_to_supplier_id)
4538            AND irel.remit_supplier_site_id = ASI2.remit_to_supplier_site_id
4539            AND irel.active = 'Y'
4540            AND to_char(l_check_date,'YYYY-MM-DD HH24:MI:SS')
4541                     BETWEEN(to_char(irel.from_date, 'YYYY-MM-DD')||' 00:00:00')
4542                        AND(to_char(nvl(irel.to_date,l_check_date),'YYYY-MM-DD') || ' 23:59:59')));
4543 
4544 
4545  --End 8217641
4546 
4547   /*BUG :8691645 */
4548 
4549   l_debug_info := 'Calling check_ccr_status ';
4550   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4551      fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4552   END IF;
4553 
4554   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4555     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4556   END IF;
4557 
4558 check_ccr_status  (l_checkrun_id
4559                   ,l_current_calling_sequence);
4560 
4561 
4562 
4563 /* BUG:8691645 */
4564 
4565 
4566   l_debug_info := 'Calling Remove_Invoices';
4567   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4568      fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4569   END IF;
4570 
4571   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4572     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4573   END IF;
4574 
4575   remove_invoices(l_checkrun_id,l_current_calling_sequence);
4576 
4577   l_debug_info := 'Calling Insert_UnselectedL';
4578   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4579      fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4580   END IF;
4581 
4582   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4583     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4584   END IF;
4585 
4586   -- Bug 12798965.
4587   -- Added following parameters.
4588   -- l_pay_thru_date_char
4589   -- l_pay_from_date_char
4590   -- l_check_date_char,
4591   -- l_disc_pay_thru_char
4592 
4593   insert_unselected(  l_payment_process_request_name,
4594                       l_hi_payment_priority,
4595                       l_low_payment_priority,
4596                       l_invoice_batch_id,
4597                       l_inv_vendor_id,
4598                       l_inv_exchange_rate_type,
4599                       l_payment_method,
4600                       l_supplier_type,
4601                       l_le_group_option,
4602                       l_ou_group_option,
4603                       l_currency_group_option,
4604                       l_pay_group_option,
4605                       l_zero_invoices_allowed,
4606                       l_check_date,
4607                       l_checkrun_id,
4608                       l_current_calling_sequence,
4609                       l_party_id,
4610  	              l_pay_thru_date_char,
4611  	              l_pay_from_date_char,
4612  	              l_check_date_char,
4613  	              l_disc_pay_thru_char);
4614 
4615 
4616 
4617   l_debug_info := 'Update amounts in ap_selected_invoices';
4618   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4619     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4620   END IF;
4621 
4622   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4623     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4624   END IF;
4625 
4626 
4627   --PM has said payment request should not take discounts
4628   UPDATE ap_selected_invoices_all asi
4629   SET      (amount_remaining,
4630             discount_amount_remaining,
4631             payment_amount,
4632             proposed_payment_amount,
4633             discount_amount)
4634             =
4635      (SELECT
4636         PS.amount_remaining,
4637         0,
4638         decode(ai.invoice_type_lookup_code,'PAYMENT REQUEST',ps.amount_remaining,
4639 				DECODE(ps.amount_remaining, 0, 0, /* Added DECODE statement for bug 10322208 */
4640 			PS.amount_remaining
4641 			- (DECODE(PS.GROSS_AMOUNT,
4642                    0, 0,
4643                    DECODE(asi.ALWAYS_TAKE_DISCOUNT_FLAG,
4644                           'Y', NVL(PS.DISCOUNT_AMOUNT_AVAILABLE,0),
4645                           GREATEST(DECODE(SIGN(l_check_date
4646                                                - NVL(PS.DISCOUNT_DATE,
4647                                                      TO_DATE('01/01/1901',
4648                                                              'MM/DD/YYYY'))),
4649                                           1, 0,
4650                                           NVL(ABS(PS.DISCOUNT_AMOUNT_AVAILABLE),0)),
4651                                    DECODE(SIGN(l_check_date
4652                                                - NVL(PS.SECOND_DISCOUNT_DATE,
4653                                                      TO_DATE('01/01/1901',
4654                                                              'MM/DD/YYYY'))),
4655                                           1, 0,
4656                                           NVL(ABS(PS.SECOND_DISC_AMT_AVAILABLE),0)),
4657                                    DECODE(SIGN(l_check_date
4658                                                - NVL(PS.THIRD_DISCOUNT_DATE,
4659                                                      TO_DATE('01/01/1901',
4660                                                              'MM/DD/YYYY'))),
4661                                           1, 0,
4662                                           NVL(ABS(PS.THIRD_DISC_AMT_AVAILABLE),0)),
4663                                    0)  * DECODE(SIGN(ps.gross_amount),-1,-1,1))
4664                           * (PS.AMOUNT_REMAINING / DECODE(PS.GROSS_AMOUNT,
4665                                                           0, 1,
4666                                                           prorated_awt_gross_amt(ps.invoice_id, ps.payment_num) )))))),
4667         decode(ai.invoice_type_lookup_code,'PAYMENT REQUEST', ps.amount_remaining,
4668 				DECODE(ps.amount_remaining, 0, 0, /* Added DECODE statement for bug 10322208 */
4669 				PS.amount_remaining
4670 			- (DECODE(PS.GROSS_AMOUNT,
4671                    0, 0,
4672                    DECODE(asi.ALWAYS_TAKE_DISCOUNT_FLAG,
4673                           'Y', NVL(PS.DISCOUNT_AMOUNT_AVAILABLE,0),
4674                           GREATEST(DECODE(SIGN(l_check_date
4675                                                - NVL(PS.DISCOUNT_DATE,
4676                                                      TO_DATE('01/01/1901',
4677                                                              'MM/DD/YYYY'))),
4678                                           1, 0,
4679                                           NVL(ABS(PS.DISCOUNT_AMOUNT_AVAILABLE),0)),
4680                                    DECODE(SIGN(l_check_date
4681                                                - NVL(PS.SECOND_DISCOUNT_DATE,
4682                                                      TO_DATE('01/01/1901',
4683                                                              'MM/DD/YYYY'))),
4684                                           1, 0,
4685                                           NVL(ABS(PS.SECOND_DISC_AMT_AVAILABLE),0)),
4686                                    DECODE(SIGN(l_check_date
4687                                                - NVL(PS.THIRD_DISCOUNT_DATE,
4688                                                      TO_DATE('01/01/1901',
4689                                                              'MM/DD/YYYY'))),
4690                                           1, 0,
4691                                           NVL(ABS(PS.THIRD_DISC_AMT_AVAILABLE),0)),
4692                                    0)  * DECODE(SIGN(ps.gross_amount),-1,-1,1))
4693                           * (PS.AMOUNT_REMAINING / DECODE(PS.GROSS_AMOUNT,
4694                                                           0, 1,
4695                                                           prorated_awt_gross_amt(ps.invoice_id, ps.payment_num) )))))),
4696         decode(ai.invoice_type_lookup_code,'PAYMENT REQUEST', 0,
4697 				DECODE(ps.amount_remaining, 0, 0, /* Added DECODE statement for bug 10322208 */
4698          DECODE(PS.GROSS_AMOUNT,
4699                0, 0,
4700                DECODE(asi.ALWAYS_TAKE_DISCOUNT_FLAG,
4701                       'Y', NVL(PS.DISCOUNT_AMOUNT_AVAILABLE,0),
4702                       GREATEST(DECODE(SIGN(l_check_date
4703                                            - NVL(PS.DISCOUNT_DATE,
4704                                                  TO_DATE('01/01/1901',
4705                                                          'MM/DD/YYYY'))),
4706                                       1, 0,
4707                                       NVL(ABS(PS.DISCOUNT_AMOUNT_AVAILABLE),0)),
4708                                DECODE(SIGN(l_check_date
4709                                            - NVL(PS.SECOND_DISCOUNT_DATE,
4710                                                  TO_DATE('01/01/1901',
4711                                                          'MM/DD/YYYY'))),
4712                                        1, 0,
4713                                        NVL(ABS(PS.SECOND_DISC_AMT_AVAILABLE),0)),
4714                                DECODE(SIGN(l_check_date
4715                                            - NVL(PS.THIRD_DISCOUNT_DATE,
4716                                                  TO_DATE('01/01/1901',
4717                                                          'MM/DD/YYYY'))),
4718                                        1, 0,
4719                                        NVL(ABS(PS.THIRD_DISC_AMT_AVAILABLE),0)),
4720                                 0)   * DECODE(SIGN(ps.gross_amount),-1,-1,1))
4721                       * (PS.AMOUNT_REMAINING / DECODE(PS.GROSS_AMOUNT,
4722                                                       0, 1,
4723                                                       prorated_awt_gross_amt(ps.invoice_id, ps.payment_num) )))))
4724     FROM  ap_payment_schedules_all PS,
4725           ap_invoices ai --Bug6040657. Changed from ap_invoices_all to ap_invoices
4726     WHERE PS.invoice_id = asi.invoice_id
4727     AND   PS.payment_num = asi.payment_num
4728     and   ai.invoice_id = ps.invoice_id)
4729   WHERE checkrun_id = l_checkrun_id;
4730 
4731 
4732   l_debug_info := 'Round amounts in ap_selected_invoices';
4733   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4734     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4735   END IF;
4736 
4737   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4738     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4739   END IF;
4740 
4741 
4742     --round the values we just updated
4743   UPDATE ap_selected_invoices_all ASI
4744   SET    payment_amount = ap_utilities_pkg.ap_round_currency
4745                     (payment_amount,payment_currency_code),
4746          proposed_payment_amount = ap_utilities_pkg.ap_round_currency
4747                     (proposed_payment_amount,payment_currency_code) ,
4748          discount_amount = ap_utilities_pkg.ap_round_currency
4749                     (discount_amount,payment_currency_code)
4750   WHERE  checkrun_id= l_checkrun_id;
4751 
4752 
4753   --get rid of $0 invoices if not allowed
4754   update ap_selected_invoices_all
4755   set ok_to_pay_flag = 'N',
4756   dont_pay_reason_code = 'ZERO INVOICE'
4757   WHERE checkrun_id = l_checkrun_id
4758   AND   l_zero_invoices_allowed = 'N'
4759   AND   amount_remaining = 0;
4760 
4761   l_debug_info := 'Calling Calculate_Interest';
4762   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4763     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4764   END IF;
4765 
4766   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4767     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4768   END IF;
4769 
4770 
4771   calculate_interest (l_checkrun_id,
4772                       l_payment_process_request_name,
4773                       l_check_date,
4774                       l_current_calling_sequence);
4775 
4776   l_debug_info := 'updating exchange rate info';
4777   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4778      fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4779   END IF;
4780 
4781   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4782     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4783   END IF;
4784 
4785 
4786   if l_batch_exchange_rate_type = 'User' then
4787 
4788     update ap_selected_invoices_all asi
4789     set (payment_exchange_rate_type, payment_exchange_rate) =
4790          (select 'User', /* exchange_rate Commented for bug#12660492 */
4791                  /* Added for bug#12660492 Start */
4792                  decode( nvl( fnd_profile.value('DISPLAY_INVERSE_RATE'),'N'),
4793                          'N',exchange_rate,
4794                          'Y', 1/exchange_rate
4795                        )
4796                  /* Added for bug#12660492 End */
4797           from ap_user_exchange_rates auer,
4798                ap_system_parameters_all asp
4799           where asp.org_id = asi.org_id
4800           and   asi.payment_currency_code = auer.payment_currency_code
4801           and   asp.base_currency_code = auer.ledger_currency_code
4802           and   asp.base_currency_code <> asi.payment_currency_code
4803           and   auer.checkrun_id = l_checkrun_id)
4804     where checkrun_id = l_checkrun_id
4805     and (invoice_id, payment_num) in
4806          (select invoice_id, payment_num
4807           from ap_selected_invoices_all asi2,
4808                ap_system_parameters_all asp2
4809           where asp2.org_id = asi2.org_id
4810           and   asp2.base_currency_code <> asi2.payment_currency_code
4811           and   asi2.checkrun_id = l_checkrun_id);
4812 
4813   else
4814   --update for all other exchange rate types
4815 
4816     update ap_selected_invoices asi
4817     set (payment_exchange_rate_type, payment_exchange_rate) =
4818          (select l_batch_exchange_rate_type,
4819                  ap_utilities_pkg.get_exchange_rate(
4820                          asi.payment_currency_code,
4821                          asp.base_currency_code,
4822                          l_batch_exchange_rate_type,
4823                          l_check_date,
4824                          'AUTOSELECT')
4825           from ap_system_parameters_all asp
4826           where asp.org_id = asi.org_id
4827           and asp.base_currency_code <> asi.payment_currency_code)
4828     where checkrun_id = l_checkrun_id
4829     and (invoice_id, payment_num) in
4830          (select invoice_id, payment_num
4831           from ap_selected_invoices_all asi2,
4832                ap_system_parameters_all asp2
4833           where asp2.org_id = asi2.org_id
4834           and   asp2.base_currency_code <> asi2.payment_currency_code
4835           and   asi2.checkrun_id = l_checkrun_id);  --Bug 5123855
4836 
4837 
4838 
4839   end if;
4840 
4841   select count(*)
4842   into l_missing_rates_count
4843   from ap_selected_invoices_all asi,
4844        ap_system_parameters_all asp
4845   where asi.org_id = asp.org_id
4846   and asi.checkrun_id = l_checkrun_id
4847   and asi.payment_currency_code <> asp.base_currency_code
4848   and asi.payment_exchange_rate is null
4849   and ((l_batch_exchange_rate_type <> 'User'
4850        and asp.make_rate_mandatory_flag = 'Y') OR
4851        l_batch_exchange_rate_type = 'User')
4852   and rownum = 1;
4853 
4854 
4855 --need to pause the request if payables options requires exchange rates
4856 --and none were found or we are using 'user'exchange rate type
4857 
4858   if l_missing_rates_count > 0 then
4859     update ap_inv_selection_criteria_all
4860     set status = 'MISSING RATES'
4861     where checkrun_id = l_checkrun_id;
4862 
4863     if l_batch_exchange_rate_type = 'User' then
4864       insert into ap_user_exchange_rates auer
4865        (checkrun_id,
4866         payment_currency_code,
4867         ledger_currency_code,
4868         creation_date,
4869         created_by,  --Bug 5123855
4870         last_update_date,
4871         last_updated_by,
4872         last_update_login)
4873       (select l_checkrun_id,
4874                asi.payment_currency_code,
4875                asp.base_currency_code,
4876                SYSDATE,
4877                FND_GLOBAL.user_id,
4878                SYSDATE,
4879                FND_GLOBAL.user_id,
4880                FND_GLOBAL.login_id
4881         from ap_selected_invoices_all asi,
4882              ap_system_parameters_all asp
4883         where asi.payment_exchange_rate is null
4884         and asp.org_id = asi.org_id
4885         and asp.base_currency_code <> asi.payment_currency_code
4886         and asi.checkrun_id = l_checkrun_id
4887         group by asi.payment_currency_code,   /* bug 5447896 */
4888                  asp.base_currency_code);
4889     end if;
4890   end if;
4891 
4892   /* Bug 7683143: Moved the Withholding creation towards the end so that
4893      Withholding invoices is created only for the invoices which have
4894      been finally selected for the PPR, and not for Invoices which
4895      have been de-selected from the PPR. */
4896 
4897 
4898     /* BUG 14498596 Start - Moved Withholding Tax logic before grouping of invoices */
4899 
4900   l_debug_info := 'Calling ap_withholding_pkg';
4901   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4902     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4903   END IF;
4904 
4905   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4906     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4907   END IF;
4908 
4909 
4910   AP_WITHHOLDING_PKG.AP_WITHHOLD_AUTOSELECT(
4911                         l_payment_process_request_name,
4912                         FND_GLOBAL.USER_ID,
4913                         FND_GLOBAL.LOGIN_ID,
4914                         FND_GLOBAL.PROG_APPL_ID,
4915                         FND_GLOBAL.CONC_PROGRAM_ID,
4916                         FND_GLOBAL.CONC_REQUEST_ID,
4917                         l_checkrun_id);
4918 
4919 --Bug6459578
4920   l_debug_info := 'Calling ap_custom_withholding_pkg';
4921   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4922     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4923   END IF;
4924 
4925   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4926     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4927   END IF;
4928 
4929   Awt_special_rounding(l_checkrun_id,l_current_calling_sequence);
4930 
4931 --Bug6459578
4932 
4933  l_debug_info := 'Grouping selected invoices';
4934   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
4935       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
4936   END IF;
4937 
4938   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4939     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
4940   END IF;
4941 
4942 
4943   group_interest_credits(l_checkrun_id, l_current_calling_sequence);
4944 
4945   /* Code Added for bug#8461050 Start */
4946   /* Need to gather table stat for ap_selected_invoices_all Since all insert/ update has
4947      already been done on the table */
4948   IF (   FND_INSTALLATION.GET_APP_INFO('SQLAP', l_status, l_industry, l_schema)
4949      AND nvl( fnd_profile.value('AP_GATHER_PPR_TABLE_STATS'), 'N') = 'Y'
4950      )
4951   THEN
4952      IF l_schema IS NOT NULL    THEN
4953         FND_STATS.GATHER_TABLE_STATS(l_schema, 'AP_SELECTED_INVOICES_ALL');
4954         FND_STATS.GATHER_TABLE_STATS(l_schema, 'AP_UNSELECTED_INVOICES_ALL'); /* Added for bug#10053374 */
4955      END IF;
4956   END IF;
4957 
4958   /* BUG 14498596 END - Moved Withholding Tax logic before grouping of invoices */
4959 
4960   /* BUG 14498596 Start - Added logic to Undo With-Holding Tax on Rejected Invoices durin PPR */
4961 
4962   DECLARE
4963   cursor c_dont_pay_invoices (p_checkrun_id number) is
4964   select invoice_id,
4965          vendor_id,
4966          payment_num,
4967          checkrun_id,
4968          withholding_amount,
4969          checkrun_name
4970   from ap_selected_invoices_all
4971   where checkrun_id = p_checkrun_id
4972   and ok_to_pay_flag = 'N';
4973 
4974  rec_dont_pay_invoices c_dont_pay_invoices%ROWTYPE;
4975 
4976  BEGIN
4977 
4978  OPEN c_dont_pay_invoices(p_checkrun_id);
4979 
4980   LOOP
4981     l_debug_info := 'Fetch CURSOR for all UN-SELECTed invoices';
4982     FETCH c_dont_pay_invoices INTO rec_dont_pay_invoices;
4983     EXIT WHEN c_dont_pay_invoices%NOTFOUND;
4984 
4985     DECLARE
4986       undo_output VARCHAR2(2000);
4987     BEGIN
4988 	  /* Added below update for bug 8888311 */
4989 
4990 	    UPDATE ap_awt_temp_distributions_all aatd
4991 		   SET withholding_amount = rec_dont_pay_invoices.withholding_amount
4992 		 WHERE invoice_id    = rec_dont_pay_invoices.invoice_id
4993            AND payment_num   =rec_dont_pay_invoices.payment_num
4994            AND checkrun_id   = rec_dont_pay_invoices.checkrun_id
4995 		   AND nvl(rec_dont_pay_invoices.withholding_amount,0) = 0;
4996 
4997         AP_WITHHOLDING_PKG.Ap_Undo_Temp_Withholding
4998                      (P_Invoice_Id             => rec_dont_pay_invoices.invoice_id
4999                      ,P_VENDor_Id              => rec_dont_pay_invoices.vendor_id
5000                      ,P_Payment_Num            => rec_dont_pay_invoices.payment_num
5001                      ,P_Checkrun_Name          => rec_dont_pay_invoices.checkrun_name
5002                      ,P_Undo_Awt_Date          => SYSDATE
5003                      ,P_Calling_Module         => 'AUTOSELECT'
5004                      ,P_Last_Updated_By        => FND_GLOBAL.USER_ID
5005                      ,P_Last_Update_Login      => FND_GLOBAL.LOGIN_ID
5006                      ,P_Program_Application_Id => FND_GLOBAL.PROG_APPL_ID
5007                      ,P_Program_Id             => FND_GLOBAL.CONC_PROGRAM_ID
5008                      ,P_Request_Id             => FND_GLOBAL.CONC_REQUEST_ID
5009                      ,P_Awt_Success            => undo_output
5010                      ,P_checkrun_id            => p_checkrun_id );
5011 
5012     END;
5013   END LOOP;
5014 
5015   l_debug_info := 'CLOSE CURSOR for all UN-SELECTed invoices';
5016   CLOSE c_dont_pay_invoices;
5017 
5018   END;
5019 
5020 /* BUG 14498596 END - Added logic to Undo With-Holding Tax on Rejected Invoices durin PPR */
5021 
5022   remove_invoices (l_checkrun_id, l_current_calling_sequence );
5023 
5024 --Overpayment Prevention, Bug 9440897
5025   mark_overpayments(l_checkrun_id, l_payment_process_request_name, l_current_calling_sequence);
5026 
5027   remove_invoices (l_checkrun_id, l_current_calling_sequence);
5028 
5029 
5030 
5031   --the rejection levels can be changed in our awt code, hence they need to be
5032   --retrieved after the call above
5033   -- Bug 7492768 Start
5034   -- We need to retrieve inv_awt_exists_flag that determines whether
5035   -- the PPR contains invoices that have AWT.
5036   -- If the flag is set then the invoice contains AWT and we must pass the
5037   -- rejection level code as REQUEST to IBY apis. Otherwise we can pass the same
5038   -- value defined by the user.
5039   select document_rejection_level_code,
5040          payment_rejection_level_code,
5041          inv_awt_exists_flag
5042   into   l_doc_rejection_level_code,
5043          l_pay_rejection_level_code,
5044          l_inv_awt_exists_flag
5045   from   ap_inv_selection_criteria_all
5046   where  checkrun_id = l_checkrun_id;
5047 
5048 
5049    --Start bug12349626
5050       --Check if inv_awt_Exists_flag is Y,if yes, then update asi
5051       -- this avoids running the update on asi unless necessary
5052 
5053       IF NVL(l_inv_awt_exists_flag, 'N') = 'Y' THEN
5054        update ap_selected_invoices_All asi
5055        set asi.AFFECTS_REJECTION_LEVEL= 'Y'
5056        where asi.checkrun_id = l_checkrun_id
5057        and  exists ( select 'ATLEAST ONE RANGE BASED PAY TIME AWT'
5058                     from ap_invoice_distributions_all aid,
5059                          AP_AWT_GROUP_TAXES_all awtt,
5060                          ap_tax_codes_all awtc
5061                    where aid.invoice_id = asi.invoice_id
5062                    and aid.pay_awt_group_id is not null
5063                    and awtt.group_id = aid.pay_awt_group_id
5064                    and awtt.tax_name = awtc.name
5065                    and awtc.tax_type = 'AWT'
5066                    and awtc.awt_rate_type <> 'F'
5067                    and awtc.enabled_flag = 'Y'
5068                    and NVL(asi.invoice_date,SYSDATE) BETWEEN
5069                        NVL(awtc.start_date,NVL(asi.invoice_date,SYSDATE)) AND
5070                       NVL(awtc.inactive_date,NVL(asi.invoice_date,SYSDATE))
5071                 );
5072      END IF;
5073 
5074     --End bug12349626
5075 
5076 
5077   /* Bug 12349626 Commenting out the IF clause below that is resetting of PPR
5078      rejection level. This functionality is now handled using the new column in
5079      asi- AFFECTS_REJECTION_LEVEL
5080 
5081   -- Bug 8746215 If flag is Y then set rejection levels as PAYEE if they are not REQUEST.
5082   IF NVL(l_inv_awt_exists_flag, 'N') = 'Y' THEN
5083     IF l_doc_rejection_level_code <> 'REQUEST' THEN
5084       l_doc_rejection_level_code := 'PAYEE';
5085     END IF;
5086     IF l_pay_rejection_level_code <> 'REQUEST' THEN
5087       l_pay_rejection_level_code := 'PAYEE';
5088     END IF;
5089     -- Bug 8746215 End
5090   END IF;
5091   -- Bug 7492768 End
5092 
5093   End of commenting code for bug12349626 */
5094 
5095 
5096 
5097   --4745133, moved the code below to this position
5098   --as we could have removed invoices in the ppr
5099   --after they have been inserted into asi
5100 
5101   select count(*)
5102   into l_count_inv_selected
5103   from ap_selected_invoices_all
5104   where checkrun_id = l_checkrun_id
5105   and rownum = 1;
5106 
5107 
5108   if l_count_inv_selected = 0 then
5109 
5110     update ap_inv_selection_criteria_all
5111     set status = 'CANCELLED NO PAYMENTS'
5112     where checkrun_id = l_checkrun_id;
5113 
5114     commit;
5115 
5116     fnd_file.put_line(FND_FILE.LOG, 'No scheduled payments matched the invoice selection criteria');
5117 
5118     l_debug_info :=  'No scheduled payments matched the invoice selection criteria';
5119     IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5120       FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
5121     END IF;
5122 
5123    -- Bug 5111495
5124    -- app_exception.raise_exception;
5125 
5126     return;
5127   end if;
5128 
5129 
5130 
5131 
5132   --5007587
5133   declare
5134 
5135   l_init_msg_list varchar2(2000);
5136   l_return_status varchar2(1);
5137   l_msg_count number;
5138   l_msg_data varchar2(2000);
5139   l_msg_index_out number;
5140 
5141   begin
5142 
5143     FV_FEDERAL_PAYMENT_FIELDS_PKG.SUBMIT_CASH_POS_REPORT(
5144       p_init_msg_list => l_init_msg_list,
5145       p_org_id        => null,
5146       p_checkrun_id   => l_checkrun_id,
5147       x_request_id    => l_req_id,
5148       x_return_status => l_return_status,
5149       x_msg_count     => l_msg_count,
5150       x_msg_data      => l_msg_data);
5151 
5152     if l_return_status <> FND_API.G_RET_STS_SUCCESS then
5153       IF l_msg_count > 0 THEN
5154           FOR i in 1..l_msg_count LOOP
5155             FND_MSG_PUB.Get( p_msg_index     => i,
5156                              p_encoded       => 'F',
5157                              p_data          => l_msg_data,
5158                              p_msg_index_out => l_msg_index_out);
5159             FND_FILE.Put_Line(FND_FILE.Log,l_msg_data);
5160           End LOOP;
5161       end if;
5162     end if;
5163   end;
5164   --end 5007857
5165 
5166 
5167 
5168 
5169 
5170   update ap_inv_selection_criteria_all
5171   set status = decode(l_payables_review_settings,'Y','REVIEW','SELECTED')
5172   where status = 'SELECTING'
5173   and checkrun_id = l_checkrun_id;
5174 
5175   -- Bug 4681857
5176   SELECT lower(iso_language),iso_territory
5177     INTO l_iso_language,l_iso_territory
5178     FROM FND_LANGUAGES
5179    WHERE language_code = USERENV('LANG');
5180 
5181    --Bug 6969710
5182    /* Commented for bug#12917747 Start
5183    SELECT nvl(template_code, 'APINVSEL' )
5184      INTO l_template_code
5185      FROM Fnd_Concurrent_Programs
5186      WHERE concurrent_program_name = 'APINVSEL'; --Bug 6969710
5187    Commented for bug#12917747 End */
5188 
5189    /* Added for bug#12917747 Start */
5190    SELECT nvl(template_code, 'APINVSEL' )
5191         , (SELECT Nvl(DEFAULT_OUTPUT_TYPE,'PDF')
5192              FROM XDO_TEMPLATES_B xtb
5193             WHERE xtb.TEMPLATE_CODE = nvl(fcp.template_code, 'APINVSEL' )
5194               AND APPLICATION_ID    = 200
5195               AND rownum = 1
5196           )
5197      INTO l_template_code
5198         , l_output_format
5199      FROM Fnd_Concurrent_Programs fcp
5200     WHERE concurrent_program_name = 'APINVSEL';
5201    /* Added for bug#12917747 End */
5202 
5203   l_xml_output:=  fnd_request.add_layout(
5204                         template_appl_name  => 'SQLAP',
5205                         template_code       => l_template_code ,   --Bug 6969710
5206                         template_language   => l_iso_language,
5207                         template_territory  => l_iso_territory ,
5208                         output_format       => l_output_format   /* Bug#12917747 */
5209                             );
5210 
5211    --below code added for bug#7435751 as we need to set the current nls character setting
5212    fnd_profile.get('ICX_NUMERIC_CHARACTERS',l_icx_numeric_characters);
5213    l_return_status:= FND_REQUEST.SET_OPTIONS( numeric_characters => l_icx_numeric_characters);
5214 
5215   --submit the selected payment schedules report
5216   l_req_id := FND_REQUEST.SUBMIT_REQUEST(
5217                   'SQLAP',
5218                   'APINVSEL',
5219                   '',
5220                   '',
5221                   FALSE,
5222                   to_char(l_checkrun_id),
5223                   chr(0));
5224 
5225   select status
5226   into l_batch_status
5227   from ap_inv_selection_criteria_all
5228   where checkrun_id = l_checkrun_id;
5229 
5230   if l_batch_status = 'SELECTED' and l_payables_review_settings <> 'Y' then
5231 
5232     l_debug_info := 'Submitting Oracle Payments Build';
5233     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
5234       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
5235     END IF;
5236 
5237     l_req_id := FND_REQUEST.SUBMIT_REQUEST(
5238                   'IBY',
5239                   'IBYBUILD',
5240                   '',
5241                   '',
5242                   FALSE,
5243                   '200',
5244                   l_payment_process_request_name,
5245                   to_char(l_bank_account_id),
5246                   to_char(l_payment_profile_id),
5247                   l_zero_invoices_allowed, -- Bug 6523501,
5248                   to_char(l_max_payment_amount),
5249                   to_char(l_min_check_amount),
5250                   l_doc_rejection_level_code,
5251                   l_pay_rejection_level_code,
5252                   l_pay_review_settings_flag,
5253                   l_create_instrs_flag,
5254                   l_payment_document_id,
5255                   /* bug 7519277*/
5256                 l_ATTRIBUTE_CATEGORY,
5257                 l_ATTRIBUTE1,
5258                 l_ATTRIBUTE2,
5259                 l_ATTRIBUTE3,
5260                 l_ATTRIBUTE4,
5261                 l_ATTRIBUTE5,
5262                 l_ATTRIBUTE6,
5263                 l_ATTRIBUTE7,
5264                 l_ATTRIBUTE8,
5265                 l_ATTRIBUTE9,
5266                 l_ATTRIBUTE10,
5267                 l_ATTRIBUTE11,
5268                 l_ATTRIBUTE12,
5269                 l_ATTRIBUTE13,
5270                 l_ATTRIBUTE14,
5271                 l_ATTRIBUTE15,
5272         /*bug 7519277*/
5273                   chr(0));
5274 
5275     l_debug_info := 'request_id ='||to_char(l_req_id);
5276     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
5277       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
5278     END IF;
5279     /* Bug 11063950 : Populated Request_id in ap_inv_selection_criteria_all */
5280     update ap_inv_selection_criteria_all
5281     set request_id = l_req_id
5282     where checkrun_id = l_checkrun_id;
5283   end if;
5284 
5285   COMMIT;
5286 
5287 EXCEPTION
5288 
5289     WHEN OTHERS then
5290 
5291     IF (SQLCODE <> -20001) THEN
5292       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
5293       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
5294       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
5295       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
5296       FND_MESSAGE.SET_TOKEN('PARAMETERS','p_checkrun_id '||p_checkrun_id
5297                             ||',P_template_id '||P_template_id
5298                             ||',p_payment_date '||p_payment_date
5299                             ||',p_pay_thru_date '||p_pay_thru_date
5300                             ||',p_pay_from_date '||p_pay_from_date);
5301 
5302 
5303 
5304     END IF;
5305     APP_EXCEPTION.RAISE_EXCEPTION;
5306 
5307 END SELECT_INVOICES;
5308 
5309 
5310 PROCEDURE recalculate (errbuf             OUT NOCOPY VARCHAR2,
5311                        retcode            OUT NOCOPY NUMBER,
5312                        p_checkrun_id      in         varchar2,
5313                        p_submit_to_iby    in  varchar2 default 'N') is
5314 
5315   l_debug_info               varchar2(2000);
5316   l_checkrun_name            ap_inv_selection_criteria_all.checkrun_name%type;-- bug# 6643035
5317   l_check_date               date;
5318   l_bank_account_id          number; --4710933
5319   l_payment_profile_id       number;
5320   l_req_id                   number;
5321   l_zero_amounts_allowed     varchar2(1);
5322   l_zero_invoices_allowed    varchar2(1); -- Bug 6523501
5323   l_max_payment_amount       number;
5324   l_min_check_amount         number;
5325   l_doc_rejection_level_code varchar2(30);
5326   l_pay_rejection_level_code varchar2(30);
5327   l_pay_review_settings_flag varchar2(1);
5328   l_create_instrs_flag       varchar2(1);
5329   l_missing_rates_count      number;
5330   l_batch_exchange_rate_type varchar2(30);
5331   l_batch_status             varchar2(30);
5332   l_payment_document_id      number(15); --4939405
5333   l_xml_output               BOOLEAN;
5334   l_iso_language             FND_LANGUAGES.iso_language%TYPE;
5335   l_iso_territory            FND_LANGUAGES.iso_territory%TYPE;
5336   l_template_code      Fnd_Concurrent_Programs.template_code%TYPE; --Bug 6969710
5337   l_output_format      XDO_TEMPLATES_B.DEFAULT_OUTPUT_TYPE%TYPE; /* Bug#12917747 */
5338    /*bug 7519277*/
5339   l_ATTRIBUTE_CATEGORY       VARCHAR2(150);
5340   l_ATTRIBUTE1               VARCHAR2(150);
5341   l_ATTRIBUTE2               VARCHAR2(150);
5342   l_ATTRIBUTE3               VARCHAR2(150);
5343   l_ATTRIBUTE4               VARCHAR2(150);
5344   l_ATTRIBUTE5               VARCHAR2(150);
5345   l_ATTRIBUTE6               VARCHAR2(150);
5346   l_ATTRIBUTE7               VARCHAR2(150);
5347   l_ATTRIBUTE8               VARCHAR2(150);
5348   l_ATTRIBUTE9               VARCHAR2(150);
5349   l_ATTRIBUTE10              VARCHAR2(150);
5350   l_ATTRIBUTE11              VARCHAR2(150);
5351   l_ATTRIBUTE12              VARCHAR2(150);
5352   l_ATTRIBUTE13              VARCHAR2(150);
5353   l_ATTRIBUTE14              VARCHAR2(150);
5354   l_ATTRIBUTE15              VARCHAR2(150);
5355   /*bug 7519277*/
5356   l_icx_numeric_characters   VARCHAR2(30); --for bug#7435751
5357   l_return_status   boolean; --for bug#7435751
5358   l_inv_awt_exists_flag      varchar2(1);  --bug12349626
5359 
5360 
5361 
5362 
5363   CURSOR c_all_sel_invs  IS
5364     SELECT invoice_id
5365     ,      vendor_id
5366     ,      payment_num
5367     ,      checkrun_id         	--bug 8888311
5368     ,      withholding_amount 	--bug 8888311
5369     FROM   ap_SELECTed_invoices_all ASI,
5370            ap_system_parameters_all asp
5371     WHERE  checkrun_name = l_checkrun_name
5372       AND  original_invoice_id IS NULL
5373       AND  asp.org_id = asi.org_id
5374       and  checkrun_id = p_checkrun_id
5375        AND  decode(nvl(ASP.allow_awt_flag, 'N'), 'Y',
5376                   decode(ASP.create_awt_dists_type,'BOTH','Y','PAYMENT',
5377                          'Y', decode(ASP.create_awt_invoices_type,'BOTH','Y','PAYMENT',
5378                                      'Y', 'N'),
5379                          'N'),
5380                   'N') = 'Y'; --Bug6660355
5381   rec_all_sel_invs c_all_sel_invs%ROWTYPE;
5382 
5383   l_current_calling_sequence varchar2(2000);
5384 
5385 
5386 
5387 BEGIN
5388 
5389 
5390 --in 11.5 we can do the undo and re-do of awt all at the same time
5391 --but if I am to handle interest here instead of the front end then
5392 --this cannot be done, we have to do interest calculations after awt
5393 --is undone
5394 
5395   --4676790, since this code runs as a concurrent request the calling
5396   --code should update the status.
5397 
5398 
5399   l_current_calling_sequence := 'ap_autoselect_pkg.recalculate';
5400 
5401   -- Bug 12566346. Start.
5402   -- Need to restore the exclusive_payment_flag for
5403   -- for original payment schedules from invoice header.
5404 
5405   l_debug_info := 'Recalculate: restoring exclusive_payment_flag.';
5406   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
5407     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
5408   END IF;
5409 
5410   update ap_selected_invoices_all asi
5411   set    exclusive_payment_flag = (select nvl(exclusive_payment_flag, 'N')
5412                                    from ap_invoices_all
5413                                    where invoice_id = asi.invoice_id)
5414   where  checkrun_id = p_checkrun_id
5415   and    exists
5416          ( select 1
5417            from   ap_selected_invoices_all asi2
5418            where  asi2.original_invoice_id is not null
5419            and    asi2.original_invoice_id = asi.invoice_id
5420            and    asi2.ok_to_pay_flag = 'Y'
5421            and    asi2.checkrun_id = p_checkrun_id
5422          );
5423 
5424   -- Bug 12566346. End.
5425 
5426   l_debug_info:= 'delete interest invoices';
5427 
5428 
5429   delete from ap_selected_invoices_all
5430   where checkrun_id = p_checkrun_id
5431   and original_invoice_id is not null;
5432 
5433   SELECT
5434         checkrun_name,
5435         check_date,
5436         nvl(zero_amounts_allowed,'N'),
5437         nvl(zero_invoices_allowed,'N'), -- Bug 6523501
5438         bank_account_id, --4710933
5439         payment_profile_id,
5440         max_payment_amount,
5441         min_check_amount,
5442         payments_review_settings,
5443         --decode(payment_profile_id,null,'N',nvl(create_instrs_flag,'N')),
5444 	nvl(create_instrs_flag,'N'),    -- Commented and added for bug 8925444
5445         document_rejection_level_code,
5446         payment_rejection_level_code,
5447         exchange_rate_type,
5448         payment_document_id,
5449         /*bug 7519277*/
5450                 ATTRIBUTE_CATEGORY,
5451                 ATTRIBUTE1,
5452                 ATTRIBUTE2,
5453                 ATTRIBUTE3,
5454                 ATTRIBUTE4,
5455                 ATTRIBUTE5,
5456                 ATTRIBUTE6,
5457                 ATTRIBUTE7,
5458                 ATTRIBUTE8,
5459                 ATTRIBUTE9,
5460                 ATTRIBUTE10,
5461                 ATTRIBUTE11,
5462                 ATTRIBUTE12,
5463                 ATTRIBUTE13,
5464                 ATTRIBUTE14,
5465                 ATTRIBUTE15
5466         /*bug 7519277*/
5467   INTO  l_checkrun_name,
5468         l_check_date,
5469         l_zero_amounts_allowed,
5470         l_zero_invoices_allowed, -- Bug 6523501
5471         l_bank_account_id,
5472         l_payment_profile_id,
5473         l_max_payment_amount,
5474         l_min_check_amount,
5475         l_pay_review_settings_flag,
5476         l_create_instrs_flag,
5477         l_doc_rejection_level_code,
5478         l_pay_rejection_level_code,
5479         l_batch_exchange_rate_type,
5480         l_payment_document_id,
5481         /* bug 7519277*/
5482                 l_ATTRIBUTE_CATEGORY,
5483                 l_ATTRIBUTE1,
5484                 l_ATTRIBUTE2,
5485                 l_ATTRIBUTE3,
5486                 l_ATTRIBUTE4,
5487                 l_ATTRIBUTE5,
5488                 l_ATTRIBUTE6,
5489                 l_ATTRIBUTE7,
5490                 l_ATTRIBUTE8,
5491                 l_ATTRIBUTE9,
5492                 l_ATTRIBUTE10,
5493                 l_ATTRIBUTE11,
5494                 l_ATTRIBUTE12,
5495                 l_ATTRIBUTE13,
5496                 l_ATTRIBUTE14,
5497                 l_ATTRIBUTE15
5498         /*bug 7519277*/
5499   FROM   ap_inv_selection_criteria_all
5500   WHERE  checkrun_id  = p_checkrun_id;
5501 
5502 
5503 
5504 
5505 --undo awt, this is essentially the same code as in ap_withholding_pkg
5506 
5507   OPEN c_all_sel_invs;
5508 
5509   LOOP
5510     l_debug_info := 'Fetch CURSOR for all SELECTed invoices';
5511     FETCH c_all_sel_invs INTO rec_all_sel_invs;
5512     EXIT WHEN c_all_sel_invs%NOTFOUND;
5513 
5514     DECLARE
5515       undo_output VARCHAR2(2000);
5516     BEGIN
5517 	  /* Added below update for bug 8888311 */
5518 
5519 	    UPDATE ap_awt_temp_distributions_all aatd
5520 		   SET withholding_amount = rec_all_sel_invs.withholding_amount
5521 		 WHERE invoice_id    = rec_all_sel_invs.invoice_id
5522            AND payment_num   = rec_all_sel_invs.payment_num
5523            AND checkrun_id   = rec_all_sel_invs.checkrun_id
5524 		   AND nvl(rec_all_sel_invs.withholding_amount,0) = 0;
5525 
5526         AP_WITHHOLDING_PKG.Ap_Undo_Temp_Withholding
5527                      (P_Invoice_Id             => rec_all_sel_invs.invoice_id
5528                      ,P_VENDor_Id              => rec_all_sel_invs.vendor_id
5529                      ,P_Payment_Num            => rec_all_sel_invs.payment_num
5530                      ,P_Checkrun_Name          => l_Checkrun_Name
5531                      ,P_Undo_Awt_Date          => SYSDATE
5532                      ,P_Calling_Module         => 'AUTOSELECT'
5533                      ,P_Last_Updated_By        => FND_GLOBAL.USER_ID
5534                      ,P_Last_Update_Login      => FND_GLOBAL.LOGIN_ID
5535                      ,P_Program_Application_Id => FND_GLOBAL.PROG_APPL_ID
5536                      ,P_Program_Id             => FND_GLOBAL.CONC_PROGRAM_ID
5537                      ,P_Request_Id             => FND_GLOBAL.CONC_REQUEST_ID
5538                      ,P_Awt_Success            => undo_output
5539                      ,P_checkrun_id            => p_checkrun_id );
5540 
5541     END;
5542   END LOOP;
5543 
5544   l_debug_info := 'CLOSE CURSOR for all SELECTed invoices';
5545   CLOSE c_all_sel_invs;
5546 
5547 
5548 
5549   update ap_selected_invoices_all
5550   set payment_grouping_number = null
5551   where checkrun_id = p_checkrun_id;
5552 
5553   -- Bug 7492768 We need to reset the inv_awt_exists_flag which indicates if the
5554   -- check run contains invoice that has awt.
5555   update ap_inv_selection_criteria_all
5556   set inv_awt_exists_flag = 'N'
5557   where checkrun_id = p_checkrun_id;
5558 
5559 --redo interest
5560   calculate_interest (p_checkrun_id,
5561                       l_checkrun_name,
5562                       l_check_date,
5563                       l_current_calling_sequence);
5564 
5565   -- Bug 9255192 Exchange rate updation should occur before calculating awt
5566   -- Moved the following code before AP_WITHHOLDING_PKG.AP_WITHHOLD_AUTOSELECT
5567   -- Code flow should be same as mentioned in Procedure Select_Invoices
5568 
5569    l_debug_info := 'Recalculate: Updating Exchage rate info';
5570    IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
5571      fnd_file.put_line(FND_FILE.LOG,l_debug_info);
5572    END IF;
5573 
5574    l_debug_info := 'Recalculate: Exchange Rate type is :'||l_batch_exchange_rate_type;
5575    IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
5576      fnd_file.put_line(FND_FILE.LOG,l_debug_info);
5577    END IF;
5578 
5579   if l_batch_exchange_rate_type = 'User' then
5580 
5581     update ap_selected_invoices_all asi
5582     set (payment_exchange_rate_type, payment_exchange_rate) =
5583          (select 'User', /* exchange_rate Commented for bug#12660492 */
5584                  /* Added for bug#12660492 Start */
5585                  decode( nvl( fnd_profile.value('DISPLAY_INVERSE_RATE'),'N'),
5586                          'N',exchange_rate,
5587                          'Y', 1/exchange_rate
5588                        )
5589                  /* Added for bug#12660492 End */
5590           from ap_user_exchange_rates auer,
5591                ap_system_parameters_all asp
5592           where asp.org_id = asi.org_id
5593           and   asi.payment_currency_code = auer.payment_currency_code
5594           and   asp.base_currency_code = auer.ledger_currency_code
5595           and   asp.base_currency_code <> asi.payment_currency_code
5596           and   auer.checkrun_id = p_checkrun_id)  --Bug 5123855
5597     where checkrun_id = p_checkrun_id
5598     and (invoice_id, payment_num) in
5599          (select invoice_id, payment_num
5600           from ap_selected_invoices_all asi2,
5601                ap_system_parameters_all asp2
5602           where asp2.org_id = asi2.org_id
5603           and   asp2.base_currency_code <> asi2.payment_currency_code
5604           and   asi2.checkrun_id = p_checkrun_id);
5605 
5606   else
5607   --update for all other exchange rate types
5608 
5609     update ap_selected_invoices asi
5610     set (payment_exchange_rate_type, payment_exchange_rate) =
5611          (select l_batch_exchange_rate_type,
5612                  ap_utilities_pkg.get_exchange_rate(
5613                          asi.payment_currency_code,
5614                          asp.base_currency_code,
5615                          l_batch_exchange_rate_type,
5616                          l_check_date,
5617                          'AUTOSELECT')
5618           from ap_system_parameters_all asp
5619           where asp.org_id = asi.org_id
5620           and asp.base_currency_code <> asi.payment_currency_code)
5621     where checkrun_id = p_checkrun_id
5622     and (invoice_id, payment_num) in
5623          (select invoice_id, payment_num
5624           from ap_selected_invoices_all asi2,
5625                ap_system_parameters_all asp2
5626           where asp2.org_id = asi2.org_id
5627           and   asp2.base_currency_code <> asi2.payment_currency_code
5628           and   asi2.checkrun_id = p_checkrun_id);
5629 
5630   end if;
5631 
5632   select count(*)
5633   into l_missing_rates_count
5634   from ap_selected_invoices_all asi,
5635        ap_system_parameters_all asp
5636   where asi.org_id = asp.org_id
5637   and asi.checkrun_id = p_checkrun_id
5638   and asi.payment_currency_code <> asp.base_currency_code
5639   and asi.payment_exchange_rate is null
5640   and ((l_batch_exchange_rate_type <> 'User'
5641        and asp.make_rate_mandatory_flag = 'Y') OR
5642        l_batch_exchange_rate_type = 'User')
5643   and rownum = 1;
5644 
5645 
5646   if l_missing_rates_count > 0 then
5647 
5648     update ap_inv_selection_criteria_all
5649     set status = 'MISSING RATES'
5650     where checkrun_id = p_checkrun_id;
5651 
5652     if l_batch_exchange_rate_type = 'User' then
5653       insert into ap_user_exchange_rates auer
5654        (checkrun_id,
5655         payment_currency_code,
5656         ledger_currency_code,
5657         creation_date,  --Bug 5123855
5658         created_by,
5659         last_update_date,
5660         last_updated_by,
5661         last_update_login)
5662        (select p_checkrun_id,
5663                asi.payment_currency_code,
5664                asp.base_currency_code,
5665                SYSDATE,
5666                FND_GLOBAL.user_id,
5667                SYSDATE,
5668                FND_GLOBAL.user_id,
5669                FND_GLOBAL.login_id
5670         from ap_selected_invoices_all asi,
5671              ap_system_parameters_all asp
5672         where asi.payment_exchange_rate is null
5673         and asp.org_id = asi.org_id
5674         and asp.base_currency_code <> asi.payment_currency_code
5675         and asi.checkrun_id = p_checkrun_id
5676         and not exists (select 'row already in auer'
5677                         from ap_user_exchange_rates auer2
5678                         where auer2.checkrun_id = asi.checkrun_id
5679                         and   auer2.payment_currency_code = asi.payment_currency_code
5680                         and   auer2.ledger_currency_code = asp.base_currency_code));
5681 
5682     end if;
5683   end if;
5684 
5685    /* BUG 14498596 Start - Moved Withholding Tax logic before grouping of invoices */
5686 
5687 --redo awt
5688   AP_WITHHOLDING_PKG.AP_WITHHOLD_AUTOSELECT(
5689                         l_checkrun_name,
5690                         FND_GLOBAL.USER_ID,
5691                         FND_GLOBAL.LOGIN_ID,
5692                         FND_GLOBAL.PROG_APPL_ID,
5693                         FND_GLOBAL.CONC_PROGRAM_ID,
5694                         FND_GLOBAL.CONC_REQUEST_ID,
5695                         p_checkrun_id);
5696 
5697   -- Start Bug 6743242
5698 
5699   l_debug_info := 'Calling ap_custom_withholding_pkg';
5700   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
5701     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
5702   END IF;
5703 
5704   IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5705     FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||'.recalculate',l_debug_info);
5706   END IF;
5707 
5708   awt_special_rounding(p_checkrun_id,l_current_calling_sequence);
5709 
5710   -- End Bug 6743242
5711 
5712   --Bug 9255311 Regroup should occur before withholding so that orphans are not
5713 --left in ap_awt_temp_distributions_all
5714 --regroup
5715 
5716   group_interest_credits(p_checkrun_id, l_current_calling_sequence);
5717 
5718 --Overpayment Prevention, Bug 9440897
5719   mark_overpayments(p_checkrun_id, l_checkrun_name, l_current_calling_sequence);
5720 
5721 /* BUG 14498596 END - Moved Withholding Tax logic before grouping of invoices */
5722 
5723 /* BUG 14498596 Start - Added logic to Undo With-Holding Tax on Rejected Invoices durin PPR */
5724 
5725   DECLARE
5726   cursor c_dont_pay_invoices (p_checkrun_id number) is
5727   select invoice_id,
5728          vendor_id,
5729          payment_num,
5730          checkrun_id,
5731          withholding_amount,
5732          checkrun_name
5733   from ap_selected_invoices_all
5734   where checkrun_id = p_checkrun_id
5735   and ok_to_pay_flag = 'N';
5736 
5737  rec_dont_pay_invoices c_dont_pay_invoices%ROWTYPE;
5738 
5739  BEGIN
5740 
5741  OPEN c_dont_pay_invoices(p_checkrun_id);
5742 
5743   LOOP
5744     l_debug_info := 'Fetch CURSOR for all UN-SELECTed invoices';
5745     FETCH c_dont_pay_invoices INTO rec_dont_pay_invoices;
5746     EXIT WHEN c_dont_pay_invoices%NOTFOUND;
5747 
5748     DECLARE
5749       undo_output VARCHAR2(2000);
5750     BEGIN
5751 	  /* Added below update for bug 8888311 */
5752 
5753 	    UPDATE ap_awt_temp_distributions_all aatd
5754 		   SET withholding_amount = rec_dont_pay_invoices.withholding_amount
5755 		 WHERE invoice_id    = rec_dont_pay_invoices.invoice_id
5756            AND payment_num   =rec_dont_pay_invoices.payment_num
5757            AND checkrun_id   = rec_dont_pay_invoices.checkrun_id
5758 		   AND nvl(rec_dont_pay_invoices.withholding_amount,0) = 0;
5759 
5760         AP_WITHHOLDING_PKG.Ap_Undo_Temp_Withholding
5761                      (P_Invoice_Id             => rec_dont_pay_invoices.invoice_id
5762                      ,P_VENDor_Id              => rec_dont_pay_invoices.vendor_id
5763                      ,P_Payment_Num            => rec_dont_pay_invoices.payment_num
5764                      ,P_Checkrun_Name          => rec_dont_pay_invoices.checkrun_name
5765                      ,P_Undo_Awt_Date          => SYSDATE
5766                      ,P_Calling_Module         => 'AUTOSELECT'
5767                      ,P_Last_Updated_By        => FND_GLOBAL.USER_ID
5768                      ,P_Last_Update_Login      => FND_GLOBAL.LOGIN_ID
5769                      ,P_Program_Application_Id => FND_GLOBAL.PROG_APPL_ID
5770                      ,P_Program_Id             => FND_GLOBAL.CONC_PROGRAM_ID
5771                      ,P_Request_Id             => FND_GLOBAL.CONC_REQUEST_ID
5772                      ,P_Awt_Success            => undo_output
5773                      ,P_checkrun_id            => p_checkrun_id );
5774 
5775     END;
5776   END LOOP;
5777 
5778   l_debug_info := 'CLOSE CURSOR for all UN-SELECTed invoices';
5779   CLOSE c_dont_pay_invoices;
5780 
5781   END;
5782 
5783 /* BUG 14498596 END - Added logic to Undo With-Holding Tax on Rejected Invoices durin PPR */
5784 
5785   remove_invoices (p_checkrun_id, l_current_calling_sequence );
5786 
5787 
5788 
5789   /* Start bug12349626
5790      check if inv_awt_Exists_flag is Y,if yes, then update asi
5791      this avoids running the update on asi unless necessary */
5792 
5793      Select inv_awt_exists_flag
5794      into l_inv_awt_exists_flag
5795      from ap_inv_selection_criteria_all
5796      WHERE  checkrun_id  = p_checkrun_id;
5797 
5798      l_debug_info := 'Recalculate: restoring affects_rejection_level data';
5799      IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
5800        fnd_file.put_line(FND_FILE.LOG,l_debug_info);
5801      END IF;
5802 
5803      IF NVL(l_inv_awt_exists_flag, 'N') = 'Y' THEN
5804        update ap_selected_invoices_All asi
5805        set asi.AFFECTS_REJECTION_LEVEL= 'Y'
5806        where asi.checkrun_id = p_checkrun_id
5807        and  exists ( select 'ATLEAST ONE RANGE BASED PAY TIME AWT'
5808                     from ap_invoice_distributions_all aid,
5809                          AP_AWT_GROUP_TAXES_all awtt,
5810                          ap_tax_codes_all awtc
5811                    where aid.invoice_id = asi.invoice_id
5812                    and aid.pay_awt_group_id is not null
5813                    and awtt.group_id = aid.pay_awt_group_id
5814                    and awtt.tax_name = awtc.name
5815                    and awtc.tax_type = 'AWT'
5816                    and awtc.awt_rate_type <> 'F'
5817                    and awtc.enabled_flag = 'Y'
5818                    and NVL(asi.invoice_date,SYSDATE) BETWEEN
5819                        NVL(awtc.start_date,NVL(asi.invoice_date,SYSDATE)) AND
5820                       NVL(awtc.inactive_date,NVL(asi.invoice_date,SYSDATE))
5821                 );
5822      END IF;
5823 
5824     --End bug12349626
5825 
5826 
5827     /* Bug 12349626 Commenting out the IF clause below that is resetting of PPR
5828        rejection level. This functionality is now handled using the new column
5829        AFFECTS_REJECTION_LEVEL
5830 
5831      -- Bug 7492768 start
5832      -- Bug 8746215 If inv_awt_exists is Y, then set rejection level as PAYEE if rejection level is not REQUEST.
5833      select decode(nvl(inv_awt_exists_flag, 'N'), 'Y', decode(document_rejection_level_code,'REQUEST',document_rejection_level_code,'PAYEE'), document_rejection_level_code) document_rejection_level_code,
5834        decode(nvl(inv_awt_exists_flag, 'N'), 'Y', decode(payment_rejection_level_code,'REQUEST',payment_rejection_level_code,'PAYEE'), payment_rejection_level_code) payment_rejection_level_code
5835       --Bug 8746215 End
5836       into l_doc_rejection_level_code,
5837            l_pay_rejection_level_code
5838       FROM   ap_inv_selection_criteria_all
5839       WHERE  checkrun_id  = p_checkrun_id;
5840       -- Bug 7492768 End
5841 
5842       End of bug12349626 */
5843 
5844 
5845       --bug12349626. Noticed there is duplicate call to remove_invoices
5846       --hence commenting out
5847       --remove_invoices (p_checkrun_id, l_current_calling_sequence );
5848 
5849 -- Commented the following code for bug 9255192
5850 -- Now exchange rate will be calculated before calling WITHHOLDING pkg
5851 /*
5852   if l_batch_exchange_rate_type = 'User' then
5853 
5854     update ap_selected_invoices_all asi
5855     set (payment_exchange_rate_type, payment_exchange_rate) =
5856          (select 'User', exchange_rate
5857           from ap_user_exchange_rates auer,
5858                ap_system_parameters_all asp
5859           where asp.org_id = asi.org_id
5860           and   asi.payment_currency_code = auer.payment_currency_code
5861           and   asp.base_currency_code = auer.ledger_currency_code
5862           and   asp.base_currency_code <> asi.payment_currency_code
5863           and   auer.checkrun_id = p_checkrun_id)  --Bug 5123855
5864     where checkrun_id = p_checkrun_id
5865     and (invoice_id, payment_num) in
5866          (select invoice_id, payment_num
5867           from ap_selected_invoices_all asi2,
5868                ap_system_parameters_all asp2
5869           where asp2.org_id = asi2.org_id
5870           and   asp2.base_currency_code <> asi2.payment_currency_code
5871           and   asi2.checkrun_id = p_checkrun_id);
5872 
5873   else
5874   --update for all other exchange rate types
5875 
5876     update ap_selected_invoices asi
5877     set (payment_exchange_rate_type, payment_exchange_rate) =
5878          (select l_batch_exchange_rate_type,
5879                  ap_utilities_pkg.get_exchange_rate(
5880                          asi.payment_currency_code,
5881                          asp.base_currency_code,
5882                          l_batch_exchange_rate_type,
5883                          l_check_date,
5884                          'AUTOSELECT')
5885           from ap_system_parameters_all asp
5886           where asp.org_id = asi.org_id
5887           and asp.base_currency_code <> asi.payment_currency_code)
5888     where checkrun_id = p_checkrun_id
5889     and (invoice_id, payment_num) in
5890          (select invoice_id, payment_num
5891           from ap_selected_invoices_all asi2,
5892                ap_system_parameters_all asp2
5893           where asp2.org_id = asi2.org_id
5894           and   asp2.base_currency_code <> asi2.payment_currency_code
5895           and   asi2.checkrun_id = p_checkrun_id);
5896 
5897 
5898 
5899   end if;
5900 
5901   select count(*)
5902   into l_missing_rates_count
5903   from ap_selected_invoices_all asi,
5904        ap_system_parameters_all asp
5905   where asi.org_id = asp.org_id
5906   and asi.checkrun_id = p_checkrun_id
5907   and asi.payment_currency_code <> asp.base_currency_code
5908   and asi.payment_exchange_rate is null
5909   and ((l_batch_exchange_rate_type <> 'User'
5910        and asp.make_rate_mandatory_flag = 'Y') OR
5911        l_batch_exchange_rate_type = 'User')
5912   and rownum = 1;
5913 
5914 
5915 
5916   if l_missing_rates_count > 0 then
5917 
5918     update ap_inv_selection_criteria_all
5919     set status = 'MISSING RATES'
5920     where checkrun_id = p_checkrun_id;
5921 
5922     if l_batch_exchange_rate_type = 'User' then
5923       insert into ap_user_exchange_rates auer
5924        (checkrun_id,
5925         payment_currency_code,
5926         ledger_currency_code,
5927         creation_date,  --Bug 5123855
5928         created_by,
5929         last_update_date,
5930         last_updated_by,
5931         last_update_login)
5932        (select p_checkrun_id,
5933                asi.payment_currency_code,
5934                asp.base_currency_code,
5935                SYSDATE,
5936                FND_GLOBAL.user_id,
5937                SYSDATE,
5938                FND_GLOBAL.user_id,
5939                FND_GLOBAL.login_id
5940         from ap_selected_invoices_all asi,
5941              ap_system_parameters_all asp
5942         where asi.payment_exchange_rate is null
5943         and asp.org_id = asi.org_id
5944         and asp.base_currency_code <> asi.payment_currency_code
5945         and asi.checkrun_id = p_checkrun_id
5946         and not exists (select 'row already in auer'
5947                         from ap_user_exchange_rates auer2
5948                         where auer2.checkrun_id = asi.checkrun_id
5949                         and   auer2.payment_currency_code = asi.payment_currency_code
5950                         and   auer2.ledger_currency_code = asp.base_currency_code));
5951 
5952     end if;
5953   end if;
5954 */
5955 
5956 
5957 
5958 
5959   --5007587
5960   declare
5961 
5962   l_init_msg_list varchar2(2000);
5963   l_return_status varchar2(1);
5964   l_msg_count number;
5965   l_msg_data varchar2(2000);
5966   l_msg_index_out number;
5967 
5968   begin
5969 
5970     FV_FEDERAL_PAYMENT_FIELDS_PKG.SUBMIT_CASH_POS_REPORT(
5971       p_init_msg_list => l_init_msg_list,
5972       p_org_id        => null,
5973       p_checkrun_id   => p_checkrun_id,
5974       x_request_id    => l_req_id,
5975       x_return_status => l_return_status,
5976       x_msg_count     => l_msg_count,
5977       x_msg_data      => l_msg_data);
5978 
5979     if l_return_status <> FND_API.G_RET_STS_SUCCESS then
5980       IF l_msg_count > 0 THEN
5981           FOR i in 1..l_msg_count LOOP
5982             FND_MSG_PUB.Get( p_msg_index     => i,
5983                              p_encoded       => 'F',
5984                              p_data          => l_msg_data,
5985                              p_msg_index_out => l_msg_index_out);
5986             FND_FILE.Put_Line(FND_FILE.Log,l_msg_data);
5987           End LOOP;
5988       end if;
5989     end if;
5990   end;
5991   --end 5007857
5992 
5993 
5994 
5995 
5996 
5997 
5998   select status
5999   into l_batch_status
6000   from ap_inv_selection_criteria_all
6001   where checkrun_id = p_checkrun_id;
6002 
6003 
6004 
6005 
6006 
6007   if p_submit_to_iby = 'Y' and l_batch_status = 'CALCULATING' then
6008 
6009     update ap_inv_selection_criteria_all
6010     set status = 'SELECTED'
6011     where checkrun_id = p_checkrun_id;
6012 
6013     SELECT lower(iso_language),iso_territory
6014     INTO l_iso_language,l_iso_territory
6015     FROM FND_LANGUAGES
6016     WHERE language_code = USERENV('LANG');
6017 
6018     -- Bug 4681857
6019 
6020     --Bug 6969710
6021     /* Commented for bug#12917747 Start
6022     SELECT nvl(template_code, 'APINVSEL' )
6023           INTO l_template_code
6024           FROM Fnd_Concurrent_Programs
6025           WHERE concurrent_program_name = 'APINVSEL';  --Bug 6969710
6026     Commented for bug#12917747 End */
6027 
6028    /* Added for bug#12917747 Start */
6029    SELECT nvl(template_code, 'APINVSEL' )
6030         , (SELECT Nvl(DEFAULT_OUTPUT_TYPE,'PDF')
6031              FROM XDO_TEMPLATES_B xtb
6032             WHERE xtb.TEMPLATE_CODE = nvl(fcp.template_code, 'APINVSEL' )
6033               AND APPLICATION_ID    = 200
6034               AND rownum = 1
6035           )
6036      INTO l_template_code
6037         , l_output_format
6038      FROM Fnd_Concurrent_Programs fcp
6039     WHERE concurrent_program_name = 'APINVSEL';
6040    /* Added for bug#12917747 End */
6041 
6042     l_xml_output:=  fnd_request.add_layout(
6043                         template_appl_name  => 'SQLAP',
6044                         template_code       => l_template_code , --Bug 6969710
6045                         template_language   => l_iso_language,
6046                         template_territory  => l_iso_territory ,
6047                         output_format       => l_output_format  /* Bug#12917747 */
6048                             );
6049 
6050    --below code added for bug#7435751 as we need to set the current nls character setting
6051    fnd_profile.get('ICX_NUMERIC_CHARACTERS',l_icx_numeric_characters);
6052    l_return_status:= FND_REQUEST.SET_OPTIONS( numeric_characters => l_icx_numeric_characters);
6053 
6054     --submit the selected payment schedules report
6055     l_req_id := FND_REQUEST.SUBMIT_REQUEST(
6056                   'SQLAP',
6057                   'APINVSEL',
6058                   '',
6059                   '',
6060                   FALSE,
6061                   to_char(p_checkrun_id),
6062                   chr(0));
6063 
6064     l_req_id := FND_REQUEST.SUBMIT_REQUEST(
6065                   'IBY',
6066                   'IBYBUILD',
6067                   '',
6068                   '',
6069                   FALSE,
6070                   '200',
6071                   l_checkrun_name,
6072                   to_char(l_bank_account_id),
6073                   to_char(l_payment_profile_id),
6074                   l_zero_invoices_allowed, -- Bug 6523501,
6075                   to_char(l_max_payment_amount),
6076                   to_char(l_min_check_amount),
6077                   l_doc_rejection_level_code,
6078                   l_pay_rejection_level_code,
6079                   l_pay_review_settings_flag,
6080                   l_create_instrs_flag,
6081                   l_payment_document_id,
6082                   /*bug 7519277*/
6083                                   l_ATTRIBUTE_CATEGORY,
6084                                   l_ATTRIBUTE1,
6085                                   l_ATTRIBUTE2,
6086                                   l_ATTRIBUTE3,
6087                                   l_ATTRIBUTE4,
6088                                   l_ATTRIBUTE5,
6089                                   l_ATTRIBUTE6,
6090                                   l_ATTRIBUTE7,
6091                                   l_ATTRIBUTE8,
6092                                   l_ATTRIBUTE9,
6093                                   l_ATTRIBUTE10,
6094                                   l_ATTRIBUTE11,
6095                                   l_ATTRIBUTE12,
6096                                   l_ATTRIBUTE13,
6097                                   l_ATTRIBUTE14,
6098                                   l_ATTRIBUTE15,
6099                                 /*bug 7519277*/
6100                   chr(0));
6101   --4676790
6102   elsif p_submit_to_iby = 'N' and l_batch_status = 'CALCULATING' then
6103 
6104     update ap_inv_selection_criteria_all
6105     set status = 'REVIEW'
6106     where checkrun_id = p_checkrun_id;
6107 
6108   end if;
6109 
6110   commit;
6111 
6112 
6113 exception
6114     WHEN OTHERS then
6115 
6116     IF (SQLCODE <> -20001) THEN
6117       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
6118       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
6119       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
6120       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
6121       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_checkrun_id: '||
6122                                            to_char(p_checkrun_id));
6123 
6124     END IF;
6125     APP_EXCEPTION.RAISE_EXCEPTION;
6126 
6127 
6128 
6129 END recalculate;
6130 
6131 
6132 
6133 PROCEDURE cancel_batch (errbuf             OUT NOCOPY VARCHAR2,
6134                         retcode            OUT NOCOPY NUMBER,
6135                         p_checkrun_id      in         varchar2) is
6136 
6137 l_debug_info varchar2(2000);
6138 l_current_calling_sequence varchar2(2000);
6139 l_checkrun_name ap_inv_selection_criteria_all.checkrun_name%type;-- bug# 6643035
6140 l_psr_id number;
6141 l_return_status varchar2(1);
6142 l_fd_count NUMBER;  /* Bug 14336393 */
6143 excp_return_success EXCEPTION;
6144 
6145 begin
6146 
6147   l_current_calling_sequence := 'ap_autoselect_pkg.cancel_batch';
6148 
6149   select checkrun_name
6150   into l_checkrun_name
6151   from ap_inv_selection_criteria_all
6152   where checkrun_id = p_checkrun_id;
6153 
6154 
6155   begin
6156 
6157     select PAYMENT_SERVICE_REQUEST_ID
6158     into l_psr_id
6159     from iby_pay_service_requests
6160     where calling_app_id = 200
6161     and CALL_APP_PAY_SERVICE_REQ_CODE = l_checkrun_name;
6162   exception
6163     when no_data_found then null;
6164   end;
6165 
6166   Select count(1)   --Bug 14336393
6167   into l_fd_count
6168   from iby_fd_docs_payable_v
6169   where calling_app_doc_unique_ref1 = p_checkrun_id
6170   and calling_app_id = 200;
6171 
6172   if (l_psr_id is not null and l_fd_count <> 0) then
6173 
6174     IBY_DISBURSE_UI_API_PUB_PKG.terminate_pmt_request (
6175       l_psr_id,
6176       'TERMINATED',
6177       l_return_status);
6178 
6179 	if(l_return_status <> FND_API.G_RET_STS_SUCCESS) then  /* Bug 14336393 */
6180        	l_debug_info := ('The return status from IBY API Terminate PMT Request is:' || l_return_status);
6181 		RAISE excp_return_success;
6182     end if;
6183 
6184   else
6185     if l_psr_id is not null then    /* Bug 14336393 */
6186 
6187 		IBY_DISBURSE_UI_API_PUB_PKG.terminate_pmt_request (
6188           l_psr_id,
6189           'TERMINATED',
6190           l_return_status);
6191 
6192 	    if(l_return_status <> FND_API.G_RET_STS_SUCCESS) then  /* Bug 14336393 */
6193        	    l_debug_info := ('The return status from IBY API Terminate PMT Request is:' || l_return_status);
6194 		    RAISE excp_return_success;
6195         end if;
6196 	end if;
6197 
6198     update ap_inv_selection_criteria_all
6199     set status = 'CANCELING'
6200     where checkrun_id = p_checkrun_id;
6201 
6202     /* commit;  Commenting out as it is not required at this stage Bug 14336393 */
6203 
6204 
6205     l_debug_info := 'delete unselected invoices';
6206 
6207     delete from ap_unselected_invoices_all
6208     where checkrun_id = p_checkrun_id;
6209 
6210     l_debug_info := 'undo awt';
6211 
6212     AP_WITHHOLDING_PKG.AP_WITHHOLD_CANCEL(l_checkrun_name,
6213                      FND_GLOBAL.USER_ID,
6214                      FND_GLOBAL.LOGIN_ID,     -- Bug 5478602
6215                      FND_GLOBAL.PROG_APPL_ID,
6216                      FND_GLOBAL.CONC_PROGRAM_ID,
6217                      FND_GLOBAL.CONC_REQUEST_ID,
6218                      p_checkrun_id,
6219                      null,
6220                      null);
6221 
6222 
6223     l_debug_info := 'delete selected invoices';
6224 
6225     delete from ap_selected_invoices_all
6226     where checkrun_id = p_checkrun_id;
6227 
6228 
6229     l_debug_info := 'update payment schedules';
6230 
6231     update ap_payment_schedules_all
6232     set checkrun_id = null
6233     where checkrun_id = p_checkrun_id;
6234 
6235     update ap_inv_selection_criteria_all
6236     set status = 'CANCELED' --seeded with one L
6237     where checkrun_id = p_checkrun_id;
6238 
6239   end if;
6240 
6241 COMMIT; /* added for bug 14336393*/
6242 exception
6243     WHEN OTHERS then
6244 
6245     IF (SQLCODE <> -20001) THEN
6246       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
6247       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
6248       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
6249       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
6250       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_checkrun_id: '||
6251                                            to_char(p_checkrun_id));
6252 
6253     END IF;
6254 	ROLLBACK;
6255     FND_File.Put_Line(fnd_file.log,l_debug_info);
6256     APP_EXCEPTION.RAISE_EXCEPTION;
6257 end cancel_batch;
6258 
6259 
6260 
6261 PROCEDURE selection_criteria_report(
6262                         errbuf             OUT NOCOPY VARCHAR2,
6263                         retcode            OUT NOCOPY NUMBER,
6264                         p_checkrun_id      in         varchar2)is
6265 
6266 l_qryCtx                   DBMS_XMLGEN.ctxHandle;
6267 l_result_clob              CLOB;
6268 l_current_calling_sequence varchar2(2000);
6269 l_debug_info               varchar2(200);
6270 
6271 begin
6272 
6273   l_current_calling_sequence := 'ap_autoselect_pkg.selection_criteria_report';
6274   l_debug_info:= 'select from ap_inv_selection_criteria_all';
6275 
6276   fnd_file.put_line(fnd_file.output, '<SELECTION_CRITERIA_RPT>');
6277 
6278   l_qryCtx := DBMS_XMLGEN.newContext(
6279     'select aisc.checkrun_name, aisc.pay_from_date, aisc.pay_thru_date,
6280             aisc.hi_payment_priority, aisc.low_payment_priority,
6281             aisc.pay_only_when_due_flag, aisc.zero_amounts_allowed,
6282             aisc.zero_invoices_allowed, ab.batch_name,
6283             vndr.meaning supplier_type, hz.party_name,
6284             iby.payment_method_name, rate.displayed_field document_exchange_rate_type,
6285             apt.template_name
6286       from ap_inv_selection_criteria_all aisc,
6287            ap_batches_all ab,
6288            iby_payment_methods_vl iby,
6289            fnd_lookups vndr,
6290            hz_parties hz,
6291            ap_lookup_codes rate,
6292            ap_payment_templates apt
6293      where checkrun_id ='|| p_checkrun_id ||'
6294      and apt.template_id(+) = aisc.template_id
6295      and aisc.invoice_batch_id = ab.batch_id(+)
6296      and aisc.payment_method_code = iby.payment_method_code(+)
6297      and aisc.vendor_type_lookup_code = vndr.lookup_code(+)
6298      and vndr.lookup_type(+) = ''VENDOR TYPE''
6299      and aisc.party_id = hz.party_id(+)
6300      and rate.lookup_type(+) = ''INVOICE_EXCHANGE_RATE_TYPE''
6301      and aisc.inv_exchange_rate_type = rate.lookup_code(+)');
6302 
6303   DBMS_XMLGEN.setRowSetTag(l_qryCtx,'CRITERIA');
6304   DBMS_XMLGEN.setRowTag(l_qryCtx, 'SELECTION_CRITERIA');
6305   l_result_clob :=DBMS_XMLGEN.GETXML(l_qryCtx);
6306   l_result_clob := substr(l_result_clob,instr(l_result_clob,'>')+1);
6307   DBMS_XMLGEN.closeContext(l_qryCtx);
6308   ap_utilities_pkg.clob_to_file(l_result_clob);
6309 
6310 
6311   l_debug_info := 'select pay group';
6312 
6313 
6314   l_qryCtx := DBMS_XMLGEN.newContext('SELECT vendor_pay_group '||
6315                                      'FROM ap_pay_group '||
6316                                      'WHERE checkrun_id = '||to_char(p_checkrun_id));
6317   DBMS_XMLGEN.setRowSetTag(l_qryCtx,'PAY');
6318   DBMS_XMLGEN.setRowTag(l_qryCtx, 'PAY_GROUP');
6319   l_result_clob :=DBMS_XMLGEN.GETXML(l_qryCtx);
6320   l_result_clob := substr(l_result_clob,instr(l_result_clob,'>')+1);
6321   DBMS_XMLGEN.closeContext(l_qryCtx);
6322   ap_utilities_pkg.clob_to_file(l_result_clob);
6323 
6324 
6325   l_debug_info := 'select currency group';
6326 
6327   l_qryCtx := DBMS_XMLGEN.newContext('SELECT currency_code '||
6328                                      'FROM AP_CURRENCY_GROUP '||
6329                                      'WHERE checkrun_id = '||to_char(p_checkrun_id));
6330   DBMS_XMLGEN.setRowSetTag(l_qryCtx,'CURRENCY');
6331   DBMS_XMLGEN.setRowTag(l_qryCtx, 'CURRENCY_GROUP');
6332   l_result_clob :=DBMS_XMLGEN.GETXML(l_qryCtx);
6333   l_result_clob := substr(l_result_clob,instr(l_result_clob,'>')+1);
6334   DBMS_XMLGEN.closeContext(l_qryCtx);
6335   ap_utilities_pkg.clob_to_file(l_result_clob);
6336 
6337 
6338 
6339   l_debug_info:= 'select le group';
6340 
6341   l_qryCtx := DBMS_XMLGEN.newContext('SELECT name legal_entity_name '||
6342                                      'FROM ap_le_group aleg, xle_entity_profiles xle '||
6343                                      'WHERE aleg.legal_entity_id = xle.legal_entity_id '||
6344                                      'AND checkrun_id = '||to_char(p_checkrun_id));
6345   DBMS_XMLGEN.setRowSetTag(l_qryCtx,'LEGAL_ENTITY');
6346   DBMS_XMLGEN.setRowTag(l_qryCtx, 'LE_GROUP');
6347   l_result_clob :=DBMS_XMLGEN.GETXML(l_qryCtx);
6348   l_result_clob := substr(l_result_clob,instr(l_result_clob,'>')+1);
6349   DBMS_XMLGEN.closeContext(l_qryCtx);
6350   ap_utilities_pkg.clob_to_file(l_result_clob);
6351 
6352 
6353   l_debug_info := 'select ou group';
6354 
6355   l_qryCtx := DBMS_XMLGEN.newContext('SELECT name organization_name '||
6356                                      'FROM AP_OU_GROUP AOG, HR_OPERATING_UNITS HR '||
6357                                      'WHERE hr.organization_id = aog.org_id '||
6358                                      'AND checkrun_id = '||to_char(p_checkrun_id));
6359   DBMS_XMLGEN.setRowSetTag(l_qryCtx,'ORGANIZATION');
6360   DBMS_XMLGEN.setRowTag(l_qryCtx, 'OU_GROUP');
6361   l_result_clob :=DBMS_XMLGEN.GETXML(l_qryCtx);
6362   l_result_clob := substr(l_result_clob,instr(l_result_clob,'>')+1);
6363   DBMS_XMLGEN.closeContext(l_qryCtx);
6364   ap_utilities_pkg.clob_to_file(l_result_clob);
6365 
6366   fnd_file.put_line(fnd_file.output, '</SELECTION_CRITERIA_RPT>');
6367 
6368 EXCEPTION
6369 
6370     WHEN OTHERS then
6371 
6372     IF (SQLCODE <> -20001) THEN
6373       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
6374       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
6375       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
6376       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
6377       FND_MESSAGE.SET_TOKEN('PARAMETERS','p_checkrun_id '||p_checkrun_id);
6378 
6379 
6380 
6381     END IF;
6382     APP_EXCEPTION.RAISE_EXCEPTION;
6383 
6384 
6385 END selection_criteria_report;
6386 
6387  --Overpayment Prevention, Bug 9440897
6388 
6389 FUNCTION get_prepay_with_tax(p_invoice_id in number)
6390         RETURN NUMBER IS
6391  	l_prepay_with_tax NUMBER;
6392     BEGIN
6393         SELECT  ((0 - SUM(NVL(ail.amount,0)))*ai.payment_cross_rate)
6394         INTO l_prepay_with_tax
6395         FROM ap_invoice_lines_all ail,ap_invoices_all ai
6396         WHERE ail.invoice_id = p_invoice_id
6397 	  AND ail.invoice_id=ai.invoice_id
6398           AND ail.prepay_invoice_id is not null
6399           AND   ail.line_type_lookup_code in ('TAX', 'PREPAY')
6400           AND   NVL(ail.invoice_includes_prepay_flag, 'N') = 'N'
6401         GROUP BY ai.payment_cross_rate;
6402         return l_prepay_with_tax;
6403     END get_prepay_with_tax;
6404 
6405 /*
6406    This procedure will check for invoices that would be
6407    overpaid by the selected invoices records created.
6408    If any are found it will mark the selected invoices
6409    ok_to_pay_flag as N and remove any related awt
6410    temp distributions.
6411 
6412    This should be called after all processing that would
6413    change a payment amount is complete.
6414 
6415    The remove_invoices procedure should be called after
6416    this procedure
6417 */
6418 PROCEDURE mark_overpayments ( p_checkrun_id in number,
6419                               p_checkrun_name in varchar2,
6420 			      p_calling_sequence in varchar2) IS
6421 
6422     l_debug_info                  varchar2(2000);
6423     l_current_calling_sequence    varchar2(2000);
6424 
6425     CURSOR c_invs_to_remove_with_awt IS
6426     select si.invoice_id
6427     , si.vendor_id
6428     , si.payment_num
6429     from ap_selected_invoices_all si
6430     , ap_awt_temp_distributions_all atd
6431     where si.ok_to_pay_flag = 'N'
6432     and dont_pay_reason_code = 'OVERPAYMENT'
6433     and si.invoice_id = atd.invoice_id
6434     and si.payment_num = atd.payment_num
6435     and si.checkrun_id = p_checkrun_id
6436     and si.checkrun_name = atd.checkrun_name;
6437     --May have to use checkrun name for Quick payments
6438     rec_invs_to_remove_with_awt   c_invs_to_remove_with_awt%ROWTYPE;
6439 
6440 BEGIN
6441 
6442 l_current_calling_sequence := p_calling_sequence || '<-mark_overpayments ';
6443 l_debug_info := 'Inside mark overpayments';
6444   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
6445     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
6446   END IF;
6447 
6448     update ap_selected_invoices_all si
6449     set ok_to_pay_flag = 'N',
6450     dont_pay_reason_code = 'OVERPAYMENT'
6451     WHERE si.checkrun_id = p_checkrun_id
6452     AND si.invoice_id in
6453        (select /*+ use_nl_index(I AP_INVOICES_U1) */ si2.invoice_id
6454        from ap_selected_invoices_all si2
6455        , ap_invoices_all i
6456        where si2.checkrun_id = p_checkrun_id
6457        and si2.invoice_id = i.invoice_id
6458        and si2.original_invoice_id is null
6459        group by si2.invoice_id,i.invoice_amount, decode(i.net_of_retainage_flag, 'Y', 0,
6460                nvl(AP_INVOICES_UTILITY_PKG.GET_RETAINED_TOTAL(si2.invoice_id, si2.org_id),0)),i.payment_cross_rate
6461        having abs((nvl(i.invoice_amount,0) - nvl(sum(si2.withholding_amount),0)
6462                - nvl(AP_INVOICES_UTILITY_PKG.get_amount_withheld(si2.invoice_id),0)
6463                + decode(i.net_of_retainage_flag, 'Y', 0,
6464 		   nvl(AP_INVOICES_UTILITY_PKG.GET_RETAINED_TOTAL(si2.invoice_id, si2.org_id),0)))*i.payment_cross_rate
6465                /* retainage is returned as a negative */
6466             )
6467              < abs( nvl(sum(si2.discount_amount),0)  + nvl(sum(si2.payment_amount),0)
6468 	       + nvl(get_prepay_with_tax(si2.invoice_id),0)
6469                /* Bug 9570635 */
6470                + nvl((select sum(nvl(p.amount,0)) + sum(nvl(p.discount_taken,0))
6471                                 from ap_invoice_payments_all p
6472                                 where p.invoice_id = si2.invoice_id),0)));
6473 
6474 /*
6475   undo awt for invoices to be removed, this is essentially the same code as in ap_withholding_pkg
6476   Since this procedure is called after awt is calculated and before
6477   remove_invoices we have to handle temp awt undo here._
6478 */
6479     OPEN c_invs_to_remove_with_awt;
6480 
6481     LOOP
6482       l_debug_info := 'Fetch CURSOR for selected invoices marked for removal that have awt';
6483       FETCH c_invs_to_remove_with_awt INTO rec_invs_to_remove_with_awt;
6484       EXIT WHEN c_invs_to_remove_with_awt%NOTFOUND;
6485            DECLARE
6486              undo_output VARCHAR2(2000);
6487            BEGIN
6488                AP_WITHHOLDING_PKG.Ap_Undo_Temp_Withholding
6489                             (P_Invoice_Id             => rec_invs_to_remove_with_awt.invoice_id
6490                             ,P_vendor_Id              => rec_invs_to_remove_with_awt.vendor_id
6491                             ,P_Payment_Num            => rec_invs_to_remove_with_awt.payment_num
6492                             ,P_Checkrun_Name          => p_checkrun_name
6493                             ,P_Undo_Awt_Date          => SYSDATE
6494                             ,P_Calling_Module         => 'AUTOSELECT'
6495                             ,P_Last_Updated_By        => FND_GLOBAL.USER_ID
6496                             ,P_Last_Update_Login      => FND_GLOBAL.LOGIN_ID
6497                             ,P_Program_Application_Id => FND_GLOBAL.PROG_APPL_ID
6498                             ,P_Program_Id             => FND_GLOBAL.CONC_PROGRAM_ID
6499                             ,P_Request_Id             => FND_GLOBAL.CONC_REQUEST_ID
6500                             ,P_Awt_Success            => undo_output
6501                             ,P_checkrun_id            => p_checkrun_id );
6502 
6503            END;
6504     END LOOP;
6505     CLOSE c_invs_to_remove_with_awt;
6506 
6507 EXCEPTION
6508     WHEN OTHERS then
6509 
6510     IF (SQLCODE <> -20001) THEN
6511       FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
6512       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
6513       FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',l_current_calling_sequence );
6514       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info );
6515       FND_MESSAGE.SET_TOKEN('PARAMETERS', 'p_checkrun_id: '||
6516                                            to_char(p_checkrun_id));
6517    END IF;
6518    APP_EXCEPTION.RAISE_EXCEPTION;
6519 
6520 END mark_overpayments;
6521 
6522 -- Bug 11824219.
6523 -- API invoked by IBY to verify whether a list of payable documents
6524 -- can be removed or not. Invoice schedules and related interest invoice
6525 -- schedules should be removed together. API checks whether the
6526 -- standard/interest invoice pair go hand in hand or not, either both
6527 -- removed or both retained. API returns success if the list of payables
6528 -- documents can be removed.
6529 
6530 PROCEDURE check_doc_payable_remove
6531      ( p_rejected_docs_group_id IN  NUMBER,
6532        x_return_status          OUT nocopy VARCHAR2) IS
6533 
6534   l_status                    boolean := true ;
6535   l_checkrun_id               number;
6536   l_current_calling_sequence  varchar2(2000);
6537   l_debug_info                varchar2(3000);
6538   l_count                     number ;
6539 
6540   -- This cursor holds the list of documents that IBY want to verify.
6541   -- Instead of passing a list of documents IBY is stamping the relevant
6542   -- documents with p_rejected_docs_group_id and passing the
6543   -- p_rejected_docs_group_id to this API.
6544 
6545   CURSOR c_sel_invs  IS
6546     SELECT  asi.invoice_id
6547      ,      asi.vendor_id
6548      ,      asi.payment_num
6549      ,      asi.original_invoice_id
6550      ,      asi.original_payment_num
6551      ,      asi.payment_grouping_number
6552     FROM    ap_selected_invoices_all ASI,
6553             iby_fd_docs_payable_v ibydocs
6554     WHERE   checkrun_id = l_checkrun_id
6555     AND     ibydocs.calling_app_doc_unique_ref1 = TO_CHAR(ASI.checkrun_id)
6556     AND     ibydocs.calling_app_doc_unique_ref2 = TO_CHAR(ASI.invoice_id)
6557     AND     ibydocs.calling_app_doc_unique_ref3 = TO_CHAR(ASI.payment_num)
6558     AND     ibydocs.rejected_docs_group_id = p_rejected_docs_group_id
6559     AND     ibydocs.calling_app_id = 200 ;
6560 
6561   rec_sel_invs c_sel_invs%ROWTYPE;
6562 
6563 BEGIN
6564 
6565   l_debug_info := 'fetching checkrun_id.';
6566   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
6567     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
6568   END IF;
6569 
6570   select calling_app_doc_unique_ref1
6571   into   l_checkrun_id
6572   from   iby_fd_docs_payable_v
6573   where  rejected_docs_group_id = p_rejected_docs_group_id
6574   and    rownum = 1;
6575 
6576   l_debug_info := 'checkrun_id = ' || l_checkrun_id;
6577   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
6578     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
6579   END IF;
6580 
6581   l_debug_info := 'open cursor c_sel_invs';
6582   IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
6583     fnd_file.put_line(FND_FILE.LOG,l_debug_info);
6584   END IF;
6585 
6586   OPEN c_sel_invs;
6587 
6588   LOOP
6589 
6590     l_debug_info := 'fetch c_sel_invs for selected schedules.';
6591     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
6592       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
6593     END IF;
6594 
6595     FETCH c_sel_invs INTO rec_sel_invs;
6596     EXIT WHEN c_sel_invs%NOTFOUND;
6597 
6598     -- Check whether the interest/parent pair exists in the list of
6599     -- documents which are selected for removal. If the pair exists
6600     -- is the reject list, then removal is allowed.
6601 
6602     l_debug_info := 'checking for invoice_id = ' || rec_sel_invs.invoice_id
6603                     || ' ,payment_num = ' || rec_sel_invs.payment_num
6604                     || ' ,original_invoice_id = ' || rec_sel_invs.original_invoice_id
6605                     || ' ,original_payment_num = ' || rec_sel_invs.original_payment_num
6606                     || ' ,payment_grouping_number = ' || rec_sel_invs.payment_grouping_number ;
6607     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
6608       fnd_file.put_line(FND_FILE.LOG,l_debug_info);
6609     END IF;
6610 
6611     --   Following select is almost exactly same as cursor c_sel_invs. This is to check whether
6612     --   the pair is present in the list of docs to be removed. original_invoice_id invoice_id
6613     --   conditions added. This select works both with standard and interest schedule.
6614     --   rec_sel_invs.original_invoice_id IS NULL - for standard
6615     --   rec_sel_invs.original_invoice_id IS NOT NULL - for interest schedule
6616     --
6617     --   If the count returne is non zero, then pair is also present in the list
6618     --   of docs to be removed and safe to remove.
6619 
6620     SELECT  count(*) INTO l_count
6621     FROM    ap_selected_invoices_all ASI,
6622             iby_fd_docs_payable_v ibydocs
6623     WHERE   ASI.checkrun_id = l_checkrun_id
6624     AND     ASI.invoice_id <> rec_sel_invs.invoice_id
6625     AND     ( ( rec_sel_invs.original_invoice_id IS NULL -- standard schedule
6626                 AND ASI.original_invoice_id = rec_sel_invs.invoice_id
6627 	        AND ASI.original_payment_num = rec_sel_invs.payment_num
6628               ) OR
6629               ( rec_sel_invs.original_invoice_id IS NOT NULL -- interest schedule
6630                 AND ASI.invoice_id = rec_sel_invs.original_invoice_id
6631 	        AND ASI.payment_num = rec_sel_invs.original_payment_num
6632 	      )
6633             )
6634     AND     ibydocs.calling_app_doc_unique_ref1 = TO_CHAR(ASI.checkrun_id)
6635     AND     ibydocs.calling_app_doc_unique_ref2 = TO_CHAR(ASI.invoice_id)
6636     AND     ibydocs.calling_app_doc_unique_ref3 = TO_CHAR(ASI.payment_num)
6637     AND     ibydocs.rejected_docs_group_id = p_rejected_docs_group_id
6638     AND     ibydocs.calling_app_id = 200 ;
6639 
6640     IF (l_count = 0) THEN
6641 
6642      -- Schedule/interest pair does not exist in the removal list.
6643      -- Need to check whether the pair exists in the selected
6644      -- schedules list. If yes, then the schedule can not be removed.
6645      -- exclusive_payment_flag is considered only if federal
6646      -- is installed. If federal is not installed, then
6647      -- standard/interest pair will always to grouped in one payment
6648      -- regardless of exclusive_payment_flag flag status. Federal
6649      -- check is also included in the query.
6650 
6651      -- If atleast one occurrance such case is reported iteration can be
6652      -- terminated and signal that the docs can not be removed can be
6653      -- retunred to IBY.
6654 
6655      l_debug_info := 'schedule/interest pair does not exist in the removal list.';
6656      IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
6657        fnd_file.put_line(FND_FILE.LOG,l_debug_info);
6658      END IF;
6659 
6660      -- Following query checks against all the schedules selected as part of the batch.
6661      -- If pair is not present in this, then it is safe to remove the schedule in this
6662      -- iteration.
6663 
6664      SELECT count(*) into l_count
6665      FROM   ap_selected_invoices_all ASI
6666      WHERE  ASI.checkrun_id = l_checkrun_id
6667      AND    ASI.invoice_id <> rec_sel_invs.invoice_id
6668      AND    ( ( rec_sel_invs.original_invoice_id IS NULL -- selected row is standard schedule
6669                 AND ASI.original_invoice_id = rec_sel_invs.invoice_id
6670                 AND ASI.original_payment_num = rec_sel_invs.payment_num
6671               ) OR
6672               ( rec_sel_invs.original_invoice_id IS NOT NULL -- selected row is interest schedule
6673                 AND ASI.invoice_id = rec_sel_invs.original_invoice_id
6674                 AND ASI.payment_num = rec_sel_invs.original_payment_num
6675               )
6676             )
6677      AND    ASI.payment_grouping_number = rec_sel_invs.payment_grouping_number
6678      AND    ASI.ok_to_pay_flag = 'Y'
6679      AND    (Ap_Payment_Util_Pkg.is_federal_installed(ASI.org_id) = 'N'
6680              OR (Ap_Payment_Util_Pkg.is_federal_installed(asi.org_id) = 'Y'
6681                  AND asi.exclusive_payment_flag = 'N')
6682             ) ;
6683 
6684      IF (l_count <> 0) THEN
6685         l_debug_info := 'payables docs can not be removed. Returning status N.'
6686                         || ' invoice_id = ' || rec_sel_invs.invoice_id
6687                         || ' ,payment_num = ' || rec_sel_invs.payment_num;
6688         IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
6689            fnd_file.put_line(FND_FILE.LOG,l_debug_info);
6690         END IF;
6691 
6692         l_status := false ;
6693         EXIT ;
6694      END IF ;
6695 
6696     END IF ;
6697 
6698   END LOOP;
6699 
6700   CLOSE c_sel_invs;
6701 
6702   IF (l_status = true) THEN
6703       x_return_status := FND_API.G_RET_STS_SUCCESS;
6704   ELSE
6705       x_return_status := FND_API.G_RET_STS_ERROR;
6706   END IF ;
6707 
6708 EXCEPTION
6709   WHEN OTHERS THEN
6710     l_debug_info := 'Caught in exception block.' ;
6711     IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
6712        fnd_file.put_line(FND_FILE.LOG,l_debug_info);
6713     END IF;
6714     x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
6715 
6716 END check_doc_payable_remove;
6717 
6718 END AP_AUTOSELECT_PKG;