DBA Data[Home] [Help]

PACKAGE BODY: APPS.AR_IREC_PAYMENTS

Source


1 PACKAGE BODY AR_IREC_PAYMENTS AS
2 /* $Header: ARIRPMTB.pls 120.99.12020000.19 2013/03/29 09:26:04 melapaku ship $ */
3 
4 /*=======================================================================+
5  |  Package Global Constants
6  +=======================================================================*/
7 G_PKG_NAME      CONSTANT VARCHAR2(30)    := 'AR_IREC_PAYMENTS';
8 G_CREATION_FAILED    CONSTANT VARCHAR2(30)    := 'CREATION_FAILED';
9 G_APP_FAILED    CONSTANT VARCHAR2(30)    := 'APP_FAILED';
10 G_SVC_FAILED    CONSTANT VARCHAR2(30)    := 'SVC_FAILED';
11 G_CC_AUTH_FAILED    CONSTANT VARCHAR2(30)    := 'CC_AUTH_FAILED';
12 G_SUCCESSFUL    CONSTANT VARCHAR2(30)    := 'SUCCESSFUL';
13 G_FAILED        CONSTANT VARCHAR2(30)    := 'FAILED';
14 
15 TYPE INVOICE_REC_TYPE IS RECORD
16      (PAYMENT_SCHEDULE_ID     NUMBER(15),
17       PAYMENT_AMOUNT		  NUMBER,
18       CUSTOMER_ID             NUMBER(15),
19       ACCOUNT_NUMBER          VARCHAR2(30),
20       CUSTOMER_TRX_ID         NUMBER(15),
21       CURRENCY_CODE           VARCHAR2(15),
22       SERVICE_CHARGE          NUMBER
23      );
24 
25 TYPE INVOICE_LIST_TABTYPE IS TABLE OF INVOICE_REC_TYPE;
26 
27 
28 /*========================================================================
29  | Prototype Declarations Procedures
30  *=======================================================================*/
31 
32   PG_DEBUG varchar2(1) := NVL(FND_PROFILE.value('AFLOG_ENABLED'), 'N');
33 
34 
35   FUNCTION get_iby_account_type(p_account_type        IN VARCHAR2) RETURN VARCHAR2;
36 
37   PROCEDURE write_debug_and_log(p_message IN VARCHAR2);
38 
39   PROCEDURE write_API_output(p_msg_count        IN NUMBER,
40                              p_msg_data         IN VARCHAR2);
41 
42   PROCEDURE apply_service_charge ( p_customer_id		  IN NUMBER,
43                                    p_site_use_id          IN NUMBER DEFAULT NULL,
44                                    x_return_status        OUT NOCOPY VARCHAR2);
45 
46   PROCEDURE apply_cash ( p_customer_id		    IN NUMBER,
47                          p_site_use_id          IN NUMBER DEFAULT NULL,
48                          p_cash_receipt_id      IN NUMBER,
49                          p_return_status         OUT NOCOPY VARCHAR2,
50                          p_apply_err_count       OUT NOCOPY NUMBER,
51                          x_msg_count           OUT NOCOPY NUMBER,
52                          x_msg_data            OUT NOCOPY VARCHAR2
53                        );
54 
55   PROCEDURE create_receipt (p_payment_amount        IN NUMBER,
56                             p_customer_id           IN NUMBER,
57                             p_site_use_id           IN NUMBER,
58                             p_bank_account_id       IN NUMBER,
59                             p_receipt_date          IN DATE DEFAULT trunc(SYSDATE),
60                             p_receipt_method_id     IN NUMBER,
61                             p_receipt_currency_code IN VARCHAR2,
62                             p_receipt_exchange_rate IN NUMBER,
63                             p_receipt_exchange_rate_type IN VARCHAR2,
64                             p_receipt_exchange_rate_date IN DATE,
65                             p_trxn_extn_id	    IN NUMBER,
66                             p_cash_receipt_id       OUT NOCOPY NUMBER,
67                             p_status                OUT NOCOPY VARCHAR2,
68                             x_msg_count           OUT NOCOPY NUMBER,
69                             x_msg_data            OUT NOCOPY VARCHAR2);
70 
71   PROCEDURE process_payment(
72 		p_cash_receipt_id     IN  NUMBER,
73 	        p_payer_rec           IN  IBY_FNDCPT_COMMON_PUB.PayerContext_rec_type,
74 	        P_payee_rec           IN  IBY_FNDCPT_TRXN_PUB.PayeeContext_rec_type,
75                 p_called_from         IN  VARCHAR2,
76                 p_response_error_code OUT NOCOPY VARCHAR2,
77                 x_msg_count           OUT NOCOPY NUMBER,
78                 x_msg_data            OUT NOCOPY VARCHAR2,
79 	        x_return_status       OUT NOCOPY VARCHAR2,
80                 p_cc_auth_code        OUT NOCOPY VARCHAR2,
81                 x_auth_result           OUT NOCOPY IBY_FNDCPT_TRXN_PUB.AuthResult_rec_type);
82 
83  PROCEDURE update_cc_bill_to_site(
84 		p_cc_location_rec	IN   HZ_LOCATION_V2PUB.LOCATION_REC_TYPE,
85 		x_cc_bill_to_site_id	IN  NUMBER,
86 		x_return_status		OUT NOCOPY VARCHAR2,
87 		x_msg_count		OUT NOCOPY NUMBER,
88 		x_msg_data		OUT NOCOPY VARCHAR2);
89 
90 /*========================================================================
91  | Prototype Declarations Functions
92  *=======================================================================*/
93 /*========================================================================
94  | PUBLIC function get_credit_card_type
95  |
96  | DESCRIPTION
97  |      Determines if a credit card number is valid
98  |      ----------------------------------------
99  |
100  | PSEUDO CODE/LOGIC
101  |
102  |
103  |
104  |
105  | PARAMETERS
106  |      credit_card_number   IN      Credit card number --
107  |                                   without white spaces
108  |
109  | RETURNS
110  |      TRUE  if credit card number is valid
111  |      FALSE if credit card number is invalid
112  |
113  | KNOWN ISSUES
114  |
115  |
116  |
117  | NOTES
118  |
119  |
120  |
121  | MODIFICATION HISTORY
122  | Date                  Author            Description of Changes
123  | 23-JAN-2001           O Steinmeier      Created
124  |
125  *=======================================================================*/
126 FUNCTION is_credit_card_number_valid(  p_credit_card_number IN  VARCHAR2 )
127          RETURN NUMBER IS
128 
129 
130   TYPE numeric_tab_typ IS TABLE of number INDEX BY BINARY_INTEGER;
131   TYPE character_tab_typ IS TABLE of char(1) INDEX BY BINARY_INTEGER;
132 
133   l_stripped_num_table		numeric_tab_typ;   /* Holds credit card number stripped of white spaces */
134   l_product_table		numeric_tab_typ;   /* Table of cc digits multiplied by 2 or 1,for validity check */
135   l_len_credit_card_num   	number := 0;  	   /* Length of credit card number stripped of white spaces */
136   l_product_tab_sum   		number := 0;  	   /* Sum of digits in product table */
137   l_actual_cc_check_digit       number := 0;  	   /* First digit of credit card, numbered from right to left */
138   l_mod10_check_digit        	number := 0;  	   /* Check digit after mod10 algorithm is applied */
139   j 				number := 0;  	   /* Product table index */
140   BEGIN
141 	arp_util.debug('ar_irec_payments_pkg.is_credit_card_number_valid()+0');
142 
143 	SELECT lengthb(p_credit_card_number)
144 	INTO   l_len_credit_card_num
145 	FROM   dual;
146 
147 	FOR i in 1..l_len_credit_card_num LOOP
148 		SELECT to_number(substrb(p_credit_card_number,i,1))
149 		INTO   l_stripped_num_table(i)
150 		FROM   dual;
151 	END LOOP;
152 	l_actual_cc_check_digit := l_stripped_num_table(l_len_credit_card_num);
153 
154 	FOR i in 1..l_len_credit_card_num-1 LOOP
155 		IF ( mod(l_len_credit_card_num+1-i,2) > 0 )
156 		THEN
157 		    -- Odd numbered digit.  Store as is, in the product table.
158 		    j := j+1;
159 	 	    l_product_table(j) := l_stripped_num_table(i);
160 		ELSE
161 		    -- Even numbered digit.  Multiply digit by 2 and store in the product table.
162 		    -- Numbers beyond 5 result in 2 digits when multiplied by 2. So handled seperately.
163 	            IF (l_stripped_num_table(i) >= 5)
164 		    THEN
165 		         j := j+1;
166 	 		 l_product_table(j) := 1;
167 		         j := j+1;
168 	 		 l_product_table(j) := (l_stripped_num_table(i) - 5) * 2;
169 		    ELSE
170 		         j := j+1;
171 	 		 l_product_table(j) := l_stripped_num_table(i) * 2;
172 		    END IF;
173 		END IF;
174 	END LOOP;
175 
176 	-- Sum up the product table's digits
177 	FOR k in 1..j LOOP
178 		l_product_tab_sum := l_product_tab_sum + l_product_table(k);
179 	END LOOP;
180 
181 	l_mod10_check_digit := mod( (10 - mod( l_product_tab_sum, 10)), 10);
182 
183 	-- If actual check digit and check_digit after mod10 don't match, the credit card is an invalid one.
184 	IF ( l_mod10_check_digit <> l_actual_cc_check_digit)
185 	THEN
186 		arp_util.debug('Card is Valid');
187 		arp_util.debug('ar_irec_payments_pkg.is_credit_card_number_valid()-');
188 		return(0);
189 	ELSE
190 		arp_util.debug('Card is not Valid');
191 		arp_util.debug('ar_irec_payments_pkg.is_credit_card_number_valid()-');
192 		return(1);
193 	END IF;
194 
195 END is_credit_card_number_valid;
196 
197 
198 /*========================================================================
199  | PUBLIC function get_credit_card_type
200  |
201  | DESCRIPTION
202  |      Determines for a given credit card number the credit card type.
203  |      ----------------------------------------
204  |
205  | PSEUDO CODE/LOGIC
206  |
207  | PARAMETERS
208  |      credit_card_number   IN      Credit card number
209  |
210  | RETURNS
211  |      credit_card type (based on lookup type  AR_IREC_CREDIT_CARD_TYPE
212  |
213  | KNOWN ISSUES
214  |
215  |
216  |
217  | NOTES
218  |
219  |
220  |
221  | MODIFICATION HISTORY
222  | Date                  Author            Description of Changes
223  | 22-JAN-2001           O Steinmeier      Created
224  | 11-AUG-2008          avepati             Bug 6493495 - TST1203.XB5.QA: CREDIT CARD PAYMENT NOT WORKING
225  |
226  *=======================================================================*/
227 FUNCTION get_credit_card_type(  p_credit_card_number IN  VARCHAR2 )
228          RETURN VARCHAR2 IS
229 
230   /*-----------------------------------------------------------------------+
231  | Use for file debug or standard output debug                           |
232  +-----------------------------------------------------------------------*/
233 
234 --   arp_standard.debug('AR_IREC_PAYMENTS.get_credit_card_type()+');
235 
236 --   arp_standard.debug(' p_credit_card_number :' || p_credit_card_number);
237 
238    l_card_issuer     iby_creditcard_issuers_b.card_issuer_code%TYPE;
239    l_issuer_range   iby_cc_issuer_ranges.cc_issuer_range_id%TYPE;
240    l_card_prefix    iby_cc_issuer_ranges.card_number_prefix%TYPE;
241    l_digit_check    iby_creditcard_issuers_b.digit_check_flag%TYPE;
242 
243  CURSOR c_range
244     (ci_card_number IN iby_creditcard.ccnumber%TYPE,
245      ci_card_len IN NUMBER)
246     IS
247       SELECT cc_issuer_range_id, r.card_issuer_code,
248         card_number_prefix, NVL(digit_check_flag,'N')
249       FROM iby_cc_issuer_ranges r, iby_creditcard_issuers_b i
250       WHERE (card_number_length = ci_card_len)
251         AND (INSTR(ci_card_number,card_number_prefix) = 1)
252         AND (r.card_issuer_code = i.card_issuer_code);
253   BEGIN
254     IF (c_range%ISOPEN) THEN CLOSE c_range; END IF;
255 
256     OPEN c_range(p_credit_card_number,LENGTH(p_credit_card_number));
257     FETCH c_range INTO l_issuer_range, l_card_issuer,
258       l_card_prefix, l_digit_check;
259     CLOSE c_range;
260 
261 --   arp_standard.debug(' l_card_issuer  :' || l_card_issuer);
262 
263     IF (l_card_issuer IS NULL) THEN
264       l_card_issuer := 'UNKNOWN';
265       l_digit_check := 'N';
266     END IF;
267     RETURN  l_card_issuer;
268 END get_credit_card_type;
269 
270 /*========================================================================
271  | PUBLIC function get_exchange_rate
272  |
273  | DESCRIPTION
274  |      Returns exchange rate information
275  |      ----------------------------------------
276  |
277  | PSEUDO CODE/LOGIC
278  |
279  | PARAMETERS
280  |
281  |
282  |
283  |
284  |
285  | RETURNS
286  |
287  |
288  | KNOWN ISSUES
289  |
290  |
291  |
292  | NOTES
293  |
294  |
295  |
296  | MODIFICATION HISTORY
297  | Date                  Author            Description of Changes
298  | 27-FEB-2001           O Steinmeier      Created
299  |
300  *=======================================================================*/
301 
302  PROCEDURE get_exchange_rate(
303               p_trx_currency_code   IN VARCHAR2,
304               p_trx_exchange_rate   IN NUMBER,
305               p_def_exchange_rate_date  IN DATE DEFAULT trunc(SYSDATE),
306               p_exchange_rate       OUT NOCOPY NUMBER,
307               p_exchange_rate_type  OUT NOCOPY VARCHAR2,
308               p_exchange_rate_date  OUT NOCOPY DATE) IS
309 
310 
311    l_fixed_rate     VARCHAR2(30);
312    l_procedure_name VARCHAR2(30);
313    l_debug_info	    VARCHAR2(200);
314 
315  BEGIN
316 
317    l_procedure_name := '.get_exchange_rate';
318 
319    -- By default set the exchange rate date to the proposed default.
320    --------------------------------------------------------------------------------
321    l_debug_info := 'Set the exchange rate date to the proposed default';
322    --------------------------------------------------------------------------------
323    p_exchange_rate_date := p_def_exchange_rate_date;
324 
325    -- first check if invoice is in foreign currency:
326 
327    if (p_trx_currency_code = arp_global.functional_currency) then
328 
329      -- trx currency is base currency; no exchange rate needed.
330      --------------------------------------------------------------------------------
331      l_debug_info := 'Transaction currency is base currency; no exchange rate needed';
332      --------------------------------------------------------------------------------
333      IF (PG_DEBUG = 'Y') THEN
334         arp_standard.debug('Trx currency is functional --> no exchange rate');
335      END IF;
336 
337      p_exchange_rate := NULL;
338      p_exchange_rate_type := NULL;
339      p_exchange_rate_date := NULL;
340 
341      RETURN;
342 
343    end if;
344 
345    -- check if currencies have fixed-rate relationship
346    --------------------------------------------------------------------------------
347    l_debug_info := 'Check if currencies have fixed-rate relationship';
348    --------------------------------------------------------------------------------
349    l_fixed_rate := gl_currency_api.is_fixed_rate(
350                          p_trx_currency_code,
351                          arp_global.functional_currency,
352                          p_exchange_rate_date);
353 
354    if l_fixed_rate = 'Y' then
355      --------------------------------------------------------------------------
356      l_debug_info := 'Exchange rate is fixed';
357      --------------------------------------------------------------------------
358      IF (PG_DEBUG = 'Y') THEN
359         arp_standard.debug('Fixed Rate');
360      END IF;
361 
362      p_exchange_rate_type := 'EMU FIXED';
363 
364      /* no need to get rate; rct api will get it anyway
365 
366      p_exchange_rate := arpcurr.getrate
367              (p_trx_currency_code,
368               arp_global.functional_currency,
369               p_exchange_rate_date,
370               p_exchange_rate_type);
371 
372      */
373 
374      IF (PG_DEBUG = 'Y') THEN
375         arp_standard.debug('Rate = ' || to_char(p_exchange_rate));
376      END IF;
377 
378    else  -- exchange rate is not fixed --> check profile for default type
379 
380      -------------------------------------------------------------------------------------
381      l_debug_info := 'Exchange rate is not fixed - check profile option for default type';
382      -------------------------------------------------------------------------------------
383      IF (PG_DEBUG = 'Y') THEN
384         arp_standard.debug('No Fixed Rate');
385      END IF;
386      p_exchange_rate_type := fnd_profile.value('AR_DEFAULT_EXCHANGE_RATE_TYPE');
387 
388      IF (PG_DEBUG = 'Y') THEN
389         arp_standard.debug('Profile option default exch rate type: '|| p_exchange_rate_type);
390      END IF;
391 
392      if (p_exchange_rate_type IS NOT NULL) then
393 
394        -- try to get exchange rate from GL for this rate type
395        -------------------------------------------------------------------------------------------
396        l_debug_info := 'Exchange rate type obtained from profile option - get exchange rate from GL';
397        -------------------------------------------------------------------------------------------
398        p_exchange_rate :=  arpcurr.getrate
399                (p_trx_currency_code,
400                 arp_global.functional_currency,
401                 p_exchange_rate_date,
402                 p_exchange_rate_type);
403 
404        IF (PG_DEBUG = 'Y') THEN
405           arp_standard.debug('Rate = ' || to_char(p_exchange_rate));
406        END IF;
407 
408        if p_exchange_rate = -1 then -- no rate found in GL
409 
410          -------------------------------------------------------------------------------------------
411          l_debug_info := 'Exchange rate not found in GL- use invoice exchange rate';
412          -------------------------------------------------------------------------------------------
413          IF (PG_DEBUG = 'Y') THEN
414             arp_standard.debug('no conversion rate found... using trx rate');
415          END IF;
416 
417          p_exchange_rate_type := 'User';
418          p_exchange_rate := p_trx_exchange_rate;
419 
420        else -- rate was successfully derived --> null it out so
421             -- rct api can rederive it (it doesn't allow a derivable rate
422             -- to be passed in!)
423 
424            p_exchange_rate := NULL;
425 
426 
427        end if;
428 
429      else -- rate type profile is not set --> use invoice exchange rate
430        -------------------------------------------------------------------------------------------
431        l_debug_info := 'Rate type profile not set - use invoice exchange rate';
432        -------------------------------------------------------------------------------------------
433        p_exchange_rate_type := 'User';
434        p_exchange_rate := p_trx_exchange_rate;
435 
436      end if;
437 
438    end if; -- fixed/non-fixed rate case
439 
440      IF (PG_DEBUG = 'Y') THEN
441         arp_standard.debug('Leaving get_exchange_rate: ');
442         arp_standard.debug('p_exchange_rate_type = ' || p_exchange_rate_type);
443         arp_standard.debug('p_exchange_rate      = ' || to_char(p_exchange_rate));
444      END IF;
445 
446  EXCEPTION
447     WHEN OTHERS THEN
448       write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
449       write_debug_and_log('- Transaction Currency Code: '||p_trx_currency_code);
450       write_debug_and_log('- Transaction Exchange Rate: '||p_trx_exchange_rate);
451       write_debug_and_log('- Exchange Rate found: '||p_exchange_rate);
452       write_debug_and_log('ERROR =>'|| SQLERRM);
453 
454       FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
455       FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
456       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
457       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
458       FND_MSG_PUB.ADD;
459 
460  END get_exchange_rate;
461 
462 
463 /*========================================================================
464  | PUBLIC function get_payment_information
465  |
466  | DESCRIPTION
467  |      Returns payment method and remittance bank information
468  |      ----------------------------------------
469  |
470  | PSEUDO CODE/LOGIC
471  |
472  | PARAMETERS
473  |
474  |
475  |
476  |
477  |
478  | RETURNS
479  |
480  |
481  | KNOWN ISSUES
482  |
483  |
484  |
485  | NOTES
486  |
487  |
488  |
489  | MODIFICATION HISTORY
490  | Date                  Author            Description of Changes
491  | 13-FEB-2001           O Steinmeier      Created
492  | 26-APR-2004           vnb               Bug # 3467287 - Customer Site ID made an input
493  |										   parameter.
494  | 22-JUN-2007		 mbolli		   Bug#6109909 - Not using 'Payment Method' set at
495  |					     customer/site level
496  | 19-AUG-2009   nkanchan   Bug # 8780501 - Payments are failing
497  |
498  *=======================================================================*/
499 
500 PROCEDURE  get_payment_information(
501                   p_customer_id		    IN NUMBER,
502                   p_site_use_id             IN NUMBER DEFAULT NULL,
503 		  p_payment_schedule_id     IN NUMBER,
504                   p_payment_instrument      IN VARCHAR2,
505                   p_trx_date                IN DATE,
506          	  p_currency_code           OUT NOCOPY VARCHAR2,
507                   p_exchange_rate           OUT NOCOPY VARCHAR2,
508           	  p_receipt_method_id       OUT NOCOPY NUMBER,
509            	  p_remit_bank_account_id   OUT NOCOPY NUMBER,
510            	  p_receipt_creation_status OUT NOCOPY VARCHAR2,
511                   p_trx_number              OUT NOCOPY VARCHAR2,
512 		  p_payment_channel_code    OUT NOCOPY VARCHAR2
513                   ) IS
514 
515 
516 CURSOR payment_method_info_cur IS
517    SELECT rm.receipt_method_id receipt_method_id, rm.payment_channel_code payment_channel_code,
518           rc.creation_status receipt_creation_status
519    FROM   ar_system_parameters sp,
520           ar_receipt_classes rc,
521           ar_receipt_methods rm
522    WHERE  rm.receipt_method_id = decode(p_payment_instrument,                        /* J Rautiainen ACH Implementation */
523                                        'BANK_ACCOUNT', sp.irec_ba_receipt_method_id, /* J Rautiainen ACH Implementation */
524                                         sp.irec_cc_receipt_method_id)                /* J Rautiainen ACH Implementation */
525       AND rm.receipt_class_id = rc.receipt_class_id;
526 
527   --Bug3186314: Cursor to get the payment method at customer/site level.
528   CURSOR cust_payment_method_info_cur(p_siteuseid NUMBER, p_currcode VARCHAR2) IS
529    SELECT arm.receipt_method_id receipt_method_id, arm.payment_channel_code payment_channel_code,
530           arc.creation_status receipt_creation_status
531    FROM      ar_receipt_methods         arm,
532              ra_cust_receipt_methods    rcrm,
533              ar_receipt_method_accounts arma,
534              ce_bank_acct_uses_ou_v          aba,
535              ce_bank_accounts           cba,
536              ar_receipt_classes         arc
537    WHERE     arm.receipt_method_id = rcrm.receipt_method_id
538    AND       arm.receipt_method_id = arma.receipt_method_id
539    AND       arm.receipt_class_id  = arc.receipt_class_id
540    AND       rcrm.customer_id      = p_customer_id
541    AND       arma.remit_bank_acct_use_id = aba.bank_acct_use_id
542    AND       aba.bank_account_id = cba.bank_account_id
543    AND
544              (
545                  NVL(rcrm.site_use_id,
546                      p_siteuseid)   = p_siteuseid
547                OR
548                  (
549                         p_siteuseid IS NULL
550                    AND  rcrm.site_use_id  IS NULL
551                  )
552              )
553 --Bug#6109909
554    --AND       rcrm.primary_flag          = 'Y'
555    AND       (
556                  cba.currency_code    =
557                              p_currcode OR
558                  cba.receipt_multi_currency_flag = 'Y'
559              )
560    AND      (
561                  (    p_payment_instrument = 'BANK_ACCOUNT'
562 --Bug 6024713: Choose 'NONE' if arm.payment_type_code is NULL
563 --Bug#6109909:
564       -- In 11i The 'PaymentMethod' in UI maps to 'payment_type_code' column of table ar_receipts_methods
565       -- and in R12, it maps to 'payment_channel_code' whose values are taken from IBY sources.
566       -- In R12, the 'payment_type_code' is 'NONE' for new records.
567       -- AND In R12, Here we are not handling the code for the other payment Methods like Bills Receivable, Debit Card etc..,
568 
569              --  and nvl(arm.payment_type_code, 'NONE') <> 'CREDIT_CARD'
570                   and arm.payment_channel_code <> 'CREDIT_CARD'
571                   and arc.remit_flag = 'Y'
572                   and arc.confirm_flag = 'N')
573              OR  (    p_payment_instrument <> 'BANK_ACCOUNT'
574     --Bug#6109909
575                 --and nvl(arm.payment_type_code, 'NONE') = 'CREDIT_CARD')
576                   and arm.payment_channel_code = 'CREDIT_CARD')
577             )
578 
579   -- Bug#6109909:
580      -- In R12,Currency code is not mandatory on the customer bank account and so removing the
581      -- below condition.
582      -- Observations for the below condition, if it requires in future:
583      -- a. The where caluse criteria 'party_id = p_customer_id' should be replaced
584      --    with 'cust_account_id = p_customer_id'
585      -- b. For 'AUTOMATIC' creation methods, Don't validate the currencyCode for
586      -- 'Credit Card' instrucment types. Here validate only for 'BankAccount'
587 
588   /*
589 
590    AND      ( arc.creation_method_code = 'MANUAL' or
591             ( arc.creation_method_code = 'AUTOMATIC' and
592 --Bug 4947418: Modified the following query as ar_customer_bank_accounts_v
593 --has been obsoleted in r12.
594               p_currcode in (select currency_code from
595 		iby_fndcpt_payer_assgn_instr_v
596 		where party_id=p_customer_id)))
597    */
598 
599 
600    -- AND       aba.set_of_books_id = arp_trx_global.system_info.system_parameters.set_of_books_id
601    AND       TRUNC(nvl(aba.end_date,
602                          p_trx_date)) >=
603              TRUNC(p_trx_date)
604 --Bug 6024713: Added TRUNC for the left side for the below 3 criterias
605    AND       TRUNC(p_trx_date) between
606                       TRUNC(nvl(
607                                    arm.start_date,
608                                   p_trx_date))
609                   and TRUNC(nvl(
610                                   arm.end_date,
611                                   p_trx_date))
612    AND       TRUNC(p_trx_date) between
613                       TRUNC(nvl(
614                                    rcrm.start_date,
615                                   p_trx_date))
616                   and TRUNC(nvl(
617                                   rcrm.end_date,
618                                   p_trx_date))
619    AND       TRUNC(p_trx_date) between
620                       TRUNC(arma.start_date)
621                   and TRUNC(nvl(
622                                   arma.end_date,
623                                   p_trx_date))
624               ORDER BY rcrm.primary_flag DESC;
625 
626 --Bug 6339265 : Cursor to get CC Payment Method set in the profile OIR_CC_PMT_METHOD.
627  CURSOR cc_profile_pmt_method_info_cur IS
628   SELECT arm.receipt_method_id receipt_method_id,
629     arm.payment_channel_code payment_channel_code,
630     arc.creation_status receipt_creation_status
631   FROM ar_receipt_methods arm,
632     ar_receipt_method_accounts arma,
633     ce_bank_acct_uses_ou_v aba,
634     ce_bank_accounts       cba,
635     ar_receipt_classes arc
636   WHERE arm.payment_channel_code = 'CREDIT_CARD'
637     AND arm.receipt_method_id = NVL( to_number(fnd_profile.VALUE('OIR_CC_PMT_METHOD')), arm.receipt_method_id)
638     AND arm.receipt_method_id = arma.receipt_method_id
639     AND arm.receipt_class_id = arc.receipt_class_id
640     AND arma.remit_bank_acct_use_id = aba.bank_acct_use_id
641     AND aba.bank_account_id = cba.bank_account_id
642     AND (cba.currency_code = p_currency_code OR cba.receipt_multi_currency_flag = 'Y')
643     AND TRUNC(nvl(aba.end_date,p_trx_date)) >= TRUNC(p_trx_date)
644     AND TRUNC(p_trx_date) BETWEEN TRUNC(nvl(arm.start_date,   p_trx_date)) AND TRUNC(nvl(arm.end_date,   p_trx_date))
645     AND TRUNC(p_trx_date) BETWEEN TRUNC(arma.start_date) AND TRUNC(nvl(arma.end_date,   p_trx_date));
646 
647   --Bug 6339265 : Cursor to get Bank Acount Payment Method set in the profile OIR_BA_PMT_METHOD.
648  CURSOR ba_profile_pmt_method_info_cur IS
649   SELECT arm.receipt_method_id receipt_method_id,
650     arm.payment_channel_code payment_channel_code,
651     arc.creation_status receipt_creation_status
652   FROM ar_receipt_methods arm,
653     ar_receipt_method_accounts arma,
654     ce_bank_acct_uses_ou_v aba,
655     ce_bank_accounts       cba,
656     ar_receipt_classes arc
657   WHERE NVL(arm.payment_channel_code,'NONE') <> 'CREDIT_CARD'
658     AND arm.receipt_method_id = NVL( to_number(fnd_profile.VALUE('OIR_BA_PMT_METHOD')), arm.receipt_method_id)
659     AND arm.receipt_method_id = arma.receipt_method_id
660     AND arm.receipt_class_id = arc.receipt_class_id
661     AND arma.remit_bank_acct_use_id = aba.bank_acct_use_id
662     AND aba.bank_account_id = cba.bank_account_id
663     AND (cba.currency_code = p_currency_code OR cba.receipt_multi_currency_flag = 'Y')
664     AND TRUNC(nvl(aba.end_date,p_trx_date)) >= TRUNC(p_trx_date)
665     AND TRUNC(p_trx_date) BETWEEN TRUNC(nvl(arm.start_date,   p_trx_date)) AND TRUNC(nvl(arm.end_date,   p_trx_date))
666     AND TRUNC(p_trx_date) BETWEEN TRUNC(arma.start_date) AND TRUNC(nvl(arma.end_date,   p_trx_date));
667 
668 CURSOR payment_schedule_info_cur IS
669    SELECT customer_site_use_id, invoice_currency_code, exchange_rate,trx_number
670    FROM   ar_payment_schedules
671    WHERE  payment_schedule_id = p_payment_schedule_id;
672 
673    payment_method_info    payment_method_info_cur%ROWTYPE;
674    payment_schedule_info  payment_schedule_info_cur%ROWTYPE;
675    cust_payment_method_info  cust_payment_method_info_cur%ROWTYPE;
676    cc_profile_pmt_method_info cc_profile_pmt_method_info_cur%ROWTYPE;
677    ba_profile_pmt_method_info ba_profile_pmt_method_info_cur%ROWTYPE;
678 
679   l_customer_id		RA_CUST_RECEIPT_METHODS.CUSTOMER_ID%TYPE;
680   l_site_use_id		RA_CUST_RECEIPT_METHODS.SITE_USE_ID%TYPE;
681   l_currency_code	AR_PAYMENT_SCHEDULES_ALL.INVOICE_CURRENCY_CODE%TYPE;
682 
683   l_procedure_name VARCHAR2(30);
684   l_debug_info	   VARCHAR2(200);
685 
686 BEGIN
687 
688    l_procedure_name := '.get_payment_information';
689 
690    --------------------------------------------------------------------
691    l_debug_info := 'Get payment schedule information';
692    --------------------------------------------------------------------
693    OPEN payment_schedule_info_cur;
694    FETCH payment_schedule_info_cur INTO payment_schedule_info;
695    close payment_schedule_info_cur;
696 
697    l_currency_code := payment_schedule_info.invoice_currency_code;
698    l_site_use_id   := payment_schedule_info.customer_site_use_id;
699    p_trx_number    := payment_schedule_info.trx_number;
700    p_exchange_rate := payment_schedule_info.exchange_rate;
701 
702    -- ### required change: error handling
703    -- ### in case the query fails.
704 
705   --Bug # 3467287 - The Global Temp table must be striped by Customer and Customer Site.
706   if (p_payment_schedule_id is null ) then
707     -- this is the case for multiple invoices.
708     ------------------------------------------------------------------------
709     l_debug_info := 'There are multiple invoices: get customer information';
710     ------------------------------------------------------------------------
711     BEGIN
712       select customer_id,customer_site_use_id,currency_code into l_customer_id,l_site_use_id,l_currency_code
713       from AR_IREC_PAYMENT_LIST_GT
714       where customer_id = p_customer_id
715       and customer_site_use_id = nvl(decode(p_site_use_id, -1, null, p_site_use_id), customer_site_use_id);
716       EXCEPTION
717         when others then
718           IF (PG_DEBUG = 'Y') THEN
719             arp_standard.debug('There may be invoices with different sites');
720           END IF;
721     END;
722     if ( l_customer_id is null ) then
723      --Code should not come here ideally
724      BEGIN
725         select currency_code into l_currency_code
726         from AR_IREC_PAYMENT_LIST_GT
727         group by currency_code;
728         EXCEPTION
729           when others then
730             IF (PG_DEBUG = 'Y') THEN
731               arp_standard.debug('There may be invoices with different currencies');
732             END IF;
733       END;
734     end if;
735   end if;
736 
737   -- IF Customer Site Use Id is -1 then it is to be set as null
738   IF ( l_site_use_id = -1 ) THEN
739     l_site_use_id := NULL;
740   END IF;
741 
742     IF (p_payment_instrument <> 'BANK_ACCOUNT') THEN
743 	  ---------------------------------------------------------------------------------
744 	  l_debug_info := 'Get payment method information from the OIR_CC_PMT_METHOD profile';
745 	  ---------------------------------------------------------------------------------
746 	  IF (fnd_profile.VALUE('OIR_CC_PMT_METHOD') IS NOT NULL AND fnd_profile.VALUE('OIR_CC_PMT_METHOD') <> 'DISABLED') THEN
747 
748             BEGIN
749 
750 		  OPEN  cc_profile_pmt_method_info_cur;
751 		  FETCH cc_profile_pmt_method_info_cur INTO cc_profile_pmt_method_info;
752 
753 	      /* If CC Payment Method set is NULL or DISABLED or an invalid payment method, it returns NO rows */
754 
755 		  IF cc_profile_pmt_method_info_cur%FOUND THEN
756 		    p_receipt_creation_status	:=  cc_profile_pmt_method_info.receipt_creation_status;
757 		    p_receipt_method_id		:=  cc_profile_pmt_method_info.receipt_method_id;
758                     p_payment_channel_code  :=  cc_profile_pmt_method_info.payment_channel_code;
759 		  END IF;
760 
761 		  CLOSE cc_profile_pmt_method_info_cur;
762 
763             EXCEPTION
764               WHEN OTHERS THEN
765                 l_debug_info := 'Invalid Payment Method is Set in the profile OIR_CC_PMT_METHOD. Value in profile=' ||  fnd_profile.VALUE('OIR_CC_PMT_METHOD');
766 		     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
767 		        fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info
768                                             ||':ERROR =>'|| SQLERRM);
769 		     end if;
770             END;
771 
772 	  END IF;
773   END IF;
774 
775   IF (p_payment_instrument <> 'CREDIT_CARD') THEN
776 	  ---------------------------------------------------------------------------------
777 	  l_debug_info := 'Get payment method information from the OIR_BA_PMT_METHOD profile';
778 	  ---------------------------------------------------------------------------------
779 	  IF (fnd_profile.VALUE('OIR_BA_PMT_METHOD') IS NOT NULL AND fnd_profile.VALUE('OIR_BA_PMT_METHOD') <> 'DISABLED') THEN
780 
781             BEGIN
782 
783 		  OPEN  ba_profile_pmt_method_info_cur;
784 		  FETCH ba_profile_pmt_method_info_cur INTO ba_profile_pmt_method_info;
785 
786 	      /* If BA Payment Method set is NULL or DISABLED or an invalid payment method, it returns NO rows */
787 
788 		  IF ba_profile_pmt_method_info_cur%FOUND THEN
789 		    p_receipt_creation_status	:=  ba_profile_pmt_method_info.receipt_creation_status;
790 		    p_receipt_method_id		:=  ba_profile_pmt_method_info.receipt_method_id;
791 		    p_payment_channel_code  :=  ba_profile_pmt_method_info.payment_channel_code;
792 		  END IF;
793 
794 		  CLOSE ba_profile_pmt_method_info_cur;
795 
796             EXCEPTION
797               WHEN OTHERS THEN
798                 l_debug_info := 'Invalid Payment Method is Set in the profile OIR_BA_PMT_METHOD. Value in profile=' ||  fnd_profile.VALUE('OIR_BA_PMT_METHOD');
799 		     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
800 		        fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info
801                                             ||':ERROR =>'|| SQLERRM);
802 		     end if;
803             END;
804 
805 	  END IF;
806   END IF;
807 
808   IF ( p_receipt_method_id IS NULL ) THEN
809 
810   ---------------------------------------------------------------------------------
811   l_debug_info := 'Get payment method information from the relevant customer site';
812   ---------------------------------------------------------------------------------
813   OPEN  cust_payment_method_info_cur(l_site_use_id, l_currency_code);
814   FETCH cust_payment_method_info_cur INTO cust_payment_method_info;
815 
816   IF cust_payment_method_info_cur%FOUND THEN
817     p_receipt_creation_status := cust_payment_method_info.receipt_creation_status;
818     p_receipt_method_id := cust_payment_method_info.receipt_method_id;
819     p_payment_channel_code := cust_payment_method_info.payment_channel_code;
820   END IF;
821   CLOSE cust_payment_method_info_cur;
822  END IF;
823 
824   if ( p_receipt_method_id is null ) then
825     ----------------------------------------------------------------------------------------
826     l_debug_info := 'Get payment method information from the customer at the account level';
827     ----------------------------------------------------------------------------------------
828     l_site_use_id := NULL;
829     OPEN  cust_payment_method_info_cur(l_site_use_id, l_currency_code);
830     FETCH cust_payment_method_info_cur INTO cust_payment_method_info;
831 
832     IF cust_payment_method_info_cur%FOUND THEN
833       p_receipt_creation_status := cust_payment_method_info.receipt_creation_status;
834       p_receipt_method_id := cust_payment_method_info.receipt_method_id;
835       p_payment_channel_code := cust_payment_method_info.payment_channel_code;
836     END IF;
837     CLOSE cust_payment_method_info_cur;
838   end if;
839 
840   if ( p_receipt_method_id is null ) then
841     -- get from system parameters
842     ----------------------------------------------------------------------------------------
843     l_debug_info := 'Get payment method information from the system parameters';
844     ----------------------------------------------------------------------------------------
845     OPEN  payment_method_info_cur;
846     FETCH payment_method_info_cur INTO payment_method_info;
847 
848     IF payment_method_info_cur%FOUND THEN
849       p_receipt_creation_status := payment_method_info.receipt_creation_status;
850       p_receipt_method_id := payment_method_info.receipt_method_id;
851       p_payment_channel_code := payment_method_info.payment_channel_code;
852     END IF;
853     CLOSE payment_method_info_cur;
854   end if;
855 
856   --Bug # 3467287 - p_site_use_id is made an input parameter.
857   --p_site_use_id   := l_site_use_id;
858   p_currency_code := l_currency_code;
859 
860 EXCEPTION
861     WHEN OTHERS THEN
862       write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
863       write_debug_and_log('- Customer Id: '||p_customer_id);
864       write_debug_and_log('- Customer Site Id: '||p_site_use_id);
865       write_debug_and_log('- Receipt Method Id: '||p_receipt_method_id);
866       write_debug_and_log('- Payment Schedule Id: '||p_payment_schedule_id);
867       write_debug_and_log('ERROR =>'|| SQLERRM);
868 
869       FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
870       FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
871       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
872       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
873       FND_MSG_PUB.ADD;
874 
875 END get_payment_information;
876 
877 /*========================================================================
878  | PUBLIC procedure update_expiration_date
879  |
880  | DESCRIPTION
881  |      Updates credit card expiration date
882  |      ----------------------------------------
883  |
884  | PSEUDO CODE/LOGIC
885  |
886  | PARAMETERS
887  |
888  |      p_bank_account_id         Credit Card bank account id
889  |      p_expiration_date	  New expiration date
890  |
891  | KNOWN ISSUES
892  |
893  |
894  |
895  | NOTES
896  |
897  |
898  |
899  | MODIFICATION HISTORY
900  | Date                  Author            Description of Changes
901  | 10-FEB-2001           O Steinmeier      Created
902  |
903  | Removed code 'BANK_ACCOUNT_NUM = p_bank_account_num AND ' from select for bug # 9046643
904  | 06-Feb-2013           melapaku  Bug16262617 - cannot remove end date entered via ireceivables pay function
905  | 01-Mar-2013           melapaku  Bug16420473 - CANNOT END DATE BANK ACC WHICH IS ASSOCIATED AT ACC AND SITE LEVEL IN
906  |                                               IRECEIVABLES
907  *=======================================================================*/
908 PROCEDURE update_expiration_date( p_bank_account_id     IN  NUMBER,
909                                   p_expiration_date     IN  DATE,
910                                   p_payment_instrument  IN VARCHAR2,
911                                   p_branch_id			IN iby_ext_bank_accounts.BRANCH_ID%TYPE,
912                                   p_bank_id			    IN iby_ext_bank_accounts.BANK_ID%TYPE,
913                                   p_bank_account_num	IN iby_ext_bank_accounts.BANK_ACCOUNT_NUM%TYPE,
914                                   p_currency			IN iby_ext_bank_accounts.CURRENCY_CODE%TYPE,
915                                   p_object_version_number IN iby_ext_bank_accounts.OBJECT_VERSION_NUMBER%TYPE,
916 				  x_return_status       OUT NOCOPY VARCHAR,
917 				  x_msg_count           OUT NOCOPY NUMBER,
918 				  x_msg_data            OUT NOCOPY VARCHAR2,
919                                   p_customer_id IN NUMBER,
920                                   p_customer_site_id IN NUMBER) IS
921 
922 CURSOR instr_details(p_bank_account_id IN NUMBER,
923                       l_party_id IN NUMBER,
924                       l_customer_site_id IN NUMBER) IS
925   select org_id,instr_assignment_id,assignment_start_date,acct_site_use_id
926   from IBY_FNDCPT_PAYER_ASSGN_INSTR_V
927   where INSTRUMENT_ID =  p_bank_account_id AND PARTY_ID = l_party_id
928   AND((l_customer_site_id IS NOT NULL AND ACCT_SITE_USE_ID = l_customer_site_id ) OR (l_customer_site_id IS NULL AND ACCT_SITE_USE_ID IS NULL));
929 
930    l_create_credit_card		IBY_FNDCPT_SETUP_PUB.CreditCard_rec_type;
931    l_ext_bank_acct_rec      IBY_EXT_BANKACCT_PUB.ExtBankAcct_rec_type;
932    l_result_rec			IBY_FNDCPT_COMMON_PUB.Result_rec_type;
933    l_procedure_name		VARCHAR2(30);
934    l_party_id  NUMBER;
935    l_payerContext_Rec_type	IBY_FNDCPT_COMMON_PUB.PayerContext_Rec_type;
936    l_pmtInstrAssignment_Rec_type	IBY_FNDCPT_SETUP_PUB.PmtInstrAssignment_rec_type;
937    l_pmtInstr_rec_type		IBY_FNDCPT_SETUP_PUB.PmtInstrument_rec_type;
938    l_org_id NUMBER;
939    l_instr_assignment_id NUMBER;
940    l_assignment_start_date DATE;
941    l_assignment_id		NUMBER(15,0);
942    l_customer_site_id NUMBER;
943    l_acct_site_use_id NUMBER;
944 BEGIN
945 
946 l_procedure_name		     := '.update_expiration_date';
947 WRITE_DEBUG_AND_LOG('Input Parameters for update_expiration_date'||
948                     'p_customer_site_id ' || p_customer_site_id ||
949                     'p_object_version_number ' || p_object_version_number ||
950                     'p_bank_account_id ' || p_bank_account_id ||
951                     'p_currency ' || p_currency||
952 			              'p_expiration_date '||p_expiration_date||
953                     'p_customer_id '||p_customer_id||
954                     'p_branch_id '||p_branch_id
955                    );
956 
957 --Added for Bug#16262617
958 IF (p_customer_site_id = -1) THEN
959    l_customer_site_id := NULL;
960 ELSE
961   l_customer_site_id := p_customer_site_id;
962 END IF;
963 
964 IF p_payment_instrument = 'CREDIT_CARD' THEN
965 
966         WRITE_DEBUG_AND_LOG('In CC expiration date update');
967         l_create_credit_card.card_id         := p_bank_account_id ;
968         l_create_credit_card.expiration_date := p_expiration_date;
969 
970         IBY_FNDCPT_SETUP_PUB.update_card(
971 	        p_api_version      => 1.0,
972 	        p_init_msg_list    => FND_API.G_TRUE,
973 	        p_commit           => FND_API.G_FALSE,
974 	        x_return_status    => x_return_status,
975 	        x_msg_count        => x_msg_count,
976 	        x_msg_data         => x_msg_data,
977 	        p_card_instrument  => l_create_credit_card,
978 	        x_response         => l_result_rec);
979 
980 
981    IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
982       if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
983 	      fnd_log.string(fnd_log.LEVEL_STATEMENT,
984                       G_PKG_NAME||l_procedure_name,
985                       'ERROR IN UPDATING CREDIT CARD');
986           fnd_log.string(fnd_log.LEVEL_STATEMENT,
987                       G_PKG_NAME||l_procedure_name,l_result_rec.result_code);
988       end if;
989       x_msg_data      := l_result_rec.result_code;
990       x_return_status := FND_API.G_RET_STS_ERROR;
991       write_error_messages(x_msg_data, x_msg_count);
992     END IF;
993 ELSE
994         WRITE_DEBUG_AND_LOG('In BA expiration date update');
995        -- Modified for Bug#16262617 : Start
996         SELECT PARTY_ID INTO l_party_id FROM HZ_CUST_ACCOUNTS WHERE CUST_ACCOUNT_ID = p_customer_id;
997          -- Modified for Bug#16420473 :Start
998         OPEN instr_details(p_bank_account_id,l_party_id,l_customer_site_id);
999         IF (instr_details%NOTFOUND) THEN
1000             select org_id,instr_assignment_id,assignment_start_date,acct_site_use_id
1001             into l_org_id,l_instr_assignment_id,l_assignment_start_date,l_acct_site_use_id
1002             from IBY_FNDCPT_PAYER_ASSGN_INSTR_V
1003             where INSTRUMENT_ID =  p_bank_account_id AND PARTY_ID = l_party_id
1004             AND ACCT_SITE_USE_ID IS NULL;
1005            CLOSE instr_details;
1006         ELSE
1007            FETCH instr_details into l_org_id,l_instr_assignment_id,l_assignment_start_date,l_acct_site_use_id;
1008            CLOSE instr_details;
1009         END IF;
1010         -- Modified for Bug#16420473 :End
1011         l_payerContext_Rec_type.Payment_Function	:= 'CUSTOMER_PAYMENT';
1012 	      l_payerContext_Rec_type.Party_Id		:= l_party_id;
1013         l_payerContext_Rec_type.Cust_Account_Id		:= p_customer_id;
1014    	if(l_acct_site_use_id is not null) then
1015 	   	  l_payerContext_Rec_type.Org_Type		:= 'OPERATING_UNIT';
1016 		  l_payerContext_Rec_type.Org_Id		:= l_org_id;
1017 		  l_payerContext_Rec_type.Account_Site_id	:= l_acct_site_use_id;
1018 	 end if;
1019         l_pmtInstr_rec_type.Instrument_type := 'BANKACCOUNT';
1020 	l_pmtInstr_rec_type.Instrument_Id   := p_bank_account_id;
1021 
1022 	l_pmtInstrAssignment_Rec_type.Assignment_Id	:= l_instr_assignment_id;
1023 	l_pmtInstrAssignment_Rec_type.Instrument	:= l_pmtInstr_rec_type;
1024 	l_pmtInstrAssignment_Rec_type.Priority		:= 1;
1025 	l_pmtInstrAssignment_Rec_type.Start_Date	:= l_assignment_start_date;
1026 	l_pmtInstrAssignment_Rec_type.End_Date		:= p_expiration_date;
1027 
1028         WRITE_DEBUG_AND_LOG('l_instr_assignment_id '||l_instr_assignment_id||
1029                        'l_assignment_start_date '||l_assignment_start_date||
1030                        'l_org_id '||l_org_id||' l_party_id '||l_party_id||
1031                        'l_payerContext_Rec_type.Account_Site_id '||l_payerContext_Rec_type.Account_Site_id||
1032                        'l_customer_site_id '||l_customer_site_id);
1033 
1034 	IBY_FNDCPT_SETUP_PUB.Set_Payer_Instr_Assignment(
1035 		    p_api_version      => 1.0,
1036 		    p_init_msg_list    => FND_API.G_FALSE,
1037 		    p_commit           => FND_API.G_FALSE,
1038 		    x_return_status    => x_return_status,
1039 		    x_msg_count        => x_msg_count,
1040 		    x_msg_data         => x_msg_data,
1041 		    p_payer            => l_payerContext_Rec_type,
1042 		    p_assignment_attribs => l_pmtInstrAssignment_Rec_type,
1043 		    x_assign_id        => l_assignment_id,
1044 		    x_response         => l_result_rec
1045 	);
1046    -- Modified for Bug# 16262617 : End
1047 
1048     IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
1049       if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
1050 	      fnd_log.string(fnd_log.LEVEL_STATEMENT,
1051                       G_PKG_NAME||l_procedure_name,
1052                       'ERROR IN UPDATING BANK ACCOUNT');
1053           fnd_log.string(fnd_log.LEVEL_STATEMENT,
1054                       G_PKG_NAME||l_procedure_name,x_msg_data);
1055       end if;
1056       x_return_status := FND_API.G_RET_STS_ERROR;
1057       write_error_messages(x_msg_data, x_msg_count);
1058     END IF;
1059 END IF;
1060 
1061 
1062 EXCEPTION
1063 WHEN OTHERS THEN
1064       write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
1065       write_debug_and_log('- Card Id: '||p_bank_account_id);
1066       write_debug_and_log('- Expiration Date: '||p_expiration_date);
1067       write_debug_and_log('ERROR =>'|| SQLERRM);
1068 
1069       FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
1070       FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
1071       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
1072 
1073       FND_MSG_PUB.ADD;
1074 
1075 END;
1076 /*========================================================================
1077  | PUBLIC function allow_payment
1078  |
1079  | DESCRIPTION
1080  |      Determines if payment schedule can be paid:
1081  |
1082  |   It will return TRUE if
1083  |
1084  |   - payment button is enabled via function security
1085  |     (need to define function)
1086  |   - the remaining balance of the payment schedule is > 0
1087  |   - a payment method has been defined in AR_SYSTEM_PARAMETERS
1088  |     for credit card payments
1089  |   - a bank account assignment in the currency of the invoice
1090  |     exists and is active.
1091  |
1092  |   Use this function to enable or disable the "Pay" button on
1093  |   the invoice and invoice activities pages.
1094  |
1095  |
1096  |      ----------------------------------------
1097  |
1098  | PSEUDO CODE/LOGIC
1099  |
1100  | PARAMETERS
1101  |
1102  |      p_payment_schedule_id     Payment Schedule to be paid
1103  |
1104  | KNOWN ISSUES
1105  |
1106  |
1107  |
1108  | NOTES
1109  |
1110  |
1111  |
1112  | MODIFICATION HISTORY
1113  | Date                  Author            Description of Changes
1114  | 13-FEB-2001           O Steinmeier      Created
1115  |
1116  *=======================================================================*/
1117 
1118 
1119 FUNCTION allow_payment(p_payment_schedule_id IN NUMBER, p_customer_id IN NUMBER , p_customer_site_id IN NUMBER)  RETURN BOOLEAN IS
1120 
1121   l_ps_balance    NUMBER;
1122   l_bank_account_method   NUMBER;
1123   l_credit_card_method    NUMBER; /* J Rautiainen ACH Implementation */
1124   l_currency_code ar_payment_schedules.invoice_currency_code%type;
1125   l_class        ar_payment_schedules.class%TYPE;
1126   l_creation_status ar_receipt_classes.creation_status%TYPE;
1127 
1128 BEGIN
1129 
1130   -- check that function security is allowing access to payment button
1131 
1132   IF NOT fnd_function.test('ARW_PAY_INVOICE') THEN
1133     RETURN FALSE;
1134   END IF;
1135 
1136   -- check trx type and balance: trx type must be debit item, balance > 0
1137 
1138   SELECT amount_due_remaining, class, invoice_currency_code
1139   INTO   l_ps_balance, l_class, l_currency_code
1140   FROM   ar_payment_schedules
1141   WHERE  payment_schedule_id = p_payment_schedule_id;
1142   --Bug 4161986 - Pay Icon does not appear in the ChargeBack and its activities page. Added the class CB(Chargeback)
1143   IF l_ps_balance <= 0
1144      OR l_class NOT IN ('INV', 'DEP', 'GUAR', 'DM', 'CB') THEN
1145 
1146      RETURN FALSE;
1147 
1148   END IF;
1149 
1150   -- verify that method is set up
1151   l_credit_card_method := is_credit_card_payment_enabled(p_customer_id , p_customer_site_id , l_currency_code) ;
1152 
1153   -- Bug 3338276
1154   -- If one-time payment is enabled, bank account payment is not enabled;
1155   -- Hence, the check for valid bank account payment methods can be defaulted to 0.
1156   -- Bug 3886652 - Customer Id and Customer Site Use Id added as params to ARI_CONFIG.save_payment_instrument_info
1157   IF NOT ARI_UTILITIES.save_payment_instrument_info(p_customer_id , p_customer_site_id) THEN
1158     l_bank_account_method := 0;
1159   ELSE
1160     l_bank_account_method := is_bank_acc_payment_enabled(p_customer_id , p_customer_site_id , l_currency_code);
1161   END IF;
1162 
1163   IF   l_bank_account_method  = 0
1164    AND l_credit_card_method = 0
1165   THEN
1166     RETURN FALSE;
1167 
1168   END IF;
1169 
1170   RETURN TRUE;
1171 
1172 END allow_payment;
1173 
1174 -- cover function on top of allow_payments to allow usage in SQL statements.
1175 
1176 FUNCTION payment_allowed(p_payment_schedule_id IN NUMBER,p_customer_id IN NUMBER , p_customer_site_id IN NUMBER) RETURN NUMBER IS
1177 BEGIN
1178   if allow_payment(p_payment_schedule_id , p_customer_id , p_customer_site_id ) then
1179      return 1;
1180   else
1181      return 0;
1182   end if;
1183 END payment_allowed;
1184 
1185 /*========================================================================
1186  | PUBLIC procedure get_default_payment_instrument
1187  |
1188  | DESCRIPTION
1189  |      Return payment instrument information if one can be defaulted for the user
1190  |      ----------------------------------------
1191  |
1192  | PSEUDO CODE/LOGIC
1193  |
1194  | PARAMETERS
1195  |      customer_id IN Customer Id to which credit cards are releated to
1196  |      customer_site_use_id IN Customer Site Use Id to which credit cards are releated to
1197  |	currency_code	IN	VARCHAR2
1198  |
1199  | RETURNS
1200  |      p_bank_account_num_masked Masked credit card number
1201  |      p_credit_card_type        Type of the credit card
1202  |      p_expiry_month            Credit card expiry month
1203  |      p_expiry_year             Credit card expiry year
1204  |      p_credit_card_expired     '1' if credit card has expired, '0' otherwise
1205  |      p_bank_account_id         Bank Account id of the credit card
1206  |
1207  | KNOWN ISSUES
1208  |
1209  | NOTES
1210  |
1211  | MODIFICATION HISTORY
1212  | Date                  Author            Description of Changes
1213  | 22-JAN-2001           J Rautiainen      Created
1214  | 20-May-2004		 hikumar	   Added currencyCode
1215  | 26-Oct-2004       vnb           Bug 3944029 - Correct payment instrument to be picked at customer account level
1216  | 23-Dec-2004       vnb           Bug 3928412 - RA_CUSTOMERS obsolete;removed reference to it
1217  | 09-Nov-2009      avepati     Bug 9098662 - Able to make payments with end dated bank accounts
1218  | 11-Oct-2010      avepati     Bug 10121591 - 12I CREDIT CARDS AFTER UPGRADE DOES NOT HAVE EXPIRY DATES POPULATED
1219  | 12-Jan-13        melapaku    Bug 16097315 - IRECEIVABLES SHOWS FUTURE DATED BANK ACCOUNTS
1220  *=======================================================================*/
1221 PROCEDURE get_default_payment_instrument(p_customer_id             IN  NUMBER,
1222                                          p_customer_site_use_id    IN  NUMBER DEFAULT NULL,
1223                                          p_currency_code	   IN  VARCHAR2,
1224 					 p_bank_account_num_masked OUT NOCOPY VARCHAR2,
1225                                          p_account_type            OUT NOCOPY VARCHAR2,
1226                                          p_expiry_month            OUT NOCOPY VARCHAR2,
1227                                          p_expiry_year             OUT NOCOPY VARCHAR2,
1228                                          p_credit_card_expired     OUT NOCOPY VARCHAR2,
1229                                          p_bank_account_id         OUT NOCOPY ce_bank_accounts.bank_account_id%TYPE,
1230                                          p_bank_branch_id          OUT NOCOPY ce_bank_accounts.bank_branch_id%TYPE,
1231                                          p_account_holder          OUT NOCOPY VARCHAR2,
1232                                          p_card_brand		   OUT NOCOPY VARCHAR2,
1233                                          p_cvv_code		   OUT NOCOPY VARCHAR2,
1234                                          p_conc_address		   OUT NOCOPY VARCHAR2,
1235                                          p_cc_bill_site_id  	   OUT NOCOPY NUMBER,
1236                                          p_instr_assignment_id	   OUT NOCOPY NUMBER,
1237                                          p_bank_party_id	   OUT NOCOPY NUMBER,
1238                                          p_branch_party_id	   OUT NOCOPY NUMBER,
1239                                          p_object_version_no	   OUT NOCOPY NUMBER
1240                                          ) IS
1241 
1242   cursor last_used_instr_cur  IS
1243               SELECT bank.masked_bank_account_num  bank_account_num_masked,
1244   bank.bank_account_type account_type,
1245   NULL expiry_month,
1246   NULL expiry_year,
1247   '0' credit_card_expired,
1248   u.instrument_id bank_account_id,
1249   bank.branch_id bank_branch_id,
1250   bank.bank_account_name account_holder,
1251   NULL cvv_code,
1252   NULL conc_address,
1253   NULL card_code,
1254   NULL party_site_id,
1255   u.instrument_payment_use_id instr_assignment_id,
1256   bank.bank_id bank_party_id,
1257   bank.branch_id branch_party_id,
1258   bank.object_version_number
1259 FROM hz_cust_accounts cust,
1260   hz_party_preferences pp1,
1261   iby_external_payers_all p,
1262   iby_pmt_instr_uses_all u,
1263   iby_ext_bank_accounts bank,
1264   hz_organization_profiles bapr,
1265   hz_organization_profiles brpr,
1266   iby_account_owners ow
1267 WHERE cust.cust_account_id = p_customer_id
1268  AND pp1.party_id = cust.party_id
1269  AND pp1.category = 'LAST_USED_PAYMENT_INSTRUMENT'
1270  AND pp1.preference_code = 'INSTRUMENT_ID'
1271  AND p.cust_account_id = p_customer_id
1272  AND p.party_id = cust.party_id
1273  AND (	(p.acct_site_use_id = p_customer_site_use_id) 	OR
1274 	(p.acct_site_use_id IS NULL  AND decode(p_customer_site_use_id,   -1,   NULL,   p_customer_site_use_id) IS NULL)  )
1275  AND u.ext_pmt_party_id = p.ext_payer_id
1276  AND u.instrument_type = 'BANKACCOUNT'
1277  AND u.payment_flow = 'FUNDS_CAPTURE'
1278  AND u.instrument_id = pp1.value_number
1279  AND nvl(TRUNC(bank.start_date),sysdate - 1) <= TRUNC(sysdate) -- Added for Bug# 16097315
1280  AND nvl(TRUNC(u.start_date),   sysdate - 1) <= TRUNC(sysdate) -- 16097315 to not fetch the instrument if start date is in future
1281  AND nvl(trunc(u.end_date), sysdate+10) >= TRUNC(sysdate) -- 13601435, to avoid picking end dated bank account assignments
1282  AND pp1.value_number = bank.ext_bank_account_id(+)
1283  AND (  decode(bank.currency_code,   NULL,   'Y',   'N')='Y'  OR bank.currency_code = p_currency_code)
1284  AND bank.bank_id = bapr.party_id(+)
1285  AND bank.branch_id = brpr.party_id(+)
1286  AND TRUNC(sysdate) BETWEEN nvl(TRUNC(bapr.effective_start_date),   sysdate -1)  AND nvl(TRUNC(bapr.effective_end_date),   sysdate + 1)
1287  AND TRUNC(sysdate) BETWEEN nvl(TRUNC(brpr.effective_start_date),   sysdate -1)  AND nvl(TRUNC(brpr.effective_end_date),   sysdate + 1)
1288  AND bank.ext_bank_account_id = ow.ext_bank_account_id(+)
1289  AND ow.primary_flag(+) = 'Y'
1290  AND nvl(TRUNC(bank.end_date),   sysdate + 10) >= TRUNC(sysdate)  --bug 9098662
1291 
1292 
1293 UNION ALL
1294 
1295 
1296  SELECT c.CARD_NUMBER bank_account_num_masked,
1297   c.CARD_ISSUER_NAME account_type,
1298  decode(sysoptions.supplemental_data_option,'Y','XX',to_char(to_date(c.CARD_EXPIRYDATE),'MM')) expiry_month,
1299  decode(sysoptions.supplemental_data_option,'Y','XXXX',to_char(to_date(c.CARD_EXPIRYDATE),'YYYY')) expiry_year,
1300   decode(c.CARD_EXPIRED_FLAG,'Y','1','0') credit_card_expired,
1301   c.INSTRUMENT_ID bank_account_id,
1302   1 bank_branch_id,
1303   nvl(c.CARD_HOLDER_NAME,   hzcc.party_name) account_holder,
1304   NULL cvv_code,
1305   arp_addr_pkg.format_address(loc.address_style,   loc.address1,   loc.address2,   loc.address3,   loc.address4,   loc.city,   loc.county,   loc.state,   loc.province,   loc.postal_code,   terr.territory_short_name) conc_address,
1306   c.CARD_ISSUER_CODE card_code,
1307   psu.party_site_id,
1308   c.INSTR_ASSIGNMENT_ID,
1309   NULL bank_party_id,
1310   NULL branch_party_id,
1311   NULL object_version_number
1312 FROM hz_cust_accounts cust,
1313   hz_party_preferences pp1,
1314   iby_external_payers_all p,
1315   IBY_FNDCPT_PAYER_ASSGN_INSTR_V c,
1316   hz_parties hzcc,
1317   hz_party_site_uses psu,
1318   hz_party_sites hps,
1319   hz_locations loc,
1320   fnd_territories_vl terr,
1321 (select ENCRYPT_SUPPLEMENTAL_CARD_DATA as  supplemental_data_option from iby_sys_security_options) sysoptions
1322 WHERE cust.cust_account_id = p_customer_id
1323  AND cust.party_id = hzcc.party_id
1324  AND pp1.party_id = hzcc.party_id
1325  AND pp1.category = 'LAST_USED_PAYMENT_INSTRUMENT'
1326  AND pp1.preference_code = 'INSTRUMENT_ID'
1327  AND p.cust_account_id = p_customer_id
1328  AND p.party_id = hzcc.party_id
1329  AND (	(p.acct_site_use_id = p_customer_site_use_id)  	OR
1330 	(p.acct_site_use_id IS NULL  AND decode(p_customer_site_use_id,   -1,   NULL,   p_customer_site_use_id) IS NULL)  )
1331  AND c.INSTRUMENT_TYPE  = 'CREDITCARD'
1332  AND nvl(TRUNC(c.assignment_start_date), sysdate - 1)  <= TRUNC(sysdate) -- Added for Bug#16097315
1333  AND nvl(TRUNC(c.assignment_end_date),   sysdate + 10) >= TRUNC(sysdate) -- bug 11832912
1334  AND c.instrument_id = pp1.value_number
1335  AND c.EXT_PAYER_ID = p.ext_payer_id
1336  AND c.CARD_BILLING_ADDRESS_ID = psu.party_site_use_id(+)
1337  AND psu.party_site_id = hps.party_site_id(+)
1338  AND hps.location_id = loc.location_id(+)
1339  AND loc.country = terr.territory_code(+);
1340 
1341 
1342  CURSOR bank_account_cur IS
1343 	SELECT
1344 		  u.instrument_type instrument_type,
1345 		  bank.masked_bank_account_num bank_account_num_masked,
1346 		  bank.bank_account_type account_type,
1347 		  null expiry_month,
1348 		  null expiry_year,
1349 		  '0' credit_card_expired,
1350 		  u.instrument_id bank_account_id,
1351 		  bank.branch_id bank_branch_id,
1352 		  bank.bank_account_name account_holder,
1353 		  null cvv_code,
1354 		  null conc_address,
1355 		  null card_code,
1356 		  null party_site_id,
1357 		  u.instrument_payment_use_id instr_assignment_id,
1358 		  bank.bank_id bank_party_id,
1359 		  bank.branch_id branch_party_id,
1360 		  bank.object_version_number
1361 	FROM
1362 		  hz_cust_accounts cust,
1363 		  iby_external_payers_all p,
1364 		  iby_pmt_instr_uses_all u,
1365 		  iby_ext_bank_accounts bank,
1366 		  hz_organization_profiles bapr,
1367 		  hz_organization_profiles brpr,
1368 		  iby_account_owners ow
1369 
1370 	WHERE
1371 		 cust.cust_account_id = p_customer_id
1372 		 AND p.cust_account_id = cust.cust_account_id
1373 		 AND p.party_id = cust.party_id
1374 		 AND (
1375 			(p.acct_site_use_id = p_customer_site_use_id)
1376 				OR
1377 			(p.acct_site_use_id IS NULL AND DECODE(p_customer_site_use_id, -1, NULL, p_customer_site_use_id) IS NULL)
1378 		    )
1379 		 AND u.ext_pmt_party_id = p.ext_payer_id
1380 		 AND u.instrument_type='BANKACCOUNT'
1381 		 AND u.payment_flow = 'FUNDS_CAPTURE'
1382 		 AND u.instrument_id = bank.ext_bank_account_id(+)
1383                  AND nvl(TRUNC(bank.start_date),sysdate - 1)  <= TRUNC(sysdate) -- Added for Bug#16097315
1384                  AND nvl(TRUNC(u.start_date),   sysdate  - 1) <= TRUNC(sysdate) -- Added for Bug#16097315
1385 		 AND nvl(TRUNC(u.end_date),   sysdate + 10) >= TRUNC(sysdate)   -- bug 13601435 to avoid fetching end dated bank account assignments
1386 		 AND ( decode(bank.currency_code,   NULL,   'Y',   'N')='Y' OR bank.currency_code = p_currency_code)
1387 		 AND bank.bank_id = bapr.party_id(+)
1388 		 AND bank.branch_id = brpr.party_id(+)
1389 		 AND TRUNC(sysdate) BETWEEN nvl(TRUNC(bapr.effective_start_date),   sysdate -1)  AND nvl(TRUNC(bapr.effective_end_date),   sysdate + 1)
1390 		 AND TRUNC(sysdate) BETWEEN nvl(TRUNC(brpr.effective_start_date),   sysdate -1)  AND nvl(TRUNC(brpr.effective_end_date),   sysdate + 1)
1391 		 AND bank.ext_bank_account_id = ow.ext_bank_account_id(+)
1392 		 AND nvl(TRUNC(bank.end_date),   sysdate + 10) >= TRUNC(sysdate) -- bug 13601435 to avoid fetching end dated bank account
1393 		 AND ow.primary_flag(+) = 'Y'
1394 		 AND nvl(TRUNC(ow.end_date),   sysdate + 10) > TRUNC(sysdate);
1395 
1396  CURSOR credit_card_cur IS
1397 	SELECT
1398 		  u.instrument_type instrument_type,
1399 		  c.masked_cc_number bank_account_num_masked,
1400 		  decode(i.card_issuer_code, NULL, ccunk.meaning, i.card_issuer_name) account_type,
1401 		  null expiry_month,
1402 		  null expiry_year,
1403 		  '0' credit_card_expired,
1404 		  u.instrument_id bank_account_id,
1405 		  1 bank_branch_id,
1406 		  NVL(c.chname,hzcc.party_name) account_holder,
1407 		  NULL cvv_code,
1408 		  arp_addr_pkg.format_address(loc.address_style,   loc.address1,   loc.address2,   loc.address3,   loc.address4,   loc.city,   loc.county,   loc.state,   loc.province,   loc.postal_code,   terr.territory_short_name) conc_address,
1409 		  c.card_issuer_code card_code,
1410 		  psu.party_site_id,
1411 		  u.instrument_payment_use_id instr_assignment_id,
1412 		  NULL bank_party_id,
1413 		  NULL branch_party_id,
1414 		  NULL object_version_number
1415 	FROM
1416 		  fnd_lookup_values_vl ccunk,
1417 		  iby_creditcard c,
1418 		  iby_creditcard_issuers_vl i,
1419 		  iby_external_payers_all p,
1420 		  iby_pmt_instr_uses_all u,
1421 		  hz_parties hzcc,
1422 		  hz_cust_accounts cust,
1423 		  hz_party_site_uses psu,
1424 		  hz_party_sites hps,
1425 		  hz_locations loc,
1426 		  fnd_territories_vl terr
1427 	WHERE
1428 		 cust.cust_account_id = p_customer_id
1429 		 AND p.cust_account_id = cust.cust_account_id
1430 		 AND p.party_id = cust.party_id
1431 		 AND (
1432 			(p.acct_site_use_id = p_customer_site_use_id)
1433 				OR
1434 			(p.acct_site_use_id IS NULL AND DECODE(p_customer_site_use_id, -1, NULL, p_customer_site_use_id) IS NULL)
1435 		     )
1436 		 AND u.ext_pmt_party_id = p.ext_payer_id
1437 		 AND u.instrument_type = 'CREDITCARD'
1438 		 AND u.payment_flow = 'FUNDS_CAPTURE'
1439                  AND nvl(TRUNC(u.start_date), sysdate - 1)  <= TRUNC(sysdate)  -- Added for Bug#16097315
1440  		 AND nvl(TRUNC(u.end_date),   sysdate + 10) >= TRUNC(sysdate)   -- bug 11832912
1441 		 AND u.instrument_id = c.instrid(+)
1442 		 AND nvl(c.inactive_date,   sysdate + 10) > sysdate
1443 		 AND c.card_issuer_code = i.card_issuer_code(+)
1444 		 AND c.card_owner_id = hzcc.party_id(+)
1445 		 AND c.addressid = psu.party_site_use_id(+)
1446 		 AND psu.party_site_id = hps.party_site_id(+)
1447 		 AND hps.location_id = loc.location_id(+)
1448 		 AND loc.country = terr.territory_code(+)
1449 		 AND ccunk.lookup_type = 'IBY_CARD_TYPES'
1450 		 AND ccunk.lookup_code = 'UNKNOWN';
1451 
1452 
1453   bank_account_rec     bank_account_cur%ROWTYPE;
1454   credit_card_rec      credit_card_cur%ROWTYPE;
1455   last_used_instr_rec  last_used_instr_cur%ROWTYPE;
1456 
1457 
1458   l_ba_count           NUMBER := 0;
1459   l_cc_count           NUMBER := 0;
1460   l_result             ce_bank_accounts.bank_account_num%TYPE;
1461   l_payment_instrument VARCHAR2(100);
1462 
1463   x_return_status     VARCHAR2(100);
1464   x_cvv_use           VARCHAR2(100);
1465   x_billing_addr_use  VARCHAR2(100);
1466   x_msg_count         NUMBER;
1467   x_msg_data          VARCHAR2(100);
1468 
1469 BEGIN
1470 
1471     get_payment_channel_attribs
1472     (
1473       p_channel_code => 'CREDIT_CARD',
1474       x_return_status  => x_return_status,
1475       x_cvv_use => x_cvv_use,
1476       x_billing_addr_use => x_billing_addr_use,
1477       x_msg_count => x_msg_count,
1478       x_msg_data => x_msg_data
1479      );
1480 
1481 /*
1482 If there are multiple BA and only 1 CC, we return the CC details
1483 If there is 1 BA and multiple CC, we return the BA details
1484 If there is 1 BA, 1CC we return the BA details
1485 
1486 Return NULL values in the following cases:
1487 1)If there are more than one BA and more than one CC
1488 2)If no saved instrument exists
1489 3)If there's only one saved instrument and it doesn't have address
1490 */
1491 
1492    OPEN last_used_instr_cur;
1493    FETCH last_used_instr_cur INTO last_used_instr_rec;
1494 
1495    IF last_used_instr_cur%FOUND THEN
1496 	  --If there's a last used instrument, return the address and other details.
1497 	  --But, if that instrument doesn't have a BilltositeID associated(i.e., no bill to address), we return empty values
1498 
1499      CLOSE last_used_instr_cur;
1500 
1501 -- bank_branch_id will be always 1  for CC , --  bug 7712779
1502 
1503 if(last_used_instr_rec.bank_branch_id = 1) then
1504     if(ar_irec_payments.is_credit_card_payment_enabled(p_customer_id , p_customer_site_use_id , p_currency_code) = 1) then
1505      p_bank_account_num_masked := last_used_instr_rec.bank_account_num_masked;
1506      p_credit_card_expired     := last_used_instr_rec.credit_card_expired;
1507      p_account_type            := last_used_instr_rec.account_type;
1508      p_expiry_month            := last_used_instr_rec.expiry_month;
1509      p_expiry_year             := last_used_instr_rec.expiry_year;
1510      p_bank_account_id         := last_used_instr_rec.bank_account_id;
1511      p_bank_branch_id          := last_used_instr_rec.bank_branch_id;
1512      p_account_holder          := last_used_instr_rec.account_holder;
1513      p_cvv_code		       := last_used_instr_rec.cvv_code;
1514      p_card_brand	       := last_used_instr_rec.card_code;
1515      p_conc_address	       := last_used_instr_rec.conc_address;
1516      p_cc_bill_site_id	       := last_used_instr_rec.party_site_id;
1517      p_instr_assignment_id     := last_used_instr_rec.instr_assignment_id;
1518      p_bank_party_id	       := last_used_instr_rec.bank_party_id;
1519      p_branch_party_id	       := last_used_instr_rec.branch_party_id;
1520      p_object_version_no       := last_used_instr_rec.object_version_number;
1521    end if;
1522 
1523    else
1524    -- bug 7712779
1525 
1526     if(ar_irec_payments.is_bank_acc_payment_enabled(p_customer_id , p_customer_site_use_id , p_currency_code)=1) then
1527      p_bank_account_num_masked := last_used_instr_rec.bank_account_num_masked;
1528      p_credit_card_expired     := last_used_instr_rec.credit_card_expired;
1529      p_account_type            := last_used_instr_rec.account_type;
1530      p_expiry_month            := last_used_instr_rec.expiry_month;
1531      p_expiry_year             := last_used_instr_rec.expiry_year;
1532      p_bank_account_id         := last_used_instr_rec.bank_account_id;
1533      p_bank_branch_id          := last_used_instr_rec.bank_branch_id;
1534      p_account_holder          := last_used_instr_rec.account_holder;
1535      p_cvv_code		       := last_used_instr_rec.cvv_code;
1536      p_card_brand	       := last_used_instr_rec.card_code;
1537      p_conc_address	       := last_used_instr_rec.conc_address;
1538      p_cc_bill_site_id	       := last_used_instr_rec.party_site_id;
1539      p_instr_assignment_id     := last_used_instr_rec.instr_assignment_id;
1540      p_bank_party_id	       := last_used_instr_rec.bank_party_id;
1541      p_branch_party_id	       := last_used_instr_rec.branch_party_id;
1542      p_object_version_no       := last_used_instr_rec.object_version_number;
1543     end if;
1544 
1545   end if;
1546 
1547 
1548      /* Bug 4744886 - When last used payment instrument is created without Address
1549         and if profile value now requires Address, then this procedure will return
1550         no default instrument found, so that it would be taken to Adv Pmt Page
1551 
1552 	p_bank_branch_id is 1 only for Credit Cards
1553       */
1554 
1555 
1556     if(p_bank_branch_id = 1 and p_cc_bill_site_id is NULL
1557 	     and (x_billing_addr_use ='REQUIRED') ) then
1558             p_bank_account_num_masked := '';
1559             p_account_type            := '';
1560             p_expiry_month            := '';
1561             p_expiry_year             := '';
1562             p_bank_account_id         := TO_NUMBER(NULL);
1563             p_bank_branch_id          := TO_NUMBER(NULL);
1564             p_credit_card_expired     := '';
1565             p_account_holder          := '';
1566             p_card_brand	      := '';
1567             p_cvv_code		      := '';
1568             p_conc_address	      := '';
1569             p_cc_bill_site_id	      := TO_NUMBER(NULL);
1570             p_instr_assignment_id     := TO_NUMBER(NULL);
1571             p_bank_party_id	      := TO_NUMBER(NULL);
1572             p_branch_party_id	      := TO_NUMBER(NULL);
1573             p_object_version_no	      := TO_NUMBER(NULL);
1574      END IF;
1575 
1576 
1577    ELSE
1578      --If there's NO last used instrument
1579 
1580      CLOSE last_used_instr_cur;
1581 
1582      FOR bank_account_rec IN bank_account_cur LOOP
1583 
1584               --  bug 7712779
1585 
1586      	       if(ar_irec_payments.is_bank_acc_payment_enabled(p_customer_id , p_customer_site_use_id , p_currency_code) = 0) then
1587                     EXIT;
1588 	       end if;
1589 
1590 		--If there are any BA, in the first iteration read those values.
1591 		--From 2nd iteration, maintain a count of the BA and CC existing
1592 
1593 	       IF (l_ba_count = 0) THEN
1594 		     l_payment_instrument      :='BANKACCOUNT';
1595 		     p_bank_account_num_masked := bank_account_rec.bank_account_num_masked;
1596 		     p_credit_card_expired     := bank_account_rec.credit_card_expired;
1597 		     p_account_type            := bank_account_rec.account_type;
1598 		     p_expiry_month            := bank_account_rec.expiry_month;
1599 		     p_expiry_year             := bank_account_rec.expiry_year;
1600 		     p_bank_account_id         := bank_account_rec.bank_account_id;
1601 		     p_bank_branch_id          := bank_account_rec.bank_branch_id;
1602 		     p_account_holder          := bank_account_rec.account_holder;
1603 		     p_card_brand	       := '';
1604 		     p_cvv_code		       := '';
1605 		     p_conc_address	       := '';
1606 		     p_cc_bill_site_id	       := '';
1607 		     p_instr_assignment_id     := bank_account_rec.instr_assignment_id;
1608 		     p_bank_party_id	       := bank_account_rec.bank_party_id;
1609 		     p_branch_party_id	       := bank_account_rec.branch_party_id;
1610 		     p_object_version_no       := bank_account_rec.object_version_number;
1611 	       END IF;
1612 
1613 	       l_ba_count                := l_ba_count + 1;
1614 
1615 		IF(l_ba_count > 1) THEN
1616 	  	     EXIT;
1617 		END IF;
1618 
1619      END LOOP;
1620 
1621      FOR credit_card_rec IN credit_card_cur LOOP
1622 
1623           --  bug 7712779
1624 
1625      		if(ar_irec_payments.is_credit_card_payment_enabled(p_customer_id , p_customer_site_use_id , p_currency_code)=0) then
1626                       EXIT;
1627 		end if;
1628 
1629 	       IF(l_ba_count <>1 AND l_cc_count = 0) THEN
1630 		     l_payment_instrument      := 'CREDITCARD';
1631 		     p_bank_account_num_masked := bank_account_rec.bank_account_num_masked;
1632 		     p_credit_card_expired     := bank_account_rec.credit_card_expired;
1633 		     p_account_type            := bank_account_rec.account_type;
1634 		     p_expiry_month            := bank_account_rec.expiry_month;
1635 		     p_expiry_year             := bank_account_rec.expiry_year;
1636 		     p_bank_account_id         := bank_account_rec.bank_account_id;
1637 		     p_bank_branch_id          := bank_account_rec.bank_branch_id;
1638 		     p_account_holder          := bank_account_rec.account_holder;
1639 		     p_card_brand	       := bank_account_rec.card_code;
1640 		     p_cvv_code		       := bank_account_rec.cvv_code;
1641 		     p_conc_address	       := bank_account_rec.conc_address;
1642 		     p_cc_bill_site_id	       := bank_account_rec.party_site_id;
1643 		     p_instr_assignment_id     := bank_account_rec.instr_assignment_id;
1644 		     p_bank_party_id	       := '';
1645 		     p_branch_party_id	       := '';
1646 		     p_object_version_no       := '';
1647 		END IF;
1648 
1649 		l_cc_count                := l_cc_count + 1;
1650 
1651 		IF(l_cc_count > 1) THEN
1652 			EXIT;
1653 		END IF;
1654      END LOOP;
1655 
1656 
1657      IF (   (l_payment_instrument = 'BANKACCOUNT'  AND l_ba_count > 1)
1658 	 OR (l_payment_instrument = 'CREDITCARD'   AND l_cc_count > 1)
1659 	 OR (l_payment_instrument IS NULL)
1660 	 OR (p_bank_branch_id = 1 and p_cc_bill_site_id is NULL
1661 	     and x_billing_addr_use ='REQUIRED')
1662 	) THEN
1663        p_bank_account_num_masked := '';
1664        p_account_type            := '';
1665        p_expiry_month            := '';
1666        p_expiry_year             := '';
1667        p_bank_account_id         := TO_NUMBER(NULL);
1668        p_bank_branch_id          := TO_NUMBER(NULL);
1669        p_credit_card_expired     := '';
1670        p_account_holder          := '';
1671        p_card_brand		 := '';
1672        p_cvv_code		 := '';
1673        p_conc_address	         := '';
1674        p_cc_bill_site_id	 := TO_NUMBER(NULL);
1675        p_instr_assignment_id     := TO_NUMBER(NULL);
1676        p_bank_party_id	         := '';
1677        p_branch_party_id	 := '';
1678        p_object_version_no       := '';
1679      END IF;
1680 
1681    END IF;
1682 
1683 END get_default_payment_instrument;
1684 
1685 
1686 
1687 
1688 
1689 
1690 /*========================================================================
1691  | PUBLIC function is_credit_card_expired
1692  |
1693  | DESCRIPTION
1694  |      Determines if a given credit card expiration date has passed.
1695  |      ----------------------------------------
1696  |
1697  | PSEUDO CODE/LOGIC
1698  |      This function compares given month and year in the given parameter
1699  |      to the month and year of the current date.
1700  |
1701  | PARAMETERS
1702  |      p_expiration_date   IN   Credit card expiration date
1703  |
1704  | RETURNS
1705  |      1     if credit card has expired
1706  |      0     if credit card has not expired
1707  |
1708  | KNOWN ISSUES
1709  |
1710  | NOTES
1711  |
1712  | MODIFICATION HISTORY
1713  | Date                  Author            Description of Changes
1714  | 21-Feb-2001           Jani Rautiainen   Created
1715  |
1716  *=======================================================================*/
1717 FUNCTION is_credit_card_expired(  p_expiration_date IN  DATE ) RETURN NUMBER IS
1718 
1719   CURSOR current_date_cur IS
1720     select to_char(to_number(to_char(sysdate,'MM'))) current_month,
1721            to_char(sysdate,'YYYY') current_year
1722     from dual;
1723 
1724   current_date_rec     current_date_cur%ROWTYPE;
1725 
1726 BEGIN
1727 
1728   OPEN current_date_cur;
1729   FETCH current_date_cur INTO current_date_rec;
1730   CLOSE current_date_cur;
1731 
1732   IF to_number(to_char(p_expiration_date,'YYYY')) < to_number(current_date_rec.current_year)
1733      OR (to_number(to_char(p_expiration_date,'YYYY')) = to_number(current_date_rec.current_year)
1734          AND  to_number(to_char(p_expiration_date,'MM')) < to_number(current_date_rec.current_month)) THEN
1735      return 1; --TRUE;
1736   else
1737      return 0; --FALSE
1738   end if;
1739 
1740 END is_credit_card_expired;
1741 
1742 /*========================================================================
1743  | PUBLIC procedure store_last_used_ba
1744  |
1745  | DESCRIPTION
1746  |      Stores the last used bank account
1747  |
1748  | PSEUDO CODE/LOGIC
1749  |
1750  | PARAMETERS
1751  |      p_customer_id      IN  NUMBER
1752  |      p_bank_account_id  IN  NUMBER
1753  |	p_instr_type	   IN  VARCHAR2 DEFAULT 'BA'
1754  |
1755  | RETURNS
1756  |      p_status	   OUT NOCOPY varchar2
1757  |
1758  | KNOWN ISSUES
1759  |
1760  | NOTES
1761  |
1762  | MODIFICATION HISTORY
1763  | Date                  Author            Description of Changes
1764  | 09-May-2001           J Rautiainen      Created
1765  | 26-Oct-2005	 	 rsinthre          Bug 4673563 - Error in updating last used instrument
1766  *=======================================================================*/
1767 PROCEDURE store_last_used_ba(p_customer_id     IN  NUMBER,
1768                              p_bank_account_id IN  NUMBER,
1769                              p_instr_type      IN  VARCHAR2 DEFAULT 'BA',
1770                              p_status          OUT NOCOPY VARCHAR2) IS
1771   l_msg_count             NUMBER;
1772   l_object_version_number NUMBER;
1773   l_msg_data              VARCHAR(2000);
1774 
1775   CURSOR customer_party_cur IS
1776     SELECT party_id
1777     FROM   hz_cust_accounts
1778     WHERE  cust_account_id = p_customer_id;
1779 
1780         CURSOR object_version_cur(p_party_id IN NUMBER, p_preference_code IN VARCHAR2) IS
1781            SELECT party_preference_id, object_version_number
1782         FROM   hz_party_preferences
1783         WHERE  party_id = p_party_id
1784         AND    category = 'LAST_USED_PAYMENT_INSTRUMENT'
1785         AND    preference_code = p_preference_code;
1786 
1787        customer_party_rec customer_party_cur%ROWTYPE;
1788       object_version_rec object_version_cur%ROWTYPE;
1789 
1790  BEGIN
1791 
1792    OPEN customer_party_cur;
1793    FETCH customer_party_cur INTO customer_party_rec;
1794    CLOSE customer_party_cur;
1795 
1796       OPEN object_version_cur(customer_party_rec.party_id,'INSTRUMENT_TYPE') ;
1797    FETCH object_version_cur INTO object_version_rec;
1798    CLOSE object_version_cur;
1799 
1800   SAVEPOINT STORE_INST;
1801 
1802     HZ_PREFERENCE_PUB.Put(
1803        p_party_id                 => customer_party_rec.party_id
1804   , p_category                  => 'LAST_USED_PAYMENT_INSTRUMENT'
1805   , p_preference_code          => 'INSTRUMENT_TYPE'
1806   , p_value_varchar2           => p_instr_type
1807   , p_module                   => 'IRECEIVABLES'
1808   , p_additional_value1        => NULL
1809   , p_additional_value2        => NULL
1810   , p_additional_value3        => NULL
1811   , p_additional_value4        => NULL
1812   , p_additional_value5        => NULL
1813   , p_object_version_number    => object_version_rec.object_version_number
1814   , x_return_status            => p_status
1815   , x_msg_count                => l_msg_count
1816   , x_msg_data                 => l_msg_data);
1817 
1818    IF ( p_status <> FND_API.G_RET_STS_SUCCESS ) THEN
1819                  write_error_messages(l_msg_data, l_msg_count);
1820                   ROLLBACK TO STORE_INST;
1821                  RETURN;
1822           END IF;
1823 
1824     OPEN object_version_cur(customer_party_rec.party_id,'INSTRUMENT_ID') ;
1825      FETCH object_version_cur INTO object_version_rec;
1826      CLOSE object_version_cur;
1827 
1828     HZ_PREFERENCE_PUB.Put(
1829         p_party_id                 => customer_party_rec.party_id
1830     , p_category                  => 'LAST_USED_PAYMENT_INSTRUMENT'
1831     , p_preference_code          => 'INSTRUMENT_ID'
1832     , p_value_number             => p_bank_account_id
1833     , p_module                   => 'IRECEIVABLES'
1834     , p_additional_value1        => NULL
1835     , p_additional_value2        => NULL
1836     , p_additional_value3        => NULL
1837     , p_additional_value4        => NULL
1838     , p_additional_value5        => NULL
1839     , p_object_version_number    => object_version_rec.object_version_number
1840     , x_return_status            => p_status
1841     , x_msg_count                => l_msg_count
1842     , x_msg_data                 => l_msg_data);
1843 
1844      IF ( p_status <> FND_API.G_RET_STS_SUCCESS ) THEN
1845                    write_error_messages(l_msg_data, l_msg_count);
1846                    ROLLBACK TO STORE_INST;
1847                    RETURN;
1848             END IF;
1849      --If payment process goes through, the transaction will be committed irrespective of
1850      --the result of this procedure. If the record is stored successfully in hz party preference, commit
1851      COMMIT;
1852 
1853 
1854      END store_last_used_ba;
1855 
1856 /*========================================================================
1857  | PUBLIC function is_bank_account_duplicate
1858  |
1859  | DESCRIPTION
1860  |      Checks whether given bank account number already exists
1861  |
1862  | PSEUDO CODE/LOGIC
1863  |
1864  | PARAMETERS
1865  |      p_bank_account_number IN  VARCHAR2
1866  |      p_routing_number      IN  VARCHAR2
1867  |      p_account_holder_name IN  VARCHAR2
1868  |
1869  | RETURNS
1870  |      Return Value: 0 if given bank account number does not exist.
1871  |                    1 if given bank account number already exists.
1872  |
1873  | KNOWN ISSUES
1874  |
1875  | NOTES
1876  |
1877  | MODIFICATION HISTORY
1878  | Date                  Author            Description of Changes
1879  | 01-Aug-2001           J Rautiainen      Created
1880  |
1881  | 15-Apr-2002           AMMISHRA          Bug:2210677 , Passed an extra
1882  |                                         parameter p_account_holder_name
1883  *=======================================================================*/
1884 FUNCTION is_bank_account_duplicate(p_bank_account_number IN  VARCHAR2,
1885                         p_routing_number      IN  VARCHAR2 DEFAULT NULL,
1886                         p_account_holder_name IN VARCHAR2) RETURN NUMBER IS
1887 
1888   CURSOR cc_cur(p_instrument_id iby_creditcard.instrid%TYPE)  is
1889          SELECT  count(1) ca_exists
1890 	 FROM    IBY_FNDCPT_PAYER_ASSGN_INSTR_V IBY
1891 	 WHERE   IBY.instrument_id = p_instrument_id
1892 	 AND     IBY.CARD_HOLDER_NAME <> p_account_holder_name;
1893 
1894   CURSOR ba_cur IS
1895     SELECT count(1) ba_exists
1896     FROM   iby_ext_bank_accounts_v ba
1897     WHERE  ba.branch_number       = p_routing_number
1898     AND    ba.bank_account_number = p_bank_account_number
1899     AND    ROWNUM = 1
1900     AND    ba.bank_account_name <> p_account_holder_name;
1901 
1902    ba_rec ba_cur%ROWTYPE;
1903    cc_rec cc_cur%ROWTYPE;
1904 
1905    l_create_credit_card		IBY_FNDCPT_SETUP_PUB.CreditCard_rec_type;
1906    l_result_rec			IBY_FNDCPT_COMMON_PUB.Result_rec_type;
1907    l_procedure_name		VARCHAR2(30);
1908    l_return_status		VARCHAR2(2);
1909    l_msg_count			NUMBER;
1910    l_msg_data			VARCHAR2(2000);
1911 BEGIN
1912   l_procedure_name := '.is_bank_account_duplicate';
1913 
1914     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
1915 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,' Begin +');
1916     end if;
1917 
1918   IF p_routing_number IS NULL THEN
1919 
1920     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
1921 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,' Calling..  IBY_FNDCPT_SETUP_PUB.Card_Exists ');
1922     end if;
1923 
1924 	   IBY_FNDCPT_SETUP_PUB.Card_Exists(
1925 		 p_api_version      => 1.0,
1926 		 p_init_msg_list    => FND_API.G_FALSE,
1927 		 x_return_status    => l_return_status,
1928 		 x_msg_count        => l_msg_count,
1929 		 x_msg_data         => l_msg_data,
1930 		 p_owner_id         => null,
1931 		 p_card_number      => p_bank_account_number,
1932 		 x_card_instrument  => l_create_credit_card,
1933 		 x_response         => l_result_rec);
1934 
1935     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
1936 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_return_status :: ' || l_return_status);
1937 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Return 0 - credit card exists validation is not required from OIR');
1938     end if;
1939     --Bug 14534172 - As per bug, do not validate the credit card exists from OIR.
1940     return 0;
1941     /*
1942 	  IF ( l_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
1943 	      -- no card exists
1944 		   return 0;
1945 	  ELSE
1946 	       OPEN  cc_cur(l_create_credit_card.card_id);
1947 	       FETCH cc_cur into cc_rec;
1948 	       CLOSE cc_cur;
1949 
1950     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
1951 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_create_credit_card.card_id :: ' || l_create_credit_card.card_id);
1952 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'cc_rec.ca_exists :: ' || cc_rec.ca_exists);
1953     end if;
1954 
1955 	       if cc_rec.ca_exists = 0 then
1956 		       return 0;
1957 	       else
1958 		       return 1;
1959 	       end if;
1960 
1961 	  END IF;
1962 	  */
1963 
1964   ELSE
1965 
1966     open ba_cur;
1967     fetch ba_cur into ba_rec;
1968     close ba_cur;
1969 
1970     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
1971 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'ba_rec.ba_exists :: ' || ba_rec.ba_exists);
1972     end if;
1973 
1974     if ba_rec.ba_exists = 0 then
1975        return 0;
1976     else
1977        return 1;
1978     end if;
1979 
1980   END IF;
1981 
1982 EXCEPTION
1983 
1984 WHEN OTHERS THEN
1985       write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
1986       write_debug_and_log('- Account Number: '||p_bank_account_number);
1987       write_debug_and_log('- Holder Name: '||p_account_holder_name);
1988       write_debug_and_log('ERROR =>'|| SQLERRM);
1989 
1990       FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
1991       FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
1992       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
1993 
1994       FND_MSG_PUB.ADD;
1995 
1996 END is_bank_account_duplicate;
1997 
1998 /*========================================================================
1999  | PUBLIC function is_bank_account_duplicate
2000  |
2001  | DESCRIPTION
2002  |      Checks whether given bank account number already exists
2003  |
2004  | PSEUDO CODE/LOGIC
2005  |
2006  | PARAMETERS
2007  |      p_bank_account_number IN  VARCHAR2
2008  |
2009  | RETURNS
2010  |      Return Value: 0 if given bank account number does not exist.
2011  |                    1 if given bank account number already exists.
2012  |
2013  | KNOWN ISSUES
2014  |
2015  | NOTES
2016  |
2017  | MODIFICATION HISTORY
2018  | Date                  Author            Description of Changes
2019  | 01-Aug-2001           J Rautiainen      Created
2020  |
2021  *=======================================================================*/
2022 FUNCTION is_credit_card_duplicate(p_bank_account_number IN  VARCHAR2,
2023 				  p_account_holder_name IN  VARCHAR2) RETURN NUMBER IS
2024 BEGIN
2025   return  is_bank_account_duplicate(p_bank_account_number => p_bank_account_number,
2026                                     p_routing_number      => NULL,
2027 			            p_account_holder_name => p_account_holder_name);
2028 END is_credit_card_duplicate;
2029 
2030 /*========================================================================
2031  | PUBLIC function get_iby_account_type
2032  |
2033  | DESCRIPTION
2034  |      Maps AP bank account type to a iPayment bank account type. If
2035  |      AP bank account type is not recognized, CHECKING is used.
2036  |
2037  | PSEUDO CODE/LOGIC
2038  |
2039  | PARAMETERS
2040  |      p_account_type      Account type from the ap table
2041  |
2042  | RETURNS
2043  |      iPayment bank account type
2044  |
2045  | KNOWN ISSUES
2046  |
2047  | NOTES
2048  |
2049  | MODIFICATION HISTORY
2050  | Date                  Author            Description of Changes
2051  | 28-Feb-2002           J Rautiainen      Created
2052  |
2053  *=======================================================================*/
2054 FUNCTION get_iby_account_type(p_account_type        IN VARCHAR2) RETURN VARCHAR2 IS
2055 
2056   CURSOR account_type_cur IS
2057     select LOOKUP_CODE
2058     from FND_LOOKUPS
2059     where LOOKUP_TYPE = 'IBY_BANKACCT_TYPES'
2060     and   LOOKUP_CODE = UPPER(p_account_type);
2061 
2062   account_type_rec account_type_cur%ROWTYPE;
2063 BEGIN
2064 
2065   OPEN  account_type_cur;
2066   FETCH account_type_cur INTO account_type_rec;
2067 
2068   IF account_type_cur%FOUND THEN
2069     CLOSE account_type_cur;
2070     RETURN account_type_rec.LOOKUP_CODE;
2071   ELSE
2072     CLOSE account_type_cur;
2073     RETURN 'CHECKING';
2074   END IF;
2075 
2076 END get_iby_account_type;
2077 
2078 /*===========================================================================+
2079  | PROCEDURE write_debug_and_log                                             |
2080  |    	                                                                     |
2081  | DESCRIPTION                                                               |
2082  |    Writes standard messages to standard debugging and to the log          |
2083  |                                                                           |
2084  | SCOPE - PUBLIC                                                            |
2085  |                                                                           |
2086  | EXETERNAL PROCEDURES/FUNCTIONS ACCESSED                                   |
2087  |    arp_util.debug                                                         |
2088  |                                                                           |
2089  | ARGUMENTS  : IN:  p_message - Message to be writted                       |
2090  |                                                                           |
2091  | RETURNS    : NONE                                                         |
2092  |                                                                           |
2093  | MODIFICATION HISTORY                                                      |
2094  |     28-Feb-2002  Jani Rautiainen      Created                             |
2095  |                                                                           |
2096  +===========================================================================*/
2097 PROCEDURE write_debug_and_log(p_message IN VARCHAR2) IS
2098 
2099 BEGIN
2100 
2101  /*------------------------------------------------+
2102   | Write the message to log and to the standard   |
2103   | debugging channel                              |
2104   +------------------------------------------------*/
2105   IF FND_GLOBAL.CONC_REQUEST_ID is not null THEN
2106 
2107    /*------------------------------------------------+
2108     | Only write to the log if call was made from    |
2109     | concurrent program.                            |
2110     +------------------------------------------------*/
2111     fnd_file.put_line(FND_FILE.LOG,p_message);
2112 
2113   END IF;
2114 
2115   IF (PG_DEBUG = 'Y') THEN
2116      arp_standard.debug('OIR'|| p_message);
2117   END IF;
2118 EXCEPTION
2119   WHEN others THEN
2120    /*-------------------------------------------------------+
2121     | Error writing to the log, nothing we can do about it. |
2122     | Error is not raised since API messages also contain   |
2123     | non fatal warnings. If a real exception happened it   |
2124     | is handled on the calling routine.                    |
2125     +-------------------------------------------------------*/
2126     NULL;
2127 
2128 END write_debug_and_log;
2129 
2130 /*===========================================================================+
2131  | PROCEDURE write_API_output                                                |
2132  |    	                                                                     |
2133  | DESCRIPTION                                                               |
2134  |    Writes API output to the concurrent program log. Messages from the     |
2135  |    API can contain warnings and errors                                    |
2136  |                                                                           |
2137  | SCOPE - PUBLIC                                                            |
2138  |                                                                           |
2139  | EXETERNAL PROCEDURES/FUNCTIONS ACCESSED                                   |
2140  |    arp_util.debug                                                         |
2141  |                                                                           |
2142  | ARGUMENTS  : IN:  p_msg_count  - Number of messages from the API          |
2143  |                   p_msg_data   - Actual messages from the API             |
2144  |                                                                           |
2145  | RETURNS    : NONE                                                         |
2146  |                                                                           |
2147  | MODIFICATION HISTORY                                                      |
2148  |     28-Feb-2002  Jani Rautiainen      Created                             |
2149  |                                                                           |
2150  +===========================================================================*/
2151 PROCEDURE write_API_output(p_msg_count        IN NUMBER,
2152                            p_msg_data         IN VARCHAR2) IS
2153 
2154   l_msg_data       VARCHAR2(2000);
2155 BEGIN
2156 
2157     --Bug 3810143 - Ensure that the messages are picked up from the message
2158     --stack in any case.
2159     FOR l_count IN 1..p_msg_count LOOP
2160 
2161          l_msg_data := FND_MSG_PUB.Get(FND_MSG_PUB.G_NEXT,FND_API.G_FALSE);
2162          write_debug_and_log(to_char(l_count)||' : '||l_msg_data);
2163 
2164     END LOOP;
2165 
2166 EXCEPTION
2167   WHEN others THEN
2168    /*-------------------------------------------------------+
2169     | Error writing to the log, nothing we can do about it. |
2170     | Error is not raised since API messages also contain   |
2171     | non fatal warnings. If a real exception happened it   |
2172     | is handled on the calling routine.                    |
2173     +-------------------------------------------------------*/
2174     NULL;
2175 
2176 END write_API_output;
2177 
2178 /*========================================================================
2179  | PUBLIC store_last_used_cc
2180  |
2181  | DESCRIPTION
2182  |      Backward compatibility methods introduced for mobile account
2183  |      management.
2184  |      ----------------------------------------
2185  |
2186  | MODIFICATION HISTORY
2187  | Date                  Author            Description of Changes
2188  | 10-Mar-2002           J Rautiainen      Created
2189  | 26-Apr-2004           vnb               Added Customer Site as input parameter.
2190  |
2191  *=======================================================================*/
2192 
2193 PROCEDURE store_last_used_cc(p_customer_id     IN  NUMBER,
2194                              p_bank_account_id IN  NUMBER,
2195                              p_status          OUT NOCOPY VARCHAR2) IS
2196 
2197 BEGIN
2198 store_last_used_ba(p_customer_id     => p_customer_id,
2199                    p_bank_account_id => p_bank_account_id,
2200                    p_instr_type      => 'CC',
2201                    p_status          => p_status);
2202 
2203 
2204 END store_last_used_cc;
2205 
2206 
2207 /*============================================================
2208  | PUBLIC procedure create_invoice_pay_list
2209  |
2210  | DESCRIPTION
2211  |   Creates a list of transactions to be paid by the customer
2212  |   based on the list type. List type has the following values:
2213  |   OPEN_INVOICES
2214  | PSEUDO CODE/LOGIC
2215  |
2216  | PARAMETERS
2217  |   p_customer_id           IN    NUMBER
2218  |   p_currency_code         IN    VARCHAR2
2219  |   p_customer_site_use_id  IN    NUMBER DEFAULT NULL
2220  |   p_payment_schedule_id   IN    NUMBER DEFAULT NULL
2221  |   p_trx_type              IN    VARCHAR2 DEFAULT NULL
2222  |
2223  | KNOWN ISSUES
2224  |
2225  |
2226  |
2227  | NOTES
2228  |
2229  |
2230  |
2231  | MODIFICATION HISTORY
2232  | Date          Author       Description of Changes
2233  | 13-Jan-2003   krmenon      Created
2234  | 31-Dec-2004   vnb          Bug 4071551 - Removed redundant code
2235  | 20-Jan-2005   vnb          Bug 4117211 - Original discount amount column added for ease of resetting payment amounts
2236  | 08-Jul-2005	 rsinthre     Bug 4437225 - Disputed amount against invoice not displayed during payment
2237  | 05-Mar-2010   avepati    Bug#9173720 -Able to see same invoice twice in payment details page.
2238  | 22-Mar-2010   nkanchan     Bug 8293098 - Service change based on credit card types
2239  | 09-Jun-2010   nkanchan Bug # 9696274- PAGE ERRORS OUT ON NAVIGATING 'PAY BELOW' RELATED CUSTOMER DATA
2240  +============================================================*/
2241 PROCEDURE create_invoice_pay_list ( p_customer_id           IN NUMBER,
2242                                     p_customer_site_use_id  IN NUMBER DEFAULT NULL,
2243                                     p_payment_schedule_id   IN NUMBER DEFAULT NULL,
2244                                     p_currency_code         IN VARCHAR2,
2245                                     p_payment_type           IN varchar2 DEFAULT NULL,
2246                                     p_lookup_code           IN varchar2 DEFAULT NULL) IS
2247 
2248   -- Cursor to fetch all the open invoices
2249   CURSOR open_invoice_list (p_customer_id NUMBER,
2250                             p_customer_site_use_id NUMBER,
2251                             p_payment_schedule_id NUMBER,
2252                             p_currency_code VARCHAR2) IS
2253   SELECT ps.CUSTOMER_ID,
2254            ps.CUSTOMER_SITE_USE_ID,   -- Bug # 3828358
2255            acct.ACCOUNT_NUMBER,
2256            ps.CUSTOMER_TRX_ID,
2257            ps.TRX_NUMBER,
2258            ps.TRX_DATE,
2259   	 ps.class,
2260            ps.DUE_DATE,
2261   	 ps.PAYMENT_SCHEDULE_ID,
2262            ps.STATUS,
2263            trm.name term_desc,
2264   	 ARPT_SQL_FUNC_UTIL.Get_Number_Of_Due_Dates(ps.term_id) number_of_installments,
2265   	 ps.terms_sequence_number,
2266   	 ps.amount_line_items_original line_amount,
2267   	 ps.tax_original tax_amount,
2268   	 ps.freight_original freight_amount,
2269   	 ps.receivables_charges_charged finance_charge,
2270   	 ps.INVOICE_CURRENCY_CODE,
2271   	 ps.AMOUNT_DUE_ORIGINAL,
2272   	 ps.AMOUNT_DUE_REMAINING,
2273   	 0 payment_amt,
2274   	 0 service_charge,
2275   	 0 discount_amount,
2276   	 case WHEN ((trunc(ps.trx_date) - trunc(sysdate)) <= 0) then TRUNC(SYSDATE) else ps.trx_date end as receipt_date,
2277   	 '' receipt_number,
2278            ct.PURCHASE_ORDER AS PO_NUMBER,
2279            NULL AS SO_NUMBER,
2280            ct.printing_option,
2281 
2282            ct.ATTRIBUTE_CATEGORY,
2283            ct.ATTRIBUTE1,
2284            ct.ATTRIBUTE2,
2285            ct.ATTRIBUTE3,
2286            ct.ATTRIBUTE4,
2287            ct.ATTRIBUTE5,
2288            ct.ATTRIBUTE6,
2289            ct.ATTRIBUTE7,
2290            ct.ATTRIBUTE8,
2291            ct.ATTRIBUTE9,
2292            ct.ATTRIBUTE10,
2293            ct.ATTRIBUTE11,
2294            ct.ATTRIBUTE12,
2295            ct.ATTRIBUTE13,
2296            ct.ATTRIBUTE14,
2297            ct.ATTRIBUTE15,
2298            ct.INTERFACE_HEADER_CONTEXT,
2299 	   ct.INTERFACE_HEADER_ATTRIBUTE1,
2300 	   ct.INTERFACE_HEADER_ATTRIBUTE2,
2301 	   ct.INTERFACE_HEADER_ATTRIBUTE3,
2302 	   ct.INTERFACE_HEADER_ATTRIBUTE4,
2303 	   ct.INTERFACE_HEADER_ATTRIBUTE5,
2304 	   ct.INTERFACE_HEADER_ATTRIBUTE6,
2305 	   ct.INTERFACE_HEADER_ATTRIBUTE7,
2306 	   ct.INTERFACE_HEADER_ATTRIBUTE8,
2307 	   ct.INTERFACE_HEADER_ATTRIBUTE9,
2308 	   ct.INTERFACE_HEADER_ATTRIBUTE10,
2309 	   ct.INTERFACE_HEADER_ATTRIBUTE11,
2310 	   ct.INTERFACE_HEADER_ATTRIBUTE12,
2311 	   ct.INTERFACE_HEADER_ATTRIBUTE13,
2312 	   ct.INTERFACE_HEADER_ATTRIBUTE14,
2313 	   ct.INTERFACE_HEADER_ATTRIBUTE15,
2314   	 sysdate LAST_UPDATE_DATE,
2315   	 0 LAST_UPDATED_BY,
2316   	 sysdate CREATION_DATE,
2317   	 0 CREATED_BY,
2318   	 0 LAST_UPDATE_LOGIN,
2319   	 0 APPLICATION_AMOUNT,
2320   	 0 CASH_RECEIPT_ID,
2321   	 0  ORIGINAL_DISCOUNT_AMT,
2322            ps.org_id,
2323   	 ct.PAYING_CUSTOMER_ID,
2324   	 ct.PAYING_SITE_USE_ID,
2325 ( decode( nvl(ps.AMOUNT_DUE_ORIGINAL,0),0,1,(ps.AMOUNT_DUE_ORIGINAL/abs(ps.AMOUNT_DUE_ORIGINAL)) ) *abs(nvl(ps.amount_in_dispute,0)) ) dispute_amt
2326   FROM AR_PAYMENT_SCHEDULES ps,
2327        RA_CUSTOMER_TRX ct,
2328        HZ_CUST_ACCOUNTS acct,
2329        RA_TERMS trm
2330   WHERE ps.CLASS IN ('INV', 'DM', 'CB', 'DEP')
2331   AND ps.customer_trx_id = ct.customer_trx_id
2332   AND acct.cust_account_id = ps.customer_id
2333   AND ps.status = 'OP'
2334   AND ps.term_id = trm.term_id(+)
2335   AND ( ps.payment_schedule_id = p_payment_schedule_id
2336   	OR   p_payment_schedule_id IS NULL)
2337 
2338 	 AND ps.customer_id = p_customer_id
2339 	 AND ps.customer_site_use_id = nvl(decode(p_customer_site_use_id, -1, null, p_customer_site_use_id), ps.customer_site_use_id)
2340 	 AND ps.invoice_currency_code = p_currency_code;
2341 
2342   l_query_period NUMBER(15);
2343   l_query_date   DATE;
2344   l_total_service_charge NUMBER;
2345   l_discount_amount NUMBER;
2346   l_rem_amt_rcpt    NUMBER;
2347   l_rem_amt_inv     NUMBER;
2348   l_grace_days_flag VARCHAR2(2);
2349 
2350   l_paying_cust_id  NUMBER(15);
2351   l_pay_for_cust_id NUMBER(15);
2352   l_pay_for_cust_site_id NUMBER(15);
2353   l_paying_cust_site_id  NUMBER(15);
2354   l_dispute_amount	NUMBER := 0;
2355   l_trx_rec_exists number :=0;
2356 
2357   l_procedure_name  VARCHAR2(50);
2358   l_debug_info      VARCHAR2(200);
2359 
2360   TYPE t_open_invoice_list_rec
2361         IS TABLE OF open_invoice_list%ROWTYPE index by binary_integer ;
2362 
2363   l_open_invoice_list_rec  t_open_invoice_list_rec;
2364 
2365 
2366 BEGIN
2367   --Assign default values
2368   l_query_period         := -12;
2369   l_total_service_charge := 0;
2370   l_discount_amount      := 0;
2371   l_rem_amt_rcpt         := 0;
2372   l_rem_amt_inv          := 0;
2373   l_procedure_name       := '.create_invoice_pay_list';
2374 
2375   SAVEPOINT create_invoice_pay_list_sp;
2376 
2377   ----------------------------------------------------------------------------------------
2378   l_debug_info := 'Clear the transaction list for the active customer, site, currency';
2379   -----------------------------------------------------------------------------------------
2380   IF (PG_DEBUG = 'Y') THEN
2381      arp_standard.debug(l_debug_info);
2382   END IF;
2383 
2384   --Bug # 3467287 - The Global Temp table must be striped by Customer and Customer Site.
2385   --DELETE FROM AR_IREC_PAYMENT_LIST_GT
2386   --WHERE CUSTOMER_ID        = p_customer_id
2387   --AND CUSTOMER_SITE_USE_ID = nvl(p_customer_site_use_id, CUSTOMER_SITE_USE_ID)
2388   --AND CURRENCY_CODE        = p_currency_code;
2389 -- commented the delete sql as part of  bug 9173720
2390 
2391 --Added for bug # 9696274
2392   if(p_payment_schedule_id is not null) then
2393     DELETE FROM AR_IREC_PAYMENT_LIST_GT
2394     WHERE  PAYMENT_SCHEDULE_ID = p_payment_schedule_id
2395     AND CURRENCY_CODE        = p_currency_code;
2396   end if;
2397 
2398   ----------------------------------------------------------------------------------------
2399   l_debug_info := 'Fetch all the rows into the global temporary table';
2400   -----------------------------------------------------------------------------------------
2401   IF (PG_DEBUG = 'Y') THEN
2402      arp_standard.debug(l_debug_info);
2403   END IF;
2404 
2405   Open  open_invoice_list(p_customer_id,
2406                                p_customer_site_use_id,
2407                                p_payment_schedule_id,
2408                                p_currency_code );
2409   FETCH  open_invoice_list BULK COLLECT INTO l_open_invoice_list_rec;
2410     close open_invoice_list;
2411 
2412     --l_grace_days_flag := is_grace_days_enabled_wrapper();
2413     l_grace_days_flag := ARI_UTILITIES.is_discount_grace_days_enabled(p_customer_id,p_customer_site_use_id);
2414 
2415   FOR trx IN l_open_invoice_list_rec.first .. l_open_invoice_list_rec.last loop
2416 
2417      IF (PG_DEBUG = 'Y') THEN
2418         arp_standard.debug('Inserting: '||l_open_invoice_list_rec(trx).trx_number);
2419      END IF;
2420 
2421      ----------------------------------------------------------------------------------------
2422      l_debug_info := 'Calculate discount';
2423      -----------------------------------------------------------------------------------------
2424      IF (PG_DEBUG = 'Y') THEN
2425         arp_standard.debug(l_debug_info);
2426      END IF;
2427 
2428 
2429      arp_discounts_api.get_discount(p_ps_id	        => l_open_invoice_list_rec(trx).payment_schedule_id,
2430 		                    p_apply_date	=> trunc(sysdate),
2431                             	    p_in_applied_amount => l_open_invoice_list_rec(trx).amount_due_remaining - l_open_invoice_list_rec(trx).dispute_amt,
2432 		                    p_grace_days_flag   => l_grace_days_flag,
2433 		                    p_out_discount      => l_open_invoice_list_rec(trx).ORIGINAL_DISCOUNT_AMT,
2434 		                    p_out_rem_amt_rcpt 	=> l_rem_amt_rcpt,
2435 		                    p_out_rem_amt_inv 	=> l_rem_amt_inv,
2436 				    p_called_from	=> 'OIR');
2437 
2438      l_open_invoice_list_rec(trx).discount_amount := l_open_invoice_list_rec(trx).ORIGINAL_DISCOUNT_AMT;
2439 
2440     l_open_invoice_list_rec(trx).PAYING_CUSTOMER_ID := l_open_invoice_list_rec(trx).CUSTOMER_ID;
2441     l_open_invoice_list_rec(trx).PAYING_SITE_USE_ID := l_open_invoice_list_rec(trx).CUSTOMER_SITE_USE_ID;
2442 
2443     --Bug 4479224
2444 	l_open_invoice_list_rec(trx).CUSTOMER_ID := p_customer_id;
2445 	if(p_customer_site_use_id = null) then
2446 		l_open_invoice_list_rec(trx).CUSTOMER_SITE_USE_ID := -1;
2447 	else
2448 		l_open_invoice_list_rec(trx).CUSTOMER_SITE_USE_ID := p_customer_site_use_id;
2449 	end if;
2450 
2451 
2452 
2453     BEGIN
2454 	        l_open_invoice_list_rec(trx).payment_amt  := ARI_UTILITIES.curr_round_amt(l_open_invoice_list_rec(trx).AMOUNT_DUE_REMAINING
2455 		                                           - l_open_invoice_list_rec(trx).discount_amount - l_open_invoice_list_rec(trx).dispute_amt,
2456 							     l_open_invoice_list_rec(trx).INVOICE_CURRENCY_CODE);
2457 
2458     EXCEPTION
2459         WHEN OTHERS THEN
2460             null;
2461     END;
2462 
2463 --Commented for bug # 9696274
2464 -- Added for bug 	9173720
2465 --		BEGIN
2466 --    select 1 into l_trx_rec_exists FROM ar_irec_payment_list_gt where payment_schedule_id = l_open_invoice_list_rec(trx).payment_schedule_id;
2467 --   EXCEPTION
2468 --   WHEN NO_DATA_FOUND THEN
2469 --        l_trx_rec_Exists :=0;
2470 --    END;
2471 
2472 --    IF (l_trx_rec_exists = 1) Then
2473 --	l_open_invoice_list_rec.delete(trx);
2474 --    END IF ;
2475    end loop;
2476 
2477     FORALL trx
2478     IN l_open_invoice_list_rec.first .. l_open_invoice_list_rec.last
2479     INSERT INTO AR_IREC_PAYMENT_LIST_GT
2480       VALUES l_open_invoice_list_rec(trx);
2481 
2482    ----------------------------------------------------------------------------------------
2483    l_debug_info := 'Compute service charge';
2484    -----------------------------------------------------------------------------------------
2485    IF (PG_DEBUG = 'Y') THEN
2486       arp_standard.debug(l_debug_info);
2487    END IF;
2488    l_total_service_charge := get_service_charge(p_customer_id, p_customer_site_use_id, p_payment_type, p_lookup_code);
2489 
2490    COMMIT;
2491 
2492 EXCEPTION
2493      WHEN OTHERS THEN
2494          IF (PG_DEBUG = 'Y') THEN
2495              arp_standard.debug('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
2496 	     arp_standard.debug('- Customer Id: '||p_customer_id);
2497 	     arp_standard.debug('- Customer Site Use Id: '|| p_customer_site_use_id);
2498 	     arp_standard.debug('- Currency Code: '||p_currency_code);
2499              arp_standard.debug('- Payment Schedule Id: '||p_payment_schedule_id);
2500              arp_standard.debug('ERROR =>'|| SQLERRM);
2501          END IF;
2502 
2503 	 ROLLBACK TO create_invoice_pay_list_sp;
2504 
2505          FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
2506          FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
2507          FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
2508          FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
2509          FND_MSG_PUB.ADD;
2510 END create_invoice_pay_list;
2511 
2512 /*============================================================
2513   | PUBLIC procedure create_open_credit_pay_list
2514   |
2515   | DESCRIPTION
2516   |   Copy all open credit transactions for the active customer, site and currency from the
2517   |   AR_PAYMENT_SCHEDULES to the Payment List GT
2518   |
2519   | PSEUDO CODE/LOGIC
2520   |
2521   | PARAMETERS
2522   |   p_customer_id               IN NUMBER
2523   |   p_customer_site_use_id      IN NUMBER DEFAULT NULL
2524   |   p_currency_code             IN VARCHAR2
2525   |
2526   | KNOWN ISSUES
2527   |
2528   |
2529   |
2530   | NOTES
2531   |
2532   |
2533   |
2534   | MODIFICATION HISTORY
2535   | Date          Author       Description of Changes
2536   | 21-JAN-2004   rsinthre     Created
2537   | 08-Jul-2005	  rsinthre     Bug 4437225 - Disputed amount against invoice not displayed during payment
2538   +============================================================*/
2539 
2540 PROCEDURE create_open_credit_pay_list(p_customer_id           IN NUMBER,
2541                             p_customer_site_use_id  IN NUMBER DEFAULT NULL,
2542                             p_currency_code         IN VARCHAR2
2543                            ) IS
2544   CURSOR credit_transactions_list (p_customer_id NUMBER,
2545                             p_customer_site_use_id NUMBER,
2546                             p_currency_code VARCHAR2) IS
2547   ( SELECT * FROM
2548    (SELECT ps.CUSTOMER_ID,
2549          DECODE(ps.CUSTOMER_SITE_USE_ID,null,-1,ps.CUSTOMER_SITE_USE_ID) as CUSTOMER_SITE_USE_ID,
2550          acct.ACCOUNT_NUMBER,
2551          ps.CUSTOMER_TRX_ID,
2552          ps.TRX_NUMBER,
2553          ps.TRX_DATE,
2554          ps.class,
2555          ps.DUE_DATE,
2556          ps.PAYMENT_SCHEDULE_ID,
2557          ps.STATUS,
2558          trm.name term_desc,
2559          ARPT_SQL_FUNC_UTIL.Get_Number_Of_Due_Dates(ps.term_id) number_of_installments,
2560          ps.terms_sequence_number,
2561          ps.amount_line_items_original line_amount,
2562          ps.tax_original tax_amount,
2563          ps.freight_original freight_amount,
2564          ps.receivables_charges_charged finance_charge,
2565          ps.INVOICE_CURRENCY_CODE,
2566          ps.AMOUNT_DUE_ORIGINAL,
2567          DECODE (ps.class, 'PMT', ar_irec_payments.get_pymt_amnt_due_remaining(ps.cash_receipt_id),ps.AMOUNT_DUE_REMAINING) as AMOUNT_DUE_REMAINING,
2568 	 0 payment_amt,
2569 	 0 service_charge,
2570 	 0 discount_amount,
2571          case WHEN ((trunc(ps.trx_date) - trunc(sysdate)) <= 0) then TRUNC(SYSDATE) else ps.trx_date end as receipt_date,
2572 	 '' receipt_number,
2573          ct.PURCHASE_ORDER AS PO_NUMBER,
2574          NULL AS SO_NUMBER,
2575          ct.printing_option,
2576 	 ct.INTERFACE_HEADER_CONTEXT,
2577          ct.INTERFACE_HEADER_ATTRIBUTE1,
2578          ct.INTERFACE_HEADER_ATTRIBUTE2,
2579          ct.INTERFACE_HEADER_ATTRIBUTE3,
2580          ct.INTERFACE_HEADER_ATTRIBUTE4,
2581          ct.INTERFACE_HEADER_ATTRIBUTE5,
2582          ct.INTERFACE_HEADER_ATTRIBUTE6,
2583          ct.INTERFACE_HEADER_ATTRIBUTE7,
2584          ct.INTERFACE_HEADER_ATTRIBUTE8,
2585          ct.INTERFACE_HEADER_ATTRIBUTE9,
2586          ct.INTERFACE_HEADER_ATTRIBUTE10,
2587          ct.INTERFACE_HEADER_ATTRIBUTE11,
2588          ct.INTERFACE_HEADER_ATTRIBUTE12,
2589          ct.INTERFACE_HEADER_ATTRIBUTE13,
2590          ct.INTERFACE_HEADER_ATTRIBUTE14,
2591          ct.INTERFACE_HEADER_ATTRIBUTE15,
2592          ps.ATTRIBUTE_CATEGORY,
2593          ps.ATTRIBUTE1,
2594          ps.ATTRIBUTE2,
2595          ps.ATTRIBUTE3,
2596          ps.ATTRIBUTE4,
2597          ps.ATTRIBUTE5,
2598          ps.ATTRIBUTE6,
2599          ps.ATTRIBUTE7,
2600          ps.ATTRIBUTE8,
2601          ps.ATTRIBUTE9,
2602          ps.ATTRIBUTE10,
2603          ps.ATTRIBUTE11,
2604          ps.ATTRIBUTE12,
2605          ps.ATTRIBUTE13,
2606          ps.ATTRIBUTE14,
2607          ps.ATTRIBUTE15,
2608 	 sysdate LAST_UPDATE_DATE,
2609 	 0 LAST_UPDATED_BY,
2610 	 sysdate CREATION_DATE,
2611 	 0 CREATED_BY,
2612 	 0 LAST_UPDATE_LOGIN,
2613 	 0 APPLICATION_AMOUNT,
2614 	 ps.CASH_RECEIPT_ID,
2615 	 0  ORIGINAL_DISCOUNT_AMT,
2616          ps.org_id,
2617 	 0 PAYING_CUSTOMER_ID,
2618 	 0 PAYING_SITE_USE_ID,
2619 	 0  dispute_amt
2620   FROM AR_PAYMENT_SCHEDULES ps,
2621        RA_CUSTOMER_TRX_ALL ct,
2622        HZ_CUST_ACCOUNTS acct,
2623        RA_TERMS trm
2624   WHERE ps.customer_id = p_customer_id
2625   AND   ( ps.CLASS = 'CM'
2626           OR
2627           ps.CLASS = 'PMT'
2628         )
2629   AND   ps.customer_trx_id = ct.customer_trx_id(+)
2630   AND   nvl(ps.customer_site_use_id,-1) = nvl(p_customer_site_use_id, nvl(ps.customer_site_use_id,-1))
2631   AND   acct.cust_account_id = ps.customer_id
2632   AND   ps.status = 'OP'
2633   AND   ps.invoice_currency_code = p_currency_code
2634   AND   ps.term_id = trm.term_id(+))
2635   WHERE AMOUNT_DUE_REMAINING < 0);
2636 
2637    l_procedure_name           VARCHAR2(50);
2638    l_debug_info	 	          VARCHAR2(200);
2639    TYPE t_credit_transactions_list_rec
2640          IS TABLE OF credit_transactions_list%ROWTYPE index by binary_integer ;
2641 
2642    l_credit_transactions_list_rec  t_credit_transactions_list_rec ;
2643 
2644 BEGIN
2645     l_procedure_name           := '.create_open_credit_pay_list';
2646 
2647 
2648     ---------------------------------------------------------------------------
2649     l_debug_info := 'Fetch all open credit transactions into Payment List GT';
2650     ---------------------------------------------------------------------------
2651     IF (PG_DEBUG = 'Y') THEN
2652         arp_standard.debug(l_debug_info);
2653     END IF;
2654 
2655     Open  credit_transactions_list(p_customer_id,
2656                                  p_customer_site_use_id,
2657                                  p_currency_code );
2658     FETCH  credit_transactions_list BULK COLLECT INTO l_credit_transactions_list_rec;
2659       close credit_transactions_list;
2660 
2661     	 FOR trx IN l_credit_transactions_list_rec.first .. l_credit_transactions_list_rec.last loop
2662     		l_credit_transactions_list_rec(trx).payment_amt  := l_credit_transactions_list_rec(trx).AMOUNT_DUE_REMAINING;
2663 	   end loop;
2664 
2665 	 FORALL trx
2666 	   IN l_credit_transactions_list_rec.first .. l_credit_transactions_list_rec.last
2667 
2668 	   INSERT INTO AR_IREC_PAYMENT_LIST_GT
2669 	   VALUES l_credit_transactions_list_rec(trx);
2670 
2671     COMMIT;
2672 
2673 EXCEPTION
2674 WHEN OTHERS THEN
2675       IF (PG_DEBUG = 'Y') THEN
2676         arp_standard.debug('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
2677         arp_standard.debug('- Customer Id: '||p_customer_id);
2678         arp_standard.debug('- Customer Site Use Id: '||p_customer_site_use_id);
2679         arp_standard.debug('- Currency Code: '||p_currency_code);
2680         arp_standard.debug('ERROR =>'|| SQLERRM);
2681       END IF;
2682 
2683       FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
2684       FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
2685       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
2686       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
2687       FND_MSG_PUB.ADD;
2688 
2689 END create_open_credit_pay_list;
2690 
2691 /*============================================================
2692  | PUBLIC procedure cal_discount_and_service_chrg
2693  |
2694  | DESCRIPTION
2695  |   Calculate discount and service charge on the selected
2696  |   invoices and update the amounts
2697  |
2698  | PSEUDO CODE/LOGIC
2699  |
2700  | PARAMETERS
2701  |
2702  | KNOWN ISSUES
2703  |
2704  |
2705  |
2706  | NOTES
2707  |   This procedure acts on the rows inserted in the global
2708  |   temporary table by the create_invoice_pay_list procedure.
2709  |   It is session specific.
2710  |
2711  |
2712  | MODIFICATION HISTORY
2713  | Date          Author       Description of Changes
2714  | 13-Jan-2003   krmenon      Created
2715  | 26-Apr-2004   vnb          Added Customer and Customer Site as input params.
2716  | 10-Jun-2004   vnb          Bug # 3458134 - Check if the grace days for discount option is
2717  |							  enabled while calculating discount
2718  | 19-Jul-2004   vnb          Bug # 2830823 - Added exception block to handle exceptions
2719  | 31-Dec-2004   vnb          Bug 4071551 - Removed redundant code
2720  | 07-Jul-2005		 rsinthre  Bug 4437220 - Payment amount not changed when discount recalculated
2721  | 22-Mar-2010   nkanchan     Bug 8293098 - Service change based on credit card types
2722  | 18-May-2011  rsinthre      Bug 12542249 - DISCOUNT AMT NOT COMING CORRECTLY FOR INSTALLMENT PAYMENT TERMS
2723  | 11-Oct-2012  melapaku      Bug 14672025 - DISCOUNT CALCULATION IS WRONG FOR FUTURE DATED PAYMENTS.
2724  | 19-Oct-2012  melapaku      Bug 14781706 -  FUTURE DATED PAYMENT INCLUDING CREDIT MEMO FAILS WITH
2725  |                                            APPLY DATE MUST BE GREATER RECEIPT DATE
2726  +============================================================*/
2727 PROCEDURE cal_discount_and_service_chrg (p_customer_id	IN NUMBER,
2728                                          p_site_use_id  IN NUMBER DEFAULT NULL,
2729                                          p_receipt_date IN DATE DEFAULT trunc(SYSDATE),
2730                                          p_payment_type  IN varchar2 DEFAULT NULL,
2731                                          p_lookup_code  IN varchar2 DEFAULT NULL) IS
2732   --l_invoice_list        ARI_SERVICE_CHARGE_PKG.INVOICE_LIST_TABTYPE;
2733 
2734   l_total_service_charge  NUMBER;
2735   l_count                 NUMBER;
2736   l_payment_amount        NUMBER;
2737   l_prev_disc_amt         NUMBER;
2738   l_discount_amount       NUMBER;
2739   l_amt_due_remaining     NUMBER;
2740   l_rem_amt_rcpt          NUMBER;
2741   l_rem_amt_inv           NUMBER;
2742   l_grace_days_flag       VARCHAR2(2);
2743 
2744   l_procedure_name        VARCHAR2(50);
2745   l_debug_info            VARCHAR2(200);
2746   l_receipt_date          DATE;
2747 
2748   --Bug # 3467287 - The Global Temp table must be striped by Customer and Customer Site.
2749   --Bug 4062938 - Select only debit transactions
2750   CURSOR invoice_list IS
2751     SELECT  payment_schedule_id,
2752             receipt_date,
2753             payment_amt as payment_amount,
2754             amount_due_remaining,
2755             discount_amount,
2756             customer_id,
2757             account_number,
2758             customer_trx_id,
2759             currency_code,
2760             service_charge,
2761             trx_date
2762     FROM AR_IREC_PAYMENT_LIST_GT
2763     WHERE customer_id = p_customer_id
2764     AND customer_site_use_id = nvl(decode(p_site_use_id, -1, null, p_site_use_id), customer_site_use_id)
2765     AND trx_class in ('INV','DEP', 'DM', 'CB', 'CM') --Modified for Bug 14781706
2766     FOR UPDATE;
2767 
2768 BEGIN
2769    --Assign default values
2770    l_total_service_charge     := 0;
2771    l_discount_amount          := 0;
2772    l_payment_amount           := 0;
2773    l_prev_disc_amt            := 0;
2774    l_amt_due_remaining        := 0;
2775    l_rem_amt_rcpt             := 0;
2776    l_rem_amt_inv              := 0;
2777    l_procedure_name           := '.cal_discount_and_service_chrg';
2778 
2779    SAVEPOINT cal_disc_and_service_charge_sp;
2780 
2781    -- Check if grace days have to be considered for discount.
2782    --l_grace_days_flag := is_grace_days_enabled_wrapper();
2783    l_grace_days_flag := ARI_UTILITIES.is_discount_grace_days_enabled(p_customer_id,p_site_use_id);
2784 
2785    -- Create the invoice list table
2786    FOR invoice_rec in invoice_list
2787    LOOP
2788       ---------------------------------------------------------------------------
2789       l_debug_info := 'Calculate discount';
2790       ---------------------------------------------------------------------------
2791       IF (PG_DEBUG = 'Y') THEN
2792          arp_standard.debug(l_debug_info);
2793       END IF;
2794       l_prev_disc_amt       := invoice_rec.discount_amount;
2795       l_payment_amount          := invoice_rec.payment_amount;
2796       l_amt_due_remaining       := invoice_rec.amount_due_remaining;
2797       l_receipt_date            := p_receipt_date;
2798       -- Bug# 14672025 - Added IF condition inorder to fetch the correct receipt date based on payment type
2799        if (((p_payment_type = 'CREDIT_CARD') and (invoice_rec.trx_date >= trunc(sysdate)))) then
2800          l_receipt_date	:= invoice_rec.trx_date;
2801       end if;
2802       if((p_payment_type = 'BANK_ACCOUNT') and (trunc(l_receipt_date) < trunc(invoice_rec.trx_date))) then
2803          l_receipt_date	:= invoice_rec.trx_date;
2804       end if;
2805 
2806       arp_discounts_api.get_discount(  p_ps_id	            => invoice_rec.payment_schedule_id,
2807 		                       p_apply_date	    => p_receipt_date, -- Modified for Bug#14672025
2808                             	       p_in_applied_amount  => invoice_rec.payment_amount,
2809 		                       p_grace_days_flag    => l_grace_days_flag,
2810 		                       p_out_discount       => l_discount_amount,
2811 		                       p_out_rem_amt_rcpt   => l_rem_amt_rcpt,
2812 		                       p_out_rem_amt_inv    => l_rem_amt_inv);
2813 
2814       IF (PG_DEBUG = 'Y') THEN
2815          arp_standard.debug('Trx: '||invoice_rec.payment_schedule_id||
2816 	                         ' Discount: '||l_discount_amount||
2817 	                         ' Rcpt: '||l_rem_amt_rcpt||
2818 		                 ' Inv: '||l_rem_amt_inv||
2819 				 'l_receipt_date: '||l_receipt_date);
2820       END IF;
2821 
2822      	-- Bug 4352272 - Support both positive and negative invoices
2823 	if((abs(l_payment_amount + l_discount_amount) > abs(l_amt_due_remaining)) OR (abs(l_payment_amount + l_prev_disc_amt) = abs(l_amt_due_remaining))) then
2824 		l_payment_amount := l_amt_due_remaining - l_discount_amount;
2825 	end if;
2826 
2827 
2828 
2829       -----------------------------------------------------------------------------------------
2830       l_debug_info := 'Update transaction list with discount and receipt date';
2831       -----------------------------------------------------------------------------------------
2832       IF (PG_DEBUG = 'Y') THEN
2833          arp_standard.debug(l_debug_info);
2834       END IF;
2835       UPDATE AR_IREC_PAYMENT_LIST_GT
2836       SET discount_amount = l_discount_amount,
2837 	      receipt_date    = trunc(l_receipt_date),
2838           payment_amt = l_payment_amount
2839       WHERE CURRENT OF invoice_list;
2840 
2841    END LOOP;
2842 
2843    -----------------------------------------------------------------------------------------
2844    l_debug_info := 'Compute service charge';
2845    -----------------------------------------------------------------------------------------
2846    IF (PG_DEBUG = 'Y') THEN
2847       arp_standard.debug(l_debug_info);
2848    END IF;
2849    -- Bug # 3467287 - The service charge calculator API is striped by
2850    --                 Customer and Customer Site.
2851    -- Bug 3886652 - Customer Id and Customer Site Use Id added as params to ARI_CONFIG.is_service_charge_enabled
2852    l_total_service_charge := get_service_charge(p_customer_id, p_site_use_id, p_payment_type, p_lookup_code);
2853 
2854    --COMMIT;
2855 
2856 EXCEPTION
2857     WHEN OTHERS THEN
2858     	BEGIN
2859             write_debug_and_log('Unexpected Exception while calculating discount and service charge');
2860             write_debug_and_log('- Customer Id: '||p_customer_id);
2861             write_debug_and_log('- Customer Site Id: '||p_site_use_id);
2862             write_debug_and_log('- Total Service charge: '||l_total_service_charge);
2863             write_debug_and_log(SQLERRM);
2864         END;
2865 
2866 	ROLLBACK TO cal_disc_and_service_charge_sp;
2867 
2868 	FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
2869         FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
2870         FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
2871         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
2872         FND_MSG_PUB.ADD;
2873 
2874 END cal_discount_and_service_chrg;
2875 
2876 /*============================================================
2877  | procedure create_payment_instrument
2878  |
2879  | DESCRIPTION
2880  |   Creates a payment instrument with the given details
2881  |
2882  | PSEUDO CODE/LOGIC
2883  |
2884  | PARAMETERS
2885  |
2886  | KNOWN ISSUES
2887  |
2888  |
2889  |
2890  | NOTES
2891  |
2892  |
2893  |
2894  | MODIFICATION HISTORY
2895  | Date          Author       Description of Changes
2896  | 15-Jun-2005   rsinthre     Created
2897  | 18-Oct-2005	 rsinthre     Bug 4673563 - Error making credit card payment
2898  | 04-Aug-2009   avepati      Bug 8664350 - R12 UNABLE TO LOAD FEDERAL RESERVE ACH PARTICIPANT DATA
2899  | 11-Nov-2009  avepati      Bug 8915943 -  BANK DETAILS NOT COMING ON CLICKING SHOW DETAILS FOR BANK
2900  | 13-Feb-2013           melapaku  Bug16306925 - PAYMENTS FAIL WHEN SAME BANK ACCOUNT NUMBER , ROUTING NUMBER AND ACCOUNT
2901  +============================================================*/
2902 PROCEDURE create_payment_instrument (  p_customer_id         IN NUMBER,
2903 					p_customer_site_id    IN NUMBER,
2904 					p_account_number      IN VARCHAR2,
2905 					p_payer_party_id      IN NUMBER,
2906 					p_expiration_date     IN DATE,
2907 					p_account_holder_name IN VARCHAR2,
2908 					p_account_type        IN VARCHAR2,
2909 					p_payment_instrument  IN VARCHAR2,
2910 					p_address_country     IN VARCHAR2 default null,
2911 					p_bank_branch_id      IN NUMBER ,
2912 					p_receipt_curr_code   IN VARCHAR2,
2913 					p_bank_id	      IN NUMBER,
2914 					p_card_brand	      IN VARCHAR2,
2915 					p_cc_bill_to_site_id  IN NUMBER,
2916 					p_single_use_flag     IN VARCHAR2,
2917 					p_iban	        IN VARCHAR2,
2918           p_routing_number      IN VARCHAR2,
2919 					p_status              OUT NOCOPY VARCHAR2,
2920 					x_msg_count           OUT NOCOPY NUMBER,
2921 					x_msg_data            OUT NOCOPY VARCHAR2,
2922 				  p_assignment_id       OUT NOCOPY NUMBER,
2923 				  p_bank_account_id     OUT NOCOPY NUMBER) IS
2924 
2925 
2926   l_create_credit_card		IBY_FNDCPT_SETUP_PUB.CreditCard_rec_type;
2927   l_ext_bank_act_rec		IBY_EXT_BANKACCT_PUB.ExtBankAcct_rec_type;
2928   l_result_rec			IBY_FNDCPT_COMMON_PUB.Result_rec_type;
2929   l_location_rec		HZ_LOCATION_V2PUB.LOCATION_REC_TYPE;
2930   l_party_site_rec		HZ_PARTY_SITE_V2PUB.party_site_rec_type;
2931   l_payerContext_Rec_type	IBY_FNDCPT_COMMON_PUB.PayerContext_Rec_type;
2932   l_pmtInstrAssignment_Rec_type	IBY_FNDCPT_SETUP_PUB.PmtInstrAssignment_rec_type;
2933   l_pmtInstr_rec_type		IBY_FNDCPT_SETUP_PUB.PmtInstrument_rec_type;
2934 
2935   l_payer_attibute_id		NUMBER(15,0);
2936    l_joint_acct_owner_id NUMBER;
2937   l_instrument_type		VARCHAR2(20);
2938   l_assignment_id		NUMBER(15,0);
2939   l_count NUMBER := 0;
2940 --  l_bank_account_id		NUMBER;
2941   x_return_status               VARCHAR2(100);
2942   l_procedure_name		VARCHAR2(30);
2943   l_debug_info	 	        VARCHAR2(200);
2944   l_bank_branch_cur_exists    VARCHAR2(1) := 'N';
2945 
2946 
2947 --  l_commit                      VARCHAR2(2);
2948 
2949  -- added for bug 8664350
2950   CURSOR bank_branch_cur(l_routing_number VARCHAR2) IS
2951       SELECT decode(country,null, bank_home_country,country) country_code,bank_party_id,branch_party_id
2952       FROM   ce_bank_branches_V
2953       WHERE  branch_number = l_routing_number;
2954 
2955   CURSOR bank_branch_name_cur (l_routing_number VARCHAR2) IS
2956       SELECT decode(bank_name,null,routing_number,bank_name) bank_name,
2957              decode(bank_name,null,routing_number,bank_name) branch_name
2958       FROM   ar_bank_directory
2959       WHERE  routing_number = l_routing_number;
2960 
2961    CURSOR ce_chk_bank_exists_cur(l_bank_name VARCHAR2) IS   -- cursor to check whether the bank exists in ce_bank_Branches_v or not
2962       SELECT bank_party_id,branch_party_id, branch_number
2963       FROM   ce_bank_branches_V
2964       WHERE  upper(bank_name) = upper(l_bank_name);
2965 
2966    CURSOR chk_instr_assigned_cur(l_bank_account_id NUMBER, p_customer_id NUMBER, p_customer_site_id NUMBER) IS
2967       select INSTRUMENT_PAYMENT_USE_ID,ORDER_OF_PREFERENCE,START_DATE from IBY_PMT_INSTR_USES_ALL
2968       where instrument_id = l_bank_account_id
2969       and EXT_PMT_PARTY_ID = (select EXT_PAYER_ID from IBY_EXTERNAL_PAYERS_ALL
2970                               where CUST_ACCOUNT_ID = p_customer_id
2971                               and ACCT_SITE_USE_ID = p_customer_site_id);
2972 
2973     l_api_version               NUMBER := 1.0;
2974     l_init_msg_list             VARCHAR2(30) DEFAULT FND_API.G_TRUE;
2975     l_commit                    VARCHAR2(30) DEFAULT FND_API.G_FALSE;
2976     l_bank_account_id           iby_ext_bank_accounts_v.bank_account_id%TYPE;
2977     l_start_date                iby_ext_bank_accounts_v.start_date%TYPE;
2978     l_end_date                  iby_ext_bank_accounts_v.end_date%TYPE;
2979     l_bank_acct_response        iby_fndcpt_common_pub.result_rec_type;
2980     l_bank_response             IBY_FNDCPT_COMMON_PUB.Result_rec_type;
2981     l_branch_response           IBY_FNDCPT_COMMON_PUB.Result_rec_type;
2982     l_ext_bank_rec            	IBY_EXT_BANKACCT_PUB.extbank_rec_type;
2983     l_ext_branch_rec            IBY_EXT_BANKACCT_PUB.ExtBankBranch_rec_type;
2984     l_bank_party_id             ce_bank_branches_v.bank_party_id%TYPE;
2985     l_branch_party_id           ce_bank_branches_v.branch_party_id%TYPE;
2986     l_address_country           ce_bank_branches_v.country% TYPE default 'US';
2987     l_bank_name                 ar_bank_directory.bank_name%type;
2988     l_branch_name               ar_bank_directory.bank_name%type;
2989     l_st_date                   IBY_PMT_INSTR_USES_ALL.start_date%TYPE;
2990     l_priority                  IBY_PMT_INSTR_USES_ALL.order_of_preference%TYPE;
2991     l_bank_id                   ce_bank_branches_v.bank_party_id%TYPE;
2992     l_branch_id                 ce_bank_branches_v.branch_party_id%TYPE;
2993 
2994     bank_branch_rec             bank_branch_cur%ROWTYPE;
2995     bank_branch_name_rec        bank_branch_name_cur%ROWTYPE;
2996     ce_chk_bank_exists_rec      ce_chk_bank_exists_cur%ROWTYPE;
2997     instr_assign_rec            chk_instr_assigned_cur%ROWTYPE;
2998 
2999 BEGIN
3000 
3001   l_procedure_name  := '.create_payment_instrument';
3002   l_commit :=  FND_API.G_FALSE;
3003 
3004       if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3005         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'p_bank_id :: ' ||p_bank_id);
3006         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'p_bank_branch_id :: ' ||p_bank_branch_id);
3007       end if;
3008 
3009   IF (p_payment_instrument = 'BANK_ACCOUNT') THEN
3010 
3011     l_bank_id  := p_bank_id;
3012     l_branch_id := p_bank_branch_id;
3013 
3014     OPEN bank_branch_cur(p_routing_number);
3015     FETCH bank_branch_cur INTO bank_branch_rec;
3016 
3017     IF (bank_branch_cur%FOUND) then
3018       CLOSE bank_branch_cur;
3019       l_bank_branch_cur_exists := 'Y';
3020       l_bank_party_id   := bank_branch_rec.bank_party_id;
3021       l_branch_party_id := bank_branch_rec.branch_party_id;
3022       l_address_country := bank_branch_rec.country_code;
3023 
3024       if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3025         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Bank and Branch exist for this Routing Number'||p_routing_number);
3026         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Bank Id :: ' ||l_bank_party_id);
3027         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Branch Id :: ' ||l_branch_party_id);
3028         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_address_country :: ' ||l_address_country);
3029       end if;
3030 
3031     l_bank_id  := l_bank_party_id;  --bug 8915943
3032     l_branch_id := l_branch_party_id;
3033 
3034     ELSE
3035      CLOSE bank_branch_cur;
3036     END IF;
3037 
3038 --Fetching bank and branch names
3039 
3040     OPEN bank_branch_name_cur(p_routing_number);
3041     FETCH bank_branch_name_cur INTO bank_branch_name_rec;
3042 
3043     IF (bank_branch_name_cur%FOUND) then
3044       CLOSE bank_branch_name_cur;
3045       l_bank_name   := bank_branch_name_rec.bank_name;
3046       l_branch_name := bank_branch_name_rec.branch_name;
3047 
3048       if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3049         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Fetcheing Bank Name and Branch name for this routing number :: '||p_routing_number);
3050         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Bank Name :: ' ||l_bank_name);
3051         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Branch Name :: ' ||l_branch_name);
3052 
3053       end if;
3054     ELSE
3055      CLOSE bank_branch_name_cur;
3056     END IF;
3057 
3058 -- Check wether bank already exists in CE . If bank aleady exists create a branch with this routing number for that bank
3059     OPEN ce_chk_bank_exists_cur(l_bank_name);
3060     FETCH ce_chk_bank_exists_cur INTO ce_chk_bank_exists_rec;
3061 
3062     IF (ce_chk_bank_exists_cur%FOUND and l_bank_name is not null) then
3063       CLOSE ce_chk_bank_exists_cur;
3064       l_bank_party_id   := ce_chk_bank_exists_rec.bank_party_id;
3065 
3066       if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3067 	      fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, 'This Bank ' || l_bank_name || ' for the routing number '|| p_routing_number ||'already exists in CE_BANK_BRANCHES_V');
3068         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Bank Id :: ' ||l_bank_party_id);
3069         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Branch Id :: ' ||l_branch_party_id);
3070       end if;
3071 
3072     ELSE
3073      CLOSE ce_chk_bank_exists_cur;
3074     END IF;
3075 
3076   IF ( l_bank_party_id is not NULL and  l_branch_party_id is NULL)   THEN
3077 
3078     l_ext_branch_rec.branch_party_id := NULL;
3079     l_ext_branch_rec.bank_party_id   := l_bank_party_id;
3080     l_ext_branch_rec.branch_name     := p_routing_number;
3081     l_ext_branch_rec.branch_number   := p_routing_number;
3082     l_ext_branch_rec.branch_type     := 'ABA';
3083     l_ext_branch_rec.bch_object_version_number :='1';
3084     l_ext_branch_rec.typ_object_version_number :='1';
3085 
3086 		if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3087       fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Calling iby_ext_bankacct_pub.create_ext_bank_branch .....');
3088     end if;
3089 
3090     iby_ext_bankacct_pub.create_ext_bank_branch(
3091       -- IN parameters
3092       p_api_version         => l_api_version,
3093       p_init_msg_list       => l_init_msg_list,
3094       p_ext_bank_branch_rec => l_ext_branch_rec,
3095       -- OUT parameters
3096       x_branch_id           => l_branch_party_id,
3097       x_return_status       => x_return_status,
3098       x_msg_count           => x_msg_count,
3099       x_msg_data            => x_msg_data,
3100       x_response            => l_branch_response);
3101 
3102      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3103         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'End iby_ext_bankacct_pub.create_ext_bank_branch');
3104         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'branch party id :: '||l_branch_party_id);
3105         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'branch x_return_status ::' || x_return_status);
3106         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'branch x_msg_data ::' || x_msg_data);
3107      end if;
3108 
3109     IF ( x_return_status = FND_API.G_RET_STS_SUCCESS ) THEN
3110 					l_bank_id   := l_bank_party_id;
3111           l_branch_id := l_branch_party_id;
3112     end if;
3113 
3114      /*---------------------------------------------------------------+
3115       | If bank and branch could not be found, create new bank,branch |
3116       +---------------------------------------------------------------*/
3117 
3118 	elsif   ( l_bank_party_id is  NULL and  l_branch_party_id is NULL)   THEN
3119 
3120     l_ext_bank_rec.bank_id          := NULL;
3121     l_ext_bank_rec.bank_name        := l_bank_name;
3122     l_ext_bank_rec.bank_number      := p_routing_number;
3123     l_ext_bank_rec.institution_type := 'BANK';
3124     l_ext_bank_rec.country_code     := 'US';  --Create banks are used from Federal Sites.. which has details about US banks only.
3125     l_ext_bank_rec.object_version_number := '1';
3126 
3127     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3128       fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Calling iby_ext_bankacct_pub.create_ext_bank .....');
3129     end if;
3130 
3131       iby_ext_bankacct_pub.create_ext_bank(
3132       -- IN parameters
3133       p_api_version         => l_api_version,
3134       p_init_msg_list       => l_init_msg_list,
3135       p_ext_bank_rec        => l_ext_bank_rec,
3136       -- OUT parameters
3137       x_bank_id             => l_bank_party_id,
3138       x_return_status       => x_return_status,
3139       x_msg_count           => x_msg_count,
3140       x_msg_data            => x_msg_data,
3141       x_response            => l_bank_response );
3142 
3143     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3144         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'end  iby_ext_bankacct_pub.create_ext_bank');
3145         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'bank party Id ::' || l_bank_party_id);
3146         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'bank x_return_status ::' || x_return_status);
3147         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'bank x_msg_data ::' || x_msg_data);
3148     end if;
3149 
3150     IF ( x_return_status = FND_API.G_RET_STS_SUCCESS ) THEN
3151           l_bank_id   := l_bank_party_id;
3152     end if;
3153 
3154     l_ext_branch_rec.branch_party_id := NULL;
3155     l_ext_branch_rec.bank_party_id   := l_bank_party_id;
3156     l_ext_branch_rec.branch_name     := l_branch_name;
3157     l_ext_branch_rec.branch_number   := p_routing_number;
3158     l_ext_branch_rec.branch_type     := 'ABA';
3159     l_ext_branch_rec.bch_object_version_number :='1';
3160     l_ext_branch_rec.typ_object_version_number :='1';
3161 
3162     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3163       fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Calling iby_ext_bankacct_pub.create_ext_bank_branch .....');
3164     end if;
3165 
3166     iby_ext_bankacct_pub.create_ext_bank_branch(
3167       -- IN parameters
3168       p_api_version         => l_api_version,
3169       p_init_msg_list       => l_init_msg_list,
3170       p_ext_bank_branch_rec => l_ext_branch_rec,
3171       -- OUT parameters
3172       x_branch_id           => l_branch_party_id,
3173       x_return_status       => x_return_status,
3174       x_msg_count           => x_msg_count,
3175       x_msg_data            => x_msg_data,
3176       x_response            => l_branch_response);
3177 
3178      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3179         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'End iby_ext_bankacct_pub.create_ext_bank_branch');
3180         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'branch party id :: '||l_branch_party_id);
3181         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'branch x_return_status ::' || x_return_status);
3182         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'branch x_msg_data ::' || x_msg_data);
3183      end if;
3184 
3185     IF ( x_return_status = FND_API.G_RET_STS_SUCCESS ) THEN
3186           l_branch_id := l_branch_party_id;
3187     end if;
3188 end if;
3189 -- Added for Bug# 16306925
3190   IF(l_bank_branch_cur_exists = 'Y') then
3191      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3192         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Inside when l_bank_branch_cur_exists = '||l_bank_branch_cur_exists);
3193     end if;
3194 
3195 --   select EXT_BANK_ACCOUNT_ID into l_bank_account_id from iby_ext_bank_accounts where BANK_ACCOUNT_NUM = p_account_number;
3196 --l_bank_id  := l_bank_party_id;  --bug 8915943
3197 --    l_branch_id := l_branch_party_id;
3198 		begin
3199 		select ext_bank_account_id into l_bank_account_id from iby_ext_bank_accounts where BANK_ACCOUNT_NUM = p_account_number and bank_id = l_bank_id and branch_id = l_branch_id;
3200 
3201     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3202         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Inside when l_bank_branch_cur_exists,l_bank_account_id  = '||l_bank_account_id);
3203     end if;
3204 		exception
3205 			when others then
3206   --------------------------------------------------------------------------------------------------------
3207   l_debug_info := 'Call IBY create external bank acct - create_ext_bank_acct - to Create a new bank account';
3208   ---------------------------------------------------------------------------------------------------------
3209 
3210       l_ext_bank_act_rec.acct_owner_party_id		:=  p_payer_party_id;
3211       if(p_address_country IS NULL OR p_address_country = '') then
3212             l_ext_bank_act_rec.country_code		:= l_address_country;
3213       else  l_ext_bank_act_rec.country_code		:= p_address_country;
3214       end if;
3215       l_ext_bank_act_rec.bank_account_name		:= p_account_holder_name;
3216       l_ext_bank_act_rec.bank_account_num		:= p_account_number;
3217       l_ext_bank_act_rec.bank_id           		 := l_bank_id;
3218       l_ext_bank_act_rec.branch_id          		:= l_branch_id;
3219       l_ext_bank_act_rec.currency		:= p_receipt_curr_code;
3220       l_ext_bank_act_rec.multi_currency_allowed_flag	:= 'Y';
3221       l_ext_bank_act_rec.acct_type		:= p_account_type;
3222       l_ext_bank_act_rec.iban			:= p_iban;
3223 
3224      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3225         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'calling IBY_EXT_BANKACCT_PUB.create_ext_bank_acct ..');
3226         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_ext_bank_act_rec.bank_id :: '||l_ext_bank_act_rec.bank_id);
3227         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_ext_bank_act_rec.branch_id ::' || l_ext_bank_act_rec.branch_id);
3228         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_ext_bank_act_rec.country_code ::' || l_ext_bank_act_rec.country_code);
3229         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_ext_bank_act_rec.acct_owner_party_id :: '||l_ext_bank_act_rec.acct_owner_party_id);
3230         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_ext_bank_act_rec.bank_account_num ::' || l_ext_bank_act_rec.bank_account_num);
3231         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_ext_bank_act_rec.currency ::' || l_ext_bank_act_rec.currency);
3232         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_ext_bank_act_rec.bank_account_name ::' || l_ext_bank_act_rec.bank_account_name);
3233         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_ext_bank_act_rec.iban	 ::' || l_ext_bank_act_rec.iban	);
3234         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_ext_bank_act_rec.acct_type ::' || l_ext_bank_act_rec.acct_type);
3235     end if;
3236 
3237     IBY_EXT_BANKACCT_PUB.create_ext_bank_acct(
3238       p_api_version                => 1.0,
3239       p_init_msg_list            	 => FND_API.G_FALSE,
3240       p_ext_bank_acct_rec          => l_ext_bank_act_rec,
3241       x_acct_id		=> l_bank_account_id,
3242       x_return_status            	 => x_return_status,
3243       x_msg_count                	 => x_msg_count,
3244       x_msg_data                 	 => x_msg_data,
3245       x_response                   => l_result_rec);
3246 
3247       write_debug_and_log('l_bank_account_id :'||l_bank_account_id);
3248       IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
3249             x_msg_data := l_result_rec.result_code;
3250             p_status := FND_API.G_RET_STS_ERROR;
3251             write_error_messages(x_msg_data, x_msg_count);
3252             RETURN;
3253      END IF;
3254 		end; -- exception end
3255   END IF; -- IF l_bank_branch_exists
3256 
3257 
3258    ELSE
3259 -----------------------------------------------------------------------------------------
3260   l_debug_info := 'Call IBY create card - Create_Card - to Create a new CC';
3261 -----------------------------------------------------------------------------------------
3262 
3263 	  l_create_credit_card.Card_Id                   := NULL;
3264 	  l_create_credit_card.Owner_Id                  := p_payer_party_id;
3265 	  l_create_credit_card.Card_Holder_Name          := p_account_holder_name;
3266 	  if p_cc_bill_to_site_id > 0 then
3267 		  l_create_credit_card.Billing_Address_Id        := p_cc_bill_to_site_id;
3268 		  l_create_credit_card.Billing_Postal_Code       := NULL;
3269 		  l_create_credit_card.Billing_Address_Territory := NULL;
3270 	  else
3271 		  l_create_credit_card.Billing_Address_Id        := NULL;
3272 		  l_create_credit_card.Billing_Postal_Code       := 94065;
3273 		  l_create_credit_card.Billing_Address_Territory := 'US';
3274 	  end if;
3275 	  l_create_credit_card.Card_Number               := p_account_number;
3276 	  l_create_credit_card.Expiration_Date           := p_expiration_date;
3277 	  l_create_credit_card.Instrument_Type           := 'CREDITCARD';
3278 	  l_create_credit_card.PurchaseCard_SubType      := NULL;
3279 	  l_create_credit_card.Card_Issuer               := p_card_brand;
3280 	  l_create_credit_card.Single_Use_Flag           := p_single_use_flag;
3281 	  l_create_credit_card.Info_Only_Flag            := 'N';
3282 
3283 	IBY_FNDCPT_SETUP_PUB.create_card(
3284 	 p_api_version      => 1.0,
3285 	 p_init_msg_list    => FND_API.G_FALSE,
3286 	 p_commit           => l_commit,
3287 	 x_return_status    => x_return_status,
3288 	 x_msg_count        => x_msg_count,
3289 	 x_msg_data         => x_msg_data,
3290 	 p_card_instrument  => l_create_credit_card,
3291 	 x_card_id          => l_bank_account_id,
3292 	 x_response         => l_result_rec);
3293 
3294         write_debug_and_log('l_card_id :'||l_bank_account_id);
3295 	IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
3296 	          p_status := FND_API.G_RET_STS_ERROR;
3297                   x_msg_data := l_result_rec.result_code;
3298 	          write_error_messages(x_msg_data, x_msg_count);
3299 	          RETURN;
3300 	END IF;
3301   END IF;
3302   -- Added for Bug#16306925
3303     if(p_payment_instrument = 'BANK_ACCOUNT') then
3304       SELECT COUNT(*) INTO l_count
3305       FROM IBY_ACCOUNT_OWNERS
3306       WHERE ACCOUNT_OWNER_PARTY_ID = p_payer_party_id
3307       AND EXT_BANK_ACCOUNT_ID = l_bank_account_id;
3308 
3309     if(l_count <= 0) then
3310     write_debug_and_log('Adding joint account owner >> l_bank_account_id '||l_bank_account_id||' p_payer_party_id :'||p_payer_party_id);
3311     IBY_EXT_BANKACCT_PUB.add_joint_account_owner(
3312          p_api_version      => 1.0,
3313 		     p_init_msg_list    => FND_API.G_FALSE,
3314          p_bank_account_id  => l_bank_account_id,
3315          p_acct_owner_party_id => p_payer_party_id,
3316          x_joint_acct_owner_id => l_joint_acct_owner_id,
3317          x_return_status    => x_return_status,
3318 		     x_msg_count        => x_msg_count,
3319 		     x_msg_data         => x_msg_data,
3320          x_response         => l_result_rec
3321        );
3322      write_debug_and_log('l_joint_acct_owner_id : '||l_joint_acct_owner_id);
3323        IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
3324 	          p_status := FND_API.G_RET_STS_ERROR;
3325             x_msg_data := l_result_rec.result_code;
3326 	          write_error_messages(x_msg_data, x_msg_count);
3327            RETURN;
3328 	      END IF;
3329     end if ; -- l_count <= 0
3330 end if;  -- if bank account
3331 	--Now assign the instrument to the payer.
3332    OPEN chk_instr_assigned_cur(l_bank_account_id,p_customer_id,p_customer_site_id);
3333    FETCH chk_instr_assigned_cur INTO instr_assign_rec;
3334      IF (chk_instr_assigned_cur%FOUND) then
3335       CLOSE chk_instr_assigned_cur;
3336       l_assignment_id := instr_assign_rec.instrument_payment_use_id;
3337       l_priority := instr_assign_rec.order_of_preference;
3338       l_st_date  := instr_assign_rec.start_date;
3339       write_debug_and_log('l_bank_account_id = '||l_bank_account_id||' p_customer_id = '|| p_customer_id||' p_customer_site_id = '||p_customer_site_id);
3340       write_debug_and_log('l_assignment_id = '||l_assignment_id||'l_priority '||l_priority
3341                        ||'l_st_date '||l_st_date);
3342       ELSE
3343        CLOSE chk_instr_assigned_cur;
3344        l_assignment_id := NULL;
3345        l_priority := 1;
3346        l_st_date := sysdate;
3347      END IF;
3348      -- End  Bug# 16306925
3349 	-----------------------------------------------------------------------------------------
3350 	  l_debug_info := 'Call IBY Instrumnet Assignment - To assign instrument';
3351 	-----------------------------------------------------------------------------------------
3352   write_debug_and_log(l_debug_info );
3353 
3354 	if(p_payment_instrument = 'BANK_ACCOUNT') then
3355 		l_instrument_type := 'BANKACCOUNT';
3356 	else
3357 		l_instrument_type := 'CREDITCARD';
3358 	end if;
3359 
3360 	l_payerContext_Rec_type.Payment_Function	:= 'CUSTOMER_PAYMENT';
3361 	l_payerContext_Rec_type.Party_Id		:= p_payer_party_id;
3362 	l_payerContext_Rec_type.Cust_Account_Id		:= p_customer_id;
3363 	if(p_customer_site_id is not null) then
3364 		l_payerContext_Rec_type.Org_Type		:= 'OPERATING_UNIT';
3365 		l_payerContext_Rec_type.Org_Id			:= mo_global.get_current_org_id;
3366 		l_payerContext_Rec_type.Account_Site_id		:= p_customer_site_id;
3367 	end if;
3368 
3369   l_pmtInstr_rec_type.Instrument_type := l_instrument_type;
3370 	l_pmtInstr_rec_type.Instrument_Id   := l_bank_account_id;
3371 
3372 		l_pmtInstrAssignment_Rec_type.Assignment_Id	:= l_assignment_id;
3373 		l_pmtInstrAssignment_Rec_type.Instrument	:= l_pmtInstr_rec_type;
3374 		l_pmtInstrAssignment_Rec_type.Priority		:= l_priority;
3375 		l_pmtInstrAssignment_Rec_type.Start_Date	:= l_st_date;
3376 		l_pmtInstrAssignment_Rec_type.End_Date		:= NULL;
3377 
3378 
3379 	IBY_FNDCPT_SETUP_PUB.Set_Payer_Instr_Assignment(
3380 		    p_api_version      => 1.0,
3381 		    p_init_msg_list    => FND_API.G_FALSE,
3382 		    p_commit           => FND_API.G_FALSE,
3383 		    x_return_status    => x_return_status,
3384 		    x_msg_count        => x_msg_count,
3385 		    x_msg_data         => x_msg_data,
3386 		    p_payer            => l_payerContext_Rec_type,
3387 		    p_assignment_attribs => l_pmtInstrAssignment_Rec_type,
3388 		    x_assign_id        => l_assignment_id,
3389 		    x_response         => l_result_rec
3390 	);
3391 
3392 	IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
3393 		  p_status := FND_API.G_RET_STS_ERROR;
3394 		  x_msg_data := l_result_rec.result_code;
3395 		  write_error_messages(x_msg_data, x_msg_count);
3396 		  RETURN;
3397 	END IF;
3398 	p_assignment_id := l_assignment_id;
3399 	p_bank_account_id := l_bank_account_id;
3400 	p_status := x_return_status;
3401 
3402 	write_debug_and_log('instrument_assignment_id :'||p_assignment_id );
3403 
3404 	   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3405 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Create Payment Instrument - Return status - '||x_return_status);
3406 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Create Payment Instrument - Message Count - '||x_msg_count);
3407 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Create Payment Instrument - Message Data - '||x_msg_data);
3408 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Create Payment Instrument - Credit Card Number - '||p_account_number);
3409 	  end if;
3410 
3411 	  IF (PG_DEBUG = 'Y') THEN
3412 	    arp_standard.debug(l_debug_info);
3413 	  END IF;
3414 
3415 
3416 EXCEPTION
3417     WHEN OTHERS THEN
3418       p_status := FND_API.G_RET_STS_ERROR;
3419       write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
3420       write_debug_and_log('- Card Number: '||p_account_number);
3421       write_debug_and_log('- CC Billing Addrress Site Id: '||p_cc_bill_to_site_id);
3422       write_debug_and_log('- Singe Use Flag: '||p_single_use_flag);
3423       write_debug_and_log('- Return Status: '||p_status);
3424       write_debug_and_log('ERROR =>'|| SQLERRM);
3425 
3426       FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
3427       FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
3428       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
3429       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
3430       FND_MSG_PUB.ADD;
3431 END create_payment_instrument;
3432 
3433 /*============================================================
3434  | procedure create_cc_bill_to_site
3435  |
3436  | DESCRIPTION
3437  |   Creates/Updates Credit card bill to location with the given details
3438  |
3439  | PSEUDO CODE/LOGIC
3440  |
3441  | PARAMETERS
3442  |
3443  | KNOWN ISSUES
3444  |
3445  |
3446  |
3447  | NOTES
3448  |
3449  |
3450  |
3451  | MODIFICATION HISTORY
3452  | Date          Author       Description of Changes
3453  | 17-Aug-2005   rsinthre     Created
3454  +============================================================*/
3455 PROCEDURE create_cc_bill_to_site(
3456 		p_init_msg_list		IN   VARCHAR2  := FND_API.G_FALSE,
3457 		p_commit		IN   VARCHAR2  := FND_API.G_TRUE,
3458 		p_cc_location_rec	IN   HZ_LOCATION_V2PUB.LOCATION_REC_TYPE,
3459 		p_payer_party_id	IN   NUMBER,
3460 		x_cc_bill_to_site_id	IN OUT  NOCOPY NUMBER,
3461 		x_return_status		OUT NOCOPY VARCHAR2,
3462 		x_msg_count		OUT NOCOPY NUMBER,
3463 		x_msg_data		OUT NOCOPY VARCHAR2) IS
3464 
3465 l_location_id			NUMBER(15,0);
3466 l_location_rec			HZ_LOCATION_V2PUB.LOCATION_REC_TYPE;
3467 l_party_site_rec		HZ_PARTY_SITE_V2PUB.party_site_rec_type;
3468 l_party_site_number		VARCHAR2(30);
3469 l_object_version_number		NUMBER(15,0);
3470 CURSOR location_id_cur IS
3471 	select hps.location_id, hl.object_version_number from hz_party_sites hps, hz_locations hl where party_site_id = x_cc_bill_to_site_id
3472 	and hps.location_id = hl.location_id;
3473   location_id_rec	location_id_cur%ROWTYPE;
3474 
3475 l_procedure_name		VARCHAR2(30);
3476 l_debug_info	 	        VARCHAR2(200);
3477 
3478 BEGIN
3479 	l_procedure_name  := '.create_cc_bill_to_site';
3480 	-----------------------------------------------------------------------------------------
3481 	 l_debug_info := 'Call TCA create location - create_location - to create location for new CC';
3482 	-----------------------------------------------------------------------------------------
3483 
3484 		hz_location_v2pub.create_location(
3485 		    p_init_msg_list              => p_init_msg_list,
3486 		    p_location_rec               => p_cc_location_rec,
3487 		    x_location_id                => l_location_id,
3488 		    x_return_status              => x_return_status,
3489 		    x_msg_count                  => x_msg_count,
3490 		    x_msg_data                   => x_msg_data);
3491 
3492 		    IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
3493 		      x_return_status := FND_API.G_RET_STS_ERROR;
3494 		      write_error_messages(x_msg_data, x_msg_count);
3495 		      RETURN;
3496 		    END IF;
3497 
3498                 write_debug_and_log('cc_billing_location_id :'||l_location_id);
3499 
3500 		l_party_site_rec.party_id := p_payer_party_id;
3501 		l_party_site_rec.location_id := l_location_id;
3502 		l_party_site_rec.identifying_address_flag := 'N';
3503 		l_party_site_rec.created_by_module := 'ARI';
3504 
3505 		hz_party_site_v2pub.create_party_site (
3506 		p_init_msg_list         => p_init_msg_list,
3507 		p_party_site_rec        => l_party_site_rec,
3508 		x_party_site_id         => x_cc_bill_to_site_id,
3509 		x_party_site_number     => l_party_site_number,
3510 		x_return_status         => x_return_status,
3511 		x_msg_count             => x_msg_count,
3512 		x_msg_data              => x_msg_data
3513 		);
3514 
3515 		write_debug_and_log('cc_billing_site_id :'||x_cc_bill_to_site_id);
3516 
3517 		IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
3518 	          x_return_status := FND_API.G_RET_STS_ERROR;
3519 	          write_error_messages(x_msg_data, x_msg_count);
3520 	          RETURN;
3521 		END IF;
3522 
3523 EXCEPTION
3524     WHEN OTHERS THEN
3525       x_return_status := FND_API.G_RET_STS_ERROR;
3526 
3527       write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
3528       write_debug_and_log('- Return Status: '||x_return_status);
3529       write_debug_and_log('ERROR =>'|| SQLERRM);
3530 
3531       FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
3532       FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
3533       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
3534       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
3535       FND_MSG_PUB.ADD;
3536 
3537 END create_cc_bill_to_site;
3538 
3539 /*============================================================
3540  | PUBLIC procedure create_receipt
3541  |
3542  | DESCRIPTION
3543  |   Creates a cash receipt fpr the given customer
3544  |
3545  | PSEUDO CODE/LOGIC
3546  |
3547  | PARAMETERS
3548  |
3549  | KNOWN ISSUES
3550  |
3551  |
3552  |
3553  | NOTES
3554  |
3555  |
3556  |
3557  | MODIFICATION HISTORY
3558  | Date          Author       Description of Changes
3559  | 13-Jan-2003   krmenon      Created
3560  | 17-Nov-2004   vnb          Bug 4000279 - Modified to return error message, if any
3561  +============================================================*/
3562  PROCEDURE create_receipt (p_payment_amount		IN NUMBER,
3563                            p_customer_id		IN NUMBER,
3564                            p_site_use_id		IN NUMBER,
3565                            p_bank_account_id		IN NUMBER,
3566                            p_receipt_date		IN DATE DEFAULT trunc(SYSDATE),
3567                            p_receipt_method_id		IN NUMBER,
3568                            p_receipt_currency_code	IN VARCHAR2,
3569                            p_receipt_exchange_rate	IN NUMBER,
3570                            p_receipt_exchange_rate_type IN VARCHAR2,
3571                            p_receipt_exchange_rate_date IN DATE,
3572                            p_trxn_extn_id		IN NUMBER,
3573                            p_cash_receipt_id		OUT NOCOPY NUMBER,
3574                            p_status			OUT NOCOPY VARCHAR2,
3575                            x_msg_count			OUT NOCOPY NUMBER,
3576                            x_msg_data			OUT NOCOPY VARCHAR2) IS
3577 
3578   l_receipt_method_id       AR_CASH_RECEIPTS_ALL.RECEIPT_METHOD_ID%TYPE;
3579   l_receipt_creation_status VARCHAR2(80);
3580   l_cash_receipt_id         AR_CASH_RECEIPTS_ALL.CASH_RECEIPT_ID%TYPE;
3581   x_return_status           VARCHAR2(100);
3582 
3583   l_procedure_name           VARCHAR2(30);
3584   l_debug_info	 	     VARCHAR2(200);
3585   l_instr_assign_id	     NUMBER;
3586 
3587 BEGIN
3588 
3589   l_procedure_name  := '.create_receipt';
3590 
3591   fnd_log_repository.init;
3592 
3593   -----------------------------------------------------------------------------------------
3594   l_debug_info := 'Call public AR receipts API - create_cash - to create receipt for payment';
3595   -----------------------------------------------------------------------------------------
3596   write_debug_and_log('p_payment_amount:'||p_payment_amount);
3597   write_debug_and_log('p_receipt_method_id:'||p_receipt_method_id);
3598   write_debug_and_log('p_trxn_extn_id:'||p_trxn_extn_id);
3599   write_debug_and_log('p_customer_id:'||p_customer_id);
3600   write_debug_and_log('p_site_use_id:'||p_site_use_id);
3601   write_debug_and_log('p_receipt_currency_code:'||p_receipt_currency_code);
3602   -------------------------------------------------------------------------------------------
3603 
3604   AR_RECEIPT_API_PUB.create_cash(
3605             p_api_version           => 1.0,
3606             p_init_msg_list         => FND_API.G_TRUE,
3607     	    p_commit                => FND_API.G_FALSE,
3608             p_validation_level      => FND_API.G_VALID_LEVEL_FULL,
3609             x_return_status         => x_return_status,
3610             x_msg_count             => x_msg_count,
3611             x_msg_data              => x_msg_data,
3612             p_amount                => p_payment_amount,
3613             p_receipt_method_id     => p_receipt_method_id,
3614             p_customer_id           => p_customer_id,
3615             p_customer_site_use_id  => p_site_use_id,
3616             p_default_site_use	=> 'N',
3617             p_payment_trxn_extension_id     => p_trxn_extn_id,
3618             p_currency_code         => p_receipt_currency_code,
3619             p_exchange_rate         => p_receipt_exchange_rate,
3620             p_exchange_rate_type    => p_receipt_exchange_rate_type,
3621             p_exchange_rate_date    => p_receipt_exchange_rate_date,
3622             p_receipt_date          => trunc(p_receipt_date),
3623             p_cr_id                 => l_cash_receipt_id,
3624             p_called_from           => 'IREC');
3625 
3626   p_cash_receipt_id := l_cash_receipt_id;
3627   p_status := x_return_status;
3628   write_debug_and_log('p_receipt_currency_code:'||l_cash_receipt_id);
3629 
3630   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3631 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Create Cash - Rerturn status - '||x_return_status);
3632 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Create Cash - Message Count - '||x_msg_count);
3633 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Create Cash - Message Data - '||x_msg_data);
3634 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Create Cash - CR Id - '||l_cash_receipt_id);
3635   end if;
3636 
3637   arp_standard.debug('X_RETURN_STATUS=>'||X_RETURN_STATUS);
3638   arp_standard.debug('X_MSG_COUNT=>'||to_char(X_MSG_COUNT));
3639 
3640 EXCEPTION
3641     WHEN OTHERS THEN
3642       p_status := FND_API.G_RET_STS_ERROR;
3643 
3644       write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
3645       write_debug_and_log('- Customer Id: '||p_customer_id);
3646       write_debug_and_log('- Customer Site Id: '||p_site_use_id);
3647       write_debug_and_log('- Cash Receipt Id: '||p_cash_receipt_id);
3648       write_debug_and_log('- Bank Account Id: '||p_bank_account_id);
3649       write_debug_and_log('- Return Status: '||p_status);
3650       write_debug_and_log('ERROR =>'|| SQLERRM);
3651 
3652       FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
3653       FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
3654       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
3655       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
3656       FND_MSG_PUB.ADD;
3657 
3658 END create_receipt;
3659 
3660 /*=============================================================
3661  | HISTORY
3662  |  17-Nov-2004   vnb          Bug 4000279 - Modified to return error message, if any
3663  |
3664  | PARAMETERS
3665  |
3666  |   p_customer_id          IN    Customer Id
3667  |   p_site_use_id          IN    Customer Site Id
3668  |   p_cash_receipt_id      IN    Cash Receipt Id
3669  |   p_return_status       OUT    Success/Error status
3670  |   p_apply_err_count     OUT    Number of unsuccessful applications
3671  |
3672  +=============================================================*/
3673 PROCEDURE apply_cash ( p_customer_id		    IN NUMBER,
3674                        p_site_use_id            IN NUMBER DEFAULT NULL,
3675                        p_cash_receipt_id        IN NUMBER,
3676                        p_return_status         OUT NOCOPY VARCHAR2,
3677                        p_apply_err_count       OUT NOCOPY NUMBER,
3678                        x_msg_count           OUT NOCOPY NUMBER,
3679                        x_msg_data            OUT NOCOPY VARCHAR2
3680                      ) IS
3681 
3682 --Bug # 3467287 - The Global Temp table must be striped by Customer and Customer Site.
3683 CURSOR credit_trx_list IS
3684   SELECT *
3685   FROM ar_irec_payment_list_gt
3686   WHERE customer_id = p_customer_id
3687   AND customer_site_use_id = nvl(decode(p_site_use_id, -1, null, p_site_use_id), customer_site_use_id)
3688   AND ( trx_class = 'CM'
3689           OR
3690         trx_class = 'PMT'
3691 	  );
3692 
3693 CURSOR debit_trx_list IS
3694   SELECT *
3695   FROM ar_irec_payment_list_gt
3696   WHERE customer_id = p_customer_id
3697   AND customer_site_use_id = nvl(decode(p_site_use_id, -1, null, p_site_use_id), customer_site_use_id)
3698   AND ( trx_class = 'INV' OR
3699          trx_class = 'DM' OR
3700          trx_class = 'GUAR' OR
3701          trx_class = 'CB' OR
3702          trx_class = 'DEP'
3703 	   )
3704   ORDER BY amount_due_remaining ASC;
3705 
3706   x_return_status           VARCHAR2(100);
3707 
3708   l_msg_count               NUMBER;
3709   l_msg_data                VARCHAR2(255);
3710   l_apply_err_count         NUMBER;
3711 
3712   l_application_ref_num        ar_receivable_applications.application_ref_num%TYPE;
3713   l_receivable_application_id  ar_receivable_applications.receivable_application_id%TYPE;
3714   l_applied_rec_app_id         ar_receivable_applications.receivable_application_id%TYPE;
3715   l_acctd_amount_applied_from  ar_receivable_applications.acctd_amount_applied_from%TYPE;
3716   l_acctd_amount_applied_to    ar_receivable_applications.acctd_amount_applied_to%TYPE;
3717 
3718   l_procedure_name VARCHAR2(30);
3719   l_debug_info	   VARCHAR2(200);
3720 
3721  credit_trx_list_count NUMBER;
3722  debit_trx_list_count NUMBER;
3723  total_trx_count NUMBER;
3724 
3725 BEGIN
3726 
3727   --Assign default values
3728   l_msg_count       := 0;
3729   l_apply_err_count := 0;
3730   l_procedure_name  := '.apply_cash';
3731 
3732     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3733     fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'In apply_cash: p_customer_id='||p_customer_id ||','
3734 	              || 'p_site_use_id=' || p_site_use_id || ','
3735 	              || 'p_cash_receipt_id=' || p_cash_receipt_id);
3736     end if;
3737 
3738     --Pring in the debug log : Total No of rows in ar_irec_payment_list_gt
3739 
3740   SELECT COUNT(*)
3741   INTO 	 total_trx_count
3742   FROM 	 ar_irec_payment_list_gt;
3743 
3744   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3745      fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Total no of rows in ar_irec_payment_list_gt='||total_trx_count);
3746   end if;
3747 
3748 --Pring in the debug log : No of rows that will be picked by the cursor credit_trx_list
3749 
3750   SELECT  COUNT(*)
3751   INTO    credit_trx_list_count
3752   FROM    ar_irec_payment_list_gt
3753   WHERE   customer_id = p_customer_id
3754   AND customer_site_use_id = nvl(decode(p_site_use_id, -1, null, p_site_use_id), customer_site_use_id)
3755   AND ( trx_class = 'CM'  OR trx_class = 'PMT' );
3756 
3757   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3758      fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'credit_trx_list_count: '||credit_trx_list_count);
3759   end if;
3760 
3761 --Pring in the debug log : No of rows that will be picked by the cursor debit_trx_list
3762 
3763   SELECT  count(*)
3764   INTO    debit_trx_list_count
3765   FROM    ar_irec_payment_list_gt
3766   WHERE   customer_id = p_customer_id
3767   AND customer_site_use_id = nvl(decode(p_site_use_id, -1, null, p_site_use_id), customer_site_use_id)
3768   AND ( trx_class = 'INV' OR
3769          trx_class = 'DM' OR
3770          trx_class = 'GUAR' OR
3771          trx_class = 'CB' OR
3772          trx_class = 'DEP'
3773 	   );
3774 
3775   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3776      fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'debit_trx_list_count: ' || debit_trx_list_count);
3777   end if;
3778 
3779   --
3780   -- Establish a save point
3781   --
3782   SAVEPOINT ARI_Apply_Cash_Receipt_PVT;
3783 
3784   ----------------------------------------------------------------------------------
3785   l_debug_info := 'Step 1: Apply credits against the receipt (if any)';
3786   ----------------------------------------------------------------------------------
3787 
3788     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3789        fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info);
3790     end if;
3791 
3792   FOR trx in credit_trx_list
3793   LOOP
3794 
3795   	if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3796 	    fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, 'trx.trx_class=' || trx.trx_class);
3797         end if;
3798 
3799         IF (trx.trx_class = 'CM') THEN
3800         -- The transaction is a credit memo
3801 
3802         if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3803               fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Calling AR_RECEIPT_API_PUB.apply for CM:'
3804                   ||'trx.customer_trx_id=' || trx.customer_trx_id || ','
3805                   ||'trx.terms_sequence_number=' || trx.terms_sequence_number || ','
3806                   ||'trx.payment_schedule_id=' || trx.payment_schedule_id || ','
3807                   ||'trx.payment_amt=' || trx.payment_amt || ','
3808                   ||'trx.discount_amount=' || trx.discount_amount);
3809         end if;
3810 
3811             AR_RECEIPT_API_PUB.apply(
3812                             p_api_version           => 1.0,
3813                             p_init_msg_list         => FND_API.G_TRUE,
3814                             p_commit                => FND_API.G_FALSE,
3815                             p_validation_level      => FND_API.G_VALID_LEVEL_FULL,
3816                             x_return_status         => x_return_status,
3817                             x_msg_count             => x_msg_count,
3818                             x_msg_data              => x_msg_data,
3819                             p_cash_receipt_id       => p_cash_receipt_id,
3820                             p_customer_trx_id       => trx.customer_trx_id,
3821                             p_installment           => trx.terms_sequence_number,
3822                             p_applied_payment_schedule_id => trx.payment_schedule_id,
3823                             p_amount_applied        => trx.payment_amt,
3824                             p_discount              => trx.discount_amount,
3825 			    p_apply_date            => trunc(trx.receipt_date),
3826                             p_called_from           => 'IREC'
3827                             );
3828 
3829 	   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3830 	        fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Execution of AR_RECEIPT_API_PUB.apply is over');
3831 	   end if;
3832 
3833         ELSE
3834         -- The transaction must be a payment
3835 
3836           if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3837               fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Calling AR_RECEIPT_API_PUB.apply_open_receipt for PMT:'
3838               || 'trx.cash_receipt_id='  || trx.cash_receipt_id ||','
3839               || 'trx.payment_amt=' || trx.payment_amt || ','
3840               || 'l_application_ref_num=' || l_application_ref_num || ','
3841               || 'l_receivable_application_id=' || l_receivable_application_id || ','
3842               || 'l_applied_rec_app_id=' || l_applied_rec_app_id || ','
3843               || 'l_acctd_amount_applied_from=' || l_acctd_amount_applied_from || ','
3844               || 'l_acctd_amount_applied_to=' || l_acctd_amount_applied_to);
3845 	    end if;
3846 
3847             AR_RECEIPT_API_PUB.apply_open_receipt
3848                             (p_api_version                 => 1.0,
3849                              p_init_msg_list               => FND_API.G_TRUE,
3850                              p_commit                      => FND_API.G_FALSE,
3851                              x_return_status               => x_return_status,
3852                              x_msg_count                   => x_msg_count,
3853                              x_msg_data                    => x_msg_data,
3854                              p_cash_receipt_id             => p_cash_receipt_id,
3855                              p_open_cash_receipt_id        => trx.cash_receipt_id,
3856                              p_amount_applied              => trx.payment_amt,
3857                              p_called_from                 => 'IREC',
3858                              x_application_ref_num         => l_application_ref_num,
3859                              x_receivable_application_id   => l_receivable_application_id,
3860                              x_applied_rec_app_id          => l_applied_rec_app_id,
3861                              x_acctd_amount_applied_from   => l_acctd_amount_applied_from,
3862                              x_acctd_amount_applied_to     => l_acctd_amount_applied_to
3863                              );
3864 
3865 	   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3866 	        fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Execution of AR_RECEIPT_API_PUB.apply_open_receipt is over');
3867 	   end if;
3868 
3869         END IF;
3870 
3871           if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3872 	        fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'x_return_status=' || x_return_status);
3873 	   end if;
3874 
3875         -- Check for errors and increment the count for
3876         -- errored applcations
3877         IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
3878             l_apply_err_count := l_apply_err_count + 1;
3879             p_apply_err_count := l_apply_err_count;
3880             p_return_status   := FND_API.G_RET_STS_ERROR;
3881             ROLLBACK TO ARI_Apply_Cash_Receipt_PVT;
3882             RETURN;
3883         END IF;
3884 
3885         if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3886 	       fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Applied receipt '||trx.trx_number||', Status: '||x_return_status);
3887         end if;
3888 
3889         write_debug_and_log('X_RETURN_STATUS=>'||X_RETURN_STATUS);
3890         write_debug_and_log('X_MSG_COUNT=>'||to_char(X_MSG_COUNT));
3891 
3892   END LOOP;
3893   ----------------------------------------------------------------------------------
3894   l_debug_info := 'Step 2: Apply debits against the receipt';
3895   ----------------------------------------------------------------------------------
3896 
3897     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3898        fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info);
3899   end if;
3900 
3901   FOR trx in debit_trx_list
3902   LOOP
3903 
3904       if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3905        fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, 'Calling AR_RECEIPT_API_PUB.apply for debit trx: '
3906 	       || 'p_cash_receipt_id=' || p_cash_receipt_id || ','
3907 	       || 'trx.customer_trx_id=' || trx.customer_trx_id || ','
3908 	       || 'trx.payment_schedule_id=' || trx.payment_schedule_id || ','
3909 	       || 'trx.payment_amt=' || trx.payment_amt || ','
3910 	       || 'trx.service_charge='|| trx.service_charge || ','
3911 	       || 'trx.discount_amount=' || trx.discount_amount || ','
3912 	       || 'p_apply_date=' || To_Char(trunc(trx.receipt_date)) );
3913       end if;
3914 
3915     --
3916     -- Call the application API
3917     --
3918     AR_RECEIPT_API_PUB.apply(
3919         p_api_version           => 1.0,
3920         p_init_msg_list         => FND_API.G_TRUE,
3921         p_commit                => FND_API.G_FALSE,
3922         p_validation_level      => FND_API.G_VALID_LEVEL_FULL,
3923         x_return_status         => x_return_status,
3924         x_msg_count             => x_msg_count,
3925         x_msg_data              => x_msg_data,
3926         p_cash_receipt_id       => p_cash_receipt_id,
3927         p_customer_trx_id       => trx.customer_trx_id,
3928         p_applied_payment_schedule_id => trx.payment_schedule_id,
3929         p_amount_applied        => trx.payment_amt + nvl(trx.service_charge,0),
3930         p_discount              => trx.discount_amount,
3931         p_apply_date            => trunc(trx.receipt_date),
3932         p_called_from           => 'IREC'
3933         );
3934 
3935     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3936         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Execution of AR_RECEIPT_API_PUB.apply is over. Return Status=' || x_return_status);
3937         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'x_msg_data=' || x_msg_data);
3938         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'x_msg_count=' || x_msg_count);
3939     end if;
3940 
3941     -- Check for errors and increment the count for
3942     -- errored applcations
3943     IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
3944       l_apply_err_count := l_apply_err_count + 1;
3945       p_apply_err_count := l_apply_err_count;
3946       p_return_status   := FND_API.G_RET_STS_ERROR;
3947       ROLLBACK TO ARI_Apply_Cash_Receipt_PVT;
3948       RETURN;
3949     END IF;
3950 
3951     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3952 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Applied Cash to '||trx.trx_number||' Status: '||x_return_status);
3953     end if;
3954 
3955     write_debug_and_log('X_RETURN_STATUS=>'||X_RETURN_STATUS);
3956     write_debug_and_log('X_MSG_COUNT=>'||to_char(X_MSG_COUNT));
3957     write_debug_and_log('x_msg_data=>'||x_msg_data);
3958 
3959   END LOOP;
3960 
3961   p_apply_err_count := l_apply_err_count;
3962   -- There are no errored applications; set the
3963   -- return status to success
3964   p_return_status := FND_API.G_RET_STS_SUCCESS;
3965 
3966     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
3967     fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Exiting apply_cash with return status: '||p_return_status);
3968   end if;
3969 
3970 EXCEPTION
3971     WHEN OTHERS THEN
3972     	BEGIN
3973 	    p_return_status := FND_API.G_RET_STS_ERROR;
3974 
3975             write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
3976             write_debug_and_log('- Customer Id: '||p_customer_id);
3977             write_debug_and_log('- Customer Site Id: '||p_site_use_id);
3978             write_debug_and_log('- Cash Receipt Id: '||p_cash_receipt_id);
3979             write_debug_and_log('- Return Status: '||p_return_status);
3980             write_debug_and_log(SQLERRM);
3981 
3982             FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
3983             FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
3984             FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
3985             FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
3986             FND_MSG_PUB.ADD;
3987         END;
3988 
3989 END apply_cash;
3990 
3991 
3992 /*=====================================================================
3993  | FUNCTION get_service_charge
3994  |
3995  | DESCRIPTION
3996  |   This function will calculate the service charge for the multiple
3997  |   invoices that have been selected for payment and return the
3998  |   total service charge that is to be applied.
3999  |
4000  | HISTORY
4001  |   26-APR-2004     vnb      Bug # 3467287 - Added Customer and Customer Site
4002  |							  as input parameters.
4003  |   19-JUL-2004     vnb      Bug # 2830823 - Added exception block to handle exceptions
4004  |   21-SEP-2004     vnb      Bug # 3886652 - Added customer site use id to ARI_SERVICE_CHARGE_PKG.INVOICE_LIST_TABTYPE
4005  | 22-Mar-2010   nkanchan     Bug 8293098 - Service change based on credit card types
4006  |
4007  +=====================================================================*/
4008  FUNCTION get_service_charge (  p_customer_id		    IN NUMBER,
4009                                 p_site_use_id          IN NUMBER DEFAULT NULL,
4010                                 p_payment_type       IN varchar2 DEFAULT NULL,
4011                                 p_lookup_code       IN varchar2 DEFAULT NULL)
4012                              RETURN NUMBER IS
4013 
4014  l_invoice_list             ARI_SERVICE_CHARGE_PKG.INVOICE_LIST_TABTYPE;
4015  l_total_service_charge     NUMBER;
4016  l_count                    NUMBER;
4017  l_currency_code            AR_IREC_PAYMENT_LIST_GT.currency_code%TYPE;
4018  l_service_charge           NUMBER;
4019 
4020  l_procedure_name           VARCHAR2(30);
4021  l_debug_info	 	    VARCHAR2(200);
4022 
4023  --Bug # 3467287 - The Global Temp table must be striped by Customer and Customer Site.
4024  --Bug # 3886652 - Added customer site use id to ARI_SERVICE_CHARGE_PKG.INVOICE_LIST_TABTYPE
4025  CURSOR invoice_list IS
4026    SELECT  payment_schedule_id,
4027            payment_amt as payment_amount,
4028            customer_id,
4029            customer_site_use_id,
4030            account_number,
4031            customer_trx_id,
4032            currency_code,
4033            service_charge
4034    FROM AR_IREC_PAYMENT_LIST_GT
4035    WHERE customer_id = p_customer_id
4036    AND customer_site_use_id = nvl(decode(p_site_use_id, -1, null, p_site_use_id), customer_site_use_id)
4037    AND trx_class IN ('INV','DM','CB','DEP');
4038 
4039  BEGIN
4040   --Assign default values
4041   l_total_service_charge := 0;
4042   l_procedure_name       :=  '.get_service_charge';
4043 
4044   SAVEPOINT service_charge_sp;
4045 
4046    ----------------------------------------------------------------------------------------
4047    l_debug_info := 'Check if service charge is enabled; else return zero';
4048    -----------------------------------------------------------------------------------------
4049    IF (PG_DEBUG = 'Y') THEN
4050        arp_standard.debug(l_debug_info);
4051    END IF;
4052    IF NOT (ARI_UTILITIES.is_service_charge_enabled(p_customer_id, p_site_use_id)) THEN
4053       RETURN l_total_service_charge;
4054    END IF;
4055 
4056    ----------------------------------------------------------------------------------------
4057    l_debug_info := 'Create the invoice list table';
4058    -----------------------------------------------------------------------------------------
4059    IF (PG_DEBUG = 'Y') THEN
4060        arp_standard.debug(l_debug_info);
4061    END IF;
4062 
4063    IF (PG_DEBUG = 'Y') THEN
4064        arp_standard.debug('In getServiceCharge begin for Loop..');
4065    END IF;
4066 
4067    FOR invoice_rec in invoice_list
4068    LOOP
4069 
4070      --Bug 4071551 - Changed the indexing field to Payment Schedule Id from Customer Trx Id to keep uniqueness
4071      l_count := invoice_rec.payment_schedule_id;
4072 
4073      IF (PG_DEBUG = 'Y') THEN
4074        arp_standard.debug('Index: '||l_count);
4075      END IF;
4076 
4077      l_invoice_list(l_count).payment_schedule_id := invoice_rec.payment_schedule_id;
4078      l_invoice_list(l_count).payment_amount      := invoice_rec.payment_amount;
4079      l_invoice_list(l_count).customer_id         := invoice_rec.customer_id;
4080      --Bug # 3886652 - Added customer site use id to ARI_SERVICE_CHARGE_PKG.INVOICE_LIST_TABTYPE
4081      l_invoice_list(l_count).customer_site_use_id:= invoice_rec.customer_site_use_id;
4082      l_invoice_list(l_count).account_number      := invoice_rec.account_number;
4083      l_invoice_list(l_count).customer_trx_id     := invoice_rec.customer_trx_id;
4084      l_invoice_list(l_count).currency_code       := invoice_rec.currency_code;
4085      l_invoice_list(l_count).service_charge      := invoice_rec.service_charge;
4086 
4087      l_currency_code := invoice_rec.currency_code;
4088 
4089    IF (PG_DEBUG = 'Y') THEN
4090        arp_standard.debug('invoice_rec.payment_schedule_id: '||invoice_rec.payment_schedule_id);
4091        arp_standard.debug('invoice_rec.payment_amount: '||invoice_rec.payment_amount);
4092        arp_standard.debug('invoice_rec.customer_id: '||invoice_rec.customer_id);
4093        arp_standard.debug('invoice_rec.customer_site_use_id: '||invoice_rec.customer_site_use_id);
4094        arp_standard.debug('invoice_rec.account_number: '||invoice_rec.account_number);
4095        arp_standard.debug('invoice_rec.customer_trx_id '||invoice_rec.customer_trx_id);
4096        arp_standard.debug('invoice_rec.currency_code: '||invoice_rec.currency_code);
4097        arp_standard.debug('invoice_rec.service_charge: '||invoice_rec.service_charge);
4098 
4099    END IF;
4100 
4101 
4102    END LOOP;
4103 
4104    IF (PG_DEBUG = 'Y') THEN
4105        arp_standard.debug('End first Loop. Total records: '||l_invoice_list.COUNT);
4106    END IF;
4107 
4108    ----------------------------------------------------------------------------------------
4109    l_debug_info := 'Call the service charge package to compute';
4110    -----------------------------------------------------------------------------------------
4111    IF (PG_DEBUG = 'Y') THEN
4112        arp_standard.debug(l_debug_info);
4113    END IF;
4114    ARI_SERVICE_CHARGE_PKG.compute_service_charge(l_invoice_list, p_payment_type, p_lookup_code);
4115 
4116    l_count := l_invoice_list.FIRST;
4117 
4118    WHILE l_count IS NOT NULL
4119    LOOP
4120      l_service_charge := ARI_UTILITIES.curr_round_amt(l_invoice_list(l_count).service_charge, l_currency_code);
4121 
4122      IF (PG_DEBUG = 'Y') THEN
4123        arp_standard.debug('Index: '|| l_count||' PaymentScheduleId: '||l_invoice_list(l_count).payment_schedule_id ||
4124                           'Service Charge: '||l_invoice_list(l_count).service_charge);
4125      END IF;
4126 
4127      ----------------------------------------------------------------------------------------
4128      l_debug_info := 'Update service charge in the Payment GT';
4129      -----------------------------------------------------------------------------------------
4130      IF (PG_DEBUG = 'Y') THEN
4131          arp_standard.debug(l_debug_info);
4132      END IF;
4133      UPDATE ar_irec_payment_list_gt
4134      SET    service_charge = l_service_charge
4135      WHERE  payment_schedule_id = l_invoice_list(l_count).payment_schedule_id;
4136 
4137      l_total_service_charge := l_total_service_charge + l_service_charge;
4138 
4139      -- Error handling required
4140      IF SQL%ROWCOUNT < 1 THEN
4141 	IF (PG_DEBUG = 'Y') THEN
4142 	   arp_standard.debug('Error - Cannot update '||l_count);
4143         END IF;
4144      END IF;
4145 
4146      l_count := l_invoice_list.NEXT(l_count);
4147 
4148    END LOOP;
4149 
4150    COMMIT;
4151 
4152    RETURN l_total_service_charge;
4153 
4154  EXCEPTION
4155     WHEN OTHERS THEN
4156     	BEGIN
4157             write_debug_and_log('Unexpected Exception while computing service charge');
4158             write_debug_and_log('- Customer Id: '||p_customer_id);
4159             write_debug_and_log('- Customer Site Id: '||p_site_use_id);
4160             write_debug_and_log('- Total Service charge: '||l_total_service_charge);
4161             write_debug_and_log(SQLERRM);
4162         END;
4163 
4164 	ROLLBACK TO service_charge_sp;
4165 
4166 	FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
4167         FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
4168         FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
4169         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
4170         FND_MSG_PUB.ADD;
4171 
4172  END get_service_charge;
4173 
4174 /*=====================================================================
4175  | PROCEDURE apply_service_charge
4176  |
4177  | DESCRIPTION
4178  |   This function will calculate the service charge for the multiple
4179  |   invoices that have been selected for payment and return the
4180  |   total service charge that is to be applied.
4181  |
4182  | HISTORY
4183  |  26-APR-2004  vnb         Bug # 3467287 - Added Customer and Customer Site
4184  |                           as input parameters.
4185  |  19-JUL-2004  vnb         Bug # 2830823 - Added exception block to handle exceptions
4186  |  21-SEP-2004  vnb         Bug # 3886652 - Added customer site use id to ARI_SERVICE_CHARGE_PKG.INVOICE_LIST_TABTYPE
4187  |
4188  +=====================================================================*/
4189  PROCEDURE apply_service_charge ( p_customer_id		    IN NUMBER,
4190                                   p_site_use_id         IN NUMBER DEFAULT NULL,
4191                                   x_return_status OUT NOCOPY VARCHAR2) IS
4192 
4193  l_invoice_list             ARI_SERVICE_CHARGE_PKG.INVOICE_LIST_TABTYPE;
4194  l_total_service_charge     NUMBER;
4195  l_count                    NUMBER;
4196  l_return_status            VARCHAR2(2);
4197  l_procedure_name           VARCHAR2(50);
4198  l_debug_info	 	    VARCHAR2(200);
4199 
4200  --Bug # 3467287 - The Global Temp table must be striped by Customer and Customer Site.
4201  --Bug # 3886652 - Added customer site use id to ARI_SERVICE_CHARGE_PKG.INVOICE_LIST_TABTYPE
4202  CURSOR invoice_list IS
4203    SELECT  payment_schedule_id,
4204            payment_amt as payment_amount,
4205            customer_id,
4206            customer_site_use_id,
4207            account_number,
4208            customer_trx_id,
4209            currency_code,
4210            service_charge,
4211 	   receipt_date
4212    FROM AR_IREC_PAYMENT_LIST_GT
4213    WHERE customer_id = p_customer_id
4214     AND customer_site_use_id = nvl(decode(p_site_use_id, -1, null, p_site_use_id), customer_site_use_id)
4215    AND ( trx_class = 'INV' OR
4216          trx_class = 'DM' OR
4217          trx_class = 'GUAR' OR
4218          trx_class = 'CB' OR
4219          trx_class = 'DEP'
4220 	   );
4221 
4222  BEGIN
4223    --Assign default values
4224    l_total_service_charge := 0;
4225    l_procedure_name := '.apply_service_charge';
4226 
4227    fnd_log_repository.init;
4228    if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4229 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'+');
4230    end if;
4231 
4232    l_count := 1;
4233 
4234    -- Create the invoice list table
4235    ----------------------------------------------------------------------------------
4236    l_debug_info := 'Create the invoice list table';
4237    ----------------------------------------------------------------------------------
4238 
4239   IF (PG_DEBUG = 'Y') THEN
4240        arp_standard.debug('In Apply_Service_Charge begin for Loop..');
4241    END IF;
4242 
4243    FOR invoice_rec in invoice_list
4244    LOOP
4245 
4246      --l_count := invoice_rec.customer_trx_id;
4247      --l_invoice_list.EXTEND;
4248      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4249 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Index: '||l_count);
4250      end if;
4251      l_invoice_list(l_count).payment_schedule_id := invoice_rec.payment_schedule_id;
4252      l_invoice_list(l_count).payment_amount := invoice_rec.payment_amount;
4253      l_invoice_list(l_count).customer_id := invoice_rec.customer_id;
4254      --Bug # 3886652 - Added customer site use id to ARI_SERVICE_CHARGE_PKG.INVOICE_LIST_TABTYPE
4255      l_invoice_list(l_count).customer_site_use_id := invoice_rec.customer_site_use_id;
4256      l_invoice_list(l_count).account_number := invoice_rec.account_number;
4257      l_invoice_list(l_count).customer_trx_id := invoice_rec.customer_trx_id;
4258      l_invoice_list(l_count).currency_code := invoice_rec.currency_code;
4259      l_invoice_list(l_count).service_charge := invoice_rec.service_charge;
4260      l_invoice_list(l_count).apply_date := invoice_rec.receipt_date;
4261      l_invoice_list(l_count).gl_date := invoice_rec.receipt_date;
4262 
4263 
4264    IF (PG_DEBUG = 'Y') THEN
4265        arp_standard.debug('invoice_rec.payment_schedule_id: '||invoice_rec.payment_schedule_id);
4266        arp_standard.debug('invoice_rec.payment_amount: '||invoice_rec.payment_amount);
4267        arp_standard.debug('invoice_rec.customer_id: '||invoice_rec.customer_id);
4268        arp_standard.debug('invoice_rec.customer_site_use_id: '||invoice_rec.customer_site_use_id);
4269        arp_standard.debug('invoice_rec.account_number: '||invoice_rec.account_number);
4270        arp_standard.debug('invoice_rec.customer_trx_id '||invoice_rec.customer_trx_id);
4271        arp_standard.debug('invoice_rec.currency_code: '||invoice_rec.currency_code);
4272        arp_standard.debug('invoice_rec.service_charge: '||invoice_rec.service_charge);
4273 
4274    END IF;
4275 
4276      l_count := l_count + 1;
4277    END LOOP;
4278 
4279    -- Call the service charge compute package
4280    ----------------------------------------------------------------------------------
4281    l_debug_info := 'Apply service charge';
4282    ----------------------------------------------------------------------------------
4283    l_return_status := ARI_SERVICE_CHARGE_PKG.apply_charge(l_invoice_list);
4284 
4285    IF ( l_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
4286      -- bug 3672530 - Ensure graceful error handling
4287      x_return_status := FND_API.G_RET_STS_ERROR;
4288      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4289 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'ERROR: Loop count is: '||l_count);
4290      end if;
4291      APP_EXCEPTION.RAISE_EXCEPTION;
4292    END IF;
4293 
4294    if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4295 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'-');
4296    end if;
4297 
4298  EXCEPTION
4299     WHEN OTHERS THEN
4300     	BEGIN
4301 	    x_return_status := FND_API.G_RET_STS_ERROR;
4302 
4303             write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
4304             write_debug_and_log('- Customer Id: '||p_customer_id);
4305             write_debug_and_log('- Customer Site Id: '||p_site_use_id);
4306             write_debug_and_log('- Total Service charge: '||l_total_service_charge);
4307             write_debug_and_log('- Return Status: '||l_return_status);
4308             write_debug_and_log(SQLERRM);
4309 
4310             FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
4311             FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
4312             FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
4313             FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
4314             FND_MSG_PUB.ADD;
4315         END;
4316 
4317 END apply_service_charge;
4318 
4319 
4320  /*==============================================================
4321  | PROCEDURE  pay_multiple_invoices
4322  |
4323  | DESCRIPTION Used to make paymnets from iRec UI
4324  |
4325  | PARAMETERS  Lots
4326  |
4327  | KNOWN ISSUES
4328  |
4329  | NOTES
4330  | p_cc_bill_to_site_id value is sent as 0 when OIR_VERIFY_CREDIT_CARD_DETAILS profile is NONE or SECURITY_CODE for both New  Credit Cards
4331  | p_cc_bill_to_site_id value is sent as -1 when OIR_VERIFY_CREDIT_CARD_DETAILS is either BOTH or ADDRESS and for New Credit Card  Accounts
4332  | p_cc_bill_to_site_id value is sent as CC bill site id when OIR_VERIFY_CREDIT_CARD_DETAILS profile is either BOTH or ADDRESS for Saved Credit Cards
4333  |
4334  | MODIFICATION HISTORY
4335  | Date          Author       Description of Changes
4336  | 13-Jan-2003   krmenon      Created
4337  | 21-OCT-2004   vnb          Bug 3944029 - Modified pay_multiple_invoices to pass
4338  |							  correct site_use_id to other APIs
4339  | 03-NOV-2004   vnb          Bug 3335944 - One Time Credit Card Verification
4340  | 18-Oct-2005	 rsinthre     Bug 4673563 - Error making credit card payment
4341  | 14-Mar-2013   melapaku     Bug 16471455 - Payment Audit History Feature
4342  +==============================================================*/
4343  PROCEDURE pay_multiple_invoices(p_payment_amount      IN NUMBER,
4344                                 p_discount_amount     IN NUMBER,
4345                                 p_customer_id         IN NUMBER,
4346                                 p_site_use_id         IN NUMBER,
4347                                 p_account_number      IN VARCHAR2,
4348                                 p_expiration_date     IN DATE,
4349                                 p_account_holder_name IN VARCHAR2,
4350                                 p_account_type        IN VARCHAR2,
4351                                 p_payment_instrument  IN VARCHAR2,
4352                                 p_address_line1       IN VARCHAR2 default null,
4353                                 p_address_line2       IN VARCHAR2 default null,
4354                                 p_address_line3       IN VARCHAR2 default null,
4355                                 p_address_line4       IN VARCHAR2 default null, -- Added for Bug#14797865
4356                                 p_address_city        IN VARCHAR2 default null,
4357                                 p_address_county      IN VARCHAR2 default null,
4358                                 p_address_state       IN VARCHAR2 default null,
4359                                 p_address_country     IN VARCHAR2 default null,
4360                                 p_address_postalcode  IN VARCHAR2 default null,
4361                                 p_cvv2                IN NUMBER,
4362                                 p_bank_branch_id      IN NUMBER,
4363                                 p_receipt_date        IN DATE DEFAULT trunc(SYSDATE),
4364                                 p_new_account_flag    IN VARCHAR2 DEFAULT 'FALSE',
4365 					  p_receipt_site_id     IN NUMBER,
4366 				p_bank_id	      IN NUMBER,
4367 				p_card_brand	      IN VARCHAR2,
4368 				p_cc_bill_to_site_id  IN NUMBER,
4369 				p_single_use_flag     IN VARCHAR2 default 'N',
4370 				p_iban	        IN VARCHAR2,
4371 				p_routing_number      IN VARCHAR2,
4372 				p_instr_assign_id     IN NUMBER default 0,
4373                                 p_payment_audit_id    IN NUMBER, -- Added for Bug 16471455
4374 				p_bank_account_id     IN OUT NOCOPY NUMBER,
4375                                 p_cash_receipt_id     OUT NOCOPY NUMBER,
4376                                 p_cc_auth_code        OUT NOCOPY VARCHAR2,
4377                                 p_cc_auth_id          OUT NOCOPY NUMBER, -- Added for Bug 16471455
4378                                 p_status              OUT NOCOPY VARCHAR2,
4379                                 p_status_reason       OUT NOCOPY VARCHAR2, -- Added for Bug 16471455
4380                                 x_msg_count           OUT NOCOPY NUMBER,
4381                                 x_msg_data            OUT NOCOPY VARCHAR2
4382 
4383                                 ) IS
4384   -- =================================
4385   -- DECLARE ALL LOCAL VARIABLES HERE
4386   -- =================================
4387   l_receipt_currency_code       AR_CASH_RECEIPTS_ALL.CURRENCY_CODE%TYPE;
4388   l_receipt_exchange_rate       AR_CASH_RECEIPTS_ALL.EXCHANGE_RATE%TYPE;
4389   l_receipt_exchange_rate_type  AR_CASH_RECEIPTS_ALL.EXCHANGE_RATE_TYPE%TYPE;
4390   l_receipt_exchange_rate_date  DATE;
4391 
4392   l_invoice_exchange_rate       AR_PAYMENT_SCHEDULES_ALL.EXCHANGE_RATE%TYPE;
4393   l_receipt_method_id           AR_CASH_RECEIPTS_ALL.RECEIPT_METHOD_ID%TYPE;
4394   l_remit_bank_account_id       AR_CASH_RECEIPTS_ALL.REMIT_BANK_ACCT_USE_ID%TYPE;
4395   l_receipt_creation_status     VARCHAR2(80);
4396   l_site_use_id                 NUMBER(15);
4397   l_site_use_id_pay_instr       NUMBER(15); -- Added for Bug#14556872
4398   l_bank_account_id 	        NUMBER;
4399   l_bank_account_uses_id        NUMBER;
4400   l_cvv2                        iby_fndcpt_tx_extensions.instrument_security_code%TYPE;
4401 
4402   l_invoice_trx_number          AR_PAYMENT_SCHEDULES_ALL.TRX_NUMBER%TYPE;
4403   l_cr_id                       AR_CASH_RECEIPTS_ALL.CASH_RECEIPT_ID%TYPE;
4404   x_return_status               VARCHAR2(100);
4405   l_msg_count                   NUMBER;
4406   l_msg_data                    VARCHAR2(4000);
4407   x_auth_result                 IBY_FNDCPT_TRXN_PUB.AuthResult_rec_type;
4408   l_call_payment_processor      VARCHAR2(1);
4409   l_response_error_code         VARCHAR2(80);
4410   l_bank_branch_id	        CE_BANK_ACCOUNTS.BANK_BRANCH_ID%TYPE;
4411   l_apply_err_count             NUMBER;
4412   p_payment_schedule_id         NUMBER;
4413 
4414   l_create_credit_card		IBY_FNDCPT_SETUP_PUB.CreditCard_rec_type;
4415   l_result_rec_type		IBY_FNDCPT_COMMON_PUB.Result_rec_type;
4416   l_procedure_name VARCHAR2(30);
4417 
4418   l_debug_info	 	        VARCHAR2(200);
4419 
4420     l_payer_rec			IBY_FNDCPT_COMMON_PUB.PayerContext_rec_type;
4421     l_trxn_rec			IBY_FNDCPT_TRXN_PUB.TrxnExtension_rec_type;
4422     l_payee_rec         IBY_FNDCPT_TRXN_PUB.PayeeContext_rec_type;
4423     l_result_rec		IBY_FNDCPT_COMMON_PUB.Result_rec_type;
4424     l_payment_channel_code	IBY_FNDCPT_PMT_CHNNLS_B.PAYMENT_CHANNEL_CODE%TYPE;
4425 
4426     l_cc_location_rec		HZ_LOCATION_V2PUB.LOCATION_REC_TYPE;
4427     l_cc_bill_to_site_id	NUMBER;
4428 
4429     l_extn_id number;
4430     l_payer_party_id  NUMBER;
4431     l_auth_id         NUMBER; -- Added for Bug 16471455
4432    l_payment_server_order_num VARCHAR2(80);
4433        l_instr_assign_id number;
4434 
4435     l_cvv_use           VARCHAR2(100);
4436     l_billing_addr_use  VARCHAR2(100);
4437   CURSOR party_id_cur IS
4438     SELECT PARTY_ID FROM HZ_CUST_ACCOUNTS WHERE CUST_ACCOUNT_ID = p_customer_id;
4439 
4440     party_id_rec		party_id_cur%ROWTYPE;
4441 
4442     p_site_use_id_srvc_chrg NUMBER;
4443     l_home_country  			varchar2(10);
4444 
4445 BEGIN
4446   --Assign default values
4447 
4448   l_receipt_currency_code  := 'USD';
4449   l_call_payment_processor := FND_API.G_TRUE;
4450   l_apply_err_count        := 0;
4451   x_msg_count              := 0;
4452   x_msg_data               := '';
4453   l_procedure_name         := '.pay_multiple_invoices';
4454 
4455 
4456   fnd_log_repository.init;
4457 
4458    --------------------------------------------------------------------
4459   l_debug_info := 'In debug mode, log we have entered this procedure';
4460   --------------------------------------------------------------------
4461   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4462 	  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,
4463                  'Begin+');
4464 	  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,
4465                  'p_payment_amount ' ||p_payment_amount ||
4466                  'p_discount_amount ' ||p_discount_amount ||
4467                  'p_customer_id ' || p_customer_id ||
4468                  'p_site_use_id ' ||p_site_use_id ||
4469                  'p_account_number ' ||p_account_number ||
4470                  'p_expiration_date ' ||p_expiration_date ||
4471                  'p_account_holder_name ' ||p_account_holder_name ||
4472                  'p_account_type ' || p_account_type ||
4473                  'p_payment_instrument ' || p_payment_instrument ||
4474                  'p_bank_branch_id ' ||p_bank_branch_id ||
4475                  'p_new_account_flag ' ||p_new_account_flag ||
4476                  'p_receipt_date ' ||p_receipt_date ||
4477                  'p_receipt_site_id '||p_receipt_site_id ||
4478                  'p_bank_account_id ' ||p_bank_account_id ||
4479                  'p_single_use_flag ' ||p_single_use_flag ||
4480                  'p_cc_bill_to_site_id: '||p_cc_bill_to_site_id ||
4481                  'p_address_line1: '||p_address_line1 ||
4482                  'p_address_line2: '||p_address_line2 ||
4483                  'p_address_line3 '||p_address_line3 ||
4484                  'p_address_line4 '||p_address_line4 ||
4485                  'p_address_city: '||p_address_city ||
4486                  'p_address_country: '||p_address_country||
4487                  'p_payment_audit_id: '||p_payment_audit_id);
4488   end if;
4489  -- IF Customer Site Use Id is -1 then it is to be set as null
4490   IF ( p_site_use_id = -1 ) THEN
4491       -- Added for Bug#14556872
4492       l_site_use_id_pay_instr := NULL;
4493 -- Bug 12410542 when  system option - Require Billing location is enabled
4494 -- then Primary Bill To Site Id is passed  while creating the Receipt
4495 
4496 	IF arp_global.sysparam.site_required_flag = 'Y' THEN
4497 
4498   		BEGIN
4499                SELECT site_use.site_use_id into l_site_use_id
4500                FROM   hz_cust_site_uses site_use,
4501                       hz_cust_acct_sites acct_site
4502                WHERE  acct_site.cust_account_id   =  p_customer_id
4503                  AND  acct_site.status        = 'A'
4504                  AND  site_use.cust_acct_site_id  = acct_site.cust_acct_site_id
4505                  AND  site_use.site_use_code = nvl('BILL_TO',site_use.site_use_code)
4506                  AND  site_use.status        = 'A'
4507                  AND  site_use.primary_flag  = 'Y';
4508    		 EXCEPTION
4509       		when others then
4510         	l_site_use_id := NULL;
4511         	IF (PG_DEBUG = 'Y') THEN
4512           	arp_standard.debug('No primary bill to site exists ');
4513         	END IF;
4514   	END;
4515 
4516 	ELSE
4517 		l_site_use_id := NULL;
4518 	END IF;
4519 
4520   ELSE
4521     l_site_use_id := p_site_use_id;
4522     -- Added for Bug#14556872
4523     l_site_use_id_pay_instr := p_site_use_id;
4524   END IF;
4525 
4526 -- Added for bug 9683510
4527  IF(p_site_use_id is NULL AND (p_receipt_site_id IS NOT NULL OR  p_receipt_site_id <> -1)) THEN
4528 	l_site_use_id := p_receipt_site_id;
4529  END IF;
4530 
4531   IF p_cvv2 = 0 OR p_payment_instrument = 'BANK_ACCOUNT' THEN
4532    l_cvv2 := NULL;
4533      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4534 	  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,
4535                  'Since p_cvv2 is 0 or p_payment_instrument is BANK_ACCOUNT, setting l_cvv2 as null');
4536     end if;
4537   else
4538    l_cvv2 := p_cvv2;
4539    if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4540 	  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,
4541                  'Since p_cvv2 is not 0 and p_payment_instrument is not BANK_ACCOUNT, setting l_cvv2 as p_cvv2');
4542     end if;
4543   END IF;
4544 
4545 
4546   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4547 	  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,
4548                  'Calling get_payment_information');
4549   end if;
4550 
4551 
4552   ---------------------------------------------------------------------------
4553   l_debug_info := 'Get the Payment Schedule Id if there is only one invoice';
4554   ---------------------------------------------------------------------------
4555   BEGIN
4556     select payment_schedule_id into p_payment_schedule_id
4557     from AR_IREC_PAYMENT_LIST_GT
4558     where customer_id = p_customer_id
4559     and customer_site_use_id = nvl(l_site_use_id, customer_site_use_id);
4560     EXCEPTION
4561       when others then
4562         IF (PG_DEBUG = 'Y') THEN
4563           arp_standard.debug('There may be multiple invoices for payment');
4564         END IF;
4565   END;
4566 
4567   ---------------------------------------------------------------------------
4568   l_debug_info := 'Call get_payment_information';
4569   ---------------------------------------------------------------------------
4570 
4571   get_payment_information(
4572           p_customer_id             => p_customer_id,
4573           p_site_use_id             => l_site_use_id,
4574           p_payment_schedule_id     => p_payment_schedule_id,
4575           p_payment_instrument      => p_payment_instrument,
4576           p_trx_date                => trunc(p_receipt_date),
4577           p_currency_code           => l_receipt_currency_code,
4578           p_exchange_rate           => l_invoice_exchange_rate,
4579           p_receipt_method_id       => l_receipt_method_id,
4580           p_remit_bank_account_id   => l_remit_bank_account_id,
4581           p_receipt_creation_status => l_receipt_creation_status,
4582           p_trx_number              => l_invoice_trx_number,
4583 	  p_payment_channel_code    => l_payment_channel_code);
4584 
4585   --DEBUG
4586   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4587 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_rct_curr => ' || l_receipt_currency_code);
4588 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_rct_method_id => ' ||l_receipt_method_id );
4589 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_remit_bank_account_id => ' || l_Remit_bank_account_id);
4590 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_receipt_creation_status => ' || l_receipt_creation_status );
4591 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_site_use_id => ' || l_site_use_id );
4592 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_receipt_currency_code => ' || l_receipt_currency_code);
4593   end if;
4594 
4595  IF p_payment_instrument = 'CREDIT_CARD' THEN
4596 	  get_payment_channel_attribs
4597 	  (
4598 		  p_channel_code 	   => 'CREDIT_CARD',
4599 		  x_return_status    => x_return_status,
4600 		  x_cvv_use 	       => l_cvv_use,
4601 		  x_billing_addr_use => l_billing_addr_use,
4602 		  x_msg_count 	     => x_msg_count,
4603 		  x_msg_data 	       => x_msg_data
4604 	  );
4605 	    IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
4606 
4607 		  if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4608 			  fnd_log.string(fnd_log.LEVEL_STATEMENT,
4609 				  G_PKG_NAME||l_procedure_name,
4610 				  'ERROR IN GETTING IBY PAYMENT CHANNEL ATTRIBUTES');
4611 		  end if;
4612 
4613 		  x_return_status := FND_API.G_RET_STS_ERROR;
4614 		  write_error_messages(x_msg_data, x_msg_count);
4615 		  RETURN;
4616     	   END IF;
4617 
4618 END IF;
4619 
4620   -- If the payment instrument is a bank account then
4621   -- set the bank branch id
4622   IF (p_payment_instrument = 'BANK_ACCOUNT') THEN
4623       l_bank_branch_id := p_bank_branch_id;
4624   ELSE
4625       l_bank_branch_id := null;
4626   END IF;
4627 
4628   --KRMENON DEBUG
4629 IF (l_receipt_currency_code IS NULL OR '' = l_receipt_currency_code) THEN
4630     --Bug2925392: Get Currency from AR_IREC_PAYMENT_LIST_GT. All records will have same currency.
4631     --Bug # 3467287 - The Global Temp table must be striped by Customer and Customer Site.
4632     ---------------------------------------------------------------------------
4633     l_debug_info := 'If the currency code is not set yet, get the currency code';
4634     ---------------------------------------------------------------------------
4635     BEGIN
4636       select currency_code into l_receipt_currency_code
4637       from AR_IREC_PAYMENT_LIST_GT
4638       where customer_id = p_customer_id
4639       and customer_site_use_id = nvl(l_site_use_id, customer_site_use_id);
4640       --group by currency_code;
4641       EXCEPTION
4642         when others then
4643           IF (PG_DEBUG = 'Y') THEN
4644             arp_standard.debug('Error getting currency code');
4645           END IF;
4646     END;
4647   END IF;
4648 
4649   SAVEPOINT ARI_Create_Cash_PVT;
4650 
4651 	OPEN party_id_cur;
4652 	FETCH party_id_cur INTO party_id_rec;
4653 	IF(party_id_cur%FOUND) THEN
4654 		l_payer_party_id := party_id_rec.party_id;
4655 	END IF;
4656 	CLOSE party_id_cur;
4657 
4658 	l_cc_bill_to_site_id			:= p_cc_bill_to_site_id;
4659 	l_cc_location_rec.country		:= p_address_country;
4660 	l_cc_location_rec.address1		:= p_address_line1;
4661 	l_cc_location_rec.address2		:= p_address_line2;
4662 	l_cc_location_rec.address3		:= p_address_line3;
4663 	l_cc_location_rec.city			:= p_address_city;
4664 	l_cc_location_rec.postal_code		:= p_address_postalcode;
4665 	l_cc_location_rec.state			:= p_address_state;
4666 	l_cc_location_rec.county		:= p_address_county;
4667 	l_cc_location_rec.created_by_module	:= 'ARI';
4668         -- Bug#14797865 : Removed the condition if billing_addr_use is required
4669 	IF(p_payment_instrument = 'CREDIT_CARD') and l_cc_bill_to_site_id = -1 THEN
4670            create_cc_bill_to_site(
4671 			p_init_msg_list		=> FND_API.G_FALSE,
4672 			p_commit		=> FND_API.G_FALSE,
4673 			p_cc_location_rec	=> l_cc_location_rec,
4674 			p_payer_party_id	=> l_payer_party_id,
4675 			x_cc_bill_to_site_id	=> l_cc_bill_to_site_id,
4676 			x_return_status		=> x_return_status,
4677 			x_msg_count		=> l_msg_count,
4678 			x_msg_data		=> l_msg_data);
4679 
4680 		 IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
4681 
4682 		      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4683 			      fnd_log.string(fnd_log.LEVEL_STATEMENT,
4684 				      G_PKG_NAME||l_procedure_name,
4685 				      'ERROR IN CREATING PAYMENT INSTRUMENT');
4686 		      end if;
4687 
4688 		      p_status := FND_API.G_RET_STS_ERROR;
4689 		      ROLLBACK TO ARI_Create_Cash_PVT;
4690 		      write_error_messages(x_msg_data, x_msg_count);
4691 		      RETURN;
4692 		 END IF;
4693         END IF;	--p_payment_instrument
4694 
4695 
4696 
4697 
4698   IF ( p_new_account_flag = 'TRUE' ) THEN
4699   -- Now create a payment instrument
4700     ---------------------------------------------------------------------------
4701     l_debug_info := 'Create a payment instrument';
4702     ---------------------------------------------------------------------------
4703     create_payment_instrument ( p_customer_id         => p_customer_id,
4704 				p_customer_site_id    => l_site_use_id_pay_instr, -- Modified for Bug#14556872
4705 				p_account_number      => p_account_number,
4706 				p_payer_party_id      => l_payer_party_id,
4707 				p_expiration_date     => p_expiration_date,
4708 				p_account_holder_name => p_account_holder_name,
4709 				p_account_type        => p_account_type,
4710 				p_payment_instrument  => p_payment_instrument,
4711 				p_address_country     => p_address_country,
4712 				p_bank_branch_id      => p_bank_branch_id,
4713 				p_receipt_curr_code   => l_receipt_currency_code,
4714 				p_status              => x_return_status,
4715 				x_msg_count           => l_msg_count,
4716 				x_msg_data            => l_msg_data,
4717 				p_bank_id	      => p_bank_id,
4718 				p_card_brand	      => p_card_brand,
4719 				p_cc_bill_to_site_id  => l_cc_bill_to_site_id,
4720 				p_single_use_flag     => p_single_use_flag,
4721 				p_iban	        => p_iban,
4722 				p_routing_number     => p_routing_number,
4723 				p_assignment_id       => l_instr_assign_id,
4724 				p_bank_account_id   => l_bank_account_id) ;
4725     -- Check if the payment instrument was created successfully
4726     IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
4727       if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4728 	      fnd_log.string(fnd_log.LEVEL_STATEMENT,
4729                       G_PKG_NAME||l_procedure_name,
4730                       'ERROR IN CREATING PAYMENT INSTRUMENT');
4731       end if;
4732 
4733       p_status := FND_API.G_RET_STS_ERROR;
4734       write_error_messages(x_msg_data, x_msg_count);
4735       ROLLBACK TO ARI_Create_Cash_PVT;
4736       RETURN;
4737     ELSE
4738     	-- When payment instrument is created successfully
4739     	IF ( ARI_UTILITIES.save_payment_instrument_info(p_customer_id, l_site_use_id) ) THEN
4740 	    -- If iRec set up is not to save CC then, if update of CC fails we should roll back even create.
4741 	    -- So here the commit flag is controlled by that profile
4742   	if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4743 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'ARI_UTILITIES.save_payment_instrument_info is true');
4744 	end if;
4745 	    commit;
4746  	END IF;
4747     END IF;
4748 
4749   ELSE
4750     l_bank_account_id := p_bank_account_id;
4751     l_instr_assign_id := p_instr_assign_id;
4752   END IF;
4753 
4754 
4755   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4756 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Done with bank Creation .....');
4757 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Expiration date for bank account: ' || p_expiration_date);
4758 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Bank Acct Id: '||l_bank_account_id);
4759 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Bank Acct Uses Id: '||l_bank_account_uses_id);
4760   end if;
4761 
4762   -----------------------------------------------------------------------------------------
4763   l_debug_info := 'Call public IBY API - create TRANSACTION EXTENSION';
4764   -----------------------------------------------------------------------------------------
4765         SAVEPOINT ARI_Create_Trans_Extn_PVT;
4766         l_payer_rec.payment_function:='CUSTOMER_PAYMENT';
4767         l_payer_rec.Cust_Account_Id:=p_customer_id;
4768         l_payer_rec.Account_Site_Id:=l_site_use_id;
4769         l_payer_rec.PARTY_ID := l_payer_party_id;
4770         if l_site_use_id is not null then
4771 	        l_payer_rec.org_type:= 'OPERATING_UNIT';
4772 	        l_payer_rec.org_id:= mo_global.get_current_org_id;
4773         else
4774              l_payer_rec.org_type:= NULL;
4775 	        l_payer_rec.org_id:= NULL;
4776         end if;
4777 	l_payee_rec.org_type := 'OPERATING_UNIT';
4778 	l_payee_rec.org_id := mo_global.get_current_org_id ;
4779 
4780         select 'ARI_'||ar_payment_server_ord_num_s.nextval
4781         into l_payment_server_order_num
4782         from dual;
4783 
4784         l_trxn_rec.Originating_Application_Id:=222;
4785         l_trxn_rec.Order_Id:=l_payment_server_order_num;
4786         l_trxn_rec.Instrument_Security_Code :=l_cvv2;
4787         -- Debug message
4788         write_debug_and_log('l_payment_channel_code'||l_payment_channel_code);
4789         write_debug_and_log('l_instr_assign_id'||l_instr_assign_id);
4790         write_debug_and_log('l_payment_server_order_num'||l_payment_server_order_num);
4791         IBY_FNDCPT_TRXN_PUB.Create_Transaction_Extension
4792                           (
4793 			    p_api_version	=>1.0,
4794 			    p_init_msg_list	=>FND_API.G_TRUE,
4795 			--    p_commit		=> FND_API.G_FALSE, -- bug 9683510
4796          		    x_return_status	=>x_return_status,
4797 		            x_msg_count		=>l_msg_count,
4798 		            x_msg_data		=> l_msg_data,
4799 			    p_payer		=> l_payer_rec,
4800 			    p_pmt_channel	=> l_payment_channel_code,
4801 			    p_instr_assignment	=>l_instr_assign_id,
4802 			    p_trxn_attribs	=> l_trxn_rec,
4803 			    x_entity_id		=> l_extn_id,
4804 			    x_response		=> l_result_rec);
4805 
4806       IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
4807 	      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4808 		      fnd_log.string(fnd_log.LEVEL_STATEMENT,
4809 			      G_PKG_NAME||l_procedure_name,
4810 			      'ERROR IN CREATING TRANSACTION EXTENSION');
4811 		  fnd_log.string(fnd_log.LEVEL_STATEMENT,
4812 			      G_PKG_NAME||l_procedure_name,l_result_rec.result_code);
4813 	      end if;
4814               x_msg_count := x_msg_count + l_msg_count;
4815 	      if (l_msg_data is not null) then
4816 		    x_msg_data  := x_msg_data || l_msg_data || '*';
4817 	      end if;
4818 
4819 	      x_msg_data := x_msg_data || '*' || l_result_rec.result_code;
4820 	      p_status := FND_API.G_RET_STS_ERROR;
4821 	      ROLLBACK TO ARI_Create_Trans_Extn_PVT;
4822 	      write_error_messages(x_msg_data, x_msg_count);
4823 	      RETURN;
4824     END IF;
4825 
4826   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4827 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Done with create trxn extn.....');
4828 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_extn_id : ' ||l_extn_id);
4829   end if;
4830   write_debug_and_log('l_receipt_currency_code : ' || l_receipt_currency_code);
4831   write_debug_and_log('l_invoice_exchange_rate : ' || to_char(l_invoice_exchange_rate));
4832   write_debug_and_log('l_extn_id : ' || l_extn_id);
4833 
4834   ---------------------------------------------------------------------------
4835   l_debug_info := 'Call get_exchange_rate';
4836   ---------------------------------------------------------------------------
4837   get_exchange_rate( p_trx_currency_code      => l_receipt_currency_code,
4838                      p_trx_exchange_rate      => l_invoice_exchange_rate,
4839                      p_def_exchange_rate_date => trunc(SYSDATE),
4840                      p_exchange_rate          => l_receipt_exchange_rate,
4841                      p_exchange_rate_type     => l_receipt_exchange_rate_type,
4842                      p_exchange_rate_date     => l_receipt_exchange_rate_date);
4843 
4844 if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4845 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Done with getexchangerate.....');
4846 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_receipt_currency_code : ' || l_receipt_currency_code);
4847 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_receipt_exchange_rate : ' || to_char(l_invoice_exchange_rate));
4848   end if;
4849 
4850   -- for demo purposes only: if fnd function ARIPAYMENTDEMOMODE
4851   -- is added to the menu of the current responsibility, supress
4852   -- call to iPayment after the receipt creation.
4853 
4854  /*------------------------------------------------------+
4855   | For credit cards iPayment is called to authorize and |
4856   | capture the payment. For bank account transfers      |
4857   | iPayment is called in receivables remittance process |
4858   +------------------------------------------------------*/
4859   IF (fnd_function.test('ARIPAYMENTDEMOMODE')
4860      OR p_payment_instrument = 'BANK_ACCOUNT') THEN /* J Rautiainen ACH Implementation */
4861     l_call_payment_processor := FND_API.G_FALSE;
4862   ELSE
4863     l_call_payment_processor := FND_API.G_TRUE;
4864   END IF;
4865 
4866 -- commented for bug 9683510
4867 /*  IF (p_receipt_site_id <> -1) THEN
4868     l_site_use_id := p_receipt_site_id;
4869   END IF;  */
4870 
4871   -- Now create a cash receipt
4872   ---------------------------------------------------------------------------
4873   l_debug_info := 'Create a cash receipt: Call create_receipt';
4874   ---------------------------------------------------------------------------
4875   /*------------------------------------+
4876    | Standard start of API savepoint    |
4877    +------------------------------------*/
4878  SAVEPOINT ARI_Create_Receipt_PVT;  -- added for bug 11654712
4879 
4880   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4881 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'calling  create_receipt api ....');
4882   end if;
4883 
4884   create_receipt (p_payment_amount		=> p_payment_amount,
4885                   p_customer_id			=> p_customer_id,
4886                   p_site_use_id			=> l_site_use_id,
4887                   p_bank_account_id		=> l_bank_account_id,
4888                   p_receipt_date		=> trunc(p_receipt_date),
4889                   p_receipt_method_id		=> l_receipt_method_id,
4890                   p_receipt_currency_code	=> l_receipt_currency_code,
4891                   p_receipt_exchange_rate	=> l_receipt_exchange_rate,
4892                   p_receipt_exchange_rate_type	=> l_receipt_exchange_rate_type,
4893                   p_receipt_exchange_rate_date	=> l_receipt_exchange_rate_date,
4894                   p_trxn_extn_id		=> l_extn_id,
4895                   p_cash_receipt_id		=> p_cash_receipt_id,
4896                   p_status			=> x_return_status,
4897                   x_msg_count			=> l_msg_count,
4898                   x_msg_data			=> l_msg_data
4899                  );
4900 
4901   arp_standard.debug('create receipt -->  ' || x_return_status || 'receipt id --> ' || p_cash_receipt_id);
4902   arp_standard.debug('X_RETURN_STATUS=>'||X_RETURN_STATUS);
4903 
4904   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4905 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Done with receipt creation ....');
4906 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Return Status: '||x_return_status);
4907 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Cash Receipt Id: '||to_char(p_cash_receipt_id));
4908 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Bank Account Id: '||to_char(p_bank_account_id));
4909   end if;
4910 
4911   -- Check for error in receipt creation. If it is an error
4912   -- the rollback and return.
4913   IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS OR p_cash_receipt_id IS NULL ) THEN
4914       --Bug 3672530 - Error handling
4915 	    p_status := FND_API.G_RET_STS_ERROR;
4916             p_status_reason := G_CREATION_FAILED;
4917 	    ROLLBACK TO ARI_Create_Receipt_PVT;
4918             write_error_messages(x_msg_data, x_msg_count);
4919       RETURN;
4920   END IF;
4921 
4922   p_site_use_id_srvc_chrg := l_site_use_id;
4923 -- commented for bug 9683510
4924 /*  IF (p_receipt_site_id <> -1) THEN
4925     p_site_use_id_srvc_chrg := p_receipt_site_id;
4926   END IF; */
4927 
4928   -- If service charge has been enabled, adjust the invoice
4929   -- with the service charge
4930   -- Bug 3886652 - Customer Id and Customer Site Use Id added as params to ARI_CONFIG.is_service_charge_enabled
4931   IF ( ARI_UTILITIES.is_service_charge_enabled(p_customer_id, p_site_use_id_srvc_chrg) ) THEN
4932     ---------------------------------------------------------------------------------
4933     l_debug_info := 'Service charge enabled: adjust the invoice with service charge';
4934     ---------------------------------------------------------------------------------
4935     apply_service_charge(p_customer_id, null, x_return_status);  -- Bug 9596552
4936     IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
4937       --Bug 3672530 - Error handling
4938       p_status := FND_API.G_RET_STS_ERROR;
4939       p_status_reason := G_SVC_FAILED; -- Added for Bug 16471455
4940       ROLLBACK TO ARI_Create_Receipt_PVT;
4941       write_error_messages(x_msg_data, x_msg_count);
4942       RETURN;
4943     END IF;
4944   END IF;
4945 
4946    --Bug 8239939 , 6026781: All locations project. Reset the site_use_id to actual value
4947  --when navigating from All Locations or My All Locations
4948 -- commented for bug 9683510
4949 /*  IF (p_receipt_site_id <> -1) THEN
4950     l_site_use_id := p_site_use_id;
4951   END IF; */
4952 
4953 
4954   -- If the cash receipt has been created successfully then
4955   -- apply the receipt to the transactions selected
4956   ---------------------------------------------------------------------------------
4957   l_debug_info := 'Apply the receipt to the transactions selected:call apply_cash';
4958   ---------------------------------------------------------------------------------
4959   apply_cash( p_customer_id     => p_customer_id,
4960               p_site_use_id     => p_site_use_id, -- Modified for Bug#14646910, we don't require l_site_use_id to be passed while applying the receipt to the transactions
4961               p_cash_receipt_id => p_cash_receipt_id,
4962               p_return_status   => x_return_status,
4963               p_apply_err_count => l_apply_err_count,
4964               x_msg_count       => l_msg_count,
4965               x_msg_data        => l_msg_data
4966             );
4967 
4968   -- Check if any of the applications errored out
4969   -- If so the rollback everything and return
4970   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
4971 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Apply Cash call ended with Status : '||x_return_status);
4972 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_apply_err_count : '||l_apply_err_count);
4973 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'x_msg_data : '|| x_msg_data);
4974   end if;
4975 
4976   IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
4977       p_status := FND_API.G_RET_STS_ERROR;
4978       p_status_reason := G_APP_FAILED; -- Added for Bug 16471455
4979 	    ROLLBACK TO ARI_Create_Receipt_PVT;
4980 	    if (l_apply_err_count > 0) then
4981 		   x_msg_count := x_msg_count + l_msg_count;
4982 	    end if;
4983 	    if (l_msg_data is not null) then
4984 		    x_msg_data  := x_msg_data || l_msg_data || '*';
4985 	    end if;
4986 	    write_error_messages(x_msg_data, x_msg_count);
4987 	    RETURN;
4988   END IF;
4989 
4990   -- Seems like all is fine. So we shall go ahead and
4991   -- do the final task of capturing the CC payment
4992   -- only if it is a credit card payment
4993   IF (p_payment_instrument = 'CREDIT_CARD' AND
4994       l_call_payment_processor = FND_API.G_TRUE) THEN
4995 
4996       BEGIN
4997             select pr.home_country into l_home_country
4998             from ar_cash_receipts_all cr,
4999             ce_bank_acct_uses bau,
5000             ce_bank_accounts cba,
5001             hz_parties bank,
5002             hz_organization_profiles pr
5003             where cr.cash_receipt_id = p_cash_receipt_id
5004             AND    cr.remit_bank_acct_use_id = bau.bank_acct_use_id
5005             AND    bau.bank_account_id = cba.bank_account_id
5006             AND    cba.bank_id = bank.party_id
5007             AND    bank.party_id = pr.party_id;
5008       EXCEPTION
5009             when others then
5010               IF (PG_DEBUG = 'Y') THEN
5011                 arp_standard.debug('Error getting Home Country Code..');
5012                 l_home_country := null;
5013               END IF;
5014       END;
5015 
5016     if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
5017         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Got home country code..'||l_home_country);
5018 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Calling process_payment .....');
5019     end if;
5020 
5021     l_payee_rec.Int_Bank_Country_Code := l_home_country;
5022     --------------------------------------------------------------------
5023     l_debug_info := 'Capture Credit Card payment';
5024     --------------------------------------------------------------------
5025     process_payment(p_cash_receipt_id     => p_cash_receipt_id,
5026                     p_payer_rec		  => l_payer_rec,
5027                     p_payee_rec           => l_payee_rec,
5028                     p_called_from         => 'IREC',
5029                     p_response_error_code => l_response_error_code,
5030                     x_msg_count           => l_msg_count,
5031                     x_msg_data            => l_msg_data,
5032                     x_return_status       => x_return_status,
5033 		    p_cc_auth_code        => p_cc_auth_code,
5034                     x_auth_result         => x_auth_result);
5035    l_auth_id := x_auth_result.Auth_Id;
5036    if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
5037 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Process Payment ended with Status : '||x_return_status);
5038 	fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Response Code: '|| l_response_error_code);
5039         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_auth_id: '|| l_auth_id);
5040     end if;
5041     -- If the payment processor call fails, then we need to rollback all the changes
5042     -- made in the create() and apply() routines also.
5043     IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5044      x_msg_count := x_msg_count + l_msg_count;
5045 	     if (l_msg_data is not null) then
5046 		      x_msg_data  := x_msg_data || l_msg_data || '*';
5047 	     end if;
5048        --   x_msg_data := x_msg_data || '*' || l_result_rec.result_code;  --  bug 8353477
5049        --Bug 3672530 - Error handling
5050        p_status := FND_API.G_RET_STS_ERROR;
5051        p_status_reason := G_CC_AUTH_FAILED; -- Added for Bug 16471455
5052        ROLLBACK TO ARI_Create_Cash_PVT;
5053        write_error_messages(x_msg_data, x_msg_count);
5054        RETURN; -- exit back to caller
5055     END IF;
5056   END IF; -- END PROCESS_PAYMENT CALL
5057   -- Now that we have successfully captured the payment
5058   -- erase the CC info if setup says not to store this
5059   -- info
5060   -- Bug 3886652 - Customer and Customer Site added to ARI_CONFIG APIs
5061   --               to add flexibility in configuration.
5062   IF NOT ( ARI_UTILITIES.save_payment_instrument_info(p_customer_id, p_site_use_id) ) THEN
5063 
5064     ---------------------------------------------------------------------------------------------------------
5065     l_debug_info := 'Payment instrument information not to be stored, erase the CC information after payment';
5066     ---------------------------------------------------------------------------------------------------------
5067           l_create_credit_card.Card_Id                   := l_bank_account_id;
5068 	  l_create_credit_card.Active_Flag               := 'N';
5069 	  l_create_credit_card.Inactive_Date             := TRUNC(SYSDATE - 1);
5070           l_create_credit_card.single_use_flag           := 'Y';
5071 
5072 	if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
5073 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Before Calling  IBY_FNDCPT_SETUP_PUB.Update_Card .....');
5074 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_create_credit_card.Card_Id : ' || l_create_credit_card.Card_Id);
5075 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_create_credit_card.Active_Flag : '||l_create_credit_card.Active_Flag);
5076 		fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_create_credit_card.single_use_flag : '||l_create_credit_card.single_use_flag);
5077 	end if;
5078 
5079 	IBY_FNDCPT_SETUP_PUB.Update_Card
5080             (
5081             p_api_version      => 1.0,
5082             p_init_msg_list    => FND_API.G_TRUE,
5083             p_commit           => FND_API.G_FALSE,
5084             x_return_status    => x_return_status,
5085             x_msg_count        => l_msg_count,
5086             x_msg_data         => l_msg_data,
5087             p_card_instrument  => l_create_credit_card,
5088             x_response         => l_result_rec_type
5089             );
5090 
5091 	IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
5092 	 p_status := FND_API.G_RET_STS_ERROR;
5093 	 x_msg_count := x_msg_count + l_msg_count;
5094 	 if (l_msg_data is not null) then
5095 		    x_msg_data  := x_msg_data || l_msg_data || '*';
5096 	 end if;
5097 	 x_msg_data := x_msg_data || '*' || l_result_rec.result_code;
5098 	 ROLLBACK TO ARI_Create_Receipt_PVT;
5099 	 write_error_messages(x_msg_data, x_msg_count);
5100 	 RETURN;
5101 	END IF;
5102   ELSE
5103  	IF ( p_payment_instrument = 'CREDIT_CARD' ) THEN
5104 		l_create_credit_card.Card_Id                   := l_bank_account_id;
5105                 l_create_credit_card.single_use_flag           := p_single_use_flag;
5106                 if(p_single_use_flag = 'Y') THEN
5107                    l_create_credit_card.Active_Flag            := 'N';
5108                    l_create_credit_card.Inactive_Date          := TRUNC(SYSDATE - 1); -- Added for Bug#14798065
5109                 end if;
5110                 l_create_credit_card.Card_Holder_Name          := p_account_holder_name;
5111 
5112       -- Bug#14797865 : Removed the condition if billing_addr_use is required
5113       IF(l_cc_bill_to_site_id <> 0 AND l_cc_bill_to_site_id <> -1) THEN
5114         l_create_credit_card.Billing_Address_Id        := l_cc_bill_to_site_id;
5115       END IF;
5116        if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
5117 		  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Inside Else,Save payment instr set to yes..before update CC');
5118 		  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_create_credit_card.Card_Id : ' || l_create_credit_card.Card_Id);
5119 		  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_create_credit_card.Active_Flag : '||l_create_credit_card.Active_Flag);
5120 		  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_create_credit_card.single_use_flag : '||l_create_credit_card.single_use_flag);
5121       fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'l_create_credit_card.Inactive_Date: '||l_create_credit_card.Inactive_Date);
5122 	  end if;
5123 
5124 		IBY_FNDCPT_SETUP_PUB.Update_Card
5125 		(
5126 			p_api_version      => 1.0,
5127 			p_init_msg_list    => FND_API.G_TRUE,
5128 			p_commit           => FND_API.G_FALSE,
5129 			x_return_status    => x_return_status,
5130 			x_msg_count        => l_msg_count,
5131 			x_msg_data         => l_msg_data,
5132 			p_card_instrument  => l_create_credit_card,
5133 			x_response         => l_result_rec_type
5134 		);
5135 
5136 	        IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
5137 		        p_status := FND_API.G_RET_STS_ERROR;
5138 		        x_msg_count := x_msg_count + l_msg_count;
5139 		        if (l_msg_data is not null) then
5140 			            x_msg_data  := x_msg_data || l_msg_data || '*';
5141 		        end if;
5142 		        x_msg_data := x_msg_data || '*' || l_result_rec.result_code;
5143 		        ROLLBACK TO ARI_Create_Cash_PVT;
5144 		        write_error_messages(x_msg_data, x_msg_count);
5145 		        RETURN;
5146 		END IF;
5147 	END IF;
5148 
5149   END IF;
5150 
5151 SAVEPOINT ARI_Update_CC_Bill_To_Site_PVT;
5152    IF p_cc_bill_to_site_id > 0 THEN
5153    ---------------------------------------------------------------------------------------------------------
5154     l_debug_info := 'CC billing site update required';
5155     ---------------------------------------------------------------------------------------------------------
5156 	   update_cc_bill_to_site(
5157 			p_cc_location_rec	=> l_cc_location_rec,
5158 			x_cc_bill_to_site_id	=> p_cc_bill_to_site_id ,
5159 			x_return_status		=> x_return_status,
5160 			x_msg_count		=> l_msg_count,
5161 			x_msg_data		=> l_msg_data);
5162 
5163 
5164 	  IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
5165 		p_status := FND_API.G_RET_STS_ERROR;
5166 		x_msg_count := x_msg_count + l_msg_count;
5167 		if (l_msg_data is not null) then
5168 			    x_msg_data  := x_msg_data || l_msg_data || '*';
5169 		end if;
5170 		x_msg_data := x_msg_data || '*' || l_result_rec.result_code;
5171 		ROLLBACK TO ARI_Update_CC_Bill_To_Site_PVT;
5172 		write_error_messages(x_msg_data, x_msg_count);
5173 		RETURN;
5174 	END IF;
5175 
5176    END IF;
5177 
5178   p_status := FND_API.G_RET_STS_SUCCESS;
5179 
5180   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
5181 	  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,
5182                  'End-');
5183   end if;
5184 
5185 EXCEPTION
5186     WHEN OTHERS THEN
5187       write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
5188       write_debug_and_log('- Customer Id: '||p_customer_id);
5189       write_debug_and_log('- Customer Site Id: '||p_site_use_id);
5190       write_debug_and_log('- Cash Receipt Id: '||p_cash_receipt_id);
5191       write_debug_and_log('- Return Status: '||p_status);
5192       write_debug_and_log('ERROR =>'|| SQLERRM);
5193 
5194       FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
5195       FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
5196       FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
5197       FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
5198       FND_MSG_PUB.ADD;
5199 
5200       p_status := FND_API.G_RET_STS_ERROR;
5201       write_error_messages(x_msg_data, x_msg_count);
5202 
5203 END pay_multiple_invoices;
5204 
5205 
5206 
5207 /*==============================================================
5208  | PROCEDURE process_payment
5209  |
5210  | DESCRIPTION
5211  |
5212  | PARAMETERS
5213  |
5214  | KNOWN ISSUES
5215  |
5216  | NOTES
5217  |   This procedure is the same as the on in the ar_receipt_api_pub.
5218  |   It was duplicated here in order to avoid exposing the api as a
5219  |   public api.
5220  |
5221  | MODIFICATION HISTORY
5222  | Date          Author       Description of Changes
5223  | 13-Jan-2003   krmenon      Created
5224  | 25-Feb-2004   vnb          Modified to add 'org_id' to rct_info
5225  |                            cursor,to be passed onto iPayment API
5226  | 07-Oct-2004   vnb          Bug 3335944 - One Time Credit Card Verification
5227  | 14-Mar-2013   melapaku     Bug16471455 - Payment Audit History
5228  +==============================================================*/
5229 PROCEDURE process_payment(
5230 	        p_cash_receipt_id     IN  NUMBER,
5231 	        p_payer_rec           IN  IBY_FNDCPT_COMMON_PUB.PayerContext_rec_type,
5232 	        P_payee_rec           IN  IBY_FNDCPT_TRXN_PUB.PayeeContext_rec_type,
5233                 p_called_from         IN  VARCHAR2,
5234                 p_response_error_code OUT NOCOPY VARCHAR2,
5235                 x_msg_count           OUT NOCOPY NUMBER,
5236                 x_msg_data            OUT NOCOPY VARCHAR2,
5237 	        x_return_status       OUT NOCOPY VARCHAR2,
5238 		p_cc_auth_code        OUT NOCOPY VARCHAR2,
5239                 x_auth_result         OUT NOCOPY IBY_FNDCPT_TRXN_PUB.AuthResult_rec_type) IS
5240 
5241   CURSOR rct_info_cur IS
5242      SELECT cr.receipt_number,
5243 	    cr.amount,
5244             cr.currency_code,
5245             rc.creation_status,
5246             cr.org_id,cr.payment_trxn_extension_id,
5247             cr.receipt_method_id
5248      FROM   ar_cash_receipts cr,
5249             ar_receipt_methods rm,
5250 	    ar_receipt_classes rc
5251      WHERE  cr.cash_receipt_id = p_cash_receipt_id
5252        AND  cr.receipt_method_id = rm.receipt_method_id
5253        and  rm.receipt_class_id = rc.receipt_class_id;
5254 
5255 
5256   rct_info rct_info_cur%ROWTYPE;
5257 
5258   l_cr_rec ar_cash_receipts%ROWTYPE;
5259 
5260 
5261 
5262 l_auth_rec        IBY_FNDCPT_TRXN_PUB.AuthAttribs_rec_type;
5263 l_amount_rec      IBY_FNDCPT_TRXN_PUB.Amount_rec_type;
5264 x_response	  IBY_FNDCPT_COMMON_PUB.Result_rec_type;
5265 
5266 l_payment_trxn_extension_id number;
5267 
5268   l_action VARCHAR2(80);
5269 
5270   l_return_status VARCHAR2(1);
5271   l_msg_count NUMBER;
5272   l_msg_data  VARCHAR2(2000);
5273   l_procedure_name VARCHAR2(30);
5274   l_debug_info	   VARCHAR2(200);
5275 
5276 BEGIN
5277   --Assign default values
5278   l_return_status  := FND_API.G_RET_STS_SUCCESS;
5279   l_procedure_name := '.process_payment';
5280 
5281   arp_standard.debug('Entering credit card processing...'||p_cash_receipt_id);
5282   ---------------------------------------------------------------------------------
5283   l_debug_info := 'Entering credit card processing';
5284   ---------------------------------------------------------------------------------
5285   OPEN rct_info_cur;
5286   FETCH rct_info_cur INTO rct_info;
5287 
5288   IF rct_info_cur%FOUND THEN
5289         ---------------------------------------------------------------------------------
5290         l_debug_info := 'This is a credit card account - determining if capture is necessary';
5291         ---------------------------------------------------------------------------------
5292         write_debug_and_log('l_debug_info');
5293 
5294         -- determine whether to AUTHORIZE only or to
5295         -- CAPTURE and AUTHORIZE in one step.  This is
5296         -- dependent on the receipt creation status, i.e.,
5297         -- if the receipt is created as remitted or cleared, the
5298         -- funds need to be authorized and captured.  If the
5299         -- receipt is confirmed, the remittance process will
5300         -- handle the capture and at this time we'll only
5301         -- authorize the charges to the credit card.
5302 
5303         if rct_info.creation_status IN ('REMITTED', 'CLEARED') THEN
5304           l_action := 'AUTHANDCAPTURE';
5305         elsif rct_info.creation_status = 'CONFIRMED' THEN
5306           l_action := 'AUTHONLY';
5307         else
5308           arp_standard.debug('ERROR: Creation status is ' || rct_info.creation_status);
5309           FND_MESSAGE.set_name('AR', 'AR_PAY_PROCESS_INVALID_STATUS');
5310           FND_MSG_PUB.Add;
5311 
5312           x_return_status := FND_API.G_RET_STS_ERROR;  -- should never happen
5313           RETURN;
5314         end if;
5315         l_payment_trxn_extension_id:= rct_info.payment_trxn_extension_id;
5316         -- Step 1: (always performed):
5317         -- authorize credit card charge
5318 
5319         ---------------------------------------------------------------------------------
5320         l_debug_info := 'Authorize credit card charge: set auth record';
5321         ---------------------------------------------------------------------------------
5322 
5323      l_auth_rec.Memo := NULL;
5324      l_auth_rec.Order_Medium := NULL;
5325      l_auth_rec.ShipFrom_SiteUse_Id  := NULL;
5326      l_auth_rec.ShipFrom_PostalCode := NULL;
5327      l_auth_rec.ShipTo_SiteUse_Id  := NULL;
5328      l_auth_rec.ShipTo_PostalCode := NULL;
5329      l_auth_rec.RiskEval_Enable_Flag  := NULL;
5330 
5331      l_amount_rec.Value     := rct_info.amount;
5332      l_amount_rec.Currency_Code := rct_info.currency_code;
5333 
5334       /*Bug 8263633 pass receipt method id as per IBY requirement*/
5335       l_auth_rec.receipt_method_id := rct_info.receipt_method_id;
5336 
5337         -- call to iPayment API OraPmtReq to authorize funds
5338         write_debug_and_log('Calling Create_Authorization');
5339         write_debug_and_log('p_trxn_entity_id: ' || l_PAYMENT_TRXN_EXTENSION_ID);
5340         write_debug_and_log('p_payer_rec.payment_function:' || p_payer_rec.payment_function);
5341         write_debug_and_log('p_payer_rec.org_type: ' ||  p_payer_rec.org_type);
5342         write_debug_and_log('p_payer_rec.Cust_Account_Id: ' || p_payer_rec.Cust_Account_Id);
5343         write_debug_and_log('p_payer_rec.Account_Site_Id: ' ||p_payer_rec.Account_Site_Id );
5344 	write_debug_and_log('l_amount_rec.Value: ' || to_char(l_amount_rec.Value) );
5345         write_debug_and_log('l_amount_rec.Currency_Code: ' ||l_amount_rec.Currency_Code );
5346         write_debug_and_log('p_payee_rec.org_type: ' || p_payee_rec.org_type);
5347         write_debug_and_log('p_payee_rec.org_id : ' || p_payee_rec.org_id  );
5348         write_debug_and_log('l_auth_rec.receipt_method_id : ' || l_auth_rec.receipt_method_id  );
5349 	    write_debug_and_log('p_payee_rec.Int_Bank_Country_Code : ' || p_payee_rec.Int_Bank_Country_Code  );
5350 
5351         ---------------------------------------------------------------------------------
5352         l_debug_info := 'Call to iPayment API to authorize funds';
5353         ---------------------------------------------------------------------------------
5354 
5355 
5356         IBY_FNDCPT_TRXN_PUB.Create_Authorization(
5357 		    p_api_version	         => 1.0,
5358 		    p_init_msg_list		 => FND_API.G_TRUE,
5359 		    x_return_status		 => l_return_status,
5360 		    x_msg_count			 => l_msg_count,
5361 		    x_msg_data		         => l_msg_data,
5362 		    p_payer			 => p_payer_rec,
5363 		    p_payee			 => p_payee_rec,
5364 		    p_trxn_entity_id		 => l_PAYMENT_TRXN_EXTENSION_ID,
5365 		    p_auth_attribs		 => l_auth_rec,
5366 		    p_amount			 => l_amount_rec,
5367 		    x_auth_result		 => x_auth_result,
5368 		    x_response			 => x_response);
5369 
5370     	 arp_standard.debug('l_return_status: ' || l_return_status);
5371 
5372          x_msg_count           := l_msg_count;
5373          x_msg_data            := l_msg_data;
5374          p_response_error_code := x_response.Result_Code ;
5375 
5376          write_debug_and_log('-------------------------------------');
5377          write_debug_and_log('x_response.Result_Code: ' || x_response.Result_Code);
5378          write_debug_and_log('x_response.Result_Message: ' || x_response.Result_Message);
5379          write_debug_and_log('x_response.Result_Category: ' || x_response.Result_Category);
5380          write_debug_and_log('x_auth_result.Auth_Id : ' || x_auth_result.Auth_Id );
5381          write_debug_and_log('x_auth_result.Auth_Date: ' || TO_CHAR(x_auth_result.Auth_Date));
5382 	 write_debug_and_log('x_auth_result.Auth_Code: ' || x_auth_result.Auth_Code);
5383 	 write_debug_and_log('x_auth_result.AVS_Code: ' || x_auth_result.AVS_Code);
5384 	 write_debug_and_log('x_auth_result.Instr_SecCode_Check: ' || x_auth_result.Instr_SecCode_Check);
5385 	 write_debug_and_log('x_auth_result.PaymentSys_Code: ' || x_auth_result.PaymentSys_Code);
5386 	 write_debug_and_log('x_auth_result.PaymentSys_Msg: ' || x_auth_result.PaymentSys_Msg);
5387          write_debug_and_log('-------------------------------------');
5388 
5389         -- check if call was successful
5390         --Add message to message stack only it it is called from iReceivables
5391         --if not pass the message stack received from iPayment
5392 
5393         if (l_return_status <> FND_API.G_RET_STS_SUCCESS)
5394            AND (NVL(p_called_from,'NONE') = 'IREC')  then
5395 
5396           FND_MESSAGE.set_name('AR', 'AR_CC_AUTH_FAILED');
5397           FND_MSG_PUB.Add;
5398           x_return_status := l_return_status;
5399              --Bug 7673372 - When IBY API throws an error without contacting 3rd pmt system the error msg would
5400              --returned in x_response.Result_Message;
5401            x_msg_data := x_response.Result_Message;
5402           RETURN;
5403         elsif (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
5404           p_cc_auth_code := x_auth_result.Auth_Code;
5405           x_return_status := l_return_status;
5406           RETURN;
5407         end if;
5408 
5409         -- update cash receipt with authorization code
5410          ---------------------------------------------------------------------------------
5411         l_debug_info := 'update cash receipt with authorization code and payment server order id';
5412         ---------------------------------------------------------------------------------
5413 
5414         ARP_CASH_RECEIPTS_PKG.set_to_dummy(l_cr_rec);
5415         l_cr_rec.approval_code := x_auth_result.Auth_Code;
5416         ARP_CASH_RECEIPTS_PKG.update_p(l_cr_rec, p_cash_receipt_id);
5417 
5418           write_debug_and_log('CR rec updated with payment server auth code');
5419 
5420         -- see if capture is also required
5421 
5422         if (l_action = 'AUTHANDCAPTURE') then
5423 
5424           write_debug_and_log('starting capture...');
5425           ---------------------------------------------------------------------------------
5426           l_debug_info := 'Capture required: capture funds';
5427           ---------------------------------------------------------------------------------
5428           -- Step 2: (optional): capture funds
5429 
5430            ---------------------------------------------------------------------------------
5431           l_debug_info := 'Call iPayment API to capture funds';
5432           ---------------------------------------------------------------------------------
5433           IBY_FNDCPT_TRXN_PUB.Create_Settlement(
5434 		    p_api_version           => 1.0,
5435 		    p_init_msg_list         => FND_API.G_TRUE,
5436 		    x_return_status         => l_return_status,
5437 		    x_msg_count             => l_msg_count,
5438 		    x_msg_data              => l_msg_data,
5439 		    p_payer		    => p_payer_rec,
5440 		    p_trxn_entity_id	    => l_PAYMENT_TRXN_EXTENSION_ID,
5441 		    p_amount                => l_amount_rec,
5442 		    x_response              => x_response);
5443 
5444 
5445             write_debug_and_log('CAPTURE l_return_status: ' || l_return_status);
5446 
5447             x_msg_count           := l_msg_count;
5448             x_msg_data            := l_msg_data;
5449             p_response_error_code := x_response.Result_Code;
5450 
5451             arp_standard.debug('-------------------------------------');
5452             arp_standard.debug('x_response.Result_Code: ' ||x_response.Result_Code);
5453             arp_standard.debug('x_response.Result_Category: ' || x_response.Result_Category);
5454             arp_standard.debug('x_response.Result_Message: ' || x_response.Result_Message);
5455 
5456             arp_standard.debug('-------------------------------------');
5457 
5458            --Add message to message stack only it it is called from iReceivables
5459            --if not pass the message stack received from iPayment
5460 
5461            if (l_return_status <> FND_API.G_RET_STS_SUCCESS) AND (NVL(p_called_from,'NONE') = 'IREC')  then
5462               FND_MESSAGE.set_name('AR', 'AR_CC_CAPTURE_FAILED');
5463               FND_MSG_PUB.Add;
5464            end if;
5465            x_return_status := l_return_status;
5466              --Bug 7673372 - When IBY API throws an error without contacting 3rd pmt system the error msg would
5467              --returned in x_response.Result_Message;
5468            x_msg_data := x_response.Result_Message;
5469 
5470         END IF;  -- if capture required...
5471 
5472       ELSE
5473 
5474         write_debug_and_log('should never come here --> receipt method cursor has no rows');
5475         -- currently no processing required
5476 
5477     END IF;
5478 
5479 EXCEPTION
5480     WHEN OTHERS THEN
5481     	BEGIN
5482 	    x_return_status := FND_API.G_RET_STS_ERROR;
5483 
5484             write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
5485             write_debug_and_log('- Cash Receipt Id: '||p_cash_receipt_id);
5486             write_debug_and_log('- Return Status: '||x_return_status);
5487             write_debug_and_log(SQLERRM);
5488 
5489             FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
5490             FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
5491             FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
5492             FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
5493             FND_MSG_PUB.ADD;
5494         END;
5495 
5496 END process_payment;
5497 
5498 
5499 FUNCTION validate_payment_setup (p_customer_id IN NUMBER , p_customer_site_id IN NUMBER , p_currency_code IN VARCHAR2) RETURN NUMBER
5500 IS
5501 
5502   l_ccmethodcount NUMBER;
5503   l_bamethodcount NUMBER; /* J Rautiainen ACH Implementation */
5504   l_creation_status ar_receipt_classes.creation_status%TYPE;
5505   l_procedure_name VARCHAR2(30);
5506 BEGIN
5507 
5508   l_procedure_name  := '.validate_payment_setup';
5509 
5510   -- check that function security is allowing access to payment button
5511 
5512   IF NOT fnd_function.test('ARW_PAY_INVOICE') THEN
5513     RETURN 0;
5514   END IF;
5515 
5516   -- verify that payment method is set up
5517   l_ccmethodcount  := is_credit_card_payment_enabled(p_customer_id , p_customer_site_id , p_currency_code) ;
5518 
5519   -- Bug 3338276
5520   -- If one-time payment is enabled, bank account payment is not enabled;
5521   -- Hence, the check for valid bank account payment methods can be defaulted to 0.
5522   -- Bug 3886652 - Customer Id and Customer Site Use Id added as params to ARI_CONFIG.save_payment_instrument_info
5523   IF NOT ARI_UTILITIES.save_payment_instrument_info(p_customer_id , p_customer_site_id) THEN
5524     l_bamethodcount := 0;
5525   ELSE
5526     l_bamethodcount := is_bank_acc_payment_enabled(p_customer_id , p_customer_site_id , p_currency_code);
5527   END IF;
5528 
5529    IF   l_ccmethodcount  = 0
5530    AND l_bamethodcount = 0  /* J Rautiainen ACH Implementation */
5531    THEN
5532     RETURN 0;
5533   END IF;
5534 
5535   RETURN 1;
5536 
5537 END validate_payment_setup;
5538 
5539 /*============================================================
5540   | PUBLIC procedure create_transaction_list_record
5541   |
5542   | DESCRIPTION
5543   |   Creates a record in the transaction List to be paid by the customer
5544   |   based on the selected list .
5545   |
5546   | PSEUDO CODE/LOGIC
5547   |
5548   | PARAMETERS
5549   |   p_payment_schedule_id   IN    NUMBER
5550   |   p_customer_id	      IN    NUMBER
5551   |   p_customer_site_id      IN    NUMBER
5552   |
5553   | KNOWN ISSUES
5554   |
5555   |
5556   |
5557   | NOTES
5558   |
5559   |
5560   |
5561   | MODIFICATION HISTORY
5562   | Date          Author       Description of Changes
5563   | 27-JUN-2003   yreddy       Created
5564   | 31-DEC-2004   vnb          Bug 4071551 - Modified for avoiding redundant code
5565   | 20-Jan-2005   vnb          Bug 4117211 - Original discount amount column added for ease of resetting payment amounts
5566   | 26-May-05     rsinthre     Bug # 4392371 - OIR needs to support cross customer payment
5567   | 08-Jul-2005	  rsinthre     Bug 4437225 - Disputed amount against invoice not displayed during payment
5568   | 08-Jun-2010  nkanchan Bug # 9696274 - PAGE ERRORS OUT ON NAVIGATING 'PAY BELOW' RELATED CUSTOMER DATA
5569   +============================================================*/
5570 PROCEDURE create_transaction_list_record( p_payment_schedule_id   IN NUMBER,
5571 					  p_customer_id           IN NUMBER,
5572 					  p_customer_site_id	  IN NUMBER
5573                                   ) IS
5574 
5575   l_query_period             NUMBER(15);
5576   l_query_date               DATE;
5577   l_total_service_charge     NUMBER;
5578   l_discount_amount          NUMBER;
5579   l_rem_amt_rcpt             NUMBER;
5580   l_rem_amt_inv              NUMBER;
5581   l_amount_due_remaining     NUMBER;
5582   l_trx_class                VARCHAR2(20);
5583   l_cash_receipt_id          NUMBER;
5584   l_grace_days_flag          VARCHAR2(2);
5585 
5586   l_pay_for_cust_id	     NUMBER(15);
5587   l_paying_cust_id	     NUMBER(15);
5588   l_pay_for_cust_site_id     NUMBER(15);
5589   l_paying_cust_site_id      NUMBER(15);
5590   l_dispute_amount	     NUMBER := 0;
5591   l_customer_trx_id	     NUMBER(15,0);
5592 
5593   l_procedure_name           VARCHAR2(50);
5594   l_debug_info	 	     VARCHAR2(200);
5595 
5596 BEGIN
5597   --Assign default values
5598   l_query_period         := -12;
5599   l_total_service_charge := 0;
5600   l_discount_amount      := 0;
5601   l_rem_amt_rcpt         := 0;
5602   l_rem_amt_inv          := 0;
5603   l_amount_due_remaining := 0;
5604 
5605   l_procedure_name       := '.create_transaction_list_record';
5606 
5607   SAVEPOINT create_trx_list_record_sp;
5608 
5609   select class, amount_due_remaining, cash_receipt_id, ps.CUSTOMER_ID, ct.PAYING_CUSTOMER_ID, ps.CUSTOMER_SITE_USE_ID,ct.PAYING_SITE_USE_ID, ps.customer_trx_id,
5610     (decode( nvl(AMOUNT_DUE_ORIGINAL,0),0,1,(AMOUNT_DUE_ORIGINAL/abs(AMOUNT_DUE_ORIGINAL)) ) *abs(nvl(amount_in_dispute,0)) )
5611   into l_trx_class, l_amount_due_remaining, l_cash_receipt_id, l_pay_for_cust_id, l_paying_cust_id, l_pay_for_cust_site_id, l_paying_cust_site_id, l_customer_trx_id, l_dispute_amount
5612   from ar_payment_schedules ps, ra_customer_trx_all ct
5613   where ps.CUSTOMER_TRX_ID = ct.CUSTOMER_TRX_ID(+)
5614   and ps.payment_schedule_id = p_payment_schedule_id;
5615 
5616    --Bug 4479224
5617    l_paying_cust_id := p_customer_id;
5618    --l_paying_cust_site_id := p_customer_site_id;
5619    --Commented for bug 9696274
5620    if( p_customer_site_id IS NULL OR p_customer_site_id = '' OR p_customer_site_id = -1) then
5621       if(l_paying_cust_id = l_pay_for_cust_id) then
5622          l_paying_cust_site_id := l_pay_for_cust_site_id;
5623       else
5624          l_paying_cust_site_id := -1;
5625       end if;
5626    else
5627       l_paying_cust_site_id := p_customer_site_id;
5628    end if;
5629 
5630   ----------------------------------------------------------------------------------------
5631   l_debug_info := 'If the transaction is a Payment, then set the Remaining Amount';
5632   -----------------------------------------------------------------------------------------
5633   IF (PG_DEBUG = 'Y') THEN
5634         arp_standard.debug(l_debug_info);
5635   END IF;
5636   -- Bug 4000279 - Modified to check for 'UNAPP' status only
5637   IF (l_trx_class = 'PMT') THEN
5638 
5639 	select -sum(app.amount_applied)
5640         into  l_amount_due_remaining
5641  	from ar_receivable_applications app
5642 	where nvl( app.confirmed_flag, 'Y' ) = 'Y'
5643         and app.status = 'UNAPP'
5644         and app.cash_receipt_id = l_cash_receipt_id;
5645    ----------------------------------------------------------------------------------------
5646    l_debug_info := 'If the transaction is a debit, then calculate discount';
5647    -----------------------------------------------------------------------------------------
5648    IF (PG_DEBUG = 'Y') THEN
5649         arp_standard.debug(l_debug_info);
5650    END IF;
5651    ELSIF (l_trx_class = 'INV' OR l_trx_class = 'DEP' OR l_trx_class = 'DM' OR l_trx_class = 'CB') THEN
5652 	  --Bug 6819964 - If AR API errors out then payments are failing as l_discount_amount is not set to any value
5653 	  begin
5654         	--l_grace_days_flag := is_grace_days_enabled_wrapper();
5655         	l_grace_days_flag := ARI_UTILITIES.is_discount_grace_days_enabled(p_customer_id,p_customer_site_id);
5656         	arp_discounts_api.get_discount(p_ps_id	            => p_payment_schedule_id,
5657 		                       p_apply_date	    => trunc(sysdate),
5658                             	       p_in_applied_amount  => (l_amount_due_remaining - l_dispute_amount),
5659 		                       p_grace_days_flag    => l_grace_days_flag,
5660 		                       p_out_discount       => l_discount_amount,
5661 		                       p_out_rem_amt_rcpt   => l_rem_amt_rcpt,
5662 		                       p_out_rem_amt_inv    => l_rem_amt_inv,
5663 				       p_called_from        => 'OIR' );
5664 	  exception
5665 		when others then
5666 			l_discount_amount := 0;
5667 			write_debug_and_log('Unexpected Exception while calculating discount');
5668 			write_debug_and_log('Payment Schedule Id: '||p_payment_schedule_id);
5669 	  end;
5670    END IF;
5671 
5672     --Bug 4117211 - Original discount amount column added for ease of resetting payment amounts
5673     ----------------------------------------------------------------------------------------
5674     l_debug_info := 'Populate the Payment GT with the transaction';
5675     -----------------------------------------------------------------------------------------
5676     IF (PG_DEBUG = 'Y') THEN
5677         arp_standard.debug(l_debug_info);
5678     END IF;
5679 
5680     INSERT INTO AR_IREC_PAYMENT_LIST_GT
5681       ( CUSTOMER_ID,
5682         CUSTOMER_SITE_USE_ID,
5683         ACCOUNT_NUMBER,
5684         CUSTOMER_TRX_ID,
5685         TRX_NUMBER,
5686         PAYMENT_SCHEDULE_ID,
5687         TRX_DATE,
5688         DUE_DATE,
5689         STATUS,
5690         TRX_CLASS,
5691         PO_NUMBER,
5692         SO_NUMBER,
5693         CURRENCY_CODE,
5694         AMOUNT_DUE_ORIGINAL,
5695         AMOUNT_DUE_REMAINING,
5696         DISCOUNT_AMOUNT,
5697         SERVICE_CHARGE,
5698         PAYMENT_AMT,
5699         PAYMENT_TERMS,
5700         NUMBER_OF_INSTALLMENTS,
5701         TERMS_SEQUENCE_NUMBER,
5702         LINE_AMOUNT,
5703         TAX_AMOUNT,
5704         FREIGHT_AMOUNT,
5705         FINANCE_CHARGES,
5706         RECEIPT_DATE,
5707         PRINTING_OPTION,
5708 	INTERFACE_HEADER_CONTEXT,
5709         INTERFACE_HEADER_ATTRIBUTE1,
5710         INTERFACE_HEADER_ATTRIBUTE2,
5711         INTERFACE_HEADER_ATTRIBUTE3,
5712         INTERFACE_HEADER_ATTRIBUTE4,
5713         INTERFACE_HEADER_ATTRIBUTE5,
5714         INTERFACE_HEADER_ATTRIBUTE6,
5715         INTERFACE_HEADER_ATTRIBUTE7,
5716         INTERFACE_HEADER_ATTRIBUTE8,
5717         INTERFACE_HEADER_ATTRIBUTE9,
5718         INTERFACE_HEADER_ATTRIBUTE10,
5719         INTERFACE_HEADER_ATTRIBUTE11,
5720         INTERFACE_HEADER_ATTRIBUTE12,
5721         INTERFACE_HEADER_ATTRIBUTE13,
5722         INTERFACE_HEADER_ATTRIBUTE14,
5723         INTERFACE_HEADER_ATTRIBUTE15,
5724         ATTRIBUTE_CATEGORY,
5725         ATTRIBUTE1,
5726         ATTRIBUTE2,
5727         ATTRIBUTE3,
5728         ATTRIBUTE4,
5729         ATTRIBUTE5,
5730         ATTRIBUTE6,
5731         ATTRIBUTE7,
5732         ATTRIBUTE8,
5733         ATTRIBUTE9,
5734         ATTRIBUTE10,
5735         ATTRIBUTE11,
5736         ATTRIBUTE12,
5737         ATTRIBUTE13,
5738         ATTRIBUTE14,
5739         ATTRIBUTE15,
5740         CASH_RECEIPT_ID,
5741 	ORIGINAL_DISCOUNT_AMT,
5742     ORG_ID,
5743 	PAY_FOR_CUSTOMER_ID,
5744 	PAY_FOR_CUSTOMER_SITE_ID,
5745 	DISPUTE_AMT
5746       )
5747        SELECT l_paying_cust_id,
5748          decode(l_paying_cust_site_id, null, -1,to_number(''), -1, l_paying_cust_site_id),
5749          acct.ACCOUNT_NUMBER,
5750          ps.CUSTOMER_TRX_ID,
5751          ps.TRX_NUMBER,
5752          ps.PAYMENT_SCHEDULE_ID,
5753          ps.TRX_DATE,
5754          ps.DUE_DATE,
5755          ps.STATUS,
5756          ps.class,
5757          ct.PURCHASE_ORDER AS PO_NUMBER,
5758          NULL AS SO_NUMBER,
5759 	 ps.INVOICE_CURRENCY_CODE,
5760 	 ps.AMOUNT_DUE_ORIGINAL,
5761          l_amount_due_remaining,
5762 	 l_discount_amount,
5763 	 0,
5764 	 DECODE(ps.class, 'PMT', l_amount_due_remaining, 'CM', l_amount_due_remaining,
5765 			ARI_UTILITIES.curr_round_amt(l_amount_due_remaining-l_discount_amount -l_dispute_amount,ps.INVOICE_CURRENCY_CODE)),
5766          trm.name term_desc,
5767 	 ARPT_SQL_FUNC_UTIL.Get_Number_Of_Due_Dates(ps.term_id) number_of_installments,
5768          ps.terms_sequence_number,
5769          ps.amount_line_items_original line_amount,
5770          ps.tax_original tax_amount,
5771          ps.freight_original freight_amount,
5772          ps.receivables_charges_charged finance_charge,
5773          case WHEN ((trunc(ps.trx_date) - trunc(sysdate)) <= 0) then TRUNC(SYSDATE) else ps.trx_date end as receipt_date,
5774          ct.printing_option,
5775 	 ct.INTERFACE_HEADER_CONTEXT,
5776          ct.INTERFACE_HEADER_ATTRIBUTE1,
5777          ct.INTERFACE_HEADER_ATTRIBUTE2,
5778          ct.INTERFACE_HEADER_ATTRIBUTE3,
5779          ct.INTERFACE_HEADER_ATTRIBUTE4,
5780          ct.INTERFACE_HEADER_ATTRIBUTE5,
5781          ct.INTERFACE_HEADER_ATTRIBUTE6,
5782          ct.INTERFACE_HEADER_ATTRIBUTE7,
5783          ct.INTERFACE_HEADER_ATTRIBUTE8,
5784          ct.INTERFACE_HEADER_ATTRIBUTE9,
5785          ct.INTERFACE_HEADER_ATTRIBUTE10,
5786          ct.INTERFACE_HEADER_ATTRIBUTE11,
5787          ct.INTERFACE_HEADER_ATTRIBUTE12,
5788          ct.INTERFACE_HEADER_ATTRIBUTE13,
5789          ct.INTERFACE_HEADER_ATTRIBUTE14,
5790          ct.INTERFACE_HEADER_ATTRIBUTE15,
5791          ct.ATTRIBUTE_CATEGORY,
5792          ct.ATTRIBUTE1,
5793          ct.ATTRIBUTE2,
5794          ct.ATTRIBUTE3,
5795          ct.ATTRIBUTE4,
5796          ct.ATTRIBUTE5,
5797          ct.ATTRIBUTE6,
5798          ct.ATTRIBUTE7,
5799          ct.ATTRIBUTE8,
5800          ct.ATTRIBUTE9,
5801          ct.ATTRIBUTE10,
5802          ct.ATTRIBUTE11,
5803          ct.ATTRIBUTE12,
5804          ct.ATTRIBUTE13,
5805          ct.ATTRIBUTE14,
5806          ct.ATTRIBUTE15,
5807          ps.cash_receipt_id,
5808 	 l_discount_amount,
5809 	 ps.org_id,
5810 	 l_pay_for_cust_id,
5811 	 --Bug 4062938 - Handling of transactions with no site id
5812 	 decode(ps.customer_site_use_id, null, -1,ps.customer_site_use_id) as CUSTOMER_SITE_USE_ID,
5813 	 (decode( nvl(ps.AMOUNT_DUE_ORIGINAL,0),0,1,(ps.AMOUNT_DUE_ORIGINAL/abs(ps.AMOUNT_DUE_ORIGINAL)) ) *abs(nvl(ps.amount_in_dispute,0)) )
5814       FROM AR_PAYMENT_SCHEDULES ps,
5815            RA_CUSTOMER_TRX_ALL ct,
5816            HZ_CUST_ACCOUNTS acct,
5817            RA_TERMS trm
5818       WHERE ps.payment_schedule_id = p_payment_schedule_id
5819       AND   ps.CLASS IN ('INV', 'DM', 'GUAR', 'CB', 'DEP', 'CM', 'PMT' )  -- CCA - hikumar
5820       AND   ps.customer_trx_id = ct.customer_trx_id(+)
5821       AND   acct.cust_account_id = ps.customer_id
5822       AND   ps.term_id = trm.term_id(+);
5823 
5824    COMMIT;
5825 
5826 EXCEPTION
5827      WHEN OTHERS THEN
5828          IF (PG_DEBUG = 'Y') THEN
5829              arp_standard.debug('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
5830              arp_standard.debug('- Payment Schedule Id: '||p_payment_schedule_id);
5831              arp_standard.debug('ERROR =>'|| SQLERRM);
5832          END IF;
5833 
5834 	 ROLLBACK to create_trx_list_record_sp;
5835 
5836          FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
5837          FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
5838          FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
5839          FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
5840          FND_MSG_PUB.ADD;
5841 
5842 END create_transaction_list_record;
5843 
5844 /*========================================================================
5845  | PUBLIC procedure is_credit_card_payment_enabled
5846  |
5847  | DESCRIPTION
5848  |      Checks if the credit card payment method has been setup
5849  |      ----------------------------------------
5850  |
5851  | PSEUDO CODE/LOGIC
5852  |
5853  | PARAMETERS
5854  |
5855  | RETURNS
5856  |      Number 1 or 0 corresponing to true and false for the credit card
5857  |      payment has been setup or not.
5858  |
5859  | MODIFICATION HISTORY
5860  | Date          Author       Description of Changes
5861  | 10-Mar-2004   hikumar       Created
5862  ========================================================================*/
5863 
5864 FUNCTION is_credit_card_payment_enabled(p_customer_id IN NUMBER , p_customer_site_id IN NUMBER , p_currency_code IN VARCHAR2)
5865 RETURN NUMBER IS
5866 system_cc_payment_method	NUMBER ;
5867 customer_cc_payment_method      NUMBER ;
5868 profile_cc_payment_method VARCHAR2(200);
5869 
5870 CURSOR cc_profile_pmt_method_info_cur IS
5871   SELECT arm.receipt_method_id receipt_method_id,
5872     arc.creation_status receipt_creation_status
5873   FROM ar_receipt_methods arm,
5874     ar_receipt_method_accounts arma,
5875     ce_bank_acct_uses_ou_v aba,
5876     ce_bank_accounts       cba,
5877     ar_receipt_classes arc
5878   WHERE arm.payment_channel_code = 'CREDIT_CARD'
5879     AND arm.receipt_method_id = NVL( to_number(fnd_profile.VALUE('OIR_CC_PMT_METHOD')), arm.receipt_method_id)
5880     AND arm.receipt_method_id = arma.receipt_method_id
5881     AND arm.receipt_class_id = arc.receipt_class_id
5882     AND arma.remit_bank_acct_use_id = aba.bank_acct_use_id
5883     AND aba.bank_account_id = cba.bank_account_id
5884     AND (cba.currency_code = p_currency_code OR cba.receipt_multi_currency_flag = 'Y')
5885     AND TRUNC(nvl(aba.end_date,sysdate)) >= TRUNC(sysdate)
5886     AND TRUNC(sysdate) BETWEEN TRUNC(nvl(arm.start_date,   sysdate)) AND TRUNC(nvl(arm.end_date,   sysdate))
5887     AND TRUNC(sysdate) BETWEEN TRUNC(arma.start_date) AND TRUNC(nvl(arma.end_date,   sysdate));
5888 
5889 
5890 
5891  cc_profile_pmt_method_info cc_profile_pmt_method_info_cur%ROWTYPE;
5892 
5893  l_procedure_name  VARCHAR2(30);
5894  l_debug_info  VARCHAR2(300);
5895 
5896 BEGIN
5897 
5898 l_procedure_name := 'is_credit_card_payment_enabled';
5899 
5900    --------------------------------------------------------------------
5901    l_debug_info := 'Checking if valid CC payment method is set in the profile OIR_CC_PMT_METHOD';
5902    --------------------------------------------------------------------
5903      IF (PG_DEBUG = 'Y') THEN
5904         arp_standard.debug(l_debug_info);
5905      END IF;
5906 
5907   profile_cc_payment_method := FND_PROFILE.value('OIR_CC_PMT_METHOD');
5908 
5909   IF (profile_cc_payment_method = 'DISABLED') THEN   /* Credit Card Payment is Disabled */
5910     RETURN 0;
5911   ELSIF (profile_cc_payment_method IS NOT NULL) THEN /* A Credit Card Payment Method has been mentioned */
5912     OPEN  cc_profile_pmt_method_info_cur;
5913     FETCH cc_profile_pmt_method_info_cur INTO cc_profile_pmt_method_info;
5914     /* If CC Payment Method set is NULL or DISABLED or an invalid payment method, it returns NO rows */
5915     IF cc_profile_pmt_method_info_cur%FOUND THEN
5916        l_debug_info := 'Payment Method Set in the profile OIR_CC_PMT_METHOD is Valid. Val=' ||  fnd_profile.VALUE('OIR_CC_PMT_METHOD');
5917         if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
5918          fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info);
5919         end if;
5920       RETURN 1;
5921      ELSE
5922       l_debug_info := 'Invalid Payment Method is Set in the profile OIR_CC_PMT_METHOD. Value in profile=' ||  fnd_profile.VALUE('OIR_CC_PMT_METHOD');
5923        if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
5924           fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info);
5925        end if;
5926       RETURN 0;
5927     END IF;
5928    CLOSE cc_profile_pmt_method_info_cur;
5929 
5930   END IF;
5931 
5932   l_debug_info := 'No value is set in the profile OIR_CC_PMT_METHOD. Checking at customer site, acct and system options level.';
5933 
5934      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
5935         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info);
5936      end if;
5937 
5938  /* Default behavior, as no Credit Card Payment method is mentioned in the OIR_CC_PMT_METHOD profile */
5939 
5940  -- verify that Credit Card payment method is set up in AR_SYSTEM_PARAMETERS
5941   -- Bug 3886652 - Customer Id and Customer Site Use Id added as params to ARI_CONFIG.save_payment_instrument_info
5942   SELECT  /*+ leading(rc) */  count(irec_cc_receipt_method_id)
5943   INTO system_cc_payment_method
5944   FROM   ar_system_parameters sp,
5945          ar_receipt_methods rm,
5946          ar_receipt_method_accounts rma,
5947          ce_bank_accounts cba,
5948          ce_bank_acct_uses_ou_v ba,
5949          ar_receipt_classes rc
5950   WHERE  sp.irec_cc_receipt_method_id = rm.receipt_method_id
5951     AND  rma.receipt_method_id = rm.receipt_method_id
5952     AND  rma.remit_bank_acct_use_id = ba.bank_acct_use_id
5953     AND  ba.bank_account_id = cba.bank_account_id
5954     AND  ( cba.currency_code = p_currency_code
5955 	    OR
5956 	   cba.receipt_multi_currency_flag = 'Y' )
5957     AND  sysdate < nvl(ba.end_date, SYSDATE+1)
5958     AND  sysdate between rma.start_date and nvl(rma.end_date, SYSDATE)
5959     AND  sysdate between rm.start_date and NVL(rm.end_date, SYSDATE)
5960     /* Commented for bug 12670265
5961      AND (
5962            save_payment_inst_info_wrapper(p_customer_id,p_customer_site_id) = 'true'
5963           OR
5964              -- If the one time payment is true , then ensure that the receipt
5965               -- class is set for one step remittance.
5966               rc.creation_status IN ('REMITTED','CLEARED')) */
5967               and rc.receipt_class_id = rm.receipt_class_id;
5968 
5969  -- verify that Credit Card payment method is set up at Customer Account Level or Site Level
5970 
5971   SELECT count ( arm.receipt_method_id )
5972   INTO customer_cc_payment_method
5973   FROM    ar_receipt_methods         arm,
5974           ra_cust_receipt_methods    rcrm,
5975           ar_receipt_method_accounts arma,
5976           ce_bank_acct_uses_ou_v          aba,
5977           ce_bank_accounts           cba,
5978           ar_receipt_classes         arc
5979   WHERE   arm.receipt_method_id = rcrm.receipt_method_id
5980      AND       arm.receipt_method_id = arma.receipt_method_id
5981      AND       arm.receipt_class_id  = arc.receipt_class_id
5982      AND       rcrm.customer_id      = p_customer_id
5983      AND       arma.remit_bank_acct_use_id = aba.bank_acct_use_id
5984      AND       aba.bank_account_id = cba.bank_account_id
5985      AND     ( NVL(rcrm.site_use_id,p_customer_site_id)  = p_customer_site_id
5986                OR
5987                (p_customer_site_id is null and rcrm.site_use_id is null)
5988               )
5989      AND   (
5990                  cba.currency_code    =  p_currency_code
5991                  OR
5992                  cba.receipt_multi_currency_flag = 'Y'
5993               )
5994 -- Bug#6109909
5995 --     AND  arm.payment_type_code = 'CREDIT_CARD'
5996      AND  arm.payment_channel_code = 'CREDIT_CARD'
5997      AND  arc.creation_method_code = 'AUTOMATIC'
5998      -- AND       aba.set_of_books_id = arp_trx_global.system_info.system_parameters.set_of_books_id
5999      AND sysdate < NVL ( aba.end_date , sysdate+1)
6000      AND sysdate between arm.start_date AND NVL(arm.end_date, sysdate)
6001      AND sysdate between arma.start_date AND NVL(arma.end_date, sysdate)
6002      /* Commented for bug 12670265
6003      AND (
6004           ( save_payment_inst_info_wrapper(p_customer_id,p_customer_site_id) = 'true' )
6005           OR
6006           (   -- If the one time payment is true , then ensure that the receipt
6007               -- class is set for one step remittance.
6008             arc.creation_status IN ('REMITTED','CLEARED')
6009           )
6010          ) */
6011       ;
6012 
6013   IF( (customer_cc_payment_method = 0 ) AND  (system_cc_payment_method = 0))
6014   THEN
6015     RETURN 0 ;
6016   ELSE
6017     RETURN 1 ;
6018   END IF;
6019 
6020 EXCEPTION
6021 WHEN OTHERS THEN
6022         l_debug_info := 'Unknown exception. Value in profile OIR_CC_PMT_METHOD=' ||  fnd_profile.VALUE('OIR_CC_PMT_METHOD');
6023         write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
6024        	write_debug_and_log('ERROR =>'|| SQLERRM);
6025         write_debug_and_log('-DEBUG_INFO-' || l_debug_info);
6026         RETURN 0;
6027 
6028 END is_credit_card_payment_enabled ;
6029 
6030 
6031 
6032 
6033 /*========================================================================
6034  | PUBLIC procedure is_bank_acc_payment_enabled
6035  |
6036  | DESCRIPTION
6037  |      Checks if the Bank Account payment method has been setup
6038  |      ----------------------------------------
6039  |
6040  | PSEUDO CODE/LOGIC
6041  |
6042  | PARAMETERS
6043  |
6044  | RETURNS
6045  |      Number 1 or 0 corresponing to true and false for the credit card
6046  |      payment has been setup or not.
6047  |
6048  | MODIFICATION HISTORY
6049  | Date          Author       Description of Changes
6050  | 10-Mar-2004   hikumar       Created
6051  ========================================================================*/
6052 
6053 FUNCTION is_bank_acc_payment_enabled(p_customer_id IN NUMBER , p_customer_site_id IN NUMBER , p_currency_code IN VARCHAR2)
6054 RETURN NUMBER IS
6055 system_bank_payment_method  	NUMBER ;
6056 customer_bank_payment_method    NUMBER ;
6057 profile_ba_payment_method VARCHAR2(200);
6058 
6059 CURSOR ba_profile_pmt_method_info_cur IS
6060   SELECT arm.receipt_method_id receipt_method_id,
6061     arc.creation_status receipt_creation_status
6062   FROM ar_receipt_methods arm,
6063     ar_receipt_method_accounts arma,
6064     ce_bank_acct_uses_ou_v aba,
6065     ce_bank_accounts       cba,
6066     ar_receipt_classes arc
6067   WHERE NVL(arm.payment_channel_code,'NONE') <> 'CREDIT_CARD'
6068     AND arm.receipt_method_id = NVL( to_number(fnd_profile.VALUE('OIR_BA_PMT_METHOD')), arm.receipt_method_id)
6069     AND arm.receipt_method_id = arma.receipt_method_id
6070     AND arm.receipt_class_id = arc.receipt_class_id
6071     AND arma.remit_bank_acct_use_id = aba.bank_acct_use_id
6072     AND aba.bank_account_id = cba.bank_account_id
6073     AND (cba.currency_code = p_currency_code OR cba.receipt_multi_currency_flag = 'Y')
6074     AND TRUNC(nvl(aba.end_date,sysdate)) >= TRUNC(sysdate)
6075     AND TRUNC(sysdate) BETWEEN TRUNC(nvl(arm.start_date,   sysdate)) AND TRUNC(nvl(arm.end_date,   sysdate))
6076     AND TRUNC(sysdate) BETWEEN TRUNC(arma.start_date) AND TRUNC(nvl(arma.end_date,   sysdate));
6077 
6078  ba_profile_pmt_method_info ba_profile_pmt_method_info_cur%ROWTYPE;
6079 
6080  l_procedure_name  VARCHAR2(30);
6081  l_debug_info  VARCHAR2(300);
6082 
6083 BEGIN
6084 
6085 l_procedure_name := 'is_bank_acc_payment_enabled';
6086 
6087    --------------------------------------------------------------------
6088    l_debug_info := 'Checking if valid Bank Account payment method is set in the profile OIR_BA_PMT_METHOD';
6089    --------------------------------------------------------------------
6090      IF (PG_DEBUG = 'Y') THEN
6091         arp_standard.debug(l_debug_info);
6092      END IF;
6093 
6094   profile_ba_payment_method := FND_PROFILE.value('OIR_BA_PMT_METHOD');
6095 
6096   IF (profile_ba_payment_method = 'DISABLED') THEN   /* Bank Account Payment is Disabled */
6097     RETURN 0;
6098   ELSIF (profile_ba_payment_method IS NOT NULL) THEN /* A Bank Account Payment Method has been mentioned */
6099     OPEN  ba_profile_pmt_method_info_cur;
6100     FETCH ba_profile_pmt_method_info_cur INTO ba_profile_pmt_method_info;
6101     /* If Bank Account Payment Method set is NULL or DISABLED or an invalid payment method, it returns NO rows */
6102     IF ba_profile_pmt_method_info_cur%FOUND THEN
6103        l_debug_info := 'Payment Method Set in the profile OIR_BA_PMT_METHOD is Valid. Val=' ||  fnd_profile.VALUE('OIR_BA_PMT_METHOD');
6104         if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
6105          fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info);
6106         end if;
6107       RETURN 1;
6108      ELSE
6109       l_debug_info := 'Invalid Payment Method is Set in the profile OIR_BA_PMT_METHOD. Value in profile=' ||  fnd_profile.VALUE('OIR_BA_PMT_METHOD');
6110        if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
6111           fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info);
6112        end if;
6113       RETURN 0;
6114     END IF;
6115    CLOSE ba_profile_pmt_method_info_cur;
6116 
6117   END IF;
6118 
6119   l_debug_info := 'No value is set in the profile OIR_BA_PMT_METHOD. Checking at customer site, acct and system options level.';
6120 
6121      if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
6122         fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, l_debug_info);
6123      end if;
6124 
6125  /* Default behavior, as no Bank Account Payment method is mentioned in the OIR_BA_PMT_METHOD profile */
6126 
6127  -- verify that Bank Account payment method is set up in AR_SYSTEM_PARAMETERS
6128 
6129   SELECT count(irec_ba_receipt_method_id) /* J Rautiainen ACH Implementation */
6130   INTO system_bank_payment_method
6131   FROM   ar_system_parameters sp,
6132          ar_receipt_methods rm,
6133          ar_receipt_method_accounts rma,
6134          ce_bank_acct_uses_ou_v ba,
6135          ce_bank_accounts cba
6136   WHERE  sp.irec_ba_receipt_method_id = rm.receipt_method_id
6137     AND  rma.receipt_method_id = rm.receipt_method_id
6138     AND  rma.remit_bank_acct_use_id = ba.bank_acct_use_id
6139     AND  ba.bank_account_id = cba.bank_account_id
6140     AND  ( cba.currency_code = p_currency_code
6141 	    OR cba.receipt_multi_currency_flag = 'Y')
6142     AND  sysdate < nvl(ba.end_date, SYSDATE+1)
6143     AND  sysdate between rma.start_date and nvl(rma.end_date, SYSDATE)
6144     AND  sysdate between rm.start_date and NVL(rm.end_date, SYSDATE);
6145 
6146  -- verify that Bank Account payment method is set up in AR_SYSTEM_PARAMETERS
6147 
6148   SELECT count ( arm.receipt_method_id )
6149   INTO customer_bank_payment_method
6150   FROM    ar_receipt_methods         arm,
6151           ra_cust_receipt_methods    rcrm,
6152           ar_receipt_method_accounts arma,
6153           ce_bank_acct_uses_ou_v          aba,
6154           ce_bank_accounts           cba,
6155           ar_receipt_classes         arc
6156   WHERE   arm.receipt_method_id = rcrm.receipt_method_id
6157     AND       arm.receipt_method_id = arma.receipt_method_id
6158     AND       arm.receipt_class_id  = arc.receipt_class_id
6159     AND       rcrm.customer_id      = p_customer_id
6160     AND       arma.remit_bank_acct_use_id  = aba.bank_acct_use_id
6161     AND       aba.bank_account_id = cba.bank_account_id
6162     AND     ( NVL(rcrm.site_use_id,p_customer_site_id)  = p_customer_site_id
6163               OR
6164              (p_customer_site_id is null and rcrm.site_use_id is null)
6165             )
6166     AND   (
6167                  cba.currency_code    =  p_currency_code
6168                  OR
6169                  cba.receipt_multi_currency_flag = 'Y'
6170             )
6171    AND   (   arc.remit_flag = 'Y'
6172              and arc.confirm_flag = 'N'
6173 	  )
6174    AND (
6175 	  arc.creation_method_code = 'MANUAL'
6176 	  or
6177    --Bug#6109909
6178           ( arm.payment_channel_code = 'BANK_ACCT_XFER'
6179 	    and arc.creation_method_code = 'AUTOMATIC' )
6180 	)
6181    -- AND       aba.set_of_books_id = arp_trx_global.system_info.system_parameters.set_of_books_id
6182    AND sysdate < NVL ( aba.end_date , sysdate+1)
6183    AND sysdate between arm.start_date AND NVL(arm.end_date, sysdate)
6184    AND sysdate between arma.start_date AND NVL(arma.end_date, sysdate) ;
6185 
6186   IF( (customer_bank_payment_method = 0) AND  (system_bank_payment_method = 0))
6187   THEN
6188     RETURN 0 ;
6189   ELSE
6190     RETURN 1 ;
6191   END IF;
6192 
6193 EXCEPTION
6194 WHEN OTHERS THEN
6195         l_debug_info := 'Unknown exception. Value in profile OIR_BA_PMT_METHOD=' ||  fnd_profile.VALUE('OIR_BA_PMT_METHOD');
6196         write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
6197        	write_debug_and_log('ERROR =>'|| SQLERRM);
6198         write_debug_and_log('-DEBUG_INFO-' || l_debug_info);
6199         RETURN 0;
6200 
6201 END is_bank_acc_payment_enabled ;
6202 
6203 /*============================================================
6204   | PUBLIC function save_payment_inst_info_wrapper
6205   |
6206   | DESCRIPTION
6207   |   This is a wrapper to return a VARCHAR2 instead of the Boolean returned
6208   |   by ARI_CONFIG.save_payment_instrument_info.
6209   |
6210   | PSEUDO CODE/LOGIC
6211   |
6212   | PARAMETERS
6213   |
6214   | KNOWN ISSUES
6215   |
6216   |
6217   |
6218   | NOTES
6219   |
6220   |
6221   |
6222   | MODIFICATION HISTORY
6223   | Date          Author       Description of Changes
6224   | 29-APR-2004   vnb          Created
6225   | 21-SEP-2004   vnb          Bug 3886652 - Customer Id and Customer Site Use Id added as params to ARI_CONFIG.save_payment_instrument_info
6226   +============================================================*/
6227  FUNCTION save_payment_inst_info_wrapper ( p_customer_id          IN VARCHAR2,
6228                                            p_customer_site_use_id IN VARCHAR2 DEFAULT NULL)
6229  RETURN VARCHAR2 IS
6230  l_save_payment_inst_flag VARCHAR2(6);
6231  BEGIN
6232     -- Bug 3886652 - Customer Id and Customer Site Use Id added as params to ARI_CONFIG.save_payment_instrument_info
6233     if (ARI_UTILITIES.save_payment_instrument_info(p_customer_id, nvl(p_customer_site_use_id,-1))) then
6234         l_save_payment_inst_flag := 'true';
6235     else
6236         l_save_payment_inst_flag := 'false';
6237     end if;
6238 
6239     return l_save_payment_inst_flag;
6240 
6241  END save_payment_inst_info_wrapper;
6242 
6243  /*============================================================
6244   | PUBLIC function is_grace_days_enabled_wrapper
6245   |
6246   | DESCRIPTION
6247   |   This is a wrapper to return a VARCHAR2 instead of the Boolean returned
6248   |   by ARI_CONFIG.is_discount_grace_days_enabled.
6249   |
6250   | PSEUDO CODE/LOGIC
6251   |
6252   | PARAMETERS
6253   |
6254   | KNOWN ISSUES
6255   |
6256   |
6257   |
6258   | NOTES
6259   |
6260   |
6261   |
6262   | MODIFICATION HISTORY
6263   | Date          Author       Description of Changes
6264   | 28-APR-2004   vnb          Created
6265   +============================================================*/
6266  FUNCTION is_grace_days_enabled_wrapper RETURN VARCHAR2 IS
6267  l_grace_days_flag VARCHAR2(2);
6268  BEGIN
6269     if (ARI_UTILITIES.is_discount_grace_days_enabled) then
6270         l_grace_days_flag := 'Y';
6271     else
6272         l_grace_days_flag := 'N';
6273     end if;
6274 
6275     return l_grace_days_flag;
6276 
6277   END is_grace_days_enabled_wrapper;
6278 
6279 /*============================================================
6280   | PUBLIC function get_discount_wrapper
6281   |
6282   | DESCRIPTION
6283   |   This is a function that is a wrapper to call the AR API for calculating
6284   |   discounts.
6285   |
6286   | PSEUDO CODE/LOGIC
6287   |
6288   | PARAMETERS
6289   |
6290   | KNOWN ISSUES
6291   |
6292   |
6293   |
6294   | NOTES
6295   |
6296   |
6297   |
6298   | MODIFICATION HISTORY
6299   | Date          Author       Description of Changes
6300   | 19-JUL-2004   vnb          Created
6301   +============================================================*/
6302 FUNCTION get_discount_wrapper ( p_ps_id	  IN ar_payment_schedules.payment_schedule_id%TYPE,
6303                                  p_in_applied_amount IN NUMBER) RETURN NUMBER IS
6304     l_discount_amount NUMBER;
6305     l_customer_id     NUMBER;
6306     l_customer_site_use_id NUMBER;
6307     l_rem_amt_rcpt    NUMBER;
6308     l_rem_amt_inv     NUMBER;
6309     l_grace_days_flag VARCHAR2(2);
6310   BEGIN
6311     SELECT CUSTOMER_ID, CUSTOMER_SITE_USE_ID
6312     INTO  l_customer_id, l_customer_site_use_id
6313     FROM  ar_payment_schedules
6314     WHERE PAYMENT_SCHEDULE_ID = p_ps_id;
6315 
6316      -- Check if grace days have to be considered for discount.
6317      --l_grace_days_flag := is_grace_days_enabled_wrapper();
6318      l_grace_days_flag := ARI_UTILITIES.is_discount_grace_days_enabled(l_customer_id,l_customer_site_use_id);
6319 
6320      arp_discounts_api.get_discount(p_ps_id	            => p_ps_id,
6321 		                           p_apply_date	        => trunc(sysdate),
6322                             	   p_in_applied_amount  => p_in_applied_amount,
6323 		                           p_grace_days_flag    => l_grace_days_flag,
6324 		                           p_out_discount       => l_discount_amount,
6325 		                           p_out_rem_amt_rcpt 	=> l_rem_amt_rcpt,
6326 		                           p_out_rem_amt_inv 	=> l_rem_amt_inv);
6327 
6328      return l_discount_amount;
6329 
6330   EXCEPTION
6331     when others then
6332         begin
6333             l_discount_amount := 0;
6334             write_debug_and_log('Unexpected Exception while calculating discount');
6335             write_debug_and_log('- Payment Schedule Id: '||p_ps_id);
6336             write_debug_and_log(SQLERRM);
6337             return l_discount_amount;
6338         end;
6339   END;
6340 
6341 /*============================================================
6342   | PUBLIC function write_error_messages
6343   |
6344   | DESCRIPTION
6345   |   This is a procedure that reads and returns the error messages
6346   |   from the message stack.
6347   |
6348   | PSEUDO CODE/LOGIC
6349   |
6350   | PARAMETERS
6351   |
6352   | KNOWN ISSUES
6353   |
6354   |
6355   |
6356   | NOTES
6357   |
6358   |
6359   |
6360   | MODIFICATION HISTORY
6361   | Date          Author       Description of Changes
6362   | 23-JUL-2004   vnb          Created
6363   +============================================================*/
6364   PROCEDURE write_error_messages (  p_msg_data IN OUT NOCOPY VARCHAR2,
6365                                     p_msg_count IN OUT NOCOPY NUMBER) IS
6366 
6367   l_msg_data VARCHAR2(2000);
6368 
6369   BEGIN
6370         p_msg_data := p_msg_data || '*';
6371         p_msg_count := 0;
6372         LOOP
6373             l_msg_data:=FND_MSG_PUB.GET(p_encoded=>FND_API.G_FALSE);
6374             IF (l_msg_data IS NULL)THEN
6375                 l_msg_data:=FND_MSG_PUB.GET(p_encoded=>FND_API.G_TRUE);
6376                 IF (l_msg_data IS NULL)THEN
6377                     EXIT;
6378                 END IF;
6379                             END IF;
6380             p_msg_data := p_msg_data || l_msg_data || '*';
6381             p_msg_count := p_msg_count + 1;
6382 	    write_debug_and_log(l_msg_data);
6383         END LOOP;
6384   END;
6385 
6386   /*=====================================================================
6387  | PROCEDURE reset_payment_amounts
6388  |
6389  | DESCRIPTION
6390  |   This function will reset the payment amounts on the Payment GT
6391  |   when the user clicks 'Reset to Defaults' button on Advanced Payment page
6392  |
6393  | PARAMETERS
6394  |   p_customer_id	   IN     NUMBER
6395  |   p_site_use_id     IN     NUMBER DEFAULT NULL
6396  |
6397  | HISTORY
6398  |   20-JAN-2005     vnb      Created
6399  |
6400  +=====================================================================*/
6401  PROCEDURE reset_payment_amounts (  p_customer_id		    IN NUMBER,
6402                                     p_site_use_id          IN NUMBER DEFAULT NULL,
6403                                     p_payment_type       IN varchar2 DEFAULT NULL,
6404                                     p_lookup_code       IN varchar2 DEFAULT NULL) IS
6405     l_total_service_charge     NUMBER;
6406     l_procedure_name           VARCHAR2(50);
6407     l_debug_info               VARCHAR2(200);
6408 
6409  BEGIN
6410     --Assign default values
6411     l_total_service_charge     := 0;
6412     l_procedure_name          := '.reset_payment_amounts';
6413 
6414     SAVEPOINT reset_payment_amounts_sp;
6415     -----------------------------------------------------------------------------------------
6416     l_debug_info := 'Update transaction list with original discount and payment amount';
6417     -----------------------------------------------------------------------------------------
6418     IF (PG_DEBUG = 'Y') THEN
6419        arp_standard.debug(l_debug_info);
6420     END IF;
6421     --Striping by currency code is not required because
6422     --it is not possible to navigate to Payment page with multiple currencies
6423     --in the Transaction List for a cusomer context
6424     UPDATE AR_IREC_PAYMENT_LIST_GT
6425     SET discount_amount = original_discount_amt,
6426 	    payment_amt = amount_due_remaining - original_discount_amt - nvl(dispute_amt,0)
6427     WHERE customer_id = p_customer_id
6428     AND   customer_site_use_id = nvl(decode(p_site_use_id, -1, null, p_site_use_id),customer_site_use_id);
6429 
6430     -----------------------------------------------------------------------------------------
6431     l_debug_info := 'Compute service charge';
6432     -----------------------------------------------------------------------------------------
6433     IF (PG_DEBUG = 'Y') THEN
6434        arp_standard.debug(l_debug_info);
6435     END IF;
6436     l_total_service_charge := get_service_charge(p_customer_id, p_site_use_id, p_payment_type,p_lookup_code);
6437 
6438     COMMIT;
6439 
6440  EXCEPTION
6441     WHEN OTHERS THEN
6442         write_debug_and_log('Unexpected Exception while resetting payment and discount amounts');
6443         write_debug_and_log('- Customer Id: '||p_customer_id);
6444         write_debug_and_log('- Customer Site Id: '||p_site_use_id);
6445         write_debug_and_log('- Total Service charge: '||l_total_service_charge);
6446         write_debug_and_log(SQLERRM);
6447 
6448         ROLLBACK TO reset_payment_amounts_sp;
6449 
6450  END reset_payment_amounts;
6451 
6452 
6453 /*=====================================================================
6454  | FUNCTION get_pymt_amnt_due_remaining
6455  |
6456  | DESCRIPTION
6457  |   This function will calculate the remianing amount for a
6458  |   payment that has been selected for apply credit andd return the
6459  |   total amount dure remaining that can be applied.
6460  |
6461  | HISTORY
6462  |
6463  +=====================================================================*/
6464  FUNCTION get_pymt_amnt_due_remaining (  p_cash_receipt_id    IN NUMBER) RETURN NUMBER IS
6465 
6466  l_amount_due_remaining NUMBER ;
6467 
6468  BEGIN
6469   select - sum(app.amount_applied) INTO l_amount_due_remaining
6470              	        from ar_receivable_applications app
6471 	                    where nvl( app.confirmed_flag, 'Y' ) = 'Y'
6472                         AND app.status = 'UNAPP'
6473                         AND app.cash_receipt_id = p_cash_receipt_id;
6474 
6475    RETURN l_amount_due_remaining;
6476 
6477   END get_pymt_amnt_due_remaining;
6478 
6479 /*============================================================
6480  | procedure update_cc_bill_to_site
6481  |
6482  | DESCRIPTION
6483  |   Creates/Updates Credit card bill to location with the given details
6484  |
6485  | PSEUDO CODE/LOGIC
6486  |
6487  | PARAMETERS
6488  |
6489  | KNOWN ISSUES
6490  |
6491  |
6492  |
6493  | NOTES
6494  |
6495  |
6496  |
6497  | MODIFICATION HISTORY
6498  | Date          Author       Description of Changes
6499  | 17-Aug-2005   rsinthre     Created
6500  +============================================================*/
6501   PROCEDURE update_cc_bill_to_site(
6502 		p_cc_location_rec	IN   HZ_LOCATION_V2PUB.LOCATION_REC_TYPE,
6503 		x_cc_bill_to_site_id	IN  NUMBER,
6504 		x_return_status		OUT NOCOPY VARCHAR2,
6505 		x_msg_count		OUT NOCOPY NUMBER,
6506 		x_msg_data		OUT NOCOPY VARCHAR2) IS
6507 
6508 l_location_id			NUMBER(15,0);
6509 l_location_rec			HZ_LOCATION_V2PUB.LOCATION_REC_TYPE;
6510 l_party_site_rec		HZ_PARTY_SITE_V2PUB.party_site_rec_type;
6511 l_party_site_number		VARCHAR2(30);
6512 l_object_version_number		NUMBER(15,0);
6513 
6514 CURSOR location_id_cur IS
6515 	select hps.location_id, hl.object_version_number
6516 	from hz_party_sites hps, hz_locations hl
6517 	where party_site_id = x_cc_bill_to_site_id
6518 	and hps.location_id = hl.location_id;
6519 
6520 location_id_rec	location_id_cur%ROWTYPE;
6521 
6522 l_procedure_name		VARCHAR2(30);
6523 l_debug_info	 	        VARCHAR2(200);
6524 
6525 BEGIN
6526 	l_procedure_name  := '.update_cc_bill_to_site';
6527 -----------------------------------------------------------------------------------------
6528   l_debug_info := 'Call TCA update location - update_location - to update location for CC';
6529 -----------------------------------------------------------------------------------------
6530           write_debug_and_log('Site_id_to_update'|| x_cc_bill_to_site_id);
6531 
6532 --Get LocationId from PartySiteId and update the location
6533 		OPEN location_id_cur;
6534 		FETCH location_id_cur INTO location_id_rec;
6535 		IF(location_id_cur%FOUND) THEN
6536 			l_location_id		:= location_id_rec.location_id;
6537 			l_object_version_number	:= location_id_rec.object_version_number;
6538 		ELSE
6539 		   write_debug_and_log('No Location found for site:'||x_cc_bill_to_site_id );
6540 		   x_return_status := FND_API.G_RET_STS_ERROR;
6541 		   write_error_messages(x_msg_data, x_msg_count);
6542 		   RETURN;
6543 		END IF;
6544 		CLOSE location_id_cur;
6545 
6546 		write_debug_and_log('Loaction id to update:'|| l_location_id);
6547 
6548 		l_location_rec.location_id	:= l_location_id;
6549 		l_location_rec.country		:= p_cc_location_rec.country;
6550 		l_location_rec.address1		:= p_cc_location_rec.address1;
6551 		l_location_rec.address2		:= p_cc_location_rec.address2;
6552 		l_location_rec.address3		:= p_cc_location_rec.address3;
6553 		l_location_rec.city		:= p_cc_location_rec.city;
6554 		l_location_rec.postal_code	:= p_cc_location_rec.postal_code;
6555 		l_location_rec.state		:= p_cc_location_rec.state;
6556 		l_location_rec.county		:= p_cc_location_rec.county;
6557 
6558 		HZ_LOCATION_V2PUB.update_location(
6559 		p_init_msg_list             => FND_API.G_TRUE,
6560 		p_location_rec              => l_location_rec,
6561 		p_object_version_number     => l_object_version_number,
6562 		x_return_status             => x_return_status,
6563 		x_msg_count                 => x_msg_count,
6564 		x_msg_data                  => x_msg_data);
6565 
6566 		IF ( x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
6567 	          x_return_status := FND_API.G_RET_STS_ERROR;
6568 	          write_error_messages(x_msg_data, x_msg_count);
6569 	          RETURN;
6570 		END IF;
6571 
6572 EXCEPTION
6573     WHEN OTHERS THEN
6574 	    x_return_status := FND_API.G_RET_STS_ERROR;
6575 
6576             write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
6577 
6578 	    write_debug_and_log('l_location_id'|| l_location_id);
6579             write_debug_and_log('- Return Status: '||x_return_status);
6580             write_debug_and_log(SQLERRM);
6581 
6582             FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
6583             FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
6584             FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
6585             FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
6586             FND_MSG_PUB.ADD;
6587 
6588 END update_cc_bill_to_site;
6589 
6590  /*=====================================================================
6591  | PROCEDURE get_payment_channel_attribs
6592  |
6593  | DESCRIPTION
6594  |   Gets payment channel attribute usages
6595  |
6596  | PARAMETERS
6597  |   p_channel_code	IN  	    VARCHAR2
6598  |   x_return_status 	OUT NOCOPY  VARCHAR2
6599  |   x_cvv_use 		OUT NOCOPY  VARCHAR2
6600  |   x_billing_addr_use	OUT NOCOPY  VARCHAR2
6601  |   x_msg_count        OUT NOCOPY  NUMBER
6602  |   x_msg_data         OUT NOCOPY  VARCHAR2
6603  |
6604  | HISTORY
6605  |   20-SEP-2006     abathini      Created
6606  |
6607  +=====================================================================*/
6608 PROCEDURE get_payment_channel_attribs(	p_channel_code 		IN 	    VARCHAR2,
6609 					x_return_status 	OUT NOCOPY  VARCHAR2,
6610 					x_cvv_use 		OUT NOCOPY  VARCHAR2,
6611 					x_billing_addr_use	OUT NOCOPY  VARCHAR2,
6612 					x_msg_count           	OUT NOCOPY  NUMBER,
6613 					x_msg_data            	OUT NOCOPY  VARCHAR2
6614 				     )
6615 IS
6616 useRecType IBY_FNDCPT_SETUP_PUB.PmtChannel_AttribUses_rec_type;
6617 resRecType IBY_FNDCPT_COMMON_PUB.Result_rec_type;
6618 l_procedure_name		VARCHAR2(50);
6619 l_debug_info	 	        VARCHAR2(200);
6620 BEGIN
6621 
6622  l_procedure_name := '.get_payment_channel_attribs';
6623  -----------------------------------------------------------------------------------------
6624  l_debug_info := 'Call IBY_FNDCPT_SETUP_PUB.Get_Payment_Channel_Attribs - to get payment channel attribute usages';
6625  -----------------------------------------------------------------------------------------
6626     IBY_FNDCPT_SETUP_PUB.Get_Payment_Channel_Attribs
6627     (
6628             p_api_version 		=> 1.0,
6629             x_return_status 	=> x_return_status,
6630             x_msg_count 		=> x_msg_count,
6631             x_msg_data 		=> x_msg_data,
6632             p_channel_code 		=> p_channel_code,
6633             x_channel_attrib_uses	=> useRecType,
6634             x_response 		=> resRecType
6635     );
6636 
6637     x_cvv_use := useRecType.Instr_SecCode_Use;
6638     x_billing_addr_use := useRecType.Instr_Billing_Address;
6639 
6640 EXCEPTION
6641     WHEN OTHERS THEN
6642 	    x_return_status := FND_API.G_RET_STS_ERROR;
6643 
6644             write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
6645 
6646 	    write_debug_and_log('p_channel_code'|| p_channel_code);
6647             write_debug_and_log('- Return Status: '||x_return_status);
6648             write_debug_and_log(SQLERRM);
6649 
6650             FND_MESSAGE.SET_NAME ('AR','ARI_REG_DISPLAY_UNEXP_ERROR');
6651             FND_MESSAGE.SET_TOKEN('PROCEDURE', G_PKG_NAME || l_procedure_name);
6652             FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
6653             FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
6654             FND_MSG_PUB.ADD;
6655 END get_payment_channel_attribs;
6656 
6657 /*=====================================================================
6658  | PROCEDURE update_invoice_payment_status
6659  |
6660  | DESCRIPTION
6661  |   This procedure will update the PAYMENT_APPROVAL column in ar_payment_schedules
6662  |   with the value p_inv_pay_status for the records in p_payment_schedule_id_list
6663  |
6664  | PARAMETERS
6665  |   p_payment_schedule_id_list	   IN     Inv_list_table_type
6666  |   p_inv_pay_status     		   IN     VARCHAR2
6667  |
6668  | HISTORY
6669  |   17-FEB-2007     abathini      	   Created
6670  |
6671  +=====================================================================*/
6672 
6673 PROCEDURE update_invoice_payment_status( p_payment_schedule_id_list	IN Inv_list_table_type,
6674                                  	     p_inv_pay_status			IN VARCHAR2,
6675                                  	     x_return_status			OUT  NOCOPY VARCHAR2,
6676 				                 x_msg_count            		OUT  NOCOPY NUMBER,
6677 				                 x_msg_data             		OUT  NOCOPY VARCHAR2
6678                                  ) IS
6679 
6680 l_last_update_login		NUMBER(15);
6681 l_last_update_date		DATE;
6682 l_last_updated_by		NUMBER(15);
6683 
6684 BEGIN
6685 
6686     l_last_update_login     := FND_GLOBAL.LOGIN_ID;
6687     l_last_update_date      := sysdate;
6688     l_last_updated_by       := FND_GLOBAL.USER_ID;
6689 
6690    FORALL trx
6691     IN p_payment_schedule_id_list.first .. p_payment_schedule_id_list.last
6692     UPDATE AR_PAYMENT_SCHEDULES set PAYMENT_APPROVAL =  p_inv_pay_status,
6693     LAST_UPDATE_DATE = l_last_update_date, LAST_UPDATED_BY = l_last_updated_by,
6694     LAST_UPDATE_LOGIN = l_last_update_login
6695     where payment_schedule_id = p_payment_schedule_id_list(trx);
6696 
6697     x_return_status := FND_API.G_RET_STS_SUCCESS;
6698     x_msg_count := 0;
6699 
6700 EXCEPTION
6701     WHEN OTHERS THEN
6702       x_return_status := FND_API.G_RET_STS_ERROR;
6703       FND_MSG_PUB.count_and_get(p_encoded => fnd_api.g_false,
6704                                 p_count => x_msg_count,
6705                                 p_data  => x_msg_data);
6706 
6707 END update_invoice_payment_status;
6708 
6709 /*=====================================================================
6710  | FUNCTION get_customer_site_use_id
6711  |
6712  | DESCRIPTION
6713  | This function checks if the user has access to the primary bill to site
6714  | of the customer. If yes, then returns that site id.
6715  | else, checks if the transactions selected by the user belongs
6716  | to a same site. If yes, then return that site id else, returns -1.
6717  |
6718  | PARAMETERS
6719  |   p_session_id  IN   NUMBER
6720  |   p_customer_id IN   NUMBER
6721  |
6722  | RETURN
6723  |   l_customer_site_use_id  NUMBER
6724  | HISTORY
6725  |   29-Oct-2009     rsinthre              Created
6726  |
6727  +=====================================================================*/
6728 
6729  FUNCTION get_customer_site_use_id (p_session_id IN NUMBER,
6730                                     p_customer_id IN NUMBER
6731                                    )
6732 				 RETURN NUMBER
6733  IS
6734 
6735  l_customer_site_use_id  NUMBER;
6736  l_debug_info		 VARCHAR2(200);
6737  l_procedure_name 	 VARCHAR2(30);
6738 
6739  e_no_rows_in_GT EXCEPTION;
6740 
6741  CURSOR get_cust_site_use_id_cur IS
6742 	SELECT DISTINCT pay_for_customer_site_id
6743 	FROM   ar_irec_payment_list_gt
6744 	WHERE  customer_id = p_customer_id;
6745 
6746  BEGIN
6747 
6748   l_procedure_name := '.get_customer_site_use_id';
6749   l_customer_site_use_id := NULL;
6750 
6751   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
6752 	  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name, 'Begin+');
6753 	  fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,
6754             'p_session_id=' || p_session_id ||
6755             'p_user_id=' || FND_GLOBAL.user_id ||
6756             'p_customer_id=' || p_customer_id);
6757   end if;
6758 
6759 
6760   ---------------------------------------------------------------------------
6761   l_debug_info := 'Check if the user has access to the primary bill to site id';
6762   ---------------------------------------------------------------------------
6763   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
6764 	 fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,l_debug_info);
6765   end if;
6766 
6767   BEGIN
6768 
6769       SELECT  usite.customer_site_use_id
6770       INTO    l_customer_site_use_id
6771       FROM    ar_irec_user_acct_sites_all usite,
6772               hz_cust_site_uses hzcsite
6773       WHERE
6774       usite.session_id 	    =	p_session_id
6775       AND usite.customer_id	    =	p_customer_id
6776       AND usite.user_id 	    =	FND_GLOBAL.user_id
6777       AND hzcsite.site_use_id   =	usite.customer_site_use_id
6778       AND hzcsite.primary_flag  =	'Y'
6779       AND hzcsite.site_use_code =	'BILL_TO'
6780       AND hzcsite.status 	    =	'A' ;
6781   EXCEPTION
6782 	WHEN NO_DATA_FOUND THEN
6783 	l_customer_site_use_id := NULL;
6784   END;
6785 
6786   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
6787 	 fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Check for acess to the Primary bill to site returned site id=' || l_customer_site_use_id);
6788   end if;
6789 
6790   IF (l_customer_site_use_id IS NULL) THEN
6791   /* So, user does not have access to primary bill to site
6792     Check, if the selected transactions belong to a same site. If yes, then return that site id else return -1.
6793   */
6794      OPEN get_cust_site_use_id_cur;
6795      LOOP
6796           FETCH get_cust_site_use_id_cur INTO l_customer_site_use_id ;
6797 
6798           IF get_cust_site_use_id_cur%ROWCOUNT >1 THEN
6799                if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
6800                   fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'The selected transactions belong to more than one site');
6801                end if;
6802               l_customer_site_use_id := -1;
6803               EXIT;
6804           ELSIF get_cust_site_use_id_cur%ROWCOUNT = 0 THEN
6805                if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
6806                   fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Query on ar_irec_payment_list_gt returned 0 rows');
6807                end if;
6808                RAISE e_no_rows_in_GT;
6809                EXIT;
6810           END IF;
6811 
6812           EXIT WHEN get_cust_site_use_id_cur%NOTFOUND OR get_cust_site_use_id_cur%NOTFOUND IS NULL;
6813      END LOOP;
6814      CLOSE get_cust_site_use_id_cur;
6815 
6816   END IF;
6817 
6818   if( FND_LOG.LEVEL_STATEMENT >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) then
6819       fnd_log.string(fnd_log.LEVEL_STATEMENT,G_PKG_NAME||l_procedure_name,'Return val: l_customer_site_use_id=' || l_customer_site_use_id);
6820   end if;
6821 
6822  RETURN l_customer_site_use_id;
6823 
6824  EXCEPTION
6825     WHEN e_no_rows_in_GT THEN
6826       write_debug_and_log('No rows present in ar_irec_payment_list_gt for the given customer in ' || G_PKG_NAME || l_procedure_name);
6827       write_debug_and_log('p_session_id: '|| p_session_id);
6828       write_debug_and_log('p_user_id: '|| FND_GLOBAL.user_id);
6829       write_debug_and_log('p_customer_id: '|| p_customer_id);
6830 
6831     WHEN OTHERS THEN
6832       write_debug_and_log('Unexpected Exception in ' || G_PKG_NAME || l_procedure_name);
6833       write_debug_and_log('ERROR =>'|| SQLERRM);
6834       write_debug_and_log('p_session_id: '|| p_session_id);
6835       write_debug_and_log('p_user_id: '|| FND_GLOBAL.user_id);
6836       write_debug_and_log('p_customer_id: '|| p_customer_id);
6837 
6838 
6839  END get_customer_site_use_id;
6840 
6841  /*============================================================
6842   | PUBLIC function get_future_discount_wrapper
6843   |
6844   | DESCRIPTION
6845   |   This is a function that is a wrapper to call the AR API for calculating
6846   |   future discounts.
6847   |
6848   | PSEUDO CODE/LOGIC
6849   |
6850   | PARAMETERS
6851   |
6852   | KNOWN ISSUES
6853   |
6854   |
6855   |
6856   | NOTES
6857   |
6858   |
6859   |
6860   | MODIFICATION HISTORY
6861   | Date          Author       Description of Changes
6862   | 06-MAY-2011   rsinthre     Created for bug 10106518
6863   +============================================================*/
6864 FUNCTION get_future_discount_wrapper ( p_ps_id	  	   IN ar_payment_schedules.payment_schedule_id%TYPE,
6865                                        p_in_applied_amount IN NUMBER,
6866                                        p_discount_date     IN DATE DEFAULT NULL) RETURN NUMBER IS
6867     l_discount_amount NUMBER;
6868     l_rem_amt_rcpt    NUMBER;
6869     l_rem_amt_inv     NUMBER;
6870     l_grace_days_flag VARCHAR2(2);
6871     l_discount_date DATE;
6872 
6873   BEGIN
6874      -- Check if grace days have to be considered for discount.
6875      l_grace_days_flag := is_grace_days_enabled_wrapper();
6876      if(p_discount_date IS NULL) then
6877       l_discount_date := trunc(sysdate);
6878     else
6879       l_discount_date := trunc(p_discount_date);
6880     end if;
6881 
6882      arp_discounts_api.get_discount(p_ps_id	        => p_ps_id,
6883 		                    p_apply_date	=> l_discount_date,
6884                             	    p_in_applied_amount => p_in_applied_amount,
6885 		                    p_grace_days_flag   => l_grace_days_flag,
6886 		                    p_out_discount      => l_discount_amount,
6887 		                    p_out_rem_amt_rcpt  => l_rem_amt_rcpt,
6888 		                    p_out_rem_amt_inv   => l_rem_amt_inv);
6889 
6890      return l_discount_amount;
6891 
6892   EXCEPTION
6893     when others then
6894         begin
6895             l_discount_amount := 0;
6896             write_debug_and_log('Unexpected Exception while calculating future discount');
6897             write_debug_and_log('- Payment Schedule Id: '||p_ps_id);
6898             write_debug_and_log(SQLERRM);
6899             return l_discount_amount;
6900         end;
6901   END;
6902 
6903 END AR_IREC_PAYMENTS;