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