DBA Data[Home] [Help]

PACKAGE BODY: APPS.PN_INDEX_AMOUNT_PKG

Source


1 PACKAGE BODY pn_index_amount_pkg AS
2 -- $Header: PNINAMTB.pls 120.39.12010000.2 2008/09/04 12:25:58 mumohan ship $
3 -- +===========================================================================+
4 -- |                   Copyright (c) 2001 Oracle Corporation
5 -- |                      Redwood Shores, California, USA
6 -- |                            All rights reserved.
7 -- +===========================================================================+
8 -- | Name
9 -- |  pn_index_amount_pkg
10 -- |
11 -- | Description
12 -- |  This package contains procedures used to calculate index amounts.
13 -- |
14 -- | History
15 -- | 27-MAR-01 jreyes    Created
16 -- | 19-JUN-01 jreyes    Adding call to create schedules and items..
17 -- | 21-JUN-01 jreyes    Adding call to get amount precision from fnd_currency.get_info...
18 -- | 24-JUN-01 jreyes    Opened increase on types to all payment term types (LOOKUP Code: PN_PAYMENT_TERM_TYPE)
19 -- | 04-JUL-01 jreyes    Removed references to _MM procedures
20 -- | 24-JUL-01 psidhu    Removed code_code_combinaton_id from call to
21 -- |                     PNT_PAYMENT_TERMS_PKG.Insert_Row.
22 -- | 03-AUG-01 psidhu    Added WHENEVER SQLERROR EXIT FAILURE ROLLBACK and
23 -- |                     WHENEVER OSERROR  EXIT FAILURE ROLLBACK.
24 -- | 07-AUG-01 psidhu    Added code for aggregation functionality.
25 -- |                     Added public function build_distributions_string
26 -- |                     Procedure create_payment_term_rec_aggr
27 -- |                     modified the following packages:
28 -- |                     - sum_payment_items
29 -- |                     - chk_normalized_amount
30 -- |                     - create_payment_term_record
31 -- | 29-AUG-01 psidhu    Added procedure CREATE_AGGR_PAYMENT_TERM
32 -- | 13-NOV-01 ahhkumar  Fix for Bug 2101480 In the Procedure Calculate_initial_basis
33 -- |                     pass the parameter p_include_index_items as 'N' in call to sum_payment_terms
34 -- | 14-NOV-01 ahhkumar  Fix for Bug 2102073 in the procedure update_index_hist_line_batch initialise the
35 -- |                     variable v_index_percent_change as null
36 -- | 05-dEC-01 achauhan  Fix for aggregation - Made changes to create_aggr_payment_terms for
37 -- |                     aggregation functionality and also to sum_payment_items, for
38 -- |                     calculation of annualized basis.
39 -- | 06-DEC-01 achauhan  In approve_index_pay_term added code to update pn_index_lease_terms
40 -- | 12-DEC-01 achauhan  Added the condition to pick up approved rent increase terms, in the
41 -- |                     sum_payment_items routine.
42 -- | 15-JAN-02 mmisra    Added dbdrv command.
43 -- | 01-FEB-02 achauhan  Commented out NOCOPY the calls to print_payment_terms and print_basis_periods
44 -- | 01-FEB-02 Mrinal    Added checkfile command.
45 -- | 24-FEB-02 psidhu    Fix for bug# 2227270. Removed code to default GL accounts from the main lease
46 -- |                     while creating index rent terms in procedure create_payment_term_record.
47 -- | 06-MAY-02 psidhu    Fix for bug 2352453 and 2356045.
48 -- | 19-JUL-02 psidhu    Fix for bug# 2452909. Added procedure process_currency_code.
49 -- | 01-AUG-02 psidhu    Changes for carry forward funtionality. Added paramters p_index_period_id,
50 -- |                     p_carry_forward_flag,op_constraint_applied_amount,op_carry_forward_amount
51 -- |                     to derive_constrained_rent. Added functions derive_carry_forward_amount,
52 -- |                     derive_prev_negative_rent,get_increase_over_constraint and get_max_assessment_dt.
53 -- |                     Added procedure calculate_subsequent_periods.
54 -- | 17-OCT-02 psidhu    Changes for carry forward funtionality.Removed function derive_carry_forward_amount.
55 -- |                     Added function derive_cum_carry_forward.Added parameter op_constraint_applied_percent
56 -- |                     and op_carry_forward_percent to procedure calculate_period.Made changes to procedure
57 -- |                     derive_constrained_rent to handle cumulative carry forward in percent.
58 -- |                     Added parameter op_carry_forward_percent and op_constraint_applied_percent.
59 -- | 31-OCT-02 ahhkumar  BUG#2593961 edit procedure create_payment_terms  pass the
60 -- |                     parmeter p_include_index_items ='N'
61 -- |                     in sum_payment_items where p_basis_type = c_basis_type_compound
62 -- | 03-JAN-03 mmisra    Put check to validate term template in calculate_batch and
63 -- |                     calculate_period.
64 -- | 14-AUG-03 ftanudja  Handled untouched index lease payment terms. #3027574.
65 -- | 23-OCT-03 ftanudja  Fixed message logging logic in calculate.#3209774.
66 -- | 11-NOV-03 ftanudja  Take into account only approved terms for cursor
67 -- |                     fetch_generated_il_terms in create_aggr... #3243150.
68 -- | 18-FEB-04 ftanudja  Added parameter for create_payment_term_record.
69 -- |                     #3255737. Consolidated logic for updating initial
70 -- |                     basis in calculate_basis_amount, calculate_period.
71 -- |                     # 3436147
72 -- | 27-MAY-04 vmmehta  Fix for bug# 3562600.
73 -- |                    Procedure calculate: Call calculate_initial_basis if retain_initial_basis_flag not set and update initial basis.
74 -- |                    Procedure calculate_period: Removed update initial_basis as it is done in calculculate.
75 -- |                    Procedure calculate_basis_amount: Code changes to use initial basis as basis amount for
76 -- |                    first period for all basis types
77 -- | 13-Jul-04 ftanudja o Added parameter ip_auto_find_sch_day in
78 -- |                      approve_index_pay_term_batch. #3701195.
79 -- | 08-OCT-04 stripath o Modified for BUG# 3961117, Created function Get_Calculate_Date,
80 -- |                      added new parameter p_calculate_date to procedures create_payment_terms,
81 -- |                      create_payment_term_record.  Do not to create backbills
82 -- |                      if Assessment Date <= p__Calculate_Date (CutOff Date).
83 -- | 01-DEC-04 ftanudja o Added fix for #3964221, term created w/
84 -- |                      start date > end date.
85 -- | 27-DEC-04 abanerje Converted hardcoded english text messages
86 -- |                    to translatable seeded messages.
87 -- |                    Bug #3592834.
88 -- | 18-JAN-05 ftanudja o Before approving negative consolidation terms,
89 -- |                      check if schedule day conflicts in create_
90 -- |                      aggr_payment_term proc.
91 -- |                    o Add batch commit for approve_index_pay_
92 -- |                      term_batch. #4081821.
93 -- | 19-JAN-05 ftanudja o Fixed range query for batch approval.#4129147
94 -- | 21-APR-05 ftanudja o Added code to use default area type code if location is
95 -- |                      not null in create_payment_term_record(). #
96 -- | 14-Jul-05 SatyaDeepo Replaced bases views with their repective _ALL tables
97 -- | 19-SEP-05 piagrawa  o Modified the signature of Get_Calculate_Date
98 -- | 05-MAY-06 Hareesha  o Bug #5115291 Added parameter p_norm_st_date to
99 -- |                       procedure create_payment_term_record
100 -- | 31-OCT-06 acprakas  o Bug#4967164. Modified procedure create_aggr_payment_terms
101 -- |                       to create negative terms only when index payment term type is not 'ATLEAST'
102 -- | 01-NOV-06 Prabhakar o Added parameter p_end_date to the create_payment_term_record.
103 -- | 12-DEC-06 Prabhakar o Added p_prorate_factor parameter to derive_constrined_rent
104 -- |                       and create_payment_terms procedures.
105 -- +===========================================================================+
106 
107 ------------------------------------------------------------------------
108 -- PROCEDURE : build_distributions_string
109 -- DESCRIPTION: This function is used to derive a string that denotes
110 --              the distributions entries for a certain payment term.
111 --
112 --
113 ------------------------------------------------------------------------
114 FUNCTION build_distributions_string (
115    ip_payment_term_id IN NUMBER
116 )
117    RETURN VARCHAR2 IS
118    CURSOR c_distributions (
119       ip_payment_term_id IN NUMBER
120    ) IS
121       SELECT   pd.payment_term_id
122               ,pd.account_class
123               ,pd.account_id
124               ,pd.percentage
125           FROM pn_distributions_all pd
126          WHERE pd.payment_term_id = ip_payment_term_id
127       ORDER BY pd.account_class,
128                pd.account_id,
129                pd.percentage;
130 
131    v_big_string   VARCHAR2 (4000);
132 BEGIN
133 
134 
135    FOR c_dist_rec IN c_distributions (ip_payment_term_id)
136    LOOP
137       v_big_string :=    c_dist_rec.account_class
138                       || ','
139                       ||   c_dist_rec.account_id
140                       || ','
141                       || c_dist_rec.percentage
142                       || ','
143                       || v_big_string;
144    END LOOP;
145 
146    if v_big_string is null then
147 
148       --v_big_string := ip_payment_term_id;
149       v_big_string := 'IGNORE';
150 
151    end if;
152 
153    RETURN v_big_string;
154 
155 END build_distributions_string;
156 
157 
158 ------------------------------------------------------------------------
159 -- PROCEDURE : format
160 -- DESCRIPTION: This function is used the print_basis_periods procedure
161 --              to format any amount to This is only used to display
162 --              date to the output or log files.
163 --
164 --
165 --
166 ------------------------------------------------------------------------
167 
168 
169     FUNCTION format (
170       p_number          IN   NUMBER
171      ,p_precision       IN   NUMBER DEFAULT NULL
172      ,p_currency_code   IN   VARCHAR2 DEFAULT NULL
173    )
174       RETURN VARCHAR2 IS
175       v_currency_code      gl_sets_of_books.currency_code%TYPE;
176       v_formatted_number   VARCHAR2 (100);
177       v_format_mask        VARCHAR2 (100);
178       v_field_length       NUMBER                                := 20;
179       v_min_acct_unit      NUMBER;
180    BEGIN
181 
182       /* if p_number is not blank, apply format
183          if it is blank, just print a blank space */
184 
185       IF p_number IS NOT NULL THEN
186 
187          /* deriving a format mask if precision is specified. */
188 
189          IF p_precision IS NOT NULL THEN
190             fnd_currency.safe_build_format_mask (
191                format_mask                   => v_format_mask
192               ,field_length                  => v_field_length
193               ,precision                     => p_precision
194               ,min_acct_unit                 => v_min_acct_unit
195             );
196          ELSE
197 
198             IF p_currency_code IS NOT NULL THEN
199                v_currency_code := p_currency_code;
200             ELSE
201                v_currency_code := g_currency_code;
202             END IF;
203 
204 
205             /*  getting format make for currency code defined */
206 
207             v_format_mask := fnd_currency.get_format_mask (
208                                 currency_code                 => v_currency_code
209                                ,field_length                  => v_field_length
210                              );
211          END IF;
212 
213          v_formatted_number := TO_CHAR (p_number, v_format_mask);
214       ELSE
215 
216          /* set formatted number to a space if no number is passed */
217 
218          v_formatted_number := ' ';
219       END IF;
220 
221       RETURN v_formatted_number;
222 
223 
224    END format;
225 
226 
227 ------------------------------------------------------------------------
228 -- PROCEDURE : GET_AMOUNT_PRECISION
229 -- DESCRIPTION: This function is used any currency amount
230 --
231 ------------------------------------------------------------------------
232    FUNCTION get_amount_precision (
233       p_currency_code   IN   VARCHAR2 DEFAULT NULL
234    )
235       RETURN NUMBER IS
236       v_currency_code   gl_sets_of_books.currency_code%TYPE;
237       v_precision       NUMBER;
238       v_ext_precision   NUMBER;
239       v_min_acct_unit   NUMBER;
240    BEGIN
241 
242       IF p_currency_code IS NOT NULL THEN
243          v_currency_code := p_currency_code;
244       ELSE
245          v_currency_code := g_currency_code;
246       END IF;
247 
248       fnd_currency.get_info (
249          currency_code                 => v_currency_code
250         ,precision                     => v_precision
251         ,ext_precision                 => v_ext_precision
252         ,min_acct_unit                 => v_min_acct_unit
253       );
254 
255       RETURN v_precision;
256 
257    END get_amount_precision;
258 
259 
260 ------------------------------------------------------------------------
261 -- PROCEDURE : put_log
262 -- DESCRIPTION: This procedure will display the text in the log file
263 --              of a concurrent program
264 --
265 ------------------------------------------------------------------------
266 
267    PROCEDURE put_log (
268       p_string   IN   VARCHAR2
269    ) IS
270    BEGIN
271       -- pn_index_lease_common_pkg.put_log (p_string);
272       pnp_debug_pkg.log(p_string);
273    END put_log;
274 
275 
276 ------------------------------------------------------------------------
277 -- PROCEDURE : put_output
278 -- DESCRIPTION: This procedure will display the text in the log file
279 --              of a concurrent program
280 --
281 ------------------------------------------------------------------------
282 
283    PROCEDURE put_output (
284       p_string   IN   VARCHAR2
285    ) IS
286    BEGIN
287       -- pn_index_lease_common_pkg.put_output (p_string);
288       pnp_debug_pkg.put_log_msg(p_string);
289    END put_output;
290 
291 
292 ------------------------------------------------------------------------
293 -- PROCEDURE : display_error_messages
294 -- DESCRIPTION: This procedure will parse a string of error message codes
295 --              delimited of with a comma.  It will lookup each code using
296 --              fnd_messages routine.
297 ------------------------------------------------------------------------
298 
299    PROCEDURE display_error_messages (
300       ip_message_string   IN   VARCHAR2
301    ) IS
302       message_string   VARCHAR2 (4000);
303       msg_len          NUMBER;
304       ind_message      VARCHAR2 (40);
305       comma_loc        NUMBER;
306    BEGIN
307       message_string := ip_message_string;
308 
309       IF message_string IS NOT NULL THEN
310          -- append a comma to the end of the string.
311          message_string :=    message_string
312                            || ',';
313          -- get location of the first comma
314          comma_loc := INSTR (message_string, ',', 1, 1);
315          -- get length of message
316          msg_len := LENGTH (message_string);
317       ELSE
318          comma_loc := 0;
319       END IF;
320 
321       fnd_message.clear;
322 
323       --
324       -- loop will cycle thru each occurrence of delimted text
325       -- and display message with its code..
326       --
327       WHILE comma_loc <> 0
328       LOOP
329          --
330          -- get error message to process
331          --
332          ind_message := SUBSTR (message_string, 1,   comma_loc
333                                                    - 1);
334 
335          --
336          -- check the length of error message code
337          --
338          --
339          IF LENGTH (ind_message) > 30 THEN
340             put_log (   '**** MESSAGE CODE '
341                      || ind_message
342                      || ' TOO LONG');
343          ELSE
344             --put_log (   'Message Code='
345             --         || ind_message);
346 
347             --
348             -- Convert error message code to its 'user-friendly' message;
349             --
350             fnd_message.set_name ('PN', ind_message);
351             --
355                         || fnd_message.get
352             -- Display message to the output log
353             --
354             put_output (   '-->'
356                         || ' ('
357                         || ind_message
358                         || ')');
359             --
360             -- delete the current message from string of messges
361             -- e.g.
362             --  before: message_string = "message1, message2, message3,"
363             --  after:  message_string = "message2, message3,"
364             --
365             message_string := SUBSTR (
366                                  message_string
367                                 ,  comma_loc
368                                  + 1
369                                 ,  LENGTH (message_string)
370                                  - comma_loc
371                               );
372             --
373             -- locate the first occurrence of a comma
374             --
375             comma_loc := INSTR (message_string, ',', 1, 1);
376          END IF; --LENGTH (ind_message) > 30
377       END LOOP;
378    END display_error_messages;
379 
380 
381 ------------------------------------------------------------------------
382 -- PROCEDURE : print_payment_terms
383 -- DESCRIPTION: This procedure is will print payment term information
384 --              for a given index lease period.
385 --
386 ------------------------------------------------------------------------
387 
388    PROCEDURE print_payment_terms (
389       p_index_period_id   IN   NUMBER
390      ,p_payment_term_id   IN   NUMBER DEFAULT NULL
391    ) IS
392       CURSOR index_periods_pay (
393          ip_index_period_id   IN   NUMBER
394       ) IS
395          SELECT   ppt.actual_amount
396                  ,ppt.frequency_code
397                  ,ppt.start_date
398                  ,ppt.end_date
399                  ,ppt.index_term_indicator
400                  ,ppt.status
401                  ,DECODE (ppt.normalize, 'Y', 'NORMALIZE') "NORMALIZE"
402              FROM pn_payment_terms_all ppt
403             WHERE ppt.index_period_id = ip_index_period_id
404          ORDER BY ppt.start_date;
405 
406       CURSOR index_periods_payments (
407          ip_index_period_id   IN   NUMBER
408         ,ip_payment_term_id   IN   NUMBER
409       ) IS
410          SELECT   ppt.actual_amount
411                  ,ppt.frequency_code
412                  ,ppt.start_date
413                  ,ppt.end_date
414                  ,ppt.index_term_indicator
415                  ,ppt.status
416                  ,DECODE (ppt.normalize, 'Y', 'NORMALIZE') "NORMALIZE"
417              FROM pn_payment_terms_all ppt
418             WHERE ppt.index_period_id = ip_index_period_id
419               AND (   ppt.payment_term_id = ip_payment_term_id
420                    OR ip_payment_term_id IS NULL
421                   )
422          ORDER BY ppt.start_date;
423 
424       v_line_count   NUMBER;
425       ilp_pay_rec    index_periods_payments%ROWTYPE;
426       l_message VARCHAR2(2000) := NULL;
427    BEGIN
428       -- Reset line counter for periods.
429       v_line_count := 0;
430       --
431       -- Printing the index periods of the report report
432       --
433       v_line_count :=   v_line_count
434                       + 1;
435       fnd_message.set_name ('PN','PN_RICAL_PAYMENT');
436       l_message := '         '||fnd_message.get;
437       fnd_message.set_name ('PN','PN_RICAL_START');
438       l_message := l_message||'      '||fnd_message.get;
439       fnd_message.set_name ('PN','PN_RICAL_END');
440       l_message := l_message||'        '||fnd_message.get;
441       fnd_message.set_name ('PN','PN_RICAL_PAYMENT');
442       l_message := l_message||'                     '||fnd_message.get;
443       fnd_message.set_name ('PN','PN_RICAL_INDEX');
444       l_message := l_message||'        '||fnd_message.get;
445       fnd_message.set_name ('PN','PN_RICAL_NORZ');
446       l_message := l_message||'        '||fnd_message.get;
447       put_output(l_message);
448 
449       l_message := NULL;
450 
451       fnd_message.set_name ('PN','PN_RICAL_FREQ');
452       l_message := '         '||fnd_message.get;
453       fnd_message.set_name ('PN','PN_RICAL_DATE');
454       l_message := l_message||'     '||fnd_message.get;
455       fnd_message.set_name ('PN','PN_RICAL_DATE');
456       l_message := l_message||'        '||fnd_message.get;
457       fnd_message.set_name ('PN','PN_RICAL_AMT');
458       l_message := l_message||'        '||fnd_message.get;
459       fnd_message.set_name ('PN','PN_RICAL_STATUS');
460       l_message := l_message||'      '||fnd_message.get;
461       fnd_message.set_name ('PN','PN_RICAL_PAYMENT_TYPE');
462       l_message := l_message||'        '||fnd_message.get;
463       fnd_message.set_name ('PN','PN_RICAL_YES_NO');
464       l_message := l_message||'        '||fnd_message.get;
465       put_output(l_message);
466 
467       put_output (
468          '         ---------  -----------  -----------  ----------  -----------  ------------------  ---------'
469       );
470 
471       -- for performance reasons, one of two cursors can be executed..
472       --    cursor index_periods_pay is to display all payments for a period..
473       --    cursor index_periods_payments is to display payment details for one payment.
474       --
475 
476 
477       IF p_payment_term_id IS NULL THEN
481       END IF;
478          OPEN index_periods_pay (p_index_period_id);
479       ELSE
480          OPEN index_periods_payments (p_index_period_id, p_payment_term_id);
482 
483       LOOP
484          IF index_periods_pay%ISOPEN THEN
485             FETCH index_periods_pay INTO ilp_pay_rec;
486             EXIT WHEN index_periods_pay%NOTFOUND;
487          ELSE
488             FETCH index_periods_payments INTO ilp_pay_rec;
489             EXIT WHEN index_periods_payments%NOTFOUND;
490          END IF;
491 
492          put_output (
493                LPAD (ilp_pay_rec.frequency_code, 18, ' ')
494             || LPAD (ilp_pay_rec.start_date, 13, ' ')
495             || LPAD (ilp_pay_rec.end_date, 13, ' ')
496             || LPAD (format (ilp_pay_rec.actual_amount, 2), 12, ' ')
497             || LPAD (ilp_pay_rec.status, 13, ' ')
498             || LPAD (ilp_pay_rec.index_term_indicator, 20, ' ')
499             || LPAD (ilp_pay_rec.normalize, 11, ' ')
500          );
501       END LOOP;
502 
503       put_output ('.         ');
504 
505       --
506       -- Print Message if no payment terms found for this period
507       --
508       IF v_line_count = 0 THEN
509          put_output ('*********************************************');
510          fnd_message.set_name ('PN','PN_RICAL_NO_PAY');
511          put_output(fnd_message.get);
512          put_output ('*********************************************');
513       END IF;
514    END print_payment_terms;
515 
516 
517 ------------------------------------------------------------------------
518 -- PROCEDURE : print_basis_periods
519 -- DESCRIPTION: This procedure is will print to the output log index rent
520 --              period details and any payment terms for this period
521 ------------------------------------------------------------------------
522 
523    PROCEDURE print_basis_periods (
524       p_index_lease_id    IN   NUMBER
525      ,p_index_period_id   IN   NUMBER
526    ) IS
527       CURSOR index_lease_periods (
528          ip_index_lease_id    IN   NUMBER
529         ,ip_index_period_id   IN   NUMBER
530       ) IS
531          SELECT   pilp.basis_percent_change
532                  ,pilp.current_basis
533                  ,pilp.index_percent_change
534                  ,pilp.index_finder_date
535                  ,pilp.index_period_id
536                  ,pilp.basis_start_date
537                  ,pilp.basis_end_date
538                  ,pilp.assessment_date
539                  ,pilp.line_number
540                  ,pilp.relationship
541                  ,pilp.constraint_rent_due
542                  ,pilp.current_index_line_id
543                  ,pilp.current_index_line_value
544                  ,pilp.previous_index_line_id
545                  ,pilp.previous_index_line_value
546                  ,pilp.unconstraint_rent_due
547              FROM pn_index_lease_periods_all pilp
548             WHERE pilp.index_lease_id = ip_index_lease_id
549               AND pilp.index_period_id = ip_index_period_id
550          ORDER BY pilp.line_number;
551 
552       v_line_count   NUMBER;
553       l_message VARCHAR2(2000) := NULL;
554 
555    BEGIN
556       -- Reset line counter for periods.
557       v_line_count := 0;
558 
559       --
560       -- Printing the index periods of the report report
561       --
562       <<index_periods>>
563       FOR ilp_rec IN index_lease_periods (p_index_lease_id, p_index_period_id)
564       LOOP
565          --
566          -- Printing the Headers of the report
567          --
568          fnd_message.set_name ('PN','PN_RICAL_CUR');
569          l_message := '      '||fnd_message.get;
570          fnd_message.set_name ('PN','PN_RICAL_ASS');
571          l_message := l_message||'    '||fnd_message.get;
572          fnd_message.set_name ('PN','PN_RICAL_INDX');
573          l_message := l_message||'                  '||fnd_message.get;
574          fnd_message.set_name ('PN','PN_RICAL_BAS');
575          l_message := l_message||'       '||fnd_message.get;
576          fnd_message.set_name ('PN','PN_RICAL_UCON');
577          l_message := l_message||'  '||fnd_message.get;
578          fnd_message.set_name ('PN','PN_RICAL_CON');
579          l_message := l_message||'   '||fnd_message.get;
580          put_output(l_message);
581 
582          l_message := NULL;
583 
584          fnd_message.set_name ('PN','PN_RICAL_BAS');
585          l_message := '       '||fnd_message.get;
586          fnd_message.set_name ('PN','PN_RICAL_DATE');
587          l_message := l_message||'        '||fnd_message.get;
588          fnd_message.set_name ('PN','PN_RICAL_REL');
589          l_message := l_message||'        '||fnd_message.get;
590          fnd_message.set_name ('PN','PN_RICAL_CHG');
591          l_message := l_message||'   '||fnd_message.get;
592          fnd_message.set_name ('PN','PN_RICAL_CHG');
593          l_message := l_message||'  '||fnd_message.get;
594          fnd_message.set_name ('PN','PN_RICAL_RENT_DUE');
595          l_message := l_message||'   '||fnd_message.get;
596          l_message := l_message||'   '||fnd_message.get;
597          l_message := l_message||' '||fnd_message.get;
598          put_output(l_message);
599 
600          put_output (
601             '     ---------  ------------  -----------  ----------  ----------  ----------  ----------'
602          );
603          --  Print the Period Details
607             || LPAD (TO_CHAR (ilp_rec.assessment_date, 'DD-MON-RRRR'), 14, ' ')
604          --  format function will display 3 decimal places for all numbers
605          put_output (
606                LPAD (format (ilp_rec.current_basis, 2), 14, ' ')
608             || LPAD (ilp_rec.relationship, 13, ' ')
609             || LPAD (format (ilp_rec.index_percent_change, 3), 13, ' ')
610             || LPAD (format (ilp_rec.basis_percent_change, 3), 11, ' ')
611             || LPAD (format (ilp_rec.unconstraint_rent_due, 2), 12, ' ')
612             || LPAD (format (ilp_rec.constraint_rent_due, 2), 12, ' ')
613          );
614          v_line_count :=   v_line_count
615                          + 1;
616           print_payment_terms (p_index_period_id => ilp_rec.index_period_id);
617       END LOOP index_periods; -- ilp_rec
618 
619       --
620       -- Print Message if no basis periods found
621       --
622       IF v_line_count = 0 THEN
623          put_output ('**************************************');
624          fnd_message.set_name ('PN','PN_RICAL_NO_PRDS');
625          put_output(fnd_message.get);
626          put_output ('**************************************');
627       END IF;
628    END print_basis_periods;
629 
630 
631 ------------------------------------------------------------------------
632 -- PROCEDURE : derive_index_period_id
633 -- DESCRIPTION: This procedure is used to derive the index period id of the
634 --              index rent period prior to the assessment date that is provided.
635 --              'current assessment date'
636 --
637 --              If no assessment date is provided, then the id of the last
638 --              period will be returned..
639 ------------------------------------------------------------------------
640 
641    PROCEDURE derive_index_period_id (
642       p_index_lease_id         IN       NUMBER
643      ,p_assessment_date        IN       DATE
644      ,op_prev_index_lease_id   OUT NOCOPY      NUMBER
645    ) IS
646    BEGIN
647       --
648       --put_log ('..In derive_index_period_id');
649       --
650 
651       SELECT pilp.index_period_id
652         INTO op_prev_index_lease_id
653         FROM pn_index_lease_periods_all pilp
654        WHERE pilp.index_lease_id = p_index_lease_id
655          AND pilp.assessment_date = (SELECT MAX (pilp.assessment_date)
656                                        FROM pn_index_lease_periods_all pilp
657                                       WHERE pilp.index_lease_id = p_index_lease_id
658                                       /*
659                                       -- if p_assessment_date is null, this will return the
660                                       -- assessment date of the last index rent period.
661                                       */
662                                         AND (   pilp.assessment_date < p_assessment_date
663                                              OR p_assessment_date IS NULL
664                                             ));
665    EXCEPTION
666       WHEN OTHERS THEN
667          put_log (   'Unable to derive prev. index ID SQLERRM:'
668                   || SQLERRM);
669    END derive_index_period_id;
670 
671 
672 ------------------------------------------------------------------------
673 -- PROCEDURE : derive_prev_index_amount
674 -- DESCRIPTION: This procedure is used to derive the index amount of the
675 --              the previous index rent period.  This value is needed when
676 --              calculating index rent basis type of COMPOUND.
677 --
678 ------------------------------------------------------------------------
679 
680    PROCEDURE derive_prev_index_amount (
681       p_index_lease_id    IN       NUMBER
682      ,p_assessment_date   IN       DATE
683      ,op_type             IN       VARCHAR2 -- Type: UNCONSTRAINT OR CONSTRAINT
684      ,op_index_amount     OUT NOCOPY      NUMBER
685    ) IS
686       v_index_period_id   pn_index_lease_periods.index_period_id%TYPE;
687    BEGIN
688       --put_log ('..In derive_prev_index_amount');
689 
690       --
691       -- getting the index period of the period prior to this assessment date
692       --
693       derive_index_period_id (
694          p_index_lease_id              => p_index_lease_id
695         ,p_assessment_date             => p_assessment_date
696         ,op_prev_index_lease_id        => v_index_period_id
697       );
698 
699       IF v_index_period_id IS NOT NULL THEN
700          SELECT DECODE (
701                    op_type
702                   ,'UNCONSTRAINT', unconstraint_rent_due
703                   ,'CONSTRAINT', constraint_rent_due
704                 )
705            INTO op_index_amount
706            FROM pn_index_lease_periods_all pilp
707           WHERE index_period_id = v_index_period_id;
708       END IF;
709    EXCEPTION
710       WHEN OTHERS THEN
711          put_log (   'Unable to derive prev. index amount SQLERRM:'
712                   || SQLERRM);
713    END derive_prev_index_amount;
714 
715 
716 ------------------------------------------------------------------------
717 -- PROCEDURE : derive_prev_index_amount
718 -- DESCRIPTION: This procedure is used to derive the index amount of the
719 --              the previous index rent period.  This value is needed when
720 --              calculating index rent basis type of COMPOUND.
721 --
725       p_index_lease_id    IN       NUMBER
722 ------------------------------------------------------------------------
723 
724    PROCEDURE derive_next_period_details(
726      ,p_assessment_date   IN       DATE
727      ,op_next_index_period_id OUT NOCOPY NUMBER
728      ,op_basis_start_date OUT NOCOPY DATE
729      ,op_basis_end_date OUT NOCOPY DATE
730    ) IS
731    BEGIN
732       --put_log ('..In derive_next_peroid_details');
733 
734         SELECT pilp.index_period_id,pilp.basis_start_date,pilp.basis_end_date
735         INTO op_next_index_period_id,op_basis_start_date,op_basis_end_date
736         FROM pn_index_lease_periods_all pilp
737         WHERE pilp.index_lease_id = p_index_lease_id
738         AND pilp.assessment_date = (SELECT MIN (pilp.assessment_date)
739                                     FROM pn_index_lease_periods_all pilp
740                                     WHERE pilp.index_lease_id = p_index_lease_id
741                                     AND pilp.assessment_date > p_assessment_date
742                                     );
743 
744 
745       EXCEPTION
746       WHEN OTHERS THEN
747          put_log (   'Unable to derive next periods index information SQLERRM:'
748                   || SQLERRM);
749    END derive_next_period_details;
750 
751 
752 
753 
754 ------------------------------------------------------------------------
755 -- PROCEDURE : convert_basis_to_annual_amt
756 -- DESCRIPTION: This procedure will convert a basis amount for a given index rent
757 --              period to its annual equivalent
758 ------------------------------------------------------------------------
759 
760    PROCEDURE convert_basis_to_annual_amt (
761       p_basis_amount           IN       NUMBER
762      ,p_basis_start_date       IN       DATE
763      ,p_basis_end_date         IN       DATE
764      ,op_basis_amount_annual   OUT NOCOPY      NUMBER
765    ) IS
766       v_basis_duration        NUMBER;
767       v_annual_basis_amount   pn_index_lease_periods.current_basis%TYPE;
768    BEGIN
769       v_basis_duration := CEIL (MONTHS_BETWEEN (p_basis_end_date, p_basis_start_date));
770 
771       --
772       -- get the duration of basis period (ie. no of months between
773       -- basis start and end date.
774       --
775       IF      p_basis_start_date IS NULL
776           AND p_basis_end_date IS NULL THEN
777          --
778          -- if basis start and end date, are null, assume
779          -- that initial basis is used
780          --
781          v_annual_basis_amount := p_basis_amount;
782       ELSIF v_basis_duration = 12 THEN
783          --
784          -- if the duration between basis dates is 12, assume the basis is the annual amount..
785          --
786          v_annual_basis_amount := p_basis_amount;
787       ELSE
788          v_annual_basis_amount :=   (p_basis_amount / v_basis_duration)
789                                   * 12;
790       END IF; -- p_basis_start_date is null and    p_basis_end_date is null
791 
792       --
793       -- divide basis amount by the number of months between basis dates
794       --
795 
796       op_basis_amount_annual := v_annual_basis_amount;
797    END convert_basis_to_annual_amt;
798 
799 
800 ------------------------------------------------------------------------
801       -- PROCEDURE : derive_sum_prev_actual_amounts
802       -- DESCRIPTION: This procedure is used to derive the sum of all the
803       --              actual amounts of the previous index rent periods.
804       --              This value is needed when calculating annualized basis
805       --              for basis type of COMPOUND while creating payment terms.
806       --
807    ------------------------------------------------------------------------
808 
809    PROCEDURE derive_sum_prev_actual_amounts (
810       p_lease_id            IN       NUMBER
811      ,p_index_lease_id      IN       NUMBER
812      ,p_index_period_id     IN       NUMBER
813      ,p_prev_index_amount   OUT NOCOPY      NUMBER
814    ) IS
815    BEGIN
816       --put_log ('..In derive_sum_prev_index_amount');
817 
818       SELECT SUM (
819                   ppt.actual_amount
820                 * DECODE (
821                      frequency_code
822                     ,c_spread_frequency_monthly, 12
823                     ,c_spread_frequency_quarterly, 4
824                     ,c_spread_frequency_semiannual, 2
825                     ,c_spread_frequency_annually, 1
826                     ,c_spread_frequency_one_time, 0
827                   )
828              )
829         INTO p_prev_index_amount
830         FROM pn_payment_terms_all ppt, pn_index_lease_periods_all ppi
831        WHERE ppt.index_period_id = ppi.index_period_id
832          AND ppi.index_lease_id = p_index_lease_id
833          AND ppi.assessment_date < (SELECT assessment_date
834                                       FROM pn_index_lease_periods_all
835                                      WHERE index_period_id = p_index_period_id)
836          AND ppt.lease_id = p_lease_id;
837    EXCEPTION
838       WHEN OTHERS THEN
839          put_log (   'Unable to derive sum of prev. actual amounts SQLERRM:'
840                   || SQLERRM);
841    END derive_sum_prev_actual_amounts;
842 
843 
844 ------------------------------------------------------------------------
845   -- PROCEDURE :   derive_sum_prev_index_amounts
849   --.
846   -- DESCRIPTION: This procedure is used to derive the sum of all the
847   --              index rents prior to the assessment date that is provided.
848   --              'current assessment date'
850   ------------------------------------------------------------------------
851 
852    PROCEDURE derive_sum_prev_index_amounts (
853       p_index_lease_id        IN       NUMBER
854      ,p_assessment_date       IN       DATE
855      ,op_type                 IN       VARCHAR2
856      ,p_sum_prev_index_amts   OUT NOCOPY      NUMBER
857    ) IS
858    BEGIN
859       --
860       --put_log ('..derive_sum_prev_index_amounts');
861       --
862 
863       SELECT SUM (
864                 DECODE (
865                    op_type
866                   ,'UNCONSTRAINT', unconstraint_rent_due
867                   ,'CONSTRAINT', constraint_rent_due
868                 )
869              )
870         INTO p_sum_prev_index_amts
871         FROM pn_index_lease_periods_all pilp
872        WHERE pilp.index_lease_id = p_index_lease_id
873          AND pilp.assessment_date < p_assessment_date;
874    EXCEPTION
875       WHEN OTHERS THEN
876          put_log (   'Unable to derive sum of prev. index amounts SQLERRM:'
877                   || SQLERRM);
878    END derive_sum_prev_index_amounts;
879 
880 
881 -------------------------------------------------------------------------------------------
882 -- PROCEDURE : sum_payment_items
883 -- DESCRIPTION: This procedure will sum all the payment items that is
884 --              within the date range specified of the type specified.
885 --              and of payment that is passed. type
886 --
887 -- 03-Feb-05 Kiran    o Bug # 4031003 - based on the profile value of
888 --                      PN_CALC_ANNUALIZED_BASIS decide whether to calculate
889 --                      annualized basis for the terms active as of the period
890 --                      End date or the for the entire period.
891 --                      Replaced the old 2 cursors with 4 new ones.
892 -- 19-SEP-05 piagrawa o Modified to pass org id to pn_mo_cache_utils.
893 --                      get_profile_value
894 -- 14-AUG-06 pikhar   o Added check to find out if contributing terms have
895 --                      include_in_var_rent = 'INCLUDE_RI'
896 -- 23-SEP-06 prabhakar o Modified the curosrs to fetch terms from pn_index_exclude_term_all
897 --                       with flag 'I' or from pn_payment_terms_all
898 -- 27-NOV-07 acprakas  o Bug#6457105. Modified to consider new values for system option incl_terms_by_default_flag.
899 --------------------------------------------------------------------------------------------
900 
901 PROCEDURE sum_payment_items (
902   p_index_lease_id      IN NUMBER
903  ,p_basis_start_date    IN DATE
904  ,p_basis_end_date      IN DATE
905  ,p_type_code           IN VARCHAR2 /* Payment Type: Base Rent or Operating Expense */
906  ,p_include_index_items IN VARCHAR2
907  ,op_sum_amount         OUT NOCOPY NUMBER
908 ) IS
909 
910 l_count                 NUMBER := 0;
911 l_total_sum             NUMBER := 0;
912 l_amount                PN_PAYMENT_TERMS.ACTUAL_AMOUNT%TYPE;
913 l_frequency             PN_PAYMENT_TERMS.FREQUENCY_CODE%TYPE;
914 l_payment_term_id       PN_PAYMENT_TERMS.PAYMENT_TERM_ID%TYPE;
915 l_payments              NUMBER := 0;
916 /* profile to determine how to calculate annualized basis */
917 l_calc_annualized_basis VARCHAR2(30);
918 l_org_id                NUMBER;
919 l_include_in_var_rent   VARCHAR2(30);
920 l_increase_on           VARCHAR2(30);
921 
922 /* if the parameter p_include_index_items = 'N',
923    then the select statement should ignore payment items
924    whose parent payment term is from an index increase. */
925 
926 /* gets the data from all terms active in the basis period */
927 CURSOR csr_exc_get_item_period (p_payment_type VARCHAR2,p_org_id NUMBER) IS
928   SELECT ppt.payment_term_id
929         ,NVL(ppt.actual_amount, ppt.estimated_amount)
930         ,ppt.frequency_code
931     FROM pn_payment_terms_all ppt
932         ,pn_index_leases_all pil
933    WHERE pil.index_lease_id = p_index_lease_id
934      AND ppt.lease_id = pil.lease_id
935      AND ppt.payment_term_type_code
936            = DECODE(p_payment_type, c_increase_on_gross,
937                     ppt.payment_term_type_code, p_payment_type)
938      AND NVL(ppt.index_period_id, -1) NOT IN
939           (SELECT index_period_id
940              FROM pn_index_lease_periods_all ppilx
941             WHERE ppilx.index_lease_id = p_index_lease_id)
942      AND NVL(ppt.status,'-1')
943            = DECODE(ppt.index_period_id, NULL,
944                     NVL(ppt.status,'-1'), 'APPROVED')
945      AND ppt.end_date >= p_basis_start_date
946      AND ppt.start_date <= p_basis_end_date
947      AND ppt.frequency_code <> c_spread_frequency_one_time
948      AND (
949          ppt.payment_term_id  IN (SELECT piet.payment_term_id
950          FROM pn_index_exclude_term_all piet
951          WHERE piet.index_lease_id = p_index_lease_id
952          AND piet.include_exclude_flag = 'I')
953                         OR
954          (
955          ppt.payment_term_id NOT IN (select piet.payment_term_id
956          FROM pn_index_exclude_term_all piet
957          WHERE piet.index_lease_id = p_index_lease_id)
958          AND ( pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'Y' OR
959 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'G' and  NVL(pil.gross_flag,'N') = 'Y') OR
963          )
960 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'U' and  NVL(pil.gross_flag,'N') = 'N')
961 	     )
962          )
964      AND ppt.currency_code = pil.currency_code;
965 
966 /* gets the data from all terms active on the basis period end date */
967 CURSOR csr_exc_get_item_enddate (p_payment_type VARCHAR2, p_org_id NUMBER) IS
968   SELECT ppt.payment_term_id
969         ,NVL(ppt.actual_amount, ppt.estimated_amount)
970         ,ppt.frequency_code
971     FROM pn_payment_terms_all ppt
972         ,pn_index_leases_all pil
973    WHERE pil.index_lease_id = p_index_lease_id
974      AND ppt.lease_id = pil.lease_id
975      AND ppt.payment_term_type_code
976            = DECODE(p_payment_type, c_increase_on_gross,
977                     ppt.payment_term_type_code, p_payment_type)
978      AND NVL(ppt.index_period_id, -1) NOT IN
979           (SELECT index_period_id
980              FROM pn_index_lease_periods_all ppilx
981             WHERE ppilx.index_lease_id = p_index_lease_id)
982      AND NVL(ppt.status,'-1')
983            = DECODE(ppt.index_period_id, NULL,
984                     NVL(ppt.status,'-1'), 'APPROVED')
985      AND ppt.end_date >= p_basis_end_date
986      AND ppt.start_date <= p_basis_end_date
987      AND ppt.frequency_code <> c_spread_frequency_one_time
988      AND (
989          ppt.payment_term_id  IN (SELECT piet.payment_term_id
990          FROM pn_index_exclude_term_all piet
991          WHERE piet.index_lease_id = p_index_lease_id
992          AND piet.include_exclude_flag = 'I')
993                         OR
994          (
995          ppt.payment_term_id NOT IN (select piet.payment_term_id
996 	 FROM pn_index_exclude_term_all piet
997          WHERE piet.index_lease_id = p_index_lease_id)
998          AND ( pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'Y' OR
999 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'G' and  NVL(pil.gross_flag,'N') = 'Y') OR
1000 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'U' and  NVL(pil.gross_flag,'N') = 'N')
1001 	     )
1002 	 )
1003 	 )
1004      AND ppt.currency_code = pil.currency_code;
1005 
1006 /* Only approved rent increase terms will be picked up for basis calculation */
1007 
1008 /* gets the data from all terms active in the basis period */
1009 CURSOR csr_inc_get_item_period (p_payment_type VARCHAR2,p_org_id NUMBER) IS
1010   SELECT ppt.payment_term_id
1011         ,NVL(ppt.actual_amount,ppt.estimated_amount)
1012         ,ppt.frequency_code
1013     FROM pn_payment_terms_all ppt
1014         ,pn_index_leases_all pil
1015    WHERE pil.index_lease_id = p_index_lease_id
1016      AND ppt.lease_id = pil.lease_id
1017      AND ppt.payment_term_type_code
1018          = DECODE(p_payment_type,c_increase_on_gross,
1019                   ppt.payment_term_type_code, p_payment_type)
1020      AND NVL(ppt.status,'-1')
1021          = DECODE(ppt.index_period_id,NULL,
1022                   NVL(ppt.status,'-1'),'APPROVED')
1023      AND ppt.end_date >= p_basis_start_date
1024      AND ppt.start_date <= p_basis_end_date
1025      AND ppt.frequency_code <> c_spread_frequency_one_time
1026      AND (
1027          ppt.payment_term_id  IN (SELECT piet.payment_term_id
1028          FROM pn_index_exclude_term_all piet
1029          WHERE piet.index_lease_id = p_index_lease_id
1030          AND piet.include_exclude_flag = 'I')
1031                                OR
1032          (
1033          ppt.payment_term_id NOT IN (select piet.payment_term_id
1034          FROM pn_index_exclude_term_all piet
1035          WHERE piet.index_lease_id = p_index_lease_id)
1036          AND ( pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'Y' OR
1037 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'G' and  NVL(pil.gross_flag,'N') = 'Y') OR
1038 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'U' and  NVL(pil.gross_flag,'N') = 'N')
1039 	     )
1040          )
1041          )
1042       AND ppt.currency_code = pil.currency_code;
1043 
1044 /* gets the data from all terms active on the basis period end date */
1045 CURSOR csr_inc_get_item_enddate (p_payment_type VARCHAR2,p_org_id NUMBER) IS
1046   SELECT ppt.payment_term_id
1047         ,NVL(ppt.actual_amount,ppt.estimated_amount)
1048         ,ppt.frequency_code
1049     FROM pn_payment_terms_all ppt
1050         ,pn_index_leases_all pil
1051    WHERE pil.index_lease_id = p_index_lease_id
1052      AND ppt.lease_id = pil.lease_id
1053      AND ppt.payment_term_type_code
1054          = DECODE(p_payment_type,c_increase_on_gross,
1055                   ppt.payment_term_type_code, p_payment_type)
1056      AND NVL(ppt.status,'-1')
1057          = DECODE(ppt.index_period_id,NULL,
1058                   NVL(ppt.status,'-1'),'APPROVED')
1059      AND ppt.end_date >= p_basis_end_date
1060      AND ppt.start_date <= p_basis_end_date
1061      AND ppt.frequency_code <> c_spread_frequency_one_time
1062      AND (
1063          ppt.payment_term_id  IN (SELECT piet.payment_term_id
1064          FROM pn_index_exclude_term_all piet
1065          WHERE piet.index_lease_id = p_index_lease_id
1066          AND piet.include_exclude_flag = 'I')
1067                                OR
1068          (
1069          ppt.payment_term_id NOT IN (select piet.payment_term_id
1070          FROM pn_index_exclude_term_all piet
1071          WHERE piet.index_lease_id = p_index_lease_id)
1075 	     )
1072          AND ( pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'Y' OR
1073 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'G' and  NVL(pil.gross_flag,'N') = 'Y') OR
1074 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',p_org_id) = 'U' and  NVL(pil.gross_flag,'N') = 'N')
1076          )
1077          )
1078      AND ppt.currency_code = pil.currency_code;
1079 
1080   CURSOR org_id_cur IS
1081    SELECT org_id, increase_on
1082    FROM pn_index_leases_all
1083    WHERE index_lease_id = p_index_lease_id;
1084 
1085 BEGIN
1086 
1087   put_log ('..In sum_payment_items');
1088   put_log ('..In sum_payment_items p_basis_start_date'|| to_char(p_basis_start_date));
1089   put_log ('..In sum_payment_items p_basis_end_date'|| to_char(p_basis_end_date));
1090 
1091   l_total_sum := 0;
1092   l_count := 0;
1093 
1094   FOR org_id_rec IN org_id_cur LOOP
1095      l_org_id := org_id_rec.org_id;
1096      l_increase_on := org_id_rec.increase_on;
1097   END LOOP;
1098 
1099   /* get the value for the PN_CALC_ANNUALIZED_BASIS profile */
1100   l_calc_annualized_basis
1101     := pn_mo_cache_utils.get_profile_value('PN_CALC_ANNUALIZED_BASIS', l_org_id);
1102 
1103   /*  if increase on GROSS, get all payment items regardless of type */
1104 
1105   IF p_type_code = c_increase_on_gross THEN
1106 
1107     /* summing all cash items regardless of type... */
1108 
1109     IF p_include_index_items = 'N' THEN
1110 
1111       IF NVL(l_calc_annualized_basis,'PERIOD') = 'PERIOD' THEN
1112 
1113         OPEN csr_exc_get_item_period (c_increase_on_gross,l_org_id);
1114 
1115       ELSIF NVL(l_calc_annualized_basis,'PERIOD') = 'ENDDATE' THEN
1116 
1117         OPEN csr_exc_get_item_enddate (c_increase_on_gross,l_org_id);
1118 
1119       END IF;
1120 
1121     ELSIF p_include_index_items = 'Y' THEN
1122 
1123       IF NVL(l_calc_annualized_basis,'PERIOD') = 'PERIOD' THEN
1124 
1125         OPEN csr_inc_get_item_period (c_increase_on_gross,l_org_id);
1126 
1127       ELSIF NVL(l_calc_annualized_basis,'PERIOD') = 'ENDDATE' THEN
1128 
1129         OPEN csr_inc_get_item_enddate (c_increase_on_gross,l_org_id);
1130 
1131       END IF;
1132 
1133     END IF;
1134 
1135   ELSE
1136     /* summing all cash items for the particular payment type... */
1137 
1138     IF p_include_index_items = 'N' THEN
1139 
1140       IF NVL(l_calc_annualized_basis,'PERIOD') = 'PERIOD' THEN
1141 
1142         OPEN csr_exc_get_item_period (p_type_code,l_org_id);
1143 
1144       ELSIF NVL(l_calc_annualized_basis,'PERIOD') = 'ENDDATE' THEN
1145 
1146         OPEN csr_exc_get_item_enddate (p_type_code,l_org_id);
1147 
1148       END IF;
1149 
1150     ELSIF p_include_index_items = 'Y' THEN
1151 
1152       IF NVL(l_calc_annualized_basis,'PERIOD') = 'PERIOD' THEN
1153 
1154         OPEN csr_inc_get_item_period (p_type_code,l_org_id);
1155 
1156       ELSIF NVL(l_calc_annualized_basis,'PERIOD') = 'ENDDATE' THEN
1157 
1158         OPEN csr_inc_get_item_enddate (p_type_code,l_org_id);
1159 
1160       END IF;
1161 
1162     END IF;
1163 
1164   END IF;
1165 
1166   /* Get each of the payment term and the payment term amount and
1167      store it in a PL/SQL table . Also add it to op_sum_amount to get the
1168      total amount of all the payment terms */
1169   g_include_in_var_check := NULL;
1170   g_include_in_var_rent  := NULL;
1171   LOOP
1172 
1173     l_count := l_count + 1;
1174 
1175     put_log('..Before fetch'|| p_include_index_items);
1176     put_log('..Before fetch...l_payment_term_id = ' || l_payment_term_id);
1177     put_log('..Before fetch...l_amount = ' || l_amount);
1178     put_log('..Before fetch...l_frequency = ' || l_frequency);
1179 
1180     IF csr_exc_get_item_period%ISOPEN THEN
1181 
1182       FETCH csr_exc_get_item_period INTO
1183         l_payment_term_id,
1184         l_amount,
1185         l_frequency;
1186 
1187       EXIT WHEN csr_exc_get_item_period%NOTFOUND;
1188 
1189     ELSIF csr_exc_get_item_enddate%ISOPEN THEN
1190 
1191       FETCH csr_exc_get_item_enddate INTO
1192         l_payment_term_id,
1193         l_amount,
1194         l_frequency;
1195 
1196       EXIT WHEN csr_exc_get_item_enddate%NOTFOUND;
1197 
1198     ELSIF csr_inc_get_item_period%ISOPEN THEN
1199 
1200       FETCH csr_inc_get_item_period INTO
1201         l_payment_term_id,
1202         l_amount,
1203         l_frequency;
1204 
1205       EXIT WHEN csr_inc_get_item_period%NOTFOUND;
1206 
1207     ELSIF csr_inc_get_item_enddate%ISOPEN THEN
1208 
1209       FETCH csr_inc_get_item_enddate INTO
1210         l_payment_term_id,
1211         l_amount,
1212         l_frequency;
1213 
1214       EXIT WHEN csr_inc_get_item_enddate%NOTFOUND;
1215 
1216     END IF;
1217 
1218     put_log ('..After fetch'|| p_include_index_items);
1219 
1220     put_log('..After fetch...l_payment_term_id = ' || l_payment_term_id);
1221     put_log('..After fetch...l_amount = ' || l_amount);
1222     put_log('..After fetch...l_frequency = ' || l_frequency);
1223 
1224     IF l_frequency = 'MON' THEN
1225       l_payments := 12;
1226     ELSIF l_frequency = 'QTR' THEN
1227        l_payments :=  4;
1231        l_payments :=  1;
1228     ELSIF l_frequency = 'SA' THEN
1229        l_payments :=  2;
1230     ELSIF l_frequency = 'YR' THEN
1232     END IF;
1233 
1234     l_total_sum := nvl(l_total_sum,0) + nvl(l_amount,0) * l_payments;
1235 
1236     /* This is used to find if the contributing terms have same value for
1237        include_in_var_rent */
1238 
1239 
1240     IF l_increase_on is NOT NULL THEN
1241        SELECT include_in_var_rent
1242        INTO l_include_in_var_rent
1243        FROM pn_payment_terms_all ppt
1244        WHERE ppt.payment_term_id = l_payment_term_id
1245        AND ppt.payment_term_type_code = nvl(p_type_code,ppt.payment_term_type_code);
1246     ELSE
1247        SELECT include_in_var_rent
1248        INTO l_include_in_var_rent
1249        FROM pn_payment_terms_all ppt
1250        WHERE ppt.payment_term_id = l_payment_term_id;
1251     END IF;
1252 
1253     IF l_count = 1 THEN
1254        g_include_in_var_rent := l_include_in_var_rent;
1255        g_include_in_var_check := 'T';
1256        l_count := l_count + 1;
1257     ELSE
1258        IF nvl(g_include_in_var_rent,'F') <> nvl(l_include_in_var_rent,'F') THEN
1259           g_include_in_var_check := 'F';
1260        END IF;
1261     END IF;
1262 
1263   END LOOP;
1264 
1265   IF csr_exc_get_item_period%ISOPEN THEN
1266 
1267     CLOSE csr_exc_get_item_period;
1268 
1269   ELSIF csr_exc_get_item_enddate%ISOPEN THEN
1270 
1271     CLOSE csr_exc_get_item_enddate;
1272 
1273   ELSIF csr_inc_get_item_period%ISOPEN THEN
1274 
1275     CLOSE csr_inc_get_item_period;
1276 
1277   ELSIF csr_inc_get_item_enddate%ISOPEN THEN
1278 
1279     CLOSE csr_inc_get_item_enddate;
1280 
1281   END IF;
1282 
1283   op_sum_amount := l_total_sum;
1284 
1285 END sum_payment_items;
1286 
1287 ------------------------------------------------------------------------
1288 -- PROCEDURE : calculate_basis_amount
1289 -- DESCRIPTION: This procedure will calculate the basis amount for a given index rent period
1290 -- HISTORY
1291 -- 13-FEB-04 ftanudja o removed redundant 'UPDATE pn_index_leases set initial_basis..' 3436147
1292 -- 05-JUN-07 Prabhakar o bug #6110109. In case of compound, the annulaised basis amount
1293 --                       amount is made zero instead of NULL, when basis amount is zero.
1294 ------------------------------------------------------------------------
1295 
1296    PROCEDURE calculate_basis_amount (
1297       p_index_lease_id      IN       NUMBER
1298      ,p_basis_start_date    IN       DATE
1299      ,p_basis_end_date      IN       DATE
1300      ,p_assessment_date     IN       DATE
1301      ,p_initial_basis       IN       NUMBER
1302      ,p_line_number         IN       NUMBER
1303      ,p_increase_on         IN       VARCHAR2
1304      ,p_basis_type          IN       VARCHAR2
1305      ,p_prev_index_amount   IN       NUMBER
1306      ,p_recalculate         IN       VARCHAR2   -- Fix for bug# 1956128
1307      ,op_basis_amount       OUT NOCOPY      NUMBER
1308      ,op_msg                OUT NOCOPY      VARCHAR2
1309    ) IS
1310 
1311     --v_basis_amt_oper_expenses   NUMBER;
1312     --v_basis_amt_base_rent       NUMBER;
1313       v_prev_index_amt          pn_index_lease_periods.constraint_rent_due%TYPE;
1314       v_msg                     VARCHAR2 (1000);
1315       v_basis_amount            pn_index_lease_periods.current_basis%TYPE;
1316       v_previous_basis_amount   pn_index_lease_periods.current_basis%TYPE;
1317       v_previous_index_id       pn_index_lease_periods.index_period_id%TYPE;
1318       v_sum_prev_index_amts     NUMBER;
1319       v_annual_basis_amount     NUMBER;
1320 
1321    BEGIN
1322       put_log ('..IN CALCULATE_BASIS_AMOUNT');
1323       --put_log (   '      Basis Type       = '
1324       --         || p_basis_type);
1325 
1326       --
1327       -- if index rent and main lease commencement dates are equal
1328       --      basis start and end date will be null
1329       --
1330       IF      p_basis_start_date IS NULL
1331           AND p_basis_end_date IS NULL THEN
1332          --
1333          -- If Basis Dates are Blank
1334          --
1335          --        use initial basis,
1336 
1337 
1338          IF p_initial_basis IS NOT NULL THEN
1339             v_annual_basis_amount := p_initial_basis;
1340          ELSE
1341             v_msg := 'PN_INDEX_INIT_BASIS_REQD';
1342          END IF;
1343       ELSE
1344 
1345                  IF p_basis_type = c_basis_type_fixed THEN
1346 
1347                            -- if basis type = fixed use initial basis for basis amt.
1348 
1349                            v_annual_basis_amount := p_initial_basis;
1350 
1351                  ELSIF p_basis_type = c_basis_type_rolling THEN
1352 
1353                             IF p_line_number = 1 THEN
1354 
1355                                    v_annual_basis_amount := p_initial_basis;
1356 
1357                             ELSE    -- period <> 1
1358                           put_log('rolling **** bst dt' || p_basis_start_date);
1359                           put_log('rolling **** ben dt' || p_basis_end_date);
1360                           put_log('rolling **** p_increase_on ' || p_increase_on);
1361                           put_log('rolling **** p_index_lease_id ' || to_char(p_index_lease_id));
1362                             sum_payment_items (
1363                                p_index_lease_id              => p_index_lease_id
1364                               ,p_basis_start_date            => p_basis_start_date
1365                               ,p_basis_end_date              => p_basis_end_date
1366                               ,p_type_code                   => p_increase_on
1367                               ,op_sum_amount                 => v_annual_basis_amount
1368                             );
1369                           put_log('rolling **** v_annual_basis_amount ' || to_char(v_annual_basis_amount));
1370 
1371                             END IF;
1372 
1373                  ELSIF p_basis_type = c_basis_type_compound THEN
1374                             --
1375                             -- From Compound basis type, we need the index amount from previous period
1376                             --
1377 
1378                             IF p_prev_index_amount IS NULL and p_line_number <> 1 THEN
1379                                -- derive previous index amount.
1380                                derive_prev_index_amount (
1381                                   p_index_lease_id              => p_index_lease_id
1382                                  ,p_assessment_date             => p_assessment_date
1383                                  ,op_type                       => 'CONSTRAINT'
1384                                  ,op_index_amount               => v_prev_index_amt
1385                                );
1386                             ELSE
1387                                v_prev_index_amt := p_prev_index_amount;
1388                             END IF;
1389 
1390                             IF v_prev_index_amt IS NULL THEN
1391                                IF p_line_number = 1 THEN
1392                                   v_prev_index_amt := 0;
1393                                   v_sum_prev_index_amts := 0;
1394                                ELSE
1395                                   v_msg := 'PN_INDEX_PREV_INDEX_REQ';
1396                                END IF; -- p_line_number = 1 THEN
1397                             END IF; --v_prev_index_amt IS NULL
1398 
1399                             --
1400                             -- the general rule the basis amount for compounding is to use the basis amount
1401                             --    of the previous period. EXCEPT for the first period..
1402                             --
1403                             -- for the first period,
1404                             --    use initial basis,
1405                             --      if initial basis is not availble, calculate the basis using INCREASE ON type
1406                             --
1407 
1408 
1409 
1410                             IF p_line_number = 1 THEN
1411 
1412                                   -- initial basis for basis amt.
1413                                   v_previous_basis_amount := p_initial_basis;
1414 
1415                             ELSE -- p_line_number = 1
1416                                 --
1417                                 -- processing line number > 2
1418                                 --
1419                                 --
1420                                 -- in the compound scenario,
1421                                 --  when summing up items, we should not include
1422                                 --    index items b/c the basis amount already includes
1423                                 --    constraint rent amount of previous index periods
1424                                 --
1425 
1426                                sum_payment_items (
1427                                   p_index_lease_id              => p_index_lease_id
1428                                  ,p_basis_start_date            => p_basis_start_date
1429                                  ,p_basis_end_date              => p_basis_end_date
1430                                  ,p_type_code                   => p_increase_on
1431                                  ,p_include_index_items         => 'N'
1432                                  ,op_sum_amount                 => v_previous_basis_amount
1436                                IF v_prev_index_amt IS NOT NULL THEN
1433                                );
1434 
1435                                -- deriving the sum of all the previous index rent increases
1437                                   derive_sum_prev_index_amounts (
1438                                      p_index_lease_id              => p_index_lease_id
1439                                     ,p_assessment_date             => p_assessment_date
1440                                     ,op_type                       => 'CONSTRAINT'
1441                                     ,p_sum_prev_index_amts         => v_sum_prev_index_amts
1442                                   );
1443                                ELSE
1444                                   v_sum_prev_index_amts := NULL;
1445                                END IF;
1446                             END IF; -- p_line_number = ???
1447 
1448                             IF nvl(v_previous_basis_amount,0) = 0 THEN
1449                                --v_annual_basis_amount := null;  bug #6110109
1450                                v_annual_basis_amount := 0;
1451                             ELSE
1452                                v_annual_basis_amount := v_previous_basis_amount
1453                                                       + v_sum_prev_index_amts;
1454                             END IF;
1455 
1456                  END IF; -- p_basis_type = ???
1457                  put_log ('calculate_basis_amount **** v_previous_basis_amount '||v_previous_basis_amount);
1458                  put_log ('calculate_basis_amount **** v_sum_prev_index_amts '||v_sum_prev_index_amts);
1459 
1460       END IF; -- p_basis_start_date is not null and p_basis_end_date is not null
1461 
1462       op_msg := v_msg;
1463       op_basis_amount := v_annual_basis_amount;
1464        put_log ('calculate_basis_amount **** op_basis_amount ' || to_char(op_basis_amount));
1465    END calculate_basis_amount;
1466 
1467 
1468 ------------------------------------------------------------------------
1469 -- PROCEDURE : calculate_initial_basis
1470 -- DESCRIPTION: This procedure will calculate the initial basis for a given
1471 --
1472 --
1473 ------------------------------------------------------------------------
1474 
1475    PROCEDURE calculate_initial_basis (
1476       p_index_lease_id   IN       NUMBER
1477      ,op_basis_amount    OUT NOCOPY      NUMBER
1478      ,op_msg             OUT NOCOPY      VARCHAR2
1479    ) IS
1480 
1481 /*
1482    IF INCREASE_ON = Base Rent THEN
1483             sum all payment items of type = Base Rent (Code: BASER), between the basis start and end date;
1484 
1485          ELSE IF INCREASE_ON = Operating Expenses
1486             sum all payment items of type = Operating Expenses (Code: OEXP) , between the basis start and end date;
1487 
1488          ELSE IF INCREASE_ON = Gross Rent
1489             sum all payment items of type = Base Rent (Code: BASER) AND Operating Expenses (Code: OEXP), between the basis
1490 start and end date;
1491 
1492 */
1493 
1494       CURSOR ilp_curr (
1495          p_index_lease_id   IN   NUMBER
1496       ) IS
1497          SELECT pil.index_lease_id
1498                ,pil.initial_basis
1499                ,pil.basis_type
1500                ,nvl(pil.increase_on,c_increase_on_gross) "INCREASE_ON"
1501                ,pilp.index_period_id
1502                ,pilp.basis_start_date
1503                ,pilp.basis_end_date
1504            FROM pn_index_leases_all pil, pn_index_lease_periods_all pilp
1505           WHERE pil.index_lease_id = pilp.index_lease_id
1506             AND pil.index_lease_id = p_index_lease_id
1507             AND pilp.line_number = 1;
1508 
1509       ilp_rec                     ilp_curr%ROWTYPE;
1510       v_basis_amt_oper_expenses   pn_index_lease_periods.current_basis%TYPE;
1511       v_basis_amt_base_rent       pn_index_lease_periods.current_basis%TYPE;
1512       --v_prev_index_amt            NUMBER;
1513       v_basis_amount              pn_index_lease_periods.current_basis%TYPE;
1514       v_msg                       VARCHAR2 (1000);
1515       v_annual_basis_amt          pn_index_lease_periods.current_basis%TYPE;
1516       l_include_index_items       VARCHAR2(1) := null;
1517 
1518    BEGIN
1519       put_log ('..In calculate_initial_basis');
1520       OPEN ilp_curr (p_index_lease_id);
1521       FETCH ilp_curr INTO ilp_rec;
1522 
1523       IF (ilp_curr%NOTFOUND) THEN
1524          CLOSE ilp_curr;
1525          op_msg := 'PN_AT_LEAST_ONE_PERIOD_REQD';
1526          put_log ('    Error: Index or Main Lease not found');
1527          RETURN;
1528       END IF;
1529 
1530       --
1531       -- if index rent and main lease commencement dates are equal
1532       --      basis start and end date will be null
1533       --
1534       IF      ilp_rec.basis_start_date IS NULL
1535           AND ilp_rec.basis_end_date IS NULL THEN
1536          --
1537          -- If Basis Dates are Blank
1538          --
1539          --        use initial basis,
1540 
1541          IF ilp_rec.initial_basis IS NOT NULL THEN
1542             v_annual_basis_amt := ilp_rec.initial_basis;
1543          ELSE
1544             --
1545             -- if initial basis is blank, send back error.
1546             --
1547             v_msg := 'PN_INDEX_INIT_BASIS_REQD';
1548          END IF;
1549       ELSE
1550 
1551          IF ilp_rec.basis_type = c_basis_type_compound THEN
1552 
1553             l_include_index_items := 'N';
1554 
1555          ELSE
1556 
1560 
1557             l_include_index_items := 'Y';
1558 
1559          END IF;
1561          sum_payment_items (
1562                p_index_lease_id              => p_index_lease_id
1563               ,p_basis_start_date            => ilp_rec.basis_start_date
1564               ,p_basis_end_date              => ilp_rec.basis_end_date
1565               ,p_type_code                   => ilp_rec.increase_on
1566               ,p_include_index_items         => l_include_index_items                 -- Bug#2101480
1567               ,op_sum_amount                 => v_annual_basis_amt
1568             );
1569 
1570       END IF; --p_basis_start_date is not null and p_basis_end_date is not null
1571 
1572       CLOSE ilp_curr;
1573       op_msg := v_msg;
1574       op_basis_amount := v_annual_basis_amt;
1575    END calculate_initial_basis;
1576 
1577 
1578 ------------------------------------------------------------------------
1579 -- PROCEDURE : calculate_index_amount
1580 -- DESCRIPTION: This procedure will calculate the UNCONSTRAINED index amount for
1581 --              a given index rent period
1582 --
1583 ------------------------------------------------------------------------
1584    PROCEDURE calculate_index_amount (
1585       p_relationship               IN         VARCHAR2
1586      ,p_basis_percent_change       IN         NUMBER
1587      ,p_adj_index_percent_change   IN         NUMBER
1588      ,p_current_basis              IN         NUMBER
1589      ,op_index_amount         OUT NOCOPY      NUMBER
1590      ,op_msg                  OUT NOCOPY      VARCHAR2
1591    ) IS
1592       v_annual_basis_amt        pn_index_lease_periods.current_basis%TYPE;
1593       v_percent_multiplier      NUMBER;
1594       v_found_all_reqd_fields   BOOLEAN;
1595       v_index_rent_amount       pn_index_lease_periods.unconstraint_rent_due%TYPE;
1596       v_msg                     VARCHAR2 (1000);
1597    BEGIN
1598       --put_log ('..In calculate_index_amount');
1599       --
1600       -- detemine if all required to calculate the index is available.
1601       --
1602       v_found_all_reqd_fields := FALSE;
1603 
1604       IF p_relationship = c_relation_basis_only THEN
1605          IF      p_basis_percent_change IS NOT NULL
1606              AND p_current_basis IS NOT NULL THEN
1607             v_found_all_reqd_fields := TRUE;
1608          ELSE
1609             v_msg := 'PN_INDEX_REQD_FLDS_BASIS_ONLY';
1610          END IF;
1611       ELSIF p_relationship = c_relation_index_only THEN
1612          IF      p_adj_index_percent_change IS NOT NULL
1613              AND p_current_basis IS NOT NULL THEN
1614             v_found_all_reqd_fields := TRUE;
1615          ELSE
1616             v_msg := 'PN_INDEX_REQD_FLDS_INDEX_ONLY';
1617          END IF;
1618       ELSIF p_relationship IN (c_relation_greater_of, c_relation_lesser_of) THEN
1619          IF      p_adj_index_percent_change IS NOT NULL
1620              AND p_current_basis IS NOT NULL
1621              AND p_basis_percent_change IS NOT NULL THEN
1622             v_found_all_reqd_fields := TRUE;
1623          ELSE
1624             v_msg := 'PN_INDEX_REQD_FLDS_GT_LT_ONLY';
1625          END IF;
1626       END IF;
1627 
1628       -- Only calculate the index if all required fields are available.
1629 
1630       IF v_found_all_reqd_fields THEN
1631 
1632 --   Determine the multiplier to the basis amount to get the index amount.
1633 --   Relationship          Method
1634 --   ************          ****************
1635 --   Basis Only            use the basis percentage as multiplier
1636 --   Index Only            use the index percentage as multiplier
1637 --   Greater of            Get the the greater value between index and basis percentage as multiplier
1638 --   Lesser of             Get the the lesser value between index and basis percentage as multiplier
1639 
1640          IF p_relationship = c_relation_basis_only THEN
1641             v_percent_multiplier := p_basis_percent_change / 100;
1642          ELSIF p_relationship = c_relation_index_only THEN
1643             v_percent_multiplier := p_adj_index_percent_change / 100;
1644          ELSIF p_relationship = c_relation_greater_of THEN
1645             v_percent_multiplier :=
1646                            GREATEST (p_adj_index_percent_change, p_basis_percent_change) / 100;
1647          ELSIF p_relationship = c_relation_lesser_of THEN
1648             v_percent_multiplier :=
1649                               LEAST (p_adj_index_percent_change, p_basis_percent_change) / 100;
1650          END IF; -- p_relationship =
1651 
1652          v_annual_basis_amt := p_current_basis;
1653          --
1654          -- calculating unconstrained index amount.
1655          --
1656          v_index_rent_amount := v_annual_basis_amt * v_percent_multiplier;
1657          op_index_amount := ROUND (v_index_rent_amount, get_amount_precision);
1658       ELSE
1659          op_msg := v_msg;
1660       END IF; --  v_found_all_reqd_fields
1661    END calculate_index_amount;
1662 
1663 
1664 
1665 
1666 ------------------------------------------------------------------------
1667 -- PROCEDURE : derive_constrained_rent
1668 -- DESCRIPTION: This procedure will:
1669 --              apply all constraints that have been defined for a given index rent.
1670 --              process negative rent as defined in agreement
1671 --              apply rounding as defined in agreement
1672 --
1673 -- 12-DEC-2006 Prabhakar o Added parameter p_prorate_factor
1674 -- 17-APR-2007 Prabhakar o Bug #5988076. Modifyied the way of deriving
1678       p_index_lease_id              IN       NUMBER
1675 --                         negative rent in case of Next Period.
1676 ------------------------------------------------------------------------
1677    PROCEDURE derive_constrained_rent (
1679      ,p_current_basis               IN       NUMBER
1680      ,p_index_period_id             IN       NUMBER
1681      ,p_assessment_date             IN       DATE
1682      ,p_negative_rent_type          IN       VARCHAR2
1683      ,p_unconstrained_rent_amount   IN       NUMBER
1684      ,p_prev_index_amount           IN       NUMBER
1685      ,p_carry_forward_flag          IN       VARCHAR2
1686      ,p_prorate_factor              IN       NUMBER
1687      ,op_constrained_rent_amount    OUT NOCOPY      NUMBER
1688      ,op_constraint_applied_amount  OUT NOCOPY      NUMBER
1689      ,op_constraint_applied_percent OUT NOCOPY      NUMBER
1690      ,op_carry_forward_amount       OUT NOCOPY      NUMBER
1691      ,op_carry_forward_percent      OUT NOCOPY      NUMBER
1692      ,op_msg                        OUT NOCOPY      VARCHAR2
1693    )
1694    IS
1695    CURSOR il_cons ( ip_index_lease_id   IN   NUMBER, ip_prorate_factor IN NUMBER ) IS
1696    SELECT scope,
1697           ( maximum_amount * ip_prorate_factor ) maximum_amount,
1698           ( maximum_percent * ip_prorate_factor ) maximum_percent,
1699           ( minimum_amount * ip_prorate_factor ) minimum_amount,
1700           ( minimum_percent * ip_prorate_factor ) minimum_percent
1701    FROM pn_index_lease_constraints_all
1702    WHERE index_lease_id = ip_index_lease_id;
1703 
1704    l_lower_bound_amt                NUMBER:=null;
1705    l_upper_bound_amt                NUMBER:=null;
1706    l_min_current_period             NUMBER:=null;
1707    l_max_current_period             NUMBER:=null;
1708    l_prev_period_index_amt          pn_index_lease_periods.constraint_rent_due%type:=null;
1709    l_previous_negative_rent         pn_index_lease_periods.unconstraint_rent_due%type:=null;
1710    l_constrained_amount             pn_index_lease_periods.constraint_rent_due%type:=null;
1711    l_unconstrained_amount           pn_index_lease_periods.unconstraint_rent_due%type:=null;
1712    l_last_index_period_id           pn_index_lease_periods.index_period_id%type:=null;
1713    l_min_current_constr_pct         pn_index_lease_periods.constraint_applied_percent%type:=null;
1714    l_max_current_constr_pct         pn_index_lease_periods.constraint_applied_percent%type:=null;
1715    l_min_current_constr_amt         pn_index_lease_periods.constraint_applied_amount%type:=null;
1716    l_max_current_constr_amt         pn_index_lease_periods.constraint_applied_amount%type:=null;
1717    l_lower_bound_const_pct          pn_index_lease_periods.constraint_applied_percent%type:=null;
1718    l_lower_bound_const_amt          pn_index_lease_periods.constraint_applied_amount%type:=null;
1719    l_upper_bound_const_pct          pn_index_lease_periods.constraint_applied_percent%type:=null;
1720    l_upper_bound_const_amt          pn_index_lease_periods.constraint_applied_amount%type:=null;
1721    l_carry_forward_amount           pn_index_lease_periods.carry_forward_amount%type:=null;
1722    l_carry_forward_percent          pn_index_lease_periods.carry_forward_percent%type:=null;
1723 
1724    BEGIN
1725 
1726       put_log ('pn_index_amount_pkg.derive_constrained_rent   (+): ');
1727       put_log('derive_constrained_rent - p_index_lease_id :'||p_index_lease_id);
1728       put_log('derive_constrained_rent - p_current_basis  :'||p_current_basis);
1729       put_log('derive_constrained_rent - p_index_period_id :'||p_index_period_id);
1730       put_log('derive_constrained_rent - p_negative_rent_type :'||p_negative_rent_type);
1731       put_log('derive_constrained_rent - p_unconstrained_rent_amount :'||p_unconstrained_rent_amount);
1732       put_log('derive_constrained_rent - p_prev_index_amount :'||p_prev_index_amount);
1733       put_log('derive_constrained_rent - p_carry_forward_flag :'||p_carry_forward_flag);
1734 
1735       l_prev_period_index_amt := p_prev_index_amount;
1736 
1737 
1738       /* Derive the minimum constraint and the maximum constraint */
1739 
1740       FOR il_rec IN il_cons (p_index_lease_id, p_prorate_factor)
1741       LOOP
1742          put_log('derive_constrained_rent - Scope           :'||il_rec.scope);
1743          put_log('derive_constrained_rent - minimum_percent :'||il_rec.minimum_percent);
1744          put_log('derive_constrained_rent - maximum_percent :'||il_rec.maximum_percent);
1745          put_log('derive_constrained_rent - minimum_amount  :'||il_rec.minimum_amount);
1746          put_log('derive_constrained_rent - maximum_amount  :'||il_rec.maximum_amount);
1747 
1748          l_min_current_period := null;
1749          l_max_current_period := null;
1750          l_min_current_constr_pct := null;
1751          l_max_current_constr_pct := null;
1752          l_min_current_constr_amt := null;
1753          l_max_current_constr_amt := null;
1754 
1755          IF il_rec.scope = c_constraint_rent_due THEN
1756 
1757             if il_rec.minimum_percent is not null then
1758                l_min_current_period := (il_rec.minimum_percent/100) * p_current_basis;
1759                l_min_current_constr_pct := il_rec.minimum_percent;
1760             elsif il_rec.minimum_amount is not null then
1761                l_min_current_period := il_rec.minimum_amount;
1762                l_min_current_constr_amt := il_rec.minimum_amount;
1763             end if;
1764 
1765             if il_rec.maximum_percent is not null then
1766                l_max_current_period := (il_rec.maximum_percent/100) * p_current_basis;
1767                l_max_current_constr_pct := il_rec.maximum_percent;
1771             end if;
1768             elsif il_rec.maximum_amount is not null then
1769                l_max_current_period := il_rec.maximum_amount;
1770                l_max_current_constr_amt := il_rec.maximum_amount;
1772 
1773          ELSIF il_rec.scope = c_constraint_period_to_period THEN
1774 
1775             /* derive the previous periods constrained rent amount. */
1776 
1777             if l_prev_period_index_amt is null then
1778                derive_prev_index_amount (
1779                     p_index_lease_id              => p_index_lease_id,
1780                     p_assessment_date             => p_assessment_date,
1781                     op_type                       => 'CONSTRAINT',
1782                     op_index_amount               => l_prev_period_index_amt);
1783             end if;
1784 
1785             if il_rec.minimum_percent is not null then
1786                l_min_current_period := l_prev_period_index_amt * ( (il_rec.minimum_percent/100) + 1);
1787                l_min_current_constr_pct := il_rec.minimum_percent;
1788             elsif il_rec.minimum_amount is not null then
1789                l_min_current_period := l_prev_period_index_amt + il_rec.minimum_amount ;
1790                l_min_current_constr_amt := il_rec.minimum_amount;
1791             end if;
1792 
1793             if il_rec.maximum_percent is not null then
1794                l_max_current_period := l_prev_period_index_amt * ( (il_rec.maximum_percent/100) + 1);
1795                l_max_current_constr_pct := il_rec.maximum_percent;
1796             elsif il_rec.maximum_amount is not null then
1797                l_max_current_period := l_prev_period_index_amt + il_rec.maximum_amount;
1798                l_max_current_constr_amt := il_rec.maximum_amount;
1799             end if;
1800 
1801          END IF;     --- il_rec.scope = c_constraint_rent_due
1802 
1803          put_log('derive_constrained_rent - l_min_current_period  :'||l_min_current_period);
1804          put_log('derive_constrained_rent - l_max_current_period  :'||l_max_current_period);
1805 
1806          /* Get the greatest of all minimums and the least of all maximum constraints */
1807 
1808          IF l_lower_bound_amt is null or
1809             nvl(l_min_current_period,l_lower_bound_amt) > l_lower_bound_amt then
1810 
1811             l_lower_bound_amt := l_min_current_period;
1812             l_lower_bound_const_pct := l_min_current_constr_pct;
1813             l_lower_bound_const_amt := l_min_current_constr_amt;
1814          END IF;
1815 
1816          IF l_upper_bound_amt is null or
1817             nvl(l_max_current_period,l_upper_bound_amt) < l_upper_bound_amt then
1818 
1819             l_upper_bound_amt := l_max_current_period;
1820             l_upper_bound_const_pct := l_max_current_constr_pct;
1821             l_upper_bound_const_amt := l_max_current_constr_amt;
1822          END IF;
1823 
1824        END LOOP constraints;
1825 
1826 
1827        put_log('derive_constrained_rent - min constraint for the period :'||l_lower_bound_amt);
1828        put_log('derive_constrained_rent - max constraint for the period :'||l_upper_bound_amt);
1829 
1830 
1831        l_unconstrained_amount  := p_unconstrained_rent_amount;
1832 
1833 
1834       /* Handle negative rent.
1835          o if negative rent type is ignore then current rent due is 0
1836          o if negative rent type is next period then if current period
1837            is not the last period then l_constrained rent := 0
1838          o if negative rent type is next period then if current period is
1839            the last period or l_unconstrained_amount >0 then derive the previous
1840            periods negative rent and add to the current periods unconstrained rent
1841            due. */
1842 
1843 
1844       IF p_negative_rent_type = c_negative_rent_ignore AND
1845          l_unconstrained_amount < 0 THEN
1846 
1847          l_unconstrained_amount := 0;
1848 
1849       ELSIF p_negative_rent_type = c_negative_rent_next_period THEN
1850 
1851          /* get the id of the last index rent period.*/
1852 
1853          derive_index_period_id (
1854                p_index_lease_id              => p_index_lease_id,
1855                p_assessment_date             => NULL,
1856                op_prev_index_lease_id        => l_last_index_period_id );
1857 
1858          l_last_index_period_id := nvl(l_last_index_period_id,p_index_period_id);
1859 
1860 
1861          if l_unconstrained_amount < 0 and
1862             l_last_index_period_id <> p_index_period_id then
1863 
1864             l_unconstrained_amount := 0;
1865 
1866          elsif l_unconstrained_amount >= 0   or
1867                l_last_index_period_id = p_index_period_id  then
1868 
1869           /* get the previous periods negative index rent */
1870 
1871             l_previous_negative_rent := derive_prev_negative_rent(
1872                                                p_index_lease_id   => p_index_lease_id,
1873                                                p_assessment_date  => p_assessment_date);
1874 
1875             l_unconstrained_amount :=   l_unconstrained_amount + nvl(l_previous_negative_rent,0);
1876 
1877             if l_unconstrained_amount < 0 and l_last_index_period_id <> p_index_period_id then
1878                 l_unconstrained_amount := 0;
1879             end if;
1880 
1881          end if;
1882 
1883       END IF; -- p_negative_rent_type = c_negative_rent_next_period
1884 
1885 
1886 
1887       /* Add carry forward amounts to unconstrained rent due if carry forward flag is checked */
1888 
1889 
1893 
1890        put_log('derive_constrained_rent - before adding carry forward amt,l_unconstrained_amount :' ||l_unconstrained_amount);
1891 
1892        IF p_carry_forward_flag IN('A','P') THEN
1894           derive_cum_carry_forward(
1895                                    p_index_lease_id   => p_index_lease_id,
1896                                    p_assessment_date  => p_assessment_date,
1897                                    op_carry_forward_amount => l_carry_forward_amount,
1898                                    op_carry_forward_percent => l_carry_forward_percent);
1899 
1900           if p_carry_forward_flag ='A' then
1901              l_unconstrained_amount := l_unconstrained_amount + nvl(l_carry_forward_amount,0);
1902              l_carry_forward_amount := 0;
1903           else
1904              l_unconstrained_amount := l_unconstrained_amount +
1905                                        (nvl(l_carry_forward_percent,0)* (p_current_basis/100));
1906              l_carry_forward_percent := 0;
1907           end if;
1908 
1909        END IF;
1910 
1911 
1912        put_log('derive_constrained_rent - after adding carry forward amt,l_unconstrained_amount :'||l_unconstrained_amount);
1913 
1914       /* Apply constraints */
1915 
1916       IF nvl(l_upper_bound_amt, l_lower_bound_amt) < nvl(l_lower_bound_amt, l_upper_bound_amt) THEN
1917 
1918          put_log ('ERROR: INVALID RANGE DERIVED BY CONSTRAINTS.....');
1919          put_log ('l_lower_bound_amt = ' || l_lower_bound_amt);
1920          put_log ('l_upper_bound_amt = ' || l_upper_bound_amt);
1921          op_msg := 'PN_INDEX_CONS_INVALID_RANGE';
1922 
1923          l_constrained_amount := l_unconstrained_amount;
1924 
1925       ELSIF l_lower_bound_amt IS NOT NULL AND
1926          l_unconstrained_amount < l_lower_bound_amt THEN
1927 
1928          l_constrained_amount := l_lower_bound_amt;
1929          op_constraint_applied_amount := l_lower_bound_const_amt;
1930          op_constraint_applied_percent := l_lower_bound_const_pct;
1931 
1932       ELSIF l_upper_bound_amt IS NOT NULL AND
1933             l_unconstrained_amount > l_upper_bound_amt THEN
1934 
1935          l_constrained_amount := l_upper_bound_amt;
1936          op_constraint_applied_amount := l_upper_bound_const_amt;
1937          op_constraint_applied_percent := l_upper_bound_const_pct;
1938 
1939          put_log('max constraint applied : l_constrained_amount :'||l_constrained_amount);
1940 
1941          if p_carry_forward_flag = 'A' then
1942 
1943             l_carry_forward_amount := ROUND(l_unconstrained_amount - l_constrained_amount,
1944                                              get_amount_precision);
1945          elsif p_carry_forward_flag = 'P' then
1946 
1947             l_carry_forward_percent := ROUND((l_unconstrained_amount - l_constrained_amount)*
1948                                               (100/p_current_basis),5);
1949          end if;
1950 
1951       ELSE
1952          l_constrained_amount := l_unconstrained_amount;
1953       END IF;
1954 
1955       op_constrained_rent_amount := l_constrained_amount;
1956       op_carry_forward_percent := l_carry_forward_percent;
1957       op_carry_forward_amount := l_carry_forward_amount;
1958 
1959       op_constraint_applied_amount := round(op_constraint_applied_amount,get_amount_precision);
1960       op_constrained_rent_amount := round(op_constrained_rent_amount,get_amount_precision);
1961       op_constraint_applied_percent := round(op_constraint_applied_percent,5);
1962 
1963       put_log ('derive_constrained_rent - op_constraint_applied_amount  :'||op_constraint_applied_amount);
1964       put_log ('derive_constrained_rent - op_carry_forward_amount       :'||op_carry_forward_amount);
1965       put_log ('derive_constrained_rent - op_constraint_applied_percent :'||op_constraint_applied_percent);
1966       put_log ('derive_constrained_rent - op_carry_forward_percent      :'||op_carry_forward_percent);
1967       put_log ('derive_constrained_rent - op_constrained_rent_amount    :'||op_constrained_rent_amount);
1968       put_log ('pn_index_amount_pkg.derive_constrained_rent   (-): ');
1969 
1970    END derive_constrained_rent;
1971 
1972 
1973 ------------------------------------------------------------------------
1974 -- PROCEDURE : lookup_index_history
1975 -- DESCRIPTION: This procedure will derive the cpi value and index history id using
1976 --              finder date provided.
1977 --
1978 ------------------------------------------------------------------------
1979 
1980    PROCEDURE lookup_index_history (
1981       p_index_history_id    IN       NUMBER
1982      ,p_index_finder_date   IN       DATE
1983      ,op_cpi_value          OUT NOCOPY      NUMBER
1984      ,op_cpi_id             OUT NOCOPY      NUMBER
1985      ,op_msg                OUT NOCOPY      VARCHAR2
1986    ) IS
1987       v_index_line_id   pn_index_history_lines.index_line_id%TYPE;
1988       v_index_figure    pn_index_history_lines.index_figure%TYPE;
1989       v_msg             VARCHAR2 (1000);
1990       v_found_index     BOOLEAN;
1991    BEGIN
1992       --put_log ('..In lookup_index_history');
1993       --
1994       -- When performing lookup, ignore the day component is optional...
1995       --
1996       BEGIN
1997          --
1998          -- for performance considerations, lookup will first be done with the full finder date..
1999          --
2000 
2001          BEGIN
2002             SELECT phl.index_line_id
2003                   ,phl.index_figure
2004               INTO v_index_line_id
2005                   ,v_index_figure
2009             v_found_index := TRUE;
2006               FROM pn_index_history_lines phl
2007              WHERE phl.index_id = p_index_history_id
2008                AND phl.index_date = p_index_finder_date;
2010          EXCEPTION
2011             WHEN OTHERS THEN
2012                v_found_index := FALSE;
2013          END;
2014 
2015          IF NOT v_found_index THEN
2016             SELECT phl.index_line_id
2017                   ,phl.index_figure
2018               INTO v_index_line_id
2019                   ,v_index_figure
2020               FROM pn_index_history_lines phl
2021              WHERE phl.index_id = p_index_history_id
2022                AND TO_NUMBER (TO_CHAR (phl.index_date, 'MMYYYY')) =
2023                                        TO_NUMBER (TO_CHAR (p_index_finder_date, 'MMYYYY'));
2024          END IF; --NOT V_FOUND_INDEX
2025 
2026          --
2027          -- get
2028          --
2029          op_cpi_value := v_index_figure;
2030          op_cpi_id := v_index_line_id;
2031 
2032          IF op_cpi_value IS NULL THEN
2033             v_msg := 'PN_INDEX_HIST_REC_IS_BLANK';
2034          END IF;
2035       EXCEPTION
2036          WHEN TOO_MANY_ROWS THEN
2037             put_log (
2038                   '      Duplicate records for the finder date: '
2039                || TO_CHAR (p_index_finder_date, 'MON-YYYY')
2040             );
2041             v_msg := 'PN_INDEX_DUP_HIST_REC_NOT_FOUND';
2042          WHEN NO_DATA_FOUND THEN
2043             put_log (
2044                   '      Unable to find a record using the finder date: '
2045                || TO_CHAR (p_index_finder_date, 'MON-YYYY')
2046             );
2047             v_msg := 'PN_INDEX_HIST_REC_NOT_FOUND';
2048          WHEN OTHERS THEN
2049             put_log (   '      Cannot Derive Index Amount - Unknow Error:'
2050                      || SQLERRM);
2051       END;
2052 
2053       op_msg := v_msg;
2054    END lookup_index_history;
2055 
2056 
2057 ------------------------------------------------------------------------
2058 -- PROCEDURE : calculate_index_percentage
2059 -- DESCRIPTION: This procedure will derive the current and previous CPI for a given index period.
2060 --              It will also calculate the index change percentage
2061 --
2062 -- 09-Jul-2001  psidhu
2063 --              Added Fix for bug # 1873888
2064 -- 23-aug-2001  psidhu
2065 --              Added fix for bug # 1952508
2066 --
2067 ------------------------------------------------------------------------
2068 
2069    PROCEDURE calculate_index_percentage (
2070       p_index_finder_type       IN       VARCHAR2
2071      ,p_reference_period_type   IN       VARCHAR2
2072      ,p_index_finder_date       IN       DATE
2073      ,p_index_history_id        IN       NUMBER
2074      ,p_base_index              IN       NUMBER
2075      ,p_base_index_line_id      IN       NUMBER
2076      ,p_index_lease_id          IN       NUMBER
2077      ,p_assessment_date         IN       DATE
2078      ,p_prev_assessment_date    IN       DATE
2079      ,op_current_cpi_value      IN OUT NOCOPY   NUMBER
2080      ,op_current_cpi_id         IN OUT NOCOPY   NUMBER
2081      ,op_previous_cpi_value     IN OUT NOCOPY   NUMBER
2082      ,op_previous_cpi_id        IN OUT NOCOPY   NUMBER
2083      ,op_index_percent_change   OUT NOCOPY      NUMBER
2084      ,op_msg                    OUT NOCOPY      VARCHAR2
2085    ) IS
2086       v_current_cpi_value           pn_index_lease_periods.current_index_line_value%TYPE;
2087       v_current_cpi_id              pn_index_lease_periods.current_index_line_id%TYPE;
2088       v_previous_cpi_value          pn_index_lease_periods.previous_index_line_value%TYPE;
2089       v_previous_cpi_id             pn_index_lease_periods.previous_index_line_id%TYPE;
2090       v_prev_assessment_date        pn_index_lease_periods.assessment_date%TYPE;
2091       v_prev_period_id              pn_index_lease_periods.index_period_id%TYPE;
2092       v_num_months_bet_asmnt_date   NUMBER;
2093       v_num_days_bet_asmnt_date    NUMBER;
2094       v_msg                         VARCHAR2 (1000);
2095       v_all_msg                     VARCHAR2 (1000);
2096       v_current_finder_date         pn_index_lease_periods.index_finder_date%TYPE;
2097       v_previous_finder_date        pn_index_lease_periods.index_finder_date%TYPE;
2098       v_upper_index_date_code       NUMBER;
2099       v_lower_index_date_code       NUMBER;
2100 
2101       CURSOR get_relationship IS
2102          SELECT relationship
2103          FROM pn_index_lease_periods_all
2104          WHERE assessment_date = p_assessment_date
2105          AND index_lease_id = p_index_lease_id;
2106 
2107       v_relationship_default VARCHAR2(30);
2108 
2109    /*
2110    - Calculate the index change (CALCULATE_INDEX_PERCENTAGE)
2111 
2112 
2113 
2114                Derive Current CPI:
2115 
2116                     Note: Finder date lookup only match the year and month and not the day.
2117 
2118                     IF INDEX_FINDER = Always Finder Date (Code: ??) or THEN
2119                          Current CPI = Lookup PN_INDEX_HISTORY_LINES using finder date
2120 
2121                     ELSE INDEX_FINDER = Backbill (Code: ??)
2122                          Current CPI = Lookup PN_INDEX_HISTORY_LINES using finder date
2123 
2124                     ELSE INDEX_FINDER = Most Recent(Code: ??)
2125 
2126                          Current CPI = Lookup PN_INDEX_HISTORY_LINES using the most recent reported
2127 
2128                               index from up to a year from the finder date.
2129 
2130                Derive Previous  CPI:
2131 
2135 
2132                     Note: Finder date lookup only match the year and month and not the day.
2133 
2134                     IF REFERENCE_PERIOD = Base Year (Code: ??) THEN
2136                          Previous CPI = Base Index Value from Agreement (PN_INDEX_LEASES.BASE_INDEX)
2137 
2138                     ELSE IF REFERENCE_PERIOD = Previous Year (Code: ??) THEN
2139 
2140                          1> Take the elapsed time between the current assessment date and the prevous period's assessment
2141 date
2142                          2> Use as finder date the date from (current finder date - number in Step 1) to derive a CPI to be
2143 used as the previous CPI.
2144 
2145 
2146                If Both Previous and Current CPI are available, calculate Index
2147 
2148                     - Index = (Current Index - Previous Index)  Previous Index
2149 
2150 
2151 
2152    */
2153 
2154 
2155 
2156 
2157    BEGIN
2158       --put_log ('..In calculate_index_percentage');
2159 
2160 
2161       --
2162       -- if no current cpi value, derive a current cpi
2163       --
2164 
2165       IF op_current_cpi_value IS NOT NULL THEN
2166          v_current_cpi_value := op_current_cpi_value;
2167          v_current_cpi_id := op_current_cpi_id;
2168          v_current_finder_date := p_index_finder_date;
2169       ELSE
2170          --
2171          -- if index finder type
2172          --     use finder date or use finder w/ backbill
2173          --
2174          IF    p_index_finder_type = c_index_finder_finder_date
2175             OR p_index_finder_type = c_index_finder_backbill THEN
2176             --
2177             -- Use the finder date to derive current CPI
2178             --
2179             v_current_finder_date := p_index_finder_date;
2180          ELSIF p_index_finder_type = c_index_finder_most_recent THEN
2181             --
2182             -- If finder type = USE MOST RECENT, use the last reported index within a year of the current
2183             -- date.
2184             --
2185             -- Deriving the date of last reported index upto within a year of today's date
2186 
2187             -- first, decide the upper and lower date range to be used:
2188             --        since the index date has no day component, each date is converted
2189             --        to its six digit equivalent
2190 
2191             SELECT TO_NUMBER (TO_CHAR (p_index_finder_date, 'YYYYMM'))
2192                   ,TO_NUMBER (TO_CHAR (ADD_MONTHS (p_index_finder_date, -12), 'YYYYMM'))
2193               INTO v_upper_index_date_code
2194                   ,v_lower_index_date_code
2195               FROM DUAL;
2196             --
2197             -- second, derive the finder date to be used.
2198             --
2199             SELECT MAX (phl.index_date)
2200               INTO v_current_finder_date
2201               FROM pn_index_history_lines phl
2202              WHERE phl.index_id = p_index_history_id
2203                AND TO_NUMBER (TO_CHAR (phl.index_date, 'YYYYMM'))
2204                       BETWEEN v_lower_index_date_code
2205                           AND v_upper_index_date_code
2206                AND index_figure IS NOT NULL;
2207          END IF; -- p_index_finder_type = ??
2208 
2209          lookup_index_history (
2210             p_index_history_id            => p_index_history_id
2211            ,p_index_finder_date           => v_current_finder_date
2212            ,op_cpi_value                  => v_current_cpi_value
2213            ,op_cpi_id                     => v_current_cpi_id
2214            ,op_msg                        => v_msg
2215          );
2216       --pn_index_lease_common_pkg.append_msg (p_new_msg => v_msg, p_all_msg => v_all_msg);
2217 
2218       END IF; -- op_current_cpi_value is not null 0
2219 
2220       --
2221       -- if no previous cpi value, derive a current cpi
2222       --
2223 
2224       IF op_previous_cpi_value IS NOT NULL THEN
2225          v_previous_cpi_value := op_previous_cpi_value;
2226          v_previous_cpi_id := op_previous_cpi_id;
2227       ELSE
2228          --
2229          -- Deriving the Previous  CPI
2230          --
2231          IF p_reference_period_type = c_ref_period_base_year THEN
2232             --put_log ('      Reference Period: BASE YEAR');
2233             --
2234             -- If Reference Period = Base Year, use the Base Index Value from the agreement
2235             --    window.
2236             IF    p_base_index IS NOT NULL
2237                OR p_base_index_line_id IS NOT NULL THEN
2238                v_previous_cpi_value := p_base_index;
2239                v_previous_cpi_id := p_base_index_line_id;
2240             ELSE
2241                --put_log ('      Base Index is Missing.');
2242                pn_index_lease_common_pkg.append_msg (
2243                   p_new_msg                     => 'PN_INDEX_BASE_INDEX_REQUIRED'
2244                  ,p_all_msg                     => v_all_msg
2245                );
2246             END IF;
2247          ELSIF p_reference_period_type = c_ref_period_prev_year_asmt_dt THEN
2248             --put_log ('      Reference Period: PREV YEAR');
2249 
2250             --
2251             -- If Reference Period = Prev Year
2252 
2253             --
2254             -- Get the assessment date of the previous period, if not passed from calling program
2255             --
2256             IF p_prev_assessment_date IS NULL THEN
2257                --
2261                  INTO v_prev_assessment_date
2258                -- Get the latest assessment date before the current assessment date
2259                --
2260                SELECT MAX (pilp.assessment_date)
2262                  FROM pn_index_lease_periods_all pilp
2263                 WHERE pilp.index_lease_id = p_index_lease_id
2264                   AND pilp.assessment_date < p_assessment_date;
2265             ELSE
2266                v_prev_assessment_date := p_prev_assessment_date;
2267             END IF; --p_prev_assessment_date IS NULL
2268 
2269             IF v_prev_assessment_date IS NULL THEN
2270                --
2271                -- if we can't derive a previous assessment date, then
2272                -- we must be in the first period, therefore use
2273                -- base index.
2274                --
2275                v_previous_cpi_value := p_base_index;
2276             ELSE
2277                --
2278                -- Get the duration between assessment dates
2279                --
2280                  v_num_months_bet_asmnt_date :=
2281                       CEIL (MONTHS_BETWEEN (p_assessment_date, v_prev_assessment_date));
2282                --
2283                -- Derive a new finder date but subtracting the duration between assessment dates from the finder
2284                --  date used to dervie the current CPI.
2285                --
2286                v_previous_finder_date :=
2287                       ADD_MONTHS (v_current_finder_date, -1 * v_num_months_bet_asmnt_date);
2288                --
2289                -- Derive a new index amount using the finder date derived from previous step.
2290                --
2291                lookup_index_history (
2292                   p_index_history_id            => p_index_history_id
2293                  ,p_index_finder_date           => v_previous_finder_date
2294                  ,op_cpi_value                  => v_previous_cpi_value
2295                  ,op_cpi_id                     => v_previous_cpi_id
2296                  ,op_msg                        => v_msg
2297                );
2298             END IF; --v_prev_assessment_date IS NULL
2299          ELSIF p_reference_period_type = c_ref_period_prev_year_prv_cpi THEN
2300             --
2301             -- reference period is previous year, and use the cpi of the previous index rent period
2302             --
2303 
2304 
2305             --
2306             -- derive the index id of the period id of the previous assessment date
2307             --
2308 
2309             derive_index_period_id (
2310                p_index_lease_id              => p_index_lease_id
2311               ,p_assessment_date             => p_assessment_date
2312               ,op_prev_index_lease_id        => v_prev_period_id
2313             );
2314 
2315             --
2316             -- getting the current cpi info of the prev index rent period
2317             --
2318             IF v_prev_period_id IS NOT NULL THEN
2319                SELECT current_index_line_id
2320                      ,current_index_line_value
2321                  INTO v_previous_cpi_id
2322                      ,v_previous_cpi_value
2323                  FROM pn_index_lease_periods_all
2324                 WHERE index_period_id = v_prev_period_id;
2325              ELSE
2326              -- Fix for bug # 1873888
2327              -- If no previous CPI is found, then use base index
2328                IF p_base_index IS NOT NULL
2329                 OR p_base_index_line_id IS NOT NULL THEN
2330                         v_previous_cpi_value := p_base_index;
2331                         v_previous_cpi_id := p_base_index_line_id;
2332                 ELSE
2333                        --put_log ('      Base Index is Missing.');
2334                          pn_index_lease_common_pkg.append_msg (
2335                                p_new_msg                     => 'PN_INDEX_BASE_INDEX_REQUIRED'
2336                               ,p_all_msg                     => v_all_msg
2337                                                              );
2338                        END IF;
2339                --
2340               END IF;
2341          END IF; --p_reference_period_type = ????
2342 
2343          put_log (
2344                '      Finder Date Used:   Current='
2345             || TO_CHAR (v_current_finder_date, 'MON-YYYY')
2346             || '    Previous='
2347             || NVL (TO_CHAR (v_previous_finder_date, 'MON-YYYY'), 'Using Base Year')
2348          );
2349       END IF; --op_previous_cpi_value IS NOT NULL
2350 
2351       --
2352       -- Calculate CPI
2353       --
2354 
2355       IF      v_current_cpi_value IS NOT NULL
2356           AND v_previous_cpi_value IS NOT NULL THEN
2357          op_index_percent_change := ROUND (
2358                                          (  v_current_cpi_value
2359                                           - v_previous_cpi_value
2360                                          )
2361                                        / v_previous_cpi_value
2362                                        * 100
2363                                       ,5             --fix for bug # 1952508
2364                                     );
2365       ELSE
2366 
2367          FOR rec IN get_relationship LOOP
2368             v_relationship_default := rec.relationship;
2369          END LOOP;
2370 
2371          IF v_relationship_default IN ('GREATER_OF','LESSER_OF') THEN
2372 
2373             pn_index_lease_common_pkg.append_msg (
2377 
2374                p_new_msg                     => 'PN_INDEX_INDEX_CHANGE_REQ'
2375               ,p_all_msg                     => v_all_msg
2376             );
2378          ELSIF v_relationship_default IN ('INDEX_ONLY') THEN
2379             pn_index_lease_common_pkg.append_msg (
2380                p_new_msg                     => 'PN_INDEX_PERIOD_INDEX_REQ'
2381               ,p_all_msg                     => v_all_msg
2382             );
2383          END IF;
2384 
2385       END IF;
2386 
2387       op_current_cpi_value := v_current_cpi_value;
2388       op_current_cpi_id := v_current_cpi_id;
2389       op_previous_cpi_value := v_previous_cpi_value;
2390       op_previous_cpi_id := v_previous_cpi_id;
2391       op_msg := v_all_msg;
2392    END calculate_index_percentage;
2393 
2394 
2395 ------------------------------------------------------------------------
2396 -- PROCEDURE : chk_normalized_amount
2397 -- DESCRIPTION: This look at a period's payment terms and derive the annual
2398 --                 amount that has been normalized.  This is important
2399 --                 when calculating the backbill amount.
2400 ------------------------------------------------------------------------
2401 
2402 
2403    PROCEDURE chk_normalized_amount (
2404       p_index_period_id            IN       NUMBER
2405      ,op_normalize_amount_annual   OUT NOCOPY      NUMBER
2406      ,op_msg                       OUT NOCOPY      VARCHAR2
2407    ) IS
2408       v_found_normalize        NUMBER (1);
2409       v_normalized_amount      pn_payment_terms.actual_amount%TYPE;
2410       v_normalized_frequency   pn_payment_terms.frequency_code%TYPE;
2411       v_multiplier             NUMBER (3);
2412 
2413 
2414      /* cursor to select all normalized payment terms recurring payment that are APPROVED and not normalized.*/
2415 
2416       CURSOR c1 IS
2417          SELECT ppt.actual_amount
2418                ,ppt.frequency_code
2419            FROM pn_payment_terms_all ppt
2420           WHERE ppt.index_period_id = p_index_period_id
2421       AND ppt.index_term_indicator = c_index_pay_term_type_atlst;
2422 
2423    BEGIN
2424 
2425       op_normalize_amount_annual := 0;
2426 
2427       FOR c1_rec IN c1
2428       LOOP
2429          v_normalized_amount := c1_rec.actual_amount;
2430          v_normalized_frequency := c1_rec.frequency_code;
2431          SELECT DECODE (
2432                    v_normalized_frequency
2433                   ,c_spread_frequency_monthly, 12
2434                   ,c_spread_frequency_one_time, 1
2435                   ,c_spread_frequency_quarterly, 4
2436                   ,c_spread_frequency_semiannual, 2
2437                   ,c_spread_frequency_annually, 1
2438                   ,1
2439                 )
2440            INTO v_multiplier
2441            FROM DUAL;
2442          op_normalize_amount_annual :=   (v_normalized_amount * v_multiplier)
2443                                        + op_normalize_amount_annual;
2444       END LOOP;
2445 
2446    END chk_normalized_amount;
2447 
2448 
2449 ------------------------------------------------------------------------
2450 -- PROCEDURE : chk_approved_amount
2451 -- DESCRIPTION: This procedure will check for all approved  non-normailized
2452 --              recurring payment terms
2453 ------------------------------------------------------------------------
2454 
2455 
2456 
2457 PROCEDURE chk_approved_amount (
2458       p_index_period_id IN NUMBER
2459      ,p_index_term_indicator IN VARCHAR2
2460      ,op_approved_amount_annual OUT NOCOPY NUMBER
2461      ,op_msg OUT NOCOPY VARCHAR2
2462    ) IS
2463       v_found_approved         NUMBER (1);
2464       v_all_approved_amounts   NUMBER                                 := 0;
2465       v_multiplier             NUMBER (3);
2466 
2467       --
2468       -- cursor to select all recurring payment that are APPROVED.
2469       --
2470       CURSOR c1 IS
2471          SELECT ppt.payment_term_id, ppt.actual_amount, ppt.frequency_code
2472            FROM pn_payment_terms_all ppt
2473           WHERE ppt.index_period_id = p_index_period_id
2474             AND ppt.status =c_payment_term_status_approved
2475             AND ppt.index_term_indicator = p_index_term_indicator;
2476    BEGIN
2477       FOR cursor_rec IN c1
2478       LOOP
2479 
2480          SELECT DECODE (
2481                    cursor_rec.frequency_code
2482                   ,c_spread_frequency_monthly, 12
2483                   ,c_spread_frequency_one_time, 1
2484                   ,c_spread_frequency_quarterly, 4
2485                   ,c_spread_frequency_semiannual, 2
2486                   ,c_spread_frequency_annually, 1
2487                   ,1
2488                 )
2489            INTO v_multiplier
2490            FROM DUAL;
2491          v_all_approved_amounts :=   (cursor_rec.actual_amount * v_multiplier)
2492                                    + v_all_approved_amounts;
2493       END LOOP;
2494 
2495       op_approved_amount_annual := v_all_approved_amounts;
2496    END chk_approved_amount;
2497 
2498 
2499    ------------------------------------------------------------------------
2500    -- PROCEDURE : chk_approved_amount
2501    -- DESCRIPTION: This procedure will check for all approved  non-normailized
2502    --              recurring payment terms
2503    ------------------------------------------------------------------------
2504 
2505 
2506 
2507    PROCEDURE chk_aggregated_approved_amount (
2511         ,p_payment_purpose_code IN VARCHAR2
2508          p_index_period_id IN NUMBER
2509         ,p_index_term_indicator IN VARCHAR2
2510         ,p_location_id IN NUMBER
2512         ,p_payment_term_type_code IN VARCHAR2
2513         ,p_vendor_id IN NUMBER
2514         ,p_vendor_site_id IN NUMBER
2515         ,p_customer_id IN NUMBER
2516         ,p_customer_site_use_id IN NUMBER
2517         ,p_distribution_string IN VARCHAR2
2518         ,p_normalize IN VARCHAR2
2519         ,op_approved_amount_annual OUT NOCOPY NUMBER
2520         ,op_msg OUT NOCOPY VARCHAR2
2521       ) IS
2522          v_found_approved         NUMBER (1);
2523          v_approved_amount        pn_payment_terms.actual_amount%TYPE;
2524          v_approved_frequency     pn_payment_terms.frequency_code%TYPE;
2525          v_all_approved_amounts   NUMBER                                 := 0;
2526          v_multiplier             NUMBER (3);
2527          v_exists                 NUMBER := 0;
2528 
2529          --
2530          -- cursor to select all recurring payment that are APPROVED and not normalized.
2531          --
2532          CURSOR c1(ip_location_id IN NUMBER
2533                   ,ip_payment_purpose_code IN VARCHAR2
2534                   ,ip_payment_term_type_code IN VARCHAR2
2535                   ,ip_vendor_id IN NUMBER
2536                   ,ip_vendor_site_id IN NUMBER
2537                   ,ip_customer_id IN NUMBER
2538                   ,ip_customer_site_use_id IN NUMBER
2539                   ,ip_distribution_string IN VARCHAR2
2540                   ,ip_index_term_indicator IN VARCHAR2
2541                   ,ip_normalize IN VARCHAR2
2542                   ,ip_index_period_id IN NUMBER)IS
2543          SELECT ppt.payment_term_id, ppt.actual_amount,ppt.frequency_code
2544          FROM pn_payment_terms_all ppt,
2545               pn_payment_items_all ppi
2546          WHERE ppt.index_period_id = ip_index_period_id
2547          AND ppt.status =c_payment_term_status_approved
2548          AND ppt.index_term_indicator = ip_index_term_indicator
2549          AND ppt.payment_purpose_code = ip_payment_purpose_code
2550          AND ppt.payment_term_type_code = ip_payment_term_type_code
2551          AND ppt.payment_term_id = ppi.payment_term_id
2552          AND ppi.payment_item_type_lookup_code = 'CASH'
2553          AND DECODE (
2554                      ip_index_term_indicator
2555                     ,c_index_pay_term_type_atlst, NVL (ppt.normalize, 'N')
2556                     ,'IGNORE'
2557                       ) = ip_normalize
2558          AND (   ppt.location_id = ip_location_id
2559                OR ip_location_id IS NULL
2560               )
2561          AND (   ppt.vendor_id = ip_vendor_id
2562                OR ip_vendor_id IS NULL
2563               )
2564          AND (   ppt.vendor_site_id = ip_vendor_site_id
2565                OR ip_vendor_site_id IS NULL
2566              )
2567          AND (   ppt.customer_id = ip_customer_id
2568                OR ip_customer_id IS NULL
2569              )
2570          AND (   ppt.customer_site_use_id = ip_customer_site_use_id
2571                OR ip_customer_site_use_id IS NULL
2572              )
2573          AND (   build_distributions_string (ppt.payment_term_id) = ip_distribution_string
2574                OR ip_distribution_string IS NULL
2575               );
2576       BEGIN
2577 
2578          SELECT '1'
2579          INTO v_exists
2580          FROM pn_payment_terms_all
2581          WHERE index_period_id = p_index_period_id
2582          AND   status = c_payment_term_status_approved
2583          AND   index_term_indicator = p_index_term_indicator;
2584 
2585 
2586          IF v_exists = 1   THEN
2587 
2588             FOR cursor_rec IN c1  (ip_location_id => p_location_id
2589                                   ,ip_payment_purpose_code => p_payment_purpose_code
2590                                   ,ip_payment_term_type_code => p_payment_term_type_code
2591                                   ,ip_vendor_id  => p_vendor_id
2592                                   ,ip_vendor_site_id => p_vendor_site_id
2593                                   ,ip_customer_id => p_customer_id
2594                                   ,ip_customer_site_use_id  => p_customer_site_use_id
2595                                   ,ip_distribution_string  => p_distribution_string
2596                                   ,ip_index_term_indicator  => p_index_term_indicator
2597                                   ,ip_normalize => p_normalize
2598                                   ,ip_index_period_id => p_index_period_id )
2599             LOOP
2600 
2601                SELECT DECODE (
2602                       cursor_rec.frequency_code
2603                      ,c_spread_frequency_monthly, 12
2604                      ,c_spread_frequency_one_time, 1
2605                      ,c_spread_frequency_quarterly, 4
2606                      ,c_spread_frequency_semiannual, 2
2607                      ,c_spread_frequency_annually, 1
2608                      ,1
2609                    )
2610               INTO v_multiplier
2611               FROM DUAL;
2612               v_all_approved_amounts :=   (cursor_rec.actual_amount * v_multiplier)
2613                                          + v_all_approved_amounts;
2614            END LOOP;
2615 
2616          op_approved_amount_annual := v_all_approved_amounts;
2617         END IF;
2618 
2619          EXCEPTION
2620          WHEN NO_DATA_FOUND THEN  op_approved_amount_annual := 0;
2621          WHEN OTHERS THEN
2625       END chk_aggregated_approved_amount;
2622             put_log (   '      Cannot Derive Aggregated approved amount - Unknow Error:'
2623                      || SQLERRM);
2624 
2626 
2627 
2628 
2629 ------------------------------------------------------------------------
2630 -- PROCEDURE : derive_payment_start_date
2631 -- DESCRIPTION: This procedure will derive the current and previous CPI for a given index period.
2632 --              It will also calculate the index change percentage
2633 --
2634 --  08-OCT-2004  Satish Tripathi o Modified for BUG# 3961117, added new parameter p_calculate_date
2635 --                                 for not to create backbills if Assessment Date <= CutOff Date.
2636 --  01-DEC-2006  Prabhakar o Changed the parameter name p_main_lease_termination_date
2637 --                           to p_end_date.
2638 --  30-MAR-2007  Hareesha  o Bug # 5958131 Added handling for new option
2639 --                           of createing single term for backbill + recurring terms.
2640 ------------------------------------------------------------------------
2641 
2642 
2643 
2644    PROCEDURE derive_payment_start_date (
2645       p_spread_frequency              IN       VARCHAR2
2646      ,p_assessment_date               IN       DATE
2647      ,p_end_date                      IN       DATE
2648      ,p_calculate_date                IN       DATE
2649      ,p_index_lease_id                IN       NUMBER
2650      ,op_recur_pay_start_date         OUT NOCOPY DATE
2651      ,op_num_pymt_since_assmt_dt      OUT NOCOPY NUMBER
2652    ) IS
2653       v_recurring_payment_start_date   DATE;
2654       v_num_months_bet_payments        NUMBER;
2655       v_num_pymt_since_assmt_dt        NUMBER := 0;
2656       l_index_finder_method            VARCHAR2(30);
2657 
2658       CURSOR get_index_finder IS
2659          SELECT index_finder_method
2660          FROM pn_index_leases_all
2661          WHERE index_lease_id = p_index_lease_id;
2662 
2663    BEGIN
2664 
2665       put_log(' derive_payment_start_date (+) ');
2666       --
2667       -- Determine the start date for the recurring payment.
2668       -- Will also determine the no. of payments made for this
2669       -- period since the assessment date.
2670 
2671       SELECT DECODE (
2672                 p_spread_frequency
2673                ,c_spread_frequency_monthly, 1
2674                ,c_spread_frequency_quarterly, 3
2675                ,c_spread_frequency_semiannual, 6
2676                ,c_spread_frequency_annually, 12
2677                ,1
2678              )
2679         INTO v_num_months_bet_payments
2680         FROM DUAL;
2681       v_recurring_payment_start_date := p_assessment_date;
2682 
2683       FOR rec IN get_index_finder LOOP
2684          l_index_finder_method := rec.index_finder_method;
2685       END LOOP;
2686       --
2687       -- if the current date is later than the assessment date
2688       --   derive a start date of recurring payments, using the spread
2689       --   frequency defined in the agreement.
2690       --
2691 
2692       IF p_calculate_date > p_assessment_date AND
2693          ( (NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') IN ('OT','RECUR')) OR
2694             (NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') IN ('SINGLETERM') AND
2695               l_index_finder_method IN ('FINDER_DATE')))
2696       THEN
2697          v_num_pymt_since_assmt_dt := 0;
2698 
2699         /*Fix for bug# 2007492
2700           If main lease termination date < sysdate then
2701           derive the num of payments from assessment date to the main lease termination date. */
2702 
2703          WHILE v_recurring_payment_start_date < least(trunc(SYSDATE),trunc(p_end_date))
2704          LOOP
2705             -- get the next payment date
2706             v_recurring_payment_start_date :=
2707                    ADD_MONTHS (v_recurring_payment_start_date, v_num_months_bet_payments);
2708             -- increment counter of no. of payments
2709             v_num_pymt_since_assmt_dt :=   v_num_pymt_since_assmt_dt
2710                                          + 1;
2711          END LOOP;
2712       END IF;
2713 
2714       op_recur_pay_start_date := v_recurring_payment_start_date;
2715       op_num_pymt_since_assmt_dt := v_num_pymt_since_assmt_dt;
2716       put_log(' derive_payment_start_date (-) '||v_recurring_payment_start_date);
2717    END derive_payment_start_date;
2718 
2719 
2720 
2721 ------------------------------------------------------------------------
2722 -- PROCEDURE : derive_term_end_date
2723 -- DESCRIPTION : This procedure will derive the RI term end date
2724 --
2725 -- 01-DEC-2006 Prabhakar o Created.
2726 --
2727 -- 07-MAR-2007 Prabhakar o Modified to return index_termination_date
2728 --                         as the last assessment period end date.
2729 --                         Fix for Bug : 5917452
2730 -- 02-APR-2007 Hareesha  o Bug # 5960582 Added handling for new profile-option
2731 --                         PN_RENT_INCREASE_TERM_END_DATE
2732 ------------------------------------------------------------------------
2733 PROCEDURE derive_term_end_date (ip_index_lease_id                 NUMBER
2734                                ,ip_index_period_id                NUMBER
2735                                ,ip_main_lease_termination_date    DATE
2736                                ,op_term_end_date     OUT NOCOPY   DATE) IS
2737    v_end_date                       DATE;
2738    v_reference_period_type          VARCHAR2(30);
2739    v_basis_type                     VARCHAR2(30);
2740    v_max_assessment_date            DATE;
2741    v_current_assessment_date        DATE;
2745    TABLE OF DATE INDEX BY BINARY_INTEGER;
2742    v_next_assessment_date           DATE;
2743 
2744    TYPE assessment_date IS
2746    assessment_date_table  assessment_date;
2747 
2748    v_period_number                 NUMBER := 0;
2749    v_assess_in_years               NUMBER;
2750    v_index_termination_date        DATE;
2751 
2752    CURSOR ref_period_cur(p_index_lease_id NUMBER) IS
2753    SELECT basis_type,reference_period,assessment_interval,termination_date
2754    FROM pn_index_leases_all
2755    WHERE index_lease_id = p_index_lease_id;
2756 
2757    CURSOR assessment_date_cur(p_index_lease_id NUMBER) IS
2758    SELECT assessment_date, index_period_id
2759    FROM pn_index_lease_periods_all
2760    WHERE index_lease_id = p_index_lease_id
2761    ORDER BY assessment_date;
2762 
2763 BEGIN
2764 
2765 /* NOTE : If the profile option is period_end and ref type is base yaer and basis type is fixed
2766                    then term end date is one day prior to the next assessment date.
2767                    For the last term lease termination date is the term end date.
2768                    In all other cases the deafult term end date is lease termination date  */
2769 
2770       FOR ref_period_rec IN ref_period_cur(ip_index_lease_id)  LOOP
2771           v_reference_period_type := ref_period_rec.reference_period;
2772           v_assess_in_years := ref_period_rec.assessment_interval;
2773           v_basis_type := ref_period_rec.basis_type;
2774           v_index_termination_date := ref_period_rec.termination_date;
2775        END LOOP;
2776 
2777        FOR assessment_date_rec IN assessment_date_cur(ip_index_lease_id) LOOP
2778            IF assessment_date_rec.index_period_id = ip_index_period_id THEN
2779               v_current_assessment_date := assessment_date_rec.assessment_date;
2780            END IF;
2781 
2782            v_period_number := v_period_number + 1;
2783            assessment_date_table(v_period_number) := assessment_date_rec.assessment_date;
2784 
2785            v_max_assessment_date := assessment_date_rec.assessment_date;
2786        END LOOP;
2787 
2788         v_end_date := ip_main_lease_termination_date; -- default value
2789 
2790         IF nvl(fnd_profile.value('PN_IR_TERM_END_DATE'),'LEASE_END') = 'PERIOD_END' AND
2791              v_basis_type = c_basis_type_fixed AND
2792              v_reference_period_type = c_ref_period_base_year
2793         THEN
2794            IF v_current_assessment_date < v_max_assessment_date THEN
2795               v_period_number := 1;
2796               WHILE ( assessment_date_table(v_period_number) <= v_current_assessment_date) LOOP
2797                  v_next_assessment_date := assessment_date_table(v_period_number +1);
2798                  v_period_number := v_period_number +1;
2799               END LOOP;
2800               v_end_date := v_next_assessment_date-1;
2801             ELSE
2802                v_end_date := least(ip_main_lease_termination_date,v_index_termination_date);
2803             END IF;
2804 
2805         ELSE
2806 
2807            IF NVL(fnd_profile.value('PN_RENT_INCREASE_TERM_END_DATE'),'END_LEASE') = 'END_AGRMNT' THEN
2808               v_end_date := v_index_termination_date;
2809            ELSE
2810               v_end_date := ip_main_lease_termination_date;
2811            END IF;
2812         END IF;
2813 
2814         op_term_end_date := v_end_date;
2815 
2816 END derive_term_end_date;
2817 
2818 
2819 
2820 ------------------------------------------------------------------------
2821 -- PROCEDURE : insert_inter_term
2822 -- DESCRIPTION: This procedure will store information of individual terms contribution
2823 --              toward a particular rent increase.
2824 --
2825 ------------------------------------------------------------------------
2826 
2827 procedure insert_inter_term (ip_index_period_id      NUMBER,
2828                              ip_index_term_indicator VARCHAR2,
2829                              ip_combination_amt         NUMBER,
2830                              ip_total_terms_amt         NUMBER,
2831                              ip_rent_increase_term_id   NUMBER,
2832                              ip_index_lease_id          NUMBER) IS
2833 
2834 i                     NUMBER;
2835 l_term_contribution   NUMBER;
2836 l_total_inter_term    NUMBER;
2837 l_sum_of_terms_loop   NUMBER := 0;
2838 l_index_lease_term_id pn_index_lease_terms.index_lease_term_id%type;
2839 
2840 cursor cur_total_inter_term ( ip_payment_term_id NUMBER) IS
2841     SELECT SUM(amount) total_inter_term
2842     FROM   pn_index_lease_terms_all
2843     WHERE  index_period_id = ip_index_period_id
2844     AND    lease_term_id   = ip_payment_term_id
2845     AND    index_term_indicator = ip_index_term_indicator;
2846 
2847 begin
2848 
2849 /* From the Pl/SQL table which contains the payment term id and the annualized amounts of the
2850    payment terms contained in an aggregation combination, find out NOCOPY their individual contribution
2851    towards the rent of the aggregation combination. */
2852 
2853 FOR i in 1..item_amt_tab.count
2854 loop
2855       /* Added the condition if ip_total_terms_amt <> 0 then ..  as a fix for
2856          bug # 2352453 . Added on 06-May-2002 by psidhu */
2857 
2858       IF ip_total_terms_amt <> 0 THEN
2859          l_term_contribution := (ip_combination_amt/ip_total_terms_amt) * item_amt_tab(i).amount;
2860       ELSE
2861          l_term_contribution := 0;
2862       END IF;
2863 
2864       /* for the last term the contribution will be the difference of the aggr combination
2868 
2865          rent and the sum of rent contributions by prior payment terms of the combination */
2866 
2867       IF i = item_amt_tab.count THEN
2869          l_term_contribution :=  ip_combination_amt - l_sum_of_terms_loop;
2870 
2871       ELSE
2872 
2873         l_sum_of_terms_loop := l_sum_of_terms_loop + l_term_contribution;
2874 
2875      END IF;
2876 
2877      /* Get the approved contributions for the payment term, from the intermediate table */
2878 
2879      open cur_total_inter_term(item_amt_tab(i).payment_term_id);
2880 
2881      fetch cur_total_inter_term into l_total_inter_term;
2882 
2883      close cur_total_inter_term;
2884 
2885 
2886      IF ((NVL(l_term_contribution,0) - NVL(l_total_inter_term,0)) <> 0 ) THEN
2887 
2888 
2889         l_index_lease_term_id := NULL;
2890 
2891         PN_INDEX_LEASE_TERMS_PKG.INSERT_ROW
2892         (
2893         X_INDEX_LEASE_TERM_ID     => l_index_lease_term_id
2894         ,X_INDEX_LEASE_ID         => ip_index_lease_id
2895         ,X_INDEX_PERIOD_ID        => ip_index_period_id
2896         ,X_LEASE_TERM_ID          => item_amt_tab(i).payment_term_id
2897         ,X_RENT_INCREASE_TERM_ID  => ip_rent_increase_term_id
2898         ,X_AMOUNT                 => (NVL(l_term_contribution,0)- NVL(l_total_inter_term,0))
2899         ,X_APPROVED_FLAG          => 'DRAFT'
2900         ,X_INDEX_TERM_INDICATOR   => ip_index_term_indicator
2901         ,X_LAST_UPDATE_DATE       => SYSDATE
2902         ,X_LAST_UPDATED_BY        => NVL (fnd_profile.VALUE ('USER_ID'), 0)
2903         ,X_CREATION_DATE          => SYSDATE
2904         ,X_CREATED_BY             => NVL (fnd_profile.VALUE ('USER_ID'), 0)
2905         ,X_LAST_UPDATE_LOGIN      => NVL (fnd_profile.VALUE ('USER_ID'), 0)
2906         );
2907 
2908     END IF;
2909 
2910 END LOOP;
2911 
2912 end insert_inter_term;
2913 
2914 --------------------------------------------------------------------------------
2915 -- PROCEDURE : create_aggr_payment_terms
2916 -- DESCRIPTION: This procedure will create payment terms during
2917 --              aggregation.
2918 -- 12-FEB-02 psidhu   o bug# 2221341. Added condition in cursor cur_unq_comb to
2919 --                      fetch index rent increase payment terms only if
2920 --                      basis_type <>COMPOUND.
2921 --                    o bug# 2214561. Round payment term contribution for unique
2922 --                      aggregation combination.
2923 -- 14-AUG-03 ftanudja o Handled untouched index lease payment terms. #3027574.
2924 -- 11-NOV-03 ftanudja o Take into account only approved terms for cursor
2925 --                      fetch_generated_il_terms. #3243150.
2926 -- 08-OCT-04 Satish   o BUG# 3961117, added new parameter p_calculate_date for
2927 --                      not to create backbills if Assessment Date <= CutOff Dt
2928 -- 01-DEC-04 ftanudja o Before calling create_payment_term_record, check if
2929 --                      start date < lease termination date. #3964221.
2930 --                    o Changed cursor cur_unq_comb to exclude one time payment
2931 --                      term combinations.
2932 -- 18-JAN-05 ftanudja o Before approving negative consolidation terms,
2933 --                      check if schedule day conflicts. #4081821.
2934 -- 03-Feb-05 Kiran    o Bug # 4031003 - based on the profile value of
2935 --                      PN_CALC_ANNUALIZED_BASIS decide whether to calculate
2936 --                      annualized basis for the terms active as of the period
2937 --                      End date or the for the entire period.
2938 -- 14-APR-05 ftanudja o Added cur_sum_backbill_overlap_items and logic to
2939 --                      take into account recurring term amount overlapping
2940 --                      with backbill. #4307736
2941 -- 19-SEP-05 piagrawa o Modified to pass org id to pn_mo_cache_utils.
2942 --                      get_profile_value
2943 -- 06-APR-06 hkulkarn o Bug4291907 -  check if v_created_payment_term_id IS not
2944 --                      null before making call to insert_inter_term
2945 -- 05-MAY-06 Hareesha o Bug# 5115291 Get the latest norm_st_date of
2946 --                      the parent term and pass it to create_payment_term_record.
2947 -- 31-OCT-06 acprakas o Bug#4967164. Modified the procedure to create negative terms
2948 --                      only when index payment term type is not 'ATLEAST'.
2949 -- 10-AUG-06 Pikhar   o Codev. Added include_in_var_rent to cur_unq_comb
2950 -- 29-Sep-06 Pseeram  o Modified the cursor cur_uniq_comb and cur_payment_terms
2951 -- 01-NOV-06 pseeram  o Added two cursors ref_period_cur and assessment_date_cur
2952 --                      for term length option.
2953 -- 01-DEC-06 Pseeram  o Removed the two cusrors ref_period_cur and assessment_date_cur
2954 --                      and the term length end_date handling is moved to
2955 --                      procedure derive_term_end_date.
2956 -- 09-JAN-07 lbala    o Removed call to get_schedule_date which checked for schedule
2957 --                      day conflicts for M28 item # 11
2958 -- 02-JAn-07 Hareesha o M28#16 Changes for Recurring backbill.
2959 -- 30-MAR-07 Hareesha o Bug # 5958131 Added handling for new option of backbill+recur.
2960 -- 23-APR-07 Hareesha o Bug 6005637 Removed the check of not to create reversal terms for
2961 --                      ATLEAST terms, ATLEAST terms wud get created for basis-only also,
2962 --                      restricting from creation of reversal terms is causing the above bug.
2963 --                      Hence, removed the restriction.
2964 -- 26-APR-07 Hareesha o Bug#6016064 Add condition to check if start-dt <= end-dt,
2965 --                      createterms,else do not.
2969 PROCEDURE create_aggr_payment_terms (
2966 -- 12-DEC-07 acprakas  o Bug#6457105. Modified to consider new values for system option incl_terms_by_default_flag.
2967 --------------------------------------------------------------------------------
2968 
2970       p_index_lease_id              IN       NUMBER
2971      ,p_basis_start_date            IN        DATE
2972      ,p_basis_end_date              IN        DATE
2973      ,p_index_term_indicator        IN       VARCHAR2
2974      ,p_lease_id                    IN       NUMBER
2975      ,p_assessment_date             IN       DATE
2976      ,p_normalized_amount_annual    IN       NUMBER
2977      ,p_basis_relationship          IN       VARCHAR2
2978      ,p_basis_type                  IN       VARCHAR2
2979      ,p_total_rent_amount           IN       NUMBER
2980      ,p_increase_on                 IN       VARCHAR2
2981      ,p_rounding_flag               IN       VARCHAR2
2982      ,p_index_finder_type           IN       VARCHAR2
2983      ,p_main_lease_termination_date IN       DATE
2984      ,p_index_period_id             IN       NUMBER
2985      ,p_calculate_date              IN       DATE
2986      ,op_msg                        OUT NOCOPY VARCHAR2
2987      )
2988 AS
2989 
2990     l_gross_flag                      PN_INDEX_LEASES_ALL.GROSS_FLAG%TYPE;
2991 
2992   CURSOR cur_unq_comb (
2993             ip_index_lease_id IN NUMBER
2994            ,ip_basis_start_date IN DATE
2995            ,ip_basis_end_date IN DATE
2996            ,ip_type_code IN VARCHAR2
2997            ,ip_index_term_indicator IN VARCHAR2
2998            ,ip_org_id IN NUMBER
2999          )
3000   IS
3001   SELECT DISTINCT ppt.location_id
3002         ,ppt.payment_purpose_code
3003         ,ppt.payment_term_type_code
3004         ,ppt.vendor_id
3005         ,ppt.vendor_site_id
3006         ,ppt.customer_id
3007         ,ppt.customer_site_use_id
3008         ,ppt.frequency_code
3009         ,ppt.include_in_var_rent
3010         ,build_distributions_string (ppt.payment_term_id) "DISTRIBUTION_STRING"
3011         ,NVL (ppt.normalize, 'N') "NORMALIZE"
3012    FROM  pn_payment_terms_all ppt,
3013          pn_index_leases_all  pil
3014    WHERE pil.index_lease_id = ip_index_lease_id
3015    AND   ppt.lease_id = pil.lease_id
3016    AND   nvl(ppt.status,'-1') = decode(ppt.index_period_id,null,nvl(ppt.status,'-1'),'APPROVED')
3017    AND   ppt.end_date >= ip_basis_start_date AND ppt.start_date <= ip_basis_end_date
3018    AND   ppt.payment_term_type_code = decode(ip_type_code,c_increase_on_gross,
3019                                              ppt.payment_term_type_code,ip_type_code)
3020    AND   (
3021          ppt.payment_term_id  IN (SELECT piet.payment_term_id
3022          FROM pn_index_exclude_term_all piet
3023          WHERE piet.index_lease_id = p_index_lease_id
3024          AND piet.include_exclude_flag = 'I')
3025                                OR
3026          (
3027          ppt.payment_term_id NOT IN (select piet.payment_term_id
3028          FROM pn_index_exclude_term_all piet
3029          WHERE piet.index_lease_id = p_index_lease_id)
3030          AND ( pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',ip_org_id) = 'Y' OR
3031 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',ip_org_id) = 'G' and  NVL(pil.gross_flag,'N') = 'Y') OR
3032 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',ip_org_id) = 'U' and  NVL(pil.gross_flag,'N') = 'N')
3033 	     )
3034          )
3035          )
3036    AND (( p_basis_type = c_basis_type_compound AND
3037                             not exists( SELECT null
3038                                         FROM pn_index_lease_periods_all plpx
3039                                         WHERE plpx.index_period_id = ppt.index_period_id
3040                                         AND plpx.index_lease_id = p_index_lease_id))
3041           OR p_basis_type <> c_basis_type_compound)
3042    AND ppt.frequency_code <> c_spread_frequency_one_time
3043    AND ppt.currency_code = pil.currency_code
3044 
3045    order by 1,2,3,4,5,6,7,8,9,10,11;
3046 
3047    /* Cursor to get the sum of payment term amounts for a given unique
3048       aggregation combination */
3049 
3050    CURSOR cur_payment_terms (
3051             ip_lease_id IN NUMBER
3052            ,ip_location_id IN NUMBER
3053            ,ip_payment_purpose_code IN VARCHAR2
3054            ,ip_payment_term_type_code IN VARCHAR2
3055            ,ip_vendor_id IN NUMBER
3056            ,ip_vendor_site_id IN NUMBER
3057            ,ip_customer_id IN NUMBER
3058            ,ip_customer_site_use_id IN NUMBER
3059            ,ip_frequency_code IN VARCHAR2
3060            ,ip_distribution_string IN VARCHAR2
3061            ,ip_index_term_indicator IN VARCHAR2
3062            ,ip_normalize IN VARCHAR2
3063            ,ip_include_in_var_rent IN VARCHAR2
3064            ,ip_index_lease_id IN NUMBER    -- Fix for bug# 1950708
3065            ,ip_basis_start_date IN DATE
3066            ,ip_basis_end_date IN DATE
3067            ,ip_org_id IN NUMBER
3068         ) IS
3069    SELECT ppt.payment_term_id,nvl(ppt.actual_amount,ppt.estimated_amount)
3070          ,ppt.frequency_code
3071          ,ppt.norm_start_date
3072    FROM pn_payment_terms_all ppt
3073    WHERE ppt.payment_purpose_code = ip_payment_purpose_code
3074    AND ppt.payment_term_type_code = ip_payment_term_type_code
3075    AND nvl(ppt.include_in_var_rent,'N') = nvl(ip_include_in_var_rent,'N')
3076    AND nvl(ppt.status,'-1') = decode(ppt.index_period_id,null,nvl(ppt.status,'-1'),'APPROVED')
3077    AND NVL (ppt.normalize, 'N')= ip_normalize
3081    AND nvl(ppt.customer_id ,-1)= nvl(ip_customer_id,nvl(ppt.customer_id,-1))
3078    AND nvl(ppt.location_id,-1) = nvl(ip_location_id,nvl(ppt.location_id,-1))
3079    AND nvl(ppt.vendor_id,-1) = nvl(ip_vendor_id,nvl(ppt.vendor_id,-1))
3080    AND nvl(ppt.vendor_site_id,-1) = nvl(ip_vendor_site_id,nvl(ppt.vendor_site_id,-1))
3082    AND nvl(ppt.customer_site_use_id,-1) = nvl(ip_customer_site_use_id,
3083                                               nvl(ppt.customer_site_use_id,-1))
3084    AND ppt.frequency_code = ip_frequency_code
3085    AND ( build_distributions_string (ppt.payment_term_id) = ip_distribution_string
3086          OR ip_distribution_string IS NULL
3087         )
3088    AND   (
3089          ppt.payment_term_id  IN (SELECT piet.payment_term_id
3090          FROM pn_index_exclude_term_all piet
3091          WHERE piet.index_lease_id = p_index_lease_id
3092          AND piet.include_exclude_flag = 'I')
3093                                OR
3094          (
3095          ppt.payment_term_id NOT IN (select piet.payment_term_id
3096          FROM pn_index_exclude_term_all piet
3097          WHERE piet.index_lease_id = p_index_lease_id)
3098          AND ( pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',ip_org_id) = 'Y' OR
3099 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',ip_org_id) = 'G' and l_gross_flag = 'Y' ) OR
3100 	      (pn_mo_cache_utils.get_profile_value('incl_terms_by_default_flag',ip_org_id) = 'U' and l_gross_flag = 'N' )
3101 	     )
3102          )
3103          )
3104    AND ( ( p_basis_type = c_basis_type_compound AND
3105                            not exists( SELECT null
3106                                        FROM pn_index_lease_periods_all plpx
3107                                        WHERE plpx.index_period_id = ppt.index_period_id
3108                                        AND plpx.index_lease_id = p_index_lease_id))
3109                   OR p_basis_type <> c_basis_type_compound)
3110    AND ppt.end_date >= ip_basis_start_date AND ppt.start_date <= ip_basis_end_date
3111    AND ppt.FREQUENCY_CODE <> c_spread_frequency_one_time
3112    AND ppt.lease_id = p_lease_id
3113    AND ppt.currency_code = g_currency_code;
3114 
3115    CURSOR fetch_generated_il_terms IS
3116     SELECT payment_term_id,
3117            actual_amount,
3118            location_id,
3119            payment_purpose_code,
3120            payment_term_type_code,
3121            vendor_id,
3122            vendor_site_id,
3123            customer_id,
3124            customer_site_use_id,
3125            frequency_code,
3126            index_term_indicator,
3127            start_date,
3128            normalize,
3129            schedule_day,
3130            end_date,
3131            include_in_var_rent
3132       FROM pn_payment_terms_all
3133      WHERE lease_id = p_lease_id
3134        AND index_period_id = p_index_period_id
3135        AND status = c_payment_term_status_approved;
3136 
3137    CURSOR cur_period_term_sum_amt (
3138             ip_lease_id               IN NUMBER
3139            ,ip_location_id            IN NUMBER
3140            ,ip_payment_purpose_code   IN VARCHAR2
3141            ,ip_payment_term_type_code IN VARCHAR2
3142            ,ip_vendor_id              IN NUMBER
3143            ,ip_vendor_site_id         IN NUMBER
3144            ,ip_customer_id            IN NUMBER
3145            ,ip_customer_site_use_id   IN NUMBER
3146            ,ip_frequency_code         IN VARCHAR2
3147            ,ip_distribution_string    IN VARCHAR2
3148            ,ip_index_term_indicator   IN VARCHAR2
3149            ,ip_normalize              IN VARCHAR2
3150            ,ip_index_period_id        IN NUMBER
3151            ,ip_include_in_var_rent    IN VARCHAR2
3152          ) IS
3153    SELECT nvl(ppt.actual_amount,0) actual_amount, ppt.index_term_indicator, ppt.payment_term_id
3154    FROM pn_payment_terms_all ppt
3155    WHERE ppt.payment_purpose_code = ip_payment_purpose_code
3156    AND ppt.payment_term_type_code = ip_payment_term_type_code
3157    AND ppt.index_period_id = ip_index_period_id
3158    AND nvl(ppt.status,'-1') = 'APPROVED'
3159    AND ((ip_index_term_indicator = c_index_pay_term_type_atlst
3160          AND ppt.index_term_indicator in (c_index_pay_term_type_atlst,c_index_pay_term_type_atlst_bb)) OR
3161         (ip_index_term_indicator = c_index_pay_term_type_recur
3162          AND ppt.index_term_indicator in (c_index_pay_term_type_recur,c_index_pay_term_type_backbill))
3163         )
3164    AND ((ppt.index_term_indicator = 'ATLEAST'
3165          AND nvl(ppt.normalize,'N') = ip_normalize) OR
3166                 (ppt.index_term_indicator <> 'ATLEAST'))
3167    AND nvl(ppt.location_id,-1) = nvl(ip_location_id,nvl(ppt.location_id,-1))
3168    AND nvl(ppt.vendor_id,-1) = nvl(ip_vendor_id,nvl(ppt.vendor_id,-1))
3169    AND nvl(ppt.vendor_site_id,-1) = nvl(ip_vendor_site_id,nvl(ppt.vendor_site_id,-1))
3170    AND nvl(ppt.customer_id ,-1)= nvl(ip_customer_id,nvl(ppt.customer_id,-1))
3171    AND nvl(ppt.customer_site_use_id,-1) = nvl(ip_customer_site_use_id,
3172                                               nvl(ppt.customer_site_use_id,-1))
3173    AND  ((ppt.index_term_indicator in (c_index_pay_term_type_atlst,
3174                                        c_index_pay_term_type_recur)
3175          AND ppt.frequency_code = ip_frequency_code) OR
3176         (ppt.index_term_indicator in (c_index_pay_term_type_atlst_bb,
3177                                       c_index_pay_term_type_backbill)
3178          AND ppt.frequency_code = ppt.frequency_code)
3179          )
3180    AND (build_distributions_string (ppt.payment_term_id) = ip_distribution_string
3184 
3181         OR ip_distribution_string IS NULL
3182         )
3183    AND ppt.currency_code = g_currency_code;
3185    -- NOTE on the end_date logic:
3186    -- The recurring terms are created on the next available sch date after SYSDATE.
3187    -- The backbill term takes into account the gap between the assessment date
3188    -- and the start date of the recurring term.
3189    -- Therefore, the start date should be assessment date; the end date should be
3190    -- => last_day_of(month_of(recurring term start date) - 1).
3191 
3192    CURSOR cur_sum_backbill_overlap_items (
3193             p_end_date                pn_payment_terms.end_date%TYPE
3194            ,p_location_id             pn_payment_terms.location_id%TYPE
3195            ,p_payment_purpose_code    pn_payment_terms.payment_purpose_code%TYPE
3196            ,p_payment_term_type_code  pn_payment_terms.payment_term_type_code%TYPE
3197            ,p_vendor_id               pn_payment_terms.vendor_id%TYPE
3198            ,p_vendor_site_id          pn_payment_terms.vendor_site_id%TYPE
3199            ,p_customer_id             pn_payment_terms.customer_id%TYPE
3200            ,p_customer_site_use_id    pn_payment_terms.customer_site_use_id%TYPE
3201            ,p_distribution_string     VARCHAR2
3202            ,p_normalize               pn_payment_terms.normalize%TYPE
3203          ) IS
3204    SELECT sum(item.actual_amount)  sum_overlap_amt
3205      FROM pn_payment_items_all         item,
3206           pn_payment_terms_all     term
3207     WHERE item.payment_term_id                            = term.payment_term_id
3208       AND item.due_date BETWEEN p_assessment_date AND p_end_date
3209       AND term.index_period_id                            = p_index_period_id
3210       AND term.index_term_indicator                       = p_index_term_indicator
3211       AND nvl(term.location_id, -1)                       = nvl(p_location_id, -1)
3212       AND nvl(term.payment_purpose_code, 'N')             = nvl(p_payment_purpose_code, 'N')
3213       AND nvl(term.payment_term_type_code, 'N')           = nvl(p_payment_term_type_code, 'N')
3214       AND nvl(term.vendor_id, -1)                         = nvl(p_vendor_id, -1)
3215       AND nvl(term.vendor_site_id, -1)                    = nvl(p_vendor_site_id, -1)
3216       AND nvl(term.customer_id, -1)                       = nvl(p_customer_id, -1)
3217       AND nvl(term.customer_site_use_id, -1)              = nvl(p_customer_site_use_id, -1)
3218       AND nvl(term.normalize, 'N')                        = p_normalize
3219       AND build_distributions_string(term.payment_term_id) = p_distribution_string;
3220 
3221    CURSOR org_id_cur IS
3222       SELECT org_id
3223       FROM pn_index_leases_all
3224       WHERE index_lease_id = p_index_lease_id;
3225 
3226   CURSOR gross_flag_cur IS
3227       SELECT NVL(GROSS_FLAG,'N')
3228       FROM pn_index_leases_all
3229       WHERE index_lease_id = p_index_lease_id;
3230 
3231    v_op_sum_amount                   NUMBER := 0;
3232    v_payment_amount                  NUMBER := 0;
3233    v_type_code                       VARCHAR2(100);
3234    v_start_date                      DATE;
3235    v_num_pymt_since_assmt_dt         NUMBER;
3236    v_payments_per_year               NUMBER;
3237    v_total_amt                       NUMBER := 0;
3238    v_total_backbill_rent_amt         NUMBER := 0;
3239    v_backbill_amt                    NUMBER := 0;
3240    v_total_backbill_amt              NUMBER := 0;
3241    v_previous_backbill_amt           NUMBER := 0;
3242    v_basis_start_date                pn_index_lease_periods.basis_start_date%type;
3243    v_basis_end_date                  pn_index_lease_periods.basis_end_date%type;
3244    v_msg                             VARCHAR2(100);
3245    prev_payment_purpose_code         pn_payment_terms.payment_purpose_code%type := null;
3246    prev_payment_term_type_code       pn_payment_terms.payment_term_type_code%type := null;
3247    prev_location_id                  pn_payment_terms.location_id%type := null;
3248    prev_vendor_id                    pn_payment_terms.vendor_id%type := null;
3249    prev_vendor_site_id               pn_payment_terms.vendor_site_id%type := null;
3250    prev_customer_id                  pn_payment_terms.customer_id%type := null;
3251    prev_customer_site_use_id         pn_payment_terms.customer_site_use_id%type := null;
3252    prev_distribution_string          VARCHAR2(2000) := null;
3253    prev_normalize                    VARCHAR2(10)   := null;
3254    prev_frequency_code               pn_payment_terms.frequency_code%TYPE;
3255    prev_end_date                     pn_payment_terms.end_date%TYPE;
3256    v_overlap_backbill_amt            NUMBER := 0;
3257    prev_include_in_var_rent          VARCHAR2(30)   := null;
3258    v_count                           NUMBER := 0;
3259    v_source_payment_term_id          NUMBER := 0;
3260    v_prev_payment_term_id            NUMBER := 0;
3261    curr_location_id                  pn_payment_terms.location_id%type := null;
3262    curr_payment_purpose_code         pn_payment_terms.payment_purpose_code%type := null;
3263    curr_frequency_code               pn_payment_terms.frequency_code%type := null;
3264    --curr_include_in_var_rent          pn_payment_terms.include_in_var_rent%type := null;
3265    curr_include_in_var_rent          VARCHAR2(30);
3266    p_normalized                      VARCHAR2(1):='N';
3267    p_backbill_term_indicator         VARCHAR2(100) := null;
3268    v_date                            VARCHAR2(100);
3269    v_approved_amount_annual          NUMBER := 0;
3270    v_prorated_backbill_amt           NUMBER := 0;
3271    v_existing_payment_amount         NUMBER := 0;
3272    v_previous_exist_backbill         NUMBER := 0;
3273    v_total_exist_backbill            NUMBER := 0;
3274    v_existing_backbill               NUMBER := 0;
3278    i                                 NUMBER := 0;
3275    v_created_payment_term_id         PN_PAYMENT_TERMS.PAYMENT_TERM_ID%TYPE;
3276    l_frequency                       PN_PAYMENT_TERMS.FREQUENCY_CODE%TYPE;
3277    l_count                           NUMBER := 0;
3279    l_amount                          NUMBER := 0;
3280 
3281    TYPE term_rec IS  RECORD (amount NUMBER, type VARCHAR2(30));
3282 
3283    exist_term_rec term_rec;
3284 
3285    TYPE exist_payment    IS TABLE OF exist_term_rec%TYPE INDEX BY BINARY_INTEGER;
3286    TYPE payment_term_tbl IS TABLE OF pn_payment_terms_all%ROWTYPE INDEX BY BINARY_INTEGER;
3287    TYPE id_tbl           IS TABLE OF pn_payment_terms.payment_term_id%TYPE INDEX BY BINARY_INTEGER;
3288 
3289    exist_term_tab   exist_payment;
3290    appr_ind_lease_tbl  exist_payment;
3291 
3292    l_check_term_tbl    payment_term_tbl;
3293    l_impacted_term_tbl payment_term_tbl;
3294    l_chklist_tbl       id_tbl;
3295    l_used              BOOLEAN;
3296    l_nxt_schdate       DATE;
3297    l_day               pn_payment_terms.schedule_day%TYPE;
3298    l_org_id            NUMBER;
3299 
3300    l_lst_norm_st_date  DATE;
3301    l_this_norm_st_date  DATE;
3302 
3303 
3304    /* for calculate annualized basis on ENDATE/PERIOD option */
3305    l_calc_annualized_basis VARCHAR2(30);
3306    v_end_date                       DATE;
3307    v_reference_period_type          VARCHAR2(30);
3308 
3309    l_backbill_st_date        DATE;
3310    l_backbill_end_date       DATE;
3311    l_backbill_end_date_temp  DATE;
3312    l_backbill_freq           VARCHAR2(30);
3313    l_backbill_amt            NUMBER;
3314    l_recur_bb_calc_date      DATE;
3315    l_backbill_normalize      VARCHAR2(1);
3316 
3317    CURSOR ref_period_cur ( p_index_lease_id NUMBER) IS
3318    SELECT reference_period
3319    FROM pn_index_leases_all
3320    WHERE index_lease_id = p_index_lease_id;
3321 
3322 
3323 BEGIN
3324 
3325    put_log ('In create_aggr_payment_terms (+)');
3326 
3327    FOR org_id_rec IN org_id_cur LOOP
3328      l_org_id := org_id_rec.org_id;
3329    END LOOP;
3330 
3331     /* to get the reference period_type */
3332     FOR ref_period_rec IN ref_period_cur(p_index_lease_id) LOOP
3333             v_reference_period_type := ref_period_rec.reference_period;
3334     END LOOP;
3335 
3336    l_calc_annualized_basis
3337      := pn_mo_cache_utils.get_profile_value('PN_CALC_ANNUALIZED_BASIS', l_org_id);
3338 
3339    SELECT NVL (p_increase_on, c_increase_on_gross)
3340    INTO v_type_code
3341    FROM  DUAL;
3342 
3343    v_basis_start_date := p_basis_start_date;
3344    v_basis_end_date   := p_basis_end_date;
3345 
3346 
3347    IF p_basis_type = c_basis_type_compound   THEN
3348 
3349       put_log('create_aggr_payment_terms - getting annualized basis');
3350 
3351       sum_payment_items (
3352             p_index_lease_id              => p_index_lease_id
3353            ,p_basis_start_date            => v_basis_start_date
3354            ,p_basis_end_date              => v_basis_end_date
3355            ,p_type_code                   => v_type_code
3356            ,p_include_index_items         => 'N'
3357            ,op_sum_amount                 => v_op_sum_amount );
3358    ELSE
3359       put_log('create_aggr_payment_terms - getting basis');
3360 
3361       sum_payment_items (
3362             p_index_lease_id              => p_index_lease_id
3363            ,p_basis_start_date            => v_basis_start_date
3364            ,p_basis_end_date              => v_basis_end_date
3365            ,p_type_code                   => v_type_code
3366            ,op_sum_amount                 => v_op_sum_amount );
3367    END IF;
3368 
3369    l_check_term_tbl.delete;
3370    l_chklist_tbl.delete;
3371 
3372    FOR cache_cur IN fetch_generated_il_terms LOOP
3373       l_count := l_check_term_tbl.COUNT;
3374       l_check_term_tbl(l_count).payment_term_id        := cache_cur.payment_term_id;
3375       l_check_term_tbl(l_count).frequency_code         := cache_cur.frequency_code;
3376       l_check_term_tbl(l_count).index_term_indicator   := cache_cur.index_term_indicator;
3377       l_check_term_tbl(l_count).start_date             := cache_cur.start_date;
3378       l_check_term_tbl(l_count).actual_amount          := cache_cur.actual_amount;
3379 
3380       l_check_term_tbl(l_count).payment_purpose_code   := cache_cur.payment_purpose_code;
3381       l_check_term_tbl(l_count).payment_term_type_code := cache_cur.payment_term_type_code;
3382       l_check_term_tbl(l_count).location_id            := cache_cur.location_id;
3383       l_check_term_tbl(l_count).vendor_id              := cache_cur.vendor_id;
3384       l_check_term_tbl(l_count).vendor_site_id         := cache_cur.vendor_site_id;
3385       l_check_term_tbl(l_count).customer_id            := cache_cur.customer_id;
3386       l_check_term_tbl(l_count).customer_site_use_id   := cache_cur.customer_site_use_id;
3387       l_check_term_tbl(l_count).normalize              := cache_cur.normalize;
3388       l_check_term_tbl(l_count).include_in_var_rent    := cache_cur.include_in_var_rent;
3389       l_check_term_tbl(l_count).end_date               := cache_cur.end_date;
3390       l_check_term_tbl(l_count).schedule_day           := cache_cur.schedule_day;
3391 
3392    END LOOP;
3393 
3394    put_log ('create_aggr_payment_terms - basis amt '|| to_char(v_op_sum_amount));
3395 
3396    v_count := 0;
3397 
3398    /* getting unique combination of payment terms for a lease. */
3399 
3403                    ip_index_lease_id             => p_index_lease_id
3400     put_log('create_aggr_payment_terms - getting unique comb.');
3401 
3402     FOR rec_unq_comb IN cur_unq_comb (
3404                   ,ip_basis_start_date           => v_basis_start_date
3405                   ,ip_basis_end_date             => v_basis_end_date
3406                   ,ip_type_code                  => v_type_code
3407                   ,ip_index_term_indicator       => p_index_term_indicator
3408                   ,ip_org_id                     => l_org_id )
3409 
3410     LOOP
3411        put_log('create_aggr_payment_terms - in unique comb. loop');
3412 
3413        put_log('create_aggr_payment_terms - derive_payment_start_date');
3414 
3415        /* to get the term_end_date */
3416        derive_term_end_date(ip_index_lease_id               =>  p_index_lease_id
3417                            ,ip_index_period_id              =>  p_index_period_id
3418                            ,ip_main_lease_termination_date  =>  p_main_lease_termination_date
3419                            ,op_term_end_date                =>  v_end_date);
3420 
3421        derive_payment_start_date (
3422                   p_spread_frequency            => rec_unq_comb.frequency_code
3423                  ,p_assessment_date             => p_assessment_date
3424                  ,p_end_date                    => v_end_date
3425                  ,p_calculate_date              => p_calculate_date
3426                  ,p_index_lease_id              => p_index_lease_id
3427                  ,op_recur_pay_start_date       => v_start_date
3428                  ,op_num_pymt_since_assmt_dt    => v_num_pymt_since_assmt_dt
3429                  );
3430 
3431        SELECT DECODE (
3432                   rec_unq_comb.frequency_code
3433                  ,c_spread_frequency_monthly, 12
3434                  ,c_spread_frequency_quarterly, 4
3435                  ,c_spread_frequency_semiannual, 2
3436                  ,c_spread_frequency_annually, 1
3437                  ,1 )
3438        INTO v_payments_per_year
3439        FROM DUAL;
3440 
3441        IF p_index_finder_type in ( c_index_finder_backbill, c_index_finder_most_recent) AND
3442           NVL (v_num_pymt_since_assmt_dt, 0) <> 0 THEN
3443 
3444           SELECT decode(p_index_term_indicator,
3445                         c_index_pay_term_type_atlst,
3446                         c_index_pay_term_type_atlst_bb,
3447                         c_index_pay_term_type_recur,
3448                         c_index_pay_term_type_backbill)
3449           INTO p_backbill_term_indicator
3450           FROM DUAL;
3451 
3452        END IF;
3453 
3454 
3455        put_log('create_aggr_payment_terms - getting annualized payments');
3456 
3457        /* Get the sum of annualized payments of all the payment terms that belong
3458           to a given unique aggr. combination */
3459 
3460        /* Initialize the table and the counter variables */
3461 
3462        item_amt_tab.delete;
3463 
3464        l_count := 0;
3465        v_total_amt := 0;
3466 
3467        OPEN gross_flag_cur;
3468        FETCH gross_flag_cur INTO l_gross_flag;
3469        Close gross_flag_cur;
3470 
3471        IF NVL(l_calc_annualized_basis,'PERIOD') = 'PERIOD' THEN
3472          /* annualized basis calculated for terms active for the IR period */
3473          OPEN cur_payment_terms ( p_lease_id
3474                                  ,rec_unq_comb.location_id
3475                                  ,rec_unq_comb.payment_purpose_code
3476                                  ,rec_unq_comb.payment_term_type_code
3477                                  ,rec_unq_comb.vendor_id
3478                                  ,rec_unq_comb.vendor_site_id
3479                                  ,rec_unq_comb.customer_id
3480                                  ,rec_unq_comb.customer_site_use_id
3481                                  ,rec_unq_comb.frequency_code
3482                                  ,rec_unq_comb.distribution_string
3483                                  ,p_index_term_indicator
3484                                  ,rec_unq_comb.normalize
3485                                  ,rec_unq_comb.include_in_var_rent
3486                                  ,p_index_lease_id
3487                                  ,v_basis_start_date
3488                                  ,v_basis_end_date
3489                                  ,l_org_id);
3490 
3491        ELSIF NVL(l_calc_annualized_basis,'PERIOD') = 'ENDDATE' THEN
3492          /* annualized basis calculated for terms active on period end date */
3493          OPEN cur_payment_terms ( p_lease_id
3494                                  ,rec_unq_comb.location_id
3495                                  ,rec_unq_comb.payment_purpose_code
3496                                  ,rec_unq_comb.payment_term_type_code
3497                                  ,rec_unq_comb.vendor_id
3498                                  ,rec_unq_comb.vendor_site_id
3499                                  ,rec_unq_comb.customer_id
3500                                  ,rec_unq_comb.customer_site_use_id
3501                                  ,rec_unq_comb.frequency_code
3502                                  ,rec_unq_comb.distribution_string
3503                                  ,p_index_term_indicator
3504                                  ,rec_unq_comb.normalize
3505                                  ,rec_unq_comb.include_in_var_rent
3506                                  ,p_index_lease_id
3507                                  ,v_basis_end_date
3508                                  ,v_basis_end_date
3512        l_lst_norm_st_date := NULL;
3509                                  ,l_org_id);
3510        END IF;
3511 
3513        l_this_norm_st_date := NULL;
3514 
3515        LOOP
3516 
3517           put_log ('create_aggr_payment_terms - in annualized payments loop');
3518           l_count := l_count + 1;
3519 
3520           FETCH cur_payment_terms INTO
3521                 item_amt_tab(l_count).payment_term_id,
3522                 l_amount,
3523                 l_frequency,
3524                 l_this_norm_st_date;
3525 
3526           EXIT WHEN cur_payment_terms%NOTFOUND;
3527 
3528           IF l_frequency = 'MON' THEN
3529             item_amt_tab(l_count).amount := l_amount * 12;
3530           ELSIF l_frequency = 'QTR' THEN
3531             item_amt_tab(l_count).amount := l_amount * 4;
3532           ELSIF l_frequency = 'SA' THEN
3533             item_amt_tab(l_count).amount := l_amount * 2;
3534           ELSIF l_frequency = 'YR' THEN
3535             item_amt_tab(l_count).amount := l_amount;
3536           END IF;
3537 
3538           IF l_lst_norm_st_date IS NULL THEN
3539             l_lst_norm_st_date := l_this_norm_st_date;
3540           ELSE
3541             IF l_this_norm_st_date > l_lst_norm_st_date THEN
3542               l_lst_norm_st_date := l_this_norm_st_date;
3543             END IF;
3544           END IF;
3545 
3546           v_total_amt := v_total_amt + item_amt_tab(l_count).amount;
3547 
3548           /* store the payment_term_id to be used later on in the program
3549              when creating the new payment term */
3550 
3551           v_source_payment_term_id := item_amt_tab(l_count).payment_term_id;
3552 
3553        END LOOP;
3554 
3555        put_log ('create_aggr_payment_terms - annualized payments amt '|| to_char(v_total_amt));
3556 
3557        close cur_payment_terms;
3558 
3559        put_log ('create_aggr_payment_terms - v_source_payment_term_id'|| to_char(v_source_payment_term_id));
3560        put_log ('create_aggr_payment_terms - total rent'||to_char(p_total_rent_amount) );
3561 
3562        /* Get the payment contribution for the unique aggr. combination */
3563 
3564        IF v_op_sum_amount <> 0 THEN
3565           v_payment_amount := ROUND(p_total_rent_amount * (v_total_amt/v_op_sum_amount)
3566                                    ,get_amount_precision);
3567        ELSE
3568           v_payment_amount := 0;
3569        END IF;
3570 
3571        /* get the amount of the approved payment terms for a
3572           given period. If p_index_term_indicator is 'ATLEAST'
3573           then get the amounts for both the 'ATLEAST'and the
3574           'ATLEAST BACKBILL' in one go and store in a PL/SQL
3575           table. Similarly, if the p_index_term_indicator in
3576           'RECUR' then get the amounts for both the 'RECUR' and
3577            the 'RECUR back Bill' and store it in a PL/SQL table */
3578 
3579        put_log ('create_aggr_payment_terms - delete tab ' );
3580 
3581        i := 0;
3582 
3583        exist_term_tab.delete;
3584        appr_ind_lease_tbl.delete;
3585 
3586        /* fetch all contributing index lease payment terms */
3587 
3588        FOR sum_amt_cur IN cur_period_term_sum_amt(
3589                              p_lease_id
3590                             ,rec_unq_comb.location_id
3591                             ,rec_unq_comb.payment_purpose_code
3592                             ,rec_unq_comb.payment_term_type_code
3593                             ,rec_unq_comb.vendor_id
3594                             ,rec_unq_comb.vendor_site_id
3595                             ,rec_unq_comb.customer_id
3596                             ,rec_unq_comb.customer_site_use_id
3597                             ,rec_unq_comb.frequency_code
3598                             ,rec_unq_comb.distribution_string
3599                             ,p_index_term_indicator
3600                             ,rec_unq_comb.normalize
3601                             ,p_index_period_id
3602                             ,rec_unq_comb.include_in_var_rent) LOOP
3603 
3604           i                                     := appr_ind_lease_tbl.COUNT;
3605           l_chklist_tbl(l_chklist_tbl.COUNT)    := sum_amt_cur.payment_term_id;
3606           appr_ind_lease_tbl(i).amount          := sum_amt_cur.actual_amount;
3607           appr_ind_lease_tbl(i).type            := sum_amt_cur.index_term_indicator;
3608 
3609        END LOOP;
3610 
3611        /* sum the actual amount values based on its type */
3612 
3613        FOR c1 IN 0 .. appr_ind_lease_tbl.COUNT - 1 LOOP
3614           i := 0;
3615           FOR c2 IN 1 .. exist_term_tab.COUNT LOOP
3616              IF exist_term_tab(c2).type = appr_ind_lease_tbl(c1).type THEN
3617                 exist_term_tab(c2).amount := exist_term_tab(c2).amount + appr_ind_lease_tbl(c1).amount;
3618                 i := 1;
3619                 exit;
3620              END IF;
3621           END LOOP;
3622 
3623           IF i = 0 THEN
3624              i                        := exist_term_tab.COUNT + 1;
3625              exist_term_tab(i).type   := appr_ind_lease_tbl(c1).type;
3626              exist_term_tab(i).amount := appr_ind_lease_tbl(c1).amount;
3627           END IF;
3628        END LOOP;
3629 
3630        /* get the existing terms amount for type of ATLEASE/RECUR */
3631 
3632        v_existing_payment_amount := 0;
3633 
3634        for i in 1 .. exist_term_tab.count
3635        loop
3636 
3637           if exist_term_tab(i).type in (c_index_pay_term_type_atlst,
3641 
3638                                         c_index_pay_term_type_recur) then
3639 
3640              v_existing_payment_amount := exist_term_tab(i).amount * v_payments_per_year;
3642              exit;
3643           end if;
3644        end loop;
3645 
3646        put_log('create_aggr_payment_terms p_index_term_indicator - '|| p_index_term_indicator);
3647        put_log ('create_aggr_payment_terms - v_payment_amount ' || to_char(v_payment_amount));
3648        put_log ('create_aggr_payment_terms - rec_unq_comb.vendor_id ' || to_char(rec_unq_comb.vendor_id));
3649        put_log ('create_aggr_payment_terms - rec_unq_comb.vendor_site_id ' || to_char(rec_unq_comb.vendor_site_id));
3650        put_log ('create_aggr_payment_terms - rec_unq_comb.payment_term_type_code ****'|| rec_unq_comb.payment_term_type_code);
3651 
3652        put_log ('create_aggr_payment_terms - existing pay amt ' || to_char(v_existing_payment_amount));
3653 
3654       /* Create atleast/recurring payment terms if main lease termination date > sysdate
3655          Fix for bug# 2007492 */
3656 
3657        -- NOTE: assumption is payment end date = lease termination date
3658        IF ((v_payment_amount - v_existing_payment_amount) <> 0) AND
3659           (v_start_date <= p_main_lease_termination_date) THEN
3660 
3661 
3662           p_normalized := NVL(rec_unq_comb.normalize,'N');
3663 
3664           IF v_start_date <= v_end_date  AND
3665              (( TRUNC(p_main_lease_termination_date) > p_calculate_date AND
3666                NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') IN ('OT','RECUR') ) OR
3667               NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'SINGLETERM')
3668           THEN
3669 
3670           create_payment_term_record (
3671                 p_lease_id               => p_lease_id
3672                ,p_location_id            => rec_unq_comb.location_id
3673                ,p_purpose_code           => rec_unq_comb.payment_purpose_code
3674                ,p_index_period_id        => p_index_period_id
3675                ,p_term_template_id       => NULL
3676                ,p_spread_frequency       => rec_unq_comb.frequency_code
3677                ,p_rounding_flag          => p_rounding_flag
3678                ,p_payment_amount         => v_payment_amount - v_existing_payment_amount
3679                ,p_normalized             => p_normalized
3680                ,p_include_in_var_rent    => rec_unq_comb.include_in_var_rent
3681                ,p_start_date             => v_start_date
3682                ,p_index_term_indicator   => p_index_term_indicator
3683                ,p_payment_term_id        => v_source_payment_term_id
3684                ,p_basis_relationship     => p_basis_relationship
3685                ,p_called_from            => 'INDEX'
3686                ,p_calculate_date         => p_calculate_date
3687                ,p_norm_st_date           => l_lst_norm_st_date
3688                ,p_end_date               => v_end_date
3689                ,op_payment_term_id       => v_created_payment_term_id
3690                ,op_msg                   => v_msg
3691                );
3692           END IF;
3693 
3694           IF NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'RECUR' AND
3695    	     p_index_finder_type in (c_index_finder_backbill,
3696                                      c_index_finder_most_recent)
3697 	  THEN
3698              derive_term_end_date(
3699                             ip_index_lease_id               =>  p_index_lease_id
3700                            ,ip_index_period_id              =>  p_index_period_id
3701                            ,ip_main_lease_termination_date  =>  p_main_lease_termination_date
3702                            ,op_term_end_date                =>  l_backbill_end_date_temp);
3703 
3704                    l_backbill_st_date   := p_assessment_date ;
3705                    l_backbill_end_date  := LEAST(v_start_date - 1,l_backbill_end_date_temp);
3706                    l_backbill_freq      := rec_unq_comb.frequency_code;
3707                    l_backbill_amt       := v_payment_amount - v_existing_payment_amount;
3708                    l_recur_bb_calc_date := p_calculate_date;
3709                    l_backbill_normalize := NVL(rec_unq_comb.normalize,'N');
3710 
3711              IF l_backbill_st_date <= NVL(l_backbill_end_date,TRUNC(SYSDATE)) THEN
3712 
3713                 create_payment_term_record (
3714                          p_lease_id               => p_lease_id
3715                         ,p_location_id            => rec_unq_comb.location_id
3716                         ,p_purpose_code           => rec_unq_comb.payment_purpose_code
3717                         ,p_index_period_id        => p_index_period_id
3718                         ,p_term_template_id       => NULL
3719                         ,p_spread_frequency       => l_backbill_freq
3720                         ,p_rounding_flag          => p_rounding_flag
3721                         ,p_payment_amount         => l_backbill_amt
3722                         ,p_normalized             => l_backbill_normalize
3723                         ,p_include_in_var_rent    => rec_unq_comb.include_in_var_rent
3724                         ,p_start_date             => l_backbill_st_date
3725                         ,p_index_term_indicator   => p_backbill_term_indicator
3726                         ,p_payment_term_id        => v_source_payment_term_id
3727                         ,p_basis_relationship     => p_basis_relationship
3728                         ,p_called_from            => 'INDEX'
3729                         ,p_calculate_date         => p_calculate_date
3730                         ,p_norm_st_date           => l_lst_norm_st_date
3731                         ,p_end_date               => l_backbill_end_date
3732                         ,p_recur_bb_calc_date     => l_recur_bb_calc_date
3736           END IF;
3733                         ,op_payment_term_id       => v_created_payment_term_id
3734                         ,op_msg                   => v_msg );
3735              END IF;
3737 
3738           /* insert records into intermediate table */
3739           IF v_created_payment_term_id IS NOT NULL THEN --#@#Bug4291907
3740           insert_inter_term (
3741                 ip_index_period_id       => p_index_period_id,
3742                 ip_index_term_indicator  => p_index_term_indicator,
3743                 ip_combination_amt       => v_payment_amount,
3744                 ip_total_terms_amt       => v_total_amt,
3745                 ip_rent_increase_term_id => v_created_payment_term_id,
3746                 ip_index_lease_id        => p_index_lease_id);
3747           END IF; --#@#Bug4291907
3748 
3749        END IF;
3750 
3751        IF v_count = 0  THEN
3752           prev_payment_purpose_code    := rec_unq_comb.payment_purpose_code;
3753           prev_payment_term_type_code  := rec_unq_comb.payment_term_type_code;
3754           prev_location_id             := rec_unq_comb.location_id;
3755           prev_vendor_id               := rec_unq_comb.vendor_id;
3756           prev_vendor_site_id          := rec_unq_comb.vendor_site_id;
3757           prev_include_in_var_rent     := rec_unq_comb.include_in_var_rent;
3758           prev_customer_id             := rec_unq_comb.customer_id;
3759           prev_customer_site_use_id    := rec_unq_comb.customer_site_use_id;
3760           prev_distribution_string     := rec_unq_comb.distribution_string;
3761           prev_frequency_code          := rec_unq_comb.frequency_code;
3762           prev_normalize               := p_normalized;
3763           prev_end_date                := last_day(add_months(v_start_date, -1));
3764 
3765           v_count := 1;
3766        END IF;
3767 
3768        /* Determine the amounts for the backbill payment terms */
3769 
3770        IF p_index_finder_type in (c_index_finder_backbill,
3771                                   c_index_finder_most_recent) AND
3772           NVL (v_num_pymt_since_assmt_dt, 0) <> 0 THEN
3773 
3774           IF NVL(prev_payment_purpose_code,'N')       = NVL(rec_unq_comb.payment_purpose_code,'N')   AND
3775              NVL(prev_payment_term_type_code,'N')     = NVL(rec_unq_comb.payment_term_type_code,'N') AND
3776              NVL(prev_location_id,0)                  = NVL(rec_unq_comb.location_id,0)              AND
3777              NVL(prev_vendor_id,0)                    = NVL(rec_unq_comb.vendor_id,0)                AND
3778              NVL(prev_vendor_site_id,0)               = NVL(rec_unq_comb.vendor_site_id,0)           AND
3779              NVL(prev_customer_id,0)                  = NVL(rec_unq_comb.customer_id ,0)             AND
3780              NVL(prev_customer_site_use_id,0)         = NVL(rec_unq_comb.customer_site_use_id,0)     AND
3781              prev_distribution_string                 = rec_unq_comb.distribution_string             AND
3782              NVL(prev_normalize,'N')                  = nvl(p_normalized, 'N')                       AND
3783              NVL(prev_include_in_var_rent,'N')        = NVL(rec_unq_comb.include_in_var_rent,'N')
3784           THEN
3785 
3786              v_backbill_amt := ROUND (  (v_payment_amount / v_payments_per_year)
3787                                          * v_num_pymt_since_assmt_dt
3788                                       ,get_amount_precision );
3789              v_total_backbill_amt := v_total_backbill_amt + v_backbill_amt;
3790              v_prev_payment_term_id := v_source_payment_term_id;
3791 
3792              /* get the existing terms amount for type of ATLEASE/RECUR */
3793 
3794              v_existing_backbill := 0;
3795 
3796              for i in 1 .. exist_term_tab.count
3797              loop
3798                 if exist_term_tab(i).type in (c_index_pay_term_type_atlst_bb,
3799                                               c_index_pay_term_type_backbill) then
3800 
3801                    v_existing_backbill := exist_term_tab(i).amount ;
3802                    exit;
3803                 end if;
3804              end loop;
3805 
3806              v_total_exist_backbill := v_total_exist_backbill + v_existing_backbill;
3807 
3808           ELSE
3809              v_previous_backbill_amt := v_total_backbill_amt;
3810              v_previous_exist_backbill := v_total_exist_backbill;
3811 
3812              v_overlap_backbill_amt := 0; -- reset
3813 
3814              put_log('determining the back bill overlap amount');
3815 
3816              FOR sum_amt_rec IN cur_sum_backbill_overlap_items (
3817                                    p_end_date               => prev_end_date
3818                                   ,p_location_id            => prev_location_id
3819                                   ,p_payment_purpose_code   => prev_payment_purpose_code
3820                                   ,p_payment_term_type_code => prev_payment_term_type_code
3821                                   ,p_vendor_id              => prev_vendor_id
3822                                   ,p_vendor_site_id         => prev_vendor_site_id
3823                                   ,p_customer_id            => prev_customer_id
3824                                   ,p_customer_site_use_id   => prev_customer_site_use_id
3825                                   ,p_distribution_string    => prev_distribution_string
3826                                   ,p_normalize              => p_normalized)
3827              LOOP
3828                 v_overlap_backbill_amt := nvl(sum_amt_rec.sum_overlap_amt,0);
3829              END LOOP;
3830 
3831              put_log('back bill overlap amount: '||v_overlap_backbill_amt);
3832 
3836                    combination */
3833              if (v_previous_backbill_amt - v_previous_exist_backbill - v_overlap_backbill_amt) <> 0 THEN
3834 
3835                 /* Creating the backbill/atleast backbill payment term for the earlier
3837 
3838                 IF NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'OT' THEN
3839                    l_backbill_st_date   := TRUNC(SYSDATE) ;
3840                    l_backbill_end_date  := NULL;
3841                    l_backbill_freq      := c_spread_frequency_one_time;
3842                    l_backbill_amt       := (v_previous_backbill_amt -
3843                                             v_previous_exist_backbill -
3844                                             v_overlap_backbill_amt);
3845                    l_backbill_normalize := 'N';
3846 
3847 
3848 
3849                   IF l_backbill_st_date <= NVL(l_backbill_end_date,TRUNC(SYSDATE)) THEN
3850 
3851                    create_payment_term_record (
3852                          p_lease_id               => p_lease_id
3853                         ,p_location_id            => prev_location_id
3854                         ,p_purpose_code           => prev_payment_purpose_code
3855                         ,p_index_period_id        => p_index_period_id
3856                         ,p_term_template_id       => NULL
3857                         ,p_spread_frequency       => l_backbill_freq
3858                         ,p_rounding_flag          => p_rounding_flag
3859                         ,p_payment_amount         => l_backbill_amt
3860                         ,p_normalized             => l_backbill_normalize
3861                         ,p_include_in_var_rent    => prev_include_in_var_rent
3862                         ,p_start_date             => l_backbill_st_date
3863                         ,p_index_term_indicator   => p_backbill_term_indicator
3864                         ,p_payment_term_id        => v_prev_payment_term_id
3865                         ,p_basis_relationship     => p_basis_relationship
3866                         ,p_called_from            => 'INDEX'
3867                         ,p_calculate_date         => p_calculate_date
3868                         ,p_norm_st_date           => l_lst_norm_st_date
3869                         ,p_end_date               => l_backbill_end_date
3870                         ,p_recur_bb_calc_date     => l_recur_bb_calc_date
3871                         ,op_payment_term_id       => v_created_payment_term_id
3872                         ,op_msg                   => v_msg );
3873 
3874                   END IF;
3875                 END IF;
3876 
3877                    /* Insert records into the intermediate table , for the backbill amounts */
3878 
3879               IF v_created_payment_term_id IS NOT NULL THEN --#@#Bug4291907
3880                 insert_inter_term (
3881                          ip_index_period_id => p_index_period_id,
3882                          ip_index_term_indicator      => p_backbill_term_indicator,
3883                          ip_combination_amt           => v_payment_amount,
3884                          ip_total_terms_amt           => v_total_amt,
3885                          ip_rent_increase_term_id     => v_created_payment_term_id,
3886                          ip_index_lease_id            => p_index_lease_id);
3887               END IF; --#@#Bug4291907
3888 
3889              end if;
3890 
3891              v_total_backbill_amt := 0;
3892              v_backbill_amt :=0;
3893              v_total_exist_backbill := 0;
3894              v_backbill_amt := ROUND ((v_payment_amount / v_payments_per_year)
3895                                        * v_num_pymt_since_assmt_dt
3896                                         ,get_amount_precision );
3897              v_existing_backbill := 0;
3898 
3899              v_total_backbill_amt := v_total_backbill_amt + v_backbill_amt;
3900 
3901              /* get the existing terms amount for type of ATLEASE/RECUR */
3902 
3903              for i in 1 .. exist_term_tab.count
3904              loop
3905                 if exist_term_tab(i).type in (c_index_pay_term_type_atlst_bb,
3906                                               c_index_pay_term_type_backbill) then
3907 
3908                    v_existing_backbill := exist_term_tab(i).amount ;
3909                    exit;
3910                 end if;
3911              end loop;
3912 
3913              v_total_exist_backbill := v_total_exist_backbill + v_existing_backbill;
3914              v_prev_payment_term_id := v_source_payment_term_id;
3915 
3916              prev_payment_purpose_code    := rec_unq_comb.payment_purpose_code;
3917              prev_payment_term_type_code  := rec_unq_comb.payment_term_type_code;
3918              prev_location_id             := rec_unq_comb.location_id;
3919              prev_vendor_id               := rec_unq_comb.vendor_id;
3920              prev_vendor_site_id          := rec_unq_comb.vendor_site_id;
3921              prev_customer_id             := rec_unq_comb.customer_id;
3922              prev_customer_site_use_id    := rec_unq_comb.customer_site_use_id;
3923              prev_normalize               := p_normalized;
3924              prev_include_in_var_rent     := rec_unq_comb.include_in_var_rent;
3925              prev_distribution_string     := rec_unq_comb.distribution_string;
3926              prev_end_date                := last_day(add_months(v_start_date, -1));
3927 
3928           END IF; /* Combination comparison suing the prev and current variables */
3929        END IF;  /* index_finder_backbill */
3930 
3931       -- END IF; /*  p_total_rent_amount > 0 */
3932 
3933        curr_location_id             := rec_unq_comb.location_id;
3934        curr_payment_purpose_code    := rec_unq_comb.payment_purpose_code;
3938 
3935        curr_frequency_code          := rec_unq_comb.frequency_code;
3936        curr_include_in_var_rent     := rec_unq_comb.include_in_var_rent;
3937    END LOOP;
3939    /* check to see if you need to do the backbill creation for the last combination record */
3940 
3941    IF p_index_finder_type in ( c_index_finder_backbill, c_index_finder_most_recent) AND
3942       NVL (v_num_pymt_since_assmt_dt, 0) <> 0 THEN
3943 
3944       put_log('determining the back bill overlap amount');
3945 
3946       v_overlap_backbill_amt := 0; -- reset
3947 
3948       FOR sum_amt_rec IN cur_sum_backbill_overlap_items (
3949                             p_end_date               => prev_end_date
3950                            ,p_location_id            => prev_location_id
3951                            ,p_payment_purpose_code   => prev_payment_purpose_code
3952                            ,p_payment_term_type_code => prev_payment_term_type_code
3953                            ,p_vendor_id              => prev_vendor_id
3954                            ,p_vendor_site_id         => prev_vendor_site_id
3955                            ,p_customer_id            => prev_customer_id
3956                            ,p_customer_site_use_id   => prev_customer_site_use_id
3957                            ,p_distribution_string    => prev_distribution_string
3958                            ,p_normalize              => p_normalized)
3959       LOOP
3960          v_overlap_backbill_amt := nvl(sum_amt_rec.sum_overlap_amt,0);
3961       END LOOP;
3962 
3963       put_log('back bill overlap amount: '||v_overlap_backbill_amt);
3964 
3965       IF (v_total_backbill_amt - v_total_exist_backbill - v_overlap_backbill_amt) <> 0 THEN
3966 
3967          IF NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'OT' THEN
3968            l_backbill_st_date   := TRUNC(SYSDATE) ;
3969            l_backbill_end_date  := NULL;
3970            l_backbill_freq      := c_spread_frequency_one_time;
3971            l_backbill_amt       := (v_total_backbill_amt - v_total_exist_backbill - v_overlap_backbill_amt);
3972          /*ELSE
3973 
3974            derive_term_end_date(
3975                 ip_index_lease_id               =>  p_index_lease_id
3976                ,ip_index_period_id              =>  p_index_period_id
3977                ,ip_main_lease_termination_date  =>  p_main_lease_termination_date
3978                ,op_term_end_date                =>  l_backbill_end_date_temp);
3979 
3980             l_backbill_st_date   := p_assessment_date ;
3981             l_backbill_end_date  := LEAST(v_start_date - 1,l_backbill_end_date_temp);
3982             l_backbill_freq      := curr_frequency_code;
3983             l_backbill_amt       := v_payment_amount - v_existing_payment_amount;
3984             l_recur_bb_calc_date := p_calculate_date;
3985             l_backbill_normalize := NVL(p_normalized,'N');*/
3986 
3987           /* Create a backbill term for the differnece */
3988 
3989          IF l_backbill_st_date <= NVL(l_backbill_end_date,TRUNC(SYSDATE)) THEN
3990 
3991             create_payment_term_record (
3992                p_lease_id               => p_lease_id
3993               ,p_location_id            => curr_location_id
3994               ,p_purpose_code           => curr_payment_purpose_code
3995               ,p_index_period_id        => p_index_period_id
3996               ,p_term_template_id       => NULL
3997               ,p_spread_frequency       => l_backbill_freq
3998               ,p_rounding_flag          => p_rounding_flag
3999               ,p_payment_amount         => l_backbill_amt
4000               ,p_normalized             => l_backbill_normalize
4001               ,p_include_in_var_rent    => curr_include_in_var_rent
4002               ,p_start_date             => l_backbill_st_date
4003               ,p_index_term_indicator   => p_backbill_term_indicator
4004               ,p_payment_term_id        => v_source_payment_term_id
4005               ,p_basis_relationship     => p_basis_relationship
4006               ,p_called_from            => 'INDEX'
4007               ,p_calculate_date         => p_calculate_date
4008               ,p_norm_st_date           => l_lst_norm_st_date
4009               ,p_end_date               => l_backbill_end_date
4010               ,p_recur_bb_calc_date     => l_recur_bb_calc_date
4011               ,op_payment_term_id       => v_created_payment_term_id
4012               ,op_msg                   => v_msg );
4013 
4014            END IF;
4015         END IF;
4016 
4017          /* Insert record into the intermediate table */
4018         IF v_created_payment_term_id IS NOT NULL THEN --#@#Bug4291907
4019          insert_inter_term (
4020               ip_index_period_id => p_index_period_id,
4021               ip_index_term_indicator      => p_backbill_term_indicator,
4022               ip_combination_amt           => v_payment_amount,
4023               ip_total_terms_amt           => v_total_amt,
4024               ip_rent_increase_term_id     => v_created_payment_term_id,
4025               ip_index_lease_id            => p_index_lease_id);
4026         END IF ;--#@#Bug4291907
4027 
4028 
4029       END IF;
4030 
4031    END IF;
4032 
4033    /* clean up: determine which index rent payment terms hasn't been touched */
4034 
4035    FOR c1 IN 0 .. l_check_term_tbl.COUNT - 1 LOOP
4036       l_used := FALSE;
4037       FOR c2 IN 0 .. l_chklist_tbl.COUNT - 1 LOOP
4038          IF l_chklist_tbl(c2) = l_check_term_tbl(c1).payment_term_id THEN
4039             l_used := TRUE;
4040             exit;
4041          END IF;
4042       END LOOP;
4043 
4044       IF NOT l_used THEN
4045          l_check_term_tbl(c1).attribute1 := 'NOTUSED';
4049    END LOOP;
4046       ELSE
4047          l_check_term_tbl(c1).attribute1 := 'USED';
4048       END IF;
4050 
4051    /* group them together in a new consolidated table, grouped using given criteria */
4052 
4053    l_impacted_term_tbl.delete;
4054 
4055    FOR c1 IN 0 .. l_check_term_tbl.COUNT - 1 LOOP
4056       IF l_check_term_tbl(c1).attribute1 = 'NOTUSED' THEN
4057          l_used := FALSE;
4058 
4059          FOR c2 IN 0 .. l_impacted_term_tbl.COUNT - 1 LOOP
4060            /* if found, add the amount and exit */
4061            IF
4062             l_impacted_term_tbl(c2).frequency_code         = l_check_term_tbl(c1).frequency_code AND
4063             l_impacted_term_tbl(c2).index_term_indicator   = l_check_term_tbl(c1).index_term_indicator AND
4064             l_impacted_term_tbl(c2).start_date             = l_check_term_tbl(c1).start_date AND
4065             l_impacted_term_tbl(c2).payment_purpose_code   = l_check_term_tbl(c1).payment_purpose_code AND
4066             l_impacted_term_tbl(c2).payment_term_type_code = l_check_term_tbl(c1).payment_term_type_code AND
4067             ((l_impacted_term_tbl(c2).location_id          = l_check_term_tbl(c1).location_id) OR
4068              (l_impacted_term_tbl(c2).location_id IS NULL AND l_check_term_tbl(c1).location_id IS NULL)) AND
4069             ((l_impacted_term_tbl(c2).vendor_id            = l_check_term_tbl(c1).vendor_id) OR
4070              (l_impacted_term_tbl(c2).vendor_id IS NULL AND l_check_term_tbl(c1).vendor_id IS NULL)) AND
4071             ((l_impacted_term_tbl(c2).vendor_site_id       = l_check_term_tbl(c1).vendor_site_id) OR
4072              (l_impacted_term_tbl(c2).vendor_site_id IS NULL AND l_check_term_tbl(c1).vendor_site_id IS NULL)) AND
4073             ((l_impacted_term_tbl(c2).customer_id          = l_check_term_tbl(c1).customer_id) OR
4074              (l_impacted_term_tbl(c2).customer_id IS NULL AND l_check_term_tbl(c1).customer_id IS NULL)) AND
4075             ((l_impacted_term_tbl(c2).customer_site_use_id = l_check_term_tbl(c1).customer_site_use_id) OR
4076              (l_impacted_term_tbl(c2).customer_site_use_id IS NULL AND l_check_term_tbl(c1).customer_site_use_id IS NULL)) AND
4077             ((l_impacted_term_tbl(c2).include_in_var_rent            = l_check_term_tbl(c1).include_in_var_rent) OR
4078              (l_impacted_term_tbl(c2).include_in_var_rent IS NULL AND l_check_term_tbl(c1).include_in_var_rent IS NULL)) AND
4079             ((l_impacted_term_tbl(c2).normalize            = l_check_term_tbl(c1).normalize) OR
4080              (l_impacted_term_tbl(c2).normalize IS NULL AND l_check_term_tbl(c1).normalize IS NULL)) AND
4081             build_distributions_string(l_impacted_term_tbl(c2).payment_term_id) =
4082             build_distributions_string(l_check_term_tbl(c1).payment_term_id)
4083           THEN
4084               l_impacted_term_tbl(c2).actual_amount := l_impacted_term_tbl(c2).actual_amount +
4085                                                        l_check_term_tbl(c1).actual_amount;
4086               l_used := TRUE;
4087               exit;
4088           END IF;
4089          END LOOP;
4090 
4091          IF NOT l_used THEN
4092             /* add to the table */
4093             l_count := l_impacted_term_tbl.COUNT;
4094 
4095             l_impacted_term_tbl(l_count).payment_term_id        := l_check_term_tbl(c1).payment_term_id;
4096             l_impacted_term_tbl(l_count).frequency_code         := l_check_term_tbl(c1).frequency_code;
4097             l_impacted_term_tbl(l_count).index_term_indicator   := l_check_term_tbl(c1).index_term_indicator;
4098             l_impacted_term_tbl(l_count).actual_amount          := l_check_term_tbl(c1).actual_amount;
4099             l_impacted_term_tbl(l_count).payment_purpose_code   := l_check_term_tbl(c1).payment_purpose_code;
4100             l_impacted_term_tbl(l_count).payment_term_type_code := l_check_term_tbl(c1).payment_term_type_code;
4101             l_impacted_term_tbl(l_count).location_id            := l_check_term_tbl(c1).location_id;
4102             l_impacted_term_tbl(l_count).vendor_id              := l_check_term_tbl(c1).vendor_id;
4103             l_impacted_term_tbl(l_count).vendor_site_id         := l_check_term_tbl(c1).vendor_site_id;
4104             l_impacted_term_tbl(l_count).customer_id            := l_check_term_tbl(c1).customer_id;
4105             l_impacted_term_tbl(l_count).customer_site_use_id   := l_check_term_tbl(c1).customer_site_use_id;
4106             l_impacted_term_tbl(l_count).normalize              := l_check_term_tbl(c1).normalize;
4107             l_impacted_term_tbl(l_count).include_in_var_rent    := l_check_term_tbl(c1).include_in_var_rent;
4108             l_impacted_term_tbl(l_count).start_date             := l_check_term_tbl(c1).start_date;
4109             l_impacted_term_tbl(l_count).end_date               := l_check_term_tbl(c1).end_date;
4110             l_impacted_term_tbl(l_count).schedule_day           := l_check_term_tbl(c1).schedule_day;
4111 
4112          END IF;
4113       END IF;
4114    END LOOP;
4115 
4116    /* consolidate amounts and create payment terms to negate the lefovers */
4117 
4118    FOR c1 IN 0 .. l_impacted_term_tbl.COUNT - 1 LOOP
4119 
4120       IF l_impacted_term_tbl(c1).actual_amount <> 0 THEN
4121 
4122          IF l_impacted_term_tbl(c1).frequency_code = 'MON' THEN
4123            l_impacted_term_tbl(c1).actual_amount := 12 * l_impacted_term_tbl(c1).actual_amount;
4124          ELSIF l_impacted_term_tbl(c1).frequency_code = 'QTR' THEN
4125            l_impacted_term_tbl(c1).actual_amount :=  4 * l_impacted_term_tbl(c1).actual_amount;
4126          ELSIF l_impacted_term_tbl(c1).frequency_code = 'SA' THEN
4127            l_impacted_term_tbl(c1).actual_amount :=  2 * l_impacted_term_tbl(c1).actual_amount;
4128          END IF;
4129 
4130          create_payment_term_record (
4131             p_lease_id               => p_lease_id
4135            ,p_term_template_id       => NULL
4132            ,p_location_id            => l_impacted_term_tbl(c1).location_id
4133            ,p_purpose_code           => l_impacted_term_tbl(c1).payment_purpose_code
4134            ,p_index_period_id        => p_index_period_id
4136            ,p_spread_frequency       => l_impacted_term_tbl(c1).frequency_code
4137            ,p_rounding_flag          => p_rounding_flag
4138            ,p_payment_amount         => l_impacted_term_tbl(c1).actual_amount * -1
4139            ,p_normalized             => l_impacted_term_tbl(c1).normalize
4140            ,p_include_in_var_rent    => l_impacted_term_tbl(c1).include_in_var_rent
4141            ,p_start_date             => l_impacted_term_tbl(c1).start_date
4142            ,p_index_term_indicator   => l_impacted_term_tbl(c1).index_term_indicator
4143            ,p_payment_term_id        => l_impacted_term_tbl(c1).payment_term_id
4144            ,p_basis_relationship     => p_basis_relationship
4145            ,p_called_from            => 'NEGRENT'
4146            ,p_calculate_date         => p_calculate_date
4147            ,p_norm_st_date           => l_lst_norm_st_date
4148            ,p_end_date               => NULL
4149            ,op_payment_term_id       => v_created_payment_term_id
4150            ,op_msg                   => v_msg );
4151 
4152        IF v_created_payment_term_id IS NOT NULL THEN --#@#Bug4291907
4153          insert_inter_term (
4154            ip_index_period_id           => p_index_period_id,
4155            ip_index_term_indicator      => l_impacted_term_tbl(c1).index_term_indicator,
4156            ip_combination_amt           => l_impacted_term_tbl(c1).actual_amount,
4157            ip_total_terms_amt           => l_impacted_term_tbl(c1).actual_amount,
4158            ip_rent_increase_term_id     => v_created_payment_term_id,
4159            ip_index_lease_id            => p_index_lease_id);
4160         END IF; --#@#Bug4291907
4161 
4162                  put_log(' approving payment term ID: '||v_created_payment_term_id);
4163 
4164                  approve_index_pay_term (
4165                      ip_lease_id            => p_lease_id
4166                     ,ip_index_pay_term_id   => v_created_payment_term_id
4167                     ,op_msg                 => v_msg);
4168 
4169       END IF;
4170    END LOOP;
4171 
4172 EXCEPTION
4173    WHEN OTHERS THEN
4174       PUT_LOG('Error in pn_index_amount_pkg.create_aggr_payment_terms :'||to_char(sqlcode)||' : '||sqlerrm);
4175       RAISE;
4176 
4177 END create_aggr_payment_terms;
4178 
4179 ------------------------------------------------------------------------
4180 -- PROCEDURE   : get_backbill_overlap_amt
4181 -- DESCRIPTION : Gets overlap amount from recurring term given 1) a start
4182 --               2) an end date 3) term template id and 4) index period id
4183 -- HISTORY:
4184 -- 14-APR-05 ftanudja o Created. #4307736.
4185 -- 12-JUL-2005   Mrinal Misra   o Added NOCOPY with OUT parameter.
4186 ------------------------------------------------------------------------
4187 
4188 PROCEDURE get_backbill_overlap_amt(
4189             p_term_template_id     pn_payment_terms.term_template_id%TYPE,
4190             p_index_period_id      pn_payment_terms.index_period_id%TYPE,
4191             p_index_term_indicator pn_payment_terms.index_term_indicator%TYPE,
4192             p_start_date           pn_payment_terms.start_date%TYPE,
4193             p_end_date             pn_payment_terms.end_date%TYPE,
4194             p_overlap_amt          OUT NOCOPY NUMBER)
4195 IS
4196   CURSOR get_overlap_sum IS
4197    SELECT sum(item.actual_amount) sum_overlap_amt
4198      FROM pn_payment_items_all item,
4199           pn_payment_terms_all term
4200     WHERE item.payment_term_id = term.payment_term_id
4201       AND term.term_template_id = p_term_template_id
4202       AND term.index_period_id  = p_index_period_id
4203       AND term.index_term_indicator = p_index_term_indicator
4204       AND item.due_date BETWEEN p_start_date AND p_end_date;
4205 
4206   l_answer NUMBER;
4207 
4208 BEGIN
4209 
4210    put_log('pn_index_amount_pkg.get_backbill_overlap_amt:  (+) ');
4211 
4212    l_answer := 0;
4213 
4214    FOR ans_rec IN get_overlap_sum LOOP
4215       l_answer := nvl(ans_rec.sum_overlap_amt,0);
4216    END LOOP;
4217 
4218    p_overlap_amt := l_answer;
4219 
4220    put_log('pn_index_amount_pkg.get_backbill_overlap_amt:  (-) : '||l_answer);
4221 
4222 END get_backbill_overlap_amt;
4223 
4224    ------------------------------------------------------------------------
4225    -- PROCEDURE : create_payment_terms
4226    -- DESCRIPTION: This procedure will create payment terms for a particular index
4227    --              period id.
4228    -- HISTORY:
4229    -- 06-MAY-02 psidhu   o Added parameter p_negative_rent_type. Fix for bug# 2356045.
4230    -- 31-OCT-02 ahhkumar o BUG#2593961  pass the parmeter p_include_index_items ='N'
4231    --                      in sum_payment_items where p_basis_type = c_basis_type_compound
4232    -- 08-OCT-04 stripath o Modified for BUG# 3961117, added new parameter p_calculate_date
4233    --                      for not to create backbills if Assessment Date <= CutOff Date.
4234    -- 01-DEC-04 ftanudja o Before calling create_payment_term_record, check if
4235    --                      start date < lease termination date. Reference #3964221.
4236    -- 14-APR-05 ftanudja o Add call to get_backbill_overlap_amt() and logic to
4237    --                      take into account recurring term amount overlapping
4238    --                      with backbill. #4307736
4239    -- 01-NOV-06 prabhakar o Added two cursors ref_period_cur and assessment_date_cur
4243    --                         procedure derive_term_end_date.
4240    --                         for term length option.
4241    -- 01-DEC-06 Prabhakar o Removed the two cusrors ref_period_cur and assessment_date_cur
4242    --                         and the term length end_date handling is moved to
4244    -- 11-DEC-06 Prabhakar o Moved the call to derive_term_end_date before the normailzed
4245    --                         if condition for the bug fix #5704914
4246    -- 12-DEC-06 Prabhakr  o Added p_prorate_factor parameter.
4247    -- 02-JAN-07 Hareesha  o M28#16 Changes fro recurring backbill.
4248    -- 30-MAR-07 Hareesha o Bug # 5958131 Added handling for new option of backbill+recur.
4249    -- 26-APR-07 Hareesha o Bug # 6016064 Added a check if st-dt <= end-dt,
4250    --                      create terms else do not.
4251    ------------------------------------------------------------------------
4252       PROCEDURE create_payment_terms (
4253          p_lease_id               IN       NUMBER
4254         ,p_index_lease_id         IN       NUMBER
4255         ,p_location_id            IN       NUMBER
4256         ,p_purpose_code           IN       VARCHAR2
4257         ,p_index_period_id        IN       NUMBER
4258         ,p_term_template_id       IN       NUMBER
4259         ,p_relationship           IN       VARCHAR2
4260         ,p_assessment_date        IN       DATE
4261         ,p_basis_amount           IN       NUMBER
4262         ,p_basis_percent_change   IN       NUMBER
4263         ,p_spread_frequency       IN       VARCHAR2
4264         ,p_rounding_flag          IN       VARCHAR2
4265         ,p_index_amount           IN       NUMBER
4266         ,p_index_finder_type      IN       VARCHAR2
4267         ,p_basis_type             IN       VARCHAR2
4268         ,p_basis_start_date       IN       DATE
4269         ,p_basis_end_date         IN       DATE
4270         ,p_increase_on            IN       VARCHAR2
4271         ,p_negative_rent_type     IN       VARCHAR2
4272         ,p_carry_forward_flag     IN       VARCHAR2
4273         ,p_calculate_date         IN       DATE
4274         ,p_prorate_factor         IN       NUMBER
4275         ,op_msg                   OUT NOCOPY      VARCHAR2
4276       ) IS
4277          v_msg                            VARCHAR2 (1000);
4278          v_normalize                      pn_term_templates.normalize%TYPE;
4279          v_index_amount                   pn_index_lease_periods.constraint_rent_due%TYPE;
4280          v_uncontrained_index_amount      NUMBER;
4281          v_constrained_rent_amount        NUMBER := 0;
4282          v_normalized_amount_annual       NUMBER;
4283          v_adjusted_amount                NUMBER;
4284          v_num_pymt_since_assmt_dt        NUMBER;
4285          v_payments_per_year              NUMBER;
4286          v_backbill_amt                   NUMBER;
4287          v_backbill_overlap_amt           NUMBER;
4288          v_backbill_chk_str_dt            DATE;
4289          v_backbill_chk_end_dt            DATE;
4290          v_recurring_payment_start_date   DATE;
4291          v_normalize_basis_amount         NUMBER;
4292          v_basis_amount                   NUMBER;
4293          v_annual_basis_amount            NUMBER;
4294          v_existing_amounts               pn_payment_terms.actual_amount%TYPE;
4295          v_prev_index_amt                 NUMBER;
4296          v_adjusted_amount_aggr           NUMBER;
4297          v_atleast_indicator              VARCHAR2(1):= 'N';
4298          v_prv_normalized_amount          NUMBER := 0;
4299          v_main_lease_termination_date    DATE;
4300          v_approved_amt_annual_atlst_bb   NUMBER := 0;
4301          v_approved_amt_annual_bb         NUMBER := 0;
4302          v_num_years                      NUMBER;
4303          v_constrained_backbill_amt       NUMBER := 0;
4304          v_ot_amount                      NUMBER := 0;
4305          v_created_payment_term_id        NUMBER;
4306          v_constraint_applied_amount      pn_index_lease_periods.constraint_applied_amount%type;
4307          v_carry_forward_amount           pn_index_lease_periods.carry_forward_amount%type;
4308          v_constraint_applied_percent     pn_index_lease_periods.constraint_applied_percent%type;
4309          v_carry_forward_percent          pn_index_lease_periods.carry_forward_percent%type;
4310          v_end_date                       DATE;
4311          v_reference_period_type          VARCHAR2(30);
4312 
4313          CURSOR ref_period_cur ( p_index_lease_id NUMBER) IS
4314          SELECT reference_period
4315          FROM pn_index_leases_all
4316          WHERE index_lease_id = p_index_lease_id;
4317 
4318          l_backbill_st_date        DATE;
4319          l_backbill_end_date       DATE;
4320          l_backbill_end_date_temp  DATE;
4321          l_backbill_freq           VARCHAR2(30);
4322          l_backbill_amt            NUMBER;
4323          l_recur_bb_calc_date      DATE;
4324          l_backbill_normalize      VARCHAR2(1);
4325          l_found_atlst_bb          NUMBER := 0;
4326 
4327 BEGIN
4328    put_log('pn_index_amount_pkg.create_payment_terms   :  (+) ');
4329 
4330    v_index_amount := p_index_amount;
4331 
4332 
4333   /* sets date for payment terms that will have todays date.*/
4334 
4335    SELECT pld.lease_termination_date
4336    INTO v_main_lease_termination_date
4337    FROM pn_lease_details_all pld
4338    WHERE pld.lease_id = p_lease_id;
4339 
4340    IF g_create_terms_ext_period = 'Y' THEN
4341       SELECT NVL(pld.lease_extension_end_date,pld.lease_termination_date)
4342       INTO v_main_lease_termination_date
4343       FROM pn_lease_details_all pld
4347    /* derive payment defaults for this index lease */
4344       WHERE pld.lease_id = p_lease_id;
4345    END IF;
4346 
4348 
4349    BEGIN
4350 
4351       put_log ('Checking if normalizing...');
4352 
4353       IF p_term_template_id IS NOT NULL THEN
4354          SELECT normalize
4355          INTO v_normalize
4356          FROM pn_term_templates_all
4357          WHERE term_template_id = p_term_template_id;
4358       ELSE
4359         /* if p_term_template_id is null, then payment term aggregation will be done */
4360          v_normalize := 'Y';
4361       END IF;
4362 
4363    EXCEPTION
4364    WHEN OTHERS THEN
4365        put_log (   'Cannot Get Payment Term Defaults - Unknown Error:'
4366                 || SQLERRM);
4367    END;
4368 
4369    /* to get the reference period_type */
4370     FOR ref_period_rec IN ref_period_cur(p_index_lease_id) LOOP
4371             v_reference_period_type := ref_period_rec.reference_period;
4372     END LOOP;
4373 
4374    /* check if index rent period already has a normalized amount.*/
4375 
4376    chk_normalized_amount (
4377            p_index_period_id             => p_index_period_id
4378           ,op_normalize_amount_annual    => v_normalized_amount_annual
4379           ,op_msg                        => v_msg
4380         );
4381 
4382 
4383   /* create a normalized payment term, if no normalized record is found
4384      and 'Normalize' flag is set to 'Y'and relation is 'Greater Of' or 'Basis Only'
4385 
4386 
4387      jreyes 22-AUG-01 - added clause "p_assessment_date > sysdate" to IF statement
4388 
4389      IF v_normalized_amount_annual = 0
4390      AND NVL (v_normalize, 'N') = 'Y'
4391      AND p_relationship IN (c_relation_greater_of, c_relation_basis_only) THEN
4392 
4393 
4394      Calculate index amount to normalize.Do this by calculating the index amount as
4395      if using basis only If no basis amount is provided, calculate index amount as
4396      the annualized basis of the current period +  sum of previous index increases */
4397 
4398     /* to get the term end date */
4399     derive_term_end_date(ip_index_lease_id               =>  p_index_lease_id
4400                         ,ip_index_period_id              =>  p_index_period_id
4401                         ,ip_main_lease_termination_date  =>  v_main_lease_termination_date
4402                         ,op_term_end_date                =>  v_end_date);
4403 
4404 
4405    IF NVL (v_normalize, 'N') = 'Y' AND
4406       p_relationship IN (c_relation_greater_of, c_relation_basis_only) THEN
4407 
4408       IF p_basis_amount IS NULL THEN
4409 
4410          BEGIN
4411 
4412             IF p_basis_type = c_basis_type_compound THEN
4413 
4414                sum_payment_items (
4415                         p_index_lease_id              => p_index_lease_id
4416                        ,p_basis_start_date            => p_basis_start_date
4417                        ,p_basis_end_date              => p_basis_end_date
4418                        ,p_type_code                   => p_increase_on
4419                        ,p_include_index_items         => 'N'               --Added for BUG#2593961
4420                        ,op_sum_amount                 => v_annual_basis_amount
4421                                        );
4422 
4423                derive_sum_prev_actual_amounts (
4424                         p_lease_id                    => p_lease_id
4425                        ,p_index_lease_id              => p_index_lease_id
4426                        ,p_index_period_id             => p_index_period_id
4427                        ,p_prev_index_amount           => v_prev_index_amt
4428                                       );
4429 
4430                v_normalize_basis_amount := v_annual_basis_amount +
4431                                            NVL (v_prev_index_amt, 0);
4432             ELSE
4433                SELECT current_basis
4434                INTO v_normalize_basis_amount
4435                FROM pn_index_lease_periods_all pilp
4436                WHERE pilp.index_lease_id = p_index_lease_id
4437                AND line_number = 1;
4438             END IF;
4439 
4440          EXCEPTION
4441          WHEN OTHERS THEN
4442               v_normalize_basis_amount := 0;
4443          END;
4444 
4445       ELSE
4446          v_normalize_basis_amount := p_basis_amount;
4447       END IF;  -- p_basis_amount IS NULL
4448 
4449 
4450       /* calculate the amount of the the at least amount.. */
4451 
4452       calculate_index_amount (
4453            p_relationship                => c_relation_basis_only
4454           ,p_adj_index_percent_change    => NULL
4455           ,p_basis_percent_change        => p_basis_percent_change
4456           ,p_current_basis               => v_normalize_basis_amount
4457           ,op_index_amount               => v_uncontrained_index_amount
4458           ,op_msg                        => v_msg
4459                                   );
4460 
4461       /* Applying constraints to the at least amount */
4462 
4463       IF v_uncontrained_index_amount IS NOT NULL THEN
4464 
4465          derive_constrained_rent (
4466                     p_index_lease_id              => p_index_lease_id
4467                    ,p_current_basis               => p_basis_amount
4468                    ,p_index_period_id             => p_index_period_id
4469                    ,p_assessment_date             => p_assessment_date
4470                    ,p_negative_rent_type          => p_negative_rent_type
4474                    ,op_constrained_rent_amount    => v_constrained_rent_amount
4471                    ,p_unconstrained_rent_amount   => v_uncontrained_index_amount
4472                    ,p_carry_forward_flag          => nvl(p_carry_forward_flag,'N')
4473                    ,p_prorate_factor              => p_prorate_factor
4475                    ,op_constraint_applied_amount  => v_constraint_applied_amount
4476                    ,op_constraint_applied_percent => v_constraint_applied_percent
4477                    ,op_carry_forward_amount       => v_carry_forward_amount
4478                    ,op_carry_forward_percent      => v_carry_forward_percent
4479                    ,op_msg                        => v_msg
4480                                         );
4481 
4482       END IF; --v_uncontrained_index_amount IS NOT NULL
4483 
4484 
4485       /* Changed the logic so that the ATLEAST amount is always checked for the correct
4486          amount and not only when the atleast amount = 0 */
4487 
4488       IF (v_constrained_rent_amount - v_normalized_amount_annual) >= 0  and
4489          p_term_template_id IS NOT NULL THEN
4490 
4491          /* non aggregation ... */
4492 
4493          /* determine the start date */
4494 
4495          derive_payment_start_date (
4496                p_spread_frequency            => p_spread_frequency
4497               ,p_assessment_date             => p_assessment_date
4498               ,p_end_date                    => v_end_date
4499               ,p_calculate_date              => p_calculate_date
4500               ,p_index_lease_id               =>  p_index_lease_id
4501               ,op_recur_pay_start_date       => v_recurring_payment_start_date
4502               ,op_num_pymt_since_assmt_dt    => v_num_pymt_since_assmt_dt
4503               );
4504          /* Fix for bug# 1988909 */
4505 
4506          IF   p_spread_frequency = c_spread_frequency_one_time THEN
4507 
4508             v_num_years := CEIL (MONTHS_BETWEEN (v_main_lease_termination_date,
4509                                                  v_recurring_payment_start_date)) / 12;
4510             v_constrained_backbill_amt := v_constrained_rent_amount;
4511             v_constrained_rent_amount := v_constrained_rent_amount * v_num_years;
4512 
4513          END IF;
4514 
4515 
4516          /* create a record on pn_payment_terms table if main lease termination
4517             date > sysdate.
4518             Fix for bug# 2007492 */
4519 
4520        IF TRUNC(v_main_lease_termination_date) > p_calculate_date AND
4521             v_recurring_payment_start_date <= v_main_lease_termination_date AND
4522             v_recurring_payment_start_date <= v_end_date  THEN
4523 
4524             create_payment_term_record (
4525                        p_lease_id                    => p_lease_id
4526                       ,p_location_id                 => p_location_id
4527                       ,p_purpose_code                => p_purpose_code
4528                       ,p_index_period_id             => p_index_period_id
4529                       ,p_term_template_id            => p_term_template_id
4530                       ,p_spread_frequency            => p_spread_frequency
4531                       ,p_rounding_flag               => p_rounding_flag
4532                       ,p_start_date                  => v_recurring_payment_start_date
4533                       ,p_payment_amount              => v_constrained_rent_amount
4534                       ,p_normalized                  => 'Y'
4535                       ,p_index_term_indicator        => c_index_pay_term_type_atlst
4536                       ,p_payment_term_id             => NULL
4537                       ,p_basis_relationship          => p_relationship
4538                       ,p_called_from                 => 'INDEX'
4539                       ,p_end_date                    => v_end_date
4540                       ,op_payment_term_id            => v_created_payment_term_id
4541                       ,p_calculate_date              => p_calculate_date
4542                       ,op_msg                        => v_msg
4543                                              );
4544          END IF;
4545 
4546 
4547          /* Determine if we need to calculate a normalized backbill amount */
4548 
4549          IF p_index_finder_type in ( c_index_finder_backbill, c_index_finder_most_recent) AND
4550             NVL(v_num_pymt_since_assmt_dt, 0) <> 0 THEN
4551             /* Derive Backbill Amount:
4552                Count number of payments between sysdate and assessment date
4553                (SQL: (months_between (assessment_date, sysdate) + 1 )invoiced per year,
4554                Calculate the backbill amount (monthly amount X no. of months between
4555                sysdate and assessment date) */
4556 
4557             SELECT DECODE (
4558                 p_spread_frequency
4559                ,c_spread_frequency_monthly, 12
4560                ,c_spread_frequency_quarterly, 4
4561                ,c_spread_frequency_semiannual, 2
4562                ,c_spread_frequency_annually, 1
4563                ,1
4564               )
4565             INTO v_payments_per_year
4566             FROM DUAL;
4567 
4568             chk_approved_amount (
4569                  p_index_period_id             => p_index_period_id
4570                 ,p_index_term_indicator        => c_index_pay_term_type_atlst_bb
4571                 ,op_approved_amount_annual     => v_approved_amt_annual_atlst_bb
4572                 ,op_msg                        => v_msg );
4573 
4574             /* Fix for bug# 1988909 */
4575 
4576             IF p_spread_frequency = c_spread_frequency_one_time AND
4580                                                     p_assessment_date)) / 12;
4577                NVL(v_constrained_rent_amount,0) <>0  THEN
4578 
4579                v_num_years := CEIL (MONTHS_BETWEEN (v_recurring_payment_start_date,
4581                v_backbill_amt := ROUND(v_constrained_backbill_amt * v_num_years,
4582                                                         get_amount_precision);
4583             ELSE
4584                v_backbill_amt := ROUND (
4585                                         (v_constrained_rent_amount / v_payments_per_year)
4586                                          * v_num_pymt_since_assmt_dt
4587                                        ,get_amount_precision
4588                                        );
4589             END IF;
4590 
4591             put_log('create_payment_Terms :v_approved_amt_annual_atlst_bb *******'||v_approved_amt_annual_atlst_bb);
4592 
4593             v_backbill_overlap_amt := 0;
4594             v_backbill_chk_str_dt  := p_assessment_date;
4595             v_backbill_chk_end_dt  := last_day(add_months(v_recurring_payment_start_date, -1));
4596 
4597             get_backbill_overlap_amt(
4598                p_term_template_id     => p_term_template_id,
4599                p_index_period_id      => p_index_period_id,
4600                p_index_term_indicator => c_index_pay_term_type_atlst,
4601                p_start_date           => v_backbill_chk_str_dt,
4602                p_end_date             => v_backbill_chk_end_dt,
4603                p_overlap_amt          => v_backbill_overlap_amt);
4604 
4605             v_backbill_amt := v_backbill_amt - v_approved_amt_annual_atlst_bb - v_backbill_overlap_amt;
4606 
4607             IF v_backbill_amt <> 0 THEN
4608 
4609                IF NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'OT' THEN
4610                    l_backbill_st_date   := TRUNC(SYSDATE) ;
4611                    l_backbill_end_date  := NULL;
4612                    l_backbill_freq      := c_spread_frequency_one_time;
4613                    l_backbill_amt       := v_backbill_amt;
4614                 ELSIF NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'RECUR' THEN
4615 
4616                    derive_term_end_date(
4617                          ip_index_lease_id               =>  p_index_lease_id
4618                         ,ip_index_period_id              =>  p_index_period_id
4619                         ,ip_main_lease_termination_date  =>  v_main_lease_termination_date
4620                         ,op_term_end_date                =>  l_backbill_end_date_temp);
4621 
4622                    l_backbill_st_date   := p_assessment_date ;
4623                    l_backbill_end_date  := LEAST(v_recurring_payment_start_date - 1,l_backbill_end_date_temp);
4624                    l_backbill_freq      := p_spread_frequency;
4625                    l_backbill_amt       := v_constrained_rent_amount;
4626                    l_recur_bb_calc_date := p_calculate_date;
4627 
4628                 END IF;
4629 
4630                 IF l_backbill_st_date <= NVL(l_backbill_end_date,TRUNC(SYSDATE)) THEN
4631 
4632                    create_payment_term_record (
4633                       p_lease_id                    => p_lease_id
4634                      ,p_location_id                 => p_location_id
4635                      ,p_purpose_code                => p_purpose_code
4636                      ,p_index_period_id             => p_index_period_id
4637                      ,p_term_template_id            => p_term_template_id
4638                      ,p_spread_frequency            => l_backbill_freq
4639                      ,p_rounding_flag               => p_rounding_flag
4640                      ,p_payment_amount              => l_backbill_amt
4641                      ,p_start_date                  => l_backbill_st_date
4642                      ,p_normalized                  => 'Y' --6/8/2001change from 'BACKBILL' to 'ATLEAST'
4643                      ,p_index_term_indicator        => c_index_pay_term_type_atlst_bb
4644                      ,p_payment_term_id             => NULL
4645                      ,p_basis_relationship          => p_relationship
4646                      ,p_called_from                 => 'INDEX'
4647                      ,p_calculate_date              => p_calculate_date
4648                      ,p_end_date                    => l_backbill_end_date
4649                      ,p_recur_bb_calc_date          => l_recur_bb_calc_date
4650                      ,op_payment_term_id            => v_created_payment_term_id
4651                      ,op_msg                        => v_msg);
4652 
4653                 END IF;
4654 
4655              END IF;
4656           END IF;
4657 
4658         ELSE
4659                   /* aggregation */
4660 
4661                    create_aggr_payment_terms (
4662                         p_index_lease_id            => p_index_lease_id
4663                        ,p_basis_start_date          => p_basis_start_date
4664                        ,p_basis_end_date            => p_basis_end_date
4665                        ,p_index_term_indicator      => c_index_pay_term_type_atlst
4666                        ,p_lease_id                  => p_lease_id
4667                        ,p_assessment_date           => p_assessment_date
4668                        ,p_normalized_amount_annual  => v_normalized_amount_annual
4669                        ,p_basis_relationship        => p_relationship
4670                        ,p_basis_type                => p_basis_type
4671                        ,p_total_rent_amount         => v_constrained_rent_amount
4672                        ,p_increase_on               => p_increase_on
4673                        ,p_rounding_flag             => p_rounding_flag
4674                        ,p_main_lease_termination_date => v_main_lease_termination_date
4678                        ,op_msg                      => v_msg
4675                        ,p_index_finder_type         => p_index_finder_type
4676                        ,p_index_period_id           => p_index_period_id
4677                        ,p_calculate_date            => p_calculate_date
4679                        );
4680 
4681         END IF; -- p_index_finder_type in(c_index_finder_backbill ...
4682 
4683    END IF; --  NVL(v_normalize,'N') = 'Y'
4684 
4685 
4686 
4687    /* create recurring payments */
4688 
4689 
4690    IF v_index_amount IS NOT NULL THEN
4691 
4692       /* Check if we have normalized amount.  If so, get the amount normalized,
4693          this amount must be subtracted from the calculated index amount */
4694 
4695 
4696       chk_normalized_amount (
4697               p_index_period_id             => p_index_period_id
4698              ,op_normalize_amount_annual    => v_normalized_amount_annual
4699              ,op_msg                        => v_msg
4700                                 );
4701 
4702       IF v_normalized_amount_annual = 0 THEN
4703          SELECT count(*)
4704          INTO l_found_atlst_bb
4705          FROM pn_payment_terms_all
4706          WHERE index_period_id = p_index_period_id
4707          AND index_term_indicator = c_index_pay_term_type_atlst_bb;
4708       END IF;
4709 
4710       IF TRUNC(v_main_lease_termination_date) <= p_calculate_date OR
4711          l_found_atlst_bb <> 0  THEN
4712 
4713          IF NVL(p_rounding_flag,'N') = 'Y' THEN
4714             v_ot_amount :=   ROUND( v_constrained_rent_amount ,0);
4715          ELSE
4716             v_ot_amount :=   ROUND( v_constrained_rent_amount , get_amount_precision);
4717          END IF;
4718 
4719          v_normalized_amount_annual := v_normalized_amount_annual + v_ot_amount;
4720 
4721       END IF;
4722 
4723 
4724       /* checking to see if there any recurring payments that have been approved..
4725          if so, subtract that amount from the current index amount. */
4726 
4727       chk_approved_amount (
4728           p_index_period_id             => p_index_period_id
4729          ,p_index_term_indicator        => c_index_pay_term_type_recur
4730          ,op_approved_amount_annual     => v_existing_amounts
4731          ,op_msg                        => v_msg );
4732 
4733 
4734       IF p_term_template_id IS NOT NULL    THEN   -- non aggregation
4735 
4736          SELECT DECODE (
4737                   p_spread_frequency
4738                  ,c_spread_frequency_monthly, 12
4739                  ,c_spread_frequency_quarterly, 4
4740                  ,c_spread_frequency_semiannual, 2
4741                  ,c_spread_frequency_annually, 1
4742                  ,1
4743                )
4744          INTO v_payments_per_year
4745          FROM DUAL;
4746 
4747 
4748          /* deriving the start date of the recurring payment */
4749 
4750          derive_payment_start_date (
4751                p_spread_frequency            => p_spread_frequency
4752               ,p_assessment_date             => p_assessment_date
4753               ,p_end_date                    => v_end_date
4754               ,p_calculate_date              => p_calculate_date
4755               ,p_index_lease_id               =>  p_index_lease_id
4756               ,op_recur_pay_start_date       => v_recurring_payment_start_date
4757               ,op_num_pymt_since_assmt_dt    => v_num_pymt_since_assmt_dt
4758               );
4759 
4760          /* Fix for bug# 1988909  */
4761 
4762          IF p_spread_frequency = c_spread_frequency_one_time THEN
4763 
4764             v_num_years := CEIL (MONTHS_BETWEEN (v_main_lease_termination_date,
4765                                                  v_recurring_payment_start_date)) / 12;
4766             v_index_amount := v_index_amount * v_num_years;
4767          END IF;
4768 
4769          /* Fix for bug# 2007844 */
4770 
4771          IF TRUNC(v_main_lease_termination_date) > p_calculate_date THEN
4772             IF NVL(p_rounding_flag,'N') = 'Y' THEN
4773                v_index_amount := ROUND(
4774                                    v_index_amount / v_payments_per_year
4775                                   ,0 ) * v_payments_per_year;
4776             ELSE
4777                v_index_amount := ROUND (
4778                                    v_index_amount / v_payments_per_year
4779                                   ,get_amount_precision
4780                                     )  * v_payments_per_year;
4781             END IF;
4782          END IF;
4783 
4784          /* Subtract the normalized amount from the current index amount
4785             This new amount is what we will use for the recurring payment amount */
4786 
4787          put_log('create_payment_terms : v_index_amount '||v_index_amount);
4788          put_log('create_payment_terms : v_normalized_amount_annual '||v_normalized_amount_annual);
4789          put_log('create_payment_terms : v_existing_amounts '||v_existing_amounts);
4790 
4791          v_adjusted_amount :=   v_index_amount
4792                               - v_normalized_amount_annual
4793                               - v_existing_amounts ;
4794 
4795          put_log('create_payment_terms : v_adjusted_amount '||v_adjusted_amount);
4796 
4797          IF v_adjusted_amount IS NOT NULL THEN
4798 
4799             /* creating the payment term record
4800                added on 22-AUG-01
4801                create a record on pn_payment_terms table if main lease termination
4805             IF TRUNC(v_main_lease_termination_date) > p_calculate_date AND
4802                date > sysdate.
4803                Fix for bug# 2007492 */
4804 
4806                v_recurring_payment_start_date <= v_main_lease_termination_date AND
4807                v_recurring_payment_start_date <= v_end_date  THEN
4808 
4809                create_payment_term_record (
4810                                         p_lease_id                    => p_lease_id
4811                                        ,p_location_id                 => p_location_id
4812                                        ,p_purpose_code                => p_purpose_code
4813                                        ,p_index_period_id             => p_index_period_id
4814                                        ,p_term_template_id            => p_term_template_id
4815                                        ,p_spread_frequency            => p_spread_frequency
4816                                        ,p_rounding_flag               => p_rounding_flag
4817                                        ,p_payment_amount              => v_adjusted_amount
4818                                        ,p_start_date                  => v_recurring_payment_start_date
4819                                        ,p_normalized                  => v_normalize
4820                                        ,p_index_term_indicator        => c_index_pay_term_type_recur
4821                                        ,p_payment_term_id             => NULL
4822                                        ,p_basis_relationship          => p_relationship
4823                                        ,p_called_from                 => 'INDEX'
4824                                        ,p_calculate_date              => p_calculate_date
4825                                        ,p_end_date                    => v_end_date
4826                                        ,op_payment_term_id            => v_created_payment_term_id
4827                                        ,op_msg                        => v_msg
4828                                                                );
4829             END IF;
4830 
4831             /* check to see if we need to calculate a backbill amount. */
4832 
4833 
4834             IF p_index_finder_type in ( c_index_finder_backbill, c_index_finder_most_recent)
4835                AND NVL (v_num_pymt_since_assmt_dt, 0) <> 0 THEN
4836 
4837                /* Derive Backbill Amount:
4838                   Count number of payments between sysdate and assessment date
4839                   (SQL: (months_between (assessment_date, sysdate) + 1 )invoiced per year,
4840                    Calculate the backbill amount (monthly amount X no. of months
4841                    between sysdate and assessment date) */
4842 
4843 
4844                SELECT DECODE (
4845                               p_spread_frequency
4846                              ,c_spread_frequency_monthly, 12
4847                              ,c_spread_frequency_quarterly, 4
4848                              ,c_spread_frequency_semiannual, 2
4849                              ,c_spread_frequency_annually, 1
4850                              ,1
4851                               )
4852                INTO v_payments_per_year
4853                FROM DUAL;
4854 
4855                chk_approved_amount (
4856                               p_index_period_id             => p_index_period_id
4857                              ,p_index_term_indicator        => c_index_pay_term_type_backbill
4858                              ,op_approved_amount_annual     => v_approved_amt_annual_bb
4859                              ,op_msg                        => v_msg );
4860 
4861                put_log('create_payment_terms :v_approved_amt_annual_bb  **** '||v_approved_amt_annual_bb);
4862 
4863                /* Fix for bug# 1988909             */
4864 
4865                IF p_spread_frequency = c_spread_frequency_one_time AND
4866                   NVL(v_adjusted_amount,0) <> 0  THEN
4867 
4868                   v_num_years := CEIL (MONTHS_BETWEEN (v_recurring_payment_start_date,
4869                                                        p_assessment_date)) / 12;
4870                   v_backbill_amt := ROUND(p_index_amount * v_num_years,
4871                                           get_amount_precision);
4872                ELSE
4873                   v_backbill_amt := ((v_index_amount - v_normalized_amount_annual)/
4874                                       v_payments_per_year) * v_num_pymt_since_assmt_dt;
4875                                     --(v_adjusted_amount / v_payments_per_year)
4876                END IF;
4877 
4878                put_log('create_payment_terms : v_backbill_amt '||v_backbill_amt);
4879 
4880                v_backbill_overlap_amt := 0;
4881                v_backbill_chk_str_dt  := p_assessment_date;
4882                v_backbill_chk_end_dt  := last_day(add_months(v_recurring_payment_start_date, -1));
4883 
4884                get_backbill_overlap_amt(
4885                   p_term_template_id     => p_term_template_id,
4886                   p_index_period_id      => p_index_period_id,
4887                   p_index_term_indicator => c_index_pay_term_type_recur,
4888                   p_start_date           => v_backbill_chk_str_dt,
4889                   p_end_date             => v_backbill_chk_end_dt,
4890                   p_overlap_amt          => v_backbill_overlap_amt);
4891 
4892                v_backbill_amt := v_backbill_amt - v_approved_amt_annual_bb - v_backbill_overlap_amt;
4893 
4894                IF v_backbill_amt <> 0 THEN
4895                   IF NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'OT' THEN
4896                      l_backbill_st_date   := TRUNC(SYSDATE) ;
4897                      l_backbill_end_date  := NULL;
4901                   ELSIF NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'RECUR' THEN
4898                      l_backbill_freq      := c_spread_frequency_one_time;
4899                      l_backbill_amt       := v_backbill_amt;
4900                      l_backbill_normalize := 'N';
4902 
4903                      derive_term_end_date(
4904                          ip_index_lease_id               =>  p_index_lease_id
4905                         ,ip_index_period_id              =>  p_index_period_id
4906                         ,ip_main_lease_termination_date  =>  v_main_lease_termination_date
4907                         ,op_term_end_date                =>  l_backbill_end_date_temp);
4908 
4909                      l_backbill_st_date   := p_assessment_date ;
4910                      l_backbill_end_date  := LEAST(v_recurring_payment_start_date - 1,l_backbill_end_date_temp);
4911                      l_backbill_freq      := p_spread_frequency;
4912                      l_backbill_amt       := v_adjusted_amount;
4913                      l_recur_bb_calc_date := p_calculate_date;
4914                      l_backbill_normalize := NVL(v_normalize,'N');
4915 
4916                   END IF;
4917 
4918                   IF l_backbill_st_date <= NVL(l_backbill_end_date,TRUNC(SYSDATE)) THEN
4919 
4920                      create_payment_term_record (
4921                           p_lease_id                    => p_lease_id
4922                          ,p_location_id                 => p_location_id
4923                          ,p_purpose_code                => p_purpose_code
4924                          ,p_index_period_id             => p_index_period_id
4925                          ,p_term_template_id            => p_term_template_id
4926                          ,p_spread_frequency            => l_backbill_freq
4927                          ,p_rounding_flag               => p_rounding_flag
4928                          ,p_payment_amount              => l_backbill_amt
4929                          ,p_start_date                  => l_backbill_st_date
4930                          ,p_normalized                  => l_backbill_normalize
4931                          ,p_index_term_indicator        => c_index_pay_term_type_backbill
4932                          ,p_payment_term_id             => NULL
4933                          ,p_basis_relationship          => p_relationship
4934                          ,p_called_from                 => 'INDEX'
4935                          ,p_calculate_date              => p_calculate_date
4936                          ,p_end_date                    => l_backbill_end_date
4937                          ,p_recur_bb_calc_date          => l_recur_bb_calc_date
4938                          ,op_payment_term_id            => v_created_payment_term_id
4939                          ,op_msg                        => v_msg);
4940 
4941                   END IF;
4942               END IF;
4943 
4944             END IF; --p_index_finder_type = c_index_finder_backbill
4945 
4946          END IF; -- v_adjusted_amount IS NOT NULL
4947 
4948 
4949       ELSE
4950 
4951          /* aggregation .. */
4952 
4953          put_log('in aggregation *');
4954 
4955          IF (p_relationship IN (c_relation_greater_of, c_relation_basis_only)) then
4956 
4957             IF (p_index_amount > NVL(v_constrained_rent_amount,0))AND
4958                NVL(p_index_amount,0) <> 0  THEN
4959 
4960                v_adjusted_amount_aggr :=  p_index_amount - NVL(v_constrained_rent_amount,0);
4961             ELSE
4962                v_adjusted_amount_aggr := 0;
4963             END IF;
4964 
4965             put_log ('p_index-amount ' || to_char(p_index_amount));
4966             put_log ('v_constrained_rent_amount ' || to_char(v_constrained_rent_amount));
4967 
4968          ELSE
4969             v_adjusted_amount_aggr :=  p_index_amount;
4970          END IF;
4971 
4972          IF v_adjusted_amount_aggr <> 0   THEN
4973 
4974             create_aggr_payment_terms (
4975                              p_index_lease_id            => p_index_lease_id
4976                             ,p_basis_start_date          => p_basis_start_date
4977                             ,p_basis_end_date            => p_basis_end_date
4978                             ,p_index_term_indicator      => c_index_pay_term_type_recur
4979                             ,p_lease_id                  => p_lease_id
4980                             ,p_assessment_date           => p_assessment_date
4981                             ,p_normalized_amount_annual  => null
4982                             ,p_basis_relationship        => p_relationship
4983                             ,p_basis_type                => p_basis_type
4984                             ,p_total_rent_amount         => v_adjusted_amount_aggr
4985                             ,p_increase_on               => p_increase_on
4986                             ,p_rounding_flag             => p_rounding_flag
4987                             ,p_main_lease_termination_date => v_main_lease_termination_date
4988                             ,p_index_finder_type         => p_index_finder_type
4989                             ,p_index_period_id           => p_index_period_id
4990                             ,p_calculate_date            => p_calculate_date
4991                             ,op_msg                      => v_msg
4992                             );
4993          END IF;
4994 
4995       END IF;  -- p_termplate_id is not null
4996 
4997    END IF; --v_index_amount IS NOT NULL
4998 
4999  END create_payment_terms;
5000 
5001 
5005 -- 21-FEB-02  psidhu  o Added x_calling_form parameter in the call to procedure
5002 -------------------------------------------------------------------------------
5003 -- PROCEDURE  : create_payment_term_record
5004 --
5006 --                      pnt_payment_terms_pkg.insert_row.
5007 -- 16-APR-02  kkhegde o Bug#2205537
5008 --                      Added select statement to get location_id so that when
5009 --                      user defines a rent increase
5010 --                      ( using a default term template )
5011 --                      and specifies a location
5012 --                      ( in the agreements header ), this
5013 --                      same location shld be defaulted for all
5014 --                       index rent terms  created for that rent increase.
5015 -- 18-SEP-02 ftanudja o changed call from fnd_profile.value('PN_SET..')
5016 --                      to wrapper function
5017 --                      pn_mo_cache_utils.get_profile_value('PN_SET..').
5018 -- 26-JAN-04 ftanudja o added handling logic for p_called_from ='NEGRENT'.
5019 --                      #3255737.
5020 --                      If 'NEGRENT' then use the term end dt,
5021 --                      not lease term dt.
5022 -- 14-JUN-04 abanerje o Modified call to pnt_payment_terms_pkg.insert_row
5023 --                      to populate the term_template_id. Bug #3657130.
5024 -- 08-OCT-04 stripath o Modified for BUG# 3961117, added new parameter p_calculate_date
5025 --                      for not to create backbills if Assessment Date <= CutOff Date.
5026 -- 21-APR-05 ftanudja o Added area_type_code, area defaulting. #4324777
5027 -- 15-JUL-05 ftanudja o R12: tax_classification_code. #4495054.
5028 -- 19-SEP-05 piagrawa o Modified to pass org id to pn_mo_cache_utils.
5029 --                      get_profile_value
5030 -- 25-NOV-05 pikhar   o Modified org id passed to pn_mo_cache_utils.
5031 --                      get_profile_value
5032 -- 06-APR-06 hkulkarn o Bug#4291907 - modified to comapre the term amount
5033 --                      with value in system option SMALLEST_TERM_AMOUNT
5034 -- 18-APR-06 Hareesha o Bug#5115291 - Get the latest norm_start_date
5035 --                      of the parent term and insert it into the RI term
5036 --                      created it.
5037 -- 05-MAY-06 Hareesha o Bug# 5115291 - Added parameter p_norm_st_date
5038 --                      Populate norm_st_date into RI term from parameter.
5039 -- 10-AUG-06 Pikhar   o Codev. Added include_in_var_rent
5040 -- 01-NOV-06 Prabhkar o Added parameter p_end_date.
5041 -- 02-JAN-07 Hareesha o M28#16 Changes for recurring backbill.
5042 -- 15-FEB-07 Pikhar   o bug 5881424. Copied include_in_var_rent to NULL if it
5043 --                      is not INCLUDE_RI
5044 -- 09-JUL-08 mumohan  o bug#6967722: In create_payment_term_record procedure,
5045 --                      corrected the code in call pnt_payment_terms_pkg.insert_row,
5046 --                      to copy the payment terms DFF into payment terms DFF of
5047 --                      new IR term and not in AR Projects DFF.
5048 -------------------------------------------------------------------------------
5049 
5050 
5051    PROCEDURE create_payment_term_record (
5052       p_lease_id               IN       NUMBER
5053      ,p_location_id            IN       NUMBER
5054      ,p_purpose_code           IN       VARCHAR2
5055      ,p_index_period_id        IN       NUMBER
5056      ,p_term_template_id       IN       NUMBER
5057      ,p_spread_frequency       IN       VARCHAR2
5058      ,p_rounding_flag          IN       VARCHAR2
5059      ,p_payment_amount         IN       NUMBER
5060      ,p_normalized             IN       VARCHAR2
5061      ,p_start_date             IN       DATE
5062      ,p_index_term_indicator   IN       VARCHAR2
5063      ,p_payment_term_id        IN       NUMBER
5064      ,p_basis_relationship     IN       VARCHAR2
5065      ,p_called_from            IN       VARCHAR2
5066      ,p_calculate_date         IN       DATE
5067      ,p_norm_st_date           IN       DATE
5068      ,p_end_date               IN       DATE
5069      ,p_recur_bb_calc_date     IN       DATE
5070      ,op_payment_term_id       OUT NOCOPY      NUMBER
5071      ,op_msg                   OUT NOCOPY      VARCHAR2
5072      ,p_include_in_var_rent    IN VARCHAR2
5073    ) IS
5074       v_name                     pn_term_templates.name%TYPE;
5075       v_normalize                pn_term_templates.normalize%TYPE := 'N';
5076       v_schedule_day             pn_term_templates.schedule_day%TYPE;
5077       v_payment_purpose_code     pn_term_templates.payment_purpose_code%TYPE;
5078       v_payment_term_type_code   pn_term_templates.payment_term_type_code%TYPE;
5079       v_accrual_account_id       pn_term_templates.accrual_account_id%TYPE;
5080       v_project_id               pn_term_templates.project_id%TYPE;
5081       v_task_id                  pn_term_templates.task_id%TYPE;
5082       v_organization_id          pn_term_templates.organization_id%TYPE;
5083       v_expenditure_type         pn_term_templates.expenditure_type%TYPE;
5084       v_expenditure_item_date    pn_term_templates.expenditure_item_date%TYPE;
5085       v_vendor_id                pn_term_templates.vendor_id%TYPE;
5086       v_vendor_site_id           pn_term_templates.vendor_site_id%TYPE;
5087       v_customer_id              pn_term_templates.customer_id%TYPE;
5088       v_customer_site_use_id     pn_term_templates.customer_site_use_id%TYPE;
5089       v_cust_ship_site_id        pn_term_templates.cust_ship_site_id%TYPE;
5090       v_ap_ar_term_id            pn_term_templates.ap_ar_term_id%TYPE;
5091       v_cust_trx_type_id         pn_term_templates.cust_trx_type_id%TYPE;
5092       v_tax_group_id             pn_term_templates.tax_group_id%TYPE;
5096       v_distribution_set_id      pn_term_templates.distribution_set_id%TYPE;
5093       v_tax_code_id              pn_term_templates.tax_code_id%TYPE;
5094       v_tax_classification_code  pn_term_templates.tax_classification_code%TYPE;
5095       v_tax_included             pn_term_templates.tax_included%TYPE;
5097       v_inv_rule_id              pn_term_templates.inv_rule_id%TYPE;
5098       v_account_rule_id          pn_term_templates.account_rule_id%TYPE;
5099       v_salesrep_id              pn_term_templates.salesrep_id%TYPE;
5100       v_set_of_books_id          pn_term_templates.set_of_books_id%TYPE;
5101       v_currency_code            pn_payment_terms.currency_code%TYPE;
5102       v_po_header_id             pn_term_templates.po_header_id%TYPE;
5103       v_cust_po_number           pn_term_templates.cust_po_number%TYPE;
5104       v_receipt_method_id        pn_term_templates.receipt_method_id%TYPE;
5105       v_attribute_category       pn_term_templates.attribute_category%TYPE;
5106       v_attribute1               pn_term_templates.attribute1%TYPE;
5107       v_attribute2               pn_term_templates.attribute2%TYPE;
5108       v_attribute3               pn_term_templates.attribute3%TYPE;
5109       v_attribute4               pn_term_templates.attribute4%TYPE;
5110       v_attribute5               pn_term_templates.attribute5%TYPE;
5111       v_attribute6               pn_term_templates.attribute6%TYPE;
5112       v_attribute7               pn_term_templates.attribute7%TYPE;
5113       v_attribute8               pn_term_templates.attribute8%TYPE;
5114       v_attribute9               pn_term_templates.attribute9%TYPE;
5115       v_attribute10              pn_term_templates.attribute10%TYPE;
5116       v_attribute11              pn_term_templates.attribute11%TYPE;
5117       v_attribute12              pn_term_templates.attribute12%TYPE;
5118       v_attribute13              pn_term_templates.attribute13%TYPE;
5119       v_attribute14              pn_term_templates.attribute14%TYPE;
5120       v_attribute15              pn_term_templates.attribute15%TYPE;
5121       v_lease_termination_date   pn_lease_details.lease_termination_date%TYPE;
5122       v_lease_change_id          pn_lease_details.lease_change_id%TYPE;
5123       v_lease_class_code         pn_leases.lease_class_code%TYPE;
5124       v_distribution_id          pn_distributions.distribution_id%TYPE;
5125       v_rowid                    VARCHAR2 (100);
5126       v_payment_term_id          pn_payment_terms.payment_term_id%TYPE;
5127       v_freq_divisor             NUMBER;
5128       v_converted_amount         NUMBER;
5129       v_actual_amount            pn_payment_terms.actual_amount%TYPE;
5130       v_gl_set_of_books_id       gl_sets_of_books.set_of_books_id%TYPE;
5131       v_expense_account_id       pn_lease_details.expense_account_id%TYPE;
5132       v_receivable_account_id    pn_lease_details.receivable_account_id%TYPE;
5133       v_account_class            pn_distributions.account_class%TYPE;
5134       v_payment_end_date         DATE;
5135       v_num_years                NUMBER;
5136       rec_payment_details        pn_payment_terms%ROWTYPE;
5137       c_rec                      pn_distributions%ROWTYPE;
5138       v_frequency_code           pn_payment_terms.frequency_code%type;
5139       v_location_id              pn_payment_terms.location_id%type;
5140       v_payment_start_date       DATE := null;
5141       v_term_end_date            DATE := null;
5142       v_assessment_date          DATE := null;
5143       v_org_id                   pn_payment_terms_all.org_id%type;
5144       v_area                     pn_payment_terms.area%TYPE;
5145       v_area_type_code           pn_payment_terms.area_type_code%TYPE;
5146       l_org_id                   NUMBER;
5147       l_norm_st_date             DATE := NULL;
5148       v_include_in_var_rent      pn_payment_terms_all.include_in_var_rent%TYPE ;
5149 
5150       CURSOR distributions (ip_term_template_id   IN   NUMBER)
5151       IS
5152       SELECT *
5153       FROM pn_distributions_all
5154       WHERE term_template_id = ip_term_template_id;
5155 
5156       CURSOR distributions_aggr (ip_payment_term_id IN   NUMBER )
5157       IS
5158       SELECT *
5159       FROM pn_distributions_all
5160       WHERE payment_term_id = ip_payment_term_id;
5161 
5162       CURSOR get_location_id IS
5163        SELECT location_id
5164        FROM pn_index_leases_all
5165        WHERE index_lease_id =
5166               (SELECT index_lease_id
5167                FROM pn_index_lease_periods_all
5168                WHERE index_period_id = p_index_period_id);
5169 
5170       CURSOR org_id_cur IS
5171        SELECT org_id
5172        FROM pn_leases_all
5173        WHERE lease_id = p_lease_id;
5174 
5175 
5176       CURSOR get_vr_nbp_flag IS
5177        SELECT vr_nbp_flag
5178        FROM pn_index_leases_all
5179        WHERE index_lease_id =
5180               (SELECT index_lease_id
5181                FROM pn_index_lease_periods_all
5182                WHERE index_period_id = p_index_period_id);
5183 
5184    BEGIN
5185       put_log ('pn_index_amount_pkg.create_payment_term_record  (+) :');
5186 
5187       IF NVL (p_payment_amount, 0) <> 0 THEN
5188 
5189            /* derive payment defaults for this index lease */
5190 
5191            BEGIN
5192 
5193            v_location_id := null;
5194 
5195            IF p_term_template_id is NULL THEN
5196                         SELECT include_in_var_rent
5197                               ,normalize
5198                               ,schedule_day
5199                               ,end_date
5203                               ,task_id
5200                               ,payment_purpose_code
5201                               ,payment_term_type_code
5202                               ,project_id
5204                               ,organization_id
5205                               ,expenditure_type
5206                               ,expenditure_item_date
5207                               ,vendor_id
5208                               ,vendor_site_id
5209                               ,customer_id
5210                               ,customer_site_use_id
5211                               ,cust_ship_site_id
5212                               ,ap_ar_term_id
5213                               ,cust_trx_type_id
5214                               ,tax_group_id
5215                               ,tax_code_id
5216                               ,tax_classification_code
5217                               ,tax_included
5218                               ,distribution_set_id
5219                               ,inv_rule_id
5220                               ,account_rule_id
5221                               ,salesrep_id
5222                               ,set_of_books_id
5223                               ,currency_code
5224                               ,po_header_id
5225                               ,cust_po_number
5226                               ,receipt_method_id
5227                               ,attribute_category
5228                               ,attribute1
5229                               ,attribute2
5230                               ,attribute3
5231                               ,attribute4
5232                               ,attribute5
5233                               ,attribute6
5234                               ,attribute7
5235                               ,attribute8
5236                               ,attribute9
5237                               ,attribute10
5238                               ,attribute11
5239                               ,attribute12
5240                               ,attribute13
5241                               ,attribute14
5242                               ,attribute15
5243                               ,frequency_code
5244                               ,location_id
5245                               ,org_id
5246                           INTO v_include_in_var_rent
5247                               ,v_normalize
5248                               ,v_schedule_day
5249                               ,v_term_end_date
5250                               ,v_payment_purpose_code
5251                               ,v_payment_term_type_code
5252                               ,v_project_id
5253                               ,v_task_id
5254                               ,v_organization_id
5255                               ,v_expenditure_type
5256                               ,v_expenditure_item_date
5257                               ,v_vendor_id
5258                               ,v_vendor_site_id
5259                               ,v_customer_id
5260                               ,v_customer_site_use_id
5261                               ,v_cust_ship_site_id
5262                               ,v_ap_ar_term_id
5263                               ,v_cust_trx_type_id
5264                               ,v_tax_group_id
5265                               ,v_tax_code_id
5266                               ,v_tax_classification_code
5267                               ,v_tax_included
5268                               ,v_distribution_set_id
5269                               ,v_inv_rule_id
5270                               ,v_account_rule_id
5271                               ,v_salesrep_id
5272                               ,v_set_of_books_id
5273                               ,v_currency_code
5274                               ,v_po_header_id
5275                               ,v_cust_po_number
5276                               ,v_receipt_method_id
5277                               ,v_attribute_category
5278                               ,v_attribute1
5279                               ,v_attribute2
5280                               ,v_attribute3
5281                               ,v_attribute4
5282                               ,v_attribute5
5283                               ,v_attribute6
5284                               ,v_attribute7
5285                               ,v_attribute8
5286                               ,v_attribute9
5287                               ,v_attribute10
5288                               ,v_attribute11
5289                               ,v_attribute12
5290                               ,v_attribute13
5291                               ,v_attribute14
5292                               ,v_attribute15
5293                               ,v_frequency_code
5294                               ,v_location_id
5295                               ,v_org_id
5296                           FROM pn_payment_terms_all
5297                          WHERE payment_term_id = p_payment_term_id;
5298            ELSE
5299                          SELECT name
5300                               ,normalize
5301                               ,schedule_day
5302                               ,payment_purpose_code
5303                               ,payment_term_type_code
5304                               ,accrual_account_id
5305                               ,project_id
5306                               ,task_id
5307                               ,organization_id
5308                               ,expenditure_type
5309                               ,expenditure_item_date
5310                               ,vendor_id
5314                               ,cust_ship_site_id
5311                               ,vendor_site_id
5312                               ,customer_id
5313                               ,customer_site_use_id
5315                               ,ap_ar_term_id
5316                               ,cust_trx_type_id
5317                               ,tax_group_id
5318                               ,tax_code_id
5319                               ,tax_classification_code
5320                               ,tax_included
5321                               ,distribution_set_id
5322                               ,inv_rule_id
5323                               ,account_rule_id
5324                               ,salesrep_id
5325                               ,set_of_books_id
5326                               ,po_header_id
5327                               ,cust_po_number
5328                               ,receipt_method_id
5329                               ,attribute_category
5330                               ,attribute1
5331                               ,attribute2
5332                               ,attribute3
5333                               ,attribute4
5334                               ,attribute5
5335                               ,attribute6
5336                               ,attribute7
5337                               ,attribute8
5338                               ,attribute9
5339                               ,attribute10
5340                               ,attribute11
5341                               ,attribute12
5342                               ,attribute13
5343                               ,attribute14
5344                               ,attribute15
5345                               ,org_id
5346                           INTO v_name
5347                               ,v_normalize
5348                               ,v_schedule_day
5349                               ,v_payment_purpose_code
5350                               ,v_payment_term_type_code
5351                               ,v_accrual_account_id
5352                               ,v_project_id
5353                               ,v_task_id
5354                               ,v_organization_id
5355                               ,v_expenditure_type
5356                               ,v_expenditure_item_date
5357                               ,v_vendor_id
5358                               ,v_vendor_site_id
5359                               ,v_customer_id
5360                               ,v_customer_site_use_id
5361                               ,v_cust_ship_site_id
5362                               ,v_ap_ar_term_id
5363                               ,v_cust_trx_type_id
5364                               ,v_tax_group_id
5365                               ,v_tax_code_id
5366                               ,v_tax_classification_code
5367                               ,v_tax_included
5368                               ,v_distribution_set_id
5369                               ,v_inv_rule_id
5370                               ,v_account_rule_id
5371                               ,v_salesrep_id
5372                               ,v_set_of_books_id
5373                               ,v_po_header_id
5374                               ,v_cust_po_number
5375                               ,v_receipt_method_id
5376                               ,v_attribute_category
5377                               ,v_attribute1
5378                               ,v_attribute2
5379                               ,v_attribute3
5380                               ,v_attribute4
5381                               ,v_attribute5
5382                               ,v_attribute6
5383                               ,v_attribute7
5384                               ,v_attribute8
5385                               ,v_attribute9
5386                               ,v_attribute10
5387                               ,v_attribute11
5388                               ,v_attribute12
5389                               ,v_attribute13
5390                               ,v_attribute14
5391                               ,v_attribute15
5392                               ,v_org_id
5393                           FROM pn_term_templates_all
5394                           WHERE term_template_id = p_term_template_id;
5395 
5396                   IF p_term_template_id is NOT NULL THEN
5397                      FOR nbp_rec IN get_vr_nbp_flag
5398                      LOOP
5399                         IF g_include_in_var_check = 'T' THEN
5400                            v_include_in_var_rent := g_include_in_var_rent;
5401                         ELSIF g_include_in_var_check = 'F' AND nbp_rec.vr_nbp_flag = 'Y' THEN
5402                            v_include_in_var_rent := 'INCLUDE_RI';
5403                         ELSE
5404                            v_include_in_var_rent := NULL;
5405                         END IF;
5406                      END LOOP;
5407                   END IF;
5408 
5409                   FOR locn_rec IN get_location_id LOOP
5410                      v_location_id := locn_rec.location_id;
5411                   END LOOP;
5412 
5413                   IF v_location_id IS NULL THEN
5414                      put_log ('Cannot Get Location Id for Payment Term Record - NO_DATA_FOUND');
5415                   END IF;
5416 
5417               END IF;
5418 
5419        EXCEPTION
5420            WHEN TOO_MANY_ROWS THEN
5421              put_log ('Cannot Get Payment Term Details - TOO_MANY_ROWS');
5422            WHEN NO_DATA_FOUND THEN
5423              put_log ('Cannot Get Payment Term Details - NO_DATA_FOUND');
5427 
5424            WHEN OTHERS THEN
5425              put_log ('Cannot Get Payment Term Details - Unknown Error:'|| SQLERRM);
5426        END;
5428        IF p_term_template_id is null THEN
5429 
5430              IF p_index_term_indicator not in (c_index_pay_term_type_atlst) AND
5431              NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'OT' then
5432                 v_normalize := 'N';
5433              ELSE
5434                 v_normalize := p_normalized;
5435              END IF;
5436 
5437              IF p_index_term_indicator in (c_index_pay_term_type_atlst_bb,
5438                                            c_index_pay_term_type_backbill) AND
5439                 NVL(fnd_profile.value('PN_RI_BACKBILL_TYPE'),'OT') = 'OT'
5440              THEN
5441                  v_frequency_code := c_spread_frequency_one_time;
5442              END IF;
5443        ELSE
5444                v_normalize := p_normalized;
5445 
5446        END IF;
5447 
5448        BEGIN
5449            SELECT trunc(pilp.assessment_date)
5450            INTO v_assessment_date
5451            FROM pn_index_lease_periods_all pilp
5452            WHERE pilp.index_period_id = p_index_period_id;
5453 
5454        EXCEPTION
5455            WHEN TOO_MANY_ROWS THEN
5456               put_log ('Cannot Get Index Period Details - TOO_MANY_ROWS');
5457            WHEN NO_DATA_FOUND THEN
5458               put_log ('Cannot Get Index Period Details - NO_DATA_FOUND');
5459            WHEN OTHERS THEN
5460               put_log (   'Cannot Get Index Period Details - Unknown Error:'
5461                   || SQLERRM);
5462        END;
5463 
5464        BEGIN
5465 
5466            SELECT pl.lease_class_code
5467                  ,pld.expense_account_id
5468                  ,pld.lease_termination_date
5469                  ,pld.lease_change_id
5470            INTO v_lease_class_code
5471                ,v_expense_account_id
5472                ,v_lease_termination_date
5473                ,v_lease_change_id
5474            FROM pn_leases_all pl, pn_lease_details_all pld
5475            WHERE pl.lease_id = pld.lease_id
5476            AND pld.lease_id = p_lease_id;
5477 
5478       EXCEPTION
5479         WHEN TOO_MANY_ROWS THEN
5480            put_log ('Cannot Get Main Lease Details - TOO_MANY_ROWS');
5481         WHEN NO_DATA_FOUND THEN
5482            put_log ('Cannot Get Main Lease Details - NO_DATA_FOUND');
5483         WHEN OTHERS THEN
5484            put_log (   'Cannot Get Main Lease Details - Unknown Error:'
5485                      || SQLERRM);
5486       END;
5487 
5488       IF v_org_id IS NULL THEN
5489         FOR org_id_rec IN org_id_cur LOOP
5490           v_org_id := org_id_rec.org_id;
5491         END LOOP;
5492       END IF;
5493 
5494       /* Derive SET_OF_BOOKS_ID and currency code */
5495 
5496       v_gl_set_of_books_id := pn_mo_cache_utils.get_profile_value('PN_SET_OF_BOOKS_ID', v_org_id);
5497 
5498 
5499       IF p_term_template_id is not null THEN
5500          v_currency_code := g_currency_code;
5501       END IF;
5502 
5503 
5504      /*  if the payment frequency is one-time the payment start and end date will be the same
5505          Bug: 1817219 */
5506 
5507       v_payment_start_date := p_start_date;
5508 
5509       IF p_spread_frequency IN (c_spread_frequency_one_time)  THEN
5510 
5511          IF v_assessment_date < p_calculate_date AND
5512             p_index_term_indicator IN (c_index_pay_term_type_recur,c_index_pay_term_type_atlst) AND
5513             p_called_from IN ('INDEX','NEGRENT')  THEN
5514             v_payment_start_date := p_calculate_date;
5515          END IF;
5516 
5517          IF TRUNC(v_lease_termination_date) <= p_calculate_date AND
5518             p_called_from IN ('INDEX','NEGRENT')  THEN
5519             v_payment_start_date := v_assessment_date;
5520          END IF;
5521 
5522          v_payment_end_date := v_payment_start_date;
5523       ELSE
5524 
5525          IF p_called_from = 'NEGRENT' THEN
5526             v_payment_end_date := v_term_end_date;
5527          ELSE
5528             v_payment_end_date := p_end_date;
5529          END IF;
5530 
5531       END IF;
5532 
5533       /* convert annualized amount to value based on frequency code */
5534 
5535       IF p_spread_frequency = c_spread_frequency_monthly THEN
5536          v_freq_divisor := 12;
5537       ELSIF p_spread_frequency = c_spread_frequency_one_time THEN
5538          v_freq_divisor := 1;
5539       ELSIF p_spread_frequency = c_spread_frequency_quarterly THEN
5540          v_freq_divisor := 4;
5541       ELSIF p_spread_frequency = c_spread_frequency_semiannual THEN
5542          v_freq_divisor := 2;
5543       ELSIF p_spread_frequency = c_spread_frequency_annually THEN
5544          v_freq_divisor := 1;
5545       END IF;
5546 
5547       /* since the index rent is an annual amount.  it has to be converted
5548          to the amount to be paid based on the frequency */
5549 
5550       v_converted_amount := p_payment_amount / v_freq_divisor;
5551 
5552      /* if no schedule day from template set schedule day to the day of  today's date or
5553         that of the derived start date,whichever is of the two dates is later.. */
5554 
5555       IF v_schedule_day IS NULL THEN
5556          IF p_calculate_date > p_start_date THEN
5557             v_schedule_day := TO_NUMBER(TO_CHAR(p_calculate_date, 'DD'));
5558          ELSE
5562 
5559             v_schedule_day := TO_NUMBER(TO_CHAR(p_start_date, 'DD'));
5560          END IF;
5561       END IF;
5563 
5564       /* Depending on the lease class code, certain fields are not needed and will be nulled out*/
5565 
5566 
5567       IF v_lease_class_code = c_lease_class_direct THEN
5568          v_customer_id := NULL;
5569          v_customer_site_use_id := NULL;
5570          v_cust_ship_site_id := NULL;
5571          v_cust_trx_type_id := NULL;
5572          v_inv_rule_id := NULL;
5573          v_account_rule_id := NULL;
5574          v_salesrep_id := NULL;
5575          v_cust_po_number := NULL;
5576          v_receipt_method_id := NULL;
5577       ELSE
5578          v_project_id := NULL;
5579          v_task_id := NULL;
5580          v_organization_id := NULL;
5581          v_expenditure_type := NULL;
5582          v_expenditure_item_date := NULL;
5583          v_vendor_id := NULL;
5584          v_vendor_site_id := NULL;
5585          v_tax_group_id := NULL;
5586          v_distribution_set_id := NULL;
5587          v_po_header_id := NULL;
5588       END IF; --v_lease_class_code = C_LEASE_CLASS_DIRECT
5589 
5590       IF pn_r12_util_pkg.is_r12 THEN
5591          v_tax_group_id := NULL;
5592          v_tax_code_id := NULL;
5593       ELSE
5594          v_tax_classification_code := NULL;
5595       END IF;
5596 
5597       /* round off the index amount if necessary */
5598 
5599       IF NVL (p_rounding_flag, 'N') = 'Y' THEN
5600          v_actual_amount := ROUND (v_converted_amount, 0);
5601       ELSE
5602          v_actual_amount :=
5603                   ROUND (v_converted_amount, get_amount_precision);
5604       END IF; -- NVL (p_rounding_flag, 'N') = 'Y'
5605 
5606        /* figure out location and default area type and area size */
5607 
5608        IF v_location_id IS NOT NULL AND
5609           v_payment_start_date IS NOT NULL THEN
5610 
5611           v_area_type_code := 'LOCTN_RENTABLE';
5612           v_area := pnp_util_func.fetch_tenancy_area(
5613                        p_lease_id       => p_lease_id,
5614                        p_location_id    => p_location_id,
5615                        p_as_of_date     => v_payment_start_date,
5616                        p_area_type_code => v_area_type_code);
5617 
5618       END IF;
5619 
5620       /* Create a record in PN_PAYMENT_TERMS table */
5621 
5622       IF ( v_actual_amount <> 0
5623       AND abs(v_actual_amount) > nvl(pn_mo_cache_utils.get_profile_value('SMALLEST_TERM_AMOUNT',v_org_id),0)
5624          ) THEN  --#@#Bug4291907
5625 
5626          /* pikhar Start - Added for bug 5881424 - 15-FEB-07 */
5627          IF v_include_in_var_rent = 'INCLUDE_RI' THEN
5628            NULL;
5629          ELSE
5630            v_include_in_var_rent := NULL;
5631          END IF;
5632          /* pikhar Finished - Added for bug 5881424 - 15-FEB-07 */
5633 
5634          pnt_payment_terms_pkg.insert_row (
5635             x_rowid                       => v_rowid
5636            ,x_payment_term_id             => v_payment_term_id
5637            ,x_index_period_id             => p_index_period_id
5638            ,x_index_term_indicator        => p_index_term_indicator
5639            ,x_last_update_date            => SYSDATE
5640            ,x_last_updated_by             => NVL (fnd_profile.VALUE ('USER_ID'), 0)
5641            ,x_creation_date               => SYSDATE
5642            ,x_created_by                  => NVL (fnd_profile.VALUE ('USER_ID'), 0)
5643            ,x_payment_purpose_code        => NVL (v_payment_purpose_code, p_purpose_code)
5644            ,x_payment_term_type_code      => NVL (v_payment_term_type_code,c_payment_term_type_index)
5645            ,x_frequency_code              => p_spread_frequency
5646            ,x_lease_id                    => p_lease_id
5647            ,x_lease_change_id             => v_lease_change_id
5648            ,x_start_date                  => v_payment_start_date   --p_start_date
5649            ,x_end_date                    => v_payment_end_date
5650            ,x_set_of_books_id             => NVL(v_set_of_books_id,v_gl_set_of_books_id)
5651            ,x_currency_code               => v_currency_code
5652            ,x_rate                        => 1 -- not used in application
5653            ,x_last_update_login           => NVL (fnd_profile.VALUE ('USER_ID'), 0)
5654            ,x_vendor_id                   => v_vendor_id
5655            ,x_vendor_site_id              => v_vendor_site_id
5656            ,x_target_date                 => NULL
5657            ,x_actual_amount               => v_actual_amount
5658            ,x_estimated_amount            => NULL
5659            ,x_attribute_category          => v_attribute_category
5660            ,x_attribute1                  => v_attribute1
5661            ,x_attribute2                  => v_attribute2
5662            ,x_attribute3                  => v_attribute3
5663            ,x_attribute4                  => v_attribute4
5664            ,x_attribute5                  => v_attribute5
5665            ,x_attribute6                  => v_attribute6
5666            ,x_attribute7                  => v_attribute7
5667            ,x_attribute8                  => v_attribute8
5668            ,x_attribute9                  => v_attribute9
5669            ,x_attribute10                 => v_attribute10
5670            ,x_attribute11                 => v_attribute11
5671            ,x_attribute12                 => v_attribute12
5672            ,x_attribute13                 => v_attribute13
5676            ,x_project_attribute1          => NULL
5673            ,x_attribute14                 => v_attribute14
5674            ,x_attribute15                 => v_attribute15
5675            ,x_project_attribute_category  => NULL
5677            ,x_project_attribute2          => NULL
5678            ,x_project_attribute3          => NULL
5679            ,x_project_attribute4          => NULL
5680            ,x_project_attribute5          => NULL
5681            ,x_project_attribute6          => NULL
5682            ,x_project_attribute7          => NULL
5683            ,x_project_attribute8          => NULL
5684            ,x_project_attribute9          => NULL
5685            ,x_project_attribute10         => NULL
5686            ,x_project_attribute11         => NULL
5687            ,x_project_attribute12         => NULL
5688            ,x_project_attribute13         => NULL
5689            ,x_project_attribute14         => NULL
5690            ,x_project_attribute15         => NULL
5691            ,x_customer_id                 => v_customer_id
5692            ,x_customer_site_use_id        => v_customer_site_use_id
5693            ,x_normalize                   => v_normalize --p_normalized
5694            ,x_location_id                 => v_location_id
5695            ,x_schedule_day                => v_schedule_day
5696            ,x_cust_ship_site_id           => v_cust_ship_site_id
5697            ,x_ap_ar_term_id               => v_ap_ar_term_id
5698            ,x_cust_trx_type_id            => v_cust_trx_type_id
5699            ,x_project_id                  => v_project_id
5700            ,x_task_id                     => v_task_id
5701            ,x_organization_id             => v_organization_id
5702            ,x_expenditure_type            => v_expenditure_type
5703            ,x_expenditure_item_date       => v_expenditure_item_date
5704            ,x_tax_group_id                => v_tax_group_id
5705            ,x_tax_code_id                 => v_tax_code_id
5706            ,x_tax_classification_code     => v_tax_classification_code
5707            ,x_tax_included                => v_tax_included
5708            ,x_distribution_set_id         => v_distribution_set_id
5709            ,x_inv_rule_id                 => v_inv_rule_id
5710            ,x_account_rule_id             => v_account_rule_id
5711            ,x_salesrep_id                 => v_salesrep_id
5712            ,x_approved_by                 => NULL
5713            ,x_status                      => c_payment_term_status_draft
5714            ,x_po_header_id                => v_po_header_id
5715            ,x_cust_po_number              => v_cust_po_number
5716            ,x_receipt_method_id           => v_receipt_method_id
5717            ,x_calling_form                => 'PNTRENTI'
5718            ,x_org_id                      => v_org_id
5719            ,x_term_template_id            => p_term_template_id
5720            ,x_area                        => v_area
5721            ,x_area_type_code              => v_area_type_code
5722            ,x_norm_start_date             => p_norm_st_date
5723            ,x_include_in_var_rent         => v_include_in_var_rent
5724            ,x_recur_bb_calc_date          => p_recur_bb_calc_date
5725          );
5726 
5727          op_payment_term_id := v_payment_term_id;
5728 
5729          put_output (
5730                LPAD (p_spread_frequency, 18, ' ')
5731             || LPAD (v_payment_start_date, 13, ' ')
5732             || LPAD (v_payment_end_date, 13, ' ')
5733             || LPAD (format (v_actual_amount, 2), 12, ' ')
5734             || LPAD (c_payment_term_status_draft, 13, ' ')
5735             || LPAD (p_index_term_indicator, 20, ' ')
5736             || LPAD (v_normalize, 11, ' ')
5737          );
5738 
5739          put_output ('.         ');
5740 
5741 
5742          /* Get distributions from template. */
5743 
5744          IF p_term_template_id IS NULL THEN
5745                OPEN distributions_aggr (p_payment_term_id);
5746           ELSE
5747                OPEN distributions (p_term_template_id);
5748          END IF;
5749 
5750 
5751          LOOP
5752              IF distributions_aggr%ISOPEN THEN
5753                    FETCH distributions_aggr into c_rec;
5754                    EXIT WHEN distributions_aggr%NOTFOUND;
5755               ELSIF distributions%ISOPEN  THEN
5756                    FETCH distributions into c_rec;
5757                    EXIT WHEN distributions%NOTFOUND;
5758               END IF;
5759 
5760             put_log('create_payment_term_record - account_class :'||c_rec.account_class);
5761 
5762             /* Create a record in PN_DISTRIBUTIONS table */
5763 
5764             pn_distributions_pkg.insert_row (
5765                x_rowid                       => v_rowid
5766               ,x_distribution_id             => v_distribution_id
5767               ,x_account_id                  => c_rec.account_id
5768               ,x_payment_term_id             => v_payment_term_id
5769               ,x_term_template_id            => NULL
5770               ,x_account_class               => c_rec.account_class
5771               ,x_percentage                  => c_rec.percentage
5772               ,x_line_number                 => c_rec.line_number
5773               ,x_last_update_date            => SYSDATE
5774               ,x_last_updated_by             => NVL (fnd_profile.VALUE ('USER_ID'), 0)
5775               ,x_creation_date               => SYSDATE
5776               ,x_created_by                  => NVL (fnd_profile.VALUE ('USER_ID'), 0)
5777               ,x_last_update_login           => NVL (fnd_profile.VALUE ('USER_ID'), 0)
5781               ,x_attribute3                  => c_rec.attribute3
5778               ,x_attribute_category          => c_rec.attribute_category
5779               ,x_attribute1                  => c_rec.attribute1
5780               ,x_attribute2                  => c_rec.attribute2
5782               ,x_attribute4                  => c_rec.attribute4
5783               ,x_attribute5                  => c_rec.attribute5
5784               ,x_attribute6                  => c_rec.attribute6
5785               ,x_attribute7                  => c_rec.attribute7
5786               ,x_attribute8                  => c_rec.attribute8
5787               ,x_attribute9                  => c_rec.attribute9
5788               ,x_attribute10                 => c_rec.attribute10
5789               ,x_attribute11                 => c_rec.attribute11
5790               ,x_attribute12                 => c_rec.attribute12
5791               ,x_attribute13                 => c_rec.attribute13
5792               ,x_attribute14                 => c_rec.attribute14
5793               ,x_attribute15                 => c_rec.attribute15
5794             );
5795             v_rowid := NULL;
5796             v_distribution_id := NULL;
5797 
5798          END LOOP payment_term_template;
5799 
5800          v_payment_term_id := NULL;
5801 
5802       END IF; --v_actual_amount <> 0
5803 
5804      END IF; --p_amount <> 0 then
5805 
5806    put_log ('pn_index_amount_pkg.create_payment_term_record  (-) :');
5807 
5808    END create_payment_term_record;
5809 
5810 -------------------------------------------------------------------------------
5811 --  FUNCTION   : Get_Calculate_Date
5812 --  DESCRIPTION: This function returns returns the lease of assessment date and
5813 --               the profile option cut off date (change from Legacy to PN).
5814 --  HISTORY    :
5815 --  08-OCT-2004  Satish Tripathi o Created for BUG# 3961117.
5816 --                                 Do not to create backbills if Assessment
5817 --                                 Date <= CutOff Date.
5818 --  21-OCT-2004  Satish Tripathi o Added TO_DATE to profile PN_CUTOFF_DATE,
5819 --                                 default 01/01/0001.
5820 -------------------------------------------------------------------------------
5821 FUNCTION Get_Calculate_Date (p_assessment_date  IN DATE,
5822                              p_period_str_date  IN DATE)
5823 RETURN   DATE
5824 IS
5825    l_prof_cut_off    VARCHAR2(30) := pn_mo_cache_utils.get_profile_value('PN_CUTOFF_DATE');
5826    l_cut_off_date    DATE := NULL;
5827    l_calculate_date  DATE;
5828 BEGIN
5829 
5830    put_log('PN_INDEX_AMOUNT_PKG.Get_Calculate_Date (+) Asmt Dt: '||p_assessment_date
5831            ||', PrdStrDt: '||p_period_str_date||', CutOffDt: '||l_prof_cut_off);
5832 
5833    IF l_prof_cut_off IS NOT NULL THEN
5834       l_cut_off_date := TO_DATE(l_prof_cut_off, 'MM/DD/YYYY');
5835    ELSE
5836       l_cut_off_date := TO_DATE('01/01/0001', 'DD/MM/YYYY');
5837    END IF;
5838 
5839    IF TRUNC(l_cut_off_date) >= TRUNC(p_assessment_date) THEN
5840       l_calculate_date := TRUNC(p_assessment_date);
5841    ELSE
5842       l_calculate_date := TRUNC(SYSDATE);
5843    END IF;
5844 
5845    put_log('PN_INDEX_AMOUNT_PKG.Get_Calculate_Date (-) Calc Dt: '||l_calculate_date);
5846 
5847    RETURN l_calculate_date;
5848 END Get_Calculate_Date;
5849 
5850 
5851 -------------------------------------------------------------------------------
5852 --  FUNCTION    : Get_Calculate_Date (overloaded)
5853 --  DESCRIPTION : This function returns returns the lease of assessment date
5854 --                and the profile option cut off date(change from Legacy to PN)
5855 --  HISTORY     :
5856 --  19-SEP-05   piagrawa  o Modified the signature of procedure. Also passed
5857 --                          org id in pn_mo_cache_utils.get_profile_value
5858 -------------------------------------------------------------------------------
5859 FUNCTION Get_Calculate_Date (p_assessment_date  IN DATE,
5860                              p_period_str_date  IN DATE,
5861                              p_org_id           IN NUMBER)
5862 RETURN   DATE
5863 IS
5864    l_prof_cut_off    VARCHAR2(30) := pn_mo_cache_utils.get_profile_value('PN_CUTOFF_DATE', p_org_id);
5865    l_cut_off_date    DATE := NULL;
5866    l_calculate_date  DATE;
5867 BEGIN
5868 
5869    put_log('PN_INDEX_AMOUNT_PKG.Get_Calculate_Date (+) Asmt Dt: '||p_assessment_date
5870            ||', PrdStrDt: '||p_period_str_date||', CutOffDt: '||l_prof_cut_off);
5871 
5872    IF l_prof_cut_off IS NOT NULL THEN
5873       l_cut_off_date := TO_DATE(l_prof_cut_off, 'MM/DD/YYYY');
5874    ELSE
5875       l_cut_off_date := TO_DATE('01/01/0001', 'DD/MM/YYYY');
5876    END IF;
5877 
5878    IF TRUNC(l_cut_off_date) >= TRUNC(p_assessment_date) THEN
5879       l_calculate_date := TRUNC(p_assessment_date);
5880    ELSE
5881       l_calculate_date := TRUNC(SYSDATE);
5882    END IF;
5883 
5884    put_log('PN_INDEX_AMOUNT_PKG.Get_Calculate_Date (-) Calc Dt: '||l_calculate_date);
5885 
5886    RETURN l_calculate_date;
5887 END Get_Calculate_Date;
5888 
5889 --------------------------------------------------------------------------------
5890 -- PROCEDURE : calculate_period
5891 -- DESCRIPTION: This procedure will calculate the index amount for a period
5892 --             o Calculate Basis Amount
5893 --             o Calculate Index Percentage Change (if necessary)
5894 -- HISTORY
5895 -- 13-FEB-04 ftanudja  o Fixed logic for 'UPDATE pn_index_leases set
5899 -- 03-Feb-05 Vivek     o Bug 4099136. Select NULL as purpose in cursor c1
5896 --                       initial_basis..' Bug # 3436147
5897 -- 08-OCT-04 Satish    o BUG# 3961117. Get calculate_date and pass it for not to
5898 --                       create backbills if Assessment Date <= CutOff Date.
5900 -- 19-sep-05 piagrawa  o passed org id in pn_mo_cache_utils.get_profile_value
5901 -- 24-NOV-06 Prabhakar o Added handling for index multiplier in calculating RI
5902 --                       by passing adjusted index percentage to index_amonut.
5903 -- 12-DEC-06 Prabhakar o Added the derivation of proration_factor
5904 --                     o Added proration_rule,proration_period_start_date and
5905 --                       assessment_interval columns to cursor c1.
5906 -- 09-Jan-07 Lokesh    o Removed code to change schedule_day as the value
5907 --                       returned by get_schedule_date for M28 item# 11
5908 -- 30-Jan-07 Lokesh    o Removed to_date for GSCC error
5909 -- 23-Jul-07 Prabhakar o Bug # 6263259.
5910 --------------------------------------------------------------------------------
5911 
5912    PROCEDURE calculate_period (
5913       ip_index_lease_id              IN       NUMBER
5914      ,ip_index_lease_period_id       IN       NUMBER
5915      ,ip_recalculate                 IN       VARCHAR2
5916      ,op_current_basis               OUT NOCOPY      NUMBER
5917      ,op_unconstraint_rent_due       OUT NOCOPY      NUMBER
5918      ,op_constraint_rent_due         OUT NOCOPY      NUMBER
5919      ,op_index_percent_change        OUT NOCOPY      NUMBER
5920      ,op_current_index_line_id       OUT NOCOPY      NUMBER
5921      ,op_current_index_line_value    OUT NOCOPY      NUMBER
5922      ,op_previous_index_line_id      OUT NOCOPY      NUMBER
5923      ,op_previous_index_line_value   OUT NOCOPY      NUMBER
5924      ,op_previous_index_amount       IN OUT NOCOPY   NUMBER
5925      ,op_previous_asmt_date          IN OUT NOCOPY   DATE
5926      ,op_constraint_applied_amount   OUT NOCOPY      NUMBER
5927      ,op_carry_forward_amount        OUT NOCOPY      NUMBER
5928      ,op_constraint_applied_percent  OUT NOCOPY      NUMBER
5929      ,op_carry_forward_percent       OUT NOCOPY      NUMBER
5930      ,op_msg                         OUT NOCOPY      VARCHAR2
5931    ) IS
5932       v_basis_amount                pn_index_lease_periods.current_basis%TYPE;
5933       v_index_percent_change        pn_index_lease_periods.index_percent_change%TYPE;
5934       v_uncontrained_index_amount   pn_index_lease_periods.unconstraint_rent_due%TYPE;
5935       v_msg                         VARCHAR2 (100);
5936       v_all_msg                     VARCHAR2 (4000);
5937       v_period_msg                  VARCHAR2 (1000); -- messages for current period only
5938       v_constrained_rent_amount     pn_index_lease_periods.constraint_rent_due%TYPE;
5939       v_current_cpi_value           pn_index_lease_periods.current_index_line_value%TYPE;
5940       v_current_cpi_id              pn_index_lease_periods.current_index_line_id%TYPE;
5941       v_previous_cpi_value          pn_index_lease_periods.previous_index_line_value%TYPE;
5942       v_previous_cpi_id             pn_index_lease_periods.previous_index_line_id%TYPE;
5943       v_main_lease_commencement_date pn_lease_details.lease_commencement_date%type;
5944       v_initial_basis_amt           NUMBER := 0;
5945       v_constraint_applied_amount   pn_index_lease_periods.constraint_applied_amount%type;
5946       v_carry_forward_amount        pn_index_lease_periods.carry_forward_amount%type;
5947       v_constraint_applied_percent  pn_index_lease_periods.constraint_applied_percent%type;
5948       v_carry_forward_percent       pn_index_lease_periods.carry_forward_percent%type;
5949       l_err_flag                    VARCHAR2 (1);
5950       l_pre_index_rent_id           NUMBER;
5951       l_calculate_date              DATE;
5952       v_adj_index_percent_change    NUMBER;
5953       l_proration_rule              VARCHAR2(30);
5954       l_proration_period_start_date  DATE;
5955       l_prorate_factor              NUMBER :=1;
5956       l_months                      NUMBER := NULL;
5957 
5958 
5959       CURSOR c1 (
5960          p_index_lease_period_id   NUMBER
5961       ) IS
5962          SELECT pil.index_lease_id
5963                ,pil.index_id
5964                ,pil.lease_id
5965                ,pil.commencement_date
5966                ,pil.currency_code
5967                ,nvl(pil.increase_on,c_increase_on_gross) "INCREASE_ON"
5968                ,pil.basis_type
5969                ,pil.initial_basis
5970                ,pil.index_finder_method
5971                ,pil.base_index
5972                ,pil.base_index_line_id
5973                ,NVL (pil.rounding_flag, 'N') "ROUNDING_FLAG"
5974                ,pil.reference_period
5975                ,pil.spread_frequency
5976                ,pil.term_template_id
5977                ,pil.negative_rent_type
5978                ,NULL as purpose
5979                ,pil.location_id
5980                ,pil.index_lease_number
5981                ,pil.carry_forward_flag
5982                ,pilp.basis_percent_change
5983                ,pilp.current_basis
5984                ,pilp.index_percent_change
5985                ,pilp.index_finder_date
5986                ,pilp.index_period_id
5987                ,pilp.basis_start_date
5988                ,pilp.basis_end_date
5989                ,pilp.assessment_date
5990                ,pilp.line_number
5991                ,pilp.relationship
5992                ,pilp.constraint_rent_due
5993                ,pilp.unconstraint_rent_due
5994                ,pilp.current_index_line_id
5995                ,pilp.current_index_line_value
5996                ,pilp.previous_index_line_id
6000                ,pilp.carry_forward_percent
5997                ,pilp.previous_index_line_value
5998                ,pilp.carry_forward_amount
5999                ,pilp.constraint_applied_amount
6001                ,pilp.constraint_applied_percent
6002                ,pl.lease_class_code
6003                ,pil.org_id
6004                ,nvl (pilp.index_multiplier, 1) "INDEX_MULTIPLIER"
6005                ,nvl (pil.proration_rule, 'NO_PRORATION') "PRORATION_RULE"
6006                ,pil.proration_period_start_date
6007                ,pil.assessment_interval
6008            FROM pn_index_leases_all pil,
6009                 pn_index_lease_periods_all pilp,
6010                 pn_leases_all pl
6011           WHERE pil.index_lease_id = pilp.index_lease_id
6012             AND pil.lease_id = pl.lease_id
6013             AND pilp.index_period_id = p_index_lease_period_id;
6014 
6015       l_message VARCHAR2(2000) := NULL;
6016 
6017       CURSOR get_lease_details(p_lease_id NUMBER) IS
6018          SELECT lease_commencement_date,
6019                 lease_termination_date,
6020                 lease_extension_end_date
6021          FROM pn_leases_all lease, pn_lease_details_all ldet
6022          WHERE lease.lease_id = ldet.lease_id
6023          AND   lease.lease_id = p_lease_id;
6024 
6025       CURSOR get_extendable_terms(p_index_period_id NUMBER,l_term_date DATE) IS
6026          SELECT *
6027          FROM pn_payment_terms_all
6028          WHERE index_period_id = p_index_period_id
6029          AND end_date = l_term_date;
6030 
6031       l_comm_date DATE;
6032       l_term_date DATE;
6033       l_ext_end_dt DATE;
6034       l_term_rec pn_payment_terms_all%ROWTYPE;
6035       l_return_status VARCHAR2(100);
6036       l_schd_date  DATE := NULL;
6037       l_schd_day   NUMBER := NULL;
6038       l_terms_exist BOOLEAN := FALSE;
6039 
6040    BEGIN
6041 
6042       put_log('PN_INDEX_AMOUNT_PKG.calculate_period (+) LeaseId: '||ip_index_lease_id
6043               ||', PrdId: '||ip_index_lease_period_id||', ReCalc: '||ip_recalculate);
6044       v_all_msg := 'PN_INDEX_SUCCESS';
6045       l_pre_index_rent_id := NULL;
6046 
6047       FOR c_rec IN c1 (ip_index_lease_period_id)
6048       LOOP
6049 
6050          IF c_rec.index_period_id <> NVL(l_pre_index_rent_id,-9999) THEN
6051             l_err_flag := 'N';
6052             l_pre_index_rent_id := c_rec.index_period_id;
6053             IF c_rec.term_template_id IS NOT NULL AND
6054                NOT pnp_util_func.validate_term_template(p_term_temp_id   => c_rec.term_template_id,
6055                                                         p_lease_cls_code => c_rec.lease_class_code) THEN
6056 
6057                l_err_flag := 'Y';
6058                v_all_msg := 'PN_MISS_TERM_TEMP_DATA';
6059             END IF;
6060          END IF;
6061          IF l_err_flag = 'N' THEN
6062             l_calculate_date := Get_Calculate_Date(
6063                                     p_assessment_date => c_rec.assessment_date
6064                                    ,p_period_str_date => c_rec.basis_start_date
6065                                    ,p_org_id          => c_rec.org_id
6066                                    );
6067          put_output ('****************************************');
6068          fnd_message.set_name ('PN','PN_RICAL_PROC');
6069          put_output(fnd_message.get||'...');
6070          fnd_message.set_name ('PN','PN_RICAL_LSNO');
6071          fnd_message.set_token ('NUM', c_rec.index_lease_number);
6072          put_output(fnd_message.get);
6073          fnd_message.set_name ('PN','PN_RICAL_LS_PRD');
6074          fnd_message.set_token ('NUM', c_rec.line_number);
6075          fnd_message.set_token ('ID', c_rec.index_period_id);
6076          put_output(fnd_message.get);
6077          fnd_message.set_name ('PN','PN_RICAL_ASS_DATE');
6078          fnd_message.set_token ('DATE', c_rec.assessment_date);
6079          put_output(fnd_message.get);
6080          put_output ('****************************************');
6081 
6082         /* Initialize global variable g_currency_code */
6083 
6084          g_currency_code := c_rec.currency_code;
6085 
6086         /* Calculate index rent if no constrained rent is found or
6087            RECALCULATE parameter is set to 'Y'es. */
6088 
6089          IF c_rec.constraint_rent_due IS NULL
6090             OR NVL (ip_recalculate, 'N') = 'Y' THEN
6091 
6092                calculate_basis_amount (
6093                   p_index_lease_id              => c_rec.index_lease_id
6094                  ,p_basis_start_date            => c_rec.basis_start_date
6095                  ,p_basis_end_date              => c_rec.basis_end_date
6096                  ,p_assessment_date             => c_rec.assessment_date
6097                  ,p_initial_basis               => c_rec.initial_basis
6098                  ,p_line_number                 => c_rec.line_number
6099                  ,p_increase_on                 => c_rec.increase_on
6100                  ,p_basis_type                  => c_rec.basis_type
6101                  ,p_prev_index_amount           => op_previous_index_amount
6102                  ,p_recalculate                 => ip_recalculate
6103                  ,op_basis_amount               => v_basis_amount
6104                  ,op_msg                        => v_msg
6105                );
6106 
6107             pn_index_lease_common_pkg.append_msg (
6108                p_new_msg                     => v_msg
6109               ,p_all_msg                     => v_period_msg );
6110 
6111             v_msg := NULL;
6112 
6113 
6117               (   c_rec.index_percent_change IS NULL OR
6114             put_log ('Calculating the Index Percentage');
6115 
6116             IF c_rec.relationship IN (c_relation_index_only, c_relation_greater_of, c_relation_lesser_of) AND
6118                  (c_rec.index_finder_method = c_index_finder_most_recent AND
6119                   c_rec.assessment_date >= l_calculate_date)
6120               ) THEN
6121 
6122                calculate_index_percentage (
6123                   p_index_finder_type           => c_rec.index_finder_method
6124                  ,p_reference_period_type       => c_rec.reference_period
6125                  ,p_index_finder_date           => c_rec.index_finder_date
6126                  ,p_index_history_id            => c_rec.index_id
6127                  ,p_base_index                  => c_rec.base_index
6128                  ,p_base_index_line_id          => c_rec.base_index_line_id
6129                  ,p_index_lease_id              => c_rec.index_lease_id
6130                  ,p_assessment_date             => c_rec.assessment_date
6131                  ,p_prev_assessment_date        => op_previous_asmt_date
6132                  ,op_current_cpi_value          => v_current_cpi_value
6133                  ,op_current_cpi_id             => v_current_cpi_id
6134                  ,op_previous_cpi_value         => v_previous_cpi_value
6135                  ,op_previous_cpi_id            => v_previous_cpi_id
6136                  ,op_index_percent_change       => v_index_percent_change
6137                  ,op_msg                        => v_msg
6138                );
6139 
6140             ELSE
6141                v_index_percent_change := c_rec.index_percent_change;
6142                v_current_cpi_value := c_rec.current_index_line_value;
6143                v_current_cpi_id := c_rec.current_index_line_id;
6144                v_previous_cpi_value := c_rec.previous_index_line_value;
6145                v_previous_cpi_id := c_rec.previous_index_line_id;
6146             END IF; -- c_rec.relationship in ???
6147 
6148             v_adj_index_percent_change := v_index_percent_change * c_rec.index_multiplier;
6149 
6150             put_log ('v_msg ' || v_msg);
6151             pn_index_lease_common_pkg.append_msg (
6152                p_new_msg                     => v_msg
6153               ,p_all_msg                     => v_period_msg
6154             );
6155             v_msg := NULL;
6156 
6157             calculate_index_amount (
6158                p_relationship                => c_rec.relationship
6159               ,p_adj_index_percent_change    => v_adj_index_percent_change
6160               ,p_basis_percent_change        => c_rec.basis_percent_change
6161               ,p_current_basis               => v_basis_amount
6162               ,op_index_amount               => v_uncontrained_index_amount
6163               ,op_msg                        => v_msg
6164             );
6165 
6166             put_log ('3 v_msg ' || v_msg);
6167             pn_index_lease_common_pkg.append_msg (
6168                p_new_msg                     => v_msg
6169               ,p_all_msg                     => v_period_msg
6170             );
6171             v_msg := NULL;
6172 
6173            put_log('********************** p_unconstrained_rent_amount ******************************'||
6174                    v_uncontrained_index_amount);
6175 
6176                l_prorate_factor := 1;
6177                IF c_rec.commencement_date = c_rec.assessment_date THEN
6178 
6179                    IF c_rec.proration_rule = 'DAYS_365' THEN
6180                        l_prorate_factor := (
6181                                              c_rec.commencement_date -
6182                                              c_rec.proration_period_start_date
6183                                             )/(365*c_rec.assessment_interval);
6184 
6185                    ELSIF c_rec.proration_rule = 'FUL_PART_MON_12' THEN
6186                        l_months := MONTHS_BETWEEN (
6187                                                    c_rec.commencement_date,
6188                                                    c_rec.proration_period_start_date
6189                                                   );
6190 
6191                       IF TRUNC (l_months, 0) <> l_months THEN
6192                          l_months := TRUNC (l_months, 0) + 1;
6193                       END IF;
6194 
6195                       l_prorate_factor := l_months/(12*c_rec.assessment_interval);
6196 
6197                    END IF;
6198 
6199                END IF;
6200 
6201 	    IF v_uncontrained_index_amount IS NOT NULL THEN  -- Bug #6263259
6202 
6203                derive_constrained_rent (
6204                   p_index_lease_id              => c_rec.index_lease_id
6205                  ,p_current_basis               => v_basis_amount
6206                  ,p_index_period_id             => c_rec.index_period_id
6207                  ,p_assessment_date             => c_rec.assessment_date
6208                  ,p_negative_rent_type          => c_rec.negative_rent_type
6209                  ,p_unconstrained_rent_amount   => v_uncontrained_index_amount
6210                  ,p_carry_forward_flag          => nvl(c_rec.carry_forward_flag,'N')
6211                  ,p_prorate_factor              => l_prorate_factor
6212                  ,op_constrained_rent_amount    => v_constrained_rent_amount
6213                  ,op_constraint_applied_amount  => v_constraint_applied_amount
6214                  ,op_constraint_applied_percent => v_constraint_applied_percent
6215                  ,op_carry_forward_amount       => v_carry_forward_amount
6219 
6216                  ,op_carry_forward_percent      => v_carry_forward_percent
6217                  ,op_msg                        => v_msg
6218                                 );
6220                put_log ('v_msg ' || v_msg);
6221                pn_index_lease_common_pkg.append_msg (
6222                   p_new_msg                     => v_msg
6223                  ,p_all_msg                     => v_period_msg
6224                );
6225                v_msg := NULL;
6226 
6227             END IF; -- v_uncontrained_index_amount
6228 
6229 
6230             /* Delete from the Intermediate table PN_INDEX_LEASE_TERMS_ALL */
6231 
6232 
6233             DELETE FROM pn_index_lease_terms_all ilt
6234             WHERE ilt.index_period_id = c_rec.index_period_id
6235             AND ilt.approved_flag <> c_payment_term_status_approved ;
6236 
6237             DELETE FROM pn_distributions_all
6238                   WHERE payment_term_id IN (SELECT payment_term_id
6239                                             FROM pn_payment_terms_all ppt
6240                                             WHERE ppt.index_period_id = c_rec.index_period_id
6241                                                AND ppt.status <> c_payment_term_status_approved);
6242 
6243             DELETE FROM pn_payment_terms_all ppt
6244                   WHERE ppt.index_period_id = c_rec.index_period_id
6245                     AND ppt.status <> c_payment_term_status_approved;
6246 
6247          --
6248          -- Printing the Headers of the report
6249          --
6250          fnd_message.set_name ('PN','PN_RICAL_CUR');
6251          l_message := '      '||fnd_message.get;
6252          fnd_message.set_name ('PN','PN_RICAL_ASS');
6253          l_message := l_message||'    '||fnd_message.get;
6254          fnd_message.set_name ('PN','PN_RICAL_INDX');
6255          l_message := l_message||'                  '||fnd_message.get;
6256          fnd_message.set_name ('PN','PN_RICAL_BAS');
6257          l_message := l_message||'       '||fnd_message.get;
6258          fnd_message.set_name ('PN','PN_RICAL_UCON');
6259          l_message := l_message||'  '||fnd_message.get;
6260          fnd_message.set_name ('PN','PN_RICAL_CON');
6261          l_message := l_message||'   '||fnd_message.get;
6262          put_output(l_message);
6263 
6264          l_message := NULL;
6265 
6266          fnd_message.set_name ('PN','PN_RICAL_BAS');
6267          l_message := '       '||fnd_message.get;
6268          fnd_message.set_name ('PN','PN_RICAL_DATE');
6269          l_message := l_message||'        '||fnd_message.get;
6270          fnd_message.set_name ('PN','PN_RICAL_REL');
6271          l_message := l_message||'        '||fnd_message.get;
6272          fnd_message.set_name ('PN','PN_RICAL_CHG');
6273          l_message := l_message||'   '||fnd_message.get;
6274          fnd_message.set_name ('PN','PN_RICAL_CHG');
6275          l_message := l_message||'  '||fnd_message.get;
6276          fnd_message.set_name ('PN','PN_RICAL_RENT_DUE');
6277          l_message := l_message||'   '||fnd_message.get;
6278          l_message := l_message||'   '||fnd_message.get;
6279          fnd_message.set_name ('PN','PN_RICAL_DUE');
6280          l_message := l_message||' '||fnd_message.get;
6281          put_output(l_message);
6282 
6283          put_output (
6284             '     ---------  ------------  -----------  ----------  ----------  ----------  ----------'
6285          );
6286 
6287          --  Print the Period Details
6288          --  format function will display 3 decimal places for all numbers
6289 
6290          put_output (
6291                LPAD (format (v_basis_amount, 2), 14, ' ')
6292             || LPAD (TO_CHAR (c_rec.assessment_date, 'DD-MON-RRRR'), 14, ' ')
6293             || LPAD (c_rec.relationship, 13, ' ')
6294             || LPAD (format (v_index_percent_change, 3), 13, ' ')
6295             || LPAD (format (c_rec.basis_percent_change, 3), 11, ' ')
6296             || LPAD (format (v_uncontrained_index_amount, 2), 12, ' ')
6297             || LPAD (format (v_constrained_rent_amount, 2), 12, ' ')
6298          );
6299 
6300            put_output ('.         ');
6301 
6302            fnd_message.set_name ('PN','PN_RICAL_PAYMENT');
6303            l_message := '         '||fnd_message.get;
6304            fnd_message.set_name ('PN','PN_RICAL_START');
6305            l_message := l_message||'      '||fnd_message.get;
6306            fnd_message.set_name ('PN','PN_RICAL_END');
6307            l_message := l_message||'        '||fnd_message.get;
6308            fnd_message.set_name ('PN','PN_RICAL_PAYMENT');
6309            l_message := l_message||'                     '||fnd_message.get;
6310            fnd_message.set_name ('PN','PN_RICAL_INDEX');
6311            l_message := l_message||'        '||fnd_message.get;
6312            fnd_message.set_name ('PN','PN_RICAL_NORZ');
6313            l_message := l_message||'        '||fnd_message.get;
6314            put_output(l_message);
6315 
6316            l_message := NULL;
6317 
6318            fnd_message.set_name ('PN','PN_RICAL_FREQ');
6319            l_message := '         '||fnd_message.get;
6320            fnd_message.set_name ('PN','PN_RICAL_DATE');
6321            l_message := l_message||'     '||fnd_message.get;
6322            fnd_message.set_name ('PN','PN_RICAL_DATE');
6323            l_message := l_message||'        '||fnd_message.get;
6324            fnd_message.set_name ('PN','PN_RICAL_AMT');
6325            l_message := l_message||'        '||fnd_message.get;
6326            fnd_message.set_name ('PN','PN_RICAL_STATUS');
6327            l_message := l_message||'      '||fnd_message.get;
6331            l_message := l_message||'      '||fnd_message.get;
6328            fnd_message.set_name ('PN','PN_RICAL_PAYMENT_TYPE');
6329            l_message := l_message||'        '||fnd_message.get;
6330            fnd_message.set_name ('PN','PN_RICAL_YES_NO');
6332            put_output(l_message);
6333 
6334            put_output (
6335          '         ---------  -----------  -----------  ----------  -----------  ------------------  ---------'
6336            );
6337 
6338            FOR l_rec IN get_lease_details(c_rec.lease_id) LOOP
6339                l_comm_date := l_rec.lease_commencement_date;
6340                l_term_date := l_rec.lease_termination_date;
6341                l_ext_end_dt := l_rec.lease_extension_end_date;
6342             END LOOP;
6343 
6344        FOR terms_rec IN get_extendable_terms(c_rec.index_period_id,l_term_date) LOOP
6345                l_terms_exist := TRUE;
6346        END LOOP;
6347 
6348        IF (NVL(fnd_profile.value('PN_IR_TERM_END_DATE'),'LEASE_END') <> 'PERIOD_END' OR
6349                (c_rec.basis_type <> c_basis_type_fixed AND
6350                 c_rec.reference_period <> c_ref_period_base_year))
6351        AND NVL(l_ext_end_dt, l_term_date) > l_term_date
6352        AND NOT(l_terms_exist)
6353        THEN
6354                g_create_terms_ext_period := 'Y';
6355        END IF;
6356 
6357 
6358             put_log ('Creating Payment Terms');
6359 
6360             create_payment_terms (
6361                p_lease_id                    => c_rec.lease_id
6362               ,p_index_lease_id              => c_rec.index_lease_id
6363               ,p_location_id                 => c_rec.location_id
6364               ,p_purpose_code                => c_rec.purpose
6365               ,p_index_period_id             => c_rec.index_period_id
6366               ,p_term_template_id            => c_rec.term_template_id
6367               ,p_relationship                => c_rec.relationship
6368               ,p_assessment_date             => c_rec.assessment_date
6369               ,p_basis_amount                => v_basis_amount
6370               ,p_basis_percent_change        => c_rec.basis_percent_change
6371               ,p_spread_frequency            => c_rec.spread_frequency
6372               ,p_rounding_flag               => c_rec.rounding_flag
6373               ,p_index_amount                => v_constrained_rent_amount
6374               ,p_index_finder_type           => c_rec.index_finder_method
6375               ,p_basis_type                  => c_rec.basis_type
6376               ,p_basis_start_date            => c_rec.basis_start_date
6377               ,p_basis_end_date              => c_rec.basis_end_date
6378               ,p_increase_on                 => c_rec.increase_on
6379               ,p_negative_rent_type          => c_rec.negative_rent_type
6380               ,p_carry_forward_flag          => c_rec.carry_forward_flag
6381               ,p_calculate_date              => l_calculate_date
6382               ,p_prorate_factor              => l_prorate_factor
6383               ,op_msg                        => v_msg
6384             );
6385 
6386             put_log ('v_msg ' || v_msg);
6387             pn_index_lease_common_pkg.append_msg (
6388                p_new_msg                     => v_msg
6389               ,p_all_msg                     => v_period_msg
6390             );
6391             v_msg := NULL;
6392 
6393             op_current_basis := v_basis_amount;
6394             op_unconstraint_rent_due := v_uncontrained_index_amount;
6395             op_constraint_rent_due := v_constrained_rent_amount;
6396             op_index_percent_change := v_index_percent_change;
6397             op_current_index_line_id := v_current_cpi_id;
6398             op_current_index_line_value := v_current_cpi_value;
6399             op_previous_index_line_id := v_previous_cpi_id;
6400             op_previous_index_line_value := v_previous_cpi_value;
6401             op_previous_index_amount := v_constrained_rent_amount;
6402             op_previous_asmt_date := c_rec.assessment_date;
6403             op_constraint_applied_amount := v_constraint_applied_amount;
6404             op_carry_forward_amount := v_carry_forward_amount;
6405             op_constraint_applied_percent := v_constraint_applied_percent;
6406             op_carry_forward_percent := v_carry_forward_percent;
6407 
6408          ELSE
6409             op_current_basis := c_rec.current_basis;
6410             op_unconstraint_rent_due := c_rec.unconstraint_rent_due;
6411             op_constraint_rent_due := c_rec.constraint_rent_due;
6412             op_index_percent_change := c_rec.index_percent_change;
6413             op_current_index_line_id := c_rec.current_index_line_id;
6414             op_current_index_line_value := c_rec.current_index_line_value;
6415             op_previous_index_line_id := c_rec.previous_index_line_id;
6416             op_previous_index_line_value := c_rec.previous_index_line_value;
6417             op_previous_index_amount := c_rec.constraint_rent_due;
6418             op_previous_asmt_date := c_rec.assessment_date;
6419             op_constraint_applied_amount := c_rec.constraint_applied_amount;
6420             op_carry_forward_amount := c_rec.carry_forward_amount;
6421             op_constraint_applied_percent := c_rec.constraint_applied_percent;
6422             op_carry_forward_percent := c_rec.carry_forward_percent;
6423 
6424             v_msg := 'PN_INDEX_INDEX_AMOUNT_EXISTS';
6425             pn_index_lease_common_pkg.append_msg (
6426                p_new_msg                     => v_msg
6427               ,p_all_msg                     => v_period_msg
6428             );
6429 
6433             p_new_msg                     => v_period_msg
6430          END IF; --C_REC.constraint_rent_due IS NULL
6431 
6432          pn_index_lease_common_pkg.append_msg (
6434            ,p_all_msg                     => v_all_msg
6435          );
6436          v_period_msg := NULL;
6437 
6438          END IF;
6439 
6440          /* create terms for extended period */
6441         FOR l_rec IN get_lease_details(c_rec.lease_id) LOOP
6442             l_comm_date := l_rec.lease_commencement_date;
6443             l_term_date := l_rec.lease_termination_date;
6444             l_ext_end_dt := l_rec.lease_extension_end_date;
6445          END LOOP;
6446 
6447     IF (NVL(fnd_profile.value('PN_IR_TERM_END_DATE'),'LEASE_END') <> 'PERIOD_END' OR
6448        (c_rec.basis_type <> c_basis_type_fixed AND
6449         c_rec.reference_period <> c_ref_period_base_year))
6450     AND NVL(l_ext_end_dt, l_term_date) > l_term_date
6451     AND NVL(fnd_profile.value('PN_RENT_INCREASE_TERM_END_DATE'),'END_LEASE') ='END_LEASE'
6452     THEN
6453        FOR terms_rec IN get_extendable_terms(c_rec.index_period_id,l_term_date) LOOP
6454                l_term_rec := terms_rec;
6455 
6456                IF NVL(terms_rec.normalize,'N') = 'N' THEN
6457 
6458                   l_schd_date := pn_schedules_items.Get_Schedule_Date (
6459                                       p_lease_id   => c_rec.lease_id,
6460                                       p_day        => terms_rec.schedule_day,
6461                                       p_start_date => l_term_date + 1,
6462                                       p_end_date   => l_ext_end_dt,
6463                                       p_freq       => pn_schedules_items.get_frequency(terms_rec.frequency_code)
6464                                  );
6465 
6466                   l_schd_day  := TO_NUMBER(TO_CHAR(l_schd_date,'DD'));
6467                   IF l_schd_day <> terms_rec.schedule_day THEN
6468                      l_term_rec.start_date      := l_term_date + 1;
6469                      l_term_rec.end_date        := l_ext_end_dt;
6470 
6471                      pn_schedules_items.Insert_Payment_Term(
6472                         p_payment_term_rec   => l_term_rec,
6473                         x_return_status      => l_return_status,
6474                         x_return_message     => op_msg);
6475 
6476                   ELSE
6477                       UPDATE pn_payment_terms_all
6478                       SET end_date          = l_ext_end_dt,
6479                          last_update_date  = SYSDATE,
6480                          last_updated_by   = fnd_global.user_id,
6481                          last_update_login = fnd_global.login_id
6482                       WHERE payment_term_id = terms_rec.payment_term_id;
6483                   END IF;
6484 
6485                ELSE
6486 
6487                   l_term_rec.normalize := 'N';
6488                   l_term_rec.start_date := l_term_date + 1;
6489                   l_term_rec.end_date   := l_ext_end_dt;
6490                   l_term_rec.index_norm_flag := 'Y';
6491                   l_term_rec.parent_term_id  := terms_rec.payment_term_id;
6492 
6493                   pn_schedules_items.Insert_Payment_Term(
6494                      p_payment_term_rec   => l_term_rec,
6495                      x_return_status      => l_return_status,
6496                      x_return_message     => op_msg);
6497 
6498                 END IF;
6499              END LOOP;
6500 
6501       END IF;
6502 
6503 
6504       END LOOP index_lease_period;
6505 
6506       fnd_message.set_name ('PN','PN_RICAL_MSG');
6507       put_output (fnd_message.get||' :');
6508 
6509       display_error_messages (ip_message_string => v_all_msg);
6510       op_msg := SUBSTR (v_all_msg, 1,   INSTR (   v_all_msg
6511                                                  || ',', ',')
6512                                  - 1);
6513 
6514       put_log('PN_INDEX_AMOUNT_PKG.calculate_period (-) PrvAmt: '||op_previous_index_amount
6515               ||', ConsAmt: '||op_constraint_applied_amount||', CFAmt: '||op_carry_forward_amount);
6516 
6517    END calculate_period;
6518 
6519 
6520 ------------------------------------------------------------------------
6521 -- PROCEDURE : calculate
6522 -- DESCRIPTION: This procedure will invoke the ff procedures:
6523 --                 - Calculate Basis Amount
6524 --                 - Calculate Index Percentage Change (if necessary)
6525 --
6526 -- HISTORY:
6527 -- 23-OCT-03  ftanudja  o fixed msg logging logic.3209774
6528 ------------------------------------------------------------------------
6529 
6530    PROCEDURE calculate (
6531       ip_index_lease_id          IN       NUMBER
6532      ,ip_index_lease_period_id   IN       NUMBER
6533      ,ip_recalculate             IN       VARCHAR2
6534      ,ip_commit                  IN       VARCHAR2
6535      ,op_msg                     OUT NOCOPY      VARCHAR2
6536    ) IS
6537       v_basis_amount                NUMBER;
6538       v_index_percent_change        NUMBER;
6539       v_uncontrained_index_amount   NUMBER;
6540       v_all_msg                     VARCHAR2 (4000);
6541       v_period_msg                  VARCHAR2 (1000);
6542       v_p_constrained_rent_amount   NUMBER;
6543       v_prev_index_amount           NUMBER;
6544       v_prev_asmt_date              DATE;
6545       v_current_cpi_value           NUMBER;
6549       v_index_lease_id              NUMBER;
6546       v_current_cpi_id              NUMBER;
6547       v_previous_cpi_value          NUMBER;
6548       v_previous_cpi_id             NUMBER;
6550       v_index_period_id             NUMBER;
6551       v_lease_id                    NUMBER;
6552       v_constraint_applied_amount   pn_index_lease_periods.constraint_applied_amount%type;
6553       v_carry_forward_amount        pn_index_lease_periods.carry_forward_amount%type;
6554       v_constraint_applied_percent  pn_index_lease_periods.constraint_applied_percent%type;
6555       v_carry_forward_percent       pn_index_lease_periods.carry_forward_percent%type;
6556       v_initial_basis               pn_index_leases.initial_basis%type;
6557       v_retain_initial_basis_flag   pn_index_leases.retain_initial_basis_flag%type;
6558       v_msg                         VARCHAR2(1000);
6559 
6560 
6561       CURSOR c1 (
6562          p_index_lease_id   IN   NUMBER
6563       ) IS
6564          SELECT   pil.index_lease_id
6565                  ,pilp.index_period_id
6566                  ,pil.lease_id
6567                  ,pil.retain_initial_basis_flag
6568                  ,pil.initial_basis
6569              FROM pn_index_leases_all pil, pn_index_lease_periods_all pilp
6570             WHERE pil.index_lease_id = pilp.index_lease_id
6571               AND pil.index_lease_id = p_index_lease_id
6572          ORDER BY pilp.line_number;
6573 
6574       CURSOR c2 (
6575          p_index_lease_id          IN   NUMBER
6576         ,p_index_lease_period_id   IN   NUMBER
6577       ) IS
6578          SELECT   pil.index_lease_id
6579                  ,pilp.index_period_id
6580                  ,pil.lease_id
6581                  ,pil.retain_initial_basis_flag
6582                  ,pil.initial_basis
6583              FROM pn_index_leases_all pil, pn_index_lease_periods_all pilp
6584             WHERE pil.index_lease_id = pilp.index_lease_id
6585               AND pil.index_lease_id = p_index_lease_id
6586               AND pilp.index_period_id = p_index_lease_period_id
6587          ORDER BY pilp.line_number;
6588 
6589 
6590    BEGIN
6591 
6592       v_all_msg := 'PN_INDEX_SUCCESS';
6593 
6594 
6595      /* for performance reasons, one of two cursors can be executed..
6596         cursor c1 is need when all periods of an index rent is processed (IP_INDEX_PERIOD_ID IS NULL)
6597         cursor c2 is need when all an individual period is processed */
6598 
6599 
6600       IF ip_index_lease_period_id IS NULL THEN
6601          OPEN c1 (ip_index_lease_id);
6602       ELSE
6603          OPEN c2 (ip_index_lease_id, ip_index_lease_period_id);
6604       END IF;
6605 
6606       LOOP
6607 
6608          IF c1%ISOPEN THEN
6609             FETCH c1 INTO v_index_lease_id, v_index_period_id,v_lease_id,v_retain_initial_basis_flag,v_initial_basis;
6610             EXIT WHEN c1%NOTFOUND;
6611          ELSE
6612             FETCH c2 INTO v_index_lease_id, v_index_period_id,v_lease_id,v_retain_initial_basis_flag,v_initial_basis;
6613             EXIT WHEN c2%NOTFOUND;
6614          END IF;
6615 
6616       /* Check if retain initial basis flag is set, if not re-calculate initial_basis */
6617 
6618          IF (v_initial_basis IS NULL OR (NVL(v_retain_initial_basis_flag,'N')='N')) THEN
6619                 calculate_initial_basis
6620                 (
6621                 p_index_lease_id => v_index_lease_id,
6622                 op_basis_amount  => v_initial_basis,
6623                 op_msg           => v_msg
6624                 );
6625 
6626              IF v_msg IS NULL THEN
6627                UPDATE pn_index_leases_all
6628                   SET initial_basis = v_initial_basis
6629                      ,last_update_date = SYSDATE
6630                      ,last_updated_by = NVL (fnd_profile.VALUE ('USER_ID'), 0)
6631                WHERE index_lease_id = v_index_lease_id;
6632              END IF;
6633          END IF;
6634 
6635          calculate_period (
6636             ip_index_lease_id             => v_index_lease_id
6637            ,ip_index_lease_period_id      => v_index_period_id
6638            ,ip_recalculate                => ip_recalculate
6639            ,op_current_basis              => v_basis_amount
6640            ,op_unconstraint_rent_due      => v_uncontrained_index_amount
6641            ,op_constraint_rent_due        => v_p_constrained_rent_amount
6642            ,op_index_percent_change       => v_index_percent_change
6643            ,op_current_index_line_id      => v_current_cpi_id
6644            ,op_current_index_line_value   => v_current_cpi_value
6645            ,op_previous_index_line_id     => v_previous_cpi_id
6646            ,op_previous_index_line_value  => v_previous_cpi_value
6647            ,op_previous_index_amount      => v_prev_index_amount
6648            ,op_previous_asmt_date         => v_prev_asmt_date
6649            ,op_constraint_applied_amount  => v_constraint_applied_amount
6650            ,op_carry_forward_amount       => v_carry_forward_amount
6651            ,op_constraint_applied_percent => v_constraint_applied_percent
6652            ,op_carry_forward_percent      => v_carry_forward_percent
6653            ,op_msg                        => v_period_msg
6654          );
6655 
6656          pn_index_lease_common_pkg.append_msg (
6657             p_new_msg                     => v_period_msg
6658            ,p_all_msg                     => v_all_msg
6659          );
6660 
6661          UPDATE pn_index_lease_periods_all
6665                ,index_percent_change = v_index_percent_change
6662             SET current_basis = v_basis_amount
6663                ,unconstraint_rent_due = v_uncontrained_index_amount
6664                ,constraint_rent_due = v_p_constrained_rent_amount
6666                ,current_index_line_id = v_current_cpi_id
6667                ,current_index_line_value = v_current_cpi_value
6668                ,previous_index_line_id = v_previous_cpi_id
6669                ,previous_index_line_value = v_previous_cpi_value
6670                ,constraint_applied_amount = v_constraint_applied_amount
6671                ,carry_forward_amount = v_carry_forward_amount
6672                ,constraint_applied_percent = v_constraint_applied_percent
6673                ,carry_forward_percent = v_carry_forward_percent
6674                ,last_update_date = SYSDATE
6675                ,last_updated_by = NVL (fnd_profile.VALUE ('USER_ID'), 0)
6676           WHERE index_period_id = v_index_period_id;
6677 
6678 
6679          v_prev_index_amount := v_p_constrained_rent_amount;
6680 
6681       END LOOP index_lease;
6682 
6683       IF ip_index_lease_period_id IS NULL THEN
6684          CLOSE c1;
6685       ELSE
6686          CLOSE c2;
6687       END IF;
6688 
6689 
6690      /*  only passback the first message.*/
6691 
6692       op_msg := SUBSTR (v_all_msg, 1,INSTR (   v_all_msg|| ',', ',')- 1);
6693 
6694 
6695     /* Issue COMMIT if required by calling program.
6696        Primarily used by index rent form.
6697        To avoid multiple save message appearing on the form. */
6698 
6699      IF NVL (ip_commit, 'N') = 'Y' THEN
6700         COMMIT;
6701      END IF;
6702 
6703 
6704   END calculate;
6705 
6706 
6707 -------------------------------------------------------------------------------
6708 -- PROCEDURE   : calculate_batch
6709 -- DESCRIPTION : This procedure is used by concurrent process that will
6710 --               allow users to choose on or more index leases to calculate and
6711 --               index rent amount for.
6712 -- HISTORY
6713 -- 25-MAR-04 ftanudja o Fixed csr il_recs p_location_code logic.
6714 -- 09-MAR-05 ftanudja o Used profile option 'PN_RECALC_INDEX_RENT'
6715 --                      for recalculate logic. #4212326.
6716 -- 15-SEP-05 pikhar   o replaced fnd_profile.value(PN_RECALC_INDEX_RENT)
6717 --                      with pn_mo_cache_utils.get_profile_value
6718 -- 25-NOV-05 pikhar   o Replaced pn_locations_all with pn_locations
6719 -- 15-DEC-05 pikhar   o replaced get_profile_value(PN_RECALC_INDEX_RENT) with
6720 --                      get_profile_value('RECALC_IR_ON_ACC_CHG_FLAG'
6721 -------------------------------------------------------------------------------
6722 
6723    PROCEDURE calculate_batch (
6724       errbuf                        OUT NOCOPY      VARCHAR2
6725      ,retcode                       OUT NOCOPY      VARCHAR2
6726      ,ip_index_lease_number_lower   IN       VARCHAR2
6727      ,ip_index_lease_number_upper   IN       VARCHAR2
6728      ,ip_assessment_date_lower      IN       VARCHAR2
6729      ,ip_assessment_date_upper      IN       VARCHAR2
6730      ,ip_lease_class                IN       VARCHAR2
6731      ,ip_main_lease_number          IN       VARCHAR2
6732      ,ip_location_code              IN       VARCHAR2
6733      ,ip_user_responsible           IN       VARCHAR2
6734      ,ip_recalculate                IN       VARCHAR2
6735    ) IS
6736       CURSOR il_recs (
6737          p_index_rent_number_lower   IN   VARCHAR2
6738         ,p_index_rent_number_upper   IN   VARCHAR2
6739         ,p_assessment_date_lower     IN   VARCHAR2
6740         ,p_assessment_date_upper     IN   VARCHAR2
6741         ,p_lease_class               IN   VARCHAR2
6742         ,p_main_lease_number         IN   VARCHAR2
6743         ,p_location_code             IN   VARCHAR2
6744         ,p_user_responsible          IN   VARCHAR2
6745         ) IS
6746          SELECT pil.index_lease_id
6747                ,pilp.index_period_id
6748                ,pl.lease_class_code
6749                ,pl.lease_num
6750                ,pil.abstracted_by
6751                ,pil.location_id
6752                ,pilp.assessment_date
6753                ,pil.index_lease_number
6754                ,pil.term_template_id
6755                ,pil.org_id
6756            FROM pn_leases_all pl, pn_index_leases pil, pn_index_lease_periods_all pilp
6757           WHERE pl.lease_id = pil.lease_id
6758             AND pil.index_lease_id = pilp.index_lease_id
6759             AND (pil.index_lease_number >= nvl(p_index_rent_number_lower,pil.index_lease_number))
6760             AND (pil.index_lease_number <= nvl(p_index_rent_number_upper,pil.index_lease_number))
6761             AND (pl.lease_num = nvl(p_main_lease_number,pl.lease_num))
6762             AND (pilp.assessment_date >= nvl(p_assessment_date_lower,pilp.assessment_date))
6763             AND ((nvl(pil.carry_forward_flag,'N') = 'N' and
6764                     pilp.assessment_date <= nvl(p_assessment_date_upper,pilp.assessment_date)) OR
6765                  (nvl(pil.carry_forward_flag,'N') in ('A','P') and
6766                   pilp.assessment_date <= nvl(get_max_assessment_dt(pil.index_lease_id,p_assessment_date_upper),
6767                                           pilp.assessment_date))
6768                 )
6769             AND (pl.lease_class_code = nvl(p_lease_class,pl.lease_class_code))
6770             AND (p_location_code is null OR pil.location_id IN
6771                  (SELECT location_id FROM pn_locations
6772                   START WITH location_code = p_location_code
6776                  p_user_responsible is null);
6773                   CONNECT BY PRIOR location_id = parent_location_id)
6774                 )
6775             AND (pil.abstracted_by = p_user_responsible OR
6777 
6778       v_msg                 VARCHAR2 (1000);
6779       l_pre_index_lease_id  NUMBER;
6780       l_err_flag            VARCHAR2(1);
6781       l_recalculate         VARCHAR2(1);
6782    BEGIN
6783 
6784       put_log('ip_index_lease_number_lower    '|| ip_index_lease_number_lower);
6785       put_log('ip_index_lease_number_upper    '|| ip_index_lease_number_upper);
6786       put_log('ip_assessment_date_lower  '     || ip_assessment_date_lower);
6787       put_log('ip_assessment_date_upper  '     || ip_assessment_date_upper);
6788       put_log('ip_lease_class          '       || ip_lease_class);
6789       put_log('ip_main_lease_number    '       || ip_main_lease_number);
6790       put_log('ip_location_id          '       || ip_location_code);
6791       put_log('ip_user_responsible     '       || ip_user_responsible);
6792       put_log('ip_recalculate          '       || ip_recalculate);
6793       put_log('Processing the Following Lease Periods:');
6794 
6795 
6796       FOR il_rec IN il_recs (
6797                        ip_index_lease_number_lower
6798                       ,ip_index_lease_number_upper
6799                       ,fnd_date.canonical_to_date(ip_assessment_date_lower)
6800                       ,fnd_date.canonical_to_date(ip_assessment_date_upper)
6801                       ,ip_lease_class
6802                       ,ip_main_lease_number
6803                       ,ip_location_code
6804                       ,ip_user_responsible --,ip_recalculate
6805                     )
6806       LOOP
6807 
6808          put_log( 'Lease ID: '|| il_rec.index_lease_id|| ' Period ID: '|| il_rec.index_period_id);
6809 
6810          IF il_rec.index_lease_id <> NVL(l_pre_index_lease_id,-9999) THEN
6811           l_err_flag := 'N';
6812           l_pre_index_lease_id := il_rec.index_lease_id;
6813 
6814           IF il_rec.term_template_id IS NOT NULL AND
6815              NOT pnp_util_func.validate_term_template(p_term_temp_id   => il_rec.term_template_id,
6816                                                       p_lease_cls_code => il_rec.lease_class_code) THEN
6817 
6818              l_err_flag := 'Y';
6819              fnd_message.set_name ('PN', 'PN_MISS_TERM_TEMP_DATA');
6820              put_output(fnd_message.get);
6821           END IF;
6822        END IF;
6823 
6824        IF nvl(pn_mo_cache_utils.get_profile_value('RECALC_IR_ON_ACC_CHG_FLAG',il_rec.org_id),'Y') = 'N' THEN
6825           l_recalculate := 'N';
6826        ELSE
6827           l_recalculate := ip_recalculate;
6828        END IF;
6829 
6830        IF l_err_flag = 'N' THEN
6831          calculate (
6832             ip_index_lease_id             => il_rec.index_lease_id
6833            ,ip_index_lease_period_id      => il_rec.index_period_id
6834            ,ip_recalculate                => l_recalculate
6835            ,op_msg                        => v_msg
6836          );
6837       END IF;
6838 
6839       END LOOP index_lease_period;
6840 
6841    END calculate_batch;
6842 
6843 -------------------------------------------------------------------------------
6844 -- PROCEDURE : update_index_hist_line
6845 -- DESCRIPTION: This procedure is by the index history window any time index
6846 --             history line is updated.
6847 --
6848 -------------------------------------------------------------------------------
6849    PROCEDURE update_index_hist_line (
6850       ip_index_history_line_id   IN       NUMBER
6851      ,ip_recalculate             IN       VARCHAR2
6852      ,op_msg                     OUT NOCOPY      VARCHAR2
6853    ) IS
6854       CURSOR index_periods (
6855          p_index_history_line_id   IN   NUMBER
6856       ) IS
6857          SELECT pilp.index_lease_id
6858                ,pilp.index_period_id
6859            FROM pn_index_lease_periods_all pilp
6860           WHERE (   pilp.previous_index_line_id = p_index_history_line_id
6861                  OR pilp.current_index_line_id = p_index_history_line_id
6862                 );
6863 
6864       v_msg   VARCHAR2 (1000);
6865    BEGIN
6866       v_msg := 'PN_NEW_INDEX_HIST_SUCCESS';
6867 
6868       --op_msg := v_msg;
6869 
6870 
6871 
6872       --
6873       -- pick index periods the that use the index_history_line_id
6874       -- either as current or previous index rent
6875       --
6876       <<index_rent_periods>>
6877       FOR ilp_rec IN index_periods (ip_index_history_line_id)
6878       LOOP
6879          --put_log (
6880          --   'Lease ID: '|| ilp_rec.index_lease_id || '   Period ID: ' || ilp_rec.index_period_id);
6881 
6882          --
6883          -- calculate index rent for this index rent period
6884          --
6885          calculate (
6886             ip_index_lease_id             => ilp_rec.index_lease_id
6887            ,ip_index_lease_period_id      => ilp_rec.index_period_id
6888            ,ip_recalculate                => ip_recalculate
6889            ,op_msg                        => v_msg
6890          );
6891       END LOOP index_rent_periods; --ilp_pay_rec
6892    END update_index_hist_line;
6893 
6894 
6895 -------------------------------------------------------------------------------
6896 -- PROCEDURE : update_index_hist_line_batch
6897 -- DESCRIPTION: This procedure is used by the index history window any time index
6901 -- 02-MAR-2007  Hareesha  o Bug #5909546 When the Base-index is updated in the
6898 --             history line is updated.  It will be submitted as a batch program
6899 --             by the form.
6900 --
6902 --                          index-history, update the base-index of impacted
6903 --                          RI agreements.
6904 -- 02-MAY-2007  Prabhakar o Bug #6027113. When Index History is modified,
6905 --                          only the base index of the impacted RI agreement
6906 --                          will be updated by checking the base_year and
6907 --                          modified index_date.
6908 -------------------------------------------------------------------------------
6909    PROCEDURE update_index_hist_line_batch (
6910       errbuf                OUT NOCOPY      VARCHAR2
6911      ,retcode               OUT NOCOPY      VARCHAR2
6912      ,ip_index_history_id   IN       NUMBER
6913      ,ip_recalculate        IN       VARCHAR2
6914    ) IS
6915       CURSOR index_hist_lines_modified (
6916          p_index_history_id   IN   NUMBER
6917       ) IS
6918          SELECT pihl.index_line_id
6919                ,pihl.index_figure
6920 	       ,pihl.index_date
6921            FROM pn_index_history_lines pihl
6922           WHERE pihl.updated_flag = 'Y'
6923             AND pihl.index_id = p_index_history_id;
6924 
6925       CURSOR index_periods (
6926          p_index_history_line_id   IN   NUMBER
6927       ) IS
6928          SELECT pilp.index_lease_id
6929                ,pilp.index_period_id
6930                ,pilp.previous_index_line_id
6931                ,pilp.current_index_line_id
6932                ,pilp.current_index_line_value
6933                ,pilp.previous_index_line_value
6934                ,pilp.constraint_rent_due
6935            FROM pn_index_lease_periods_all pilp
6936           WHERE (   pilp.previous_index_line_id = p_index_history_line_id
6937                  OR pilp.current_index_line_id = p_index_history_line_id
6938                 );
6939 
6940       v_msg                    VARCHAR2 (1000);
6941       v_current_cpi_value      NUMBER;
6942       v_previous_cpi_value     NUMBER;
6943       v_index_percent_change   NUMBER := null;   --  #Bug2102073
6944       v_new_index_figure       pn_index_history_lines.index_figure%TYPE;
6945       v_updated_index_date     pn_index_history_lines.index_date%TYPE;
6946 
6947    BEGIN
6948       put_log (   'ip_index_history_line_id     '
6949                || ip_index_history_id);
6950       put_log (   'ip_recalculate          '
6951                || ip_recalculate);
6952       v_msg := 'PN_NEW_INDEX_HIST_SUCCESS';
6953 
6954       --
6955       -- get all index history line that have been updated
6956       --
6957       <<index_history_lines>>
6958       FOR ihl_rec IN index_hist_lines_modified (ip_index_history_id)
6959       LOOP
6960          v_new_index_figure := ihl_rec.index_figure;
6961 	 v_updated_index_date := ihl_rec.index_date;
6962 
6963          --
6964          -- get index period lines that use the current index history line
6965          --
6966          <<index_rent_periods>>
6967          FOR ilp_rec IN index_periods (ihl_rec.index_line_id)
6968          LOOP
6969             put_log (
6970                   'Lease ID: '
6971                || ilp_rec.index_lease_id
6972                || '   Period ID: '
6973                || ilp_rec.index_period_id
6974                || '   Value: '
6975                || ihl_rec.index_figure
6976             );
6977 
6978             --
6979             -- checking which index value (current or previous) is going to be updated
6980             --
6981 
6982             -- for each period found,
6983             --  check if previous or current is being updated by looking at the
6984             --  id field.
6985             --  if it's being updated, then
6986 
6987             --
6988             -- check if the current cpi value is being updated
6989             --    if not, use existing value as cpi..
6990 
6991             IF ilp_rec.current_index_line_id = ihl_rec.index_line_id THEN
6992                v_current_cpi_value := v_new_index_figure;
6993             ELSE
6994                v_current_cpi_value := ilp_rec.current_index_line_value;
6995             END IF; --ilp_rec.current_index_line_id = ihl_rec.index_line_id
6996 
6997             --
6998             -- check if the previous cpi value is being updated
6999             --    if not, use existing value as cpi..
7000 
7001             IF ilp_rec.previous_index_line_id = ihl_rec.index_line_id THEN
7002                v_previous_cpi_value := v_new_index_figure;
7003             ELSE
7004                v_previous_cpi_value := ilp_rec.previous_index_line_value;
7005             END IF; --ilp_rec.previous_index_line_id = ihl_rec.index_line_id
7006 
7007             --
7008             -- if we have a current and  previous cpi value, calculate a new index change percentag
7009             --
7010 
7011             IF      v_current_cpi_value IS NOT NULL
7012                 AND v_previous_cpi_value IS NOT NULL THEN
7013                v_index_percent_change := ROUND (
7014                                               (  v_current_cpi_value
7015                                                - v_previous_cpi_value
7016                                               )
7017                                             / v_previous_cpi_value
7018                                             * 100
7019                                            ,2
7023             --
7020                                          );
7021             END IF;
7022 
7024             -- update the current index period record only if:
7025             --     contrained rent is null
7026             --     OR recalculate is set yes
7027             --
7028 
7029             IF    ilp_rec.constraint_rent_due IS NULL
7030                OR NVL (ip_recalculate, 'N') = 'Y' THEN
7031                UPDATE pn_index_lease_periods_all
7032                   SET index_percent_change = v_index_percent_change
7033                      ,current_index_line_value = v_current_cpi_value
7034                      ,previous_index_line_value = v_previous_cpi_value
7035                 WHERE index_period_id = ilp_rec.index_period_id;
7036             END IF;
7037                         v_index_percent_change := null;   -- Bug #2102073
7038             --
7039             -- calculate index rent for this index rent period
7040             --
7041 
7042             calculate (
7043                ip_index_lease_id             => ilp_rec.index_lease_id
7044               ,ip_index_lease_period_id      => ilp_rec.index_period_id
7045               ,ip_recalculate                => ip_recalculate
7046               ,op_msg                        => v_msg
7047             );
7048 
7049             UPDATE pn_index_leases_all
7050             SET base_index = v_new_index_figure
7051             WHERE index_lease_id = ilp_rec.index_lease_id
7052 	    AND base_year = v_updated_index_date;
7053 
7054          END LOOP index_rent_periods; --ilp_pay_rec
7055 
7056          --
7057          -- null out NOCOPY the update flag of history line
7058          -- this column is always updated by the index history
7059          -- form every time a record is updated.
7060          --
7061          UPDATE pn_index_history_lines
7062             SET updated_flag = NULL
7063           WHERE index_line_id = ihl_rec.index_line_id;
7064 
7065       END LOOP index_history_lines;
7066    END update_index_hist_line_batch;
7067 
7068 
7069 -------------------------------------------------------------------------------
7070 -- PROCEDURE : approve_index_pay_term
7071 -- DESCRIPTION: This procedure is called every time a index rent payment is term
7072 --              is approved.
7073 -- 09-Jul-01  psidhu o Added parameters err_msg and err_code to
7074 --                     pn_schedules.schedules_items.
7075 -- 14-AUG-06  pikhar o Conver the value of include_in_var_rent to NULL if it is
7076 --                     not equal to INCLUDE_RI
7077 -------------------------------------------------------------------------------
7078 
7079    PROCEDURE approve_index_pay_term (ip_lease_id            IN          NUMBER
7080                                     ,ip_index_pay_term_id   IN          NUMBER
7081                                     ,op_msg                 OUT NOCOPY  VARCHAR2
7082                                     ) IS
7083       v_msg                  VARCHAR2(1000);
7084       err_msg                VARCHAR2(2000);
7085       err_code               VARCHAR2(2000);
7086       l_include_in_var_rent  VARCHAR2(30);
7087 
7088    BEGIN
7089       pn_index_lease_common_pkg.chk_for_payment_reqd_fields (
7090          p_payment_term_id             => ip_index_pay_term_id
7091         ,p_msg                         => v_msg
7092       );
7093 
7094       IF v_msg IS NULL THEN
7095          v_msg := 'PN_INDEX_APPROVE_SUCCESS';
7096          --
7097          -- call api to create schedules and items
7098          --
7099 
7100          pn_schedules_items.schedules_items (
7101             errbuf                        => err_msg
7102            ,retcode                       => err_code
7103            ,p_lease_id                    => ip_lease_id
7104            ,p_lease_context               => 'ADD'
7105            ,p_called_from                 => 'IND'
7106            ,p_term_id                     => ip_index_pay_term_id
7107            ,p_term_end_dt                 => NULL
7108          );
7109 
7110          --
7111          -- update status of payment term record
7112          --
7113 
7114          select include_in_var_rent
7115          into l_include_in_var_rent
7116          from pn_payment_terms_all
7117          where payment_term_id = ip_index_pay_term_id;
7118 
7119          IF l_include_in_var_rent = 'INCLUDE_RI' THEN
7120             /* NBPs need to be recalculated */
7121             update pn_payment_terms_all
7122             set update_nbp_flag = 'Y'
7123             where payment_term_id = ip_index_pay_term_id;
7124          ELSE
7125             l_include_in_var_rent := NULL;
7126          END IF;
7127 
7128 
7129          UPDATE pn_payment_terms_all
7130             SET status = c_payment_term_status_approved
7131                ,include_in_var_rent = l_include_in_var_rent
7132                ,last_update_date = SYSDATE
7133                ,last_updated_by = NVL (fnd_profile.VALUE ('USER_ID'), 0)
7134                ,approved_by = NVL (fnd_profile.VALUE ('USER_ID'), 0)
7135           WHERE payment_term_id = ip_index_pay_term_id;
7136 
7137          --
7138          -- update status of records in pn_index_lease_terms
7139          --
7140          UPDATE pn_index_lease_terms_all
7141             SET APPROVED_FLAG = c_payment_term_status_approved
7142                ,last_update_date = SYSDATE
7143                ,last_updated_by = NVL (fnd_profile.VALUE ('USER_ID'), 0)
7144           WHERE rent_increase_term_id = ip_index_pay_term_id;
7148    END approve_index_pay_term;
7145       END IF;
7146 
7147       op_msg := v_msg;
7149 
7150 
7151 -------------------------------------------------------------------------------
7152 -- PROCEDURE : approve_index_pay_term_batch
7153 -- DESCRIPTION: This procedure is called by the mass index payment term
7154 --              approval concurrent index program.
7155 --
7156 -- NOTES: how the parameter ip_auto_find_sch_day plays a role when
7157 --        approved schedules exist
7158 --
7159 -- IF ip_auto_find_sch_day = 'Y' :
7160 --  a) record current schedule day => N
7161 --  b) find next available schedule day => X
7162 --  c) if found:
7163 --       update term sch day to X
7164 --       generate schedules and items
7165 --       update item transaction date to N
7166 --     else:
7167 --       error
7168 -- ELSE
7169 --   error
7170 --
7171 -- 20-Feb-2002  Pooja Sidhu o Added code to approve a payment term only if
7172 --                            main lease is in the final status. Fix for
7173 --                            bug# 2215729.
7174 -- 21-Feb-2002  Pooja Sidhu o Added check to approve a payment term if schedule
7175 --                            day of payment term does not overlap with an existing
7176 --                            approved schedule by calling procedure
7177 --                            pnt_payment_terms_pkg.check_approved_schedule_exists.
7178 --                            Fix for bug# 2235148.
7179 -- 13-Jul-2004  ftanudja    o Added parameter ip_auto_find_sch_day. #3701195.
7180 -- 18-Jan-2005  ftanudja    o Added batch commit capability. #4081821.
7181 -- 19-Jan-2005  ftanudja    o Fixed il_recs CSR for range queries. #4129147.
7182 -- 25-Nov-2005  pikhar      o Replaced pn_index_leases_all with pn_index_leases
7183 -- 09-JAN-07    lbala       o Removed call to get_schedule_date and auto creation
7184 --                            of shedules for M28 item# 11
7185 -------------------------------------------------------------------------------
7186 
7187    PROCEDURE approve_index_pay_term_batch (
7188       errbuf                        OUT NOCOPY      VARCHAR2
7189      ,retcode                       OUT NOCOPY      VARCHAR2
7190      ,ip_index_lease_number_lower   IN       VARCHAR2
7191      ,ip_index_lease_number_upper   IN       VARCHAR2
7192      ,ip_assessment_date_lower      IN       VARCHAR2
7193      ,ip_assessment_date_upper      IN       VARCHAR2
7194      ,ip_lease_class                IN       VARCHAR2
7195      ,ip_main_lease_number_lower    IN       VARCHAR2
7196      ,ip_main_lease_number_upper    IN       VARCHAR2
7197      ,ip_location_code              IN       VARCHAR2
7198      ,ip_user_responsible           IN       VARCHAR2
7199      ,ip_payment_start_date_lower   IN       VARCHAR2
7200      ,ip_payment_start_date_upper   IN       VARCHAR2
7201      ,ip_approve_normalize_only     IN       VARCHAR2
7202      ,ip_index_period_id            IN       VARCHAR2
7203      ,ip_payment_status             IN       VARCHAR2
7204      ,ip_auto_find_sch_day          IN       VARCHAR2
7205    ) IS
7206 
7207       v_msg                   VARCHAR2 (1000);
7208       v_counter               NUMBER          := 0;
7209       l_errmsg                VARCHAR2(2000);
7210       l_errmsg1               VARCHAR2(2000);
7211       l_return_status         VARCHAR2 (2) := NULL;
7212       l_nxt_schdate           DATE;
7213       l_day                   pn_payment_terms.schedule_day%TYPE;
7214       l_info                  VARCHAR2(1000);
7215       l_message               VARCHAR2(2000) := NULL;
7216       l_appr_count            NUMBER := 0;
7217       l_batch_size            NUMBER := 1000;
7218       l_errbuf                VARCHAR2(80);
7219       l_retcode               VARCHAR2(80);
7220       l_update_nbp_flag       VARCHAR2(1);
7221       l_dummy                 VARCHAR2(1);
7222       l_var_rent_id           NUMBER;
7223 
7224       CURSOR il_recs (
7225          p_index_rent_number_lower    IN   VARCHAR2
7226         ,p_index_rent_number_upper    IN   VARCHAR2
7227         ,p_assessment_date_lower      IN   VARCHAR2
7228         ,p_assessment_date_upper      IN   VARCHAR2
7229         ,p_lease_class                IN   VARCHAR2
7230         ,p_main_lease_number_lower    IN   VARCHAR2
7231         ,p_main_lease_number_upper    IN   VARCHAR2
7232         ,p_location_code              IN   VARCHAR2
7233         ,p_user_responsible           IN   VARCHAR2
7234         ,p_payment_start_date_lower   IN   VARCHAR2
7235         ,p_payment_start_date_upper   IN   VARCHAR2
7236         ,p_approve_normalize_only     IN   VARCHAR2
7237         ,p_index_period_id            IN   NUMBER
7238         ,p_payment_status             IN   VARCHAR2
7239       ) IS
7240          SELECT pil.lease_id
7241                ,pil.index_lease_id
7242                ,pilp.index_period_id
7243                ,ppt.payment_term_id
7244                ,pl.lease_class_code
7245                ,pl.lease_num
7246                ,pl.status lease_status
7247                ,pil.index_lease_number
7248                ,pil.abstracted_by
7249                ,pil.location_id
7250                ,pilp.assessment_date
7251                ,pilp.line_number
7252                ,ppt.start_date
7253                ,ppt.actual_amount
7254                ,ppt.frequency_code
7255                ,ppt.end_date
7256                ,ppt.index_term_indicator
7257                ,ppt.status
7258                ,DECODE (ppt.normalize, 'Y', 'NORMALIZE') "NORMALIZE"
7259                ,ppt.schedule_day
7263                ,pn_payment_terms_all ppt
7260            FROM pn_leases_all pl
7261                ,pn_index_leases pil
7262                ,pn_index_lease_periods_all pilp
7264           WHERE pl.lease_id = pil.lease_id
7265             AND pil.index_lease_id = pilp.index_lease_id
7266             AND pilp.index_period_id = ppt.index_period_id
7267             AND (pilp.index_period_id = p_index_period_id
7268                  OR p_index_period_id IS NULL)
7269             AND (pil.index_lease_number BETWEEN
7270                  nvl(p_index_rent_number_lower, pil.index_lease_number) AND
7271                  nvl(p_index_rent_number_upper, pil.index_lease_number))
7272             AND (pl.lease_num BETWEEN
7273                  nvl(p_main_lease_number_lower, pl.lease_num) AND
7274                  nvl(p_main_lease_number_upper, pl.lease_num))
7275             AND (pilp.assessment_date BETWEEN
7276                  nvl(fnd_date.canonical_to_date (p_assessment_date_lower), pilp.assessment_date) AND
7277                  nvl(fnd_date.canonical_to_date (p_assessment_date_upper), pilp.assessment_date))
7278             AND (pl.lease_class_code = p_lease_class
7279                  OR p_lease_class IS NULL)
7280             AND (pil.location_id = p_location_code
7281                  OR p_location_code IS NULL)
7282             AND (pil.abstracted_by = p_user_responsible
7283                  OR p_user_responsible IS NULL)
7284             AND (ppt.start_date BETWEEN
7285                  nvl(fnd_date.canonical_to_date (p_payment_start_date_lower), ppt.start_date) AND
7286                  nvl(fnd_date.canonical_to_date (p_payment_start_date_upper), ppt.start_date))
7287             AND ((p_approve_normalize_only = 'Y'
7288                   AND NVL (ppt.normalize, 'N') = 'Y')
7289                   OR p_approve_normalize_only = 'N')
7290             AND ppt.status = p_payment_status;
7291 
7292 
7293       CURSOR var_cur(p1_lease_id IN NUMBER)
7294       IS
7295          SELECT var_rent_id
7296          FROM pn_var_rents_all
7297          WHERE lease_id = p1_lease_id;
7298 
7299       CURSOR terms_cur (p1_lease_id IN NUMBER)
7300       IS
7301          SELECT UPDATE_NBP_FLAG
7302          FROM PN_PAYMENT_TERMS_ALL
7303          WHERE lease_id = p1_lease_id
7304          FOR UPDATE NOWAIT;
7305 
7306       CURSOR bkhd_exists_cur
7307       IS
7308          select 'x'
7309          FROM DUAL
7310          where exists (select BKHD_DEFAULT_ID
7311                        from pn_var_bkpts_head_all
7312                        where period_id IN (select PERIOD_ID
7313                                            FROM pn_var_periods_all
7314                                            where VAR_RENT_ID = l_var_rent_id)
7315                        AND BKHD_DEFAULT_ID IS NOT NULL);
7316 
7317    BEGIN
7318       put_log('pn_index_amount_pkg.approve_index_pay_term_batch (+) : ');
7319 
7320       put_log ('ip_index_lease_number_lower    '|| ip_index_lease_number_lower);
7321       put_log ('ip_index_lease_number_upper    '|| ip_index_lease_number_upper);
7322       put_log ('ip_assessment_date_lower  '     || ip_assessment_date_lower);
7323       put_log ('ip_assessment_date_upper  '     || ip_assessment_date_upper);
7324       put_log ('ip_lease_class          '       || ip_lease_class);
7325       put_log ('ip_main_lease_number_lower    ' || ip_main_lease_number_lower);
7326       put_log ('ip_main_lease_number_upper    ' || ip_main_lease_number_upper);
7327       put_log ('ip_location_id          '       || ip_location_code);
7328       put_log ('ip_user_responsible     '       || ip_user_responsible);
7329       put_log ('ip_payment_start_date_lower  '  || ip_payment_start_date_lower);
7330       put_log ('ip_payment_start_date_upper  '  || ip_payment_start_date_upper);
7331       put_log ('ip_approve_normalize_only  '    || ip_approve_normalize_only);
7332       put_log ('ip_index_period_id  '           || ip_index_period_id);
7333       put_log ('ip_payment_status  '            || ip_payment_status);
7334       put_log ('Processing the Following Lease Periods:');
7335 
7336       /* get all index rent payment terms to process */
7337 
7338       FOR il_rec IN il_recs (
7339                        ip_index_lease_number_lower
7340                       ,ip_index_lease_number_upper
7341                       ,ip_assessment_date_lower
7342                       ,ip_assessment_date_upper
7343                       ,ip_lease_class
7344                       ,ip_main_lease_number_lower
7345                       ,ip_main_lease_number_upper
7346                       ,ip_location_code
7347                       ,ip_user_responsible
7348                       ,ip_payment_start_date_lower
7349                       ,ip_payment_start_date_upper
7350                       ,ip_approve_normalize_only
7351                       ,ip_index_period_id
7352                       ,ip_payment_status
7353                     )
7354       LOOP
7355          v_counter :=   v_counter  +  1;
7356 
7357          put_output ('****************************************');
7358          fnd_message.set_name ('PN','PN_RICAL_PROC');
7359          put_output(fnd_message.get||'...');
7360          fnd_message.set_name ('PN','PN_RICAL_LSNO');
7361          fnd_message.set_token ('NUM', il_rec.index_lease_number);
7362          put_output(fnd_message.get);
7363          fnd_message.set_name ('PN','PN_RICAL_LS_PRD');
7364          fnd_message.set_token ('NUM', il_rec.line_number);
7368          fnd_message.set_token ('DATE', il_rec.assessment_date);
7365          fnd_message.set_token ('ID', il_rec.index_period_id);
7366          put_output(fnd_message.get);
7367          fnd_message.set_name ('PN','PN_RICAL_ASS_DATE');
7369          put_output(fnd_message.get);
7370          put_output ('****************************************');
7371 
7372          /* if main lease is in draft status disallow approval */
7373 
7374          IF nvl(il_rec.lease_status,'D') = 'D' THEN
7375             fnd_message.set_name('PN','PN_NO_APPR_TERM');
7376             l_errmsg := fnd_message.get;
7377             put_output('+----------------------------------------------------------+');
7378             put_output(l_errmsg);
7379             put_output('+----------------------------------------------------------+');
7380          ELSE
7381 
7382                l_info := ' approving payment term ID: '||il_rec.payment_term_id||' ';
7383                approve_index_pay_term (
7384                    ip_lease_id                   => il_rec.lease_id
7385                   ,ip_index_pay_term_id          => il_rec.payment_term_id
7386                   ,op_msg                        => v_msg);
7387 
7388 
7389                 --Recalculate Natural Breakpoint if any changes in Lease Payment Terms
7390 
7391                 l_update_nbp_flag := NULL;
7392                 l_dummy           := NULL;
7393                 FOR terms_rec IN terms_cur(p1_lease_id => il_rec.lease_id)
7394                 LOOP
7395                    IF terms_rec.UPDATE_NBP_FLAG = 'Y' THEN
7396                       l_update_nbp_flag := 'Y';
7397                       EXIT;
7398                    END IF;
7399                 END LOOP;
7400 
7401                 IF l_update_nbp_flag = 'Y' THEN
7402                    FOR var_rec in var_cur(p1_lease_id => il_rec.lease_id)
7403                    LOOP
7404 
7405                       l_var_rent_id := var_rec.var_rent_id;
7406 
7407                       OPEN bkhd_exists_cur;
7408                       FETCH bkhd_exists_cur INTO l_dummy;
7409                       CLOSE bkhd_exists_cur;
7410 
7411                       pn_var_natural_bp_pkg.build_bkpt_details_main(errbuf        => l_errbuf,
7412                                                                     retcode       => l_retcode,
7413                                                                     p_var_rent_id => var_rec.var_rent_id);
7414 
7415                       IF l_dummy IS NOT NULL THEN
7416                          pn_var_defaults_pkg.create_setup_data (x_var_rent_id => var_rec.var_rent_id);
7417                       END IF;
7418 
7419                       pnp_debug_pkg.log('Updated Natural Breakpoints for VR - '||var_rec.var_rent_id);
7420 
7421 
7422                    END LOOP;
7423 
7424                    UPDATE pn_payment_terms_all
7425                    SET UPDATE_NBP_FLAG = NULL
7426                    WHERE lease_id = il_rec.lease_id;
7427 
7428 
7429 
7430                 END IF;
7431 
7432                 -- Finished Recalculating Natural Breakpoint if any changes in Lease Payment Terms
7433 
7434          END IF;  --nvl(il_rec.lease_status,'D') = 'D'
7435 
7436          l_message := NULL;
7437          fnd_message.set_name ('PN','PN_RICAL_PAYMENT');
7438          l_message := '         '||fnd_message.get;
7439          fnd_message.set_name ('PN','PN_RICAL_START');
7440          l_message := l_message||'      '||fnd_message.get;
7441          fnd_message.set_name ('PN','PN_RICAL_END');
7442          l_message := l_message||'        '||fnd_message.get;
7443          fnd_message.set_name ('PN','PN_RICAL_PAYMENT');
7444          l_message := l_message||'                     '||fnd_message.get;
7445          /*fnd_message.set_name ('PN','PN_RICAL_INDEX');
7446          l_message := l_message||'                        '||fnd_message.get; */
7447          fnd_message.set_name ('PN','PN_RICAL_NORZ');
7448          l_message := l_message||'                          '||fnd_message.get;
7449          put_output(l_message);
7450 
7451          l_message := NULL;
7452 
7453          fnd_message.set_name ('PN','PN_RICAL_FREQ');
7454          l_message := '         '||fnd_message.get;
7455          fnd_message.set_name ('PN','PN_RICAL_DATE');
7456          l_message := l_message||'    '||fnd_message.get;
7457 	 fnd_message.set_name ('PN','PN_RICAL_DATE');
7458          l_message := l_message||'         '||fnd_message.get;
7459          fnd_message.set_name ('PN','PN_RICAL_AMT');
7460          l_message := l_message||'       '||fnd_message.get;
7461          fnd_message.set_name ('PN','PN_RICAL_STATUS');
7462          l_message := l_message||'       '||fnd_message.get;
7463          fnd_message.set_name ('PN','PN_RICAL_PAYMENT_TYPE');
7464          l_message := l_message||'      '||fnd_message.get;
7465         /* fnd_message.set_name ('PN','PN_RICAL_YES_NO');
7466          l_message := l_message||'       '||fnd_message.get;*/
7467          put_output(l_message);
7468 
7469          put_output (
7470          '         ---------  -----------  -----------  ----------  -----------  ------------------  ------------'
7471                     );
7472          put_output ('.         ');
7473          put_output (
7474                LPAD (il_rec.frequency_code, 18, ' ')
7475             || LPAD (il_rec.start_date, 13, ' ')
7476             || LPAD (il_rec.end_date, 13, ' ')
7477             || LPAD (format (il_rec.actual_amount, 2), 12, ' ')
7481          put_output ('.         ');
7478             || LPAD (il_rec.status, 13, ' ')
7479             || LPAD (il_rec.index_term_indicator, 20, ' ')
7480             || LPAD (il_rec.NORMALIZE, 11, ' '));
7482          display_error_messages (ip_message_string => v_msg);
7483 
7484       END LOOP;
7485 
7486       IF v_counter = 0 THEN
7487          fnd_message.set_name ('PN','PN_RICAL_MSG');
7488          put_output (fnd_message.get||' :');
7489          display_error_messages (ip_message_string => 'PN_INDEX_NO_PAYT_TO_APPROVE');
7490       END IF;
7491 
7492 
7493 
7494       put_log('pn_index_amount_pkg.approve_index_pay_term_batch (-) : ');
7495 
7496    END approve_index_pay_term_batch;
7497 
7498 
7499 -------------------------------------------------------------------------------
7500 -- PROCEDURE  : process_currency_code
7501 -- DESCRIPTION: This procedure is called by the index rent form
7502 --              when the currency_code field is changed. Fix for
7503 --              bug# 2452909.
7504 --
7505 -------------------------------------------------------------------------------
7506 
7507    PROCEDURE process_currency_code (p_index_lease_id in number) IS
7508    l_msg1 varchar2(1000);
7509    l_msg2 varchar2(1000);
7510 
7511    BEGIN
7512 
7513     /* Delete from table pn_index_exclude_term */
7514 
7515      Delete pn_index_exclude_term_all
7516      where index_lease_id = p_index_lease_id;
7517 
7518     /* undo the periods */
7519 
7520      pn_index_rent_periods_pkg.undo_periods(
7521          p_index_lease_id => p_index_lease_id,
7522          p_msg => l_msg1);
7523 
7524     /* generate periods */
7525 
7526      pn_index_rent_periods_pkg.generate_periods(
7527          ip_index_lease_id => p_index_lease_id,
7528          op_msg => l_msg2);
7529 
7530 
7531    EXCEPTION
7532    when others then
7533    put_log('Error in pn_index_amount_pkg.process_currency_code :'||to_char(sqlcode)||' : '||sqlerrm);
7534    raise;
7535 
7536 END process_currency_code;
7537 
7538 
7539 -------------------------------------------------------------------------------
7540 -- PROCEDURE  : derive_cum_carry_forward
7541 -- DESCRIPTION: Derive the value of the column carry_forward_amount and
7542 --              carry_forward_percent of the period prior to the current period.
7543 --
7544 -------------------------------------------------------------------------------
7545   PROCEDURE derive_cum_carry_forward (
7546       p_index_lease_id    IN       NUMBER,
7547       p_assessment_date   IN       DATE,
7548       op_carry_forward_amount OUT NOCOPY NUMBER,
7549       op_carry_forward_percent OUT NOCOPY NUMBER) IS
7550   CURSOR csr_cum_carry_for IS
7551   SELECT pilp.carry_forward_amount,
7552          pilp.carry_forward_percent
7553   FROM pn_index_lease_periods_all pilp
7554   WHERE pilp.index_lease_id = p_index_lease_id
7555   AND pilp.assessment_date = (SELECT MAX (pilp.assessment_date)
7556                               FROM pn_index_lease_periods_all pilp
7557                               WHERE pilp.index_lease_id = p_index_lease_id
7558                               AND   pilp.assessment_date < p_assessment_date);
7559 
7560   BEGIN
7561 
7562   put_log ('pn_index_amount_pkg.derive_cum_carry_forward   (+) : ');
7563 
7564   OPEN csr_cum_carry_for;
7565   FETCH csr_cum_carry_for into op_carry_forward_amount,op_carry_forward_percent;
7566   CLOSE csr_cum_carry_for;
7567 
7568   put_log ('pn_index_amount_pkg.derive_cum_carry_forward   (-) :');
7569 
7570   EXCEPTION
7571   WHEN OTHERS then
7572   put_log ('derive_cum_carry_forward : Unable to derive previous periods carry forward amount :'
7573             || SQLERRM);
7574 
7575 
7576   END derive_cum_carry_forward;
7577 
7578   -----------------------------------------------------------------------------
7579   -- FUNCTION   : derive_prev_negative_rent
7580   -- DESCRIPTION: If the negative rent option for the index rent agreement
7581   --              is 'NEXT PERIOD' for the current period derive the negative
7582   --              unconstrained rent amounts of the previous periods.
7583   --
7584   --  17-APR-2007  Prabhakar o Bug : #5988076. The derivation of previous
7585   --                           negative rent was corrected.( see the Note.)
7586   --
7587   -----------------------------------------------------------------------------
7588 
7589  FUNCTION derive_prev_negative_rent (
7590       p_index_lease_id    IN       NUMBER
7591      ,p_assessment_date   IN       DATE)
7592   RETURN number
7593   IS
7594   CURSOR csr_negative_rent IS
7595   SELECT unconstraint_rent_due, constraint_rent_due
7596   FROM pn_index_lease_periods_all
7597   WHERE index_lease_id = p_index_lease_id
7598   AND assessment_date < p_assessment_date
7599   ORDER BY assessment_date desc;
7600 
7601   l_previous_negative_rent number := 0;
7602 
7603   BEGIN
7604 
7605   put_log ('pn_index_amount_pkg.derive_prev_negative_rent   (+) : ');
7606 
7607   /*
7608 
7609   Note : The previous sum of negative rents can be found out as
7610           "the sum of the all previous unconstrained rent-dues
7611            whose constrained rent due is greater than zero."
7612 
7613          The constrained rent due can be zero because of neagtive rent or
7614          zero percent change. For the periods whose Ri is not computed,
7615          default value of zero is taken.
7616 
7617   */
7618 
7619   for rec_negative_rent in csr_negative_rent
7620   loop
7621 
7622      exit when rec_negative_rent.constraint_rent_due is not null and rec_negative_rent.constraint_rent_due > 0;
7623      l_previous_negative_rent := nvl(rec_negative_rent.unconstraint_rent_due,0) + l_previous_negative_rent;
7624 
7625   end loop;
7626 
7627   put_log ('pn_index_amount_pkg.derive_prev_negative_rent   (-) :');
7628 
7629   RETURN l_previous_negative_rent;
7630 
7631   END derive_prev_negative_rent;
7632 
7633   -----------------------------------------------------------------------------
7634   -- FUNCTION   : get_increase_over_constraint
7635   -- DESCRIPTION:
7636   --
7637   -----------------------------------------------------------------------------
7638 
7639   FUNCTION get_increase_over_constraint (
7640       p_carry_forward_flag     IN VARCHAR2,
7641       p_constraint_amount      IN NUMBER,
7642       p_unconstrained_rent     IN NUMBER,
7643       p_constrained_rent       IN NUMBER)
7644   RETURN number
7645   IS
7646   BEGIN
7647 
7648   if nvl(p_carry_forward_flag,'N') = 'Y' and
7649      p_constraint_amount is not null then
7650 
7651      if p_unconstrained_rent > p_constrained_rent  then
7652         return (p_unconstrained_rent - p_constrained_rent);
7653      else
7654         return 0;
7655      end if;
7656   else
7657      return null;
7658   end if;
7659 
7660   END get_increase_over_constraint;
7661 
7662 
7663   -----------------------------------------------------------------------------
7664   -- FUNCTION   : get_max_assessment_dt
7665   -- DESCRIPTION: get the maximum assessment date after the current assessment
7666   --              date where the calcuation has been done.
7667   --
7668   -----------------------------------------------------------------------------
7669 
7670   FUNCTION get_max_assessment_dt(p_index_lease_id IN NUMBER,
7671                                  p_assessment_date IN DATE)
7672   RETURN DATE
7673   IS
7674   CURSOR csr_get_dt
7675   IS
7676   SELECT max(assessment_date)
7677   FROM pn_index_lease_periods_all
7678   WHERE index_lease_id = p_index_lease_id
7679   AND assessment_date > p_assessment_date
7680   AND constraint_rent_due is not null;
7681 
7682   l_max_assmt_dt DATE := null;
7683 
7684   BEGIN
7685 
7686      OPEN csr_get_dt;
7687      FETCH csr_get_dt into l_max_assmt_dt;
7688      IF csr_get_dt%notfound THEN
7689         l_max_assmt_dt := p_assessment_date;
7690      END IF;
7691      CLOSE csr_get_dt;
7692 
7693      RETURN l_max_assmt_dt;
7694 
7695   END get_max_assessment_dt;
7696 
7697 
7698   -----------------------------------------------------------------------------
7699   -- PROCEDURE   : calculate_subsequent_periods
7700   -- DESCRIPTION:  This procedure is called by table handler
7701   --               pn_index_periods_pkg while calculating for an index lease
7702   --               period. If carry forward flag is 'Y' then calculate for
7703   --               all subsequent periods after the current period.
7704   --
7705   -----------------------------------------------------------------------------
7706 
7707   PROCEDURE calculate_subsequent_periods(p_index_lease_id  IN NUMBER,
7708                                          p_assessment_date IN DATE)
7709   IS
7710   CURSOR csr_get_periods is
7711   SELECT index_lease_id,
7712          index_period_id,
7713          assessment_date
7714   FROM  pn_index_lease_periods_all
7715   WHERE index_lease_id = p_index_lease_id
7716   AND assessment_date > p_assessment_date
7717   AND assessment_date <= get_max_assessment_dt(index_lease_id,p_assessment_date);
7718 
7719   v_msg VARCHAR2(1000);
7720 
7721   BEGIN
7722 
7723   put_log('pn_index_amount_pkg.calculate_subsequent_periods  (+) : ');
7724 
7725   FOR rec_get_periods in csr_get_periods
7726   LOOP
7727 
7728      put_log('Calculate_subsequent_periods : Assessment Date '|| rec_get_periods.assessment_date);
7729 
7730      calculate (
7731             ip_index_lease_id             => rec_get_periods.index_lease_id
7732            ,ip_index_lease_period_id      => rec_get_periods.index_period_id
7733            ,ip_recalculate                => 'Y'
7734            ,op_msg                        => v_msg );
7735 
7736      put_log('v_msg   : '||v_msg);
7737 
7738   END LOOP;
7739 
7740   put_log('pn_index_amount_pkg.calculate_subsequent_periods  (-)  : ');
7741 
7742   END calculate_subsequent_periods;
7743 
7744 
7745 END pn_index_amount_pkg;
7746