DBA Data[Home] [Help]

PACKAGE BODY: APPS.AR_CALC_LATE_CHARGE

Source


1 PACKAGE BODY AR_CALC_LATE_CHARGE AS
2 /* $Header: ARCALATB.pls 120.40.12020000.7 2012/12/14 11:07:20 vpotti ship $           */
3 
4     l_debug_flag        	varchar2(1);
5     pg_last_updated_by          number;
6     pg_last_update_login        number;
7     l_disputed_items		varchar2(1);
8     l_request_id		number;
9 
10     TYPE CurrencyCodeType  IS TABLE OF VARCHAR2(15)  INDEX BY BINARY_INTEGER;
11     TYPE PrecisionType     IS TABLE OF NUMBER(1)     INDEX BY BINARY_INTEGER;
12     TYPE MauType           IS TABLE OF NUMBER        INDEX BY BINARY_INTEGER;
13     NextElement            BINARY_INTEGER := 0;
14     CurrencyCode           CurrencyCodeType;
15     Precision              PrecisionType;
16     Mau                    MauType;
17 
18 
19     CURSOR CurrencyCursor( cp_currency_code VARCHAR2 ) IS
20     SELECT  precision,
21             minimum_accountable_unit
22     FROM    fnd_currencies
23     WHERE   currency_code = cp_currency_code;
24 
25 PROCEDURE GetCurrencyDetails( p_currency_code IN  VARCHAR2,
26                               p_precision     OUT NOCOPY NUMBER,
27                               p_mau           OUT NOCOPY NUMBER ) IS
28     i BINARY_INTEGER := 0;
29 BEGIN
30     WHILE i < NextElement
31     LOOP
32         EXIT WHEN CurrencyCode(i) = p_currency_code;
33         i := i + 1;
34     END LOOP;
35 
36     IF i = NextElement
37     THEN
38         OPEN CurrencyCursor( p_currency_code );
39         DECLARE
40             l_Precision NUMBER;
41             l_Mau       NUMBER;
42         BEGIN
43             FETCH CurrencyCursor
44             INTO    l_Precision,
45                     l_Mau;
46             IF CurrencyCursor%NOTFOUND THEN
47                 RAISE NO_DATA_FOUND;
48             END IF;
49             Precision(i)    := l_Precision;
50             Mau(i)          := l_Mau;
51         END;
52         CLOSE CurrencyCursor;
53         CurrencyCode(i) := p_currency_code;
54         NextElement     := i + 1;
55     END IF;
56     p_precision := Precision(i);
57     p_mau       := Mau(i);
58 EXCEPTION
59     WHEN OTHERS THEN
60         IF CurrencyCursor%ISOPEN THEN
61            CLOSE CurrencyCursor;
62         END IF;
63     RAISE;
64 END;
65 
66 FUNCTION Currency_Round(p_amount		IN	NUMBER,
67 		        p_currency_code		IN	VARCHAR2) RETURN NUMBER IS
68     l_precision NUMBER(1);
69     l_mau       NUMBER;
70 BEGIN
71     GetCurrencyDetails( p_currency_code, l_precision, l_mau );
72     IF l_mau IS NOT NULL
73     THEN
74         RETURN( ROUND( p_amount / l_mau) * l_mau );
75     ELSE
76         RETURN( ROUND( p_amount, l_precision ));
77     END IF;
78 EXCEPTION
79     WHEN OTHERS THEN
80         RAISE;
81 END Currency_Round;
82 
83 
84 /*----------------------------------------------------|
85 | PROCEDURE debug                                     |
86 |-----------------------------------------------------|
87 |  Parameters                                         |
88 |                 mesg        in  varchar2            |
89 |-----------------------------------------------------|
90 |  Description                                        |
91 |           Takes message string as an argument and   |
92 |           outputs to request log depending on debug |
93 |           flag                                      |
94 |----------------------------------------------------*/
95 
96 
97 procedure debug (mesg in varchar2) is
98 
99 begin
100         FND_FILE.PUT_LINE( FND_FILE.LOG,mesg);
101 end debug;
102 
103 /* Function which returns the next value for the interest_header_id
104    This is required as the sequence value can not be derived in
105    a subquery */
106 FUNCTION get_next_hdr_id RETURN NUMBER IS
107   l_next_hdr_id	   NUMBER;
108 BEGIN
109 
110   select ar_interest_headers_s.nextval
111   into   l_next_hdr_id
112   from dual;
113 
114   return l_next_hdr_id;
115 
116 END get_next_hdr_id;
117 
118 Function first_day(p_calculation_date    IN     DATE ) RETURN DATE IS
119   /* Function which returns the first day of the month corresponding to
120      the input date */
121 begin
122 
123   return(to_date(('01/'||to_char(p_calculation_date,'MM/YYYY')),'DD/MM/YYYY'));
124   --return(last_day(add_months(p_calculation_date,-1))+1);
125 
126 end first_day;
127 
128 
129 Function Calculate_Interest (p_amount 	       		IN	NUMBER,
130                              p_formula         		IN	VARCHAR2,
131                              p_days_late     		IN	NUMBER,
132                              p_interest_rate  		IN	NUMBER,
133                              p_days_in_period		IN	NUMBER,
134                              p_currency   	     	IN	VARCHAR2,
135 			     p_payment_schedule_id	IN	NUMBER DEFAULT NULL) return NUMBER IS
136 l_interest      	     number;
137 BEGIN
138 
139    IF l_debug_flag = 'Y' THEN
140 	debug('ar_calc_late_charge.Calculate_Interest()+ ');
141 	debug('Input Parameters.... ');
142         debug('p_payment_schedule_id	:	'||p_payment_schedule_id);
143 	debug('p_amount			:	'|| p_amount);
144 	debug('p_formula		:	'||p_formula);
145  	debug('p_days_late		:	'|| p_days_late);
146 	debug('p_interest_rate		:	'||p_interest_rate);
147 	debug('p_days_in_period		:	'||p_days_in_period);
148 	debug('p_currency		:	'||p_currency);
149    END IF;
150 
151   /* The p_forumla can be N (Meaning SIMPLE), Y (COMPOUND) or F (FLAT_RATE). Based on this, the calculation of
152      the interest will be different.
153      SIMPLE:
154      	(Interest Rate/Days in Period)/100 * Invoice Amount * Days Late
155      COMPOUND:
156 	(Interest Rate/Days in Period)/100 * (Invoice Amount + Interest Already Charged) * Days Late
157      AVERAGE_DAILY_BALANCE:
158 	Average Daily Balance * (Interest Rate) / 100
159      FLAT_RATE:
160 	Overdue Amount * Interest Rate / 100
161     */
162 
163    IF p_formula = 'N' THEN
164 	l_interest := (p_interest_rate/p_days_in_period)/100 * p_amount * p_days_late;
165    ELSIF p_formula = 'Y' THEN
166 	/* In this case, the assumption is that the p_amount includes the Interest Already Charged also */
167 	l_interest := (p_interest_rate/p_days_in_period)/100 * p_amount * p_days_late;
168    ELSIF p_formula = 'F' THEN
169 	l_interest := (p_amount) * (p_interest_rate) / 100;
170    END IF;
171 
172    IF l_debug_flag = 'Y' THEN
173 	debug('l_interest before currency rounding : '||l_interest);
174    END IF;
175 
176    IF l_interest <> 0 THEN
177 	l_interest := ar_calc_late_charge.currency_round(l_interest,p_currency);
178    END IF;
179 
180    IF l_debug_flag = 'Y' THEN
181 	debug('l_interest after currency rounding : '||l_interest);
182 	debug('ar_calc_late_charge.Calculate_Interest()- ');
183    END IF;
184 
185    return l_interest;
186 
187 END Calculate_Interest;
188 
189 
190 /* Bug 8556955 Added procedure to calculate late charges for Invoices in
191    case receipt is reversed.
192 */
193 Procedure Insert_int_rev_rect_overdue( p_fin_charge_date        IN      DATE,
194                                        p_worker_number          IN      NUMBER,
195                                        p_total_workers          IN      NUMBER) IS
196 
197  l_fin_charge_date              DATE;
198  l_worker_number                number;
199  l_total_workers                number;
200 
201 BEGIN
202 
203    IF l_debug_flag = 'Y' THEN
204                 debug('Interest_int_rec_rect_overdue+');
205    END IF;
206 
207             l_fin_charge_date   :=      p_fin_charge_date;
208             l_worker_number     :=      p_worker_number;
209             l_total_workers     :=      p_total_workers;
210 
211 Insert into ar_late_charge_trx_t
212                 (late_charge_trx_id,
213                  customer_id,
214                  customer_site_use_id,
215                  currency_code,
216                  customer_trx_id,
217                  legal_entity_id,
218                  payment_schedule_id,
219                  class,
220                  amount_due_original,
221                  amount_due_remaining,
222                  fin_charge_charged,
223                  trx_date,
224                  cust_trx_type_id,
225                  last_charge_date,
226                  exchange_rate_type,
227                  min_interest_charge,
228                  max_interest_charge,
229                  overdue_late_pay_amount,
230                  original_balance,
231                  due_date,
232                  receipt_date,
233                  finance_charge_date,
234                  charge_type,
235                  actual_date_closed,
236                  interest_rate,
237                  interest_days,
238                  rate_start_date,
239                  rate_end_date,
240                  schedule_days_start,
241                  schedule_days_to,
242                  late_charge_amount,
243                  late_charge_type,
244                  late_charge_term_id,
245                  interest_period_days,
246                  interest_calculation_period,
247                  charge_on_finance_charge_flag,
248                  message_text_id,
249                  interest_type,
250                  min_fc_invoice_overdue_type,
251                  min_fc_invoice_amount,
252                  min_fc_invoice_percent,
253                  charge_line_type,
254                  org_id,
255                  request_id,
256                  display_flag )
257         SELECT   ar_late_charge_trx_s.nextval,
258                  b.customer_id,
259                  b.customer_site_use_id ,
260                  b.invoice_currency_code,
261                  b.customer_trx_id,
262                  b.legal_entity_id,
263                  b.payment_schedule_id,
264                  b.class ,
265                  b.amount_due_original,
266                  b.amount_due_remaining ,
267                  b.finance_charge_charged,
268                  b.trx_date,
269                  b.cust_trx_type_id,
270                  NVL(b.last_charge_date, decode(b.finance_charge_charged,
271                                                    0, NULL,
272                                                    b.last_accrue_charge_date)) last_charge_date,
273                  b.exchange_rate_type,
274                  b.min_interest_charge,
275                  b.max_interest_charge,
276                  b.overdue_amt,
277                  b.original_balance,
278                  b.due_date,
279                  NULL,
280                  b.fin_charge_date,
281                  b.charge_type,
282                  b.actual_date_closed,
283                  decode(b.interest_type,
284                         'CHARGES_SCHEDULE',sched_lines.rate,
285                         'FIXED_RATE',b.interest_rate, NULL) interest_rate,
286                  least(decode(b.multiple_interest_rates_flag,
287                                   'Y',decode(sched_hdrs.schedule_header_type,
288                                              'RATE',
289                                               nvl(sched_hdrs.end_date,b.eff_fin_charge_date),
290                                               b.eff_fin_charge_date),
291                                     b.eff_fin_charge_date)) -
292                    greatest(decode(b.multiple_interest_rates_flag,
293                                   'Y',decode(sched_hdrs.schedule_header_type,
294                                              'RATE',sched_hdrs.start_date-1,b.eff_due_date),
295                                        b.eff_due_date), b.eff_due_date,b.eff_last_charge_date) interest_days,
296                  sched_hdrs.start_date rate_start_date,
297                  sched_hdrs.end_date rate_end_date,
298                  bucket_lines.days_start schedule_days_start,
299                  bucket_lines.days_to  schedule_days_to,
300                  decode(b.interest_type,
301                         'FIXED_AMOUNT',0,
302                         'CHARGE_PER_TIER',0 ,
303                               decode(sched_hdrs.schedule_header_type,
304                                        'AMOUNT',0,
305                                         ar_calc_late_charge.calculate_interest(
306                                                            decode(b.charge_on_finance_charge_flag,
307 							          'F',0,b.overdue_amt),
308                                                            b.charge_on_finance_charge_flag,
309                                                            least(decode(b.multiple_interest_rates_flag,
310                                                                        'Y',decode(sched_hdrs.schedule_header_type,
311                                                                                   'RATE',
312                                                                                    nvl(sched_hdrs.end_date,
313                                                                                          b.eff_fin_charge_date),
314                                                                                    b.eff_fin_charge_date),
315                                                                        b.eff_fin_charge_date)) -
316                                                              greatest(decode(b.multiple_interest_rates_flag,
317                                                                        'Y',decode(sched_hdrs.schedule_header_type,
318                                                                                   'RATE',sched_hdrs.start_date-1,
319                                                                                    b.eff_due_date),
320                                                                         b.eff_due_date),b.eff_due_date,
321                                                                         b.eff_last_charge_date),
322                                                             decode(b.interest_type,
323                                                                     'CHARGES_SCHEDULE',sched_lines.rate,
324                                                                      'FIXED_RATE',b.interest_rate, NULL),
325                                                             b.interest_period_days,
326                                                             b.invoice_currency_code,
327                                                             b.payment_schedule_id))) late_charge_amount,
328                  b.late_charge_type,
329                  b.late_charge_term_id,
330                  b.interest_period_days,
331                  b.interest_calculation_period,
332                  b.charge_on_finance_charge_flag,
333                  b.message_text_id,
334                  b.interest_type,
335                  b.min_fc_invoice_overdue_type,
336                  b.min_fc_invoice_amount,
337                  b.min_fc_invoice_percent,
338                  'INTEREST',
339                  b.org_id,
340                  -1,
341                  'Y'
342      from (
343                 select
344                       ps.customer_id,
345                       decode(ps.class,
346                              'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
347                                                                               ps.customer_site_use_id,
348                                                                               ps.org_id),
349                              'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
350                                                                                ps.customer_site_use_id,
351                                                                                ps.org_id),
352                               ps.customer_site_use_id) customer_site_use_id,
353                       ps.invoice_currency_code,
354                       ps.customer_trx_id,
355 		      int_headers.legal_entity_id,
356                       ps.payment_schedule_id,
357                       ps.class ,
358                       ps.amount_due_original,
359                       ps.amount_due_remaining,
360                       int_lines.interest_charged finance_charge_charged,
361                       ps.trx_date,
362                       ps.cust_trx_type_id,
363                       cr.receipt_date last_charge_date,
364                       cust_site.last_accrue_charge_date ,
365                       cust_site.exchange_rate,
366                       cust_site.exchange_rate_type,
367                       cust_site.min_interest_charge,
368                       cust_site.max_interest_charge,
369 		      nvl(int_lines.outstanding_amount,0) overdue_amt,
370 		      nvl(int_lines.outstanding_amount,0) original_balance,
371                       decode(ps.class,'PMT',ps.trx_date,ps.due_date) due_date,
372 		      l_fin_charge_date fin_charge_date,
373                       ps.actual_date_closed,
374                       cust_site.late_charge_type,
375                       cust_site.late_charge_term_id    ,
376                       cust_site.interest_period_days,
377                       cust_site.interest_calculation_period,
378                       cust_site.charge_on_finance_charge_flag,
379                       cust_site.message_text_id,
380                       cust_site.interest_type,
381                       cust_site.interest_rate,
382                       cust_site.interest_schedule_id,
383                       cust_site.min_fc_invoice_overdue_type,
384                       cust_site.min_fc_invoice_amount,
385                       cust_site.min_fc_invoice_percent,
386                       cust_site.multiple_interest_rates_flag,
387                       cust_site.hold_charged_invoices_flag,
388                       ps.org_id,
389                       cust_site.interest_fixed_amount,
390                       ps.cash_receipt_id,
391                       'OVERDUE' charge_type,
392                       decode(cust_site.interest_calculation_period,
393                         'DAILY',ps.last_charge_date,
394                         'MONTHLY',last_day(ps.last_charge_date)) eff_fin_charge_date,
395                       decode(cust_site.interest_calculation_period,
396                         'DAILY',nvl(int_lines.payment_date,
397                                     decode(int_lines.finance_charge_charged,
398                                            0,int_lines.due_date,
399                                            int_lines.last_charge_date)),
400                         'MONTHLY',first_day(nvl(int_lines.last_charge_date,
401                                                 decode(int_lines.finance_charge_charged,
402                                                        0,int_lines.due_date,
403                                                        int_lines.last_charge_date)))) eff_last_charge_date,
404                       decode(cust_site.interest_calculation_period,
405                              'DAILY',int_lines.due_date,
406                              'MONTHLY',first_day(int_lines.due_date)) eff_due_date
407                       from ar_interest_lines int_lines,
408 		      ar_interest_headers int_headers,
409                       ar_cash_receipts cr,
410                       ar_payment_schedules ps,
411                       ar_lc_cust_sites_t cust_site,
412                       ar_late_charge_cust_balance_gt bal
413                       where ps.customer_id = cust_site.customer_id
414                       and   cust_site.customer_site_use_id = decode(ps.class,
415                                                        'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
416                                                                                                ps.customer_site_use_id,
417                                                                                                ps.org_id),
418                                                        'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
419                                                                                               ps.customer_site_use_id,
420                                                                                               ps.org_id),
421                                                          ps.customer_site_use_id)
422                       and   ps.invoice_currency_code = cust_site.currency_code
423                       and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
424                                           decode(l_total_workers,l_worker_number,0,l_worker_number)
425 		      and int_headers.customer_id=cust_site.customer_id
426                       and cr.reversal_date is not null
427                       and cr.cash_receipt_id=int_lines.cash_receipt_id
428                       and ps.payment_schedule_id=int_lines.payment_schedule_id
429                       and   ps.org_id = cust_site.org_id
430                       and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE')
431                       and int_lines.type='LATE'
432 		      and int_lines.interest_header_id=int_headers.interest_header_id
433 --                      and   cust_site.late_charge_type = 'INV'
434                    /* Apply Customer Level tolerances */
435                      and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
436                      and   cust_site.org_id = bal.org_id
437                      and   decode(cust_site.min_fc_balance_overdue_type,
438                          'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
439                                     * nvl(bal.customer_open_balance,0)/100),
440                          'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
441                             0) <= nvl(bal.customer_overdue_balance,0)
442 		      /* Added NVL() for cust_site.credit_items_flag as part of Bug 10280458, manishri */
443                       and   decode(nvl(cust_site.disputed_transactions_flag,'N'),
444                                 'N',decode(nvl(ps.amount_in_dispute,0),
445                                            0, 'Y','N'),
446                                 'Y' ) = 'Y'
447                       and   decode(nvl(cust_site.credit_items_flag, 'N'),'N',
448                             decode (ps.class, 'PMT','N','CM','N','INV',decode(sign(ps.amount_due_original),-1,'N','Y'),'Y'),'Y') = 'Y'
449                       and   nvl(ps.receipt_confirmed_flag, 'Y') = 'Y'
450                       and ps.last_charge_date > cr.receipt_date
451                       and cr.reversal_date < l_fin_charge_date
452                       and cr.reversal_date > ps.last_charge_date
453                 group by ps.customer_id,
454                       decode(ps.class,
455                              'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
456                                                                               ps.customer_site_use_id,
457                                                                               ps.org_id),
458                              'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
459                                                                                ps.customer_site_use_id,
460                                                                                ps.org_id),
461                               ps.customer_site_use_id),
462                       ps.invoice_currency_code,
463                       ps.customer_trx_id,
464                       int_headers.legal_entity_id,
465                       ps.payment_schedule_id,
466                       ps.class ,
467                       ps.amount_due_original,
468                       ps.amount_due_remaining,
469                       int_lines.interest_charged,
470                       ps.trx_date,
471                       ps.cust_trx_type_id,
472                       cr.receipt_date,
473                       cust_site.last_accrue_charge_date,
474                       cust_site.exchange_rate,
475                       cust_site.exchange_rate_type,
476                       cust_site.min_interest_charge,
477                       cust_site.max_interest_charge,
478                       nvl(int_lines.outstanding_amount,0),
479 		      nvl(int_lines.outstanding_amount,0),
480                       decode(ps.class,'PMT',ps.trx_date,ps.due_date),
481 		      l_fin_charge_date ,
482                       ps.actual_date_closed,
483                       cust_site.late_charge_type,
484                       cust_site.late_charge_term_id,
485                       cust_site.interest_period_days,
486                       cust_site.interest_calculation_period,
487                       cust_site.charge_on_finance_charge_flag,
488                       cust_site.message_text_id,
489                       cust_site.interest_type,
490                       cust_site.interest_rate,
491                       cust_site.interest_schedule_id,
492                       cust_site.min_fc_invoice_overdue_type,
493                       cust_site.min_fc_invoice_amount,
494                       cust_site.min_fc_invoice_percent,
495                       cust_site.multiple_interest_rates_flag,
496                       cust_site.hold_charged_invoices_flag,
497                       ps.org_id,
498                       cust_site.interest_fixed_amount,
499                       ps.cash_receipt_id,
500                       'OVERDUE',
501                       decode(cust_site.interest_calculation_period,
502                         'DAILY',ps.last_charge_date,
503                         'MONTHLY',last_day(ps.last_charge_date)),
504                       decode(cust_site.interest_calculation_period,
505                         'DAILY',nvl(int_lines.payment_date,
506                                     decode(int_lines.finance_charge_charged,
507                                            0,int_lines.due_date,
508                                            int_lines.last_charge_date)),
509                         'MONTHLY',first_day(nvl(int_lines.last_charge_date,
510                                                 decode(int_lines.finance_charge_charged,
511                                                        0,int_lines.due_date,
512                                                        int_lines.last_charge_date)))),
513                       decode(cust_site.interest_calculation_period,
514                              'DAILY',int_lines.due_date,
515                              'MONTHLY',first_day(int_lines.due_date))
516                              ) b,
517                          ar_charge_schedule_hdrs sched_hdrs,
518                          ar_charge_schedule_lines  sched_lines,
519                          ar_aging_bucket_lines bucket_lines
520                 where b.interest_schedule_id = sched_hdrs.schedule_id(+)
521                 and   sched_hdrs.schedule_header_id = sched_lines.schedule_header_id(+)
522                 and   sched_hdrs.schedule_id = sched_lines.schedule_id(+)
523                 and    nvl(sched_hdrs.status,'A') = 'A'
524                 and   sched_lines.aging_bucket_id = bucket_lines.aging_bucket_id(+)
525                 and   sched_lines.aging_bucket_line_id = bucket_lines.aging_bucket_line_id(+)
526                 /* Condition 1: days late should be between the bucket lines start and end days */
527                 and   (l_fin_charge_date- b.due_date) >= nvl(bucket_lines.days_start,(l_fin_charge_date- b.due_date))
528                 and   (l_fin_charge_date - b.due_date) <= nvl(bucket_lines.days_to,(l_fin_charge_date- b.due_date))
529                 /* Condition 2:
530                    Start_date of the schedule should be less than or equal to the finance charge date */
531                 and   nvl(sched_hdrs.start_date,l_fin_charge_date) <= l_fin_charge_date
532                /* condition 3:
533                   If multiple interest rates have to be used, end date of the schedule should be greater than
534                   or equal to the due date or the date from which we are calculating the charge
535                   Otherwise, the end_date should either be null or it should be greater than the
536                   due_date
537                 */
538                 and  (decode(b.multiple_interest_rates_flag,'Y',
539                              decode(sched_hdrs.schedule_header_type,
540                                     'RATE',greatest(b.due_date,nvl(b.last_charge_date,b.due_date)),
541                                     b.due_date),
542                              b.due_date) <= sched_hdrs.end_date
543                        OR sched_hdrs.end_date IS NULL )
544                 /* Condition 4: If multiple rates need not be used, we should pick up the rate
545                    that is effective on the due_date of the transaction.
546                    Also note that the multiple interest rates are used only for Interest
547                    Calculation and only when rates are used*/
548                 and decode(b.multiple_interest_rates_flag,'Y',
549                        decode(sched_hdrs.schedule_header_type,
550                                'RATE',sched_hdrs.start_date,
551                                b.due_date),
552                        b.due_date )>= nvl(sched_hdrs.start_date,b.due_date);
553 
554 
555    IF l_debug_flag = 'Y' THEN
556         debug('Interest_int_rec_rect_overdue-');
557    END IF;
558 
559 
560 
561 
562 END;
563 
564 
565 /*========================================================================+
566   Update the amount by distributing applicable interest amount evenly
567   across the all late charge interest rows.
568  ========================================================================*/
569 
570 
571 /*Late charge Case of charge per tier.*/
572 /*Enhancement 6469663*/
573 PROCEDURE update_interest_amt(p_line_type in VARCHAR2) IS
574 
575   CURSOR recordPerCust(l_line_type IN VARCHAR2) IS
576   SELECT count(*) reccount,sum(amount_due_original) total_due_org,
577          CUSTOMER_ID,CUSTOMER_SITE_USE_ID,SCHEDULE_DAYS_START,SCHEDULE_DAYS_TO,CURRENCY_CODE,
578          LATE_CHARGE_AMOUNT,LATE_CHARGE_TYPE,ORG_ID
579   FROM  AR_LATE_CHARGE_TRX_T
580   WHERE INTEREST_TYPE = 'CHARGE_PER_TIER'
581   /*and   LATE_CHARGE_TYPE = l_charge_type /*'INV'*/
582   AND   CHARGE_LINE_TYPE = l_line_type   /*'INTEREST' /* l_line_type*/
583   AND OVERDUE_LATE_PAY_AMOUNT > 0
584   AND DECODE(charge_line_type,'INTEREST',DECODE (MIN_FC_INVOICE_OVERDUE_TYPE, /*Bug 11704667*/
585                  'AMOUNT',MIN_FC_INVOICE_AMOUNT ,
586                  'PERCENT',(nvl(MIN_FC_INVOICE_PERCENT,0) * AMOUNT_DUE_ORIGINAL/100),
587                             nvl(ORIGINAL_BALANCE,0)),1) <= decode(charge_line_type,'INTEREST',ORIGINAL_BALANCE,1) /*Bug 11704667*/
588   GROUP BY
589   CUSTOMER_ID,
590   CUSTOMER_SITE_USE_ID,
591   SCHEDULE_DAYS_START,
592   SCHEDULE_DAYS_TO,
593   CURRENCY_CODE,
594   LATE_CHARGE_AMOUNT,
595   LATE_CHARGE_TYPE,
596   ORG_ID;
597 
598   CURSOR trx_t(l_line_type IN VARCHAR2) IS
599   SELECT LATE_CHARGE_TRX_ID,CUSTOMER_ID,CUSTOMER_SITE_USE_ID,SCHEDULE_DAYS_START,SCHEDULE_DAYS_TO,CURRENCY_CODE,
600          LATE_CHARGE_TYPE,ORG_ID,AMOUNT_DUE_ORIGINAL
601   FROM AR_LATE_CHARGE_TRX_T
602   WHERE INTEREST_TYPE = 'CHARGE_PER_TIER'
603 /*  and   LATE_CHARGE_TYPE =  l_charge_type /*'INV'*/
604   AND   CHARGE_LINE_TYPE =  l_line_type /*'INTEREST';  /* l_line_type;*/
605   AND OVERDUE_LATE_PAY_AMOUNT > 0
606   AND DECODE(charge_line_type,'INTEREST',DECODE (MIN_FC_INVOICE_OVERDUE_TYPE, /*Bug 11704667*/
607                  'AMOUNT',MIN_FC_INVOICE_AMOUNT ,
608                  'PERCENT',(nvl(MIN_FC_INVOICE_PERCENT,0) * AMOUNT_DUE_ORIGINAL/100),
609                             nvl(ORIGINAL_BALANCE,0)),1) <=  decode(charge_line_type,'INTEREST',ORIGINAL_BALANCE,1); /*Bug 11704667*/
610 
611 
612  TYPE rec_per_customer IS  RECORD
613  (
614    rec_per_tier         NUMBER,
615    total_due_org        NUMBER,
616    customer_id          NUMBER,
617    customer_site_use_id NUMBER,
618    schdl_start          NUMBER,
619    schdl_to             NUMBER,
620    currency_code        VARCHAR2(15),
621    late_charge_type     VARCHAR2(5),
622    curr_code		VARCHAR2(15),
623    org_id               NUMBER,
624    late_charge_amt      NUMBER,
625    last_amt             NUMBER
626  );
627  TYPE rec_per_cust_tier is  table of rec_per_customer index by binary_integer;
628  p_rec_cust_per_tier rec_per_cust_tier;
629 
630  TYPE cust_trx_id is table of ar_late_charge_trx_t.late_charge_trx_id%TYPE INDEX BY BINARY_INTEGER;
631  p_cust_sites_id cust_trx_id;
632 
633 
634  TYPE lc_per_trx is  table of ar_late_charge_trx_t.late_charge_amount%type INDEX BY BINARY_INTEGER;
635  p_lc_per_trx lc_per_trx;
636 
637  i number;
638  j number;
639  l_temp_amt number;
640 BEGIN
641  IF l_debug_flag = 'Y' THEN
642    debug('update interest amount+');
643  END IF;
644 
645 /*Bug 8559863 Restrict to 0 out late charge for charge per tier case. It results in inaccurate late charges
646   for other scenario. Fixed as part of this bug*/
647  UPDATE ar_late_charge_trx_t SET late_charge_amount =  0 where amount_due_original < 0
648  AND INTEREST_TYPE = 'CHARGE_PER_TIER';
649  i := 0;
650  FOR recpertier in recordPerCust(p_line_type)
651  LOOP
652     BEGIN
653      i := i+1;
654      p_rec_cust_per_tier(i).rec_per_tier          := recpertier.reccount;
655      p_rec_cust_per_tier(i).customer_id           := recpertier.customer_id;
656      p_rec_cust_per_tier(i).customer_site_use_id  := recpertier.customer_site_use_id;
657      p_rec_cust_per_tier(i).schdl_start           := recpertier.schedule_days_start;
658      p_rec_cust_per_tier(i).schdl_to              := recpertier.schedule_days_to;
659      p_rec_cust_per_tier(i).currency_code         := recpertier.currency_code;
660      p_rec_cust_per_tier(i).late_charge_type      := recpertier.late_charge_type;
661      p_rec_cust_per_tier(i).curr_code             := recpertier.currency_code;
662      p_rec_cust_per_tier(i).org_id		  := recpertier.org_id;
663      p_rec_cust_per_tier(i).total_due_org         := recpertier.total_due_org;
664      p_rec_cust_per_tier(i).late_charge_amt       := recpertier.late_charge_amount;
665      p_rec_cust_per_tier(i).last_amt              := recpertier.late_charge_amount;
666      EXCEPTION
667      WHEN OTHERS THEN
668      debug('Error ' ||substr( sqlerrm,1,50));
669      END;
670  END LOOP;
671 
672  j := 0;
673  FOR lc_trx in trx_t(p_line_type)
674  LOOP
675    FOR trx_count in 1.. p_rec_cust_per_tier.count
676    LOOP
677      IF p_rec_cust_per_tier(trx_count).customer_id             = lc_trx.customer_id
678        AND p_rec_cust_per_tier(trx_count).currency_code	       = lc_trx.currency_code
679        AND p_rec_cust_per_tier(trx_count).schdl_start 	       = lc_trx.schedule_days_start
680        AND p_rec_cust_per_tier(trx_count).schdl_to             = lc_trx.schedule_days_to
681        AND p_rec_cust_per_tier(trx_count).late_charge_type     = lc_trx.late_charge_type
682        AND p_rec_cust_per_tier(trx_count).customer_site_use_id = lc_trx.customer_site_use_id
683        AND p_rec_cust_per_tier(trx_count).org_id               = lc_trx.org_id
684      THEN
685        j := j+1;
686        IF p_rec_cust_per_tier(trx_count).rec_per_tier = 1 THEN
687          p_lc_per_trx(j)      := p_rec_cust_per_tier(trx_count).last_amt;
688          p_cust_sites_id(j)   := lc_trx.late_charge_trx_id;
689        ELSE
690          l_temp_amt	      := Currency_round((lc_trx.amount_due_original/p_rec_cust_per_tier(trx_count).total_due_org)*p_rec_cust_per_tier(trx_count).late_charge_amt,p_rec_cust_per_tier(trx_count).curr_code);
691 
692          IF p_rec_cust_per_tier(trx_count).last_amt <= l_temp_amt and p_rec_cust_per_tier(trx_count).last_amt >= 0 THEN
693             l_temp_amt          :=p_rec_cust_per_tier(trx_count).last_amt ;
694          END IF;
695 
696          p_lc_per_trx(j)      := l_temp_amt;
697          p_cust_sites_id(j)   := lc_trx.late_charge_trx_id;
698          p_rec_cust_per_tier(trx_count).rec_per_tier := p_rec_cust_per_tier(trx_count).rec_per_tier -1;
699          p_rec_cust_per_tier(trx_count).last_amt := p_rec_cust_per_tier(trx_count).last_amt - l_temp_amt;
700        END IF;
701      END IF;
702    END LOOP;
703  END LOOP;
704   IF l_debug_flag = 'Y' THEN
705     debug('update interest amount : count  of record '  || p_lc_per_trx.count );
706   END IF;
707   IF p_lc_per_trx.count > 0 THEN
708     IF l_debug_flag = 'Y' THEN
709       FOR rec in p_cust_sites_id.FIRST..p_cust_sites_id.LAST
710       LOOP
711         debug('TRX id  ' || p_cust_sites_id(rec));
712         debug('LC Amt  ' || p_lc_per_trx(rec));
713       END LOOP;
714     END IF;
715     FORALL trxindex in p_lc_per_trx.FIRST..p_lc_per_trx.LAST
716       UPDATE ar_late_charge_trx_t set late_charge_amount = p_lc_per_trx(trxindex)
717       WHERE late_charge_trx_id = p_cust_sites_id(trxindex);
718   END IF;
719  IF l_debug_flag = 'Y' THEN
720    debug('update interest amount-');
721  END IF;
722 END update_interest_amt;
723 
724 
725 /*========================================================================+
726    Returns the site_use_id of a Late Charge Site associated with the
727    customers address if present else return NULL.
728  ========================================================================*/
729 
730 FUNCTION get_late_charge_site (
731                       p_customer_id  IN		NUMBER,
732 		      p_org_id	     IN		NUMBER) RETURN NUMBER IS
733 
734   l_late_charge_site_use_id hz_cust_site_uses.site_use_id%type;
735 
736 BEGIN
737 
738   select site_uses.site_use_id
739   into   l_late_charge_site_use_id
740   from   hz_cust_acct_sites acct_site,
741          hz_cust_site_uses site_uses
742   where  acct_site.cust_account_id    = p_customer_id
743   and    site_uses.cust_acct_site_id    = acct_site.cust_acct_site_id
744   and    site_uses.site_use_code = 'LATE_CHARGE'
745   and    site_uses.org_id = p_org_id
746   and    site_uses.status = 'A';
747 
748   return l_late_charge_site_use_id;
749 
750   EXCEPTION
751 
752     WHEN NO_DATA_FOUND THEN
753       return to_number(NULL);
754 
755     WHEN OTHERS THEN
756       raise;
757 
758 END get_late_charge_site;
759 
760 /*=======================================================================+
761   If a given site is defined as a Bill To and a Late Charges site, the
762   site_use_id associated with the Bill To Site use will be stored in
763   hz_customer_profiles. Otherwise, the site_use_id associated with the
764   Late Charges site use will be stored in hz_customer_profiles. This
765   function returns the appropriate site_use_id to be joined with the
766   hz_customer_profiles to get the profile set up
767  =======================================================================*/
768 
769 Function get_profile_class_site_use_id(
770 				p_site_use_id	IN	NUMBER,
771 				p_org_id	IN	NUMBER) RETURN NUMBER IS
772  l_profile_class_site_use_id	number;
773 
774 BEGIN
775 
776     /* check if there is a row in customer profiles using this site_use_id
777        if found, regardless of it's site_use_code, return that site_use_id */
778 
779      select site_use_id
780      into l_profile_class_site_use_id
781      from hz_customer_profiles
782      where site_use_id = p_site_use_id;
783 
784      return l_profile_class_site_use_id;
785 
786 EXCEPTION WHEN NO_DATA_FOUND THEN
787   BEGIN
788       select site_use_id
789         into l_profile_class_site_use_id
790         from hz_customer_profiles
791        where site_use_id in ( select site_use_id
792                               from hz_cust_site_uses
793                               where cust_acct_site_id =
794                                   ( SELECT cust_acct_site_id
795                                     FROM hz_cust_site_uses
796                                     WHERE site_use_id = p_site_use_id)
797                                 and status = 'A'
798                                 and site_use_code in ('BILL_TO','LATE_CHARGE'));
799       return l_profile_class_site_use_id;
800    EXCEPTION
801    WHEN NO_DATA_FOUND THEN
802       return null;
803    WHEN TOO_MANY_ROWS THEN
804       BEGIN
805        select site_use_id
806         into l_profile_class_site_use_id
807         from hz_customer_profiles
808        where site_use_id in ( select site_use_id
809                               from hz_cust_site_uses
810                               where cust_acct_site_id =
811                                   ( SELECT cust_acct_site_id
812                                     FROM hz_cust_site_uses
813                                     WHERE site_use_id = p_site_use_id)
814                                 and status = 'A'
815                                 and site_use_code = 'BILL_TO');
816 
817         return l_profile_class_site_use_id;
818       EXCEPTION
819       WHEN NO_DATA_FOUND THEN
820          return null;
821       END;
822 
823    END;
824 
825 END get_profile_class_site_use_id;
826 
827 /*==============================================================
828   Function which returns the valid bill to site associated with
829   a given site
830   =============================================================*/
831 FUNCTION get_bill_to_site_use_id(p_customer_id  IN NUMBER,
832                                  p_site_use_id  IN NUMBER,
833 				 p_org_id	IN NUMBER)
834                  RETURN NUMBER IS
835   l_cust_acct_site_id      number;
836   l_bill_to_site_use_id	   number;
837   l_site_use_code          varchar2(30);
838 BEGIN
839   /* Check if the passed site_use_id corresponds to a bill_to use */
840   select cust_acct_site_id,
841          site_use_code
842    into  l_cust_acct_site_id,
843          l_site_use_code
844    from  hz_cust_site_uses
845    where site_use_id = p_site_use_id
846     and  org_id = p_org_id;
847 
848    IF l_site_use_code = 'BILL_TO' THEN
849       return p_site_use_id;
850    ELSE
851      BEGIN
852        /* Check if the passed site has a bill to usage */
853        select site_use_id
854        into   l_bill_to_site_use_id
855        from   hz_cust_site_uses
856        where cust_acct_site_id = l_cust_acct_site_id
857         and  site_use_code = 'BILL_TO'
858         and  org_id = p_org_id;
859 
860        return l_bill_to_site_use_id;
861 
862      EXCEPTION
863        WHEN NO_DATA_FOUND THEN
864          BEGIN
865             /* Get the primary bill to site */
866             select site_use.site_use_id
867               into l_bill_to_site_use_id
868               from hz_cust_site_uses site_use,
869                    hz_cust_acct_sites sites
870              where sites.cust_account_id = p_customer_id
871                and sites.bill_to_flag = 'P'
872                and sites.status ='A'
873                and sites.cust_acct_site_id = site_use.cust_acct_site_id
874                and site_use.site_use_code = 'BILL_TO'
875                and site_use.org_id = p_org_id;
876 
877             return l_bill_to_site_use_id;
878          EXCEPTION WHEN OTHERS THEN
879             return NULL;
880          END;
881       END;
882     END IF;
883 END get_bill_to_site_use_id;
884 
885 /*=======================================================================+
886   Function which returns the next date on which a debit or a credit item
887   is created for a customer, site, currency, org combination. This is with
888   respect to the input as_of_date. If it doesn't find any, it returns the
889   finance charge date. This is used in calculating the average daily balance
890   =======================================================================*/
891 Function get_next_activity_date(p_customer_id           IN      NUMBER,
892                                 p_site_use_id           IN      NUMBER,
893                                 p_currency_code         IN      VARCHAR2,
894                                 p_org_id                IN      NUMBER,
895                                 p_post_bill_debit       IN      VARCHAR2,
896                                 p_as_of_date            IN      DATE,
897                                 p_fin_charge_date       IN      DATE) RETURN DATE IS
898   l_next_date		date;
899   l_next_bill_date	date;
900 
901 BEGIN
902 
903      select min(billing_date)-1
904      into   l_next_bill_date
905      from   ar_cons_inv
906      where  customer_id = p_customer_id
907      and    site_use_id = p_site_use_id
908      and    currency_code = p_currency_code
909      and    org_id = p_org_id
910      and    billing_date > p_as_of_date
911      and    billing_date <= p_fin_charge_date
912      and    status in ('IMPORTED','ACCEPTED','FINAL');
913 
914      IF l_next_bill_date IS NULL THEN
915         l_next_bill_date := p_fin_charge_date;
916      END IF;
917 
918   select min(trx_date) -1
919     into l_next_date
920     from ar_payment_schedules ps
921     where customer_id = p_customer_id
922     and   decode(ps.class,
923           'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
924                                                            ps.customer_site_use_id,
925                                                            ps.org_id),
926           'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
927                                                             ps.customer_site_use_id,
928                                                             ps.org_id),
929            ps.customer_site_use_id) =  p_site_use_id
930     and   ps.invoice_currency_code = p_currency_code
931     and   ps.org_id = p_org_id
932     and   decode(p_post_bill_debit,
933                  'INCLUDE_DEBIT_ITEM','Y',
934                  'EXCLUDE_DEBIT_ITEM',decode(ps.class,
935 					     'PMT','Y',
936 					     'CM','Y',
937 					     'N')) = 'Y'
938     and   trx_date > p_as_of_date
939     and   trx_date <= p_fin_charge_date;
940 
941     IF l_next_date IS NULL THEN
942        l_next_date := p_fin_charge_date;
943     END IF;
944 
945     IF l_next_bill_date < l_next_date THEN
946       return l_next_bill_date;
947     ELSE
948       return l_next_date;
949     END IF;
950 
951 EXCEPTION WHEN NO_DATA_FOUND THEN
952 
953    return p_fin_charge_date;
954 
955 END get_next_activity_date;
956 
957 /*=======================================================================+
958   This fuction retrieves the receivables_trx_id that should be used for
959   creating adjustments for the Interest portion of the late charges. The
960   heirarchy used is Ship To, Bill To and System Options.
961  +=======================================================================*/
962 FUNCTION get_int_rec_trx_id(p_customer_trx_id	IN	NUMBER,
963 	    		    p_fin_charge_date	IN	DATE,
964                             p_org_id		IN	NUMBER) RETURN NUMBER IS
965   p_int_receivables_trx_id	number;
966 BEGIN
967 select  rt.receivables_trx_id
968   into  p_int_receivables_trx_id
969   from  ar_receivables_trx rt
970  where  rt.receivables_trx_id =
971                     ( select decode(rsu_st.finchrg_receivables_trx_id,
972                              '',decode(rsu_bt.finchrg_receivables_trx_id,
973                                      '',sp.finchrg_receivables_trx_id,
974                                         rsu_bt.finchrg_receivables_trx_id),
975                               rsu_st.finchrg_receivables_trx_id
976                                     )
977                         from  ra_customer_trx ctrx,
978                               hz_cust_site_uses rsu_st,
979                               hz_cust_site_uses rsu_bt,
980                               ar_system_parameters sp
981                         where ctrx.customer_trx_id = p_customer_trx_id
982 			 and  ctrx.org_id = p_org_id
983 			 and  sp.org_id = p_org_id
984                          and  ctrx.bill_to_site_use_id = rsu_bt.site_use_id(+)
985                          and  ctrx.ship_to_site_use_id = rsu_st.site_use_id(+))
986  and  rt.type = 'FINCHRG'
987  and  nvl(rt.status,'A') = 'A'
988  and  rt.org_id = p_org_id
989  and  p_fin_charge_date >= nvl(rt.start_date_active,
990                                    p_fin_charge_date)
991  and  p_fin_charge_date <= nvl(rt.end_date_active,
992                                      p_fin_charge_date);
993    return p_int_receivables_trx_id;
994 EXCEPTION
995    WHEN OTHERS THEN
996       return -1;
997 END get_int_rec_trx_id;
998 
999 /*=======================================================================+
1000   This fuction retrieves the receivables_trx_id that should be used for
1001   creating adjustments for the Penalty portion of the late charges. This
1002   is fetched from System Options
1003  +=======================================================================*/
1004 FUNCTION get_penalty_rec_trx_id(p_fin_charge_date   IN      DATE,
1005                                 p_org_id            IN      NUMBER) RETURN NUMBER IS
1006   l_penalty_receivables_trx_id      number;
1007 BEGIN
1008 
1009    select  rt.receivables_trx_id
1010    into  l_penalty_receivables_trx_id
1011    from  ar_receivables_trx rt
1012   where  rt.receivables_trx_id  = (select sp.penalty_rec_trx_id
1013                                     from  ar_system_parameters sp
1014                                     where sp.org_id = p_org_id)
1015     and  rt.type = 'FINCHRG'
1016     and  nvl(rt.status,'A') = 'A'
1017     and  rt.org_id = p_org_id
1018     and  p_fin_charge_date >= nvl(rt.start_date_active,
1019                                   p_fin_charge_date)
1020     and  p_fin_charge_date <= nvl(rt.end_date_active,
1021                                   p_fin_charge_date);
1022 
1023    return l_penalty_receivables_trx_id;
1024 EXCEPTION
1025    WHEN OTHERS THEN
1026       return -1;
1027 END get_penalty_rec_trx_id;
1028 
1029 /*=======================================================================+
1030   Function which calculates the balance due of a transaction. If the formula
1031   is COMPOUND, it will consider the finance charge type adjustments that
1032   were already created against this transaction
1033  =======================================================================*/
1034 Function get_balance_as_of(p_payment_schedule_id        IN      NUMBER,
1035                            p_as_of_date                 IN      DATE,
1036                            p_class			IN	VARCHAR2,
1037                            p_formula                    IN      VARCHAR2) RETURN NUMBER IS
1038 l_balance_due  		NUMBER;
1039 l_fin_chrg_adjustment 	NUMBER;
1040 BEGIN
1041   IF p_payment_schedule_id IS NOT NULL THEN
1042     IF p_class <> 'PMT' THEN
1043       select sum(amount_due_original), sum(fin_charge_charged)
1044       into   l_balance_due,l_fin_chrg_adjustment
1045       from
1046 	(select amount_due_original,0 fin_charge_charged
1047          from   ar_payment_schedules
1048          where  payment_schedule_id = p_payment_schedule_id
1049          union all
1050          select  nvl(-1 *(ra.amount_applied
1051                       + nvl(ra.earned_discount_taken,0)
1052                       + nvl(ra.unearned_discount_taken,0))
1053                                     ,0) amount_applied,
1054                0 fin_charge_charged
1055          from  ar_receivable_applications ra,
1056                ar_payment_schedules ps_cm_cr
1057          where applied_payment_schedule_id = p_payment_schedule_id
1058           and  ra.status = 'APP'
1059           and  nvl(ra.confirmed_flag,'Y') = 'Y'
1060           and  ps_cm_cr.payment_schedule_id = ra.payment_schedule_id
1061           and  ps_cm_cr.trx_date <= p_as_of_date
1062          union all
1063          select  nvl(ra.amount_applied_from, ra.amount_applied),
1064                0 fin_charge_charged
1065          from  ar_receivable_applications ra
1066          where payment_schedule_id = p_payment_schedule_id
1067           and  ra.apply_date <= p_as_of_date
1068           and  ra.status = 'APP'
1069           and  nvl(ra.confirmed_flag,'Y') = 'Y'
1070           and  p_class = 'CM'
1071           and  ra.application_type = 'CM'
1072          union all
1073          select adj.amount,
1074                 CASE WHEN adj.type ='CHARGES'
1075                                THEN  adj.amount
1076                                ELSE  0 END fin_charge_charged
1077          from  ar_adjustments adj
1078          where adj.payment_schedule_id = p_payment_schedule_id
1079          and   adj.apply_date <= p_as_of_date
1080          and   adj.status = 'A');
1081       IF p_formula <> 'Y' THEN
1082          IF (abs(l_balance_due) < abs(l_fin_chrg_adjustment) AND
1083             sign(l_balance_due) = sign(l_fin_chrg_adjustment)
1084             OR l_balance_due = 0 ) THEN
1085                l_balance_due := 0;
1086          ELSE
1087                l_balance_due := l_balance_due - l_fin_chrg_adjustment;
1088          END IF;
1089       END IF;
1090 
1091     ELSIF p_class ='PMT' THEN
1092       /* Compound and Simple Interest doesn't matter for Payments as there can not be any
1093          adjustments against receipts */
1094       /* For receipts the balance should be directly taken from ar_payment_schedules.
1095          amount_due_remaining. The receipt date is considered for calculating the balances
1096          of the transaction and not the application date */
1097       select  ps.amount_due_remaining
1098       into l_balance_due
1099       from ar_payment_schedules ps
1100       where ps.payment_schedule_id = p_payment_schedule_id
1101       and   ps.class ='PMT'
1102       and   nvl(ps.receipt_confirmed_flag,'Y') = 'Y';
1103     END IF;
1104 
1105     return nvl(l_balance_due,0);
1106   END IF;
1107 
1108 EXCEPTION
1109   WHEN OTHERS THEN
1110       return 0;
1111 END get_balance_as_of;
1112 
1113 /*=======================================================================+
1114   Function which returns the balance of the customer by adding or subtracting
1115   the debit or credit items from the balance forward bill
1116  =======================================================================*/
1117 Function get_cust_balance(p_customer_id                 IN      NUMBER,
1118                           p_site_use_id                 IN      NUMBER,
1119                           p_currency_code               IN      VARCHAR2,
1120                           p_org_id                      IN      NUMBER,
1121                           p_post_billing_debit          IN      VARCHAR2,
1122                           p_as_of_date                  IN      DATE) return NUMBER IS
1123   l_cust_balance   number;
1124 
1125 BEGIN
1126           select sum(bal_amount)
1127           into l_cust_balance
1128          from (
1129            select  sum(ending_balance) bal_amount
1130             from   ar_cons_inv cons_inv
1131             where  cons_inv.customer_id = p_customer_id
1132             and    cons_inv.site_use_id   = p_site_use_id
1133             and    cons_inv.currency_code = p_currency_code
1134 	    and    cons_inv.org_id = p_org_id
1135             and    cons_inv.status       in('FINAL', 'ACCEPTED','IMPORTED')
1136             and    cons_inv.billing_date  =  (select max(ci2.billing_date)
1137 		                                from   ar_cons_inv ci2
1138                 		                where  ci2.customer_id = p_customer_id
1139                                 		and    ci2.site_use_id   = p_site_use_id
1140 		                                and    ci2.currency_code = p_currency_code
1141 						and    ci2.org_id = p_org_id
1142                                 		and    ci2.billing_date  <= p_as_of_date
1143 		                                and    ci2.status  in ('FINAL', 'ACCEPTED','IMPORTED'))
1144            union all
1145            select sum(amount_due_original)
1146            from   ar_payment_schedules ps
1147            where  ps.customer_id = p_customer_id
1148            and    decode(ps.class,
1149                          'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1150                                                                           ps.customer_site_use_id,
1151                                                                           ps.org_id),
1152                          'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1153                                                                            ps.customer_site_use_id,
1154                                                                            ps.org_id),
1155                           ps.customer_site_use_id) = p_site_use_id
1156            and    ps.invoice_currency_code = p_currency_code
1157            and    ps.org_id  = p_org_id
1158            and    decode(p_post_billing_debit,
1159                          'INCLUDE_DEBIT_ITEM','Y',
1160                          'EXCLUDE_DEBIT_ITEM',decode(ps.class,
1161                                                      'PMT','Y',
1162                                                      'CM','Y',
1163                                                      'N'),
1164                          'N') = 'Y'
1165            and    (ps.trx_date >  (select max(ci2.billing_date)
1166                                 from   ar_cons_inv ci2
1167                                 where  ci2.customer_id = p_customer_id
1168                                 and    ci2.site_use_id   = p_site_use_id
1169                                 and    ci2.currency_code = p_currency_code
1170 				and    ci2.org_id = p_org_id
1171                                 AND    ci2.billing_date  <= p_as_of_date
1172                                 AND    ci2.status in ('FINAL','ACCEPTED','IMPORTED'))
1173                   OR
1174                    /* No BFB exists for this customer.. for run date to run date option we
1175                       have to calculate the ADB even for the period before the first BFB is
1176                       created. i.e. There should not be any gaps in the ADB calculation */
1177                   (not exists (select cons_inv_id
1178                                from  ar_cons_inv ci2
1179                                 where  ci2.customer_id = p_customer_id
1180                                 and    ci2.site_use_id   = p_site_use_id
1181                                 and    ci2.currency_code = p_currency_code
1182                                 and    ci2.org_id = p_org_id
1183                                 AND    ci2.billing_date  <= p_as_of_date
1184                                 AND    ci2.status in ('FINAL','ACCEPTED','IMPORTED'))))
1185           and     ps.trx_date <= p_as_of_date);
1186 
1187           return l_cust_balance;
1188 
1189 EXCEPTION WHEN OTHERS THEN
1190    return 0;
1191 END get_cust_balance;
1192 
1193 /*=======================================================================+
1194   Function which checks whethers a particular customer, site and currency
1195   combination is eligible for charge calculation. It returns 'Y' or 'N'. This
1196   is used for applying the customer level tolerances in Average Daily Balance
1197   scenario.
1198   Psedo Logic
1199   ===========
1200   For checking the eligibility, the balance of the last balance forward bill
1201   is taken. The debit items till the due_date of the bill are added to that
1202   and the credit items till the bill due_date + receipt grace days are
1203   subtracted from that. This is compared to the threshold of min_customer
1204   balance overdue
1205  =======================================================================*/
1206 
1207 FUNCTION check_adb_eligibility(	p_customer_id			IN	NUMBER,
1208 				p_site_use_id			IN	NUMBER,
1209 			    	p_currency_code			IN	VARCHAR2,
1210 			    	p_org_id			IN	VARCHAR2,
1211 		    		p_receipt_grace_days		IN	NUMBER,
1212                             	p_min_fc_bal_overdue_type   	IN	VARCHAR2,
1213 			    	p_min_fc_bal_amount		IN	NUMBER,
1214 			    	p_min_fc_bal_percent		IN	NUMBER,
1215                             	p_fin_charge_date		IN	DATE) RETURN VARCHAR2 IS
1216 l_cust_eligible_bal     NUMBER;
1217 l_cust_threshold        NUMBER;
1218 
1219 BEGIN
1220         IF l_debug_flag = 'Y' THEN
1221            debug('ar_calc_late_charge.check_adb_eligibility()+');
1222            debug('Customer_id 		:	'||p_customer_id);
1223            debug('Site Use ID		:	'||p_site_use_id);
1224            debug('Currency_code		:	'||p_currency_code);
1225            debug('Org ID			:	'||p_org_id);
1226 	   debug('Receipt Grace Days	:	'||p_receipt_grace_days);
1227            debug('min_fc_bal_overdue_type:	'||p_min_fc_bal_overdue_type);
1228            debug('min_fc_bal_amount	:	'||p_min_fc_bal_amount);
1229            debug('min_fc_bal_percent	:	'||p_min_fc_bal_percent);
1230            debug('Finance Charge Date	:	'||p_fin_charge_date);
1231         END IF;
1232 
1233         IF p_min_fc_bal_overdue_type = 'AMOUNT' THEN
1234            l_cust_threshold := p_min_fc_bal_amount;
1235         END IF;
1236 	select 	sum(a.balance)
1237          into   l_cust_eligible_bal
1238          from (
1239 	         select sum(ci.ending_balance) balance
1240         	 from   ar_cons_inv ci
1241 	         where  ci.customer_id = p_customer_id
1242         	 and    ci.site_use_id = p_site_use_id
1243 	         and    ci.currency_code = p_currency_code
1244         	 and    ci.org_id = p_org_id
1245 	         and    ci.billing_date = (select max(ci2.billing_date)
1246         	                          from   ar_cons_inv ci2
1247                 	                  where  ci2.customer_id =  p_customer_id
1248                         	          and    ci2.site_use_id   =  p_site_use_id
1249                                 	  and    ci2.currency_code = p_currency_code
1250 	                                  and    ci2.org_id = p_org_id
1251         	                          and    ci2.billing_date  <= p_fin_charge_date
1252                 	                  and    ci2.status  in ('FINAL', 'ACCEPTED','IMPORTED'))
1253 	         and    ci.status  in ('FINAL', 'ACCEPTED','IMPORTED')
1254         	 union all
1255                  select sum(ps.amount_due_original)
1256 	         from   ar_cons_inv ci,
1257 	                ar_payment_schedules ps
1258 	         where  ci.customer_id = p_customer_id
1259  		 and    ci.site_use_id = p_site_use_id
1260 	 	 and    ci.currency_code = p_currency_code
1261         	 and    ci.org_id = p_org_id
1262 	         and    ci.billing_date = (select max(ci2.billing_date)
1263         	                           from   ar_cons_inv ci2
1264 	                                   where  ci2.customer_id =  p_customer_id
1265         	                           and    ci2.site_use_id   =  p_site_use_id
1266                 	                   and    ci2.currency_code = p_currency_code
1267                          	           and    ci2.org_id = p_org_id
1268                                 	   and    ci2.billing_date  <= p_fin_charge_date
1269 	                                   and    ci2.status  in ('FINAL', 'ACCEPTED','IMPORTED'))
1270         	 and    ci.status  in ('FINAL', 'ACCEPTED','IMPORTED')
1271 	         and    ps.customer_id = ci.customer_id
1272         	 and    decode(ps.class,
1273 	        	      'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1274              		  	                                               ps.customer_site_use_id,
1275                           			                               ps.org_id),
1276  			      'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1277         	        		                                        ps.customer_site_use_id,
1278                 	                		                        ps.org_id),
1279 			       ps.customer_site_use_id) =  ci.site_use_id
1280         	 and    ps.invoice_currency_code = ci.currency_code
1281 	         and    ps.org_id = ci.org_id
1282         	 and    ps.trx_date > ci.billing_date
1283                 /* As of now, don't consider the debit items for checking the eligibility,
1284                    as documented in FDD. This will cause incorrect results for Run Date to
1285                    Run Date option as this function will return N when there are no bills for
1286                    the customer. Waiting for the PM feedback on this.*/
1287                  and    ps.class in ('PMT','CM')
1288 	         and    decode(ps.class,
1289         	              'PMT',ci.due_date + nvl(p_receipt_grace_days,0),
1290                 	      'CM', ci.due_date + nvl(p_receipt_grace_days,0),
1291 	                      ci.due_date) >= ps.trx_date)a;
1292 
1293         IF l_debug_flag = 'Y' THEN
1294 	     debug('l_cust_eligible_bal	:	'||l_cust_eligible_bal);
1295         END IF;
1296 
1297         IF nvl(l_cust_eligible_bal,0) >= nvl(l_cust_threshold,0) THEN
1298 	    IF l_debug_flag = 'Y' THEN
1299                debug('Returning Y');
1300             END IF;
1301             return 'Y';
1302         ELSE
1303 	    IF l_debug_flag = 'Y' THEN
1304                debug('Returning N');
1305             END IF;
1306             return 'N';
1307         END IF;
1308 	IF l_debug_flag = 'Y' THEN
1309            debug('ar_calc_late_charge.check_adb_eligibility()-');
1310         END IF;
1311 EXCEPTION WHEN OTHERS THEN
1312      --IF l_debug_flag = 'Y' THEN
1313         debug('EXCEPTION : ar_calc_late_charge.check_adb_eligibility()');
1314      --END IF;
1315      return 'N';
1316 
1317 END check_adb_eligibility;
1318 
1319 /*=======================================================================+
1320   Function which returns the first date on which the activity started for
1321   a customer. This is for calculating the average daily balance even before
1322   creating a Balance Forward Bill
1323  =======================================================================*/
1324 
1325 FUNCTION get_first_activity_date(p_customer_id                IN      NUMBER,
1326                                  p_site_use_id                IN      NUMBER,
1327                                  p_currency_code              IN      VARCHAR2,
1328                                  p_org_id                     IN      NUMBER) return DATE IS
1329   l_first_activity_date	DATE;
1330 BEGIN
1331    select min(trx_date)
1332    into   l_first_activity_date
1333    from   ar_payment_schedules ps
1334    where  ps.customer_id = p_customer_id
1335    and    decode(ps.class,
1336 		'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1337                      		                                   ps.customer_site_use_id,
1338 	                                   			   ps.org_id),
1339                 'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1340                   	                                           ps.customer_site_use_id,
1341                                         		           ps.org_id),
1342     		ps.customer_site_use_id) = p_site_use_id
1343    and    ps.invoice_currency_code = p_currency_code
1344    and	  ps.org_id = p_org_id;
1345 
1346    return l_first_activity_date;
1347 
1348 EXCEPTION WHEN OTHERS THEN
1349    return NULL;
1350 END get_first_activity_date;
1351 
1352 
1353 PROCEDURE get_cust_late_charge_policy(p_org_id		          IN      NUMBER,
1354                                       p_fin_charge_date           IN      DATE,
1355                                       p_customer_name_from        IN      VARCHAR2,
1356                                       p_customer_name_to          IN      VARCHAR2,
1357                                       p_customer_number_from      IN      VARCHAR2,
1358                                       p_customer_number_to        IN      VARCHAR2,
1359                                       p_currency_code             IN      VARCHAR2,
1360                                       p_cust_site_use_id          IN      NUMBER,
1361 				      p_worker_number		  IN	  NUMBER,
1362 				      p_total_workers		  IN	  NUMBER) IS
1363    /*Late charge changes for amount per tier Enhacement 6469663*/
1364    CURSOR wrong_setup(fin_charge_date in date ) is
1365    select substrb(party.party_name,1,50) name,lc_site.lc_cust_sites_id,lc_site.customer_id,lc_site.currency_code,lc_site.customer_site_use_id,
1366           'INTEREST' type
1367    FROM ar_lc_cust_sites_t lc_site,hz_cust_accounts cust_acct,hz_parties party,ar_charge_schedules c_schdl,ar_charge_schedule_headers_v h_schdl
1368    WHERE lc_site.interest_type = 'CHARGE_PER_TIER'
1369    AND   lc_site.interest_schedule_id = c_schdl.schedule_id
1370    AND   c_schdl.schedule_id   = h_schdl.schedule_id
1371    AND   fin_charge_date between h_schdl.start_date and nvl(h_schdl.end_date,to_date('31-12-4712','DD-MM-YYYY'))
1372    AND   h_schdl.SCHEDULE_HEADER_TYPE <> 'AMOUNT'
1373    AND   lc_site.customer_id   = cust_acct.cust_account_id
1374    AND   cust_acct.party_id = party.party_id
1375    UNION
1376    select substrb(party.party_name,1,50) name,lc_site.lc_cust_sites_id,lc_site.customer_id,lc_site.currency_code,lc_site.customer_site_use_id,
1377           'PENALTY' type
1378    FROM ar_lc_cust_sites_t lc_site,hz_cust_accounts cust_acct,hz_parties party,ar_charge_schedules c_schdl,ar_charge_schedule_headers_v h_schdl
1379    WHERE lc_site.penalty_type = 'CHARGE_PER_TIER'
1380    AND   lc_site.penalty_schedule_id = c_schdl.schedule_id
1381    AND   c_schdl.schedule_id   = h_schdl.schedule_id
1382    AND   fin_charge_date between h_schdl.start_date and nvl(h_schdl.end_date,to_date('31-12-4712','DD-MM-YYYY'))
1383    AND   h_schdl.SCHEDULE_HEADER_TYPE <> 'AMOUNT'
1384    AND   lc_site.customer_id   = cust_acct.cust_account_id
1385    AND   cust_acct.party_id = party.party_id
1386    ORDER BY name,currency_code,customer_site_use_id,type;
1387 
1388 
1389 
1390    l_org_id			         NUMBER;
1391    l_customer_name_from                  hz_parties.party_name%type;
1392    l_customer_name_to                    hz_parties.party_name%type;
1393    l_customer_number_from                hz_cust_accounts.account_number%type;
1394    l_customer_number_to                  hz_cust_accounts.account_number%type;
1395    l_cust_site_use_id                    number;
1396    l_fin_charge_date                     date;
1397    l_currency_code			 VARCHAR2(15);
1398    l_use_late_charge_site		 VARCHAR2(1);
1399    l_worker_number			 number;
1400    l_total_workers			 number;
1401    l_ins_statement			 VARCHAR2(32000);
1402    l_customer_name_where                 VARCHAR2(200);
1403    l_customer_number_where               VARCHAR2(200);
1404    l_currency_where                      VARCHAR2(100);
1405    l_cust_site_where                     VARCHAR2(100);
1406    l_org_where                           VARCHAR2(50);
1407    v_cursor                   		 NUMBER;
1408    l_ignore    		                 INTEGER;
1409    l_first_rec				 BOOLEAN;
1410 BEGIN
1411    IF l_debug_flag = 'Y' THEN
1412       debug( 'ar_calc_late_charge.get_cust_late_charge_policy()+' );
1413    END IF;
1414 
1415    l_org_id			:=	p_org_id;
1416    l_customer_name_from		:=	p_customer_name_from;
1417    l_customer_name_to		:=	p_customer_name_to;
1418    l_customer_number_from	:=	p_customer_number_from;
1419    l_customer_number_to		:=	p_customer_number_to;
1420    l_cust_site_use_id		:=	p_cust_site_use_id;
1421    l_fin_charge_date		:=	p_fin_charge_date;
1422    l_currency_code		:=	p_currency_code;
1423    l_worker_number		:=	p_worker_number;
1424    l_total_workers		:=	p_total_workers;
1425 
1426    IF l_debug_flag = 'Y' THEN
1427      debug('l_customer_name_from	:	'||l_customer_name_from);
1428      debug('l_customer_name_to		:	'||l_customer_name_to);
1429      debug('l_customer_number_from	:	'||l_customer_number_from);
1430      debug('l_customer_number_to	:	'||l_customer_number_to);
1431      debug('l_org_id			:	'||l_org_id);
1432    END IF;
1433 
1434    /*  If the profile AR: Use Late Charges Profile is set to Yes, we will use the profiles
1435        and policies defined for the Late charges site. if no profile is defined at this site,
1436        we will use the customer level profile. If the AR: Use Late Charges Profile is set to
1437        No, we will use the individual profiles defined for the corresponding bill to sites.
1438        If no profiles exist, we will use the customer level profile. */
1439 
1440       l_use_late_charge_site :=  nvl(FND_PROFILE.value('AR_USE_STATEMENTS_AND_DUNNING_SITE_PROFILE'),'N');
1441 
1442       /* Bug fix 5384500 */
1443      IF l_customer_name_from IS NOT NULL AND l_customer_name_to IS NULL THEN
1444         l_customer_name_where := 'AND party.party_name >= :l_customer_name_from ';
1445      ELSIF l_customer_name_from IS NULL and l_customer_name_to IS NOT NULL THEN
1446         l_customer_name_where := 'AND party.party_name <= :l_customer_name_to ';
1447      ELSIF l_customer_name_from IS NOT NULL and l_customer_name_to IS NOT NULL THEN
1448         l_customer_name_where := 'AND party.party_name  >= :l_customer_name_from AND party.party_name  <= :l_customer_name_to ';
1449      ELSE
1450         l_customer_name_where := NULL;
1451      END IF;
1452 
1453      IF l_customer_number_from IS NOT NULL AND l_customer_number_to IS NULL THEN
1454         l_customer_number_where := 'AND cust_acct.account_number >= :l_customer_number_from ';
1455      ELSIF l_customer_number_from IS NULL AND l_customer_number_to IS NOT NULL THEN
1456         l_customer_number_where := 'AND cust_acct.account_number <= :l_customer_number_to ';
1457      ELSIF l_customer_number_from IS NOT NULL AND l_customer_number_to IS NOT NULL THEN
1458         l_customer_number_where := 'AND cust_acct.account_number  >= :l_customer_number_from AND cust_acct.account_number  <= :l_customer_number_to ';
1459      ELSE
1460         l_customer_number_where := NULL;
1461      END IF;
1462 
1463      IF l_currency_code IS NOT NULL THEN
1464         l_currency_where := ' AND  ps.invoice_currency_code = :l_currency_code ';
1465      ELSE
1466         l_currency_where := NULL;
1467      END IF;
1468 
1469      IF l_cust_site_use_id IS NOT NULL THEN
1470         l_cust_site_where := ' AND ps.customer_site_use_id = :l_cust_site_use_id ';
1471      ELSE
1472         l_cust_site_where := NULL;
1473      END IF;
1474 
1475      IF l_org_id IS NOT NULL THEN
1476         l_org_where := ' AND sysparam.org_id = :l_org_id ';
1477      ELSE
1478         l_org_where := NULL;
1479      END IF;
1480 
1481     l_ins_statement :=
1482       'insert into ar_lc_cust_sites_t
1483                (lc_cust_sites_id,
1484                 customer_id,
1485                 customer_site_use_id,
1486                 currency_code,
1487                 customer_profile_id,
1488                 collector_id,
1489                 late_charge_calculation_trx,
1490                 credit_items_flag,
1491                 disputed_transactions_flag,
1492                 payment_grace_days,
1493                 late_charge_type,
1494                 late_charge_term_id ,
1495                 interest_period_days,
1496                 interest_calculation_period,
1497                 charge_on_finance_charge_flag,
1498                 hold_charged_invoices_flag,
1499                 message_text_id,
1500                 multiple_interest_rates_flag,
1501                 charge_begin_date,
1502                 cons_inv_flag,
1503                 cons_bill_level,
1504                 cust_acct_profile_amt_id,
1505                 exchange_rate_type,
1506                 exchange_rate,
1507                 min_fc_invoice_overdue_type,
1508                 min_fc_invoice_amount,
1509                 min_fc_invoice_percent,
1510                 min_fc_balance_overdue_type,
1511                 min_fc_balance_amount,
1512                 min_fc_balance_percent,
1513                 min_interest_charge,
1514                 max_interest_charge,
1515                 interest_type,
1516                 interest_Rate,
1517                 interest_fixed_amount,
1518                 interest_schedule_id,
1519                 penalty_type,
1520                 penalty_rate,
1521                 penalty_fixed_amount,
1522                 penalty_schedule_id,
1523                 last_accrue_charge_date,
1524                 org_id,
1525                 request_id)
1526          (select ar_lc_cust_sites_s.nextval,
1527                 customer_id,
1528                 customer_site_use_id,
1529                 currency_code,
1530                 cust_account_profile_id,
1531                 collector_id,
1532                 late_charge_calculation_trx,
1533                 credit_items_flag,
1534                 disputed_transaction_flag,
1535                 payment_grace_days,
1536                 late_charge_type,
1537                 late_charge_term_id,
1538                 interest_period_days,
1539                 interest_calculation_period,
1540                 charge_on_finance_charge_flag,
1541                 hold_charged_invoices_flag,
1542                 message_text_id,
1543                 multiple_interest_rates_flag,
1544                 charge_begin_date,
1545                 cons_inv_flag,
1546                 cons_bill_level,
1547                 cust_acct_profile_amt_id,
1548                 exchange_rate_type,
1549                 exchange_rate,
1550                 min_fc_invoice_overdue_type,
1551                 min_fc_invoice_amount,
1552                 min_fc_invoice_percent,
1553                 min_fc_balance_overdue_type,
1554                 min_fc_balance_amount,
1555                 min_fc_balance_percent,
1556                 min_interest_charge,
1557                 max_interest_charge,
1558                 interest_type ,
1559                 interest_rate,
1560                 interest_fixed_amount,
1561                 interest_schedule_id,
1562                 penalty_type,
1563                 penalty_rate,
1564                 penalty_fixed_amount,
1565                 penalty_schedule_id,
1566                 last_accrue_charge_date,
1567                 org_id,
1568                 :l_request_id
1569          from
1570          (select distinct
1571                 ps.customer_id,
1572                 decode(ps.class,
1573                        ''PMT'',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1574                                                                          ps.customer_site_use_id,
1575                                                                          ps.org_id),
1576                        ''BR'',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1577                                                                         ps.customer_site_use_id,
1578                                                                         ps.org_id),
1579                         ps.customer_site_use_id) customer_site_use_id,
1580                 ps.invoice_currency_code        currency_code,
1581                 profiles.cust_account_profile_id,
1582                 profiles.collector_id,
1583                 profiles.late_charge_calculation_trx,
1584                 profiles.credit_items_flag,
1585                 profiles.disputed_transactions_flag disputed_transaction_flag,
1586                 profiles.payment_grace_days,
1587                 profiles.late_charge_type,
1588                 profiles.late_charge_term_id,
1589                 profiles.interest_period_days,
1590                 profiles.interest_calculation_period,
1591                 profiles.charge_on_finance_charge_flag,
1592                 profiles.hold_charged_invoices_flag,
1593                 profiles.message_text_id,
1594                 profiles.multiple_interest_rates_flag,
1595                 profiles.charge_begin_date,
1596                 profiles.cons_inv_flag,
1597                 profiles.cons_bill_level,
1598                 prof_amts.cust_acct_profile_amt_id,
1599                 decode(ps.exchange_rate_type,
1600                        NULL, NULL,
1601                        prof_amts.exchange_rate_type) exchange_rate_type,
1602                 NULL exchange_rate,
1603                 prof_amts.min_fc_invoice_overdue_type,
1604                 prof_amts.min_fc_invoice_amount,
1605                 prof_amts.min_fc_invoice_percent,
1606                 prof_amts.min_fc_balance_overdue_type,
1607                 prof_amts.min_fc_balance_amount,
1608                 prof_amts.min_fc_balance_percent,
1609                 prof_amts.min_interest_charge,
1610                 prof_amts.max_interest_charge,
1611                 prof_amts.interest_type ,
1612                 prof_amts.interest_rate,
1613                 prof_amts.interest_fixed_amount,
1614                 prof_amts.interest_schedule_id,
1615                 prof_amts.penalty_type ,
1616                 prof_amts.penalty_rate,
1617                 prof_amts.penalty_fixed_amount,
1618                 prof_amts.penalty_schedule_id,
1619                 site_use.last_accrue_charge_date,
1620                 ps.org_id
1621           from  ar_payment_schedules ps,
1622                 ar_transaction_history th,
1623                 ra_customer_trx trx,
1624                 hz_cust_accounts cust_acct,
1625                 hz_parties party,
1626                 hz_customer_profiles profiles,
1627                 hz_cust_profile_amts prof_amts,
1628                 hz_cust_site_uses site_use,
1629                 ar_system_parameters sysparam
1630           WHERE cust_acct.party_id = party.party_id
1631          '|| l_customer_name_where ||'
1632          '|| l_customer_number_where || '
1633           AND   cust_acct.status = ''A''
1634           AND   ps.customer_id = cust_acct.cust_account_id
1635           AND   ps.customer_trx_id = th.customer_trx_id(+)
1636          '|| l_currency_where ||'
1637          '|| l_cust_site_where ||'
1638           AND   nvl(th.current_record_flag,''Y'') = ''Y''
1639           AND   nvl(th.status,''*'') not in (''PROTESTED'',''MATURED_PEND_RISK_ELIMINATION'',''CLOSED'', ''CANCELLED'')
1640 	  AND   ps.org_id = sysparam.org_id
1641          '||l_org_where ||'
1642 	  AND   nvl(sysparam.allow_late_charges,''N'') = ''Y''
1643           AND   ps.customer_trx_id      = trx.customer_trx_id(+)
1644           AND   nvl(ps.last_charge_date,ps.due_date) < :l_fin_charge_date
1645           AND   nvl(trx.finance_charges,decode(ps.class,''DEP'',''N'',''Y'')) = ''Y''
1646           AND   profiles.cust_account_id = cust_acct.cust_account_id
1647           AND   ((ar_calc_late_charge.get_profile_class_site_use_id
1648                                                   (decode(:l_use_late_charge_site ,
1649                                                           ''Y'',ar_calc_late_charge.get_late_charge_site(ps.customer_id,
1650                                                                                                        ps.org_id),
1651                                                           ''N'',ps.customer_site_use_id)
1652                                                       ,ps.org_id) IS NULL
1653                   and profiles.site_use_id is null)
1654                  OR profiles.site_use_id = ar_calc_late_charge.get_profile_class_site_use_id
1655                                                   (decode(:l_use_late_charge_site,
1656                                                           ''Y'',ar_calc_late_charge.get_late_charge_site(ps.customer_id,
1657                                                                                                        ps.org_id),
1658                                                           ''N'',ps.customer_site_use_id)
1659                                                        ,ps.org_id))
1660           AND   profiles.interest_charges = ''Y''
1661           AND   profiles.cust_account_profile_id =  prof_amts.cust_account_profile_id
1662           AND   prof_amts.currency_code = ps.invoice_currency_code
1663           AND   site_use.site_use_id (+) =  decode(ps.class,
1664                                                    ''PMT'',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1665                                                                                                 ps.customer_site_use_id,
1666 	                                   							ps.org_id),
1667                                                    ''BR'',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1668                                                                                                 ps.customer_site_use_id,
1669                                                                                                 ps.org_id),
1670                                                     ps.customer_site_use_id)
1671             AND   mod(nvl(ps.customer_site_use_id,0),:l_total_workers) =
1672                                           decode(:l_total_workers,:l_worker_number,0,:l_worker_number))a
1673             /* Make sure that this customer, site and currency combination is not
1674                part of a failed final batch */
1675             WHERE  not exists (select ''exists failed batch''
1676                       from   ar_interest_headers hdr,
1677                              ar_interest_batches bat
1678                       where  hdr.customer_id = a.customer_id
1679                       and    hdr.customer_site_use_id = a.customer_site_use_id
1680                       and    hdr.currency_code = a.currency_code
1681                       and    hdr.org_id = a.org_id
1682                       and    hdr.interest_batch_id = bat.interest_batch_id
1683                       and    hdr.process_status <> ''S''
1684                       and    bat.batch_status =''F''
1685                       and    bat.transferred_status <> ''S''))';
1686 
1687     IF l_debug_flag = 'Y' THEN
1688        debug(l_ins_statement);
1689     END IF;
1690 
1691      v_cursor := dbms_sql.open_cursor;
1692 
1693     dbms_sql.parse(v_cursor,l_ins_statement,DBMS_SQL.NATIVE);
1694 
1695     IF l_customer_name_from IS NOT NULL THEN                                                                                                       dbms_sql.bind_variable(v_cursor, ':l_customer_name_from', l_customer_name_from);
1696     END IF;
1697 
1698     IF l_customer_name_to IS NOT NULL THEN
1699        dbms_sql.bind_variable(v_cursor, ':l_customer_name_to', l_customer_name_to);
1700     END IF;
1701 
1702     IF l_customer_number_from IS NOT NULL THEN
1703        dbms_sql.bind_variable(v_cursor, ':l_customer_number_from', l_customer_number_from);
1704     END IF;
1705 
1706     IF l_customer_number_to IS NOT NULL THEN
1707        dbms_sql.bind_variable(v_cursor, ':l_customer_number_to', l_customer_number_to);
1708     END IF;
1709 
1710     dbms_sql.bind_variable(v_cursor, ':l_request_id', l_request_id);
1711 
1712     IF l_currency_code IS NOT NULL THEN
1713        dbms_sql.bind_variable(v_cursor, ':l_currency_code', l_currency_code);
1714     END IF;
1715 
1716     IF l_cust_site_use_id IS NOT NULL THEN
1717        dbms_sql.bind_variable(v_cursor, ':l_cust_site_use_id', l_cust_site_use_id);
1718     END IF;
1719 
1720     dbms_sql.bind_variable(v_cursor, ':l_fin_charge_date',l_fin_charge_date);
1721 
1722     IF l_org_id IS NOT NULL THEN
1723         dbms_sql.bind_variable(v_cursor, ':l_org_id', l_org_id);
1724     END IF;
1725 
1726     dbms_sql.bind_variable(v_cursor, ':l_use_late_charge_site',l_use_late_charge_site);
1727     dbms_sql.bind_variable(v_cursor, ':l_worker_number',l_worker_number);
1728     dbms_sql.bind_variable(v_cursor, ':l_total_workers', l_total_workers);
1729 
1730     l_ignore := dbms_sql.execute(v_cursor);
1731 
1732  /*Late Charge Changes for charge per tier Enhacement 6469663*/
1733    l_first_rec := TRUE;
1734    FOR setup in wrong_setup(p_fin_charge_date)
1735    LOOP
1736        IF l_first_rec THEN
1737          debug('Active interest tier has schedule type of percentage for Charge per Tier calculation method. Please define interest tier with amount schedule type.');
1738          debug('---------------------------------------------------------------------------------------------------------------------------------------------------');
1739          debug(rpad('CUSTOMER',50) ||' ' ||  rpad('CURRENCY',8) || ' ' || rpad('SITE_USE_ID',12) || ' ' ||  rpad('TYPE' , 8));
1740          debug(lpad(' ',51,'-') || lpad(' ', 9,'-' ) || lpad(' ',13,'-') || lpad(' ',9,'-'));
1741          l_first_rec := FALSE;
1742        END IF;
1743        debug(rpad(setup.name,50) || ' ' || rpad(setup.currency_code ,8) || ' ' || rpad(setup.customer_site_use_id,12) || ' ' || setup.type);
1744    END LOOP;
1745 
1746    /*Late Charge Changes for charge per tier Enhacement 6469663*/
1747    UPDATE ar_lc_cust_sites_t set penalty_type = NULL
1748    WHERE lc_cust_sites_id IN
1749    ( select lc_cust_sites_id
1750      FROM ar_lc_cust_sites_t lc_site,hz_cust_accounts cust_acct,hz_parties party,ar_charge_schedules c_schdl,ar_charge_schedule_headers_v h_schdl
1751      WHERE lc_site.penalty_type = 'CHARGE_PER_TIER'
1752      AND   lc_site.penalty_schedule_id = c_schdl.schedule_id
1753      AND   c_schdl.schedule_id   = h_schdl.schedule_id
1754      AND   p_fin_charge_date between h_schdl.start_date and nvl(h_schdl.end_date,to_date('31-12-4712','DD-MM-YYYY'))
1755      AND   h_schdl.SCHEDULE_HEADER_TYPE <> 'AMOUNT'
1756      AND   lc_site.customer_id   = cust_acct.cust_account_id
1757      AND   cust_acct.party_id = party.party_id
1758    );
1759 
1760    delete from ar_lc_cust_sites_t
1761    where lc_cust_sites_id IN
1762    (
1763      select lc_cust_sites_id
1764      FROM ar_lc_cust_sites_t lc_site,hz_cust_accounts cust_acct,hz_parties party,ar_charge_schedules c_schdl,ar_charge_schedule_headers_v h_schdl
1765      WHERE lc_site.interest_type = 'CHARGE_PER_TIER'
1766      AND   lc_site.interest_schedule_id = c_schdl.schedule_id
1767      AND   c_schdl.schedule_id   = h_schdl.schedule_id
1768      AND   p_fin_charge_date between h_schdl.start_date and nvl(h_schdl.end_date,to_date('31-12-4712','DD-MM-YYYY'))
1769      AND   h_schdl.SCHEDULE_HEADER_TYPE <> 'AMOUNT'
1770      AND   lc_site.customer_id   = cust_acct.cust_account_id
1771      AND   cust_acct.party_id = party.party_id
1772    );
1773 
1774    IF l_debug_flag = 'Y' THEN
1775       debug( 'ar_calc_late_charge.get_cust_late_charge_policy()-' );
1776    END IF;
1777 
1778    EXCEPTION
1779      WHEN  OTHERS THEN
1780         --IF l_debug_flag = 'Y' THEN
1781             debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
1782             debug('EXCEPTION: ar_calc_late_charge.get_cust_late_charge_policy' );
1783         --END IF;
1784         RAISE;
1785 END get_cust_late_charge_policy;
1786 
1787 PROCEDURE insert_credit_amount(p_fin_charge_date	IN	DATE,
1788 			       p_worker_number          IN      NUMBER,
1789                                p_total_workers          IN      NUMBER) IS
1790  l_fin_charge_date	DATE;
1791  l_worker_number        number;
1792  l_total_workers        number;
1793 BEGIN
1794         IF l_debug_flag = 'Y' THEN
1795               debug( 'ar_calc_late_charge.insert_credit_amount()+' );
1796         END IF;
1797 
1798         l_fin_charge_date	:=	p_fin_charge_date;
1799 	l_worker_number         :=      p_worker_number;
1800         l_total_workers         :=      p_total_workers;
1801 
1802         /* The sum of credit amount is inserted into ar_late_charge_credits_gt.
1803            a) All Unapplied or On Account Receipts and the Open On Account Credit Memos
1804               constitute the credit amount
1805            b) Credits are inserted as positive amounts, for easiness of handling the applications
1806            c) Credits are calculated for a customer_id, site_use_id, currency_code and legal_entity_id
1807               combination
1808         */
1809 
1810         insert into ar_late_charge_credits_gt
1811                 (customer_id,
1812                  customer_site_use_id,
1813                  currency_code,
1814                  legal_entity_id,
1815                  org_id,
1816                  credit_amount)
1817           (
1818          select customer_id,
1819                 customer_site_use_id,
1820                 currency_code,
1821                 legal_entity_id,
1822                 org_id,
1823                 sum(balance_due)
1824                 /* The receipt balance is taken as -1*amount_due_remaining from ar_payment
1825                    schedules as receipt date is considered for calculating the balances of
1826                    the transaction and not the application date */
1827           from (select cr.pay_from_customer customer_id,
1828                        ar_calc_late_charge.get_bill_to_site_use_id(cr.pay_from_customer,
1829                                                                    cr.customer_site_use_id,
1830 								   cr.org_id) customer_site_use_id,
1831                        cr.currency_code,
1832                        cr.legal_entity_id,
1833 		       cr.org_id,
1834                        -1* ps.amount_due_remaining balance_due
1835                 from  ar_cash_receipts cr,
1836                       ar_payment_schedules ps,
1837                       ar_lc_cust_sites_t cust_site,
1838                       ar_late_charge_cust_balance_gt bal
1839                where  ps.actual_date_closed > l_fin_charge_date
1840                 and   ps.class ='PMT'
1841                 and   ps.trx_date <= l_fin_charge_date
1842                 and   nvl(ps.last_charge_date,l_fin_charge_date-1) < l_fin_charge_date
1843                 and   ps.customer_id = cust_site.customer_id
1844                 and   ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
1845                                                                   ps.customer_site_use_id,
1846                                                                   ps.org_id) = cust_site.customer_site_use_id
1847                 and   ps.invoice_currency_code = cust_site.currency_code
1848                 and   ps.org_id = cust_site.org_id
1849                 and   cr.pay_from_customer = cust_site.customer_id
1850                 and   cr.currency_code = cust_site.currency_code
1851                 and   cr.org_id = cust_site.org_id
1852                 and   NVL(cust_site.credit_items_flag,'N') = 'Y'
1853                 and   cust_site.late_charge_type in ('ADJ','DM')
1854                 /* Apply Customer Level tolerances */
1855                 and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
1856                 and   cust_site.org_id = bal.org_id
1857                 and   decode(cust_site.min_fc_balance_overdue_type,
1858                              'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
1859                                         * nvl(bal.customer_open_balance,0)/100),
1860                              'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
1861                              0) <= nvl(bal.customer_overdue_balance,0)
1862                 and   cr.receipt_date < l_fin_charge_date
1863                 and   cr.cash_receipt_id = ps.cash_receipt_id
1864                 and   cr.org_id = ps.org_id
1865                 and   cr.cash_receipt_id = ps.cash_receipt_id
1866                 and   nvl(ps.receipt_confirmed_flag,'Y') ='Y'
1867                 and   decode(cust_site.hold_charged_invoices_flag,
1868                               'Y', decode(ps.last_charge_date,
1869                                           NULL,'Y','N'),
1870                               'N') = 'N'
1871                 UNION ALL
1872                 select ps.customer_id,
1873                        ps.customer_site_use_id,
1874                        ps.invoice_currency_code,
1875                        trx.legal_entity_id,
1876                        ps.org_id,
1877                        /* Always get the true balance of the CM as of the finance charge date. For that,
1878                           p_charge_on_finance_charge_flag is passed as Y */
1879                        -1*ar_calc_late_charge.get_balance_as_of(ps.payment_schedule_id,
1880                                                                 l_fin_charge_date,
1881                                                                 'CM',
1882                                                                 'Y') balance_due
1883                 from   ar_payment_schedules ps,
1884                        ra_customer_trx trx,
1885                        ra_cust_trx_types types,
1886                        ar_lc_cust_sites_t cust_site,
1887                        ar_late_charge_cust_balance_gt bal
1888                 where  ps.customer_id = cust_site.customer_id
1889                 and    ps.customer_site_use_id = cust_site.customer_site_use_id
1890                 and    ps.invoice_currency_code = cust_site.currency_code
1891                 and    mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
1892                                           decode(l_total_workers,l_worker_number,0,l_worker_number)
1893 		and    ps.org_id = cust_site.org_id
1894                 and    ps.actual_date_closed > l_fin_charge_date
1895                 and    ps.class = 'CM'
1896                 and    ps.trx_date <= l_fin_charge_date
1897                 and    nvl(ps.last_charge_date,l_fin_charge_date-1) < l_fin_charge_date
1898                 and    cust_site.late_charge_type in ('ADJ','DM')
1899                 /* Apply Customer Level tolerances */
1900                 and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
1901 		and   cust_site.org_id = bal.org_id
1902                 and   decode(cust_site.min_fc_balance_overdue_type,
1903                              'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
1904                                         * nvl(bal.customer_open_balance,0)/100),
1905                              'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
1906                              0) <= nvl(bal.customer_overdue_balance,0)
1907                 and    decode(cust_site.disputed_transactions_flag,'N',
1908                          decode(nvl(ps.amount_in_dispute,0), 0, 'Y','N'),'Y' ) = 'Y'
1909                 and    NVL(cust_site.credit_items_flag,'N') = 'Y'
1910                 and    decode(cust_site.hold_charged_invoices_flag,
1911                               'Y', decode(ps.last_charge_date,
1912                                           NULL,'Y','N'),
1913                               'N') = 'N'
1914                 and    trx.customer_trx_id = ps.customer_trx_id
1915 	        and    trx.org_id = ps.org_id
1916                 and    nvl(trx.finance_charges,'Y') = 'Y'
1917                 and    types.cust_trx_type_id = ps.cust_trx_type_id
1918 		and    types.org_id = ps.org_id
1919                 and    nvl(types.exclude_from_late_charges,'N') <> 'Y'
1920                )
1921           group by customer_id,
1922                    customer_site_use_id,
1923                    currency_code,
1924                    legal_entity_id,
1925 		   org_id);
1926 
1927         IF l_debug_flag = 'Y' THEN
1928               debug( 'ar_calc_late_charge.insert_credit_amount()-' );
1929         END IF;
1930    EXCEPTION
1931      WHEN  OTHERS THEN
1932         --IF l_debug_flag = 'Y' THEN
1933             debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
1934             debug('EXCEPTION: ar_calc_late_charge.insert_credit_amount' );
1935         --END IF;
1936         RAISE;
1937 
1938 END insert_credit_amount;
1939 
1940 /*=========================================================================================+
1941  | PROCEDURE insert_int_overdue_adj_dm                                                     |
1942  |                                                                                         |
1943  | DESCRIPTION                                                                             |
1944  |                                                                                         |
1945  |   This procedure calculates the overdue balance of the debit items and applies those    |
1946  |   against the credit items in the order of the due_date. The Interest Amount is  then   |
1947  |   calculated on the remaining amount of those debit items and inserted into             |
1948  |   ar_late_charge_trx_t                                                                  |
1949  |                                                                                         |
1950  | PSEUDO CODE/LOGIC                                                                       |
1951  |                                                                                         |
1952  |  a) Get the overdue balances of the debit items as sum of                               |
1953  |       i) amount_due_remaining from ar_payment_schedules                                 |
1954  |      ii) amount_applied + discount from ar_receivable_applications after the            |
1955  |          finance charge date. Note that the trx_date of the credit items is considered  |
1956  |          for determining this as compared to the application date                       |
1957  |     iii) amount_adjusted from ar_adjustments after the finance charge date              |
1958  |  b) If simple / flat interest has to be computed, the finance charge computed before    |
1959  |     finance charge date has to be deducted from the above amount.                       |
1960  |  c) From the above computed balance, the debit items are adjusted against the credit    |
1961  |     amount in the order of the due date. If two debit items have the same due date, the |
1962  |     debit items are ordered in the order of their payment schedule ids                  |
1963  |                                                                                         |
1964  | PARAMETERS                                                                              |
1965  |                                                                                         |
1966  |                                                                                         |
1967  | KNOWN ISSUES                                                                            |
1968  |                                                                                         |
1969  | NOTES                                                                                   |
1970  |                                                                                         |
1971  |   Original_balance        : This is the balance as of the finance charge date           |
1972  |   Overdue_late_pay_amount : This is the amount on which finance charge is computed.     |
1973  |                             This could be different from original balance as the credits|
1974  |                             could have been adjusted against this                       |
1975  |                                                                                         |
1976  | MODIFICATION HISTORY                                                                    |
1977  | Date                  Author            Description of Changes                          |
1978  | 15-FEB-2006           rkader            Created                                         |
1979  | 19-JUL-2006           rkader            Bug fix 5290709 : Credit items are also         |
1980  |                                         selected with display_flag N. So the ordering   |
1981  |                                         should be such that, the credit items will come |
1982  |                                         last. Debit items with positive sign should come|
1983  |                                         before the debit items with negative sign       |
1984  |                                                                                         |
1985  *=========================================================================================*/
1986 
1987 PROCEDURE insert_int_overdue_adj_dm(p_fin_charge_date 	IN	DATE,
1988 				    p_worker_number     IN      NUMBER,
1989                                     p_total_workers     IN      NUMBER) IS
1990  l_fin_charge_date	DATE;
1991  l_worker_number        number;
1992  l_total_workers        number;
1993 BEGIN
1994         IF l_debug_flag = 'Y' THEN
1995               debug( 'ar_calc_late_charge.insert_int_overdue_adj_dm()+' );
1996         END IF;
1997 
1998         l_fin_charge_date	:=	p_fin_charge_date;
1999         l_worker_number         :=      p_worker_number;
2000         l_total_workers         :=      p_total_workers;
2001 
2002         insert into ar_late_charge_trx_t
2003                 (late_charge_trx_id,
2004                  customer_id,
2005                  customer_site_use_id,
2006                  currency_code,
2007                  customer_trx_id,
2008                  legal_entity_id,
2009                  payment_schedule_id,
2010                  class,
2011                  amount_due_original,
2012                  amount_due_remaining,
2013                  fin_charge_charged,
2014                  trx_date,
2015                  cust_trx_type_id,
2016                  last_charge_date,
2017                  exchange_rate_type,
2018                  min_interest_charge,
2019                  max_interest_charge,
2020                  overdue_late_pay_amount,
2021                  original_balance,
2022                  due_date,
2023                  receipt_date,
2024                  finance_charge_date,
2025                  charge_type,
2026                  actual_date_closed,
2027                  interest_rate,
2028                  interest_days,
2029                  rate_start_date,
2030                  rate_end_date,
2031                  schedule_days_start,
2032                  schedule_days_to,
2033                  late_charge_amount,
2034                  late_charge_type,
2035                  late_charge_term_id,
2036                  interest_period_days,
2037                  interest_calculation_period,
2038                  charge_on_finance_charge_flag,
2039                  message_text_id,
2040                  interest_type,
2041                  min_fc_invoice_overdue_type,
2042                  min_fc_invoice_amount,
2043                  min_fc_invoice_percent,
2044                  charge_line_type,
2045 		 org_id,
2046 		 request_id,
2047                  display_flag)
2048       ( select
2049                  ar_late_charge_trx_s.nextval,
2050                  c.customer_id,
2051                  c.customer_site_use_id ,
2052                  c.invoice_currency_code,
2053                  c.customer_trx_id,
2054                  c.legal_entity_id,
2055                  c.payment_schedule_id,
2056                  c.class ,
2057                  c.amount_due_original,
2058                  c.amount_due_remaining ,
2059                  c.fin_charge_charged,
2060                  c.trx_date,
2061                  c.cust_trx_type_id,
2062                  c.last_charge_date,
2063                  c.exchange_rate_type,
2064                  c.min_interest_charge,
2065                  c.max_interest_charge,
2066                  decode(c.class,
2067                         'CM',0,
2068                         'PMT',0,
2069                         decode(dense_rank() over(partition by c.customer_id,
2070                                                   c.customer_site_use_id,
2071                                                   c.invoice_currency_code,
2072                                                   c.legal_entity_id,
2073                                                   c.org_id
2074                                          order by decode(c.class,
2075                                                                'PMT',99,
2076                                                                'CM',99,
2077                                                                decode(sign(c.overdue_amt),+1,-1,1)),
2078                                                   c.balance_rtotal), 1, c.balance_rtotal,
2079                                                                      2, decode(sign(c.balance_rtotal-c.overdue_amt),
2080                                                                                 +1, c.overdue_amt, c.balance_rtotal),
2081                                                                      c.overdue_amt)) overdue_amount,
2082                  c.original_balance,
2083                  c.due_date,
2084                  NULL receipt_date,
2085                  c.fin_charge_date,
2086                  c.charge_type,
2087                  c.actual_date_closed,
2088                  decode(c.interest_type,
2089                         'CHARGES_SCHEDULE',sched_lines.rate,
2090                         'FIXED_RATE',c.interest_rate, NULL) interest_rate,
2091                  least(decode(c.multiple_interest_rates_flag,
2092                                  'Y',decode(sched_hdrs.schedule_header_type,
2093                                             'RATE',
2094                                              nvl(sched_hdrs.end_date,c.eff_fin_charge_date),
2095                                              c.eff_fin_charge_date),
2096                                c.eff_fin_charge_date),c.eff_fin_charge_date) -
2097                   greatest(decode(c.multiple_interest_rates_flag,
2098                                   'Y',decode(sched_hdrs.schedule_header_type,
2099                                             'RATE',sched_hdrs.start_date-1,c.eff_due_date),
2100                                   c.eff_due_date), c.eff_due_date,c.eff_last_charge_date) interest_days,
2101                  sched_hdrs.start_date rate_start_date,
2102                  sched_hdrs.end_date rate_end_date ,
2103                  bucket_lines.days_start schedule_days_start,
2104                  bucket_lines.days_to  schedule_days_to    ,
2105                  decode(c.class, 'PMT',0,'CM',0,
2106                         decode(decode(dense_rank()
2107                                over(partition by c.customer_id,
2108                                                  c.customer_site_use_id,
2109                                                  c.invoice_currency_code,
2110                                                  c.legal_entity_id,
2111 						 c.org_id
2112                                     order by c.balance_rtotal),
2113                              1, c.balance_rtotal,
2114                              2, decode(sign(c.balance_rtotal-c.overdue_amt),
2115                                       +1, c.overdue_amt, c.balance_rtotal),
2116                              c.overdue_amt),
2117                        0,0,
2118                        decode(c.interest_type,'FIXED_AMOUNT',decode(c.class,'INV',decode(sign(c.original_balance),-1,0,c.interest_fixed_amount),c.interest_fixed_amount), /*Bug 8559863*/
2119                                               'CHARGE_PER_TIER', sched_lines.amount,  /*Late Charge Charge per tier Enhacement 6469663*/
2120                                decode(sched_hdrs.schedule_header_type,'AMOUNT', sched_lines.amount,
2121                                       ar_calc_late_charge.calculate_interest(
2122                                             decode(dense_rank()
2123                                                       over(partition by c.customer_id,
2124                                                                         c.customer_site_use_id,
2125                                                                         c.invoice_currency_code,
2126                                                                         c.legal_entity_id,
2127                                                                         c.org_id
2128                                                            order by decode(c.class,
2129                                                                'PMT',99,
2130                                                                'CM',99,
2131                                                                decode(sign(c.overdue_amt),+1,-1,1)),c.balance_rtotal),
2132                                                        1, c.balance_rtotal,
2133                                                        2, decode(sign(c.balance_rtotal-c.overdue_amt),
2134                                                                   +1, c.overdue_amt, c.balance_rtotal),
2135                                                        c.overdue_amt),
2136                                              c.charge_on_finance_charge_flag,
2137                                              least(decode(c.multiple_interest_rates_flag,
2138                                                           'Y',decode(sched_hdrs.schedule_header_type,
2139                                                                      'RATE',
2140                                                                       nvl(sched_hdrs.end_date,c.eff_fin_charge_date),
2141                                                                       c.eff_fin_charge_date),
2142                                                            c.eff_fin_charge_date),c.eff_fin_charge_date) -
2143                                                 greatest(decode(c.multiple_interest_rates_flag,
2144                                                                'Y',decode(sched_hdrs.schedule_header_type,
2145                                                                           'RATE',sched_hdrs.start_date-1,
2146                                                                            c.eff_due_date),
2147                                                                 c.eff_due_date), c.eff_due_date,c.eff_last_charge_date),
2148                                               decode(c.interest_type,
2149                                                      'CHARGES_SCHEDULE',sched_lines.rate,
2150                                                      'FIXED_RATE',c.interest_rate, NULL),
2151                                               c.interest_period_days,
2152                                               c.invoice_currency_code,
2153 					      c.payment_schedule_id))))) late_charge_amount,
2154                  c.late_charge_type,
2155                  c.late_charge_term_id,
2156                  c.interest_period_days,
2157                  c.interest_calculation_period,
2158                  c.charge_on_finance_charge_flag,
2159                  c.message_text_id,
2160                  c.interest_type,
2161                  c.min_fc_invoice_overdue_type,
2162                  c.min_fc_invoice_amount,
2163                  c.min_fc_invoice_percent,
2164                  'INTEREST',
2165 		 c.org_id,
2166 		 l_request_id,
2167                  decode(c.class,
2168                         'PMT','N',
2169                         'CM','N',
2170                         decode(decode(dense_rank() over(partition by c.customer_id,
2171                                                   c.customer_site_use_id,
2172                                                   c.invoice_currency_code,
2173                                                   c.legal_entity_id,
2174                                                   c.org_id
2175                                          order by decode(c.class,
2176                                                          'PMT',99,
2177                                                          'CM',99,
2178                                                          decode(sign(c.overdue_amt),+1,-1,1)),
2179                                                   c.balance_rtotal), 1, c.balance_rtotal,
2180                                                                      2, decode(sign(c.balance_rtotal-c.overdue_amt),
2181                                                                                 +1, c.overdue_amt, c.balance_rtotal),
2182                                                                      c.overdue_amt) ,
2183                                 0,'N','Y')) display_flag
2184   from
2185       (select
2186                  b.customer_id,
2187                  b.customer_site_use_id ,
2188                  b.invoice_currency_code,
2189                  b.customer_trx_id,
2190                  b.legal_entity_id,
2191                  b.payment_schedule_id,
2192                  b.class ,
2193                  b.amount_due_original,
2194                  b.amount_due_remaining ,
2195                  b.fin_charge_charged,
2196                  b.trx_date,
2197                  b.cust_trx_type_id,
2198                  nvl(b.last_charge_date,
2199                      decode(b.fin_charge_charged,
2200                             0,NULL,
2201                             b.last_accrue_charge_date)) last_charge_date,
2202                  b.exchange_rate_type,
2203                  b.min_interest_charge,
2204                  b.max_interest_charge,
2205                  b.overdue_amt,
2206                  b.original_balance,
2207                  b.due_date,
2208                  b.fin_charge_date,
2209                  b.charge_type,
2210                  b.actual_date_closed,
2211                  b.late_charge_type,
2212                  b.late_charge_term_id,
2213                  b.interest_period_days,
2214                  b.interest_calculation_period,
2215                  b.charge_on_finance_charge_flag,
2216                  b.message_text_id,
2217                  nvl(credits.credit_amount,0) credit_amount,
2218                  b.interest_type,
2219                  b.min_fc_invoice_overdue_type,
2220                  b.min_fc_invoice_amount,
2221                  b.min_fc_invoice_percent,
2222                  b.interest_rate,
2223                  b.interest_schedule_id,
2224                  b.multiple_interest_rates_flag,
2225                  b.interest_fixed_amount,
2226                  b.org_id,
2227                  decode(b.interest_calculation_period,
2228                         'DAILY',l_fin_charge_date,
2229                         'MONTHLY',last_day(l_fin_charge_date)) eff_fin_charge_date,
2230                  decode(b.interest_calculation_period,
2231                         'DAILY',nvl(b.last_charge_date,
2232                                     decode(b.fin_charge_charged,
2233                                            0,b.due_date,
2234                                            b.last_accrue_charge_date)),
2235                         'MONTHLY',first_day(nvl(b.last_charge_date,
2236                                                 decode(b.fin_charge_charged,
2237                                                        0,b.due_date,
2238                                                        b.last_accrue_charge_date)))) eff_last_charge_date,
2239                  decode(b.interest_calculation_period,
2240                         'DAILY',b.due_date,
2241                         'MONTHLY',first_day(b.due_date)) eff_due_date,
2242                  decode(sign(nvl(credits.credit_amount,0) - sum(b.overdue_amt)
2243                                                 over(partition by b.customer_id,
2244                                                      b.customer_site_use_id,
2245                                                      b.invoice_currency_code,
2246                                                      b.legal_entity_id,
2247 				                     b.org_id
2248                                                 order by decode(b.class,
2249                                                                'PMT',99,
2250                                                                'CM',99,
2251                                                                decode(sign(b.overdue_amt),+1,-1,1)),
2252                                                          b.due_date, b.payment_schedule_id)),+1,0,0,0,
2253                    (sum(b.overdue_amt)
2254                         over(partition by b.customer_id,
2255                                           b.customer_site_use_id,
2256                                           b.invoice_currency_code,
2257                                           b.legal_entity_id,
2258                                           b.org_id
2259                            order by decode(b.class,
2260                                           'PMT',99,
2261                                           'CM',99,
2262                                           decode(sign(b.overdue_amt),+1,-1,1)),
2263                                     b.due_date, b.payment_schedule_id) - nvl(credits.credit_amount,0))) balance_rtotal
2264  from (
2265        select
2266                  a.customer_id,
2267                  a.customer_site_use_id ,
2268                  a.invoice_currency_code,
2269                  a.customer_trx_id,
2270                  nvl(trx.legal_entity_id,cr.legal_entity_id) legal_entity_id,
2271                  a.payment_schedule_id,
2272                  a.class ,
2273                  a.amount_due_original,
2274                  a.amount_due_remaining ,
2275                  sum(a.fin_charge_charged) fin_charge_charged,
2276                  a.trx_date,
2277                  a.cust_trx_type_id,
2278                  a.last_charge_date,
2279                  a.last_accrue_charge_date,
2280                  a.exchange_rate_type,
2281                  a.min_interest_charge,
2282                  a.max_interest_charge,
2283                  sum(decode(a.charge_on_finance_charge_flag,'Y', a.overdue_amt,
2284                             a.overdue_amt- a.fin_charge_charged)) overdue_amt,
2285                  sum(a.overdue_amt) original_balance,
2286                  a.due_date,
2287                  a.fin_charge_date,
2288                  a.charge_type,
2289                  a.actual_date_closed,
2290                  a.late_charge_type,
2291                  a.late_charge_term_id,
2292                  a.interest_period_days,
2293                  a.interest_calculation_period,
2294                  a.charge_on_finance_charge_flag,
2295                  a.message_text_id,
2296                  --credits.credit_amount,
2297                  a.interest_type,
2298                  a.min_fc_invoice_overdue_type,
2299                  a.min_fc_invoice_amount,
2300                  a.min_fc_invoice_percent,
2301                  a.interest_rate,
2302                  a.interest_schedule_id,
2303                  a.multiple_interest_rates_flag,
2304                  a.hold_charged_invoices_flag,
2305                  a.interest_fixed_amount,
2306                  a.org_id
2307            from (
2308            select
2309                  ps.customer_id,
2310                  decode(ps.class,
2311                         'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
2312                                                                          ps.customer_site_use_id,
2313 									 ps.org_id),
2314                         ps.customer_site_use_id) customer_site_use_id ,
2315                  ps.invoice_currency_code,
2316                  ps.customer_trx_id,
2317                  ps.payment_schedule_id,
2318                  ps.class ,
2319                  ps.amount_due_original,
2320                  ps.amount_due_remaining,
2321                  sum(case when adj.apply_date > l_fin_charge_date
2322                       then adj.amount*-1 else 0 end )  overdue_amt,
2323                  sum(case when adj.apply_date <= l_fin_charge_date then
2324                           case when adj.type ='CHARGES' then
2325                                  adj.amount else 0 end
2326                       else 0 end)  fin_charge_charged,
2327                  ps.trx_date,
2328                  ps.cust_trx_type_id,
2329                  ps.last_charge_date,
2330                  cust_site.exchange_rate,
2331                  cust_site.exchange_rate_type,
2332                  cust_site.min_interest_charge,
2333                  cust_site.max_interest_charge,
2334                  ps.due_date,
2335                  l_fin_charge_date  fin_charge_date,
2336                  cust_site.late_charge_type,
2337                  cust_site.late_charge_term_id    ,
2338                  cust_site.interest_period_days,
2339                  cust_site.interest_calculation_period,
2340                  cust_site.charge_on_finance_charge_flag,
2341                  cust_site.message_text_id,
2342                  ps.actual_date_closed,
2343                  cust_site.last_accrue_charge_date,
2344                  cust_site.interest_type,
2345                  cust_site.interest_rate,
2346                  cust_site.interest_fixed_amount,
2347                  cust_site.min_fc_invoice_overdue_type,
2348                  cust_site.min_fc_invoice_amount,
2349                  cust_site.min_fc_invoice_percent,
2350                  cust_site.interest_schedule_id interest_schedule_id,
2351                  cust_site.multiple_interest_rates_flag,
2352                  cust_site.hold_charged_invoices_flag,
2353                  ps.org_id,
2354                  ps.cash_receipt_id,
2355                  'OVERDUE' charge_type
2356             from  ar_payment_schedules ps,
2357                   ar_adjustments adj,
2358                   ar_lc_cust_sites_t cust_site,
2359                   ar_late_charge_cust_balance_gt bal
2360             where ps.customer_id = cust_site.customer_id
2361             and   cust_site.customer_site_use_id = decode(ps.class,
2362                                                     'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
2363                                                                                              ps.customer_site_use_id,
2364 											     ps.org_id),
2365                                                      ps.customer_site_use_id)
2366             and   ps.invoice_currency_code = cust_site.currency_code
2367             and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
2368                                           decode(l_total_workers,l_worker_number,0,l_worker_number)
2369             and   ps.org_id = cust_site.org_id
2370             and   ps.actual_date_closed > l_fin_charge_date
2371             and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE','OVERDUE')
2372             and   cust_site.late_charge_type in ('ADJ','DM')
2373             /* Apply Customer Level tolerances */
2374             and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
2375 	    and	  cust_site.org_id  = bal.org_id
2376             and   decode(cust_site.min_fc_balance_overdue_type,
2377                          'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
2378                                     * nvl(bal.customer_open_balance,0)/100),
2379                          'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
2380                          nvl(bal.customer_overdue_balance,0))  <= nvl(bal.customer_overdue_balance,0)
2381             and   decode(nvl(cust_site.disputed_transactions_flag,'N'),
2382                          'N',decode(nvl(ps.amount_in_dispute,0),
2383                                        0, 'Y','N'),
2384                          'Y' ) = 'Y'
2385             and   decode(nvl(cust_site.credit_items_flag,'N'),
2386                          'N',decode(ps.class,'INV',decode(sign(ps.amount_due_original),-1,'N','Y'),'Y'),
2387                          'Y' ) = 'Y'                    /*Bug8559863*/
2388             --and   ps.class not in ('CM','PMT')
2389             and   ps.due_date < (l_fin_charge_date - nvl(cust_site.payment_grace_days,0))
2390             and   nvl(ps.last_charge_date,l_fin_charge_date-1) < l_fin_charge_date
2391             and   nvl(ps.receipt_confirmed_flag, 'Y') = 'Y'
2392             and   nvl(cust_site.charge_begin_date,ps.due_date) <= ps.due_date
2393             and   adj.payment_schedule_id = ps.payment_schedule_id
2394             and   adj.status = 'A'
2395             group by
2396                   ps.customer_id,
2397                   decode(ps.class,
2398                         'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
2399                                                                          ps.customer_site_use_id,
2400 									 ps.org_id),
2401                         ps.customer_site_use_id),
2402                   ps.invoice_currency_code,
2403                   ps.customer_trx_id,
2404                   ps.payment_schedule_id,
2405                   ps.class ,
2406                   ps.amount_due_original,
2407                   ps.amount_due_remaining,
2408                   ps.trx_date,
2409                   ps.cust_trx_type_id,
2410                   ps.last_charge_date,
2411                   cust_site.exchange_rate,
2412                   cust_site.exchange_rate_type,
2413                   cust_site.min_interest_charge,
2414                   cust_site.max_interest_charge,
2415                   ps.due_date,
2416                   l_fin_charge_date ,
2417                   cust_site.late_charge_type,
2418                   cust_site.late_charge_term_id    ,
2419                   cust_site.interest_period_days,
2420                   cust_site.interest_calculation_period,
2421                   cust_site.charge_on_finance_charge_flag,
2422                   cust_site.message_text_id,
2423                   ps.actual_date_closed,
2424                   cust_site.interest_type,
2425                   cust_site.interest_rate,
2426                   cust_site.interest_fixed_amount,
2427                   cust_site.min_fc_invoice_overdue_type,
2428                   cust_site.min_fc_invoice_amount,
2429                   cust_site.min_fc_invoice_percent,
2430                   cust_site.interest_schedule_id,
2431                   cust_site.multiple_interest_rates_flag,
2432                   cust_site.hold_charged_invoices_flag,
2433 		  ps.org_id,
2434                   ps.cash_receipt_id,
2435                   cust_site.last_accrue_charge_date
2436             union all
2437           select  ps.customer_id,
2438                   decode(ps.class,
2439                          'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
2440                                                                           ps.customer_site_use_id,
2441 									  ps.org_id),
2442                          ps.customer_site_use_id) customer_site_use_id,
2443                   ps.invoice_currency_code,
2444                   ps.customer_trx_id,
2445                   ps.payment_schedule_id,
2446                   ps.class ,
2447                   ps.amount_due_original,
2448                   ps.amount_due_remaining,
2449                   sum(app.amount_applied + nvl(app.earned_discount_taken,0)
2450                                      + nvl(app.unearned_discount_taken,0)) overdue_amt,
2451                   0 fin_charge_charged,
2452                   ps.trx_date,
2453                   ps.cust_trx_type_id,
2454                   ps.last_charge_date,
2455                   cust_site.exchange_rate,
2456                   cust_site.exchange_rate_type,
2457                   cust_site.min_interest_charge,
2458                   cust_site.max_interest_charge,
2459                   ps.due_date,
2460                   l_fin_charge_date ,
2461                   cust_site.late_charge_type,
2462                   cust_site.late_charge_term_id    ,
2463                   cust_site.interest_period_days,
2464                   cust_site.interest_calculation_period,
2465                   cust_site.charge_on_finance_charge_flag,
2466                   cust_site.message_text_id,
2467                   ps.actual_date_closed,
2468                   cust_site.last_accrue_charge_date ,
2469                   cust_site.interest_type,
2470                   cust_site.interest_rate,
2471                   cust_site.interest_fixed_amount,
2472                   cust_site.min_fc_invoice_overdue_type,
2473                   cust_site.min_fc_invoice_amount,
2474                   cust_site.min_fc_invoice_percent,
2475                   cust_site.interest_schedule_id,
2476                   cust_site.multiple_interest_rates_flag,
2477                   cust_site.hold_charged_invoices_flag,
2478                   ps.org_id,
2479                   ps.cash_receipt_id,
2480                   'OVERDUE' charge_type
2481             from  ar_payment_schedules ps,
2482                   ar_receivable_applications app,
2483                   ar_payment_schedules ps_cm_cr,
2484                   ar_lc_cust_sites_t cust_site,
2485                   ar_late_charge_cust_balance_gt bal
2486            where  ps.customer_id = cust_site.customer_id
2487             and   cust_site.customer_site_use_id = decode(ps.class,
2488                                                    'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
2489                                                                                              ps.customer_site_use_id,
2490 											     ps.org_id),
2491                                                     ps.customer_site_use_id)
2492             and   ps.invoice_currency_code = cust_site.currency_code
2493             and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
2494                                           decode(l_total_workers,l_worker_number,0,l_worker_number)
2495             and   ps.org_id = cust_site.org_id
2496             and   ps.actual_date_closed > l_fin_charge_date
2497             and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE','OVERDUE')
2498             and   cust_site.late_charge_type in ('ADJ','DM')
2499             /* Apply Customer Level tolerances */
2500             and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
2501 	    and   cust_site.org_id = bal.org_id
2502             and   decode(cust_site.min_fc_balance_overdue_type,
2503                          'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
2504                                     * nvl(bal.customer_open_balance,0)/100),
2505                          'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
2506                           nvl(bal.customer_overdue_balance,0))  <= nvl(bal.customer_overdue_balance,0)
2507             and   decode(nvl(cust_site.disputed_transactions_flag,'N'),
2508                          'N',decode(nvl(ps.amount_in_dispute,0),
2509                                        0, 'Y','N'),
2510                          'Y' ) = 'Y'
2511             and   decode(nvl(cust_site.credit_items_flag,'N'),
2512                          'N',decode(ps.class,'INV',decode(sign(ps.amount_due_original),-1,'N','Y'),'Y'),
2513                          'Y' ) = 'Y'                    /*Bug8559863*/
2514             and   ps.due_date < (l_fin_charge_date - nvl(cust_site.payment_grace_days,0))
2515             and   nvl(ps.last_charge_date,l_fin_charge_date-1) < l_fin_charge_date
2516             and   nvl(ps.receipt_confirmed_flag, 'Y') = 'Y'
2517             and   app.applied_payment_schedule_id = ps.payment_schedule_id
2518             --and   ps.class not in ('CM','PMT')
2519             and   nvl(cust_site.charge_begin_date,ps.due_date) <= ps.due_date
2520             and   app.status = 'APP'
2521             and   nvl( app.confirmed_flag, 'Y' ) = 'Y'
2522             /* The receipt or Credit Memo date should be considered for applications */
2523             and   ps_cm_cr.payment_schedule_id = app.payment_schedule_id
2524             and   ps_cm_cr.trx_date > l_fin_charge_date
2525          group by ps.customer_id,
2526                   decode(ps.class,
2527                         'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
2528                                                                          ps.customer_site_use_id,
2529 									 ps.org_id),
2530                         ps.customer_site_use_id),
2531                   ps.invoice_currency_code,
2532                   ps.customer_trx_id,
2533                   ps.payment_schedule_id,
2534                   ps.class ,
2535                   ps.amount_due_original,
2536                   ps.amount_due_remaining,
2537                   ps.trx_date,
2538                   ps.cust_trx_type_id,
2539                   ps.last_charge_date,
2540                   cust_site.exchange_rate,
2541                   cust_site.exchange_rate_type,
2542                   cust_site.min_interest_charge,
2543                   cust_site.max_interest_charge,
2544                   ps.due_date,
2545                   l_fin_charge_date ,
2546                   cust_site.late_charge_type,
2547                   cust_site.late_charge_term_id    ,
2548                   cust_site.interest_period_days,
2549                   cust_site.interest_calculation_period,
2550                   cust_site.charge_on_finance_charge_flag,
2551                   cust_site.message_text_id,
2552                   ps.actual_date_closed ,
2553                   cust_site.interest_type,
2554                   cust_site.interest_rate,
2555                   cust_site.interest_fixed_amount,
2556                   cust_site.min_fc_invoice_overdue_type,
2557                   cust_site.min_fc_invoice_amount,
2558                   cust_site.min_fc_invoice_percent,
2559                   cust_site.interest_schedule_id,
2560                   cust_site.multiple_interest_rates_flag,
2561                   cust_site.hold_charged_invoices_flag,
2562                   ps.org_id,
2563                   ps.cash_receipt_id,
2564                   cust_site.last_accrue_charge_date
2565            UNION ALL
2566            select ps.customer_id,
2567                   decode(ps.class,
2568                          'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
2569                                                                          ps.customer_site_use_id,
2570 									 ps.org_id),
2571                           ps.customer_site_use_id) customer_site_use_id,
2572                   ps.invoice_currency_code,
2573                   ps.customer_trx_id,
2574                   ps.payment_schedule_id,
2575                   ps.class ,
2576                   ps.amount_due_original,
2577                   ps.amount_due_remaining,
2578                   ps.amount_due_remaining overdue_amt,
2579                   0 fin_charge_charged,
2580                   ps.trx_date,
2581                   ps.cust_trx_type_id,
2582                   ps.last_charge_date,
2583                   cust_site.exchange_rate,
2584                   cust_site.exchange_rate_type,
2585                   cust_site.min_interest_charge,
2586                   cust_site.max_interest_charge,
2587                   ps.due_date,
2588                   l_fin_charge_date ,
2589                   cust_site.late_charge_type,
2590                   cust_site.late_charge_term_id    ,
2591                   cust_site.interest_period_days,
2592                   cust_site.interest_calculation_period,
2593                   cust_site.charge_on_finance_charge_flag,
2594                   cust_site.message_text_id,
2595                   ps.actual_date_closed,
2596                   cust_site.last_accrue_charge_date ,
2597                   cust_site.interest_type,
2598                   cust_site.interest_rate,
2599                   cust_site.interest_fixed_amount,
2600                   cust_site.min_fc_invoice_overdue_type,
2601                   cust_site.min_fc_invoice_amount,
2602                   cust_site.min_fc_invoice_percent,
2603                   cust_site.interest_schedule_id,
2604                   cust_site.multiple_interest_rates_flag,
2605                   cust_site.hold_charged_invoices_flag,
2606      		  ps.org_id,
2607                   ps.cash_receipt_id,
2608                   'OVERDUE' charge_type
2609             from  ar_payment_schedules ps,
2610                   ar_lc_cust_sites_t cust_site,
2611                   ar_late_charge_cust_balance_gt bal
2612             where ps.customer_id = cust_site.customer_id
2613             and   cust_site.customer_site_use_id = decode(ps.class,
2614                                                      'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
2615                                                                                            ps.customer_site_use_id,
2616 											   ps.org_id),
2617                                                      ps.customer_site_use_id)
2618             and   ps.invoice_currency_code = cust_site.currency_code
2619             and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
2620                                           decode(l_total_workers,l_worker_number,0,l_worker_number)
2621  	    and   ps.org_id = cust_site.org_id
2622             and   ps.actual_date_closed > l_fin_charge_date
2623             and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE','OVERDUE')
2624             and   cust_site.late_charge_type in ('ADJ','DM')
2625             /* Apply Customer Level tolerances */
2626             and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
2627 	    and   cust_site.org_id = bal.org_id
2628             and   decode(cust_site.min_fc_balance_overdue_type,
2629                          'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
2630                                     * nvl(bal.customer_open_balance,0)/100),
2631                          'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
2632                            nvl(bal.customer_overdue_balance,0))  <= nvl(bal.customer_overdue_balance,0)
2633             and   decode(nvl(cust_site.disputed_transactions_flag,'N'),
2634                          'N',decode(nvl(ps.amount_in_dispute,0),
2635                                        0, 'Y','N'),
2636                          'Y' ) = 'Y'
2637             and   decode(nvl(cust_site.credit_items_flag,'N'),
2638                          'N',decode(ps.class,'INV',decode(sign(ps.amount_due_original),-1,'N','Y'),'Y'),
2639                          'Y' ) = 'Y'                    /*Bug8559863*/
2640             --and   ps.class not in ('PMT','CM')
2641             and   nvl(cust_site.charge_begin_date,ps.due_date) <= ps.due_date
2642             and   ps.due_date < (l_fin_charge_date - nvl(cust_site.payment_grace_days,0))
2643             and   nvl(ps.last_charge_date,l_fin_charge_date-1) < l_fin_charge_date
2644             and   nvl(ps.receipt_confirmed_flag, 'Y') = 'Y') a,
2645                   ra_customer_trx  trx,
2646                   ar_transaction_history th,
2647                   ra_cust_trx_types types,
2648                   ar_cash_receipts cr
2649         where  trx.customer_trx_id(+) = a.customer_trx_id
2650         and    nvl(trx.finance_charges,decode(a.class,'DEP','N','Y')) = 'Y'
2651         and    a.customer_trx_id = th.customer_trx_id(+)
2652         and    nvl(th.current_record_flag,'Y') = 'Y'
2653         and    nvl(th.status,'*') not in ('PROTESTED','MATURED_PEND_RISK_ELIMINATION','CLOSED', 'CANCELLED')
2654         and    types.cust_trx_type_id(+) = a.cust_trx_type_id
2655         and    types.org_id(+) = a.org_id
2656         and    nvl(types.exclude_from_late_charges,'N') <> 'Y'
2657         and    cr.cash_receipt_id(+) = a.cash_receipt_id
2658         group by
2659                a.customer_id,
2660                a.customer_site_use_id ,
2661                a.invoice_currency_code,
2662                a.customer_trx_id,
2663                nvl(trx.legal_entity_id,cr.legal_entity_id),
2664                a.payment_schedule_id,
2665                a.class,
2666                a.amount_due_original,
2667                a.amount_due_remaining ,
2668                a.trx_date,
2669                a.cust_trx_type_id,
2670                a.last_charge_date,
2671                a.last_accrue_charge_date,
2672                a.exchange_rate_type,
2673                a.min_interest_charge,
2674                a.max_interest_charge,
2675                a.due_date,
2676                a.fin_charge_date,
2677                a.charge_type,
2678                a.actual_date_closed,
2679                a.late_charge_type,
2680                a.late_charge_term_id,
2681                a.interest_period_days,
2682                a.interest_calculation_period,
2683                a.charge_on_finance_charge_flag,
2684                a.message_text_id,
2685                --credits.credit_amount,
2686                a.interest_type,
2687                a.min_fc_invoice_overdue_type,
2688                a.min_fc_invoice_amount,
2689                a.min_fc_invoice_percent,
2690                a.interest_rate,
2691                a.interest_schedule_id,
2692                a.multiple_interest_rates_flag,
2693                a.hold_charged_invoices_flag,
2694                a.org_id,
2695                a.interest_fixed_amount)b,
2696                ar_late_charge_credits_gt credits
2697             where decode(b.hold_charged_invoices_flag,
2698                         'Y',decode(b.last_charge_date,
2699                                    NULL,b.fin_charge_charged,1),
2700                          0) = 0
2701               and b.customer_id = credits.customer_id(+)
2702 	      and b.customer_site_use_id = credits.customer_site_use_id (+)
2703 	      and b.invoice_currency_code = credits.currency_code (+)
2704               and b.org_id = credits.org_id (+)
2705 	      and b.legal_entity_id = credits.legal_entity_id(+))c,
2706                   ar_charge_schedule_hdrs sched_hdrs,
2707                   ar_charge_schedule_lines  sched_lines,
2708                   ar_aging_bucket_lines bucket_lines
2709          where   c.interest_schedule_id = sched_hdrs.schedule_id(+)
2710            and   sched_hdrs.schedule_header_id = sched_lines.schedule_header_id(+)
2711            and   sched_hdrs.schedule_id = sched_lines.schedule_id(+)
2712            and    nvl(sched_hdrs.status,'A') = 'A'
2713            and   sched_lines.aging_bucket_id = bucket_lines.aging_bucket_id(+)
2714            and   sched_lines.aging_bucket_line_id = bucket_lines.aging_bucket_line_id(+)
2715            /* Condition 1: days late should be between the bucket lines start and end days */
2716            and   (l_fin_charge_date- c.due_date) >= nvl(bucket_lines.days_start,(l_fin_charge_date- c.due_date))
2717            and   (l_fin_charge_date - c.due_date) <= nvl(bucket_lines.days_to,(l_fin_charge_date- c.due_date))
2718            /* Condition 2: Start_date of the schedule should be less than or equal to the
2719               finance charge date */
2720            and   nvl(sched_hdrs.start_date,l_fin_charge_date) <= l_fin_charge_date
2721           /* condition 3:
2722               If multiple interest rates have to be used, end date of the schedule should be greater than
2723               or equal to the due date or the date from which we are calculating the charge
2724               Otherwise, the end_date should either be null or it should be greater than the
2725               due_date
2726                */
2727            and  (decode(c.multiple_interest_rates_flag,'Y',
2728                         decode(sched_hdrs.schedule_header_type,
2729                                'RATE',greatest(c.due_date,nvl(c.last_charge_date,c.due_date)),
2730                                c.due_date),
2731                         c.due_date) <= sched_hdrs.end_date
2732                    OR sched_hdrs.end_date IS NULL )
2733            /* Condition 4: If multiple rates need not be used, we should pick up the rate
2734               that is effective on the due date.
2735               Also note that the multiple interest rates are used only for Interest
2736               Calculation and only when rates are used*/
2737            and decode(c.multiple_interest_rates_flag,'Y',
2738                        decode(sched_hdrs.schedule_header_type,
2739                                'RATE',sched_hdrs.start_date,
2740                                c.due_date),
2741                        c.due_date)>= nvl(sched_hdrs.start_date,c.due_date)
2742            /* Make sure that this payment schedule is not part of a failed final batch */
2743             and not exists (select payment_schedule_id
2744                              from   ar_interest_lines lines,
2745                                     ar_interest_headers hdrs,
2746                                     ar_interest_batches bat
2747                              where  lines.payment_schedule_id = c.payment_schedule_id
2748                              and    lines.interest_header_id = hdrs.interest_header_id
2749                              and    hdrs.interest_batch_id = bat.interest_batch_id
2750                              and    bat.batch_status ='F'
2751                              and    bat.transferred_status <> 'S'));
2752 
2753 
2754    IF l_debug_flag = 'Y' THEN
2755       debug( 'ar_calc_late_charge.insert_int_overdue_adj_dm()-' );
2756    END IF;
2757     --
2758    EXCEPTION
2759      WHEN  OTHERS THEN
2760         --IF l_debug_flag = 'Y' THEN
2761             debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
2762             debug('EXCEPTION: ar_calc_late_charge.insert_int_overdue_adj_dm' );
2763         --END IF;
2764         RAISE;
2765 END insert_int_overdue_adj_dm;
2766 /*=========================================================================================+
2767  | PROCEDURE insert_int_overdue_inv                                                        |
2768  |                                                                                         |
2769  | DESCRIPTION                                                                             |
2770  |                                                                                         |
2771  |   This procedure calculates the overdue balance of the debit and credit items. The      |
2772  |   Interest Amount is  then calculated on the overdue balance and inserted into          |
2773  |   ar_late_charge_trx_t                                                                  |
2774  |                                                                                         |
2775  | PSEUDO CODE/LOGIC                                                                       |
2776  |                                                                                         |
2777  |  a) Get the overdue balances of the items as sum of                                     |
2778  |       i) amount_due_remaining from ar_payment_schedules                                 |
2779  |      ii) amount_applied + discount from ar_receivable_applications after the            |
2780  |          finance charge date. The data on which the credit item is created is used      |
2781  |          instead of the application date                                                |
2782  |     iii) amount_adjusted from ar_adjustments after the finance charge date              |
2783  |  b) If simple / flat interest has to be computed, the finance charge computed before    |
2784  |     finance charge date has to be deducted from the above amount                        |
2785  |  c) In this case, the Credit items are treated similar to Debit Items. Interest is      |
2786  |     calculated on the credit items as done for debit items.                             |
2787  |                                                                                         |
2788  | PARAMETERS                                                                              |
2789  |                                                                                         |
2790  |                                                                                         |
2791  | KNOWN ISSUES                                                                            |
2792  |                                                                                         |
2793  | NOTES                                                                                   |
2794  |                                                                                         |
2795  | MODIFICATION HISTORY                                                                    |
2796  | Date                  Author            Description of Changes                          |
2797  | 15-FEB-2006           rkader            Created                                         |
2798  |                                                                                         |
2799  *=========================================================================================*/
2800 PROCEDURE insert_int_overdue_inv(p_fin_charge_date	IN	DATE,
2801                                  p_worker_number        IN      NUMBER,
2802                                  p_total_workers        IN      NUMBER) IS
2803 
2804  l_fin_charge_date		DATE;
2805  l_worker_number                number;
2806  l_total_workers                number;
2807 
2808 BEGIN
2809             IF l_debug_flag = 'Y' THEN
2810                 debug( 'ar_calc_late_charge.insert_int_overdue_inv()+' );
2811             END IF;
2812 
2813             l_fin_charge_date	:= 	p_fin_charge_date;
2814             l_worker_number     :=      p_worker_number;
2815             l_total_workers     :=      p_total_workers;
2816 /*Bug10335029 Changed sqls to have comparision of tolerance only if its populated else ignore*/
2817             insert into ar_late_charge_trx_t
2818                 (late_charge_trx_id,
2819                  customer_id,
2820                  customer_site_use_id,
2821                  currency_code,
2822                  customer_trx_id,
2823                  legal_entity_id,
2824                  payment_schedule_id,
2825                  class,
2826                  amount_due_original,
2827                  amount_due_remaining,
2828                  fin_charge_charged,
2829                  trx_date,
2830                  cust_trx_type_id,
2831                  last_charge_date,
2832                  exchange_rate_type,
2833                  min_interest_charge,
2834                  max_interest_charge,
2835                  overdue_late_pay_amount,
2836                  original_balance,
2837                  due_date,
2838                  receipt_date,
2839                  finance_charge_date,
2840                  charge_type,
2841                  actual_date_closed,
2842                  interest_rate,
2843                  interest_days,
2844                  rate_start_date,
2845                  rate_end_date,
2846                  schedule_days_start,
2847                  schedule_days_to,
2848                  late_charge_amount,
2849                  late_charge_type,
2850                  late_charge_term_id,
2851                  interest_period_days,
2852                  interest_calculation_period,
2853                  charge_on_finance_charge_flag,
2854                  message_text_id,
2855                  interest_type,
2856                  min_fc_invoice_overdue_type,
2857                  min_fc_invoice_amount,
2858                  min_fc_invoice_percent,
2859                  charge_line_type,
2860 		 org_id,
2861                  request_id,
2862                  display_flag )
2863           (
2864           select ar_late_charge_trx_s.nextval,
2865                  b.customer_id,
2866                  b.customer_site_use_id ,
2867                  b.invoice_currency_code,
2868                  b.customer_trx_id,
2869                  b.legal_entity_id,
2870                  b.payment_schedule_id,
2871                  b.class ,
2872                  b.amount_due_original,
2873                  b.amount_due_remaining ,
2874                  b.fin_charge_charged,
2875                  b.trx_date,
2876                  b.cust_trx_type_id,
2877                  NVL(b.last_charge_date, decode(b.fin_charge_charged,
2878                                                    0, NULL,
2879                                                    b.last_accrue_charge_date)) last_charge_date,
2880                  b.exchange_rate_type,
2881                  b.min_interest_charge,
2882                  b.max_interest_charge,
2883                  b.overdue_amt,
2884                  b.original_balance,
2885                  b.due_date,
2886                  NULL,
2887                  b.fin_charge_date,
2888                  b.charge_type,
2889                  b.actual_date_closed,
2890                  decode(b.interest_type,
2891                         'CHARGES_SCHEDULE',sched_lines.rate,
2892                         'FIXED_RATE',b.interest_rate, NULL) interest_rate,
2893                  least(decode(b.multiple_interest_rates_flag,
2894                                   'Y',decode(sched_hdrs.schedule_header_type,
2895                                              'RATE',
2896                                               nvl(sched_hdrs.end_date,b.eff_fin_charge_date),
2897                                               b.eff_fin_charge_date),
2898                                     b.eff_fin_charge_date),b.eff_fin_charge_date) -
2899                    greatest(decode(b.multiple_interest_rates_flag,
2900                                   'Y',decode(sched_hdrs.schedule_header_type,
2901                                              'RATE',sched_hdrs.start_date-1,b.eff_due_date),
2902                                        b.eff_due_date), b.eff_due_date,b.eff_last_charge_date) interest_days,
2903                  sched_hdrs.start_date rate_start_date,
2904                  sched_hdrs.end_date rate_end_date,
2905                  bucket_lines.days_start schedule_days_start,
2906                  bucket_lines.days_to  schedule_days_to,
2907                  decode(b.interest_type,
2908                         'FIXED_AMOUNT',decode(b.class,
2909                                               'PMT', 0, /* -1* b.interest_fixed_amount,*/
2910                                               'CM', 0,  /*  -1 * b.interest_fixed_amount,*/
2911 					      'INV',decode(sign(b.original_balance),-1,0,b.interest_fixed_amount),  /*Bug 8559863 Take 0 late charge for -ve invoices fixed_amount scenario */
2912                                               b.interest_fixed_amount),
2913                         'CHARGE_PER_TIER', sched_lines.amount,  /*Late charge case of charge per tier Enhacement 6469663*/
2914                               decode(sched_hdrs.schedule_header_type,
2915                                        'AMOUNT',decode(b.class,
2916                                                        'PMT',-1* sched_lines.amount,
2917                                                        'CM', -1* sched_lines.amount,
2918                                                        sched_lines.amount),
2919                                         ar_calc_late_charge.calculate_interest(
2920                                                            b.overdue_amt,
2921                                                            b.charge_on_finance_charge_flag,
2922                                                            least(decode(b.multiple_interest_rates_flag,
2923                                                                        'Y',decode(sched_hdrs.schedule_header_type,
2924                                                                                   'RATE',
2925                                                                                    nvl(sched_hdrs.end_date,
2926                                                                                          b.eff_fin_charge_date),
2927                                                                                    b.eff_fin_charge_date),
2928                                                                        b.eff_fin_charge_date),b.eff_fin_charge_date) -
2929                                                              greatest(decode(b.multiple_interest_rates_flag,
2930                                                                        'Y',decode(sched_hdrs.schedule_header_type,
2931                                                                                   'RATE',sched_hdrs.start_date-1,
2932                                                                                    b.eff_due_date),
2933                                                                         b.eff_due_date),b.eff_due_date,
2934                                                                         b.eff_last_charge_date),
2935                                                             decode(b.interest_type,
2936                                                                     'CHARGES_SCHEDULE',sched_lines.rate,
2937                                                                      'FIXED_RATE',b.interest_rate, NULL),
2938                                                             b.interest_period_days,
2939                                                             b.invoice_currency_code,
2940 							    b.payment_schedule_id))) late_charge_amount,
2941                  b.late_charge_type,
2942                  b.late_charge_term_id,
2943                  b.interest_period_days,
2944                  b.interest_calculation_period,
2945                  b.charge_on_finance_charge_flag,
2946                  b.message_text_id,
2947                  b.interest_type,
2948                  b.min_fc_invoice_overdue_type,
2949                  b.min_fc_invoice_amount,
2950                  b.min_fc_invoice_percent,
2951                  'INTEREST',
2952                  b.org_id,
2953                  l_request_id,
2954                  'Y'
2955      from (
2956           select a.customer_id,
2957                  a.customer_site_use_id ,
2958                  a.invoice_currency_code,
2959                  nvl(a.customer_trx_id, a.cash_receipt_id) customer_trx_id,
2960                  nvl(trx.legal_entity_id,cr.legal_entity_id) legal_entity_id,
2961                  a.payment_schedule_id,
2962                  a.class ,
2963                  a.amount_due_original,
2964                  a.amount_due_remaining ,
2965                  sum(a.fin_charge_charged) fin_charge_charged,
2966                  a.trx_date,
2967                  a.cust_trx_type_id,
2968                  a.last_charge_date,
2969                  a.last_accrue_charge_date,
2970                  a.exchange_rate_type,
2971                  a.min_interest_charge,
2972                  a.max_interest_charge,
2973                  sum(decode(a.charge_on_finance_charge_flag,'Y', a.overdue_amt,
2974                              a.overdue_amt- a.fin_charge_charged)) overdue_amt,
2975                  sum(a.overdue_amt) original_balance,
2976                  a.due_date,
2977                  a.fin_charge_date,
2978                  a.charge_type,
2979                  a.actual_date_closed,
2980                  a.late_charge_type,
2981                  a.late_charge_term_id,
2982                  a.interest_period_days,
2983                  a.interest_calculation_period,
2984                  a.charge_on_finance_charge_flag,
2985                  a.message_text_id,
2986                  a.interest_type,
2987                  a.interest_rate,
2988                  a.interest_schedule_id,
2989                  a.min_fc_invoice_overdue_type,
2990                  a.min_fc_invoice_amount,
2991                  a.min_fc_invoice_percent,
2992                  a.multiple_interest_rates_flag,
2993                  a.hold_charged_invoices_flag,
2994 		 a.org_id,
2995                  a.interest_fixed_amount,
2996                  decode(a.interest_calculation_period,
2997                         'DAILY',l_fin_charge_date,
2998                         'MONTHLY',last_day(l_fin_charge_date)) eff_fin_charge_date,
2999                  decode(a.interest_calculation_period,
3000                         'DAILY',nvl(a.last_charge_date,
3001                                     decode(a.fin_charge_charged,
3002                                            0,a.due_date,
3003                                            a.last_accrue_charge_date)),
3004                         'MONTHLY',first_day(nvl(a.last_charge_date,
3005                                                 decode(a.fin_charge_charged,
3006                                                        0,a.due_date,
3007                                                        a.last_accrue_charge_date)))) eff_last_charge_date,
3008                  decode(a.interest_calculation_period,
3009                              'DAILY',a.due_date,
3010                              'MONTHLY',first_day(a.due_date)) eff_due_date
3011            from (
3012                   select
3013                       ps.customer_id,
3014                       decode(ps.class,
3015                              'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3016                                                                               ps.customer_site_use_id,
3017 									      ps.org_id),
3018                              'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3019                                                                                ps.customer_site_use_id,
3020                                                                                ps.org_id),
3021                               ps.customer_site_use_id) customer_site_use_id,
3022                       ps.invoice_currency_code,
3023                       ps.customer_trx_id,
3024                       ps.payment_schedule_id,
3025                       ps.class ,
3026                       ps.amount_due_original,
3027                       ps.amount_due_remaining,
3028                       sum(case when adj.apply_date > l_fin_charge_date
3029                            then adj.amount*-1 else 0 end )  overdue_amt,
3030                       sum(case when adj.apply_date <= l_fin_charge_date then
3031                              case when adj.type ='CHARGES' then
3032                                     adj.amount else 0 end
3033                              else 0 end)  fin_charge_charged,
3034                       ps.trx_date,
3035                       ps.cust_trx_type_id,
3036                       ps.last_charge_date,
3037                       cust_site.exchange_rate,
3038                       cust_site.exchange_rate_type,
3039                       cust_site.min_interest_charge,
3040                       cust_site.max_interest_charge,
3041                       decode(ps.class,'PMT',ps.trx_date,ps.due_date) due_date,
3042                       l_fin_charge_date  fin_charge_date,
3043                       cust_site.late_charge_type,
3044                       cust_site.late_charge_term_id,
3045                       cust_site.interest_period_days,
3046                       cust_site.interest_calculation_period,
3047                       cust_site.charge_on_finance_charge_flag,
3048                       cust_site.message_text_id,
3049                       ps.actual_date_closed,
3050                       cust_site.last_accrue_charge_date,
3051                       cust_site.interest_type,
3052                       cust_site.interest_rate,
3053                       cust_site.interest_fixed_amount,
3054                       cust_site.interest_schedule_id interest_schedule_id,
3055                       cust_site.min_fc_invoice_overdue_type,
3056                       cust_site.min_fc_invoice_amount,
3057                       cust_site.min_fc_invoice_percent,
3058                       cust_site.multiple_interest_rates_flag,
3059                       cust_site.hold_charged_invoices_flag,
3060 		      ps.org_id,
3061 		      ps.cash_receipt_id,
3062                       'OVERDUE' charge_type
3063                   from  ar_payment_schedules ps,
3064                         ar_adjustments adj,
3065                         ar_lc_cust_sites_t cust_site,
3066                         ar_late_charge_cust_balance_gt bal
3067                    where ps.customer_id = cust_site.customer_id
3068                    and   cust_site.customer_site_use_id = decode(ps.class,
3069                                                        'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3070                                                                                                ps.customer_site_use_id,
3071                                                                                                ps.org_id),
3072                                                        'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3073                                                                                               ps.customer_site_use_id,
3074                                                                                               ps.org_id),
3075                                                          ps.customer_site_use_id)
3076                    and   ps.invoice_currency_code = cust_site.currency_code
3077                    and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
3078                                           decode(l_total_workers,l_worker_number,0,l_worker_number)
3079 		   and   ps.org_id = cust_site.org_id
3080                    and   ps.actual_date_closed > l_fin_charge_date
3081                    and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE','OVERDUE')
3082                    and   cust_site.late_charge_type = 'INV'
3083                    /* Apply Customer Level tolerances */
3084                    and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
3085 		   and   cust_site.org_id = bal.org_id
3086                    and   decode(cust_site.min_fc_balance_overdue_type,
3087                          'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
3088                                     * nvl(bal.customer_open_balance,0)/100),
3089                          'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
3090                            nvl(bal.customer_overdue_balance,0)) <= nvl(bal.customer_overdue_balance,0)
3091                    and   decode(nvl(cust_site.disputed_transactions_flag,'N'),
3092                                 'N',decode(nvl(ps.amount_in_dispute,0),
3093                                            0, 'Y','N'),
3094                                 'Y' ) = 'Y'
3095                    /* Added NVL() for cust_site.credit_items_flag as part of Bug 10280458, manishri */
3096                    and   decode(NVL(cust_site.credit_items_flag, 'N'),'N',
3097                             decode (ps.class, 'PMT','N','CM','N','Y'),'Y') = 'Y'
3098                    and   decode(ps.class,
3099                                 'PMT', ps.trx_date,
3100                                 ps.due_date) < decode(ps.class,
3101                                                'PMT', l_fin_charge_date,
3102                                                'CM', l_fin_charge_date,
3103                                                (l_fin_charge_date  - nvl(cust_site.payment_grace_days,0)))
3104                    and   nvl(ps.last_charge_date,l_fin_charge_date-1) < l_fin_charge_date
3105                    and   nvl(cust_site.charge_begin_date,decode(ps.class,'PMT',ps.trx_date,ps.due_date))
3106                                              <= decode(ps.class,'PMT',ps.trx_date,ps.due_date)
3107                    and   nvl(ps.receipt_confirmed_flag, 'Y') = 'Y'
3108                    and   adj.payment_schedule_id = ps.payment_schedule_id
3109                    and   adj.status = 'A'
3110                    group by
3111                    ps.customer_id,
3112                       decode(ps.class,
3113                              'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3114                                                                               ps.customer_site_use_id,
3115 									      ps.org_id),
3116                              'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3117                                                                                ps.customer_site_use_id,
3118 									       ps.org_id),
3119                               ps.customer_site_use_id),
3120                       ps.invoice_currency_code,
3121                       ps.customer_trx_id,
3122                       ps.payment_schedule_id,
3123                       ps.class ,
3124                       ps.amount_due_original,
3125                       ps.amount_due_remaining,
3126                       ps.trx_date,
3127                       ps.cust_trx_type_id,
3128                       ps.last_charge_date,
3129                       cust_site.exchange_rate,
3130                       cust_site.exchange_rate_type,
3131                       cust_site.min_interest_charge,
3132                       cust_site.max_interest_charge,
3133                       decode(ps.class,'PMT',ps.trx_date,ps.due_date),
3134                       l_fin_charge_date ,
3135                       cust_site.late_charge_type,
3136                       cust_site.late_charge_term_id    ,
3137                       cust_site.interest_period_days,
3138                       cust_site.interest_calculation_period,
3139                       cust_site.charge_on_finance_charge_flag,
3140                       cust_site.message_text_id,
3141                       ps.actual_date_closed,
3142                       cust_site.interest_type,
3143                       cust_site.interest_rate,
3144                       cust_site.interest_fixed_amount,
3145                       cust_site.interest_schedule_id,
3146                       cust_site.min_fc_invoice_overdue_type,
3147                       cust_site.min_fc_invoice_amount,
3148                       cust_site.min_fc_invoice_percent,
3149                       cust_site.multiple_interest_rates_flag,
3150                       cust_site.hold_charged_invoices_flag,
3151 		      ps.org_id,
3152                       ps.cash_receipt_id,
3153                       cust_site.last_accrue_charge_date
3154                 UNION ALL
3155                    select  ps.customer_id,
3156                       decode(ps.class,
3157                              'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3158                                                                               ps.customer_site_use_id,
3159                                                                               ps.org_id),
3160                              'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3161                                                                                ps.customer_site_use_id,
3162                                                                                ps.org_id),
3163                               ps.customer_site_use_id) customer_site_use_id,
3164                       ps.invoice_currency_code,
3165                       ps.customer_trx_id,
3166                       ps.payment_schedule_id,
3167                       ps.class ,
3168                       ps.amount_due_original,
3169                       ps.amount_due_remaining,
3170                       nvl(sum(app.amount_applied
3171                               + nvl(app.earned_discount_taken,0)
3172                               + nvl(app.unearned_discount_taken,0)),0) overdue_amt,
3173                       0 fin_charge_charged,
3174                       ps.trx_date,
3175                       ps.cust_trx_type_id,
3176                       ps.last_charge_date,
3177                       cust_site.exchange_rate,
3178                       cust_site.exchange_rate_type,
3179                       cust_site.min_interest_charge,
3180                       cust_site.max_interest_charge,
3181                       decode(ps.class,'PMT',ps.trx_date,ps.due_date) due_date,
3182                       l_fin_charge_date ,
3183                       cust_site.late_charge_type,
3184                       cust_site.late_charge_term_id    ,
3185                       cust_site.interest_period_days,
3186                       cust_site.interest_calculation_period,
3187                       cust_site.charge_on_finance_charge_flag,
3188                       cust_site.message_text_id,
3189                       ps.actual_date_closed,
3190                       cust_site.last_accrue_charge_date ,
3191                       cust_site.interest_type,
3192                       cust_site.interest_rate,
3193                       cust_site.interest_fixed_amount,
3194                       cust_site.interest_schedule_id,
3195                       cust_site.min_fc_invoice_overdue_type,
3196                       cust_site.min_fc_invoice_amount,
3197                       cust_site.min_fc_invoice_percent,
3198                       cust_site.multiple_interest_rates_flag,
3199                       cust_site.hold_charged_invoices_flag,
3200                       ps.org_id,
3201                       ps.cash_receipt_id,
3202                       'OVERDUE' charge_type
3203                    from  ar_payment_schedules ps,
3204                          ar_receivable_applications app,
3205 			 ar_payment_schedules ps_cm_cr,
3206                          ar_lc_cust_sites_t cust_site,
3207                          ar_late_charge_cust_balance_gt bal
3208                   where  ps.customer_id = cust_site.customer_id
3209                    and   cust_site.customer_site_use_id = decode(ps.class,
3210                                                        'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3211                                                                                                ps.customer_site_use_id,
3212                                                                                                ps.org_id),
3213                                                        'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3214                                                                                               ps.customer_site_use_id,
3215                                                                                               ps.org_id),
3216                                                          ps.customer_site_use_id)
3217                    and   ps.invoice_currency_code = cust_site.currency_code
3218                    and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
3219                                            decode(l_total_workers,l_worker_number,0,l_worker_number)
3220                    and   ps.org_id = cust_site.org_id
3221                    and   ps.actual_date_closed > l_fin_charge_date
3222                    and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE','OVERDUE')
3223                    and   cust_site.late_charge_type = 'INV'
3224                    /* Apply Customer Level tolerances */
3225                    and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
3226                    and   cust_site.org_id = bal.org_id
3227                    and   decode(cust_site.min_fc_balance_overdue_type,
3228                          'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
3229                                     * nvl(bal.customer_open_balance,0)/100),
3230                          'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
3231                             nvl(bal.customer_overdue_balance,0)) <= nvl(bal.customer_overdue_balance,0)
3232                    and   decode(nvl(cust_site.disputed_transactions_flag,'N'),
3233                                 'N',decode(nvl(ps.amount_in_dispute,0),
3234                                            0, 'Y','N'),
3235                                 'Y' ) = 'Y'
3236                    /* Added NVL() for cust_site.credit_items_flag as part of Bug 10280458, manishri */
3237                    and   decode(NVL(cust_site.credit_items_flag, 'N'),'N',
3238                             decode (ps.class, 'PMT','N','CM','N','INV',decode(sign(ps.amount_due_original),-1,'N','Y'),'Y'),'Y') = 'Y'
3239                    and   decode(ps.class,
3240                                 'PMT', ps.trx_date,
3241                                 ps.due_date) < decode(ps.class,
3242                                                'PMT', l_fin_charge_date,
3243                                                'CM', l_fin_charge_date,
3244                                                (l_fin_charge_date  - nvl(cust_site.payment_grace_days,0)))
3245                    and   nvl(ps.last_charge_date,l_fin_charge_date-1) < l_fin_charge_date
3246                    and   nvl(cust_site.charge_begin_date,decode(ps.class,'PMT',ps.trx_date,ps.due_date))
3247                                               <= decode(ps.class,'PMT',ps.trx_date,ps.due_date)
3248                    and   nvl(ps.receipt_confirmed_flag, 'Y') = 'Y'
3249                    and   app.applied_payment_schedule_id = ps.payment_schedule_id
3250                    and   app.status = 'APP'
3251                    and   nvl( app.confirmed_flag, 'Y' ) = 'Y'
3252                    /* The receipt or Credit Memo date has to be compared for application date */
3253                    and   ps_cm_cr.payment_schedule_id = app.payment_schedule_id
3254                    and   ps_cm_cr.trx_date > l_fin_charge_date
3255                 group by ps.customer_id,
3256                       decode(ps.class,
3257                              'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3258                                                                               ps.customer_site_use_id,
3259                                                                               ps.org_id),
3260                              'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3261                                                                                ps.customer_site_use_id,
3262                                                                                ps.org_id),
3263                               ps.customer_site_use_id),
3264                       ps.invoice_currency_code,
3265                       ps.customer_trx_id,
3266                       ps.payment_schedule_id,
3267                       ps.class ,
3268                       ps.amount_due_original,
3269                       ps.amount_due_remaining,
3270                       ps.trx_date,
3271                       ps.cust_trx_type_id,
3272                       ps.last_charge_date,
3273                       cust_site.exchange_rate,
3274                       cust_site.exchange_rate_type,
3275                       cust_site.min_interest_charge,
3276                       cust_site.max_interest_charge,
3277                       decode(ps.class,'PMT',ps.trx_date,ps.due_date),
3278                       l_fin_charge_date ,
3279                       cust_site.late_charge_type,
3280                       cust_site.late_charge_term_id,
3281                       cust_site.interest_period_days,
3282                       cust_site.interest_calculation_period,
3283                       cust_site.charge_on_finance_charge_flag,
3284                       cust_site.message_text_id,
3285                       ps.actual_date_closed ,
3286                       cust_site.interest_type,
3287                       cust_site.interest_rate,
3288                       cust_site.interest_fixed_amount,
3289                       cust_site.interest_schedule_id,
3290                       cust_site.min_fc_invoice_overdue_type,
3291                       cust_site.min_fc_invoice_amount,
3292                       cust_site.min_fc_invoice_percent,
3293                       cust_site.multiple_interest_rates_flag,
3294                       cust_site.hold_charged_invoices_flag,
3295                       ps.org_id,
3296                       ps.cash_receipt_id,
3297                       cust_site.last_accrue_charge_date
3298                UNION ALL
3299                    select  ps.customer_id,
3300                       ps.customer_site_use_id,
3301 		      ps.invoice_currency_code,
3302                       ps.customer_trx_id,
3303                       ps.payment_schedule_id,
3304                       ps.class ,
3305                       ps.amount_due_original,
3306                       ps.amount_due_remaining,
3307                       nvl(sum( nvl(-1*app.amount_applied_from, -1*app.amount_applied)),0) overdue_amt,
3308                       0 fin_charge_charged,
3309                       ps.trx_date,
3310                       ps.cust_trx_type_id,
3311                       ps.last_charge_date,
3312                       cust_site.exchange_rate,
3313                       cust_site.exchange_rate_type,
3314                       cust_site.min_interest_charge,
3315                       cust_site.max_interest_charge,
3316                       ps.due_date  due_date,
3317                       l_fin_charge_date ,
3318                       cust_site.late_charge_type,
3319                       cust_site.late_charge_term_id    ,
3320                       cust_site.interest_period_days,
3321                       cust_site.interest_calculation_period,
3322                       cust_site.charge_on_finance_charge_flag,
3323                       cust_site.message_text_id,
3324                       ps.actual_date_closed,
3325                       cust_site.last_accrue_charge_date ,
3326                       cust_site.interest_type,
3327                       cust_site.interest_rate,
3328                       cust_site.interest_fixed_amount,
3329                       cust_site.interest_schedule_id,
3330                       cust_site.min_fc_invoice_overdue_type,
3331                       cust_site.min_fc_invoice_amount,
3332                       cust_site.min_fc_invoice_percent,
3333                       cust_site.multiple_interest_rates_flag,
3334                       cust_site.hold_charged_invoices_flag,
3335                       ps.org_id,
3336                       ps.cash_receipt_id,
3337                       'OVERDUE' charge_type
3338                    from  ar_payment_schedules ps,
3339                          ar_receivable_applications app,
3340                          ar_lc_cust_sites_t cust_site,
3341                          ar_late_charge_cust_balance_gt bal
3342                   where  ps.customer_id = cust_site.customer_id
3343                    and   cust_site.customer_site_use_id =  ps.customer_site_use_id
3344                    and   ps.invoice_currency_code = cust_site.currency_code
3345                    and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
3346                                            decode(l_total_workers,l_worker_number,0,l_worker_number)
3347                    and   ps.org_id = cust_site.org_id
3348                    and   ps.actual_date_closed > l_fin_charge_date
3349 		   and   ps.class = 'CM'
3350                    and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE','OVERDUE')
3351                    and   cust_site.late_charge_type = 'INV'
3352                    /* Apply Customer Level tolerances */
3353                    and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
3354                    and   cust_site.org_id = bal.org_id
3355                    and   decode(cust_site.min_fc_balance_overdue_type,
3356                          'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
3357                                     * nvl(bal.customer_open_balance,0)/100),
3358                          'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
3359                             nvl(bal.customer_overdue_balance,0)) <= nvl(bal.customer_overdue_balance,0)
3360                    and   decode(nvl(cust_site.disputed_transactions_flag,'N'),
3361                                 'N',decode(nvl(ps.amount_in_dispute,0),
3362                                            0, 'Y','N'),
3363                                 'Y' ) = 'Y'
3364                    /* Added NVL() for cust_site.credit_items_flag as part of Bug 10280458, manishri */
3365                    and   decode(NVL(cust_site.credit_items_flag, 'N'),'N',
3366                             decode (ps.class, 'PMT','N','CM','N','INV',decode(sign(ps.amount_due_original),-1,'N','Y'),'Y'),'Y') = 'Y'
3367                    and    ps.due_date < decode(ps.class,
3368                                                'PMT', l_fin_charge_date,
3369                                                'CM', l_fin_charge_date,
3370                                                (l_fin_charge_date  - nvl(cust_site.payment_grace_days,0)))
3371                    and   nvl(ps.last_charge_date,l_fin_charge_date-1) < l_fin_charge_date
3372                    and   nvl(cust_site.charge_begin_date,decode(ps.class,'PMT',ps.trx_date,ps.due_date))
3373                                               <= decode(ps.class,'PMT',ps.trx_date,ps.due_date)
3374                    and   nvl(ps.receipt_confirmed_flag, 'Y') = 'Y'
3375                    and   app.payment_schedule_id = ps.payment_schedule_id
3376                    and   app.status = 'APP'
3377                    and   app.application_type = 'CM'
3378                    and   nvl( app.confirmed_flag, 'Y' ) = 'Y'
3379                    and   app.apply_date > l_fin_charge_date
3380                 group by ps.customer_id,
3381                       ps.customer_site_use_id,
3382                       ps.invoice_currency_code,
3383                       ps.customer_trx_id,
3384                       ps.payment_schedule_id,
3385                       ps.class ,
3386                       ps.amount_due_original,
3387                       ps.amount_due_remaining,
3388                       ps.trx_date,
3389                       ps.cust_trx_type_id,
3390                       ps.last_charge_date,
3391                       cust_site.exchange_rate,
3392                       cust_site.exchange_rate_type,
3393                       cust_site.min_interest_charge,
3394                       cust_site.max_interest_charge,
3395                       ps.due_date,
3396                       l_fin_charge_date ,
3397                       cust_site.late_charge_type,
3398                       cust_site.late_charge_term_id,
3399                       cust_site.interest_period_days,
3400                       cust_site.interest_calculation_period,
3401                       cust_site.charge_on_finance_charge_flag,
3402                       cust_site.message_text_id,
3403                       ps.actual_date_closed ,
3404                       cust_site.interest_type,
3405                       cust_site.interest_rate,
3406                       cust_site.interest_fixed_amount,
3407                       cust_site.interest_schedule_id,
3408                       cust_site.min_fc_invoice_overdue_type,
3409                       cust_site.min_fc_invoice_amount,
3410                       cust_site.min_fc_invoice_percent,
3411                       cust_site.multiple_interest_rates_flag,
3412                       cust_site.hold_charged_invoices_flag,
3413                       ps.org_id,
3414                       ps.cash_receipt_id,
3415                       cust_site.last_accrue_charge_date
3416                 UNION ALL
3417                    select ps.customer_id,
3418                       decode(ps.class,
3419                              'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3420                                                                               ps.customer_site_use_id,
3421 									      ps.org_id),
3422                              'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3423                                                                                ps.customer_site_use_id,
3424 									       ps.org_id),
3425                               ps.customer_site_use_id) customer_site_use_id,
3426                       ps.invoice_currency_code,
3427                       ps.customer_trx_id,
3428                       ps.payment_schedule_id,
3429                       ps.class ,
3430                       ps.amount_due_original,
3431                       ps.amount_due_remaining,
3432                       ps.amount_due_remaining overdue_amt,
3433                       0 fin_charge_charged,
3434                       ps.trx_date,
3435                       ps.cust_trx_type_id,
3436                       ps.last_charge_date,
3437                       cust_site.exchange_rate,
3438                       cust_site.exchange_rate_type,
3439                       cust_site.min_interest_charge,
3440                       cust_site.max_interest_charge,
3441                       decode(ps.class,'PMT',ps.trx_date,ps.due_date)due_date,
3442                       l_fin_charge_date ,
3443                       cust_site.late_charge_type,
3444                       cust_site.late_charge_term_id    ,
3445                       cust_site.interest_period_days,
3446                       cust_site.interest_calculation_period,
3447                       cust_site.charge_on_finance_charge_flag,
3448                       cust_site.message_text_id,
3449                       ps.actual_date_closed,
3450                       cust_site.last_accrue_charge_date ,
3451                       cust_site.interest_type,
3452                       cust_site.interest_rate,
3453                       cust_site.interest_fixed_amount,
3454                       cust_site.interest_schedule_id,
3455                       cust_site.min_fc_invoice_overdue_type,
3456                       cust_site.min_fc_invoice_amount,
3457                       cust_site.min_fc_invoice_percent,
3458                       cust_site.multiple_interest_rates_flag,
3459                       cust_site.hold_charged_invoices_flag,
3460                       ps.org_id,
3461 		      ps.cash_receipt_id,
3462                       'OVERDUE' charge_type
3463                    from  ar_payment_schedules ps,
3464                          ar_lc_cust_sites_t cust_site,
3465                          ar_late_charge_cust_balance_gt bal
3466                    where ps.customer_id = cust_site.customer_id
3467                    and   cust_site.customer_site_use_id = decode(ps.class,
3468                                                       'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3469                                                                                              ps.customer_site_use_id,
3470 											     ps.org_id),
3471                                                       'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3472                                                                                              ps.customer_site_use_id,
3473 											     ps.org_id),
3474                                                          ps.customer_site_use_id)
3475                    and   ps.invoice_currency_code = cust_site.currency_code
3476                    and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
3477                                           decode(l_total_workers,l_worker_number,0,l_worker_number)
3478 		   and   ps.org_id = cust_site.org_id
3479                    and   ps.actual_date_closed > l_fin_charge_date
3480                    and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE','OVERDUE')
3481                    and   cust_site.late_charge_type = 'INV'
3482                    /* Apply Customer Level tolerances */
3483                    and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
3484 		   and   cust_site.org_id = bal.org_id
3485                    and   decode(cust_site.min_fc_balance_overdue_type,
3486                          'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
3487                                     * nvl(bal.customer_open_balance,0)/100),
3488                          'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
3489                             nvl(bal.customer_overdue_balance,0)) <= nvl(bal.customer_overdue_balance,0)
3490                    and   decode(nvl(cust_site.disputed_transactions_flag,'N'),
3491                                 'N',decode(nvl(ps.amount_in_dispute,0),
3492                                            0, 'Y','N'),
3493                                 'Y' ) = 'Y'
3494                    /* Added NVL() for cust_site.credit_items_flag as part of Bug 10280458, manishri */
3495                    and   decode(NVL(cust_site.credit_items_flag, 'N'),'N',
3496                             decode (ps.class, 'PMT','N','CM','N','INV',decode(sign(ps.amount_due_original),-1,'N','Y'),'Y'),'Y') = 'Y'  /*8559863*/
3497                    and   decode(ps.class,
3498                                 'PMT', ps.trx_date,
3499                                 ps.due_date) < decode(ps.class,
3500                                                'PMT', l_fin_charge_date,
3501                                                'CM', l_fin_charge_date,
3502                                                (l_fin_charge_date  - nvl(cust_site.payment_grace_days,0)))
3503                    and   nvl(ps.last_charge_date,l_fin_charge_date-1) < l_fin_charge_date
3504                    and   nvl(cust_site.charge_begin_date,decode(ps.class,'PMT',ps.trx_date,ps.due_date))
3505 						 <= decode(ps.class,'PMT',ps.trx_date,ps.due_date)
3506                    and   decode(ps.class,
3507                                 'PMT',ps.trx_date,
3508                                 'CM',ps.trx_date,ps.due_date) <= l_fin_charge_date
3509                    and   nvl(ps.receipt_confirmed_flag, 'Y') = 'Y') a,
3510                          ra_customer_trx  trx,
3511                          ra_cust_trx_types types,
3512                          ar_transaction_history th,
3513 			 ar_cash_receipts cr
3514                    where trx.customer_trx_id(+) = a.customer_trx_id
3515                    and   nvl(trx.finance_charges,decode(a.class,'DEP','N','Y')) = 'Y'
3516                    and   a.customer_trx_id = th.customer_trx_id(+)
3517                    and   nvl(th.current_record_flag,'Y') = 'Y'
3518                    and   nvl(th.status,'*') not in ('PROTESTED','MATURED_PEND_RISK_ELIMINATION','CLOSED', 'CANCELLED')
3519                    and   types.cust_trx_type_id(+) = a.cust_trx_type_id
3520 		   and	 types.org_id(+) = a.org_id
3521                    and   nvl(types.exclude_from_late_charges,'N') <> 'Y'
3522                    and   cr.cash_receipt_id(+) = a.cash_receipt_id
3523                    and   decode(a.hold_charged_invoices_flag,
3524                                'Y',decode(a.last_charge_date,
3525                                           NULL,a.fin_charge_charged,1),
3526                                 0) = 0
3527                   group by a.customer_id,
3528                            a.customer_site_use_id ,
3529                            a.invoice_currency_code,
3530                            nvl(a.customer_trx_id,a.cash_receipt_id),
3531                            nvl(trx.legal_entity_id,cr.legal_entity_id),
3532                            a.payment_schedule_id,
3533                            a.class ,
3534                            a.amount_due_original,
3535                            a.amount_due_remaining ,
3536                            a.trx_date,
3537                            a.cust_trx_type_id,
3538                            a.last_charge_date,
3539                            a.last_accrue_charge_date,
3540                            a.exchange_rate_type,
3541                            a.min_interest_charge,
3542                            a.max_interest_charge,
3543                            a.due_date,
3544                            a.fin_charge_date,
3545                            a.charge_type,
3546                            a.actual_date_closed,
3547                            a.late_charge_type,
3548                            a.late_charge_term_id,
3549                            a.interest_period_days,
3550                            a.interest_calculation_period,
3551                            a.charge_on_finance_charge_flag,
3552                            a.message_text_id,
3553                            a.interest_type,
3554                            a.interest_rate,
3555                            a.interest_schedule_id,
3556                            a.min_fc_invoice_overdue_type,
3557                            a.min_fc_invoice_amount,
3558                            a.min_fc_invoice_percent,
3559                            a.multiple_interest_rates_flag,
3560                            a.hold_charged_invoices_flag,
3561 			   a.org_id,
3562                            a.interest_fixed_amount,
3563                            decode(a.interest_calculation_period,
3564                                   'DAILY',l_fin_charge_date,
3565                                   'MONTHLY',last_day(l_fin_charge_date)),
3566                            decode(a.interest_calculation_period,
3567                                   'DAILY',nvl(a.last_charge_date,
3568                                               decode(a.fin_charge_charged,
3569                                                      0,a.due_date,
3570                                                      a.last_accrue_charge_date)),
3571                                   'MONTHLY',first_day(nvl(a.last_charge_date,
3572                                                           decode(a.fin_charge_charged,
3573                                                                  0,a.due_date,
3574                                                                  a.last_accrue_charge_date)))),
3575                            decode(a.interest_calculation_period,
3576                                   'DAILY',a.due_date,
3577                                   'MONTHLY',first_day(a.due_date)))b,
3578                          ar_charge_schedule_hdrs sched_hdrs,
3579                          ar_charge_schedule_lines  sched_lines,
3580                          ar_aging_bucket_lines bucket_lines
3581                 where b.interest_schedule_id = sched_hdrs.schedule_id(+)
3582                 and   sched_hdrs.schedule_header_id = sched_lines.schedule_header_id(+)
3583                 and   sched_hdrs.schedule_id = sched_lines.schedule_id(+)
3584                 and    nvl(sched_hdrs.status,'A') = 'A'
3585                 and   sched_lines.aging_bucket_id = bucket_lines.aging_bucket_id(+)
3586                 and   sched_lines.aging_bucket_line_id = bucket_lines.aging_bucket_line_id(+)
3587                 /* Condition 1: days late should be between the bucket lines start and end days */
3588                 and   (l_fin_charge_date- b.due_date) >= nvl(bucket_lines.days_start,(l_fin_charge_date- b.due_date))
3589                 and   (l_fin_charge_date - b.due_date) <= nvl(bucket_lines.days_to,(l_fin_charge_date- b.due_date))
3590                 /* Condition 2:
3591                    Start_date of the schedule should be less than or equal to the finance charge date */
3592                 and   nvl(sched_hdrs.start_date,l_fin_charge_date) <= l_fin_charge_date
3593                /* condition 3:
3594                   If multiple interest rates have to be used, end date of the schedule should be greater than
3595                   or equal to the due date or the date from which we are calculating the charge
3596                   Otherwise, the end_date should either be null or it should be greater than the
3597                   due_date
3598                 */
3599                 and  (decode(b.multiple_interest_rates_flag,'Y',
3600                              decode(sched_hdrs.schedule_header_type,
3601                                     'RATE',greatest(b.due_date,nvl(b.last_charge_date,b.due_date)),
3602                                     b.due_date),
3603                              b.due_date) <= sched_hdrs.end_date
3604                        OR sched_hdrs.end_date IS NULL )
3605                 /* Condition 4: If multiple rates need not be used, we should pick up the rate
3606                    that is effective on the due_date of the transaction.
3607                    Also note that the multiple interest rates are used only for Interest
3608                    Calculation and only when rates are used*/
3609                 and decode(b.multiple_interest_rates_flag,'Y',
3610                        decode(sched_hdrs.schedule_header_type,
3611                                'RATE',sched_hdrs.start_date,
3612                                b.due_date),
3613                        b.due_date )>= nvl(sched_hdrs.start_date,b.due_date)
3614                 /* Make sure that this payment schedule is not part of a failed final batch */
3615                 and not exists (select payment_schedule_id
3616                                 from   ar_interest_lines lines,
3617                                        ar_interest_headers hdrs,
3618 				       ar_interest_batches bat
3619 				where  lines.payment_schedule_id = b.payment_schedule_id
3620 				and    lines.interest_header_id = hdrs.interest_header_id
3621                                 and    hdrs.interest_batch_id = bat.interest_batch_id
3622                                 and    bat.batch_status ='F'
3623                                 and    bat.transferred_status <> 'S'));
3624 
3625 
3626 
3627        IF l_debug_flag = 'Y' THEN
3628              debug( 'ar_calc_late_charge.insert_int_overdue_inv()-' );
3629        END IF;
3630     --
3631  EXCEPTION
3632         WHEN  OTHERS THEN
3633              --IF l_debug_flag = 'Y' THEN
3634                   debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
3635                   debug('EXCEPTION: ar_calc_late_charge.insert_int_overdue_inv' );
3636              --END IF;
3637              RAISE;
3638 
3639 END insert_int_overdue_inv;
3640 /*=========================================================================================+
3641  | PROCEDURE insert_int_late_pay                                                           |
3642  |                                                                                         |
3643  | DESCRIPTION                                                                             |
3644  |                                                                                         |
3645  |   This procedure finds out the late payments on any debit item. By late payment, we     |
3646  |   mean the applications done on it after the due_date / last finance charge date .      |
3647  |   Interest Amount is  then calculated on the overdue balance and inserted into          |
3648  |   ar_late_charge_trx_t                                                                  |
3649  |                                                                                         |
3650  | PSEUDO CODE/LOGIC                                                                       |
3651  |                                                                                         |
3652  | a) The Receipt Date is used for finding out the late applications on a debit item. So,  |
3653  |    if an application is Reversed, that need not be considered as the application and    |
3654  |    it's reversal  will cancel out each other on that receipt date.                      |
3655  | b) The finance charge that is already charged on this invoice is fetched from           |
3656  |    ar_adjustments                                                                       |
3657  | c) Open Credit Items are not considered as we are tracking only the late applications   |
3658  |                                                                                         |
3659  | PARAMETERS                                                                              |
3660  |                                                                                         |
3661  |                                                                                         |
3662  | KNOWN ISSUES                                                                            |
3663  |                                                                                         |
3664  | NOTES                                                                                   |
3665  |                                                                                         |
3666  | MODIFICATION HISTORY                                                                    |
3667  | Date                  Author            Description of Changes                          |
3668  | 16-FEB-2006           rkader            Created                                         |
3669  | 11-JUL-2006           rkader            Bug 5290709 : Last charge date should not be    |
3670  |                                         considered for the calculation of the interest. |
3671  |                                         The late payment is always from the due date    |
3672  |                                         to the receipt date                             |
3673  |24-JUN-2008            naneja            Bug 7162382 : In above fix for bug 5290709      |
3674  |                                         Late charge was calculated in duplicate for     |
3675  |                                         late payment and overdue invoice case.          |
3676  |                                         Last run must have calculated interest for      |
3677  |                                         amount of                                       |
3678  |                                         late payment. Thus merge 5290709 fix of         |
3679  |                                         late payment only fix with this fix.            |
3680  |22-JUN-2009            naneja            Inserted data for new column cash_receipt_id    |
3681  |                                         Bug 8556955                                     |
3682  *=========================================================================================*/
3683 
3684 PROCEDURE insert_int_late_pay(p_fin_charge_date		IN	DATE,
3685                               p_worker_number           IN      NUMBER,
3686                               p_total_workers           IN      NUMBER) IS
3687 
3688   l_fin_charge_date	DATE;
3689   l_worker_number       number;
3690   l_total_workers       number;
3691 
3692 BEGIN
3693        IF l_debug_flag = 'Y' THEN
3694              debug( 'ar_calc_late_charge.insert_int_late_pay()+' );
3695        END IF;
3696 
3697        l_fin_charge_date 	    :=	    p_fin_charge_date;
3698        l_worker_number              :=      p_worker_number;
3699        l_total_workers              :=      p_total_workers;
3700 
3701 /*=========================================================================================*
3702  | Sample Cases:                                                                           |
3703  | Case1:                                                                                  |
3704  |    Suppose that there is an invoice for 1000 USD, due on 01-JAN-2006.                   |
3705  |    1) There is a receipt application on this invoice on 20-Jan-2006, for 500 USD.       |
3706  |    2) Late Charge is computed on this Late Payment as on 31-Jan-2006, and let's say that|
3707  |       the calculated amount is 50 USD (500 USD paid late by 20 days) and we are creating|
3708  |       adjustments. So the balance of this invoice is 550 USD as on 31-Jan-2006.         |
3709  |    3) Consider the following cases of another application on this invoice and we have to|
3710  |       compute the finance charge as of 28-Feb-2006.                                     |
3711  |       Case  a) A receipt application for 550 USD on 10-Feb-2006                         |
3712  |       Case  b) A receipt application for 500 USD on 10-Feb-2006                         |
3713  |       Case  c) A receipt application for 600 USD on 10-Feb-2006                         |
3714  |                                                                                         |
3715  |     If we have to calculate Compound Interest, we will have the late paid amount (amount|
3716  |     on which interest is computed) as                                                   |
3717  |     Case  a) 550 USD Case  b) 500 USD  Case  c) 550 USD                                 |
3718  |                                                                                         |
3719  |     If Simple or Flat Rate has to be used, we should not charge interest on interest. So|
3720  |     the late paid amount should be computed subtracting upto the finance charge already |
3721  |     charged on this invoice. So the late paid amount will be                            |
3722  |     Case a) 500 USD Case  b) 500 USD  Case  c) 500 USD                                  |
3723  |                                                                                         |
3724  |     Note that the interest will NOT be calculated on the over applied amount.           |
3725  *=========================================================================================*/
3726 /*Bug 8277068 Corrected interest days calclulation to pick least from eff_apply_date and charge schedule end date*/
3727        insert into ar_late_charge_trx_t
3728            (late_charge_trx_id,
3729             customer_id,
3730             customer_site_use_id,
3731             currency_code,
3732             customer_trx_id,
3733             legal_entity_id,
3734             payment_schedule_id,
3735             class,
3736             amount_due_original,
3737             amount_due_remaining,
3738             fin_charge_charged,
3739             trx_date,
3740             cust_trx_type_id,
3741             last_charge_date,
3742             --exchange_rate,
3743             exchange_rate_type,
3744             min_interest_charge,
3745             max_interest_charge,
3746             overdue_late_pay_amount,
3747             original_balance,
3748             due_date,
3749             receipt_date,
3750             finance_charge_date,
3751             charge_type,
3752             actual_date_closed,
3753             interest_rate,
3754             interest_days,
3755             rate_start_date,
3756             rate_end_date,
3757             schedule_days_start,
3758             schedule_days_to,
3759             late_charge_amount,
3760             late_charge_type,
3761             late_charge_term_id,
3762             interest_period_days,
3763             interest_calculation_period,
3764             charge_on_finance_charge_flag,
3765             message_text_id,
3766             interest_type,
3767             min_fc_invoice_overdue_type,
3768             min_fc_invoice_amount,
3769             min_fc_invoice_percent,
3770             charge_line_type,
3771 	    org_id,
3772 	    request_id,
3773             display_flag,
3774 	    cash_receipt_id)
3775        (select ar_late_charge_trx_s.nextval,
3776                a.customer_id,
3777                a.customer_site_use_id ,
3778                a.invoice_currency_code,
3779                a.customer_trx_id,
3780                a.legal_entity_id,
3781                a.payment_schedule_id,
3782                a.class ,
3783                a.amount_due_original,
3784                a.amount_due_remaining,
3785                a.fin_charge_charged,
3786                a.trx_date,
3787                a.cust_trx_type_id,
3788                a.last_charge_date ,
3789                --exchange_rate,
3790                a.exchange_rate_type,
3791                a.min_interest_charge,
3792                a.max_interest_charge,
3793                decode(sign(a.late_pay_amount - a.original_balance),
3794                           -1, a.late_pay_amount,
3795                            0, a.late_pay_amount,
3796                            a.original_balance) overdue_late_pay_amount,
3797                a.original_balance,
3798                a.due_date,
3799                a.receipt_date,
3800                a.finance_charge_date,
3801                a.charge_type,
3802                a.actual_date_closed,
3803                decode(a.interest_type,
3804                          'CHARGES_SCHEDULE',sched_lines.rate,
3805                          'FIXED_RATE',a.interest_rate, NULL) interest_rate,
3806                least(decode(a.multiple_interest_rates_flag,
3807                            'Y',decode(sched_hdrs.schedule_header_type,
3808                                       'RATE', nvl(sched_hdrs.end_date,a.eff_apply_date),
3809                                        a.eff_apply_date),
3810                               a.eff_apply_date),a.eff_apply_date) -
3811                   greatest(decode(a.multiple_interest_rates_flag,
3812                                   'Y',decode(sched_hdrs.schedule_header_type,
3813                                             'RATE',sched_hdrs.start_date-1,a.eff_due_date),
3814                      a.eff_due_date), a.eff_due_date,decode(a.eff_charge_type,'OVERDUE_LATE',a.eff_last_charge_date,a.eff_due_date)) interest_days, /*Merge-Bug fix 5290709 for overdue and late case*/
3815               sched_hdrs.start_date rate_start_date,
3816               sched_hdrs.end_date rate_end_date ,
3817               bucket_lines.days_start schedule_days_start,
3818               bucket_lines.days_to  schedule_days_to,
3819               decode(a.interest_type,
3820                      'FIXED_AMOUNT',a.interest_fixed_amount,
3821                         decode(sched_hdrs.schedule_header_type,
3822                                'AMOUNT',sched_lines.amount,
3823                                ar_calc_late_charge.calculate_interest(
3824                                                       decode(sign(a.late_pay_amount - a.original_balance),
3825                                                              -1,a.late_pay_amount,
3826                                                               0,a.late_pay_amount,
3827                                                               a.original_balance),
3828                                                       a.charge_on_finance_charge_flag,
3829                                                       least(decode(a.multiple_interest_rates_flag,
3830                                                                   'Y',decode(sched_hdrs.schedule_header_type,
3831                                                                      'RATE', nvl(sched_hdrs.end_date,a.eff_apply_date),
3832                                                                                 a.eff_apply_date),
3833                                                                    a.eff_apply_date),a.eff_apply_date) -
3834                                                           greatest(decode(a.multiple_interest_rates_flag,
3835                                                                      'Y',decode(sched_hdrs.schedule_header_type,
3836                                                                        'RATE',sched_hdrs.start_date-1,a.eff_due_date),
3837                      a.eff_due_date), a.eff_due_date,decode(a.eff_charge_type,'OVERDUE_LATE',a.eff_last_charge_date,a.eff_due_date)),/* Merge fix  7162382 for overdue and late case -Bug fix 5290709 */
3838                                                       decode(a.interest_type,
3839                                                             'CHARGES_SCHEDULE',sched_lines.rate,
3840                                                             'FIXED_RATE',a.interest_rate, NULL),
3841                                                              a.interest_period_days,
3842                                                       a.invoice_currency_code,
3843 						      a.payment_schedule_id))) late_charge_amount,
3844               a.late_charge_type,
3845               a.late_charge_term_id,
3846               a.interest_period_days,
3847               a.interest_calculation_period,
3848               a.charge_on_finance_charge_flag,
3849               a.message_text_id,
3850               a.interest_type,
3851               a.min_fc_invoice_overdue_type,
3852               a.min_fc_invoice_amount,
3853               a.min_fc_invoice_percent,
3854               'INTEREST',
3855 	      a.org_id,
3856 	      l_request_id,
3857               'Y',
3858 	      a.cash_receipt_id
3859      from
3860      (
3861       select  ps.customer_id,
3862               decode(ps.class,
3863                      'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3864                                                                       ps.customer_site_use_id,
3865 								      ps.org_id),
3866                       ps.customer_site_use_id) customer_site_use_id ,
3867               ps.invoice_currency_code,
3868               ps.customer_trx_id,
3869               nvl(trx.legal_entity_id,cr.legal_entity_id) legal_entity_id,
3870               ps.payment_schedule_id,
3871               ps.class ,
3872               ps.amount_due_original,
3873               ps.amount_due_remaining,
3874               nvl(adj.fin_charge_charged,0) fin_charge_charged,
3875               ps.trx_date,
3876               ps.cust_trx_type_id,
3877               nvl(ps.last_charge_date,
3878                        decode(nvl(adj.fin_charge_charged,0),0,NULL,
3879                                    cust_site.last_accrue_charge_date)) last_charge_date ,
3880               cust_site.exchange_rate_type,
3881               cust_site.min_interest_charge,
3882               cust_site.max_interest_charge,
3883               sum(app.amount_applied + nvl(app.earned_discount_taken,0) +
3884                                    nvl(app.unearned_discount_taken,0)) late_pay_amount,
3885               ar_calc_late_charge.get_balance_as_of(ps.payment_schedule_id,
3886                                                     cr.receipt_date-1,
3887                                                     ps.class,
3888                                                     cust_site.charge_on_finance_charge_flag) original_balance,
3889               ps.due_date,
3890               cr.receipt_date,
3891               l_fin_charge_date finance_charge_date,
3892               cust_site.late_charge_type,
3893               ps.actual_date_closed,
3894               cust_site.late_charge_term_id,
3895               cust_site.interest_period_days,
3896               cust_site.interest_calculation_period,
3897               cust_site.charge_on_finance_charge_flag,
3898               cust_site.message_text_id,
3899               cust_site.last_accrue_charge_date,
3900               cust_site.interest_type,
3901               cust_site.interest_rate,
3902               cust_site.interest_fixed_amount,
3903               cust_site.interest_schedule_id interest_schedule_id,
3904               cust_site.min_fc_invoice_overdue_type,
3905               cust_site.min_fc_invoice_amount,
3906               cust_site.min_fc_invoice_percent,
3907               cust_site.multiple_interest_rates_flag,
3908               cust_site.hold_charged_invoices_flag,
3909 	      ps.org_id,
3910               decode(cust_site.interest_calculation_period,
3911                      'DAILY',cr.receipt_date,
3912                      'MONTHLY',last_day(cr.receipt_date)) eff_apply_date,
3913               decode(cust_site.interest_calculation_period,
3914                      'DAILY',nvl(ps.last_charge_date,
3915                                      decode(nvl(adj.fin_charge_charged,0),0,ps.due_date,
3916                                            nvl(cust_site.last_accrue_charge_date,ps.due_date))),
3917                      'MONTHLY',first_day(nvl(ps.last_charge_date,
3918                        decode(nvl(adj.fin_charge_charged,0),0,ps.due_date,
3919                                    nvl(cust_site.last_accrue_charge_date,ps.due_date))))) eff_last_charge_date,
3920               decode(cust_site.interest_calculation_period,
3921                      'DAILY',ps.due_date,
3922                      'MONTHLY',first_day(ps.due_date)) eff_due_date,
3923               'LATE' charge_type,
3924 	      cust_site.late_charge_calculation_trx eff_charge_type,
3925 	      cr.cash_receipt_id
3926          from  ar_payment_schedules ps,
3927                ar_lc_cust_sites_t cust_site,
3928                ar_late_charge_cust_balance_gt bal,
3929                ar_receivable_applications app,
3930                ar_cash_receipts cr,
3931                ra_cust_trx_types types,
3932                ra_customer_trx trx,
3933                ar_transaction_history th,
3934                (select ps.payment_schedule_id ,sum(adj.amount) fin_charge_charged
3935                  from ar_payment_schedules ps,
3936                       ar_adjustments adj,
3937                       ar_lc_cust_sites_t cust_site
3938                 where ps.customer_id = cust_site.customer_id
3939                 and   decode(cust_site.customer_site_use_id,'','X', ps.customer_site_use_id)
3940                         = decode(cust_site.customer_site_use_id,'','X', cust_site.customer_site_use_id)
3941                 and   ps.invoice_currency_code = cust_site.currency_code
3942                 and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
3943                                           decode(l_total_workers,l_worker_number,0,l_worker_number)
3944                 and   ps.org_id = cust_site.org_id
3945                 and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE','LATE')
3946                 and   decode(cust_site.disputed_transactions_flag,'N',
3947                          decode(nvl(ps.amount_in_dispute,0), 0, 'Y','N'),'Y' ) = 'Y'
3948                 and   ps.class not in ('CM','PMT')
3949                 and   adj.payment_schedule_id = ps.payment_schedule_id
3950                 and   adj.status = 'A'
3951                 and   adj.apply_date <= l_fin_charge_date
3952                 and   adj.type ='CHARGES'
3953                 group by ps.payment_schedule_id) adj
3954         where  ps.customer_id = cust_site.customer_id
3955          and   cust_site.customer_site_use_id = decode(ps.class,
3956                                                        'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
3957                                                                                               ps.customer_site_use_id,
3958 											      ps.org_id),
3959                                                        ps.customer_site_use_id)
3960          and   ps.invoice_currency_code = cust_site.currency_code
3961          and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
3962                                           decode(l_total_workers,l_worker_number,0,l_worker_number)
3963 	 and   ps.org_id = cust_site.org_id
3964          and   cust_site.late_charge_calculation_trx in ('OVERDUE_LATE','LATE')
3965          and   decode(nvl(cust_site.disputed_transactions_flag,'N'),
3966                           'N',decode(nvl(ps.amount_in_dispute,0),
3967                                       0, 'Y','N'),
3968                           'Y' ) = 'Y'
3969          /* Apply Customer Level tolerances */
3970          and   cust_site.lc_cust_sites_id = bal.late_charge_cust_sites_id
3971 	 and   cust_site.org_id = bal.org_id
3972 /*Commenting as part of bug13632418 */
3973 /*         and   decode(cust_site.min_fc_balance_overdue_type,
3974                       'PERCENT',(nvl(cust_site.min_fc_balance_percent,0)
3975                                 * nvl(bal.customer_open_balance,0)/100),
3976                       'AMOUNT',nvl(cust_site.min_fc_balance_amount,0),
3977                             nvl(bal.customer_overdue_balance,0)) <= nvl(bal.customer_overdue_balance,0) */ /*Bug8464171*/
3978          and   app.applied_payment_schedule_id = ps.payment_schedule_id
3979          and   app.application_type = 'CASH'
3980          and   app.status = 'APP'
3981          and   app.reversal_gl_date IS NULL
3982          and   nvl(app.confirmed_flag, 'Y' ) = 'Y'
3983          and   cr.cash_receipt_id = app.cash_receipt_id
3984          and   ps.class not in ('CM','PMT')
3985          and   ps.due_date < (cr.receipt_date - nvl(cust_site.payment_grace_days,0))
3986          and   nvl(cust_site.charge_begin_date,ps.due_date) <= ps.due_date
3987          and   cr.receipt_date <= l_fin_charge_date
3988          and   cr.receipt_date > nvl(ps.last_charge_date,cr.receipt_date-1)
3989          and   adj.payment_schedule_id(+) = ps.payment_schedule_id
3990          and   decode(cust_site.hold_charged_invoices_flag,
3991                          'Y',decode(ps.last_charge_date,
3992                                     NULL,nvl(adj.fin_charge_charged,0),
3993                                     1),
3994                          0) = 0
3995          /* The Payments are not fetched. So there can be a hard join with cust_trx_types */
3996          and  types.cust_trx_type_id = ps.cust_trx_type_id
3997 	 and  types.org_id = ps.org_id
3998          and  nvl(types.exclude_from_late_charges,'N') <> 'Y'
3999          and  trx.customer_trx_id(+) = ps.customer_trx_id
4000          and  nvl(trx.finance_charges,decode(ps.class,'DEP','N','Y')) = 'Y'
4001          and  th.customer_trx_id(+) = ps.customer_trx_id
4002 	 and  nvl(th.current_record_flag,'Y') = 'Y'
4003          and  nvl(th.status,'*') not in ('PROTESTED','MATURED_PEND_RISK_ELIMINATION','CLOSED', 'CANCELLED')
4004   group by    ps.customer_id,
4005               decode(ps.class,
4006                      'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
4007                                                                       ps.customer_site_use_id,
4008 								      ps.org_id),
4009                       ps.customer_site_use_id),
4010               ps.invoice_currency_code,
4011               ps.customer_trx_id,
4012               nvl(trx.legal_entity_id,cr.legal_entity_id),
4013               ps.payment_schedule_id,
4014               ps.class ,
4015               ps.amount_due_original,
4016               ps.amount_due_remaining,
4017               nvl(adj.fin_charge_charged,0),
4018               ps.trx_date,
4019               ps.cust_trx_type_id,
4020               nvl(ps.last_charge_date,
4021                        decode(nvl(adj.fin_charge_charged,0),0,NULL,
4022                                    cust_site.last_accrue_charge_date)),
4023               cust_site.exchange_rate_type,
4024               cust_site.min_interest_charge,
4025               cust_site.max_interest_charge,
4026               ar_calc_late_charge.get_balance_as_of(ps.payment_schedule_id,
4027                                                     cr.receipt_date-1,
4028                                                     ps.class,
4029                                                     cust_site.charge_on_finance_charge_flag),
4030               ps.due_date,
4031               cr.receipt_date,
4032               l_fin_charge_date,
4033               cust_site.late_charge_type,
4034               ps.actual_date_closed,
4035               cust_site.late_charge_term_id,
4036               cust_site.interest_period_days,
4037               cust_site.interest_calculation_period,
4038               cust_site.charge_on_finance_charge_flag,
4039               cust_site.message_text_id,
4040               cust_site.last_accrue_charge_date,
4041               cust_site.interest_type,
4042               cust_site.interest_rate,
4043               cust_site.interest_fixed_amount,
4044               cust_site.interest_schedule_id,
4045               cust_site.min_fc_invoice_overdue_type,
4046               cust_site.min_fc_invoice_amount,
4047               cust_site.min_fc_invoice_percent,
4048               cust_site.multiple_interest_rates_flag,
4049               cust_site.hold_charged_invoices_flag,
4050 	      ps.org_id,
4051               decode(cust_site.interest_calculation_period,
4052                      'DAILY',cr.receipt_date,
4053                      'MONTHLY',last_day(cr.receipt_date)),
4054               decode(cust_site.interest_calculation_period,
4055                      'DAILY',nvl(ps.last_charge_date,
4056                                      decode(nvl(adj.fin_charge_charged,0),0,ps.due_date,
4057                                            nvl(cust_site.last_accrue_charge_date,ps.due_date))),
4058                      'MONTHLY',first_day(nvl(ps.last_charge_date,
4059                        decode(nvl(adj.fin_charge_charged,0),0,ps.due_date,
4060                                    nvl(cust_site.last_accrue_charge_date,ps.due_date))))),
4061               decode(cust_site.interest_calculation_period,
4062                      'DAILY',ps.due_date,
4063                      'MONTHLY',first_day(ps.due_date)),
4064 	      cust_site.late_charge_calculation_trx,
4065 	      cr.cash_receipt_id) a,
4066                    ar_charge_schedule_hdrs sched_hdrs,
4067                    ar_charge_schedule_lines  sched_lines,
4068                    ar_aging_bucket_lines bucket_lines
4069           where   a.interest_schedule_id = sched_hdrs.schedule_id(+)
4070           and   sched_hdrs.schedule_header_id = sched_lines.schedule_header_id(+)
4071           and   sched_hdrs.schedule_id = sched_lines.schedule_id(+)
4072           and    nvl(sched_hdrs.status,'A') = 'A'
4073           and   sched_lines.aging_bucket_id = bucket_lines.aging_bucket_id(+)
4074           and   sched_lines.aging_bucket_line_id = bucket_lines.aging_bucket_line_id(+)
4075           /* Condition 1: days late should be between the bucket lines start and end days */
4076           and   (a.receipt_date- a.due_date) >= nvl(bucket_lines.days_start,(a.receipt_date- a.due_date))
4077           and   (a.receipt_date - a.due_date) <= nvl(bucket_lines.days_to,(a.receipt_date- a.due_date))
4078           /* Condition 2: Start_date of the schedule should be less than or equal to the
4079              finance charge date */
4080           and   nvl(sched_hdrs.start_date,a.receipt_date) <= a.receipt_date
4081           /* condition 3:
4082               If multiple interest rates have to be used, end date of the schedule should be greater than
4083               or equal to the due date or the date from which we are calculating the charge
4084               Otherwise, the end_date should either be null or it should be greater than the
4085               due_date to pick up the rate effective as of the due_date
4086               Bug 8343193 For multiple interest rate for late payment we need to consider schedules from due date
4087                */
4088            and  (decode(a.multiple_interest_rates_flag,'Y',
4089                         decode(sched_hdrs.schedule_header_type,
4090                                'RATE',greatest(a.due_date,decode(a.eff_charge_type,'LATE',a.due_date,nvl(a.last_charge_date,a.due_date))),
4091                                 a.due_date),
4092                         a.due_date) <= sched_hdrs.end_date
4093                    OR sched_hdrs.end_date IS NULL )
4094           /* Condition 4: If multiple rates need not be used, we should pick up the rate
4095              that is effective on the due date.
4096              Also note that the multiple interest rates are used only for Interest
4097              Calculation and only when rates are used*/
4098            and decode(a.multiple_interest_rates_flag,'Y',
4099                        decode(sched_hdrs.schedule_header_type,
4100                                'RATE',sched_hdrs.start_date,
4101                                a.due_date),
4102                        a.due_date)>= nvl(sched_hdrs.start_date,a.due_date)
4103             /* Make sure that this payment schedule is not part of a failed final batch */
4104              and not exists (select payment_schedule_id
4105                              from   ar_interest_lines lines,
4106                                     ar_interest_headers hdrs,
4107                                     ar_interest_batches bat
4108                              where  lines.payment_schedule_id = a.payment_schedule_id
4109                              and    lines.interest_header_id = hdrs.interest_header_id
4110                              and    hdrs.interest_batch_id = bat.interest_batch_id
4111                              and    bat.batch_status ='F'
4112                              and    bat.transferred_status <> 'S'));
4113 
4114         IF l_debug_flag = 'Y' THEN
4115             debug( 'ar_calc_late_charge.insert_int_late_pay()-' );
4116         END IF;
4117 
4118     --
4119    EXCEPTION
4120      WHEN  OTHERS THEN
4121         --IF l_debug_flag = 'Y' THEN
4122             debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
4123             debug('EXCEPTION: ar_calc_late_charge.insert_int_late_pay' );
4124         --END IF;
4125         RAISE;
4126 
4127 END insert_int_late_pay;
4128 /*=========================================================================================+
4129  | PROCEDURE insert_int_avg_daily_bal                                                      |
4130  |                                                                                         |
4131  | DESCRIPTION                                                                             |
4132  |                                                                                         |
4133  |   This procedure computes the average daily balance of the debit items and calculates   |
4134  |   Interest on this average daily balance and inserts the records into                   |
4135  |   ar_late_charge_trx_t                                                                  |
4136  |                                                                                         |
4137  | PSEUDO CODE/LOGIC                                                                       |
4138  |                                                                                         |
4139  |                                                                                         |
4140  | PARAMETERS                                                                              |
4141  |                                                                                         |
4142  |                                                                                         |
4143  | KNOWN ISSUES                                                                            |
4144  |                                                                                         |
4145  | NOTES                                                                                   |
4146  |                                                                                         |
4147  | 1. Average Daily Balance method involves three steps                                    |
4148  |    a) Determinition                                                                     |
4149  |       For determining if a customer, site and currency combination is to be charged, the|
4150  |       balance of the last bill is taken and the credit items upto the due_date plus     |
4151  |       receipt grace days is subtracted from this. If this balance is atleast the min    |
4152  |       customer balance threshold, charge will be calculated.                            |
4153  |    b) Charge computation                                                                |
4154  |       Based on the set up in post_billing_debit_items and late_charge_billing_calc_mode,|
4155  |       (in ar_system_parameters), different items and date range will be used to         |
4156  |       calculate the average daily balance                                               |
4157  |    c) Generation of the document in AR.                                                 |
4158  | 2. The following fields are not used for Average Daily Balance                          |
4159  |    a) credit_items_flag                                                                 |
4160  |    b) disputed_transaction_flag                                                         |
4161  |    c) multiple_interest_rates_flag                                                      |
4162  |    d) interest days per period                                                          |
4163  |    e) interest calculation period                                                       |
4164  |    f) hold_charged_invoices_flag                                                        |
4165  |    g) minimum invoice overdue + value                                                   |
4166  | 3. The following fields have different validation for Average Daily Balance             |
4167  |    a) Late charge type - Interest Invoices only                                         |
4168  |    b) Interest Calculation Formula - Flat only                                          |
4169  |    c) Interest Charge and Penalty Charge - can not be Charges Schedule                  |
4170  |                                                                                         |
4171  | MODIFICATION HISTORY                                                                    |
4172  | Date                  Author            Description of Changes                          |
4173  |                                                                                         |
4174  | 05-APR-2006           rkader            Created                                         |
4175  |                                                                                         |
4176  *=========================================================================================*/
4177 PROCEDURE insert_int_avg_daily_bal(p_fin_charge_date	IN	DATE,
4178                                    p_worker_number      IN      NUMBER,
4179                                    p_total_workers      IN      NUMBER) IS
4180 
4181    l_fin_charge_date	         DATE;
4182    l_worker_number               number;
4183    l_total_workers               number;
4184 
4185 BEGIN
4186 
4187     IF l_debug_flag = 'Y' THEN
4188          debug( 'ar_calc_late_charge. insert_int_avg_daily_bal()+' );
4189     END IF;
4190 
4191     l_fin_charge_date   := 	p_fin_charge_date;
4192     l_worker_number     :=      p_worker_number;
4193     l_total_workers     :=      p_total_workers;
4194 
4195    /* Insert records for the system option set up RUN DATE TO RUN DATE */
4196 
4197    insert into ar_late_charge_trx_t
4198       (late_charge_trx_id,
4199        customer_id,
4200        customer_site_use_id,
4201        currency_code,
4202        customer_trx_id,
4203        legal_entity_id,
4204        payment_schedule_id,
4205        class,
4206        amount_due_original,
4207        amount_due_remaining,
4208        fin_charge_charged,
4209        trx_date,
4210        cust_trx_type_id,
4211        last_charge_date,
4212        exchange_rate_type,
4213        min_interest_charge,
4214        max_interest_charge,
4215        overdue_late_pay_amount,
4216        original_balance,
4217        due_date,
4218        receipt_date,
4219        finance_charge_date,
4220        charge_type,
4221        actual_date_closed,
4222        interest_rate,
4223        interest_days,
4224        rate_start_date,
4225        rate_end_date,
4226        schedule_days_start,
4227        schedule_days_to,
4228        late_charge_amount,
4229        late_charge_type,
4230        late_charge_term_id,
4231        interest_period_days,
4232        interest_calculation_period,
4233        charge_on_finance_charge_flag,
4234        message_text_id,
4235        interest_type,
4236        min_fc_invoice_overdue_type,
4237        min_fc_invoice_amount,
4238        min_fc_invoice_percent,
4239        charge_line_type,
4240        org_id,
4241        request_id,
4242        display_flag )
4243    ( select ar_late_charge_trx_s.nextval,
4244           b.customer_id,
4245           b.site_use_id,
4246           b.currency_code,
4247           NULL, -- customer_trx_id
4248           NULL, -- How to determine this?
4249           -99, -- payment_schedule_id
4250           NULL, -- class, search for some look up for cons_inv
4251           NULL, -- amount_due_original
4252           NULL, -- amount_due_remaining
4253           NULL, -- fin_charge_already_charged
4254           NULL, -- trx_date
4255           NULL, --cust_trx_type is not applicable
4256           b.last_accrue_charge_date,
4257           b.exchange_rate_type,
4258           b.min_interest_charge,
4259           b.max_interest_charge,
4260           b.overdue_late_pay_amount,
4261           b.overdue_late_pay_amount, -- original balance
4262           NULL, --Due date not applicable
4263           NULL, --receipt_date
4264           l_fin_charge_date,
4265           'AVERAGE_DAILY_BALANCE',
4266           NULL,
4267           b.interest_rate,
4268           b.interest_days,
4269           NULL, -- rate start_date,
4270           NULL, -- rate end date
4271           NULL, -- bucket days start
4272           NULL, -- bucket days end
4273           b.late_charge_amount,
4274           'INV',
4275           b.late_charge_term_id,
4276           NULL, -- interest_period_days not applicable
4277           NULL, -- interest_calculation_period not applicable
4278           'F' , -- only flat rate is applicable
4279           b.message_text_id,
4280           b.interest_type,
4281           NULL, -- invoice level tolerances are not applicable (min_fc_invoice_overdue_type)
4282           NULL, -- min_fc_invoice_amount
4283           NULL, -- min_fc_invoice_percent
4284           'INTEREST',
4285           b.org_id,
4286           l_request_id,
4287           'Y'
4288   from
4289     (
4290     select
4291            a.customer_id,
4292            a.site_use_id,
4293            a.currency_code,
4294            a.last_accrue_charge_date,
4295            a.exchange_rate_type,
4296            a.min_interest_charge,
4297            a.max_interest_charge,
4298            ar_calc_late_charge.currency_round(sum(a.balance * (a.date_to - a.date_from+1))
4299                                                / sum(a.date_to - a.date_from+1),
4300                                                    a.currency_code) overdue_late_pay_amount,
4301            decode(a.interest_type,
4302                   'FIXED_RATE',a.interest_rate, NULL) interest_rate,
4303            sum(a.date_to - a.date_from+1) interest_days,
4304            decode(a.interest_type,
4305                   'FIXED_AMOUNT', a.interest_fixed_amount,
4306                   'FIXED_RATE',
4307                     ar_calc_late_charge.currency_round(nvl(
4308                                                            ((sum(a.balance * (a.date_to - a.date_from+1))/
4309                                                              sum(a.date_to - a.date_from+1))/100
4310                                                                 *a.interest_rate
4311                                                            ),
4312                                                           0), a.currency_code)) late_charge_amount,
4313            a.late_charge_term_id,
4314            a.message_text_id,
4315            a.interest_type,
4316            a.org_id,
4317            a.payment_grace_days,
4318            a.min_fc_balance_overdue_type,
4319            a.min_fc_balance_amount,
4320            a.min_fc_balance_percent
4321   from
4322   (
4323     select cons_inv.customer_id,
4324            cons_inv.site_use_id,
4325            cons_inv.currency_code,
4326            cons_inv.org_id,
4327            cons_inv.billing_date date_from,
4328            decode(sign(l_fin_charge_date -
4329                	   ar_calc_late_charge.get_next_activity_date(cons_inv.customer_id,
4330        					       	      cons_inv.site_use_id,
4331        						      cons_inv.currency_code,
4332        						      cons_inv.org_id,
4333 						      sysparam.post_billing_item_inclusion,
4334 						      cons_inv.billing_date,
4335         	                                      l_fin_charge_date)),
4336                   -1,l_fin_charge_date,
4337                    ar_calc_late_charge.get_next_activity_date(cons_inv.customer_id,
4338                                                       cons_inv.site_use_id,
4339                                                       cons_inv.currency_code,
4340                                                       cons_inv.org_id,
4341                                                       sysparam.post_billing_item_inclusion,
4342                                                       cons_inv.billing_date,
4343                                                       l_fin_charge_date)) date_to,
4344           cons_inv.ending_balance balance,
4345           cust_sites.last_accrue_charge_date,
4346           cust_sites.exchange_rate_type,
4347           cust_sites.min_interest_charge,
4348           cust_sites.max_interest_charge,
4349 	  cust_sites.interest_type,
4350 	  cust_sites.interest_rate,
4351 	  cust_sites.interest_fixed_amount,
4352           cust_sites.interest_schedule_id,
4353 	  cust_sites.late_charge_term_id,
4354 	  cust_sites.message_text_id,
4355           cust_sites.payment_grace_days,
4356           cust_sites.min_fc_balance_overdue_type,
4357           cust_sites.min_fc_balance_amount,
4358           cust_sites.min_fc_balance_percent
4359     from  ar_cons_inv cons_inv,
4360           ar_lc_cust_sites_t cust_sites,
4361 	  ar_system_parameters sysparam
4362    where cons_inv.customer_id = cust_sites.customer_id
4363    and   cons_inv.site_use_id = cust_sites.customer_site_use_id
4364    and   cons_inv.currency_code = cust_sites.currency_code
4365    and   mod(nvl(cust_sites.customer_site_use_id,0),l_total_workers) =
4366                      decode(l_total_workers,l_worker_number,0,l_worker_number)
4367    and   cons_inv.org_id = cust_sites.org_id
4368    and   cons_inv.billing_date = (select max(ci2.billing_date)
4369    	                          from   ar_cons_inv ci2
4370                 	          where  ci2.customer_id = cust_sites.customer_id
4371                         	  and    ci2.site_use_id   = cust_sites.customer_site_use_id
4372                                   and    ci2.currency_code = cust_sites.currency_code
4373                                   and    ci2.org_id = cust_sites.org_id
4374 	                          and    ci2.billing_date  <= l_fin_charge_date
4375         	                  and    ci2.status  in ('FINAL', 'ACCEPTED','IMPORTED'))
4376    and   cust_sites.late_charge_calculation_trx = 'AVG_DAILY_BALANCE'
4377    and   sysparam.org_id = cons_inv.org_id
4378    and    sysparam.late_charge_billing_calc_mode = 'RUN_TO_RUN_DATE'
4379    union
4380   select  cust_site.customer_id,
4381           cust_site.customer_site_use_id,
4382           cust_site.currency_code,
4383           cust_site.org_id,
4384           decode(cust_site.last_accrue_charge_date,
4385     	         NULL, ar_calc_late_charge.get_first_activity_date(cust_site.customer_id,
4386       		  						   cust_site.customer_site_use_id,
4387 								   cust_site.currency_code,
4388 								   cust_site.org_id),
4389                  cust_site.last_accrue_charge_date+1) date_from,
4390           decode(sign(l_fin_charge_date -
4391              	  ar_calc_late_charge.get_next_activity_date(cust_site.customer_id,
4392       						     cust_site.customer_site_use_id,
4393 						     cust_site.currency_code,
4394 						     cust_site.org_id,
4395 						     sysparam.post_billing_item_inclusion,
4396 						     decode(cust_site.last_accrue_charge_date,
4397                	                                            NULL,get_first_activity_date(cust_site.customer_id,
4398       								                         cust_site.customer_site_use_id,
4399 								 			 cust_site.currency_code,
4400 								 			 cust_site.org_id),
4401                                                             cust_site.last_accrue_charge_date+1),
4402 	                                              l_fin_charge_date)),
4403                  -1, l_fin_charge_date,
4404                   ar_calc_late_charge.get_next_activity_date(cust_site.customer_id,
4405                                                      cust_site.customer_site_use_id,
4406                                                      cust_site.currency_code,
4407                                                      cust_site.org_id,
4408                                                      sysparam.post_billing_item_inclusion,
4409                                                      decode(cust_site.last_accrue_charge_date,
4410                                                             NULL,get_first_activity_date(cust_site.customer_id,
4411                                                                                          cust_site.customer_site_use_id,                                                                                         cust_site.currency_code,
4412                                                                                          cust_site.org_id),
4413                                                             cust_site.last_accrue_charge_date+1),
4414                                                       l_fin_charge_date)) date_to,
4415      	 ar_calc_late_charge.get_cust_balance(cust_site.customer_id,
4416       		                              cust_site.customer_site_use_id,
4417 					      cust_site.currency_code,
4418 					      cust_site.org_id,
4419 					      sysparam.post_billing_item_inclusion,
4420 					      decode(cust_site.last_accrue_charge_date,
4421                				 	     NULL,get_first_activity_date(cust_site.customer_id,
4422       						 		 	 	  cust_site.customer_site_use_id,
4423 									 	  cust_site.currency_code,
4424 									 	  cust_site.org_id),
4425                                               cust_site.last_accrue_charge_date+1)) balance,
4426          cust_site.last_accrue_charge_date,
4427          cust_site.exchange_rate_type,
4428          cust_site.min_interest_charge,
4429          cust_site.max_interest_charge,
4430          cust_site.interest_type,
4431 	 cust_site.interest_rate,
4432 	 cust_site.interest_fixed_amount,
4433          cust_site.interest_schedule_id,
4434 	 cust_site.late_charge_term_id,
4435 	 cust_site.message_text_id,
4436          cust_site.payment_grace_days,
4437          cust_site.min_fc_balance_overdue_type,
4438          cust_site.min_fc_balance_amount,
4439          cust_site.min_fc_balance_percent
4440    from  ar_lc_cust_sites_t cust_site,
4441          ar_system_parameters sysparam
4442    where sysparam.org_id = cust_site.org_id
4443    and   sysparam.late_charge_billing_calc_mode = 'RUN_TO_RUN_DATE'
4444    and   cust_site.late_charge_calculation_trx = 'AVG_DAILY_BALANCE'
4445    and   mod(nvl(cust_site.customer_site_use_id,0),l_total_workers) =
4446        	              decode(l_total_workers,l_worker_number,0,l_worker_number)
4447   union
4448   /* select distinct : even if more than one item exists with the same trx_date,
4449       consider this date only once */
4450   select cust_sites.customer_id,
4451          cust_sites.customer_site_use_id,
4452          cust_sites.currency_code,
4453          cust_sites.org_id,
4454          ps.trx_date,
4455          decode(sign(l_fin_charge_date -
4456         	      ar_calc_late_charge.get_next_activity_date(ps.customer_id,
4457         					    ps.customer_site_use_id,
4458        						    ps.invoice_currency_code,
4459        						    ps.org_id,
4460 						    sysparam.post_billing_item_inclusion,
4461 						    ps.trx_date,
4462 	                                            l_fin_charge_date)),
4463                  -1, l_fin_charge_date,
4464                  ar_calc_late_charge.get_next_activity_date(ps.customer_id,
4465                                                     ps.customer_site_use_id,
4466                                                     ps.invoice_currency_code,
4467                                                     ps.org_id,
4468                                                     sysparam.post_billing_item_inclusion,
4469                                                     ps.trx_date,
4470                                                     l_fin_charge_date)) date_to,
4471       	ar_calc_late_charge.get_cust_balance(ps.customer_id,
4472        			    		     ps.customer_site_use_id,
4473         				     ps.invoice_currency_code,
4474         				     ps.org_id,
4475 					     sysparam.post_billing_item_inclusion,
4476 					     ps.trx_date) balance,
4477         cust_sites.last_accrue_charge_date,
4478         cust_sites.exchange_rate_type,
4479         cust_sites.min_interest_charge,
4480         cust_sites.max_interest_charge,
4481         cust_sites.interest_type,
4482 	cust_sites.interest_rate,
4483 	cust_sites.interest_fixed_amount,
4484         cust_sites.interest_schedule_id,
4485         cust_sites.late_charge_term_id,
4486         cust_sites.message_text_id,
4487         cust_sites.payment_grace_days,
4488         cust_sites.min_fc_balance_overdue_type,
4489         cust_sites.min_fc_balance_amount,
4490         cust_sites.min_fc_balance_percent
4491     from  ar_payment_schedules ps,
4492           ar_lc_cust_sites_t cust_sites,
4493           ar_system_parameters sysparam
4494    where  ps.customer_id = cust_sites.customer_id
4495    and    decode(ps.class,
4496 	        'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
4497 	                                                         ps.customer_site_use_id,
4498 	       	                                                 ps.org_id),
4499 	        'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
4500 	                                                          ps.customer_site_use_id,
4501 	                                                          ps.org_id),
4502         	ps.customer_site_use_id) = cust_sites.customer_site_use_id
4503    and    ps.invoice_currency_code = cust_sites.currency_code
4504    and    ps.org_id = cust_sites.org_id
4505    and    cust_sites.late_charge_calculation_trx = 'AVG_DAILY_BALANCE'
4506    and   mod(nvl(cust_sites.customer_site_use_id,0),l_total_workers) =
4507                        decode(l_total_workers,l_worker_number,0,l_worker_number)
4508    and    sysparam.org_id = cust_sites.org_id
4509    and    sysparam.late_charge_billing_calc_mode = 'RUN_TO_RUN_DATE'
4510    and    decode(sysparam.post_billing_item_inclusion,
4511                 'INCLUDE_DEBIT_ITEM','Y',
4512                 'EXCLUDE_DEBIT_ITEM',decode(ps.class,
4513                                            'PMT','Y',
4514                                            'CM','Y',
4515                                            'N'),
4516 	               'N')  = 'Y'
4517    and   ps.trx_date <= l_fin_charge_date
4518    and   ( ps.trx_date > (select max(ci2.billing_date)
4519                           from   ar_cons_inv ci2
4520                           where  ci2.customer_id = cust_sites.customer_id
4521                           and    ci2.site_use_id   = cust_sites.customer_site_use_id
4522                           and    ci2.currency_code = cust_sites.currency_code
4523                           and    ci2.org_id = cust_sites.org_id
4524                           and    ci2.billing_date  < l_fin_charge_date
4525                           and    ci2.status  in ('FINAL', 'ACCEPTED','IMPORTED'))
4526        	OR       (
4527         not exists (select ci2.billing_date
4528     	            from   ar_cons_inv ci2
4529 	            where  ci2.customer_id = cust_sites.customer_id
4530 	            and    ci2.site_use_id   = cust_sites.customer_site_use_id
4531 		    and    ci2.currency_code = cust_sites.currency_code
4532 		    and    ci2.org_id = cust_sites.org_id
4533 		    and    ci2.billing_date  < ps.trx_date
4534 		    and    ci2.status  in ('FINAL', 'ACCEPTED','IMPORTED'))
4535         and ps.trx_date >= decode(cust_sites.last_accrue_charge_date,
4536                                   NULL,get_first_activity_date(cust_sites.customer_id,
4537         	 	   	                               cust_sites.customer_site_use_id,
4538 							       cust_sites.currency_code,
4539 							       cust_sites.org_id),
4540                                               cust_sites.last_accrue_charge_date+1)))) a
4541    where nvl(a.balance,0) <> 0
4542   group by a.customer_id,
4543            a.site_use_id,
4544            a.currency_code,
4545            a.org_id,
4546            a.last_accrue_charge_date,
4547            a.exchange_rate_type,
4548            a.min_interest_charge,
4549            a.max_interest_charge,
4550 	   a.interest_type,
4551 	   a.interest_rate,
4552 	   a.interest_fixed_amount,
4553            a.interest_schedule_id,
4554 	   a.late_charge_term_id,
4555 	   a.message_text_id,
4556            a.payment_grace_days,
4557            a.min_fc_balance_overdue_type,
4558            a.min_fc_balance_amount,
4559            a.min_fc_balance_percent)b
4560     /* Apply the customer level tolerance - check for eligibility */
4561     where ar_calc_late_charge.check_adb_eligibility(b.customer_id,
4562                                                 b.site_use_id,
4563                                                 b.currency_code,
4564                                                 b.org_id,
4565                                                 b.payment_grace_days,
4566                                                 b.min_fc_balance_overdue_type,
4567                                                 b.min_fc_balance_amount,
4568                                                 b.min_fc_balance_percent,
4569                                                 l_fin_charge_date) = 'Y');
4570 
4571    /* Insert records for the system option set up DUE DATE TO RUN DATE */
4572 
4573    insert into ar_late_charge_trx_t
4574       (late_charge_trx_id,
4575        customer_id,
4576        customer_site_use_id,
4577        currency_code,
4578        customer_trx_id,
4579        legal_entity_id,
4580        payment_schedule_id,
4581        class,
4582        amount_due_original,
4583        amount_due_remaining,
4584        fin_charge_charged,
4585        trx_date,
4586        cust_trx_type_id,
4587        last_charge_date,
4588        exchange_rate_type,
4589        min_interest_charge,
4590        max_interest_charge,
4591        overdue_late_pay_amount,
4592        original_balance,
4593        due_date,
4594        receipt_date,
4595        finance_charge_date,
4596        charge_type,
4597        actual_date_closed,
4598        interest_rate,
4599        interest_days,
4600        rate_start_date,
4601        rate_end_date,
4602        schedule_days_start,
4603        schedule_days_to,
4604        late_charge_amount,
4605        late_charge_type,
4606        late_charge_term_id,
4607        interest_period_days,
4608        interest_calculation_period,
4609        charge_on_finance_charge_flag,
4610        message_text_id,
4611        interest_type,
4612        min_fc_invoice_overdue_type,
4613        min_fc_invoice_amount,
4614        min_fc_invoice_percent,
4615        charge_line_type,
4616        org_id,
4617        request_id,
4618        display_flag)
4619     (
4620     select ar_late_charge_trx_s.nextval,
4621            b.customer_id,
4622            b.site_use_id,
4623            b.currency_code,
4624            NULL, -- customer_trx_id
4625            NULL, -- How to determine this?
4626            -99, -- payment_schedule_id
4627            NULL, -- class, search for some look up for cons_inv
4628            NULL, -- amount_due_original
4629            NULL, -- amount_due_remaining
4630            NULL, -- fin_charge_already_charged
4631            NULL, -- trx_date
4632            NULL, --cust_trx_type is not applicable
4633            b.last_accrue_charge_date,
4634            b.exchange_rate_type,
4635            b.min_interest_charge,
4636            b.max_interest_charge,
4637            b.overdue_late_pay_amount,
4638            b.overdue_late_pay_amount original_balance,
4639            NULL, --Due date not applicable
4640            NULL, --receipt_date
4641            l_fin_charge_date,
4642            'AVERAGE_DAILY_BALANCE',
4643            NULL,
4644            decode(b.interest_type,
4645                   'FIXED_RATE',b.interest_rate, NULL) interest_rate,
4646            b.tot_days interest_days,
4647            NULL, -- rate start date
4648            NULL, -- rate end date
4649            NULL, -- bucket days start
4650            NULL, -- bucket days to
4651            decode(b.interest_type,
4652                   'FIXED_AMOUNT', b.interest_fixed_amount,
4653                   'FIXED_RATE',
4654                          ar_calc_late_charge.currency_round(nvl(b.overdue_late_pay_amt_org /100* b.interest_rate,0),
4655                                                             b.currency_code)) late_charge_amount,
4656            'INV'  ,
4657            b.late_charge_term_id,
4658            NULL, -- interest_period_days not applicable
4659            NULL, -- interest_calculation_period not applicable
4660            'F' , -- only flat rate is applicable
4661            b.message_text_id,
4662            b.interest_type,
4663            NULL, -- invoice level tolerances are not applicable (min_fc_invoice_overdue_type)
4664            NULL, -- min_fc_invoice_amount
4665            NULL, -- min_fc_invoice_percent
4666            'INTEREST',
4667            b.org_id,
4668            l_request_id,
4669            'Y'
4670   from (
4671    select a.customer_id,
4672           a.site_use_id,
4673           a.currency_code,
4674           a.org_id,
4675           a.last_accrue_charge_date,
4676           a.exchange_rate_type,
4677           a.min_interest_charge,
4678           a.max_interest_charge,
4679           a.interest_type,
4680           a.interest_rate,
4681           a.interest_fixed_amount,
4682           a.interest_schedule_id,
4683           a.late_charge_term_id,
4684           a.message_text_id,
4685           a.payment_grace_days,
4686           a.min_fc_balance_overdue_type,
4687           a.min_fc_balance_amount,
4688           a.min_fc_balance_percent,
4689           ar_calc_late_charge.currency_round(sum(a.balance * (a.date_to - a.date_from+1)) /
4690                                              sum(a.date_to - a.date_from+1),
4691                                              a.currency_code) overdue_late_pay_amount,
4692           sum(a.balance * (a.date_to - a.date_from+1)) /
4693                                              sum(a.date_to - a.date_from+1) overdue_late_pay_amt_org,
4694           sum(a.balance * (a.date_to - a.date_from+1)) tot_amt,
4695           sum(a.date_to - a.date_from+1) tot_days
4696   from
4697   (
4698     select cons_inv.customer_id,
4699            cons_inv.site_use_id,
4700            cons_inv.currency_code,
4701            cons_inv.org_id,
4702            cons_inv.due_date+1 date_from,
4703            decode(sign(l_fin_charge_date-
4704                                ar_calc_late_charge.get_next_activity_date(cons_inv.customer_id,
4705                                                       cons_inv.site_use_id,
4706                                                       cons_inv.currency_code,
4707                                                       cons_inv.org_id,
4708                                                       sysparam.post_billing_item_inclusion,
4709                                                       cons_inv.due_date+1,
4710                                                       l_fin_charge_date)),
4711                    -1,l_fin_charge_date,
4712                    ar_calc_late_charge.get_next_activity_date(cons_inv.customer_id,
4713                                                       cons_inv.site_use_id,
4714                                                       cons_inv.currency_code,
4715                                                       cons_inv.org_id,
4716                                                       sysparam.post_billing_item_inclusion,
4717                                                       cons_inv.due_date+1,
4718                                                       l_fin_charge_date)) date_to,
4719           ar_calc_late_charge.get_cust_balance(cons_inv.customer_id,
4720        					    cons_inv.site_use_id,
4721        					    cons_inv.currency_code,
4722        					    cons_inv.org_id,
4723 					    sysparam.post_billing_item_inclusion,
4724 					    cons_inv.due_date) balance,
4725           cust_sites.last_accrue_charge_date,
4726           cust_sites.exchange_rate_type,
4727           cust_sites.min_interest_charge,
4728           cust_sites.max_interest_charge,
4729           cust_sites.interest_type,
4730           cust_sites.interest_rate,
4731           cust_sites.interest_fixed_amount,
4732           cust_sites.interest_schedule_id,
4733           cust_sites.late_charge_term_id,
4734           cust_sites.message_text_id,
4735           cust_sites.payment_grace_days,
4736           cust_sites.min_fc_balance_overdue_type,
4737           cust_sites.min_fc_balance_amount,
4738           cust_sites.min_fc_balance_percent
4739     from  ar_cons_inv cons_inv,
4740           ar_lc_cust_sites_t cust_sites,
4741           ar_system_parameters sysparam
4742    where cons_inv.customer_id = cust_sites.customer_id
4743    and   cons_inv.site_use_id = cust_sites.customer_site_use_id
4744    and   cons_inv.currency_code = cust_sites.currency_code
4745    and   mod(nvl(cust_sites.customer_site_use_id,0),l_total_workers) =
4746                      decode(l_total_workers,l_worker_number,0,l_worker_number)
4747    and   cons_inv.org_id = cust_sites.org_id
4748    and   cons_inv.billing_date = (select max(ci2.billing_date)
4749                                   from   ar_cons_inv ci2
4750                                   where  ci2.customer_id = cust_sites.customer_id
4751                                   and    ci2.site_use_id   = cust_sites.customer_site_use_id
4752                                   and    ci2.currency_code = cust_sites.currency_code
4753                                   and    ci2.org_id = cust_sites.org_id
4754                                   and    ci2.billing_date  <= l_fin_charge_date
4755                                   and    ci2.status  in ('FINAL', 'ACCEPTED','IMPORTED'))
4756    and   cust_sites.late_charge_calculation_trx = 'AVG_DAILY_BALANCE'
4757    and   sysparam.org_id = cons_inv.org_id
4758    and    sysparam.late_charge_billing_calc_mode = 'DUE_TO_RUN_DATE'
4759   union
4760   /* select distinct : even if more than one item exists with the same trx_date,
4761       consider this date only once */
4762   select cust_sites.customer_id,
4763          cust_sites.customer_site_use_id,
4764          cust_sites.currency_code,
4765          cust_sites.org_id,
4766          ps.trx_date,
4767          decode(sign(l_fin_charge_date -
4768                         ar_calc_late_charge.get_next_activity_date(ps.customer_id,
4769                                                     ps.customer_site_use_id,
4770                                                     ps.invoice_currency_code,
4771                                                     ps.org_id,
4772                                                     sysparam.post_billing_item_inclusion,
4773                                                     ps.trx_date,
4774                                                     l_fin_charge_date)),
4775                   -1, l_fin_charge_date,
4776                   ar_calc_late_charge.get_next_activity_date(ps.customer_id,
4777                                                     ps.customer_site_use_id,
4778                                                     ps.invoice_currency_code,
4779                                                     ps.org_id,
4780                                                     sysparam.post_billing_item_inclusion,
4781                                                     ps.trx_date,
4782                                                     l_fin_charge_date)) date_to,
4783         ar_calc_late_charge.get_cust_balance(ps.customer_id,
4784                                              ps.customer_site_use_id,
4785                                              ps.invoice_currency_code,
4786                                              ps.org_id,
4787                                              sysparam.post_billing_item_inclusion,
4788                                              ps.trx_date) balance,
4789         cust_sites.last_accrue_charge_date,
4790         cust_sites.exchange_rate_type,
4791         cust_sites.min_interest_charge,
4792         cust_sites.max_interest_charge,
4793         cust_sites.interest_type,
4794         cust_sites.interest_rate,
4795         cust_sites.interest_fixed_amount,
4796         cust_sites.interest_schedule_id,
4797         cust_sites.late_charge_term_id,
4798         cust_sites.message_text_id,
4799         cust_sites.payment_grace_days,
4800         cust_sites.min_fc_balance_overdue_type,
4801         cust_sites.min_fc_balance_amount,
4802         cust_sites.min_fc_balance_percent
4803     from  ar_payment_schedules ps,
4804           ar_lc_cust_sites_t cust_sites,
4805           ar_system_parameters sysparam
4806    where  ps.customer_id = cust_sites.customer_id
4807    and    decode(ps.class,
4808                 'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
4809                                                                  ps.customer_site_use_id,
4810                                                                  ps.org_id),
4811                 'PMT',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
4812                                                                   ps.customer_site_use_id,
4813                                                                   ps.org_id),
4814                 ps.customer_site_use_id) = cust_sites.customer_site_use_id
4815    and    ps.invoice_currency_code = cust_sites.currency_code
4816    and    ps.org_id = cust_sites.org_id
4817    and    cust_sites.late_charge_calculation_trx = 'AVG_DAILY_BALANCE'
4818    and   mod(nvl(cust_sites.customer_site_use_id,0),l_total_workers) =
4819                        decode(l_total_workers,l_worker_number,0,l_worker_number)
4820    and    sysparam.org_id = cust_sites.org_id
4821    and    sysparam.late_charge_billing_calc_mode = 'DUE_TO_RUN_DATE'
4822    and    decode(sysparam.post_billing_item_inclusion,
4823                 'INCLUDE_DEBIT_ITEM','Y',
4824                 'EXCLUDE_DEBIT_ITEM',decode(ps.class,
4825                                            'PMT','Y',
4826                                            'CM','Y',
4827                                            'N'),
4828                        'N')  = 'Y'
4829    and   ps.trx_date <= l_fin_charge_date
4830    and   ps.trx_date > (select max(ci2.due_date)
4831                           from   ar_cons_inv ci2
4832                           where  ci2.customer_id = cust_sites.customer_id
4833                           and    ci2.site_use_id   = cust_sites.customer_site_use_id
4834                           and    ci2.currency_code = cust_sites.currency_code
4835                           and    ci2.org_id = cust_sites.org_id
4836                           and    ci2.billing_date  < l_fin_charge_date
4837                           and    ci2.status  in ('FINAL', 'ACCEPTED','IMPORTED')))a
4838    where nvl(a.balance,0) <> 0
4839   /* Apply the customer level tolerance - check for eligibility */
4840   and ar_calc_late_charge.check_adb_eligibility(a.customer_id,
4841                                                 a.site_use_id,
4842                                                 a.currency_code,
4843                                                 a.org_id,
4844                                                 a.payment_grace_days,
4845                                                 a.min_fc_balance_overdue_type,
4846                                                 a.min_fc_balance_amount,
4847                                                 a.min_fc_balance_percent,
4848                                                 l_fin_charge_date) = 'Y'
4849   group by a.customer_id,
4850            a.site_use_id,
4851            a.currency_code,
4852            a.org_id,
4853            a.last_accrue_charge_date,
4854            a.exchange_rate_type,
4855            a.min_interest_charge,
4856            a.max_interest_charge,
4857            a.interest_type,
4858            a.interest_rate,
4859            a.interest_fixed_amount,
4860            a.interest_schedule_id,
4861            a.late_charge_term_id,
4862            a.message_text_id,
4863            a.payment_grace_days,
4864            a.min_fc_balance_overdue_type,
4865            a.min_fc_balance_amount,
4866            a.min_fc_balance_percent) b
4867       /* Make sure that this customer, site and currency combination is not
4868          part of a failed final batch */
4869       where not exists (select 'exists failed batch'
4870                       from   ar_interest_headers hdr,
4871                              ar_interest_batches bat
4872                       where  hdr.customer_id = b.customer_id
4873                       and    hdr.customer_site_use_id = b.site_use_id
4874                       and    hdr.currency_code = b.currency_code
4875                       and    hdr.interest_batch_id = bat.interest_batch_id
4876                       and    bat.batch_status ='F'
4877                       and    bat.transferred_status <> 'S'));
4878 
4879       IF l_debug_flag = 'Y' THEN
4880           debug( 'ar_calc_late_charge. insert_int_avg_daily_bal()-' );
4881       END IF;
4882     --
4883    EXCEPTION
4884       WHEN  OTHERS THEN
4885           --IF l_debug_flag = 'Y' THEN
4886               debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
4887               debug('EXCEPTION: ar_calc_late_charge. insert_int_avg_daily_bal' );
4888           --END IF;
4889           RAISE;
4890 
4891 END insert_int_avg_daily_bal;
4892 
4893 PROCEDURE insert_cust_balances(p_as_of_date	IN 	DATE,
4894 			       p_worker_number  IN      NUMBER,
4895                                p_total_workers  IN      NUMBER) IS
4896 BEGIN
4897       IF l_debug_flag = 'Y' THEN
4898           debug( 'ar_calc_late_charge.insert_cust_balances()+');
4899       END IF;
4900           INSERT INTO ar_late_charge_cust_balance_gt
4901                 (late_charge_cust_sites_id,
4902                  customer_id,
4903                  customer_site_use_id,
4904                  currency_code,
4905                  customer_open_balance,
4906                  customer_overdue_balance,
4907                  org_id)
4908           (SELECT a.lc_cust_sites_id,
4909                  a.customer_id,
4910                  a.customer_site_use_id,
4911                  a.currency_code,
4912                  sum(open_bal) open_balance,
4913                  sum(overdue_bal) overdue_balance,
4914                  org_id
4915           FROM
4916              (SELECT /*+ cardinality(cust_site,1) leading(cust_site ps) use_nl(cust_site ps) index(ps AR_PAYMENT_SCHEDULES_N6) */
4917                      cust_site.lc_cust_sites_id,
4918                      ps.customer_id,
4919                      cust_site.customer_site_use_id,
4920                      ps.invoice_currency_code currency_code,
4921                      sum(ps.amount_due_remaining) open_bal,
4922                      sum((case when (decode(ps.class,'CM',ps.due_date,ps.due_date + NVL(cust_site.payment_grace_days,0))) < p_as_of_date then 1 else 0 end)
4923                           * ps.amount_due_remaining) overdue_bal,
4924                      ps.org_id
4925                FROM  ar_payment_schedules_all ps,
4926                      ar_lc_cust_sites_t cust_site,
4927                      ra_customer_trx ct,
4928                      ra_cust_trx_types typ
4929                WHERE ps.customer_id = cust_site.customer_id
4930                AND   ps.customer_trx_id = ct.customer_trx_id  --Bug12884574
4931                AND   ct.cust_trx_type_id = typ.cust_trx_type_id  --Bug12884574
4932 	       AND   ct.org_id = typ.org_id  --Bug12884574
4933                AND DECODE(nvl(typ.exclude_from_late_charges, 'N'), 'Y', 'X','N', decode(nvl(ct.FINANCE_CHARGES,'Y'), 'Y','Y','N','X')) = 'Y'  --Bug12884574
4934                AND   cust_site.customer_site_use_id = decode(ps.class,
4935                                                        'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
4936                                                                                               ps.customer_site_use_id,
4937 											      ps.org_id),
4938                                                        ps.customer_site_use_id)
4939                AND   ps.invoice_currency_code = cust_site.currency_code
4940                AND   mod(nvl(cust_site.customer_site_use_id,0),p_total_workers) =
4941                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
4942                AND   ps.org_id = cust_site.org_id
4943                AND   ps.payment_schedule_id+0 > 0
4944                AND   ps.actual_date_closed  >= p_as_of_date
4945                AND   ps.class IN ('CB', 'CM','DEP','DM','GUAR','INV','BR')
4946                AND   ps.trx_date  <= p_as_of_date
4947                GROUP BY cust_site.lc_cust_sites_id,
4948                       ps.customer_id,
4949                       cust_site.customer_site_use_id,
4950                       ps.invoice_currency_code,
4951                       ps.org_id
4952                UNION ALL
4953                SELECT cust_site.lc_cust_sites_id,
4954                       ps.customer_id,
4955                       cust_site.customer_site_use_id,
4956                       ps.invoice_currency_code currency_code,
4957                      sum(ra.amount_applied  + NVL(ra.earned_discount_taken,0)
4958                               + NVL(ra.unearned_discount_taken,0))open_bal,
4959                      sum((case when ps.due_date + NVL(cust_site.payment_grace_days,0) < p_as_of_date then 1 else 0 end)
4960                             * (ra.amount_applied  + NVL(ra.earned_discount_taken,0)
4961                               + NVL(ra.unearned_discount_taken,0))) overdue_bal,
4962                      ps.org_id
4963                FROM  ar_payment_schedules ps,
4964                      ar_receivable_applications ra,
4965                      ar_payment_schedules ps_cm_cr,
4966                      ar_lc_cust_sites_t cust_site,
4967                      ra_customer_trx ct,
4968                      ra_cust_trx_types typ
4969                WHERE ps.customer_id = cust_site.customer_id
4970                AND   ct.customer_trx_id = ps.customer_trx_id  --Bug12884574
4971                AND   ct.cust_trx_type_id = typ.cust_trx_type_id  --Bug12884574
4972 	       AND   ct.org_id = typ.org_id  --Bug12884574
4973                AND DECODE(nvl(typ.exclude_from_late_charges, 'N'), 'Y', 'X','N', decode(nvl(ct.FINANCE_CHARGES,'Y'), 'Y','Y','N','X')) = 'Y'  --Bug12884574
4974                AND   cust_site.customer_site_use_id = decode(ps.class,
4975                                                        'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
4976                                                                                               ps.customer_site_use_id,
4977 											      ps.org_id),
4978                                                          ps.customer_site_use_id)
4979                AND   ps.invoice_currency_code = cust_site.currency_code
4980                AND   mod(nvl(cust_site.customer_site_use_id,0),p_total_workers) =
4981                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
4982                AND   ps.org_id = cust_site.org_id
4983                AND   ra.applied_payment_schedule_id = ps.payment_schedule_id
4984                AND   ps.actual_date_closed  < p_as_of_date
4985                AND   ps.actual_date_closed >= nvl(cust_site.last_accrue_charge_date,ps.actual_date_closed)
4986                AND   ps.actual_date_closed > ps.due_date + nvl(cust_site.payment_grace_days,0)
4987                AND   nvl(ps.actual_date_closed,p_As_of_Date) between nvl(ps.last_charge_date,p_as_of_date) and p_as_of_date
4988 			   /*bug 14202135, replaced this  */
4989 			   /*nvl(ps.last_charge_date,p_As_of_Date) between nvl(cust_site.last_accrue_charge_date,p_as_of_date) and p_as_of_date*/
4990                AND   ps.class IN ('CB','DEP','DM','GUAR','INV','BR')
4991                AND   ra.status = 'APP'
4992                AND   ps.trx_date <=ps.due_date
4993                AND   NVL(ra.confirmed_flag,'Y') = 'Y'
4994                AND   ps_cm_cr.payment_schedule_id = ra.payment_schedule_id
4995                AND   ps_cm_cr.trx_date > ps.due_date
4996 	       AND   cust_site.late_charge_calculation_trx <> 'OVERDUE'
4997                GROUP BY cust_site.lc_cust_sites_id, ps.customer_id, cust_site.customer_site_use_id, ps.invoice_currency_code, ps.org_id
4998                UNION ALL
4999                SELECT cust_site.lc_cust_sites_id,
5000                       ps.customer_id,
5001                       cust_site.customer_site_use_id,
5002                       ps.invoice_currency_code currency_code,
5003                      sum(ra.amount_applied  + NVL(ra.earned_discount_taken,0)
5004                               + NVL(ra.unearned_discount_taken,0))open_bal,
5005                      sum((case when ps.due_date + NVL(cust_site.payment_grace_days,0) < p_as_of_date then 1 else 0 end)
5006                             * (ra.amount_applied  + NVL(ra.earned_discount_taken,0)
5007                               + NVL(ra.unearned_discount_taken,0))) overdue_bal,
5008                      ps.org_id
5009                FROM  ar_payment_schedules ps,
5010                      ar_receivable_applications ra,
5011                      ar_payment_schedules ps_cm_cr,
5012                      ar_lc_cust_sites_t cust_site,
5013                     ra_customer_trx ct,
5014                      ra_cust_trx_types typ
5015                WHERE ps.customer_id = cust_site.customer_id
5016                AND   ct.customer_trx_id = ps.customer_trx_id  --Bug12884574
5017                AND   ct.cust_trx_type_id = typ.cust_trx_type_id  --Bug12884574
5018 	       AND   ct.org_id = typ.org_id  --Bug12884574
5019                AND DECODE(nvl(typ.exclude_from_late_charges, 'N'), 'Y', 'X','N', decode(nvl(ct.FINANCE_CHARGES,'Y'), 'Y','Y','N','X')) = 'Y'  --Bug12884574
5020                AND   cust_site.customer_site_use_id = decode(ps.class,
5021                                                        'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
5022                                                                                               ps.customer_site_use_id,
5023 											      ps.org_id),
5024                                                          ps.customer_site_use_id)
5025                AND   ps.invoice_currency_code = cust_site.currency_code
5026                AND   mod(nvl(cust_site.customer_site_use_id,0),p_total_workers) =
5027                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
5028                AND   ps.org_id = cust_site.org_id
5029                AND   ra.applied_payment_schedule_id = ps.payment_schedule_id
5030                AND   ps.actual_date_closed  >= p_as_of_date
5031                AND   ps.class IN ('CB', 'CM','DEP','DM','GUAR','INV','BR')
5032                AND   ra.status = 'APP'
5033                AND   ps.trx_date <= p_as_of_date
5034                AND   NVL(ra.confirmed_flag,'Y') = 'Y'
5035                AND   ps_cm_cr.payment_schedule_id = ra.payment_schedule_id
5036                AND   ps_cm_cr.trx_date > p_as_of_date
5037                GROUP BY cust_site.lc_cust_sites_id,
5038                       ps.customer_id,
5039                       cust_site.customer_site_use_id,
5040                       ps.invoice_currency_code,
5041                       ps.org_id
5042                UNION ALL
5043                SELECT cust_site.lc_cust_sites_id,
5044                       ps.customer_id,
5045                       cust_site.customer_site_use_id,
5046                       ps.invoice_currency_code currency_code,
5047                      sum(-1*(ra.amount_applied  + NVL(ra.earned_discount_taken,0)
5048                               + NVL(ra.unearned_discount_taken,0))) open_bal,
5049                      sum (-1*(case when ps.due_date < p_as_of_date then 1 else 0 end)
5050                            *(ra.amount_applied  + NVL(ra.earned_discount_taken,0)
5051                               + NVL(ra.unearned_discount_taken,0))) overdue_bal,
5052                      ps.org_id
5053                FROM  ar_payment_schedules ps,
5054                      ar_receivable_applications ra,
5055                      ar_lc_cust_sites_t cust_site,
5056                      ra_customer_trx ct,
5057                      ra_cust_trx_types typ
5058                WHERE ps.customer_id = cust_site.customer_id
5059                AND   ct.customer_trx_id = ps.customer_trx_id  --Bug12884574
5060                AND   ct.cust_trx_type_id = typ.cust_trx_type_id  --Bug12884574
5061 	       AND   ct.org_id = typ.org_id  --Bug12884574
5062                AND DECODE(nvl(typ.exclude_from_late_charges, 'N'), 'Y', 'X','N', decode(nvl(ct.FINANCE_CHARGES,'Y'), 'Y','Y','N','X')) = 'Y'  --Bug12884574
5063                AND   cust_site.customer_site_use_id = decode(ps.class,
5064                                                         'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
5065                                                                                               ps.customer_site_use_id,
5066 											      ps.org_id),
5067                                                          ps.customer_site_use_id)
5068                AND   ps.invoice_currency_code = cust_site.currency_code
5069                AND   mod(nvl(cust_site.customer_site_use_id,0),p_total_workers) =
5070                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
5071                AND   ps.org_id = cust_site.org_id
5072                AND   ra.payment_schedule_id = ps.payment_schedule_id
5073                AND   ps.payment_schedule_id+0 > 0
5074                AND   ps.actual_date_closed  >= p_as_of_date
5075                AND   ps.class  = 'CM'
5076                AND   ra.apply_date > p_as_of_date
5077                AND   ra.status = 'APP'
5078                AND   ra.application_type = 'CM'
5079                AND   ps.trx_date <= p_as_of_date
5080                AND   NVL(ra.confirmed_flag,'Y') = 'Y'
5081                GROUP BY cust_site.lc_cust_sites_id,
5082                       ps.customer_id,
5083                       cust_site.customer_site_use_id,
5084                       ps.invoice_currency_code,
5085 	 	      ps.org_id
5086                UNION ALL
5087                SELECT cust_site.lc_cust_sites_id,
5088                       ps.customer_id,
5089                       cust_site.customer_site_use_id,
5090                       ps.invoice_currency_code currency_code,
5091                       sum(-1 *adj.amount) open_bal,
5092                   sum(-1*(case when (decode(ps.class,'CM',ps.due_date,ps.due_date + NVL(cust_site.payment_grace_days,0))) < p_as_of_date then 1 else 0 end)
5093                            *(adj.amount)) overdue_bal,
5094                       ps.org_id
5095                FROM  ar_adjustments adj ,
5096                      ar_payment_schedules ps,
5097                      ar_lc_cust_sites_t cust_site,
5098                      ra_customer_trx ct,
5099                      ra_cust_trx_types typ
5100                WHERE ps.customer_id = cust_site.customer_id
5101                AND   ct.customer_trx_id = ps.customer_trx_id  --Bug12884574
5102                AND   ct.cust_trx_type_id = typ.cust_trx_type_id  --Bug12884574
5103 	       AND   ct.org_id = typ.org_id  --Bug12884574
5104                AND DECODE(nvl(typ.exclude_from_late_charges, 'N'), 'Y', 'X','N', decode(nvl(ct.FINANCE_CHARGES,'Y'), 'Y','Y','N','X')) = 'Y'  --Bug12884574
5105                AND   cust_site.customer_site_use_id = decode(ps.class,
5106                                                         'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
5107                                                                                               ps.customer_site_use_id,
5108 											      ps.org_id),
5109                                                          ps.customer_site_use_id)
5110                AND   mod(nvl(cust_site.customer_site_use_id,0),p_total_workers) =
5111                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
5112                AND   ps.org_id = cust_site.org_id
5113                AND   ps.payment_schedule_id + 0 > 0
5114                AND   ps.actual_date_closed  >= p_as_of_date
5115                AND   ps.class IN ('CB', 'CM','DEP','DM','GUAR','INV','BR')
5116                AND   ps.trx_date  <= p_as_of_date
5117                AND   adj.payment_schedule_id = ps.payment_schedule_id
5118                AND   adj.apply_date > p_as_of_date
5119                AND   adj.status = 'A'
5120                GROUP BY cust_site.lc_cust_sites_id,
5121                       ps.customer_id,
5122                       cust_site.customer_site_use_id,
5123                       ps.invoice_currency_code,
5124 		      ps.org_id
5125                UNION ALL
5126                /* Unapplied Receipts
5127                   For receipts, consider the trx_date instead of the due_date*/
5128                SELECT cust_site.lc_cust_sites_id,
5129                       ps.customer_id,
5130                       cust_site.customer_site_use_id,
5131                       ps.invoice_currency_code currency_code,
5132                       sum(ps.amount_due_remaining) open_bal,
5133                       sum(ps.amount_due_remaining) overdue_bal,
5134                       ps.org_id
5135                FROM  ar_payment_schedules ps,
5136                      ar_lc_cust_sites_t cust_site
5137                WHERE ps.customer_id = cust_site.customer_id
5138                AND   cust_site.customer_site_use_id = ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
5139                                                                                                 ps.customer_site_use_id,
5140 												ps.org_id)
5141                AND   ps.invoice_currency_code = cust_site.currency_code
5142                AND   mod(nvl(cust_site.customer_site_use_id,0),p_total_workers) =
5143                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
5144 	       AND   ps.org_id = cust_site.org_id
5145                AND   ps.class = 'PMT'
5146                AND   ps.actual_date_closed >= p_as_of_date
5147                AND   nvl( ps.receipt_confirmed_flag, 'Y' ) = 'Y'
5148                AND   ps.trx_date  <= p_as_of_date
5149                GROUP BY cust_site.lc_cust_sites_id,
5150                       ps.customer_id,
5151                       cust_site.customer_site_use_id,
5152                       ps.invoice_currency_code,
5153                       ps.org_id
5154                UNION ALL
5155                /* Cancelled BR */
5156                SELECT cust_site.lc_cust_sites_id,
5157                       ps.customer_id,
5158                       cust_site.customer_site_use_id,
5159                       ps.invoice_currency_code currency_code,
5160                       sum(decode(nvl(ard.amount_cr,0), 0, nvl(ard.amount_dr,0),
5161                                            (ard.amount_cr * -1)))open_bal,
5162                       sum((case when ps.trx_date < p_as_of_date then 1 else 0 end)
5163                                  *(decode(nvl(ard.amount_cr,0), 0, nvl(ard.amount_dr,0),
5164                                      (ard.amount_cr * -1)))) overdue_bal,
5165                       ps.org_id
5166                  FROM ar_payment_schedules ps,
5167                       ar_distributions ard,
5168                       ar_transaction_history ath,
5169                       ra_customer_trx_lines lines,
5170                      ar_lc_cust_sites_t cust_site,
5171                       ra_customer_trx ct,
5172                       ra_cust_trx_types typ
5173                WHERE ps.customer_id = cust_site.customer_id
5174                AND   ps.customer_trx_id = ct.customer_trx_id  --Bug12884574
5175                AND   ct.cust_trx_type_id = typ.cust_trx_type_id  --Bug12884574
5176 	       AND   ct.org_id = typ.org_id  --Bug12884574
5177                AND DECODE(nvl(typ.exclude_from_late_charges, 'N'), 'Y', 'X','N', decode(nvl(ct.FINANCE_CHARGES,'Y'), 'Y','Y','N','X')) = 'Y'  --Bug12884574
5178                AND   cust_site.customer_site_use_id = decode(ps.class,
5179                                                          'BR',ar_calc_late_charge.get_bill_to_site_use_id(ps.customer_id,
5180                                                                                               ps.customer_site_use_id,
5181 											      ps.org_id),
5182                                                          ps.customer_site_use_id)
5183                AND   ps.invoice_currency_code = cust_site.currency_code
5184                AND   mod(nvl(cust_site.customer_site_use_id,0),p_total_workers) =
5185                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
5186                AND   ps.org_id = cust_site.org_id
5187                AND   ps.payment_schedule_id+0 > 0
5188                AND   ps.actual_date_closed  >= p_as_of_date
5189                AND   ps.class IN ( 'BR','CB', 'CM','DEP','DM','GUAR','INV')
5190                AND   ath.trx_date > p_as_of_date
5191                AND   ath.event = 'CANCELLED'
5192                AND   ps.trx_date <= p_as_of_date
5193                AND   ps.customer_trx_id = ath.customer_trx_id
5194                AND   ard.source_table = 'TH'
5195                AND   ard.source_id = ath.transaction_history_id
5196                AND   ps.customer_trx_id = lines.customer_trx_id
5197                AND   ard.source_id_secondary = lines.customer_trx_line_id
5198                GROUP BY cust_site.lc_cust_sites_id,
5199                       ps.customer_id,
5200                       cust_site.customer_site_use_id,
5201                       ps.invoice_currency_code,
5202                       ps.org_id) a
5203         GROUP BY a.lc_cust_sites_id,
5204                  a.customer_id,
5205                  a.customer_site_use_id,
5206                  a.currency_code,
5207                  a.org_id);
5208       IF l_debug_flag = 'Y' THEN
5209           debug( 'ar_calc_late_charge.insert_cust_balances()-');
5210       END IF;
5211 
5212    EXCEPTION
5213       WHEN  OTHERS THEN
5214           --IF l_debug_flag = 'Y' THEN
5215               debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
5216               debug('EXCEPTION: ar_calc_late_charge.insert_cust_balances' );
5217           --END IF;
5218           RAISE;
5219 
5220 
5221 END insert_cust_balances;
5222 
5223 
5224 /*=========================================================================================+
5225  | PROCEDURE insert_penalty_lines                                                          |
5226  |                                                                                         |
5227  | DESCRIPTION                                                                             |
5228  |                                                                                         |
5229  |   This procedure calculates the penalty against a payment schedule by adding the        |
5230  |   all the interest charged against it. The penalty is either a fixed amount or a        |
5231  |   percentage of the interest charge. The calculated Penalty is inserted back into       |
5232  |   ar_late_charge_trx_t                                                                  |
5233  |                                                                                         |
5234  | PSEUDO CODE/LOGIC                                                                       |
5235  |                                                                                         |
5236  |                                                                                         |
5237  | PARAMETERS                                                                              |
5238  |                                                                                         |
5239  |                                                                                         |
5240  | KNOWN ISSUES                                                                            |
5241  |                                                                                         |
5242  | NOTES                                                                                   |
5243  |                                                                                         |
5244  |  Since we are storing the balance as of the receipt date in the Original balance column |
5245  |  in ar_late_charge_trx_t (in the case of LATE payments) , this column is not inserted   |
5246  |  for  PENALTY lines. The receipt_date is also inserted as NULL as there can be multiple |
5247  |  receipts against one payment schedule, but only one penalty line                       |
5248  |                                                                                         |
5249  | MODIFICATION HISTORY                                                                    |
5250  | Date                  Author            Description of Changes                          |
5251  |                                                                                         |
5252  | 20-FEB-2006           rkader            Created                                         |
5253  |                                                                                         |
5254  *=========================================================================================*/
5255 PROCEDURE insert_penalty_lines(p_worker_number             IN      NUMBER,
5256                                p_total_workers             IN      NUMBER) IS
5257 
5258 BEGIN
5259 
5260       IF l_debug_flag = 'Y' THEN
5261          debug( 'ar_calc_late_charge.insert_penalty_lines()+' );
5262       END IF;
5263 
5264       insert into ar_late_charge_trx_t
5265            ( late_charge_trx_id,
5266              customer_id,
5267              customer_site_use_id,
5268              currency_code,
5269              customer_trx_id,
5270              legal_entity_id,
5271              payment_schedule_id,
5272              class,
5273              amount_due_original,
5274              amount_due_remaining,
5275              fin_charge_charged,
5276              trx_date,
5277              cust_trx_type_id,
5278              last_charge_date,
5279              exchange_rate_type,
5280              min_interest_charge,
5281              max_interest_charge,
5282              overdue_late_pay_amount,
5283              original_balance,
5284              due_date,
5285              receipt_date,
5286              finance_charge_date,
5287              charge_type,
5288              actual_date_closed,
5289              interest_rate,
5290              interest_days,
5291              rate_start_date,
5292              rate_end_date,
5293              schedule_days_start,
5294              schedule_days_to,
5295              late_charge_amount,
5296              late_charge_type,
5297              late_charge_term_id,
5298              interest_period_days,
5299              interest_calculation_period,
5300              charge_on_finance_charge_flag,
5301              message_text_id,
5302              interest_type,
5303              charge_line_type,
5304 	     org_id,
5305 	     request_id,
5306              display_flag)
5307      (select ar_late_charge_trx_s.nextval,
5308              a.customer_id,
5309              a.customer_site_use_id,
5310              a.currency_code,
5311              a.customer_trx_id,
5312              a.legal_entity_id,
5313              a.payment_schedule_id,
5314              a.class,
5315              a.amount_due_original,
5316              a.amount_due_remaining,
5317              a.fin_charge_charged,
5318              a.trx_date,
5319              a.cust_trx_type_id,
5320              a.last_charge_date,
5321              a.exchange_rate_type,
5322              a.min_interest_charge,
5323              a.max_interest_charge,
5324              a.interest,
5325              a.original_balance,
5326              a.due_date,
5327              a.receipt_date,
5328              a.finance_charge_date,
5329              decode(a.charge_type,
5330                     'AVERAGE_DAILY_BALANCE', a.charge_type,
5331                     'PENALTY') charge_type,
5332              a.actual_date_closed,
5333              a.penalty_rate,
5334              decode(a.charge_type,
5335                     'AVERAGE_DAILY_BALANCE',a.interest_days,
5336                     (a.finance_charge_date - nvl(a.last_charge_date, a.due_date))) interest_days,
5337              a.rate_start_date,
5338              a.rate_end_date,
5339              a.schedule_days_start,
5340              a.schedule_days_to,
5341              NVL(a.penalty_amount,ar_calc_late_charge.currency_round(nvl(a.penalty_rate,0) * a.interest/100,
5342                                                                     a.currency_code)),
5343              a.late_charge_type,
5344              a.late_charge_term_id,
5345              a.interest_period_days,
5346              a.interest_calculation_period,
5347              a.charge_on_finance_charge_flag,
5348              a.message_text_id,
5349              a.penalty_type,
5350              'PENALTY',
5351 	     a.org_id,
5352 	     l_request_id,
5353              'Y'
5354   from
5355      (select trx.customer_id,
5356              trx.customer_site_use_id,
5357              trx.currency_code,
5358              trx.customer_trx_id,
5359              trx.legal_entity_id,
5360              trx.payment_schedule_id,
5361              trx.class,
5362              trx.amount_due_original,
5363              trx.amount_due_remaining,
5364              trx.fin_charge_charged,
5365              trx.trx_date,
5366              trx.cust_trx_type_id,
5367              trx.last_charge_date,
5368              trx.exchange_rate_type,
5369              trx.min_interest_charge,
5370              trx.max_interest_charge,
5371              sum(trx.late_charge_amount) interest,
5372              NULL original_balance,
5373              trx.due_date,
5374              NULL receipt_date,
5375              trx.finance_charge_date,
5376              trx.actual_date_closed,
5377              decode(cust_site.penalty_type, 'CHARGES_SCHEDULE', sched_lines.rate,
5378                                              'FIXED_RATE', cust_site.penalty_rate,
5379                                               NULL) penalty_rate,
5380              sched_hdrs.start_date rate_start_date,
5381              sched_hdrs.end_date rate_end_date ,
5382              bucket_lines.days_start schedule_days_start,
5383              bucket_lines.days_to  schedule_days_to,
5384              decode(cust_site.penalty_type,
5385                       'FIXED_AMOUNT',decode(trx.class,
5386                                             'CM',-1 * cust_site.penalty_fixed_amount,
5387                                             'PMT', -1*cust_site.penalty_fixed_amount,
5388                                             cust_site.penalty_fixed_amount),
5389                       'CHARGES_SCHEDULE',decode(sched_hdrs.schedule_header_type,
5390                                                 'AMOUNT',decode(trx.class,
5391                                                                'CM', -1*sched_lines.amount,
5392                                                                'PMT',-1*sched_lines.amount,
5393                                                                sched_lines.amount),
5394                                                 NULL),
5395                       'CHARGE_PER_TIER',decode(sched_hdrs.schedule_header_type,
5396                                                 'AMOUNT',decode(trx.class,
5397                                                                'CM', -1*sched_lines.amount,
5398                                                                'PMT',-1*sched_lines.amount,
5399                                                                sched_lines.amount),
5400                                                 NULL),  /*Enhacement 6469663*/
5401                       NULL) penalty_amount,
5402              trx.late_charge_type,
5403              trx.late_charge_term_id,
5404              trx.interest_period_days,
5405              trx.interest_calculation_period,
5406              trx.charge_on_finance_charge_flag,
5407              trx.message_text_id,
5408 	     trx.org_id,
5409              decode(trx.charge_type,'AVERAGE_DAILY_BALANCE',trx.interest_days,1) interest_days,
5410              decode(trx.charge_type,'AVERAGE_DAILY_BALANCE',trx.charge_type, NULL) charge_type,
5411              cust_site.penalty_type
5412      from    ar_lc_cust_sites_t cust_site,
5413              ar_late_charge_trx_t trx,
5414              ar_charge_schedule_hdrs sched_hdrs,
5415              ar_charge_schedule_lines sched_lines,
5416              ar_aging_bucket_lines bucket_lines
5417      where   cust_site.customer_id = trx.customer_id
5418       and    cust_site.customer_site_use_id = trx.customer_site_use_id
5419       and    cust_site.currency_code = trx.currency_code
5420       and    mod(nvl(cust_site.customer_site_use_id,0),p_total_workers) =
5421                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
5422       and    cust_site.org_id = trx.org_id
5423       and    cust_site.penalty_schedule_id = sched_hdrs.schedule_id(+)
5424       and    sched_hdrs.schedule_header_id = sched_lines.schedule_header_id(+)
5425       and    sched_hdrs.schedule_id = sched_lines.schedule_id(+)
5426       and    nvl(sched_hdrs.status,'A') = 'A'
5427       and    sched_lines.aging_bucket_id = bucket_lines.aging_bucket_id(+)
5428       and    sched_lines.aging_bucket_line_id = bucket_lines.aging_bucket_line_id(+)
5429       /* Calculate the penalty only if the penalty type is defined for the customer */
5430       and    cust_site.penalty_type IS NOT NULL
5431       /* Condition 1: days late should be between the bucket lines start and end days
5432          For ADB, the interest_days should be used. */
5433       and    (( trx.charge_type = 'AVERAGE_DAILY_BALANCE'
5434                and trx.interest_days >= nvl(bucket_lines.days_start,trx.interest_days)
5435                and trx.interest_days <= nvl(bucket_lines.days_to,trx.interest_days))
5436              OR
5437               (trx.charge_type <> 'AVERAGE_DAILY_BALANCE'
5438                and (trx.finance_charge_date- trx.due_date) >=nvl(bucket_lines.days_start,
5439                                                           (trx.finance_charge_date- trx.due_date))
5440               and   (trx.finance_charge_date- trx.due_date) <= nvl(bucket_lines.days_to,
5441                                                           (trx.finance_charge_date- trx.due_date))))
5442       /* The rate effective on the due date should be picked up. So, the due
5443          date should fall between the start date and end date of the charge schedule
5444          Condition 2: Start_date of the schedule should be less than or equal to the
5445          due date
5446          Condition 3: End date of the schedule should be greater than or equal to the
5447          due date or it should be NULL
5448          For Average Daily Balance, the rate effective on the charge calculation should be
5449          picked up */
5450        and ((trx.charge_type = 'AVERAGE_DAILY_BALANCE'
5451              and trx.finance_charge_date >= nvl(sched_hdrs.start_date,trx.finance_charge_date)
5452              and (trx.finance_charge_date <= sched_hdrs.end_date
5453                    OR sched_hdrs.end_date IS NULL))
5454             OR
5455            (trx.charge_type <> 'AVERAGE_DAILY_BALANCE'
5456     	     and   nvl(sched_hdrs.start_date,trx.due_date) <= trx.due_date
5457             and  ( sched_hdrs.end_date >= trx.due_date
5458                         OR sched_hdrs.end_date IS NULL)))
5459      /* Create the panalty lines only if the late charge documents will be created out
5460         of this record */
5461        and  trx.display_flag = 'Y'
5462      /* Do not populate the Penalty lines if the invoice level tolerances are not met
5463          For Average Daily Balance, there is no invoice level tolerances*/
5464       and decode(trx.charge_type,
5465                  'AVERAGE_DAILY_BALANCE',  nvl(trx.original_balance,0),
5466                  decode(trx.class,
5467                 	'CM', nvl(trx.original_balance,0),
5468 	                'PMT',nvl(trx.original_balance,0),
5469                         decode(trx.min_fc_invoice_overdue_type,
5470                               'AMOUNT',nvl(trx.min_fc_invoice_amount,0),
5471                               'PERCENT',(nvl(trx.min_fc_invoice_percent,0)
5472                                       * trx.amount_due_original/100),
5473                                nvl(trx.original_balance,0)))) <= nvl(trx.original_balance,0)
5474     group by trx.customer_id,
5475              trx.customer_site_use_id,
5476              trx.currency_code,
5477              trx.customer_trx_id,
5478              trx.legal_entity_id,
5479              trx.payment_schedule_id,
5480              trx.class,
5481              trx.amount_due_original,
5482              trx.amount_due_remaining,
5483              trx.fin_charge_charged,
5484              trx.trx_date,
5485              trx.cust_trx_type_id,
5486              trx.last_charge_date,
5487              trx.exchange_rate_type,
5488              trx.min_interest_charge,
5489              trx.max_interest_charge,
5490              trx.due_date,
5491              trx.finance_charge_date,
5492              decode(trx.charge_type,'AVERAGE_DAILY_BALANCE',trx.charge_type, NULL),
5493              trx.actual_date_closed,
5494              decode(cust_site.penalty_type, 'CHARGES_SCHEDULE', sched_lines.rate,
5495                                              'FIXED_RATE', cust_site.penalty_rate,
5496                                               NULL),
5497              sched_hdrs.start_date,
5498              sched_hdrs.end_date,
5499              bucket_lines.days_start,
5500              bucket_lines.days_to,
5501              decode(cust_site.penalty_type,
5502                       'FIXED_AMOUNT',decode(trx.class,
5503                                             'CM',-1 * cust_site.penalty_fixed_amount,
5504                                             'PMT', -1*cust_site.penalty_fixed_amount,
5505                                             cust_site.penalty_fixed_amount),
5506                       'CHARGES_SCHEDULE',decode(sched_hdrs.schedule_header_type,
5507                                                 'AMOUNT',decode(trx.class,
5508                                                                'CM', -1*sched_lines.amount,
5509                                                                'PMT',-1*sched_lines.amount,
5510                                                                sched_lines.amount),
5511                                                 NULL),
5512                       'CHARGE_PER_TIER',decode(sched_hdrs.schedule_header_type,
5513                                                 'AMOUNT',decode(trx.class,
5514                                                                'CM', -1*sched_lines.amount,
5515                                                                'PMT',-1*sched_lines.amount,
5516                                                                sched_lines.amount),
5517                                                 NULL), /*Enhacement 6469663*/
5518                       NULL),
5519              trx.late_charge_type,
5520 	     trx.org_id,
5521              decode(trx.charge_type,'AVERAGE_DAILY_BALANCE',trx.interest_days,1),
5522              trx.late_charge_term_id,
5523              trx.interest_period_days,
5524              trx.interest_calculation_period,
5525              trx.charge_on_finance_charge_flag,
5526              trx.message_text_id,
5527              cust_site.penalty_type) a);
5528 
5529       IF l_debug_flag = 'Y' THEN
5530          debug( 'ar_calc_late_charge.insert_penalty_lines()-' );
5531       END IF;
5532     --
5533    EXCEPTION
5534       WHEN  OTHERS THEN
5535            --IF l_debug_flag = 'Y' THEN
5536                debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
5537                debug('EXCEPTION: ar_calc_late_charge.insert_penalty_lines' );
5538            --END IF;
5539            RAISE;
5540 END insert_penalty_lines;
5541 
5542 PROCEDURE  delete_draft_batches(p_worker_number		IN	NUMBER,
5543                                 p_total_workers         IN	NUMBER) IS
5544 
5545 BEGIN
5546 
5547      IF l_debug_flag = 'Y' THEN
5548          debug('ar_calc_late_charge.delete_draft_batches()+');
5549          debug('p_worker_number :	'||p_worker_number);
5550          debug('p_total_workers :	'||p_total_workers);
5551      END IF;
5552     /* delete lines first */
5553 
5554      delete from ar_interest_lines
5555      where interest_header_id in (select hdr.interest_header_id
5556                                    from ar_interest_batches batch,
5557 					ar_interest_headers hdr
5558   				  where batch.batch_status = 'D'
5559 				    and batch.interest_batch_id = hdr.interest_batch_id
5560                                     and mod(nvl(hdr.customer_site_use_id,0),p_total_workers) =
5561                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
5562                                     and batch.request_id <> l_request_id
5563 				    and exists (select late_charge_trx_id
5564 						from   ar_late_charge_trx_t trx
5565 						where	trx.customer_id = hdr.customer_id
5566 						and	trx.customer_site_use_id = hdr.customer_site_use_id
5567                                                 and     trx.currency_code = hdr.currency_code
5568 						and	nvl(trx.legal_entity_id,-99)  =  nvl(hdr.legal_entity_id,-99)
5569 						and	trx.org_id = hdr.org_id));
5570     /* delete headers */
5571 
5572     delete from ar_interest_headers hdr
5573     where not exists (select interest_line_id
5574                         from ar_interest_lines lines
5575                        where hdr.interest_header_id = lines.interest_header_id)
5576      and  hdr.request_id <> l_request_id;
5577 
5578     /* Deleting the empty batches are done later in delete_empty_batches */
5579 
5580 
5581     IF l_debug_flag = 'Y' THEN
5582       debug('ar_calc_late_charge.delete_draft_batches()-');
5583     END IF;
5584 
5585 EXCEPTION WHEN OTHERS THEN
5586        --IF l_debug_flag = 'Y' THEN
5587          debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
5588          debug('EXCEPTION : ar_calc_late_charge.delete_draft_batches()');
5589        --END IF;
5590        RAISE;
5591 END delete_draft_batches;
5592 
5593 
5594 
5595 PROCEDURE insert_int_batches(p_operating_unit_id	IN	NUMBER,
5596 			     p_batch_name		IN	VARCHAR2,
5597                  	     p_fin_charge_date		IN	DATE,
5598 		             p_batch_status		IN	VARCHAR2,
5599 	                     p_gl_date			IN	DATE,
5600                              p_request_id		IN	NUMBER) IS
5601 
5602  l_operating_unit_id    number;
5603  l_batch_name		ar_interest_batches.batch_name%type;
5604  l_fin_charge_date	date;
5605  l_batch_status		varchar2(1);
5606  l_gl_date		date;
5607  l_srs_request_id	number;
5608 
5609 BEGIN
5610 
5611   IF l_debug_flag = 'Y' THEN
5612      debug( 'ar_calc_late_charge.insert_int_batches()+' );
5613   END IF;
5614 
5615   l_operating_unit_id	:=	p_operating_unit_id;
5616   l_batch_name		:=	p_batch_name;
5617   l_fin_charge_date	:=	p_fin_charge_date;
5618   l_batch_status	:=	p_batch_status;
5619   l_gl_date		:=	p_gl_date;
5620   l_srs_request_id	:=	p_request_id;
5621 
5622   IF l_batch_name IS NULL THEN
5623      select meaning
5624      into   l_batch_name
5625      from   ar_lookups
5626      where  lookup_type = 'AR_LATE_CHARGE_LABELS'
5627      and   lookup_code = 'LATE_CHARGE_BATCH';
5628      IF l_debug_flag = 'Y' THEN
5629          debug( 'Batch Name Derived : '||l_batch_name);
5630      END IF;
5631   END IF;
5632 
5633      insert into ar_interest_batches
5634         ( interest_batch_id,
5635           batch_name,
5636           calculate_interest_to_date,
5637           batch_status,
5638           gl_date,
5639           last_update_date,
5640           last_updated_by,
5641           last_update_login,
5642           created_by,
5643           creation_date,
5644           transferred_status,
5645 	  request_id,
5646           org_id,
5647           object_version_number)
5648   (select ar_interest_batches_s.nextval,
5649           l_batch_name||' '||ar_interest_batches_s2.nextval
5650              ||' '||to_char(l_fin_charge_date,'DD-Mon-YYYY'),
5651           l_fin_charge_date,
5652           l_batch_status,
5653           l_gl_date,
5654           sysdate,
5655           pg_last_updated_by,
5656           pg_last_update_login,
5657           pg_last_updated_by,
5658           sysdate,
5659           'N',
5660           l_srs_request_id,
5661           sysparam.org_id,
5662           1
5663     from ar_system_parameters sysparam
5664     where nvl(l_operating_unit_id,sysparam.org_id) = sysparam.org_id);
5665 
5666   IF l_debug_flag = 'Y' THEN
5667      debug( 'ar_calc_late_charge.insert_int_batches()-' );
5668   END IF;
5669     --
5670   EXCEPTION
5671      WHEN  OTHERS THEN
5672         --IF l_debug_flag = 'Y' THEN
5673             debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
5674             debug('EXCEPTION: ar_calc_late_charge.insert_int_batches' );
5675         --END IF;
5676         RAISE;
5677 END insert_int_batches;
5678 
5679 
5680 PROCEDURE insert_int_headers(p_fin_charge_date	IN	DATE,
5681 			     p_worker_number	IN	NUMBER,
5682 			     p_total_workers    IN	NUMBER) IS
5683 BEGIN
5684 
5685    IF l_debug_flag = 'Y' THEN
5686       debug( 'ar_calc_late_charge.insert_int_headers()+' );
5687    END IF;
5688 
5689    insert into ar_interest_headers
5690        (interest_header_id,
5691         interest_batch_id,
5692         customer_id,
5693         customer_site_use_id,
5694         header_type,
5695         currency_code,
5696         cust_trx_type_id,
5697         late_charge_calculation_trx,
5698         credit_items_flag,
5699         disputed_transactions_flag,
5700         payment_grace_days,
5701         late_charge_term_id,
5702         interest_period_days,
5703         interest_calculation_period,
5704         charge_on_finance_charge_flag,
5705         hold_charged_invoices_flag,
5706         message_text_id,
5707         multiple_interest_rates_flag,
5708         charge_begin_date,
5709         cust_acct_profile_amt_id,
5710         exchange_rate,
5711         exchange_rate_type,
5712         min_fc_invoice_overdue_type,
5713         min_fc_invoice_amount,
5714         min_fc_invoice_percent,
5715         min_fc_balance_overdue_type,
5716         min_fc_balance_amount,
5717         min_fc_balance_percent,
5718         min_interest_charge,
5719         max_interest_charge,
5720         interest_type,
5721         interest_rate,
5722         interest_fixed_amount,
5723         interest_schedule_id,
5724         penalty_type,
5725         penalty_rate,
5726         penalty_fixed_amount,
5727         penalty_schedule_id,
5728         last_accrue_charge_date,
5729         finance_charge_date,
5730         customer_profile_id,
5731         collector_id,
5732         legal_entity_id,
5733         last_update_date,
5734         last_updated_by,
5735         last_update_login,
5736         created_by,
5737         creation_date,
5738         process_status,
5739         process_message,
5740         request_id,
5741         worker_num,
5742         object_version_number,
5743         org_id,
5744         display_flag)
5745    (select hdr.interest_header_id,
5746            bat.interest_batch_id,
5747            hdr.customer_id,
5748            hdr.customer_site_use_id,
5749            cust_site.late_charge_type header_type,
5750            hdr.currency_code,
5751            decode(cust_site.late_charge_type,
5752                   'INV', sysparam.late_charge_inv_type_id,
5753 		  'DM',sysparam.late_charge_dm_type_id) cust_trx_type_id,
5754            cust_site.late_charge_calculation_trx,
5755            cust_site.credit_items_flag,
5756            cust_site.disputed_transactions_flag,
5757            cust_site.payment_grace_days,
5758            cust_site.late_charge_term_id,
5759            cust_site.interest_period_days,
5760            cust_site.interest_calculation_period,
5761            cust_site.charge_on_finance_charge_flag,
5762            cust_site.hold_charged_invoices_flag,
5763            cust_site.message_text_id,
5764            cust_site.multiple_interest_rates_flag,
5765            cust_site.charge_begin_date,
5766            cust_site.cust_acct_profile_amt_id,
5767            cust_site.exchange_rate,
5768            cust_site.exchange_rate_type,
5769            cust_site.min_fc_invoice_overdue_type,
5770            cust_site.min_fc_invoice_amount,
5771            cust_site.min_fc_invoice_percent,
5772            cust_site.min_fc_balance_overdue_type,
5773            cust_site.min_fc_balance_amount,
5774            cust_site.min_fc_balance_percent,
5775            cust_site.min_interest_charge,
5776            cust_site.max_interest_charge,
5777            cust_site.interest_type,
5778            cust_site.interest_rate,
5779            cust_site.interest_fixed_amount,
5780            cust_site.interest_schedule_id,
5781            cust_site.penalty_type,
5782            cust_site.penalty_rate,
5783            cust_site.penalty_fixed_amount,
5784            cust_site.penalty_schedule_id,
5785            cust_site.last_accrue_charge_date,
5786            p_fin_charge_date,
5787            cust_site.customer_profile_id,
5788            cust_site.collector_id,
5789            hdr.legal_entity_id,
5790            sysdate,
5791            pg_last_updated_by,
5792            pg_last_update_login,
5793            pg_last_updated_by,
5794            sysdate,
5795            'N',
5796            NULL,
5797            l_request_id,
5798            p_worker_number,
5799            1,
5800            cust_site.org_id,
5801            hdr.display_flag
5802     from   (select lines.interest_header_id,
5803                    trx.customer_id,
5804                    trx.customer_site_use_id,
5805                    trx.legal_entity_id,
5806                    trx.currency_code,
5807                    trx.late_charge_type,
5808 		   trx.org_id,
5809                    trx.display_flag
5810             from   ar_interest_lines lines,
5811                    ar_late_charge_trx_t trx
5812             where  lines.payment_schedule_id = trx.payment_schedule_id
5813 	    and    lines.org_id = trx.org_id
5814 	    and    lines.type=trx.charge_type
5815 	    and    not exists (select interest_header_id
5816                                 from ar_interest_headers headers
5817                                 where headers.interest_header_id = lines.interest_header_id)
5818             and    mod(nvl(trx.customer_site_use_id,0),p_total_workers) =
5819                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
5820             /*Bug fix 5290709: If display flag is No, we should not consider this record if there is another record
5821               existing with display flag Yes */
5822             and ((trx.display_flag = 'Y' and sign(trx.late_charge_amount) <> 0)
5823              OR (trx.display_flag = 'N' and not exists (select 1
5824                                                         from ar_late_charge_trx_t trx1
5825                                                         where trx1.payment_schedule_id = trx.payment_schedule_id
5826                                                         and trx1.display_flag = 'Y')))
5827             and nvl(lines.cash_receipt_id,-1) = nvl(trx.cash_receipt_id,-1)
5828             group  by lines.interest_header_id,
5829                       trx.customer_id,
5830                       trx.customer_site_use_id,
5831                       trx.legal_entity_id,
5832                       trx.currency_code,
5833                       trx.late_charge_type,
5834 		      trx.org_id,
5835                       trx.display_flag) hdr,
5836            ar_lc_cust_sites_t cust_site,
5837 	   ar_interest_batches bat,
5838            ar_system_parameters sysparam
5839     where  hdr.customer_id = cust_site.customer_id
5840       and  hdr.customer_site_use_id = cust_site.customer_site_use_id
5841       and  hdr.currency_code = cust_site.currency_code
5842       and  mod(nvl(cust_site.customer_site_use_id,0),p_total_workers) =
5843                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
5844       and  hdr.late_charge_type = cust_site.late_charge_type
5845       and  hdr.org_id = cust_site.org_id
5846       and  bat.org_id = cust_site.org_id
5847       and  sysparam.org_id = cust_site.org_id
5848       and  bat.request_id = l_request_id);
5849 
5850    IF l_debug_flag = 'Y' THEN
5851       debug( 'ar_calc_late_charge.insert_int_headers()-' );
5852    END IF;
5853     --
5854    EXCEPTION
5855      WHEN  OTHERS THEN
5856         --IF l_debug_flag = 'Y' THEN
5857             debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
5858             debug('EXCEPTION: ar_calc_late_charge.insert_int_headers' );
5859         --END IF;
5860         RAISE;
5861 END insert_int_headers;
5862 
5863 /*=========================================================================================+
5864  | PROCEDURE INSERT_INT_LINES                                                              |
5865  |                                                                                         |
5866  | DESCRIPTION                                                                             |
5867  |                                                                                         |
5868  |   This procedure is used to insert interest and penalty lines to ar_interest_lines      |
5869  |   table.                                                                                |
5870  |                                                                                         |
5871  | PSEUDO CODE/LOGIC                                                                       |
5872  |                                                                                         |
5873  |                                                                                         |
5874  | The tolerances should be applied on the interest lines before inserting into            |
5875  | ar_interest_lines, mainly max_interest_charge.                                          |
5876  | The logic:                                                                              |
5877  |                                                                                         |
5878  |  1. Sort the interest lines in the order of charge_line_type, rate_start_date,          |
5879  |      charge_type,receipt_date and fin_charge_charged                                    |
5880  |  2. Calculate the running total of the calculated interest charge in that order         |
5881  |     (in the select statement, it is denoted as late_charge_rtot)                        |
5882  |  3. Tolerances are applicable only on charge_line_type = INTEREST                       |
5883  |  4. At any point in this order of calculation ,                                         |
5884  |     a)  if the running total is less than or equal to the maximum allowed interest      |
5885  |         charge, we should take the charge as  the calculated charge itself.             |
5886  |     b)  if the running total is greater than the maximum allowed interest charge        |
5887  |         i) if the maximum allowed interest charge is less than the running total till   |
5888  |            the previous line, that means the maximum interest is already covered by     |
5889  |            the previous line atleast. So, that charge should be 0 for the current line  |
5890  |        ii) otherwise, it should be the least of (the difference between the maximum     |
5891  |            interest charge and the running total till the previous line) and the max    |
5892  |            interest charge                                                              |
5893  |                                                                                         |
5894  | PARAMETERS                                                                              |
5895  |                                                                                         |
5896  |                                                                                         |
5897  | KNOWN ISSUES                                                                            |
5898  |                                                                                         |
5899  | NOTES                                                                                   |
5900  |                                                                                         |
5901  | MODIFICATION HISTORY                                                                    |
5902  | Date                  Author            Description of Changes                          |
5903  | 22-DEC-2005           rkader            Created                                         |
5904  | 21-SEP-2006           rkader            Bug 5556598. Modified the logic as explained    |
5905  |                                         above                                           |
5906  |                                         Bug8556955                                      |
5907  |22-JUN-2009            naneja            Inserted data for new column cash_receipt_id    |
5908  *=========================================================================================*/
5909 PROCEDURE insert_int_lines(p_worker_number	IN	NUMBER,
5910 			   p_total_workers	IN	NUMBER) IS
5911 BEGIN
5912    IF l_debug_flag = 'Y' THEN
5913       debug( 'ar_calc_late_charge.insert_int_lines()+' );
5914    END IF;
5915 
5916    insert into ar_interest_lines
5917        (interest_line_id,
5918         interest_header_id,
5919         payment_schedule_id,
5920         type,
5921         original_trx_class,
5922         daily_interest_charge,
5923         outstanding_amount,
5924         days_overdue_late,
5925         days_of_interest,
5926         interest_charged,
5927         payment_date,
5928         finance_charge_charged,
5929         amount_due_original,
5930         amount_due_remaining,
5931         original_trx_id,
5932         receivables_trx_id,
5933         last_charge_date,
5934         due_date,
5935         actual_date_closed,
5936         interest_rate,
5937         rate_start_date,
5938         rate_end_date,
5939         schedule_days_from,
5940         schedule_days_to,
5941         last_update_date,
5942         last_updated_by,
5943         last_update_login,
5944         created_by,
5945         creation_date,
5946         process_status,
5947         process_message,
5948         org_id,
5949         object_version_number,
5950         cash_receipt_id)
5951  (select ar_interest_lines_s.nextval interest_line_id,
5952          b.interest_header_id,
5953          b.payment_schedule_id,
5954          b.charge_type,
5955          b.class,
5956          decode(b.class,
5957                 'PMT',b.late_charge_amount,
5958                 'CM', b.late_charge_amount,
5959                 decode(b.charge_line_type,
5960                        'INTEREST',
5961                          decode(sign(b.late_charge_rtot - b.max_interest_charge),
5962                                   -1, b.late_charge_amount,
5963                                    0 ,b.late_charge_amount,
5964                                   +1,decode(sign(b.max_interest_charge -
5965                                               (b.late_charge_rtot - b.late_charge_amount)),
5966                                             -1,0,
5967                                             least((b.max_interest_charge -
5968                                                   (b.late_charge_rtot - b.late_charge_amount)),
5969                                                    b.max_interest_charge))),
5970                       'PENALTY', b.late_charge_amount))
5971                               /decode(b.days_of_interest,0,1,b.days_of_interest) daily_interest_charge,
5972          b.outstanding_amount,
5973          b.days_overdue_late,
5974          b.days_of_interest,
5975          decode(b.class,
5976                 'PMT',b.late_charge_amount,
5977                 'CM', b.late_charge_amount,
5978                 decode(b.charge_line_type,
5979                        'INTEREST',
5980                          decode(sign(b.late_charge_rtot - b.max_interest_charge),
5981                                   -1, b.late_charge_amount,
5982                                    0 ,b.late_charge_amount,
5983                                   +1,decode(sign(b.max_interest_charge -
5984                                               (b.late_charge_rtot - b.late_charge_amount)),
5985                                             -1,0,
5986                                             least((b.max_interest_charge -
5987                                                   (b.late_charge_rtot - b.late_charge_amount)),
5988                                                    b.max_interest_charge))),
5989                       'PENALTY', b.late_charge_amount)) interest_charged,
5990          b.payment_date,
5991          b.fin_charge_charged,
5992          b.amount_due_original,
5993          b.amount_due_remaining,
5994          b.original_trx_id,
5995          b.receivables_trx_id,
5996          b.last_charge_date,
5997          b.due_date,
5998          b.actual_date_closed,
5999          b.interest_rate,
6000          b.rate_start_date,
6001          b.rate_end_date,
6002          b.schedule_days_start,
6003          b.schedule_days_to,
6004          sysdate,
6005          pg_last_updated_by,
6006          pg_last_update_login,
6007          pg_last_updated_by,
6008          sysdate,
6009          'N',
6010          NULL,
6011          b.org_id,
6012          1,
6013 	 b.cash_receipt_id
6014       from
6015       (select
6016               a.interest_header_id,
6017               a.payment_schedule_id,
6018               a.charge_type,
6019               a.class,
6020               a.outstanding_amount,
6021               a.days_overdue_late,
6022               a.days_of_interest,
6023               a.late_charge_amount,
6024               a.charge_line_type,
6025               a.late_charge_rtot,
6026               a.max_interest_charge,
6027               a.payment_date,
6028               a.fin_charge_charged,
6029               a.amount_due_original,
6030               a.amount_due_remaining,
6031               a.original_trx_id,
6032               a.receivables_trx_id,
6033               a.last_charge_date,
6034               a.due_date,
6035               a.actual_date_closed,
6036               a.interest_rate,
6037               a.rate_start_date,
6038               a.rate_end_date,
6039               a.schedule_days_start,
6040               a.schedule_days_to,
6041               a.org_id,
6042 	      a.cash_receipt_id
6043        from
6044         (select
6045                 hdr.interest_header_id,
6046                 trx.payment_schedule_id,
6047                 trx.charge_type,
6048                 trx.class,
6049                 trx.overdue_late_pay_amount outstanding_amount,
6050                 /*bug 7431976 for invoice picked under late payment used receipt date. Bug 10230536 for correcting overdue days for overdue case*/
6051                 (decode(trx.charge_type,'LATE',(nvl(trx.receipt_date,trx.finance_charge_date) - trx.due_date) ,(trx.finance_charge_date -trx.due_date))) days_overdue_late,
6052                 trx.interest_days days_of_interest,
6053                 trx.late_charge_amount,
6054                 trx.charge_line_type,
6055                 decode(trx.charge_line_type,
6056                        'INTEREST',  sum(trx.late_charge_amount)
6057                                             over (partition by trx.payment_schedule_id
6058                                                   order by trx.payment_schedule_id,
6059                                                            trx.charge_line_type,
6060                                                            trx.rate_start_date,
6061                                                            trx.charge_type,
6062                                                            trx.receipt_date,
6063                                                            trx.fin_charge_charged),
6064                        'PENALTY', NULL) late_charge_rtot,
6065                 trx.receipt_date payment_date,
6066                 nvl(trx.max_interest_charge,9999999999999999) max_interest_charge,
6067                 trx.fin_charge_charged,
6068                 trx.amount_due_original,
6069                 trx.amount_due_remaining,
6070                 trx.customer_trx_id original_trx_id,
6071                 decode(hdr.late_charge_type,
6072                         'ADJ',decode(trx.charge_line_type,
6073                                       'PENALTY',ar_calc_late_charge.get_penalty_rec_trx_id(trx.finance_charge_date,
6074                                                                                            trx.org_id),
6075                                       'INTEREST',ar_calc_late_charge.get_int_rec_trx_id(trx.customer_trx_id,
6076                                                                               trx.finance_charge_date,
6077 									      trx.org_id),
6078                                        NULL),
6079                        NULL) receivables_trx_id,
6080                 trx.last_charge_date,
6081                 trx.due_date,
6082                 trx.actual_date_closed,
6083                 trx.interest_rate,
6084                 trx.rate_start_date,
6085                 trx.rate_end_date,
6086                 trx.schedule_days_start,
6087                 trx.schedule_days_to,
6088        		trx.org_id,
6089 		trx.cash_receipt_id
6090           from
6091            (select
6092                 ar_calc_late_charge.get_next_hdr_id interest_header_id,
6093                 a.customer_id,
6094                 a.customer_site_use_id,
6095                 a.currency_code,
6096                 a.legal_entity_id,
6097                 a.late_charge_type,
6098                 a.payment_schedule_id,
6099 		a.org_id,
6100                 a.display_flag
6101             from
6102                  (select trx.customer_id,
6103                          trx.customer_site_use_id,
6104                          trx.currency_code,
6105                          trx.legal_entity_id,
6106                          trx.late_charge_type,
6107 			 trx.org_id,
6108                          trx.display_flag,
6109                          decode(trx.late_charge_type,'INV',-99,trx.payment_schedule_id) payment_schedule_id
6110                   from   ar_late_charge_trx_t trx
6111                   where  mod(nvl(trx.customer_site_use_id,0),p_total_workers) =
6112                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
6113                  /*Bug fix 5290709: If display flag is No, we should not consider this record if there is another record
6114                    existing with display flag Yes */
6115                  and ((trx.display_flag = 'Y' and sign(trx.late_charge_amount) <> 0)
6116                  OR (trx.display_flag = 'N' and not exists (select 1
6117                                                             from ar_late_charge_trx_t trx1
6118                                                             where trx1.payment_schedule_id = trx.payment_schedule_id
6119                                                             and trx1.display_flag = 'Y')))
6120                 group by trx.customer_id,
6121                          trx.customer_site_use_id,
6122                          trx.currency_code,
6123                          trx.legal_entity_id,
6124                          trx.late_charge_type,
6125 			 trx.org_id,
6126                          trx.display_flag,
6127                          decode(trx.late_charge_type,'INV',-99,trx.payment_schedule_id))a)hdr,
6128                  (select trx.payment_schedule_id,
6129                          sum(trx.late_charge_amount) total_interest
6130                     from ar_late_charge_trx_t trx
6131                   where  trx.charge_line_type = 'INTEREST'
6132                     and  mod(nvl(trx.customer_site_use_id,0),p_total_workers) =
6133                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
6134                   group  by trx.payment_schedule_id) int_tab,
6135                   ar_late_charge_trx_t trx
6136            /* Apply the invoice level tolerances */
6137            where decode(trx.class,
6138                        'CM', nvl(trx.original_balance,0),
6139                        'PMT',nvl(trx.original_balance,0),
6140                        decode(trx.display_flag,
6141                               'N', nvl(trx.original_balance,0),
6142                               decode(trx.min_fc_invoice_overdue_type,
6143                                      'AMOUNT',nvl(trx.min_fc_invoice_amount,0),
6144                                       'PERCENT',(nvl(trx.min_fc_invoice_percent,0) * trx.amount_due_original/100),
6145                                       nvl(trx.original_balance,0)))) <= nvl(trx.original_balance,0)
6146              and trx.payment_schedule_id = int_tab.payment_schedule_id
6147           /* Apply Min Interest charge tolerance  Bug 8559863 Restrict tolerance application on negatvie invoice as well
6148              Similar to CM case */
6149              and decode(trx.class,
6150                         'CM',int_tab.total_interest,
6151                         'PMT',int_tab.total_interest,
6152 			'INV', decode(sign(trx.original_balance),-1,int_tab.total_interest,
6153 				                        decode(trx.display_flag,
6154                                					'N', int_tab.total_interest,
6155 			                                        nvl(trx.min_interest_charge,0))),
6156                         decode(trx.display_flag,
6157                                'N', int_tab.total_interest,
6158 				nvl(trx.min_interest_charge,0))) <= int_tab.total_interest
6159              and mod(nvl(trx.customer_site_use_id,0),p_total_workers) =
6160                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
6161              and hdr.customer_id = trx.customer_id
6162              and hdr.customer_site_use_id = trx.customer_site_use_id
6163              and hdr.currency_code = trx.currency_code
6164              and hdr.legal_entity_id = trx.legal_entity_id
6165              and hdr.late_charge_type = trx.late_charge_type
6166 	     and hdr.org_id = trx.org_id
6167              /*Bug fix 5290709: If display flag is No, we should not consider this record if there is another record
6168                    existing with display flag Yes */
6169               and ((trx.display_flag = 'Y' and sign(trx.late_charge_amount) <> 0)
6170                  OR (trx.display_flag = 'N' and not exists (select 1
6171                                                             from ar_late_charge_trx_t trx1
6172                                                             where trx1.payment_schedule_id = trx.payment_schedule_id
6173                                                             and trx1.display_flag = 'Y')))
6174              and hdr.payment_schedule_id = decode(trx.late_charge_type,'INV',-99,trx.payment_schedule_id)) a ) b);
6175 
6176    IF l_debug_flag = 'Y' THEN
6177       debug( 'ar_calc_late_charge.insert_int_lines()-' );
6178    END IF;
6179     --
6180    EXCEPTION
6181      WHEN  OTHERS THEN
6182         --IF l_debug_flag = 'Y' THEN
6183             debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
6184             debug('EXCEPTION: ar_calc_late_charge.insert_int_lines');
6185         --END IF;
6186         RAISE;
6187 END insert_int_lines;
6188 
6189 /* This procedure is used to insert records in ar_interest lines
6190    when the calculation method is average daily balance */
6191 
6192 PROCEDURE insert_int_lines_adb(p_worker_number      IN      NUMBER,
6193                                p_total_workers      IN      NUMBER) IS
6194 BEGIN
6195    IF l_debug_flag = 'Y' THEN
6196       debug( 'ar_calc_late_charge.insert_int_lines_adb()+' );
6197    END IF;
6198 
6199  insert into ar_interest_lines
6200        (interest_line_id,
6201         interest_header_id,
6202         payment_schedule_id,
6203         type,
6204         original_trx_class,
6205         daily_interest_charge,
6206         outstanding_amount,
6207         days_overdue_late,
6208         days_of_interest,
6209         interest_charged,
6210         payment_date,
6211         finance_charge_charged,
6212         amount_due_original,
6213         amount_due_remaining,
6214         original_trx_id,
6215         receivables_trx_id,
6216         last_charge_date,
6217         due_date,
6218         actual_date_closed,
6219         interest_rate,
6220         rate_start_date,
6221         rate_end_date,
6222         schedule_days_from,
6223         schedule_days_to,
6224         last_update_date,
6225         last_updated_by,
6226         last_update_login,
6227         created_by,
6228         creation_date,
6229         process_status,
6230         process_message,
6231         org_id,
6232         object_version_number)
6233  (select ar_interest_lines_s.nextval interest_line_id,
6234          b.interest_header_id,
6235          -99, --payment_schedule_id
6236          decode(b.charge_line_type, 'PENALTY', b.charge_line_type,b.charge_type) charge_type,
6237          b.class,
6238          b.late_charge_amount/decode(b.days_of_interest,0,1,b.days_of_interest) daily_interest_charge,
6239          b.outstanding_amount,
6240          b.days_overdue_late,
6241          b.days_of_interest,
6242          b.late_charge_amount interest_charged,
6243          b.payment_date,
6244          b.fin_charge_charged,
6245          b.amount_due_original,
6246          b.amount_due_remaining,
6247          b.original_trx_id,
6248          b.receivables_trx_id,
6249          b.last_charge_date,
6250          b.due_date,
6251          b.actual_date_closed,
6252          b.interest_rate,
6253          b.rate_start_date,
6254          b.rate_end_date,
6255          b.schedule_days_start,
6256          b.schedule_days_to,
6257          sysdate,
6258          pg_last_updated_by,
6259          pg_last_update_login,
6260          pg_last_updated_by,
6261          sysdate,
6262          'N',
6263          NULL,
6264          b.org_id,
6265          1
6266     from
6267       (select
6268               a.interest_header_id,
6269               a.payment_schedule_id,
6270               a.charge_type,
6271               a.class,
6272               a.outstanding_amount,
6273               a.days_overdue_late,
6274               a.days_of_interest,
6275               a.late_charge_amount,
6276               a.charge_line_type,
6277               a.payment_date,
6278               a.fin_charge_charged,
6279               a.amount_due_original,
6280               a.amount_due_remaining,
6281               a.original_trx_id,
6282               a.receivables_trx_id,
6283               a.last_charge_date,
6284               a.due_date,
6285               a.actual_date_closed,
6286               a.interest_rate,
6287               a.rate_start_date,
6288               a.rate_end_date,
6289               a.schedule_days_start,
6290               a.schedule_days_to,
6291               a.org_id
6292        from
6293         (
6294 	  select
6295                 hdr.interest_header_id,
6296                 trx.payment_schedule_id,
6297                 trx.charge_type,
6298                 trx.class,
6299                 trx.overdue_late_pay_amount outstanding_amount,
6300                 trx.interest_days days_overdue_late,
6301                 trx.interest_days days_of_interest,
6302                 decode(trx.charge_line_type,
6303                        'INTEREST',decode(sign(nvl(trx.max_interest_charge,9999999999999999) -
6304                                          trx.late_charge_amount),
6305                                          +1,trx.late_charge_amount,
6306                                          0, trx.late_charge_amount,
6307                                          -1, nvl(trx.max_interest_charge,9999999999999999)),
6308                        'PENALTY',trx.late_charge_amount ) late_charge_amount,
6309                 trx.charge_line_type,
6310                 trx.receipt_date payment_date,
6311                 trx.fin_charge_charged,
6312                 trx.amount_due_original,
6313                 trx.amount_due_remaining,
6314                 trx.customer_trx_id original_trx_id,
6315                 NULL receivables_trx_id,
6316                 trx.last_charge_date,
6317                 trx.due_date,
6318                 trx.actual_date_closed,
6319                 trx.interest_rate,
6320                 trx.rate_start_date,
6321                 trx.rate_end_date,
6322                 trx.schedule_days_start,
6323                 trx.schedule_days_to,
6324                 trx.org_id
6325           from
6326            (select
6327                 ar_calc_late_charge.get_next_hdr_id interest_header_id,
6328                 a.customer_id,
6329                 a.customer_site_use_id,
6330                 a.currency_code,
6331                 a.legal_entity_id,
6332                 a.late_charge_type,
6333                 a.payment_schedule_id,
6334                 a.org_id
6335             from
6336                  (select trx.customer_id,
6337                          trx.customer_site_use_id,
6338                          trx.currency_code,
6339                          trx.legal_entity_id,
6340                          trx.late_charge_type,
6341                          trx.org_id,
6342                          decode(trx.late_charge_type,'INV',-99,trx.payment_schedule_id) payment_schedule_id
6343                   from   ar_late_charge_trx_t trx
6344                   where  mod(nvl(trx.customer_site_use_id,0),p_total_workers) =
6345                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
6346                 group by trx.customer_id,
6347                          trx.customer_site_use_id,
6348                          trx.currency_code,
6349                          trx.legal_entity_id,
6350                          trx.late_charge_type,
6351                          trx.org_id,
6352                          decode(trx.late_charge_type,'INV',-99,trx.payment_schedule_id))a)hdr,
6353                   (select trx.payment_schedule_id,
6354                          sum(trx.late_charge_amount) total_interest
6355                     from ar_late_charge_trx_t trx
6356                   where  trx.charge_line_type = 'INTEREST'
6357                     and  mod(nvl(trx.customer_site_use_id,0),1) =
6358                                           decode(1,1,0,1)
6359                   group  by trx.payment_schedule_id) int_tab,
6360                   ar_late_charge_trx_t trx
6361           /* Apply Min Interest charge tolerance */
6362             where decode(trx.charge_line_type,
6363                          'INTEREST', nvl(trx.min_interest_charge,0),
6364                          'PENALTY',nvl(trx.late_charge_amount,0)) <= nvl(trx.late_charge_amount,0)
6365              and mod(nvl(trx.customer_site_use_id,0),p_total_workers) =
6366                                           decode(p_total_workers,p_worker_number,0,p_worker_number)
6367              and trx.payment_schedule_id = int_tab.payment_schedule_id
6368              and hdr.customer_id = trx.customer_id
6369              and hdr.customer_site_use_id = trx.customer_site_use_id
6370              and hdr.currency_code = trx.currency_code
6371              and nvl(hdr.legal_entity_id,-99) = nvl(trx.legal_entity_id,-99)
6372              and hdr.late_charge_type = trx.late_charge_type
6373              and hdr.org_id = trx.org_id
6374              and trx.charge_type = 'AVERAGE_DAILY_BALANCE'
6375              and hdr.payment_schedule_id = decode(trx.late_charge_type,'INV',-99,trx.payment_schedule_id)) a )b);
6376 
6377    IF l_debug_flag = 'Y' THEN
6378       debug( 'ar_calc_late_charge.insert_int_lines_adb()-' );
6379    END IF;
6380     --
6381    EXCEPTION
6382      WHEN  OTHERS THEN
6383         --IF l_debug_flag = 'Y' THEN
6384             debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
6385             debug('EXCEPTION: ar_calc_late_charge.insert_int_lines_adb');
6386         --END IF;
6387         RAISE;
6388 END insert_int_lines_adb;
6389 
6390 PROCEDURE delete_empty_batches IS
6391 BEGIN
6392     IF l_debug_flag = 'Y' THEN
6393       debug('ar_calc_late_charge.delete_empty_batches()+');
6394     END IF;
6395 
6396     delete from ar_interest_batches bat
6397     where not exists (select interest_header_id
6398                        from  ar_interest_headers hdr
6399                        where bat.interest_batch_id = hdr.interest_batch_id)
6400     and ( request_id = l_request_id
6401          OR batch_status = 'D') ;
6402 
6403     IF l_debug_flag = 'Y' THEN
6404       debug('ar_calc_late_charge.delete_empty_batches()-');
6405     END IF;
6406 EXCEPTION WHEN OTHERS THEN
6407     --IF l_debug_flag = 'Y' THEN
6408        debug('EXCEPTION : '||SQLCODE||' : '||SQLERRM);
6409        debug('EXCEPTION:  ar_calc_late_charge.delete_empty_batches()');
6410     --END IF;
6411 END delete_empty_batches;
6412 
6413 PROCEDURE lock_batches IS
6414 
6415   CURSOR c_lock IS
6416     select interest_batch_id, batch_name, transferred_status
6417       from ar_interest_batches
6418      where request_id = l_request_id
6419      for update of transferred_status nowait;
6420 
6421   TYPE l_int_batch_rec_type IS RECORD(
6422                 interest_batch_id       DBMS_SQL.NUMBER_TABLE,
6423                 batch_name              DBMS_SQL.VARCHAR2_TABLE,
6424                 transferred_status      DBMS_SQL.VARCHAR2_TABLE);
6425 
6426   l_int_batch_tbl                         l_int_batch_rec_type;
6427   l_bulk_fetch_rows                       number := 1000;
6428   l_last_fetch_rows                       boolean := FALSE;
6429 
6430 BEGIN
6431     debug('ar_calc_late_charge.lock_batches ()+');
6432 
6433     OPEN c_lock;
6434 
6435     LOOP
6436         FETCH c_lock BULK COLLECT INTO
6437             l_int_batch_tbl
6438         LIMIT l_bulk_fetch_rows;
6439 
6440         IF c_lock%NOTFOUND  THEN
6441            EXIT;
6442         END IF;
6443     END LOOP;
6444     CLOSE c_lock;
6445 
6446     debug('ar_calc_late_charge.lock_batches ()-');
6447 EXCEPTION
6448    WHEN OTHERS THEN
6449      debug('EXCEPTION : ar_calc_late_charge.lock_batches ()');
6450      debug('EXCEPTION : '||SQLCODE ||' : '||SQLERRM);
6451    RAISE;
6452 END lock_batches;
6453 
6454 
6455 PROCEDURE debug_cust_sites IS
6456  CURSOR customer_sites_cur IS
6457        SELECT   org_id,
6458 		lc_cust_sites_id,
6459                 customer_id,
6460                 customer_site_use_id,
6461                 currency_code,
6462                 late_charge_calculation_trx,
6463                 credit_items_flag,
6464                 disputed_transactions_flag,
6465                 payment_grace_days,
6466                 late_charge_type,
6467                 late_charge_term_id ,
6468                 interest_period_days,
6469                 interest_calculation_period,
6470                 charge_on_finance_charge_flag,
6471                 hold_charged_invoices_flag,
6472                 message_text_id,
6473                 multiple_interest_rates_flag,
6474                 charge_begin_date,
6475                 cust_acct_profile_amt_id,
6476                 exchange_rate_type,
6477                 min_fc_invoice_overdue_type,
6478                 min_fc_invoice_amount,
6479                 min_fc_invoice_percent,
6480                 min_fc_balance_overdue_type,
6481                 min_fc_balance_amount,
6482                 min_fc_balance_percent,
6483                 min_interest_charge,
6484                 max_interest_charge,
6485                 interest_type,
6486                 interest_Rate,
6487                 interest_fixed_amount,
6488                 interest_schedule_id,
6489                 penalty_type,
6490                 penalty_rate,
6491                 penalty_fixed_amount,
6492                 penalty_schedule_id,
6493                 last_accrue_charge_date
6494        FROM  ar_lc_cust_sites_t
6495        ORDER BY org_id,
6496 		customer_id,
6497                 customer_site_use_id,
6498                 currency_code;
6499 
6500 TYPE l_customer_sites_rec_type IS RECORD(
6501           org_id			DBMS_SQL.NUMBER_TABLE,
6502           lc_cust_sites_id	DBMS_SQL.NUMBER_TABLE,
6503           customer_id			DBMS_SQL.NUMBER_TABLE,
6504           customer_site_use_id		DBMS_SQL.NUMBER_TABLE,
6505           currency_code			DBMS_SQL.VARCHAR2_TABLE,
6506           late_charge_calculation_trx	DBMS_SQL.VARCHAR2_TABLE,
6507           credit_items_flag		DBMS_SQL.VARCHAR2_TABLE,
6508           disputed_transactions_flag	DBMS_SQL.VARCHAR2_TABLE,
6509           payment_grace_days		DBMS_SQL.NUMBER_TABLE,
6510           late_charge_type		DBMS_SQL.VARCHAR2_TABLE,
6511           late_charge_term_id		DBMS_SQL.NUMBER_TABLE,
6512           interest_period_days		DBMS_SQL.NUMBER_TABLE,
6513           interest_calculation_period	DBMS_SQL.VARCHAR2_TABLE,
6514           charge_on_finance_charge_flag	DBMS_SQL.VARCHAR2_TABLE,
6515           hold_charged_invoices_flag	DBMS_SQL.VARCHAR2_TABLE,
6516           message_text_id		DBMS_SQL.NUMBER_TABLE,
6517           multiple_interest_rates_flag	DBMS_SQL.VARCHAR2_TABLE,
6518           charge_begin_date		DBMS_SQL.DATE_TABLE,
6519           cust_acct_profile_amt_id	DBMS_SQL.NUMBER_TABLE,
6520           exchange_rate_type		DBMS_SQL.VARCHAR2_TABLE,
6521           min_fc_invoice_overdue_type	DBMS_SQL.VARCHAR2_TABLE,
6522           min_fc_invoice_amount		DBMS_SQL.NUMBER_TABLE,
6523           min_fc_invoice_percent	DBMS_SQL.NUMBER_TABLE,
6524           min_fc_balance_overdue_type	DBMS_SQL.VARCHAR2_TABLE,
6525           min_fc_balance_amount		DBMS_SQL.NUMBER_TABLE,
6526           min_fc_balance_percent	DBMS_SQL.NUMBER_TABLE,
6527           min_interest_charge		DBMS_SQL.NUMBER_TABLE,
6528           max_interest_charge		DBMS_SQL.NUMBER_TABLE,
6529           interest_type			DBMS_SQL.VARCHAR2_TABLE,
6530           interest_Rate			DBMS_SQL.NUMBER_TABLE,
6531           interest_fixed_amount		DBMS_SQL.NUMBER_TABLE,
6532           interest_schedule_id		DBMS_SQL.NUMBER_TABLE,
6533           penalty_type			DBMS_SQL.VARCHAR2_TABLE,
6534           penalty_rate			DBMS_SQL.NUMBER_TABLE,
6535           penalty_fixed_amount		DBMS_SQL.NUMBER_TABLE,
6536           penalty_schedule_id		DBMS_SQL.NUMBER_TABLE,
6537           last_accrue_charge_date	DBMS_SQL.DATE_TABLE);
6538 
6539 l_lc_cust_sites_tbl             	l_customer_sites_rec_type;
6540 l_bulk_fetch_rows			number := 1000;
6541 l_last_fetch_rows			boolean := FALSE;
6542 
6543 BEGIN
6544    OPEN customer_sites_cur;
6545    LOOP
6546         FETCH customer_sites_cur BULK COLLECT INTO
6547             l_lc_cust_sites_tbl
6548         LIMIT l_bulk_fetch_rows;
6549 
6550         IF customer_sites_cur%NOTFOUND THEN
6551             l_last_fetch_rows := TRUE;
6552         END IF;
6553 
6554         IF (l_lc_cust_sites_tbl.lc_cust_sites_id.COUNT = 0) AND (l_last_fetch_rows) THEN
6555           debug('Customer Sites Cursor: ' || 'COUNT = 0 and LAST FETCH ');
6556           EXIT;
6557         END IF;
6558 
6559         IF l_lc_cust_sites_tbl.lc_cust_sites_id.COUNT > 0 THEN
6560           debug('Set Up Information of the Selected Customers');
6561           FOR i IN 1 .. l_lc_cust_sites_tbl.lc_cust_sites_id.LAST LOOP
6562             debug('======================================================');
6563 	    debug('Org_ID			:	'||l_lc_cust_sites_tbl.org_id(i));
6564             debug('Customer_ID 			:	'||l_lc_cust_sites_tbl.customer_id(i));
6565             debug('customer_site_use_id		:	'||l_lc_cust_sites_tbl.customer_site_use_id(i));
6566             debug('currency_code		:	'||l_lc_cust_sites_tbl.currency_code(i));
6567             debug('late_charge_calculation_trx	:	'||l_lc_cust_sites_tbl.late_charge_calculation_trx(i));
6568             debug('credit_items_flag		:	'||l_lc_cust_sites_tbl.credit_items_flag(i));
6569             debug('disputed_transactions_flag	:	'||l_lc_cust_sites_tbl.disputed_transactions_flag(i));
6570             debug('payment_grace_days		:	'||l_lc_cust_sites_tbl.payment_grace_days(i));
6571             debug('late_charge_type		:	'||l_lc_cust_sites_tbl.late_charge_type(i));
6572             debug('late_charge_term_id 		:	'||l_lc_cust_sites_tbl.late_charge_term_id(i));
6573             debug('interest_period_days		:	'||l_lc_cust_sites_tbl.interest_period_days(i));
6574             debug('interest_calculation_period	:	'||l_lc_cust_sites_tbl.interest_calculation_period(i));
6575             debug('charge_on_finance_charge_flag:	'||l_lc_cust_sites_tbl.charge_on_finance_charge_flag(i));
6576             debug('hold_charged_invoices_flag	:	'||l_lc_cust_sites_tbl.hold_charged_invoices_flag(i));
6577             debug('message_text_id		:	'||l_lc_cust_sites_tbl.message_text_id(i));
6578             debug('multiple_interest_rates_flag	:	'||l_lc_cust_sites_tbl.multiple_interest_rates_flag(i));
6579             debug('charge_begin_date		:	'||l_lc_cust_sites_tbl.charge_begin_date(i));
6580             debug('cust_acct_profile_amt_id	:	'||l_lc_cust_sites_tbl.cust_acct_profile_amt_id(i));
6581             debug('exchange_rate_type		:	'||l_lc_cust_sites_tbl.exchange_rate_type(i));
6582             debug('min_fc_invoice_overdue_type	:	'||l_lc_cust_sites_tbl.min_fc_invoice_overdue_type(i));
6583             debug('min_fc_invoice_amount	:	'||l_lc_cust_sites_tbl.min_fc_invoice_amount(i));
6584             debug('min_fc_invoice_percent	:	'||l_lc_cust_sites_tbl.min_fc_invoice_percent(i));
6585             debug('min_fc_balance_overdue_type	:	'||l_lc_cust_sites_tbl.min_fc_balance_overdue_type(i));
6586             debug('min_fc_balance_amount	:	'||l_lc_cust_sites_tbl.min_fc_balance_amount(i));
6587             debug('min_fc_balance_percent	:	'||l_lc_cust_sites_tbl.min_fc_balance_percent(i));
6588             debug('min_interest_charge		:	'||l_lc_cust_sites_tbl.min_interest_charge(i));
6589             debug('max_interest_charge		:	'||l_lc_cust_sites_tbl.max_interest_charge(i));
6590             debug('interest_type		:	'||l_lc_cust_sites_tbl.interest_type(i));
6591             debug('interest_Rate		:	'||l_lc_cust_sites_tbl.interest_Rate(i));
6592             debug('interest_fixed_amount	:	'||l_lc_cust_sites_tbl.interest_fixed_amount(i));
6593             debug('interest_schedule_id		:	'||l_lc_cust_sites_tbl.interest_schedule_id(i));
6594             debug('penalty_type			:	'||l_lc_cust_sites_tbl.penalty_type(i));
6595             debug('penalty_rate			:	'||l_lc_cust_sites_tbl.penalty_rate(i));
6596             debug('penalty_fixed_amount		:	'||l_lc_cust_sites_tbl.penalty_fixed_amount(i));
6597             debug('penalty_schedule_id		:	'||l_lc_cust_sites_tbl.penalty_schedule_id(i));
6598             debug('last_accrue_charge_date	:	'||l_lc_cust_sites_tbl.last_accrue_charge_date(i));
6599           END LOOP;
6600         END IF;
6601         IF l_last_fetch_rows THEN
6602            EXIT;
6603         END IF;
6604    END LOOP;
6605    CLOSE customer_sites_cur;
6606 END debug_cust_sites;
6607 
6608 PROCEDURE debug_customer_balances IS
6609 CURSOR cust_balance_cur IS
6610        select   org_id,
6611 		customer_id,
6612                 customer_site_use_id,
6613                 currency_code,
6614                 customer_open_balance,
6615                 customer_overdue_balance
6616        from  ar_late_charge_cust_balance_gt
6617        order by org_id,
6618 		customer_id,
6619                 customer_site_use_id,
6620                 currency_code;
6621 
6622 TYPE l_cust_balance_type IS RECORD(
6623 		org_id				DBMS_SQL.NUMBER_TABLE,
6624 		customer_id			DBMS_SQL.NUMBER_TABLE,
6625                 customer_site_use_id		DBMS_SQL.NUMBER_TABLE,
6626                 currency_code			DBMS_SQL.VARCHAR2_TABLE,
6627                 customer_open_balance		DBMS_SQL.NUMBER_TABLE,
6628                 customer_overdue_balance	DBMS_SQL.NUMBER_TABLE);
6629 
6630 l_cust_balance_tbl                 	l_cust_balance_type;
6631 l_bulk_fetch_rows			number := 1000;
6632 l_last_fetch_rows			boolean := FALSE;
6633 
6634 BEGIN
6635    OPEN cust_balance_cur;
6636    LOOP
6637         FETCH cust_balance_cur BULK COLLECT INTO
6638             l_cust_balance_tbl
6639         LIMIT l_bulk_fetch_rows;
6640 
6641         IF cust_balance_cur%NOTFOUND THEN
6642             l_last_fetch_rows := TRUE;
6643         END IF;
6644 
6645         IF (l_cust_balance_tbl.customer_id.COUNT = 0) AND (l_last_fetch_rows) THEN
6646           debug('Customer Balances Cursor: ' || 'COUNT = 0 and LAST FETCH ');
6647           EXIT;
6648         END IF;
6649 
6650         IF l_cust_balance_tbl.customer_id.COUNT > 0 THEN
6651           debug('Balance Information of the selected customers');
6652 
6653           FOR i IN 1 .. l_cust_balance_tbl.customer_id.COUNT LOOP
6654             debug('==================================================');
6655             debug('org_id			:	'||l_cust_balance_tbl.org_id(i));
6656             debug('customer_id 			:	'||l_cust_balance_tbl.customer_id(i));
6657             debug('customer_site_use_id 	:	'||l_cust_balance_tbl.customer_site_use_id(i));
6658             debug('currency_code 		:	'||l_cust_balance_tbl.currency_code(i));
6659             debug('customer_open_balance	:	'||l_cust_balance_tbl.customer_open_balance(i));
6660             debug('customer_overdue_balance	:	'||l_cust_balance_tbl.customer_overdue_balance(i));
6661           END LOOP;
6662         END IF;
6663         IF l_last_fetch_rows THEN
6664            EXIT;
6665         END IF;
6666    END LOOP;
6667    CLOSE cust_balance_cur;
6668 
6669 END debug_customer_balances;
6670 
6671 PROCEDURE debug_credit_amts IS
6672 CURSOR cust_credits_cur IS
6673        select   customer_id,
6674                 customer_site_use_id,
6675                 currency_code,
6676                 legal_entity_id,
6677                 credit_amount
6678        from ar_late_charge_credits_gt
6679        order by customer_id,
6680                 customer_site_use_id,
6681                 currency_code,
6682                 legal_entity_id;
6683 
6684 TYPE l_cust_credits_rec_type IS RECORD(
6685 		customer_id		DBMS_SQL.NUMBER_TABLE,
6686                 customer_site_use_id	DBMS_SQL.NUMBER_TABLE,
6687                 currency_code		DBMS_SQL.VARCHAR2_TABLE,
6688                 legal_entity_id		DBMS_SQL.NUMBER_TABLE,
6689                 credit_amount		DBMS_SQL.NUMBER_TABLE);
6690 
6691 l_cust_credits_tbl                 	l_cust_credits_rec_type;
6692 l_bulk_fetch_rows			number := 1000;
6693 l_last_fetch_rows			boolean := FALSE;
6694 
6695 BEGIN
6696    OPEN cust_credits_cur;
6697    LOOP
6698         FETCH cust_credits_cur BULK COLLECT INTO
6699             l_cust_credits_tbl
6700         LIMIT l_bulk_fetch_rows;
6701 
6702         IF cust_credits_cur%NOTFOUND THEN
6703             l_last_fetch_rows := TRUE;
6704         END IF;
6705 
6706         IF (l_cust_credits_tbl.customer_id.COUNT = 0) AND (l_last_fetch_rows) THEN
6707           debug('Credits Cursor: ' || 'COUNT = 0 and LAST FETCH ');
6708           EXIT;
6709         END IF;
6710 
6711         IF l_cust_credits_tbl.customer_id.COUNT > 0 THEN
6712           debug('Credit Information of the selected customers');
6713 
6714           FOR i IN 1 .. l_cust_credits_tbl.customer_id.COUNT LOOP
6715             debug('==================================================');
6716             debug('customer_id 			:	'||l_cust_credits_tbl.customer_id(i));
6717             debug('customer_site_use_id 	:	'||l_cust_credits_tbl.customer_site_use_id(i));
6718             debug('currency_code 		:	'||l_cust_credits_tbl.currency_code(i));
6719             debug('legal_entity_id 		:	'||l_cust_credits_tbl.legal_entity_id(i));
6720             debug('credit amount 		:	'||l_cust_credits_tbl.credit_amount(i));
6721           END LOOP;
6722         END IF;
6723         IF l_last_fetch_rows THEN
6724            EXIT;
6725         END IF;
6726    END LOOP;
6727    CLOSE cust_credits_cur;
6728 END debug_credit_amts;
6729 
6730 PROCEDURE debug_payment_schedules IS
6731 CURSOR payment_schedules_cur IS
6732         select   late_charge_trx_id,
6733                  customer_id,
6734                  customer_site_use_id,
6735                  currency_code,
6736                  customer_trx_id,
6737                  legal_entity_id,
6738                  payment_schedule_id,
6739                  class,
6740                  amount_due_original,
6741                  amount_due_remaining,
6742                  fin_charge_charged,
6743                  trx_date,
6744                  cust_trx_type_id,
6745                  last_charge_date,
6746                  exchange_rate_type,
6747                  min_interest_charge,
6748                  max_interest_charge,
6749                  overdue_late_pay_amount,
6750                  original_balance,
6751                  due_date,
6752                  receipt_date,
6753                  finance_charge_date,
6754                  charge_type,
6755                  actual_date_closed,
6756                  interest_rate,
6757                  interest_days,
6758                  rate_start_date,
6759                  rate_end_date,
6760                  schedule_days_start,
6761                  schedule_days_to,
6762                  late_charge_amount,
6763                  late_charge_type,
6764                  late_charge_term_id,
6765                  interest_period_days,
6766                  interest_calculation_period,
6767                  charge_on_finance_charge_flag,
6768                  message_text_id,
6769                  interest_type,
6770                  min_fc_invoice_overdue_type,
6771                  min_fc_invoice_amount,
6772                  min_fc_invoice_percent,
6773                  charge_line_type
6774        from ar_late_charge_trx_t
6775        order by customer_id,
6776                 customer_site_use_id,
6777                 currency_code,
6778                 legal_entity_id,
6779                 due_date,
6780                 payment_schedule_id,
6781                 rate_start_date,
6782                 charge_line_type;
6783 
6784 TYPE l_payment_schedules_rec_type IS RECORD(
6785 		late_charge_trx_id		DBMS_SQL.NUMBER_TABLE,
6786 		customer_id			DBMS_SQL.NUMBER_TABLE,
6787                 customer_site_use_id		DBMS_SQL.NUMBER_TABLE,
6788                 currency_code			DBMS_SQL.VARCHAR2_TABLE,
6789                 customer_trx_id			DBMS_SQL.NUMBER_TABLE,
6790                 legal_entity_id			DBMS_SQL.NUMBER_TABLE,
6791                 payment_schedule_id		DBMS_SQL.NUMBER_TABLE,
6792                 class				DBMS_SQL.VARCHAR2_TABLE,
6793                 amount_due_original		DBMS_SQL.NUMBER_TABLE,
6794                 amount_due_remaining		DBMS_SQL.NUMBER_TABLE,
6795                 fin_charge_charged		DBMS_SQL.NUMBER_TABLE,
6796                 trx_date			DBMS_SQL.DATE_TABLE,
6797                 cust_trx_type_id		DBMS_SQL.NUMBER_TABLE,
6798                 last_charge_date		DBMS_SQL.DATE_TABLE,
6799                 exchange_rate_type		DBMS_SQL.VARCHAR2_TABLE,
6800                 min_interest_charge		DBMS_SQL.NUMBER_TABLE,
6801                 max_interest_charge		DBMS_SQL.NUMBER_TABLE,
6802                 overdue_late_pay_amount		DBMS_SQL.NUMBER_TABLE,
6803                 original_balance		DBMS_SQL.NUMBER_TABLE,
6804                 due_date			DBMS_SQL.DATE_TABLE,
6805                 receipt_date			DBMS_SQL.DATE_TABLE,
6806                 finance_charge_date		DBMS_SQL.DATE_TABLE,
6807                 charge_type			DBMS_SQL.VARCHAR2_TABLE,
6808                 actual_date_closed		DBMS_SQL.DATE_TABLE,
6809                 interest_rate			DBMS_SQL.NUMBER_TABLE,
6810                 interest_days			DBMS_SQL.NUMBER_TABLE,
6811                 rate_start_date			DBMS_SQL.DATE_TABLE,
6812                 rate_end_date			DBMS_SQL.DATE_TABLE,
6813                 schedule_days_start		DBMS_SQL.NUMBER_TABLE,
6814                 schedule_days_to		DBMS_SQL.NUMBER_TABLE,
6815                 late_charge_amount		DBMS_SQL.NUMBER_TABLE,
6816                 late_charge_type		DBMS_SQL.VARCHAR2_TABLE,
6817                 late_charge_term_id		DBMS_SQL.NUMBER_TABLE,
6818                 interest_period_days		DBMS_SQL.NUMBER_TABLE,
6819                 interest_calculation_period	DBMS_SQL.VARCHAR2_TABLE,
6820                 charge_on_finance_charge_flag	DBMS_SQL.VARCHAR2_TABLE,
6821                 message_text_id			DBMS_SQL.NUMBER_TABLE,
6822                 interest_type			DBMS_SQL.VARCHAR2_TABLE,
6823                 min_fc_invoice_overdue_type	DBMS_SQL.VARCHAR2_TABLE,
6824                 min_fc_invoice_amount		DBMS_SQL.NUMBER_TABLE,
6825                 min_fc_invoice_percent		DBMS_SQL.VARCHAR2_TABLE,
6826                 charge_line_type		DBMS_SQL.VARCHAR2_TABLE);
6827 
6828 l_payment_schedules_tbl                 l_payment_schedules_rec_type;
6829 l_bulk_fetch_rows			number := 1000;
6830 l_last_fetch_rows			boolean := FALSE;
6831 
6832 BEGIN
6833    OPEN payment_schedules_cur;
6834    LOOP
6835         FETCH payment_schedules_cur BULK COLLECT INTO
6836             l_payment_schedules_tbl
6837         LIMIT l_bulk_fetch_rows;
6838 
6839         IF payment_schedules_cur%NOTFOUND THEN
6840             l_last_fetch_rows := TRUE;
6841         END IF;
6842 
6843         IF (l_payment_schedules_tbl.late_charge_trx_id.COUNT = 0) AND (l_last_fetch_rows) THEN
6844           debug('Payment Schedules Cursor: ' || 'COUNT = 0 and LAST FETCH ');
6845           EXIT;
6846         END IF;
6847 
6848         IF l_payment_schedules_tbl.late_charge_trx_id.COUNT > 0 THEN
6849           debug('Selected Payment schedule IDs and the details');
6850 
6851           FOR i IN 1 .. l_payment_schedules_tbl.late_charge_trx_id.COUNT LOOP
6852             debug('==================================================');
6853             debug('customer_id 			:	'||l_payment_schedules_tbl.customer_id(i));
6854             debug('customer_site_use_id 	:	'||l_payment_schedules_tbl.customer_site_use_id(i));
6855             debug('currency_code 		:	'||l_payment_schedules_tbl.currency_code(i));
6856             debug('customer_trx_id 		:	'||l_payment_schedules_tbl.customer_trx_id(i));
6857             debug('legal_entity_id 		:	'||l_payment_schedules_tbl.legal_entity_id(i));
6858             debug('payment_schedule_id 		:	'||l_payment_schedules_tbl.payment_schedule_id(i));
6859             debug('class 			:	'||l_payment_schedules_tbl.class(i));
6860             debug('amount_due_original 		:	'||l_payment_schedules_tbl.amount_due_original(i));
6861             debug('amount_due_remaining 	:	'||l_payment_schedules_tbl.amount_due_remaining(i));
6862             debug('fin_charge_charged 		:	'||l_payment_schedules_tbl.fin_charge_charged(i));
6863             debug('trx_date 			:	'||l_payment_schedules_tbl.trx_date(i));
6864             debug('cust_trx_type_id 		:	'||l_payment_schedules_tbl.cust_trx_type_id(i));
6865             debug('last_charge_date 		:	'||l_payment_schedules_tbl.last_charge_date(i));
6866             debug('exchange_rate_type 		:	'||l_payment_schedules_tbl.exchange_rate_type(i));
6867             debug('min_interest_charge 		:	'||l_payment_schedules_tbl.min_interest_charge(i));
6868             debug('max_interest_charge 		:	'||l_payment_schedules_tbl.max_interest_charge(i));
6869             debug('overdue_late_pay_amount 	:	'||l_payment_schedules_tbl.overdue_late_pay_amount(i));
6870             debug('original_balance 		:	'||l_payment_schedules_tbl.original_balance(i));
6871             debug('due_date 			:	'||l_payment_schedules_tbl.due_date(i));
6872             debug('receipt_date 		:	'||l_payment_schedules_tbl.receipt_date(i));
6873             debug('finance_charge_date 		:	'||l_payment_schedules_tbl.finance_charge_date(i));
6874             debug('charge_type 			:	'||l_payment_schedules_tbl.charge_type(i));
6875             debug('actual_date_closed 		:	'||l_payment_schedules_tbl.actual_date_closed(i));
6876             debug('interest_rate 		:	'||l_payment_schedules_tbl.interest_rate(i));
6877             debug('interest_days 		:	'||l_payment_schedules_tbl.interest_days(i));
6878             debug('rate_start_date 		:	'||l_payment_schedules_tbl.rate_start_date(i));
6879             debug('rate_end_date 		:	'||l_payment_schedules_tbl.rate_end_date(i));
6880             debug('schedule_days_start 		:	'||l_payment_schedules_tbl.schedule_days_start(i));
6881             debug('schedule_days_to 		:	'||l_payment_schedules_tbl.schedule_days_to(i));
6882             debug('late_charge_amount 		:	'||l_payment_schedules_tbl.late_charge_amount(i));
6883             debug('late_charge_type 		:	'||l_payment_schedules_tbl.late_charge_type(i));
6884             debug('late_charge_term_id 		:	'||l_payment_schedules_tbl.late_charge_term_id(i));
6885             debug('interest_period_days 	:	'||l_payment_schedules_tbl.interest_period_days(i));
6886             debug('interest_calculation_period 	:	'||l_payment_schedules_tbl.interest_calculation_period(i));
6887             debug('charge_on_finance_charge_flag:	'||l_payment_schedules_tbl.charge_on_finance_charge_flag(i));
6888             debug('message_text_id 		:	'||l_payment_schedules_tbl.message_text_id(i));
6889             debug('interest_type 		:	'||l_payment_schedules_tbl.interest_type(i));
6890             debug('min_fc_invoice_overdue_type 	:	'||l_payment_schedules_tbl.min_fc_invoice_overdue_type(i));
6891             debug('min_fc_invoice_amount 	:	'||l_payment_schedules_tbl.min_fc_invoice_amount(i));
6892             debug('min_fc_invoice_percent 	:	'||l_payment_schedules_tbl.min_fc_invoice_percent(i));
6893             debug('charge_line_type 		:	'||l_payment_schedules_tbl.charge_line_type(i));
6894           END LOOP;
6895         END IF;
6896         IF l_last_fetch_rows THEN
6897            EXIT;
6898         END IF;
6899    END LOOP;
6900    CLOSE payment_schedules_cur;
6901 
6902 END debug_payment_schedules;
6903 /*=========================================================================================+
6904  | PUBLIC PROCEDURE CREATE_LATE_CHARGE_DOCUMENT                                            |
6905  |                                                                                         |
6906  | DESCRIPTION                                                                             |
6907  |                                                                                         |
6908  |   This procedure is called from the concurrent program to generate late charges         |
6909  |   associated with overdue invoices or late payments                                     |
6910  |                                                                                         |
6911  | PSEUDO CODE/LOGIC                                                                       |
6912  |                                                                                         |
6913  | The whole logic can be split in the following way                                       |
6914  |   1)  Create Adjustments / Debit Memo                                                   |
6915  |       a) For Overdue and Average Daily Balance, the open credit items should be         |
6916  |          applied to the oldest invoice first                                            |
6917  |       b) For Late Payments, credit items need not be considered as we are tracking      |
6918  |          only the late applications                                                     |
6919  |   2)  Create Interest Invoices                                                          |
6920  |       Credit items should be treated as any other debit item. Interest and Penalty      |
6921  |       should be computed on these, but no tolerance applied                             |
6922  |                                                                                         |
6923  | General Notes:                                                                          |
6924  |                                                                                         |
6925  | 1. Hold Charged Invoices : Interest should be calculated only once on any item.         |
6926  |    How to determine this? 11i Interest Invoice feature uses ps.last_charge_date to      |
6927  |    store the last date on which interest is calculated on a payment_schedule. So if this|
6928  |    is populated, we can assume that Interest Invoice was created on this payment        |
6929  |    schedule. 11i AR Finance Charge functionality uses the field last_accrue_charge_date |
6930  |    in hz_cust_site_uses to store the last date on which Finance Charge was computed on  |
6931  |    the invoices of a given customer site use. Such finance charges will be created as   |
6932  |    Adjustments and can be derived from ar_adjustments. If any of these two conditions   |
6933  |    are satisfied, the payment_schedule is treated as if Interest was computed on it.    |
6934  |    If hold_charged_invoices_flag = 'Y' then                                             |
6935  |       ps.last_charge_date should be NULL                                                |
6936  |       AND fin_charge_charged should be Zero                                             |
6937  |    for a payment schedule to become eligibale for finance charge computation            |
6938  |                                                                                         |
6939  | 2. Calculation of days late: While fetching the eligible items, the payment_grace_days  |
6940  |    should be added to the due_date. But if the item has crossed the due_date +          |
6941  |    payment_grace_days, the days_late should be computed from the original due_date      |
6942  |    without considering the payment_grace_days                                           |
6943  |                                                                                         |
6944  | 3. Use Multiple Interest Rates : If this option is selected, and there are multiple     |
6945  |    interest rates applicable during the period from the due_date to the finance charge  |
6946  |    date, the interest will be calculated using all the applicable rates considering the |
6947  |    corresponding days. This option is used only if the Interest is defined as a         |
6948  |    percentage rate. If fixed amounts are applicable during this period, only the rate   |
6949  |    applicable as of the finance charge date is considered. If this option is unchecked, |
6950  |    the rate / amount applicable as of the finance charge date is considered.            |
6951  |    It is also to be noted that the multiple interest rates are used only for the        |
6952  |    interest computation and not for the penalty computation                             |
6953  |                                                                                         |
6954  | 4. For Receipts, the maturity_date is stored in the column due_date in payment schedules|
6955  |    So, the receipt date should be considered instead of the due_date for receipts       |
6956  |                                                                                         |
6957  | 5. If the interest definition is to use amount and not rate (either as fixed amount or  |
6958  |    as a schedule), and we are computing interest on a credit item, the interest amount  |
6959  |    should be multiplied by -1.                                                          |
6960  |                                                                                         |
6961  | 6. Simple Vs. Compound Interest : If Compound Interest has to be computed, the balance  |
6962  |    can be computed based on the amount_due_remaining in payment schedules. Otherwise,the|
6963  |    previously charged finance charge has to be deducted from amount_due_remaining. This |
6964  |    is the case the finance charges were created as Adjustments.                         |
6965  |    If we are creating interest invoices or Debit memos, then we have separate documents |
6966  |    having their own due dates. So these will always have interest on them - and this is |
6967  |    compound interest. We wouldn't compound the amount onto the original transaction     |
6968  |    because we have created a new transaction and we are charging the additional interest|
6969  |    on that.So to have simple interest, you would have to ensure that the interest       |
6970  |    invoice transaction type was excluded from finance charges - so that interest is not |
6971  |    calculated on the interest.                                                          |
6972  |                                                                                         |
6973  | 7. Penalty is computed on the computed Interest                                         |
6974  |                                                                                         |
6975  | 8. Tolerances are applied only on the Interest and not on the Penalty. i.e.Penalty is   |
6976  |    is levied regardless of the maximum tolerances. Only the interest charge is validated|
6977  |    against the maximum charge tolerances                                                |
6978  |                                                                                         |
6979  | 9. Interest Calculation Period : Daily Vs Monthly                                       |
6980  |    While using Daily method, the interest will be calculated exactly on the number of   |
6981  |    days between the due date and the finance charge date. On the other hand, if Monthly |
6982  |    method is used, interest will be calculated for the number of days between the first |
6983  |    day of the month corresponding to due_date to the last day of the month corresponding|
6984  |    to the finance_charge_date                                                           |
6985  |                                                                                         |
6986  |10. Application of Tolerances                                                            |
6987  |    1. Customer Level Tolerances : This could be a fixed amount or a Percentage          |
6988  |       Since this set up is done at profile amount level, this is applicable for a       |
6989  |       customer, site and currency combination.                                          |
6990  |       a) Fixed Amount :  If the set up is Amount, it means that the customer should be  |
6991  |          charged an interest only if the total overdue balance for this customer, site  |
6992  |          and currency combination is greater than or equal to the amount mentioned in   |
6993  |          the set up.                                                                    |
6994  |       b) Percentage : This means that, the customer should be changed an interest only  |
6995  |          if the total overdue balance for this customer , site and currency combination |
6996  |          is greater than or equal to the given percentage of the total open balance for |
6997  |          this customer, site and currency combination.                                  |
6998  |       Overdue Balance : Is the sum of balances of the debit and credit items which are  |
6999  |       past due as of the finance charge date. These balances will be computed as of the |
7000  |       finance charge date                                                               |
7001  |       Open Balance : Is the sum of balances of the debit and credit items which are open|
7002  |       as of the finance charge date. These balances will be computed as of the finance  |
7003  |       charge date                                                                       |
7004  |       These computations are similar for Overdue Invoices and Late Payments. But for    |
7005  |       Average Daily Balance, the application of tolerances are completely differemt.    |
7006  |       For Overdue Invoices and Late Payments, consider the following example:           |
7007  |       Customer xyz has the following invoices                                           |
7008  |                                                                                         |
7009  |         a) invoice 101 for 1000 USD with trx_date of 01-Dec-2005 and due_date of        |
7010  |            01-Jan-2006.  There are  receipt applications on this invoice on 15-Jan-2006 |
7011  |            for 400 USD and  10-Feb-2006 for 600 USD                                     |
7012  |         b) Invoice 102 for 2000 USD with a trx_date of 01-Jan-2006 and due_date of      |
7013  |            01-Feb-2006. There are no applications on this invoice.                      |
7014  |                                                                                         |
7015  |       We are calculating the finance charge as of  31-Jan-2006. As of this date, the    |
7016  |       invoice 101 is overdue by 600 USD, where as the invoice 102 is open (but not      |
7017  |       overdue) by 2000 USD. So the overdue balance will be 600 USD and the open balance |
7018  |       will be 2600 USD.                                                                 |
7019  |                                                                                         |
7020  |    2. Invoice Level Tolerances :  Similar to the case above. Instead of the overdue     |
7021  |       customer balance, the overdue invoice amount will be used. Instead of the Open    |
7022  |       customer balance, the original invoice amount will be used (amount_due_original   |
7023  |       from ar_payment_schedules).                                                       |
7024  |                                                                                         |
7025  |       In my example above, as of 31-Jan-2006,  the invoice 101 is overdue by 600 USD and|
7026  |       the original invoice amount is 1000 USD . So 60% of this invoice is overdue as of |
7027  |       this date. Invoice 102 will not be considered as it is not overdue.               |
7028  |                                                                                         |
7029  |    3. Min and Max Interest Charges: These tolerances will be applied after the interest |
7030  |       is calculated. These will be applied only on the interest charged and not on the  |
7031  |       penalty. If the interest is less than the Min Interest Charge, no Interest or     |
7032  |       Penalty Records will be created for this Payment schedule. On the other hand, if  |
7033  |       the interest is more than the Max Interest Charge, the Interest portion will be   |
7034  |       limited to the maximum amount, but the Penalty will be computed on the actual     |
7035  |       Interest Charge.                                                                  |
7036  |       For example, the maximum interest is defined as 1000. The following interest      |
7037  |       charges and penalty cahrges are computed on a single payment schedule             |
7038  |       interest        interest_days    rate_start_date      rate_end_date    type       |
7039  |       --------        -------------    --------------      --------------   ------      |
7040  |        40.00             4             7-JUN-2005           10-JUN-2005      INTEREST   |
7041  |        60.00             5            11-JUN-2005           15-JUN-2005      INTEREST   |
7042  |        1320.00          240           16-JUN-2005                            INTEREST   |
7043  |        106.00           249           07-JUN-2005           10-JUN-2005      PENALTY    |
7044  |                                                                                         |
7045  |        After the application of the maximum interest tolerances, the following Interest |
7046  |        and penalty lines will be created                                                |
7047  |       interest        interest_days    rate_start_date      rate_end_date    type       |
7048  |       --------        -------------    --------------      --------------   ------      |
7049  |        40.00             4             7-JUN-2005           10-JUN-2005      INTEREST   |
7050  |        60.00             5            11-JUN-2005           15-JUN-2005      INTEREST   |
7051  |        900.00           240           16-JUN-2005                            INTEREST   |
7052  |        106.00           249           07-JUN-2005           10-JUN-2005      PENALTY    |
7053  |                                                                                         |
7054  | PARAMETERS                                                                              |
7055  |                                                                                         |
7056  |                                                                                         |
7057  | KNOWN ISSUES                                                                            |
7058  |                                                                                         |
7059  | NOTES                                                                                   |
7060  |                                                                                         |
7061  | MODIFICATION HISTORY                                                                    |
7062  | Date                  Author            Description of Changes                          |
7063  | 22-DEC-2005           rkader            Created                                         |
7064  |                                                                                         |
7065  *=========================================================================================*/
7066 
7067 PROCEDURE create_late_charge_document
7068 			(errbuf                 OUT NOCOPY VARCHAR2,
7069 			 retcode                OUT NOCOPY NUMBER,
7070                          p_operating_unit_id	IN	VARCHAR2,
7071                          p_customer_name_from   IN      VARCHAR2,
7072                          p_customer_name_to     IN      VARCHAR2,
7073                          p_customer_num_from    IN 	VARCHAR2,
7074                          p_customer_num_to      IN	VARCHAR2,
7075                          p_cust_site_use_id     IN      VARCHAR2,
7076                          p_gl_date              IN      VARCHAR2,
7077                          p_fin_charge_date      IN      VARCHAR2,
7078                          p_currency_code        IN      VARCHAR2,
7079                          p_mode			IN	VARCHAR2,
7080 			 p_disputed_items	IN	VARCHAR2,
7081                          p_called_from          IN      VARCHAR2,
7082                          p_enable_debug         IN      VARCHAR2,
7083                          p_worker_number        IN      VARCHAR2,
7084                          p_total_workers        IN      VARCHAR2,
7085 			 p_master_request_id	IN	VARCHAR2) IS
7086 
7087    l_org_id				 number(15);
7088    l_mode				 varchar2(1);
7089    l_customer_name_from  		 hz_parties.party_name%type;
7090    l_customer_name_to   		 hz_parties.party_name%type;
7091    l_customer_number_from                hz_cust_accounts.account_number%type;
7092    l_customer_number_to			 hz_cust_accounts.account_number%type;
7093    l_cust_site_use_id                    number;
7094    l_fin_charge_date                     date;
7095    l_gl_date                             date;
7096    l_compute_late_charge		 varchar2(1);
7097    l_currency_code			 varchar2(15);
7098    l_customer_id			 number;
7099    l_site_use_id			 number;
7100    l_set_of_books_id                     number;
7101    l_count_int_lines			 number;
7102    l_worker_number			 number;
7103    l_total_workers			 number;
7104    l_num_batches			 number;
7105    l_err_flag				 boolean := FALSE;
7106 BEGIN
7107 
7108    l_debug_flag 	:=	p_enable_debug;
7109 
7110    IF l_debug_flag = 'Y' THEN
7111         debug('ar_calc_late_charge.create_late_charge_document()+ ');
7112         debug('Global package variables');
7113         debug('pg_last_updated_by	: '||pg_last_updated_by);
7114 	debug('pg_last_update_login	: '||pg_last_update_login);
7115    END IF;
7116 
7117    IF l_debug_flag = 'Y' THEN
7118         debug('Input Parameters: ');
7119         debug('p_operating_unit_id   : '||p_operating_unit_id);
7120         debug('p_customer_name_from  : '||p_customer_name_from);
7121         debug('p_customer_name_to    : '||p_customer_name_to);
7122         debug('p_customer_number_from: '||p_customer_num_from);
7123         debug('p_customer_number_to  : '||p_customer_num_to);
7124         debug('p_site_use_id         : '||p_cust_site_use_id);
7125         debug('p_gl_date             : '||p_gl_date);
7126         debug('p_fin_charge_date     : '||p_fin_charge_date);
7127         debug('p_mode                : '||p_mode);
7128         debug('p_disputed_items      : '||p_disputed_items);
7129         debug('p_called_from         : '||p_called_from);
7130         debug('p_enable_debug        : '||p_enable_debug);
7131         debug('p_worker_number	     : '||p_worker_number);
7132         debug('p_total_workers       : '||p_total_workers);
7133  	debug('p_master_request_id   : '||p_master_request_id);
7134    END IF;
7135 
7136    l_org_id		      :=   p_operating_unit_id;
7137    l_customer_name_from       :=   p_customer_name_from;
7138    l_customer_name_to         :=   p_customer_name_to;
7139    l_customer_number_from     :=   p_customer_num_from;
7140    l_customer_number_to       :=   p_customer_num_to;
7141    l_cust_site_use_id         :=   p_cust_site_use_id;
7142    l_currency_code	      :=   p_currency_code;
7143    l_fin_charge_date          :=   fnd_date.canonical_to_date(p_fin_charge_date);
7144    l_gl_date                  :=   fnd_date.canonical_to_date(p_gl_date);
7145    l_mode		      :=   p_mode;
7146    l_disputed_items	      :=   p_disputed_items;
7147    l_worker_number	      :=   p_worker_number;
7148    l_total_workers            :=   p_total_workers;
7149    l_request_id		      :=   p_master_request_id; /* The master_request_id should be used for further processing */
7150 
7151    IF l_debug_flag  ='Y' THEN
7152       debug('Request ID 	:  '||l_request_id);
7153    END IF;
7154 
7155 /*
7156      select count(*)
7157      into l_num_batches
7158      from ar_interest_batches
7159      where request_id = l_request_id;
7160      debug('Number of batches found in ar_interest_batches for this request :  '||l_num_batches);
7161 */
7162 
7163    /* Check if late_charge calculation is enabled in system options */
7164    IF l_org_id IS NOT NULL THEN
7165       select allow_late_charges, set_of_books_id
7166       into   l_compute_late_charge, l_set_of_books_id
7167       from   ar_system_parameters
7168       where  org_id = l_org_id ;
7169       IF l_debug_flag = 'Y' THEN
7170          debug('Running the Program for a single Operating Unit');
7171          debug('Late Charge option in System Options 	: '||l_compute_late_charge);
7172     	 debug('Set of Books ID				: '||l_set_of_books_id);
7173       END IF;
7174    ELSE
7175       l_compute_late_charge := 'Y';
7176       IF l_debug_flag = 'Y' THEN
7177          debug('Running the program for multiple Operating Units, setting l_compute_late_charge to Y');
7178       END IF;
7179    END IF;
7180 
7181     /* Calculate interest only if the compute_late_charge is enabled in system
7182        options and there are no other batch with this name */
7183    IF l_compute_late_charge = 'Y'  THEN
7184 
7185         /* Identify the eligible customers, sites and the corresponding late charge policy
7186            set up */
7187 
7188          get_cust_late_charge_policy(p_org_id			=>	l_org_id,
7189      				     p_fin_charge_date		=>	l_fin_charge_date,
7190 				     p_customer_name_from	=>	l_customer_name_from,
7191 				     p_customer_name_to		=>	l_customer_name_to,
7192 				     p_customer_number_from	=>	l_customer_number_from,
7193 				     p_customer_number_to	=>	l_customer_number_to,
7194 				     p_currency_code		=>	l_currency_code,
7195 				     p_cust_site_use_id		=>	l_cust_site_use_id,
7196 				     p_worker_number		=>	l_worker_number,
7197 				     p_total_workers		=>	l_total_workers);
7198 
7199         /* Populate the table ar_late_charge_cust_balance_gt with the customer open balance
7200            and customer overdue balance for all the selected customer, site ,currency_code
7201            and org combination */
7202 
7203           insert_cust_balances(p_as_of_date         =>      l_fin_charge_date,
7204                                p_worker_number      =>      l_worker_number,
7205                                p_total_workers      =>      l_total_workers);
7206 
7207         /* If the late charge document is Adjustment or Debit Memo, the credit amount is summed
7208            up and inserted into ar_late_charge_credits_gt . These amounts should later be adjusted
7209            against the open debit items in the order of oldest invoice first.*/
7210 
7211          insert_credit_amount(p_fin_charge_date		=> 	l_fin_charge_date,
7212  			      p_worker_number           =>      l_worker_number,
7213                               p_total_workers           =>      l_total_workers);
7214 
7215         /* Overdue Invoices if Adjustment and Debit Memo have to be created.
7216            In this case, the overdue invoices are first applied against the credit amounts
7217            with the oldest invoice first. Oldest here means, the debit item having the oldest
7218            due date. The Interest is then calculated on the remaining balances  */
7219 
7220          insert_int_overdue_adj_dm(p_fin_charge_date	=>	l_fin_charge_date,
7221 				   p_worker_number      =>      l_worker_number,
7222 				   p_total_workers      =>      l_total_workers);
7223 
7224         /* Overdue Invoices if Interest Invoices  have to be created.
7225            In this case, the Credit items are treated similar to Debit Items.
7226            Interest is calculated on the credit items as done for debit items. */
7227 
7228          insert_int_overdue_inv(p_fin_charge_date	=> 	l_fin_charge_date,
7229 			        p_worker_number         =>      l_worker_number,
7230                                 p_total_workers         =>      l_total_workers);
7231 
7232 	/*Bug 8556955 call to insert reversed receipt late charges*/
7233          Insert_int_rev_rect_overdue(p_fin_charge_date       =>     l_fin_charge_date,
7234                                      p_worker_number         =>     l_worker_number,
7235                                      p_total_workers         =>     l_total_workers);
7236 
7237         /* Late Payments : If the charge calculation is based on Late Payments, the processing is the
7238            same irrespective of the document to be created, as credit items are not considered */
7239 
7240          insert_int_late_pay(p_fin_charge_date		=>	l_fin_charge_date,
7241                              p_worker_number            =>      l_worker_number,
7242                              p_total_workers            =>      l_total_workers);
7243 
7244         /* Average Daily Balance */
7245 
7246          insert_int_avg_daily_bal(p_fin_charge_date     =>	l_fin_charge_date,
7247                                   p_worker_number    	=>	l_worker_number,
7248 				  p_total_workers	=>	l_total_workers);
7249 
7250          /* Enhacement 6469663*/
7251          update_interest_amt('INTEREST');
7252         /* Calculate Penalty : There will be only one Penalty per payment schedule. It is either
7253            a fixed amount or a rate multiplied by the Interest */
7254 
7255          insert_penalty_lines(p_worker_number       =>      l_worker_number,
7256                               p_total_workers       =>      l_total_workers);
7257          /* Enhacement 6469663*/
7258          update_interest_amt('PENALTY');
7259         /* If there are records in  ar_late_charge_trx_t, insert data into the preview tables
7260            ar_interest_batches, ar_interest_headers and ar_interest_lines */
7261 
7262         select count(*)
7263         into   l_count_int_lines
7264         from   ar_late_charge_trx_t;
7265 
7266         debug('Number of records in the interim transactions table : '|| l_count_int_lines);
7267 
7268         IF l_count_int_lines > 0 THEN
7269 
7270            /* If debug flag is set, dump the data from the interim tables to the log file */
7271            IF l_debug_flag = 'Y' THEN
7272                debug_cust_sites;
7273                debug_customer_balances;
7274                debug_credit_amts;
7275                debug_payment_schedules;
7276            END IF;
7277 
7278            /* Before inserting data into the preview tables, we will delete all the existing
7279               Draft batches for this customer,site, currency, legal entity and org combination */
7280 
7281               delete_draft_batches(p_worker_number       =>      l_worker_number,
7282 	                           p_total_workers       =>      l_total_workers);
7283 
7284            /* Batch can not be created here. We need one batch per OU. So the workers which are
7285             processing the sites can not handle it */
7286 
7287           /*  insert_int_batches(p_batch_name		=>	l_batch_name,
7288     	            	     p_fin_charge_date		=>	l_fin_charge_date,
7289         	             p_batch_status		=>	l_mode,
7290                 	     p_gl_date			=>	l_gl_date); */
7291 
7292 	    BEGIN
7293 		    insert_int_lines(p_worker_number      	 =>      l_worker_number,
7294 				     p_total_workers       	 =>      l_total_workers);
7295 
7296 		    insert_int_lines_adb(p_worker_number         =>      l_worker_number,
7297 					 p_total_workers         =>      l_total_workers);
7298 
7299 		    insert_int_headers(p_fin_charge_date	 =>      l_fin_charge_date,
7300 				       p_worker_number       	 =>      l_worker_number,
7301 				       p_total_workers       	 =>      l_total_workers);
7302 	    EXCEPTION
7303 	    WHEN OTHERS THEN
7304 	    	ROLLBACK;
7305 	    	l_err_flag := TRUE;
7306 	    END;
7307 
7308             /* delete the data in the interim tables before commit */
7309             delete from ar_lc_cust_sites_t;
7310 
7311            delete from ar_late_charge_trx_t;
7312 
7313             COMMIT;
7314 
7315            /* If the program is run in Final Mode, invoke the api call so that the final
7316               documents are created in AR */
7317            IF l_mode = 'F' AND l_err_flag = FALSE THEN
7318               ar_late_charge_pkg.ordonancer_per_worker
7319 					( p_worker_num	=>	l_worker_number,
7320 					  p_request_id	=>	l_request_id);
7321               COMMIT;
7322            END IF;
7323 
7324         ELSE
7325            /* If debug flag is set, dump the data from the interim tables to the log file */
7326            IF l_debug_flag = 'Y' THEN
7327                debug_cust_sites;
7328                debug_customer_balances;
7329                debug_credit_amts;
7330                debug_payment_schedules;
7331            END IF;
7332             /* delete the data in the interim tables before commit */
7333 
7334             delete from ar_lc_cust_sites_t;
7335 
7336             delete from ar_late_charge_trx_t;
7337 
7338         END IF;
7339 
7340 
7341    END IF;
7342 
7343    retcode := 0;
7344 
7345    IF l_debug_flag = 'Y' THEN
7346         debug('ar_calc_late_charge.create_late_charge_document()- ');
7347    END IF;
7348 EXCEPTION WHEN OTHERS THEN
7349  /* delete the data in the interim tables before commit */
7350     delete from ar_lc_cust_sites_t;
7351 
7352    delete from ar_late_charge_trx_t;
7353 
7354 END create_late_charge_document;
7355 
7356 /*========================================================================+
7357   The wraper to parallelize the late charge document generation
7358  ========================================================================*/
7359 PROCEDURE generate_late_charge
7360                         (errbuf                 OUT NOCOPY VARCHAR2,
7361                          retcode                OUT NOCOPY NUMBER,
7362                          p_operating_unit_id    IN      VARCHAR2,
7363                          p_customer_id_from     IN      VARCHAR2,
7364                          p_customer_id_to       IN      VARCHAR2,
7365                          p_customer_num_from    IN      VARCHAR2,
7366                          p_customer_num_to      IN      VARCHAR2,
7367                          p_cust_site_use_id     IN      VARCHAR2,
7368                          p_gl_date              IN      VARCHAR2,
7369                          p_fin_charge_date      IN      VARCHAR2,
7370                          p_currency_code        IN      VARCHAR2,
7371                          p_mode                 IN      VARCHAR2,
7372                          p_disputed_items       IN      VARCHAR2,
7373                          p_called_from          IN      VARCHAR2,
7374                          p_enable_debug         IN      VARCHAR2,
7375                          p_total_workers        IN      VARCHAR2) IS
7376    l_worker_number		NUMBER ;
7377    l_req_id			NUMBER;
7378    l_rep_req_id		        NUMBER := 0;
7379    l_batch_name			ar_interest_batches.batch_name%type;
7380    l_customer_name_from         hz_parties.party_name%TYPE;
7381    l_customer_name_to           hz_parties.party_name%TYPE;
7382    l_late_charge_batch		VARCHAR2(100);
7383    l_fin_charge_date		DATE;
7384    l_gl_date			DATE;
7385    l_req_data			VARCHAR2(2000);
7386    l_num_batches	 	NUMBER;
7387    l_complete			BOOLEAN := FALSE;
7388    l_min_workers		CONSTANT NUMBER := 1;
7389    l_max_workers		CONSTANT NUMBER := 15;
7390    l_total_workers		NUMBER;
7391    l_xml_output                 BOOLEAN;
7392    l_iso_language               FND_LANGUAGES.iso_language%TYPE;
7393    l_iso_territory              FND_LANGUAGES.iso_territory%TYPE;
7394 
7395 
7396    TYPE req_status_typ  IS RECORD (
7397          request_id       NUMBER(15),
7398          dev_phase        VARCHAR2(255),
7399          dev_status       VARCHAR2(255),
7400          message          VARCHAR2(2000),
7401          phase            VARCHAR2(255),
7402          status           VARCHAR2(255));
7403 
7404    TYPE req_status_tab_typ   IS TABLE OF req_status_typ INDEX BY BINARY_INTEGER;
7405 
7406    l_req_status_tab   req_status_tab_typ;
7407 
7408    PROCEDURE submit_subrequest (p_worker_number IN NUMBER) IS
7409    BEGIN
7410       --
7411        debug('submit_subrequest()+');
7412        debug('l_customer_name_from	:	'|| l_customer_name_from);
7413        debug('l_customer_name_to	:	'|| l_customer_name_to);
7414        l_req_id := FND_REQUEST.submit_request('AR','ARCALATE',
7415                                  '',
7416                                  SYSDATE,
7417                                  FALSE,
7418                                  p_operating_unit_id,
7419                                  l_customer_name_from,
7420                                  l_customer_name_to,
7421                                  p_customer_num_from,
7422                                  p_customer_num_to,
7423                                  p_cust_site_use_id,
7424                                  p_gl_date,
7425                                  p_fin_charge_date,
7426                                  p_currency_code,
7427                                  p_mode,
7428                                  p_disputed_items,
7429                                  p_called_from,
7430                                  p_enable_debug,
7431                                  p_worker_number,
7432                                  l_total_workers,
7433                                  l_request_id
7434                                   );
7435         IF (l_req_id = 0) THEN
7436             debug('can not start for worker_id: ' ||p_worker_number );
7437             errbuf := fnd_Message.get;
7438             retcode := 2;
7439             return;
7440         ELSE
7441             commit;
7442             l_req_data := l_req_data ||l_req_id;
7443             debug('child request id: ' ||l_req_id || ' started for worker_id: ' ||p_worker_number );
7444         END IF;
7445 
7446          IF p_worker_number < p_total_workers THEN
7447             l_req_data := l_req_data || ',';
7448          END IF;
7449 
7450          l_req_status_tab(p_worker_number).request_id := l_req_id;
7451 
7452          debug('submit_subrequest()-');
7453 
7454       END submit_subrequest;
7455 
7456 BEGIN
7457    l_debug_flag       :=      p_enable_debug;
7458 
7459    l_req_data   :=   fnd_conc_global.request_data;
7460 
7461    l_req_status_tab.DELETE;
7462 
7463    IF (l_req_data is null) THEN -- first run
7464        debug('generate_late_charge()+');
7465        debug('total workers : ' || p_total_workers );
7466        BEGIN
7467           IF p_customer_id_from IS NOT NULL THEN
7468              select  hp.party_name
7469              into    l_customer_name_from
7470              from    hz_parties hp,
7471 		     hz_cust_accounts cust_acct
7472             where    hp.party_id = cust_acct.party_id
7473               and    cust_acct.cust_account_id = p_customer_id_from;
7474           ELSE
7475              l_customer_name_from := Null;
7476           END IF;
7477        EXCEPTION WHEN NO_DATA_FOUND THEN
7478              l_customer_name_from := NULL;
7479        END;
7480 
7481        debug('p_customer_id_from  : ' ||p_customer_id_from ||',	l_customer_name_from  : '|| l_customer_name_from);
7482 
7483        BEGIN
7484           IF p_customer_id_to IS NOT NULL THEN
7485              select  hp.party_name
7486              into    l_customer_name_to
7487              from    hz_parties hp,
7488    		     hz_cust_accounts cust_acct
7489              where   hp.party_id = cust_acct.party_id
7490               and    cust_acct.cust_account_id = p_customer_id_to;
7491           ELSE
7492              l_customer_name_to := Null;
7493           END IF;
7494        EXCEPTION WHEN NO_DATA_FOUND THEN
7495              l_customer_name_from := NULL;
7496        END;
7497 
7498        debug('p_customer_id_to  : ' ||p_customer_id_to ||',	l_customer_name_to  : '|| l_customer_name_to);
7499 
7500        l_request_id	          :=   fnd_global.conc_request_id;
7501        l_fin_charge_date          :=   fnd_date.canonical_to_date(p_fin_charge_date);
7502        l_gl_date                  :=   fnd_date.canonical_to_date(p_gl_date);
7503 
7504        IF l_batch_name IS NULL THEN
7505           select meaning
7506           into   l_late_charge_batch
7507           from   ar_lookups
7508           where  lookup_type = 'AR_LATE_CHARGE_LABELS'
7509           and   lookup_code = 'LATE_CHARGE_BATCH';
7510 
7511           l_batch_name := l_late_charge_batch;
7512 
7513           IF l_debug_flag  ='Y' THEN
7514               debug('l_batch_name derived           : '||l_batch_name);
7515           END IF;
7516        END IF;
7517 
7518        /* Insert one batch per OU. Since the processing is done by multiple workers,
7519           the batch is created first */
7520        insert_int_batches(p_operating_unit_id	     =>	     p_operating_unit_id,
7521  		   	  p_batch_name               =>      l_batch_name,
7522                           p_fin_charge_date          =>      l_fin_charge_date,
7523                           p_batch_status             =>      p_mode,
7524                           p_gl_date                  =>      l_gl_date,
7525                           p_request_id		     =>      l_request_id);
7526        COMMIT;
7527 
7528        /* Lock all the batches created now */
7529        lock_batches;
7530 
7531        select count(*)
7532        into l_num_batches
7533        from ar_interest_batches
7534        where request_id = l_request_id;
7535 
7536        debug('Number of batches created = '||l_num_batches);
7537 
7538        IF nvl(p_total_workers,0) < l_min_workers THEN
7539           l_total_workers	:=  l_min_workers;
7540        ELSIF p_total_workers > l_max_workers THEN
7541           l_total_workers	:=  l_max_workers;
7542        ELSE
7543           l_total_workers	:=  p_total_workers;
7544        END IF;
7545 
7546        FOR l_worker_number in 1..l_total_workers LOOP
7547 
7548            debug('worker # : ' || l_worker_number );
7549 
7550            submit_subrequest (l_worker_number);
7551 
7552        END LOOP;
7553 
7554        --fnd_conc_global.set_req_globals(conc_status => 'PAUSED',
7555          --                              request_data => to_char(l_req_id));
7556 
7557        debug('The Master program waits for child processes');
7558 
7559        -- Wait for the completion of the submitted requests
7560 
7561        FOR i in 1..l_total_workers LOOP
7562            l_complete := FND_CONCURRENT.WAIT_FOR_REQUEST(
7563                        request_id=>l_req_status_tab(i).request_id,
7564                        interval=>30,
7565                        max_wait=>144000,
7566                        phase=>l_req_status_tab(i).phase,
7567                        status=>l_req_status_tab(i).status,
7568                        dev_phase=>l_req_status_tab(i).dev_phase,
7569                        dev_status=>l_req_status_tab(i).dev_status,
7570                        message=>l_req_status_tab(i).message);
7571 
7572           IF l_req_status_tab(i).dev_phase <> 'COMPLETE' THEN
7573                retcode := 2;
7574                debug('Worker # '|| i||' has a phase '||l_req_status_tab(i).dev_phase);
7575           ELSIF l_req_status_tab(i).dev_phase = 'COMPLETE'
7576                    AND l_req_status_tab(i).dev_status <> 'NORMAL' THEN
7577                retcode := 2;
7578                debug('Worker # '|| i||' completed with status '||l_req_status_tab(i).dev_status);
7579           ELSE
7580                debug('Worker # '|| i||' completed successfully');
7581           END IF;
7582 
7583        END LOOP;
7584 
7585    END IF;
7586 
7587      /* We have one interest batch per OU. Delete all empty batches */
7588 
7589      delete_empty_batches;
7590 
7591      /* If the mode is Final, update the column transferred_status in ar_interest_bacthes
7592            a) Update the transferred_status to S if  the process_status of all the header
7593               records corresponding to a given batch is S
7594            b) Else the transferred_status should be E */
7595 
7596      IF p_mode = 'F' THEN
7597          update ar_interest_batches bat
7598          set    bat.transferred_status = 'S'
7599          where  not exists (select hdr.interest_header_id
7600                             from ar_interest_headers hdr
7601                             where bat.interest_batch_id = hdr.interest_batch_id
7602                             and hdr.process_status <> 'S')
7603          and bat.request_id = l_request_id;
7604 
7605          update ar_interest_batches bat
7606          set    bat.transferred_status = 'E'
7607          where exists (select hdr.interest_header_id
7608                        from ar_interest_headers hdr
7609                        where bat.interest_batch_id = hdr.interest_batch_id
7610                        and hdr.process_status <> 'S')
7611          and bat.request_id = l_request_id;
7612      END IF;
7613 
7614      l_req_data := fnd_conc_global.request_data;
7615 
7616      IF l_req_data IS NULL THEN
7617         /* Call the late charges report */
7618         SELECT lower(iso_language),iso_territory
7619         INTO l_iso_language,l_iso_territory
7620         FROM FND_LANGUAGES
7621         WHERE language_code = USERENV('LANG');
7622 
7623         l_xml_output:=  fnd_request.add_layout(
7624       			      template_appl_name  => 'AR',
7625 		              template_code       => 'ARLCRPT',
7626 	  	              template_language   => l_iso_language,
7627 		              template_territory  => l_iso_territory,
7628 		              output_format       => 'PDF'
7629 		            );
7630 
7631         l_rep_req_id :=  FND_REQUEST.SUBMIT_REQUEST (
7632                                 application=>'AR',
7633                                 program=>'ARLCRPT',
7634                                 sub_request=>TRUE,
7635                                 argument1=>l_request_id,
7636                                 argument2=>NULL
7637                             ) ;
7638         IF l_debug_flag ='Y'  THEN
7639            debug('Submitted Late Charge Report, Request Id :' || l_rep_req_id);
7640         END IF;
7641 
7642         fnd_conc_global.set_req_globals(conc_status => 'PAUSED',
7643                                         request_data => to_char(l_rep_req_id));
7644 
7645      END IF;
7646 
7647      commit;
7648 
7649      retcode := 0 ;
7650      debug('generate_late_charge()-');
7651 
7652 EXCEPTION
7653   WHEN OTHERS THEN
7654     RAISE ;
7655 
7656 END generate_late_charge;
7657 
7658 
7659 BEGIN
7660   /* Variables Intialization section */
7661   /* WHO columns */
7662   pg_last_updated_by        :=  arp_global.last_updated_by;
7663   pg_last_update_login      :=  arp_global.last_update_login;
7664 --  l_debug_flag	 	    := 	'Y'; /* Enable Debug now */
7665 
7666 END AR_CALC_LATE_CHARGE;