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