DBA Data[Home] [Help]

PACKAGE BODY: APPS.OKL_VARIABLE_INTEREST_PVT

Source


1 PACKAGE BODY OKL_VARIABLE_INTEREST_PVT AS
2 /* $Header: OKLRVARB.pls 120.79.12010000.10 2009/01/06 20:12:47 sgiyer ship $ */
3 
4     G_DEBUG           CONSTANT VARCHAR2(10) := OKL_DEBUG_PUB.CHECK_LOG_ENABLED;
5     G_INIT_NUMBER     CONSTANT  NUMBER := -9999;
6     G_API_TYPE        CONSTANT  VARCHAR2(4) := '_PVT';
7     G_REQUIRED_VALUE  CONSTANT  VARCHAR2(200) := OKL_API.G_REQUIRED_VALUE;
8     G_COL_NAME_TOKEN  CONSTANT  VARCHAR2(200) := OKL_API.G_COL_NAME_TOKEN;
9 	G_FIN_LINE_LTY_ID CONSTANT  NUMBER := 33;
10     rule_failed       EXCEPTION;
11 
12 
13     SUBTYPE vir_tbl_type IS OKL_VIR_PVT.vir_tbl_type;
14 
15     TYPE vrc_rec_type IS RECORD (
16        CONTRACT_NUMBER                  OKL_K_HEADERS_FULL_V.CONTRACT_NUMBER%TYPE
17       ,CONTRACT_ID                      OKL_K_HEADERS_FULL_V.ID%TYPE
18       ,START_DATE                       OKL_K_HEADERS_FULL_V.START_DATE%TYPE
19       ,END_DATE                         OKL_K_HEADERS_FULL_V.END_DATE%TYPE
20       ,INTEREST_CALCULATION_BASIS       OKL_PRODUCT_PARAMETERS_V.INTEREST_CALCULATION_BASIS%TYPE
21 	  ,DAYS_IN_A_MONTH_CODE             OKL_K_RATE_PARAMS.DAYS_IN_A_MONTH_CODE%TYPE
22 	  ,DAYS_IN_A_YEAR_CODE              OKL_K_RATE_PARAMS.DAYS_IN_A_YEAR_CODE%TYPE
23 	  ,RATE_CHANGE_VALUE                OKL_K_RATE_PARAMS.RATE_CHANGE_VALUE%TYPE
24 	  ,PROCESS_STATUS                   VARCHAR2(1));
25 
26     TYPE vrc_tbl_type IS TABLE OF vrc_rec_type INDEX BY BINARY_INTEGER;
27 
28     g_vir_tbl                     vir_tbl_type;
29     g_vir_tbl_counter             NUMBER;
30     g_vpb_tbl                     vpb_tbl_type;
31     g_vpb_tbl_counter             NUMBER := 0;
32     g_to_date                     DATE;
33     g_no_of_contracts_processed   NUMBER;
34     g_no_of_rejected_contracts    NUMBER;
35     g_no_of_successful_contracts  NUMBER;
36     -- varangan - Billing-Inline changes - Bug#5898792 - New constant added -Begin
37     -- sosharma changed the the value from STREAMS to VARIABLE_RATE
38     G_SOURCE_BILLING_TRX    CONSTANT VARCHAR2(200) :='VARIABLE_RATE';
39     -- varangan - Billing-Inline changes - Bug#5898792 - New constant added -End
40 
41 --Bug# 7277007
42 TYPE rpt_summary_rec_type IS RECORD (
43   total_contract_num_success   NUMBER
44  ,total_contract_num_error     NUMBER);
45 
46 TYPE rpt_summary_tbl_type IS TABLE OF rpt_summary_rec_type INDEX BY VARCHAR2(30);
47 g_rpt_summary_tbl         rpt_summary_tbl_type;
48 
49 TYPE error_msg_tbl_type is TABLE OF VARCHAR2(2000) INDEX BY BINARY_INTEGER;
50 
51 TYPE rpt_error_rec_type IS RECORD (
52   contract_number             okc_k_headers_b.contract_number%TYPE
53  ,product_name                okl_products.name%TYPE
54  ,interest_calc_basis         fnd_lookup_values.lookup_code%TYPE
55  ,last_int_calc_date          DATE
56  ,error_msg_tbl               error_msg_tbl_type);
57 
58 TYPE rpt_error_tbl_type IS TABLE OF rpt_error_rec_type INDEX BY BINARY_INTEGER;
59 g_rpt_error_tbl         rpt_error_tbl_type;
60 g_rpt_error_tbl_counter BINARY_INTEGER := 0;
61 
62 TYPE rpt_success_rec_type IS RECORD (
63    contract_id                okc_k_headers_b.id%TYPE
64   ,contract_number            okc_k_headers_b.contract_number%TYPE
65   ,days_in_a_month_code       okl_k_rate_params.days_in_a_month_code%TYPE
66   ,days_in_a_year_code        okl_k_rate_params.days_in_a_year_code%TYPE);
67 
68 TYPE rpt_success_tbl_type IS TABLE OF rpt_success_rec_type INDEX BY BINARY_INTEGER;
69 
70 TYPE rpt_success_icb_tbl_type IS TABLE OF rpt_success_tbl_type INDEX BY VARCHAR2(30);
71 
72 g_rpt_success_icb_tbl         rpt_success_icb_tbl_type;
73 --Bug# 7277007
74 
75 FUNCTION set_value_null(p_value_in IN VARCHAR2) RETURN VARCHAR2 IS
76 BEGIN
77   IF (p_value_in = OKL_API.G_MISS_CHAR) THEN
78     RETURN NULL;
79   END IF;
80   RETURN p_value_in;
81 END;
82 
83 FUNCTION set_value_null(p_value_in IN DATE) RETURN DATE IS
84 BEGIN
85   IF (p_value_in = OKL_API.G_MISS_DATE) THEN
86     RETURN NULL;
87   END IF;
88   RETURN p_value_in;
89 END;
90 
91 FUNCTION set_value_null(p_value_in IN NUMBER) RETURN NUMBER IS
92 BEGIN
93   IF (p_value_in = OKL_API.G_MISS_NUM) THEN
94     RETURN NULL;
95   END IF;
96   RETURN p_value_in;
97 END;
98 
99 --get the payment start date of skip and stub payments
100 FUNCTION get_pay_level_start_date(p_kle_id IN NUMBER,
101                                   p_sequence IN NUMBER) RETURN DATE IS
102   l_start_date DATE := NULL;
103 
104   cursor l_start_date_csr(cp_kle_id IN NUMBER, cp_sequence IN NUMBER) IS select start_date from (
105   select rownum sequence, --this can replace the seq since seq num is not stored by authoring
106     A.* from
107     (Select sll.id,
108            styp.code payment_type,
109            sll.object1_id1        Pay_freq,
110            sll.rule_information1  seq,
111            fnd_date.canonical_to_date(sll.rule_information2) start_date,
112            sll.rule_information3  number_periods,
113            sll.rule_information4  tuoms_per_period,
114            sll.rule_information6  amount,
115            sll.rule_information7  stub_days,
116            sll.rule_information8  stub_amount,
117            sll.rule_information10 advance_or_arrears,
118            sll.rule_information13 rate,
119            rgp.cle_id             cle_id
120     from   okc_rules_b sll,
121            okc_rules_b slh,
122            okl_strm_type_v styp,
123            okc_rule_groups_b rgp
124     where  to_number(sll.object2_id1) = slh.id
125     and    sll.rule_information_category = 'LASLL'
126     and    sll.dnz_chr_id  =  rgp.dnz_chr_id
127     and    sll.rgp_id      = rgp.id
128     and    slh.rule_information_category = 'LASLH'
129     and    slh.dnz_chr_id  =  rgp.dnz_chr_id
130     and    slh.rgp_id      = rgp.id
131     and    slh.object1_id1 = styp.id
132     and    rgp.rgd_code    = 'LALEVL'
133     and    rgp.cle_id      = cp_kle_id
134     order by rgp.cle_id
135     , fnd_date.canonical_to_date(sll.rule_information2)) A
136   )
137   where sequence = cp_sequence;
138 
139 BEGIN
140   OPEN l_start_date_csr (p_kle_id, p_sequence);
141   FETCH l_start_date_csr INTO l_start_date;
142   CLOSE l_start_date_csr;
143 
144   return l_start_date;
145 END;
146 
147 --get the start date, stub amount and stub days for a stub payment
148 FUNCTION get_stub_info(p_kle_id IN NUMBER,
149                        p_start_date IN DATE,
150                        x_stub_start_date OUT NOCOPY DATE,
151                        x_stub_days OUT NOCOPY NUMBER,
152                        x_stub_amount OUT NOCOPY NUMBER) RETURN VARCHAR2 IS
153   l_stub_start_date DATE;
154   l_stub_days NUMBER;
155   l_stub_amount NUMBER;
156 
157   CURSOR l_stub_csr(cp_kle_id IN NUMBER, cp_start_date IN DATE) IS
158   Select   fnd_date.canonical_to_date(sll.rule_information2) start_date,
159            sll.rule_information7  stub_days,
160            sll.rule_information8  stub_amount
161     from   okc_rules_b sll,
162            okc_rules_b slh,
163            okl_strm_type_v styp,
164            okc_rule_groups_b rgp
165     where  to_number(sll.object2_id1) = slh.id
166     and    sll.rule_information_category = 'LASLL'
167     and    sll.dnz_chr_id  =  rgp.dnz_chr_id
168     and    sll.rgp_id      = rgp.id
169     and    slh.rule_information_category = 'LASLH'
170     and    slh.dnz_chr_id  =  rgp.dnz_chr_id
171     and    slh.rgp_id      = rgp.id
172     and    slh.object1_id1 = styp.id
173     and    rgp.rgd_code    = 'LALEVL'
174     and    rgp.cle_id      = cp_kle_id
175     and    sll.rule_information7 IS NOT NULL
176     and    sll.rule_information8 IS NOT NULL
177     --and    fnd_date.canonical_to_date(sll.rule_information2) <= cp_start_date
178     order  by abs(fnd_date.canonical_to_date(sll.rule_information2) - cp_start_date) asc;
179 BEGIN
180   OPEN l_stub_csr(p_kle_id, p_start_date);
181   FETCH l_stub_csr INTO l_stub_start_date, l_stub_days, l_stub_amount;
182   CLOSE l_stub_csr;
183 
184   x_stub_start_date := l_stub_start_date;
185   x_stub_days := l_stub_days;
186   x_stub_amount := l_stub_amount;
187 
188   return '';
189 END;
190   ------------------------------------------------------------------------------
191   -- PROCEDURE print_line
192   --
193   --  This procedure prints message
194   --
195   -- Calls:
196   -- Called By:
197   ------------------------------------------------------------------------------
198 
199 PROCEDURE print_line (p_message IN VARCHAR2) IS
200 BEGIN
201   FND_FILE.PUT_LINE (FND_FILE.OUTPUT, p_message);
202 EXCEPTION
203   WHEN OTHERS THEN
204     FND_FILE.PUT_LINE (FND_FILE.OUTPUT, '** EXCEPTION IN print_line: '||SQLERRM);
205 END print_line;
206 
207   ------------------------------------------------------------------------------
208   -- PROCEDURE print
209   --
210   --  This procedure prints message
211   --
212   -- Calls:
213   -- Called By:
214   ------------------------------------------------------------------------------
215 /* Included this procedure to avoid GSCC error file.sql.26 */
216 PROCEDURE print(p_message IN VARCHAR2) IS
217 BEGIN
218   FND_FILE.PUT(FND_FILE.OUTPUT, p_message);
219 EXCEPTION
220   WHEN OTHERS THEN
221     FND_FILE.PUT_LINE (FND_FILE.OUTPUT, '** EXCEPTION IN print_line: '||SQLERRM);
222 END print;
223 
224   ------------------------------------------------------------------------------
225   -- PROCEDURE print_debug
226   --
227   --  This procedure prints message
228   --
229   -- Calls:
230   -- Called By:
231   ------------------------------------------------------------------------------
232 
233 PROCEDURE print_debug (p_message IN VARCHAR2) IS
234 BEGIN
235 --  IF ( G_DEBUG = 'Y' ) THEN
236     FND_FILE.PUT_LINE (FND_FILE.LOG, p_message);
237     --OKL_DEBUG_PUB.logmessage(p_message, 25);
238 --    dbms_output.put_line(p_message);
239 --  END IF;
240 EXCEPTION
241   WHEN OTHERS THEN
242     FND_FILE.PUT_LINE (FND_FILE.LOG, '** EXCEPTION IN print_line: '||SQLERRM);
243 END print_debug;
244 
245   ------------------------------------------------------------------------------
246   -- PROCEDURE print_error_message
247   --
248   --  This procedure prints error message in the request log file
249   --
250   -- Calls:
251   -- Called By:
252   ------------------------------------------------------------------------------
253 
254 PROCEDURE print_error_message (p_message IN VARCHAR2) IS
255 BEGIN
256     FND_FILE.PUT_LINE (FND_FILE.LOG, p_message);
257 EXCEPTION
258   WHEN OTHERS THEN
259     FND_FILE.PUT_LINE (FND_FILE.LOG, '** EXCEPTION IN print_line: '||SQLERRM);
260 END print_error_message;
261 
262   ------------------------------------------------------------------------------
263   -- PROCEDURE report_error
264   --
265   --  This procedure prints error messages
266   --
267   -- Calls:
268   -- Called By:
269   ------------------------------------------------------------------------------
270 
271   PROCEDURE Report_Error(p_contract_number     IN VARCHAR2,
272                          p_product_name        IN VARCHAR2,
273                          p_interest_calc_basis IN VARCHAR2,
274                          p_last_int_calc_date  IN DATE,
275                          x_msg_count OUT NOCOPY NUMBER,
276                          x_msg_data  OUT NOCOPY VARCHAR2
277                         ) IS
278 
279   x_msg_index_out NUMBER;
280   x_msg_out       VARCHAR2(2000);
281 
282   BEGIN
283 
284     okl_api.end_activity(
285                          X_msg_count => x_msg_count,
286                          X_msg_data  => x_msg_data
287                         );
288 
289      --Bug# 7277007
290      IF g_rpt_summary_tbl.EXISTS(p_interest_calc_basis)
291      THEN
292        g_rpt_summary_tbl(p_interest_calc_basis).total_contract_num_error :=
293          NVL(g_rpt_summary_tbl(p_interest_calc_basis).total_contract_num_error,0) + 1;
294      ELSE
295        g_rpt_summary_tbl(p_interest_calc_basis).total_contract_num_error := 1;
296      END IF;
297 
298     g_rpt_error_tbl_counter := g_rpt_error_tbl_counter + 1;
299     g_rpt_error_tbl(g_rpt_error_tbl_counter).contract_number      := p_contract_number;
300     g_rpt_error_tbl(g_rpt_error_tbl_counter).product_name         := p_product_name;
301     g_rpt_error_tbl(g_rpt_error_tbl_counter).interest_calc_basis  := p_interest_calc_basis;
302     g_rpt_error_tbl(g_rpt_error_tbl_counter).last_int_calc_date   := p_last_int_calc_date;
303     --Bug# 7277007
304 
305     FOR i in 1..x_msg_count
306     LOOP
307       FND_MSG_PUB.GET(
308                       p_msg_index     => i,
309                       p_encoded       => FND_API.G_FALSE,
310                       p_data          => x_msg_data,
311                       p_msg_index_out => x_msg_index_out
312                      );
313 
314       --Bug# 7277007
315       g_rpt_error_tbl(g_rpt_error_tbl_counter).error_msg_tbl(i) := SUBSTR(x_msg_data,1,2000);
316       print_debug('Error '||to_char(i)||': '||x_msg_data);
317 
318     END LOOP;
319     return;
320   EXCEPTION
321     WHEN OTHERS THEN
322       NULL;
323   END Report_Error;
324 ------------------------------------------------------------------------------
325     -- Start of Comments
326     -- Created By:       Ramesh Seela
327     -- Procedure Name    initialize_contract_params
328     -- Description:      This procedure initializes the package variables
329     -- Dependencies:
330     -- Parameters:
331     -- Version:          1.0
332     -- End of Comments
333 
334   ------------------------------------------------------------------------------
335   PROCEDURE initialize_contract_params (
336             p_api_version        IN  NUMBER,
337             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
338             x_return_status      OUT NOCOPY VARCHAR2,
339             x_msg_count          OUT NOCOPY NUMBER,
340             x_msg_data           OUT NOCOPY VARCHAR2,
341             p_contract_id        IN  NUMBER)   IS
342 
343   l_api_name                   CONSTANT    VARCHAR2(30) := 'INITIALIZE_CONTRACT_PARAMS';
344   l_api_version                CONSTANT    NUMBER       := 1.0;
345   init_ctr_params_failed       EXCEPTION;
346   l_interest_calculation_basis OKL_PRODUCT_PARAMETERS_V.interest_calculation_basis%TYPE;
347 
348 
349   Cursor contract_csr (p_contract_id NUMBER) IS
350       SELECT id,
351 	         deal_type,
352              start_date,
353              end_date,
354              currency_code,
355              pdt_id,
356              authoring_org_id
357       FROM   okl_k_headers_full_v
358       WHERE  id = p_contract_id;
359 
360   Cursor interest_params_csr (p_contract_id NUMBER) IS
361       SELECT interest_basis_code,
362              calculation_formula_id,
363              nvl(principal_basis_code, 'ACTUAL') principal_basis_code,
364              days_in_a_month_code,
365              days_in_a_year_code,
366              catchup_settlement_code
367       FROM   okl_k_rate_params
368       WHERE  khr_id = p_contract_id
369       AND    SYSDATE BETWEEN effective_from_date and nvl(effective_to_date, SYSDATE);
370 
371   Cursor product_params_csr (p_product_id NUMBER) IS
372       SELECT ppm.revenue_recognition_method,
373              ppm.interest_calculation_basis
374       FROM   okl_product_parameters_v ppm
375        WHERE ppm.id = p_product_id;
376 
377   BEGIN
378     x_return_status     := OKL_API.G_RET_STS_SUCCESS;
379 
380     print_debug('Executing procedure INITIALIZE_CONTRACT_PARAMS using following parameters : ');
381     print_debug(' p_contract_id : '|| p_contract_id );
382 
383     IF (G_CONTRACT_ID IS NULL OR G_CONTRACT_ID <> p_contract_id) THEN
384       OPEN contract_csr (p_contract_id);
385       FETCH contract_csr INTO G_CONTRACT_ID, G_DEAL_TYPE, G_CONTRACT_START_DATE, G_CONTRACT_END_DATE,
386 	                          G_CURRENCY_CODE, G_PRODUCT_ID, G_AUTHORING_ORG_ID;
387       IF (contract_csr%NOTFOUND) THEN
388         CLOSE contract_csr;
389         print_error_message('Contract cursor did not return records for contract ID :' || p_contract_id);
390         RAISE init_ctr_params_failed;
391       END IF;
392       CLOSE contract_csr;
393 
394       -- Fix for bug 6760186
395       OPEN product_params_csr (G_PRODUCT_ID);
396       FETCH product_params_csr INTO G_REVENUE_RECOGNITION_METHOD, l_interest_calculation_basis;
397       IF (product_params_csr%NOTFOUND) THEN
398         CLOSE product_params_csr;
399         print_error_message('Product Params cursor did not return records for product ID :' || G_PRODUCT_ID);
400         RAISE init_ctr_params_failed;
401       END IF;
402       CLOSE product_params_csr;
403 
404       OPEN interest_params_csr (p_contract_id);
405       FETCH interest_params_csr INTO G_INTEREST_BASIS_CODE, G_CALCULATION_FORMULA_ID, G_PRINCIPAL_BASIS_CODE,
406 	                          G_DAYS_IN_A_MONTH_CODE, G_DAYS_IN_A_YEAR_CODE, G_CATCHUP_SETTLEMENT_CODE;
407       IF (interest_params_csr%NOTFOUND) THEN
408         CLOSE interest_params_csr;
409         print_error_message('Interest Params cursor did not return records for contract ID :' || p_contract_id);
410         RAISE init_ctr_params_failed;
411       END IF;
412       CLOSE interest_params_csr;
413 
414       /* Moved this code before querying interest rate parameters --6760186 */
415       /*OPEN product_params_csr (G_PRODUCT_ID);
416       FETCH product_params_csr INTO G_REVENUE_RECOGNITION_METHOD, l_interest_calculation_basis;
417       IF (product_params_csr%NOTFOUND) THEN
418         CLOSE product_params_csr;
419         print_error_message('Product Params cursor did not return records for product ID :' || G_PRODUCT_ID);
420         RAISE init_ctr_params_failed;
421       END IF;
422       CLOSE product_params_csr;      */
423       -- 5047041
424       -- These changes are required to meet the requirements of code in procedure Interest_Date_Range
425       IF (G_INTEREST_CALCULATION_BASIS IS NULL OR G_INTEREST_CALCULATION_BASIS <> 'DAILY_INTEREST') THEN
426         G_INTEREST_CALCULATION_BASIS := l_interest_calculation_basis;
427       END IF;
428 
429       IF (l_interest_calculation_basis = 'FIXED' AND
430         G_REVENUE_RECOGNITION_METHOD = 'ACTUAL') THEN
431         G_INTEREST_CALCULATION_BASIS := 'DAILY_INTEREST';
432       END IF;
433       -- These changes are required to meet the requirements of code in procedure Interest_Date_Range
434     END IF;
435 
436 
437 
438         print_debug('Contract ID: '|| G_CONTRACT_ID);
439         print_debug('Authoring Org ID: '|| G_AUTHORING_ORG_ID);
440         print_debug('Product ID: '|| G_PRODUCT_ID);
441   	    print_debug('deal type :'|| G_DEAL_TYPE );
442 	    print_debug('Contract Start Date: '||G_CONTRACT_START_DATE);
443 	    print_debug('Contract End Date: '||G_CONTRACT_END_DATE);
444 	    print_debug('Currency code: '||G_CURRENCY_CODE);
445 	    print_debug('calculation basis : '|| G_INTEREST_CALCULATION_BASIS );
446 	    print_debug('revenue recognition method : '|| G_REVENUE_RECOGNITION_METHOD);
447 	    print_debug('Principal Balance : '|| G_CONTRACT_PRINCIPAL_BALANCE);
448 	    print_debug('Interest basis : '|| G_INTEREST_BASIS_CODE );
449 	    print_debug('Calculation Formula ID : '|| G_CALCULATION_FORMULA_ID);
450 	    print_debug('Principal Basis : '|| G_PRINCIPAL_BASIS_CODE);
451 	    print_debug('Days in a Month : '|| G_DAYS_IN_A_MONTH_CODE);
452 	    print_debug('Days in a Year  : '|| G_DAYS_IN_A_YEAR_CODE);
453 	    print_debug('Catchup Settlement Code  : '|| G_CATCHUP_SETTLEMENT_CODE);
454 
455 	    print_debug ('Exiting initialize_contract_params');
456 
457   EXCEPTION
458      WHEN init_ctr_params_failed THEN
459        print_error_message('init_ctr_params_failed Exception raised in procedure INITIALIZE_CONTRACT_PARAMS');
460        x_return_status := OKL_API.G_RET_STS_ERROR;
461 
462      WHEN OTHERS THEN
463        print_error_message('Exception raised in procedure INITIALIZE_CONTRACT_PARAMS');
464        Okl_Api.SET_MESSAGE(
465                p_app_name     => G_APP_NAME,
466                p_msg_name     => G_UNEXPECTED_ERROR,
467                p_token1       => G_SQLCODE_TOKEN,
468                p_token1_value => SQLCODE,
469                p_token2       => G_SQLERRM_TOKEN,
470                p_token2_value => SQLERRM);
471 
472        x_return_status := OKL_API.G_RET_STS_ERROR;
473 
474   END initialize_contract_params;
475 
476 ------------------------------------------------------------------------------
477     -- Start of Comments
478     -- Created By:       Ramesh Seela
479     -- Procedure Name    Get_contract_financed_amount
480     -- Description:      The function derives the financed amount at Header Level
481     -- Dependencies:
482     -- Parameters:
483     -- Version:          1.0
484     -- End of Comments
485 
486   ------------------------------------------------------------------------------
487   PROCEDURE get_contract_financed_amount (
488             p_api_version        IN  NUMBER,
489             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
490             x_return_status      OUT NOCOPY VARCHAR2,
491             x_msg_count          OUT NOCOPY NUMBER,
492             x_msg_data           OUT NOCOPY VARCHAR2,
493             p_contract_id        IN  NUMBER,
494 			x_principal_balance  OUT NOCOPY NUMBER) IS
495 
496   l_api_name               CONSTANT    VARCHAR2(30) := 'GET_CONTRACT_FINANCED_AMOUNT';
497   l_api_version            CONSTANT    NUMBER       := 1.0;
498   get_ctr_fin_amt_failed   EXCEPTION;
499 
500 
501   BEGIN
502     x_return_status     := OKL_API.G_RET_STS_SUCCESS;
503 
504     print_debug('Executing procedure GET_CONTRACT_FINANCED_AMOUNT using following parameters : ');
505     print_debug(' p_contract_id : '|| p_contract_id );
506     print_debug(' G_CONTRACT_ID : '|| G_CONTRACT_ID );
507     print_debug(' G_CONTRACT_PRINCIPAL_BALANCE : '|| G_CONTRACT_PRINCIPAL_BALANCE );
508 
509 
510     IF (G_CONTRACT_ID IS NULL OR
511         G_CONTRACT_PRINCIPAL_BALANCE IS NULL OR
512 	    G_CONTRACT_ID <> p_contract_id
513 	   ) THEN
514       -- Derive Principal Balance
515       Okl_Execute_Formula_Pub.EXECUTE(p_api_version          => 1.0,
516                                       p_init_msg_list        => OKL_API.G_FALSE,
517                                       x_return_status        => x_return_status,
518                                       x_msg_count            => x_msg_count,
519                                       x_msg_data             => x_msg_data,
520                                       p_formula_name         => 'CONTRACT_FINANCED_AMOUNT',
521                                       p_contract_id          => p_contract_id,
522                                       p_line_id              => NULL,
523                                       x_value               =>  x_principal_balance
524                                      );
525 
526       IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
527 	     print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE completed successfully');
528       ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
529   	     print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned unexpected error');
530   	     print_error_message ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned unexpected error');
531          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
532       ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
533 	     print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned exception');
534 	     print_error_message ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned exception');
535          RAISE get_ctr_fin_amt_failed;
536       END IF;
537 
538 	  G_CONTRACT_ID := p_contract_id;
539 	  G_CONTRACT_PRINCIPAL_BALANCE := x_principal_balance;
540 
541 	ELSE
542       x_principal_balance := G_CONTRACT_PRINCIPAL_BALANCE;
543 	END IF;
544 
545     print_debug('Contract Financed Amount : '|| x_principal_balance);
546 
547 
548   EXCEPTION
549      WHEN get_ctr_fin_amt_failed THEN
550        print_error_message('get_ctr_fin_amt_failed Exception raised in procedure GET_CONTRACT_FINANCED_AMOUNT');
551        x_return_status := OKL_API.G_RET_STS_ERROR;
552 
553      WHEN OTHERS THEN
554        print_error_message('Exception raised in procedure GET_CONTRACT_FINANCED_AMOUNT');
555        Okl_Api.SET_MESSAGE(
556                p_app_name     => G_APP_NAME,
557                p_msg_name     => G_UNEXPECTED_ERROR,
558                p_token1       => G_SQLCODE_TOKEN,
559                p_token1_value => SQLCODE,
560                p_token2       => G_SQLERRM_TOKEN,
561                p_token2_value => SQLERRM);
562 
563        x_return_status := OKL_API.G_RET_STS_ERROR;
564 
565   END get_contract_financed_amount;
566 
567 ------------------------------------------------------------------------------
568     -- Start of Comments
569     -- Created By:       Ramesh Seela
570     -- Procedure Name    Get_Line_financed_amount
571     -- Description:      The function derives the financed amount at Header Level
572     -- Dependencies:
573     -- Parameters:
574     -- Version:          1.0
575     -- End of Comments
576 
577   ------------------------------------------------------------------------------
578   PROCEDURE get_asset_financed_amount (
579             p_api_version        IN  NUMBER,
580             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
581             x_return_status      OUT NOCOPY VARCHAR2,
582             x_msg_count          OUT NOCOPY NUMBER,
583             x_msg_data           OUT NOCOPY VARCHAR2,
584             p_contract_id        IN  NUMBER,
585             p_line_id            IN  NUMBER,
586 			x_principal_balance  OUT NOCOPY NUMBER) IS
587 
588   l_api_name               CONSTANT    VARCHAR2(30) := 'GET_ASSET_FINANCED_AMOUNT';
589   l_api_version            CONSTANT    NUMBER       := 1.0;
590   get_asset_fin_amt_failed   EXCEPTION;
591 
592 
593   BEGIN
594     x_return_status     := OKL_API.G_RET_STS_SUCCESS;
595 
596     print_debug('Executing procedure GET_ASSET_FINANCED_AMOUNT using following parameters : ');
597     print_debug(' p_contract_id : '|| p_contract_id );
598     print_debug(' p_line_id : '|| p_line_id );
599     print_debug(' G_CONTRACT_ID : '|| G_CONTRACT_ID );
600     print_debug(' G_FIN_AST_LINE_ID : '|| G_FIN_AST_LINE_ID);
601     print_debug(' G_ASSET_PRINCIPAL_BALANCE : '|| G_ASSET_PRINCIPAL_BALANCE );
602 
603 
604     IF (G_CONTRACT_ID IS NULL OR
605 	    G_FIN_AST_LINE_ID IS NULL OR
606         G_ASSET_PRINCIPAL_BALANCE IS NULL OR
607 	    G_CONTRACT_ID <> p_contract_id OR
608 		G_FIN_AST_LINE_ID <> p_line_id
609 	   ) THEN
610       -- Derive Principal Balance
611       Okl_Execute_Formula_Pub.EXECUTE(p_api_version          => 1.0,
612                                       p_init_msg_list        => OKL_API.G_FALSE,
613                                       x_return_status        => x_return_status,
614                                       x_msg_count            => x_msg_count,
615                                       x_msg_data             => x_msg_data,
616                                       p_formula_name         => 'CONTRACT_FINANCED_AMOUNT',
617                                       p_contract_id          => p_contract_id,
618                                       p_line_id              => p_line_id,
619                                       x_value               =>  x_principal_balance
620                                      );
621 
622       IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
623 	     print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE completed successfully');
624       ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
625   	     print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned unexpected error');
626   	     print_error_message ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned unexpected error');
627          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
628       ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
629 	     print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned exception');
630 	     print_error_message ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned exception');
631          RAISE get_asset_fin_amt_failed;
632       END IF;
633 
634 	  G_CONTRACT_ID := p_contract_id;
635 	  G_FIN_AST_LINE_ID := p_line_id;
636 	  G_ASSET_PRINCIPAL_BALANCE := x_principal_balance;
637 
638 	ELSE
639       x_principal_balance := G_ASSET_PRINCIPAL_BALANCE;
640 	END IF;
641 
642     print_debug('Asset Line Financed Amount : '|| x_principal_balance);
643 
644 
645   EXCEPTION
646      WHEN get_asset_fin_amt_failed THEN
647        print_error_message('get_asset_fin_amt_failed Exception raised in procedure GET_ASSET_FINANCED_AMOUNT');
648        x_return_status := OKL_API.G_RET_STS_ERROR;
649 
650      WHEN OTHERS THEN
651        print_error_message('Exception raised in procedure GET_ASSET_FINANCED_AMOUNT');
652        Okl_Api.SET_MESSAGE(
653                p_app_name     => G_APP_NAME,
654                p_msg_name     => G_UNEXPECTED_ERROR,
655                p_token1       => G_SQLCODE_TOKEN,
656                p_token1_value => SQLCODE,
657                p_token2       => G_SQLERRM_TOKEN,
658                p_token2_value => SQLERRM);
659 
660        x_return_status := OKL_API.G_RET_STS_ERROR;
661 
662   END get_asset_financed_amount;
663   ------------------------------------------------------------------------------
664   -- PROCEDURE print_report
665   --
666   --  This procedure prints consolidated list of processed contracts
667   --
668   -- Calls:
669   -- Called By:
670   ------------------------------------------------------------------------------
671   --Bug# 7277007
672   PROCEDURE Print_Report(
673                          p_contract_number IN VARCHAR2
674                         ) IS
675 
676   l_operating_unit_name  HR_OPERATING_UNITS.name%TYPE;
677   l_currency_code        GL_LEDGERS_PUBLIC_V.currency_code%TYPE;
678   l_index                NUMBER;
679   l_rec_count            NUMBER;
680   l_no_of_days           NUMBER;
681   l_counter              NUMBER;
682   l_contract_number      OKC_K_HEADERS_B.contract_number%TYPE;
683   l_contract_number1     OKC_K_HEADERS_B.contract_number%TYPE;
684   l_contract_number2     OKC_K_HEADERS_B.contract_number%TYPE;
685   l_icb_counter          VARCHAR2(30);
686   l_days_in_a_month_code OKL_K_RATE_PARAMS.days_in_a_month_code%TYPE;
687   l_days_in_a_year_code  OKL_K_RATE_PARAMS.days_in_a_year_code%TYPE;
688   l_separator            VARCHAR2(1);
689   l_success_count        NUMBER;
690   l_rejected_count       NUMBER;
691 
692   CURSOR operating_unit_csr IS
693     SELECT hou.name,
694            book.currency_code
695     FROM   hr_operating_units hou,
696            GL_LEDGERS_PUBLIC_V book
697     WHERE  hou.set_of_books_id = book.ledger_id
698                   AND hou.ORGANIZATION_ID = mo_global.get_current_org_id();
699 
700   CURSOR var_int_params_csr (p_contract_id NUMBER) IS
701     SELECT vip.interest_calc_start_date,
702            vip.interest_calc_end_date,
703            vip.interest_rate,
704            OKL_ACCOUNTING_UTIL.format_amount(NVL(vip.principal_balance,0),chr.currency_code) principal_balance,
705            OKL_ACCOUNTING_UTIL.format_amount(NVL(vip.interest_amt,0),chr.currency_code) interest_amt,
706            vip.interest_calc_days
707     FROM   okl_var_int_params vip,
708            okc_k_headers_b chr
709     WHERE  chr.id = p_contract_id
710     AND    vip.khr_id = chr.id
711     AND    vip.request_id = g_request_id;
712 
713   BEGIN
714 
715     OPEN operating_unit_csr;
716     FETCH operating_unit_csr INTO l_operating_unit_name, l_currency_code;
717     IF ( operating_unit_csr % NOTFOUND) THEN
718        NULL;
719     END IF;
720     CLOSE operating_unit_csr;
721 
722     print_line('Create Receivables Variable Rate Invoices');
723     print_line('****************************************************************************************************');
724     print_line('Program Run Date: '||trunc(sysdate));
725     print_line('Operating Unit: '||l_operating_unit_name);
726     print_line('Contract Number: '||p_contract_number);
727     print_line('To Due Date: '||trunc(g_to_date));
728     print_line('****************************************************************************************************');
729     print_line(' ');
730     print_line(' ');
731     print_line('====================================================================================================');
732     print_line('Summary');
733     print_line(' ');
734     print_line(' _________________________________________________________________________');
735     print_line('|                               |           Number of contracts           |');
736     print_line('| Interest Calculation Basis    |   Processed |    Rejected |       Total |');
737     print_line('|_______________________________|_____________|_____________|_____________|');
738 
739     l_success_count := 0;
740     l_rejected_count := 0;
741     IF (g_rpt_summary_tbl.COUNT > 0) THEN
742       l_icb_counter := g_rpt_summary_tbl.FIRST;
743       LOOP
744 
745         l_success_count  := l_success_count + NVL(g_rpt_summary_tbl(l_icb_counter).total_contract_num_success,0);
746         l_rejected_count := l_rejected_count + NVL(g_rpt_summary_tbl(l_icb_counter).total_contract_num_error,0);
747 
748         print_line('| ' || RPAD(l_icb_counter,30,' ') || '|' ||
749                            LPAD(NVL(g_rpt_summary_tbl(l_icb_counter).total_contract_num_success,0),12,' ')  || ' |' ||
750                            LPAD(NVL(g_rpt_summary_tbl(l_icb_counter).total_contract_num_error,0),12,' ')    || ' |' ||
751                            LPAD((NVL(g_rpt_summary_tbl(l_icb_counter).total_contract_num_success,0) +
752                                  NVL(g_rpt_summary_tbl(l_icb_counter).total_contract_num_error,0)),12,' ')  || ' |');
753 
754         print_line('|_________________________________________________________________________|');
755 
756         EXIT WHEN l_icb_counter = g_rpt_summary_tbl.LAST;
757         l_icb_counter := g_rpt_summary_tbl.next(l_icb_counter);
758       END LOOP;
759     ELSE
760       print_line('|_________________________________________________________________________|');
761     END IF;
762 
763     print_line('| ' || RPAD('Total',30,' ') || '|' || LPAD(l_success_count,12,' ') || ' |' || LPAD(l_rejected_count,12,' ') || ' |');
764     print_line('|_______________________________|_____________|_____________|');
765 
766     print_line(' ');
767     print_line(' ');
768     print_line('====================================================================================================');
769 
770     IF (g_rpt_error_tbl.COUNT > 0) THEN
771       print_line('Rejected Contracts');
772       print_line('____________________________________________________________________________________________________');
773 
774       FOR i IN g_rpt_error_tbl.FIRST..g_rpt_error_tbl.LAST LOOP
775         print_line(' ');
776         print_line(RPAD('Contract Number: '||g_rpt_error_tbl(i).contract_number,77,' ')||
777                    'Product: '||g_rpt_error_tbl(i).product_name);
778 
779         IF LENGTH(g_rpt_error_tbl(i).contract_number) > 60 THEN
780           print_line(LPAD(SUBSTR(g_rpt_error_tbl(i).contract_number,61),' ',17));
781         END IF;
782 
783         print_line(RPAD('Interest Calculation Basis: '||g_rpt_error_tbl(i).interest_calc_basis,77,' ')||
784                    'Last Interest Calculation Date: '||g_rpt_error_tbl(i).last_int_calc_date);
785         print_line(' ');
786         print_line('Error Description: ');
787 
788         FOR j IN g_rpt_error_tbl(i).error_msg_tbl.FIRST..g_rpt_error_tbl(i).error_msg_tbl.LAST LOOP
789 
790           l_counter := 1;
791           WHILE l_counter <= LENGTH(g_rpt_error_tbl(i).error_msg_tbl(j))
792           LOOP
793             print_line(SUBSTR(g_rpt_error_tbl(i).error_msg_tbl(j),l_counter,105));
794             l_counter := l_counter + 105;
795           END LOOP;
796 
797         END LOOP;
798 
799         print_line(' ');
800         print_line('____________________________________________________________________________________________________');
801       END LOOP;
802 
803       print_line(' ');
804       print_line(' ');
805       print_line('====================================================================================================');
806     END IF;
807 
808     IF (g_rpt_success_icb_tbl.COUNT > 0) THEN
809 
810       print_line('Processed Contracts');
811       print_line(' ');
812 
813       l_icb_counter := g_rpt_success_icb_tbl.FIRST;
814       LOOP
815 
816         print_line('Interest Calculation Basis'||RPAD(' ',30,' ')||': '||l_icb_counter);
817         print_line(' ');
818         print_line(' '|| RPAD('_',151,'_'));
819 
820         print_line('|' || RPAD('Contract Number',40,' ') ||
821                   ' |' || RPAD('Days',15,' ') ||
822                   ' |' || RPAD('Interest',11,' ') ||
823                   ' |' || RPAD('Interest',11,' ') ||
824                   ' |' || LPAD('Interest',10,' ') ||
825                   ' |' || LPAD('Effective(%)',13,' ') ||
826                   ' |' || LPAD('Principal Amount',18,' ') ||
827                   ' |' || LPAD('Interest Amount',18,' ') ||
828                   ' |');
829 
830         print_line('|' || RPAD(' ',40,' ') ||
831                   ' |' || RPAD('Month/Year',15,' ') ||
832                   ' |' || RPAD('Start Date',11,' ') ||
833                   ' |' || RPAD('End Date',11,' ') ||
834                   ' |' || LPAD('Calc. Days',10,' ') ||
835                   ' |' || LPAD('Interest Rate',13,' ') ||
836                   ' |' || LPAD(' ',18,' ') ||
837                   ' |' || LPAD(' ',18,' ') ||
838                   ' |');
839 
840         print_line('|' || RPAD('_',151,'_') || '|');
841 
842         FOR i IN  g_rpt_success_icb_tbl(l_icb_counter).FIRST..g_rpt_success_icb_tbl(l_icb_counter).LAST LOOP
843 
844           l_contract_number  := g_rpt_success_icb_tbl(l_icb_counter)(i).contract_number;
845           l_contract_number1 := NULL;
846           l_contract_number2 := NULL;
847           IF LENGTH(l_contract_number) > 40 THEN
848             l_contract_number1 := SUBSTR(l_contract_number,41,40);
849             l_contract_number2 := SUBSTR(l_contract_number,81,40);
850           END IF;
851 
852           l_days_in_a_month_code := g_rpt_success_icb_tbl(l_icb_counter)(i).days_in_a_month_code;
853           l_days_in_a_year_code  := g_rpt_success_icb_tbl(l_icb_counter)(i).days_in_a_year_code;
854           l_separator            := '/';
855 
856           FOR var_int_param_rec IN var_int_params_csr(g_rpt_success_icb_tbl(l_icb_counter)(i).contract_id)
857           LOOP
858 
859             print_line('|' || RPAD(l_contract_number,40,' ') ||
860                       ' |' || LPAD(l_days_in_a_month_code,7,' ') || l_separator || RPAD(l_days_in_a_year_code,7,' ') ||
861                       ' |' || RPAD(TO_CHAR(var_int_param_rec.interest_calc_start_date,'DD-MON-RRRR'),11,' ') ||
862                       ' |' || RPAD(TO_CHAR(var_int_param_rec.interest_calc_end_date,'DD-MON-RRRR'),11,' ') ||
863                       ' |' || LPAD(NVL(var_int_param_rec.interest_calc_days,0),10,' ') ||
864                       ' |' || LPAD(NVL(var_int_param_rec.interest_rate,0),13,' ') ||
865                       ' |' || LPAD(NVL(var_int_param_rec.principal_balance,0),18,' ') ||
866                       ' |' || LPAD(NVL(var_int_param_rec.interest_amt,0),18,' ') ||
867                       ' |');
868 
869             IF l_contract_number1 IS NOT NULL THEN
870               print_line('|' || RPAD(l_contract_number1,40,' ') ||
871                         ' |' || RPAD(' ',15,' ') ||
872                         ' |' || RPAD(' ',11,' ') ||
873                         ' |' || RPAD(' ',11,' ') ||
874                         ' |' || LPAD(' ',10,' ') ||
875                         ' |' || LPAD(' ',13,' ') ||
876                         ' |' || LPAD(' ',18,' ') ||
877                         ' |' || LPAD(' ',18,' ') ||
878                         ' |');
879             END IF;
880 
881             IF l_contract_number2 IS NOT NULL THEN
882               print_line('|' || RPAD(l_contract_number2,40,' ') ||
883                         ' |' || RPAD(' ',15,' ') ||
884                         ' |' || RPAD(' ',11,' ') ||
885                         ' |' || RPAD(' ',11,' ') ||
886                         ' |' || LPAD(' ',10,' ') ||
887                         ' |' || LPAD(' ',13,' ') ||
888                         ' |' || LPAD(' ',18,' ') ||
889                         ' |' || LPAD(' ',18,' ') ||
890                         ' |');
891             END IF;
892             l_contract_number      := ' ';
893             l_contract_number1     := NULL;
894             l_contract_number2     := NULL;
895             l_days_in_a_month_code := ' ';
896             l_days_in_a_year_code  := ' ';
897             l_separator            := ' ';
898           END LOOP;
899           print_line('|' || RPAD('_',151,'_') || '|');
900         END LOOP;
901 
902         EXIT WHEN l_icb_counter = g_rpt_success_icb_tbl.LAST;
903         l_icb_counter := g_rpt_success_icb_tbl.next(l_icb_counter);
904         print_line(' ');
905         print_line(' ');
906       END LOOP;
907     END IF;
908 
909   EXCEPTION
910     WHEN OTHERS THEN
911       NULL;
912   END;
913 
914   ------------------------------------------------------------------------------
915     -- Start of Comments
916     -- Created By:       Sanjeev Ahuja
917     -- Function Name  contract_future rent
918     -- Description:   returns the sum of rent
919     -- Dependencies:
920     -- Parameters: contract id, date.
921     -- Version: 1.0
922     -- End of Comments
923 
924   ------------------------------------------------------------------------------
925   FUNCTION contract_future_rents(
926             p_chr_id            IN    NUMBER,
927             p_kle_id            IN    NUMBER,
928             p_date              IN    DATE,
929             p_advance_or_arrears IN   VARCHAR2) RETURN NUMBER  IS
930 
931 /*    l_api_name		CONSTANT    VARCHAR2(30) := 'contract_future_rents';
932     l_api_version	CONSTANT    NUMBER	      := 1;
933     x_return_status             VARCHAR2(1) := Okl_Api.G_RET_STS_SUCCESS;
934     x_msg_count                 NUMBER;
935     x_msg_data                  VARCHAR2(256);
936 */
937     l_rents                     NUMBER := 0;
938 
939     Cursor ln_future_rents_csr (p_chr_id NUMBER, p_kle_id NUMBER, p_date DATE, p_advance_or_arrears VARCHAR2 ) IS
940     select NVL(sum(sel.amount), 0) amount
941     from
942          okl_K_lines_full_v kle,
943          okc_statuses_b sts,
944          okl_strm_elements sel,
945          okl_streams stm,
946          okl_strm_type_b sty
947     WHERE kle.dnz_chr_id = p_chr_id
948     AND   kle.id = p_kle_id
949     AND   kle.sts_code = sts.code
950     AND   sts.ste_code NOT IN ('TERMINATED', 'EXPIRED', 'CANCELLED', 'HOLD')
951     AND   kle.dnz_chr_id = stm.khr_id
952     AND   kle.id   = stm.kle_id
953     AND   stm.say_code = 'CURR'
954     AND   stm.active_yn = 'Y'
955     AND   stm.sty_id = sty.id
956     AND   sty.stream_type_purpose = 'RENT'
957     AND   stm.id = sel.stm_id
958     AND   ((p_advance_or_arrears = 'ARREARS' and sel.stream_element_date > p_date)
959             OR (p_advance_or_arrears <> 'ARREARS' and sel.stream_element_date >= p_date));
960 
961     ln_future_rents_rec ln_future_rents_csr%ROWTYPE;
962 
963     Cursor l_chr_rents_csr (p_chr_id NUMBER, p_kle_id NUMBER, p_date DATE, p_advance_or_arrears VARCHAR2) IS
964     SELECT  NVL(SUM(sele.amount),0) amount
965     FROM    okl_strm_elements sele,
966         okl_streams str,
967         okl_strm_type_b sty
968     WHERE   sele.stm_id = str.id
969     AND     str.sty_id = sty.id
970     AND     sty.stream_type_purpose = 'RENT'
971     AND     str.say_code = 'CURR'
972     AND     str.active_yn = 'Y'
973     AND     nvl( str.purpose_code, 'XXXX' ) = 'XXXX'
974     AND     str.khr_id = p_chr_id
975     AND     str.kle_id = p_kle_id
976     AND     nvl(str.kle_id, -1) = -1
977     AND   ((p_advance_or_arrears = 'ARREARS' and sele.stream_element_date > p_date)
978             OR (p_advance_or_arrears <> 'ARREARS' and sele.stream_element_date >= p_date));
979 
980     l_chr_rents_rec l_chr_rents_csr%ROWTYPE;
981 
982   BEGIN
983 
984        IF ( p_chr_id IS NULL OR p_kle_id IS NULL) THEN
985            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
986        END IF;
987 
988        OPEN ln_future_rents_csr(p_chr_id, p_kle_id, p_date, p_advance_or_arrears);
989        FETCH ln_future_rents_csr INTO ln_future_rents_rec;
990        CLOSE ln_future_rents_csr;
991 
992        OPEN l_chr_rents_csr(p_chr_id, p_kle_id, p_date, p_advance_or_arrears);
993        FETCH l_chr_rents_csr INTO l_chr_rents_rec;
994        CLOSE l_chr_rents_csr;
995 
996        l_rents := ln_future_rents_rec.amount + l_chr_rents_rec.amount;
997 
998        print_debug('Contract future rent :' || l_rents);
999        RETURN l_rents;
1000 
1001 
1002   EXCEPTION
1003 	WHEN OTHERS  THEN
1004                Okl_Api.SET_MESSAGE(
1005                         p_app_name     => G_APP_NAME,
1006                         p_msg_name     => G_UNEXPECTED_ERROR,
1007                         p_token1       => G_SQLCODE_TOKEN,
1008                         p_token1_value => SQLCODE,
1009                         p_token2       => G_SQLERRM_TOKEN,
1010                         p_token2_value => SQLERRM);
1011                 RETURN NULL;
1012 
1013   END contract_future_rents;
1014 
1015   ------------------------------------------------------------------------------
1016 
1017     -- Start of Comments
1018     -- Created By:       Sanjeev Ahuja
1019     -- Function Name  contract_future_income
1020     -- Description:   returns sum of all future incomes of financial asset lines of a contract
1021     -- Dependencies:
1022     -- Parameters: contract id, date.
1023     -- Version: 1.0
1024     -- End of Comments
1025 
1026   ------------------------------------------------------------------------------
1027   FUNCTION contract_future_income(
1028             p_chr_id          IN  NUMBER,
1029             p_kle_id          IN  NUMBER,
1030             p_date            IN  DATE) RETURN NUMBER  IS
1031 
1032 /*    l_api_name		CONSTANT    VARCHAR2(30) := 'RETURN_CONTRACT_FUTURE_INCOME';
1033     l_api_version	CONSTANT    NUMBER	      := 1;
1034     x_return_status             VARCHAR2(1) := Okl_Api.G_RET_STS_SUCCESS;
1035     x_msg_count                 NUMBER;
1036     x_msg_data                  VARCHAR2(256);
1037 */
1038     l_income                    NUMBER := 0;
1039 
1040     Cursor l_chr_income_csr (p_chr_id NUMBER, p_kle_id NUMBER, p_date DATE) IS
1041     select NVL(sum(sel.amount), 0) amount
1042     from
1043          okl_K_lines_full_v kle,
1044          okc_statuses_b sts,
1045          okl_strm_elements sel,
1046          okl_streams stm,
1047          okl_strm_type_b sty
1048     WHERE kle.dnz_chr_id = p_chr_id
1049     AND   kle.id = p_kle_id
1050     AND   kle.sts_code = sts.code
1051     AND   sts.ste_code NOT IN ('TERMINATED', 'EXPIRED', 'CANCELLED', 'HOLD')
1052     AND   kle.dnz_chr_id = stm.khr_id
1053     AND   kle.id   = stm.kle_id
1054     AND   stm.say_code = 'CURR'
1055     AND   stm.active_yn = 'Y'
1056     AND   stm.sty_id = sty.id
1057     AND   sty.stream_type_purpose = 'LEASE_INCOME'
1058     AND   stm.id = sel.stm_id
1059     AND   sel.stream_element_date >= TRUNC(p_date, 'MONTH');
1060 
1061     l_chr_income_rec l_chr_income_csr%ROWTYPE;
1062   BEGIN
1063 
1064        IF ( p_chr_id IS  NULL OR p_kle_id IS NULL) THEN
1065            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
1066        END IF;
1067 
1068        OPEN l_chr_income_csr(p_chr_id, p_kle_id, p_date);
1069        FETCH l_chr_income_csr INTO l_chr_income_rec;
1070        CLOSE l_chr_income_csr;
1071 
1072        l_income := l_chr_income_rec.amount;
1073 
1074        print_debug('Contract future income :' || l_income);
1075        RETURN l_income;
1076 
1077 
1078   EXCEPTION
1079 
1080 	WHEN OTHERS THEN
1081                Okl_Api.SET_MESSAGE(
1082                         p_app_name     => G_APP_NAME,
1083                         p_msg_name     => G_UNEXPECTED_ERROR,
1084                         p_token1       => G_SQLCODE_TOKEN,
1085                         p_token1_value => SQLCODE,
1086                         p_token2       => G_SQLERRM_TOKEN,
1087                         p_token2_value => SQLERRM);
1088                 RETURN NULL;
1089 
1090 
1091   END contract_future_income;
1092 
1093   ------------------------------------------------------------------------------
1094 
1095     -- Start of Comments
1096     -- Created By:       Sanjeev Ahuja
1097     -- Function Name  contract_future_income
1098     -- Description:   returns sum of all future incomes of financial asset lines of a contract
1099     -- Dependencies:
1100     -- Parameters: contract id, date.
1101     -- Version: 1.0
1102     -- End of Comments
1103 
1104   ------------------------------------------------------------------------------
1105   FUNCTION contract_residual_value(
1106             p_chr_id          IN  NUMBER,
1107             p_kle_id          IN  NUMBER) RETURN NUMBER  IS
1108 
1109 /*    l_api_name		CONSTANT    VARCHAR2(30) := 'contract_residual_value';
1110     l_api_version	CONSTANT    NUMBER	      := 1;
1111     x_return_status             VARCHAR2(1) := Okl_Api.G_RET_STS_SUCCESS;
1112     x_msg_count                 NUMBER;
1113     x_msg_data                  VARCHAR2(256);
1114 */
1115     l_residual_value                    NUMBER := 0;
1116 
1117     Cursor residual_value_csr (p_chr_id     IN NUMBER, p_kle_id IN NUMBER) IS
1118     SELECT  nvl(kle.residual_value,0) Value
1119     FROM    OKC_LINE_STYLES_B LS,
1120         okl_K_lines_full_v kle,
1121 	    okc_statuses_b sts
1122     WHERE   LS.ID = KLE.LSE_ID
1123     AND     LS.LTY_CODE ='FREE_FORM1'
1124     AND     KLE.DNZ_CHR_ID = p_chr_id --289326506849179644190030423574805590144
1125     AND     KLE.id = p_kle_id
1126     AND     kle.sts_code = sts.code
1127     AND     sts.ste_code NOT IN ('TERMINATED', 'EXPIRED', 'CANCELLED', 'HOLD');
1128 
1129     residual_value_rec residual_value_csr%ROWTYPE;
1130   BEGIN
1131 
1132        IF ( p_chr_id IS NULL OR p_kle_id IS NULL ) THEN
1133            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
1134        END IF;
1135 
1136        OPEN residual_value_csr(p_chr_id, p_kle_id);
1137        FETCH residual_value_csr INTO residual_value_rec;
1138        CLOSE residual_value_csr;
1139 
1140        l_residual_value := residual_value_rec.Value;
1141 
1142        print_debug('Contract residual value :' || l_residual_value);
1143        RETURN l_residual_value;
1144 
1145 
1146   EXCEPTION
1147 
1148 	WHEN OTHERS THEN
1149                Okl_Api.SET_MESSAGE(
1150                         p_app_name     => G_APP_NAME,
1151                         p_msg_name     => G_UNEXPECTED_ERROR,
1152                         p_token1       => G_SQLCODE_TOKEN,
1153                         p_token1_value => SQLCODE,
1154                         p_token2       => G_SQLERRM_TOKEN,
1155                         p_token2_value => SQLERRM);
1156                 RETURN NULL;
1157 
1158 
1159   END contract_residual_value;
1160 
1161 ----------------------------------------------------------------------------------------------------
1162 
1163     -- Start of Comments
1164     -- Created By:       Sanjeev Ahuja
1165     -- Function Name  asset_cost_loan
1166     -- Description:   returns asset cost for a loan contract
1167     -- Dependencies:
1168     -- Parameters: contract id.
1169     -- Version: 1.0
1170     -- End of Comments
1171 
1172 ----------------------------------------------------------------------------------------------------
1173   FUNCTION asset_cost_loan(
1174             p_chr_id          IN  NUMBER) RETURN NUMBER  IS
1175 
1176     l_api_name		CONSTANT    VARCHAR2(30) := 'RETURN_CONTRACT_RESIDUAL_VALUE';
1177     l_api_version	CONSTANT    NUMBER	      := 1;
1178     x_return_status             VARCHAR2(1) := Okl_Api.G_RET_STS_SUCCESS;
1179     x_msg_count                 NUMBER;
1180     x_msg_data                  VARCHAR2(256);
1181 
1182     l_asset_cost                    NUMBER := 0;
1183 
1184     Cursor loan_asset_cost_csr (p_chr_id     IN NUMBER) IS
1185     select  sum(okl_line.capital_amount) asset_cost
1186     from    okc_k_lines_b okc_line,
1187         okc_line_styles_b style,
1188         okl_k_lines okl_line
1189     where   okc_line.chr_id             = p_chr_id --276779267018378275653765386722943545472
1190     and     okc_line.lse_id             = style.id
1191     and     style.lty_code              = 'FREE_FORM1'
1192     and     okc_line.id                 = okl_line.id;
1193 
1194     loan_asset_cost_rec loan_asset_cost_csr%ROWTYPE;
1195   BEGIN
1196 
1197        IF ( p_chr_id = NULL ) THEN
1198            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
1199        END IF;
1200 
1201        OPEN loan_asset_cost_csr(p_chr_id);
1202        FETCH loan_asset_cost_csr INTO loan_asset_cost_rec;
1203        CLOSE loan_asset_cost_csr;
1204 
1205        l_asset_cost := loan_asset_cost_rec.asset_cost;
1206 
1207        RETURN l_asset_cost;
1208 
1209 
1210   EXCEPTION
1211 
1212 	WHEN OTHERS THEN
1213                Okl_Api.SET_MESSAGE(
1214                         p_app_name     => G_APP_NAME,
1215                         p_msg_name     => G_UNEXPECTED_ERROR,
1216                         p_token1       => G_SQLCODE_TOKEN,
1217                         p_token1_value => SQLCODE,
1218                         p_token2       => G_SQLERRM_TOKEN,
1219                         p_token2_value => SQLERRM);
1220                 RETURN NULL;
1221 
1222 
1223   END asset_cost_loan;
1224 
1225 ----------------------------------------------------------------------------------------------------
1226 
1227     -- Start of Comments
1228     -- Created By:       Sanjeev Ahuja
1229     -- Function Name  payment_received
1230     -- Description:   returns payment received for a loan contract
1231     -- Dependencies:
1232     -- Parameters: contract id.
1233     -- Version: 1.0
1234     -- End of Comments
1235 
1236 ----------------------------------------------------------------------------------------------------
1237   FUNCTION payment_received(
1238             p_chr_id          IN    NUMBER,
1239             p_date            IN    DATE) RETURN NUMBER  IS
1240 
1241     l_api_name		CONSTANT    VARCHAR2(30) := 'RETURN_CONTRACT_RESIDUAL_VALUE';
1242     l_api_version	CONSTANT    NUMBER	      := 1;
1243     x_return_status             VARCHAR2(1) := Okl_Api.G_RET_STS_SUCCESS;
1244     x_msg_count                 NUMBER;
1245     x_msg_data                  VARCHAR2(256);
1246 
1247     l_payment_received                    NUMBER := 0;
1248 
1249 -- Begin - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
1250     Cursor Principal_Paid_Cur (p_chr_id     IN NUMBER, p_date   IN  DATE) IS
1251     SELECT   NVL(SUM(AR_REC.AMOUNT_APPLIED),0) AMOUNT
1252     FROM     AR_RECEIVABLE_APPLICATIONS_ALL AR_REC,
1253          AR_PAYMENT_SCHEDULES_ALL AR_PAY,
1254          okl_bpd_tld_ar_lines_v TLD,
1255          OKL_STRM_TYPE_B STRM
1256     WHERE    AR_REC.APPLY_DATE              <= p_date -- TO BE REPLACED WITH APPLY DATE
1257     AND      TLD.KHR_ID                   = p_chr_id --298074492502791815515340871034511143040
1258     AND      TLD.STY_ID                   = STRM.ID
1259     AND      STRM.STREAM_TYPE_PURPOSE       = 'PRINCIPAL_PAYMENT'
1260     AND      TLD.CUSTOMER_TRX_ID = AR_PAY.CUSTOMER_TRX_ID
1261     AND      AR_PAY.PAYMENT_SCHEDULE_ID     = AR_REC.APPLIED_PAYMENT_SCHEDULE_ID
1262     AND      AR_PAY.CLASS                   = 'INV'
1263     AND      AR_REC.STATUS                  = 'APP';
1264 -- End - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
1265 
1266 
1267     Principal_Paid_Rec Principal_Paid_Cur%ROWTYPE;
1268   BEGIN
1269 
1270        IF ( p_chr_id = NULL ) THEN
1271            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
1272        END IF;
1273 
1274        OPEN Principal_Paid_Cur(p_chr_id,p_date);
1275        FETCH Principal_Paid_Cur INTO Principal_Paid_Rec.AMOUNT;
1276        CLOSE Principal_Paid_Cur;
1277 
1278        l_payment_received := Principal_Paid_Rec.AMOUNT;
1279 
1280        RETURN l_payment_received;
1281 
1282 
1283   EXCEPTION
1284 
1285 	WHEN OTHERS THEN
1286                Okl_Api.SET_MESSAGE(
1287                         p_app_name     => G_APP_NAME,
1288                         p_msg_name     => G_UNEXPECTED_ERROR,
1289                         p_token1       => G_SQLCODE_TOKEN,
1290                         p_token1_value => SQLCODE,
1291                         p_token2       => G_SQLERRM_TOKEN,
1292                         p_token2_value => SQLERRM);
1293     RETURN NULL;
1294 
1295 
1296   END payment_received;
1297 ----------------------------------------------------------------------------------------------------
1298 
1299     -- Start of Comments
1300     -- Created By:       Sanjeev Ahuja
1301     -- Function Name  funding_req
1302     -- Description:   returns funding requested for a loan contract
1303     -- Dependencies:
1304     -- Parameters: contract id.
1305     -- Version: 1.0
1306     -- End of Comments
1307 
1308 ----------------------------------------------------------------------------------------------------
1309   FUNCTION funding_req(
1310             p_chr_id          IN    NUMBER,
1311             p_date            IN    DATE) RETURN NUMBER  IS
1312 
1313     l_api_name		CONSTANT    VARCHAR2(30) := 'RETURN_CONTRACT_RESIDUAL_VALUE';
1314     l_api_version	CONSTANT    NUMBER	      := 1;
1315     x_return_status             VARCHAR2(1) := Okl_Api.G_RET_STS_SUCCESS;
1316     x_msg_count                 NUMBER;
1317     x_msg_data                  VARCHAR2(256);
1318 
1319     l_funding_req                    NUMBER := 0;
1320 
1321     -- sjalasut, modified the cursor to change khr_id references from hdr to line
1322     -- also introduced okl_cnsld_ap_invs_all table to have consolidated ap
1323     -- invoice id joined to the ap_invoices table. fts on ap_payment_schedules_all
1324     Cursor Amount_Funded_Cur (p_chr_id     IN NUMBER, p_date   IN DATE) IS
1325     select nvl(sum(ap_inv.payment_amount_total), 0) AMOUNT
1326     from ap_invoices_all ap_inv,
1327          okl_trx_ap_invoices_b okl_inv,
1328          ap_payment_schedules_all pay_sche
1329          ,okl_cnsld_ap_invs_all cnsld
1330          ,okl_txl_ap_inv_lns_all_b okl_inv_ln
1331          ,fnd_application fnd_app
1332     where okl_inv.id = okl_inv_ln.tap_id
1333       and okl_inv_ln.khr_id = p_chr_id
1334       and ap_inv.application_id = fnd_app.application_id
1335       and fnd_app.application_short_name = 'OKL'
1336       and okl_inv_ln.cnsld_ap_inv_id = cnsld.cnsld_ap_inv_id
1337       and cnsld.cnsld_ap_inv_id = to_number(ap_inv.reference_key1)
1338       and okl_inv.funding_type_code = 'BORROWER_PAYMENT'
1339       and ap_inv.invoice_id = pay_sche.invoice_id
1340       and pay_sche.creation_date > p_date
1341       and ap_inv.payment_status_flag in ('Y','P');
1342 
1343 
1344      Amount_Funded_Rec Amount_Funded_Cur%ROWTYPE;
1345   BEGIN
1346 
1347        IF ( p_chr_id = NULL ) THEN
1348            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
1349        END IF;
1350 
1351        OPEN Amount_Funded_Cur(p_chr_id,p_date);
1352        FETCH Amount_Funded_Cur INTO Amount_Funded_Rec.AMOUNT;
1353        CLOSE Amount_Funded_Cur;
1354 
1355        l_funding_req := Amount_Funded_Rec.AMOUNT;
1356 
1357        RETURN l_funding_req;
1358 
1359 
1360   EXCEPTION
1361 
1362 	WHEN OTHERS THEN
1363                Okl_Api.SET_MESSAGE(
1364                         p_app_name     => G_APP_NAME,
1365                         p_msg_name     => G_UNEXPECTED_ERROR,
1366                         p_token1       => G_SQLCODE_TOKEN,
1367                         p_token1_value => SQLCODE,
1368                         p_token2       => G_SQLERRM_TOKEN,
1369                         p_token2_value => SQLERRM);
1370                 RETURN NULL;
1371 
1372 
1373   END funding_req;
1374 
1375 ----------------------------------------------------------------------------------------------------
1376 
1377     -- Start of Comments
1378     -- Created By:       Sanjeev Ahuja
1379     -- Function Name  prin_bal_OP_lease
1380     -- Description:   returns Principal Balance for a Operating Lease contract
1381     -- Dependencies:
1382     -- Parameters: contract id.
1383     -- Version: 1.0
1384     -- End of Comments
1385 
1386 ----------------------------------------------------------------------------------------------------
1387   FUNCTION prin_bal_OP_lease(
1388             p_chr_id          IN  NUMBER,
1389             p_kle_id          IN NUMBER) RETURN NUMBER  IS
1390 
1391 /*    l_api_name		CONSTANT    VARCHAR2(30) := 'CONTRACT_RESIDUAL_VALUE';
1392     l_api_version	CONSTANT    NUMBER	      := 1;
1393     x_return_status             VARCHAR2(1) := Okl_Api.G_RET_STS_SUCCESS;
1394     x_msg_count                 NUMBER;
1395     x_msg_data                  VARCHAR2(256);
1396 */
1397     l_net_book_value            NUMBER := 0;
1398 
1399     Cursor lease_asset_cost_csr (p_chr_id     IN NUMBER, p_kle_id IN NUMBER) IS
1400     Select  FA_BOOKS.ASSET_ID ASSET_ID,
1401         FA_BOOKS.cost ASSET_COST,
1402         FA_BOOKS.book_type_code BOOK_TYPE_CODE
1403     from    FA_BOOKS ,
1404         FA_BOOK_CONTROLS,
1405         OKC_K_LINES_B LINES,
1406         OKC_LINE_STYLES_B STYLE,
1407         OKC_K_ITEMS KITEM
1408     where   FA_BOOKS.asset_id           = KITEM.OBJECT1_ID1
1409     and     LINES.DNZ_CHR_ID            = p_chr_id --291511068054787299132375269533568315520
1410     and     LINES.cle_id                = p_kle_id
1411     and     LINES.ID                    = KITEM.CLE_ID
1412     and     LINES.LSE_ID                = STYLE.ID
1413     and     STYLE.LTY_CODE              = 'FIXED_ASSET'
1414     and     FA_BOOKS.book_type_code     = FA_BOOK_CONTROLS.book_type_code
1415     and     FA_BOOK_CONTROLS.book_class = 'CORPORATE'
1416     and     FA_BOOKS.transaction_header_id_out is null;
1417 
1418     Cursor Deprn_csr (p_asset_id     IN NUMBER,
1419                   p_book_type_code IN VARCHAR2) IS
1420     select  sum(deprn_amount) ACCUMULATED_DEPRECIATION
1421     from    fa_deprn_summary
1422     where   Asset_id                    = p_asset_id
1423     and     book_type_code              = p_book_type_code;
1424 
1425     Deprn_rec Deprn_csr%ROWTYPE;
1426 
1427   BEGIN
1428 
1429        IF ( p_chr_id = NULL ) THEN
1430            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
1431        END IF;
1432 
1433        print_debug('Asset id :' || p_kle_id);
1434        FOR l_lease_asset_cost_csr IN lease_asset_cost_csr(p_chr_id, p_kle_id)
1435        LOOP
1436 
1437          OPEN Deprn_csr(l_lease_asset_cost_csr.ASSET_ID,l_lease_asset_cost_csr.BOOK_TYPE_CODE);
1438          FETCH Deprn_csr INTO Deprn_rec.ACCUMULATED_DEPRECIATION;
1439          CLOSE Deprn_csr;
1440 
1441          print_debug('Asset cost :' || l_lease_asset_cost_csr.ASSET_COST);
1442          print_debug('Accumulated depreciation :' || Deprn_rec.ACCUMULATED_DEPRECIATION);
1443 
1444          l_net_book_value := l_net_book_value + (l_lease_asset_cost_csr.ASSET_COST -
1445                                                 Deprn_rec.ACCUMULATED_DEPRECIATION);
1446 
1447          print_debug('Net book value :' || l_net_book_value);
1448        END LOOP;
1449 
1450 
1451        RETURN l_net_book_value;
1452 
1453 
1454   EXCEPTION
1455 
1456 	WHEN OTHERS THEN
1457                Okl_Api.SET_MESSAGE(
1458                         p_app_name     => G_APP_NAME,
1459                         p_msg_name     => G_UNEXPECTED_ERROR,
1460                         p_token1       => G_SQLCODE_TOKEN,
1461                         p_token1_value => SQLCODE,
1462                         p_token2       => G_SQLERRM_TOKEN,
1463                         p_token2_value => SQLERRM);
1464                 RETURN NULL;
1465 
1466 
1467   END prin_bal_OP_lease;
1468 ----------------------------------------------------------------------------------
1469 -- Start of comments
1470 --
1471 -- Procedure Name  : get_tot_principal_amt
1472 -- Description     : get principal balance amount
1473 -- Business Rules  :
1474 -- Parameters      :
1475 -- Version         : 1.0
1476 -- End of comments
1477 ----------------------------------------------------------------------------------
1478   FUNCTION get_tot_principal_amt(
1479   p_khr_id              IN  NUMBER,
1480   p_kle_id              IN  NUMBER,
1481   p_date                IN  DATE,
1482   p_advance_or_arrears  IN  VARCHAR2) RETURN NUMBER IS
1483 
1484     l_principal_balance NUMBER := 0;
1485 
1486 
1487     l_api_version              NUMBER := 1;
1488     l_init_msg_list            VARCHAR2(100) := OKC_API.G_FALSE;
1489     x_return_status            VARCHAR2(100);
1490     x_msg_count                NUMBER;
1491     x_msg_data                 VARCHAR2(1999);
1492     x_value                    NUMBER := 0;
1493     l_formula_name             VARCHAR2(100);
1494     lx_rulv_rec		          Okl_Rule_Apis_Pvt.rulv_rec_type;
1495     p_bal_date                 DATE;
1496 
1497 
1498 
1499     CURSOR c_khr_type (p_khr_id  NUMBER) IS
1500     SELECT khr.deal_type deal_type
1501     FROM    okc_k_headers_b CHR,
1502         okl_k_headers khr
1503     WHERE   khr.id = CHR.id
1504     AND     khr.id = p_khr_id;
1505 
1506     c_khr_type_rec  c_khr_type%ROWTYPE;
1507 
1508 /*    CURSOR c_principal_bal_cur(p_contract_id NUMBER, p_bal_date DATE) IS
1509     SELECT sum(sel.amount) amount
1510     FROM   okl_strm_elements sel,okl_streams stm, okl_strm_type_b sty
1511     WHERE  stm.khr_id          = p_contract_id
1512     AND    stm.active_yn           = 'Y'
1513     AND    stm.say_code            = 'CURR'
1514     AND    sty.id                  = stm.sty_id
1515     AND   sty.stream_type_purpose  = 'PRINCIPAL_BALANCE'
1516     AND    sel.stm_id          = stm.id
1517     and   trunc(sel.stream_element_date) = ( select trunc(max(sel.stream_element_date))
1518                                  FROM   okl_strm_elements sel,okl_streams stm,
1519                                         okl_strm_type_b sty
1520                                  WHERE  stm.khr_id          = p_contract_id
1521                                  AND    stm.active_yn       = 'Y'
1522                                  AND    stm.say_code        = 'CURR'
1523                                  AND    sty.id              = stm.sty_id
1524                                  AND    sty.stream_type_purpose = 'PRINCIPAL_BALANCE'
1525                                  AND    sel.stm_id          = stm.id
1526                                  and   trunc(sel.stream_element_date) <= p_bal_date);
1527 
1528     CURSOR c_stream_date_arr(p_contract_id NUMBER, p_bal_date DATE) IS
1529     select trunc(min(sel.stream_element_date))
1530     FROM   okl_strm_elements sel,okl_streams stm,
1531            okl_strm_type_b sty
1532     WHERE  stm.khr_id          = p_contract_id
1533     AND    stm.active_yn       = 'Y'
1534     AND    stm.say_code        = 'CURR'
1535     AND    sty.id              = stm.sty_id
1536     AND    sty.stream_type_purpose = 'PRINCIPAL_BALANCE'
1537     AND    sel.stm_id          = stm.id
1538     and    sel.stream_element_date >= p_bal_date;
1539 */
1540   BEGIN
1541        IF ( p_khr_id IS NULL OR p_kle_id IS NULL ) THEN
1542            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
1543        END IF;
1544 
1545        OPEN c_khr_type(p_khr_id);
1546        FETCH c_khr_type INTO c_khr_type_rec.deal_type;
1547        CLOSE c_khr_type;
1548 
1549 
1550        /*Okl_Bp_Rules.extract_rules(
1551            	    p_api_version      => l_api_version,
1552        	        p_init_msg_list    => l_init_msg_list,
1553     	   	 	p_khr_id           => p_khr_id,
1554     			p_kle_id           => null,
1555     			p_rgd_code         => 'LAIIND',
1556     			p_rdf_code         => 'LAICLC',
1557     			x_return_status    => x_return_status,
1558     			x_msg_count        => x_msg_count,
1559     			x_msg_data         => x_msg_data,
1560     			x_rulv_rec         => lx_rulv_rec);
1561 
1562        debug_message('Variable Interest Type: '||lx_rulv_rec.rule_information5);
1563        debug_message('Reamort Date: '||p_date);*/
1564 
1565 --       if(G_INTEREST_CALCULATION_BASIS = 'REAMORT') THEN
1566 
1567          print_debug('get_tot_principal_amt : p_advance_or_arrears => ' || p_advance_or_arrears);
1568          if(c_khr_type_rec.deal_type = 'LEASEDF' or c_khr_type_rec.deal_type = 'LEASEST') THEN
1569            l_principal_balance :=  contract_future_rents(p_khr_id, p_kle_id, p_date, p_advance_or_arrears) +
1570                                 contract_residual_value(p_khr_id, p_kle_id) -
1571                                 contract_future_income(p_khr_id, p_kle_id, p_date);
1572 
1573 
1574          elsif(c_khr_type_rec.deal_type = 'LEASEOP') THEN
1575            l_principal_balance :=  prin_bal_OP_lease(p_khr_id, p_kle_id);
1576 
1577 
1578 /*         elsif(c_khr_type_rec.deal_type = 'LOAN') THEN
1579 
1580            OPEN c_stream_date_arr(p_khr_id, p_date);
1581            FETCH c_stream_date_arr INTO p_bal_date;
1582            CLOSE c_stream_date_arr;
1583 
1584            OPEN c_principal_bal_cur(p_khr_id, p_bal_date);
1585            FETCH c_principal_bal_cur INTO l_principal_balance;
1586            CLOSE c_principal_bal_cur;
1587            debug_message('Principal Balance Loan: '||l_principal_balance);
1588 */         end if;
1589 
1590 /*       else
1591          if(c_khr_type_rec.deal_type = 'LOAN') THEN
1592            l_principal_balance :=  asset_cost_loan(p_khr_id) -
1593                                 payment_received(p_khr_id,p_date);
1594 
1595          elsif(c_khr_type_rec.deal_type = 'LOAN-REVOLVING') THEN
1596            l_principal_balance :=  funding_req(p_khr_id,p_date) -
1597                                 payment_received(p_khr_id,p_date);
1598          end if;
1599        end if;*/
1600 
1601        RETURN l_principal_balance;
1602 
1603   EXCEPTION
1604     WHEN OTHERS THEN
1605       --l_return_status := OKL_API.G_RET_STS_UNEXP_ERROR ;
1606       OKL_API.Set_Message(p_app_name      => OKL_API.G_APP_NAME,
1607                           p_msg_name      => 'OKL_UNEXPECTED_ERROR',
1608                           p_token1        => 'OKL_SQLCODE',
1609                           p_token1_value  => SQLCODE,
1610                           p_token2        => 'OKL_SQLERRM',
1611                           p_token2_value  => SQLERRM);
1612     RETURN NULL;
1613 
1614   END get_tot_principal_amt;
1615   ------------------------------------------------------------------
1616   -- Function GET_TRX_TYPE to extract transaction type
1617   ------------------------------------------------------------------
1618 
1619   FUNCTION get_trx_type
1620 	(p_name		VARCHAR2,
1621 	p_language	VARCHAR2)
1622 	RETURN		NUMBER IS
1623 
1624 	CURSOR c_trx_type (cp_name VARCHAR2, cp_language VARCHAR2) IS
1625 		SELECT	id
1626 		FROM	okl_trx_types_tl
1627 		WHERE	name	= cp_name
1628 		AND	LANGUAGE	= cp_language;
1629 
1630 	l_trx_type	okl_trx_types_v.id%TYPE;
1631 
1632   BEGIN
1633 
1634     l_trx_type := NULL;
1635 
1636 	  OPEN	c_trx_type (p_name, p_language);
1637 	  FETCH	c_trx_type INTO l_trx_type;
1638 	  CLOSE	c_trx_type;
1639 
1640 	  RETURN	l_trx_type;
1641 
1642   END get_trx_type;
1643 
1644   PROCEDURE print_loan_tables(p_rent_tbl      IN csm_periodic_expenses_tbl_type,
1645                               p_csm_loan_level_tbl IN csm_loan_level_tbl_type) IS
1646     l_api_name	        CONSTANT VARCHAR2(30) := 'print_loan_tables';
1647     i NUMBER;
1648     l_source Number;
1649     l_rent_tbl csm_periodic_expenses_tbl_type;
1650     l_csm_loan_level_tbl csm_loan_level_tbl_type;
1651   BEGIN
1652     l_rent_tbl := p_rent_tbl;
1653     l_csm_loan_level_tbl := p_csm_loan_level_tbl;
1654 
1655     print_debug('*****************************************');
1656     print_debug('*******START CONTENTS OF P_RENT_TBL******');
1657     i := l_rent_tbl.first;
1658     loop
1659       exit when i is null;
1660       print_debug('l_rent_tbl element # '|| i);
1661       print_debug('----------------------------------------------------');
1662       print_debug('sequence number of the payment level: '|| set_value_null(l_rent_tbl(i).level_index_number));
1663       print_debug('number of payments for a payment level: '|| set_value_null(l_rent_tbl(i).number_of_periods));
1664       print_debug('foreign key to table OKL_SIF_RETS: '||set_value_null(l_rent_tbl(i).sir_id));
1665       print_debug('reference to the asset index number: '||set_value_null(l_rent_tbl(i).index_number));
1666       print_debug('payment type: '||set_value_null(l_rent_tbl(i).level_type));
1667       print_debug('amount: '||set_value_null(l_rent_tbl(i).amount));
1668       print_debug('advance_or_arrears: '||set_value_null(l_rent_tbl(i).advance_or_arrears));
1669       print_debug('frequency: '||set_value_null(l_rent_tbl(i).period));
1670       print_debug('lock_level_step: '||set_value_null(l_rent_tbl(i).lock_level_step));
1671       print_debug('days in a payment period: '||set_value_null(l_rent_tbl(i).days_in_period));
1672       print_debug('first payment date for a payment level: '||set_value_null(l_rent_tbl(i).first_payment_date));
1673       print_debug('rate: '||set_value_null(l_rent_tbl(i).rate));
1674       i := l_rent_tbl.next(i);
1675     end loop;
1676     print_debug('*******END CONTENTS OF P_RENT_TBL********');
1677     print_debug('*****************************************');
1678 
1679 
1680     print_debug('*****************************************');
1681     print_debug('**START CONTENTS OF P_CSM_LOAN_LEVEL_TBL*');
1682     i := l_csm_loan_level_tbl.first;
1683     loop
1684       exit when i is null;
1685       print_debug('l_csm_loan_level_tbl element # '|| i);
1686       print_debug('----------------------------------------------------');
1687       print_debug('description: '||set_value_null(l_csm_loan_level_tbl(i).description));
1688       print_debug('first payment date for a payment level: '||set_value_null(l_csm_loan_level_tbl(i).date_start));
1689       print_debug('asset line id: '||set_value_null(l_csm_loan_level_tbl(i).kle_loan_id));
1690       print_debug('sequence number of the payment level: '||set_value_null(l_csm_loan_level_tbl(i).level_index_number));
1691       print_debug('payment type: '||set_value_null(l_csm_loan_level_tbl(i).level_type));
1692 
1693       --IF (l_csm_loan_level_tbl(i).level_type <> 'FUNDING') THEN
1694       print_debug('number of payments for a payment level: '||set_value_null(l_csm_loan_level_tbl(i).number_of_periods));
1695       print_debug('lock_level_step: '||set_value_null(l_csm_loan_level_tbl(i).lock_level_step));
1696       print_debug('frequency: '||set_value_null(l_csm_loan_level_tbl(i).period));
1697       print_debug('advance_or_arrears: '||set_value_null(l_csm_loan_level_tbl(i).advance_or_arrears));
1698       print_debug('income_or_expense: '||set_value_null(l_csm_loan_level_tbl(i).income_or_expense));
1699       print_debug('query_level_yn: '||set_value_null(l_csm_loan_level_tbl(i).query_level_yn));
1700       print_debug('payment_type: '||set_value_null(l_csm_loan_level_tbl(i).payment_type));
1701       --END IF;
1702       print_debug('amount: '||set_value_null(l_csm_loan_level_tbl(i).amount));
1703       print_debug('rate: '||set_value_null(l_csm_loan_level_tbl(i).rate));
1704       i := l_csm_loan_level_tbl.next(i);
1705     end loop;
1706     print_debug('**END CONTENTS OF P_CSM_LOAN_LEVEL_TBL***');
1707     print_debug('*****************************************');
1708   Exception
1709    	WHEN OTHERS THEN
1710       print_debug('error in procedure print_loan_tables');
1711       print_debug('sqlcode : ' || sqlcode || ' $ sqlerrm : ' || sqlerrm);
1712   END print_loan_tables;
1713 
1714   PROCEDURE print_lease_tables(p_rents_tbl_in IN Okl_Create_Streams_Pub.csm_periodic_expenses_tbl_type,
1715                                p_csm_line_details_tbl IN okl_create_streams_pvt.csm_line_details_tbl_type) IS
1716     l_api_name	        CONSTANT VARCHAR2(30) := 'print_lease_tables';
1717     i NUMBER;
1718     l_source Number;
1719     l_rents_tbl_in Okl_Create_Streams_Pub.csm_periodic_expenses_tbl_type;
1720     l_csm_line_details_tbl okl_create_streams_pvt.csm_line_details_tbl_type;
1721   BEGIN
1722     l_rents_tbl_in := p_rents_tbl_in;
1723     l_csm_line_details_tbl := p_csm_line_details_tbl;
1724     print_debug('******************************************');
1725     print_debug('*****START CONTENTS OF P_RENTS_TBL_IN*****');
1726     i := l_rents_tbl_in.first;
1727     loop
1728       exit when i is null;
1729       print_debug('l_rents_tbl_in element # '|| i);
1730       print_debug('----------------------------------------------------');
1731       print_debug('description: '||set_value_null(l_rents_tbl_in(i).description));
1732       print_debug('first payment date for a payment level: '||set_value_null(l_rents_tbl_in(i).date_start));
1733       print_debug('kle_asset_id: '||set_value_null(l_rents_tbl_in(i).kle_asset_id));
1734       print_debug('sequence number of the payment level: '||set_value_null(l_rents_tbl_in(i).level_index_number));
1735       print_debug('payment type: '||set_value_null(l_rents_tbl_in(i).level_type));
1736       print_debug('number of payments for a payment level: '||set_value_null(l_rents_tbl_in(i).number_of_periods));
1737       print_debug('amount: '||set_value_null(l_rents_tbl_in(i).amount));
1738       print_debug('rate: '||set_value_null(l_rents_tbl_in(i).rate));
1739       print_debug('lock_level_step: '||set_value_null(l_rents_tbl_in(i).lock_level_step));
1740       print_debug('frequency: '||set_value_null(l_rents_tbl_in(i).period));
1741       print_debug('advance_or_arrears: '||set_value_null(l_rents_tbl_in(i).advance_or_arrears));
1742       print_debug('income_or_expense: '||set_value_null(l_rents_tbl_in(i).income_or_expense));
1743       i := l_rents_tbl_in.next(i);
1744     end loop;
1745     print_debug('******END CONTENTS OF P_RENTS_TBL_IN******');
1746     print_debug('******************************************');
1747 
1748     print_debug('*START CONTENTS OF P_CSM_LINE_DETAILS_TBL*');
1749     print_debug('******************************************');
1750     i := l_csm_line_details_tbl.first;
1751     loop
1752       exit when i is null;
1753       print_debug('kle_asset_id: '||set_value_null(l_csm_line_details_tbl(i).kle_asset_id));
1754       print_debug('----------------------------------------------------');
1755       print_debug('asset_cost: '||set_value_null(l_csm_line_details_tbl(i).asset_cost));
1756       print_debug('residual_amount: '||set_value_null(l_csm_line_details_tbl(i).residual_amount));
1757       print_debug('residual_date: '||set_value_null(l_csm_line_details_tbl(i).residual_date));
1758       print_debug('description: '||set_value_null(l_csm_line_details_tbl(i).description));
1759       i := l_csm_line_details_tbl.next(i);
1760     end loop;
1761     print_debug('**END CONTENTS OF P_CSM_LINE_DETAILS_TBL***');
1762     print_debug('*******************************************');
1763   Exception
1764    	WHEN OTHERS THEN
1765       print_debug('error in procedure print_lease_tables');
1766       print_debug('sqlcode : ' || sqlcode || ' $ sqlerrm : ' || sqlerrm);
1767   END print_lease_tables;
1768 
1769   PROCEDURE print_var_int_tables(p_rbk_tbl IN rbk_tbl,
1770                                  p_strm_lalevl_tbl IN strm_lalevl_tbl) IS
1771 
1772     l_api_name	        CONSTANT VARCHAR2(30) := 'print_var_int_tables';
1773     i NUMBER;
1774     d NUMBER;
1775     l_rbk_tbl rbk_tbl;
1776     l_strm_lalevl_tbl strm_lalevl_tbl;
1777   BEGIN
1778     l_rbk_tbl := p_rbk_tbl;
1779     l_strm_lalevl_tbl := p_strm_lalevl_tbl;
1780 
1781     print_debug('*******START CONTENTS OF P_RBK_TBL********');
1782     print_debug('******************************************');
1783     FOR i IN 1..l_rbk_tbl.COUNT
1784     LOOP
1785       print_debug('Rec#: '||i);
1786       print_debug('KHR ID: '||l_rbk_tbl(i).khr_id);
1787       print_debug('KLE ID: '||l_rbk_tbl(i).kle_id);
1788     END LOOP;
1789     print_debug('*********END CONTENTS OF P_RBK_TBL*********');
1790     print_debug('*******************************************');
1791 
1792     print_debug('***START CONTENTS OF P_STRM_LALEVL_TBL****');
1793     print_debug('******************************************');
1794     for d in 1..l_strm_lalevl_tbl.COUNT
1795     loop
1796       print_debug('Rec#: '||d);
1797       print_debug('-->Chr_Id :'||set_value_null(l_strm_lalevl_tbl(d).chr_id));
1798       print_debug('-->Cle_Id :'||set_value_null(l_strm_lalevl_tbl(d).cle_id));
1799       print_debug('-->Rule_Information_Category:'||set_value_null(l_strm_lalevl_tbl(d).rule_information_category));
1800 
1801       IF (l_strm_lalevl_tbl(d).rule_information_category = 'LASLH') THEN
1802         print_debug('-->Jtot_Object1_Code - stream_type_source :'||set_value_null(l_strm_lalevl_tbl(d).jtot_object1_code));
1803         print_debug('-->Jtot_Object2_Code - time_value :'||set_value_null(l_strm_lalevl_tbl(d).jtot_object2_code));
1804         print_debug('-->Object1_Id1 - sty_id :'||set_value_null(l_strm_lalevl_tbl(d).object1_id1));
1805         print_debug('-->Rule_Information1 - billing_schedule_type :'||set_value_null(l_strm_lalevl_tbl(d).Rule_Information1));
1806         print_debug('-->Rule_Information2 - rate_type :'||set_value_null(l_strm_lalevl_tbl(d).rule_information2));
1807       ELSE
1808         print_debug('-->Jtot_Object1_Code - time_unit_of_measure :'||set_value_null(l_strm_lalevl_tbl(d).jtot_object1_code));
1809         print_debug('-->Jtot_Object2_Code - stream_level_header :'||set_value_null(l_strm_lalevl_tbl(d).jtot_object2_code));
1810         print_debug('-->Object1_Id1 - Pay_freq :'||set_value_null(l_strm_lalevl_tbl(d).object1_id1));
1811         print_debug('-->Rule_Information1 - seq :'||set_value_null(l_strm_lalevl_tbl(d).Rule_Information1));
1812         print_debug('-->Rule_Information2 - start_date :'||set_value_null(l_strm_lalevl_tbl(d).rule_information2));
1813      END IF;
1814 
1815       print_debug('-->Rule_Information3 - number_periods :'||set_value_null(l_strm_lalevl_tbl(d).rule_information3));
1816       print_debug('-->Rule_Information4 - tuoms_per_period:'||set_value_null(l_strm_lalevl_tbl(d).rule_information4));
1817       print_debug('-->Rule_Information5 - structure:'||set_value_null(l_strm_lalevl_tbl(d).rule_information5));
1818       print_debug('-->Rule_Information6 - amount:'||set_value_null(l_strm_lalevl_tbl(d).rule_information6));
1819       print_debug('-->Rule_Information7 - stub_days:'||set_value_null(l_strm_lalevl_tbl(d).rule_information7));
1820       print_debug('-->Rule_Information8 - stub_amount:'||set_value_null(l_strm_lalevl_tbl(d).rule_information8));
1821       print_debug('-->Rule_Information10 - advance_or_arrears:'||set_value_null(l_strm_lalevl_tbl(d).rule_information10));
1822       print_debug('-->Rule_Information13 - rate:'||set_value_null(l_strm_lalevl_tbl(d).rule_information13));
1823 
1824       print_debug('-->Object1_Id2 :'||set_value_null(l_strm_lalevl_tbl(d).object1_id2));
1825       print_debug('-->Object2_Id1 :'||set_value_null(l_strm_lalevl_tbl(d).object2_id1));
1826       print_debug('-->Object2_Id2 :'||set_value_null(l_strm_lalevl_tbl(d).object2_id2));
1827     end loop;
1828     print_debug('***END CONTENTS OF P_STRM_LALEVL_TBL****');
1829     print_debug('******************************************');
1830 
1831   Exception
1832    	WHEN OTHERS THEN
1833       print_debug('error in procedure print_var_int_tables');
1834       print_debug('sqlcode : ' || sqlcode || ' $ sqlerrm : ' || sqlerrm);
1835   END print_var_int_tables;
1836 
1837 /*
1838   PROCEDURE interest_cal(
1839             p_api_version   IN   NUMBER,
1840             p_init_msg_list IN   VARCHAR2,
1841             x_return_status OUT NOCOPY VARCHAR2,
1842             x_msg_count     OUT NOCOPY NUMBER,
1843             x_msg_data      OUT NOCOPY VARCHAR2,
1844             p_interest_rec  IN   interest_rec,
1845             x_interest_rec  OUT NOCOPY interest_rec) IS
1846 
1847     ------------------------------------------------------------
1848     -- Declare Process variables
1849     ------------------------------------------------------------
1850 
1851     l_adder             NUMBER(5,2);
1852     l_adjustment_frequency  NUMBER;
1853     l_days_in_month     VARCHAR2(20);
1854     l_interest_start_date  DATE;
1855     l_method_of_calculation VARCHAR2(100);
1856     l_period_rate       NUMBER(5,2):= 0;
1857     l_days_tot          NUMBER:= 0;
1858     l_days_rate_tot     NUMBER:= 0;
1859     lx_rulv_rec		    Okl_Rule_Apis_Pvt.rulv_rec_type;
1860     l_index_name        VARCHAR2(100);
1861     l_last_int_rate     NUMBER:=0;
1862     l_date              DATE;
1863     l_first_time_calc   BOOLEAN:=FALSE;
1864     l_present_int_rate  NUMBER:=0;
1865     l_calc_days         NUMBER := 0;
1866     l_year_part         VARCHAR2(4);
1867     l_year_days         VARCHAR2(20) := '0';
1868     l_contract_start_date DATE;
1869     l_contract_end_date DATE;
1870     l_interest_amount  NUMBER;
1871     l_deal_type        okl_k_headers.deal_type%TYPE;
1872     l_last_interim_int_cal_date DATE;
1873     l_due_date         DATE;
1874     l_currency_code    okc_k_headers_b.currency_code%TYPE;
1875 
1876     l_interest_rec  interest_rec;
1877     lx_interest_rec interest_rec;
1878     ------------------------------------------------------------
1879     -- Declare variable Interest Cursor
1880     ------------------------------------------------------------
1881 
1882     CURSOR c_days_rate (p_start_date DATE, p_end_date DATE) IS
1883     select ive.value VALUE,
1884     (LEAST(trunc(p_end_date),NVL(datetime_invalid, sysdate))
1885     - GREATEST(trunc(p_start_date),datetime_valid)) DAYS
1886     ,idx.name index_name,
1887     GREATEST(trunc(p_start_date),datetime_valid) VALID_FROM,
1888     LEAST(trunc(p_end_date),NVL(datetime_invalid, sysdate)) VALID_UNTIL
1889     from okl_indices idx,
1890     okl_index_values ive
1891     where idx.id = ive.idx_id
1892     AND   ive.idx_id = l_interest_rec.index_name
1893     AND   (p_start_date between datetime_valid and nvl(datetime_invalid, SYSDATE)
1894     OR    (p_end_date between datetime_valid and nvl(datetime_invalid, SYSDATE))
1895     OR    (datetime_valid >= p_start_date AND nvl(datetime_invalid,SYSDATE) <= p_end_date) )
1896     order by VALID_FROM;
1897 
1898 
1899     CURSOR  c_implicit_rate (p_index_name VARCHAR2, p_end_date DATE) IS
1900     SELECT  val.value, ind.name index_name
1901     FROM    okl_index_values val
1902            ,okl_indices ind
1903     WHERE   val.idx_id = p_index_name
1904     AND     ind.id = val.idx_id
1905     AND     val.datetime_valid = (SELECT MAX(val.datetime_valid)
1906     FROM    OKL_INDEX_VALUES val ,
1907             OKL_INDICES ind
1908     WHERE   ind.id              =   val.idx_id
1909     AND     val.idx_id          =   p_index_name
1910     AND     val.datetime_valid <   p_end_date);
1911 
1912     CURSOR c_calc_start_date (c_contract_id NUMBER)IS
1913     select min(sel.stream_element_date)
1914     FROM    okl_strm_elements sel,okl_streams stm, okl_strm_type_b sty,
1915         okl_k_headers khr, okc_k_headers_b chr
1916     WHERE	stm.khr_id          =  c_contract_id
1917     AND	stm.active_yn		= 'Y'
1918     AND	stm.say_code		= 'CURR'
1919     AND	sty.id				= stm.sty_id
1920     AND (sty.stream_type_purpose = 'RENT' OR sty.stream_type_purpose = 'PRINCIPAL_PAYMENT')
1921     AND	sel.stm_id          = stm.id
1922     and khr.id              = stm.khr_id
1923     and chr.id              = khr.id
1924     and sel.stream_element_date > nvl(khr.date_last_interim_interest_cal,chr.start_date);
1925 
1926     CURSOR c_contract_start_date (c_contract_id NUMBER)IS
1927     SELECT  chr.start_date
1928         ,khr.deal_type
1929         ,khr.date_last_interim_interest_cal
1930         ,chr.end_date
1931         ,chr.currency_code
1932     FROM   okc_k_headers_b chr
1933         ,okl_k_headers khr
1934     WHERE	chr.id = c_contract_id
1935     AND     khr.id = chr.id;
1936 
1937     CURSOR c_last_int_rate(c_contract_id NUMBER)IS
1938     select max(tai.date_invoiced) last_date_invoiced, ipm.param_value int_rate
1939     from okl_trx_ar_invoices_v tai, okl_trx_params_b ipm
1940     where tai.khr_id = c_contract_id
1941     and tai.description = 'Variable Interest Stream Billing'
1942     and ipm.source_id = tai.id
1943     and param_value <> 0
1944     group by ipm.param_value;
1945 
1946 	BEGIN
1947 
1948   	-----------------------------------------------------------------
1949   	-- Initialize out parameters with in values
1950    	-----------------------------------------------------------------
1951 
1952     l_interest_rec := p_interest_rec;
1953 
1954     FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Calculating Interest');
1955     print_debug('In Interest Calculating Procedure');
1956    	-----------------------------------------------------------------
1957   	-- Derive Variable Interest Basis from Rules
1958    	-----------------------------------------------------------------
1959 
1960     Okl_Bp_Rules.extract_rules(
1961      	    p_api_version      => p_api_version,
1962  	        p_init_msg_list    => p_init_msg_list,
1963    	   	 	p_khr_id           => l_interest_rec.khr_id,
1964     			p_kle_id           => null,
1965     			p_rgd_code         => 'LAIIND',
1966     			p_rdf_code         => 'LAIVAR',
1967     			x_return_status    => x_return_status,
1968     			x_msg_count        => x_msg_count,
1969     			x_msg_data         => x_msg_data,
1970     			x_rulv_rec         => lx_rulv_rec);
1971 
1972 
1973 		IF 	(x_return_status = 'S' ) THEN
1974  				print_debug ('        -- Rules Found.');
1975   	ELSE
1976  				print_debug ('        -- Rules Error.');
1977 		END IF;
1978 
1979     l_interest_rec.variable_method  := lx_rulv_rec.rule_information1;
1980     l_interest_rec.index_name       := lx_rulv_rec.rule_information2;
1981     l_interest_rec.base_rate        := lx_rulv_rec.rule_information3;
1982     l_adder                         := lx_rulv_rec.rule_information4;
1983     l_interest_rec.minimum_rate     := lx_rulv_rec.rule_information6;
1984     l_interest_rec.maximum_rate     := lx_rulv_rec.rule_information5;
1985     l_interest_rec.tolerance        := lx_rulv_rec.rule_information7;
1986     --l_adjustment_frequency          := lx_rulv_rec.rule_information8;
1987 
1988     Okl_Bp_Rules.extract_rules(
1989      	    p_api_version      => p_api_version,
1990  	        p_init_msg_list    => p_init_msg_list,
1991    	   	 	p_khr_id           => l_interest_rec.khr_id,
1992     			p_kle_id           => null,
1993     			p_rgd_code         => 'LAIIND',
1994     			p_rdf_code         => 'LAICLC',
1995     			x_return_status    => x_return_status,
1996     			x_msg_count        => x_msg_count,
1997     			x_msg_data         => x_msg_data,
1998     			x_rulv_rec         => lx_rulv_rec);
1999 
2000 		IF 	(x_return_status = 'S' ) THEN
2001  				print_debug ('        -- Rules Found1.');
2002 		ELSE
2003  				print_debug ('        -- Rules Error.');
2004 		END IF;
2005 
2006 		print_debug ('        -- After Rules.'||lx_rulv_rec.rule_information1);
2007 
2008     l_interest_rec.days_in_year         := lx_rulv_rec.rule_information1;
2009 		print_debug ('        -- After Rules.');
2010     l_days_in_month                     := lx_rulv_rec.rule_information2;
2011     l_interest_rec.interest_method      := lx_rulv_rec.rule_information3;
2012     l_method_of_calculation             := lx_rulv_rec.rule_information5;
2013 
2014     print_debug('In Type: '||l_interest_rec.variable_method);
2015     --FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'In Type '||l_interest_rec.variable_method);
2016     FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Method of Calculation: '||l_interest_rec.variable_method);
2017 
2018     open c_last_int_rate(l_interest_rec.khr_id);
2019     fetch c_last_int_rate into l_date,l_last_int_rate;
2020     l_first_time_calc := FALSE;
2021     close c_last_int_rate;
2022 
2023     if(l_last_int_rate = 0) THEN
2024       l_last_int_rate := l_interest_rec.base_rate;
2025       l_first_time_calc := TRUE;
2026     END IF;
2027 
2028     print_debug (' Last Int Rate: '||l_last_int_rate);
2029   	------------------------------------------------------------
2030     -- Derive Interest Start Date
2031   	------------------------------------------------------------
2032     open c_contract_start_date(l_interest_rec.khr_id);
2033   	fetch c_contract_start_date into
2034          l_contract_start_date,l_deal_type, l_last_interim_int_cal_date, l_contract_end_date, l_currency_code;
2035   	close c_contract_start_date;
2036 
2037     If ((l_deal_type = 'LOAN' or l_deal_type ='LOAN-REVOLVING') AND
2038          (l_interest_rec.variable_method = 'FLOAT')) THEN
2039 
2040       OKL_STREAM_GENERATOR_PVT.get_next_billing_date(
2041                 p_api_version            => p_api_version,
2042        	        p_init_msg_list          => p_init_msg_list,
2043         	   	 	p_khr_id                 => l_interest_rec.khr_id,
2044                 p_billing_date           => l_last_interim_int_cal_date,
2045                 x_next_due_date          => l_due_date,
2046                 x_next_period_start_date => l_interest_rec.start_date,
2047                 x_next_period_end_date   => l_due_date,
2048           			x_return_status          => x_return_status,
2049           			x_msg_count              => x_msg_count,
2050           			x_msg_data               => x_msg_data);
2051 
2052       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Stream Element Date: '|| l_due_date);
2053 
2054       print_debug('Stream Element Date: '||l_due_date);
2055 
2056     else
2057       print_debug('Contract Id: ' || l_interest_rec.khr_id);
2058       print_debug('Interest Start Date before: '||l_interest_rec.start_date);
2059     	open c_calc_start_date(l_interest_rec.khr_id);
2060     	fetch c_calc_start_date into l_interest_rec.start_date;
2061     	close c_calc_start_date;
2062       print_debug('Interest Start Date after: '||l_interest_rec.start_date);
2063 
2064       if(l_interest_rec.start_date is null) THEN
2065         l_interest_rec.start_date := l_contract_start_date;
2066       end if;
2067 
2068     end if;
2069 
2070     print_debug('Interest Start Date: '||l_interest_rec.start_date||
2071                     ' Contract Start Date: '||l_contract_start_date ||
2072                     ' Contract End Date: '||l_contract_end_date);
2073     FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'Interest Start Date: '||l_interest_rec.start_date);
2074     FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'Contract Start Date: '||l_contract_start_date);
2075     FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'Contract End Date: '||l_contract_end_date);
2076 
2077     x_interest_rec.interest_amount := 0;
2078   	------------------------------------------------------------
2079   	-- Derive Effective Interest Rate
2080    	------------------------------------------------------------
2081 
2082     l_interest_rec.effective_rate := l_interest_rec.base_rate;
2083 
2084     print_debug('Method of Calculation: '||l_interest_rec.variable_method||
2085                     ' Base Rate: '||l_interest_rec.base_rate);
2086 
2087     --    FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Method of Calculation: '||l_interest_rec.variable_method);
2088     IF l_interest_rec.variable_method = 'FIXEDADJUST' THEN
2089 
2090         --print_debug('Index Name: ' || to_char(l_interest_rec.index_name));
2091         OPEN c_implicit_rate(l_interest_rec.index_name,l_interest_rec.start_date);
2092         FETCH c_implicit_rate INTO l_interest_rec.effective_rate, l_index_name;
2093         CLOSE c_implicit_rate;
2094 
2095         l_interest_rec.effective_rate := l_interest_rec.effective_rate + l_adder;
2096 
2097         IF  l_interest_rec.effective_rate >= l_interest_rec.maximum_rate THEN
2098             l_interest_rec.effective_rate := l_interest_rec.maximum_rate;
2099         ELSIF  l_interest_rec.effective_rate <= l_interest_rec.minimum_rate THEN
2100             l_interest_rec.effective_rate := l_interest_rec.minimum_rate;
2101         END IF;
2102 
2103         x_interest_rec.effective_rate := l_interest_rec.effective_rate;
2104 
2105         FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Interest Rate: '||l_interest_rec.effective_rate);
2106         print_debug('Implicit Rate: '||l_interest_rec.effective_rate);
2107 
2108     ELSIF l_interest_rec.variable_method = 'FLOAT' THEN
2109 
2110       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Interest Start Date: '||l_interest_rec.start_date||
2111                     ' , Interest End Date: '||l_interest_rec.end_date);
2112       print_debug('Params for Interest Days Cursor: Start Date: '||l_interest_rec.start_date||
2113                     ' End Date: '||l_interest_rec.end_date);
2114 
2115       FOR r_days_rate IN c_days_rate (l_interest_rec.start_date, l_interest_rec.end_date )
2116       LOOP
2117 
2118         if(l_days_in_month = '30') THEN
2119           if(r_days_rate.VALID_FROM = l_contract_start_date or r_days_rate.VALID_FROM <> l_interest_rec.start_date) THEN
2120             FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'1 VALID_FROM: '||r_days_rate.VALID_FROM ||
2121                           'VALID_UNTIL: ' || r_days_rate.VALID_UNTIL);
2122             print_debug('No. of Days in Month in Contract Start Date');
2123             null;
2124           else
2125             print_debug('No. of Days in Month NOT in Contract Start Date');
2126             FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'2 VALID_FROM: '||r_days_rate.VALID_FROM ||
2127                           'VALID_UNTIL: ' || r_days_rate.VALID_UNTIL);
2128             --r_days_rate.VALID_FROM := r_days_rate.VALID_FROM +1;
2129             FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'3 VALID_FROM: '||r_days_rate.VALID_FROM ||
2130                           'VALID_UNTIL: ' || r_days_rate.VALID_UNTIL);
2131           end if;
2132           print_debug('Valid From: '||r_days_rate.VALID_FROM||' Valid To: '||r_days_rate.VALID_UNTIL);
2133 
2134           l_calc_days := OKL_STREAM_GENERATOR_PVT.get_day_count(r_days_rate.VALID_FROM,
2135                                                             r_days_rate.VALID_UNTIL,
2136                                                             'Y',
2137                                                             x_return_status);
2138           print_debug('No Of Days: '||l_calc_days);
2139         else
2140 
2141           FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'5 VALID_FROM: '||r_days_rate.VALID_FROM ||
2142                           'VALID_UNTIL: ' || r_days_rate.VALID_UNTIL);
2143           l_calc_days := (r_days_rate.VALID_UNTIL - r_days_rate.VALID_FROM + 1);
2144         end if;
2145 
2146         print_debug('Values from Interest Days Cursor-Interest Rate: '||r_days_rate.VALUE||
2147                     ' Date From: '||r_days_rate.VALID_FROM||' Date Until: '||r_days_rate.VALID_UNTIL
2148                     ||' No. of Days in Between: '||r_days_rate.DAYS);
2149 
2150         print_debug('No. of Days in Month: '||l_days_in_month||
2151                     ' Interest Calc. Days: '||l_calc_days);
2152 
2153         FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'No. of Days in Month: '||l_days_in_month);
2154         FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'Interest Calc. Days: '||l_calc_days);
2155 
2156         l_year_days := l_interest_rec.days_in_year;
2157 
2158         if(l_year_days = 'ACTUAL') THEN
2159           l_year_part := to_char(l_interest_rec.start_date, 'YYYY');
2160           l_year_days := (to_date(('01-01-'||(l_year_part+1)),'DD-MM-YYYY') -
2161                            to_date(('01-01-'||l_year_part), 'DD-MM-YYYY'));
2162         else
2163           l_year_days := l_interest_rec.days_in_year;
2164         end if;
2165 
2166         l_interest_rec.principle := get_tot_principal_amt(l_interest_rec.khr_id, r_days_rate.VALID_FROM);
2167 
2168         IF((abs(l_last_int_rate - (r_days_rate.VALUE+l_adder)) >= l_interest_rec.tolerance)
2169           OR(l_first_time_calc))  THEN
2170           l_present_int_rate := r_days_rate.VALUE + l_adder;
2171         ELSE
2172           l_present_int_rate := l_last_int_rate;
2173         END IF;
2174 
2175         --        l_days_tot :=  l_days_tot + r_days_rate.DAYS;
2176 
2177         IF  l_present_int_rate >= l_interest_rec.maximum_rate THEN
2178           l_present_int_rate := l_interest_rec.maximum_rate;
2179         ELSIF  l_present_int_rate <= l_interest_rec.minimum_rate THEN
2180           l_present_int_rate := l_interest_rec.minimum_rate;
2181         END IF;
2182 
2183         x_interest_rec.effective_rate := l_present_int_rate;
2184         l_interest_rec.effective_rate := l_present_int_rate;
2185 
2186         print_debug('Effective Interest Rate: '||l_interest_rec.effective_rate||' Principal: '||l_interest_rec.Principle
2187                     ||' Month Days: '||l_calc_days||' Year Days: '||l_year_days);
2188         FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'Effective Interest Rate: '||l_interest_rec.effective_rate);
2189         FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'Principal: '||l_interest_rec.Principle);
2190 
2191         -- l_days_rate_tot := l_days_rate_tot + r_days_rate.DAYS*l_present_int_rate;
2192 
2193         l_interest_amount := OKL_ACCOUNTING_UTIL.round_amount((l_interest_rec.Principle * l_interest_rec.effective_rate/100)* (l_calc_days/l_year_days),l_currency_code);
2194 
2195         x_interest_rec.interest_amount := l_interest_amount+ x_interest_rec.interest_amount;
2196 
2197         print_debug('Interest Amount: '||l_interest_amount||' Total Interest Amount: '||x_interest_rec.interest_amount);
2198         FND_FILE.PUT_LINE(FND_FILE.OUTPUT,'Interest Amount: '||l_interest_amount||' Total Interest Amount: '||x_interest_rec.interest_amount);
2199 
2200       END LOOP;
2201 
2202       --        l_interest_rec.effective_rate := l_days_rate_tot/l_days_tot;
2203       --        x_interest_rec.effective_rate := l_interest_rec.effective_rate;
2204     END IF;
2205   	------------------------------------------------------------
2206    	-- Derive Period Interest Amount
2207    	------------------------------------------------------------
2208 
2209     --    x_interest_rec.interest_amount := l_interest_rec.Principle * ((l_calc_days)/l_year_days) * l_interest_rec.effective_rate/100;
2210 
2211   EXCEPTION
2212         WHEN OTHERS THEN NULL;
2213 
2214   END interest_cal;
2215 
2216   PROCEDURE variable_interest_old(
2217         p_api_version   IN  NUMBER,
2218         p_init_msg_list IN  VARCHAR2,
2219         x_return_status OUT NOCOPY VARCHAR2,
2220         x_msg_count     OUT NOCOPY NUMBER,
2221         x_msg_data      OUT NOCOPY VARCHAR2,
2222         p_contract_number IN VARCHAR2,
2223         P_to_date       IN  DATE)
2224 
2225     IS
2226     ------------------------------------------------------------
2227     -- Declare variables required by APIs
2228     ------------------------------------------------------------
2229 
2230     l_api_version	    CONSTANT NUMBER := 1;
2231     l_api_name	        CONSTANT VARCHAR2(30) := 'VARIABLE_INTEREST';
2232     l_return_status	    VARCHAR2(1) := OKL_API.G_RET_STS_SUCCESS;
2233     l_msg_index_out     NUMBER;
2234     l_principle_balance NUMBER := 0;
2235     --l_interim_cal_yn    BOOLEAN;
2236 
2237   	l_reamort	        VARCHAR2(30);
2238     l_request_id        NUMBER;
2239     l_trans_status      VARCHAR2(30);
2240     lx_rulv_rec		    Okl_Rule_Apis_Pvt.rulv_rec_type;
2241     e_rulv_rec		    Okl_Rule_Apis_Pvt.rulv_rec_type;
2242 
2243   	------------------------------------------------------------
2244   	-- Initialise constants
2245   	------------------------------------------------------------
2246 
2247   	l_def_desc	CONSTANT VARCHAR2(80)	    := 'Variable Interest Stream Billing';
2248   	l_line_code	CONSTANT VARCHAR2(30)	    := 'LINE';
2249   	l_final_status	CONSTANT VARCHAR2(30)	:= 'SUBMITTED';
2250   	l_trx_type_name	CONSTANT VARCHAR2(30)	:= 'Billing';
2251   	l_trx_type_lang	CONSTANT VARCHAR2(30)	:= 'US';
2252   	l_date_entered	CONSTANT DATE		    := SYSDATE;
2253   	l_zero_amount	CONSTANT NUMBER		    := 0;
2254   	l_first_line	CONSTANT NUMBER		    := 1;
2255   	l_line_step	CONSTANT NUMBER		        := 1;
2256   	l_def_no_val	CONSTANT NUMBER		    := -1;
2257   	l_null_kle_id	CONSTANT NUMBER		    := -2;
2258 
2259   	------------------------------------------------------------
2260   	-- Declare local variables used in the program
2261   	------------------------------------------------------------
2262 
2263     l_sty_id                        okl_strm_type_v.id%TYPE;
2264 
2265   	l_khr_id	okl_trx_ar_invoices_v.khr_id%TYPE;
2266   	l_bill_date	okl_trx_ar_invoices_v.date_invoiced%TYPE;
2267   	l_trx_type	okl_trx_ar_invoices_v.try_id%TYPE;
2268   	l_kle_id	okl_txl_ar_inv_lns_v.kle_id%TYPE;
2269 
2270     l_curr_code     okc_k_headers_b.currency_code%TYPE;
2271     l_ste_amount    okl_strm_elements.amount%type;
2272 
2273 
2274   	l_line_number	okl_txl_ar_inv_lns_v.line_number%TYPE;
2275   	l_detail_number	okl_txd_ar_ln_dtls_v.line_detail_number%TYPE;
2276 
2277   	l_header_amount	okl_trx_ar_invoices_v.amount%TYPE;
2278   	l_line_amount	okl_txl_ar_inv_lns_v.amount%TYPE;
2279 
2280   	l_header_id	okl_trx_ar_invoices_v.id%TYPE;
2281   	l_line_id	okl_txl_ar_inv_lns_v.id%TYPE;
2282 
2283   	l_stm_date  	                    DATE;
2284   	l_reamort_date  	                DATE;
2285   	l_period_start_date  	            DATE;
2286   	l_period_end_date  	              DATE;
2287   	l_due_date  	                    DATE;
2288     l_last_interest_cal_date          DATE;
2289     l_end_of_process                  BOOLEAN := FALSE;
2290   	l_next_reamort_date  	            DATE;
2291 
2292 -- Cursor to evaluate contracts eligible for calculating Variable Interest depending on
2293 --    Principal Payment streams are between the last interest calculation date and the date
2294 --    user wants to run upto
2295 
2296     CURSOR c_contracts_csr ( l_contract_number VARCHAR2, p_to_date DATE )IS
2297                               SELECT distinct khr.id khr_id,
2298                                      khr.deal_type,
2299                                      khr.date_last_interim_interest_cal,
2300                                      chr.contract_number,
2301                                      chr.start_date start_date
2302                               FROM   okc_k_headers_b chr,
2303 			                               okl_k_headers   khr,
2304       			                         okc_statuses_b  khs,
2305 						                  			 okc_rules_b		rules,
2306                   									 okc_rule_groups_b	rgp
2307                               WHERE   CHR.CONTRACT_NUMBER = NVL(l_contract_number,CHR.CONTRACT_NUMBER)
2308               							  AND	khr.deal_type       IN ('LOAN','LEASEDF','LOAN-REVOLVING',
2309                                                             'LEASEST','LEASEOP')
2310     		                      AND	chr.id				= khr.id
2311     		                      AND	khs.code			= chr.sts_code
2312     		                      AND	khs.ste_code		= 'ACTIVE'
2313               							  AND	rules.dnz_chr_id	= chr.id
2314               							  AND	rules.rule_information_category	  = 'LAINTP'
2315               							  AND	rgp.id							  =	rules.rgp_id
2316               							  AND	rgp.chr_id						  = chr.id
2317               							  AND	rgp.rgd_code					  =	'LAIIND'
2318                               AND NVL(rules.rule_information1, 'N') = 'Y'
2319                               ORDER BY khr.deal_type, chr.contract_number;
2320 
2321     CURSOR c_strm_elements1(p_khr_id NUMBER, p_sty_id NUMBER) IS
2322         SELECT stm.id
2323         FROM   okl_streams stm
2324         WHERE  stm.khr_id = p_khr_id
2325         AND    stm.sty_id = p_sty_id;
2326 
2327     CURSOR c_stm_id_line_number(c_stm_id NUMBER) IS
2328     	SELECT SE_LINE_NUMBER
2329     	FROM   OKL_STRM_ELEMENTS_V
2330     	WHERE  stm_id = c_stm_id
2331     	ORDER BY SE_LINE_NUMBER DESC;
2332 
2333     CURSOR c_tran_num_csr IS
2334         SELECT  okl_sif_seq.nextval
2335         FROM    dual;
2336 
2337     --get next reamort date for a contract
2338     CURSOR l_next_reamort_date_csr(cp_khr_id IN NUMBER) IS
2339     SELECT add_months(NVL(date_last_interim_interest_cal, start_date), decode(pay_freq, 'M', 1, 'Q', 3, 'S', 6, 'A', 12, 1)) next_reamort_date
2340     FROM   okl_k_headers_full_v khr,
2341            (Select distinct rgp.dnz_chr_id khr_id
2342                   ,sll.object1_id1 Pay_freq
2343             from   okc_rules_b sll,
2344                    okc_rules_b slh,
2345                    okl_strm_type_b styp,
2346                    okc_rule_groups_b rgp
2347             where  to_number(sll.object2_id1) = slh.id
2348             and    sll.rule_information_category = 'LASLL'
2349             and    sll.dnz_chr_id  =  rgp.dnz_chr_id
2350             and    sll.rgp_id      = rgp.id
2351             and    slh.rule_information_category = 'LASLH'
2352             and    slh.dnz_chr_id  =  rgp.dnz_chr_id
2353             and    slh.rgp_id      = rgp.id
2354             and    slh.object1_id1 = styp.id
2355             and    styp.stream_type_purpose = 'RENT'
2356             and    rgp.rgd_code    = 'LALEVL'
2357             and    rgp.dnz_chr_id  = cp_khr_id
2358             ) pay
2359     where  khr.id = cp_khr_id
2360     and khr.id = pay.khr_id;
2361 
2362   	l_msg_count			number;
2363 
2364   	------------------------------------------------------------
2365   	-- Declare records: i - insert, u - update, r - result
2366   	------------------------------------------------------------
2367 
2368   	-- Transaction headers
2369   	i_taiv_rec	Okl_Trx_Ar_Invoices_Pub.taiv_rec_type;
2370   	u_taiv_rec	Okl_Trx_Ar_Invoices_Pub.taiv_rec_type;
2371   	r_taiv_rec	Okl_Trx_Ar_Invoices_Pub.taiv_rec_type;
2372 
2373   	-- Transaction lines
2374   	i_tilv_rec	Okl_Txl_Ar_Inv_Lns_Pub.tilv_rec_type;
2375   	u_tilv_rec	Okl_Txl_Ar_Inv_Lns_Pub.tilv_rec_type;
2376   	r_tilv_rec	Okl_Txl_Ar_Inv_Lns_Pub.tilv_rec_type;
2377 
2378   	-- Transaction line details
2379   	i_tldv_rec	        Okl_Txd_Ar_Ln_Dtls_Pub.tldv_rec_type;
2380   	u_tldv_rec	        Okl_Txd_Ar_Ln_Dtls_Pub.tldv_rec_type;
2381     l_init_tldv_rec     Okl_Txd_Ar_Ln_Dtls_Pub.tldv_rec_type;
2382   	r_tldv_rec	        Okl_Txd_Ar_Ln_Dtls_Pub.tldv_rec_type;
2383 
2384   	-- Stream elements
2385   	u_selv_rec	        Okl_Streams_Pub.selv_rec_type;
2386   	l_init_selv_rec	    Okl_Streams_Pub.selv_rec_type;
2387   	r_selv_rec	        Okl_Streams_Pub.selv_rec_type;
2388 
2389     ------------------------------------------------------------
2390     -- Declare records
2391     ------------------------------------------------------------
2392     l_interest_rec  interest_rec;
2393     lx_interest_rec interest_rec;
2394     e_interest_rec  interest_rec;
2395     l_selv_rec      Okl_Streams_Pub.selv_rec_type;
2396     lx_selv_rec     Okl_Streams_Pub.selv_rec_type;
2397     l_stmv_rec      Okl_Streams_Pub.stmv_rec_type;
2398     lx_stmv_rec     Okl_Streams_Pub.stmv_rec_type;
2399     l_taiv_rec	   Okl_Trx_Ar_Invoices_Pub.taiv_rec_type;
2400     lx_taiv_rec	   Okl_Trx_Ar_Invoices_Pub.taiv_rec_type;
2401     l_tilv_rec	   Okl_Txl_Ar_Inv_Lns_Pub.tilv_rec_type;
2402     lx_tilv_rec	   Okl_Txl_Ar_Inv_Lns_Pub.tilv_rec_type;
2403     l_tldv_rec	   Okl_Txd_Ar_Ln_Dtls_Pub.tldv_rec_type;
2404     lx_tldv_rec	   Okl_Txd_Ar_Ln_Dtls_Pub.tldv_rec_type;
2405     l_bpd_acc_rec   Okl_Acc_Call_Pub.bpd_acc_rec_type;
2406     l_ipm_rec	   OKL_IPM_PVT.ipm_rec_type;
2407     lx_ipm_rec	   OKL_IPM_PVT.ipm_rec_type;
2408 
2409   BEGIN
2410 
2411   	------------------------------------------------------------
2412    	-- Start processing
2413    	------------------------------------------------------------
2414 
2415   	x_return_status := OKL_API.G_RET_STS_SUCCESS;
2416 
2417    	l_return_status := OKL_API.START_ACTIVITY(
2418     		p_api_name	    => l_api_name,
2419        	p_pkg_name	    => g_pkg_name,
2420     		p_init_msg_list	=> p_init_msg_list,
2421     		l_api_version	=> l_api_version,
2422     		p_api_version	=> p_api_version,
2423     		p_api_type	    => '_PVT',
2424     		x_return_status	=> l_return_status);
2425 
2426     IF (l_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
2427    		RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
2428     ELSIF (l_return_status = OKL_API.G_RET_STS_ERROR) THEN
2429     	RAISE OKL_API.G_EXCEPTION_ERROR;
2430     END IF;
2431 
2432   	------------------------------------------------------------
2433   	-- Initialise local variables
2434   	------------------------------------------------------------
2435 
2436   	l_khr_id	:= l_def_no_val;
2437   	l_kle_id	:= l_def_no_val;
2438   	l_trx_type	:= get_trx_type (l_trx_type_name, l_trx_type_lang);
2439 
2440   	-- *****************************************************************
2441   	-- ** Get try_id (Added by STM) and stm_id (Added by RD)		   *
2442   	-- *****************************************************************
2443 
2444     -- **********************
2445     -- ** Process contracts *
2446     -- **********************
2447 
2448     print_debug('***Start of Processing***');
2449     print_debug('Contract Number: '||p_contract_number);
2450     FOR r_contracts_csr IN c_contracts_csr ( p_contract_number, p_to_date) LOOP
2451       print_debug ('--------------------------------------------------------------------------');
2452       print_debug ('--------------------------------------------------------------------------');
2453       print_debug ('Start Processing for Contract Number: ' ||r_contracts_csr.contract_number);
2454       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'--------------------------------------------------------------------------');
2455       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'--------------------------------------------------------------------------');
2456       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Start Processing for Contract Number: ' ||r_contracts_csr.contract_number);
2457       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Contract Start Date: ' || r_contracts_csr.start_date);
2458       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Last Interest Calculation Date: ' ||r_contracts_csr.date_last_interim_interest_cal);
2459 
2460       print_debug('Contract Number: '||r_contracts_csr.contract_number||' Contract Start Date: '||
2461                         r_contracts_csr.start_date||' Last Interest Calculation Date: '
2462                         ||r_contracts_csr.date_last_interim_interest_cal);
2463 
2464 
2465       -- Get sty_id for the contract
2466       Okl_Streams_Util.get_primary_stream_type(
2467 		p_khr_id => r_contracts_csr.khr_id,
2468 		p_primary_sty_purpose => 'VARIABLE_INTEREST',
2469 		x_return_status => l_return_status,
2470 		x_primary_sty_id => l_sty_id );
2471 
2472         IF 	(l_return_status = 'S' ) THEN
2473          	FND_FILE.PUT_LINE (FND_FILE.OUTPUT, '        -- Stream Id for purpose VARIABLE_INTEREST retrieved.');
2474          	print_debug ('        -- Stream Id for purpose VARIABLE_INTEREST retrieved.');
2475        	ELSE
2476          	FND_FILE.PUT_LINE (FND_FILE.LOG, '        -- ERROR: Could not retrieve Stream Id for purpose VARIABLE_INTEREST.');
2477       	END IF;
2478 
2479       	IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
2480         	RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
2481       	ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
2482         	RAISE Okl_Api.G_EXCEPTION_ERROR;
2483       	END IF;
2484 
2485       l_last_interest_cal_date := null;
2486       lx_rulv_rec := e_rulv_rec;  -- Initialize rule record
2487       --l_interim_cal_yn := FALSE;
2488       Okl_Bp_Rules.extract_rules(
2489            	    p_api_version      => p_api_version,
2490        	        p_init_msg_list    => p_init_msg_list,
2491         	   	 	p_khr_id           => r_contracts_csr.khr_id,
2492           			p_kle_id           => null,
2493           			p_rgd_code         => 'LAIIND',
2494           			p_rdf_code         => 'LAICLC',
2495           			x_return_status    => x_return_status,
2496           			x_msg_count        => x_msg_count,
2497           			x_msg_data         => x_msg_data,
2498           			x_rulv_rec         => lx_rulv_rec);
2499       l_reamort := lx_rulv_rec.rule_information5;
2500 
2501       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Method of Calculation: ' || l_reamort);
2502 
2503       if (r_contracts_csr.date_last_interim_interest_cal is not null
2504             and r_contracts_csr.date_last_interim_interest_cal > r_contracts_csr.start_date) THEN
2505             l_stm_date := r_contracts_csr.date_last_interim_interest_cal;
2506       elsif(lx_rulv_rec.rule_information4 is not null
2507                 and FND_DATE.canonical_to_date(lx_rulv_rec.rule_information4) > r_contracts_csr.start_date) THEN
2508             l_stm_date := FND_DATE.canonical_to_date(lx_rulv_rec.rule_information4);
2509       else
2510             l_stm_date := r_contracts_csr.start_date;
2511       end if;
2512 
2513 
2514       if (r_contracts_csr.date_last_interim_interest_cal is not null
2515             and r_contracts_csr.date_last_interim_interest_cal > r_contracts_csr.start_date) THEN
2516             l_reamort_date := r_contracts_csr.date_last_interim_interest_cal;
2517       else
2518             l_reamort_date := null;
2519       end if;
2520 
2521       print_debug('Stream Start Date: '||l_stm_date);
2522       print_debug('ReAmort Date: '||l_reamort_date);
2523       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'ReAmort Date: '||l_reamort_date);
2524 
2525       l_end_of_process := FALSE;
2526 
2527       IF l_reamort = 'REAMORT' THEN
2528         FOR c_next_reamort_date_csr in l_next_reamort_date_csr(r_contracts_csr.khr_id) LOOP
2529           print_debug('Length of To Due Date: ' || length(p_to_date));
2530           print_debug('Next ReAmort Date: '||c_next_reamort_date_csr.next_reamort_date || ' To Due Date: ' || p_to_date);
2531           IF (trunc(c_next_reamort_date_csr.next_reamort_date) > trunc(nvl(p_to_date, sysdate)))  THEN
2532             FND_FILE.PUT_LINE (FND_FILE.OUTPUT, 'Reamort date or contract start date is past the provided end date.');
2533             x_return_status := okl_api.G_RET_STS_SUCCESS;
2534             l_end_of_process := TRUE;
2535           END IF;
2536         END LOOP;
2537       END IF;
2538 
2539       IF (l_reamort = 'REAMORT' and not(l_end_of_process)) THEN
2540         --l_interim_cal_yn := TRUE;
2541         print_debug('ReAmort Date: '||l_reamort_date);
2542 
2543         initiate_request
2544                 (p_api_version	    => l_api_version
2545               	,p_init_msg_list	=> p_init_msg_list
2546                 ,p_contract_number  => r_contracts_csr.contract_number
2547                 ,p_from_date        => l_reamort_date
2548                 ,p_to_date          => NULL
2549               	,x_return_status	=> l_return_status
2550               	,x_msg_count	    => x_msg_count
2551               	,x_msg_data	    	=> x_msg_data
2552             		,x_request_id       => l_request_id
2553             		,x_trans_status     => l_trans_status);
2554         IF ( x_return_status = Fnd_Api.G_RET_STS_ERROR )  THEN
2555         	    RAISE Fnd_Api.G_EXC_ERROR;
2556         ELSIF (X_return_status = Fnd_Api.G_RET_STS_UNEXP_ERROR ) THEN
2557     	       RAISE Fnd_Api.G_EXC_UNEXPECTED_ERROR;
2558         END IF;
2559 
2560       ELSE
2561         FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Stream Start Date: '||l_stm_date);
2562         FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Contract Id: '||r_contracts_csr.khr_id);
2563         FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'To Date: '||p_to_date);
2564 
2565         print_debug('Stream Start Date: '||l_stm_date||' KHR ID: '||r_contracts_csr.khr_id||
2566                         ' To Date: '||p_to_date);
2567 
2568         l_last_interest_cal_date := r_contracts_csr.date_last_interim_interest_cal;
2569 
2570         l_end_of_process := FALSE;
2571         l_bill_date := null;
2572         l_due_date := null;
2573         LOOP
2574           If (r_contracts_csr.deal_type = 'LOAN' or r_contracts_csr.deal_type ='LOAN-REVOLVING') THEN
2575 
2576             OKL_STREAM_GENERATOR_PVT.get_next_billing_date(
2577                 p_api_version            => p_api_version,
2578        	        p_init_msg_list          => p_init_msg_list,
2579         	   	 	p_khr_id                 => r_contracts_csr.khr_id,
2580                 p_billing_date           => l_last_interest_cal_date,
2581                 x_next_due_date          => l_due_date,
2582                 x_next_period_start_date => l_period_start_date,
2583                 x_next_period_end_date   => l_period_end_date,
2584           			x_return_status          => x_return_status,
2585           			x_msg_count              => x_msg_count,
2586           			x_msg_data               => x_msg_data);
2587           end if;
2588 
2589           If (trunc(l_due_date) = l_last_interest_cal_date or
2590               l_due_date is null or
2591               trunc(l_due_date) > trunc(sysdate) or
2592               trunc(l_due_date) > trunc(p_to_date)) THEN
2593               --EXIT;
2594               l_end_of_process := TRUE;
2595           end if;
2596 
2597           FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Stream Element Date: '|| l_due_date);
2598 
2599           print_debug('Stream Element Date: '||l_due_date);
2600 
2601   	      x_return_status := OKL_API.G_RET_STS_SUCCESS;
2602           ----------------------------------------------------
2603           -- Create new transaction header for every
2604           -- contract and bill_date combination
2605           ----------------------------------------------------
2606           print_debug('Bill Date: '||l_due_date);
2607           print_debug('Bill Date: '||l_bill_date);
2608 
2609           FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Stream Element Date: '||l_due_date|| ', Bill Date: '||l_bill_date);
2610 
2611           IF (l_bill_date is null OR
2612              l_bill_date	<> l_due_date OR
2613              (l_bill_date is not null and l_end_of_process)) THEN
2614 
2615             print_debug('Bill Date: '||l_bill_date);
2616             print_debug('In KHR: '||l_khr_id);
2617       			---------------------------------------------
2618       			-- Save previous header amount except first record
2619       			---------------------------------------------
2620             IF l_khr_id <> l_def_no_val THEN
2621               print_debug('In KHR: '||l_khr_id);
2622 
2623               u_taiv_rec.id	:= l_header_id;
2624               u_taiv_rec.amount	:= l_header_amount;
2625 
2626               Okl_Trx_Ar_Invoices_Pub.update_trx_ar_invoices
2627       					(p_api_version
2628       					,p_init_msg_list
2629       					,l_return_status
2630       					,x_msg_count
2631       					,x_msg_data
2632       					,u_taiv_rec
2633       					,r_taiv_rec);
2634 
2635               IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
2636       					RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
2637               ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
2638       					RAISE Okl_Api.G_EXCEPTION_ERROR;
2639               END IF;
2640               print_debug('Updated the TAI record successfully');
2641               FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Updated the TAI record successfully');
2642               COMMIT;
2643             END IF;
2644 
2645       			---------------------------------------------
2646       			-- Populate required columns
2647       			---------------------------------------------
2648             IF NOT(l_end_of_process) THEN
2649       			  i_taiv_rec.khr_id		    := r_contracts_csr.khr_id;
2650       			  i_taiv_rec.date_invoiced	:= l_due_date;
2651       			  i_taiv_rec.try_id		    := l_trx_type;
2652       			  i_taiv_rec.date_entered		:= l_date_entered;
2653       			  i_taiv_rec.description		:= l_def_desc;
2654       			  i_taiv_rec.trx_status_code	:= l_final_status;
2655       			  i_taiv_rec.amount		    := l_zero_amount;
2656 
2657   	          ------------------------------------------------------------
2658   	          -- Derive Organization and Set of Books
2659 	            ------------------------------------------------------------
2660 
2661   	          SELECT CHR.currency_code
2662              	  ,CHR.authoring_org_id
2663                 ,hru.set_of_books_id
2664               INTO
2665                    i_taiv_rec.currency_code
2666                   ,i_taiv_rec.org_id
2667                   ,i_taiv_rec.set_of_books_id
2668               FROM   okc_k_headers_b CHR
2669                   ,hr_operating_units hru
2670               WHERE  CHR.id =  r_contracts_csr.khr_id
2671               AND    hru.organization_id = CHR.authoring_org_id;
2672 
2673               print_debug('Before inserting into TAI');
2674       			  ---------------------------------------------
2675       			  -- Insert transaction header record
2676               ---------------------------------------------
2677       			  Okl_Trx_Ar_Invoices_Pub.insert_trx_ar_invoices
2678         				(p_api_version
2679         				,p_init_msg_list
2680         				,l_return_status
2681         				,x_msg_count
2682         				,x_msg_data
2683         				,i_taiv_rec
2684         				,r_taiv_rec);
2685 
2686               IF 	(l_return_status = 'S' ) THEN
2687          				FND_FILE.PUT_LINE (FND_FILE.OUTPUT, '        -- Internal TXN Header Created.');
2688          				print_debug ('        -- Internal TXN Header Created.');
2689        			  ELSE
2690          				FND_FILE.PUT_LINE (FND_FILE.LOG, '        -- ERROR: Creating Internal TXN Header.');
2691       			  END IF;
2692 
2693       			  IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
2694         				RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
2695       			  ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
2696         				RAISE Okl_Api.G_EXCEPTION_ERROR;
2697       			  END IF;
2698 
2699       			  ---------------------------------------------
2700       			  -- Adjust header variables
2701       			  ---------------------------------------------
2702      		      print_debug ('Line Number: '||l_first_line);
2703       			  l_line_number	:= l_first_line;
2704       			  l_header_amount	:= l_zero_amount;
2705       			  l_header_id	    := r_taiv_rec.id;
2706               print_debug ('Line Number: '||l_line_number);
2707             END IF;
2708           END IF;
2709 
2710 
2711           ----------------------------------------------------
2712           -- Create new transaction line for every
2713           -- contract line and bill_date combination
2714           ----------------------------------------------------
2715           print_debug ('Bill Date xx: '||l_bill_date||' Equals : '||l_due_date);
2716 
2717           IF (l_bill_date is null  OR
2718               l_bill_date <> l_due_date OR
2719              (l_bill_date is not null and l_end_of_process)) THEN
2720 
2721             ---------------------------------------------
2722             -- Save previous line amount except first record
2723             ---------------------------------------------
2724             IF l_kle_id <> l_def_no_val THEN
2725       			  u_tilv_rec.id		:= l_line_id;
2726       			  u_tilv_rec.amount	:= l_line_amount;
2727 
2728       			  Okl_Txl_Ar_Inv_Lns_Pub.update_txl_ar_inv_lns
2729       					(p_api_version
2730       					,p_init_msg_list
2731       					,l_return_status
2732       					,x_msg_count
2733       					,x_msg_data
2734       					,u_tilv_rec
2735       					,r_tilv_rec);
2736 
2737               IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
2738       					RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
2739       			  ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
2740       					RAISE Okl_Api.G_EXCEPTION_ERROR;
2741       			  END IF;
2742 
2743             END IF;
2744 
2745       			---------------------------------------------
2746       			-- Populate required columns
2747       			---------------------------------------------
2748             ---------------------------------------------
2749             -- Insert transaction line record
2750             ---------------------------------------------
2751 
2752             IF NOT(l_end_of_process) THEN
2753               i_tilv_rec.org_id		            := i_taiv_rec.org_id;
2754       			  i_tilv_rec.line_number		        := l_line_number;
2755       			  i_tilv_rec.tai_id		            := l_header_id;
2756       			  i_tilv_rec.description		        := l_def_desc;
2757       			  i_tilv_rec.inv_receiv_line_code	    := l_line_code;
2758       			  i_tilv_rec.amount		            := l_zero_amount;
2759       			  i_tilv_rec.date_bill_period_start   := l_due_date;
2760               --i_tilv_rec.date_bill_period_end	    := l_oks_bill_rec.DATE_BILLED_TO;
2761 
2762       			  ---------------------------------------------
2763       			  -- Columns which are not used by stream billing
2764       			  ---------------------------------------------
2765       			  i_tilv_rec.til_id_reverses	:= NULL;
2766       			  i_tilv_rec.tpl_id		    := NULL;
2767       			  i_tilv_rec.acn_id_cost		:= NULL;
2768       			  i_tilv_rec.sty_id		    := NULL;
2769       			  i_tilv_rec.quantity		    := NULL;
2770       			  i_tilv_rec.amount_applied	:= NULL;
2771       			  i_tilv_rec.org_id		    := NULL;
2772       			  i_tilv_rec.receivables_invoice_id := NULL;
2773 
2774       			  ---------------------------------------------
2775       			  -- Insert transaction line record
2776       			  ---------------------------------------------
2777       			  Okl_Txl_Ar_Inv_Lns_Pub.insert_txl_ar_inv_lns
2778         				(p_api_version
2779         				,p_init_msg_list
2780         				,l_return_status
2781         				,x_msg_count
2782         				,x_msg_data
2783         				,i_tilv_rec
2784         				,r_tilv_rec);
2785 
2786               IF (l_return_status = 'S' ) THEN
2787                 FND_FILE.PUT_LINE (FND_FILE.OUTPUT, '        -- Internal TXN Line Created.');
2788                 print_debug ('        -- Internal TXN Line Created.');
2789               ELSE
2790                 FND_FILE.PUT_LINE (FND_FILE.LOG, '        -- ERROR: Creating Internal TXN Line.');
2791       			  END IF;
2792 
2793       			  IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
2794         				RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
2795       			  ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
2796         				RAISE Okl_Api.G_EXCEPTION_ERROR;
2797       			  END IF;
2798 
2799       			  ---------------------------------------------
2800       			  -- Adjust line variables
2801       			  ---------------------------------------------
2802        			  print_debug ('Line Number before TXD: '||l_first_line);
2803       			  l_detail_number	:= l_first_line;
2804       			  l_line_amount	:= l_zero_amount;
2805       			  l_line_id	    := r_tilv_rec.id;
2806               l_line_number	:= l_line_number + l_line_step;
2807             END IF;
2808           END IF;
2809 
2810           IF (l_end_of_process) THEN
2811             EXIT;
2812           END IF;
2813 
2814           ----------------------------------------------------
2815           -- Create new transaction line detail for every stream
2816           ----------------------------------------------------
2817 
2818       	  ------------------------------------------------------------
2819       	  -- Derive Period Interest Amount
2820       	  ------------------------------------------------------------
2821 
2822           lx_interest_rec := e_interest_rec;
2823           l_interest_rec := e_interest_rec;
2824 
2825           l_interest_rec.khr_id   := r_contracts_csr.khr_id;
2826           --l_interest_rec.kle_id   := r_strm_elements.kle_id;
2827     		  l_interest_rec.end_date := l_due_date;
2828           --l_interest_rec.Principle:= r_strm_elements.amount;
2829 
2830 
2831           interest_cal(
2832                 p_api_version    =>     p_api_version,
2833                 p_init_msg_list  =>     p_init_msg_list,
2834                 x_return_status  =>     x_return_status,
2835                 x_msg_count      =>     x_msg_count,
2836                 x_msg_data       =>     x_msg_data,
2837                 p_interest_rec   =>     l_interest_rec,
2838                 x_interest_rec   =>     lx_interest_rec);
2839 
2840           l_ste_amount := lx_interest_rec.interest_amount;
2841           print_debug('Interest Amount Back: '||lx_interest_rec.interest_amount);
2842           FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Interest Amount Back: '||lx_interest_rec.interest_amount);
2843           print_debug('Interest Rate Back: '||lx_interest_rec.effective_rate);
2844 
2845           ------------------------------------------------------------
2846           -- Derive Stream Type
2847           ------------------------------------------------------------
2848           ------------------------------------------------------------
2849           -- Insert Stream Element
2850           ------------------------------------------------------------
2851 
2852           print_debug('KHR ID: '||r_contracts_csr.khr_id||
2853                                 'STY ID: '|| l_sty_id);
2854 
2855           l_selv_rec.stm_id := NULL;
2856 
2857           OPEN c_strm_elements1 (r_contracts_csr.khr_id, l_sty_id);
2858           FETCH c_strm_elements1 INTO l_selv_rec.stm_id;
2859           CLOSE c_strm_elements1;
2860 
2861           IF l_selv_rec.stm_id IS NULL THEN
2862 
2863             print_debug('No Streams');
2864 
2865            	OPEN  c_tran_num_csr;
2866            	FETCH c_tran_num_csr INTO l_stmv_rec.transaction_number;
2867             CLOSE c_tran_num_csr;
2868             FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'No Streams found.');
2869             FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Transaction Number : ' ||l_stmv_rec.transaction_number);
2870             print_debug('No Streams : '||l_stmv_rec.transaction_number);
2871 
2872             l_stmv_rec.sty_id                := l_sty_id;
2873             l_stmv_rec.khr_id                := r_contracts_csr.khr_id;
2874             l_stmv_rec.sgn_code              := 'MANL';
2875             l_stmv_rec.say_code              := 'CURR';
2876             l_stmv_rec.active_yn             := 'Y';
2877             l_stmv_rec.date_current          := sysdate;
2878             l_stmv_rec.comments              := 'Variable Interest';
2879 
2880             Okl_Streams_Pub.create_streams(
2881                     p_api_version    =>     p_api_version,
2882                     p_init_msg_list  =>     p_init_msg_list,
2883                     x_return_status  =>     x_return_status,
2884                     x_msg_count      =>     x_msg_count,
2885                     x_msg_data       =>     x_msg_data,
2886                     p_stmv_rec       =>     l_stmv_rec,
2887                     x_stmv_rec       =>     lx_stmv_rec);
2888 
2889             IF 	(x_return_status = 'S' ) THEN
2890        				print_debug ('        -- Success in Stream Creation.');
2891               FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'        -- Success in Stream Creation.');
2892        			ELSE
2893        				print_debug ('        -- Error: '||x_msg_data);
2894               FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'        -- Error: '||x_msg_data);
2895       			END IF;
2896 
2897        	    IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
2898         		    RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
2899       	    ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
2900           	   	    RAISE OKL_API.G_EXCEPTION_ERROR;
2901       	    END IF;
2902 
2903       			print_debug ('Stm ID: '||lx_stmv_rec.id);
2904             l_selv_rec.stm_id := lx_stmv_rec.id;
2905     		    print_debug ('Stm ID: '||l_selv_rec.stm_id);
2906 
2907           END IF;
2908 
2909           FND_FILE.PUT_LINE (FND_FILE.OUTPUT, 'Stream Id : '||to_char(l_selv_rec.stm_id));
2910           --FND_FILE.PUT_LINE (FND_FILE.OUTPUT, 'Stream Type Id: '||to_char(l_tilv_rec.sty_id));
2911 
2912           l_selv_rec.accrued_yn   := 'N';
2913           l_selv_rec.comments     := 'Variable Interest';
2914           l_selv_rec.stream_element_date := l_due_date;
2915           l_selv_rec.date_billed := SYSDATE;
2916           l_selv_rec.amount := lx_interest_rec.interest_amount;
2917 
2918           ----------- added by bv to populate mandatory field in table Okl_Strm_Elements.
2919           l_selv_rec.se_line_number := NULL;
2920           OPEN  c_stm_id_line_number(l_selv_rec.stm_id);
2921           FETCH c_stm_id_line_number INTO l_selv_rec.se_line_number;
2922           if(c_stm_id_line_number%rowcount = 0) THEN
2923             l_selv_rec.se_line_number := 1;
2924           else
2925             l_selv_rec.se_line_number := l_selv_rec.se_line_number+1;
2926           end if;
2927           CLOSE c_stm_id_line_number;
2928 
2929           Okl_Streams_Pub.create_stream_elements(
2930                 p_api_version    =>     p_api_version,
2931                 p_init_msg_list  =>     p_init_msg_list,
2932                 x_return_status  =>     x_return_status,
2933                 x_msg_count      =>     x_msg_count,
2934                 x_msg_data       =>     x_msg_data,
2935                 p_selv_rec       =>     l_selv_rec,
2936                 x_selv_rec       =>     lx_selv_rec);
2937 
2938           IF 	(x_return_status = 'S' ) THEN
2939        			print_debug ('        -- Success in Creating Stream Elements.');
2940             FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'        -- Success in Creating Stream Elements.');
2941   	      ELSE
2942       			print_debug ('        -- Error: '||x_msg_data);
2943             FND_FILE.PUT_LINE (FND_FILE.OUTPUT,' -- Error in Creating Stream'||x_msg_data);
2944     		  END IF;
2945 
2946 
2947    	      IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
2948     		    RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
2949    	      ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
2950     		    RAISE OKL_API.G_EXCEPTION_ERROR;
2951    	      END IF;
2952 
2953           ---------------------------------------------
2954           -- Insert record in IPM
2955           ---------------------------------------------
2956           l_ipm_rec.source_table		:= 'OKL_TRX_AR_INVOICES_V';
2957           l_ipm_rec.source_id	        := r_taiv_rec.id;
2958           l_ipm_rec.param_name		:= 'VARIABLE_INT_RATE';
2959           l_ipm_rec.param_value	    := lx_interest_rec.effective_rate;
2960           print_debug('Interest Rate in IPM: '||l_ipm_rec.param_value);
2961           print_debug('TAI: '||r_taiv_rec.id);
2962 
2963   	      OKL_IPM_PVT.insert_row
2964     				(p_api_version  => p_api_version
2965     				,p_init_msg_list=> p_init_msg_list
2966     				,x_return_status=> x_return_status
2967     				,x_msg_count    => x_msg_count
2968     				,x_msg_data     => x_msg_data
2969     				,p_ipm_rec     => l_ipm_rec
2970     				,x_ipm_rec     => lx_ipm_rec);
2971 
2972 
2973           IF 	(x_return_status = 'S' ) THEN
2974             print_debug ('        -- IPM Inserted .');
2975             FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'        -- IPM Inserted .');
2976           ELSE
2977             print_debug ('        -- IPM Error: '||x_msg_data);
2978             FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'        -- IPM Error.'||x_msg_data);
2979           END IF;
2980           FND_FILE.PUT_LINE (FND_FILE.OUTPUT, 'After Inserting into Trx Params - Status: '||x_return_status);
2981 
2982           ----------------------------------------------------
2983           -- Populate required columns
2984           ----------------------------------------------------
2985           FND_FILE.PUT_LINE (FND_FILE.OUTPUT, 'Stream Type: '||l_sty_id);
2986           print_debug ('        -- line detail number: '||l_detail_number);
2987 
2988           i_tldv_rec.sty_id                   := l_sty_id;
2989           i_tldv_rec.amount			        := lx_interest_rec.interest_amount;
2990     		  i_tldv_rec.description		        := l_def_desc;
2991           --i_tldv_rec.sel_id			        := lx_selv_rec.id;
2992     		  i_tldv_rec.til_id_details	        := l_line_id;
2993     		  i_tldv_rec.line_detail_number		:= l_detail_number;
2994           i_tldv_rec.date_calculation		    := SYSDATE;
2995           --i_tldv_rec.org_id			        := i_taiv_rec.org_id;
2996 
2997           ----------------------------------------------------
2998      		  -- Insert transaction line detail record
2999     		  ----------------------------------------------------
3000           Okl_Txd_Ar_Ln_Dtls_Pub.insert_txd_ar_ln_dtls
3001       			(p_api_version
3002       			,p_init_msg_list
3003       			,l_return_status
3004       			,x_msg_count
3005       			,x_msg_data
3006       			,i_tldv_rec
3007       			,r_tldv_rec);
3008 
3009           IF (l_return_status = 'S' ) THEN
3010               FND_FILE.PUT_LINE (FND_FILE.OUTPUT, '        -- Internal TXN Details Created.');
3011               print_debug ('        -- Internal TXN Details Created.');
3012           ELSE
3013               FND_FILE.PUT_LINE (FND_FILE.OUTPUT, '        -- ERROR: Creating Internal TXN Details.');
3014               print_debug ('        -- ERROR: Creating Internal TXN Details.');
3015               FOR i in 1..x_msg_count
3016               LOOP
3017                 FND_MSG_PUB.GET(
3018                       p_msg_index     => i,
3019                       p_encoded       => FND_API.G_FALSE,
3020                       p_data          => x_msg_data,
3021                       p_msg_index_out => l_msg_index_out
3022                      );
3023                 FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Error '||to_char(i)||': '||x_msg_data);
3024                 FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Message Index: '||l_msg_index_out);
3025                 print_debug('Error '||to_char(i)||': '||x_msg_data);
3026                 print_debug('Message Index: '||l_msg_index_out);
3027               END LOOP;
3028           END IF;
3029 
3030           IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
3031   			    RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
3032           ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
3033   			    RAISE Okl_Api.G_EXCEPTION_ERROR;
3034           END IF;
3035 
3036     		  l_bpd_acc_rec.id 		   := r_tldv_rec.id;
3037     		  l_bpd_acc_rec.source_table := 'OKL_TXD_AR_LN_DTLS_B';
3038     		  ----------------------------------------------------
3039     		  -- Create Accounting Distributions
3040     		  ----------------------------------------------------
3041           Okl_Acc_Call_Pub.CREATE_ACC_TRANS(
3042        			p_api_version
3043     		   ,p_init_msg_list
3044     		   ,x_return_status
3045     		   ,x_msg_count
3046     		   ,x_msg_data
3047   			   ,l_bpd_acc_rec);
3048 
3049    	      IF 	(x_return_status = 'S' ) THEN
3050               FND_FILE.PUT_LINE (FND_FILE.OUTPUT, '        -- Accounting Distributions Created.');
3051               print_debug ('        -- Accounting Distributions Created.');
3052           ELSE
3053               FND_FILE.PUT_LINE (FND_FILE.OUTPUT, '        -- ERROR: Accounting Distributions NOT Created.');
3054               print_debug ('        -- ERROR: Accounting Distributions NOT Created.');
3055               FOR i in 1..x_msg_count
3056               LOOP
3057                 FND_MSG_PUB.GET(
3058                       p_msg_index     => i,
3059                       p_encoded       => FND_API.G_FALSE,
3060                       p_data          => x_msg_data,
3061                       p_msg_index_out => l_msg_index_out
3062                      );
3063                 FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Error '||to_char(i)||': '||x_msg_data);
3064                 FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Message Index: '||l_msg_index_out);
3065                 print_debug('Error '||to_char(i)||': '||x_msg_data);
3066                 print_debug('Message Index: '||l_msg_index_out);
3067               END LOOP;
3068           END IF;
3069 
3070 
3071           IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
3072       			RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
3073      		  ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
3074       			RAISE Okl_Api.G_EXCEPTION_ERROR;
3075     		  END IF;
3076 
3077     		  ----------------------------------------------------
3078     		  -- Adjust line variables
3079     		  ----------------------------------------------------
3080 
3081     		  l_khr_id 	    := r_contracts_csr.khr_id;
3082     		  l_bill_date	    := l_due_date;
3083     		  l_header_amount	:= l_header_amount + l_ste_amount;
3084     		  l_line_amount	:= l_line_amount   + l_ste_amount;
3085      		  l_detail_number	:= l_detail_number + l_line_step;
3086 
3087 
3088 
3089           FND_FILE.PUT_LINE (FND_FILE.LOG, '===============================================================================');
3090 
3091           UPDATE okl_k_headers khr
3092               SET khr.date_last_interim_interest_cal =  l_due_date
3093               where khr.id = r_contracts_csr.khr_id;
3094 
3095           l_last_interest_cal_date := l_due_date;
3096           FND_FILE.PUT_LINE (FND_FILE.OUTPUT, 'After Updating Contract Header : Status'||x_return_status);
3097 
3098         END LOOP;
3099 --
3100 --        ---------------------------------------------------
3101 --        -- Commit the present record
3102 --        ---------------------------------------------------
3103 --        COMMIT;
3104 --
3105       END IF;
3106       FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'End Processing for Contract Number: ' ||r_contracts_csr.contract_number);
3107       print_debug ('End Processing for Contract Number: ' ||r_contracts_csr.contract_number);
3108     END LOOP;
3109     print_debug('***End of Processing***');
3110 
3111   	OKL_API.END_ACTIVITY (x_msg_count, x_msg_data);
3112 
3113   EXCEPTION
3114     	------------------------------------------------------------
3115     	-- Exception handling
3116     	------------------------------------------------------------
3117 
3118     WHEN OKL_API.G_EXCEPTION_ERROR THEN
3119   		x_return_status := OKL_API.HANDLE_EXCEPTIONS (
3120     					p_api_name	=> l_api_name,
3121     					p_pkg_name	=> G_PKG_NAME,
3122     					p_exc_name	=> 'OKL_API.G_RET_STS_ERROR',
3123     					x_msg_count	=> x_msg_count,
3124     					x_msg_data	=> x_msg_data,
3125     					p_api_type	=> '_PVT');
3126 
3127     WHEN OKL_API.G_EXCEPTION_UNEXPECTED_ERROR THEN
3128    		x_return_status := OKL_API.HANDLE_EXCEPTIONS (
3129     					p_api_name	=> l_api_name,
3130     					p_pkg_name	=> G_PKG_NAME,
3131     					p_exc_name	=> 'OKL_API.G_RET_STS_UNEXP_ERROR',
3132     					x_msg_count	=> x_msg_count,
3133     					x_msg_data	=> x_msg_data,
3134     					p_api_type	=> '_PVT');
3135 
3136     WHEN OTHERS THEN
3137    		x_return_status := OKL_API.HANDLE_EXCEPTIONS (
3138     					p_api_name	=> l_api_name,
3139     					p_pkg_name	=> G_PKG_NAME,
3140     					p_exc_name	=> 'OTHERS',
3141     					x_msg_count	=> x_msg_count,
3142     					x_msg_data	=> x_msg_data,
3143     					p_api_type	=> '_PVT');
3144 
3145   END variable_interest_old;
3146 */
3147 
3148   ------------------------------------------------------------------------------
3149   -- Function GET_PRINT_LEAD_DAYS to extract lead days for invoice generation
3150   ------------------------------------------------------------------------------
3151   FUNCTION get_printing_lead_days
3152 	(p_khr_id		NUMBER)
3153 	RETURN		NUMBER IS
3154 
3155     -- Derive print lead days from the rules
3156     CURSOR c_lead_days(p_khr_id IN NUMBER) IS
3157 	SELECT rule_information3
3158     FROM  okc_rules_b rule,
3159           okc_rule_groups_b rgp
3160     WHERE rgp.id = rule.rgp_id
3161     AND   rgp.dnz_chr_id = p_khr_id
3162     AND   rgd_code = 'LABILL'
3163     AND   rule_information_category = 'LAINVD';
3164 
3165     --Derive print lead days from receivables setup
3166     CURSOR c_default_lead_days(p_khr_id IN NUMBER) IS
3167 	SELECT term.printing_lead_days
3168     FROM  okl_k_headers_full_v khr
3169          ,hz_customer_profiles cp
3170          ,ra_terms term
3171     WHERE khr.id = p_khr_id
3172     AND khr.bill_to_site_use_id = cp.site_use_id
3173     AND cp.standard_terms = term.term_id;
3174 
3175     l_printing_lead_days NUMBER := 0;
3176   BEGIN
3177     OPEN c_lead_days(p_khr_id);
3178     FETCH c_lead_days INTO l_printing_lead_days;
3179     CLOSE c_lead_days;
3180 
3181     IF (l_printing_lead_days IS NULL) THEN
3182       OPEN c_default_lead_days(p_khr_id);
3183       FETCH c_default_lead_days INTO l_printing_lead_days;
3184       CLOSE c_default_lead_days;
3185     END IF;
3186 
3187     RETURN NVL(l_printing_lead_days, 0);
3188   END get_printing_lead_days;
3189 
3190   ------------------------------------------------------------------------------
3191 
3192     -- Start of Comments
3193     -- Created By:       Ramesh Seela
3194     -- Function Name    get_prorated_principal_amt_line
3195     -- Description:     Derives the principal amount from the loan amount passed.
3196     -- Dependencies:
3197     -- Parameters:       contract line id, stream element date, loan amount, and the currency code
3198     -- Version:          1.0
3199     -- End of Comments
3200 
3201   ------------------------------------------------------------------------------
3202   FUNCTION get_prorated_prin_amt_line (
3203             p_line_id             IN  NUMBER,
3204             p_stream_element_date IN  DATE,
3205             p_loan_amount         IN  NUMBER,
3206             p_currency_code       IN  VARCHAR2) RETURN NUMBER IS
3207 
3208   Cursor stream_element_interest_csr (p_line_id             NUMBER,
3209                                       p_stream_element_date DATE) IS
3210       SELECT nvl(sel_int_pmt.amount, 0) interest
3211       FROM   okl_strm_type_v sty_int_pmt
3212              ,okl_streams_v stm_int_pmt
3213              ,okl_strm_elements_v sel_int_pmt
3214        WHERE stm_int_pmt.kle_id = p_line_id
3215          AND stm_int_pmt.id = sel_int_pmt.stm_id
3216          AND sel_int_pmt.stream_element_date = p_stream_element_date
3217          AND stm_int_pmt.sty_id = sty_int_pmt.id
3218          AND stm_int_pmt.active_yn = 'Y'
3219          AND stm_int_pmt.say_code = 'CURR'
3220          AND sty_int_pmt.stream_type_purpose IN ('INTEREST_PAYMENT', 'VARIABLE_INTEREST');
3221 
3222   Cursor stream_element_principal_csr (p_line_id             NUMBER,
3223                                        p_stream_element_date DATE) IS
3224       SELECT nvl(sel_prin_pmt.amount, 0) principal
3225       FROM   okl_strm_type_v sty_prin_pmt
3226              ,okl_streams_v stm_prin_pmt
3227              ,okl_strm_elements_v sel_prin_pmt
3228        WHERE stm_prin_pmt.kle_id = p_line_id
3229          AND stm_prin_pmt.id = sel_prin_pmt.stm_id
3230          AND sel_prin_pmt.stream_element_date = p_stream_element_date
3231          AND stm_prin_pmt.sty_id = sty_prin_pmt.id
3232          AND stm_prin_pmt.active_yn = 'Y'
3233          AND stm_prin_pmt.say_code = 'CURR'
3234          AND sty_prin_pmt.stream_type_purpose = 'PRINCIPAL_PAYMENT';
3235 
3236   l_interest           okl_strm_elements_v.amount%TYPE;
3237   l_principal          okl_strm_elements_v.amount%TYPE;
3238   l_prorated_principal okl_strm_elements_v.amount%TYPE;
3239   BEGIN
3240     OPEN stream_element_interest_csr (p_line_id, p_stream_element_date);
3241     FETCH stream_element_interest_csr INTO l_interest;
3242     IF stream_element_interest_csr%NOTFOUND THEN
3243         l_interest := 0;
3244         l_prorated_principal := p_loan_amount;
3245         RETURN l_prorated_principal;
3246     END IF;
3247     CLOSE stream_element_interest_csr;
3248 
3249     OPEN stream_element_principal_csr (p_line_id, p_stream_element_date);
3250     FETCH stream_element_principal_csr INTO l_principal;
3251     IF stream_element_principal_csr%NOTFOUND THEN
3252         l_interest := 0;
3253         l_prorated_principal := p_loan_amount;
3254         RETURN l_prorated_principal;
3255     END IF;
3256     CLOSE stream_element_principal_csr;
3257 
3258     IF (( l_interest <> 0 ) AND (l_principal <> 0)) THEN
3259       l_prorated_principal :=  (p_loan_amount * l_principal) /(l_principal + l_interest);
3260       RETURN l_prorated_principal;
3261     ELSE
3262       RETURN p_loan_amount;
3263     END IF;
3264   EXCEPTION
3265       WHEN OTHERS THEN
3266       IF ( stream_element_interest_csr%ISOPEN ) THEN
3267          CLOSE stream_element_interest_csr;
3268       END IF;
3269       IF ( stream_element_principal_csr%ISOPEN ) THEN
3270          CLOSE stream_element_interest_csr;
3271       END IF;
3272       RETURN NULL;
3273   END;
3274 
3275   ------------------------------------------------------------------------------
3276 
3277     -- Start of Comments
3278     -- Created By:       Ramesh Seela
3279     -- Function Name    get_prorated_prin_amt_header
3280     -- Description:     Derives the principal amount from the loan amount passed.
3281     -- Dependencies:
3282     -- Parameters:      contract id, contract line id, stream element date, loan amount, and the currency code
3283     -- Version:          1.0
3284     -- End of Comments
3285 
3286   ------------------------------------------------------------------------------
3287   FUNCTION get_prorated_prin_amt_header (
3288             p_contract_id         IN  NUMBER,
3289             p_line_id             IN  NUMBER,
3290             p_stream_element_date IN  DATE,
3291             p_loan_amount         IN  NUMBER,
3292             p_currency_code       IN  VARCHAR2) RETURN NUMBER IS
3293 
3294   Cursor strm_elem_int_line_csr (p_line_id             NUMBER,
3295                                  p_stream_element_date DATE) IS
3296       SELECT nvl(sel_int_pmt.amount, 0) interest
3297       FROM   okl_strm_type_v sty_int_pmt
3298              ,okl_streams_v stm_int_pmt
3299              ,okl_strm_elements_v sel_int_pmt
3300        WHERE stm_int_pmt.kle_id = p_line_id
3301          AND stm_int_pmt.id = sel_int_pmt.stm_id
3302          AND sel_int_pmt.stream_element_date = p_stream_element_date
3303          AND stm_int_pmt.sty_id = sty_int_pmt.id
3304          AND stm_int_pmt.active_yn = 'Y'
3305          AND stm_int_pmt.say_code = 'CURR'
3306          AND sty_int_pmt.stream_type_purpose IN ('INTEREST_PAYMENT', 'VARIABLE_INTEREST');
3307 
3308   Cursor strm_elem_prin_line_csr (p_line_id             NUMBER,
3309                                   p_stream_element_date DATE) IS
3310       SELECT nvl(sel_prin_pmt.amount, 0) principal
3311       FROM   okl_strm_type_v sty_prin_pmt
3312              ,okl_streams_v stm_prin_pmt
3313              ,okl_strm_elements_v sel_prin_pmt
3314        WHERE stm_prin_pmt.kle_id = p_line_id
3315          AND stm_prin_pmt.id = sel_prin_pmt.stm_id
3316          AND sel_prin_pmt.stream_element_date = p_stream_element_date
3317          AND stm_prin_pmt.sty_id = sty_prin_pmt.id
3318          AND stm_prin_pmt.active_yn = 'Y'
3319          AND stm_prin_pmt.say_code = 'CURR'
3320          AND sty_prin_pmt.stream_type_purpose = 'PRINCIPAL_PAYMENT';
3321 
3322   Cursor strm_elem_int_hdr_csr (p_khr_id             NUMBER,
3323                                 p_stream_element_date DATE) IS
3324       SELECT nvl(sel_int_pmt.amount, 0) interest
3325       FROM   okl_strm_type_v sty_int_pmt
3326              ,okl_streams_v stm_int_pmt
3327              ,okl_strm_elements_v sel_int_pmt
3328        WHERE stm_int_pmt.khr_id = p_khr_id
3329          AND stm_int_pmt.id = sel_int_pmt.stm_id
3330          AND sel_int_pmt.stream_element_date = p_stream_element_date
3331          AND stm_int_pmt.sty_id = sty_int_pmt.id
3332          AND stm_int_pmt.active_yn = 'Y'
3333          AND stm_int_pmt.say_code = 'CURR'
3334          AND sty_int_pmt.stream_type_purpose IN ('INTEREST_PAYMENT', 'VARIABLE_INTEREST');
3335 
3336   Cursor strm_elem_prin_hdr_csr ( p_khr_id              NUMBER,
3337                                   p_stream_element_date DATE) IS
3338       SELECT nvl(sel_prin_pmt.amount, 0) principal
3339       FROM   okl_strm_type_v sty_prin_pmt
3340              ,okl_streams_v stm_prin_pmt
3341              ,okl_strm_elements_v sel_prin_pmt
3342        WHERE stm_prin_pmt.khr_id = p_khr_id
3343          AND stm_prin_pmt.id = sel_prin_pmt.stm_id
3344          AND sel_prin_pmt.stream_element_date = p_stream_element_date
3345          AND stm_prin_pmt.sty_id = sty_prin_pmt.id
3346          AND stm_prin_pmt.active_yn = 'Y'
3347          AND stm_prin_pmt.say_code = 'CURR'
3348          AND sty_prin_pmt.stream_type_purpose = 'PRINCIPAL_PAYMENT';
3349 
3350   l_interest           okl_strm_elements_v.amount%TYPE;
3351   l_principal          okl_strm_elements_v.amount%TYPE;
3352   l_prorated_principal okl_strm_elements_v.amount%TYPE;
3353   BEGIN
3354     IF (p_line_id IS NOT NULL) THEN
3355       OPEN strm_elem_int_line_csr (p_line_id, p_stream_element_date);
3356       FETCH strm_elem_int_line_csr INTO l_interest;
3357       IF strm_elem_int_line_csr%NOTFOUND THEN
3358         l_interest := 0;
3359         l_prorated_principal := p_loan_amount;
3360         RETURN l_prorated_principal;
3361       END IF;
3362       CLOSE strm_elem_int_line_csr;
3363 
3364       OPEN strm_elem_prin_line_csr (p_line_id, p_stream_element_date);
3365       FETCH strm_elem_prin_line_csr INTO l_principal;
3366       IF strm_elem_prin_line_csr%NOTFOUND THEN
3367         l_interest := 0;
3368         l_prorated_principal := p_loan_amount;
3369         RETURN l_prorated_principal;
3370       END IF;
3371       CLOSE strm_elem_prin_line_csr;
3372 
3373       IF (( l_interest <> 0 ) AND (l_principal <> 0)) THEN
3374         l_prorated_principal :=  (p_loan_amount * l_principal) /(l_principal + l_interest);
3375         RETURN l_prorated_principal;
3376       ELSE
3377         RETURN p_loan_amount;
3378       END IF;
3379     ELSE  /* p_line_id is NULL */
3380       OPEN strm_elem_int_hdr_csr (p_contract_id, p_stream_element_date);
3381       FETCH strm_elem_int_hdr_csr INTO l_interest;
3382       IF strm_elem_int_hdr_csr%NOTFOUND THEN
3383         l_interest := 0;
3384         l_prorated_principal := p_loan_amount;
3385         RETURN l_prorated_principal;
3386       END IF;
3387       CLOSE strm_elem_int_hdr_csr;
3388 
3389       OPEN strm_elem_prin_hdr_csr (p_contract_id, p_stream_element_date);
3390       FETCH strm_elem_prin_hdr_csr INTO l_principal;
3391       IF strm_elem_prin_hdr_csr%NOTFOUND THEN
3392         l_interest := 0;
3393         l_prorated_principal := p_loan_amount;
3394         RETURN l_prorated_principal;
3395       END IF;
3396       CLOSE strm_elem_prin_hdr_csr;
3397 
3398       IF (( l_interest <> 0 ) AND (l_principal <> 0)) THEN
3399         l_prorated_principal :=  (p_loan_amount * l_principal) /(l_principal + l_interest);
3400         RETURN l_prorated_principal;
3401       ELSE
3402         RETURN p_loan_amount;
3403       END IF;
3404     END IF;
3405   EXCEPTION
3406       WHEN OTHERS THEN
3407       IF ( strm_elem_int_line_csr%ISOPEN ) THEN
3408          CLOSE strm_elem_int_line_csr;
3409       END IF;
3410       IF ( strm_elem_prin_line_csr%ISOPEN ) THEN
3411          CLOSE strm_elem_prin_line_csr;
3412       END IF;
3413       IF ( strm_elem_int_hdr_csr%ISOPEN ) THEN
3414          CLOSE strm_elem_int_hdr_csr;
3415       END IF;
3416       IF ( strm_elem_prin_hdr_csr%ISOPEN ) THEN
3417          CLOSE strm_elem_prin_hdr_csr;
3418       END IF;
3419 
3420       RETURN NULL;
3421   END;
3422 
3423 /*
3424   ------------------------------------------------------------------------------
3425 
3426     -- Start of Comments
3427     -- Created By:       Ramesh Seela
3428     -- Procedure Name    derive_principal_date_range_loan
3429     -- Description:      returns a PL/SQL table of records with following entries Start Date, End Date,
3430     --                   Receipt Amount, and Principal Balance
3431     -- Dependencies:
3432     -- Parameters:       contract id, date.
3433     -- Version:          1.0
3434     -- End of Comments
3435 
3436   ------------------------------------------------------------------------------
3437   PROCEDURE principal_date_range_loan (
3438             p_api_version        IN  NUMBER,
3439             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
3440             x_return_status      OUT NOCOPY VARCHAR2,
3441             x_msg_count          OUT NOCOPY NUMBER,
3442             x_msg_data           OUT NOCOPY VARCHAR2,
3443             p_contract_id        IN  NUMBER,
3444             p_line_id            IN  NUMBER,
3445             p_start_date         IN  DATE,
3446             p_due_date           IN  DATE,
3447             p_calling_program    IN  VARCHAR2,
3448             x_principal_balance_tbl OUT NOCOPY  principal_balance_tbl_typ)   IS
3449 
3450   l_api_name            CONSTANT    VARCHAR2(30) := 'DERIVE_PRINCIPAL_DATE_RANGE';
3451   l_api_version         CONSTANT    NUMBER       := 1.0;
3452   l_principal_basis     OKL_K_RATE_PARAMS.principal_basis_code%TYPE;
3453   l_effective_date      DATE := SYSDATE;
3454   l_principal_balance_tbl  principal_balance_tbl_typ ;
3455   l_contract_start_date DATE;
3456   l_start_date          DATE;
3457   l_principal_balance   NUMBER;
3458   l_counter             NUMBER := 0;
3459   l_receipt_counter     NUMBER := 0;
3460   l_revenue_recognition OKL_PRODUCT_PARAMETERS_V.revenue_recognition_method%TYPE;
3461   l_receipt_date        DATE;
3462   l_interest_calc_basis OKL_PRODUCT_PARAMETERS_V.interest_calculation_basis%TYPE;
3463   l_receipt_tbl         receipt_tbl_type;
3464   l_rcpt_tbl_count      NUMBER := 0;
3465   l_rcpt_tbl_index      NUMBER := 0;
3466   l_currency_code       OKL_K_HEADERS_FULL_V.currency_code%TYPE;
3467   l_prev_rcpt_date      DATE;
3468   l_current_rcpt_date   DATE;
3469   l_total_rcpt_prin_amt NUMBER;
3470   l_current_rcpt_prin_amt NUMBER;
3471   l_total_rcpt_loan_amt NUMBER;
3472   l_current_rcpt_loan_amt NUMBER;
3473   l_prin_bal_strm_element_date DATE;
3474 
3475   Cursor principal_basis_csr (p_contract_id NUMBER,
3476                               p_effective_date DATE) IS
3477       SELECT principal_basis_code
3478       FROM   okl_k_rate_params
3479       WHERE  khr_id = p_contract_id
3480       AND    p_effective_date BETWEEN effective_from_date and nvl(effective_to_date, SYSDATE)
3481       AND    parameter_type_code = 'ACTUAL';
3482 
3483   Cursor contract_csr (p_contract_id NUMBER) IS
3484       SELECT start_date, currency_code
3485       FROM   okl_k_headers_full_v
3486       WHERE  khr_id = p_contract_id;
3487 
3488   Cursor sch_asset_prin_bal_stream_csr (p_contract_id NUMBER,
3489                                         p_line_id     NUMBER,
3490                                         p_start_date  DATE) IS
3491       SELECT MAX(stream_element_date)
3492       FROM   OKL_ASSET_STREAMS_UV
3493       WHERE  contract_id = p_contract_id
3494         AND  line_id = p_line_id
3495         AND  stream_element_date < p_start_date
3496         AND  stream_type_purpose_code = 'PRINCIPAL_BALANCE';
3497 
3498   Cursor sch_ctr_prin_bal_stream_csr (p_contract_id NUMBER,
3499                                       p_start_date  DATE) IS
3500       SELECT MAX(stream_element_date)
3501       FROM   OKL_ASSET_STREAMS_UV
3502       WHERE  contract_id = p_contract_id
3503         AND  stream_element_date < p_start_date
3504         AND  stream_type_purpose_code = 'PRINCIPAL_BALANCE';
3505 
3506   Cursor sch_asset_prin_balance_csr (p_contract_id NUMBER,
3507                                      p_line_id     NUMBER,
3508                                      p_stream_element_date  DATE) IS
3509       SELECT amount
3510       FROM   OKL_ASSET_STREAMS_UV
3511       WHERE  contract_id = p_contract_id
3512         AND  line_id = p_line_id
3513         AND  stream_element_date = p_stream_element_date
3514         AND  stream_type_purpose_code = 'PRINCIPAL_BALANCE';
3515 
3516   Cursor sch_ctr_prin_balance_csr (p_contract_id NUMBER,
3517                                    p_stream_element_date  DATE) IS
3518       SELECT SUM(nvl(amount,0))
3519       FROM   OKL_ASSET_STREAMS_UV
3520       WHERE  contract_id = p_contract_id
3521         AND  stream_element_date = p_stream_element_date
3522         AND  stream_type_purpose_code = 'PRINCIPAL_BALANCE';
3523 
3524   Cursor revenue_recognition_csr (p_contract_id NUMBER) IS
3525       SELECT ppm.revenue_recognition_method,
3526              ppm.interest_calculation_basis
3527       FROM   okl_k_headers khr,
3528              okl_product_parameters_v ppm
3529        WHERE khr.pdt_id = ppm.id
3530          AND khr.id = p_contract_id;
3531 
3532   Cursor receipt_details_csr (p_contract_id NUMBER,
3533                               p_line_id     NUMBER,
3534                               p_start_date  DATE,
3535                               p_due_date    DATE) IS
3536         SELECT raa.apply_date receipt_date,
3537                sum(raa.amount_applied) principal_pmt_rcpt_amt
3538         FROM
3539              okl_cnsld_ar_strms_b lsm
3540              ,okl_cnsld_ar_lines_b lln
3541              ,okl_cnsld_ar_hdrs_b cnr
3542              ,ar_payment_schedules_all aps
3543              ,ar_receivable_applications_all raa
3544              ,ar_cash_receipts_all cra
3545              ,okl_strm_type_v sty
3546             WHERE  lsm.receivables_invoice_id > 0
3547               AND  lsm.lln_id = lln.id
3548               AND  lln.cnr_id = cnr.id
3549               AND  cnr.trx_status_code = 'PROCESSED'
3550               AND  lsm.khr_id = p_contract_id
3551               AND  lsm.kle_id = NVL(p_line_id, lsm.kle_id)
3552               AND  lsm.receivables_invoice_id = aps.customer_trx_id
3553               AND  raa.applied_customer_trx_id = aps.customer_trx_id
3554               AND  aps.class = 'INV'
3555               AND  (raa.application_type = 'CASH' or raa.application_type = 'CM')
3556               AND  raa.status = 'APP'
3557               AND  raa.apply_date BETWEEN p_start_date AND NVL(p_due_date, raa.apply_date)
3558               AND  raa.cash_receipt_id = cra.cash_receipt_id
3559               AND  lsm.sty_id = sty.id
3560               AND  sty.stream_type_purpose IN ('PRINCIPAL_PAYMENT', 'UNSCHEDULED_PRINCIPAL_PAYMENT', 'PRINCIPAL_CATCHUP')
3561        GROUP BY raa.apply_date
3562        ORDER BY raa.apply_date asc;
3563 
3564   Cursor rcpt_dtls_actual_strm_csr (p_contract_id NUMBER,
3565                               p_line_id     NUMBER,
3566                               p_start_date  DATE,
3567                               p_due_date    DATE) IS
3568         SELECT raa.apply_date receipt_date
3569               , lsm.kle_id
3570               , sel_ln_pmt.stream_element_date
3571               , sum(raa.amount_applied) loan_pmt_rcpt_amt
3572               , get_prorated_principal_amt(lsm.kle_id, sel_ln_pmt.stream_element_date,
3573                                            sum(raa.amount_applied), l_currency_code) principal_pmt_rcpt_amt
3574         FROM
3575               okl_cnsld_ar_strms_b lsm,
3576               okl_cnsld_ar_lines_b lln,
3577               okl_cnsld_ar_hdrs_b cnr,
3578               ar_payment_schedules_all aps,
3579               ar_receivable_applications_all raa,
3580               ar_cash_receipts_all cra,
3581               okl_strm_type_v sty_ln_pmt,
3582               okl_strm_elements_v sel_ln_pmt
3583         WHERE lsm.receivables_invoice_id > 0
3584           AND lsm.lln_id = lln.id
3585           AND lln.cnr_id = cnr.id
3586           AND cnr.trx_status_code = 'PROCESSED'
3587           AND lsm.khr_id = NVL(p_contract_id, lsm.khr_id)
3588           AND lsm.kle_id = NVL(p_line_id, lsm.kle_id)
3589           AND lsm.receivables_invoice_id = aps.customer_trx_id
3590           AND raa.applied_customer_trx_id = aps.customer_trx_id
3591           AND aps.class = 'INV'
3592           AND (raa.application_type = 'CASH' or raa.application_type = 'CM')
3593           AND raa.status = 'APP'
3594           AND raa.apply_date BETWEEN p_start_date AND NVL(p_due_date, raa.apply_date)
3595           AND raa.cash_receipt_id = cra.cash_receipt_id
3596           AND lsm.sty_id = sty_ln_pmt.id
3597           AND ( sty_ln_pmt.stream_type_purpose IN ('LOAN_PAYMENT', 'VARIABLE_LOAN_PAYMENT', 'UNSCHEDULED_LOAN_PAYMENT'))
3598           AND lsm.sel_id = sel_ln_pmt.id
3599         GROUP BY raa.apply_date
3600               , lsm.kle_id
3601               , sel_ln_pmt.stream_element_date
3602         ORDER BY raa.apply_date asc;
3603 
3604   BEGIN
3605     x_return_status     := OKL_API.G_RET_STS_SUCCESS;
3606 
3607     OPEN principal_basis_csr (p_contract_id, l_effective_date);
3608     FETCH principal_basis_csr INTO l_principal_basis;
3609     IF principal_basis_csr%NOTFOUND THEN
3610        CLOSE principal_basis_csr;
3611 --     report exception;
3612     END IF;
3613     CLOSE principal_basis_csr;
3614 
3615     OPEN contract_csr (p_contract_id);
3616     FETCH contract_csr INTO l_contract_start_date, l_currency_code;
3617     IF (contract_csr%NOTFOUND) THEN
3618        CLOSE contract_csr;
3619 --     raise exception;
3620     END IF;
3621     CLOSE contract_csr;
3622 
3623     -- Derive Principal Balance
3624     Okl_Execute_Formula_Pub.EXECUTE(p_api_version          => 1.0,
3625                                     p_init_msg_list        => OKL_API.G_TRUE,
3626                                     x_return_status        => x_return_status,
3627                                     x_msg_count            => x_msg_count,
3628                                     x_msg_data             => x_msg_data,
3629                                     p_formula_name         => 'CONTRACT_FINANCED_AMOUNT',
3630                                     p_contract_id          => p_contract_id,
3631                                     p_line_id              => p_line_id,
3632                                     x_value               =>  l_principal_balance
3633                                    );
3634 
3635     IF (x_return_status <> Okl_Api.G_RET_STS_SUCCESS) THEN
3636       NULL;
3637 --       raise exception;
3638     END IF;
3639 
3640 
3641     IF (l_principal_basis = 'SCHEDULED') THEN
3642        IF (p_start_date = l_contract_start_date) THEN
3643           l_counter := l_counter + 1;
3644           l_principal_balance_tbl(l_counter).khr_id                 := p_contract_id;
3645           IF (p_line_id IS NOT NULL) THEN
3646              l_principal_balance_tbl(l_counter).kle_id              := p_line_id;
3647           ELSE
3648              l_principal_balance_tbl(l_counter).kle_id              := NULL;
3649           END IF;
3650           l_principal_balance_tbl(l_counter).from_date             := p_start_date;
3651           l_principal_balance_tbl(l_counter).to_date               := p_due_date;
3652           l_principal_balance_tbl(l_counter).principal_pmt_rcpt_amt := 0;
3653           l_principal_balance_tbl(l_counter).loan_pmt_rcpt_amt      := 0;
3654           l_principal_balance_tbl(l_counter).receipt_date           := NULL;
3655           l_principal_balance_tbl(l_counter).principal_balance      := l_principal_balance;
3656        ELSE
3657 
3658           IF (p_line_id IS NOT NULL) THEN
3659              OPEN sch_asset_prin_bal_stream_csr (p_contract_id, p_line_id, p_start_date);
3660              FETCH sch_asset_prin_bal_stream_csr INTO l_prin_bal_strm_element_date;
3661              IF (sch_asset_prin_bal_stream_csr % NOTFOUND) THEN
3662                 CLOSE sch_asset_prin_bal_stream_csr;
3663 --              raise exception;
3664              END IF;
3665              CLOSE sch_asset_prin_bal_stream_csr;
3666 
3667              OPEN sch_asset_prin_balance_csr (p_contract_id, p_line_id, l_prin_bal_strm_element_date);
3668              FETCH sch_asset_prin_balance_csr INTO l_principal_balance;
3669              IF (sch_asset_prin_balance_csr%NOTFOUND) THEN
3670                 CLOSE sch_asset_prin_balance_csr;
3671 --              raise exception;
3672              END IF;
3673              CLOSE sch_asset_prin_balance_csr;
3674 
3675           ELSE
3676              OPEN sch_ctr_prin_bal_stream_csr (p_contract_id, p_start_date);
3677              FETCH sch_ctr_prin_bal_stream_csr INTO l_prin_bal_strm_element_date;
3678              IF (sch_ctr_prin_bal_stream_csr % NOTFOUND) THEN
3679                 CLOSE sch_ctr_prin_bal_stream_csr;
3680 --              raise exception;
3681              END IF;
3682              CLOSE sch_ctr_prin_bal_stream_csr;
3683 
3684              OPEN sch_ctr_prin_balance_csr (p_contract_id, l_prin_bal_strm_element_date);
3685              FETCH sch_ctr_prin_balance_csr INTO l_principal_balance;
3686              IF (sch_ctr_prin_balance_csr%NOTFOUND) THEN
3687                 CLOSE sch_ctr_prin_balance_csr;
3688 --              raise exception;
3689              END IF;
3690              CLOSE sch_ctr_prin_balance_csr;
3691           END IF;
3692           l_counter := l_counter + 1;
3693           l_principal_balance_tbl(l_counter).khr_id                 := p_contract_id;
3694           IF (p_line_id IS NOT NULL) THEN
3695              l_principal_balance_tbl(l_counter).kle_id              := p_line_id;
3696           ELSE
3697              l_principal_balance_tbl(l_counter).kle_id              := NULL;
3698           END IF;
3699           l_principal_balance_tbl(l_counter).from_date             := p_start_date;
3700           l_principal_balance_tbl(l_counter).to_date               := p_due_date;
3701 --          l_principal_balance_tbl(l_counter).principal_pmt_rcpt_amt := 0;
3702 --          l_principal_balance_tbl(l_counter).loan_pmt_rcpt_amt      := 0;
3703           l_principal_balance_tbl(l_counter).receipt_date           := NULL;
3704           l_principal_balance_tbl(l_counter).principal_balance      := l_principal_balance;
3705        END IF;
3706     ELSIF (l_principal_basis = 'ACTUAL') THEN
3707 
3708        OPEN revenue_recognition_csr (p_contract_id);
3709        FETCH revenue_recognition_csr INTO l_revenue_recognition, l_interest_calc_basis;
3710        IF revenue_recognition_csr%NOTFOUND THEN
3711           CLOSE revenue_recognition_csr;
3712 --     report exception;
3713        END IF;
3714        CLOSE revenue_recognition_csr;
3715 
3716        IF (l_revenue_recognition <> 'ACTUAL') THEN
3717           l_counter := 0;
3718           FOR current_receipt in receipt_details_csr (p_contract_id, p_line_id, p_start_date, p_due_date)
3719           LOOP
3720              l_counter                                       := l_counter + 1;
3721              l_receipt_tbl(l_counter).khr_id                 := p_contract_id;
3722              l_receipt_tbl(l_counter).kle_id                 := p_line_id;
3723              l_receipt_tbl(l_counter).receipt_date           := current_receipt.receipt_date;
3724              l_receipt_tbl(l_counter).principal_pmt_rcpt_amt := current_receipt.principal_pmt_rcpt_amt;
3725              l_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := 0;
3726           END LOOP;
3727        ELSE
3728           l_prev_rcpt_date        := NULL;
3729           l_current_rcpt_date     := NULL;
3730           l_counter               := 0;
3731           l_total_rcpt_prin_amt   := 0;
3732           l_current_rcpt_prin_amt := 0;
3733           l_total_rcpt_loan_amt   := 0;
3734           l_current_rcpt_loan_amt := 0;
3735           FOR current_receipt in rcpt_dtls_actual_strm_csr (p_contract_id, p_line_id, p_start_date, p_due_date)
3736           LOOP
3737              l_current_rcpt_date     := current_receipt.receipt_date;
3738              l_current_rcpt_prin_amt := OKL_ACCOUNTING_UTIL.round_amount(current_receipt.principal_pmt_rcpt_amt, l_currency_code);
3739              l_current_rcpt_loan_amt := current_receipt.loan_pmt_rcpt_amt;
3740              IF (l_prev_rcpt_date = NULL) THEN
3741                 l_prev_rcpt_date := l_current_rcpt_date;
3742              END IF;
3743              IF (l_current_rcpt_date = l_prev_rcpt_date) THEN
3744                 l_total_rcpt_prin_amt := l_total_rcpt_prin_amt + l_current_rcpt_prin_amt;
3745                 l_total_rcpt_loan_amt := l_total_rcpt_loan_amt + l_current_rcpt_loan_amt;
3746              ELSE
3747                 l_counter                                       := l_counter + 1;
3748                 l_receipt_tbl(l_counter).khr_id                 := p_contract_id;
3749                 l_receipt_tbl(l_counter).kle_id                 := p_line_id;
3750                 l_receipt_tbl(l_counter).receipt_date           := l_prev_rcpt_date;
3751                 l_receipt_tbl(l_counter).principal_pmt_rcpt_amt := l_total_rcpt_prin_amt;
3752                 l_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := l_total_rcpt_loan_amt;
3753                 l_total_rcpt_prin_amt                           := l_current_rcpt_prin_amt;
3754                 l_total_rcpt_loan_amt                           := l_current_rcpt_loan_amt;
3755                 l_prev_rcpt_date                                := l_current_rcpt_date;
3756              END IF;
3757           END LOOP;
3758           IF (l_prev_rcpt_date IS NOT NULL) THEN
3759              l_counter := l_counter + 1;
3760              l_receipt_tbl(l_counter).khr_id                 := p_contract_id;
3761              l_receipt_tbl(l_counter).kle_id                 := p_line_id;
3762              l_receipt_tbl(l_counter).receipt_date           := l_prev_rcpt_date;
3763              l_receipt_tbl(l_counter).principal_pmt_rcpt_amt := l_total_rcpt_prin_amt;
3764              l_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := l_total_rcpt_loan_amt;
3765           END IF;
3766 
3767        END IF;
3768 
3769        l_start_date     := l_contract_start_date;
3770        l_counter        := 0;
3771        l_rcpt_tbl_count := l_receipt_tbl.COUNT;
3772        l_rcpt_tbl_index := l_receipt_tbl.FIRST;
3773        FOR l_rcpt_tbl_counter in 1 .. l_rcpt_tbl_count
3774        LOOP
3775           l_counter := l_counter + 1;
3776           l_principal_balance_tbl(l_counter).khr_id := p_contract_id;
3777           IF (p_line_id IS NOT NULL) THEN
3778              l_principal_balance_tbl(l_counter).kle_id := p_line_id;
3779           ELSE
3780              l_principal_balance_tbl(l_counter).kle_id := NULL;
3781           END IF;
3782           l_principal_balance_tbl(l_counter).from_date := l_start_date;
3783           IF (l_receipt_date > l_contract_start_date) THEN
3784              l_principal_balance_tbl(l_counter).to_date   := l_receipt_tbl(l_rcpt_tbl_index).receipt_date - 1;
3785           ELSE -- receipt date = contract start date
3786              l_principal_balance_tbl(l_counter).to_date   := l_receipt_tbl(l_rcpt_tbl_index).receipt_date;
3787           END IF;
3788           l_principal_balance_tbl(l_counter).principal_pmt_rcpt_amt := l_receipt_tbl(l_rcpt_tbl_index).principal_pmt_rcpt_amt;
3789           l_principal_balance_tbl(l_counter).loan_pmt_rcpt_amt := l_receipt_tbl(l_rcpt_tbl_index).loan_pmt_rcpt_amt;
3790           l_principal_balance_tbl(l_counter).receipt_date := l_receipt_tbl(l_rcpt_tbl_index).receipt_date;
3791           l_principal_balance_tbl(l_counter).principal_balance := l_principal_balance;
3792 
3793           l_start_date := l_receipt_tbl(l_rcpt_tbl_index).receipt_date;
3794           l_principal_balance := l_principal_balance - l_receipt_tbl(l_rcpt_tbl_index).principal_pmt_rcpt_amt;
3795 
3796           l_rcpt_tbl_index := l_receipt_tbl.NEXT(l_rcpt_tbl_index);
3797 
3798        END LOOP;
3799 
3800        IF (p_calling_program <> 'DAILY_INTEREST') THEN  --- check the exact value
3801           l_counter := l_counter + 1;
3802           l_principal_balance_tbl(l_counter).khr_id := p_contract_id;
3803           IF (p_line_id IS NOT NULL) THEN
3804              l_principal_balance_tbl(l_counter).kle_id := p_line_id;
3805           ELSE
3806              l_principal_balance_tbl(l_counter).kle_id := NULL;
3807           END IF;
3808           l_principal_balance_tbl(l_counter).from_date := l_start_date;
3809           l_principal_balance_tbl(l_counter).to_date   := p_due_date;
3810           l_principal_balance_tbl(l_counter).principal_pmt_rcpt_amt := 0;
3811           l_principal_balance_tbl(l_counter).loan_pmt_rcpt_amt := 0;
3812           l_principal_balance_tbl(l_counter).receipt_date := NULL;
3813           l_principal_balance_tbl(l_counter).principal_balance := l_principal_balance;
3814        END IF;
3815 
3816     END IF;
3817     x_principal_balance_tbl := l_principal_balance_tbl;
3818 
3819 
3820   EXCEPTION
3821 
3822      WHEN OTHERS THEN
3823                Okl_Api.SET_MESSAGE(
3824                         p_app_name     => G_APP_NAME,
3825                         p_msg_name     => G_UNEXPECTED_ERROR,
3826                         p_token1       => G_SQLCODE_TOKEN,
3827                         p_token1_value => SQLCODE,
3828                         p_token2       => G_SQLERRM_TOKEN,
3829                         p_token2_value => SQLERRM);
3830 
3831   END principal_date_range_loan;
3832 
3833 ------------------------------------------------------------------------------
3834 
3835     -- Start of Comments
3836     -- Created By:       Ramesh Seela
3837     -- Procedure Name    derive_principal_date_range_loan
3838     -- Description:      returns a PL/SQL table of records with following entries Start Date, End Date,
3839     --                   Receipt Amount, and Principal Balance
3840     -- Dependencies:
3841     -- Parameters:       contract id, date.
3842     -- Version:          1.0
3843     -- End of Comments
3844 
3845   ------------------------------------------------------------------------------
3846   PROCEDURE principal_date_range_rev_loan (
3847             p_api_version        IN  NUMBER,
3848             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
3849             x_return_status      OUT NOCOPY VARCHAR2,
3850             x_msg_count          OUT NOCOPY NUMBER,
3851             x_msg_data           OUT NOCOPY VARCHAR2,
3852             p_contract_id        IN  NUMBER,
3853             p_line_id            IN  NUMBER,
3854             p_start_date         IN  DATE,
3855             p_due_date           IN  DATE,
3856             p_calling_program    IN  VARCHAR2,
3857             x_principal_balance_tbl OUT NOCOPY principal_balance_tbl_typ)   IS
3858 
3859   l_api_name            CONSTANT    VARCHAR2(30) := 'DERIVE_PRINCIPAL_DATE_RANGE';
3860   l_api_version         CONSTANT    NUMBER       := 1.0;
3861   l_principal_balance_tbl  principal_balance_tbl_typ ;
3862   l_contract_start_date DATE;
3863   l_start_date          DATE;
3864   l_principal_balance   NUMBER;
3865   l_counter             NUMBER := 0;
3866   l_revenue_recognition OKL_PRODUCT_PARAMETERS_V.revenue_recognition_method%TYPE;
3867   l_interest_calc_basis OKL_PRODUCT_PARAMETERS_V.interest_calculation_basis%TYPE;
3868   l_currency_code       OKL_K_HEADERS_FULL_V.currency_code%TYPE;
3869   l_current_txn_date    DATE;
3870 
3871   Cursor contract_csr (p_contract_id NUMBER) IS
3872       SELECT start_date, currency_code
3873       FROM   okl_k_headers_full_v
3874       WHERE  khr_id = p_contract_id;
3875 
3876   Cursor revenue_recognition_csr (p_contract_id NUMBER) IS
3877       SELECT ppm.revenue_recognition_method,
3878              ppm.interest_calculation_basis
3879       FROM   okl_k_headers khr,
3880              okl_product_parameters_v ppm
3881        WHERE khr.pdt_id = ppm.id
3882          AND khr.id = p_contract_id;
3883 
3884   -- sjalasut, modified the cursor to have khr_id referred from the lines table
3885   Cursor pymt_rcpt_details_var_int_csr (p_contract_id    NUMBER,
3886                                         p_start_date     DATE,
3887                                         p_due_date       DATE,
3888                                         p_rev_rec_method VARCHAR2) IS
3889     SELECT iph.check_date txn_date,
3890            sum(iph.amount) txn_amount,
3891            'P' txn_type
3892     FROM ap_invoices_all ap_inv,
3893          okl_trx_ap_invoices_b okl_inv,
3894          ap_invoice_payment_history_v iph
3895          ,okl_cnsld_ap_invs_all cnsld
3896          ,okl_txl_ap_inv_lns_all_b okl_inv_ln
3897          ,fnd_application fnd_app
3898     WHERE okl_inv.id = okl_inv_ln.tap_id
3899       AND okl_inv_ln.khr_id = p_contract_id
3900       AND ap_inv.application_id = fnd_app.application_id
3901       AND fnd_app.application_short_name = 'OKL'
3902       AND okl_inv_ln.cnsld_ap_inv_id = cnsld.cnsld_ap_inv_id
3903       AND cnsld.cnsld_ap_inv_id = to_number(ap_inv.reference_key1)
3904       AND okl_inv.funding_type_code = 'BORROWER_PAYMENT'
3905       AND ap_inv.invoice_id = iph.invoice_id
3906       AND iph.check_date BETWEEN p_start_date AND NVL(p_due_date, iph.check_date)
3907     GROUP BY iph.check_date
3908 UNION
3909     SELECT raa.apply_date txn_date,
3910            sum(raa.amount_applied) txn_amount,
3911            'R' txn_date
3912     FROM   okl_cnsld_ar_strms_b lsm,
3913            okl_cnsld_ar_lines_b lln,
3914            okl_cnsld_ar_hdrs_b cnr,
3915            ar_payment_schedules_all aps,
3916            ar_receivable_applications_all raa,
3917            ar_cash_receipts_all cra,
3918            okl_strm_type_v sty
3919     WHERE  lsm.receivables_invoice_id > 0
3920       AND  lsm.lln_id = lln.id
3921       AND  lln.cnr_id = cnr.id
3922       AND  cnr.trx_status_code = 'PROCESSED'
3923       AND  lsm.khr_id = NVL(p_contract_id, lsm.khr_id)
3924       AND  lsm.receivables_invoice_id = aps.customer_trx_id
3925       AND  raa.applied_customer_trx_id = aps.customer_trx_id
3926       AND  aps.class = 'INV'
3927       AND  (raa.application_type = 'CASH' or raa.application_type = 'CM')
3928       AND  raa.status = 'APP'
3929       AND  raa.apply_date BETWEEN p_start_date AND NVL(p_due_date, raa.apply_date)
3930       AND  raa.cash_receipt_id = cra.cash_receipt_id
3931       AND  lsm.sty_id = sty.id
3932       AND  sty.stream_type_purpose = decode(p_rev_rec_method, 'ACTUAL', 'UNSCHEDULED_LOAN_PAYMENT','UNSCHEDULED_PRINCIPAL_PAYMENT')
3933     GROUP BY raa.apply_date
3934     ORDER BY txn_date asc;
3935 
3936   -- sjalasut, modified the cursor to have khr_id referred from okl_txl_ap_inv_lns_all_b
3937   Cursor pymt_rcpt_dtls_daily_int_csr (p_contract_id    NUMBER,
3938                                        p_start_date     DATE,
3939                                        p_due_date       DATE ) IS
3940     SELECT iph.check_date txn_date,
3941            sum(iph.amount) txn_amount,
3942            'P' txn_type
3943     FROM ap_invoices_all ap_inv,
3944          okl_trx_ap_invoices_v okl_inv,
3945          ap_invoice_payment_history_v iph
3946          ,okl_cnsld_ap_invs_all cnsld
3947          ,okl_txl_ap_inv_lns_all_b okl_inv_ln
3948          ,fnd_application fnd_app
3949     WHERE okl_inv.id = okl_inv_ln.tap_id
3950       AND okl_inv_ln.khr_id = p_contract_id
3951       AND ap_inv.application_id = fnd_app.application_id
3952       AND fnd_app.application_short_name = 'OKL'
3953       AND okl_inv_ln.cnsld_ap_inv_id = cnsld.cnsld_ap_inv_id
3954       AND cnsld.cnsld_ap_inv_id = to_number(ap_inv.reference_key1)
3955       AND okl_inv.funding_type_code = 'BORROWER_PAYMENT'
3956       AND ap_inv.invoice_id = iph.invoice_id
3957       AND iph.check_date BETWEEN p_start_date AND NVL(p_due_date, iph.check_date)
3958     GROUP BY iph.check_date
3959 UNION
3960     SELECT raa.apply_date txn_date,
3961            sum(raa.amount_applied) txn_amount,
3962            'R' txn_date
3963     FROM   okl_cnsld_ar_strms_b lsm,
3964            okl_cnsld_ar_lines_b lln,
3965            okl_cnsld_ar_hdrs_b cnr,
3966            ar_payment_schedules_all aps,
3967            ar_receivable_applications_all raa,
3968            ar_cash_receipts_all cra,
3969            okl_strm_type_v sty
3970     WHERE  lsm.receivables_invoice_id > 0
3971       AND  lsm.lln_id = lln.id
3972       AND  lln.cnr_id = cnr.id
3973       AND  cnr.trx_status_code = 'PROCESSED'
3974       AND  lsm.khr_id = NVL(p_contract_id, lsm.khr_id)
3975       AND  lsm.receivables_invoice_id = aps.customer_trx_id
3976       AND  raa.applied_customer_trx_id = aps.customer_trx_id
3977       AND  aps.class = 'INV'
3978       AND  (raa.application_type = 'CASH' or raa.application_type = 'CM')
3979       AND  raa.status = 'APP'
3980       AND  raa.apply_date BETWEEN p_start_date AND NVL(p_due_date, raa.apply_date)
3981       AND  raa.cash_receipt_id = cra.cash_receipt_id
3982       AND  lsm.sty_id = sty.id
3983       AND  sty.stream_type_purpose IN ('VARIABLE_LOAN_PAYMENT','UNSCHEDULED_LOAN_PAYMENT')
3984     GROUP BY raa.apply_date
3985     ORDER BY txn_date asc;
3986   BEGIN
3987     x_return_status     := OKL_API.G_RET_STS_SUCCESS;
3988 
3989     OPEN contract_csr (p_contract_id);
3990     FETCH contract_csr INTO l_contract_start_date, l_currency_code;
3991     IF (contract_csr%NOTFOUND) THEN
3992        CLOSE contract_csr;
3993 --     raise exception;
3994     END IF;
3995     CLOSE contract_csr;
3996 
3997     OPEN revenue_recognition_csr (p_contract_id);
3998     FETCH revenue_recognition_csr INTO l_revenue_recognition, l_interest_calc_basis;
3999     IF revenue_recognition_csr%NOTFOUND THEN
4000        CLOSE revenue_recognition_csr;
4001 --     report exception;
4002     END IF;
4003     CLOSE revenue_recognition_csr;
4004 
4005     l_counter              := 0;
4006     l_start_date           := l_contract_start_date;
4007     l_principal_balance    := 0;
4008     l_current_txn_date     := NULL;
4009 
4010     IF (p_calling_program <> 'DAILY_INTEREST') THEN
4011           FOR current_txn in pymt_rcpt_details_var_int_csr (p_contract_id, p_start_date, p_due_date, l_revenue_recognition)
4012           LOOP
4013              l_counter          := l_counter + 1;
4014              l_current_txn_date := current_txn.txn_date;
4015 
4016              l_principal_balance_tbl(l_counter).khr_id     := p_contract_id;
4017              l_principal_balance_tbl(l_counter).kle_id     := NULL;
4018              l_principal_balance_tbl(l_counter).from_date := l_start_date;
4019 
4020              IF (l_current_txn_date > l_contract_start_date) THEN
4021                 l_principal_balance_tbl(l_counter).to_date   := l_current_txn_date - 1;
4022              ELSE -- transaction date = contract start date
4023                 l_principal_balance_tbl(l_counter).to_date   := l_current_txn_date ;
4024              END IF;
4025              l_principal_balance_tbl(l_counter).principal_pmt_rcpt_amt := 0;
4026              l_principal_balance_tbl(l_counter).loan_pmt_rcpt_amt      := 0;
4027              l_principal_balance_tbl(l_counter).receipt_date           := NULL;
4028              l_principal_balance_tbl(l_counter).principal_balance      := l_principal_balance;
4029 
4030              l_start_date := l_current_txn_date;
4031              IF (current_txn.txn_type = 'P') THEN
4032                 l_principal_balance := l_principal_balance + current_txn.txn_amount;
4033              ELSE
4034                 l_principal_balance := l_principal_balance - current_txn.txn_amount;
4035              END IF;
4036           END LOOP;
4037 
4038           l_counter := l_counter + 1;
4039           l_principal_balance_tbl(l_counter).khr_id := p_contract_id;
4040           l_principal_balance_tbl(l_counter).kle_id := NULL;
4041           l_principal_balance_tbl(l_counter).from_date := l_start_date;
4042           l_principal_balance_tbl(l_counter).to_date   := p_due_date;
4043           l_principal_balance_tbl(l_counter).principal_pmt_rcpt_amt := 0;
4044           l_principal_balance_tbl(l_counter).loan_pmt_rcpt_amt := 0;
4045           l_principal_balance_tbl(l_counter).receipt_date := NULL;
4046           l_principal_balance_tbl(l_counter).principal_balance := l_principal_balance;
4047 
4048     ELSE
4049           FOR current_txn in pymt_rcpt_details_var_int_csr (p_contract_id, p_start_date, p_due_date, l_revenue_recognition)
4050           LOOP
4051              l_counter          := l_counter + 1;
4052              l_current_txn_date := current_txn.txn_date;
4053 
4054              l_principal_balance_tbl(l_counter).khr_id     := p_contract_id;
4055              l_principal_balance_tbl(l_counter).kle_id     := NULL;
4056              l_principal_balance_tbl(l_counter).from_date := l_start_date;
4057 
4058              IF (l_current_txn_date > l_contract_start_date) THEN
4059                 l_principal_balance_tbl(l_counter).to_date   := l_current_txn_date - 1;
4060              ELSE -- transaction date = contract start date
4061                 l_principal_balance_tbl(l_counter).to_date   := l_current_txn_date ;
4062              END IF;
4063              l_principal_balance_tbl(l_counter).principal_pmt_rcpt_amt := 0;
4064              l_principal_balance_tbl(l_counter).loan_pmt_rcpt_amt      := 0;
4065              l_principal_balance_tbl(l_counter).receipt_date           := NULL;
4066              l_principal_balance_tbl(l_counter).principal_balance      := l_principal_balance;
4067 
4068              l_start_date := l_current_txn_date;
4069              IF (current_txn.txn_type = 'P') THEN
4070                 l_principal_balance := l_principal_balance + current_txn.txn_amount;
4071              ELSE
4072                 l_principal_balance := l_principal_balance - current_txn.txn_amount;
4073              END IF;
4074           END LOOP;
4075 
4076           l_counter := l_counter + 1;
4077           l_principal_balance_tbl(l_counter).khr_id := p_contract_id;
4078           l_principal_balance_tbl(l_counter).kle_id := NULL;
4079           l_principal_balance_tbl(l_counter).from_date := l_start_date;
4080           l_principal_balance_tbl(l_counter).to_date   := p_due_date;
4081           l_principal_balance_tbl(l_counter).principal_pmt_rcpt_amt := 0;
4082           l_principal_balance_tbl(l_counter).loan_pmt_rcpt_amt := 0;
4083           l_principal_balance_tbl(l_counter).receipt_date := NULL;
4084           l_principal_balance_tbl(l_counter).principal_balance := l_principal_balance;
4085     END IF;
4086     x_principal_balance_tbl := l_principal_balance_tbl;
4087 
4088   EXCEPTION
4089 
4090      WHEN OTHERS THEN
4091                Okl_Api.SET_MESSAGE(
4092                         p_app_name     => G_APP_NAME,
4093                         p_msg_name     => G_UNEXPECTED_ERROR,
4094                         p_token1       => G_SQLCODE_TOKEN,
4095                         p_token1_value => SQLCODE,
4096                         p_token2       => G_SQLERRM_TOKEN,
4097                         p_token2_value => SQLERRM);
4098 
4099   END principal_date_range_rev_loan;
4100 */
4101 ------------------------------------------------------------------------------
4102     -- Start of Comments
4103     -- Created By:       Ramesh Seela
4104     -- Procedure Name    print_principal_date_range_tbl
4105     -- Description:      This procedure prints all the records in the principal date range buffer
4106     --
4107     -- Dependencies:
4108     -- Parameters:       .
4109     -- Version:          1.0
4110     -- End of Comments
4111 
4112 ------------------------------------------------------------------------------
4113 
4114   PROCEDURE print_principal_date_range_tbl ( p_principal_balance_tbl IN  principal_balance_tbl_typ) IS
4115 
4116   l_rec_count    NUMBER;
4117   l_index        NUMBER;
4118   l_counter      NUMBER := 0;
4119   BEGIN
4120        l_rec_count      := p_principal_balance_tbl.COUNT;
4121        IF (l_rec_count > 0) THEN
4122           l_index          := p_principal_balance_tbl.FIRST;
4123           print_debug('Principal Balance Table : ');
4124        ELSE
4125           print_debug('No records exist in the table');
4126        END IF;
4127        FOR l_rcpt_tbl_counter in 1 .. l_rec_count
4128        LOOP
4129           l_counter     := l_counter + 1;
4130           print_debug( 'Record : '|| l_counter );
4131 		  print_debug( 'From Date : '|| p_principal_balance_tbl(l_index).from_date);
4132 		  print_debug( 'TO Date : '|| p_principal_balance_tbl(l_index).to_date);
4133 		  print_debug( 'Principal Balance : '|| p_principal_balance_tbl(l_index).principal_balance);
4134 
4135           l_index       := p_principal_balance_tbl.NEXT(l_index);
4136        END LOOP;
4137   EXCEPTION
4138      WHEN OTHERS THEN
4139           Okl_Api.SET_MESSAGE(
4140                   p_app_name     => G_APP_NAME,
4141                   p_msg_name     => G_UNEXPECTED_ERROR,
4142                   p_token1       => G_SQLCODE_TOKEN,
4143                   p_token1_value => SQLCODE,
4144                   p_token2       => G_SQLERRM_TOKEN,
4145                   p_token2_value => SQLERRM);
4146   END;
4147 
4148 ------------------------------------------------------------------------------
4149 
4150     -- Start of Comments
4151     -- Created By:       Ramesh Seela
4152     -- Procedure Name    prin_date_range_loan_old
4153     -- Description:      This procedure is used by Variable Interest Calculation program for LOANS
4154     --                   Returns a PL/SQL table of records with following entries Start Date, End Date,
4155     --                   and Principal Balance
4156     -- Dependencies:
4157     -- Parameters:
4158     -- Version:          1.0
4159     -- Version :         1.1 - Obsoleted this local procedure due to Billing Inline changes - Bug#5898792 - 23/2/2007
4160     -- End of Comments
4161 
4162 ------------------------------------------------------------------------------
4163 
4164 
4165 ------------------------------------------------------------------------------
4166 
4167     -- Start of Comments
4168     -- Created By:       Ramesh Seela
4169     -- Procedure Name    principal_date_range_var_int_loan
4170     -- Description:      This procedure is used by Variable Interest Calculation program for LOANS
4171     --                   Returns a PL/SQL table of records with following entries Start Date, End Date,
4172     --                   and Principal Balance
4173     -- Dependencies:
4174     -- Parameters:
4175     -- Version:          1.0
4176     -- End of Comments
4177 
4178   ------------------------------------------------------------------------------
4179   PROCEDURE prin_date_range_var_int_loan (
4180             p_api_version        IN  NUMBER,
4181             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
4182             x_return_status      OUT NOCOPY VARCHAR2,
4183             x_msg_count          OUT NOCOPY NUMBER,
4184             x_msg_data           OUT NOCOPY VARCHAR2,
4185             p_contract_id        IN  NUMBER,
4186             p_line_id            IN  NUMBER,
4187             p_start_date         IN  DATE,
4188             p_due_date           IN  DATE,
4189             p_principal_basis    IN  VARCHAR2 DEFAULT NULL,
4190             x_principal_balance_tbl OUT	NOCOPY principal_balance_tbl_typ)   IS
4191 
4192   l_api_name                   CONSTANT    VARCHAR2(30) := 'PRIN_DATE_RANGE_VAR_INT_LOAN';
4193   l_api_version                CONSTANT    NUMBER       := 1.0;
4194   l_principal_basis            OKL_K_RATE_PARAMS.principal_basis_code%TYPE;
4195   l_effective_date             DATE := SYSDATE;
4196   l_principal_balance_tbl      principal_balance_tbl_typ ;
4197   l_principal_balance_tbl_tmp   principal_balance_tbl_typ ;
4198 --  l_contract_start_date        DATE;
4199   l_start_date                 DATE;
4200   l_principal_balance          NUMBER;
4201   l_counter                    NUMBER := 0;
4202   l_counter_tmp                NUMBER := 0;
4203   l_receipt_counter            NUMBER := 0;
4204 --  l_revenue_recognition        OKL_PRODUCT_PARAMETERS_V.revenue_recognition_method%TYPE;
4205   l_receipt_date               DATE;
4206 --  l_interest_calc_basis        OKL_PRODUCT_PARAMETERS_V.interest_calculation_basis%TYPE;
4207   l_receipt_tbl                receipt_tbl_type;
4208   lx_receipt_tbl               receipt_tbl_type;
4209   l_rcpt_tbl_count             NUMBER := 0;
4210   l_rcpt_tbl_index             NUMBER := 0;
4211 --  l_currency_code              OKL_K_HEADERS_FULL_V.currency_code%TYPE;
4212   l_prev_rcpt_date             DATE;
4213   l_current_rcpt_date          DATE;
4214   l_total_rcpt_prin_amt        NUMBER;
4215   l_current_rcpt_prin_amt      NUMBER;
4216   l_total_rcpt_loan_amt        NUMBER;
4217   l_current_rcpt_loan_amt      NUMBER;
4218   l_prin_bal_strm_element_date DATE;
4219   prin_date_range_loan_failed  EXCEPTION;
4220   l_previous_receipt_date      DATE;
4221 /*
4222   Cursor principal_basis_csr (p_contract_id NUMBER,
4223                               p_effective_date DATE) IS
4224       SELECT nvl(principal_basis_code, 'ACTUAL')
4225       FROM   okl_k_rate_params
4226       WHERE  khr_id = p_contract_id
4227       AND    p_effective_date BETWEEN effective_from_date and nvl(effective_to_date, p_effective_date)
4228       AND    parameter_type_code = 'ACTUAL';
4229 
4230   Cursor contract_csr (p_contract_id NUMBER) IS
4231       SELECT start_date, currency_code
4232       FROM   okl_k_headers_full_v
4233       WHERE  id = p_contract_id;
4234 */
4235   Cursor sch_asset_prin_balance_csr (p_contract_id NUMBER,
4236                                      p_line_id     NUMBER,
4237                                      p_stream_element_date  DATE) IS
4238 
4239         SELECT sel.amount
4240         FROM
4241              okl_strm_elements sel
4242              ,okl_streams str
4243              ,okl_strm_type_v sty
4244             WHERE  sel.stm_id = str.id
4245               AND  str.khr_id = p_contract_id
4246               AND  str.kle_id = p_line_id
4247               AND  str.say_code = 'CURR'
4248               AND  str.active_yn = 'Y'
4249               AND  sel.stream_element_date = p_stream_element_date
4250               AND  str.sty_id = sty.id
4251               AND  sty.stream_type_purpose = 'PRINCIPAL_BALANCE';
4252 
4253   Cursor sch_ctr_prin_balance_csr (p_contract_id NUMBER,
4254                                    p_stream_element_date  DATE) IS
4255         SELECT SUM(amount)
4256         FROM
4257              okl_strm_elements sel
4258              ,okl_streams str
4259              ,okl_strm_type_v sty
4260             WHERE  sel.stm_id = str.id
4261               AND  str.khr_id = p_contract_id
4262               AND  str.say_code = 'CURR'
4263               AND  str.active_yn = 'Y'
4264               AND  sel.stream_element_date = p_stream_element_date
4265               AND  str.sty_id = sty.id
4266               AND  sty.stream_type_purpose = 'PRINCIPAL_BALANCE';
4267 
4268 -- Begin - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
4269        --Bug# 6819044: Fetch receipt applications correctly when
4270        --              contracts have multiple asset lines and
4271        --              invoices have lines from multiple contracts
4272        Cursor receipt_details_csr (p_contract_id NUMBER,
4273                               p_line_id     NUMBER,
4274                               p_start_date  DATE,
4275                               p_due_date    DATE) IS
4276        SELECT cra.receipt_date receipt_date
4277              ,SUM(nvl(ad.amount_cr,0))- SUM(nvl(ad.amount_dr,0)) principal_pmt_rcpt_amt -- 4884843, 4872370
4278        FROM  okl_txd_ar_ln_dtls_b tld,
4279              ra_customer_trx_lines_all ractrl,
4280              okl_txl_ar_inv_lns_b til,
4281              okl_trx_ar_invoices_b tai,
4282              ar_payment_schedules_all aps,
4283              ar_receivable_applications_all raa,
4284              ar_cash_receipts_all cra,
4285              okl_strm_type_b sty,
4286              ar_distributions_all ad
4287        WHERE tai.trx_status_code = 'PROCESSED'
4288          AND tai.khr_id = p_contract_id
4289          AND tld.khr_id = p_contract_id
4290          AND ractrl.customer_trx_id = aps.customer_trx_id
4291          AND raa.applied_customer_trx_id = aps.customer_trx_id
4292          AND aps.class = 'INV'
4293          AND raa.application_type IN ('CASH','CM')
4294          AND raa.status = 'APP'
4295          AND cra.receipt_date <= NVL(p_due_date, cra.receipt_date)
4296          AND raa.cash_receipt_id = cra.cash_receipt_id
4297          AND tld.sty_id = sty.id
4298          AND sty.stream_type_purpose IN ('PRINCIPAL_PAYMENT', 'UNSCHEDULED_PRINCIPAL_PAYMENT')
4299          AND to_char(tld.id) = ractrl.interface_line_attribute14
4300          AND tld.til_id_details = til.id
4301          AND til.tai_id = tai.id
4302          AND raa.receivable_application_id = ad.source_id
4303          AND ad.source_table = 'RA'
4304          AND ad.ref_customer_trx_Line_Id = ractrl.customer_trx_line_id
4305        GROUP BY cra.receipt_date
4306        UNION ALL
4307        SELECT cra.receipt_date receipt_date
4308               ,SUM(raa.line_applied) principal_pmt_rcpt_amt -- 4884843, 4872370
4309        FROM  okl_txd_ar_ln_dtls_b tld,
4310               ra_customer_trx_lines_all ractrl,
4311               okl_txl_ar_inv_lns_b til,
4312               okl_trx_ar_invoices_b tai,
4313               ar_payment_schedules_all aps,
4314               ar_receivable_applications_all raa,
4315               ar_cash_receipts_all cra,
4316               okl_strm_type_b sty
4317        WHERE tai.trx_status_code = 'PROCESSED'
4318          AND tai.khr_id = p_contract_id
4319          AND tld.khr_id = p_contract_id
4320          AND ractrl.customer_trx_id = aps.customer_trx_id
4321          AND raa.applied_customer_trx_id = aps.customer_trx_id
4322          AND aps.class = 'INV'
4323          AND raa.application_type IN ('CASH','CM')
4324          AND raa.status = 'APP'
4325          AND cra.receipt_date <= NVL(p_due_date, cra.receipt_date)
4326          AND raa.cash_receipt_id = cra.cash_receipt_id
4327          AND tld.sty_id = sty.id
4328          AND sty.stream_type_purpose IN ('PRINCIPAL_PAYMENT', 'UNSCHEDULED_PRINCIPAL_PAYMENT')
4329          AND to_char(tld.id) = ractrl.interface_line_attribute14
4330          AND tld.til_id_details = til.id
4331          AND til.tai_id = tai.id
4332          AND  EXISTS (SELECT 1
4333                       FROM ar_distributions_all ad
4334                       WHERE raa.receivable_application_id = ad.source_id
4335                       AND ad.source_table = 'RA'
4336                       AND ad.ref_customer_trx_Line_Id IS NULL)
4337        GROUP BY cra.receipt_date
4338        UNION
4339        SELECT ocb.termination_date receipt_date,
4340               sum(ocb.termination_value_amt) principal_pmt_rcpt_amt
4341        FROM   okl_contract_balances ocb
4342        WHERE  ocb.khr_id = p_contract_id
4343        AND    ocb.kle_id = NVL(p_line_id, kle_id)
4344        AND    ocb.termination_date BETWEEN p_start_date AND p_due_date
4345        GROUP BY ocb.termination_date
4346        UNION
4347         SELECT sel.stream_element_date receipt_date,
4348                sum(sel.amount) principal_pmt_rcpt_amt
4349         FROM
4350              okl_strm_elements sel
4351              ,okl_streams str
4352              ,okl_strm_type_v sty
4353             WHERE  sel.stm_id = str.id
4354               AND  str.khr_id = p_contract_id
4355               AND  str.kle_id = NVL(p_line_id, str.kle_id)
4356               AND  str.say_code = 'CURR'
4357               AND  str.active_yn = 'Y'
4358               AND  sel.stream_element_date BETWEEN p_start_date AND NVL(p_due_date, sel.stream_element_date)
4359               AND  str.sty_id = sty.id
4360               AND  sty.stream_type_purpose = 'PRINCIPAL_CATCHUP'
4361        GROUP BY sel.stream_element_date
4362        ORDER BY receipt_date asc;
4363 -- End - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
4364 
4365   Cursor rcpt_dtls_actual_strm_csr (p_contract_id NUMBER,
4366                               p_line_id     NUMBER,
4367                               p_start_date  DATE,
4368                               p_due_date    DATE) IS
4369         SELECT sel.stream_element_date receipt_date,
4370                sum(sel.amount) principal_pmt_rcpt_amt
4371         FROM
4372              okl_strm_elements sel
4373              ,okl_streams str
4374              ,okl_strm_type_v sty
4375             WHERE  sel.stm_id = str.id
4376               AND  str.khr_id = p_contract_id
4377               AND  str.kle_id = NVL(p_line_id, str.kle_id)
4378               AND  str.say_code = 'CURR'
4379               AND  str.active_yn = 'Y'
4380               AND  sel.stream_element_date <= NVL(p_due_date, sel.stream_element_date)
4381               AND  str.sty_id = sty.id
4382               AND  sty.stream_type_purpose = 'DAILY_INTEREST_PRINCIPAL'
4383        GROUP BY sel.stream_element_date
4384        ORDER BY receipt_date asc;
4385 
4386 
4387   BEGIN
4388     x_return_status     := OKL_API.G_RET_STS_SUCCESS;
4389 
4390     print_debug('Executing procedure PRIN_DATE_RANGE_VAR_INT_LOAN using following parameters : ');
4391     print_debug(' p_contract_id : '|| p_contract_id );
4392 	print_debug(' p_line_id : '|| p_line_id );
4393     print_debug(' p_start_date : '|| to_char(p_start_date));
4394 	print_debug(' p_due_date : '|| to_char(p_due_date));
4395 	print_debug(' p_principal_basis : '|| p_principal_basis);
4396 
4397 	Initialize_contract_params( p_api_version   => 1.0,
4398                                 p_init_msg_list => OKL_API.G_FALSE,
4399                                 x_return_status => x_return_status,
4400                                 x_msg_count     => x_msg_count,
4401                                 x_msg_data      => x_msg_data,
4402                                 p_contract_id   => p_contract_id
4403                               );
4404     IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
4405 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS completed successfully');
4406     ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
4407   	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
4408   	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
4409        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
4410     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
4411 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
4412 	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
4413        RAISE prin_date_range_loan_failed;
4414     END IF;
4415 
4416 
4417 	IF (p_principal_basis IS NOT NULL) THEN
4418       l_principal_basis := p_principal_basis;
4419     ELSE
4420 /*
4421       OPEN principal_basis_csr (p_contract_id, l_effective_date);
4422       FETCH principal_basis_csr INTO l_principal_basis;
4423       IF principal_basis_csr%NOTFOUND THEN
4424        CLOSE principal_basis_csr;
4425        print_error_message (' Principal Basis not found for contract ID: '|| p_contract_id);
4426        RAISE prin_date_range_loan_failed;
4427       END IF;
4428       CLOSE principal_basis_csr;
4429 */
4430       l_principal_basis := G_PRINCIPAL_BASIS_CODE;
4431     END IF;
4432 
4433 
4434     print_debug('principal basis : '||l_principal_basis);
4435 /*
4436     OPEN contract_csr (p_contract_id);
4437     FETCH contract_csr INTO l_contract_start_date, l_currency_code;
4438     IF (contract_csr%NOTFOUND) THEN
4439        CLOSE contract_csr;
4440        print_error_message('Contract Start Date not found for contract ID : '|| p_contract_id);
4441        RAISE prin_date_range_loan_failed;
4442     END IF;
4443     CLOSE contract_csr;
4444 */
4445 --    l_contract_start_date := G_CONTRACT_START_DATE;
4446 --	l_currency_code       := G_CURRENCY_CODE;
4447 
4448     print_debug('contract start date : '||G_CONTRACT_START_DATE );
4449 	print_debug('currency code : '|| G_CURRENCY_CODE);
4450 
4451     IF (l_principal_basis = 'ACTUAL') THEN
4452 /*
4453         -- Derive Principal Balance
4454         Okl_Execute_Formula_Pub.EXECUTE(p_api_version          => 1.0,
4455                                         p_init_msg_list        => OKL_API.G_TRUE,
4456                                         x_return_status        => x_return_status,
4457                                         x_msg_count            => x_msg_count,
4458                                         x_msg_data             => x_msg_data,
4459                                         p_formula_name         => 'CONTRACT_FINANCED_AMOUNT',
4460                                         p_contract_id          => p_contract_id,
4461                                         p_line_id              => p_line_id,
4462                                         x_value               =>  l_principal_balance
4463                                        );
4464 
4465         IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
4466   	      print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE completed successfully');
4467         ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
4468   	      print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned unexpected error');
4469   	      print_error_message ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned unexpected error');
4470           RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
4471         ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
4472 	      print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned exception');
4473 	      print_error_message ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned exception');
4474           RAISE prin_date_range_loan_failed;
4475         END IF;
4476 */
4477       IF (p_line_id IS NULL) THEN
4478         get_contract_financed_amount (
4479             p_api_version       => 1.0,
4480             p_init_msg_list     => OKL_API.G_FALSE,
4481             x_return_status     => x_return_status,
4482             x_msg_count         => x_msg_count,
4483             x_msg_data          => x_msg_data,
4484             p_contract_id       => p_contract_id,
4485 			x_principal_balance => l_principal_balance);
4486 
4487         IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
4488   	      print_debug ('Procedure GET_CONTRACT_FINANCED_AMOUNT completed successfully');
4489         ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
4490   	      print_debug ('Procedure GET_CONTRACT_FINANCED_AMOUNT returned unexpected error');
4491   	      print_error_message ('Procedure GET_CONTRACT_FINANCED_AMOUNT returned unexpected error');
4492           RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
4493         ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
4494 	      print_debug ('Procedure GET_CONTRACT_FINANCED_AMOUNT returned exception');
4495 	      print_error_message ('Procedure GET_CONTRACT_FINANCED_AMOUNT returned exception');
4496           RAISE prin_date_range_loan_failed;
4497         END IF;
4498       ELSE
4499         get_asset_financed_amount (
4500             p_api_version       => 1.0,
4501             p_init_msg_list     => OKL_API.G_FALSE,
4502             x_return_status     => x_return_status,
4503             x_msg_count         => x_msg_count,
4504             x_msg_data          => x_msg_data,
4505             p_contract_id       => p_contract_id,
4506             p_line_id           => p_line_id,
4507 			x_principal_balance => l_principal_balance);
4508 
4509         IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
4510   	      print_debug ('Procedure GET_ASSET_FINANCED_AMOUNT completed successfully');
4511         ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
4512   	      print_debug ('Procedure GET_ASSET_FINANCED_AMOUNT returned unexpected error');
4513   	      print_error_message ('Procedure GET_ASSET_FINANCED_AMOUNT returned unexpected error');
4514           RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
4515         ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
4516 	      print_debug ('Procedure GET_ASSET_FINANCED_AMOUNT returned exception');
4517 	      print_error_message ('Procedure GET_ASSET_FINANCED_AMOUNT returned exception');
4518           RAISE prin_date_range_loan_failed;
4519         END IF;
4520       END IF;
4521     END IF;
4522     print_debug('principal balance : '||l_principal_balance);
4523 
4524     IF (l_principal_basis = 'SCHEDULED') THEN
4525           IF (p_line_id IS NOT NULL) THEN
4526              print_debug('Stream Element Date : '|| to_char(p_start_date));
4527 
4528              OPEN sch_asset_prin_balance_csr (p_contract_id, p_line_id, p_start_date);
4529              FETCH sch_asset_prin_balance_csr INTO l_principal_balance;
4530              IF (sch_asset_prin_balance_csr%NOTFOUND) THEN
4531                 CLOSE sch_asset_prin_balance_csr;
4532                 print_error_message('Scheduled Asset Principal Balance stream cursor did not return records for contract ID :' || p_contract_id);
4533                 RAISE prin_date_range_loan_failed;
4534              END IF;
4535              CLOSE sch_asset_prin_balance_csr;
4536 
4537              print_debug(' Principal Balance : '|| l_principal_balance);
4538 
4539           ELSE
4540              print_debug('Stream Element Date : '|| to_char(p_start_date));
4541 
4542              OPEN sch_ctr_prin_balance_csr (p_contract_id, p_start_date);
4543              FETCH sch_ctr_prin_balance_csr INTO l_principal_balance;
4544              IF (sch_ctr_prin_balance_csr%NOTFOUND) THEN
4545                CLOSE sch_ctr_prin_balance_csr;
4546                print_error_message('Scheduled Contract Principal Balance cursor did not return records for contract ID :' || p_contract_id);
4547                RAISE prin_date_range_loan_failed;
4548              END IF;
4549              CLOSE sch_ctr_prin_balance_csr;
4550 
4551              print_debug(' Principal Balance : '|| l_principal_balance);
4552           END IF;
4553 
4554           l_counter := l_counter + 1;
4555           l_principal_balance_tbl(l_counter).khr_id                 := p_contract_id;
4556 
4557           IF (p_line_id IS NOT NULL) THEN
4558              l_principal_balance_tbl(l_counter).kle_id              := p_line_id;
4559           ELSE
4560              l_principal_balance_tbl(l_counter).kle_id              := NULL;
4561           END IF;
4562           l_principal_balance_tbl(l_counter).from_date             := p_start_date;
4563           l_principal_balance_tbl(l_counter).to_date               := p_due_date;
4564           l_principal_balance_tbl(l_counter).principal_balance      := l_principal_balance;
4565 
4566     ELSIF (l_principal_basis = 'ACTUAL') THEN
4567 
4568 --       l_revenue_recognition := G_REVENUE_RECOGNITION_METHOD;
4569 --	   l_interest_calc_basis := G_INTEREST_CALCULATION_BASIS;
4570 
4571        print_debug('revenue recognition method : '|| G_REVENUE_RECOGNITION_METHOD);
4572        print_debug('Interest calculation basis: '|| G_INTEREST_CALCULATION_BASIS);
4573        l_counter := 0;
4574 
4575 	   IF (G_REVENUE_RECOGNITION_METHOD <> 'ACTUAL') THEN
4576           FOR current_receipt in receipt_details_csr (p_contract_id, p_line_id, G_CONTRACT_START_DATE, p_due_date)
4577           LOOP
4578              l_counter                                       := l_counter + 1;
4579              l_receipt_tbl(l_counter).khr_id                 := p_contract_id;
4580              l_receipt_tbl(l_counter).kle_id                 := p_line_id;
4581              l_receipt_tbl(l_counter).receipt_date           := current_receipt.receipt_date;
4582              l_receipt_tbl(l_counter).principal_pmt_rcpt_amt := current_receipt.principal_pmt_rcpt_amt;
4583              l_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := 0;
4584           END LOOP;
4585        ELSE
4586           FOR current_receipt in rcpt_dtls_actual_strm_csr(p_contract_id, p_line_id, G_CONTRACT_START_DATE, p_due_date)
4587           LOOP
4588              l_counter                                       := l_counter + 1;
4589              l_receipt_tbl(l_counter).khr_id                 := p_contract_id;
4590              l_receipt_tbl(l_counter).kle_id                 := p_line_id;
4591              l_receipt_tbl(l_counter).receipt_date           := current_receipt.receipt_date;
4592              l_receipt_tbl(l_counter).principal_pmt_rcpt_amt := current_receipt.principal_pmt_rcpt_amt;
4593              l_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := 0;
4594           END LOOP;
4595         END IF;
4596 
4597         -- Records before Consolidation
4598         l_counter := 0;
4599         l_rcpt_tbl_count := l_receipt_tbl.COUNT;
4600 
4601 		Print_debug ('Contents of Receipts table before consolidation');
4602 
4603 		FOR l_counter IN 1 .. l_rcpt_tbl_count
4604 		LOOP
4605 		  Print_debug('Record Number : '||l_counter);
4606 		  Print_debug('Contract : '||l_receipt_tbl(l_counter).khr_id);
4607 		  Print_debug('Line : '||l_receipt_tbl(l_counter).kle_id);
4608 		  Print_debug('Receipt Date: '|| l_receipt_tbl(l_counter).receipt_date);
4609 		  Print_debug('Principal Payment: '|| l_receipt_tbl(l_counter).principal_pmt_rcpt_amt);
4610 		  Print_debug(' ');
4611 		END LOOP;
4612 
4613 		-- Consolidate the receipts posted after contract start date
4614         l_counter        := 0;
4615         l_rcpt_tbl_count := l_receipt_tbl.COUNT;
4616         l_previous_receipt_date  := NULL;
4617         lx_receipt_tbl.delete;
4618 
4619         FOR l_receipt_tbl_counter in 1 .. l_rcpt_tbl_count
4620         LOOP
4621           IF (l_receipt_tbl(l_receipt_tbl_counter).receipt_date <= G_CONTRACT_START_DATE) THEN
4622             l_counter                                        := l_counter + 1;
4623             lx_receipt_tbl(l_counter).khr_id                 := l_receipt_tbl(l_receipt_tbl_counter).khr_id;
4624             lx_receipt_tbl(l_counter).kle_id                 := l_receipt_tbl(l_receipt_tbl_counter).kle_id;
4625             lx_receipt_tbl(l_counter).receipt_date           := l_receipt_tbl(l_receipt_tbl_counter).receipt_date;
4626             lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
4627             lx_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := l_receipt_tbl(l_receipt_tbl_counter).loan_pmt_rcpt_amt;
4628           ELSE
4629             IF (l_receipt_tbl(l_receipt_tbl_counter).receipt_date = l_previous_receipt_date ) THEN
4630               lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt + l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
4631               lx_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := lx_receipt_tbl(l_counter).loan_pmt_rcpt_amt + l_receipt_tbl(l_receipt_tbl_counter).loan_pmt_rcpt_amt;
4632             ELSE
4633               l_counter                                        := l_counter + 1;
4634               lx_receipt_tbl(l_counter).khr_id                 := l_receipt_tbl(l_receipt_tbl_counter).khr_id;
4635               lx_receipt_tbl(l_counter).kle_id                 := l_receipt_tbl(l_receipt_tbl_counter).kle_id;
4636               lx_receipt_tbl(l_counter).receipt_date           := l_receipt_tbl(l_receipt_tbl_counter).receipt_date;
4637               lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
4638               lx_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := l_receipt_tbl(l_receipt_tbl_counter).loan_pmt_rcpt_amt;
4639               l_previous_receipt_date :=  lx_receipt_tbl(l_counter).receipt_date;
4640             END IF;
4641           END IF;
4642         END LOOP;
4643         l_receipt_tbl := lx_receipt_tbl;
4644 
4645 
4646         -- Records after Consolidation
4647         l_counter := 0;
4648         l_rcpt_tbl_count := l_receipt_tbl.COUNT;
4649 
4650 		Print_debug ('Contents of Receipts table after consolidation');
4651 
4652 		FOR l_counter IN 1 .. l_rcpt_tbl_count
4653 		LOOP
4654 		  Print_debug('Record Number : '||l_counter);
4655 		  Print_debug('Contract : '||l_receipt_tbl(l_counter).khr_id);
4656 		  Print_debug('Line : '||l_receipt_tbl(l_counter).kle_id);
4657 		  Print_debug('Receipt Date: '|| l_receipt_tbl(l_counter).receipt_date);
4658 		  Print_debug('Principal Payment: '|| l_receipt_tbl(l_counter).principal_pmt_rcpt_amt);
4659 		  Print_debug(' ');
4660 		END LOOP;
4661 
4662         -- Process the receipts
4663         l_counter        := 0;
4664         l_rcpt_tbl_count := l_receipt_tbl.COUNT;
4665         lx_receipt_tbl.delete;
4666 
4667         FOR l_receipt_tbl_counter in 1 .. l_rcpt_tbl_count
4668         LOOP
4669           IF (l_receipt_tbl(l_receipt_tbl_counter).receipt_date <= G_CONTRACT_START_DATE) THEN
4670               l_principal_balance := l_principal_balance - l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
4671           ELSE
4672             l_counter                                        := l_counter + 1;
4673             lx_receipt_tbl(l_counter).khr_id                 := l_receipt_tbl(l_receipt_tbl_counter).khr_id;
4674             lx_receipt_tbl(l_counter).kle_id                 := l_receipt_tbl(l_receipt_tbl_counter).kle_id;
4675             lx_receipt_tbl(l_counter).receipt_date           := l_receipt_tbl(l_receipt_tbl_counter).receipt_date;
4676             lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
4677             lx_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := l_receipt_tbl(l_receipt_tbl_counter).loan_pmt_rcpt_amt;
4678           END IF;
4679         END LOOP;
4680 
4681        l_receipt_tbl    := lx_receipt_tbl;
4682        l_start_date     := G_CONTRACT_START_DATE;
4683        l_counter        := 0;
4684        l_rcpt_tbl_count := l_receipt_tbl.COUNT;
4685 
4686        print_debug('No. of Consolidated Receipts after contract start date: '|| l_rcpt_tbl_count);
4687 
4688        IF (l_rcpt_tbl_count > 0) THEN
4689           l_rcpt_tbl_index := l_receipt_tbl.FIRST;
4690        END IF;
4691 
4692        FOR l_rcpt_tbl_counter in 1 .. l_rcpt_tbl_count
4693        LOOP
4694           l_counter := l_counter + 1;
4695           l_principal_balance_tbl(l_counter).khr_id := p_contract_id;
4696           IF (p_line_id IS NOT NULL) THEN
4697              l_principal_balance_tbl(l_counter).kle_id := p_line_id;
4698           ELSE
4699              l_principal_balance_tbl(l_counter).kle_id := NULL;
4700           END IF;
4701 
4702           l_principal_balance_tbl(l_counter).from_date := l_start_date;
4703 
4704           l_receipt_date := l_receipt_tbl(l_rcpt_tbl_index).receipt_date;
4705 
4706           l_principal_balance_tbl(l_counter).to_date   := l_receipt_tbl(l_rcpt_tbl_index).receipt_date - 1;
4707           l_principal_balance_tbl(l_counter).principal_balance := l_principal_balance;
4708           l_principal_balance := l_principal_balance - l_receipt_tbl(l_rcpt_tbl_index).principal_pmt_rcpt_amt;
4709           l_start_date := l_receipt_tbl(l_rcpt_tbl_index).receipt_date;
4710           l_rcpt_tbl_index := l_receipt_tbl.NEXT(l_rcpt_tbl_index);
4711 
4712        END LOOP;
4713 
4714        l_counter := l_counter + 1;
4715        l_principal_balance_tbl(l_counter).khr_id := p_contract_id;
4716        IF (p_line_id IS NOT NULL) THEN
4717           l_principal_balance_tbl(l_counter).kle_id := p_line_id;
4718        ELSE
4719           l_principal_balance_tbl(l_counter).kle_id := NULL;
4720        END IF;
4721        l_principal_balance_tbl(l_counter).from_date := l_start_date;
4722        l_principal_balance_tbl(l_counter).to_date   := p_due_date;
4723        l_principal_balance_tbl(l_counter).principal_balance := l_principal_balance;
4724 
4725     END IF;
4726 
4727     l_counter := l_principal_balance_tbl.first;
4728     LOOP
4729       EXIT WHEN l_counter IS NULL;
4730       IF ((p_start_date >= l_principal_balance_tbl(l_counter).from_date AND p_start_date <= l_principal_balance_tbl(l_counter).to_date) OR
4731           (p_due_date >= l_principal_balance_tbl(l_counter).from_date AND p_due_date <= l_principal_balance_tbl(l_counter).to_date) OR
4732           (l_principal_balance_tbl(l_counter).from_date >= p_start_date AND l_principal_balance_tbl(l_counter).to_date <= p_due_date)) THEN
4733         l_counter_tmp := l_counter_tmp + 1;
4734         l_principal_balance_tbl_tmp(l_counter_tmp) := l_principal_balance_tbl(l_counter);
4735         l_principal_balance_tbl_tmp(l_counter_tmp).from_date := GREATEST(l_principal_balance_tbl_tmp(l_counter_tmp).from_date, p_start_date);
4736         l_principal_balance_tbl_tmp(l_counter_tmp).to_date := LEAST(l_principal_balance_tbl_tmp(l_counter_tmp).to_date, p_due_date);
4737       END IF;
4738       l_counter := l_principal_balance_tbl.next(l_counter);
4739     END LOOP;
4740 
4741     x_principal_balance_tbl := l_principal_balance_tbl_tmp;
4742 
4743     print_principal_date_range_tbl (x_principal_balance_tbl);
4744 
4745   EXCEPTION
4746      WHEN prin_date_range_loan_failed THEN
4747        print_error_message('prin_date_range_loan_failed Exception Raised in procedure PRIN_DATE_RANGE_VAR_INT_LOAN ');
4748        x_return_status := OKL_API.G_RET_STS_ERROR;
4749      WHEN OTHERS THEN
4750        print_error_message('Exception Raised in procedure PRIN_DATE_RANGE_VAR_INT_LOAN ');
4751        Okl_Api.SET_MESSAGE(
4752                p_app_name     => G_APP_NAME,
4753                p_msg_name     => G_UNEXPECTED_ERROR,
4754                p_token1       => G_SQLCODE_TOKEN,
4755                p_token1_value => SQLCODE,
4756                p_token2       => G_SQLERRM_TOKEN,
4757                p_token2_value => SQLERRM);
4758        x_return_status := OKL_API.G_RET_STS_ERROR;
4759   END prin_date_range_var_int_loan;
4760 
4761 ------------------------------------------------------------------------------
4762 
4763     -- Start of Comments
4764     -- Created By:       Ramesh Seela
4765     -- Procedure Name    prin_date_range_var_int_rloan
4766     -- Description:      This procedure is called by Variable Interest Calculation for Revolving Loans
4767     --                   Returns a PL/SQL table of records with following entries Start Date, End Date,
4768     --                   and Principal Balance
4769     -- Dependencies:
4770     -- Parameters:       contract id, date.
4771     -- Version:          1.0
4772     -- End of Comments
4773 
4774   ------------------------------------------------------------------------------
4775   PROCEDURE prin_date_range_var_int_rloan (
4776             p_api_version        IN  NUMBER,
4777             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
4778             x_return_status      OUT NOCOPY VARCHAR2,
4779             x_msg_count          OUT NOCOPY NUMBER,
4780             x_msg_data           OUT NOCOPY VARCHAR2,
4781             p_contract_id        IN  NUMBER,
4782             p_line_id            IN  NUMBER,
4783             p_start_date         IN DATE,
4784             p_due_date           IN  DATE,
4785             x_principal_balance_tbl OUT NOCOPY principal_balance_tbl_typ)   IS
4786 
4787   l_api_name                    CONSTANT    VARCHAR2(30) := 'PRIN_DATE_RANGE_VAR_INT_RLOAN';
4788   l_api_version                 CONSTANT    NUMBER       := 1.0;
4789   l_principal_balance_tbl       principal_balance_tbl_typ ;
4790   l_principal_balance_tbl_tmp   principal_balance_tbl_typ ;
4791 --  l_contract_start_date         DATE;
4792   l_start_date                  DATE;
4793   l_principal_balance           NUMBER;
4794   l_counter                     NUMBER := 0;
4795   l_counter_tmp                 NUMBER := 0;
4796 --  l_currency_code               OKL_K_HEADERS_FULL_V.currency_code%TYPE;
4797 --  l_revenue_recognition         OKL_PRODUCT_PARAMETERS_V.revenue_recognition_method%TYPE;
4798   l_current_txn_date            DATE;
4799   prin_date_range_rloan_failed EXCEPTION;
4800   l_receipt_tbl                receipt_tbl_type;
4801   lx_receipt_tbl               receipt_tbl_type;
4802   l_previous_receipt_date      DATE;
4803   l_rcpt_tbl_count             NUMBER := 0;
4804   l_rcpt_tbl_counter           NUMBER := 0;
4805 
4806 /*
4807   Cursor contract_csr (p_contract_id NUMBER) IS
4808       SELECT start_date, currency_code
4809       FROM   okl_k_headers_full_v
4810       WHERE  id = p_contract_id;
4811 
4812   Cursor revenue_recognition_csr (p_contract_id NUMBER) IS
4813       SELECT ppm.revenue_recognition_method
4814       FROM   okl_k_headers khr,
4815              okl_product_parameters_v ppm
4816        WHERE khr.pdt_id = ppm.id
4817          AND khr.id = p_contract_id;
4818 */
4819 
4820   -- sjalasut, modified the cursor to have khr_id referred from
4821   -- okl_txl_ap_inv_lns_all_b
4822   Cursor pymt_rcpt_actual_var_int_csr (p_contract_id    NUMBER,
4823                                        p_due_date       DATE) IS
4824     SELECT iph.check_date txn_date,
4825            sum(iph.amount) txn_amount,
4826            'P' txn_type
4827     FROM ap_invoices_all ap_inv,
4828          okl_trx_ap_invoices_v okl_inv,
4829          ap_invoice_payment_history_v iph
4830          ,okl_cnsld_ap_invs_all cnsld
4831          ,okl_txl_ap_inv_lns_all_b okl_inv_ln
4832          ,fnd_application fnd_app
4833     WHERE okl_inv.id = okl_inv_ln.tap_id
4834       AND okl_inv_ln.khr_id = p_contract_id
4835       AND ap_inv.application_id = fnd_app.application_id
4836       AND fnd_app.application_short_name = 'OKL'
4837       AND okl_inv_ln.cnsld_ap_inv_id = cnsld.cnsld_ap_inv_id
4838       AND cnsld.cnsld_ap_inv_id = to_number(ap_inv.reference_key1)
4839       AND okl_inv.funding_type_code = 'BORROWER_PAYMENT'
4840       AND ap_inv.invoice_id = iph.invoice_id
4841       AND iph.check_date <= NVL(p_due_date, iph.check_date)
4842     GROUP BY iph.check_date
4843 UNION
4844         SELECT sel.stream_element_date txn_date,
4845                sum(sel.amount) txn_amount,
4846                'R' txn_type
4847         FROM
4848              okl_strm_elements sel
4849              ,okl_streams str
4850              ,okl_strm_type_v sty
4851             WHERE  sel.stm_id = str.id
4852               AND  str.khr_id = p_contract_id
4853               AND  str.say_code = 'CURR'
4854               AND  str.active_yn = 'Y'
4855               AND  sel.stream_element_date <= NVL(p_due_date, sel.stream_element_date)
4856               AND  str.sty_id = sty.id
4857               AND  sty.stream_type_purpose = 'DAILY_INTEREST_PRINCIPAL'
4858        GROUP BY sel.stream_element_date
4859     ORDER BY txn_date asc, txn_type;
4860 
4861   -- sjalasut, modified the cursor to have khr_id referred from okl_txl_Ap_inv_lns_all_b
4862   -- Begin - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
4863     Cursor pymt_rcpt_est_bill_var_int_csr (p_contract_id    NUMBER,
4864                                          p_due_date       DATE) IS
4865     SELECT iph.check_date txn_date,
4866            sum(iph.amount) txn_amount,
4867            'P' txn_type
4868     FROM ap_invoices_all ap_inv,
4869          okl_trx_ap_invoices_v okl_inv,
4870          ap_invoice_payment_history_v iph
4871          ,okl_cnsld_ap_invs_all cnsld
4872          ,okl_txl_ap_inv_lns_all_b okl_inv_ln
4873          ,fnd_application fnd_app
4874     WHERE okl_inv.id = okl_inv_ln.tap_id
4875       AND okl_inv_ln.khr_id = p_contract_id
4876       AND ap_inv.application_id = fnd_app.application_id
4877       AND fnd_app.application_short_name = 'OKL'
4878       AND okl_inv_ln.cnsld_ap_inv_id = cnsld.cnsld_ap_inv_id
4879       AND cnsld.cnsld_ap_inv_id = to_number(ap_inv.reference_key1)
4880       AND okl_inv.funding_type_code = 'BORROWER_PAYMENT'
4881       AND ap_inv.invoice_id = iph.invoice_id
4882       AND iph.check_date <= NVL(p_due_date, iph.check_date)
4883     GROUP BY iph.check_date
4884 UNION
4885     SELECT cra.receipt_date txn_date,
4886            sum(raa.line_applied) txn_amount, -- 4884843, 4872370
4887            'R' txn_type
4888     FROM   okl_bpd_tld_ar_lines_v tld,
4889            ar_payment_schedules_all aps,
4890            ar_receivable_applications_all raa,
4891            ar_cash_receipts_all cra,
4892            okl_strm_type_v sty
4893     WHERE  tld.trx_status_code = 'PROCESSED'
4894       AND  tld.khr_id = NVL(p_contract_id, tld.khr_id)
4895       AND  tld.customer_trx_id = aps.customer_trx_id
4896       AND  raa.applied_customer_trx_id = aps.customer_trx_id
4897       AND  aps.class = 'INV'
4898       AND  (raa.application_type = 'CASH' or raa.application_type = 'CM')
4899       AND  raa.status = 'APP'
4900       AND  cra.receipt_date <= NVL(p_due_date, cra.receipt_date)
4901       AND  raa.cash_receipt_id = cra.cash_receipt_id
4902       AND  tld.sty_id = sty.id
4903       AND  sty.stream_type_purpose = 'UNSCHEDULED_PRINCIPAL_PAYMENT'
4904     GROUP BY cra.receipt_date
4905     ORDER BY txn_date asc, txn_type;
4906 -- End - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
4907 
4908 
4909   BEGIN
4910     x_return_status     := OKL_API.G_RET_STS_SUCCESS;
4911 
4912     print_debug('Executing procedure PRIN_DATE_RANGE_VAR_INT_RLOAN using following parameters : ');
4913     print_debug(' p_contract_id : '|| p_contract_id);
4914 	print_debug(' p_line_id : '|| p_line_id );
4915 	print_debug(' p_due_date : '|| to_char(p_due_date));
4916 
4917 	Initialize_contract_params( p_api_version   => 1.0,
4918                                 p_init_msg_list => OKL_API.G_FALSE,
4919                                 x_return_status => x_return_status,
4920                                 x_msg_count     => x_msg_count,
4921                                 x_msg_data      => x_msg_data,
4922                                 p_contract_id   => p_contract_id
4923                               );
4924     IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
4925 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS completed successfully');
4926     ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
4927   	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
4928   	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
4929        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
4930     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
4931 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
4932 	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
4933        RAISE prin_date_range_rloan_failed;
4934     END IF;
4935 /*
4936     OPEN contract_csr (p_contract_id);
4937     FETCH contract_csr INTO l_contract_start_date, l_currency_code;
4938     IF (contract_csr%NOTFOUND) THEN
4939       CLOSE contract_csr;
4940       print_error_message('Contract Cursor did not return records for contract ID :' || p_contract_id);
4941       RAISE prin_date_range_rloan_failed;
4942     END IF;
4943     CLOSE contract_csr;
4944 
4945     OPEN revenue_recognition_csr (p_contract_id);
4946     FETCH revenue_recognition_csr INTO l_revenue_recognition;
4947     IF revenue_recognition_csr%NOTFOUND THEN
4948       CLOSE revenue_recognition_csr;
4949       print_error_message('Revenue Recognition cursor did not return records for contract ID :' || p_contract_id);
4950       RAISE prin_date_range_rloan_failed;
4951     END IF;
4952     CLOSE revenue_recognition_csr;
4953 */
4954 
4955     print_debug('contract start date : '||G_CONTRACT_START_DATE );
4956 	print_debug('currency code : '|| G_CURRENCY_CODE);
4957 	print_debug ('Revenue Recognition method : '|| G_REVENUE_RECOGNITION_METHOD);
4958 
4959     l_counter              := 0;
4960 
4961     IF (G_REVENUE_RECOGNITION_METHOD = 'ACTUAL') THEN
4962       FOR current_txn in pymt_rcpt_actual_var_int_csr (p_contract_id, p_due_date)
4963       LOOP
4964         l_counter                                       := l_counter + 1;
4965         l_receipt_tbl(l_counter).khr_id                 := p_contract_id;
4966         l_receipt_tbl(l_counter).kle_id                 := NULL;
4967         l_receipt_tbl(l_counter).receipt_date           := current_txn.txn_date;
4968         l_receipt_tbl(l_counter).transaction_type       := current_txn.txn_type;
4969         l_receipt_tbl(l_counter).principal_pmt_rcpt_amt := current_txn.txn_amount;
4970         l_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := 0;
4971       END LOOP;
4972     ELSE
4973       FOR current_txn in pymt_rcpt_est_bill_var_int_csr (p_contract_id, p_due_date)
4974       LOOP
4975         l_counter                                       := l_counter + 1;
4976         l_receipt_tbl(l_counter).khr_id                 := p_contract_id;
4977         l_receipt_tbl(l_counter).kle_id                 := NULL;
4978         l_receipt_tbl(l_counter).receipt_date           := current_txn.txn_date;
4979         l_receipt_tbl(l_counter).transaction_type       := current_txn.txn_type;
4980         l_receipt_tbl(l_counter).principal_pmt_rcpt_amt := current_txn.txn_amount;
4981         l_receipt_tbl(l_counter).loan_pmt_rcpt_amt      := 0;
4982       END LOOP;
4983     END IF;
4984 
4985     l_counter        := 0;
4986     l_rcpt_tbl_count := l_receipt_tbl.COUNT;
4987 
4988     Print_debug ('Contents of Receipts table before consolidation');
4989 
4990 	FOR l_counter IN 1 .. l_rcpt_tbl_count
4991 	LOOP
4992 	  Print_debug('Record Number : '||l_counter);
4993 	  Print_debug('Contract : '||l_receipt_tbl(l_counter).khr_id);
4994 	  Print_debug('Receipt Date: '|| l_receipt_tbl(l_counter).receipt_date);
4995 	  Print_debug('Type : '|| l_receipt_tbl(l_counter).transaction_type);
4996 	  Print_debug('Principal Payment: '|| l_receipt_tbl(l_counter).principal_pmt_rcpt_amt);
4997 	  Print_debug(' ');
4998 	END LOOP;
4999 
5000 	-- Consolidate the receipts posted after contract start date
5001     l_counter        := 0;
5002     l_rcpt_tbl_count := l_receipt_tbl.COUNT;
5003     l_previous_receipt_date  := NULL;
5004     lx_receipt_tbl.delete;
5005 
5006     FOR l_receipt_tbl_counter in 1 .. l_rcpt_tbl_count
5007     LOOP
5008       IF (l_receipt_tbl(l_receipt_tbl_counter).receipt_date <= G_CONTRACT_START_DATE) THEN
5009         l_counter                                        := 1;
5010         lx_receipt_tbl(l_counter).khr_id                 := l_receipt_tbl(l_receipt_tbl_counter).khr_id;
5011         lx_receipt_tbl(l_counter).receipt_date           := G_CONTRACT_START_DATE;
5012         IF (l_receipt_tbl(l_receipt_tbl_counter).transaction_type = 'P') THEN
5013           IF (nvl(lx_receipt_tbl(l_counter).transaction_type, 'P') = 'P') THEN
5014             lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := nvl(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt,0) + l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
5015           ELSE
5016             lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := -1 * nvl(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt,0) + l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
5017           END IF;
5018         ELSE -- 'R'
5019           IF (nvl(lx_receipt_tbl(l_counter).transaction_type, 'P') = 'P') THEN
5020             lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := nvl(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt,0) - l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
5021           ELSE
5022             lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := -1 * nvl(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt,0) - l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
5023           END IF;
5024         END IF;
5025 
5026 		IF (lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt > 0) THEN
5027 		  lx_receipt_tbl(l_counter).transaction_type := 'P';
5028 		ELSE
5029 		  lx_receipt_tbl(l_counter).transaction_type := 'R';
5030 		  lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := abs(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt);
5031 		END IF;
5032       ELSE  -- receipt date > contract start date
5033         IF (l_receipt_tbl(l_receipt_tbl_counter).receipt_date = l_previous_receipt_date ) THEN
5034           IF (l_receipt_tbl(l_receipt_tbl_counter).transaction_type = 'P') THEN
5035             IF (nvl(lx_receipt_tbl(l_counter).transaction_type, 'P') = 'P') THEN
5036               lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := nvl(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt,0) + l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
5037             ELSE
5038               lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := -1 * nvl(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt,0) + l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
5039             END IF;
5040           ELSE -- transaction type = 'R'
5041             IF (nvl(lx_receipt_tbl(l_counter).transaction_type, 'P') = 'P') THEN
5042               lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := nvl(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt,0) - l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
5043             ELSE
5044               lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := -1 * nvl(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt,0) - l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
5045             END IF;
5046           END IF;
5047 
5048 		  IF (lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt > 0) THEN
5049 		    lx_receipt_tbl(l_counter).transaction_type := 'P';
5050 		  ELSE
5051 		    lx_receipt_tbl(l_counter).transaction_type := 'R';
5052 		    lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := abs(lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt);
5053 		  END IF;
5054         ELSE  -- receipt date <> previous receipt date
5055           l_counter                                        := l_counter + 1;
5056           lx_receipt_tbl(l_counter).khr_id                 := l_receipt_tbl(l_receipt_tbl_counter).khr_id;
5057           lx_receipt_tbl(l_counter).receipt_date           := l_receipt_tbl(l_receipt_tbl_counter).receipt_date;
5058           lx_receipt_tbl(l_counter).transaction_type       := l_receipt_tbl(l_receipt_tbl_counter).transaction_type;
5059           lx_receipt_tbl(l_counter).principal_pmt_rcpt_amt := l_receipt_tbl(l_receipt_tbl_counter).principal_pmt_rcpt_amt;
5060           l_previous_receipt_date :=  lx_receipt_tbl(l_counter).receipt_date;
5061         END IF;
5062       END IF;
5063     END LOOP;
5064     l_receipt_tbl := lx_receipt_tbl;
5065 
5066     l_counter        := 0;
5067     l_rcpt_tbl_count := l_receipt_tbl.COUNT;
5068 
5069     Print_debug ('Contents of Receipts table after consolidation');
5070 
5071 	FOR l_counter IN 1 .. l_rcpt_tbl_count
5072 	LOOP
5073 	  Print_debug('Record Number : '||l_counter);
5074 	  Print_debug('Contract : '||l_receipt_tbl(l_counter).khr_id);
5075 	  Print_debug('Receipt Date: '|| l_receipt_tbl(l_counter).receipt_date);
5076 	  Print_debug('Type : '|| l_receipt_tbl(l_counter).transaction_type);
5077 	  Print_debug('Principal Payment: '|| l_receipt_tbl(l_counter).principal_pmt_rcpt_amt);
5078 	  Print_debug(' ');
5079 	END LOOP;
5080 
5081     l_counter              := 0;
5082     l_start_date           := G_CONTRACT_START_DATE;
5083     l_principal_balance    := 0;
5084     l_current_txn_date     := NULL;
5085     l_rcpt_tbl_count := l_receipt_tbl.COUNT;
5086 
5087     FOR l_rcpt_tbl_counter IN 1 .. l_rcpt_tbl_count
5088     LOOP
5089       l_current_txn_date := l_receipt_tbl(l_rcpt_tbl_counter).receipt_date;
5090       IF (l_current_txn_date > G_CONTRACT_START_DATE) THEN
5091         l_counter          := l_counter + 1;
5092 --        l_current_txn_date := l_receipt_tbl(l_rcpt_tbl_counter).receipt_date;
5093         l_principal_balance_tbl(l_counter).khr_id     := p_contract_id;
5094         l_principal_balance_tbl(l_counter).kle_id     := NULL;
5095         l_principal_balance_tbl(l_counter).from_date := l_start_date;
5096         l_principal_balance_tbl(l_counter).to_date   := l_current_txn_date - 1;
5097         l_principal_balance_tbl(l_counter).principal_balance      := l_principal_balance;
5098         l_start_date := l_current_txn_date;
5099 
5100         IF (l_receipt_tbl(l_rcpt_tbl_counter).transaction_type = 'P') THEN
5101           l_principal_balance := l_principal_balance + l_receipt_tbl(l_rcpt_tbl_counter).principal_pmt_rcpt_amt;
5102         ELSE
5103           l_principal_balance := l_principal_balance - l_receipt_tbl(l_rcpt_tbl_counter).principal_pmt_rcpt_amt;
5104         END IF;
5105         print_debug ('l_principal_balance_tbl(l_counter).khr_id : '|| l_principal_balance_tbl(l_counter).khr_id);
5106         print_debug ('l_principal_balance_tbl(l_counter).from_date : '|| l_principal_balance_tbl(l_counter).from_date);
5107         print_debug ('l_principal_balance_tbl(l_counter).to_date : '|| l_principal_balance_tbl(l_counter).to_date);
5108         print_debug ('l_principal_balance_tbl(l_counter).principal_balance : '|| l_principal_balance_tbl(l_counter).principal_balance);
5109 
5110       ELSE
5111         l_principal_balance := l_principal_balance + l_receipt_tbl(l_rcpt_tbl_counter).principal_pmt_rcpt_amt;
5112       END IF;
5113 
5114     END LOOP;
5115 
5116     l_counter                                              := l_counter + 1;
5117     l_principal_balance_tbl(l_counter).khr_id              := p_contract_id;
5118     l_principal_balance_tbl(l_counter).kle_id              := NULL;
5119     l_principal_balance_tbl(l_counter).from_date           := l_start_date;
5120     l_principal_balance_tbl(l_counter).to_date             := p_due_date;
5121     l_principal_balance_tbl(l_counter).principal_balance   := l_principal_balance;
5122 
5123     print_debug ('l_principal_balance_tbl(l_counter).khr_id : '|| l_principal_balance_tbl(l_counter).khr_id);
5124     print_debug ('l_principal_balance_tbl(l_counter).from_date : '|| l_principal_balance_tbl(l_counter).from_date);
5125     print_debug ('l_principal_balance_tbl(l_counter).to_date : '|| l_principal_balance_tbl(l_counter).to_date);
5126     print_debug ('l_principal_balance_tbl(l_counter).principal_balance : '|| l_principal_balance_tbl(l_counter).principal_balance);
5127 
5128 
5129     l_counter := l_principal_balance_tbl.first;
5130     LOOP
5131       EXIT WHEN l_counter IS NULL;
5132       IF ((p_start_date >= l_principal_balance_tbl(l_counter).from_date AND p_start_date <= l_principal_balance_tbl(l_counter).to_date) OR
5133           (p_due_date >= l_principal_balance_tbl(l_counter).from_date AND p_due_date <= l_principal_balance_tbl(l_counter).to_date) OR
5134           (l_principal_balance_tbl(l_counter).from_date >= p_start_date AND l_principal_balance_tbl(l_counter).to_date <= p_due_date)) THEN
5135         l_counter_tmp := l_counter_tmp + 1;
5136         l_principal_balance_tbl_tmp(l_counter_tmp) := l_principal_balance_tbl(l_counter);
5137         l_principal_balance_tbl_tmp(l_counter_tmp).from_date := GREATEST(l_principal_balance_tbl_tmp(l_counter_tmp).from_date, p_start_date);
5138         l_principal_balance_tbl_tmp(l_counter_tmp).to_date := LEAST(l_principal_balance_tbl_tmp(l_counter_tmp).to_date, p_due_date);
5139       END IF;
5140       l_counter := l_principal_balance_tbl.next(l_counter);
5141     END LOOP;
5142 
5143     x_principal_balance_tbl := l_principal_balance_tbl_tmp;
5144 
5145     print_principal_date_range_tbl (x_principal_balance_tbl);
5146 
5147   EXCEPTION
5148      WHEN prin_date_range_rloan_failed THEN
5149        print_error_message('print_date_range_rloan_failed Exception raised inside procedure PRIN_DATE_RANGE_VAR_INT_RLOAN');
5150        x_return_status := OKL_API.G_RET_STS_ERROR;
5151 
5152      WHEN OTHERS THEN
5153        print_error_message('Exception raised inside procedure PRIN_DATE_RANGE_VAR_INT_RLOAN');
5154        Okl_Api.SET_MESSAGE(
5155                p_app_name     => G_APP_NAME,
5156                p_msg_name     => G_UNEXPECTED_ERROR,
5157                p_token1       => G_SQLCODE_TOKEN,
5158                p_token1_value => SQLCODE,
5159                p_token2       => G_SQLERRM_TOKEN,
5160                p_token2_value => SQLERRM);
5161 
5162        x_return_status := OKL_API.G_RET_STS_ERROR;
5163 
5164   END prin_date_range_var_int_rloan;
5165 
5166   ------------------------------------------------------------------------------
5167 
5168     -- Start of Comments
5169     -- Created By:       Ramesh Seela
5170     -- Procedure Name    prin_date_range_var_int_rl_old
5171     -- Description:      This procedure is called by Variable Interest Calculation for Revolving Loans
5172     --                   Returns a PL/SQL table of records with following entries Start Date, End Date,
5173     --                   and Principal Balance
5174     -- Dependencies:
5175     -- Parameters:       contract id, date.
5176     -- Version:          1.0
5177     --                   2.0 - Obsoleted this local procedure as part of Billing Inline changes- Bug#5898792 - varangan - 23/2/2007
5178     -- End of Comments
5179 
5180 ------------------------------------------------------------------------------
5181 
5182 ------------------------------------------------------------------------------
5183     -- Start of Comments
5184     -- Created By:       Ramesh Seela
5185     -- Procedure Name    prin_date_range_var_rate_ctr
5186     -- Description:      This procedure is called by Variable Interest Calculation
5187     --                   Returns a PL/SQL table of records with following entries Start Date, End Date,
5188     --                   and Principal Balance
5189     -- Dependencies:
5190     -- Parameters:
5191     -- Version:          1.0
5192     -- End of Comments
5193 
5194   ------------------------------------------------------------------------------
5195   PROCEDURE prin_date_range_var_rate_ctr (
5196             p_api_version        IN  NUMBER,
5197             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
5198             x_return_status      OUT NOCOPY VARCHAR2,
5199             x_msg_count          OUT NOCOPY NUMBER,
5200             x_msg_data           OUT NOCOPY VARCHAR2,
5201             p_contract_id        IN  NUMBER,
5202             p_line_id            IN  NUMBER,
5203             p_start_date         IN  DATE,
5204             p_due_date           IN  DATE,
5205             p_principal_basis    IN  VARCHAR2 DEFAULT NULL,
5206             x_principal_balance_tbl OUT NOCOPY  principal_balance_tbl_typ)   IS
5207 
5208   l_api_name               CONSTANT    VARCHAR2(30) := 'PRIN_DATE_RANGE_VAR_RATE_CTR';
5209   l_api_version            CONSTANT    NUMBER       := 1.0;
5210   r_principal_balance_tbl  principal_balance_tbl_typ ;
5211   l_deal_type              OKL_K_HEADERS_FULL_V.deal_type%TYPE;
5212   prin_date_range_failed   EXCEPTION;
5213 
5214 
5215   Cursor contract_csr (p_contract_id NUMBER) IS
5216       SELECT deal_type
5217       FROM   okl_k_headers_full_v
5218       WHERE  id = p_contract_id;
5219 
5220 
5221   BEGIN
5222     x_return_status     := OKL_API.G_RET_STS_SUCCESS;
5223 
5224     print_debug('Executing procedure PRIN_DATE_RANGE_VAR_RATE_CTR using following parameters : ');
5225     print_debug(' p_contract_id : '|| p_contract_id );
5226 	print_debug(' p_line_id : '|| p_line_id );
5227 	print_debug(' p_start_date : '|| to_char(p_start_date));
5228 	print_debug(' p_due_date : '|| to_char(p_due_date));
5229 
5230 	print_debug(' G_CONTRACT_ID : '|| G_CONTRACT_ID );
5231 
5232     IF (p_contract_id = G_CONTRACT_ID) THEN
5233       l_deal_type := G_DEAL_TYPE;
5234     ELSE
5235       OPEN contract_csr (p_contract_id);
5236       FETCH contract_csr INTO l_deal_type;
5237       IF (contract_csr%NOTFOUND) THEN
5238         CLOSE contract_csr;
5239         print_error_message('Contract cursor did not return records for contract ID :' || p_contract_id);
5240         RAISE prin_date_range_failed;
5241       END IF;
5242       CLOSE contract_csr;
5243     END IF;
5244 
5245     print_debug('deal type : '|| l_deal_type);
5246 
5247     IF (l_deal_type = 'LOAN') THEN
5248        prin_date_range_var_int_loan (
5249                                      p_api_version           => 1.0,
5250                                      p_init_msg_list         => OKL_API.G_FALSE,
5251                                      x_return_status         => x_return_status,
5252                                      x_msg_count             => x_msg_count,
5253                                      x_msg_data              => x_msg_data,
5254                                      p_contract_id           => p_contract_id,
5255                                      p_line_id               => p_line_id,
5256                                      p_start_date            => p_start_date,
5257                                      p_due_date              => p_due_date,
5258                                      p_principal_basis       => p_principal_basis,
5259                                      x_principal_balance_tbl => r_principal_balance_tbl);
5260 
5261        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
5262          print_error_message('Unexpected error raised in call to PRIN_DATE_RANGE_VAR_INT_LOAN');
5263          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
5264        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
5265          print_error_message('Error raised in call to PRIN_DATE_RANGE_VAR_INT_LOAN');
5266          RAISE prin_date_range_failed;
5267        END IF;
5268 
5269     ELSIF (l_deal_type = 'LOAN-REVOLVING') THEN
5270        prin_date_range_var_int_rloan (
5271                                      p_api_version           => 1.0,
5272                                      p_init_msg_list         => OKL_API.G_FALSE,
5273                                      x_return_status         => x_return_status,
5274                                      x_msg_count             => x_msg_count,
5275                                      x_msg_data              => x_msg_data,
5276                                      p_contract_id           => p_contract_id,
5277                                      p_line_id               => p_line_id,
5278                                      p_start_date            => p_start_date,
5279                                      p_due_date              => p_due_date,
5280                                      x_principal_balance_tbl => r_principal_balance_tbl);
5281        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
5282          print_error_message('Unexpected error raised in call to PRIN_DATE_RANGE_VAR_INT_RLOAN');
5283          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
5284        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
5285          print_error_message('Error raised in call to PRIN_DATE_RANGE_VAR_INT_LOAN');
5286          RAISE prin_date_range_failed;
5287        END IF;
5288     END IF;
5289 
5290     x_principal_balance_tbl := r_principal_balance_tbl;
5291 
5292   EXCEPTION
5293      WHEN prin_date_range_failed THEN
5294        print_error_message('prin_date_range_failed Exception raised in procedure PRIN_DATE_RANGE_VAR_INT_CTR');
5295        x_return_status := OKL_API.G_RET_STS_ERROR;
5296 
5297      WHEN OTHERS THEN
5298        print_error_message('Exception raised in procedure PRIN_DATE_RANGE_VAR_INT_CTR');
5299        Okl_Api.SET_MESSAGE(
5300                p_app_name     => G_APP_NAME,
5301                p_msg_name     => G_UNEXPECTED_ERROR,
5302                p_token1       => G_SQLCODE_TOKEN,
5303                p_token1_value => SQLCODE,
5304                p_token2       => G_SQLERRM_TOKEN,
5305                p_token2_value => SQLERRM);
5306 
5307        x_return_status := OKL_API.G_RET_STS_ERROR;
5308 
5309   END prin_date_range_var_rate_ctr;
5310 ------------------------------------------------------------------------------
5311 FUNCTION get_last_int_calc_date(p_khr_id IN NUMBER) RETURN DATE IS
5312   l_ret_date DATE := NULL;
5313 
5314   CURSOR c_int_calc_date_csr(cp_khr_id NUMBER) IS SELECT (max(sel.stream_element_date) - 1) last_interest_calc_date
5315   FROM  okl_streams stm,
5316         okl_strm_elements sel,
5317         okl_strm_type_b sty
5318   WHERE stm.khr_id = cp_khr_id
5319   AND   stm.id = sel.stm_id
5320   AND   stm.sty_id = sty.id
5321   AND   (sty.stream_type_purpose = 'DAILY_INTEREST_PRINCIPAL' OR sty.stream_type_purpose = 'DAILY_INTEREST_INTEREST');
5322 
5323   CURSOR c_khr_start_date_csr(cp_khr_id NUMBER) IS SELECT start_date - 1
5324   FROM okc_k_headers_b
5325   WHERE id = cp_khr_id;
5326 
5327 BEGIN
5328   OPEN c_int_calc_date_csr(p_khr_id);
5329   FETCH c_int_calc_date_csr INTO l_ret_date;
5330   CLOSE c_int_calc_date_csr;
5331 
5332   IF (l_ret_date IS NULL) THEN
5333     OPEN c_khr_start_date_csr(p_khr_id);
5334     FETCH c_khr_start_date_csr INTO l_ret_date;
5335     CLOSE c_khr_start_date_csr;
5336   END IF;
5337 
5338   RETURN l_ret_date;
5339 END;
5340 ------------------------------------------------------------------------------
5341   PROCEDURE interest_date_range (
5342             p_api_version        IN  NUMBER,
5343             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
5344             x_return_status      OUT NOCOPY VARCHAR2,
5345             x_msg_count          OUT NOCOPY NUMBER,
5346             x_msg_data           OUT NOCOPY VARCHAR2,
5347             p_contract_id        IN  NUMBER,
5348             p_start_date         IN  DATE,
5349             p_end_date           IN  DATE,
5350             p_process_flag       IN  VARCHAR2,
5351             p_rate_param_rowid   IN  ROWID,
5352             x_interest_rate_tbl OUT NOCOPY interest_rate_tbl_type)   IS
5353 
5354     -----------------------------------------------------------------
5355     -- Declare Process Variable
5356     -----------------------------------------------------------------
5357     l_api_name	        CONSTANT VARCHAR2(30)   := 'interest_date_range';
5358     l_return_status	VARCHAR2(1)             := OKL_API.G_RET_STS_SUCCESS;
5359 
5360     l_interest_rate_tbl interest_rate_tbl_type;
5361     l_start_date        DATE;
5362     l_end_date          DATE;
5363     l_int_tbl_row       NUMBER := 0;
5364     --specifies whether the rate is to be derived from interest index
5365     l_derive_rate_flag  VARCHAR2(1) := 'Y';
5366 
5367     l_rate_change_start_date DATE := NULL;
5368     l_next_rate_change_date DATE := NULL;
5369 
5370     ----------------------------------------------------------------
5371     -- Declare variable interest parameter cursor
5372     -----------------------------------------------------------------
5373     --dkagrawa changed query to use okl_prod_qlty_val_uv than okl_product_parameter_v for performance
5374     CURSOR c_int_param(cp_rate_param_rowid ROWID) IS
5375          SELECT krp.interest_index_id
5376               , NVL(krp.base_rate, 0) base_rate
5377               , NVL(krp.interest_start_date, chr.start_date) interest_start_date
5378               , NVL(krp.adder_rate, 0) adder_rate
5379               , NVL(krp.maximum_rate, 9999) maximum_rate
5380               , NVL(krp.minimum_rate, 0) minimum_rate
5381               , krp.rate_delay_code
5382               , NVL(krp.rate_delay_frequency, 0) rate_delay_frequency
5383               , NVL(krp.rate_change_start_date, chr.start_date) rate_change_start_date
5384               , NVL(krp.rate_change_frequency_code, 'DAILY') rate_change_frequency_code
5385               , NVL(krp.rate_change_value, 0) rate_change_value
5386               --if the calling process is Daily Interest, get the last int cal date from
5387               --the Daily Interest streams
5388               --for a REAMORT contract, if the calling process is Reamortization (initiate_request)
5389               --and it is being run for the first time for the contract, the last interest calc date
5390               --defaults to the start date (as there may be a previously derived value due to the fact
5391               --that the Reamort may not have completed in its entirety)
5392               --if it is called from any other process for a REAMORT contract, the last int calc date
5393               --defaults to start date minus 1
5394               --for all other types of contracts, the last int calc date
5395               --defaults to start date minus 1
5396               , decode(p_process_flag, 'DAILY_INTEREST', get_last_int_calc_date(chr.id),
5397                                    decode(ppm.quality_val, 'REAMORT', NVL(khr.date_last_interim_interest_cal,
5398                                                decode(OKL_VARIABLE_INTEREST_PVT.G_CALC_METHOD_CODE, 'REAMORT', chr.start_date, chr.start_date-1)), NVL(khr.date_last_interim_interest_cal, chr.start_date - 1))) date_last_interim_interest_cal
5399               , chr.start_date contract_start_date
5400               , chr.end_date contract_end_date
5401               , chr.id khr_id
5402               , ppm.quality_val interest_calculation_basis
5403               , NULL pay_freq
5404          FROM okl_k_rate_params krp
5405          , okl_k_headers khr
5406          , okc_k_headers_b chr
5407          , okl_prod_qlty_val_uv ppm
5408          WHERE krp.rowid = cp_rate_param_rowid
5409          AND krp.khr_id = khr.id
5410          AND khr.id = chr.id
5411          --AND TRUNC(SYSDATE) BETWEEN krp.effective_from_date and NVL(krp.effective_to_date, trunc(SYSDATE))
5412          --AND krp.parameter_type_code = 'ACTUAL'
5413          AND khr.pdt_id = ppm.pdt_id
5414          AND ppm.quality_name = 'INTEREST_CALCULATION_BASIS';
5415 
5416     TYPE int_param_tbl_type IS TABLE OF c_int_param%ROWTYPE INDEX BY BINARY_INTEGER;
5417 
5418     l_int_param_tbl int_param_tbl_type;
5419     l_param_tbl_row NUMBER := 0;
5420     x_eff_int_tbl interest_rate_tbl_type;
5421     l_eff_int_row   NUMBER := 0;
5422 
5423     ----------------------------------------------------------------
5424     -- Declare interest rate cursor
5425     -- used to derive interest rates from the interest parameter
5426     -- when interest dates are less than last int calc date
5427     -----------------------------------------------------------------
5428     CURSOR c_param_rate(cp_khr_id NUMBER, cp_start_date DATE, cp_end_date DATE, cp_process_flag IN VARCHAR2) IS
5429     SELECT vip.interest_rate VALUE,
5430            GREATEST(trunc(cp_start_date),interest_calc_start_date) VALID_FROM,
5431            LEAST(trunc(cp_end_date),NVL(interest_calc_end_date, trunc(sysdate))) VALID_UNTIL
5432     FROM okl_var_int_params vip
5433     WHERE   vip.khr_id = cp_khr_id
5434     AND   (cp_start_date BETWEEN vip.interest_calc_start_date AND nvl(vip.interest_calc_end_date, trunc(cp_start_date))
5435            OR    (cp_end_date BETWEEN vip.interest_calc_start_date AND nvl(vip.interest_calc_end_date, trunc(cp_end_date)))
5436            OR    (vip.interest_calc_start_date >= cp_start_date AND nvl(vip.interest_calc_end_date, trunc(sysdate + 9999)) <= cp_end_date) )
5437     AND   vip.calc_method_code = NVL(cp_process_flag, vip.calc_method_code)
5438     AND   vip.valid_yn = 'Y'
5439     ORDER BY VALID_FROM;
5440 
5441     ----------------------------------------------------------------
5442     -- Declare payment frequency cursor
5443     -----------------------------------------------------------------
5444     CURSOR c_pay_freq(cp_khr_id NUMBER) IS
5445     select sll_rulb.object1_id1 pay_freq
5446     from   okc_rules_b        sll_rulb,
5447       okc_rules_b        slh_rulb,
5448       okl_strm_type_b    styb,
5449       okc_rule_groups_b  rgpb
5450     where  sll_rulb.rgp_id                      = rgpb.id
5451     and    sll_rulb.rule_information_category   = 'LASLL'
5452     and    sll_rulb.dnz_chr_id                  = rgpb.dnz_chr_id
5453     and    sll_rulb.object2_id1                 = to_char(slh_rulb.id)
5454     and    slh_rulb.rgp_id                      = rgpb.id
5455     and    slh_rulb.rule_information_category   = 'LASLH'
5456     and    slh_rulb.dnz_chr_id                  = rgpb.dnz_chr_id
5457     and    styb.id                              = slh_rulb.object1_id1
5458     and    styb.stream_type_purpose             IN ('RENT', 'PRINCIPAL_PAYMENT')
5459     and    rgpb.dnz_chr_id                      = cp_khr_id
5460     and    rgpb.rgd_code                        = 'LALEVL'
5461     order by sll_rulb.rule_information1;
5462 
5463     /*Returns the interest rate from the interest index for inputted index id and date range*/
5464     PROCEDURE get_eff_int_rate(p_start_date IN DATE, p_end_date IN DATE, p_int_param_tbl IN int_param_tbl_type, x_eff_int_tbl IN OUT NOCOPY interest_rate_tbl_type) IS
5465 
5466       CURSOR c_int_rate(cp_index_id NUMBER, cp_start_date DATE, cp_end_date DATE) IS
5467       SELECT ive.value VALUE,
5468              GREATEST(trunc(cp_start_date),datetime_valid) VALID_FROM,
5469              LEAST(trunc(cp_end_date),NVL(datetime_invalid, trunc(sysdate))) VALID_UNTIL
5470       FROM okl_indices idx,
5471            okl_index_values ive
5472       WHERE   idx.id = cp_index_id
5473       AND idx.id = ive.idx_id
5474       AND   (cp_start_date BETWEEN ive.datetime_valid AND nvl(ive.datetime_invalid, trunc(cp_start_date))
5475              OR    (cp_end_date BETWEEN ive.datetime_valid AND nvl(ive.datetime_invalid, trunc(cp_end_date)))
5476              OR    (ive.datetime_valid >= cp_start_date AND nvl(ive.datetime_invalid, trunc(sysdate + 9999)) <= cp_end_date) )
5477       ORDER BY VALID_FROM;
5478 
5479       l_int_param_row NUMBER := 0;
5480       l_eff_int_row   NUMBER := 0;
5481       l_int_param_tbl int_param_tbl_type;
5482       l_eff_int_tbl   interest_rate_tbl_type;
5483     BEGIN
5484       l_int_param_tbl := p_int_param_tbl;
5485       l_eff_int_tbl.delete;
5486 
5487       l_int_param_row := l_int_param_tbl.first;
5488       l_eff_int_row := 0;
5489 
5490       print_debug('in procedure get_eff_int_rate for date range : ' || p_start_date || ' - ' || p_end_date);
5491       WHILE l_int_param_row IS NOT NULL
5492       LOOP
5493         FOR cur_int_rate IN c_int_rate(l_int_param_tbl(l_int_param_row).interest_index_id,
5494                                        p_start_date,
5495                                        p_end_date) LOOP
5496             l_eff_int_row := l_eff_int_row + 1;
5497             l_eff_int_tbl(l_eff_int_row).from_date := cur_int_rate.valid_from;
5498             l_eff_int_tbl(l_eff_int_row).to_date := cur_int_rate.valid_until;
5499             l_eff_int_tbl(l_eff_int_row).rate := cur_int_rate.value + l_int_param_tbl(l_int_param_row).adder_rate;
5500             l_eff_int_tbl(l_eff_int_row).derived_flag := 'Y';
5501             l_eff_int_tbl(l_eff_int_row).apply_tolerance := 'Y';
5502         END LOOP;
5503         l_int_param_row := l_int_param_tbl.next(l_int_param_row);
5504       END LOOP;
5505 
5506       print_debug('exit procedure get_eff_int_rate');
5507       x_eff_int_tbl := l_eff_int_tbl;
5508     EXCEPTION
5509       WHEN OTHERS THEN
5510         OKL_API.SET_MESSAGE( p_app_name     => G_APP_NAME
5511                           ,p_msg_name     => G_UNEXPECTED_ERROR
5512                           ,p_token1       => G_SQLCODE_TOKEN
5513                           ,p_token1_value => SQLCODE
5514                           ,p_token2       => G_SQLERRM_TOKEN
5515                           ,p_token2_value => SQLERRM);
5516     END get_eff_int_rate;
5517 
5518     /*returnd the next applicable rate change start date for a contract*/
5519     FUNCTION get_next_rate_change_date(p_rate_change_start_date DATE, p_int_param_tbl IN int_param_tbl_type) RETURN DATE IS
5520       l_int_param_tbl int_param_tbl_type;
5521       l_int_param_tbl_row NUMBER := 0;
5522       l_next_rate_change_date DATE;
5523       l_period_start_date DATE;
5524       l_period_end_date DATE;
5525       l_adder_months NUMBER;
5526       x_return_status VARCHAR2(1);
5527       x_msg_count NUMBER;
5528       x_msg_data VARCHAR2(4000);
5529     BEGIN
5530       print_debug('in function get_next_rate_change_date');
5531       print_debug('input parameters :-');
5532       print_debug('p_rate_change_start_date : ' || p_rate_change_start_date);
5533 
5534       l_int_param_tbl := p_int_param_tbl;
5535       l_int_param_tbl_row := l_int_param_tbl.first;
5536 
5537       IF (l_int_param_tbl(l_int_param_tbl_row).rate_change_frequency_code = 'MONTHLY') THEN
5538         l_next_rate_change_date := add_months(p_rate_change_start_date, 1);
5539       ELSIF (l_int_param_tbl(l_int_param_tbl_row).rate_change_frequency_code = 'QUARTERLY') THEN
5540         l_next_rate_change_date := add_months(p_rate_change_start_date, 3);
5541       ELSIF (l_int_param_tbl(l_int_param_tbl_row).rate_change_frequency_code = 'ANNUAL') THEN
5542         l_next_rate_change_date := add_months(p_rate_change_start_date, 12);
5543       ELSE -- (l_int_param_tbl(l_int_param_row).rate_change_frequency_code = 'BILLING_DATE' THEN
5544         IF (l_int_param_tbl(l_int_param_tbl_row).interest_calculation_basis = 'FLOAT') THEN
5545             OKL_STREAM_GENERATOR_PVT.get_next_billing_date(
5546                 p_api_version            => p_api_version,
5547        	        p_init_msg_list          => p_init_msg_list,
5548         	   	 	p_khr_id                 => l_int_param_tbl(l_int_param_tbl_row).khr_id,
5549                 p_billing_date           => p_rate_change_start_date,
5550                 x_next_due_date          => l_next_rate_change_date,
5551                 x_next_period_start_date => l_period_start_date,
5552                 x_next_period_end_date   => l_period_end_date,
5553           			x_return_status          => x_return_status,
5554           			x_msg_count              => x_msg_count,
5555           			x_msg_data               => x_msg_data);
5556         ELSE
5557           IF (l_int_param_tbl(l_int_param_tbl_row).pay_freq = 'M') THEN
5558             l_adder_months := 1;
5559           ELSIF (l_int_param_tbl(l_int_param_tbl_row).pay_freq = 'Q') THEN
5560             l_adder_months := 3;
5561           ELSIF (l_int_param_tbl(l_int_param_tbl_row).pay_freq = 'S') THEN
5562             l_adder_months := 6;
5563           ELSIF (l_int_param_tbl(l_int_param_tbl_row).pay_freq = 'A') THEN
5564             l_adder_months := 12;
5565           ELSE
5566             l_adder_months := 1;
5567           END IF;
5568           l_next_rate_change_date := add_months(p_rate_change_start_date, l_adder_months);
5569         END IF;
5570       END IF;
5571 
5572       print_debug('l_next_rate_change_date : ' || l_next_rate_change_date);
5573       print_debug('exiting function get_next_rate_change_date');
5574       RETURN l_next_rate_change_date;
5575     EXCEPTION
5576       WHEN OTHERS THEN
5577         OKL_API.SET_MESSAGE( p_app_name     => G_APP_NAME
5578                           ,p_msg_name     => G_UNEXPECTED_ERROR
5579                           ,p_token1       => G_SQLCODE_TOKEN
5580                           ,p_token1_value => SQLCODE
5581                           ,p_token2       => G_SQLERRM_TOKEN
5582                           ,p_token2_value => SQLERRM);
5583 
5584         RETURN l_next_rate_change_date;
5585     END get_next_rate_change_date;
5586 
5587     /*check the derived interest rates for tolerance*/
5588     PROCEDURE apply_tolerance(p_int_param_tbl IN int_param_tbl_type, p_eff_int_tbl IN interest_rate_tbl_type, x_eff_int_with_tol_tbl IN OUT NOCOPY interest_rate_tbl_type) IS
5589       l_int_param_row NUMBER := 0;
5590       l_eff_int_row   NUMBER := 0;
5591       l_eff_int_with_tol_row   NUMBER := 0;
5592       l_prev_eff_int_with_tol_row   NUMBER := 0;
5593 
5594       l_int_param_tbl int_param_tbl_type;
5595       l_eff_int_tbl   interest_rate_tbl_type;
5596       l_eff_int_with_tol_tbl interest_rate_tbl_type;
5597 
5598       l_first_row BOOLEAN := TRUE;
5599       l_compare_to_base BOOLEAN := TRUE;
5600       l_compare_to_min_max BOOLEAN := TRUE;
5601 
5602       cursor c_most_recent_rate(cp_khr_id IN NUMBER, cp_from_date IN DATE, cp_process_flag IN VARCHAR2) IS
5603       select interest_calc_start_date
5604             ,interest_calc_end_date
5605             ,interest_rate
5606       from (select vip.interest_calc_start_date
5607                   ,vip.interest_calc_end_date
5608                   ,vip.interest_rate
5609             from okl_var_int_params vip
5610             where vip.khr_id = cp_khr_id
5611             and   vip.interest_calc_end_date < cp_from_date
5612             AND   vip.calc_method_code = NVL(cp_process_flag, vip.calc_method_code)
5613             AND   vip.valid_yn = 'Y'
5614             order by vip.interest_calc_end_date desc)
5615       where rownum = 1;
5616 
5617     BEGIN
5618       print_debug('in procedure apply_tolerance');
5619       l_int_param_tbl := p_int_param_tbl;
5620       l_eff_int_tbl := p_eff_int_tbl;
5621       l_eff_int_with_tol_tbl.delete;
5622 
5623       l_int_param_row := l_int_param_tbl.first;
5624       l_eff_int_row := l_eff_int_tbl.first;
5625       WHILE l_eff_int_row IS NOT NULL
5626       LOOP
5627         l_prev_eff_int_with_tol_row := l_eff_int_with_tol_row;
5628         l_eff_int_with_tol_row := l_eff_int_with_tol_row + 1;
5629         l_eff_int_with_tol_tbl(l_eff_int_with_tol_row) := l_eff_int_tbl(l_eff_int_row);
5630         l_compare_to_min_max := TRUE;
5631 
5632         IF (l_eff_int_tbl(l_eff_int_row).apply_tolerance = 'Y') THEN
5633           --first row in the effective interest rates table
5634           IF (l_first_row) THEN
5635             --comparing to most recent rate
5636             FOR cur_most_recent_rate IN c_most_recent_rate(l_int_param_tbl(l_int_param_row).khr_id, l_eff_int_tbl(l_eff_int_row).from_date, p_process_flag) LOOP
5637               IF (ABS(l_eff_int_tbl(l_eff_int_row).rate - cur_most_recent_rate.interest_rate) < l_int_param_tbl(l_int_param_row).rate_change_value) THEN
5638                 l_eff_int_with_tol_tbl(l_eff_int_with_tol_row).rate := cur_most_recent_rate.interest_rate;
5639                 l_compare_to_min_max := FALSE;
5640               END IF;
5641               l_compare_to_base := FALSE;
5642             END LOOP;
5643 
5644             --compare to base rate
5645             IF (l_compare_to_base AND ABS(l_eff_int_tbl(l_eff_int_row).rate - l_int_param_tbl(l_int_param_row).base_rate) < l_int_param_tbl(l_int_param_row).rate_change_value) THEN
5646               l_eff_int_with_tol_tbl(l_eff_int_with_tol_row).rate := l_int_param_tbl(l_int_param_row).base_rate;
5647               l_compare_to_min_max := FALSE;
5648             END IF;
5649 
5650             l_first_row := FALSE;
5651           ELSE
5652             --compare to the previous entry in the rates table
5653             IF (ABS(l_eff_int_tbl(l_eff_int_row).rate - l_eff_int_with_tol_tbl(l_prev_eff_int_with_tol_row).rate) < l_int_param_tbl(l_int_param_row).rate_change_value) THEN
5654               l_eff_int_with_tol_tbl(l_eff_int_with_tol_row).rate := l_eff_int_with_tol_tbl(l_prev_eff_int_with_tol_row).rate;
5655               l_compare_to_min_max := FALSE;
5656             END IF;
5657           END IF;
5658 
5659           --compare to minimum and maximum
5660           IF (l_compare_to_min_max) THEN
5661             IF (l_eff_int_with_tol_tbl(l_eff_int_with_tol_row).rate < l_int_param_tbl(l_int_param_row).minimum_rate) THEN
5662               l_eff_int_with_tol_tbl(l_eff_int_with_tol_row).rate := l_int_param_tbl(l_int_param_row).minimum_rate;
5663             END IF;
5664 
5665             IF (l_eff_int_with_tol_tbl(l_eff_int_with_tol_row).rate > l_int_param_tbl(l_int_param_row).maximum_rate) THEN
5666               l_eff_int_with_tol_tbl(l_eff_int_with_tol_row).rate := l_int_param_tbl(l_int_param_row).maximum_rate;
5667             END IF;
5668           END IF;
5669         END IF;
5670 
5671         l_eff_int_row := l_eff_int_tbl.next(l_eff_int_row);
5672       END LOOP;
5673 
5674       x_eff_int_with_tol_tbl := l_eff_int_with_tol_tbl;
5675       print_debug('exiting procedure apply_tolerance');
5676     EXCEPTION
5677       WHEN OTHERS THEN
5678         OKL_API.SET_MESSAGE( p_app_name     => G_APP_NAME
5679                           ,p_msg_name     => G_UNEXPECTED_ERROR
5680                           ,p_token1       => G_SQLCODE_TOKEN
5681                           ,p_token1_value => SQLCODE
5682                           ,p_token2       => G_SQLERRM_TOKEN
5683                           ,p_token2_value => SQLERRM);
5684     END apply_tolerance;
5685 
5686     /*outputs the contents of tables passed to it*/
5687     PROCEDURE print_table_content(p_int_param_tbl IN int_param_tbl_type, p_eff_int_tbl IN interest_rate_tbl_type) IS
5688       l_int_param_row NUMBER := 0;
5689       l_eff_int_row   NUMBER := 0;
5690       l_out_str varchar2(2000);
5691     BEGIN
5692 
5693       print_debug('*****************************************');
5694       print_debug('****START CONTENTS OF P_INT_PARAM_TBL****');
5695       l_int_param_row := p_int_param_tbl.first;
5696       WHILE l_int_param_row IS NOT NULL
5697       LOOP
5698         print_debug('	interest_index_id : ' || p_int_param_tbl(l_int_param_row).interest_index_id);
5699         print_debug('	base_rate : ' || p_int_param_tbl(l_int_param_row).base_rate);
5700         print_debug('	interest_start_date	 : ' || 	p_int_param_tbl(l_int_param_row).interest_start_date);
5701         print_debug('	adder_rate                    	 : ' || 	p_int_param_tbl(l_int_param_row).adder_rate);
5702         print_debug('	maximum_rate	 : ' || 	p_int_param_tbl(l_int_param_row).maximum_rate);
5703         print_debug('	minimum_rate	 : ' || 	p_int_param_tbl(l_int_param_row).minimum_rate);
5704         print_debug('	rate_delay_code               	 : ' || 	p_int_param_tbl(l_int_param_row).rate_delay_code);
5705         print_debug('	rate_delay_frequency	 : ' || 	p_int_param_tbl(l_int_param_row).rate_delay_frequency);
5706         print_debug('	rate_change_start_date	 : ' || 	p_int_param_tbl(l_int_param_row).rate_change_start_date);
5707         print_debug('	rate_change_frequency_code    	 : ' || 	p_int_param_tbl(l_int_param_row).rate_change_frequency_code);
5708         print_debug('	rate_change_value	 : ' || 	p_int_param_tbl(l_int_param_row).rate_change_value);
5709         print_debug('	date_last_interim_interest_cal	 : ' || 	p_int_param_tbl(l_int_param_row).date_last_interim_interest_cal);
5710         print_debug('	contract_start_date	 : ' || 	p_int_param_tbl(l_int_param_row).contract_start_date);
5711         print_debug('	khr_id	 : ' || 	p_int_param_tbl(l_int_param_row).khr_id);
5712         print_debug('	interest_calculation_basis	 : ' || 	p_int_param_tbl(l_int_param_row).interest_calculation_basis);
5713         print_debug('	pay_freq	 : ' || 	p_int_param_tbl(l_int_param_row).pay_freq);
5714 
5715         l_int_param_row := p_int_param_tbl.next(l_int_param_row);
5716       END LOOP;
5717       print_debug('*****END CONTENTS OF P_INT_PARAM_TBL*****');
5718       print_debug('*****************************************');
5719 
5720       print_debug('*****START CONTENTS OF P_EFF_INT_TBL*****');
5721       l_eff_int_row := p_eff_int_tbl.first;
5722       l_out_str := rpad(' from_date', 14, ' ') || rpad('to_date', 15, ' ')
5723                      || rpad('rate', 15, ' ') || rpad('derived_flag', 15, ' ') || rpad('apply_tolerance', 15, ' ');
5724       print_debug(l_out_str);
5725       WHILE l_eff_int_row IS NOT NULL
5726       LOOP
5727         /*print_debug('	from_date : ' || p_eff_int_tbl(l_eff_int_row).from_date);
5728         print_debug('	to_date : ' || p_eff_int_tbl(l_eff_int_row).to_date);
5729         print_debug('	rate : ' || p_eff_int_tbl(l_eff_int_row).rate);
5730         print_debug('	derived_flag : ' || p_eff_int_tbl(l_eff_int_row).derived_flag);*/
5731         l_out_str := rpad(' ' ||  p_eff_int_tbl(l_eff_int_row).from_date, 14, ' ') ||
5732                      rpad( p_eff_int_tbl(l_eff_int_row).to_date, 15, ' ') ||
5733                      rpad(p_eff_int_tbl(l_eff_int_row).rate, 15, ' ') ||
5734                      rpad( p_eff_int_tbl(l_eff_int_row).derived_flag, 15, ' ') ||
5735                      rpad(p_eff_int_tbl(l_eff_int_row).apply_tolerance, 15, ' ');
5736 
5737         print_debug(l_out_str);
5738         l_eff_int_row := p_eff_int_tbl.next(l_eff_int_row);
5739       END LOOP;
5740       print_debug('******END CONTENTS OF P_EFF_INT_TBL******');
5741       print_debug('*****************************************');
5742 
5743 
5744     EXCEPTION
5745       WHEN OTHERS THEN
5746         print_debug('SQLCODE : ' || SQLCODE || ' SQLERRM : ' || SQLERRM);
5747     END print_table_content;
5748 
5749   BEGIN
5750 
5751     print_debug('in procedure interest_date_range');
5752     l_int_param_tbl.delete;
5753     l_param_tbl_row := 0;
5754 
5755     FOR cur_int_param IN c_int_param(p_rate_param_rowid) LOOP
5756       l_param_tbl_row := l_param_tbl_row + 1;
5757       l_int_param_tbl(l_param_tbl_row) := cur_int_param;
5758 
5759       FOR cur_pay_freq IN c_pay_freq(p_contract_id) LOOP
5760         l_int_param_tbl(l_param_tbl_row).pay_freq := cur_pay_freq.pay_freq;
5761         EXIT;
5762       END LOOP;
5763 
5764       l_interest_rate_tbl.delete;
5765       l_start_date := NVL(p_start_date, cur_int_param.contract_start_date);
5766       l_end_date := p_end_date;
5767 
5768       print_debug('cal start date : ' || l_start_date);
5769       print_debug('cal end   date : ' || l_end_date);
5770       print_debug('value of global variable okl_variable_interest_pvt.g_calc_method_code : ' || OKL_VARIABLE_INTEREST_PVT.G_CALC_METHOD_CODE);
5771 
5772       --check for interest start date
5773       print_debug('in procedure interest_date_range - check for interest start date');
5774       IF (cur_int_param.interest_start_date < l_start_date) THEN
5775         NULL;
5776       ELSE
5777         IF (cur_int_param.interest_start_date <= l_end_date) THEN
5778           l_start_date := cur_int_param.interest_start_date;
5779         ELSE
5780           RETURN;
5781         END IF;
5782       END IF;
5783 
5784       --check for date last interim interest calculated
5785       print_debug('in procedure interest_date_range - check for date last interim interest calculated');
5786       IF ((l_start_date <= cur_int_param.date_last_interim_interest_cal) AND
5787           (((cur_int_param.interest_calculation_basis = 'REAMORT') AND (OKL_VARIABLE_INTEREST_PVT.G_CALC_METHOD_CODE = 'REAMORT')) OR
5788            (cur_int_param.interest_calculation_basis <> 'REAMORT'))) THEN
5789           --check if the start date is before last int calc date and
5790           --if the proc is not called from the variable rate - initiate request
5791           --then derive the rates for the date range passed
5792           --else retrieve the previously derived rates
5793         IF (l_end_date <= cur_int_param.date_last_interim_interest_cal) THEN
5794           --get the interest rate for l_start_date to l_end_date from okl_var_int_params
5795           print_debug('in procedure interest_date_range - get the interest rate for l_start_date to l_end_date from okl_var_int_params');
5796           FOR cur_param_rate IN c_param_rate(p_contract_id, l_start_date, l_end_date, p_process_flag) LOOP
5797             l_int_tbl_row := l_int_tbl_row + 1;
5798             l_interest_rate_tbl(l_int_tbl_row).from_date := cur_param_rate.valid_from;
5799             l_interest_rate_tbl(l_int_tbl_row).to_date := cur_param_rate.valid_until;
5800             l_interest_rate_tbl(l_int_tbl_row).rate := cur_param_rate.value;
5801             l_interest_rate_tbl(l_int_tbl_row).derived_flag := 'N';
5802             l_interest_rate_tbl(l_int_tbl_row).apply_tolerance := 'N';
5803           END LOOP;
5804 
5805           print_table_content(l_int_param_tbl , l_interest_rate_tbl);
5806           l_derive_rate_flag := 'N';
5807         ELSE
5808           --get the interest rate for l_start_date to date last interim interest cal from okl_var_int_params
5809           print_debug('in procedure interest_date_range - get the interest rate for l_start_date to date last interim interest cal from okl_var_int_params');
5810           FOR cur_param_rate IN c_param_rate(p_contract_id, l_start_date, cur_int_param.date_last_interim_interest_cal, p_process_flag) LOOP
5811             l_int_tbl_row := l_int_tbl_row + 1;
5812             l_interest_rate_tbl(l_int_tbl_row).from_date := cur_param_rate.valid_from;
5813             l_interest_rate_tbl(l_int_tbl_row).to_date := cur_param_rate.valid_until;
5814             l_interest_rate_tbl(l_int_tbl_row).rate := cur_param_rate.value;
5815             l_interest_rate_tbl(l_int_tbl_row).derived_flag := 'N';
5816             l_interest_rate_tbl(l_int_tbl_row).apply_tolerance := 'N';
5817           END LOOP;
5818 
5819           print_table_content(l_int_param_tbl , l_interest_rate_tbl);
5820           l_start_date := cur_int_param.date_last_interim_interest_cal + 1;
5821           l_derive_rate_flag := 'Y';
5822         END IF;
5823       END IF;
5824 
5825       --no interest rate was available in the interest params table
5826       --therefore we need to derive the rates from the index
5827       print_debug('in procedure interest_date_range - no interest rate was available in the interest params table');
5828       print_debug('in procedure interest_date_range - therefore we need to derive the rates from the index');
5829       IF ((l_derive_rate_flag = 'N' AND NVL(l_interest_rate_tbl.count, 0) = 0) OR l_derive_rate_flag = 'Y') THEN
5830         --apply rate delay parameters to start date, end date, rate change start date
5831         print_debug('in procedure interest_date_range - apply rate delay parameters to start date, end date, rate change start date');
5832         l_rate_change_start_date := cur_int_param.rate_change_start_date;
5833 
5834         IF (cur_int_param.rate_delay_code = 'DAYS') THEN
5835           l_start_date := l_start_date - cur_int_param.rate_delay_frequency;
5836           l_end_date := l_end_date - cur_int_param.rate_delay_frequency;
5837           l_rate_change_start_date := l_rate_change_start_date - cur_int_param.rate_delay_frequency;
5838         ELSIF (cur_int_param.rate_delay_code = 'MONTHS') THEN
5839           l_start_date := add_months(l_start_date, -1 * cur_int_param.rate_delay_frequency);
5840           l_end_date := add_months(l_end_date, -1 * cur_int_param.rate_delay_frequency);
5841           l_rate_change_start_date := add_months(l_rate_change_start_date, -1 * cur_int_param.rate_delay_frequency);
5842         END IF;
5843 
5844         print_debug('in procedure interest_date_range - values after rate delay application');
5845         print_debug('in procedure interest_date_range - l_start_date: ' || l_start_date);
5846         print_debug('in procedure interest_date_range - l_end_date: ' || l_end_date);
5847         print_debug('in procedure interest_date_range - l_rate_change_start_date: ' || l_rate_change_start_date);
5848 
5849         --start dt LESS THAN RCSD
5850         print_debug('in procedure interest_date_range - start dt LESS THAN RCSD');
5851         IF (l_start_date <= l_rate_change_start_date) THEN
5852           --end dt LESS THAN RCSD
5853           print_debug('in procedure interest_date_range - end dt LESS THAN RCSD');
5854           IF(l_end_date < l_rate_change_start_date) THEN
5855             l_int_tbl_row := l_int_tbl_row + 1;
5856             l_interest_rate_tbl(l_int_tbl_row).from_date := l_start_date;
5857             l_interest_rate_tbl(l_int_tbl_row).to_date := l_end_date;
5858             l_interest_rate_tbl(l_int_tbl_row).rate := cur_int_param.base_rate;
5859             l_interest_rate_tbl(l_int_tbl_row).derived_flag := 'Y';
5860             l_interest_rate_tbl(l_int_tbl_row).apply_tolerance := 'N';
5861 
5862             print_table_content(l_int_param_tbl , l_interest_rate_tbl);
5863           ELSE
5864             --end dt NOT LESS THAN RCSD
5865             print_debug('in procedure interest_date_range - end dt NOT LESS THAN RCSD');
5866             IF (l_start_date < l_rate_change_start_date) THEN
5867               l_int_tbl_row := l_int_tbl_row + 1;
5868               l_interest_rate_tbl(l_int_tbl_row).from_date := l_start_date;
5869               l_interest_rate_tbl(l_int_tbl_row).to_date := l_rate_change_start_date - 1;
5870               l_interest_rate_tbl(l_int_tbl_row).rate := cur_int_param.base_rate;
5871               l_interest_rate_tbl(l_int_tbl_row).derived_flag := 'Y';
5872               l_interest_rate_tbl(l_int_tbl_row).apply_tolerance := 'N';
5873             END IF;
5874 
5875             --get daily rate if rate_change_frequency_code is Daily
5876             print_debug('in procedure interest_date_range - get daily rate if rate_change_frequency_code is Daily');
5877             IF (cur_int_param.rate_change_frequency_code = 'DAILY') THEN
5878               l_start_date := l_rate_change_start_date;
5879               print_debug('1 -> before calling get_eff_int_rate.');
5880               get_eff_int_rate(l_start_date, l_end_date, l_int_param_tbl , x_eff_int_tbl);
5881               l_eff_int_row := x_eff_int_tbl.first;
5882               WHILE (l_eff_int_row IS NOT NULL)
5883               LOOP
5884                 l_int_tbl_row := l_int_tbl_row + 1;
5885                 l_interest_rate_tbl(l_int_tbl_row).from_date := x_eff_int_tbl(l_eff_int_row).from_date;
5886                 l_interest_rate_tbl(l_int_tbl_row).to_date := x_eff_int_tbl(l_eff_int_row).to_date;
5887                 l_interest_rate_tbl(l_int_tbl_row).rate := x_eff_int_tbl(l_eff_int_row).rate;
5888                 l_interest_rate_tbl(l_int_tbl_row).derived_flag := x_eff_int_tbl(l_eff_int_row).derived_flag;
5889                 l_interest_rate_tbl(l_int_tbl_row).apply_tolerance := x_eff_int_tbl(l_eff_int_row).apply_tolerance;
5890                 l_eff_int_row := x_eff_int_tbl.next(l_eff_int_row);
5891               END LOOP;
5892               print_table_content(l_int_param_tbl , l_interest_rate_tbl);
5893             ELSE
5894               print_debug('in procedure interest_date_range - get the next rate change date');
5895               --get the next rate change date
5896               --and so on and so forth
5897               l_next_rate_change_date := get_next_rate_change_date(l_rate_change_start_date, l_int_param_tbl);
5898               print_debug('in procedure interest_date_range - l_next_rate_change_date : ' || l_next_rate_change_date);
5899               --end dt LESS THAN NRCSD
5900               /*IF (l_end_date < l_next_rate_change_date) THEN
5901                 get_eff_int_rate(l_rate_change_start_date, l_rate_change_start_date, l_int_param_tbl , x_eff_int_tbl);
5902                 l_eff_int_row := x_eff_int_tbl.first;
5903                 WHILE (l_eff_int_row IS NOT NULL)
5904                 LOOP
5905                   l_int_tbl_row := l_int_tbl_row + 1;
5906                   l_interest_rate_tbl(l_int_tbl_row).from_date := l_rate_change_start_date;
5907                   l_interest_rate_tbl(l_int_tbl_row).to_date := l_end_date;
5908                   l_interest_rate_tbl(l_int_tbl_row).rate := x_eff_int_tbl(l_eff_int_row).rate;
5909                   l_interest_rate_tbl(l_int_tbl_row).derived_flag := x_eff_int_tbl(l_eff_int_row).derived_flag;
5910                   l_eff_int_row := x_eff_int_tbl.next(l_eff_int_row);
5911                 END LOOP;
5912               ELSE*/
5913                 --end dt NOT LESS THAN NRCSD
5914                 print_debug('in procedure interest_date_range - end dt NOT LESS THAN NRCSD');
5915                 LOOP
5916                   print_debug('2 -> before calling get_eff_int_rate.');
5917                   get_eff_int_rate(l_rate_change_start_date, l_rate_change_start_date, l_int_param_tbl , x_eff_int_tbl);
5918                   l_eff_int_row := x_eff_int_tbl.first;
5919                   WHILE (l_eff_int_row IS NOT NULL)
5920                   LOOP
5921                     l_int_tbl_row := l_int_tbl_row + 1;
5922                     l_interest_rate_tbl(l_int_tbl_row).from_date := l_rate_change_start_date;
5923                     IF (l_end_date < l_next_rate_change_date) THEN
5924                       l_interest_rate_tbl(l_int_tbl_row).to_date := l_end_date;
5925                     ELSE
5926                       IF (l_next_rate_change_date IS NOT NULL) THEN
5927                         l_interest_rate_tbl(l_int_tbl_row).to_date := l_next_rate_change_date - 1;
5928                       ELSE
5929                         l_interest_rate_tbl(l_int_tbl_row).to_date := cur_int_param.contract_end_date;
5930                       END IF;
5931                     END IF;
5932                     l_interest_rate_tbl(l_int_tbl_row).rate := x_eff_int_tbl(l_eff_int_row).rate;
5933                     l_interest_rate_tbl(l_int_tbl_row).derived_flag := x_eff_int_tbl(l_eff_int_row).derived_flag;
5934                     l_interest_rate_tbl(l_int_tbl_row).apply_tolerance := x_eff_int_tbl(l_eff_int_row).apply_tolerance;
5935                     l_eff_int_row := x_eff_int_tbl.next(l_eff_int_row);
5936                   END LOOP;
5937 
5938                   EXIT WHEN ((l_end_date < l_next_rate_change_date) OR
5939                              (l_rate_change_start_date = cur_int_param.contract_end_date));
5940                   l_rate_change_start_date := l_next_rate_change_date;
5941                   l_next_rate_change_date := get_next_rate_change_date(l_rate_change_start_date, l_int_param_tbl);
5942                   print_debug('1 -> l_rate_change_start_date : ' || l_rate_change_start_date);
5943                   print_debug('1 -> l_next_rate_change_date : ' || l_next_rate_change_date);
5944                 END LOOP;
5945                 print_table_content(l_int_param_tbl , l_interest_rate_tbl);
5946               --END IF;
5947             END IF;
5948 
5949           END IF;
5950         ELSE
5951           --start dt NOT LESS THAN RCSD
5952           IF (cur_int_param.rate_change_frequency_code = 'DAILY') THEN
5953             --l_start_date := l_rate_change_start_date;
5954             print_debug('3 -> before calling get_eff_int_rate.');
5955             get_eff_int_rate(l_start_date, l_end_date, l_int_param_tbl , x_eff_int_tbl);
5956             l_eff_int_row := x_eff_int_tbl.first;
5957             WHILE (l_eff_int_row IS NOT NULL)
5958             LOOP
5959               l_int_tbl_row := l_int_tbl_row + 1;
5960               l_interest_rate_tbl(l_int_tbl_row).from_date := x_eff_int_tbl(l_eff_int_row).from_date;
5961               l_interest_rate_tbl(l_int_tbl_row).to_date := x_eff_int_tbl(l_eff_int_row).to_date;
5962               l_interest_rate_tbl(l_int_tbl_row).rate := x_eff_int_tbl(l_eff_int_row).rate;
5963               l_interest_rate_tbl(l_int_tbl_row).derived_flag := x_eff_int_tbl(l_eff_int_row).derived_flag;
5964               l_interest_rate_tbl(l_int_tbl_row).apply_tolerance := x_eff_int_tbl(l_eff_int_row).apply_tolerance;
5965               l_eff_int_row := x_eff_int_tbl.next(l_eff_int_row);
5966             END LOOP;
5967             print_table_content(l_int_param_tbl , l_interest_rate_tbl);
5968           ELSE
5969 
5970             print_table_content(l_int_param_tbl , l_interest_rate_tbl);
5971             print_debug('in procedure interest_date_range - start dt NOT LESS THAN RCSD');
5972             l_next_rate_change_date := get_next_rate_change_date(l_rate_change_start_date, l_int_param_tbl);
5973 
5974             LOOP
5975               print_debug('l_start_date : ' || l_start_date);
5976               print_debug('l_next_rate_change_date : ' || l_next_rate_change_date);
5977 
5978               EXIT WHEN ((l_start_date < l_next_rate_change_date) OR
5979                          (l_rate_change_start_date = cur_int_param.contract_end_date));
5980               l_rate_change_start_date := l_next_rate_change_date;
5981               l_next_rate_change_date := get_next_rate_change_date(l_rate_change_start_date, l_int_param_tbl);
5982             END LOOP;
5983 
5984             --end dt LESS THAN NRCSD
5985             print_debug('in procedure interest_date_range - end dt LESS THAN NRCSD');
5986             IF (l_end_date < l_next_rate_change_date) THEN
5987               print_debug('4 -> before calling get_eff_int_rate.');
5988               get_eff_int_rate(l_rate_change_start_date, l_rate_change_start_date, l_int_param_tbl , x_eff_int_tbl);
5989               l_eff_int_row := x_eff_int_tbl.first;
5990               WHILE (l_eff_int_row IS NOT NULL)
5991               LOOP
5992                 l_int_tbl_row := l_int_tbl_row + 1;
5993                 l_interest_rate_tbl(l_int_tbl_row).from_date := l_start_date;
5994                 l_interest_rate_tbl(l_int_tbl_row).to_date := l_end_date;
5995                 l_interest_rate_tbl(l_int_tbl_row).rate := x_eff_int_tbl(l_eff_int_row).rate;
5996                 l_interest_rate_tbl(l_int_tbl_row).derived_flag := x_eff_int_tbl(l_eff_int_row).derived_flag;
5997                 l_interest_rate_tbl(l_int_tbl_row).apply_tolerance := x_eff_int_tbl(l_eff_int_row).apply_tolerance;
5998                 l_eff_int_row := x_eff_int_tbl.next(l_eff_int_row);
5999               END LOOP;
6000               --end dt NOT LESS THAN NRCSD
6001               print_debug('in procedure interest_date_range - end dt NOT LESS THAN NRCSD');
6002               print_table_content(l_int_param_tbl , l_interest_rate_tbl);
6003             ELSE
6004               LOOP
6005                 print_debug('5 -> before calling get_eff_int_rate.');
6006                 get_eff_int_rate(l_rate_change_start_date, l_rate_change_start_date, l_int_param_tbl , x_eff_int_tbl);
6007                 l_eff_int_row := x_eff_int_tbl.first;
6008                 WHILE (l_eff_int_row IS NOT NULL)
6009                 LOOP
6010                   l_int_tbl_row := l_int_tbl_row + 1;
6011                   IF (l_start_date >= l_rate_change_start_date) THEN
6012                     l_interest_rate_tbl(l_int_tbl_row).from_date := l_start_date;
6013                   ELSE
6014                     l_interest_rate_tbl(l_int_tbl_row).from_date := l_rate_change_start_date;
6015                   END IF;
6016 
6017                   IF (l_end_date < NVL(l_next_rate_change_date, l_end_date)) THEN
6018                     l_interest_rate_tbl(l_int_tbl_row).to_date := l_end_date;
6019                   ELSE
6020                     IF (l_next_rate_change_date IS NOT NULL) THEN
6021                       l_interest_rate_tbl(l_int_tbl_row).to_date := l_next_rate_change_date - 1;
6022                     ELSE
6023                       l_interest_rate_tbl(l_int_tbl_row).to_date := cur_int_param.contract_end_date;
6024                     END IF;
6025                   END IF;
6026                   l_interest_rate_tbl(l_int_tbl_row).rate := x_eff_int_tbl(l_eff_int_row).rate;
6027                   l_interest_rate_tbl(l_int_tbl_row).derived_flag := x_eff_int_tbl(l_eff_int_row).derived_flag;
6028                   l_interest_rate_tbl(l_int_tbl_row).apply_tolerance := x_eff_int_tbl(l_eff_int_row).apply_tolerance;
6029                   l_eff_int_row := x_eff_int_tbl.next(l_eff_int_row);
6030                 END LOOP;
6031 
6032                 EXIT WHEN ((l_end_date < l_next_rate_change_date) OR
6033                             (l_rate_change_start_date = cur_int_param.contract_end_date));
6034                 l_rate_change_start_date := l_next_rate_change_date;
6035                 l_next_rate_change_date := get_next_rate_change_date(l_rate_change_start_date, l_int_param_tbl);
6036                 print_debug('2 -> l_rate_change_start_date : ' || l_rate_change_start_date);
6037                 print_debug('2 -> l_next_rate_change_date : ' || l_next_rate_change_date);
6038               END LOOP;
6039               print_table_content(l_int_param_tbl , l_interest_rate_tbl);
6040             END IF;
6041           END IF;--here
6042         END IF;
6043       END IF;
6044 
6045     END LOOP;
6046 
6047     --unapply rate delay
6048     print_debug('in procedure interest_date_range - unapply rate delay');
6049     l_param_tbl_row := l_int_param_tbl.first;
6050     l_int_tbl_row := l_interest_rate_tbl.first;
6051     WHILE l_int_tbl_row IS NOT NULL
6052     LOOP
6053       IF (l_interest_rate_tbl(l_int_tbl_row).derived_flag = 'Y') THEN
6054         IF (l_int_param_tbl(l_param_tbl_row).rate_delay_code = 'DAYS') THEN
6055           l_interest_rate_tbl(l_int_tbl_row).from_date  := l_interest_rate_tbl(l_int_tbl_row).from_date + l_int_param_tbl(l_param_tbl_row).rate_delay_frequency;
6056           l_interest_rate_tbl(l_int_tbl_row).to_date := l_interest_rate_tbl(l_int_tbl_row).to_date + l_int_param_tbl(l_param_tbl_row).rate_delay_frequency;
6057         ELSIF (l_int_param_tbl(l_param_tbl_row).rate_delay_code = 'MONTHS') THEN
6058           l_interest_rate_tbl(l_int_tbl_row).from_date := add_months(l_interest_rate_tbl(l_int_tbl_row).from_date, l_int_param_tbl(l_param_tbl_row).rate_delay_frequency);
6059           l_interest_rate_tbl(l_int_tbl_row).to_date := add_months(l_interest_rate_tbl(l_int_tbl_row).to_date, l_int_param_tbl(l_param_tbl_row).rate_delay_frequency);
6060         END IF;
6061       END IF;
6062       l_int_tbl_row := l_interest_rate_tbl.next(l_int_tbl_row);
6063     END LOOP;
6064     print_table_content(l_int_param_tbl , l_interest_rate_tbl);
6065 
6066     --apply tolerance
6067     print_debug('in procedure interest_date_range - apply tolerance');
6068     apply_tolerance(l_int_param_tbl, l_interest_rate_tbl, x_interest_rate_tbl);
6069     print_table_content(l_int_param_tbl , x_interest_rate_tbl);
6070 
6071     print_debug('exiting procedure interest_date_range');
6072     x_return_status := l_return_status;
6073   Exception
6074    	WHEN OTHERS THEN
6075       print_debug('sqlcode : ' || sqlcode || ' $ sqlerrm : ' || sqlerrm);
6076    		x_return_status := OKL_API.HANDLE_EXCEPTIONS (
6077     					p_api_name	=> l_api_name,
6078     					p_pkg_name	=> G_PKG_NAME,
6079     					p_exc_name	=> 'OTHERS',
6080     					x_msg_count	=> x_msg_count,
6081     					x_msg_data	=> x_msg_data,
6082     					p_api_type	=> '_PVT');
6083 
6084   END interest_date_range;
6085 
6086   ------------------------------------------------------------------------------
6087 
6088   PROCEDURE interest_date_range (
6089             p_api_version        IN  NUMBER,
6090             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
6091             x_return_status      OUT NOCOPY VARCHAR2,
6092             x_msg_count          OUT NOCOPY NUMBER,
6093             x_msg_data           OUT NOCOPY VARCHAR2,
6094             p_contract_id        IN  NUMBER,
6095             p_start_date         IN  DATE,
6096             p_end_date           IN  DATE,
6097             p_process_flag       IN  VARCHAR2 ,
6098             x_interest_rate_tbl OUT NOCOPY interest_rate_tbl_type)   IS
6099 
6100     -----------------------------------------------------------------
6101     -- Declare Process Variable
6102     -----------------------------------------------------------------
6103     l_api_name	        CONSTANT VARCHAR2(30)   := 'interest_date_range';
6104     l_return_status	VARCHAR2(1)             := OKL_API.G_RET_STS_SUCCESS;
6105 
6106     l_interest_rate_tbl interest_rate_tbl_type;
6107     l_interest_rate_tbl_out interest_rate_tbl_type;
6108     l_int_tbl_row       NUMBER := 0;
6109     l_int_tbl_row_out   NUMBER := 0;
6110 
6111     CURSOR c_param_rate(cp_khr_id NUMBER, cp_start_date DATE, cp_end_date DATE) IS
6112     SELECT krp.rowid rate_param_rowid,
6113            GREATEST(trunc(cp_start_date),krp.effective_from_date) start_date,
6114            LEAST(trunc(cp_end_date),NVL(krp.effective_to_date, trunc(sysdate + 9999))) end_date
6115     FROM  okl_k_rate_params krp
6116     WHERE krp.khr_id = cp_khr_id
6117     AND   krp.parameter_type_code = 'ACTUAL'
6118     AND   (cp_start_date BETWEEN krp.effective_from_date AND nvl(krp.effective_to_date, trunc(cp_start_date))
6119            OR    (cp_end_date BETWEEN krp.effective_from_date AND nvl(krp.effective_to_date, trunc(cp_end_date)))
6120            OR    (krp.effective_from_date >= cp_start_date AND nvl(krp.effective_to_date, trunc(sysdate + 9999)) <= cp_end_date));
6121 
6122   BEGIN
6123     print_debug('entering procedure interest_date_range outer with the foll. parameters:-');
6124     print_debug('p_contract_id: ' || p_contract_id);
6125     print_debug('p_start_date: ' || p_start_date);
6126     print_debug('p_end_date: ' || p_end_date);
6127     print_debug('p_process_flag: ' || p_process_flag);
6128 
6129     l_interest_rate_tbl.delete;
6130     l_interest_rate_tbl_out.delete;
6131     l_int_tbl_row_out := 0;
6132 
6133     FOR cur_param_rate IN c_param_rate(p_contract_id, p_start_date, p_end_date) LOOP
6134       print_debug('calling procedure interest_date_range inner with foll. params:-');
6135       print_debug('p_contract_id: ' || p_contract_id);
6136       print_debug('start_date: ' || cur_param_rate.start_date);
6137       print_debug('end_date: ' || cur_param_rate.end_date);
6138       print_debug('rate_param_rowid: ' || cur_param_rate.rate_param_rowid);
6139       interest_date_range (
6140               p_api_version       => 1.0,
6141               p_init_msg_list     => OKL_API.G_FALSE,
6142               x_return_status     => x_return_status,
6143               x_msg_count         => x_msg_count,
6144               x_msg_data          => x_msg_data,
6145               p_contract_id       => p_contract_id,
6146               p_start_date        => cur_param_rate.start_date,
6147               p_end_date          => cur_param_rate.end_date,
6148               p_process_flag      => p_process_flag,
6149               p_rate_param_rowid  => cur_param_rate.rate_param_rowid,
6150               x_interest_rate_tbl => l_interest_rate_tbl);
6151 
6152       IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
6153         print_error_message('Unexpected error raised in call to INTEREST_DATE_RANGE');
6154         RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
6155       ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
6156         print_error_message('Error raised in call to INTEREST_DATE_RANGE');
6157         RAISE Okl_Api.G_EXCEPTION_ERROR;
6158       END IF;
6159 
6160       print_debug('count in l_interest_rate_tbl: ' || l_interest_rate_tbl.count);
6161       l_int_tbl_row := l_interest_rate_tbl.first;
6162       LOOP
6163         EXIT WHEN l_int_tbl_row IS NULL;
6164         l_int_tbl_row_out := l_int_tbl_row_out + 1;
6165         l_interest_rate_tbl_out(l_int_tbl_row_out) := l_interest_rate_tbl(l_int_tbl_row);
6166 
6167         l_int_tbl_row := l_interest_rate_tbl.next(l_int_tbl_row);
6168       END LOOP;
6169       print_debug('count in l_interest_rate_tbl_out: ' || l_interest_rate_tbl_out.count);
6170     END LOOP;
6171 
6172     x_interest_rate_tbl := l_interest_rate_tbl_out;
6173     x_return_status := l_return_status;
6174     print_debug('exiting procedure interest_date_range outer');
6175   Exception
6176    	WHEN OTHERS THEN
6177       print_debug('sqlcode : ' || sqlcode || ' $ sqlerrm : ' || sqlerrm);
6178    		x_return_status := OKL_API.HANDLE_EXCEPTIONS (
6179     					p_api_name	=> l_api_name,
6180     					p_pkg_name	=> G_PKG_NAME,
6181     					p_exc_name	=> 'OTHERS',
6182     					x_msg_count	=> x_msg_count,
6183     					x_msg_data	=> x_msg_data,
6184     					p_api_type	=> '_PVT');
6185 
6186   END interest_date_range;
6187 
6188   ------------------------------------------------------------------------------
6189     -- Start of Comments
6190     -- Created By:       Ramesh Seela
6191     -- Procedure Name    calculate_interest
6192     -- Description:      This procedure is called by Variable Interest Calculation for Loans
6193     --                   Inputs :
6194     --                   Output : Interest Calculated
6195     -- Dependencies:
6196     -- Parameters:       Start Date, End Date, Interest Rate Range.
6197     -- Version:          1.0
6198     -- End of Comments
6199 
6200   ------------------------------------------------------------------------------
6201   Function  calculate_interest (
6202             p_api_version        IN  NUMBER,
6203             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
6204             x_return_status      OUT NOCOPY VARCHAR2,
6205             x_msg_count          OUT NOCOPY NUMBER,
6206             x_msg_data           OUT NOCOPY VARCHAR2,
6207             p_contract_id        IN  NUMBER,
6208             p_from_date          IN  DATE,
6209             p_to_date            IN  DATE,
6210             p_principal_amount   IN  NUMBER,
6211             p_currency_code      IN  VARCHAR2) RETURN NUMBER  IS
6212 
6213   l_api_name                  CONSTANT    VARCHAR2(30) := 'CALCULATE_INTEREST';
6214   l_api_version               CONSTANT    NUMBER       := 1.0;
6215   l_interest_rate_tbl         interest_rate_tbl_type;
6216   l_interest_rate_tbl_count   NUMBER;
6217   l_interest_rate_tbl_counter NUMBER;
6218   l_interest_rate_tbl_index   NUMBER;
6219   l_return_status             VARCHAR2(1) := OKC_API.G_RET_STS_SUCCESS;
6220   l_msg_count                 NUMBER;
6221   l_msg_data                  VARCHAR2(2000);
6222   l_from_date                 DATE;
6223   l_to_date                   DATE;
6224   l_interest_rate             NUMBER;
6225   l_calc_days                 NUMBER;
6226   l_year_days                 NUMBER;
6227   l_interest_amt              NUMBER := 0;
6228   l_total_interest_amt        NUMBER := 0;
6229   l_year_part                 NUMBER;
6230   l_interest_basis            OKL_K_RATE_PARAMS.interest_basis_code%TYPE;
6231   l_calculation_formula_id    OKL_K_RATE_PARAMS.calculation_formula_id%TYPE;
6232   l_derived_flag              VARCHAR2(1);
6233   calculate_interest_failed   EXCEPTION;
6234 
6235 
6236   BEGIN
6237     x_return_status     := OKL_API.G_RET_STS_SUCCESS;
6238 
6239     print_debug('Executing procedure CALCULATE_INTEREST using following parameters : ');
6240     print_debug(' p_contract_id : '|| p_contract_id );
6241 	print_debug(' p_from_date : '|| to_char(p_from_date));
6242 	print_debug(' p_to_date : '|| to_char(p_to_date));
6243 	print_debug(' p_principal_amount: '|| p_principal_amount);
6244 	print_debug(' p_currency_code : '|| p_currency_code);
6245 
6246     print_debug(' g_contract_id : '|| G_CONTRACT_ID );
6247 
6248 	Initialize_contract_params( p_api_version   => 1.0,
6249                                 p_init_msg_list => OKL_API.G_FALSE,
6250                                 x_return_status => x_return_status,
6251                                 x_msg_count     => x_msg_count,
6252                                 x_msg_data      => x_msg_data,
6253                                 p_contract_id   => p_contract_id
6254                               );
6255     IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
6256 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS completed successfully');
6257     ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
6258   	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
6259   	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
6260        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
6261     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
6262 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
6263 	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
6264        RAISE calculate_interest_failed;
6265     END IF;
6266 
6267 
6268     print_debug('Days in a month: '|| G_DAYS_IN_A_MONTH_CODE);
6269 	print_debug('Days in a year: '|| G_DAYS_IN_A_YEAR_CODE);
6270 
6271      /* start prasjain bug#5645266
6272              Added the check condition as the interest is getting calculated for
6273              31 days if the interest rate changes on 31st of the month in a 30/360
6274              contract
6275         */
6276        IF G_DAYS_IN_A_MONTH_CODE = '30' AND to_char(p_to_date,'DD') = '31'
6277        THEN
6278     interest_date_range (
6279             p_api_version       => 1.0,
6280             p_init_msg_list     => OKL_API.G_FALSE,
6281             x_return_status     => x_return_status,
6282             x_msg_count         => x_msg_count,
6283             x_msg_data          => x_msg_data,
6284             p_contract_id       => p_contract_id,
6285             p_start_date        => p_from_date,
6286             p_end_date          => p_to_date-1, /* pass the end date as 30 of the month */
6287             p_process_flag      => G_INTEREST_CALCULATION_BASIS, /* value is set in Calculate_total_interest_due */
6288             x_interest_rate_tbl => l_interest_rate_tbl);
6289 ELSE
6290            interest_date_range (
6291                p_api_version       => 1.0,
6292                p_init_msg_list     => OKL_API.G_FALSE,
6293                x_return_status     => x_return_status,
6294                x_msg_count         => x_msg_count,
6295                x_msg_data          => x_msg_data,
6296                p_contract_id       => p_contract_id,
6297                p_start_date        => p_from_date,
6298                p_end_date          => p_to_date, /* if not 31 pass the actual date */
6299                p_process_flag      => G_INTEREST_CALCULATION_BASIS, /* value is set in Calculate_total_interest_due */
6300                x_interest_rate_tbl => l_interest_rate_tbl);
6301       END IF;
6302 
6303       -- end prasjain bug#5645266
6304 
6305 
6306 
6307 
6308 
6309 
6310 
6311 
6312     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
6313       print_error_message('Unexpected error raised in call to INTEREST_DATE_RANGE');
6314       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
6315     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
6316       print_error_message('Error raised in call to INTEREST_DATE_RANGE');
6317       RAISE calculate_interest_failed;
6318     END IF;
6319 
6320     l_interest_rate_tbl_count := l_interest_rate_tbl.COUNT;
6321 
6322     print_debug('No. of records in Interest Date Range TAble : '|| l_interest_rate_tbl_count);
6323 
6324     IF (l_interest_rate_tbl_count = 0) THEN
6325        RETURN 0;
6326     END IF;
6327     l_interest_rate_tbl_index := l_interest_rate_tbl.FIRST;
6328 
6329     FOR l_interest_rate_tbl_counter in 1 .. l_interest_rate_tbl_count
6330     LOOP
6331        l_from_date     := l_interest_rate_tbl(l_interest_rate_tbl_index).from_date;
6332        l_to_date       := l_interest_rate_tbl(l_interest_rate_tbl_index).to_date;
6333        l_interest_rate := l_interest_rate_tbl(l_interest_rate_tbl_index).rate;
6334        l_derived_flag  := l_interest_rate_tbl(l_interest_rate_tbl_index).derived_flag;
6335 
6336        print_debug('From Date: '|| l_from_date ||' To Date: '|| l_to_date||' Interest: '|| l_interest_rate || 'Derived flag: '|| l_derived_flag);
6337 
6338        IF (G_DAYS_IN_A_MONTH_CODE = '30') THEN
6339           -- gboomina modified for bug 7130132 - Start
6340           -- using correct day count logic from OKL_PRICING_UTILS_PVT
6341           l_calc_days := OKL_PRICING_UTILS_PVT.get_day_count( G_DAYS_IN_A_MONTH_CODE,
6342                                                               G_DAYS_IN_A_YEAR_CODE,
6343                                                               l_from_date,
6344                                                               l_to_date,
6345                                                               'Y',
6346                                                               x_return_status);
6347           -- gboomina modified for bug 7130132 - End
6348        ELSE
6349           l_calc_days := l_to_date - l_from_date + 1;
6350        END IF;
6351 
6352        print_debug('No. of calc Days : '|| l_calc_days);
6353 
6354        IF (G_DAYS_IN_A_YEAR_CODE = 'ACTUAL') THEN
6355           l_year_part := to_char(l_from_date, 'YYYY');
6356           l_year_days := (to_date(('01-01-'||(l_year_part+1)),'DD-MM-YYYY') - to_date(('01-01-'||l_year_part),
6357 'DD-MM-YYYY'));
6358        ELSE
6359           l_year_days := G_DAYS_IN_A_YEAR_CODE;
6360        END IF;
6361 
6362        print_debug('No. of Days in the year: '|| l_year_days);
6363 
6364        l_interest_amt            := OKL_ACCOUNTING_UTIL.round_amount((p_principal_amount * l_interest_rate/100) * (
6365 l_calc_days / l_year_days), p_currency_code);
6366 
6367        print_debug(' Interest : '|| l_interest_amt);
6368        l_total_interest_amt      := l_total_interest_amt + l_interest_amt;
6369        l_interest_rate_tbl_index := l_interest_rate_tbl.NEXT(l_interest_rate_tbl_index);
6370 
6371        print_debug ('g_request_id : '|| g_request_id);
6372        print_debug ('Concurrent Request ID : '|| fnd_global.conc_request_id);
6373        print_debug ('l_derived_flag : '|| l_derived_flag);
6374 
6375        IF ((g_request_id > 0) AND (l_derived_flag = 'Y'))THEN
6376            g_vir_tbl_counter                                     := nvl(g_vir_tbl_counter,0) + 1;
6377            g_vir_tbl(g_vir_tbl_counter).id                       := okc_p_util.raw_to_number(sys_guid());
6378            g_vir_tbl(g_vir_tbl_counter).khr_id                   := p_contract_id;
6379            IF (G_CALC_METHOD_CODE = 'DAILY_INTEREST') THEN
6380              g_vir_tbl(g_vir_tbl_counter).source_table           := 'OKL_STRM_ELEMENTS_B';
6381            ELSIF (G_CALC_METHOD_CODE = 'REAMORT') THEN
6382              g_vir_tbl(g_vir_tbl_counter).source_table           := 'OKL_VAR_INT_PROCESS_B';
6383            ELSE
6384              g_vir_tbl(g_vir_tbl_counter).source_table           := 'OKL_TRX_AR_INVOICES_V';
6385            END IF;
6386            g_vir_tbl(g_vir_tbl_counter).interest_rate            := l_interest_rate;
6387            g_vir_tbl(g_vir_tbl_counter).interest_calc_start_date := l_from_date;
6388            g_vir_tbl(g_vir_tbl_counter).interest_calc_end_date   := l_to_date;
6389            g_vir_tbl(g_vir_tbl_counter).calc_method_code         := G_CALC_METHOD_CODE;
6390            g_vir_tbl(g_vir_tbl_counter).principal_balance        := p_principal_amount;
6391            g_vir_tbl(g_vir_tbl_counter).valid_yn                 := 'Y';
6392            g_vir_tbl(g_vir_tbl_counter).object_version_number    := 1.0;
6393            g_vir_tbl(g_vir_tbl_counter).org_id                   := g_authoring_org_id;
6394            g_vir_tbl(g_vir_tbl_counter).request_id               := g_request_id;
6395            g_vir_tbl(g_vir_tbl_counter).program_application_id   := NULL;
6396            g_vir_tbl(g_vir_tbl_counter).program_id               := NULL;
6397            g_vir_tbl(g_vir_tbl_counter).program_update_date      := SYSDATE;
6398            g_vir_tbl(g_vir_tbl_counter).attribute_category       := NULL;
6399            g_vir_tbl(g_vir_tbl_counter).attribute1               := NULL;
6400            g_vir_tbl(g_vir_tbl_counter).attribute2               := NULL;
6401            g_vir_tbl(g_vir_tbl_counter).attribute3               := NULL;
6402            g_vir_tbl(g_vir_tbl_counter).attribute4               := NULL;
6403            g_vir_tbl(g_vir_tbl_counter).attribute5               := NULL;
6404            g_vir_tbl(g_vir_tbl_counter).attribute6               := NULL;
6405            g_vir_tbl(g_vir_tbl_counter).attribute7               := NULL;
6406            g_vir_tbl(g_vir_tbl_counter).attribute8               := NULL;
6407            g_vir_tbl(g_vir_tbl_counter).attribute9               := NULL;
6408            g_vir_tbl(g_vir_tbl_counter).attribute10              := NULL;
6409            g_vir_tbl(g_vir_tbl_counter).attribute11              := NULL;
6410            g_vir_tbl(g_vir_tbl_counter).attribute12              := NULL;
6411            g_vir_tbl(g_vir_tbl_counter).attribute13              := NULL;
6412            g_vir_tbl(g_vir_tbl_counter).attribute14              := NULL;
6413            g_vir_tbl(g_vir_tbl_counter).attribute15              := NULL;
6414            g_vir_tbl(g_vir_tbl_counter).created_by               := FND_GLOBAL.user_id;
6415            g_vir_tbl(g_vir_tbl_counter).creation_date            := SYSDATE;
6416            g_vir_tbl(g_vir_tbl_counter).last_updated_by          := FND_GLOBAL.user_id;
6417            g_vir_tbl(g_vir_tbl_counter).last_update_date         := SYSDATE;
6418            g_vir_tbl(g_vir_tbl_counter).last_update_login        := FND_GLOBAL.login_id;
6419            g_vir_tbl(g_vir_tbl_counter).interest_amt             := l_interest_amt;
6420            g_vir_tbl(g_vir_tbl_counter).interest_calc_days       := l_calc_days;
6421        END IF;
6422     END LOOP;
6423 
6424     print_debug ('Total interest amount : '|| l_total_interest_amt);
6425 
6426     RETURN l_total_interest_amt;
6427 
6428   EXCEPTION
6429      WHEN calculate_interest_failed THEN
6430       print_error_message('Exception calculate_interest_failed raised in function CALCULATE_INTEREST');
6431       x_return_status := OKL_API.G_RET_STS_ERROR;
6432       RETURN NULL;
6433      WHEN OTHERS THEN
6434       print_error_message('Exception raised in function CALCULATE_INTEREST');
6435        Okl_Api.SET_MESSAGE(
6436                p_app_name     => G_APP_NAME,
6437                p_msg_name     => G_UNEXPECTED_ERROR,
6438                p_token1       => G_SQLCODE_TOKEN,
6439                p_token1_value => SQLCODE,
6440                p_token2       => G_SQLERRM_TOKEN,
6441                p_token2_value => SQLERRM);
6442           x_return_status := OKL_API.G_RET_STS_ERROR;
6443           RETURN NULL;
6444 
6445   END calculate_interest;
6446 
6447 ------------------------------------------------------------------------------
6448 
6449     -- Start of Comments
6450     -- Created By:       Ramesh Seela
6451     -- Procedure Name    Calc_Variable_Rate_Interest
6452     -- Description:      This procedure is called by Variable Interest Calculation for Loans
6453     -- Inputs :
6454     -- Output : Interest Calculated
6455     -- Dependencies:
6456     -- Parameters:       Start Date, End Date, Interest Rate Range.
6457     -- Version:          1.0
6458     -- End of Comments
6459 
6460   ------------------------------------------------------------------------------
6461   Function  Calc_Variable_Rate_Interest (
6462             p_api_version        IN  NUMBER,
6463             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
6464             x_return_status      OUT NOCOPY VARCHAR2,
6465             x_msg_count          OUT NOCOPY NUMBER,
6466             x_msg_data           OUT NOCOPY VARCHAR2,
6467             p_contract_id        IN  NUMBER,
6468             p_currency_code      IN  VARCHAR2,
6469             p_principal_balance_tbl IN  principal_balance_tbl_typ) RETURN NUMBER  IS
6470 
6471   l_api_name                  CONSTANT    VARCHAR2(30) := 'CALC_VARIABLE_RATE_INTEREST';
6472   l_api_version               CONSTANT    NUMBER       := 1.0;
6473   l_principal_balance_tbl     principal_balance_tbl_typ;
6474   l_principal_bal_tbl_count   NUMBER;
6475   l_principal_bal_tbl_counter NUMBER;
6476   l_principal_bal_tbl_index   NUMBER;
6477   l_return_status             VARCHAR2(1) := OKC_API.G_RET_STS_SUCCESS;
6478   l_msg_count                 NUMBER;
6479   l_msg_data                  VARCHAR2(2000);
6480   l_from_date                 DATE;
6481   l_to_date                   DATE;
6482   l_interest_amt              NUMBER := 0;
6483   l_total_interest_amt        NUMBER := 0;
6484   Calc_Var_Rate_Int_failed    EXCEPTION;
6485 
6486   BEGIN
6487     print_debug('Executing function CALC_VARIABLE_RATE_INTEREST using following parameters : ');
6488     print_debug('p_contract_id : '|| p_contract_id );
6489 	print_debug('p_currency_code : '|| p_currency_code);
6490 
6491     x_return_status               := OKL_API.G_RET_STS_SUCCESS;
6492     l_principal_balance_tbl       := p_principal_balance_tbl;
6493     l_principal_bal_tbl_count     := l_principal_balance_tbl.COUNT;
6494 
6495     print_debug ('No. of records in Principal balance table: '|| l_principal_bal_tbl_count);
6496     IF (l_principal_bal_tbl_count = 0) THEN
6497        RETURN 0;
6498     END IF;
6499     l_principal_bal_tbl_index := l_principal_balance_tbl.FIRST;
6500 
6501     FOR l_principal_bal_tbl_counter in 1 .. l_principal_bal_tbl_count
6502     LOOP
6503        l_from_date := l_principal_balance_tbl(l_principal_bal_tbl_index).from_date;
6504        l_to_date   := l_principal_balance_tbl(l_principal_bal_tbl_index).to_date;
6505 
6506        IF (l_principal_balance_tbl(l_principal_bal_tbl_index).principal_balance > 0) THEN
6507          l_interest_amt := calculate_interest (
6508                                                p_api_version       => 1.0,
6509                                                p_init_msg_list     => OKL_API.G_FALSE,
6510                                                x_return_status     => x_return_status,
6511                                                x_msg_count         => x_msg_count,
6512                                                x_msg_data          => x_msg_data,
6513                                                p_contract_id       => p_contract_id,
6514                                                p_from_date         => l_from_date,
6515                                                p_to_date           => l_to_date,
6516                                                p_principal_amount  => l_principal_balance_tbl(l_principal_bal_tbl_index).principal_balance,
6517                                                p_currency_code     => p_currency_code);
6518 
6519          IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
6520            print_error_message('Unexpected error raised in call to CALCULATE_INTEREST');
6521            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
6522          ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
6523            print_error_message('Error raised in call to CALCULATE_INTEREST');
6524            RAISE Calc_Var_Rate_Int_failed;
6525          END IF;
6526        ELSE
6527 	     l_interest_amt := 0;
6528 	   END IF;
6529 
6530        l_total_interest_amt := l_total_interest_amt + l_interest_amt;
6531        l_principal_bal_tbl_index := l_principal_balance_tbl.NEXT(l_principal_bal_tbl_index);
6532 
6533     END LOOP;
6534     print_debug('Total Interest Amount: '|| l_total_interest_amt);
6535 
6536     RETURN l_total_interest_amt;
6537 
6538   EXCEPTION
6539     WHEN Calc_Var_Rate_Int_failed THEN
6540       print_error_message('Exception Calc_Var_Rate_Int_failed raised in function CALC_VARIABLE_RATE_INTEREST');
6541       x_return_status := OKL_API.G_RET_STS_ERROR;
6542       RETURN NULL;
6543 
6544     WHEN OTHERS THEN
6545       print_error_message('Exception raised in function CALC_VARIABLE_RATE_INTEREST');
6546       Okl_Api.SET_MESSAGE(
6547               p_app_name     => G_APP_NAME,
6548               p_msg_name     => G_UNEXPECTED_ERROR,
6549               p_token1       => G_SQLCODE_TOKEN,
6550               p_token1_value => SQLCODE,
6551               p_token2       => G_SQLERRM_TOKEN,
6552               p_token2_value => SQLERRM);
6553       x_return_status := OKL_API.G_RET_STS_ERROR;
6554       RETURN NULL;
6555 
6556 
6557   END Calc_Variable_Rate_Interest;
6558 
6559 ------------------------------------------------------------------------------
6560 
6561     -- Start of Comments
6562     -- Created By:       Ramesh Seela
6563     -- Procedure Name    Create_Stream_Invoice
6564     -- Description:      This procedure is called by Variable Interest Calculation for Loans
6565     --                   Inputs :
6566     --                   Output :
6567     -- Dependencies:
6568     -- Parameters:
6569     -- Version:          1.0
6570     -- End of Comments
6571 
6572   ------------------------------------------------------------------------------
6573   Procedure Create_Stream_Invoice (
6574             p_api_version             IN  NUMBER,
6575             p_init_msg_list           IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
6576             x_return_status           OUT NOCOPY VARCHAR2,
6577             x_msg_count               OUT NOCOPY NUMBER,
6578             x_msg_data                OUT NOCOPY VARCHAR2,
6579             p_contract_id             IN  NUMBER,
6580             p_line_id                 IN  NUMBER DEFAULT NULL,
6581             p_amount                  IN  NUMBER,
6582             p_due_date                IN  DATE,
6583             p_stream_type_purpose     IN  VARCHAR2,
6584             p_create_invoice_flag     IN  VARCHAR2 DEFAULT OKL_API.G_TRUE,
6585  	        p_process_flag            IN  VARCHAR2 DEFAULT NULL,
6586  	        p_parent_strm_element_id  IN  NUMBER DEFAULT NULL,
6587 	        x_invoice_id              OUT NOCOPY NUMBER,
6588 			x_stream_element_id       OUT NOCOPY NUMBER) IS
6589 
6590   l_api_name                   CONSTANT    VARCHAR2(30) := 'CREATE_STREAM_INVOICE';
6591   l_api_version                CONSTANT    NUMBER       := 1.0;
6592   l_return_status              VARCHAR2(1) := OKC_API.G_RET_STS_SUCCESS;
6593   l_msg_count                  NUMBER;
6594   l_msg_data                   VARCHAR2(2000);
6595   l_sty_id                     OKL_STRM_TYPE_V.id%TYPE;
6596   l_stream_exists              VARCHAR2(1) := '?';
6597   l_stmv_rec                   Okl_Streams_Pub.stmv_rec_type;
6598   lx_stmv_rec                  Okl_Streams_Pub.stmv_rec_type;
6599   l_selv_rec                   Okl_Streams_Pub.selv_rec_type;
6600   lx_selv_rec                  Okl_Streams_Pub.selv_rec_type;
6601   i_taiv_rec                   Okl_Trx_Ar_Invoices_Pub.taiv_rec_type;
6602   r_taiv_rec                   Okl_Trx_Ar_Invoices_Pub.taiv_rec_type;
6603   l_def_desc                   CONSTANT VARCHAR2(80) := 'Variable Interest Stream Billing';
6604   l_final_status               CONSTANT VARCHAR2(30) := 'SUBMITTED';
6605 --  l_trx_type_name              CONSTANT VARCHAR2(30)	:= 'Billing';
6606   l_date_entered               CONSTANT DATE := SYSDATE;
6607 --  l_trx_type_id                NUMBER;
6608   l_line_code                  CONSTANT VARCHAR2(30)    := 'LINE';
6609 
6610 -- Begin - Billing Inline changes - Bug#5898792 - varangan - 28/2/2007
6611  /* i_tilv_rec                   Okl_Txl_Ar_Inv_Lns_Pub.tilv_rec_type;
6612   r_tilv_rec                   Okl_Txl_Ar_Inv_Lns_Pub.tilv_rec_type;
6613   i_tldv_rec                   Okl_Txd_Ar_Ln_Dtls_Pub.tldv_rec_type;
6614   r_tldv_rec                   Okl_Txd_Ar_Ln_Dtls_Pub.tldv_rec_type; */
6615 
6616   -----------------------------------------------------------
6617  -- Variables for billing API call
6618  -----------------------------------------------------------
6619     lp_taiv_rec        okl_tai_pvt.taiv_rec_type;
6620     lp_tilv_rec	       okl_til_pvt.tilv_rec_type;
6621     lp_tilv_tbl        okl_til_pvt.tilv_tbl_type;
6622     lp_tldv_rec        okl_tld_pvt.tldv_rec_type;
6623     lp_tldv_tbl        okl_tld_pvt.tldv_tbl_type;
6624 
6625     lx_taiv_rec        okl_tai_pvt.taiv_rec_type;
6626     lx_tilv_tbl        okl_til_pvt.tilv_tbl_type;
6627     lx_tldv_tbl        okl_tld_pvt.tldv_tbl_type;
6628 -- End - Billing Inline changes - Bug#5898792 - varangan - 28/2/2007
6629 
6630   l_msg_index_out              NUMBER;
6631   l_bpd_acc_rec                Okl_Acc_Call_Pub.bpd_acc_rec_type;
6632   l_set_of_books_id            Hr_operating_units.set_of_books_id%TYPE;
6633   l_trxH_in_rec                Okl_Trx_Contracts_Pub.tcnv_rec_type;
6634   l_trxH_out_rec               Okl_Trx_Contracts_Pub.tcnv_rec_type;
6635   l_trxL_in_tbl                Okl_Trx_Contracts_Pub.tclv_tbl_type;
6636   l_trxL_out_tbl               Okl_Trx_Contracts_Pub.tclv_tbl_type;
6637   l_acc_gen_primary_key_tbl    Okl_Account_Generator_Pvt.primary_key_tbl;
6638   l_meaning                    FND_LOOKUPS.meaning%TYPE;
6639   l_description                FND_LOOKUPS.description%TYPE;
6640 
6641   l_stream_created             VARCHAR2(1) := OKL_API.G_FALSE;
6642   l_strm_element_created       VARCHAR2(1) := OKL_API.G_FALSE;
6643   l_okl_trx_created            VARCHAR2(1) := OKL_API.G_FALSE;
6644   create_stream_invoice_failed EXCEPTION;
6645 
6646 -- 5033120
6647   l_trx_type_id                Okl_Trx_Types_V.id%TYPE;
6648   l_trx_try_id                 Okl_Trx_Types_V.try_id%TYPE;
6649   l_trx_desc                   Okl_Trx_Types_V.description%TYPE;
6650 
6651   l_tcn_type                   FND_LOOKUPS.lookup_code%TYPE;
6652   l_tcn_meaning                FND_LOOKUPS.meaning%TYPE;
6653   l_tcn_desc                   FND_LOOKUPS.description%TYPE;
6654 
6655   l_tcl_type                   FND_LOOKUPS.lookup_code%TYPE;
6656   l_tcl_meaning                FND_LOOKUPS.meaning%TYPE;
6657   l_tcl_desc                   FND_LOOKUPS.description%TYPE;
6658 
6659 --  Bug 5964482 dpsingh SLA Uptake Project
6660    l_tcn_id NUMBER;
6661    l_tmpl_identify_tbl          Okl_Account_Dist_Pvt.tmpl_identify_tbl_type;
6662    l_dist_info_tbl              Okl_Account_Dist_Pvt.dist_info_tbl_type;
6663    l_ctxt_tbl                   Okl_Account_Dist_Pvt.CTXT_TBL_TYPE;
6664    l_acc_gen_tbl                Okl_Account_Dist_Pvt.ACC_GEN_TBL_TYPE;
6665    l_template_out_tbl           Okl_Account_Dist_Pvt.avlv_out_tbl_type;
6666    l_amount_out_tbl             Okl_Account_Dist_Pvt.amount_out_tbl_type;
6667 --END: Added by dpsingh for SLA Uptake, Bug 5964482
6668 
6669   CURSOR stream_csr(p_khr_id NUMBER, p_kle_id NUMBER, p_sty_id NUMBER) IS
6670      SELECT stm.id
6671      FROM   okl_streams stm
6672      WHERE  stm.khr_id = p_khr_id
6673      AND    nvl(stm.kle_id, -9999) = NVL(p_kle_id, -9999)
6674      AND    stm.say_code = 'CURR'
6675      AND    stm.active_yn = 'Y'
6676      AND    stm.sty_id = p_sty_id;
6677 
6678   CURSOR tran_num_csr IS
6679      SELECT  okl_sif_seq.nextval
6680      FROM    dual;
6681 
6682   CURSOR c_stm_id_line_number(c_stm_id NUMBER) IS
6683      SELECT SE_LINE_NUMBER
6684      FROM   OKL_STRM_ELEMENTS_V
6685      WHERE  stm_id = c_stm_id
6686      ORDER BY SE_LINE_NUMBER DESC;
6687 
6688 
6689   CURSOR set_of_books_csr IS
6690      SELECT set_of_books_id
6691      FROM   OKL_SYS_ACCT_OPTS;
6692 
6693 
6694   CURSOR trx_type_csr (p_trx_name VARCHAR2) IS
6695      SELECT id, try_id, description
6696      FROM   okl_trx_types_v
6697      WHERE  name = p_trx_name;
6698 
6699 
6700   CURSOR fnd_lookup_csr (p_lookup_type VARCHAR2, p_lookup_code VARCHAR2) IS
6701      SELECT lookup_code, meaning, description
6702      FROM   fnd_lookups
6703      WHERE  lookup_code = p_lookup_code
6704      AND    lookup_type = p_lookup_type;
6705 
6706 --Added by dpsingh for LE Uptake
6707 CURSOR get_contract_number(p_khr_id NUMBER) IS
6708 SELECT CONTRACT_NUMBER
6709 FROM OKC_K_HEADERS_B
6710 WHERE ID = p_khr_id ;
6711 
6712 --Added by dpsingh for LE Uptake
6713 -- Bug 5964482 dpsingh for AE signature Uptake  start
6714 CURSOR get_dff_fields(p_khr_id NUMBER) IS
6715 SELECT ATTRIBUTE_CATEGORY,
6716               ATTRIBUTE1,
6717               ATTRIBUTE2,
6718               ATTRIBUTE3,
6719               ATTRIBUTE4,
6720               ATTRIBUTE5,
6721               ATTRIBUTE6,
6722               ATTRIBUTE7,
6723               ATTRIBUTE8,
6724               ATTRIBUTE9,
6725               ATTRIBUTE10,
6726               ATTRIBUTE11,
6727               ATTRIBUTE12,
6728               ATTRIBUTE13,
6729               ATTRIBUTE14,
6730               ATTRIBUTE15
6731 FROM OKL_K_HEADERS
6732 WHERE ID = p_khr_id ;
6733 -- Bug 5964482 dpsingh for AE signature Uptake  end
6734 l_legal_entity_id   NUMBER;
6735 l_cntrct_number   OKC_K_HEADERS_B.CONTRACT_NUMBER%TYPE;
6736 
6737   BEGIN
6738     print_debug('Executing procedure CREATE_STREAM_INVOICE using following parameters : ');
6739     print_debug(' p_contract_id : '|| p_contract_id );
6740 	print_debug(' p_line_id : '|| p_line_id);
6741     print_debug(' p_amount : '|| p_amount );
6742 	print_debug(' p_due_date: '|| p_due_date);
6743     print_debug(' p_stream_type_purpose : '||p_stream_type_purpose);
6744 	print_debug(' p_create_invoice_flag: '|| p_create_invoice_flag);
6745     print_debug(' p_process_flag : '|| p_process_flag);
6746     print_debug(' p_parent_strm_element_id : '|| p_parent_strm_element_id);
6747 
6748     x_return_status               := OKL_API.G_RET_STS_SUCCESS;
6749 
6750     -- Get sty_id for the contract
6751     IF (p_stream_type_purpose = 'VARIABLE_INTEREST') THEN
6752       Okl_Streams_Util.get_primary_stream_type(
6753                            p_khr_id              => p_contract_id,
6754                            p_primary_sty_purpose => p_stream_type_purpose,
6755                            x_return_status       => x_return_status,
6756                            x_primary_sty_id      => l_sty_id
6757                           );
6758     ELSE
6759       Okl_Streams_Util.get_dependent_stream_type(
6760                            p_khr_id                => p_contract_id,
6761                            p_primary_sty_purpose   => 'RENT',
6762                            p_dependent_sty_purpose => p_stream_type_purpose,
6763                            x_return_status         => x_return_status,
6764                            x_dependent_sty_id      => l_sty_id
6765                           );
6766     END IF;
6767 
6768     IF (x_return_status = 'S' ) THEN
6769        print_debug ('        -- Stream Id for purpose '|| p_stream_type_purpose || 'retrieved.');
6770     ELSE
6771        print_debug( '        -- ERROR: Could not retrieve Stream Id for purpose '|| p_stream_type_purpose );
6772     END IF;
6773 
6774     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
6775       print_error_message('Unexpected error raised in call to Okl_Streams_Util.get_primary/dependent_stream_type');
6776       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
6777     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
6778       print_error_message('Error raised in call to Okl_Streams_Util.get_primary/dependent_stream_type');
6779       RAISE create_stream_invoice_failed;
6780     END IF;
6781 
6782     l_selv_rec.stm_id := NULL;
6783 
6784     OPEN stream_csr (p_contract_id, p_line_id, l_sty_id);
6785     FETCH stream_csr INTO l_selv_rec.stm_id;
6786     IF (stream_csr%NOTFOUND) THEN
6787        NULL;
6788        print_debug('Stream Not Found : Creating a new stream');
6789     END IF;
6790     CLOSE stream_csr;
6791 
6792     IF (l_selv_rec.stm_id IS NULL) THEN
6793        OPEN  tran_num_csr;
6794        FETCH tran_num_csr INTO l_stmv_rec.transaction_number;
6795        CLOSE tran_num_csr;
6796 
6797        l_stmv_rec.sty_id                := l_sty_id;
6798        l_stmv_rec.khr_id                := p_contract_id;
6799        l_stmv_rec.kle_id                := p_line_id;
6800        l_stmv_rec.sgn_code              := 'INTC';
6801        l_stmv_rec.say_code              := 'CURR';
6802        l_stmv_rec.active_yn             := 'Y';
6803        l_stmv_rec.date_current          := sysdate;
6804 
6805        IF (p_process_flag = 'DAILY_INTEREST') THEN
6806           l_stmv_rec.comments              := 'Daily Interest';
6807        ELSE
6808           l_stmv_rec.comments              := 'Variable Interest';
6809        END IF;
6810 
6811        print_debug('Executing procedure OKL_STREAMS_PUB.CREATE_STREAMS');
6812 
6813        Okl_Streams_Pub.create_streams(
6814                                       p_api_version    =>     p_api_version,
6815                                       p_init_msg_list  =>     p_init_msg_list,
6816                                       x_return_status  =>     x_return_status,
6817                                       x_msg_count      =>     x_msg_count,
6818                                       x_msg_data       =>     x_msg_data,
6819                                       p_stmv_rec       =>     l_stmv_rec,
6820                                       x_stmv_rec       =>     lx_stmv_rec);
6821 
6822 
6823        IF (x_return_status = 'S' ) THEN
6824           print_debug ('        -- Success in Stream Creation.');
6825        ELSE
6826           print_debug ('        -- Error: '||x_msg_data);
6827        END IF;
6828 
6829        IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
6830          print_error_message('Unexpected error raised in call to Okl_Streams_Pub.create_streams');
6831          RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
6832        ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
6833          print_error_message('Error raised in call to Okl_Streams_Pub.create_streams');
6834          RAISE create_stream_invoice_failed;
6835        END IF;
6836 
6837        l_stream_created := OKL_API.G_TRUE;
6838 
6839        print_debug ('Stm ID: '||lx_stmv_rec.id);
6840        l_selv_rec.stm_id := lx_stmv_rec.id;
6841        print_debug ('Stm ID: '||l_selv_rec.stm_id);
6842 
6843     END IF;
6844 
6845     --change on 16 Nov 2005 by pgomes for bug fix 4740008
6846     --setting the value of accrued_yn to NULL instead of 'N'
6847     l_selv_rec.accrued_yn          := NULL;
6848     l_selv_rec.stream_element_date := p_due_date;
6849     l_selv_rec.date_billed         := trunc(sysdate);
6850     l_selv_rec.amount              := p_amount;
6851     l_selv_rec.sel_id              := p_parent_strm_element_id;
6852 
6853     l_selv_rec.se_line_number      := NULL;
6854     OPEN  c_stm_id_line_number(l_selv_rec.stm_id);
6855     FETCH c_stm_id_line_number INTO l_selv_rec.se_line_number;
6856     IF (c_stm_id_line_number%NOTFOUND) THEN
6857         print_debug ('Stream Elements do not exist');
6858        l_selv_rec.se_line_number := 1;
6859     ELSE
6860        l_selv_rec.se_line_number := l_selv_rec.se_line_number + 1;
6861     END IF;
6862     CLOSE c_stm_id_line_number;
6863 
6864     IF (p_process_flag = 'DAILY_INTEREST') THEN
6865        l_selv_rec.comments              := 'Daily Interest';
6866     ELSE
6867        l_selv_rec.comments              := 'Variable Interest';
6868     END IF;
6869 
6870 
6871     print_debug('Executing procedure OKL_STREAMS_PUB.CREATE_STREAM_ELEMENTS');
6872 
6873     Okl_Streams_Pub.create_stream_elements(
6874                                            p_api_version    =>     p_api_version,
6875                                            p_init_msg_list  =>     p_init_msg_list,
6876                                            x_return_status  =>     x_return_status,
6877                                            x_msg_count      =>     x_msg_count,
6878                                            x_msg_data       =>     x_msg_data,
6879                                            p_selv_rec       =>     l_selv_rec,
6880                                            x_selv_rec       =>     lx_selv_rec);
6881 
6882     IF (x_return_status = 'S' ) THEN
6883        print_debug ('        -- Success in Creating Stream Elements.');
6884     ELSE
6885        print_debug ('        -- Error: '||x_msg_data);
6886     END IF;
6887 
6888     IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
6889       print_error_message('Unexpected error raised in call to Okl_Streams_Pub.create_stream_elements');
6890       RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
6891     ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
6892       print_error_message('Error raised in call to Okl_Streams_Pub.create_stream_elements');
6893       RAISE create_stream_invoice_failed;
6894     END IF;
6895 
6896     l_strm_element_created := OKL_API.G_TRUE;
6897 
6898     x_stream_element_id :=   lx_selv_rec.id;
6899 
6900 
6901 
6902     OPEN set_of_books_csr;
6903     FETCH set_of_books_csr INTO l_set_of_books_id;
6904     IF (set_of_books_csr%NOTFOUND) THEN
6905       print_error_message('Set of books cursor did not return any records');
6906       RAISE create_stream_invoice_failed;
6907     END IF;
6908     CLOSE set_of_books_csr;
6909 
6910     IF (p_create_invoice_flag = OKL_API.G_TRUE) THEN
6911       IF (G_BILLING_TRX_TYPE_ID IS NULL) THEN
6912         OPEN trx_type_csr ('Billing');
6913         FETCH trx_type_csr INTO G_BILLING_TRX_TYPE_ID, G_BILLING_TRX_TRY_ID, G_BILLING_TRX_DESC;
6914         IF (trx_type_csr%NOTFOUND) THEN
6915           print_error_message('Transaction type cursor did not return any records');
6916           RAISE create_stream_invoice_failed;
6917         END IF;
6918         CLOSE trx_type_csr;
6919       END IF;
6920 
6921        print_debug('G_CONTRACT_ID : '|| G_CONTRACT_ID);
6922 -- Begin - Billing Inline changes - Bug#5898792 - varangan - 28/2/2007
6923        lp_taiv_rec.khr_id             := p_contract_id;
6924        lp_taiv_rec.date_invoiced      := p_due_date;
6925        lp_taiv_rec.try_id             := G_BILLING_TRX_TYPE_ID;
6926        lp_taiv_rec.date_entered       := l_date_entered;
6927        lp_taiv_rec.description        := l_def_desc;
6928        lp_taiv_rec.trx_status_code    := l_final_status;
6929        lp_taiv_rec.amount             := p_amount;
6930        lp_taiv_rec.currency_code      := G_CURRENCY_CODE;
6931        lp_taiv_rec.org_id             := G_AUTHORING_ORG_ID;
6932        lp_taiv_rec.set_of_books_id    := l_set_of_books_id;
6933        lp_taiv_rec.OKL_SOURCE_BILLING_TRX := G_SOURCE_BILLING_TRX;
6934       -- Added by dpsingh for LE Uptake
6935             l_legal_entity_id  := OKL_LEGAL_ENTITY_UTIL.get_khr_le_id(p_contract_id) ;
6936             IF  l_legal_entity_id IS NOT NULL THEN
6937 	        lp_taiv_rec.legal_entity_id :=  l_legal_entity_id;
6938             ELSE
6939                   -- get the contract number
6940                 OPEN get_contract_number(p_contract_id);
6941                 FETCH get_contract_number INTO l_cntrct_number;
6942                 CLOSE get_contract_number;
6943 		Okl_Api.set_message(p_app_name     => g_app_name,
6944                                                  p_msg_name     => 'OKL_LE_NOT_EXIST_CNTRCT',
6945 			                         p_token1           =>  'CONTRACT_NUMBER',
6946 			                         p_token1_value  =>  l_cntrct_number);
6947                 RAISE OKL_API.G_EXCEPTION_ERROR;
6948              END IF;
6949 
6950        print_debug('Executing procedure OKL_TRX_AR_INVOICES_PUB.INSERT_TRX_AR_INVOICES');
6951 
6952      /*
6953        --Commenting the existing code by calling common Billing API
6954        Okl_Trx_Ar_Invoices_Pub.insert_trx_ar_invoices
6955                                            (p_api_version,
6956                                             p_init_msg_list,
6957                                             x_return_status,
6958                                             x_msg_count,
6959                                             x_msg_data,
6960                                             i_taiv_rec,
6961                                             r_taiv_rec);
6962 
6963        IF (x_return_status = 'S' ) THEN
6964           print_debug ('        -- Internal TXN Header Created.');
6965        ELSE
6966           print_debug( '        -- ERROR: Creating Internal TXN Header.');
6967        END IF;
6968 
6969        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
6970          print_error_message('Unexpected error raised in call to Okl_Trx_Ar_Invoices_Pub.insert_trx_ar_invoices');
6971          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
6972        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
6973          print_error_message('Error raised in call to Okl_Trx_Ar_Invoices_Pub.insert_trx_ar_invoices');
6974          RAISE create_stream_invoice_failed;
6975        END IF; */
6976 
6977  -- Populate the Line record
6978        lp_tilv_rec.org_id                   := G_AUTHORING_ORG_ID;
6979        lp_tilv_rec.line_number              := 1;
6980        lp_tilv_rec.kle_id                   := p_line_id;
6981 --       x_invoice_id                        := r_taiv_rec.id;
6982        lp_tilv_rec.description              := l_def_desc;
6983        lp_tilv_rec.inv_receiv_line_code     := l_line_code;
6984        lp_tilv_rec.amount                   := p_amount;
6985        lp_tilv_rec.date_bill_period_start   := p_due_date;
6986        lp_tilv_rec.til_id_reverses          := NULL;
6987        lp_tilv_rec.tpl_id                   := NULL;
6988        lp_tilv_rec.acn_id_cost              := NULL;
6989        lp_tilv_rec.sty_id                   := NULL;
6990        lp_tilv_rec.quantity                 := NULL;
6991        lp_tilv_rec.amount_applied           := NULL;
6992        lp_tilv_rec.receivables_invoice_id   := NULL;
6993       --sosharma added txl_ar_line_number start changes
6994         lp_tilv_rec.txl_ar_line_number := 1;
6995       -- sosharma end changes
6996        lp_tilv_tbl(1) := lp_tilv_rec; -- Assign the line record in tilv_tbl structure
6997 
6998      /*
6999        --Commenting the existing code by calling common Billing API
7000        Okl_Txl_Ar_Inv_Lns_Pub.insert_txl_ar_inv_lns
7001                                                    (p_api_version,
7002                                                     p_init_msg_list,
7003                                                     x_return_status,
7004                                                     x_msg_count,
7005                                                     x_msg_data,
7006                                                     i_tilv_rec,
7007                                                     r_tilv_rec);
7008 
7009        IF (x_return_status = 'S' ) THEN
7010           print_debug ('        -- Internal TXN Line Created.');
7011        ELSE
7012           FND_FILE.PUT_LINE (FND_FILE.LOG, '        -- ERROR: Creating Internal TXN Line.');
7013        END IF;
7014 
7015        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
7016          print_error_message('Unexpected error raised in call to Okl_Txl_Ar_Inv_Lns_Pub.insert_txl_ar_inv_lns');
7017          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
7018        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
7019          print_error_message('Error raised in call to Okl_Txl_Ar_Inv_Lns_Pub.insert_txl_ar_inv_lns');
7020          RAISE create_stream_invoice_failed;
7021        END IF; */
7022 
7023        lp_tldv_rec.sty_id             := l_sty_id;
7024        lp_tldv_rec.amount             := p_amount;
7025        lp_tldv_rec.description        := l_def_desc;
7026        lp_tldv_rec.sel_id             := lx_selv_rec.id;
7027        --i_tldv_rec.til_id_details     := r_tilv_rec.id;
7028        lp_tldv_rec.line_detail_number := 1;
7029        lp_tldv_rec.date_calculation   := SYSDATE;
7030        lp_tldv_rec.org_id             := G_AUTHORING_ORG_ID; --r_taiv_rec.org_id;
7031        --sosharma added for billing issues
7032         lp_tldv_rec.txl_ar_line_number := 1;
7033        lp_tldv_tbl(1) := lp_tldv_rec;
7034 
7035             ---------------------------------------------------------------------------
7036 	    -- Call to Billing Centralized API
7037 	    ---------------------------------------------------------------------------
7038 		okl_internal_billing_pvt.create_billing_trx(p_api_version =>l_api_version,
7039 							    p_init_msg_list =>p_init_msg_list,
7040 							    x_return_status =>  x_return_status,
7041 							    x_msg_count => x_msg_count,
7042 							    x_msg_data => x_msg_data,
7043 							    p_taiv_rec => lp_taiv_rec,
7044 							    p_tilv_tbl => lp_tilv_tbl,
7045 							    p_tldv_tbl => lp_tldv_tbl,
7046 							    x_taiv_rec => lx_taiv_rec,
7047 							    x_tilv_tbl => lx_tilv_tbl,
7048 							    x_tldv_tbl => lx_tldv_tbl);
7049 
7050 	       IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
7051                  print_error_message('Unexpected error raised in call to okl_internal_billing_pvt.create_billing_trx');
7052                  RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
7053                ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
7054 	         print_error_message('Error raised in call to okl_internal_billing_pvt.create_billing_trx');
7055                  RAISE create_stream_invoice_failed;
7056                END IF;
7057               --sosharma added for billing changes
7058                x_invoice_id := lx_taiv_rec.id;
7059               --sosharma end
7060 
7061 
7062 			/*   --Commenting the existing code by calling common Billing API
7063 			     Okl_Txd_Ar_Ln_Dtls_Pub.insert_txd_ar_ln_dtls
7064 									   (p_api_version,
7065 									    p_init_msg_list,
7066 									    x_return_status,
7067 									    x_msg_count,
7068 									    x_msg_data,
7069 									    i_tldv_rec,
7070 									    r_tldv_rec);
7071 			       IF (x_return_status = 'S' ) THEN
7072 				  print_debug ('        -- Internal TXN Details Created.');
7073 			       ELSE
7074 				  print_debug ('        -- ERROR: Creating Internal TXN Details.');
7075 
7076 				  FOR i in 1..x_msg_count
7077 				  LOOP
7078 				     FND_MSG_PUB.GET(
7079 						     p_msg_index     => i,
7080 						     p_encoded       => FND_API.G_FALSE,
7081 						     p_data          => x_msg_data,
7082 						     p_msg_index_out => l_msg_index_out
7083 						    );
7084 				     print_debug('Error '||to_char(i)||': '||x_msg_data);
7085 				     print_debug('Message Index: '||l_msg_index_out);
7086 				  END LOOP;
7087 			       END IF;
7088 
7089 			       IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
7090 				 print_error_message('Unexpected error raised in call to Okl_Txd_Ar_Ln_Dtls_Pub.insert_txd_ar_ln_dtls');
7091 				 RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
7092 			       ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
7093 				 print_error_message('Error raised in call to Okl_Txd_Ar_Ln_Dtls_Pub.insert_txd_ar_ln_dtls');
7094 				 RAISE create_stream_invoice_failed;
7095 			       END IF;
7096 
7097 			       l_bpd_acc_rec.id           := r_tldv_rec.id;
7098 			       l_bpd_acc_rec.source_table := 'OKL_TXD_AR_LN_DTLS_B';
7099 
7100 			       Okl_Acc_Call_Pub.CREATE_ACC_TRANS(
7101 								 p_api_version,
7102 								 p_init_msg_list,
7103 								 x_return_status,
7104 								 x_msg_count,
7105 								 x_msg_data,
7106 								 l_bpd_acc_rec
7107 								);
7108 
7109 			      IF (x_return_status = 'S' ) THEN
7110 				 print_debug ('        -- Accounting Distributions Created.');
7111 			      ELSE
7112 				 print_debug ('        -- ERROR: Accounting Distributions NOT Created.');
7113 
7114 				 FOR i in 1..x_msg_count
7115 				 LOOP
7116 				    FND_MSG_PUB.GET(
7117 						    p_msg_index     => i,
7118 						    p_encoded       => FND_API.G_FALSE,
7119 						    p_data          => x_msg_data,
7120 						    p_msg_index_out => l_msg_index_out
7121 						   );
7122 				    print_debug('Error '||to_char(i)||': '||x_msg_data);
7123 				    print_error_message ('Error'||to_char(i)||': '|| x_msg_data);
7124 				    print_debug('Message Index: '||l_msg_index_out);
7125 				    print_error_message('Message Index: '|| l_msg_index_out);
7126 				 END LOOP;
7127 			      END IF;
7128 
7129 			      IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
7130 				print_error_message('Unexpected error raised in call to Okl_Acc_Call_Pub.CREATE_ACC_TRANS');
7131 				RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
7132 			      ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
7133 				print_error_message('Error raised in call to Okl_Acc_Call_Pub.CREATE_ACC_TRANS');
7134 				RAISE create_stream_invoice_failed;
7135 			      END IF;*/ -- end commenting existing code for common billing API call
7136 
7137     -- End - Billing Inline changes - Bug#5898792 - varangan - 28/2/2007
7138 
7139     END IF;
7140 
7141     IF (p_process_flag in ('DAILY_INTEREST', 'PRINCIPAL_CATCHUP')) THEN
7142        print_debug('Stream Type Purpose: '|| p_stream_type_purpose);
7143        IF (p_stream_type_purpose IN ('DAILY_INTEREST_PRINCIPAL', 'DAILY_INTEREST_INTEREST')) THEN
7144           ------------------------------------------------------------
7145           -- Create Contract Transaction Header and Line
7146           -- in Submitted Status
7147           ------------------------------------------------------------
7148           IF (G_RCPT_APP_TRX_TYPE_ID IS NULL) THEN
7149             OPEN trx_type_csr('Receipt Application');
7150             FETCH trx_type_csr INTO G_RCPT_APP_TRX_TYPE_ID, G_RCPT_APP_TRX_TRY_ID, G_RCPT_APP_TRX_DESC;
7151             IF (trx_type_csr%NOTFOUND) THEN
7152               CLOSE trx_type_csr;
7153               print_error_message('Transaction type cursor did not return any records');
7154               RAISE create_stream_invoice_failed;
7155             END IF;
7156             CLOSE trx_type_csr;
7157           END IF;
7158           l_trx_type_id := G_RCPT_APP_TRX_TYPE_ID;
7159           l_trx_try_id  := G_RCPT_APP_TRX_TRY_ID;
7160 		  l_trx_desc    := G_RCPT_APP_TRX_DESC;
7161 
7162           IF (G_RAP_TCN_TYPE IS NULL) THEN
7163             OPEN fnd_lookup_csr('OKL_TCN_TYPE', 'RAP');
7164             FETCH fnd_lookup_csr INTO G_RAP_TCN_TYPE,G_RAP_TCN_MEANING, G_RAP_TCN_DESC;
7165             IF (fnd_lookup_csr%NOTFOUND) THEN
7166               CLOSE fnd_lookup_csr;
7167                print_error_message('FND lookup cursor did not return any records');
7168                RAISE create_stream_invoice_failed;
7169             END IF;
7170             CLOSE fnd_lookup_csr;
7171           END IF;
7172 
7173 		  l_tcn_type    := G_RAP_TCN_TYPE;
7174 		  l_tcn_meaning := G_RAP_TCN_MEANING;
7175 		  l_tcn_desc    := G_RAP_TCN_DESC;
7176 -- new
7177        ELSIF (p_stream_type_purpose IN ('PRINCIPAL_CATCHUP')) THEN
7178           ------------------------------------------------------------
7179           -- Create Contract Transaction Header and Line for Principal Adjustment
7180           -- in Submitted Status
7181           ------------------------------------------------------------
7182           IF (G_PAD_TRX_TYPE_ID IS NULL) THEN
7183             OPEN trx_type_csr('Principal Adjustment');
7184             FETCH trx_type_csr INTO G_PAD_TRX_TYPE_ID, G_PAD_TRX_TRY_ID, G_PAD_TRX_DESC;
7185             IF (trx_type_csr%NOTFOUND) THEN
7186               CLOSE trx_type_csr;
7187               print_error_message('Transaction type cursor did not return any records');
7188               RAISE create_stream_invoice_failed;
7189             END IF;
7190             CLOSE trx_type_csr;
7191           END IF;
7192           l_trx_type_id := G_PAD_TRX_TYPE_ID;
7193           l_trx_try_id  := G_PAD_TRX_TRY_ID;
7194 		  l_trx_desc    := G_PAD_TRX_DESC;
7195 
7196           IF (G_PAD_TCN_TYPE IS NULL) THEN
7197             OPEN fnd_lookup_csr('OKL_TCN_TYPE', 'PAD');
7198             FETCH fnd_lookup_csr INTO G_PAD_TCN_TYPE,G_PAD_TCN_MEANING, G_PAD_TCN_DESC;
7199             IF (fnd_lookup_csr%NOTFOUND) THEN
7200               CLOSE fnd_lookup_csr;
7201                print_error_message('FND lookup cursor did not return any records');
7202                RAISE create_stream_invoice_failed;
7203             END IF;
7204             CLOSE fnd_lookup_csr;
7205           END IF;
7206 
7207 		  l_tcn_type    := G_PAD_TCN_TYPE;
7208 		  l_tcn_meaning := G_PAD_TCN_MEANING;
7209 		  l_tcn_desc    := G_PAD_TCN_DESC;
7210 
7211        END IF; -- new
7212 
7213           print_debug('G_CONTRACT_ID : '|| G_CONTRACT_ID);
7214           print_debug('l_tcn_type: '|| l_tcn_type);
7215           print_debug('l_trx_desc: '|| l_trx_desc);
7216           print_debug('l_trx_type_id: '|| l_trx_type_id);
7217 
7218           l_trxH_in_rec.khr_id                     := p_contract_id;
7219           l_trxH_in_rec.pdt_id                     := G_PRODUCT_ID;
7220           l_trxH_in_rec.set_of_books_id            := l_set_of_books_id;
7221           l_trxH_in_rec.tsu_code                   := 'PROCESSED';
7222           l_trxH_in_rec.tcn_type                   := l_tcn_type; --G_RAP_TCN_TYPE;
7223           l_trxH_in_rec.description                := l_trx_desc; --G_RCPT_APP_TRX_DESC;
7224           l_trxH_in_rec.date_transaction_occurred  := p_due_date;
7225           l_trxH_in_rec.try_id                     := l_trx_type_id; --G_RCPT_APP_TRX_TYPE_ID;
7226           l_trxH_in_rec.amount                     := p_amount;
7227           l_trxH_in_rec.currency_code              := G_CURRENCY_CODE;
7228           l_trxH_in_rec.org_id                     := G_AUTHORING_ORG_ID;
7229           l_trxH_in_rec.request_id                 := g_request_id;
7230 	  -- Bug 5964482 dpsingh for AE signature Uptake  start
7231          OPEN get_dff_fields(p_contract_id);
7232          FETCH get_dff_fields into l_trxH_in_rec.ATTRIBUTE_CATEGORY,
7233                                                 l_trxH_in_rec.ATTRIBUTE1,
7234                                                 l_trxH_in_rec.ATTRIBUTE2,
7235                                                 l_trxH_in_rec.ATTRIBUTE3,
7236                                                 l_trxH_in_rec.ATTRIBUTE4,
7237                                                 l_trxH_in_rec.ATTRIBUTE5,
7238                                                 l_trxH_in_rec.ATTRIBUTE6,
7239                                                 l_trxH_in_rec.ATTRIBUTE7,
7240                                                 l_trxH_in_rec.ATTRIBUTE8,
7241                                                 l_trxH_in_rec.ATTRIBUTE9,
7242                                                 l_trxH_in_rec.ATTRIBUTE10,
7243                                                 l_trxH_in_rec.ATTRIBUTE11,
7244                                                 l_trxH_in_rec.ATTRIBUTE12,
7245                                                 l_trxH_in_rec.ATTRIBUTE13,
7246                                                 l_trxH_in_rec.ATTRIBUTE14,
7247                                                 l_trxH_in_rec.ATTRIBUTE15;
7248           CLOSE get_dff_fields;
7249 	  -- Bug 5964482 dpsingh for AE signature Uptake  start
7250 	 -- Added by dpsingh for LE Uptake
7251 	  l_trxH_in_rec.legal_entity_id := l_legal_entity_id;
7252 
7253           IF (p_stream_type_purpose IN ('DAILY_INTEREST_PRINCIPAL', 'DAILY_INTEREST_INTEREST')) THEN
7254 
7255             IF (G_RAP_TCL_TYPE IS NULL) THEN
7256               OPEN fnd_lookup_csr('OKL_TCL_TYPE', 'RAP');
7257               FETCH fnd_lookup_csr INTO G_RAP_TCL_TYPE,G_RAP_TCL_MEANING, G_RAP_TCL_DESC;
7258               IF (fnd_lookup_csr%NOTFOUND) THEN
7259                 CLOSE fnd_lookup_csr;
7260                 print_error_message('FND lookup cursor did not return any records');
7261                 RAISE create_stream_invoice_failed;
7262               END IF;
7263               CLOSE fnd_lookup_csr;
7264             END IF;
7265             l_tcl_type    := G_RAP_TCL_TYPE;
7266             l_tcl_meaning := G_RAP_TCL_MEANING;
7267             l_tcl_desc    := G_RAP_TCL_DESC;
7268           ELSIF (p_stream_type_purpose  = 'PRINCIPAL_CATCHUP') THEN
7269             IF (G_PAD_TCL_TYPE IS NULL) THEN
7270               OPEN fnd_lookup_csr('OKL_TCL_TYPE', 'PAD');
7271               FETCH fnd_lookup_csr INTO G_PAD_TCL_TYPE,G_PAD_TCL_MEANING, G_PAD_TCL_DESC;
7272               IF (fnd_lookup_csr%NOTFOUND) THEN
7273                 CLOSE fnd_lookup_csr;
7274                 print_error_message('FND lookup cursor did not return any records');
7275                 RAISE create_stream_invoice_failed;
7276               END IF;
7277               CLOSE fnd_lookup_csr;
7278             END IF;
7279             l_tcl_type    := G_PAD_TCL_TYPE;
7280             l_tcl_meaning := G_PAD_TCL_MEANING;
7281             l_tcl_desc    := G_PAD_TCL_DESC;
7282           END IF;
7283 
7284           print_debug('l_tcl_type : '||l_tcl_type);
7285           print_debug('l_tcl_desc : '||l_tcl_desc);
7286 
7287           l_trxL_in_tbl(1).line_number             := 1;
7288           l_trxL_in_tbl(1).khr_id                  := p_contract_id;
7289           l_trxL_in_tbl(1).sty_id                  := l_sty_id;
7290           l_trxL_in_tbl(1).tcl_type                := l_tcl_type; --G_RAP_TCL_TYPE;
7291           l_trxL_in_tbl(1).description             := l_tcl_desc; --G_RAP_TCL_DESC;
7292           l_trxL_in_tbl(1).amount                  := p_amount;
7293           l_trxL_in_tbl(1).currency_code           := G_CURRENCY_CODE;
7294 
7295           FND_FILE.PUT_LINE (FND_FILE.LOG, 'Creating Contract Transaction.');
7296           Okl_Trx_Contracts_Pub.create_trx_contracts(
7297                   p_api_version      => l_api_version,
7298                   p_init_msg_list    => p_init_msg_list,
7299                   x_return_status    => x_return_status,
7300                   x_msg_count        => x_msg_count,
7301                   x_msg_data         => x_msg_data,
7302                   p_tcnv_rec         => l_trxH_in_rec,
7303                   p_tclv_tbl         => l_trxL_in_tbl,
7304                   x_tcnv_rec         => l_trxH_out_rec,
7305 			      x_tclv_tbl         => l_trxL_out_tbl);
7306 
7307           IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
7308             print_error_message('Unexpected error raised in call to Okl_Trx_Contracts_Pub.create_trx_contracts');
7309             RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
7310           ELSIF (x_return_Status = Okl_Api.G_RET_STS_ERROR) THEN
7311             print_error_message('Error raised in call to Okl_Trx_Contracts_Pub.create_trx_contracts');
7312             RAISE create_stream_invoice_failed;
7313           END IF;
7314 
7315           IF ((l_trxH_out_rec.id = OKL_API.G_MISS_NUM) OR
7316               (l_trxH_out_rec.id IS NULL) ) THEN
7317              OKL_API.set_message(G_APP_NAME, G_REQUIRED_VALUE,G_COL_NAME_TOKEN,'TRANSACTION_ID');
7318              print_error_message ('ERROR : OKL transaction ID is NULL');
7319              RAISE create_stream_invoice_failed;
7320           END IF;
7321 
7322           l_okl_trx_created := OKL_API.G_TRUE;
7323 
7324    	      ------------------------------------------------------------
7325   	      -- Derive and Insert Distribution Line
7326 	      ------------------------------------------------------------
7327 
7328           FND_FILE.PUT_LINE ( FND_FILE.LOG, '      -- Creating Distributions. Supplied parameters:');
7329 
7330           ------------------ Accounting Engine Calls --------------------------
7331 --START: Changes by dpsingh for SLA Uptake, Bug #5964482
7332 Okl_Acc_Call_Pvt.Okl_Populate_Acc_Gen (
7333                                                                 p_contract_id        => p_contract_id,
7334                                                                 p_contract_line_id => p_line_id,
7335                                                                 x_acc_gen_tbl      => l_acc_gen_primary_key_tbl,
7336                                                                 x_return_status	 => x_return_status);
7337 
7338    print_debug('End Debug OKLRVARB.pls call Okl_Acc_Call_Pvt.Okl_Populate_Acc_Gen  ');
7339    IF ( x_return_status = okl_api.g_ret_sts_success) THEN
7340      FND_FILE.PUT_LINE (FND_FILE.LOG, '      -- Accounting engine called successfully  ');
7341    ELSE
7342      FND_FILE.PUT_LINE (FND_FILE.LOG, '*=> ERROR : Calling Accounting engine.');
7343      IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
7344        print_error_message('Unexpected error raised in call to Okl_Acc_Call_Pvt.Okl_Populate_Acc_Gen');
7345        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
7346       ELSIF (x_return_Status = Okl_Api.G_RET_STS_ERROR) THEN
7347         print_error_message('Error raised in call to Okl_Acc_Call_Pvt.Okl_Populate_Acc_Gen');
7348         RAISE create_stream_invoice_failed;
7349        END IF;
7350      END IF;
7351 l_tcn_id := l_trxH_out_rec.id;
7352 IF l_trxL_out_tbl.count >0 THEN
7353   FOR i IN l_trxL_out_tbl.FIRST..l_trxL_out_tbl.LAST
7354   LOOP
7355     l_acc_gen_tbl(i).acc_gen_key_tbl := l_acc_gen_primary_key_tbl;
7356     l_acc_gen_tbl(i).source_id := l_trxL_out_tbl(i).id;
7357 
7358     l_tmpl_identify_tbl(i).product_id             := G_PRODUCT_ID;
7359     l_tmpl_identify_tbl(i).transaction_type_id    := l_trx_type_id; --G_RCPT_APP_TRX_TYPE_ID;
7360     l_tmpl_identify_tbl(i).stream_type_id         := l_sty_id;
7361     l_tmpl_identify_tbl(i).ADVANCE_ARREARS        := NULL;
7362     l_tmpl_identify_tbl(i).FACTORING_SYND_FLAG    := NULL;
7363     l_tmpl_identify_tbl(i).SYNDICATION_CODE       := NULL;
7364     l_tmpl_identify_tbl(i).FACTORING_CODE         := NULL;
7365     l_tmpl_identify_tbl(i).MEMO_YN                := 'N';
7366     l_tmpl_identify_tbl(i).PRIOR_YEAR_YN          := 'N';
7367 
7368       -- 4872347 Modified the source table and source id
7369     l_dist_info_tbl(i).source_id		    	   := l_trxL_out_tbl(1).id;
7370     l_dist_info_tbl(i).source_table			   := 'OKL_TXL_CNTRCT_LNS';
7371     l_dist_info_tbl(i).accounting_date		   := p_due_date;
7372     l_dist_info_tbl(i).gl_reversal_flag		   := 'N';
7373     l_dist_info_tbl(i).post_to_gl			   := 'Y';
7374     l_dist_info_tbl(i).amount				   := p_amount;
7375     l_dist_info_tbl(i).currency_code			   := G_CURRENCY_CODE;
7376     l_dist_info_tbl(i).contract_id			   := p_contract_id;
7377     l_dist_info_tbl(i).contract_line_id     	   := p_line_id;
7378   END LOOP;
7379 END IF;
7380 
7381           print_debug('Begin Debug OKLRVARB.pls call Okl_Account_Dist_Pub.CREATE_ACCOUNTING_DIST ');
7382 
7383        -- Call new signature
7384          Okl_Account_Dist_Pvt.CREATE_ACCOUNTING_DIST(
7385                                                                                          p_api_version        => p_api_version,
7386                                                                                          p_init_msg_list      => p_init_msg_list,
7387                                                                                          x_return_status      => x_return_status,
7388                                                                                          x_msg_count          => x_msg_count,
7389                                                                                          x_msg_data           => x_msg_data,
7390                                                                                          p_tmpl_identify_tbl  => l_tmpl_identify_tbl,
7391                                                                                          p_dist_info_tbl      => l_dist_info_tbl,
7392                                                                                          p_ctxt_val_tbl       => l_ctxt_tbl,
7393                                                                                          p_acc_gen_primary_key_tbl => l_acc_gen_tbl,
7394                                                                                          x_template_tbl       => l_template_out_tbl,
7395                                                                                          x_amount_tbl         => l_amount_out_tbl,
7396                                                                                          p_trx_header_id      => l_tcn_id);
7397 
7398  --END: Changes by dpsingh for SLA Uptake, Bug #5964482
7399 
7400           print_debug('End Debug OKLRVARB.pls call Okl_Account_Dist_Pub.CREATE_ACCOUNTING_DIST ');
7401 
7402 	      IF ( x_return_status = okl_api.g_ret_sts_success) THEN
7403 	         FND_FILE.PUT_LINE (FND_FILE.LOG, '      -- Accounting distributions created.  ');
7404 	      ELSE
7405 	         FND_FILE.PUT_LINE (FND_FILE.LOG, '*=> ERROR : Accounting distributions not created.'||x_msg_count || x_msg_data);
7406              IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
7407                print_error_message('Unexpected error raised in call to Okl_Account_Dist_Pub.CREATE_ACCOUNTING_DIST');
7408                RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
7409              ELSIF (x_return_Status = Okl_Api.G_RET_STS_ERROR) THEN
7410                print_error_message('Error raised in call to Okl_Account_Dist_Pub.CREATE_ACCOUNTING_DIST');
7411                RAISE create_stream_invoice_failed;
7412              END IF;
7413 	      END IF;
7414 --       END IF;
7415 
7416     -- Bug 7624242. SGIYER. Uncommented the MG Engine call for Variable Rate Contracts
7417     -- moved the call to MG engine here .. racheruv. Bug 7690456
7418    OKL_MULTIGAAP_ENGINE_PVT.CREATE_SEC_REP_TRX
7419                            (p_api_version => p_api_version
7420                            ,p_init_msg_list => p_init_msg_list
7421                            ,x_return_status => x_return_status
7422                            ,x_msg_count => x_msg_count
7423                            ,x_msg_data => x_msg_data
7424                            ,P_TCNV_REC => l_trxH_out_rec
7425                            ,P_TCLV_TBL => l_trxL_out_tbl
7426                            ,p_ctxt_val_tbl => l_ctxt_tbl
7427                            ,p_acc_gen_primary_key_tbl => l_acc_gen_primary_key_tbl);
7428 
7429     IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
7430         print_error_message('Unexpected error raised in call to OKL_MULTIGAAP_ENGINE_PVT.CREATE_SEC_REP_TRX');
7431         RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
7432     ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
7433         print_error_message('Error raised in call to OKL_MULTIGAAP_ENGINE_PVT.CREATE_SEC_REP_TRX');
7434         RAISE Okl_Api.G_EXCEPTION_ERROR;
7435     END IF;
7436      -- end the call to MG engine .. racheruv. Bug 7690456
7437  END IF;
7438 
7439 
7440   EXCEPTION
7441     WHEN create_stream_invoice_failed THEN
7442       print_error_message('Exception create_stream_invoice_failed raised in procedure CREATE_STREAM_INVOICE');
7443       IF (stream_csr%ISOPEN) THEN
7444         CLOSE stream_csr;
7445       END IF;
7446 
7447       IF (trx_type_csr%ISOPEN) THEN
7448         CLOSE trx_type_csr;
7449       END IF;
7450 
7451       IF (set_of_books_csr%ISOPEN) THEN
7452         CLOSE set_of_books_csr;
7453       END IF;
7454       -- Daily Interest calculation conc. program does not use savepoint. Delete the streams/Trx
7455       IF (p_process_flag = 'DAILY_INTEREST') THEN
7456         IF (l_strm_element_created = OKL_API.G_TRUE) THEN
7457           OKL_STREAMS_PUB.delete_stream_elements(
7458               p_api_version   => 1.0,
7459               p_init_msg_list => OKC_API.G_FALSE,
7460               x_return_status => x_return_status,
7461               x_msg_count     => x_msg_count,
7462               x_msg_data      => x_msg_data,
7463               p_selv_rec      => lx_selv_rec);
7464         END IF;
7465         IF (l_stream_created = OKL_API.G_TRUE) THEN
7466           OKL_STREAMS_PUB.delete_streams(
7467               p_api_version   => 1.0,
7468               p_init_msg_list => OKC_API.G_FALSE,
7469               x_return_status => x_return_status,
7470               x_msg_count     => x_msg_count,
7471               x_msg_data      => x_msg_data,
7472               p_stmv_rec      => lx_stmv_rec);
7473         END IF;
7474 
7475         IF (l_okl_trx_created = OKL_API.G_TRUE) THEN
7476           OKL_TRX_CONTRACTS_PUB.delete_trx_contracts(
7477               p_api_version   => 1.0,
7478               p_init_msg_list => OKC_API.G_FALSE,
7479               x_return_status => x_return_status,
7480               x_msg_count     => x_msg_count,
7481               x_msg_data      => x_msg_data,
7482               p_tcnv_rec      => l_trxH_out_rec);
7483         END IF;
7484 
7485       END IF;
7486       x_return_status := OKL_API.G_RET_STS_ERROR;
7487 
7488     WHEN OTHERS THEN
7489       print_error_message('Exception raised in procedure CREATE_STREAM_INVOICE');
7490       IF (stream_csr%ISOPEN) THEN
7491         CLOSE stream_csr;
7492       END IF;
7493 
7494       IF (trx_type_csr%ISOPEN) THEN
7495         CLOSE trx_type_csr;
7496       END IF;
7497 
7498       IF (set_of_books_csr%ISOPEN) THEN
7499         CLOSE set_of_books_csr;
7500       END IF;
7501       -- Daily Interest calculation conc. program does not use savepoint. Delete the streams/Trx
7502       IF (p_process_flag = 'DAILY_INTEREST') THEN
7503         IF (l_strm_element_created = OKL_API.G_TRUE) THEN
7504           OKL_STREAMS_PUB.delete_stream_elements(
7505               p_api_version   => 1.0,
7506               p_init_msg_list => OKC_API.G_FALSE,
7507               x_return_status => x_return_status,
7508               x_msg_count     => x_msg_count,
7509               x_msg_data      => x_msg_data,
7510               p_selv_rec      => lx_selv_rec);
7511         END IF;
7512         IF (l_stream_created = OKL_API.G_TRUE) THEN
7513           OKL_STREAMS_PUB.delete_streams(
7514               p_api_version   => 1.0,
7515               p_init_msg_list => OKC_API.G_FALSE,
7516               x_return_status => x_return_status,
7517               x_msg_count     => x_msg_count,
7518               x_msg_data      => x_msg_data,
7519               p_stmv_rec      => lx_stmv_rec);
7520         END IF;
7521 
7522         IF (l_okl_trx_created = OKL_API.G_TRUE) THEN
7523           OKL_TRX_CONTRACTS_PUB.delete_trx_contracts(
7524               p_api_version   => 1.0,
7525               p_init_msg_list => OKC_API.G_FALSE,
7526               x_return_status => x_return_status,
7527               x_msg_count     => x_msg_count,
7528               x_msg_data      => x_msg_data,
7529               p_tcnv_rec      => l_trxH_out_rec);
7530         END IF;
7531 
7532       END IF;
7533 
7534       Okl_Api.SET_MESSAGE(
7535           p_app_name     => G_APP_NAME,
7536           p_msg_name     => G_UNEXPECTED_ERROR,
7537           p_token1       => G_SQLCODE_TOKEN,
7538           p_token1_value => SQLCODE,
7539           p_token2       => G_SQLERRM_TOKEN,
7540           p_token2_value => SQLERRM);
7541 
7542       x_return_status := OKL_API.G_RET_STS_ERROR;
7543 
7544   END Create_Stream_Invoice;
7545 
7546 ------------------------------------------------------------------------------
7547 
7548     -- Start of Comments
7549     -- Created By:       Ramesh Seela
7550     -- Procedure Name    UPD_VIR_PARAMS_WITH_INVOICE
7551     -- Description:      This procedure is called by Variable Interest Calculation for Loans
7552     --                   Inputs :
7553     --                   Output : Interest Calculated
7554     -- Dependencies:
7555     -- Parameters:       Start Date, End Date, Interest Rate Range.
7556     -- Version:          1.0
7557     -- End of Comments
7558 
7559   ------------------------------------------------------------------------------
7560   Procedure upd_vir_params_with_invoice (
7561             p_api_version        IN  NUMBER,
7562             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
7563             x_return_status      OUT NOCOPY VARCHAR2,
7564             x_msg_count          OUT NOCOPY NUMBER,
7565             x_msg_data           OUT NOCOPY VARCHAR2,
7566             p_source_id          IN  NUMBER,
7567             p_vir_tbl            IN  vir_tbl_type,
7568             x_vir_tbl            OUT NOCOPY vir_tbl_type) IS
7569 
7570   l_api_name                  CONSTANT    VARCHAR2(30) := 'UPD_VIR_PARAMS_WITH_INVOICE';
7571   l_api_version               CONSTANT    NUMBER       := 1.0;
7572   l_index                     NUMBER := 0;
7573 
7574   BEGIN
7575     x_return_status               := OKL_API.G_RET_STS_SUCCESS;
7576     x_vir_tbl                    := p_vir_tbl;
7577 
7578     print_debug('Executing procedure UPD_VIR_PARAMS_WITH_INVOICE using following parameters : ');
7579     print_debug(' p_source_id : '|| p_source_id );
7580     print_debug(' g_vir_tbl_counter : '|| g_vir_tbl_counter );
7581     -- 5034946
7582     IF (NVL(g_vir_tbl_counter,0) > 0 ) THEN
7583       FOR l_index in 1 .. g_vir_tbl_counter
7584       LOOP
7585         x_vir_tbl(l_index).source_id := p_source_id;
7586       END LOOP;
7587     END IF;
7588 
7589  EXCEPTION
7590 
7591      WHEN OTHERS THEN
7592        print_error_message('Exception raised in procedure UPD_VIR_PARAMS_WITH_INVOICE');
7593         x_return_status := OKL_API.G_RET_STS_ERROR;
7594         Okl_Api.SET_MESSAGE(
7595             p_app_name     => G_APP_NAME,
7596             p_msg_name     => G_UNEXPECTED_ERROR,
7597             p_token1       => G_SQLCODE_TOKEN,
7598             p_token1_value => SQLCODE,
7599             p_token2       => G_SQLERRM_TOKEN,
7600             p_token2_value => SQLERRM);
7601 
7602   END upd_vir_params_with_invoice;
7603 
7604 ------------------------------------------------------------------------------
7605     -- Start of Comments
7606     -- Created By:       Ramesh Seela
7607     -- Procedure Name    print_g_vir_tbl
7608     -- Description:      This procedure prints all the records in the PL/SQL table g_vir_tbl
7609     --
7610     -- Dependencies:
7611     -- Parameters:       .
7612     -- Version:          1.0
7613     -- End of Comments
7614 
7615 ------------------------------------------------------------------------------
7616 
7617   PROCEDURE print_vir_tbl ( p_vir_tbl IN  vir_tbl_type) IS
7618 
7619   l_rec_count    NUMBER;
7620   l_index        NUMBER;
7621   l_counter      NUMBER := 0;
7622   BEGIN
7623        l_rec_count      := p_vir_tbl.COUNT;
7624        IF (l_rec_count > 0) THEN
7625           l_index          := p_vir_tbl.FIRST;
7626           print_debug('VIR Table : ');
7627        ELSE
7628           print_debug('No records exist in the table');
7629        END IF;
7630        FOR l_vir_tbl_counter in 1 .. l_rec_count
7631        LOOP
7632           l_counter     := l_counter + 1;
7633           print_debug( 'Record Number : '||l_counter);
7634 		  print_debug( 'id : '||p_vir_tbl(l_index).id );
7635 		  print_debug( 'khr_id : '||p_vir_tbl(l_index).khr_id);
7636           print_debug( 'source_table : '|| p_vir_tbl(l_index).source_table);
7637           print_debug( 'source_id : '|| p_vir_tbl(l_index).source_id);
7638           print_debug( 'interest_rate : '|| p_vir_tbl(l_index).interest_rate);
7639           print_debug( 'interest_calc_start_date : '|| p_vir_tbl(l_index).interest_calc_start_date);
7640           print_debug( 'interest_calc_end_date : '|| p_vir_tbl(l_index).interest_calc_end_date);
7641           print_debug( 'calc_method_code : '|| p_vir_tbl(l_index).calc_method_code);
7642           print_debug( 'principal_balance : '|| p_vir_tbl(l_index).principal_balance);
7643           print_debug( 'valid_yn : '|| p_vir_tbl(l_index).valid_yn);
7644           print_debug( 'Object_Version_Number : '|| p_vir_tbl(l_index).Object_Version_Number);
7645           print_debug( 'Org ID : '|| p_vir_tbl(l_index).Org_id);
7646           print_debug( 'request ID : '|| p_vir_tbl(l_index).request_id);
7647           print_debug( 'Program Application ID : '|| p_vir_tbl(l_index).program_application_id);
7648           print_debug( 'program ID : '|| p_vir_tbl(l_index).program_id);
7649           print_debug( 'Program Update date : '|| p_vir_tbl(l_index).program_update_date);
7650           print_debug( 'attribute category : '|| p_vir_tbl(l_index).attribute_category);
7651           print_debug( 'attribute1 : '|| p_vir_tbl(l_index).attribute1);
7652           print_debug( 'attribute2 : '|| p_vir_tbl(l_index).attribute2);
7653           print_debug( 'attribute3 : '|| p_vir_tbl(l_index).attribute3);
7654           print_debug( 'attribute4 : '|| p_vir_tbl(l_index).attribute4);
7655           print_debug( 'attribute5 : '|| p_vir_tbl(l_index).attribute5);
7656           print_debug( 'attribute6 : '|| p_vir_tbl(l_index).attribute6);
7657           print_debug( 'attribute7 : '|| p_vir_tbl(l_index).attribute7);
7658           print_debug( 'attribute8 : '|| p_vir_tbl(l_index).attribute8);
7659           print_debug( 'attribute9 : '|| p_vir_tbl(l_index).attribute9);
7660           print_debug( 'attribute10 : '|| p_vir_tbl(l_index).attribute10);
7661           print_debug( 'attribute11 : '|| p_vir_tbl(l_index).attribute11);
7662           print_debug( 'attribute12 : '|| p_vir_tbl(l_index).attribute12);
7663           print_debug( 'attribute13 : '|| p_vir_tbl(l_index).attribute13);
7664           print_debug( 'attribute14 : '|| p_vir_tbl(l_index).attribute14);
7665           print_debug( 'attribute15 : '|| p_vir_tbl(l_index).attribute15);
7666           print_debug( 'created_by : '|| p_vir_tbl(l_index).created_by);
7667           print_debug( 'creation_date : '|| p_vir_tbl(l_index).creation_date);
7668           print_debug( 'last_updated_by : '|| p_vir_tbl(l_index).last_updated_by);
7669           print_debug( 'last_update_date : '|| p_vir_tbl(l_index).last_update_date);
7670           print_debug( 'last_update_login : '|| p_vir_tbl(l_index).last_update_login);
7671           print_debug( 'interest_amt : '|| p_vir_tbl(l_index).interest_amt);
7672           print_debug( 'interest_calc_days : '|| p_vir_tbl(l_index).interest_calc_days);
7673           l_index       := p_vir_tbl.NEXT(l_index);
7674        END LOOP;
7675   EXCEPTION
7676      WHEN OTHERS THEN
7677        print_error_message('Exception raised in procedure PRINT_VIR_TBL');
7678        Okl_Api.SET_MESSAGE(
7679                p_app_name     => G_APP_NAME,
7680                p_msg_name     => G_UNEXPECTED_ERROR,
7681                p_token1       => G_SQLCODE_TOKEN,
7682                p_token1_value => SQLCODE,
7683                p_token2       => G_SQLERRM_TOKEN,
7684                p_token2_value => SQLERRM);
7685   END;
7686 
7687 ------------------------------------------------------------------------------
7688 
7689     -- Start of Comments
7690     -- Created By:       Ramesh Seela
7691     -- Procedure Name    POPULATE_VIR_PARAMS
7692     -- Description:      This procedure is called by Variable Interest Calculation for Loans
7693     --                   Inputs :
7694     --                   Output : Interest Calculated
7695     -- Dependencies:
7696     -- Parameters:       Start Date, End Date, Interest Rate Range.
7697     -- Version:          1.0
7698     -- End of Comments
7699 
7700   ------------------------------------------------------------------------------
7701   Procedure populate_vir_params(
7702             p_api_version        IN  NUMBER,
7703             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
7704             x_return_status      OUT NOCOPY VARCHAR2,
7705             x_msg_count          OUT NOCOPY NUMBER,
7706             x_msg_data           OUT NOCOPY VARCHAR2,
7707             p_vir_tbl           IN  vir_tbl_type) IS
7708 
7709   l_api_name                  CONSTANT    VARCHAR2(30) := 'POPULATE_VIR_PARAMS';
7710   l_api_version               CONSTANT    NUMBER       := 1.0;
7711   l_index                     NUMBER := 0;
7712 
7713   BEGIN
7714     x_return_status               := OKL_API.G_RET_STS_SUCCESS;
7715 
7716     print_debug('Executing procedure POPULATE_VIR_PARAMS using following parameters : ');
7717     print_debug(' p_vir_tbl.count : '|| p_vir_tbl.COUNT );
7718     print_vir_tbl (p_vir_tbl);
7719 
7720     IF (p_vir_tbl.COUNT > 0) THEN
7721   	   FORALL l_index in p_vir_tbl.FIRST .. p_vir_tbl.LAST
7722   	   save exceptions
7723        INSERT INTO okl_var_int_params VALUES p_vir_tbl(l_index);
7724 
7725         print_debug ('Exception count : '|| sql%bulk_exceptions.count);
7726        IF sql%bulk_exceptions.count > 0 then
7727           for i in 1..sql%bulk_exceptions.count loop
7728               print_debug('while fetching, error ' || i || ' occurred during '||
7729                   'iteration ' || sql%bulk_exceptions(i).error_index);
7730               print_debug('oracle error is ' ||
7731                   sqlerrm(sql%bulk_exceptions(i).error_code));
7732 
7733           end loop;
7734         end if;
7735        print_debug ('No. of records inserted : '|| SQL%rowcount);
7736 
7737     END IF;
7738 
7739  EXCEPTION
7740      WHEN OTHERS THEN
7741        print_error_message('Exception raised in procedure POPULATE_VIR_PARAMS');
7742        print_debug ('Exception during bulk insert');
7743        print_debug ('Exception count : '|| sql%bulk_exceptions.count);
7744        IF sql%bulk_exceptions.count > 0 then
7745           for i in 1..sql%bulk_exceptions.count loop
7746               print_debug('while fetching, error ' || i || ' occurred during '||
7747                   'iteration ' || sql%bulk_exceptions(i).error_index);
7748               print_debug('oracle error is ' ||
7749                   sqlerrm(sql%bulk_exceptions(i).error_code));
7750 
7751           end loop;
7752        END IF;
7753 
7754        x_return_status := OKL_API.G_RET_STS_ERROR;
7755        Okl_Api.SET_MESSAGE(
7756            p_app_name     => G_APP_NAME,
7757            p_msg_name     => G_UNEXPECTED_ERROR,
7758            p_token1       => G_SQLCODE_TOKEN,
7759            p_token1_value => SQLCODE,
7760            p_token2       => G_SQLERRM_TOKEN,
7761            p_token2_value => SQLERRM);
7762 
7763   END populate_vir_params;
7764 
7765 ------------------------------------------------------------------------------
7766 
7767   FUNCTION calculate_from_khr_start_date(p_khr_id IN NUMBER,
7768             p_from_date IN DATE) RETURN VARCHAR2 IS
7769 
7770   l_return_value varchar2(10) := 'N';
7771 
7772   --checks for online rebook
7773   CURSOR l_rebook_csr(cp_khr_id NUMBER) IS
7774   SELECT 'Y' return_value
7775   FROM   okc_k_headers_b chrb,
7776          okc_k_headers_b chrb2,
7777           okl_trx_contracts ktrx
7778   WHERE  ktrx.khr_id_old = chrb.id
7779   AND    ktrx.tsu_code = 'PROCESSED'
7780   AND    ktrx.rbr_code IS NOT NULL
7781   AND    ktrx.tcn_type = 'TRBK'
7782   --rkuttiya added for 12.1.1 Multi GAAP
7783   AND    ktrx.representation_type = 'PRIMARY'
7784   --
7785   AND    chrb.id = cp_khr_id
7786   AND    chrb2.orig_system_source_code = 'OKL_REBOOK'
7787   AND    chrb2.id = ktrx.khr_id_new
7788   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
7789                     WHERE vpb.khr_id = chrb.id
7790                     AND   vpb.source_table = 'OKL_TRX_CONTRACTS'
7791                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
7792                     AND   vpb.source_id = ktrx.id);
7793 
7794   --checks if newly created Daily Interest - Principal stream elements exist
7795   --prior to date passed
7796   CURSOR l_daily_int_strm_csr(cp_khr_id NUMBER, cp_from_date DATE) IS
7797   SELECT 'Y' return_value
7798   FROM okl_streams     stm,
7799        okl_strm_type_b sty,
7800        okl_strm_elements sel
7801   WHERE	stm.khr_id = cp_khr_id
7802   AND	  stm.sty_id = sty.id
7803   AND   sty.stream_type_purpose = 'DAILY_INTEREST_PRINCIPAL'
7804   AND	  stm.id = sel.stm_id
7805   AND   sel.stream_element_date < cp_from_date
7806   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
7807                     WHERE vpb.khr_id = stm.khr_id
7808                     AND   vpb.source_table = 'OKL_STRM_ELEMENTS_V'
7809                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
7810                     AND   vpb.source_id = sel.id);
7811 
7812   --checks if newly created Principal Catchup stream elements exist
7813   --prior to date passed
7814   CURSOR l_prin_catch_strm_csr(cp_khr_id NUMBER, cp_from_date DATE) IS
7815   SELECT 'Y' return_value
7816   FROM okl_streams     stm,
7817        okl_strm_type_b sty,
7818        okl_strm_elements sel
7819   WHERE	stm.khr_id = cp_khr_id
7820   AND	  stm.sty_id = sty.id
7821   AND   sty.stream_type_purpose = 'PRINCIPAL_CATCHUP'
7822   AND	  stm.id = sel.stm_id
7823   AND   sel.stream_element_date < cp_from_date
7824   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
7825                     WHERE vpb.khr_id = stm.khr_id
7826                     AND   vpb.source_table = 'OKL_STRM_ELEMENTS_V'
7827                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
7828                     AND   vpb.source_id = sel.id);
7829 
7830   --checks if newly created Receipt Application to PRINCIPAL_PAYMENT, UNSCHEDULED_PRINCIPAL_PAYMENT exist
7831   --prior to date passed
7832  -- Begin - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
7833 --Bug# 6819044: Fetch receipt applications correctly when
7834 --              invoices have lines from multiple contracts
7835 CURSOR l_rcpt_app_csr(cp_khr_id NUMBER, cp_from_date DATE) IS
7836   SELECT 'Y' return_value
7837   FROM  okl_txd_ar_ln_dtls_b tld
7838        ,ra_customer_trx_lines_all ractrl
7839        ,okl_txl_ar_inv_lns_b til
7840        ,okl_trx_ar_invoices_b tai
7841        ,ar_payment_schedules_all aps
7842        ,ar_receivable_applications_all raa
7843        ,ar_cash_receipts_all cra
7844        ,okl_strm_type_b sty
7845   WHERE  tai.trx_status_code = 'PROCESSED'
7846   AND    tai.khr_id = cp_khr_id
7847   AND    tld.khr_id = cp_khr_id
7848   AND    ractrl.customer_trx_id = aps.customer_trx_id
7849   AND    raa.applied_customer_trx_id = aps.customer_trx_id
7850   AND    aps.class = 'INV'
7851   AND    raa.application_type IN ('CASH','CM')
7852   AND    raa.status = 'APP'
7853   AND    cra.receipt_date < cp_from_date
7854   AND    raa.cash_receipt_id = cra.cash_receipt_id
7855   AND    tld.sty_id = sty.id
7856   AND    sty.stream_type_purpose IN ('PRINCIPAL_PAYMENT', 'UNSCHEDULED_PRINCIPAL_PAYMENT')
7857   AND    to_char(tld.id) = ractrl.interface_line_attribute14
7858   AND    tld.til_id_details = til.id
7859   AND    til.tai_id = tai.id
7860   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
7861                     WHERE vpb.khr_id = tld.khr_id
7862                     AND   vpb.source_table = 'AR_RECEIVABLE_APPLICATIONS_ALL'
7863                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
7864                     AND   vpb.source_id = raa.receivable_application_id)
7865   AND    EXISTS (SELECT 1
7866                  FROM ar_distributions_all ad
7867                  WHERE raa.receivable_application_id = ad.source_id
7868                  AND ad.source_table = 'RA'
7869                  AND (ad.ref_customer_trx_Line_Id IS NULL OR
7870                       ad.ref_customer_trx_Line_Id = ractrl.customer_trx_line_id));
7871 -- End - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
7872 
7873   --checks if newly created Borrower Payment exist
7874   --prior to date passed
7875   -- sjalasut, modified the cursor to have khr_id be passed from okl_txl_ap_inv_lns_all_b
7876   CURSOR l_borrow_payment_csr(cp_khr_id NUMBER, cp_from_date DATE) IS
7877   SELECT 'Y' return_value
7878   FROM ap_invoices_all ap_inv,
7879        okl_trx_ap_invoices_v okl_inv,
7880        ap_invoice_payment_history_v iph
7881       ,okl_cnsld_ap_invs_all cnsld
7882       ,okl_txl_ap_inv_lns_all_b okl_inv_ln
7883       ,fnd_application fnd_app
7884     WHERE okl_inv.id = okl_inv_ln.tap_id
7885       AND okl_inv_ln.khr_id = cp_khr_id
7886       AND ap_inv.application_id = fnd_app.application_id
7887       AND fnd_app.application_short_name = 'OKL'
7888       AND okl_inv_ln.cnsld_ap_inv_id = cnsld.cnsld_ap_inv_id
7889       AND cnsld.cnsld_ap_inv_id = to_number(ap_inv.reference_key1)
7890       AND okl_inv.funding_type_code = 'BORROWER_PAYMENT'
7891       AND ap_inv.invoice_id = iph.invoice_id
7892       AND iph.check_date < cp_from_date
7893       AND NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
7894                     WHERE vpb.khr_id = okl_inv_ln.khr_id
7895                     AND   vpb.source_table = 'AP_INVOICE_PAYMENTS_ALL'
7896                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
7897                     AND   vpb.source_id = iph.invoice_payment_id);
7898 
7899   --checks if newly created records for okl_contract_balances which have the asset balances
7900   --as of the partial termination date exist prior to date passed
7901   CURSOR l_partial_term_csr(cp_khr_id NUMBER, cp_from_date DATE) IS
7902   SELECT 'Y' return_value
7903   FROM   okl_contract_balances ocb
7904   WHERE  ocb.khr_id = cp_khr_id
7905   AND    ocb.termination_date < cp_from_date
7906   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
7907                     WHERE vpb.khr_id = ocb.khr_id
7908                     AND   vpb.source_table = 'OKL_CONTRACT_BALANCES'
7909                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
7910                     AND   vpb.source_id = ocb.id);
7911 
7912   BEGIN
7913     print_debug('Executing function calculate_from_khr_start_date');
7914 
7915     print_debug('Before Checking for existence of Rebook Transactions');
7916     OPEN l_rebook_csr(p_khr_id);
7917     FETCH l_rebook_csr INTO l_return_value;
7918     CLOSE l_rebook_csr;
7919     print_debug('After Checking for existence of Rebook Transactions');
7920 
7921 
7922     IF (G_DEAL_TYPE = 'LOAN') THEN
7923       IF (G_INTEREST_CALCULATION_BASIS = G_INT_CALC_BASIS_FLOAT) THEN
7924         IF (G_REVENUE_RECOGNITION_METHOD = 'ACTUAL') THEN
7925           print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
7926           print_debug('Before Checking for existence of Daily Interest streams');
7927           IF (NVL(l_return_value, 'N') = 'N') THEN
7928             OPEN l_daily_int_strm_csr(p_khr_id, p_from_date);
7929             FETCH l_daily_int_strm_csr INTO l_return_value;
7930             CLOSE l_daily_int_strm_csr;
7931           END IF;
7932           print_debug('After Checking for existence of Daily Interest streams');
7933         ELSE
7934           --rev rec method = ESTIMATED AND BILLED
7935           print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
7936           print_debug('Before Checking for existence of Receipt Applications');
7937           IF (NVL(l_return_value, 'N') = 'N') THEN
7938             OPEN l_rcpt_app_csr(p_khr_id, p_from_date);
7939             FETCH l_rcpt_app_csr INTO l_return_value;
7940             CLOSE l_rcpt_app_csr;
7941           END IF;
7942           print_debug('After Checking for existence of Receipt Applications');
7943 
7944           print_debug('Before Checking for existence of Early Termination records');
7945           IF (NVL(l_return_value, 'N') = 'N') THEN
7946             OPEN l_partial_term_csr(p_khr_id, p_from_date);
7947             FETCH l_partial_term_csr INTO l_return_value;
7948             CLOSE l_partial_term_csr;
7949           END IF;
7950           print_debug('After Checking for existence of Early Termination records');
7951         END IF;
7952       ELSIF (G_INTEREST_CALCULATION_BASIS = G_INT_CALC_BASIS_CATCHUP) THEN
7953           print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
7954           print_debug('Before Checking for existence of Receipt Applications');
7955           IF (NVL(l_return_value, 'N') = 'N') THEN
7956             OPEN l_rcpt_app_csr(p_khr_id, p_from_date);
7957             FETCH l_rcpt_app_csr INTO l_return_value;
7958             CLOSE l_rcpt_app_csr;
7959           END IF;
7960           print_debug('After Checking for existence of Receipt Applications');
7961 
7962           print_debug('Before Checking for existence of Early Termination records');
7963           IF (NVL(l_return_value, 'N') = 'N') THEN
7964             OPEN l_partial_term_csr(p_khr_id, p_from_date);
7965             FETCH l_partial_term_csr INTO l_return_value;
7966             CLOSE l_partial_term_csr;
7967           END IF;
7968           print_debug('After Checking for existence of Early Termination records');
7969 
7970           print_debug('Before Checking for existence of Principal Catchup streams');
7971           IF (NVL(l_return_value, 'N') = 'N') THEN
7972             OPEN l_prin_catch_strm_csr(p_khr_id, p_from_date);
7973             FETCH l_prin_catch_strm_csr INTO l_return_value;
7974             CLOSE l_prin_catch_strm_csr;
7975           END IF;
7976           print_debug('After Checking for existence of Principal Catchup streams');
7977 
7978           print_debug('Before Checking for existence of Catchup settlement code');
7979           IF (NVL(l_return_value, 'N') = 'N') THEN
7980             IF (G_CATCHUP_SETTLEMENT_CODE = 'NOT_ADJUST') THEN
7981               l_return_value := 'Y';
7982             END IF;
7983           END IF;
7984           print_debug('After Checking for existence of Catchup settlement code');
7985 
7986       END IF;
7987     ELSIF (G_DEAL_TYPE ='LOAN-REVOLVING') THEN
7988       IF (G_REVENUE_RECOGNITION_METHOD = 'ACTUAL') THEN
7989         print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
7990 
7991         print_debug('Before Checking for existence of Borrower payments');
7992         IF (NVL(l_return_value, 'N') = 'N') THEN
7993           OPEN l_borrow_payment_csr(p_khr_id, p_from_date);
7994           FETCH l_borrow_payment_csr INTO l_return_value;
7995           CLOSE l_borrow_payment_csr;
7996         END IF;
7997         print_debug('After Checking for existence of Borrower payments');
7998 
7999         print_debug('Before Checking for existence of Daily Interest streams');
8000         IF (NVL(l_return_value, 'N') = 'N') THEN
8001           OPEN l_daily_int_strm_csr(p_khr_id, p_from_date);
8002           FETCH l_daily_int_strm_csr INTO l_return_value;
8003           CLOSE l_daily_int_strm_csr;
8004         END IF;
8005         print_debug('After Checking for existence of Daily Interest streams');
8006       ELSE
8007         --rev rec method = ESTIMATED AND BILLED
8008         print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
8009         print_debug('Before Checking for existence of Borrower payments');
8010         IF (NVL(l_return_value, 'N') = 'N') THEN
8011           OPEN l_borrow_payment_csr(p_khr_id, p_from_date);
8012           FETCH l_borrow_payment_csr INTO l_return_value;
8013           CLOSE l_borrow_payment_csr;
8014         END IF;
8015         print_debug('After Checking for existence of Borrower payments');
8016 
8017         print_debug('Before Checking for existence of Receipt Applications');
8018         IF (NVL(l_return_value, 'N') = 'N') THEN
8019           OPEN l_rcpt_app_csr(p_khr_id, p_from_date);
8020           FETCH l_rcpt_app_csr INTO l_return_value;
8021           CLOSE l_rcpt_app_csr;
8022         END IF;
8023         print_debug('After Checking for existence of Receipt Applications');
8024       END IF;
8025     END IF;
8026     return NVL(l_return_value, 'N');
8027   EXCEPTION
8028     WHEN OTHERS THEN
8029       return l_return_value;
8030   END calculate_from_khr_start_date;
8031 
8032 ------------------------------------------------------------------------------
8033     -- Start of Comments
8034     -- Created By:       pgomes
8035     -- Procedure Name    populate_txns
8036     -- Description:      This procedure populates g_vpb_tbl with Daily Interest
8037     --                   stream id, receipt app id, EOT id, Borrower payment id
8038     -- Dependencies:
8039     -- Parameters:       .
8040     -- Version:          1.0
8041     -- End of Comments
8042 
8043 ------------------------------------------------------------------------------
8044 
8045   PROCEDURE populate_txns ( p_api_version        IN  NUMBER,
8046             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
8047             p_khr_id             IN NUMBER,
8048             p_from_date          IN DATE,
8049             p_to_date            IN DATE,
8050             x_return_status      OUT NOCOPY VARCHAR2,
8051             x_msg_count          OUT NOCOPY NUMBER,
8052             x_msg_data           OUT NOCOPY VARCHAR2) IS
8053 
8054   l_api_name                  CONSTANT    VARCHAR2(30) := 'populate_txns';
8055   l_api_version               CONSTANT    NUMBER       := 1.0;
8056   L_FETCH_SIZE                CONSTANT    NUMBER := 100;
8057   l_source_id                 OKL_VAR_PRINCIPAL_BAL_TXN.source_id%TYPE;
8058   l_source_table              OKL_VAR_PRINCIPAL_BAL_TXN.source_table%TYPE;
8059 
8060   --get the id's of Rebook Transactions
8061   CURSOR l_rebook_csr(cp_khr_id NUMBER) IS
8062   SELECT ktrx.id source_id
8063         ,'OKL_TRX_CONTRACTS' source_table
8064   FROM   okc_k_headers_b chrb,
8065          okc_k_headers_b chrb2,
8066          okl_trx_contracts ktrx
8067   WHERE  ktrx.khr_id_old = chrb.id
8068   AND    ktrx.tsu_code = 'PROCESSED'
8069   AND    ktrx.rbr_code IS NOT NULL
8070   AND    ktrx.tcn_type = 'TRBK'
8071   --rkuttiya added for 12.1.1 Multi GAAP
8072  AND     ktrx.representation_type = 'PRIMARY'
8073   --
8074   AND    chrb.id = cp_khr_id
8075   AND    chrb2.orig_system_source_code = 'OKL_REBOOK'
8076   AND    chrb2.id = ktrx.khr_id_new
8077   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
8078                     WHERE vpb.khr_id = chrb.id
8079                     AND   vpb.source_table = 'OKL_TRX_CONTRACTS'
8080                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
8081                     AND   vpb.source_id = ktrx.id);
8082 
8083   --get the id's of Daily Interest - Principal stream elements
8084   CURSOR l_daily_int_strm_csr(cp_khr_id NUMBER, cp_from_date DATE, cp_to_date DATE) IS
8085   SELECT sel.id source_id
8086   , 'OKL_STRM_ELEMENTS_V' source_table
8087   FROM okl_streams     stm,
8088        okl_strm_type_b sty,
8089        okl_strm_elements sel
8090   WHERE	stm.khr_id = cp_khr_id
8091   AND	  stm.sty_id = sty.id
8092   AND   sty.stream_type_purpose = 'DAILY_INTEREST_PRINCIPAL'
8093   AND	  stm.id = sel.stm_id
8094   --AND   sel.stream_element_date BETWEEN cp_from_date AND cp_to_date
8095   AND   sel.stream_element_date <= cp_to_date
8096   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
8097                     WHERE vpb.khr_id = stm.khr_id
8098                     AND   vpb.source_table = 'OKL_STRM_ELEMENTS_V'
8099                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
8100                     AND   vpb.source_id = sel.id);
8101 
8102   --get the id's of Principal Catchup stream elements
8103   CURSOR l_prin_catch_strm_csr(cp_khr_id NUMBER, cp_from_date DATE, cp_to_date DATE) IS
8104   SELECT sel.id source_id
8105   , 'OKL_STRM_ELEMENTS_V' source_table
8106   FROM okl_streams     stm,
8107        okl_strm_type_b sty,
8108        okl_strm_elements sel
8109   WHERE	stm.khr_id = cp_khr_id
8110   AND	  stm.sty_id = sty.id
8111   AND   sty.stream_type_purpose = 'PRINCIPAL_CATCHUP'
8112   AND	  stm.id = sel.stm_id
8113   --AND   sel.stream_element_date BETWEEN cp_from_date AND cp_to_date
8114   AND   sel.stream_element_date <= cp_to_date
8115   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
8116                     WHERE vpb.khr_id = stm.khr_id
8117                     AND   vpb.source_table = 'OKL_STRM_ELEMENTS_V'
8118                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
8119                     AND   vpb.source_id = sel.id);
8120 
8121   --get the id's of Receipt Application to PRINCIPAL_PAYMENT, UNSCHEDULED_PRINCIPAL_PAYMENT
8122 --Begin - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
8123   --Bug# 6819044: Fetch receipt applications correctly when
8124   --              invoices have lines from multiple contracts
8125   --Bug# 7007130: Fetch unique receipt application ids for
8126   --              a contract
8127   CURSOR l_rcpt_app_csr(cp_khr_id NUMBER, cp_from_date DATE, cp_to_date DATE) IS
8128   SELECT DISTINCT raa.receivable_application_id source_id
8129   , 'AR_RECEIVABLE_APPLICATIONS_ALL' source_table
8130   FROM  okl_txd_ar_ln_dtls_b tld
8131        ,ra_customer_trx_lines_all ractrl
8132        ,okl_txl_ar_inv_lns_b til
8133        ,okl_trx_ar_invoices_b tai
8134        ,ar_payment_schedules_all aps
8135        ,ar_receivable_applications_all raa
8136        ,ar_cash_receipts_all cra
8137        ,okl_strm_type_b sty
8138   WHERE  tai.trx_status_code = 'PROCESSED'
8139   AND    tai.khr_id = cp_khr_id
8140   AND    tld.khr_id = cp_khr_id
8141   AND    ractrl.customer_trx_id  = aps.customer_trx_id
8142   AND    raa.applied_customer_trx_id = aps.customer_trx_id
8143   AND    aps.class = 'INV'
8144   AND    raa.application_type IN ('CASH','CM')
8145   AND    raa.status = 'APP'
8146   AND    cra.receipt_date <= cp_to_date
8147   AND    raa.cash_receipt_id = cra.cash_receipt_id
8148   AND    tld.sty_id  = sty.id
8149   AND    sty.stream_type_purpose IN ('PRINCIPAL_PAYMENT', 'UNSCHEDULED_PRINCIPAL_PAYMENT')
8150   AND    to_char(tld.id) = ractrl.interface_line_attribute14
8151   AND    tld.til_id_details = til.id
8152   AND    til.tai_id = tai.id
8153   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
8154                     WHERE vpb.khr_id = tld.khr_id
8155                     AND   vpb.source_table = 'AR_RECEIVABLE_APPLICATIONS_ALL'
8156                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
8157                     AND   vpb.source_id = raa.receivable_application_id)
8158   AND   EXISTS (SELECT 1
8159                 FROM ar_distributions_all ad
8160                 WHERE raa.receivable_application_id = ad.source_id
8161                 AND ad.source_table = 'RA'
8162                 AND (ad.ref_customer_trx_Line_Id IS NULL OR
8163                      ad.ref_customer_trx_Line_Id = ractrl.customer_trx_line_id));
8164 
8165 -- End - Billing Inline changes - Bug#5898792 - varangan - 23/2/2007
8166 
8167   --get the id's of Borrower Payment
8168   CURSOR l_borrow_payment_csr(cp_khr_id NUMBER, cp_from_date DATE, cp_to_date DATE) IS
8169   SELECT iph.invoice_payment_id source_id
8170   , 'AP_INVOICE_PAYMENTS_ALL' source_table
8171   FROM ap_invoices_all ap_inv,
8172        okl_trx_ap_invoices_v okl_inv,
8173        ap_invoice_payment_history_v iph
8174       ,okl_cnsld_ap_invs_all cnsld
8175       ,okl_txl_ap_inv_lns_all_b okl_inv_ln
8176       ,fnd_application fnd_app
8177  WHERE okl_inv.id = okl_inv_ln.tap_id
8178    AND okl_inv_ln.khr_id = cp_khr_id
8179    AND ap_inv.application_id = fnd_app.application_id
8180    AND fnd_app.application_short_name = 'OKL'
8181    AND okl_inv_ln.cnsld_ap_inv_id = cnsld.cnsld_ap_inv_id
8182    AND cnsld.cnsld_ap_inv_id = to_number(ap_inv.reference_key1)
8183    AND   okl_inv.funding_type_code = 'BORROWER_PAYMENT'
8184    AND   ap_inv.invoice_id = iph.invoice_id
8185   --AND   iph.check_date BETWEEN cp_from_date AND cp_to_date
8186    AND   iph.check_date <= cp_to_date
8187    AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
8188                     WHERE vpb.khr_id = okl_inv_ln.khr_id
8189                     AND   vpb.source_table = 'AP_INVOICE_PAYMENTS_ALL'
8190                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
8191                     AND   vpb.source_id = iph.invoice_payment_id);
8192 
8193   --get the id's of records from okl_contract_balances which have the asset balances
8194   --as of the partial termination date
8195   CURSOR l_partial_term_csr(cp_khr_id NUMBER, cp_from_date DATE, cp_to_date DATE) IS
8196   SELECT ocb.id source_id
8197   , 'OKL_CONTRACT_BALANCES' source_table
8198   FROM   okl_contract_balances ocb
8199   WHERE  ocb.khr_id = cp_khr_id
8200   AND    ocb.termination_date BETWEEN cp_from_date AND cp_to_date
8201   AND   NOT EXISTS (select 1 FROM OKL_VAR_PRINCIPAL_BAL_TXN vpb
8202                     WHERE vpb.khr_id = ocb.khr_id
8203                     AND   vpb.source_table = 'OKL_CONTRACT_BALANCES'
8204                     AND   vpb.int_cal_process = 'VARIABLE_INTEREST'
8205                     AND   vpb.source_id = ocb.id);
8206 
8207   BEGIN
8208     x_return_status  := OKL_API.G_RET_STS_SUCCESS;
8209     print_debug('Executing procedure populate_txns');
8210 
8211     print_debug('Before fetching Rebook Transactions g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8212     OPEN l_rebook_csr(p_khr_id);
8213     LOOP
8214       --FETCH l_rebook_csr INTO g_vpb_tbl(g_vpb_tbl_counter).source_id, g_vpb_tbl(g_vpb_tbl_counter).source_table;
8215       l_source_id := NULL;
8216       l_source_table := NULL;
8217       FETCH l_rebook_csr INTO l_source_id, l_source_table;
8218       EXIT WHEN l_rebook_csr%NOTFOUND;
8219       g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8220       g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8221       g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8222       g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8223       g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8224       g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8225       g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8226       g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8227       g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8228       g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8229       g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8230       g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8231       g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8232       g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8233       g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8234       g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8235       g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8236       g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8237       g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8238       g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8239       g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8240       g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8241       g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8242       g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8243       g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8244       g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8245       g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8246       g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8247       g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8248       g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8249       g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8250       g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8251       g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8252     END LOOP;
8253     CLOSE l_rebook_csr;
8254     print_debug('After fetching Rebook Transactions g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8255 
8256     IF (G_DEAL_TYPE = 'LOAN') THEN
8257       IF (G_INTEREST_CALCULATION_BASIS = G_INT_CALC_BASIS_FLOAT) THEN
8258         IF (G_REVENUE_RECOGNITION_METHOD = 'ACTUAL') THEN
8259           print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
8260           print_debug('Before fetching Daily Interest streams g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8261           OPEN l_daily_int_strm_csr(p_khr_id, p_from_date, p_to_date);
8262           LOOP
8263             l_source_id := NULL;
8264             l_source_table := NULL;
8265             FETCH l_daily_int_strm_csr INTO l_source_id, l_source_table;
8266             EXIT WHEN l_daily_int_strm_csr%NOTFOUND;
8267             g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8268             g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8269             g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8270             g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8271             g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8272             g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8273             g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8274             g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8275             g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8276             g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8277             g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8278             g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8279             g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8280             g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8281             g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8282             g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8283             g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8284             g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8285             g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8286             g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8287             g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8288             g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8289             g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8290             g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8291             g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8292             g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8293             g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8294             g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8295             g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8296             g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8297             g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8298             g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8299             g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8300           END LOOP;
8301           CLOSE l_daily_int_strm_csr;
8302           print_debug('After fetching Daily Interest streams g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8303         ELSE
8304           --rev rec method = ESTIMATED AND BILLED
8305           IF (G_PRINCIPAL_BASIS_CODE = 'ACTUAL') THEN
8306             print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
8307             print_debug('Before fetching Receipt Applications g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8308             OPEN l_rcpt_app_csr(p_khr_id, p_from_date, p_to_date);
8309             LOOP
8310               l_source_id := NULL;
8311               l_source_table := NULL;
8312               FETCH l_rcpt_app_csr INTO l_source_id, l_source_table;
8313               EXIT WHEN l_rcpt_app_csr%NOTFOUND;
8314               g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8315               g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8316               g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8317               g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8318               g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8319               g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8320               g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8321               g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8322               g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8323               g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8324               g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8325               g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8326               g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8327               g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8328               g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8329               g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8330               g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8331               g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8332               g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8333               g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8334               g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8335               g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8336               g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8337               g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8338               g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8339               g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8340               g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8341               g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8342               g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8343               g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8344               g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8345               g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8346               g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8347             END LOOP;
8348             CLOSE l_rcpt_app_csr;
8349             print_debug('After fetching Receipt Applications g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8350 
8351             print_debug('Before fetching Early Termination records g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8352             OPEN l_partial_term_csr(p_khr_id, p_from_date, p_to_date);
8353             LOOP
8354               l_source_id := NULL;
8355               l_source_table := NULL;
8356               FETCH l_partial_term_csr INTO l_source_id, l_source_table;
8357               EXIT WHEN l_partial_term_csr%NOTFOUND;
8358               g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8359               g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8360               g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8361               g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8362               g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8363               g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8364               g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8365               g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8366               g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8367               g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8368               g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8369               g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8370               g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8371               g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8372               g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8373               g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8374               g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8375               g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8376               g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8377               g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8378               g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8379               g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8380               g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8381               g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8382               g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8383               g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8384               g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8385               g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8386               g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8387               g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8388               g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8389               g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8390               g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8391             END LOOP;
8392             CLOSE l_partial_term_csr;
8393             print_debug('After fetching Early Termination records g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8394           END IF;
8395         END IF;
8396       ELSIF (G_INTEREST_CALCULATION_BASIS = G_INT_CALC_BASIS_CATCHUP) THEN
8397           print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
8398           print_debug('Before fetching Receipt Applications g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8399           OPEN l_rcpt_app_csr(p_khr_id, p_from_date, p_to_date);
8400           LOOP
8401             l_source_id := NULL;
8402             l_source_table := NULL;
8403             FETCH l_rcpt_app_csr INTO l_source_id, l_source_table;
8404             EXIT WHEN l_rcpt_app_csr%NOTFOUND;
8405             g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8406             g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8407             g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8408             g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8409             g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8410             g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8411             g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8412             g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8413             g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8414             g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8415             g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8416             g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8417             g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8418             g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8419             g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8420             g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8421             g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8422             g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8423             g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8424             g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8425             g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8426             g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8427             g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8428             g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8429             g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8430             g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8431             g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8432             g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8433             g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8434             g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8435             g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8436             g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8437             g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8438           END LOOP;
8439           CLOSE l_rcpt_app_csr;
8440           print_debug('After fetching Receipt Applications g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8441 
8442           print_debug('Before fetching Early Termination records g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8443           OPEN l_partial_term_csr(p_khr_id, p_from_date, p_to_date);
8444           LOOP
8445             l_source_id := NULL;
8446             l_source_table := NULL;
8447             FETCH l_partial_term_csr INTO l_source_id, l_source_table;
8448             EXIT WHEN l_partial_term_csr%NOTFOUND;
8449             g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8450             g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8451             g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8452             g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8453             g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8454             g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8455             g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8456             g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8457             g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8458             g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8459             g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8460             g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8461             g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8462             g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8463             g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8464             g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8465             g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8466             g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8467             g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8468             g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8469             g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8470             g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8471             g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8472             g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8473             g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8474             g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8475             g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8476             g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8477             g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8478             g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8479             g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8480             g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8481             g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8482           END LOOP;
8483           CLOSE l_partial_term_csr;
8484           print_debug('After fetching Early Termination records g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8485 
8486           print_debug('Before fetching Principal Catchup streams g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8487           OPEN l_prin_catch_strm_csr(p_khr_id, p_from_date, p_to_date);
8488           LOOP
8489             l_source_id := NULL;
8490             l_source_table := NULL;
8491             FETCH l_prin_catch_strm_csr INTO l_source_id, l_source_table;
8492             EXIT WHEN l_prin_catch_strm_csr%NOTFOUND;
8493             g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8494             g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8495             g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8496             g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8497             g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8498             g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8499             g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8500             g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8501             g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8502             g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8503             g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8504             g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8505             g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8506             g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8507             g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8508             g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8509             g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8510             g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8511             g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8512             g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8513             g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8514             g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8515             g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8516             g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8517             g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8518             g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8519             g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8520             g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8521             g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8522             g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8523             g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8524             g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8525             g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8526           END LOOP;
8527           CLOSE l_prin_catch_strm_csr;
8528           print_debug('After fetching Principal Catchup streams g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8529       END IF;
8530     ELSIF (G_DEAL_TYPE ='LOAN-REVOLVING') THEN
8531       IF (G_REVENUE_RECOGNITION_METHOD = 'ACTUAL') THEN
8532         print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
8533         print_debug('Before fetching Borrower payments g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8534         OPEN l_borrow_payment_csr(p_khr_id, p_from_date, p_to_date);
8535         LOOP
8536           l_source_id := NULL;
8537           l_source_table := NULL;
8538           FETCH l_borrow_payment_csr INTO l_source_id, l_source_table;
8539           EXIT WHEN l_borrow_payment_csr%NOTFOUND;
8540           g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8541           g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8542           g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8543           g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8544           g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8545           g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8546           g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8547           g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8548           g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8549           g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8550           g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8551           g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8552           g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8553           g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8554           g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8555           g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8556           g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8557           g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8558           g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8559           g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8560           g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8561           g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8562           g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8563           g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8564           g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8565           g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8566           g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8567           g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8568           g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8569           g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8570           g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8571           g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8572           g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8573         END LOOP;
8574         CLOSE l_borrow_payment_csr;
8575         print_debug('After fetching Borrower payments g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8576 
8577         print_debug('Before fetching Daily Interest streams g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8578         OPEN l_daily_int_strm_csr(p_khr_id, p_from_date, p_to_date);
8579         LOOP
8580           l_source_id := NULL;
8581           l_source_table := NULL;
8582           FETCH l_daily_int_strm_csr INTO l_source_id, l_source_table;
8583           EXIT WHEN l_daily_int_strm_csr%NOTFOUND;
8584           g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8585           g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8586           g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8587           g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8588           g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8589           g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8590           g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8591           g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8592           g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8593           g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8594           g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8595           g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8596           g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8597           g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8598           g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8599           g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8600           g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8601           g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8602           g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8603           g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8604           g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8605           g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8606           g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8607           g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8608           g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8609           g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8610           g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8611           g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8612           g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8613           g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8614           g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8615           g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8616           g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8617         END LOOP;
8618         CLOSE l_daily_int_strm_csr;
8619         print_debug('After fetching Daily Interest streams g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8620       ELSE
8621         --rev rec method = ESTIMATED AND BILLED
8622         print_debug('Deal Type => ' || G_DEAL_TYPE || ' Int Calc Basis => ' || G_INTEREST_CALCULATION_BASIS || ' Rev Rec Method => ' || G_REVENUE_RECOGNITION_METHOD);
8623         print_debug('Before fetching Borrower payments g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8624         OPEN l_borrow_payment_csr(p_khr_id, p_from_date, p_to_date);
8625         LOOP
8626           l_source_id := NULL;
8627           l_source_table := NULL;
8628           FETCH l_borrow_payment_csr INTO l_source_id, l_source_table;
8629           EXIT WHEN l_borrow_payment_csr%NOTFOUND;
8630           g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8631           g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8632           g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8633           g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8634           g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8635           g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8636           g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8637           g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8638           g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8639           g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8640           g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8641           g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8642           g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8643           g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8644           g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8645           g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8646           g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8647           g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8648           g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8649           g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8650           g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8651           g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8652           g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8653           g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8654           g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8655           g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8656           g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8657           g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8658           g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8659           g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8660           g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8661           g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8662           g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8663         END LOOP;
8664         CLOSE l_borrow_payment_csr;
8665         print_debug('After fetching Borrower payments g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8666 
8667         print_debug('Before fetching Receipt Applications g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8668         OPEN l_rcpt_app_csr(p_khr_id, p_from_date, p_to_date);
8669         LOOP
8670           l_source_id := NULL;
8671           l_source_table := NULL;
8672           FETCH l_rcpt_app_csr INTO l_source_id, l_source_table;
8673           EXIT WHEN l_rcpt_app_csr%NOTFOUND;
8674           g_vpb_tbl_counter := g_vpb_tbl_counter + 1;
8675           g_vpb_tbl(g_vpb_tbl_counter).source_id := l_source_id;
8676           g_vpb_tbl(g_vpb_tbl_counter).source_table := l_source_table;
8677           g_vpb_tbl(g_vpb_tbl_counter).id := okc_p_util.raw_to_number(sys_guid());
8678           g_vpb_tbl(g_vpb_tbl_counter).khr_id := p_khr_id;
8679           g_vpb_tbl(g_vpb_tbl_counter).int_cal_process := 'VARIABLE_INTEREST';
8680           g_vpb_tbl(g_vpb_tbl_counter).OBJECT_VERSION_NUMBER := 1.0;
8681           g_vpb_tbl(g_vpb_tbl_counter).org_id                   := g_authoring_org_id;
8682           g_vpb_tbl(g_vpb_tbl_counter).request_id               := g_request_id;
8683           g_vpb_tbl(g_vpb_tbl_counter).program_application_id   := NULL;
8684           g_vpb_tbl(g_vpb_tbl_counter).program_id               := NULL;
8685           g_vpb_tbl(g_vpb_tbl_counter).program_update_date      := SYSDATE;
8686           g_vpb_tbl(g_vpb_tbl_counter).attribute_category       := NULL;
8687           g_vpb_tbl(g_vpb_tbl_counter).attribute1               := NULL;
8688           g_vpb_tbl(g_vpb_tbl_counter).attribute2               := NULL;
8689           g_vpb_tbl(g_vpb_tbl_counter).attribute3               := NULL;
8690           g_vpb_tbl(g_vpb_tbl_counter).attribute4               := NULL;
8691           g_vpb_tbl(g_vpb_tbl_counter).attribute5               := NULL;
8692           g_vpb_tbl(g_vpb_tbl_counter).attribute6               := NULL;
8693           g_vpb_tbl(g_vpb_tbl_counter).attribute7               := NULL;
8694           g_vpb_tbl(g_vpb_tbl_counter).attribute8               := NULL;
8695           g_vpb_tbl(g_vpb_tbl_counter).attribute9               := NULL;
8696           g_vpb_tbl(g_vpb_tbl_counter).attribute10              := NULL;
8697           g_vpb_tbl(g_vpb_tbl_counter).attribute11              := NULL;
8698           g_vpb_tbl(g_vpb_tbl_counter).attribute12              := NULL;
8699           g_vpb_tbl(g_vpb_tbl_counter).attribute13              := NULL;
8700           g_vpb_tbl(g_vpb_tbl_counter).attribute14              := NULL;
8701           g_vpb_tbl(g_vpb_tbl_counter).attribute15              := NULL;
8702           g_vpb_tbl(g_vpb_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
8703           g_vpb_tbl(g_vpb_tbl_counter).creation_date            := SYSDATE;
8704           g_vpb_tbl(g_vpb_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
8705           g_vpb_tbl(g_vpb_tbl_counter).last_update_date         := SYSDATE;
8706           g_vpb_tbl(g_vpb_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
8707         END LOOP;
8708         CLOSE l_rcpt_app_csr;
8709         print_debug('After fetching Receipt Applications g_vpb_tbl count is: '|| g_vpb_tbl.COUNT);
8710       END IF;
8711     END IF;
8712   EXCEPTION
8713      WHEN OTHERS THEN
8714        print_error_message('Exception raised in procedure POPULATE_TXNS');
8715        x_return_status  := OKL_API.G_RET_STS_UNEXP_ERROR;
8716        Okl_Api.SET_MESSAGE(
8717                p_app_name     => G_APP_NAME,
8718                p_msg_name     => G_UNEXPECTED_ERROR,
8719                p_token1       => G_SQLCODE_TOKEN,
8720                p_token1_value => SQLCODE,
8721                p_token2       => G_SQLERRM_TOKEN,
8722                p_token2_value => SQLERRM);
8723   END populate_txns;
8724 
8725 ------------------------------------------------------------------------------
8726     -- Start of Comments
8727     -- Created By:       pgomes
8728     -- Procedure Name    print_vpb_tbl
8729     -- Description:      This procedure prints all the records in the PL/SQL table g_vpb_tbl
8730     --
8731     -- Dependencies:
8732     -- Parameters:       .
8733     -- Version:          1.0
8734     -- End of Comments
8735 
8736 ------------------------------------------------------------------------------
8737 
8738   PROCEDURE print_vpb_tbl ( p_vpb_tbl IN  vpb_tbl_type) IS
8739 
8740   l_index        NUMBER;
8741   BEGIN
8742        print_debug('Start => Contents of p_vpb_tbl');
8743        print_debug('******************************');
8744        l_index := p_vpb_tbl.first;
8745        LOOP
8746           EXIT when l_index IS NULL;
8747           print_debug( 'Record Number : '||l_index);
8748     		  print_debug( 'id : '||p_vpb_tbl(l_index).id );
8749     		  print_debug( 'khr_id : '||p_vpb_tbl(l_index).khr_id);
8750           print_debug( 'source_table : '|| p_vpb_tbl(l_index).source_table);
8751           print_debug( 'source_id : '|| p_vpb_tbl(l_index).source_id);
8752           print_debug( 'int_cal_process : '|| p_vpb_tbl(l_index).int_cal_process);
8753           print_debug( 'Object_Version_Number : '|| p_vpb_tbl(l_index).Object_Version_Number);
8754           print_debug( 'Org ID : '|| p_vpb_tbl(l_index).Org_id);
8755           print_debug( 'request ID : '|| p_vpb_tbl(l_index).request_id);
8756           print_debug( 'Program Application ID : '|| p_vpb_tbl(l_index).program_application_id);
8757           print_debug( 'program ID : '|| p_vpb_tbl(l_index).program_id);
8758           print_debug( 'Program Update date : '|| p_vpb_tbl(l_index).program_update_date);
8759           print_debug( 'attribute category : '|| p_vpb_tbl(l_index).attribute_category);
8760           print_debug( 'attribute1 : '|| p_vpb_tbl(l_index).attribute1);
8761           print_debug( 'attribute2 : '|| p_vpb_tbl(l_index).attribute2);
8762           print_debug( 'attribute3 : '|| p_vpb_tbl(l_index).attribute3);
8763           print_debug( 'attribute4 : '|| p_vpb_tbl(l_index).attribute4);
8764           print_debug( 'attribute5 : '|| p_vpb_tbl(l_index).attribute5);
8765           print_debug( 'attribute6 : '|| p_vpb_tbl(l_index).attribute6);
8766           print_debug( 'attribute7 : '|| p_vpb_tbl(l_index).attribute7);
8767           print_debug( 'attribute8 : '|| p_vpb_tbl(l_index).attribute8);
8768           print_debug( 'attribute9 : '|| p_vpb_tbl(l_index).attribute9);
8769           print_debug( 'attribute10 : '|| p_vpb_tbl(l_index).attribute10);
8770           print_debug( 'attribute11 : '|| p_vpb_tbl(l_index).attribute11);
8771           print_debug( 'attribute12 : '|| p_vpb_tbl(l_index).attribute12);
8772           print_debug( 'attribute13 : '|| p_vpb_tbl(l_index).attribute13);
8773           print_debug( 'attribute14 : '|| p_vpb_tbl(l_index).attribute14);
8774           print_debug( 'attribute15 : '|| p_vpb_tbl(l_index).attribute15);
8775           print_debug( 'created_by : '|| p_vpb_tbl(l_index).created_by);
8776           print_debug( 'creation_date : '|| p_vpb_tbl(l_index).creation_date);
8777           print_debug( 'last_updated_by : '|| p_vpb_tbl(l_index).last_updated_by);
8778           print_debug( 'last_update_date : '|| p_vpb_tbl(l_index).last_update_date);
8779           print_debug( 'last_update_login : '|| p_vpb_tbl(l_index).last_update_login);
8780           l_index       := p_vpb_tbl.NEXT(l_index);
8781        END LOOP;
8782        print_debug('****************************');
8783        print_debug('End => Contents of p_vpb_tbl');
8784   EXCEPTION
8785      WHEN OTHERS THEN
8786        print_error_message('Exception raised in procedure PRINT_VPB_TBL');
8787        Okl_Api.SET_MESSAGE(
8788                p_app_name     => G_APP_NAME,
8789                p_msg_name     => G_UNEXPECTED_ERROR,
8790                p_token1       => G_SQLCODE_TOKEN,
8791                p_token1_value => SQLCODE,
8792                p_token2       => G_SQLERRM_TOKEN,
8793                p_token2_value => SQLERRM);
8794   END print_vpb_tbl;
8795 
8796   ------------------------------------------------------------------------------
8797 
8798     -- Start of Comments
8799     -- Created By:       pjgomes
8800     -- Procedure Name    populate_principal_bal_txn
8801     -- Description:      This procedure is called by Variable Interest Calculation for Loans
8802     --                   Inputs :
8803     --                   Output :
8804     -- Dependencies:
8805     -- Parameters:
8806     -- Version:          1.0
8807     -- End of Comments
8808 
8809   ------------------------------------------------------------------------------
8810   Procedure populate_principal_bal_txn(
8811             p_api_version        IN  NUMBER,
8812             p_init_msg_list      IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
8813             x_return_status      OUT NOCOPY VARCHAR2,
8814             x_msg_count          OUT NOCOPY NUMBER,
8815             x_msg_data           OUT NOCOPY VARCHAR2,
8816             p_vpb_tbl           IN  vpb_tbl_type) IS
8817 
8818   l_api_name                  CONSTANT    VARCHAR2(30) := 'populate_principal_bal_txn';
8819   l_api_version               CONSTANT    NUMBER       := 1.0;
8820   l_index                     NUMBER := 0;
8821 
8822   BEGIN
8823     x_return_status               := OKL_API.G_RET_STS_SUCCESS;
8824 
8825     print_debug('Executing procedure populate_principal_bal_txn using following parameters : ');
8826     print_debug(' p_vpb_tbl.count : '|| p_vpb_tbl.COUNT );
8827     print_vpb_tbl (p_vpb_tbl);
8828 
8829     IF (p_vpb_tbl.COUNT > 0) THEN
8830   	   FORALL l_index in p_vpb_tbl.FIRST .. p_vpb_tbl.LAST
8831   	   save exceptions
8832        INSERT INTO OKL_VAR_PRINCIPAL_BAL_TXN VALUES p_vpb_tbl(l_index);
8833 
8834         print_debug ('Exception count : '|| sql%bulk_exceptions.count);
8835        IF sql%bulk_exceptions.count > 0 then
8836           for i in 1..sql%bulk_exceptions.count loop
8837               print_debug('while fetching, error ' || i || ' occurred during '||
8838                   'iteration ' || sql%bulk_exceptions(i).error_index);
8839               print_debug('oracle error is ' ||
8840                   sqlerrm(sql%bulk_exceptions(i).error_code));
8841 
8842           end loop;
8843         end if;
8844        print_debug ('No. of records inserted : '|| SQL%rowcount);
8845 
8846     END IF;
8847 
8848  EXCEPTION
8849      WHEN OTHERS THEN
8850        print_error_message('Exception raised in procedure populate_principal_bal_txn');
8851        print_debug ('Exception during bulk insert');
8852        print_debug ('Exception count : '|| sql%bulk_exceptions.count);
8853        IF sql%bulk_exceptions.count > 0 then
8854           for i in 1..sql%bulk_exceptions.count loop
8855               print_debug('while fetching, error ' || i || ' occurred during '||
8856                   'iteration ' || sql%bulk_exceptions(i).error_index);
8857               print_debug('oracle error is ' ||
8858                   sqlerrm(sql%bulk_exceptions(i).error_code));
8859 
8860           end loop;
8861        END IF;
8862 
8863        x_return_status := OKL_API.G_RET_STS_ERROR;
8864        Okl_Api.SET_MESSAGE(
8865            p_app_name     => G_APP_NAME,
8866            p_msg_name     => G_UNEXPECTED_ERROR,
8867            p_token1       => G_SQLCODE_TOKEN,
8868            p_token1_value => SQLCODE,
8869            p_token2       => G_SQLERRM_TOKEN,
8870            p_token2_value => SQLERRM);
8871 
8872   END populate_principal_bal_txn;
8873 
8874     PROCEDURE var_int_rent_level(
8875         p_api_version   IN  NUMBER,
8876         p_init_msg_list IN  VARCHAR2,
8877         x_return_status OUT NOCOPY VARCHAR2,
8878         x_msg_count     OUT NOCOPY NUMBER,
8879         x_msg_data      OUT NOCOPY VARCHAR2,
8880         p_chr_id        IN NUMBER,
8881         p_trx_id        IN NUMBER,
8882         p_trx_status    IN VARCHAR2,
8883         p_rent_tbl      IN csm_periodic_expenses_tbl_type,
8884         p_csm_loan_level_tbl IN csm_loan_level_tbl_type,
8885         x_child_trx_id       OUT NOCOPY NUMBER) IS
8886 
8887     ------------------------------------------------------------
8888     -- Declare Process variables
8889     ------------------------------------------------------------
8890 
8891     l_api_name           VARCHAR2(35)    := 'var_int_rent_level';
8892     l_proc_name          VARCHAR2(35)    := 'var_int_rent_level';
8893     l_api_version        CONSTANT NUMBER := 1;
8894     l_msg_index_out             NUMBER;
8895 
8896     l_payment_type              VARCHAR2(100) := 'RENT';
8897 
8898     i                           NUMBER := 0;
8899     l_rent_count                NUMBER := 0;
8900     l_split_count               NUMBER := 0;
8901     --l_sequence                  NUMBER := 0;
8902 
8903     l_strm_lalevl_tbl           strm_lalevl_tbl;
8904     l_strm_lalevl_tbl_cntr      NUMBER := 0;
8905     l_rbk_tbl                   rbk_tbl;
8906     l_rbk_tbl_cntr              NUMBER := 0;
8907     l_rent_tbl                  csm_periodic_expenses_tbl_type;
8908     l_csm_loan_level_tbl        csm_loan_level_tbl_type;
8909     --l_split_asset_tbl           strm_lalevl_tbl;
8910     l_frequency                 okl_time_units_v.name%type;
8911     l_adder_months              NUMBER;
8912     l_payment_level_start_date  DATE;
8913     l_reamort_date              DATE;
8914     l_date_last_int_cal         DATE;
8915     l_vipv_rec                  vipv_rec;
8916     x_vipv_rec                  vipv_rec;
8917     x_strm_trx_tbl              strm_trx_tbl;
8918     l_child_trx_id              NUMBER := NULL;
8919     l_strm_lalevl_tbl_out       strm_lalevl_tbl;
8920 
8921     CURSOR l_vip_csr (p_trx_id in NUMBER) IS
8922     SELECT id
8923     FROM   okl_var_int_process_b
8924     WHERE  PARENT_TRX_ID = p_trx_id;
8925 
8926     --cursor to get existing payments
8927     Cursor l_pmt_csr (p_khr_id in number, p_cle_id in number) is
8928     select sll_rulb.dnz_chr_id                khr_id,
8929       rgpb.cle_id                            cle_id,
8930       --LASLL values
8931       sll_rulb.rule_information_category     sll_rule_information_category,
8932       to_number(sll_rulb.rule_information1)  seq, -- 4899594
8933       sll_rulb.rule_information2             start_date,
8934       sll_rulb.rule_information3             number_periods,
8935       sll_rulb.rule_information4             tuoms_per_period,
8936       sll_rulb.object1_id1                   Pay_freq,
8937       sll_rulb.rule_information5             structure,
8938       nvl( sll_rulb.rule_information10,'N')  advance_or_arrears,
8939       sll_rulb.rule_information6             amount,
8940       sll_rulb.rule_information7             stub_days,
8941       sll_rulb.rule_information8             stub_amount,
8942       sll_rulb.rule_information13            rate,
8943       sll_rulb.jtot_object1_code             time_unit_of_measure,
8944       sll_rulb.jtot_object2_code             stream_level_header,
8945       --LASLH values
8946       slh_rulb.rule_information_category     slh_rule_information_category,
8947       slh_rulb.jtot_object1_code             stream_type_source,
8948       slh_rulb.jtot_object2_code             time_value,
8949       slh_rulb.object1_id1                   sty_id,
8950       slh_rulb.rule_information1             billing_schedule_type,
8951       slh_rulb.rule_information2             rate_type
8952    from   okc_rules_b        sll_rulb,
8953       okc_rules_b        slh_rulb,
8954       okl_strm_type_b    styb,
8955       okc_rule_groups_b  rgpb
8956    where  sll_rulb.rgp_id                      = rgpb.id
8957    and    sll_rulb.rule_information_category   = 'LASLL'
8958    and    sll_rulb.dnz_chr_id                  = rgpb.dnz_chr_id
8959    and    sll_rulb.object2_id1                 = to_char(slh_rulb.id)
8960    and    slh_rulb.rgp_id                      = rgpb.id
8961    and    slh_rulb.rule_information_category   = 'LASLH'
8962    and    slh_rulb.dnz_chr_id                  = rgpb.dnz_chr_id
8963    and    styb.id                              = slh_rulb.object1_id1
8964    and    styb.stream_type_purpose             IN ('RENT', 'PRINCIPAL_PAYMENT')
8965    and    rgpb.dnz_chr_id                      = p_khr_id
8966    and    rgpb.cle_id                          = p_cle_id
8967    and    rgpb.rgd_code                        = 'LALEVL'
8968    order by to_number(sll_rulb.rule_information1); -- 4899594
8969 
8970    Cursor get_pmt_freq (l_freq in okl_time_units_v.name%type) is
8971    select id1 from okl_time_units_v
8972    where name = l_freq;
8973 
8974    CURSOR c_last_int_cur (p_contract_id NUMBER) IS
8975    SELECT NVL(date_last_interim_interest_cal, start_date) reamort_date
8976          ,currency_code
8977    FROM   okl_k_headers_full_v
8978    WHERE  id = p_chr_id;
8979 
8980    CURSOR c_freq_cur(p_contract_id NUMBER) IS
8981    select object1_id1 from okc_rules_b
8982    where dnz_chr_id = p_contract_id
8983    and rule_information_category = 'LASLL';
8984 
8985    l_pymt_rec l_pmt_csr%RowType;
8986    l_diff_in_periods   NUMBER;
8987 
8988    line_index Number := 0;
8989    l_source Number;
8990    l_kle_id NUMBER := NULL;
8991    l_prev_kle_id NUMBER := NULL;
8992    l_rent_tbl_cntr NUMBER := 0;
8993    l_csm_loan_level_tbl_cntr NUMBER := 0;
8994    l_index_number NUMBER;
8995    l_prev_index_number NUMBER;
8996    l_fetch_prior_periods BOOLEAN := TRUE;
8997    l_prior_periods NUMBER := 0;
8998    l_period_cntr NUMBER := 0;
8999    l_prior_level_date_start DATE;
9000    l_level_date_start DATE;
9001    l_sequence NUMBER := 0;
9002    l_time_unit_of_measure okc_rules_b.jtot_object1_code%type;
9003    l_stream_level_header okc_rules_b.jtot_object2_code%type;
9004    l_tuoms_per_period okc_rules_b.rule_information4%type;
9005    l_sll_rule_information_cat okc_rules_b.rule_information_category%type;
9006    l_structure okc_rules_b.rule_information5%type;
9007 
9008    l_stub_start_date DATE;
9009    l_stub_days NUMBER;
9010    l_stub_amount NUMBER;
9011    l_ret_val VARCHAR2(1);
9012    l_currency_code okc_k_headers_b.currency_code%type;
9013 
9014    --get the line id for the repriced rent from supertrump
9015    FUNCTION get_kle_id(p_trx_number IN NUMBER,
9016                        p_index_number IN NUMBER,
9017                        x_return_status OUT NOCOPY VARCHAR2) RETURN NUMBER IS
9018      l_kle_id NUMBER := -9999;
9019    BEGIN
9020      OKL_STREAMS_UTIL.get_line_id(p_trx_number => p_trx_number
9021                                  ,p_index_number => p_index_number
9022                                  ,x_kle_id => l_kle_id
9023                                  ,x_return_status => x_return_status);
9024      RETURN l_kle_id;
9025    EXCEPTION
9026      WHEN OTHERS THEN
9027      print_debug('Error deriving the asset line id for Trx Number : ' || p_trx_number || ' and Index Number : ' || p_index_number);
9028      RETURN l_kle_id;
9029    END get_kle_id;
9030 
9031   PROCEDURE print_pmt_csr(p_pmt_rec IN l_pmt_csr%RowType) IS
9032 
9033     l_api_name	        CONSTANT VARCHAR2(30) := 'print_pmt_csr';
9034     l_pymt_rec l_pmt_csr%RowType;
9035   BEGIN
9036     l_pymt_rec := p_pmt_rec;
9037     print_debug('*****************************************');
9038     print_debug('*******START CONTENTS OF P_PMT_REC******');
9039     print_debug('khr_id : ' || set_value_null(l_pymt_rec.khr_id));
9040     print_debug('cle_id : ' || set_value_null(l_pymt_rec.cle_id));
9041     print_debug('LASLL VALUES');
9042     print_debug('============');
9043     print_debug('cle_id : ' || set_value_null(l_pymt_rec.cle_id));
9044     print_debug('seq : ' || set_value_null(l_pymt_rec.seq));
9045     print_debug('start_date : ' || set_value_null(l_pymt_rec.start_date));
9046     print_debug('number_periods : ' || set_value_null(l_pymt_rec.number_periods));
9047     print_debug('tuoms_per_period : ' || set_value_null(l_pymt_rec.tuoms_per_period));
9048     print_debug('Pay_freq : ' || set_value_null(l_pymt_rec.Pay_freq));
9049     print_debug('structure : ' || set_value_null(l_pymt_rec.structure));
9050     print_debug('advance_or_arrears : ' || set_value_null(l_pymt_rec.advance_or_arrears));
9051     print_debug('amount : ' || set_value_null(l_pymt_rec.amount));
9052     print_debug('stub_days : ' || set_value_null(l_pymt_rec.stub_days));
9053     print_debug('stub_amount : ' || set_value_null(l_pymt_rec.stub_amount));
9054     print_debug('rate : ' || set_value_null(l_pymt_rec.rate));
9055     print_debug('time_unit_of_measure : ' || set_value_null(l_pymt_rec.time_unit_of_measure));
9056     print_debug('stream_level_header : ' || set_value_null(l_pymt_rec.stream_level_header));
9057     print_debug('LASLH VALUES');
9058     print_debug('============');
9059     print_debug('slh_rule_information_category : ' || set_value_null(l_pymt_rec.slh_rule_information_category));
9060     print_debug('stream_type_source : ' || set_value_null(l_pymt_rec.stream_type_source));
9061     print_debug('time_value : ' || set_value_null(l_pymt_rec.time_value));
9062     print_debug('sty_id : ' || set_value_null(l_pymt_rec.sty_id));
9063     print_debug('billing_schedule_type : ' || set_value_null(l_pymt_rec.billing_schedule_type));
9064     print_debug('rate_type : ' || set_value_null(l_pymt_rec.rate_type));
9065     print_debug('*******END CONTENTS OF P_PMT_REC********');
9066     print_debug('*****************************************');
9067 
9068   Exception
9069    	WHEN OTHERS THEN
9070       print_debug('error in procedure print_pmt_csr');
9071       print_debug('sqlcode : ' || sqlcode || ' $ sqlerrm : ' || sqlerrm);
9072   END print_pmt_csr;
9073 
9074   --procedure to consolidate consecutive sll records if the the amounts are same incase of RENT
9075   --or if amounts and rates are same incase of PRINCIPAL PAYMENT
9076   PROCEDURE consolidate_sll(p_strm_lalevl_tbl IN strm_lalevl_tbl,
9077                             x_strm_lalevl_tbl OUT NOCOPY strm_lalevl_tbl) IS
9078 
9079     l_strm_lalevl_tbl strm_lalevl_tbl;
9080     l_strm_lalevl_tbl_cntr          NUMBER := 0;
9081     l_prev_strm_lalevl_tbl_cntr     NUMBER := 0;
9082     l_strm_lalevl_tbl_out_cntr      NUMBER := 0;
9083   BEGIN
9084     print_debug('*******START CONSOLIDATE_SLL********');
9085 
9086     l_strm_lalevl_tbl := p_strm_lalevl_tbl;
9087     l_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl.first;
9088     print_debug('table count before consolidation :' || l_strm_lalevl_tbl.count);
9089 
9090     loop
9091       exit when l_strm_lalevl_tbl_cntr IS NULL;
9092       IF (l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information_category = 'LASLH') THEN
9093         l_strm_lalevl_tbl_out_cntr := l_strm_lalevl_tbl_out_cntr + 1;
9094         x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr) := l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr);
9095         l_prev_strm_lalevl_tbl_cntr := NULL;
9096       ELSIF (l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information_category = 'LASLL') THEN
9097         IF (l_prev_strm_lalevl_tbl_cntr IS NULL) THEN
9098           l_strm_lalevl_tbl_out_cntr := l_strm_lalevl_tbl_out_cntr + 1;
9099           x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr) := l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr);
9100           l_prev_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl_cntr;
9101         ELSE
9102 
9103           IF (l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information6 IS NOT NULL AND l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information13 IS NULL) THEN
9104             --for RENT
9105             --IF (l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information7 IS NULL AND l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information8 IS NULL) THEN
9106               --for payment line (not a STUB)
9107               IF (l_strm_lalevl_tbl(l_prev_strm_lalevl_tbl_cntr).rule_information6 = l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information6) THEN
9108                 --amounts are the same
9109                 x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr).rule_information3 := x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr).rule_information3 + l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information3;
9110               ELSE
9111                 --amounts are not the same
9112                 l_strm_lalevl_tbl_out_cntr := l_strm_lalevl_tbl_out_cntr + 1;
9113                 x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr) := l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr);
9114                 l_prev_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl_cntr;
9115               END IF;
9116             /*ELSE
9117               --line is a stub
9118               l_strm_lalevl_tbl_out_cntr := l_strm_lalevl_tbl_out_cntr + 1;
9119               x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr) := l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr);
9120               l_prev_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl_cntr;
9121             END IF;*/
9122           ELSIF (l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information6 IS NOT NULL AND l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information13 IS NOT NULL) THEN
9123             --for PRINCIPAL PAYMENT
9124             --IF (l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information7 IS NULL AND l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information8 IS NULL) THEN
9125               --for payment line (not a STUB)
9126 
9127               --compare amount and rate
9128               IF (l_strm_lalevl_tbl(l_prev_strm_lalevl_tbl_cntr).rule_information6 = l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information6 AND
9129                   l_strm_lalevl_tbl(l_prev_strm_lalevl_tbl_cntr).rule_information13 = l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information13) THEN
9130                 --amounts are the same
9131                 x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr).rule_information3 := x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr).rule_information3 + l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information3;
9132               ELSE
9133                 --amounts are not the same
9134                 l_strm_lalevl_tbl_out_cntr := l_strm_lalevl_tbl_out_cntr + 1;
9135                 x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr) := l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr);
9136                 l_prev_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl_cntr;
9137               END IF;
9138             /*ELSE
9139               --line is a stub
9140               l_strm_lalevl_tbl_out_cntr := l_strm_lalevl_tbl_out_cntr + 1;
9141               x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr) := l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr);
9142               l_prev_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl_cntr;
9143             END IF;*/
9144           ELSIF (l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information6 IS NULL) THEN
9145             --line is a stub
9146             l_strm_lalevl_tbl_out_cntr := l_strm_lalevl_tbl_out_cntr + 1;
9147             x_strm_lalevl_tbl(l_strm_lalevl_tbl_out_cntr) := l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr);
9148             l_prev_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl_cntr;
9149           ELSE
9150             print_debug('neither Rent nor Principal Payment');
9151           END IF;
9152 
9153         END IF;
9154 
9155       END IF;
9156 
9157       l_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl.next(l_strm_lalevl_tbl_cntr);
9158     end loop;
9159 
9160     print_debug('table count after consolidation :' || x_strm_lalevl_tbl.count);
9161     print_debug('*******END CONSOLIDATE_SLL********');
9162   Exception
9163    	WHEN OTHERS THEN
9164       print_debug('error in procedure consolidate_sll');
9165       print_debug('sqlcode : ' || sqlcode || ' $ sqlerrm : ' || sqlerrm);
9166   END consolidate_sll;
9167 
9168   BEGIN -- main process begins here
9169 
9170     print_debug('****Entering procedure VAR_INT_RENT_LEVEL****');
9171     print_debug('****Start-Creating Rent Levels and ReBooking.');
9172 
9173     x_return_status := OKL_API.G_RET_STS_SUCCESS;
9174 
9175     x_return_status := OKL_API.START_ACTIVITY(
9176       p_api_name	    => l_api_name,
9177   		p_init_msg_list	=> p_init_msg_list,
9178   		p_api_type  	=> '_PVT',
9179   		x_return_status	=> x_return_status);
9180 
9181     IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
9182 		  RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
9183     ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
9184 		  RAISE OKL_API.G_EXCEPTION_ERROR;
9185     END IF;
9186 
9187     /*begin
9188       select pg_source_seq.NEXTVAL into l_source from dual;
9189     exception
9190       when others then
9191       null;
9192     end;*/
9193     print_debug('Contract ID: '||p_chr_id);
9194     print_debug('Trans Id: ' || p_trx_id);
9195     print_debug('Trans Status: ' || p_trx_status);
9196 
9197 
9198     x_return_status := OKC_API.G_RET_STS_SUCCESS;
9199 
9200     --which is the kle id in this table
9201     l_rent_tbl := p_rent_tbl;
9202     l_csm_loan_level_tbl := p_csm_loan_level_tbl;
9203 
9204 
9205     print_debug('=======>Start - Input from Super Trump or initiate_request (for Principal Payment).');
9206     print_loan_tables(p_rent_tbl => l_rent_tbl,
9207                       p_csm_loan_level_tbl => l_csm_loan_level_tbl);
9208     print_debug('=======>End - Input from Super Trump or initiate_request (for Principal Payment).');
9209 
9210 
9211   	OPEN	c_last_int_cur (p_chr_id);
9212 	  FETCH	c_last_int_cur INTO l_reamort_date, l_currency_code;
9213     CLOSE	c_last_int_cur;
9214 
9215     --print_debug('Last Interest Calculation Date: '||l_date_last_int_cal);
9216     print_debug('Reamort Date: '||l_reamort_date || ' Currency Code: ' || l_currency_code);
9217 
9218 
9219     /*IF (p_trx_id IS NOT NULL) THEN
9220       --need the below code just in case the frequency is 'T' for a stub payment
9221       l_rent_count := p_rent_tbl.first;
9222       LOOP
9223         EXIT WHEN l_rent_count IS NULL;
9224     	  OPEN	get_pmt_freq (p_rent_tbl(l_rent_count).period);
9225       	FETCH	get_pmt_freq INTO l_frequency;
9226       	CLOSE	get_pmt_freq;
9227         EXIT WHEN l_frequency IN ('M', 'Q', 'S', 'A');
9228         l_rent_count := p_rent_tbl.next(l_rent_count);
9229       END LOOP;
9230     ELSE
9231       l_rent_count := p_rent_tbl.first;
9232       LOOP
9233         EXIT WHEN l_rent_count IS NULL;
9234         l_frequency := p_rent_tbl(l_rent_count).period;
9235         EXIT WHEN l_frequency IN ('M', 'Q', 'S', 'A');
9236         l_rent_count := p_rent_tbl.next(l_rent_count);
9237       END LOOP;
9238     END IF;*/
9239 
9240     OPEN c_freq_cur(p_chr_id);
9241     FETCH c_freq_cur INTO l_frequency;
9242     CLOSE c_freq_cur;
9243 
9244     print_debug('l_frequency: '||l_frequency);
9245 
9246     if(l_frequency = 'M') THEN
9247               l_adder_months := 1;
9248     elsif(l_frequency = 'Q') THEN
9249               l_adder_months := 3;
9250     elsif(l_frequency = 'S') THEN
9251               l_adder_months := 6;
9252     elsif(l_frequency = 'A') THEN
9253               l_adder_months := 12;
9254     end if;
9255     print_debug('l_frequency: '||l_frequency || ' l_adder_months: ' || l_adder_months);
9256 
9257     l_rent_tbl_cntr := l_rent_tbl.first;
9258     LOOP
9259       EXIT WHEN l_rent_tbl_cntr IS NULL;
9260       --round the amount
9261       IF (l_rent_tbl(l_rent_tbl_cntr).amount IS NOT NULL) THEN
9262          l_rent_tbl(l_rent_tbl_cntr).amount := OKL_ACCOUNTING_UTIL.round_amount(l_rent_tbl(l_rent_tbl_cntr).amount, l_currency_code);
9263       END IF;
9264 
9265       l_rent_tbl_cntr := l_rent_tbl.next(l_rent_tbl_cntr);
9266     END LOOP;
9267 
9268     l_index_number := NULL;
9269     l_prev_index_number := NULL;
9270     l_kle_id := NULL;
9271     l_prev_kle_id := NULL;
9272     l_rbk_tbl_cntr := 0;
9273     l_strm_lalevl_tbl_cntr := 0;
9274     l_sequence := 0;
9275     l_fetch_prior_periods := TRUE;
9276 
9277     l_rent_tbl_cntr := l_rent_tbl.first;
9278     LOOP
9279       EXIT WHEN l_rent_tbl_cntr IS NULL;
9280 
9281       --get kle_id
9282       l_index_number := l_rent_tbl(l_rent_tbl_cntr).index_number;
9283       print_debug('l_index_number: '||l_index_number);
9284 
9285       --for contracts with payments in arrears, supertrum will add a period
9286       --to the payment start date. so we gotta reverse that
9287       /*IF (p_trx_id IS NOT NULL) THEN
9288         l_rent_tbl(l_rent_tbl_cntr).first_payment_date := add_months(l_rent_tbl(l_rent_tbl_cntr).first_payment_date, -1*l_adder_months);
9289       END IF;*/
9290 
9291       IF (p_trx_id IS NOT NULL AND l_index_number IS NOT NULL) THEN
9292         --for supertrump request
9293         IF (NVL(l_prev_index_number, -99) <> l_index_number) THEN
9294           print_debug('deriving kle id');
9295           l_kle_id := get_kle_id(p_trx_number => p_trx_id,
9296                        p_index_number => l_index_number,
9297                        x_return_status => x_return_status);
9298 
9299           IF (x_return_status <> OKL_API.G_RET_STS_SUCCESS) THEN
9300             print_debug('Unable to derive kle_id from inbound supertrump call.');
9301             RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
9302           ELSE
9303             print_debug('l_kle_id: '||l_kle_id);
9304           END IF;
9305           l_sequence := 0;
9306           print_debug('l_sequence: '||l_sequence);
9307           l_prev_index_number := l_index_number;
9308         END IF;
9309       ELSE
9310         --for initiate request for Principal Payment
9311         l_kle_id := l_csm_loan_level_tbl(l_rent_tbl_cntr).kle_loan_id;
9312         l_sequence := 0;
9313         print_debug('l_sequence: '||l_sequence);
9314         print_debug('l_kle_id: '||l_kle_id);
9315       END IF;
9316 
9317       IF (NVL(l_prev_kle_id, -99) <> l_kle_id) THEN
9318         l_fetch_prior_periods := TRUE;
9319         print_debug('setting the l_fetch_prior_periods to true');
9320       END IF;
9321 
9322       IF (l_fetch_prior_periods) THEN
9323         print_debug('l_fetch_prior_periods is true: fecthing LASLL/LASLH info for kle : ' || l_kle_id);
9324         FOR l_pmt_cur IN l_pmt_csr (p_chr_id, l_kle_id) LOOP
9325           print_pmt_csr(p_pmt_rec => l_pmt_cur);
9326 
9327           --populate l_rbk_tbl table and LASLH information
9328           print_debug('previous kle_id : ' || l_prev_kle_id || '<-> current  kle_id : ' || l_kle_id);
9329           IF (NVL(l_prev_kle_id, -99) <> l_kle_id) THEN
9330             print_debug('populating l_rbk_tbl');
9331             l_rbk_tbl_cntr := l_rbk_tbl_cntr + 1;
9332             l_rbk_tbl(l_rbk_tbl_cntr).KHR_ID := p_chr_id;
9333             l_rbk_tbl(l_rbk_tbl_cntr).KLE_ID := l_kle_id;
9334             print_debug('done populating l_rbk_tbl');
9335 
9336             print_debug('populating l_strm_lalevl_tbl with LASLH information');
9337             l_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl_cntr + 1;
9338             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Chr_Id := p_chr_id;
9339             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Cle_Id := l_kle_id;
9340             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).jtot_object1_code := l_pmt_cur.stream_type_source;
9341             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).jtot_object2_code := l_pmt_cur.time_value;
9342             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information1 := l_pmt_cur.billing_schedule_type;
9343             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).rule_information2 := l_pmt_cur.rate_type;
9344             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information_category := l_pmt_cur.slh_rule_information_category;
9345             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).object1_id1 := l_pmt_cur.sty_id;
9346             l_prev_kle_id := l_kle_id;
9347             l_time_unit_of_measure := l_pmt_cur.time_unit_of_measure;
9348             l_stream_level_header := l_pmt_cur.stream_level_header;
9349             l_sll_rule_information_cat := l_pmt_cur.sll_rule_information_category;
9350             l_tuoms_per_period := l_pmt_cur.tuoms_per_period;
9351             l_structure := l_pmt_cur.structure;
9352             print_debug('done populating l_strm_lalevl_tbl with LASLH information');
9353           END IF;
9354 
9355           l_prior_level_date_start := FND_DATE.canonical_to_date(l_pmt_cur.start_date);
9356           print_debug('l_prior_level_date_start : ' || l_prior_level_date_start);
9357           l_level_date_start := NULL;
9358           l_prior_periods := 0;
9359           FOR l_period_cntr IN 1..NVL(l_pmt_cur.number_periods, 1) LOOP
9360               IF (l_prior_level_date_start < l_reamort_date) THEN
9361                 l_prior_periods := l_prior_periods + 1;
9362 
9363                 IF (l_level_date_start IS NULL) THEN
9364                   l_level_date_start := l_prior_level_date_start;
9365                   print_debug('l_level_date_start : ' || l_level_date_start);
9366                 END IF;
9367               END IF;
9368               l_prior_level_date_start := add_months(l_prior_level_date_start,  l_adder_months);
9369               print_debug('l_period_cntr :' || l_period_cntr || ' l_prior_level_date_start : ' || l_prior_level_date_start);
9370           END LOOP;
9371           print_debug('l_prior_level_date_start : ' || l_prior_level_date_start);
9372           print_debug('l_prior_periods : ' || l_prior_periods);
9373 
9374           IF (l_prior_periods > 0) THEN
9375             l_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl_cntr + 1;
9376             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Chr_Id := p_chr_id;
9377             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Cle_Id := l_kle_id;
9378             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information3 := l_prior_periods;
9379             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Jtot_Object1_Code := l_pmt_cur.time_unit_of_measure;
9380             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Jtot_Object2_Code := l_pmt_cur.stream_level_header;
9381             l_stream_level_header := l_pmt_cur.stream_level_header;
9382             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Object1_id1 := l_pmt_cur.Pay_freq;
9383             l_sequence := l_sequence + 1;
9384             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information1 := l_sequence;
9385             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information2 := fnd_date.date_to_canonical(l_level_date_start);
9386             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information4 := l_pmt_cur.tuoms_per_period;
9387             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information5 := l_structure;
9388             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information6 := l_pmt_cur.amount;
9389             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information7 := l_pmt_cur.stub_days;
9390             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information8 := l_pmt_cur.stub_amount;
9391             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information10 := l_pmt_cur.advance_or_arrears;
9392             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information_category := l_pmt_cur.sll_rule_information_category;
9393             l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information13 := l_pmt_cur.rate;
9394 
9395             print_debug('=>Start - Prior Periods Information in -> l_strm_lalevl_tbl.');
9396             print_var_int_tables(p_rbk_tbl => l_rbk_tbl,
9397                                  p_strm_lalevl_tbl => l_strm_lalevl_tbl);
9398             print_debug('=>End - Prior Periods Information in -> l_strm_lalevl_tbl.');
9399           END IF;
9400         END LOOP; --l_pmt_cur
9401         l_fetch_prior_periods := FALSE;
9402       END IF;
9403 
9404       l_strm_lalevl_tbl_cntr := l_strm_lalevl_tbl_cntr + 1;
9405       l_sequence := l_sequence + 1;
9406       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Chr_Id := p_chr_id;
9407       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Cle_Id := l_kle_id;
9408       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Jtot_Object1_Code := l_time_unit_of_measure;
9409       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Jtot_Object2_Code := l_stream_level_header;
9410       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information_category := l_sll_rule_information_cat;
9411       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information1 := l_sequence;
9412       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information3 := l_rent_tbl(l_rent_tbl_cntr).number_of_periods;
9413       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information4 := l_tuoms_per_period;
9414       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information5 := l_structure;
9415       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information6 := l_rent_tbl(l_rent_tbl_cntr).amount;
9416 
9417       --if the payment level is a stub
9418       IF (UPPER(l_rent_tbl(l_rent_tbl_cntr).period) IN ('STUB', 'T')) THEN
9419         print_debug('calling get_stub_info with p_kle_id => ' || l_kle_id || ' and p_start_date => ' || l_rent_tbl(l_rent_tbl_cntr).first_payment_date);
9420         l_ret_val := get_stub_info(p_kle_id => l_kle_id,
9421                      p_start_date => l_rent_tbl(l_rent_tbl_cntr).first_payment_date,
9422                      x_stub_start_date => l_stub_start_date,
9423                      x_stub_days => l_stub_days,
9424                      x_stub_amount => l_stub_amount);
9425         print_debug(' output of get_stub_info :');
9426         print_debug(' l_stub_start_date => ' || l_stub_start_date);
9427         print_debug(' l_stub_days => ' || l_stub_days);
9428         print_debug(' l_stub_amount => ' || l_stub_amount);
9429 
9430         l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information2 := fnd_date.date_to_canonical(l_stub_start_date);
9431         l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information3 := NULL;
9432         l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information6 := NULL;
9433         l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information7 := l_stub_days;
9434         --l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information8 := l_stub_amount;
9435         l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information8 := l_rent_tbl(l_rent_tbl_cntr).amount;
9436      ELSE
9437        l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information2 := fnd_date.date_to_canonical(l_rent_tbl(l_rent_tbl_cntr).first_payment_date);
9438      END IF;
9439       --start change by pjgomes
9440       --uncomment out the below lines when necessary changes are made
9441       --so that the l_rent_tbl structure has stub_days and stub_amount fields
9442       --l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information7 := l_rent_tbl(l_rent_tbl_cntr).stub_days;
9443       --l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information8 := l_rent_tbl(l_rent_tbl_cntr).stub_amount;
9444       --end change by pjgomes
9445 
9446 
9447       IF (p_trx_id IS NOT NULL) THEN
9448         l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information10 := l_rent_tbl(l_rent_tbl_cntr).advance_or_arrears;
9449       ELSE
9450         IF (NVL(l_rent_tbl(l_rent_tbl_cntr).advance_or_arrears, 'DODDLES') = 'ARREARS') THEN
9451           l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information10 := 'Y';
9452         ELSE
9453           l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information10 := 'N';
9454         END IF;
9455       END IF;
9456 
9457       --l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information10 := l_rent_tbl(l_rent_tbl_cntr).advance_or_arrears;
9458       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Rule_Information13 := l_rent_tbl(l_rent_tbl_cntr).rate;
9459       l_strm_lalevl_tbl(l_strm_lalevl_tbl_cntr).Object1_id1 := l_frequency;
9460       print_debug('=>Start - Current and prior Periods Information in -> l_strm_lalevl_tbl.');
9461       print_var_int_tables(p_rbk_tbl => l_rbk_tbl,
9462                            p_strm_lalevl_tbl => l_strm_lalevl_tbl);
9463       print_debug('=>End - Current and prior Periods Information in -> l_strm_lalevl_tbl.');
9464 
9465       l_rent_tbl_cntr := l_rent_tbl.next(l_rent_tbl_cntr);
9466     END LOOP; --l_rent_tbl
9467 
9468     --FOR line_count IN 1..l_split_asset_tbl.COUNT
9469 /*    i := 0;
9470     line_index := 0;
9471     l_split_count := l_split_asset_tbl.first;
9472     LOOP
9473        exit when l_split_count is null;
9474 
9475        IF(l_split_asset_tbl(l_split_count).rule_information_category = 'LASLH') THEN
9476          i := i + 1;
9477          l_strm_lalevl_tbl(i) := l_split_asset_tbl(l_split_count);
9478               print_debug('Record: '||l_split_asset_tbl(l_split_count).rule_information_category);
9479          l_sequence := 1;
9480        ELSE
9481          line_index := line_index + 1;
9482          l_rbk_tbl(line_index).KHR_ID := p_chr_id;
9483          l_rbk_tbl(line_index).KLE_ID := l_split_asset_tbl(l_split_count).cle_id;
9484          FOR r_pymt_csr IN get_pmt_csr(p_chr_id, l_split_asset_tbl(l_split_count).cle_id)
9485          LOOP
9486               print_debug('Flag from Split: '||l_split_asset_tbl(l_split_count).Rule_Information10);
9487               print_debug('CHR ID: '||p_chr_id||
9488                                     ' Cle ID: '||l_split_asset_tbl(l_split_count).cle_id
9489                                     ||' Sequence: '||l_sequence);
9490               print_debug('Count: '||l_split_count||
9491                                     ' Payment Old Start Date: '||r_pymt_csr.start_date||
9492                                     ' No. of Old Periods: '||r_pymt_csr.number_periods||
9493                                     ' Payment Start Date: '||l_reamort_date);
9494               print_debug('Payment Start Date from Split: '||l_split_asset_tbl(l_split_count).Rule_Information2);
9495 
9496               If (FND_DATE.canonical_to_date(r_pymt_csr.start_date) < l_reamort_date) Then
9497                 i := i + 1;
9498                 l_diff_in_periods := round(months_between(l_reamort_date,
9499                                                             FND_DATE.canonical_to_date(r_pymt_csr.start_date)));
9500                 print_debug('Period Diff: '||l_diff_in_periods);
9501                 FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Period Diff: '||l_diff_in_periods);
9502                 If (l_diff_in_periods >= 1 and r_pymt_csr.number_periods > l_diff_in_periods)Then
9503                   l_strm_lalevl_tbl(i).Rule_Information3 := l_diff_in_periods;
9504                 else
9505                   l_strm_lalevl_tbl(i).Rule_Information3 := r_pymt_csr.number_periods;
9506                 end if;
9507                 l_strm_lalevl_tbl(i).Chr_Id := p_chr_id;
9508                 l_strm_lalevl_tbl(i).Cle_Id := r_pymt_csr.cle_id;
9509                 l_strm_lalevl_tbl(i).Jtot_Object1_Code := 'OKL_TUOM';
9510                 l_strm_lalevl_tbl(i).Jtot_Object2_Code := 'OKL_STRMHDR';
9511                 l_strm_lalevl_tbl(i).Object1_id1 := r_pymt_csr.Pay_freq;
9512                 l_strm_lalevl_tbl(i).Rule_Information1 := l_sequence;
9513                 l_strm_lalevl_tbl(i).Rule_Information2 := r_pymt_csr.start_date;
9514                 l_strm_lalevl_tbl(i).Rule_Information4 := r_pymt_csr.tuoms_per_period;
9515                 l_strm_lalevl_tbl(i).Rule_Information6 := r_pymt_csr.amount;
9516                 l_strm_lalevl_tbl(i).Rule_Information10 := r_pymt_csr.advance_or_arrears;
9517                 l_strm_lalevl_tbl(i).Rule_Information_category := 'LASLL';
9518               END IF;
9519               l_sequence := l_sequence + 1;
9520          END LOOP;
9521          i := i + 1;
9522          -- Hard Coded the Flag as Split API is not returning it
9523          l_split_asset_tbl(l_split_count).Rule_Information1 := l_sequence;
9524          l_split_asset_tbl(l_split_count).Rule_Information10 := 'Y';
9525          l_strm_lalevl_tbl(i) := l_split_asset_tbl(l_split_count);
9526          l_sequence := l_sequence + 1;
9527        END IF;
9528        l_split_count := l_split_asset_tbl.next(l_split_count);
9529     END LOOP;
9530 
9531     print_debug('No. of Records for Mass Rebook: '||l_strm_lalevl_tbl.count);
9532 --    print_debug('Before Mass Rebook: '||x_return_status);
9533 
9534     print_debug('COUNT: '||l_rbk_tbl.COUNT);
9535 */
9536 
9537     print_debug('');
9538     print_debug('=>Start - Before consolidating SLL, contents of l_rbk_tbl and l_strm_lalevl_tbl.');
9539     print_var_int_tables(p_rbk_tbl => l_rbk_tbl,
9540                          p_strm_lalevl_tbl => l_strm_lalevl_tbl);
9541     print_debug('=>End - Before consolidating SLL, contents of l_rbk_tbl and l_strm_lalevl_tbl.');
9542 
9543     consolidate_sll(p_strm_lalevl_tbl => l_strm_lalevl_tbl,
9544                     x_strm_lalevl_tbl => l_strm_lalevl_tbl_out);
9545 
9546    l_strm_lalevl_tbl := l_strm_lalevl_tbl_out;
9547 
9548     print_debug('');
9549     print_debug('=>Start - After consolidation of SLL, before passing to mass rebook, contents of l_rbk_tbl and l_strm_lalevl_tbl.');
9550     print_var_int_tables(p_rbk_tbl => l_rbk_tbl,
9551                          p_strm_lalevl_tbl => l_strm_lalevl_tbl);
9552     print_debug('=>End - After consolidation of SLL, before passing to mass rebook, contents of l_rbk_tbl and l_strm_lalevl_tbl.');
9553 
9554 
9555     OKL_MASS_REBOOK_PVT.apply_mass_rebook(
9556                      p_api_version          => p_api_version,
9557                      p_init_msg_list        => p_init_msg_list,
9558                      x_return_status        => x_return_status,
9559                      x_msg_count            => x_msg_count,
9560                      x_msg_data             => x_msg_data,
9561                      p_rbk_tbl              => l_rbk_tbl,
9562                      p_deprn_method_code    => NULL,
9563                      p_in_service_date      => NULL,
9564                      p_life_in_months       => NULL,
9565                      p_basic_rate           => NULL,
9566                      p_adjusted_rate        => NULL,
9567                      p_residual_value       => NULL,
9568                      p_strm_lalevl_tbl      =>  l_strm_lalevl_tbl,
9569                      p_transaction_date     =>  l_reamort_date,
9570                      x_stream_trx_tbl       =>  x_strm_trx_tbl
9571                      );
9572 
9573     print_debug('After Mass Rebook status: '||x_return_status||' Error: '||x_msg_data);
9574     print_debug('After Mass Rebook x_strm_trx_tbl.count: '|| x_strm_trx_tbl.count);
9575     FND_FILE.PUT_LINE (FND_FILE.LOG,'After mass rebook Stream Table count: '|| x_strm_trx_tbl.count);
9576 
9577     IF (x_return_status <> OKL_API.G_RET_STS_SUCCESS) THEN
9578       FOR i in 1..x_msg_count
9579       LOOP
9580         FND_MSG_PUB.GET(
9581                         p_msg_index     => i,
9582                         p_encoded       => FND_API.G_FALSE,
9583                         p_data          => x_msg_data,
9584                         p_msg_index_out => l_msg_index_out
9585                        );
9586         FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Error: '||to_char(i)||': '||x_msg_data);
9587         FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Message Index: '||l_msg_index_out);
9588         print_debug('Error '||to_char(i)||': '||x_msg_data);
9589         print_debug('Message Index: '||l_msg_index_out);
9590       END LOOP;
9591 
9592       IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
9593    	          RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
9594       ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
9595    	          RAISE OKL_API.G_EXCEPTION_ERROR;
9596       END IF;
9597     ELSE
9598       i := x_strm_trx_tbl.first;
9599       l_child_trx_id := x_strm_trx_tbl(i).trx_number;
9600       x_child_trx_id :=l_child_trx_id;
9601 
9602       print_debug('child trx number :' || l_child_trx_id);
9603       loop
9604         exit when i is null;
9605         print_debug('x_strm_trx_tbl - element # ' || i || ' : ' || x_strm_trx_tbl(i).trx_number);
9606         i := x_strm_trx_tbl.next(i);
9607       end loop;
9608 
9609       -- Updating the Interest Calculation Date
9610 
9611        print_debug('Khr id : ' || p_chr_id || ' Frequency : ' || l_frequency);
9612        print_debug('Before updating  date_last_interim_interest_cal');
9613        if(l_frequency = 'M') THEN
9614               UPDATE okl_k_headers khr
9615               SET khr.date_last_interim_interest_cal =  add_months(l_reamort_date,1)
9616               where khr.id = p_chr_id;
9617        elsif(l_frequency = 'Q') THEN
9618               UPDATE okl_k_headers khr
9619               SET khr.date_last_interim_interest_cal =  add_months(l_reamort_date,3)
9620               where khr.id = p_chr_id;
9621        elsif(l_frequency = 'S') THEN
9622               UPDATE okl_k_headers khr
9623               SET khr.date_last_interim_interest_cal =  add_months(l_reamort_date,6)
9624               where khr.id = p_chr_id;
9625        elsif(l_frequency = 'A') THEN
9626               UPDATE okl_k_headers khr
9627               SET khr.date_last_interim_interest_cal =  add_months(l_reamort_date,12)
9628               where khr.id = p_chr_id;
9629        end if;
9630        print_debug('After updating  date_last_interim_interest_cal');
9631 
9632 
9633        --only for inbound supertrump call
9634        IF (p_trx_id IS NOT NULL) THEN
9635          print_debug('Fetching Var Int Process Id for trx number: ' || p_trx_id);
9636          OPEN l_vip_csr(p_trx_id);
9637          FETCH l_vip_csr INTO l_vipv_rec.id;
9638          IF l_vip_csr%NOTFOUND THEN
9639                 print_debug('Var Int Process Id not found for trx number: ' || p_trx_id);
9640          ELSE
9641                 print_debug('Var Int Process Id found for trx number: ' || p_trx_id);
9642          END IF;
9643          CLOSE l_vip_csr;
9644 
9645          i := x_strm_trx_tbl.first;
9646          l_vipv_rec.child_trx_id             :=  x_strm_trx_tbl(i).trx_number;
9647          i := null;
9648 
9649 
9650          print_debug('Before updating okl_var_int_process_b');
9651          OKL_VIP_PVT.update_row(
9652                  p_api_version                        => p_api_version,
9653   	             p_init_msg_list                      => p_init_msg_list,
9654           		   x_return_status	   			            => x_return_status,
9655   						   x_msg_count	   			                => x_msg_count,
9656   						   x_msg_data	   		                    => x_msg_data,
9657                  p_vipv_rec                           => l_vipv_rec,
9658                  x_vipv_rec                           => x_vipv_rec);
9659          print_debug('After updating okl_var_int_process_b, Status => ' || x_return_status);
9660          print_debug('****End-Creating Rent Levels and ReBooking.');
9661          print_debug('****Exiting procedure VAR_INT_RENT_LEVEL****');
9662 
9663 
9664          IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
9665      	          RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
9666          ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
9667      	          RAISE OKL_API.G_EXCEPTION_ERROR;
9668          END IF;
9669        END IF;
9670    END IF;
9671   Exception
9672    	WHEN OTHERS THEN
9673       print_debug('sqlcode : ' || sqlcode || ' $ sqlerrm : ' || sqlerrm);
9674    		x_return_status := OKL_API.HANDLE_EXCEPTIONS (
9675     					p_api_name	=> l_api_name,
9676     					p_pkg_name	=> G_PKG_NAME,
9677     					p_exc_name	=> 'OTHERS',
9678     					x_msg_count	=> x_msg_count,
9679     					x_msg_data	=> x_msg_data,
9680     					p_api_type	=> '_PVT');
9681 
9682 
9683   END var_int_rent_level;
9684 ------------------------------------------------------------------------------
9685 
9686     -- Start of Comments
9687     -- Created By:       Ramesh Seela
9688     -- Procedure Name    Create_Daily_Interest_Streams
9689     -- Description:      This procedure is called by Daily Interest Calculation program
9690     --                   Inputs :
9691     --                   Output :
9692     -- Dependencies:
9693     -- Parameters:
9694     -- Version:          1.0
9695     -- End of Comments
9696 
9697   ------------------------------------------------------------------------------
9698   Procedure Create_Daily_Interest_Streams (
9699             p_api_version             IN  NUMBER,
9700             p_init_msg_list           IN  VARCHAR2 DEFAULT OKL_API.G_FALSE,
9701             x_return_status           OUT NOCOPY VARCHAR2,
9702             x_msg_count               OUT NOCOPY NUMBER,
9703             x_msg_data                OUT NOCOPY VARCHAR2,
9704             p_contract_id             IN  NUMBER,
9705             p_line_id                 IN  NUMBER DEFAULT NULL, -- not currently used
9706             p_amount                  IN  NUMBER,
9707             p_due_date                IN  DATE,
9708             p_stream_type_purpose     IN  VARCHAR2,
9709             p_create_invoice_flag     IN  VARCHAR2 DEFAULT OKL_API.G_TRUE,
9710  	        p_process_flag            IN  VARCHAR2 DEFAULT NULL,
9711 			p_currency_code           IN  VARCHAR2 DEFAULT NULL ) IS
9712 
9713   l_api_name                  CONSTANT    VARCHAR2(30) := 'CREATE_DAILY_INTEREST_STREAMS';
9714   l_api_version               CONSTANT    NUMBER       := 1.0;
9715   l_invoice_id                NUMBER;
9716   l_stream_element_id         OKL_STRM_ELEMENTS_V.id%TYPE;
9717   i_vir_tbl                   vir_tbl_type;
9718   r_vir_tbl                   vir_tbl_type;
9719   Create_Daily_Int_Str_failed EXCEPTION;
9720   l_asset_cost                NUMBER;
9721   l_total_asset_val           NUMBER := 0;
9722   l_asset_line_tbl            okl_kle_pvt.kle_tbl_type;
9723   l_line_index                NUMBER := 0;
9724   l_index                     NUMBER := 0;
9725   l_asset_line_tbl_count      NUMBER := 0;
9726   l_invoice_amt               NUMBER;
9727   l_prorated_invoice_amt      NUMBER := 0;
9728 
9729 
9730   CURSOR contract_line_csr (p_khr_id NUMBER, p_due_date DATE) IS
9731     SELECT id
9732     FROM   okl_k_lines_full_v
9733     WHERE  chr_id = p_khr_id
9734     AND    lse_id = G_FIN_LINE_LTY_ID
9735     AND    nvl(date_terminated, p_due_date + 1) > p_due_date
9736     ORDER BY id;
9737 
9738 
9739   BEGIN
9740     print_debug('Executing procedure CREATE_DAILY_INTEREST_STREAMS using following parameters : ');
9741     print_debug(' p_contract_id : '|| p_contract_id );
9742 	print_debug(' p_line_id : '|| p_line_id);
9743     print_debug(' p_amount : '|| p_amount );
9744 	print_debug(' p_due_date: '|| p_due_date);
9745     print_debug(' p_stream_type_purpose : '||p_stream_type_purpose);
9746 	print_debug(' p_create_invoice_flag: '|| p_create_invoice_flag);
9747     print_debug(' p_process_flag : '|| p_process_flag);
9748 
9749     x_return_status               := OKL_API.G_RET_STS_SUCCESS;
9750 
9751 	Initialize_contract_params( p_api_version   => 1.0,
9752                                 p_init_msg_list => OKL_API.G_FALSE,
9753                                 x_return_status => x_return_status,
9754                                 x_msg_count     => x_msg_count,
9755                                 x_msg_data      => x_msg_data,
9756                                 p_contract_id   => p_contract_id
9757                               );
9758     IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
9759 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS completed successfully');
9760     ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
9761   	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
9762   	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
9763        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
9764     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
9765 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
9766 	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
9767        RAISE Create_Daily_Int_Str_failed;
9768     END IF;
9769 
9770     IF (p_stream_type_purpose = 'DAILY_INTEREST_INTEREST') THEN
9771 
9772       Create_Stream_Invoice (
9773              p_api_version            => 1.0,
9774              p_init_msg_list          => OKL_API.G_FALSE,
9775              x_return_status          => x_return_status,
9776              x_msg_count              => x_msg_count,
9777              x_msg_data               => x_msg_data,
9778              p_contract_id            => p_contract_id,
9779              p_line_id                => NULL,
9780              p_amount                 => p_amount,
9781              p_due_date               => p_due_date,
9782              p_stream_type_purpose    => p_stream_type_purpose,
9783              p_create_invoice_flag    => p_create_invoice_flag,
9784              p_process_flag           => p_process_flag,
9785              p_parent_strm_element_id => NULL,
9786 		     x_invoice_id             => l_invoice_id,
9787 			 x_stream_element_id      => l_stream_element_id);
9788 
9789       IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
9790         print_error_message('Unexpected error raised in call to CREATE_STREAM_INVOICE');
9791         RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
9792       ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
9793         print_error_message('Error raised in call to CREATE_STREAM_INVOICE');
9794         RAISE Create_Daily_Int_Str_failed;
9795       END IF;
9796 
9797       i_vir_tbl := g_vir_tbl;
9798 
9799       upd_vir_params_with_invoice (
9800               p_api_version   => 1.0,
9801               p_init_msg_list => OKL_API.G_TRUE,
9802               x_return_status => x_return_status,
9803               x_msg_count     => x_msg_count,
9804               x_msg_data      => x_msg_data,
9805               p_source_id     => l_stream_element_id,
9806               p_vir_tbl       => i_vir_tbl,
9807               x_vir_tbl       => r_vir_tbl);
9808       IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
9809         print_error_message('Unexpected error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
9810         RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
9811       ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
9812         print_error_message('Error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
9813         RAISE Create_Daily_Int_Str_failed;
9814       END IF;
9815 
9816       g_vir_tbl := r_vir_tbl;
9817 
9818       populate_vir_params(
9819                p_api_version    => 1.0,
9820                p_init_msg_list  => OKL_API.G_TRUE,
9821                x_return_status  => x_return_status,
9822                x_msg_count      => x_msg_count,
9823                x_msg_data       => x_msg_data,
9824                p_vir_tbl        => g_vir_tbl);
9825       IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
9826         print_error_message('Unexpected error raised in call to POPULATE_VIR_PARAMS');
9827         RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
9828       ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
9829         print_error_message('Error raised in call to POPULATE_VIR_PARAMS');
9830         RAISE Create_Daily_Int_Str_failed;
9831       END IF;
9832 
9833       g_vir_tbl.delete;
9834 	  g_vir_tbl_counter := 0;
9835 
9836 	ELSIF (p_stream_type_purpose = 'DAILY_INTEREST_PRINCIPAL') THEN
9837 	  l_total_asset_val := 0;
9838 	  FOR current_line in contract_line_csr(p_contract_id, p_due_date)
9839 	  LOOP
9840         -- Derive Asset Cost
9841         Okl_Execute_Formula_Pub.EXECUTE(
9842 		    p_api_version          => 1.0,
9843             p_init_msg_list        => OKL_API.G_FALSE,
9844             x_return_status        => x_return_status,
9845             x_msg_count            => x_msg_count,
9846             x_msg_data             => x_msg_data,
9847             p_formula_name         => 'LINE_OEC',
9848             p_contract_id          => p_contract_id,
9849             p_line_id              => current_line.id,
9850             x_value               =>  l_asset_cost);
9851         IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
9852 	      print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE completed successfully');
9853         ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
9854 	      print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned unexpected error');
9855 	      print_error_message ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned unexpected error');
9856           RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
9857         ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
9858   	      print_debug ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned exception');
9859 	      print_error_message ('Procedure OKL_EXECUTE_FORMULA_PUB.EXECUTE returned exception');
9860           RAISE Create_Daily_Int_Str_failed;
9861         END IF;
9862 
9863         IF (l_asset_cost > 0) THEN
9864           l_line_index                          := l_line_index + 1;
9865           l_asset_line_tbl(l_line_index).id     := current_line.id;
9866           l_asset_line_tbl(l_line_index).amount := l_asset_cost;
9867           l_total_asset_val                     := l_total_asset_val + l_asset_cost;
9868           print_debug('Asset id :' || l_asset_line_tbl(l_line_index).id || ' Asset Cost :' || l_asset_cost);
9869         END IF;
9870 	  END LOOP;
9871 
9872       l_asset_line_tbl_count := l_asset_line_tbl.COUNT;
9873       l_invoice_amt          := p_amount;
9874 
9875       IF (l_asset_line_tbl_count > 0) THEN
9876         print_debug('Creating DAILY_INTEREST_PRINCIPAL streams for assets.');
9877 
9878         FOR l_index in 1 .. l_asset_line_tbl_count
9879         LOOP
9880           l_prorated_invoice_amt := OKL_ACCOUNTING_UTIL.round_amount((l_asset_line_tbl(l_index).amount * l_invoice_amt / l_total_asset_val),p_currency_code);
9881 
9882           print_debug('Creating DAILY_INTEREST_PRINCIPAL streams for asset id : ' || l_asset_line_tbl(l_index).id || ' for Amount :' || l_prorated_invoice_amt);
9883 
9884           Create_Stream_Invoice (
9885                  p_api_version            => 1.0,
9886                  p_init_msg_list          => OKL_API.G_FALSE,
9887                  x_return_status          => x_return_status,
9888                  x_msg_count              => x_msg_count,
9889                  x_msg_data               => x_msg_data,
9890                  p_contract_id            => p_contract_id,
9891                  p_line_id                => l_asset_line_tbl(l_index).id,
9892                  p_amount                 => l_prorated_invoice_amt,
9893                  p_due_date               => p_due_date,
9894                  p_stream_type_purpose    => p_stream_type_purpose,
9895                  p_create_invoice_flag    => p_create_invoice_flag,
9896                  p_process_flag           => p_process_flag,
9897                  p_parent_strm_element_id => NULL,
9898        			 x_invoice_id             => l_invoice_id,
9899             	 x_stream_element_id      => l_stream_element_id);
9900 
9901           IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
9902             print_error_message('Unexpected error raised in call to CREATE_STREAM_INVOICE');
9903             RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
9904           ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
9905             print_error_message('Error raised in call to CREATE_STREAM_INVOICE');
9906             RAISE Create_Daily_Int_Str_failed;
9907           END IF;
9908           print_debug('Successfully created DAILY_INTEREST_PRINCIPAL streams for asset id : ' || l_asset_line_tbl(l_index).id || ' for Amount :' || l_prorated_invoice_amt);
9909           l_invoice_amt     := l_invoice_amt - l_prorated_invoice_amt;
9910 		  l_total_asset_val := l_total_asset_val - l_asset_line_tbl(l_index).amount;
9911         END LOOP;
9912       ELSE /* The contract is a revolving loan */
9913         print_debug('Creating DAILY_INTEREST_PRINCIPAL streams '|| ' for Amount :' || l_invoice_amt);
9914 
9915         Create_Stream_Invoice (
9916                p_api_version            => 1.0,
9917                p_init_msg_list          => OKL_API.G_FALSE,
9918                x_return_status          => x_return_status,
9919                x_msg_count              => x_msg_count,
9920                x_msg_data               => x_msg_data,
9921                p_contract_id            => p_contract_id,
9922                p_line_id                => NULL,
9923                p_amount                 => l_invoice_amt,
9924                p_due_date               => p_due_date,
9925                p_stream_type_purpose    => p_stream_type_purpose,
9926                p_create_invoice_flag    => p_create_invoice_flag,
9927                p_process_flag           => p_process_flag,
9928                p_parent_strm_element_id => NULL,
9929    			   x_invoice_id             => l_invoice_id,
9930                x_stream_element_id      => l_stream_element_id);
9931 
9932         IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
9933           print_error_message('Unexpected error raised in call to CREATE_STREAM_INVOICE');
9934           RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
9935         ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
9936           print_error_message('Error raised in call to CREATE_STREAM_INVOICE');
9937           RAISE Create_Daily_Int_Str_failed;
9938         END IF;
9939         print_debug('Successfully created DAILY_INTEREST_PRINCIPAL streams ' || ' for Amount :' || l_invoice_amt);
9940 
9941       END IF;
9942     END IF;
9943 
9944   EXCEPTION
9945     WHEN Create_Daily_Int_Str_failed THEN
9946       print_error_message('Exception Create_Daily_Int_Str_failed raised in procedure CREATE_DAILY_INTEREST_STREAMS');
9947       x_return_status := OKL_API.G_RET_STS_ERROR;
9948     WHEN OTHERS THEN
9949       print_error_message('Exception raised in procedure CREATE_DAILY_INTEREST_STREAMS');
9950       x_return_status := OKL_API.G_RET_STS_ERROR;
9951       Okl_Api.SET_MESSAGE(
9952               p_app_name     => G_APP_NAME,
9953               p_msg_name     => G_UNEXPECTED_ERROR,
9954               p_token1       => G_SQLCODE_TOKEN,
9955               p_token1_value => SQLCODE,
9956               p_token2       => G_SQLERRM_TOKEN,
9957               p_token2_value => SQLERRM);
9958 
9959   END Create_Daily_Interest_Streams;
9960 ------------------------------------------------------------------------------
9961 
9962     -- Start of Comments
9963     -- Created By:       Ramesh Seela
9964     -- Procedure Name    calculate_total_interest_due
9965     -- Description:      This procedure is called by Variable Interest Calculation for Loans
9966     --                   Inputs :
9967     --                   Output : Interest Calculated
9968     -- Dependencies:
9969     -- Parameters:       Start Date, End Date, Interest Rate Range.
9970     -- Version:          1.0
9971     -- End of Comments
9972 
9973   ------------------------------------------------------------------------------
9974   FUNCTION calculate_total_interest_due(
9975             p_api_version     IN  NUMBER,
9976             p_init_msg_list   IN  VARCHAR2,
9977             x_return_status   OUT NOCOPY VARCHAR2,
9978             x_msg_count       OUT NOCOPY NUMBER,
9979             x_msg_data        OUT NOCOPY VARCHAR2,
9980             p_contract_id     IN  NUMBER,
9981             p_currency_code   IN  VARCHAR2,
9982             p_start_date      IN  DATE,
9983             p_due_date        IN  DATE,
9984             p_principal_basis IN  VARCHAR2 DEFAULT NULL) RETURN NUMBER IS
9985 
9986   l_api_version             CONSTANT NUMBER := 1.0;
9987   l_api_name	            CONSTANT VARCHAR2(30) := 'CALCULATE_TOTAL_INTEREST_DUE';
9988   l_return_status           VARCHAR2(1) := OKL_API.G_RET_STS_SUCCESS;
9989   l_interest_calculated     NUMBER := 0;
9990   r_principal_balance_tbl   principal_balance_tbl_typ;
9991 --  l_interest_basis          OKL_K_RATE_PARAMS.interest_basis_code%TYPE;
9992 --  l_formula_id              OKL_K_RATE_PARAMS.calculation_formula_id%TYPE;
9993   l_formula_name            OKL_FORMULAE_V.name%TYPE;
9994   calc_total_int_due_failed EXCEPTION;
9995 
9996 /*
9997   Cursor interest_params_csr (p_contract_id NUMBER, p_effective_date DATE) IS
9998       SELECT interest_basis_code, calculation_formula_id
9999       FROM   okl_k_rate_params
10000       WHERE  khr_id = p_contract_id
10001       AND    p_effective_date BETWEEN effective_from_date and nvl(effective_to_date, p_effective_date)
10002       AND    parameter_type_code = 'ACTUAL';
10003 */
10004 
10005   Cursor formula_csr (p_formula_id NUMBER) IS
10006       SELECT name
10007       FROM   okl_formulae_v
10008       WHERE  id = p_formula_id;
10009 
10010 /*
10011   Cursor interest_calc_basis_csr (p_contract_id NUMBER) IS
10012       SELECT ppm.interest_calculation_basis
10013       FROM   okl_k_headers khr,
10014              okl_product_parameters_v ppm
10015        WHERE khr.pdt_id = ppm.id
10016          AND khr.id = p_contract_id;
10017 */
10018 
10019   BEGIN
10020     ------------------------------------------------------------
10021     -- Start processing
10022     ------------------------------------------------------------
10023 
10024     x_return_status := OKL_API.G_RET_STS_SUCCESS;
10025 
10026     print_debug('Executing function CALCULATE_TOTAL_INTEREST_DUE using following parameters : ');
10027     print_debug('contract ID : '|| p_contract_id);
10028 	print_debug('Currency Code : '|| p_currency_code);
10029 	print_debug('start date : '|| p_start_date);
10030 	print_Debug('Due date : '|| p_due_date);
10031 
10032 	Initialize_contract_params( p_api_version   => 1.0,
10033                                 p_init_msg_list => OKL_API.G_FALSE,
10034                                 x_return_status => x_return_status,
10035                                 x_msg_count     => x_msg_count,
10036                                 x_msg_data      => x_msg_data,
10037                                 p_contract_id   => p_contract_id
10038                               );
10039     IF (x_return_status = Okl_Api.G_RET_STS_SUCCESS) THEN
10040 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS completed successfully');
10041     ELSIF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
10042   	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
10043   	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned unexpected error');
10044        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
10045     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
10046 	   print_debug ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
10047 	   print_error_message ('Procedure INITIALIZE_CONTRACT_PARAMS returned exception');
10048        RAISE calc_total_int_due_failed;
10049     END IF;
10050 
10051 /*
10052     OPEN  interest_params_csr(p_contract_id, SYSDATE);
10053     FETCH interest_params_csr INTO l_interest_basis, l_formula_id;
10054     IF (interest_params_csr%NOTFOUND) THEN
10055       CLOSE interest_params_csr;
10056       print_error_message('Interest Params cursor did not return any records for contract ID: '|| p_contract_id);
10057       RAISE calc_total_int_due_failed;
10058     END IF;
10059     CLOSE interest_params_csr;
10060 
10061     OPEN  interest_calc_basis_csr(p_contract_id);
10062     FETCH interest_calc_basis_csr INTO g_interest_calculation_basis;
10063     IF (interest_calc_basis_csr%NOTFOUND) THEN
10064       CLOSE interest_calc_basis_csr;
10065       print_error_message('Interest calculation Basis cursor did not return any records for contract ID: '|| p_contract_id);
10066       RAISE calc_total_int_due_failed;
10067     END IF;
10068     CLOSE interest_calc_basis_csr;
10069 */
10070 
10071     print_debug('Interest Basis: '|| G_INTEREST_BASIS_CODE || ' formula ID :'|| G_CALCULATION_FORMULA_ID);
10072 
10073     IF (G_INTEREST_BASIS_CODE = 'SIMPLE') THEN
10074 
10075        prin_date_range_var_rate_ctr (
10076                                      p_api_version           => 1.0,
10077                                      p_init_msg_list         => OKL_API.G_FALSE,
10078                                      x_return_status         => x_return_status,
10079                                      x_msg_count             => x_msg_count,
10080                                      x_msg_data              => x_msg_data,
10081                                      p_contract_id           => p_contract_id,
10082                                      p_line_id               => NULL,
10083                                      p_start_date            => p_start_date,
10084                                      p_due_date              => p_due_date,
10085                                      p_principal_basis       => p_principal_basis,
10086                                      x_principal_balance_tbl => r_principal_balance_tbl);
10087        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
10088          print_error_message('Unexpected error raised in call to PRIN_DATE_RANGE_VAR_RATE_CTR');
10089          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
10090        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
10091          print_error_message('Error raised in call to PRIN_DATE_RANGE_VAR_RATE_CTR');
10092          RAISE calc_total_int_due_failed;
10093        END IF;
10094        print_debug ('Before call to Calc_Variable_Rate_Interest');
10095 
10096        l_interest_calculated := Calc_Variable_Rate_Interest (
10097                                                              p_api_version           => p_api_version,
10098                                                              p_init_msg_list         => OKL_API.G_FALSE,
10099                                                              x_return_status         => x_return_status,
10100                                                              x_msg_count             => x_msg_count,
10101                                                              x_msg_data              => x_msg_data,
10102                                                              p_contract_id           => p_contract_id,
10103                                                              p_currency_code         => p_currency_code,
10104                                                              p_principal_balance_tbl => r_principal_balance_tbl);
10105        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
10106          print_error_message('Unexpected error raised in call to CALC_VARIABLE_RATE_INTEREST');
10107          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
10108        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
10109          print_error_message('Error raised in call to CALC_VARIABLE_RATE_INTEREST');
10110          RAISE calc_total_int_due_failed;
10111        END IF;
10112     ELSE
10113        OPEN  formula_csr(G_CALCULATION_FORMULA_ID);
10114        FETCH formula_csr INTO l_formula_name;
10115        IF (formula_csr%NOTFOUND) THEN
10116          CLOSE formula_csr;
10117          print_error_message('Formula cursor did not return any records for formula ID: '|| G_CALCULATION_FORMULA_ID);
10118          RAISE calc_total_int_due_failed;
10119        END IF;
10120        CLOSE formula_csr;
10121 
10122        -- Derive Interest using formula
10123        Okl_Execute_Formula_Pub.EXECUTE(p_api_version          => 1.0,
10124                                        p_init_msg_list        => OKL_API.G_TRUE,
10125                                        x_return_status        => x_return_status,
10126                                        x_msg_count            => x_msg_count,
10127                                        x_msg_data             => x_msg_data,
10128                                        p_formula_name         => l_formula_name,
10129                                        p_contract_id          => p_contract_id,
10130                                        p_line_id              => NULL,
10131                                        x_value               =>  l_interest_calculated
10132                                       );
10133        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
10134          print_error_message('Unexpected error raised in call to OKL_EXECUTE_FORMULA_PUB.EXECUTE');
10135          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
10136        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
10137          print_error_message('Error raised in call to OKL_EXECUTE_FORMULA_PUB.EXECUTE');
10138          RAISE calc_total_int_due_failed;
10139        END IF;
10140     END IF;
10141     RETURN l_interest_calculated;
10142   EXCEPTION
10143     WHEN calc_total_int_due_failed THEN
10144       print_error_message('Exception calc_total_int_due_failed raised in function CALCULATE_TOTAL_INTEREST_DUE');
10145       x_return_status := OKL_API.G_RET_STS_ERROR;
10146       RETURN -1;
10147     WHEN OTHERS  THEN
10148       print_error_message('Exception raised in function CALCULATE_TOTAL_INTEREST_DUE');
10149       Okl_Api.SET_MESSAGE(
10150               p_app_name     => G_APP_NAME,
10151               p_msg_name     => G_UNEXPECTED_ERROR,
10152               p_token1       => G_SQLCODE_TOKEN,
10153               p_token1_value => SQLCODE,
10154               p_token2       => G_SQLERRM_TOKEN,
10155               p_token2_value => SQLERRM);
10156 
10157       x_return_status := OKL_API.G_RET_STS_ERROR;
10158       RETURN -1;
10159   END calculate_total_interest_due;
10160 
10161   PROCEDURE initiate_request(p_api_version        IN  NUMBER,
10162 			             p_init_msg_list      IN  VARCHAR2,
10163                    p_khr_id            IN  NUMBER,
10164 --					         p_from_date          IN  DATE,
10165 --					         p_to_date            IN  DATE,
10166 					         x_return_status      OUT NOCOPY VARCHAR2,
10167 					         x_msg_count          OUT NOCOPY NUMBER,
10168 					         x_msg_data           OUT NOCOPY VARCHAR2)
10169 					         --x_request_id         OUT NOCOPY NUMBER,
10170 					         --x_trans_status       OUT NOCOPY VARCHAR2)
10171   IS
10172 
10173 
10174   l_vipv_rec                         vipv_rec;
10175   x_vipv_rec                         vipv_rec;
10176   l_skip_prc_engine                  VARCHAR2(1) := OKL_API.G_FALSE;
10177   --l_rents_tbl and l_rents_tbl_in used for lease processing
10178   l_rents_tbl                        Okl_Create_Streams_Pub.csm_periodic_expenses_tbl_type;
10179   l_rents_tbl_in                     Okl_Create_Streams_Pub.csm_periodic_expenses_tbl_type;
10180   --l_rents_prin_tbl used for loan processing
10181   l_rents_prin_tbl                   csm_periodic_expenses_tbl_type;
10182   l_csm_loan_header                  okl_create_streams_pvt.csm_loan_rec_type;
10183   l_csm_loan_lines_tbl               okl_create_streams_pvt.csm_loan_line_tbl_type;
10184   l_csm_loan_levels_tbl              okl_create_streams_pvt.csm_loan_level_tbl_type;
10185   l_csm_one_off_fee_tbl              Okl_Create_Streams_Pub.csm_one_off_fee_tbl_type;
10186   l_csm_periodic_expenses_tbl        Okl_Create_Streams_Pub.csm_periodic_expenses_tbl_type;
10187   l_csm_yields_tbl                   Okl_Create_Streams_Pub.csm_yields_tbl_type;
10188   l_csm_stream_types_tbl             Okl_Create_Streams_Pub.csm_stream_types_tbl_type;
10189   --p_csm_loan_levels_tbl              csm_loan_level_tbl_type;
10190   l_csm_loan_levels_tbl_in           csm_loan_level_tbl_type;
10191   l_csm_lease_header                 okl_create_streams_pvt.csm_lease_rec_type;
10192   l_csm_line_details_tbl             okl_create_streams_pvt.csm_line_details_tbl_type;
10193   l_req_stream_types_tbl             Okl_Create_Streams_Pub.csm_stream_types_tbl_type;
10194 
10195   l_index                         NUMBER := 0;
10196   l_return_status	                VARCHAR2(1) := Okc_Api.G_RET_STS_SUCCESS;
10197   l_api_name	                    CONSTANT VARCHAR2(30) := 'initiate_request';
10198   l_api_version	                  CONSTANT NUMBER := 1;
10199   l_start_date	                  DATE;
10200   amount			                    NUMBER;
10201   tot_amount                      NUMBER;
10202   l_no_of_periods	                NUMBER;
10203   l_reamort_date	                DATE;
10204   chr_start_date	                DATE;
10205   --l_interest_rec                    interest_rec;
10206   lx_interest_rec                 interest_rec;
10207   --i	                              NUMBER:=1;
10208   --j	                              NUMBER:=1;
10209   l_deal_type	                    OKL_K_HEADERS.DEAL_TYPE%TYPE;
10210   l_msg_index_out                 NUMBER;
10211   l_term_duration	                NUMBER;
10212   l_tot_principal_amount          NUMBER := 0;
10213   l_frequency                     okc_rules_b.object1_id1%type;
10214   l_csm_line_details_ctr          NUMBER;
10215   l_first_row                     NUMBER;
10216   l_loan_levels_cntr              NUMBER;
10217   l_loan_levels_date_start        DATE;
10218   l_period_cntr                   NUMBER := 0;
10219   l_number_of_periods             NUMBER := 0;
10220   l_adder_months                  NUMBER := 0;
10221   l_interest_rate_tbl             interest_rate_tbl_type;
10222   l_interest_rate_tbl_count       NUMBER;
10223   l_interest_rate_tbl_index       NUMBER;
10224   l_contract_number               okc_k_headers_b.contract_number%type;
10225   l_principal_balance_tbl         okl_variable_interest_pvt.principal_balance_tbl_typ;
10226   l_total_lending                 NUMBER;
10227 
10228   l_rent_date_start               DATE;
10229   l_rent_cntr                     NUMBER;
10230 
10231   l_level_date_start              DATE;
10232   l_stub_level_date_start         DATE;
10233 
10234   l_super_trump_request_id        NUMBER;
10235   l_trans_status                  OKL_STREAM_INTERFACES.SIS_CODE%TYPE;
10236 
10237   l_request_id                    NUMBER;
10238   l_program_application_id        NUMBER;
10239   l_program_id                    NUMBER;
10240   l_program_update_date           DATE;
10241   l_sequence                      NUMBER := 0;
10242   l_prev_kle_id                   NUMBER := NULL;
10243   l_remaining_term_in_months      NUMBER;
10244   l_child_trx_id                  NUMBER := NULL;
10245   l_advance_or_arrears            VARCHAR2(100) := NULL;
10246   --l_made_super_trump_call         BOOLEAN := TRUE;
10247   initiate_request_failed         EXCEPTION;
10248   -- Added by prasjain bug# 6142095
10249   l_interest_rate                 okl_var_int_params.INTEREST_RATE%type;
10250   l_rebook_flag                   BOOLEAN := TRUE;
10251   l_interest_calc_end_date        DATE;
10252   -- End by prasjain bug# 6142095
10253   --dkagrawa changed query to use view okl_prod_qlty_val_uv than okl_product_parameters_v for performance
10254   CURSOR c_chr_id (cp_khr_id VARCHAR2) IS
10255   SELECT okc.contract_number
10256        , NVL(okl.date_last_interim_interest_cal, okc.start_date) start_date
10257        , okl.deal_type deal_type
10258        , ppm.quality_val interest_calculation_basis
10259        , okc.authoring_org_id
10260        , round(months_between(okc.end_date, okl.date_last_interim_interest_cal)) remaining_term_in_months
10261   FROM   okc_k_headers_b okc
10262        , okl_k_headers okl
10263        , okl_prod_qlty_val_uv ppm
10264   WHERE  okc.id = cp_khr_id
10265   AND    okl.id = okc.id
10266   AND    okl.pdt_id = ppm.pdt_id
10267   AND    ppm.quality_name = 'INTEREST_CALCULATION_BASIS';
10268 
10269   /*CURSOR c_terms_cur (p_contract_id NUMBER, p_reamort_date DATE) IS
10270   SELECT max(sel.stream_element_date)
10271   FROM    okl_strm_elements sel,
10272           okl_streams     stm,
10273   	      okl_strm_type_b sty,
10274           okc_k_headers_b   khr
10275   WHERE	stm.khr_id          = p_contract_id
10276   AND	stm.active_yn		= 'Y'
10277   AND	stm.say_code		= 'CURR'
10278   AND	sty.id				= stm.sty_id
10279   AND   sty.stream_type_purpose = 'PRINCIPAL_PAYMENT'
10280   AND	sty.billable_yn		= 'Y'
10281   AND	sel.stm_id          = stm.id
10282   and   sel.stream_element_date <= p_reamort_date
10283   and   stm.khr_id          = khr.id;*/
10284 
10285   CURSOR c_periods_cur(p_contract_id NUMBER, p_period_date DATE) IS
10286   SELECT (KHR.TERM_DURATION - round(months_between(nvl(p_period_date,K.START_DATE), K.START_DATE))) MTH,
10287          KHR.TERM_DURATION  term_duration
10288   FROM   OKC_K_HEADERS_B K, OKL_K_HEADERS KHR
10289   WHERE  K.id  = p_contract_id
10290   and    K.id = KHR.id;
10291 
10292   CURSOR c_freq_cur(p_contract_id NUMBER) IS
10293   select object1_id1 from okc_rules_b
10294   where dnz_chr_id = p_contract_id
10295   and rule_information_category = 'LASLL';
10296 
10297   -- Added by prasjain bug# 6142095
10298   CURSOR var_int_params_csr (p_contract_id NUMBER) IS
10299     SELECT interest_rate,interest_calc_end_date
10300       FROM okl_var_int_params
10301      WHERE khr_id                 = p_contract_id
10302        AND INTEREST_CALC_END_DATE = (SELECT max(INTEREST_CALC_END_DATE) FROM okl_var_int_params WHERE khr_id = p_contract_id);
10303 
10304   CURSOR c_last_int_cur (p_contract_id NUMBER) IS
10305     SELECT NVL(date_last_interim_interest_cal, start_date) reamort_date
10306       FROM okl_k_headers_full_v
10307      WHERE id = p_contract_id;
10308    -- End by prasjain bug# 6142095
10309 --start |  19-May-08 cklee  fixed Bug 7043360                                       |
10310   l_line_id_buf okl_k_lines.id%type := -1;
10311 --end |  19-May-08 cklee  fixed Bug 7043360                                       |
10312 
10313   BEGIN
10314 
10315   	x_return_status := OKL_API.G_RET_STS_SUCCESS;
10316 
10317     print_debug('****Entering procedure INITIATE_REQUEST****');
10318     FND_FILE.PUT_LINE (FND_FILE.LOG,'Initiating Super Trump Request');
10319 
10320 
10321     OPEN c_chr_id(p_khr_id);
10322     FETCH c_chr_id INTO l_contract_number, l_start_date, G_DEAL_TYPE, G_INTEREST_CALCULATION_BASIS, G_AUTHORING_ORG_ID, l_remaining_term_in_months;
10323     CLOSE c_chr_id;
10324 
10325 
10326     /*if(p_from_date is null) THEN
10327             l_start_date := chr_start_date;
10328     else
10329         --I THINK WE DO NOT NEED THIS CODE
10330         --PLEASE CHECK
10331         OPEN c_terms_cur(p_khr_id, p_from_date);
10332         FETCH c_terms_cur INTO p_start_date;
10333         CLOSE c_terms_cur;
10334     end if;*/
10335 
10336 
10337 
10338     /*if (p_start_date is null) THEN
10339         p_start_date := p_from_date;
10340     end if;*/
10341 
10342     OPEN c_periods_cur(p_khr_id, l_start_date);
10343     FETCH c_periods_cur INTO l_no_of_periods, l_term_duration;
10344     CLOSE c_periods_cur;
10345 
10346     OPEN c_freq_cur(p_khr_id);
10347     FETCH c_freq_cur INTO l_frequency;
10348     CLOSE c_freq_cur;
10349 
10350     print_debug('From Date :'||l_start_date||' Interest Start Date: '||l_start_date||
10351                         ' Periods: '||l_no_of_periods);
10352     if(l_frequency = 'M') THEN
10353               l_no_of_periods := l_no_of_periods;
10354               l_adder_months := 1;
10355     elsif(l_frequency = 'Q') THEN
10356               l_no_of_periods := ROUND(l_no_of_periods/3);
10357               l_adder_months := 3;
10358     elsif(l_frequency = 'S') THEN
10359               l_no_of_periods := ROUND(l_no_of_periods/6);
10360               l_adder_months := 6;
10361     elsif(l_frequency = 'A') THEN
10362               l_no_of_periods := ROUND(l_no_of_periods/12);
10363               l_adder_months := 12;
10364     end if;
10365 
10366     --l_interest_rec.khr_id   := p_chr_id;
10367     --l_interest_rec.start_date := l_start_date;
10368 
10369     --CHANGE THIS CODE TO FETCH INTEREST RATE
10370     /*interest_cal(
10371                 p_api_version    =>     p_api_version,
10372                 p_init_msg_list  =>     p_init_msg_list,
10373                 x_return_status  =>     x_return_status,
10374                 x_msg_count      =>     x_msg_count,
10375                 x_msg_data       =>     x_msg_data,
10376                 p_interest_rec   =>     l_interest_rec,
10377                 x_interest_rec   =>     lx_interest_rec);
10378 
10379     print_debug('From Date :'||l_start_date||' Interest Start Date: '||l_start_date||
10380                         ' Periods: '||l_no_of_periods);*/
10381 
10382     interest_date_range (
10383             p_api_version       => p_api_version,
10384             p_init_msg_list     => p_init_msg_list,
10385             x_return_status     => x_return_status,
10386             x_msg_count         => x_msg_count,
10387             x_msg_data          => x_msg_data,
10388             p_contract_id       => p_khr_id,
10389             p_start_date        => l_start_date,
10390             p_end_date          => l_start_date,
10391             p_process_flag      => G_INTEREST_CALCULATION_BASIS, /* value is set in Calculate_total_interest_due */
10392             x_interest_rate_tbl => l_interest_rate_tbl);
10393 
10394     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
10395        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
10396     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
10397        RAISE initiate_request_failed;
10398     END IF;
10399 
10400     l_interest_rate_tbl_count := l_interest_rate_tbl.COUNT;
10401 
10402     print_debug('No. of records in Interest Date Range TAble : '|| l_interest_rate_tbl_count);
10403 
10404     IF (l_interest_rate_tbl_count = 0) THEN
10405        print_error_message('Interest rate unavailable.');
10406        RAISE initiate_request_failed;
10407     END IF;
10408     l_interest_rate_tbl_index := l_interest_rate_tbl.FIRST;
10409 
10410     -- Added by prasjain bug# 6142095
10411     OPEN var_int_params_csr(p_khr_id);
10412     FETCH var_int_params_csr INTO l_interest_rate,l_interest_calc_end_date;
10413     CLOSE var_int_params_csr;
10414 
10415     print_debug('Last interest rate calculated as  : '|| l_interest_rate);
10416     print_debug('Interest rate in Index  : '|| l_interest_rate_tbl(l_interest_rate_tbl_index).rate);
10417 
10418 --start |  30-Apr-08 cklee  fixed Bug 6994233                                       |
10419     OPEN c_last_int_cur (p_khr_id);
10420     FETCH c_last_int_cur INTO l_reamort_date;
10421     CLOSE c_last_int_cur;
10422 --end |  30-Apr-08 cklee  fixed Bug 6994233                                       |
10423 
10424     If l_interest_rate_tbl(l_interest_rate_tbl_index).rate = l_interest_rate then
10425 --start |  30-Apr-08 cklee  fixed Bug 6994233                                       |
10426 --       OPEN c_last_int_cur (p_khr_id);
10427 --       FETCH c_last_int_cur INTO l_reamort_date;
10428 --       CLOSE c_last_int_cur;
10429 --end |  30-Apr-08 cklee  fixed Bug 6994233                                       |
10430        -- if l_interest_calc_end_date is equal to l_reamort_date
10431        -- means that ESG got failed last time and we need to rebook the contract
10432        If TRUNC(l_interest_calc_end_date) <> TRUNC(l_reamort_date) then
10433          print_debug('Both interest rates are same hence rebooking is not required');
10434         l_rebook_flag := FALSE;
10435        End if;
10436     End if;
10437     -- End by prasjain bug# 6142095
10438 
10439     /*FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'From Date: ' || l_start_date);
10440     FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Interest Start Date: '||l_start_date);
10441     FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Periods: '||l_no_of_periods);
10442     FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Effective interest rate: '||lx_interest_rec.effective_rate);*/
10443     If l_rebook_flag  Then -- Added by prasjian bug# 6142095
10444     If (G_DEAL_TYPE = 'LOAN') THEN
10445       OKL_LA_STREAM_PUB.extract_params_loan_reamort(p_api_version               => p_api_version,
10446   	                             p_init_msg_list             => p_init_msg_list,
10447                                  p_chr_id                    => p_khr_id,
10448                     					   x_return_status             => x_return_status,
10449                 						     x_msg_count                 => x_msg_count,
10450                                  x_msg_data                  => x_msg_data,
10451                     					   x_csm_loan_header           => l_csm_loan_header,
10452                     					   x_csm_loan_lines_tbl        => l_csm_loan_lines_tbl,
10453                     					   x_csm_loan_levels_tbl       => l_csm_loan_levels_tbl,
10454                     					   x_csm_one_off_fee_tbl       => l_csm_one_off_fee_tbl,
10455                     					   x_csm_periodic_expenses_tbl => l_csm_periodic_expenses_tbl,
10456                     					   x_csm_yields_tbl            => l_csm_yields_tbl,
10457                     					   x_csm_stream_types_tbl      => l_csm_stream_types_tbl);
10458 
10459       IF (l_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
10460      		RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
10461      	ELSIF (l_return_status = OKL_API.G_RET_STS_ERROR) THEN
10462      		RAISE initiate_request_failed;
10463      	END IF;
10464 
10465       print_debug('Contents of l_csm_loan_levels_tbl after call to OKL_LA_STREAM_PUB.extract_params_loan.');
10466       print_loan_tables(p_rent_tbl => l_rents_prin_tbl,
10467                         p_csm_loan_level_tbl => l_csm_loan_levels_tbl);
10468 
10469       l_csm_loan_header.orp_code := Okl_Create_Streams_Pub.G_ORP_CODE_VARIABLE_INTEREST;
10470       l_csm_stream_types_tbl.DELETE;
10471       l_total_lending := 0;
10472       l_rents_prin_tbl.delete;
10473       l_sequence := 0;
10474 
10475       --FOR i IN 1..l_csm_loan_levels_tbl.COUNT
10476       l_loan_levels_cntr := l_csm_loan_levels_tbl.first;
10477       LOOP
10478           EXIT WHEN l_loan_levels_cntr IS NULL;
10479 
10480           --CHECK FOR level_type = Okl_Create_Streams_Pub.G_SFE_LEVEL_PRINCIPAL
10481           --DO NOT MAKE A PRICING CALL IN THIS CASE
10482           --for Principal Payments only
10483           IF(l_csm_loan_levels_tbl(l_loan_levels_cntr).level_type = Okl_Create_Streams_Pub.G_SFE_LEVEL_PRINCIPAL)
10484              AND (l_csm_loan_levels_tbl(l_loan_levels_cntr).lock_level_step = 'false' OR l_csm_loan_levels_tbl(l_loan_levels_cntr).lock_level_step = OKC_API.G_MISS_CHAR) THEN
10485             --call var_int_rent_level passing the level payments and interest rate
10486 
10487             IF (l_csm_loan_levels_tbl(l_loan_levels_cntr).period = 'T') THEN
10488               l_loan_levels_date_start := get_pay_level_start_date(l_csm_loan_levels_tbl(l_loan_levels_cntr).kle_loan_id,
10489                                   l_csm_loan_levels_tbl(l_loan_levels_cntr).level_index_number - 1);
10490               print_debug('Fetched start date from SLL - l_loan_levels_date_start: ' || l_loan_levels_date_start);
10491             ELSE
10492               l_loan_levels_date_start := l_csm_loan_levels_tbl(l_loan_levels_cntr).date_start;
10493             END IF;
10494             l_level_date_start := NULL;
10495             l_number_of_periods := 0;
10496             FOR l_period_cntr IN 1..l_csm_loan_levels_tbl(l_loan_levels_cntr).number_of_periods LOOP
10497                 IF (l_loan_levels_date_start >= l_start_date) THEN
10498                   l_number_of_periods := l_number_of_periods + 1;
10499 
10500                   IF (l_level_date_start IS NULL) THEN
10501                     IF (l_csm_loan_levels_tbl(l_loan_levels_cntr).period = 'T') THEN
10502                       --l_level_date_start := l_csm_loan_levels_tbl(l_loan_levels_cntr).date_start;
10503                       --when PRINCIPAL_PAYMENT is defined on a contract
10504                       --the payment levels are sent from initiate_request to var_int_rent_levels
10505                       --without making a pricing call
10506                       l_level_date_start := l_loan_levels_date_start;
10507                     ELSE
10508                       l_level_date_start := l_loan_levels_date_start;
10509                     END IF;
10510                   END IF;
10511                 END IF;
10512                 l_loan_levels_date_start := add_months(l_loan_levels_date_start,  l_adder_months);
10513             END LOOP;
10514 
10515             IF (l_number_of_periods > 0) THEN
10516               --WHEN I MAKE A CALL TO var_int_rent_level, PASSING l_rents_prin_tbl AS AN INPUT PARAMETER,
10517               --WILL THIS INFORMATION BE SUFFICIENT TO MAKE A REBOOK CALL
10518               --HOW DO I IDENTIFY THE LINE ID FROM TEH BELOW DATA?
10519               --CHECK WITH DEBDIP or ASHISH
10520               --l_rents_prin_tbl(l_loan_levels_cntr).description := l_csm_loan_levels_tbl(l_loan_levels_cntr).description;
10521               IF (NVl(l_prev_kle_id, -99) <> l_csm_loan_levels_tbl(l_loan_levels_cntr).kle_loan_id) THEN
10522                 --reset the sequence for the level_index_number for each asset
10523                 l_sequence := 1;
10524                 l_prev_kle_id := l_csm_loan_levels_tbl(l_loan_levels_cntr).kle_loan_id;
10525               ELSE
10526                 l_sequence := l_sequence + 1;
10527               END IF;
10528               --l_rents_prin_tbl(l_loan_levels_cntr).level_index_number := l_csm_loan_levels_tbl(l_loan_levels_cntr).level_index_number;
10529               l_rents_prin_tbl(l_loan_levels_cntr).level_index_number := l_sequence;
10530               l_rents_prin_tbl(l_loan_levels_cntr).number_of_periods := l_number_of_periods;
10531               l_rents_prin_tbl(l_loan_levels_cntr).level_type := l_csm_loan_levels_tbl(l_loan_levels_cntr).level_type;
10532               l_rents_prin_tbl(l_loan_levels_cntr).amount := l_csm_loan_levels_tbl(l_loan_levels_cntr).amount;
10533               l_rents_prin_tbl(l_loan_levels_cntr).advance_or_arrears := l_csm_loan_levels_tbl(l_loan_levels_cntr).advance_or_arrears;
10534               l_rents_prin_tbl(l_loan_levels_cntr).period := l_csm_loan_levels_tbl(l_loan_levels_cntr).period;
10535 		          l_rents_prin_tbl(l_loan_levels_cntr).lock_level_step := Okl_Create_Streams_Pub.G_LOCK_RATE;
10536               l_rents_prin_tbl(l_loan_levels_cntr).first_payment_date := l_level_date_start;
10537   	          l_rents_prin_tbl(l_loan_levels_cntr).rate := l_interest_rate_tbl(l_interest_rate_tbl_index).rate;
10538 
10539 /*              l_rents_prin_tbl(l_loan_levels_cntr).kle_asset_id := l_csm_loan_levels_tbl(l_loan_levels_cntr).kle_loan_id;
10540               l_rents_prin_tbl(l_loan_levels_cntr).income_or_expense := l_csm_loan_levels_tbl(l_loan_levels_cntr).income_or_expense;
10541               l_rents_prin_tbl(l_loan_levels_cntr).query_level_yn := Okl_Create_Streams_Pub.G_FND_YES;
10542               l_rents_prin_tbl(l_loan_levels_cntr).structure := l_csm_loan_levels_tbl(l_loan_levels_cntr).structure;
10543               l_rents_prin_tbl(l_loan_levels_cntr).days_in_month := l_csm_loan_levels_tbl(l_loan_levels_cntr).days_in_month;
10544               l_rents_prin_tbl(l_loan_levels_cntr).days_in_year := l_csm_loan_levels_tbl(l_loan_levels_cntr).days_in_year;
10545 */            END IF;
10546           --CHECK FOR RENT PAYMENT
10547           --for Rent and Unscheduled Principal Paydown
10548           ELSIF(l_csm_loan_levels_tbl(l_loan_levels_cntr).level_type = Okl_Create_Streams_Pub.G_SFE_LEVEL_PAYMENT)
10549             OR (l_csm_loan_levels_tbl(l_loan_levels_cntr).level_type = Okl_Create_Streams_Pub.G_SFE_LEVEL_PRINCIPAL AND
10550                 l_csm_loan_levels_tbl(l_loan_levels_cntr).lock_level_step = Okl_Create_Streams_Pub.G_LOCK_AMOUNT) THEN
10551             --if(j = 1) THEN
10552             --l_loan_levels_date_start := l_csm_loan_levels_tbl(l_loan_levels_cntr).date_start;
10553             IF (l_csm_loan_levels_tbl(l_loan_levels_cntr).period = 'T') THEN
10554               l_loan_levels_date_start := get_pay_level_start_date(l_csm_loan_levels_tbl(l_loan_levels_cntr).kle_loan_id,
10555                                   l_csm_loan_levels_tbl(l_loan_levels_cntr).level_index_number - 1);
10556               print_debug('Fetched start date from SLL - l_loan_levels_date_start: ' || l_loan_levels_date_start);
10557             ELSE
10558               l_loan_levels_date_start := l_csm_loan_levels_tbl(l_loan_levels_cntr).date_start;
10559             END IF;
10560 
10561             l_level_date_start := NULL;
10562             l_number_of_periods := 0;
10563             FOR l_period_cntr IN 1..l_csm_loan_levels_tbl(l_loan_levels_cntr).number_of_periods LOOP
10564                 IF (l_loan_levels_date_start >= l_start_date) THEN
10565                   l_number_of_periods := l_number_of_periods + 1;
10566 
10567                   IF (l_level_date_start IS NULL) THEN
10568                     --l_level_date_start := l_loan_levels_date_start;
10569                     IF (l_csm_loan_levels_tbl(l_loan_levels_cntr).period = 'T') THEN
10570                       l_level_date_start := l_csm_loan_levels_tbl(l_loan_levels_cntr).date_start;
10571                     ELSE
10572                       l_level_date_start := l_loan_levels_date_start;
10573                     END IF;
10574                   END IF;
10575                 END IF;
10576                 l_loan_levels_date_start := add_months(l_loan_levels_date_start,  l_adder_months);
10577             END LOOP;
10578 
10579             IF (l_number_of_periods > 0) THEN
10580               IF (NVl(l_prev_kle_id, -99) <> l_csm_loan_levels_tbl(l_loan_levels_cntr).kle_loan_id) THEN
10581                 --reset the sequence for the level_index_number for each asset
10582                 l_sequence := 1;
10583                 l_prev_kle_id := l_csm_loan_levels_tbl(l_loan_levels_cntr).kle_loan_id;
10584               ELSE
10585                 l_sequence := l_sequence + 1;
10586               END IF;
10587 
10588               l_csm_loan_levels_tbl_in(l_loan_levels_cntr) := l_csm_loan_levels_tbl(l_loan_levels_cntr);
10589               l_csm_loan_levels_tbl_in(l_loan_levels_cntr).level_index_number := l_sequence;
10590               l_csm_loan_levels_tbl_in(l_loan_levels_cntr).query_level_yn := Okl_Create_Streams_Pub.G_FND_YES;
10591   	          l_csm_loan_levels_tbl_in(l_loan_levels_cntr).rate := l_interest_rate_tbl(l_interest_rate_tbl_index).rate;
10592               IF (l_csm_loan_levels_tbl(l_loan_levels_cntr).level_type = Okl_Create_Streams_Pub.G_SFE_LEVEL_PAYMENT) THEN
10593 		          l_csm_loan_levels_tbl_in(l_loan_levels_cntr).lock_level_step := Okl_Create_Streams_Pub.G_LOCK_RATE;
10594               ELSIF (l_csm_loan_levels_tbl(l_loan_levels_cntr).level_type = Okl_Create_Streams_Pub.G_SFE_LEVEL_PRINCIPAL) THEN
10595                   l_csm_loan_levels_tbl_in(l_loan_levels_cntr).lock_level_step := Okl_Create_Streams_Pub.G_LOCK_BOTH;
10596               END IF;
10597               l_csm_loan_levels_tbl_in(l_loan_levels_cntr).date_start := l_level_date_start;
10598               l_csm_loan_levels_tbl_in(l_loan_levels_cntr).number_of_periods := l_number_of_periods;
10599             END IF;
10600           ELSIF(l_csm_loan_levels_tbl(l_loan_levels_cntr).level_type = Okl_Create_Streams_Pub.G_SFE_LEVEL_FUNDING) THEN
10601             --is the below code OK
10602             --will this table, l_csm_loan_levels_tbl, have more than 1 row
10603             --looks like each row is being populated with the principal at the contract level and
10604             --not at the asset level
10605             --since I am changing the above code for PAYMENTS, does this code need to channge also?
10606             --THIS TABLE MUST BE POPULATED WITH ASSET LEVEL PRINCIPAL BALANCES
10607             --THERE WILL BE 1 ROW FOR EACH ASSET
10608             --ASSET IDENTIFIER kle_loan_id
10609             IF (NVl(l_prev_kle_id, -99) <> l_csm_loan_levels_tbl(l_loan_levels_cntr).kle_loan_id) THEN
10610               --reset the sequence for the level_index_number for each asset
10611               l_sequence := 1;
10612               l_prev_kle_id := l_csm_loan_levels_tbl(l_loan_levels_cntr).kle_loan_id;
10613             ELSE
10614               l_sequence := l_sequence + 1;
10615             END IF;
10616 
10617             l_csm_loan_levels_tbl_in(l_loan_levels_cntr) := l_csm_loan_levels_tbl(l_loan_levels_cntr);
10618             l_csm_loan_levels_tbl_in(l_loan_levels_cntr).level_index_number := l_sequence;
10619        		  l_csm_loan_levels_tbl_in(l_loan_levels_cntr).query_level_yn := Okl_Create_Streams_Pub.G_FND_YES;
10620 
10621             --if the level type is not Principal Paydown then
10622             --get the principal balance
10623             IF (NVL(l_csm_loan_levels_tbl_in(l_loan_levels_cntr).period, 'DMF') <> 'T') THEN
10624               l_csm_loan_levels_tbl_in(l_loan_levels_cntr).number_of_periods := l_no_of_periods;
10625   			      l_csm_loan_levels_tbl_in(l_loan_levels_cntr).date_start := l_start_date;
10626 
10627 --start |  19-May-08 cklee  fixed Bug 7043360                                       |
10628 -- note: Based on the API: prin_date_range_var_rate_ctr, we need to pass p_line_id only once to get the
10629 -- the total principal balance. So we limit one p_line_id to pass to the following API.
10630 -- Additionally, we assume the l_csm_loan_levels_tbl_in is group by kle_loan_id (p_line_id), otherwise
10631 -- the follow if statement won't work properly to get the nly one p_line_id.
10632             IF l_line_id_buf <> l_csm_loan_levels_tbl_in(l_loan_levels_cntr).kle_loan_id then
10633 --end |  19-May-08 cklee  fixed Bug 7043360                                       |
10634                   OKL_VARIABLE_INTEREST_PVT.prin_date_range_var_rate_ctr (
10635                           p_api_version        => p_api_version,
10636                           p_init_msg_list      => p_init_msg_list,
10637                           x_return_status      => x_return_status,
10638                           x_msg_count          => x_msg_count,
10639                           x_msg_data           => x_msg_data,
10640                           p_contract_id        => p_khr_id,
10641                           p_line_id            => l_csm_loan_levels_tbl_in(l_loan_levels_cntr).kle_loan_id,
10642                           p_start_date         => l_start_date,
10643                           p_due_date           => l_start_date,
10644                           p_principal_basis    => NULL,
10645                           x_principal_balance_tbl => l_principal_balance_tbl);
10646 
10647                   IF(x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR)THEN
10648                     RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
10649                   ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR)THEN
10650                     RAISE initiate_request_failed;
10651                   END IF;
10652 
10653                   --l_csm_loan_levels_tbl_in(l_loan_levels_cntr).amount := get_tot_principal_amt(p_khr_id, l_start_date);
10654                   l_csm_loan_levels_tbl_in(l_loan_levels_cntr).amount := l_principal_balance_tbl(l_principal_balance_tbl.COUNT).principal_balance;
10655                   l_total_lending := l_total_lending + l_csm_loan_levels_tbl_in(l_loan_levels_cntr).amount;
10656 
10657                   print_debug('Kle Id : ' || l_csm_loan_levels_tbl_in(l_loan_levels_cntr).kle_loan_id || 'Principal :'||l_csm_loan_levels_tbl_in(l_loan_levels_cntr).amount);
10658 --start |  19-May-08 cklee  fixed Bug 7043360                                       |
10659               END IF;
10660               l_line_id_buf := l_csm_loan_levels_tbl_in(l_loan_levels_cntr).kle_loan_id;
10661 --end |  19-May-08 cklee  fixed Bug 7043360                                       |
10662             END IF;
10663             --print_debug('Principal :'||l_csm_loan_levels_tbl_in(l_loan_levels_cntr).amount);
10664             --FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Principal: '||l_csm_loan_levels_tbl_in(l_loan_levels_cntr).amount);
10665           END IF;
10666 
10667         l_loan_levels_cntr := l_csm_loan_levels_tbl.next(l_loan_levels_cntr);
10668       END LOOP;
10669 
10670       l_tot_principal_amount := l_total_lending;
10671       l_csm_loan_header.date_start := l_start_date;
10672    	  l_csm_loan_header.date_payments_commencement := l_start_date;
10673       --l_csm_loan_header.total_lending := get_tot_principal_amt(p_khr_id, l_start_date);
10674       l_csm_loan_header.total_lending := l_total_lending;
10675 
10676 
10677       print_debug('==========================================');
10678       print_debug('Before pricing call or var_int_rent_level.');
10679       print_debug('==========================================');
10680       print_debug('Contents of l_csm_loan_header before pricing call or var_int_rent_level.');
10681       print_debug('Contract Principal : '||l_csm_loan_header.total_lending);
10682    	  l_csm_loan_header.lending_rate := l_interest_rate_tbl(l_interest_rate_tbl_index).rate;
10683       print_debug('Contract Rate : '|| l_csm_loan_header.lending_rate);
10684 
10685       print_debug('date_start :'||l_csm_loan_header.date_start);
10686       print_debug('date_payments_commencement :'||l_csm_loan_header.date_payments_commencement);
10687       print_debug('total_lending :'||l_csm_loan_header.total_lending);
10688 
10689       print_debug('# of rows in l_rents_prin_tbl :' || l_rents_prin_tbl.count);
10690       print_debug('# of rows in l_csm_loan_levels_tbl_in :' || l_csm_loan_levels_tbl_in.count);
10691       print_debug('# of rows in l_csm_loan_levels_tbl :' || l_csm_loan_levels_tbl.count);
10692 
10693       --put here temporarily during fix for bug 4887391
10694       --RETURN;
10695 
10696       IF(l_csm_loan_header.lending_rate <> 0) THEN
10697         IF (NVL(l_rents_prin_tbl.count, 0) = 0) THEN
10698           --RENT is defined on the contract payments
10699 
10700           --l_made_super_trump_call := TRUE;
10701           print_debug('Before pricing call.');
10702           print_loan_tables(p_rent_tbl => l_rents_prin_tbl,
10703                             p_csm_loan_level_tbl => l_csm_loan_levels_tbl_in);
10704 
10705         	Okl_Create_Streams_Pub.Create_Streams_Loan_Restr(p_api_version          => p_api_version,
10706                          p_init_msg_list                      => p_init_msg_list,
10707   										   p_skip_prc_engine                    => l_skip_prc_engine,
10708   										   p_csm_loan_header                    => l_csm_loan_header,
10709                          p_csm_loan_lines_tbl                 => l_csm_loan_lines_tbl,
10710   										   p_csm_loan_levels_tbl                => l_csm_loan_levels_tbl_in,
10711   										   p_csm_one_off_fee_tbl                => l_csm_one_off_fee_tbl,
10712   										   p_csm_periodic_expenses_tbl          => l_csm_periodic_expenses_tbl,
10713   										   p_csm_yields_tbl                     => l_csm_yields_tbl,
10714   										   p_csm_stream_types_tbl               => l_csm_stream_types_tbl,
10715   										   x_trans_id                           => l_super_trump_request_id,
10716   										   x_trans_status                       => l_trans_status,
10717   										   x_return_status	   			            => x_return_status,
10718   										   x_msg_count	   			                => x_msg_count,
10719   										   x_msg_data	   		                    => x_msg_data);
10720         	--l_return_status := x_return_status;
10721           print_debug('After pricing call, status :' || l_trans_status);
10722           IF(x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR)THEN
10723             RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
10724           ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR)THEN
10725             RAISE initiate_request_failed;
10726           END IF;
10727 
10728           print_debug('Super trump request id:' || l_super_trump_request_id);
10729           print_debug('super trump transaction status:'|| l_trans_status);
10730           print_debug('x return :'||x_return_status);
10731 
10732         ELSE
10733           --PRINCIPAL PAYMENT is defined on the contract payments
10734           /*print_loan_tables(p_rent_tbl => l_rents_prin_tbl,
10735                             p_csm_loan_level_tbl => l_csm_loan_levels_tbl);*/
10736 
10737           --l_made_super_trump_call := FALSE;
10738           print_debug('Before calling var_int_rent_level.');
10739           print_loan_tables(p_rent_tbl => l_rents_prin_tbl,
10740                             p_csm_loan_level_tbl => l_csm_loan_levels_tbl);
10741 
10742           var_int_rent_level(
10743                   p_api_version   => p_api_version,
10744                   p_init_msg_list => p_init_msg_list,
10745                   x_return_status => x_return_status,
10746                   x_msg_count     => x_msg_count,
10747                   x_msg_data      => x_msg_data,
10748                   p_chr_id        => p_khr_id,
10749                   p_trx_id        => NULL,
10750                   p_trx_status    => NULL,
10751                   p_rent_tbl      => l_rents_prin_tbl,
10752                   p_csm_loan_level_tbl => l_csm_loan_levels_tbl,
10753                   x_child_trx_id => l_child_trx_id);
10754 
10755           print_debug('After calling var_int_rent_level, status :' || x_return_status);
10756           print_debug('Rebook child request id:' || l_child_trx_id);
10757 
10758           IF(x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR)THEN
10759             RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
10760           ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR)THEN
10761             RAISE initiate_request_failed;
10762           END IF;
10763         END IF;
10764       END IF;
10765     ELSE
10766       --G_DEAL_TYPE = LEASE
10767 
10768        --principal_amount := get_tot_principal_amt(p_khr_id, null);
10769        -- CAll Extraction API
10770 
10771        --FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Principal Balance: '||principal_amount);
10772        --print_debug('Principal Balance: '||principal_amount);
10773 
10774        OKL_LA_STREAM_PUB.EXTRACT_PARAMS_LEASE(
10775 					p_api_version               => p_api_version,
10776           p_init_msg_list             => p_init_msg_list,
10777           p_chr_id                    => p_khr_id,
10778 					x_return_status             => x_return_status,
10779 					x_msg_count                 => x_msg_count,
10780  	        x_msg_data                  => x_msg_data,
10781 					x_csm_lease_header          => l_csm_lease_header,
10782 					x_csm_one_off_fee_tbl       => l_csm_one_off_fee_tbl,
10783 					x_csm_periodic_expenses_tbl => l_csm_periodic_expenses_tbl,
10784 					x_csm_yields_tbl            => l_csm_yields_tbl,
10785 					x_req_stream_types_tbl      => l_req_stream_types_tbl,
10786 					x_csm_line_details_tbl      => l_csm_line_details_tbl,
10787 					x_rents_tbl                 => l_rents_tbl);
10788        FOR i in 1..x_msg_count
10789        LOOP
10790           FND_MSG_PUB.GET(
10791                       p_msg_index     => i,
10792                       p_encoded       => FND_API.G_FALSE,
10793                       p_data          => x_msg_data,
10794                       p_msg_index_out => l_msg_index_out
10795                      );
10796           FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Error '||to_char(i)||': '||x_msg_data);
10797           FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Message Index: '||l_msg_index_out);
10798           print_debug('Error '||to_char(i)||': '||x_msg_data);
10799           print_debug('Message Index: '||l_msg_index_out);
10800        END LOOP;
10801 
10802        IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
10803           print_error_message('Status after Extract params: '||x_return_status);
10804           print_error_message('Message after Extract params: '||x_msg_data);
10805  		      RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
10806        ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
10807           print_error_message('Status after Extract params: '||x_return_status);
10808           RAISE initiate_request_failed;
10809        END IF;
10810     	 --Fine tune the params
10811      	 --x_csm_lease_header
10812        print_debug('Status after Extract params: '||x_return_status);
10813 
10814        print_debug('Contents of l_rents_tbl and l_csm_line_details_tbl after call to Extract params.');
10815        print_lease_tables(p_rents_tbl_in => l_rents_tbl,
10816                           p_csm_line_details_tbl => l_csm_line_details_tbl);
10817 
10818        l_csm_lease_header.orp_code := OKL_CREATE_STREAMS_PUB.G_ORP_CODE_VARIABLE_INTEREST;
10819        l_csm_lease_header.implicit_interest_rate := l_interest_rate_tbl(l_interest_rate_tbl_index).rate;
10820    	   l_csm_lease_header.date_payments_commencement := l_start_date;
10821    	   l_csm_lease_header.date_delivery := l_start_date;
10822        l_csm_lease_header.term := l_remaining_term_in_months;
10823 
10824        --Check the following with Susan.
10825        --KEERTHI WILL CHECK THE VALIDITY OF BELOW 2 FIELDS
10826        --FIND OUT FROM PM'S, ALVARO/SUSAN
10827        l_csm_lease_header.adjust := 'Rent';
10828        l_csm_lease_header.adjustment_method := 'Proportional';
10829 
10830        print_debug('----------------------------------------------------');
10831        print_debug('l_csm_lease_header information');
10832        print_debug('orp_code :'||l_csm_lease_header.orp_code);
10833        print_debug('implicit_interest_rate :'||l_csm_lease_header.implicit_interest_rate);
10834        print_debug('adjust :'||l_csm_lease_header.adjust);
10835        print_debug('adjustment_method :'||l_csm_lease_header.adjustment_method);
10836        print_debug('date_payments_commencement :'||l_csm_lease_header.date_payments_commencement);
10837        print_debug('date_delivery :'||l_csm_lease_header.date_delivery);
10838        print_debug('term :'||l_csm_lease_header.term);
10839 
10840        --we are appending to the existing table below
10841        --is this correct?
10842        --CHECK WITH PM'S
10843        l_index                                 :=  l_csm_yields_tbl.COUNT + 1;
10844        l_csm_yields_tbl(l_index).siy_type      :=  OKL_SIY_PVT.G_SIY_TYPE_INTEREST_RATE;
10845        l_csm_yields_tbl(l_index).yield_name    :=  'Full term with residual';
10846        l_csm_yields_tbl(l_index).target_value  :=  l_interest_rate_tbl(l_interest_rate_tbl_index).rate;
10847        print_debug('l_csm_yields_tbl information');
10848        print_debug('siy_type :'||l_csm_yields_tbl(l_index).siy_type);
10849        print_debug('yield_name :'||l_csm_yields_tbl(l_index).yield_name);
10850        print_debug('target_value :'||l_csm_yields_tbl(l_index).target_value);
10851 
10852 
10853        --l_rents_tbl.delete;
10854        --Are the values being passed to the l_rents_tbl correct? specifically lock_level_step
10855        l_rents_tbl_in.delete;
10856        l_rent_cntr := l_rents_tbl.first;
10857        LOOP
10858          EXIT WHEN l_rent_cntr IS NULL;
10859          --l_rent_date_start := l_rents_tbl(l_rent_cntr).date_start;
10860          IF (l_rents_tbl(l_rent_cntr).period = 'T') THEN
10861            l_rent_date_start := get_pay_level_start_date(l_rents_tbl(l_rent_cntr).kle_asset_id,
10862                                 l_rents_tbl(l_rent_cntr).level_index_number);
10863            print_debug('Fetched start date from SLL - l_rent_date_start: ' || l_rent_date_start);
10864          ELSE
10865            l_rent_date_start := l_rents_tbl(l_rent_cntr).date_start;
10866          END IF;
10867 
10868          l_number_of_periods := 0;
10869          l_level_date_start := NULL;
10870          FOR l_period_cntr IN 1..l_rents_tbl(l_rent_cntr).number_of_periods LOOP
10871            IF (l_rent_date_start  >= l_start_date) THEN
10872              l_number_of_periods := l_number_of_periods + 1;
10873              IF (l_level_date_start IS NULL) THEN
10874                 --l_level_date_start := l_rent_date_start;
10875                 IF (l_rents_tbl(l_rent_cntr).period = 'T') THEN
10876                   l_level_date_start := l_rents_tbl(l_rent_cntr).date_start;
10877                 ELSE
10878                   l_level_date_start := l_rent_date_start;
10879                 END IF;
10880              END IF;
10881            END IF;
10882            l_rent_date_start := add_months(l_rent_date_start,  l_adder_months);
10883          END LOOP;
10884 
10885          IF (l_number_of_periods > 0) THEN
10886            l_rents_tbl_in(l_rent_cntr) := l_rents_tbl(l_rent_cntr);
10887            l_rents_tbl_in(l_rent_cntr).number_of_periods := l_number_of_periods;
10888       	   --l_rents_tbl_in(l_rent_cntr).amount := 0;
10889            --REPLACE THE BELOW VALUE OF NULL WITH Okl_Create_Streams_Pub.G_LOCK_RATE
10890            l_rents_tbl_in(l_rent_cntr).lock_level_step := Okl_Create_Streams_Pub.G_LOCK_RATE;
10891            --Check the following with Susan
10892            --IN THE TABLE l_rents_tbl, OVERWRITE ONLY number_of_periods
10893            --AND DATE_START FOR THE FIRST PERIOD FROM WHICH REAMORT WILL
10894            --BE EFFECTIVE
10895            --l_rents_tbl(1).period := 'M';
10896            l_rents_tbl_in(l_rent_cntr).rate := l_interest_rate_tbl(l_interest_rate_tbl_index).rate;
10897            --l_rents_tbl(1).level_index_number := 1;
10898     	     --l_rents_tbl(1).level_type         := OKL_CREATE_STREAMS_PUB.G_SFE_LEVEL_PAYMENT;
10899       	   --l_rents_tbl(1).advance_or_arrears := OKL_CREATE_STREAMS_PUB.G_ARREARS;
10900       	   --l_rents_tbl(1).income_or_expense := OKL_CREATE_STREAMS_PUB.G_INCOME;
10901       	   l_rents_tbl_in(l_rent_cntr).date_start := l_level_date_start;
10902            --BELOW VALUE MUST BE SET TO 'Y'
10903       	   l_rents_tbl_in(l_rent_cntr).query_level_yn := Okl_Create_Streams_Pub.G_FND_YES;
10904            --l_sequence := l_sequence + 1;
10905            IF (NVl(l_prev_kle_id, -99) <> l_rents_tbl(l_rent_cntr).kle_asset_id) THEN
10906               --reset the sequence for the level_index_number for each asset
10907               l_sequence := 1;
10908               l_prev_kle_id := l_rents_tbl(l_rent_cntr).kle_asset_id;
10909            ELSE
10910               l_sequence := l_sequence + 1;
10911            END IF;
10912            l_rents_tbl_in(l_rent_cntr).level_index_number := l_sequence;
10913          END IF;
10914 
10915          --check to see if contract is in Advance or Arrears
10916          IF (l_advance_or_arrears IS NULL) THEN
10917            IF (l_rents_tbl(l_rent_cntr).advance_or_arrears = 'ARREARS') THEN
10918              l_advance_or_arrears := 'ARREARS';
10919            ELSE
10920              l_advance_or_arrears := 'ADVANCE';
10921            END IF;
10922          END IF;
10923 
10924          l_rent_cntr := l_rents_tbl.next(l_rent_cntr);
10925        END LOOP;
10926 
10927   	   --not required
10928   	   l_req_stream_types_tbl.delete;
10929 
10930        -- Get Principal balance
10931        --Are the values being passed to the l_csm_line_details_tbl correct?
10932        --should we maintain the original structure
10933        --POPULATE l_csm_line_details_tbl WITH ASSET LEVEL VALUES
10934        --l_first_row := l_row_counter;
10935 /*       l_row_counter := l_csm_line_details_tbl.next(l_row_counter);
10936        loop
10937           exit when l_row_counter is null;
10938           l_csm_line_details_tbl(l_first_row).residual_amount := NVL(l_csm_line_details_tbl(l_first_row).residual_amount, 0) + NVL(l_csm_line_details_tbl(l_row_counter).residual_amount, 0);
10939           l_row_counter := l_csm_line_details_tbl.next(l_row_counter);
10940        end loop;
10941 */
10942        print_debug('====================================================');
10943        print_debug('Before Super Trump pricing call');
10944        l_csm_line_details_ctr := l_csm_line_details_tbl.first;
10945        LOOP
10946          EXIT WHEN l_csm_line_details_ctr IS NULL;
10947          l_csm_line_details_tbl(l_csm_line_details_ctr).asset_cost := get_tot_principal_amt(p_khr_id, l_csm_line_details_tbl(l_csm_line_details_ctr).kle_asset_id,l_start_date, l_advance_or_arrears);
10948          l_tot_principal_amount := l_tot_principal_amount + l_csm_line_details_tbl(l_csm_line_details_ctr).asset_cost;
10949 
10950          l_csm_line_details_tbl(l_csm_line_details_ctr).date_delivery := l_start_date;
10951          l_csm_line_details_tbl(l_csm_line_details_ctr).date_funding  := l_start_date;
10952 
10953          print_debug('Asset id: ' || l_csm_line_details_tbl(l_csm_line_details_ctr).kle_asset_id || ' Asset principal balance: ' ||l_csm_line_details_tbl(l_csm_line_details_ctr).asset_cost);
10954          print_debug('Residual amount : ' || l_csm_line_details_tbl(l_csm_line_details_ctr).residual_amount);
10955          print_debug('Date delivery : ' || l_csm_line_details_tbl(l_csm_line_details_ctr).date_delivery);
10956          print_debug('Date funding : ' || l_csm_line_details_tbl(l_csm_line_details_ctr).date_funding);
10957          --FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Residual amount : ' || l_csm_line_details_tbl(l_csm_line_details_ctr).residual_amount);
10958 
10959 /*         l_row_counter := l_csm_line_details_tbl.next(l_first_row);
10960          loop
10961             exit when l_row_counter is null;
10962             l_csm_line_details_tbl.delete(l_row_counter);
10963             l_row_counter := l_csm_line_details_tbl.next(l_row_counter);
10964          end loop;
10965 */
10966          l_csm_line_details_ctr := l_csm_line_details_tbl.next(l_csm_line_details_ctr);
10967        END LOOP;
10968 
10969        --l_made_super_trump_call := TRUE;
10970        print_lease_tables(p_rents_tbl_in => l_rents_tbl_in,
10971                           p_csm_line_details_tbl => l_csm_line_details_tbl);
10972 
10973        --Call Supertrump API to submit request.
10974        Okl_Create_Streams_Pub.CREATE_STREAMS_LEASE_RESTR(
10975 				p_api_version               => p_api_version,
10976         p_init_msg_list             => p_init_msg_list,
10977 				x_return_status             => x_return_status,
10978 				x_msg_count                 => x_msg_count,
10979         x_msg_data                  => x_msg_data,
10980 				p_csm_lease_header          => l_csm_lease_header,
10981 				p_csm_one_off_fee_tbl       => l_csm_one_off_fee_tbl,
10982 				p_csm_periodic_expenses_tbl => l_csm_periodic_expenses_tbl,
10983 				p_csm_yields_tbl            => l_csm_yields_tbl,
10984 				p_csm_stream_types_tbl      => l_csm_stream_types_tbl,
10985 				p_csm_line_details_tbl      => l_csm_line_details_tbl,
10986 				p_rents_tbl                 => l_rents_tbl_in,
10987 				x_trans_id	   	            => l_super_trump_request_id,
10988 				x_trans_status	   	        => l_trans_status);
10989 
10990        print_debug('Super trump request id:' || l_super_trump_request_id);
10991        print_debug('super trump transaction status:'|| l_trans_status);
10992        print_debug('x return :'||x_return_status);
10993 
10994        IF (x_return_status <> OKL_API.G_RET_STS_SUCCESS) THEN
10995          print_error_message('Printing message stack.');
10996          FOR i in 1..x_msg_count
10997          LOOP
10998             FND_MSG_PUB.GET(
10999                         p_msg_index     => i,
11000                         p_encoded       => FND_API.G_FALSE,
11001                         p_data          => x_msg_data,
11002                         p_msg_index_out => l_msg_index_out
11003                        );
11004             FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Error '||to_char(i)||': '||x_msg_data);
11005             FND_FILE.PUT_LINE (FND_FILE.OUTPUT,'Message Index: '||l_msg_index_out);
11006             print_error_message('Error '||to_char(i)||': '||x_msg_data);
11007             print_error_message('Message Index: '||l_msg_index_out);
11008          END LOOP;
11009        END IF;
11010        IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
11011                       RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
11012        ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
11013                         RAISE initiate_request_failed;
11014        END IF;
11015     END IF;
11016     End IF; -- Added by prasjain bug# 6142095
11017 
11018     IF (l_super_trump_request_id IS NOT NULL OR l_child_trx_id IS NOT NULL) AND
11019         l_rebook_flag = TRUE THEN -- l_rebook_flag = TRUE added by prasjain bug# 6142095
11020       IF (l_super_trump_request_id IS NOT NULL) THEN
11021         l_vipv_rec.parent_trx_id        :=  l_super_trump_request_id;
11022       ELSIF (l_child_trx_id IS NOT NULL) THEN
11023         l_vipv_rec.parent_trx_id        :=  l_child_trx_id;
11024       ELSE
11025         l_vipv_rec.parent_trx_id        :=  null;
11026       END IF;
11027 
11028       l_vipv_rec.contract_number        :=  l_contract_number;
11029 
11030 
11031       print_debug('Updating OKL_VAR_INT_PROCESS_V');
11032       OKL_VIP_PVT.insert_row(
11033                              p_api_version                        => p_api_version,
11034     	                       p_init_msg_list                      => p_init_msg_list,
11035                       		   x_return_status	   			            => x_return_status,
11036               						   x_msg_count	   			                => x_msg_count,
11037               						   x_msg_data	   		                    => x_msg_data,
11038                              p_vipv_rec                           => l_vipv_rec,
11039                              x_vipv_rec                           => x_vipv_rec);
11040 
11041 
11042     	IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
11043      		RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
11044      	ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
11045      		RAISE initiate_request_failed;
11046      	END IF;
11047       print_debug('Updating OKL_VAR_INT_PROCESS_V Successful');
11048 
11049     END IF; -- Added by prasjain bug# 6142095
11050     -- Added by prasjain bug# 6142095 to update date_last_interim_interest_cal in case where rebook flag is False
11051     -- For the cases where Rebook Flag is True the date_last_interim_interest_cal will be updated
11052     -- In the procedure var_int_rent_level
11053 
11054 --start |  30-Apr-08 cklee  fixed Bug 6994233                                       |
11055 --    If l_rebook_flag = FALSE Then
11056 -- dev note:
11057 -- We always need to update date_last_interim_interest_cal with the new l_reamort_date, for example:
11058 -- we have index like follows:
11059 ------------------------------
11060 --  Jan  Feb  Mar Apr ...
11061 --  10   10   11  12
11062 ------------------------------
11063 --  Say, if the 1st time when the l_reamort_date is Jan, then the index is 10 and system rebook the contract
11064 --  and the 2nd time, system find that the rate is 10 (feb) so the system doesn't rebook the contract. However,
11065 -- the 3rd time, the index shall advance to Mar (index is 11) so that the system will rebook the contract with the
11066 -- proper rate for Jan, Feb, and Mar as well. So system always need to update l_reamort_date to refect the proper rate
11067 -- month by month.
11068 --end |  30-Apr-08 cklee  fixed Bug 6994233                                       |
11069               if(l_frequency = 'M') THEN
11070                  UPDATE okl_k_headers khr
11071                  SET khr.date_last_interim_interest_cal =  add_months(l_reamort_date,1)
11072                  where khr.id = p_khr_id;
11073           elsif(l_frequency = 'Q') THEN
11074                  UPDATE okl_k_headers khr
11075                  SET khr.date_last_interim_interest_cal =  add_months(l_reamort_date,3)
11076                  where khr.id = p_khr_id;
11077           elsif(l_frequency = 'S') THEN
11078                  UPDATE okl_k_headers khr
11079                  SET khr.date_last_interim_interest_cal =  add_months(l_reamort_date,6)
11080                  where khr.id = p_khr_id;
11081           elsif(l_frequency = 'A') THEN
11082                  UPDATE okl_k_headers khr
11083                  SET khr.date_last_interim_interest_cal =  add_months(l_reamort_date,12)
11084                  where khr.id = p_khr_id;
11085           end if;
11086 --start |  30-Apr-08 cklee  fixed Bug 6994233                                       |
11087 --    End if;
11088 --end |  30-Apr-08 cklee  fixed Bug 6994233                                       |
11089     -- End By prasjain bug# 6142095
11090 
11091     -- Added by prasjain bug# 6142095
11092     IF (l_super_trump_request_id IS NOT NULL OR l_child_trx_id IS NOT NULL OR l_rebook_flag = FALSE) THEN
11093     -- End by prasjain bug# 6142095
11094 
11095       IF (l_interest_rate_tbl(l_interest_rate_tbl.first).derived_flag = 'Y')THEN
11096            print_debug('Updating OKL_VAR_INT_PARAMS');
11097 
11098            IF (NVL(g_vir_tbl_counter, 0) = 0) THEN
11099              g_vir_tbl_counter := NVL(g_vir_tbl_counter, 0) + 1;
11100            END IF;
11101 
11102       	   SELECT
11103       	  		DECODE(Fnd_Global.CONC_REQUEST_ID,-1,NULL,Fnd_Global.CONC_REQUEST_ID),
11104       	  		DECODE(Fnd_Global.PROG_APPL_ID,-1,NULL,Fnd_Global.CONC_REQUEST_ID),
11105       	  		DECODE(Fnd_Global.CONC_PROGRAM_ID,-1,NULL,Fnd_Global.CONC_PROGRAM_ID),
11106       	  		DECODE(Fnd_Global.CONC_REQUEST_ID,-1,NULL,SYSDATE)
11107       	   INTO
11108       	  	   l_request_id,
11109       	  	   l_program_application_id,
11110       	  	   l_program_id,
11111       	  	   l_program_update_date
11112       	   FROM dual;
11113 
11114            g_vir_tbl.delete;
11115            g_vir_tbl_counter                                     := g_vir_tbl_counter + 1;
11116            g_vir_tbl(g_vir_tbl_counter).id                       := okc_p_util.raw_to_number(sys_guid());
11117            g_vir_tbl(g_vir_tbl_counter).khr_id                   := p_khr_id;
11118            g_vir_tbl(g_vir_tbl_counter).source_table             := 'OKL_VAR_INT_PROCESS_B';
11119            g_vir_tbl(g_vir_tbl_counter).source_id                := x_vipv_rec.id;
11120            g_vir_tbl(g_vir_tbl_counter).interest_rate            := l_interest_rate_tbl(l_interest_rate_tbl.first).rate;
11121            g_vir_tbl(g_vir_tbl_counter).interest_calc_start_date := l_start_date;
11122            g_vir_tbl(g_vir_tbl_counter).interest_calc_end_date   := l_start_date;
11123            g_vir_tbl(g_vir_tbl_counter).calc_method_code         := G_CALC_METHOD_CODE;
11124            g_vir_tbl(g_vir_tbl_counter).principal_balance        := l_tot_principal_amount;
11125            g_vir_tbl(g_vir_tbl_counter).valid_yn                 := 'Y';
11126            g_vir_tbl(g_vir_tbl_counter).object_version_number    := 1.0;
11127            g_vir_tbl(g_vir_tbl_counter).org_id                   := g_authoring_org_id;
11128            g_vir_tbl(g_vir_tbl_counter).request_id               := l_request_id;
11129            g_vir_tbl(g_vir_tbl_counter).program_application_id   := l_program_application_id;
11130            g_vir_tbl(g_vir_tbl_counter).program_id               := l_program_id;
11131            g_vir_tbl(g_vir_tbl_counter).program_update_date      := SYSDATE;
11132            g_vir_tbl(g_vir_tbl_counter).attribute_category       := NULL;
11133            g_vir_tbl(g_vir_tbl_counter).attribute1               := NULL;
11134            g_vir_tbl(g_vir_tbl_counter).attribute2               := NULL;
11135            g_vir_tbl(g_vir_tbl_counter).attribute3               := NULL;
11136            g_vir_tbl(g_vir_tbl_counter).attribute4               := NULL;
11137            g_vir_tbl(g_vir_tbl_counter).attribute5               := NULL;
11138            g_vir_tbl(g_vir_tbl_counter).attribute6               := NULL;
11139            g_vir_tbl(g_vir_tbl_counter).attribute7               := NULL;
11140            g_vir_tbl(g_vir_tbl_counter).attribute8               := NULL;
11141            g_vir_tbl(g_vir_tbl_counter).attribute9               := NULL;
11142            g_vir_tbl(g_vir_tbl_counter).attribute10              := NULL;
11143            g_vir_tbl(g_vir_tbl_counter).attribute11              := NULL;
11144            g_vir_tbl(g_vir_tbl_counter).attribute12              := NULL;
11145            g_vir_tbl(g_vir_tbl_counter).attribute13              := NULL;
11146            g_vir_tbl(g_vir_tbl_counter).attribute14              := NULL;
11147            g_vir_tbl(g_vir_tbl_counter).attribute15              := NULL;
11148            g_vir_tbl(g_vir_tbl_counter).created_by               := FND_GLOBAL.USER_ID;
11149            g_vir_tbl(g_vir_tbl_counter).creation_date            := SYSDATE;
11150            g_vir_tbl(g_vir_tbl_counter).last_updated_by          := FND_GLOBAL.USER_ID;
11151            g_vir_tbl(g_vir_tbl_counter).last_update_date         := SYSDATE;
11152            g_vir_tbl(g_vir_tbl_counter).last_update_login        := FND_GLOBAL.LOGIN_ID;
11153            g_vir_tbl(g_vir_tbl_counter).interest_amt             := NULL;
11154            g_vir_tbl(g_vir_tbl_counter).interest_calc_days       := NULL;
11155 
11156            populate_vir_params(
11157               p_api_version        => p_api_version,
11158               p_init_msg_list      => p_init_msg_list,
11159               x_return_status      => x_return_status,
11160               x_msg_count          => x_msg_count,
11161               x_msg_data           => x_msg_data,
11162               p_vir_tbl            => g_vir_tbl);
11163 
11164            IF (x_return_status = OKL_API.G_RET_STS_UNEXP_ERROR) THEN
11165              print_error_message('Unexpected error raised in call to POPULATE_VIR_PARAMS');
11166              RAISE OKL_API.G_EXCEPTION_UNEXPECTED_ERROR;
11167            ELSIF (x_return_status = OKL_API.G_RET_STS_ERROR) THEN
11168              print_error_message('Error raised in call to POPULATE_VIR_PARAMS');
11169              RAISE initiate_request_failed;
11170            END IF;
11171            print_debug('Updating OKL_VAR_INT_PARAMS Successful');
11172            g_vir_tbl.delete;
11173 
11174       END IF;
11175     END IF;
11176 
11177     print_debug('****Exiting procedure INITIATE_REQUEST****');
11178 
11179   EXCEPTION
11180     WHEN initiate_request_failed THEN
11181       print_error_message ('Exception initiate_request_failed raised in procedure initiate_request');
11182       x_return_status := OKL_API.G_RET_STS_ERROR;
11183     WHEN OTHERS  THEN
11184       print_error_message ('Exception raised in procedure initiate_request');
11185       Okl_Api.SET_MESSAGE(
11186                           p_app_name     => G_APP_NAME,
11187                           p_msg_name     => G_UNEXPECTED_ERROR,
11188                           p_token1       => G_SQLCODE_TOKEN,
11189                           p_token1_value => SQLCODE,
11190                           p_token2       => G_SQLERRM_TOKEN,
11191                           p_token2_value => SQLERRM);
11192 
11193       x_return_status := OKL_API.G_RET_STS_ERROR;
11194   END initiate_request;
11195 ------------------------------------------------------------------------------
11196 
11197     -- Start of Comments
11198     -- Created By:       Ramesh Seela
11199     -- Procedure Name    variable_interest_float
11200     -- Description:      This procedure is called by Variable Interest Calculation for Loans / Revolving Loans
11201     --                   Inputs :
11202     --                   Output :
11203     -- Dependencies:
11204     -- Parameters:
11205     -- Version:          1.0
11206     -- End of Comments
11207 
11208   ------------------------------------------------------------------------------
11209 
11210   PROCEDURE variable_interest_float_old(
11211             p_api_version     IN  NUMBER,
11212             p_init_msg_list   IN  VARCHAR2,
11213             x_return_status   OUT NOCOPY VARCHAR2,
11214             x_msg_count       OUT NOCOPY NUMBER,
11215             x_msg_data        OUT NOCOPY VARCHAR2,
11216             p_contract_id     IN  NUMBER,
11217             p_principal_basis IN  VARCHAR2,
11218             p_rev_rec_method  IN  VARCHAR2,
11219             p_deal_type       IN  VARCHAR2,
11220             p_currency_code   IN  VARCHAR2,
11221             p_start_date      IN  DATE,
11222             p_due_date        IN  DATE) IS
11223 
11224     l_api_version             CONSTANT NUMBER := 1.0;
11225     l_api_name	              CONSTANT VARCHAR2(30) := 'VARIABLE_INTEREST_FLOAT';
11226     l_return_status	          VARCHAR2(1) := OKL_API.G_RET_STS_SUCCESS;
11227     l_msg_index_out           NUMBER;
11228     l_principal_balance       NUMBER := 0;
11229     l_interest_calculated     NUMBER := 0;
11230     r_principal_balance_tbl   principal_balance_tbl_typ;
11231     l_total_loan_pmt          NUMBER := 0;
11232     l_total_principal_pmt     NUMBER := 0;
11233     l_scheduled_prin_pmnt_amt NUMBER := 0;
11234     l_invoice_id              NUMBER;
11235     l_invoice_amt             NUMBER := 0;
11236     l_interest_paid           NUMBER := 0;
11237     l_stream_type_purpose     OKL_STRM_TYPE_V.stream_type_purpose%TYPE;
11238     i_vir_tbl                 vir_tbl_type;
11239     r_vir_tbl                 vir_tbl_type;
11240     l_stream_element_id       OKL_STRM_ELEMENTS_v.id%TYPE;
11241 
11242     CURSOR loan_payment_amount_csr (p_khr_id NUMBER, p_due_date DATE, p_stream_type_purpose VARCHAR2) IS
11243        SELECT nvl(SUM(nvl(sel_prin_pmt.amount, 0)),0) pmt_amt
11244        FROM  okl_strm_type_v sty_prin_pmt,
11245              okl_streams_v stm_prin_pmt,
11246              okl_strm_elements_v sel_prin_pmt
11247        WHERE stm_prin_pmt.khr_id = p_khr_id
11248        AND   stm_prin_pmt.id = sel_prin_pmt.stm_id
11249        AND   sel_prin_pmt.stream_element_date <= p_due_date
11250        AND   stm_prin_pmt.sty_id = sty_prin_pmt.id
11251        AND   stm_prin_pmt.active_yn = 'Y'
11252        AND   stm_prin_pmt.say_code = 'CURR'
11253        AND   sty_prin_pmt.stream_type_purpose = p_stream_type_purpose ; -- 'PRINCIPAL_PAYMENT'
11254 
11255     CURSOR scheduled_prin_pmnt_amt_csr (p_khr_id NUMBER, p_due_date DATE, p_stream_type_purpose VARCHAR2) IS
11256        SELECT nvl(SUM(nvl(sel_prin_pmt.amount, 0)),0) pmt_amt
11257        FROM  okl_strm_type_v sty_prin_pmt,
11258              okl_streams_v stm_prin_pmt,
11259              okl_strm_elements_v sel_prin_pmt
11260        WHERE stm_prin_pmt.khr_id = p_khr_id
11261        AND   stm_prin_pmt.id = sel_prin_pmt.stm_id
11262        AND   sel_prin_pmt.stream_element_date = p_due_date
11263        AND   stm_prin_pmt.sty_id = sty_prin_pmt.id
11264        AND   stm_prin_pmt.active_yn = 'Y'
11265        AND   stm_prin_pmt.say_code = 'CURR'
11266        AND   sty_prin_pmt.stream_type_purpose = p_stream_type_purpose ; -- 'PRINCIPAL_PAYMENT'
11267 
11268   BEGIN
11269     ------------------------------------------------------------
11270     -- Start processing
11271     ------------------------------------------------------------
11272 
11273     x_return_status := OKL_API.G_RET_STS_SUCCESS;
11274     g_vir_tbl.delete;
11275 	g_vir_tbl_counter := 0;
11276 
11277     l_interest_calculated :=  calculate_total_interest_due(
11278                                         p_api_version     => 1.0,
11279                                         p_init_msg_list   => OKL_API.G_FALSE,
11280                                         x_return_status   => x_return_status,
11281                                         x_msg_count       => x_msg_count,
11282                                         x_msg_data        => x_msg_data,
11283                                         p_contract_id     => p_contract_id,
11284                                         p_currency_code   => p_currency_code,
11285                                         p_start_date      => p_start_date,
11286                                         p_due_date        => p_due_date);
11287        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11288           RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11289        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11290            RAISE Okl_Api.G_EXCEPTION_ERROR;
11291        END IF;
11292 
11293        l_total_loan_pmt          := 0;
11294        l_total_principal_pmt     := 0;
11295        l_interest_paid           := 0;
11296        l_scheduled_prin_pmnt_amt := 0;
11297 
11298     IF (p_deal_type = 'LOAN') THEN
11299        IF (p_principal_basis = 'ACTUAL') THEN
11300           IF (p_rev_rec_method = 'ACTUAL') THEN
11301              OPEN  loan_payment_amount_csr (p_contract_id, p_due_date, 'VARIABLE_LOAN_PAYMENT');
11302              FETCH loan_payment_amount_csr INTO l_total_loan_pmt;
11303              IF (loan_payment_amount_csr%NOTFOUND) THEN
11304                 l_total_loan_pmt := 0;
11305              END IF;
11306              CLOSE loan_payment_amount_csr;
11307 
11308              Print_debug ('Total Variable Loan Payment = '|| l_total_loan_pmt);
11309 
11310              OPEN  loan_payment_amount_csr (p_contract_id, p_due_date, 'PRINCIPAL_PAYMENT');
11311              FETCH loan_payment_amount_csr INTO l_total_principal_pmt;
11312              IF (loan_payment_amount_csr%NOTFOUND) THEN
11313                 l_total_principal_pmt := 0;
11314              END IF;
11315 
11316              CLOSE loan_payment_amount_csr;
11317 
11318              Print_debug ('Total Principal Payment = '|| l_total_principal_pmt);
11319 
11320              l_invoice_amt := l_interest_calculated + l_total_principal_pmt - l_total_loan_pmt;
11321 
11322              Print_debug ('Invoice Amount = '|| l_invoice_amt);
11323 
11324           ELSE
11325              OPEN  loan_payment_amount_csr (p_contract_id, p_due_date, 'VARIABLE_INTEREST');
11326              FETCH loan_payment_amount_csr INTO l_interest_paid;
11327              IF (loan_payment_amount_csr%NOTFOUND) THEN
11328                 l_interest_paid := 0;
11329              END IF;
11330              CLOSE loan_payment_amount_csr;
11331 
11332              l_invoice_amt := l_interest_calculated - l_interest_paid;
11333 
11334           END IF;
11335        ELSIF (p_principal_basis = 'SCHEDULED') THEN
11336           IF (p_rev_rec_method = 'ACTUAL') THEN
11337              OPEN   scheduled_prin_pmnt_amt_csr(p_contract_id, p_due_date, 'PRINCIPAL_PAYMENT');
11338              FETCH  scheduled_prin_pmnt_amt_csr INTO l_scheduled_prin_pmnt_amt;
11339              IF (scheduled_prin_pmnt_amt_csr%NOTFOUND) THEN
11340                 l_scheduled_prin_pmnt_amt := 0;
11341              END IF;
11342              CLOSE  scheduled_prin_pmnt_amt_csr;
11343              l_invoice_amt := l_interest_calculated + l_scheduled_prin_pmnt_amt;
11344           ELSE
11345              l_invoice_amt := l_interest_calculated;
11346           END IF;
11347        END IF;
11348 
11349     ELSIF (p_deal_type = 'LOAN-REVOLVING') THEN  -- 'Revolving Loan'
11350        IF (p_principal_basis = 'ACTUAL') THEN
11351           IF (p_rev_rec_method = 'ACTUAL') THEN
11352              OPEN  loan_payment_amount_csr (p_contract_id, p_due_date, 'VARIABLE_LOAN_PAYMENT');
11353              FETCH loan_payment_amount_csr INTO l_total_loan_pmt;
11354              IF (loan_payment_amount_csr%NOTFOUND) THEN
11355                 l_total_loan_pmt := 0;
11356              END IF;
11357              CLOSE loan_payment_amount_csr;
11358 
11359              l_invoice_amt := l_interest_calculated - l_total_loan_pmt;
11360 
11361           ELSE
11362              OPEN  loan_payment_amount_csr (p_contract_id, p_due_date, 'VARIABLE_INTEREST');
11363              FETCH loan_payment_amount_csr INTO l_interest_paid;
11364              IF (loan_payment_amount_csr%NOTFOUND) THEN
11365                 l_interest_paid := 0;
11366              END IF;
11367              CLOSE loan_payment_amount_csr;
11368 
11369              l_invoice_amt := l_interest_calculated - l_interest_paid;
11370 
11371           END IF;
11372        END IF;
11373     END IF;
11374 
11375     IF (p_rev_rec_method = 'ACTUAL') THEN
11376        l_stream_type_purpose := 'VARIABLE_LOAN_PAYMENT';
11377     ELSE
11378        l_stream_type_purpose := 'VARIABLE_INTEREST';
11379     END IF;
11380 
11381     Create_Stream_Invoice (
11382                            p_api_version            => 1.0,
11383                            p_init_msg_list          => OKL_API.G_FALSE,
11384                            x_return_status          => x_return_status,
11385                            x_msg_count              => x_msg_count,
11386                            x_msg_data               => x_msg_data,
11387                            p_contract_id            => p_contract_id,
11388                            p_line_id                => NULL,
11389                            p_amount                 => l_invoice_amt,
11390                            p_due_date               => p_due_date,
11391                            p_stream_type_purpose    => l_stream_type_purpose,
11392                            p_create_invoice_flag    => OKL_API.G_TRUE,
11393                            p_parent_strm_element_id => NULL,
11394 						   x_invoice_id             => l_invoice_id,
11395 						   x_stream_element_id      => l_stream_element_id);
11396 
11397     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11398        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11399     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11400        RAISE Okl_Api.G_EXCEPTION_ERROR;
11401     END IF;
11402     i_vir_tbl := g_vir_tbl;
11403 
11404     upd_vir_params_with_invoice (
11405             p_api_version   => 1.0,
11406             p_init_msg_list => OKL_API.G_TRUE,
11407             x_return_status => x_return_status,
11408             x_msg_count     => x_msg_count,
11409             x_msg_data      => x_msg_data,
11410             p_source_id     => l_invoice_id,
11411             p_vir_tbl      => i_vir_tbl,
11412             x_vir_tbl      => r_vir_tbl);
11413     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11414        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11415     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11416        RAISE Okl_Api.G_EXCEPTION_ERROR;
11417     END IF;
11418 
11419     g_vir_tbl := r_vir_tbl;
11420 
11421     populate_vir_params(
11422              p_api_version    => 1.0,
11423              p_init_msg_list  => OKL_API.G_TRUE,
11424              x_return_status  => x_return_status,
11425              x_msg_count      => x_msg_count,
11426              x_msg_data       => x_msg_data,
11427              p_vir_tbl        => g_vir_tbl);
11428     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11429       print_error_message('Unexpected error raised in call to POPULATE_VIR_PARAMS');
11430       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11431     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11432       print_error_message('Error raised in call to POPULATE_VIR_PARAMS');
11433       RAISE Okl_Api.G_EXCEPTION_ERROR;
11434     END IF;
11435 
11436   EXCEPTION
11437     WHEN OTHERS  THEN
11438       print_debug ('exception raised in variable_interest_float');
11439       Okl_Api.SET_MESSAGE(
11440                           p_app_name     => G_APP_NAME,
11441                           p_msg_name     => G_UNEXPECTED_ERROR,
11442                           p_token1       => G_SQLCODE_TOKEN,
11443                           p_token1_value => SQLCODE,
11444                           p_token2       => G_SQLERRM_TOKEN,
11445                           p_token2_value => SQLERRM);
11446 
11447       x_return_status := OKL_API.G_RET_STS_ERROR;
11448 
11449   END variable_interest_float_old;
11450 ------------------------------------------------------------------------------
11451 
11452     -- Start of Comments
11453     -- Created By:       Ramesh Seela
11454     -- Procedure Name    variable_interest_float
11455     -- Description:      This procedure is called by Variable Interest Calculation for Loans / Revolving Loans
11456     --                   Inputs :
11457     --                   Output :
11458     -- Dependencies:
11459     -- Parameters:
11460     -- Version:          1.0
11461     -- End of Comments
11462 
11463   ------------------------------------------------------------------------------
11464 
11465   PROCEDURE variable_interest_float(
11466             p_api_version     IN  NUMBER,
11467             p_init_msg_list   IN  VARCHAR2,
11468             x_return_status   OUT NOCOPY VARCHAR2,
11469             x_msg_count       OUT NOCOPY NUMBER,
11470             x_msg_data        OUT NOCOPY VARCHAR2,
11471             p_contract_id     IN  NUMBER,
11472             p_principal_basis IN  VARCHAR2,
11473             p_rev_rec_method  IN  VARCHAR2,
11474             p_deal_type       IN  VARCHAR2,
11475             p_currency_code   IN  VARCHAR2,
11476             p_start_date      IN  DATE,
11477             p_due_date        IN  DATE) IS
11478 
11479     l_api_version             CONSTANT NUMBER := 1.0;
11480     l_api_name	              CONSTANT VARCHAR2(30) := 'VARIABLE_INTEREST_FLOAT';
11481     l_return_status	          VARCHAR2(1) := OKL_API.G_RET_STS_SUCCESS;
11482     l_msg_index_out           NUMBER;
11483     l_principal_balance       NUMBER := 0;
11484     l_interest_calculated     NUMBER := 0;
11485     r_principal_balance_tbl   principal_balance_tbl_typ;
11486     l_total_loan_pmt          NUMBER := 0;
11487     l_total_principal_pmt     NUMBER := 0;
11488     l_scheduled_prin_pmnt_amt NUMBER := 0;
11489     l_invoice_id              NUMBER;
11490     l_invoice_amt             NUMBER := 0;
11491     l_interest_paid           NUMBER := 0;
11492     l_stream_type_purpose     OKL_STRM_TYPE_V.stream_type_purpose%TYPE;
11493     i_vir_tbl                 vir_tbl_type;
11494     r_vir_tbl                 vir_tbl_type;
11495     l_stream_element_id       OKL_STRM_ELEMENTS_v.id%TYPE;
11496     l_kle_id                  OKL_K_LINES.id%TYPE;
11497     l_strm_element_date       OKL_STRM_ELEMENTS.stream_element_date%TYPE;
11498     l_parent_strm_element_id  OKL_STRM_ELEMENTS.id%TYPE;
11499     var_int_float_failed      EXCEPTION;
11500 
11501     CURSOR loan_payment_amount_csr (cp_khr_id NUMBER, cp_start_date DATE, cp_due_date DATE, cp_stream_type_purpose VARCHAR2) IS
11502        SELECT nvl(SUM(nvl(sel_prin_pmt.amount, 0)),0) pmt_amt
11503        FROM  okl_strm_type_v sty_prin_pmt,
11504              okl_streams_v stm_prin_pmt,
11505              okl_strm_elements_v sel_prin_pmt
11506        WHERE stm_prin_pmt.khr_id = cp_khr_id
11507        AND   stm_prin_pmt.id = sel_prin_pmt.stm_id
11508        AND   sel_prin_pmt.stream_element_date BETWEEN cp_start_date AND  cp_due_date
11509        AND   stm_prin_pmt.sty_id = sty_prin_pmt.id
11510        AND   stm_prin_pmt.active_yn = 'Y'
11511        AND   stm_prin_pmt.say_code = 'CURR'
11512        AND   sty_prin_pmt.stream_type_purpose = cp_stream_type_purpose ; -- 'PRINCIPAL_PAYMENT'
11513 
11514     -- Derive the interest billed for previous billing periods
11515     CURSOR Interest_payment_amount_csr (cp_khr_id NUMBER, cp_start_date DATE, cp_due_date DATE) IS
11516        SELECT nvl(SUM(nvl(sel_prin_pmt.amount, 0)),0) pmt_amt
11517        FROM  okl_strm_type_v sty_prin_pmt,
11518              okl_streams_v stm_prin_pmt,
11519              okl_strm_elements_v sel_prin_pmt
11520        WHERE stm_prin_pmt.khr_id = cp_khr_id
11521        AND   stm_prin_pmt.id = sel_prin_pmt.stm_id
11522        AND   sel_prin_pmt.stream_element_date BETWEEN cp_start_date AND  cp_due_date
11523        AND   stm_prin_pmt.sty_id = sty_prin_pmt.id
11524        AND   stm_prin_pmt.active_yn = 'Y'
11525        AND   stm_prin_pmt.say_code = 'CURR'
11526        AND   sel_prin_pmt.sel_id  IS NULL
11527        AND   sty_prin_pmt.stream_type_purpose = 'VARIABLE_LOAN_PAYMENT';
11528 
11529     CURSOR contract_line_csr (cp_khr_id NUMBER, cp_due_date DATE) IS
11530        SELECT id
11531 	   FROM   okl_k_lines_full_v
11532 	   WHERE  chr_id = cp_khr_id
11533 	   AND    lse_id = G_FIN_LINE_LTY_ID
11534 	   AND    nvl(date_terminated, cp_due_date + 1) > cp_due_date
11535 	   ORDER BY id;
11536 
11537     CURSOR Principal_payment_streams_csr (cp_khr_id NUMBER, cp_kle_id NUMBER, cp_due_date DATE) IS
11538        SELECT sel.id,
11539 	          sel.stream_element_date,
11540               sel.amount
11541 	   FROM   okl_strm_type_v sty,
11542 	          okl_streams str,
11543 	          okl_strm_elements sel
11544 	   WHERE  sel.stm_id = str.id
11545 	   AND    str.khr_id = cp_khr_id
11546 	   AND    str.kle_id = cp_kle_id
11547        AND    str.say_code = 'CURR'
11548        AND    str.active_yn = 'Y'
11549 	   AND    sel.stream_element_date <= cp_due_date
11550 	   AND    str.sty_id = sty.id
11551 	   AND    sty.stream_type_purpose = 'PRINCIPAL_PAYMENT'
11552 	   AND    NOT EXISTS (
11553 	                       SELECT 'X'
11554 	                       FROM   okl_strm_elements selc
11555 	                       WHERE  selc.sel_id = sel.id)
11556 	   ORDER BY stream_element_date;
11557 
11558 
11559     CURSOR scheduled_prin_pmnt_amt_csr (cp_khr_id NUMBER, cp_due_date DATE, cp_stream_type_purpose VARCHAR2) IS
11560        SELECT nvl(SUM(nvl(sel_prin_pmt.amount, 0)),0) pmt_amt
11561        FROM  okl_strm_type_v sty_prin_pmt,
11562              okl_streams_v stm_prin_pmt,
11563              okl_strm_elements_v sel_prin_pmt
11564        WHERE stm_prin_pmt.khr_id = cp_khr_id
11565        AND   stm_prin_pmt.id = sel_prin_pmt.stm_id
11566        AND   sel_prin_pmt.stream_element_date = cp_due_date
11567        AND   stm_prin_pmt.sty_id = sty_prin_pmt.id
11568        AND   stm_prin_pmt.active_yn = 'Y'
11569        AND   stm_prin_pmt.say_code = 'CURR'
11570        AND   sty_prin_pmt.stream_type_purpose = cp_stream_type_purpose ; -- 'PRINCIPAL_PAYMENT'
11571 
11572   BEGIN
11573     ------------------------------------------------------------
11574     -- Start processing
11575     ------------------------------------------------------------
11576 
11577     print_debug('Executing procedure VARIABLE_INTEREST_FLOAT using the foll. parameters:');
11578     print_debug('contract ID:                 '|| p_contract_id);
11579   	print_Debug('Principal Basis:             '|| p_principal_basis);
11580   	print_debug('Revenue Recognition Method:  '|| p_rev_rec_method);
11581   	print_debug('Deal Type:                   '|| p_deal_type);
11582   	Print_debug('Currency Code:               '|| p_currency_code);
11583   	print_debug('Start Date:                  '|| p_start_date);
11584   	print_debug('Due Date:                    '|| p_due_date);
11585 
11586     x_return_status := OKL_API.G_RET_STS_SUCCESS;
11587     g_vir_tbl.delete;
11588  	  g_vir_tbl_counter := 0;
11589     g_vpb_tbl.delete;
11590  	  g_vpb_tbl_counter := 0;
11591 
11592     populate_txns ( p_api_version => p_api_version,
11593                 p_init_msg_list  => p_init_msg_list,
11594                 p_khr_id  => p_contract_id,
11595                 p_from_date => p_start_date,
11596                 p_to_date  => p_due_date,
11597                 x_return_status   => x_return_status,
11598                 x_msg_count       => x_msg_count,
11599                 x_msg_data        => x_msg_data);
11600 
11601    IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11602      print_error_message('Unexpected error raised in call to POPULATE_TXNS');
11603      RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11604    ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11605      print_error_message('Error raised in call to POPULATE_TXNS');
11606      RAISE var_int_float_failed;
11607    END IF;
11608 
11609     l_interest_calculated :=  calculate_total_interest_due(
11610                                         p_api_version     => 1.0,
11611                                         p_init_msg_list   => OKL_API.G_FALSE,
11612                                         x_return_status   => x_return_status,
11613                                         x_msg_count       => x_msg_count,
11614                                         x_msg_data        => x_msg_data,
11615                                         p_contract_id     => p_contract_id,
11616                                         p_currency_code   => p_currency_code,
11617                                         p_start_date      => p_start_date,
11618                                         p_due_date        => p_due_date);
11619        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11620          print_error_message('Unexpected error raised in call to CALCULATE_TOTAL_INTEREST_DUE');
11621          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11622        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11623          print_error_message('Error raised in call to CALCULATE_TOTAL_INTEREST_DUE');
11624          RAISE var_int_float_failed;
11625        END IF;
11626 
11627        l_total_loan_pmt          := 0;
11628        l_total_principal_pmt     := 0;
11629        l_interest_paid           := 0;
11630        l_scheduled_prin_pmnt_amt := 0;
11631 
11632     IF (p_deal_type = 'LOAN') THEN
11633        IF (p_principal_basis = 'ACTUAL') THEN
11634           IF (p_rev_rec_method = 'ACTUAL') THEN
11635              OPEN  interest_payment_amount_csr (p_contract_id, p_start_date, p_due_date);
11636              FETCH interest_payment_amount_csr INTO l_interest_paid;
11637              IF (interest_payment_amount_csr%NOTFOUND) THEN
11638                 l_interest_paid := 0;
11639              END IF;
11640 
11641              CLOSE interest_payment_amount_csr;
11642 
11643              Print_debug ('Total Interest Payment = '|| l_interest_paid);
11644 
11645              l_invoice_amt := l_interest_calculated - l_interest_paid;
11646 
11647           ELSE  /* Estimated and Billed */
11648              OPEN  loan_payment_amount_csr (p_contract_id, p_start_date, p_due_date, 'VARIABLE_INTEREST');
11649              FETCH loan_payment_amount_csr INTO l_interest_paid;
11650              IF (loan_payment_amount_csr%NOTFOUND) THEN
11651                 l_interest_paid := 0;
11652              END IF;
11653              CLOSE loan_payment_amount_csr;
11654 
11655              Print_debug ('Total Interest Payment = '|| l_interest_paid);
11656 
11657              l_invoice_amt := l_interest_calculated - l_interest_paid;
11658 
11659           END IF;
11660        ELSIF (p_principal_basis = 'SCHEDULED') THEN
11661 /*          IF (p_rev_rec_method = 'ACTUAL') THEN  -- not applicable
11662              OPEN   scheduled_prin_pmnt_amt_csr(p_contract_id, p_due_date, 'PRINCIPAL_PAYMENT');
11663              FETCH  scheduled_prin_pmnt_amt_csr INTO l_scheduled_prin_pmnt_amt;
11664              IF (scheduled_prin_pmnt_amt_csr%NOTFOUND) THEN
11665                 l_scheduled_prin_pmnt_amt := 0;
11666              END IF;
11667              CLOSE  scheduled_prin_pmnt_amt_csr;
11668              l_invoice_amt := l_interest_calculated + l_scheduled_prin_pmnt_amt;
11669           ELSE */
11670              l_invoice_amt := l_interest_calculated;
11671 --          END IF;
11672        END IF;
11673 
11674     ELSIF (p_deal_type = 'LOAN-REVOLVING') THEN  -- 'Revolving Loan'
11675        IF (p_principal_basis = 'ACTUAL') THEN
11676           IF (p_rev_rec_method = 'ACTUAL') THEN
11677              OPEN  loan_payment_amount_csr (p_contract_id, p_start_date, p_due_date, 'VARIABLE_LOAN_PAYMENT');
11678              FETCH loan_payment_amount_csr INTO l_total_loan_pmt;
11679              IF (loan_payment_amount_csr%NOTFOUND) THEN
11680                 l_total_loan_pmt := 0;
11681              END IF;
11682              CLOSE loan_payment_amount_csr;
11683 
11684              l_invoice_amt := l_interest_calculated - l_total_loan_pmt;
11685 
11686           ELSE
11687              OPEN  loan_payment_amount_csr (p_contract_id, p_start_date, p_due_date, 'VARIABLE_INTEREST');
11688              FETCH loan_payment_amount_csr INTO l_interest_paid;
11689              IF (loan_payment_amount_csr%NOTFOUND) THEN
11690                 l_interest_paid := 0;
11691              END IF;
11692              CLOSE loan_payment_amount_csr;
11693 
11694              l_invoice_amt := l_interest_calculated - l_interest_paid;
11695 
11696           END IF;
11697        END IF;
11698     END IF;
11699 
11700     IF (p_rev_rec_method = 'ACTUAL') THEN
11701        l_stream_type_purpose := 'VARIABLE_LOAN_PAYMENT';
11702     ELSE
11703        l_stream_type_purpose := 'VARIABLE_INTEREST';
11704     END IF;
11705 
11706     Create_Stream_Invoice (
11707                            p_api_version            => 1.0,
11708                            p_init_msg_list          => p_init_msg_list,
11709                            x_return_status          => x_return_status,
11710                            x_msg_count              => x_msg_count,
11711                            x_msg_data               => x_msg_data,
11712                            p_contract_id            => p_contract_id,
11713                            p_line_id                => NULL,
11714                            p_amount                 => l_invoice_amt,
11715                            p_due_date               => p_due_date,
11716                            p_stream_type_purpose    => l_stream_type_purpose,
11717                            p_create_invoice_flag    => OKL_API.G_TRUE,
11718                            p_parent_strm_element_id => NULL,
11719 						   x_invoice_id             => l_invoice_id,
11720 						   x_stream_element_id      => l_stream_element_id);
11721 
11722     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11723       print_error_message('Unexpected error raised in call to CREATE_STREAM_INVOICE');
11724       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11725     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11726       print_error_message('Error raised in call to CREATE_STREAM_INVOICE');
11727       RAISE var_int_float_failed;
11728     END IF;
11729     i_vir_tbl := g_vir_tbl;
11730 
11731     upd_vir_params_with_invoice (
11732             p_api_version   => 1.0,
11733             p_init_msg_list => OKL_API.G_TRUE,
11734             x_return_status => x_return_status,
11735             x_msg_count     => x_msg_count,
11736             x_msg_data      => x_msg_data,
11737             p_source_id     => l_invoice_id,
11738             p_vir_tbl      => i_vir_tbl,
11739             x_vir_tbl      => r_vir_tbl);
11740     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11741       print_error_message('Unexpected error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
11742       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11743     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11744       print_error_message('Error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
11745       RAISE var_int_float_failed;
11746     END IF;
11747 
11748     g_vir_tbl := r_vir_tbl;
11749 
11750     populate_vir_params(
11751              p_api_version    => 1.0,
11752              p_init_msg_list  => OKL_API.G_TRUE,
11753              x_return_status  => x_return_status,
11754              x_msg_count      => x_msg_count,
11755              x_msg_data       => x_msg_data,
11756              p_vir_tbl        => g_vir_tbl);
11757     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11758       print_error_message('Unexpected error raised in call to POPULATE_VIR_PARAMS');
11759       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11760     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11761       print_error_message('Error raised in call to POPULATE_VIR_PARAMS');
11762       RAISE var_int_float_failed;
11763     END IF;
11764 
11765     populate_principal_bal_txn(
11766              p_api_version    => p_api_version,
11767              p_init_msg_list  => p_init_msg_list,
11768              x_return_status  => x_return_status,
11769              x_msg_count      => x_msg_count,
11770              x_msg_data       => x_msg_data,
11771              p_vpb_tbl        => g_vpb_tbl);
11772 
11773     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11774       print_error_message('Unexpected error raised in call to POPULATE_PRINCIPAL_BAL_TXN');
11775       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11776     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11777       print_error_message('Error raised in call to POPULATE_PRINCIPAL_BAL_TXN');
11778       RAISE var_int_float_failed;
11779     END IF;
11780 
11781     g_vpb_tbl.delete;
11782  	  g_vpb_tbl_counter := 0;
11783 
11784     --4731205
11785     IF (p_deal_type = 'LOAN' AND
11786         p_principal_basis = 'ACTUAL' AND
11787         p_rev_rec_method = 'ACTUAL') THEN
11788       FOR current_line in contract_line_csr(p_contract_id, p_due_date)
11789       LOOP
11790         l_kle_id := current_line.id;
11791         FOR current_stream_element in principal_payment_streams_csr (p_contract_id, l_kle_id, p_due_date)
11792     		LOOP
11793     		  l_stream_type_purpose    := 'VARIABLE_LOAN_PAYMENT';
11794     		  l_invoice_amt            := current_stream_element.amount;
11795     		  l_strm_element_date      := current_stream_element.stream_element_date;
11796     		  l_parent_strm_element_id := current_stream_element.id;
11797               Create_Stream_Invoice (
11798                             p_api_version            => 1.0,
11799                             p_init_msg_list          => p_init_msg_list,
11800                             x_return_status          => x_return_status,
11801                             x_msg_count              => x_msg_count,
11802                             x_msg_data               => x_msg_data,
11803                             p_contract_id            => p_contract_id,
11804                             p_line_id                => l_kle_id,
11805                             p_amount                 => l_invoice_amt,
11806                             p_due_date               => l_strm_element_date,
11807                             p_stream_type_purpose    => l_stream_type_purpose,
11808                             p_create_invoice_flag    => OKL_API.G_TRUE,
11809                             p_parent_strm_element_id => l_parent_strm_element_id,
11810     	   			        x_invoice_id             => l_invoice_id,
11811     						x_stream_element_id      => l_stream_element_id);
11812               IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11813                 print_error_message('Unexpected error raised in call to CREATE_STREAM_INVOICE');
11814                 RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11815               ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11816                 print_error_message('Error raised in call to CREATE_STREAM_INVOICE');
11817                 RAISE var_int_float_failed;
11818               END IF;
11819     		END LOOP;
11820       END LOOP;
11821     END IF;
11822 
11823   EXCEPTION
11824     WHEN var_int_float_failed THEN
11825       print_error_message ('Exception var_int_float_failed raised in procedure VARIABLE_INTEREST_FLOAT');
11826       x_return_status := OKL_API.G_RET_STS_ERROR;
11827     WHEN OTHERS  THEN
11828       print_error_message ('Exception raised in procedure VARIABLE_INTEREST_FLOAT');
11829       Okl_Api.SET_MESSAGE(
11830                           p_app_name     => G_APP_NAME,
11831                           p_msg_name     => G_UNEXPECTED_ERROR,
11832                           p_token1       => G_SQLCODE_TOKEN,
11833                           p_token1_value => SQLCODE,
11834                           p_token2       => G_SQLERRM_TOKEN,
11835                           p_token2_value => SQLERRM);
11836 
11837       x_return_status := OKL_API.G_RET_STS_ERROR;
11838 
11839   END variable_interest_float;
11840 ------------------------------------------------------------------------------
11841 
11842     -- Start of Comments
11843     -- Created By:       Ramesh Seela
11844     -- Procedure Name    variable_interest_float_factor
11845     -- Description:      This procedure is used to derive the interest and generate streams and invoice for
11846     --                   contracts with interest calculation basis of FLOAT FACTOR
11847     --                   Inputs :
11848     --                   Output :
11849     -- Dependencies:
11850     -- Parameters:
11851     -- Version:          1.0
11852     -- End of Comments
11853 
11854   ------------------------------------------------------------------------------
11855   PROCEDURE variable_interest_float_factor(
11856             p_api_version     IN  NUMBER,
11857             p_init_msg_list   IN  VARCHAR2,
11858             x_return_status   OUT NOCOPY VARCHAR2,
11859             x_msg_count       OUT NOCOPY NUMBER,
11860             x_msg_data        OUT NOCOPY VARCHAR2,
11861             p_contract_id     IN  NUMBER,
11862             p_from_date      IN  DATE,
11863             p_to_date        IN  DATE) IS
11864 
11865     l_api_version               CONSTANT NUMBER := 1.0;
11866     l_api_name	                CONSTANT VARCHAR2(30) := 'VARIABLE_INTEREST_FLOAT_FACTOR';
11867     l_return_status	            VARCHAR2(1) := OKL_API.G_RET_STS_SUCCESS;
11868     l_stream_type_purpose       OKL_STRM_TYPE_V.stream_type_purpose%TYPE;
11869     l_invoice_amt               NUMBER := 0;
11870     l_formula_id                OKL_FORMULAE_V.id%TYPE;
11871     l_formula_name              OKL_FORMULAE_V.name%TYPE;
11872     l_line_id                   OKC_K_LINES_B.id%TYPE;
11873     l_stream_element_date       DATE;
11874     l_invoice_id                NUMBER;
11875     l_stream_element_id         OKL_STRM_ELEMENTS_V.id%TYPE;
11876     var_int_float_factor_failed EXCEPTION;
11877 
11878   Cursor formula_name_csr (p_formula_id NUMBER) IS
11879       SELECT fml.name
11880       FROM   okl_formulae_v fml
11881       WHERE  fml.id = p_formula_id;
11882 
11883   Cursor asset_billed_streams_csr (p_contract_id NUMBER, p_from_date DATE, p_to_date DATE) IS
11884       SELECT chrb.id contract_id, cleb.id kle_id,
11885              selb.stream_element_date, selb.amount amount
11886       FROM  okc_k_headers_b chrb, okc_k_lines_b cleb,
11887 	        okc_line_styles_b lseb, okl_strm_type_b styb,
11888             okl_strm_elements selb, okl_streams stmb
11889       WHERE cleb.dnz_chr_id = chrb.id
11890       AND   cleb.chr_id = chrb.id
11891       AND   chrb.id = p_contract_id
11892       AND   cleb.lse_id = lseb.id
11893       AND   lseb.lty_code = 'FREE_FORM1'
11894       AND   stmb.khr_id = chrb.id
11895       AND   stmb.kle_id = cleb.id
11896       AND   stmb.sty_id = styb.id
11897       AND   selb.stm_id = stmb.id
11898       AND   chrb.id = stmb.khr_id
11899       AND   stmb.say_code = 'CURR'
11900       AND   stmb.active_yn = 'Y'
11901       AND   styb.stream_type_purpose = 'RENT'
11902       --fix for bug # 4940113
11903       --AND   selb.date_billed IS NOT NULL
11904       --change on 15 Nov 2005 by pgomes for bug fix 4740293
11905 	    --AND   selb.stream_element_date BETWEEN p_from_date AND NVL(p_to_date,SYSDATE);
11906 	  AND   (selb.stream_element_date > p_from_date AND  selb.stream_element_date <= NVL(p_to_date,trunc(SYSDATE)))
11907 	  ORDER BY selb.stream_element_date, cleb.id; -- 4904798
11908 
11909   BEGIN
11910     ------------------------------------------------------------
11911     -- Start processing
11912     ------------------------------------------------------------
11913 
11914     x_return_status := OKL_API.G_RET_STS_SUCCESS;
11915 
11916     print_debug('Executing procedure VARIABLE_INTEREST_FLOAT_FACTOR using following parameters : ');
11917     print_debug('contract ID : '|| p_contract_id);
11918     print_debug('g_contract_id : '|| G_CONTRACT_ID);
11919 	print_debug('From date : '|| p_from_date);
11920 	print_Debug('To date : '|| p_to_date);
11921 
11922     print_debug ('G_CALCULATION_FORMULA_ID : '|| G_CALCULATION_FORMULA_ID);
11923 
11924     OPEN  formula_name_csr (G_CALCULATION_FORMULA_ID);
11925     FETCH formula_name_csr INTO l_formula_name;
11926     IF (formula_name_csr%NOTFOUND) THEN
11927        CLOSE formula_name_csr;
11928        Print_Debug( 'Unable to find formula for formula id :' || G_CALCULATION_FORMULA_ID);
11929        print_error_message('Interest Params cursor did not return any records for formula ID: '|| G_CALCULATION_FORMULA_ID);
11930        RAISE var_int_float_factor_failed;
11931     END IF;
11932     CLOSE formula_name_csr;
11933 
11934     Print_Debug( 'Formula Name : '|| l_formula_name);
11935 
11936     FOR current_stream IN asset_billed_streams_csr (p_contract_id, p_from_date, p_to_date)
11937     LOOP
11938        l_line_id     := current_stream.kle_id;
11939        l_invoice_amt := 0;
11940        l_stream_element_date := current_stream.stream_element_date;
11941 
11942        Print_debug( 'line id : '|| l_line_id);
11943        Print_debug('Stream Element Date: '|| l_stream_element_date);
11944 
11945        Okl_Execute_Formula_Pub.G_ADDITIONAL_PARAMETERS(1).NAME  := 'DUE_DATE';
11946        Okl_Execute_Formula_Pub.G_ADDITIONAL_PARAMETERS(1).VALUE := l_stream_element_date;
11947 
11948        -- Apply FLoat factor formula
11949        Okl_Execute_Formula_Pub.EXECUTE(
11950 	       p_api_version          => 1.0,
11951            p_init_msg_list        => OKL_API.G_TRUE,
11952            x_return_status        => x_return_status,
11953            x_msg_count            => x_msg_count,
11954            x_msg_data             => x_msg_data,
11955            p_formula_name         => l_formula_name,
11956            p_contract_id          => p_contract_id,
11957            p_line_id              => l_line_id,
11958            x_value                => l_invoice_amt
11959         );
11960 
11961        IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11962          print_error_message('Unexpected error raised in call to OKL_EXECUTE_FORMULA_PUB.EXECUTE');
11963          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11964        ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11965          print_error_message('Error raised in call to OKL_EXECUTE_FORMULA_PUB.EXECUTE');
11966          RAISE var_int_float_factor_failed;
11967        END IF;
11968 
11969        Print_debug ('Formula executed successfully');
11970        Print_debug (' Invoice Amount : '|| l_invoice_amt);
11971 
11972        l_stream_type_purpose := 'FLOAT_FACTOR_ADJUSTMENT';
11973 
11974        IF (l_invoice_amt <> 0) THEN
11975          Create_Stream_Invoice (
11976                 p_api_version            => 1.0,
11977                 p_init_msg_list          => p_init_msg_list,
11978                 x_return_status          => x_return_status,
11979                 x_msg_count              => x_msg_count,
11980                 x_msg_data               => x_msg_data,
11981                 p_contract_id            => p_contract_id,
11982                 p_line_id                => l_line_id,
11983                 p_amount                 => l_invoice_amt,
11984                 p_due_date               => l_stream_element_date,
11985                 p_stream_type_purpose    => l_stream_type_purpose,
11986                 p_create_invoice_flag    => OKL_API.G_TRUE,
11987                 p_parent_strm_element_id => NULL,
11988 				x_invoice_id             => l_invoice_id,
11989 			    x_stream_element_id      => l_stream_element_id);
11990          IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
11991            print_error_message('Unexpected error raised in call to CREATE_STREAM_INVOICE');
11992            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
11993          ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
11994            print_error_message('Error raised in call to CREATE_STREAM_INVOICE');
11995            RAISE var_int_float_factor_failed;
11996          END IF;
11997        END IF;
11998 
11999        UPDATE okl_k_headers
12000        SET    date_last_interim_interest_cal = l_stream_element_date
12001        WHERE  id = p_contract_id;
12002 
12003        COMMIT;
12004 
12005     END LOOP;
12006 
12007   EXCEPTION
12008     WHEN var_int_float_factor_failed THEN
12009       print_error_message('Exception var_int_float_factor_failed raised in procedure VARIABLE_INTEREST_FLOAT_FACTOR');
12010       x_return_status := OKL_API.G_RET_STS_ERROR;
12011     WHEN OTHERS  THEN
12012       print_error_message('Exception raised in procedure VARIABLE_INTEREST_FLOAT_FACTOR');
12013       Okl_Api.SET_MESSAGE(
12014               p_app_name     => G_APP_NAME,
12015               p_msg_name     => G_UNEXPECTED_ERROR,
12016               p_token1       => G_SQLCODE_TOKEN,
12017               p_token1_value => SQLCODE,
12018               p_token2       => G_SQLERRM_TOKEN,
12019               p_token2_value => SQLERRM);
12020 
12021       x_return_status := OKL_API.G_RET_STS_ERROR;
12022 
12023   END variable_interest_float_factor;
12024 ------------------------------------------------------------------------------
12025   FUNCTION get_next_catchup_date(p_khr_id IN NUMBER) RETURN DATE IS
12026 
12027     CURSOR c_khr_params(cp_khr_id IN NUMBER) IS
12028     select khr.date_last_interim_interest_cal date_last_interim_interest_cal
12029     , NVL(rpm.catchup_start_date, khr.start_date) catchup_start_date
12030     , NVL(rpm.catchup_frequency_code, 'MONTHLY') catchup_frequency_code
12031     , NVL(khr.date_terminated, khr.end_date) end_date
12032     from okl_k_headers_full_v khr
12033     , okl_k_rate_params rpm
12034     where khr.id = rpm.khr_id
12035     and khr.id = cp_khr_id;
12036 
12037     l_next_catchup_date DATE;
12038     l_mnth_adder NUMBER := 0;
12039     l_last_int_cal_date DATE;
12040     l_catchup_start_date DATE;
12041     l_catchup_frequency VARCHAR2(50);
12042     l_end_date DATE;
12043   BEGIN
12044     FOR cur_khr_params IN c_khr_params(p_khr_id) LOOP
12045       l_last_int_cal_date := cur_khr_params.date_last_interim_interest_cal;
12046       l_catchup_start_date := cur_khr_params.catchup_start_date;
12047       l_catchup_frequency := cur_khr_params.catchup_frequency_code;
12048       l_end_date := cur_khr_params.end_date;
12049       EXIT;
12050     END LOOP;
12051 
12052     if(UPPER(l_catchup_frequency) = 'ANNUAL') then
12053       l_mnth_adder := 12;
12054     elsif(UPPER(l_catchup_frequency) = 'SEMI_ANNUAL') then
12055       l_mnth_adder := 6;
12056     elsif(UPPER(l_catchup_frequency) = 'QUARTERLY') then
12057       l_mnth_adder := 3;
12058     elsif(UPPER(l_catchup_frequency) = 'MONTHLY') then
12059       l_mnth_adder := 1;
12060     else
12061       return null;
12062     end if;
12063 
12064     l_next_catchup_date := l_catchup_start_date;
12065     loop
12066       exit when l_next_catchup_date > NVL(l_last_int_cal_date, l_next_catchup_date - 1);
12067       --select add_months(l_next_date, l_mnth_adder) INTO l_next_date from dual;
12068       l_next_catchup_date := add_months(l_next_catchup_date, l_mnth_adder);
12069     end loop;
12070 
12071     --if next catchup date exceeds the contract end date
12072     if (l_next_catchup_date > l_end_date) then
12073       l_next_catchup_date := l_end_date;
12074     end if;
12075 
12076     return l_next_catchup_date;
12077   EXCEPTION
12078    	WHEN OTHERS THEN
12079     return l_next_catchup_date;
12080   END get_next_catchup_date;
12081 
12082   ------------------------------------------------------------------------------
12083 
12084     -- Start of Comments
12085     -- Created By:       Ramesh Seela
12086     -- Procedure Name    variable_interest_catchup
12087     -- Description:      This procedure is called by Variable Interest Calculation for Loans / Revolving Loans
12088     --                   Inputs :
12089     --                   Output :
12090     -- Dependencies:
12091     -- Parameters:
12092     -- Version:          1.0
12093     -- End of Comments
12094 
12095   ------------------------------------------------------------------------------
12096 
12097   PROCEDURE variable_interest_catchup(
12098             p_api_version     IN  NUMBER,
12099             p_init_msg_list   IN  VARCHAR2,
12100             x_return_status   OUT NOCOPY VARCHAR2,
12101             x_msg_count       OUT NOCOPY NUMBER,
12102             x_msg_data        OUT NOCOPY VARCHAR2,
12103             p_contract_id     IN  NUMBER,
12104             p_principal_basis IN  VARCHAR2,
12105             p_rev_rec_method  IN  VARCHAR2,
12106             p_deal_type       IN  VARCHAR2,
12107             p_currency_code   IN  VARCHAR2,
12108             p_start_date      IN  DATE,
12109             p_due_date        IN  DATE) IS
12110 
12111     l_api_version             CONSTANT NUMBER := 1.0;
12112     l_api_name	              CONSTANT VARCHAR2(30) := 'VARIABLE_INTEREST_CATCHUP';
12113     l_return_status	          VARCHAR2(1) := OKL_API.G_RET_STS_SUCCESS;
12114     l_msg_index_out           NUMBER;
12115     l_interest_calculated     NUMBER := 0;
12116     l_total_interest_billed   NUMBER := 0;
12117     l_principal_adjusted      NUMBER := 0;
12118 --    l_catchup_settlement_code OKL_K_RATE_PARAMS.catchup_settlement_code%TYPE;
12119     l_invoice_amt             NUMBER := 0;
12120     l_stream_type_purpose     OKL_STRM_TYPE_V.stream_type_purpose%TYPE;
12121     l_invoice_id              NUMBER;
12122     l_principal_balance_tbl   principal_balance_tbl_typ;
12123     l_total_asset_val         NUMBER := 0;
12124     l_principal_balance       NUMBER := 0;
12125     l_asset_line_tbl          okl_kle_pvt.kle_tbl_type;
12126     l_line_index              NUMBER := 0;
12127     l_index                   NUMBER := 0;
12128     l_asset_line_tbl_count    NUMBER := 0;
12129     l_prorated_invoice_amt    NUMBER := 0;
12130     i_vir_tbl                 vir_tbl_type;
12131     r_vir_tbl                 vir_tbl_type;
12132     l_stream_element_id       OKL_STRM_ELEMENTS_V.id%TYPE;
12133     var_int_catchup_failed    EXCEPTION;
12134 
12135     CURSOR interest_payment_amount_csr (cp_khr_id NUMBER, cp_start_date DATE, cp_due_date DATE) IS
12136        SELECT nvl(SUM(nvl(sel_prin_pmt.amount, 0)),0) pmt_amt
12137        FROM  okl_strm_type_v sty_prin_pmt,
12138              okl_streams_v stm_prin_pmt,
12139              okl_strm_elements_v sel_prin_pmt
12140        WHERE stm_prin_pmt.khr_id = cp_khr_id
12141        AND   stm_prin_pmt.id = sel_prin_pmt.stm_id
12142        AND   sel_prin_pmt.stream_element_date BETWEEN cp_start_date AND cp_due_date
12143        AND   stm_prin_pmt.sty_id = sty_prin_pmt.id
12144        AND   stm_prin_pmt.active_yn = 'Y'
12145        AND   stm_prin_pmt.say_code = 'CURR'
12146        AND   sty_prin_pmt.stream_type_purpose in ('INTEREST_CATCHUP', 'INTEREST_PAYMENT') ; -- 'PRINCIPAL_PAYMENT'
12147 
12148     CURSOR int_pay_amt_end_date_csr (cp_khr_id NUMBER, cp_start_date DATE) IS
12149        SELECT nvl(SUM(nvl(sel_prin_pmt.amount, 0)),0) pmt_amt
12150        FROM  okl_strm_type_v sty_prin_pmt,
12151              okl_streams_v stm_prin_pmt,
12152              okl_strm_elements_v sel_prin_pmt
12153        WHERE stm_prin_pmt.khr_id = cp_khr_id
12154        AND   stm_prin_pmt.id = sel_prin_pmt.stm_id
12155        AND   sel_prin_pmt.stream_element_date >= cp_start_date
12156        AND   stm_prin_pmt.sty_id = sty_prin_pmt.id
12157        AND   stm_prin_pmt.active_yn = 'Y'
12158        AND   stm_prin_pmt.say_code = 'CURR'
12159        AND   sty_prin_pmt.stream_type_purpose in ('INTEREST_CATCHUP', 'INTEREST_PAYMENT') ; -- 'PRINCIPAL_PAYMENT'
12160 
12161     CURSOR principal_adjustment_csr (cp_khr_id NUMBER, cp_start_date DATE, cp_due_date DATE) IS
12162        SELECT nvl(SUM(nvl(sel_prin_pmt.amount, 0)),0) pmt_amt
12163        FROM  okl_strm_type_v sty_prin_pmt,
12164              okl_streams_v stm_prin_pmt,
12165              okl_strm_elements_v sel_prin_pmt
12166        WHERE stm_prin_pmt.khr_id = cp_khr_id
12167        AND   stm_prin_pmt.id = sel_prin_pmt.stm_id
12168        AND   sel_prin_pmt.stream_element_date BETWEEN cp_start_date AND cp_due_date
12169        AND   stm_prin_pmt.sty_id = sty_prin_pmt.id
12170        AND   stm_prin_pmt.active_yn = 'Y'
12171        AND   stm_prin_pmt.say_code = 'CURR'
12172        AND   sty_prin_pmt.stream_type_purpose = 'PRINCIPAL_CATCHUP' ;
12173 
12174 /*
12175     CURSOR catchup_params_csr (p_khr_id NUMBER, p_effective_date DATE) IS
12176        SELECT catchup_settlement_code
12177        FROM   okl_k_rate_params
12178        WHERE  khr_id = p_khr_id
12179        AND    p_effective_date BETWEEN effective_from_date and nvl(effective_to_date, p_effective_date)
12180        AND    parameter_type_code = 'ACTUAL';
12181 */
12182     CURSOR contract_line_csr (p_khr_id NUMBER) IS
12183        SELECT id
12184 	   FROM   okl_k_lines_full_v
12185 	   WHERE  chr_id = p_khr_id
12186 	   AND    lse_id = G_FIN_LINE_LTY_ID
12187 	   ORDER BY id;
12188   BEGIN
12189     ------------------------------------------------------------
12190     -- Start processing
12191     ------------------------------------------------------------
12192 
12193     x_return_status := OKL_API.G_RET_STS_SUCCESS;
12194 
12195   print_debug('Executing procedure VARIABLE_INTEREST_CATCHUP using following parameters : ');
12196   print_debug('contract ID:                 '|| p_contract_id);
12197 	print_Debug('Principal Basis:             '|| p_principal_basis);
12198 	print_debug('Revenue Recognition Method:  '|| p_rev_rec_method);
12199 	print_debug('Deal Type:                   '|| p_deal_type);
12200 	Print_debug('Currency Code:               '|| p_currency_code);
12201 	print_debug('Start Date:                  '|| p_start_date);
12202 	print_debug('Due Date:                    '|| p_due_date);
12203 
12204   g_vir_tbl.delete;
12205 	g_vir_tbl_counter := 0;
12206   g_vpb_tbl.delete;
12207   g_vpb_tbl_counter := 0;
12208 
12209   populate_txns ( p_api_version => p_api_version,
12210               p_init_msg_list  => p_init_msg_list,
12211               p_khr_id  => p_contract_id,
12212               p_from_date => p_start_date,
12213               p_to_date  => p_due_date,
12214               x_return_status   => x_return_status,
12215               x_msg_count       => x_msg_count,
12216               x_msg_data        => x_msg_data);
12217 
12218   IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12219    print_error_message('Unexpected error raised in call to POPULATE_TXNS');
12220    RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12221   ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12222    print_error_message('Error raised in call to POPULATE_TXNS');
12223    RAISE var_int_catchup_failed;
12224   END IF;
12225 
12226   l_interest_calculated :=  calculate_total_interest_due(
12227                                         p_api_version     => 1.0,
12228                                         p_init_msg_list   => OKL_API.G_FALSE,
12229                                         x_return_status   => x_return_status,
12230                                         x_msg_count       => x_msg_count,
12231                                         x_msg_data        => x_msg_data,
12232                                         p_contract_id     => p_contract_id,
12233                                         p_currency_code   => p_currency_code,
12234                                         p_start_date      => p_start_date,
12235                                         p_due_date        => p_due_date);
12236     IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12237       print_error_message('Unexpected error raised in call to CALCULATE_TOTAL_INTEREST_DUE');
12238       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12239     ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12240       print_error_message('Error raised in call to CALCULATE_TOTAL_INTEREST_DUE');
12241       RAISE var_int_catchup_failed;
12242     END IF;
12243 
12244   	print_debug('Interest Calculated : ' || l_interest_calculated);
12245     l_total_interest_billed      := 0;
12246 
12247     IF (p_deal_type = 'LOAN') THEN
12248        IF (p_principal_basis = 'ACTUAL') THEN
12249           IF (p_rev_rec_method = 'STREAMS') THEN
12250              --fix for bug 5072399
12251              IF (p_due_date = G_CONTRACT_END_DATE) THEN
12252                OPEN  int_pay_amt_end_date_csr (p_contract_id, p_start_date);
12253                FETCH int_pay_amt_end_date_csr INTO l_total_interest_billed;
12254                IF (int_pay_amt_end_date_csr % NOTFOUND) THEN
12255                   l_total_interest_billed := 0;
12256                END IF;
12257                CLOSE int_pay_amt_end_date_csr;
12258              ELSE
12259                OPEN  interest_payment_amount_csr (p_contract_id, p_start_date, p_due_date);
12260                FETCH interest_payment_amount_csr INTO l_total_interest_billed;
12261                IF (interest_payment_amount_csr % NOTFOUND) THEN
12262                   l_total_interest_billed := 0;
12263                END IF;
12264                CLOSE interest_payment_amount_csr;
12265              END IF;
12266 
12267              print_debug('Interest Billed : ' || l_total_interest_billed);
12268              l_invoice_amt := OKL_ACCOUNTING_UTIL.round_amount(l_interest_calculated - l_total_interest_billed, p_currency_code);
12269 
12270              Print_debug ('Invoice Amount : '|| l_invoice_amt);
12271 
12272              IF (l_invoice_amt > 0) THEN
12273                 l_stream_type_purpose := 'INTEREST_CATCHUP';
12274                 Create_Stream_Invoice (
12275                        p_api_version         => 1.0,
12276                        p_init_msg_list       => p_init_msg_list,
12277                        x_return_status       => x_return_status,
12278                        x_msg_count           => x_msg_count,
12279                        x_msg_data            => x_msg_data,
12280                        p_contract_id         => p_contract_id,
12281                        p_line_id             => NULL,
12282                        p_amount              => l_invoice_amt,
12283                        p_due_date            => p_due_date,
12284                        p_stream_type_purpose => l_stream_type_purpose,
12285                        p_create_invoice_flag => OKL_API.G_TRUE,
12286                        p_parent_strm_element_id => NULL,
12287 					   x_invoice_id          => l_invoice_id,
12288 					   x_stream_element_id   => l_stream_element_id);
12289                 IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12290                   print_error_message('Unexpected error raised in call to CREATE_STREAM_INVOICE');
12291                   RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12292                 ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12293                   print_error_message('Error raised in call to CREATE_STREAM_INVOICE');
12294                   RAISE var_int_catchup_failed;
12295                 END IF;
12296 
12297                 i_vir_tbl := g_vir_tbl;
12298 
12299                 upd_vir_params_with_invoice (
12300                     p_api_version   => 1.0,
12301                     p_init_msg_list => OKL_API.G_TRUE,
12302                     x_return_status => x_return_status,
12303                     x_msg_count     => x_msg_count,
12304                     x_msg_data      => x_msg_data,
12305                     p_source_id     => l_invoice_id,
12306                     p_vir_tbl      => i_vir_tbl,
12307                     x_vir_tbl      => r_vir_tbl);
12308                 IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12309                   print_error_message('Unexpected error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
12310                   RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12311                 ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12312                   print_error_message('Error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
12313                   RAISE var_int_catchup_failed;
12314                 END IF;
12315 
12316                 g_vir_tbl := r_vir_tbl;
12317 
12318                 populate_vir_params(
12319                          p_api_version    => 1.0,
12320                          p_init_msg_list  => OKL_API.G_TRUE,
12321                          x_return_status  => x_return_status,
12322                          x_msg_count      => x_msg_count,
12323                          x_msg_data       => x_msg_data,
12324                          p_vir_tbl        => g_vir_tbl);
12325                 IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12326                   print_error_message('Unexpected error raised in call to POPULATE_VIR_PARAMS');
12327                   RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12328                 ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12329                   print_error_message('Error raised in call to POPULATE_VIR_PARAMS');
12330                   RAISE var_int_catchup_failed;
12331                 END IF;
12332 
12333              ELSIF (l_invoice_amt < 0) THEN
12334 /*
12335                 OPEN  catchup_params_csr (p_contract_id, SYSDATE);
12336                 FETCH catchup_params_csr INTO l_catchup_settlement_code;
12337                 IF (catchup_params_csr%NOTFOUND) THEN
12338                    CLOSE catchup_params_csr;
12339                    RAISE var_int_catchup_failed;
12340                 END IF;
12341                 CLOSE catchup_params_csr;
12342 */
12343                 print_debug (' catchup settlement code : '|| G_CATCHUP_SETTLEMENT_CODE);
12344 
12345                 IF (G_CATCHUP_SETTLEMENT_CODE = 'CREDIT') THEN
12346                    l_stream_type_purpose := 'INTEREST_CATCHUP';
12347                    Create_Stream_Invoice (
12348                           p_api_version            => 1.0,
12349                           p_init_msg_list          => p_init_msg_list,
12350                           x_return_status          => x_return_status,
12351                           x_msg_count              => x_msg_count,
12352                           x_msg_data               => x_msg_data,
12353                           p_contract_id            => p_contract_id,
12354                           p_line_id                => NULL,
12355                           p_amount                 => l_invoice_amt,
12356                           p_due_date               => p_due_date,
12357                           p_stream_type_purpose    => l_stream_type_purpose,
12358                           p_create_invoice_flag    => OKL_API.G_TRUE,
12359                           p_parent_strm_element_id => NULL,
12360 						  x_invoice_id             => l_invoice_id,
12361 			  		      x_stream_element_id      => l_stream_element_id);
12362 
12363                    IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12364                      print_error_message('Unexpected error raised in call to CREATE_STREAM_INVOICE');
12365                      RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12366                    ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12367                      print_error_message('Error raised in call to CREATE_STREAM_INVOICE');
12368                      RAISE var_int_catchup_failed;
12369                    END IF;
12370 
12371                    i_vir_tbl := g_vir_tbl;
12372 
12373                    upd_vir_params_with_invoice (
12374                        p_api_version   => 1.0,
12375                        p_init_msg_list => OKL_API.G_TRUE,
12376                        x_return_status => x_return_status,
12377                        x_msg_count     => x_msg_count,
12378                        x_msg_data      => x_msg_data,
12379                        p_source_id     => l_invoice_id,
12380                        p_vir_tbl       => i_vir_tbl,
12381                        x_vir_tbl       => r_vir_tbl);
12382                    IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12383                      print_error_message('Unexpected error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
12384                      RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12385                    ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12386                      print_error_message('Error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
12387                      RAISE var_int_catchup_failed;
12388                    END IF;
12389 
12390                    g_vir_tbl := r_vir_tbl;
12391 
12392                    populate_vir_params(
12393                             p_api_version    => 1.0,
12394                             p_init_msg_list  => OKL_API.G_TRUE,
12395                             x_return_status  => x_return_status,
12396                             x_msg_count      => x_msg_count,
12397                             x_msg_data       => x_msg_data,
12398                             p_vir_tbl        => g_vir_tbl);
12399                    IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12400                      print_error_message('Unexpected error raised in call to POPULATE_VIR_PARAMS');
12401                      RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12402                    ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12403                      print_error_message('Error raised in call to POPULATE_VIR_PARAMS');
12404                      RAISE var_int_catchup_failed;
12405                    END IF;
12406 
12407                 ELSIF (G_CATCHUP_SETTLEMENT_CODE = 'ADJUST') THEN
12408                    print_debug('Calculating PRINCIPAL_CATCHUP adjustment amounts for assets.');
12409                    l_stream_type_purpose := 'PRINCIPAL_CATCHUP';
12410                    l_line_index          := 0;
12411                    -- Identify the Assets
12412                    FOR current_line IN contract_line_csr(p_contract_id)
12413                    LOOP
12414                      prin_date_range_var_rate_ctr (
12415                           p_api_version           => 1.0,
12416                           p_init_msg_list         => OKL_API.G_FALSE,
12417                           x_return_status         => x_return_status,
12418                           x_msg_count             => x_msg_count,
12419                           x_msg_data              => x_msg_data,
12420                           p_contract_id           => p_contract_id,
12421                           p_line_id               => current_line.id,
12422                           p_start_date            => p_start_date,
12423                           p_due_date              => p_due_date,
12424                           p_principal_basis       => G_PRINCIPAL_BASIS_CODE,
12425                           x_principal_balance_tbl => l_principal_balance_tbl);
12426                      IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12427                        print_error_message('Unexpected error raised in call to PRIN_DATE_RANGE_VAR_RATE_CTR');
12428                        RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12429                      ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12430                        print_error_message('Error raised in call to PRIN_DATE_RANGE_VAR_RATE_CTR');
12431                        RAISE var_int_catchup_failed;
12432                      END IF;
12433 
12434                      IF l_principal_balance_tbl.COUNT > 0 THEN
12435                         l_principal_balance := l_principal_balance_tbl(l_principal_balance_tbl.COUNT).principal_balance;
12436                         IF (l_principal_balance > 0) THEN
12437                            l_line_index                          := l_line_index + 1;
12438                            l_asset_line_tbl(l_line_index).id     := current_line.id;
12439                            l_asset_line_tbl(l_line_index).amount := l_principal_balance;
12440                            l_total_asset_val                     := l_total_asset_val + l_principal_balance;
12441                            print_debug('Asset id :' || l_asset_line_tbl(l_line_index).id || ' Principal bal :' || l_principal_balance);
12442                         END IF;
12443                      END IF;
12444                    END LOOP;
12445                    l_asset_line_tbl_count := l_asset_line_tbl.COUNT;
12446                    l_invoice_amt          := -1 * l_invoice_amt;
12447 
12448                    OPEN  principal_adjustment_csr (p_contract_id, p_start_date, p_due_date);
12449                    FETCH principal_adjustment_csr INTO l_principal_adjusted;
12450                    IF (principal_adjustment_csr % NOTFOUND) THEN
12451                      l_principal_adjusted := 0;
12452                    END IF;
12453                    CLOSE principal_adjustment_csr;
12454 
12455                    IF (l_principal_adjusted > 0) THEN
12456                      l_invoice_amt := l_invoice_amt - l_principal_adjusted;
12457                    END IF;
12458 
12459                    print_debug('Net Invoice amount after adjustment : '|| l_invoice_amt);
12460 
12461                    IF (l_asset_line_tbl_count > 0) THEN
12462                       print_debug('Creating PRINCIPAL_CATCHUP adjustment streams for assets.');
12463 
12464                       FOR l_index in 1 .. l_asset_line_tbl_count
12465                       LOOP
12466                          l_prorated_invoice_amt := OKL_ACCOUNTING_UTIL.round_amount((l_asset_line_tbl(l_index).amount * l_invoice_amt / l_total_asset_val),p_currency_code);
12467 
12468                          print_debug('Creating PRINCIPAL_CATCHUP adjustment streams for asset id : ' || l_asset_line_tbl(l_index).id || ' for Amount :' || l_prorated_invoice_amt);
12469                          Create_Stream_Invoice (
12470                                 p_api_version            => 1.0,
12471                                 p_init_msg_list          => p_init_msg_list,
12472                                 x_return_status          => x_return_status,
12473                                 x_msg_count              => x_msg_count,
12474                                 x_msg_data               => x_msg_data,
12475                                 p_contract_id            => p_contract_id,
12476                                 p_line_id                => l_asset_line_tbl(l_index).id,
12477                                 p_amount                 => l_prorated_invoice_amt,
12478                                 p_due_date               => p_due_date,
12479                                 p_stream_type_purpose    => l_stream_type_purpose,
12480                                 p_create_invoice_flag    => OKL_API.G_FALSE,
12481                                 p_process_flag           => 'PRINCIPAL_CATCHUP',
12482                                 p_parent_strm_element_id => NULL,
12483         	    	   			x_invoice_id             => l_invoice_id,
12484             					x_stream_element_id      => l_stream_element_id);
12485 
12486                          IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12487                            print_error_message('Unexpected error raised in call to CREATE_STREAM_INVOICE');
12488                            RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12489                          ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12490                            print_error_message('Error raised in call to CREATE_STREAM_INVOICE');
12491                            RAISE var_int_catchup_failed;
12492                          END IF;
12493                          print_debug('Successfully created PRINCIPAL_CATCHUP adjustment streams for asset id : ' || l_asset_line_tbl(l_index).id || ' for Amount :' || l_prorated_invoice_amt);
12494                          l_invoice_amt := l_invoice_amt - l_prorated_invoice_amt;
12495                          l_total_asset_val := l_total_asset_val - l_asset_line_tbl(l_index).amount;
12496 
12497                       END LOOP;
12498 
12499                       i_vir_tbl := g_vir_tbl;
12500 
12501                       upd_vir_params_with_invoice (
12502                           p_api_version   => 1.0,
12503                           p_init_msg_list => OKL_API.G_TRUE,
12504                           x_return_status => x_return_status,
12505                           x_msg_count     => x_msg_count,
12506                           x_msg_data      => x_msg_data,
12507                           p_source_id     => l_stream_element_id,
12508                           p_vir_tbl       => i_vir_tbl,
12509                           x_vir_tbl      => r_vir_tbl);
12510                       IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12511                         print_error_message('Unexpected error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
12512                          RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12513                       ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12514                         print_error_message('Error raised in call to UPD_VIR_PARAMS_WITH_INVOICE');
12515                          RAISE var_int_catchup_failed;
12516                       END IF;
12517 
12518                       g_vir_tbl := r_vir_tbl;
12519 
12520                       populate_vir_params(
12521                                p_api_version    => 1.0,
12522                                p_init_msg_list  => OKL_API.G_TRUE,
12523                                x_return_status  => x_return_status,
12524                                x_msg_count      => x_msg_count,
12525                                x_msg_data       => x_msg_data,
12526                                p_vir_tbl        => g_vir_tbl);
12527                       IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12528                         print_error_message('Unexpected error raised in call to POPULATE_VIR_PARAMS');
12529                         RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12530                       ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12531                         print_error_message('Error raised in call to POPULATE_VIR_PARAMS');
12532                         RAISE var_int_catchup_failed;
12533                       END IF;
12534                    END IF;
12535                 END IF;
12536              END IF;
12537           END IF;
12538        END IF;
12539     END IF;
12540 
12541     populate_principal_bal_txn(
12542              p_api_version    => p_api_version,
12543              p_init_msg_list  => p_init_msg_list,
12544              x_return_status  => x_return_status,
12545              x_msg_count      => x_msg_count,
12546              x_msg_data       => x_msg_data,
12547              p_vpb_tbl        => g_vpb_tbl);
12548 
12549     IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12550       print_error_message('Unexpected error raised in call to POPULATE_PRINCIPAL_BAL_TXN');
12551       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12552     ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12553       print_error_message('Error raised in call to POPULATE_PRINCIPAL_BAL_TXN');
12554       RAISE var_int_catchup_failed;
12555     END IF;
12556 
12557     g_vpb_tbl.delete;
12558  	  g_vpb_tbl_counter := 0;
12559 
12560 
12561   EXCEPTION
12562     WHEN var_int_catchup_failed THEN
12563       print_error_message ('Exception var_int_catchup_failed raised in procedure VARIABLE_INTEREST_CATCHUP');
12564       x_return_status := OKL_API.G_RET_STS_ERROR;
12565     WHEN OTHERS  THEN
12566       print_error_message ('Exception raised in procedure VARIABLE_INTEREST_CATCHUP');
12567       Okl_Api.SET_MESSAGE(
12568               p_app_name     => G_APP_NAME,
12569               p_msg_name     => G_UNEXPECTED_ERROR,
12570               p_token1       => G_SQLCODE_TOKEN,
12571               p_token1_value => SQLCODE,
12572               p_token2       => G_SQLERRM_TOKEN,
12573               p_token2_value => SQLERRM);
12574       x_return_status := OKL_API.G_RET_STS_ERROR;
12575   END variable_interest_catchup;
12576 
12577 -----------------------------------------------------------------
12578   PROCEDURE variable_interest(
12579         p_api_version     IN  NUMBER,
12580         p_init_msg_list   IN  VARCHAR2,
12581         x_return_status   OUT NOCOPY VARCHAR2,
12582         x_msg_count       OUT NOCOPY NUMBER,
12583         x_msg_data        OUT NOCOPY VARCHAR2,
12584         p_contract_number IN VARCHAR2,
12585         P_to_date         IN  DATE)
12586 
12587     IS
12588     ------------------------------------------------------------
12589     -- Declare variables required by APIs
12590     ------------------------------------------------------------
12591 
12592     l_api_version                CONSTANT NUMBER := 1.0;
12593     l_api_name                   CONSTANT VARCHAR2(30) := 'VARIABLE_INTEREST';
12594     l_return_status	             VARCHAR2(1) := OKL_API.G_RET_STS_SUCCESS;
12595     l_msg_data                   VARCHAR2(2000);
12596   	l_def_no_val	             CONSTANT NUMBER		    := -1;
12597   	l_bill_date	                 OKL_TRX_AR_INVOICES_V.date_invoiced%TYPE;
12598   	l_kle_id	                 OKL_TXL_AR_INV_LNS_V.kle_id%TYPE;
12599   	l_stm_date  	             DATE;
12600   	l_period_start_date  	     DATE;
12601   	l_period_end_date  	         DATE;
12602   	l_due_date  	             DATE;
12603     l_last_interest_cal_date     DATE;
12604     l_end_of_process             BOOLEAN := FALSE;
12605     l_int_params_exist           BOOLEAN := TRUE;
12606   	l_msg_count			         NUMBER;
12607     l_from_date                  DATE;
12608     l_to_date                    DATE;
12609     l_rate_change_value          OKL_K_RATE_PARAMS.rate_change_value%TYPE;
12610     l_catchup_date               DATE;
12611     l_termination_date           DATE;
12612     l_print_lead_days            NUMBER;
12613     l_vrc_report_tbl             vrc_tbl_type;
12614     variable_interest_failed     EXCEPTION;
12615     l_int_cal_start_date         DATE;
12616     l_calculate_from_khr_start   VARCHAR2(10) := 'Y';
12617 
12618     --Bug# 7277007
12619     l_counter                    NUMBER;
12620     l_contract_number            OKC_K_HEADERS_B.contract_number%TYPE;
12621     l_product_name               OKL_PRODUCTS.name%TYPE;
12622 
12623     CURSOR c_var_int_params_csr(p_chr_id IN NUMBER,
12624                                 p_req_id IN NUMBER) IS
12625     SELECT 'Y'
12626     FROM   okl_var_int_params
12627     WHERE  khr_id = p_chr_id
12628     AND    request_id = p_req_id;
12629 
12630     l_var_int_params_found_yn VARCHAR2(1);
12631     --Bug# 7277007
12632 
12633     /* Cursor to evaluate contracts eligible for calculating Variable Interest depending on
12634     Principal Payment streams are between the last interest calculation date and the date
12635     user wants to run upto
12636     */
12637     CURSOR c_contracts_csr ( p_contract_number VARCHAR2, p_to_date DATE )IS
12638        SELECT distinct khr.id khr_id,
12639               khr.deal_type,
12640               khr.date_last_interim_interest_cal,
12641               chr.contract_number,
12642               chr.start_date start_date,
12643               chr.date_terminated termination_date,
12644               chr.end_date   end_date,
12645               chr.currency_code,
12646               ppm.interest_calculation_basis,
12647               ppm.revenue_recognition_method,
12648               chr.authoring_org_id,
12649               khr.pdt_id,
12650               --Bug# 7277007
12651               ppm.name product_name
12652        FROM   okc_k_headers_b chr,
12653               okl_k_headers   khr,
12654               okc_statuses_b  khs,
12655               okl_product_parameters_v ppm
12656        WHERE  CHR.CONTRACT_NUMBER = NVL(p_contract_number,CHR.CONTRACT_NUMBER)
12657        AND	  khr.deal_type IN ('LOAN','LEASEDF','LOAN-REVOLVING','LEASEST','LEASEOP')
12658        AND	  chr.id = khr.id
12659        AND	  khs.code = chr.sts_code
12660        AND    khs.ste_code = 'ACTIVE'
12661        AND    khr.pdt_id = ppm.id
12662        AND    ppm.interest_calculation_basis <> 'FIXED'
12663       ORDER BY khr.deal_type, chr.contract_number;
12664 
12665 
12666     CURSOR interest_params_csr (p_contract_id NUMBER,
12667                                 p_effective_date DATE) IS
12668        SELECT interest_basis_code,
12669 	          calculation_formula_id,
12670 			  nvl(principal_basis_code, 'ACTUAL'),
12671               days_in_a_month_code,
12672               days_in_a_year_code,
12673               rate_change_value,
12674               catchup_settlement_code
12675        FROM   okl_k_rate_params
12676        WHERE  khr_id = p_contract_id
12677        AND    p_effective_date BETWEEN effective_from_date and nvl(effective_to_date, p_effective_date)
12678        AND    parameter_type_code = 'ACTUAL';
12679 
12680   BEGIN
12681 
12682     ------------------------------------------------------------
12683     -- Start processing
12684     ------------------------------------------------------------
12685 
12686     x_return_status := OKL_API.G_RET_STS_SUCCESS;
12687 
12688     g_request_id    := FND_GLOBAL.CONC_REQUEST_ID;
12689 
12690     print_debug ('g_request_id : '|| g_request_id);
12691     print_debug ('Concurrent Request ID : '|| FND_GLOBAL.CONC_REQUEST_ID);
12692 
12693     g_to_date           := p_to_date;
12694 
12695     ------------------------------------------------------------
12696     -- Initialise local variables
12697     ------------------------------------------------------------
12698 
12699   	l_kle_id	:= l_def_no_val;
12700 
12701 
12702     -- **********************
12703     -- ** Process contracts *
12704     -- **********************
12705 
12706     print_debug('***Start of Processing***');
12707     print_debug('Contract Number: '||p_contract_number);
12708 
12709     g_no_of_contracts_processed   := 0;
12710     g_no_of_rejected_contracts    := 0;
12711     g_no_of_successful_contracts  := 0;
12712 
12713     FOR r_contracts_csr IN c_contracts_csr ( p_contract_number, p_to_date) LOOP
12714       print_debug ('--------------------------------------------------------------------------');
12715       print_debug ('--------------------------------------------------------------------------');
12716       print_debug ('Start Processing for Contract Number: ' ||r_contracts_csr.contract_number);
12717       print_debug('Last Interest Calculation Date: ' ||r_contracts_csr.date_last_interim_interest_cal);
12718 
12719       G_CONTRACT_ID                := r_contracts_csr.khr_id;
12720       G_AUTHORING_ORG_ID           := r_contracts_csr.authoring_org_id;
12721       G_PRODUCT_ID                 := r_contracts_csr.pdt_id;
12722       G_DEAL_TYPE                  := r_contracts_csr.deal_type;
12723       G_CONTRACT_START_DATE        := r_contracts_csr.start_date;
12724       G_CONTRACT_END_DATE          := r_contracts_csr.end_date;
12725       G_CURRENCY_CODE              := r_contracts_csr.currency_code;
12726       G_INTEREST_CALCULATION_BASIS := r_contracts_csr.interest_calculation_basis;
12727       G_CALC_METHOD_CODE           := r_contracts_csr.interest_calculation_basis;
12728       G_REVENUE_RECOGNITION_METHOD := r_contracts_csr.revenue_recognition_method;
12729       G_CONTRACT_PRINCIPAL_BALANCE := NULL;
12730       l_termination_date           := r_contracts_csr.termination_date;
12731       l_last_interest_cal_date     := r_contracts_csr.date_last_interim_interest_cal;
12732 
12733       G_FIN_AST_LINE_ID            := NULL;
12734       G_ASSET_PRINCIPAL_BALANCE    := NULL;
12735 
12736       l_print_lead_days := get_printing_lead_days (G_CONTRACT_ID);
12737 
12738       --Bug# 7277007
12739       l_contract_number := r_contracts_csr.contract_number;
12740       l_product_name    := r_contracts_csr.product_name;
12741       --Bug# 7277007
12742 
12743       OPEN interest_params_csr (G_CONTRACT_ID, nvl(p_to_date,SYSDATE));
12744       FETCH interest_params_csr INTO G_INTEREST_BASIS_CODE, G_CALCULATION_FORMULA_ID,
12745 			                         G_PRINCIPAL_BASIS_CODE, G_DAYS_IN_A_MONTH_CODE,
12746                                      G_DAYS_IN_A_YEAR_CODE, l_rate_change_value,
12747 									 G_CATCHUP_SETTLEMENT_CODE;
12748 
12749       IF interest_params_csr%NOTFOUND THEN
12750         l_int_params_exist := FALSE;
12751         print_error_message('Interest Params cursor did not return any records for contract ID: '||G_CONTRACT_ID);
12752 --       	RAISE variable_interest_failed;
12753       ELSE
12754         l_int_params_exist := TRUE;
12755       END IF;
12756       CLOSE interest_params_csr;
12757 
12758       IF (l_int_params_exist) THEN
12759         print_debug('Contract Number: '||r_contracts_csr.contract_number);
12760         print_debug('Contract ID: '|| G_CONTRACT_ID);
12761         print_debug('Authoring Org ID: '|| G_AUTHORING_ORG_ID);
12762         print_debug('Product ID: '|| G_PRODUCT_ID);
12763   	    print_debug('deal type :'|| G_DEAL_TYPE );
12764 	    print_debug('Contract Start Date: '||G_CONTRACT_START_DATE);
12765 	    print_debug('Contract End Date: '||G_CONTRACT_END_DATE);
12766 	    print_debug('Currency code: '||G_CURRENCY_CODE);
12767 	    print_debug('calculation basis : '|| G_INTEREST_CALCULATION_BASIS );
12768 	    print_debug('revenue recognition method : '|| G_REVENUE_RECOGNITION_METHOD);
12769 	    print_debug('Principal Balance : '|| G_CONTRACT_PRINCIPAL_BALANCE);
12770 	    print_debug('Last Interest Calculation Date: ' ||r_contracts_csr.date_last_interim_interest_cal );
12771 
12772 	    print_debug('Interest basis : '|| G_INTEREST_BASIS_CODE );
12773 	    print_debug('Calculation Formula ID : '|| G_CALCULATION_FORMULA_ID);
12774 	    print_debug('Principal Basis : '|| G_PRINCIPAL_BASIS_CODE);
12775 	    print_debug('Days in a Month : '|| G_DAYS_IN_A_MONTH_CODE);
12776 	    print_debug('Days in a Year  : '|| G_DAYS_IN_A_YEAR_CODE);
12777 	    print_debug('Catchup Settlement Code  : '|| G_CATCHUP_SETTLEMENT_CODE);
12778 
12779       IF (G_INTEREST_CALCULATION_BASIS = G_INT_CALC_BASIS_FLOAT_FACTORS) THEN
12780         BEGIN
12781           l_from_date := nvl(l_last_interest_cal_date,G_CONTRACT_START_DATE);
12782           l_to_date   := nvl(p_to_date, trunc(SYSDATE));
12783           --change on 15 Nov 2005 by pgomes for bug fix 4740293
12784           --considering print lead days for obtaining end date of range
12785           IF (l_to_date > trunc(SYSDATE) + l_print_lead_days) THEN
12786             l_to_date := trunc(SYSDATE) + l_print_lead_days;
12787           END IF;
12788 
12789           print_debug ('contract id : '|| G_CONTRACT_ID );
12790           print_debug ('From Date : '|| l_from_date );
12791           print_debug ('To Date : '|| l_to_date);
12792 
12793           variable_interest_float_factor(
12794                    p_api_version    => 1.0,
12795                    p_init_msg_list  => OKL_API.G_TRUE,
12796                    x_return_status  => l_return_status,
12797                    x_msg_count      => l_msg_count,
12798                    x_msg_data       => l_msg_data,
12799                    p_contract_id    => G_CONTRACT_ID,
12800                    p_from_date      => l_from_date,
12801                    p_to_date        => l_to_date);
12802           IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12803             print_error_message('Unexpected error raised in call to VARIABLE_INTEREST_FLOAT_FACTOR');
12804      	    RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12805           ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12806             print_error_message('Error raised in call to VARIABLE_INTEREST_FLOAT_FACTOR');
12807       	    RAISE variable_interest_failed;
12808           END IF;
12809           print_debug('Variable interest calculation completed successfully for contract id : '|| G_CONTRACT_ID);
12810 
12811           g_no_of_successful_contracts := g_no_of_successful_contracts + 1;
12812         EXCEPTION
12813           WHEN OTHERS THEN
12814             g_no_of_rejected_contracts := g_no_of_rejected_contracts + 1;
12815             ROLLBACK;
12816             report_error (
12817               p_contract_number     => l_contract_number,
12818               p_product_name        => l_product_name,
12819               p_interest_calc_basis => G_INTEREST_CALCULATION_BASIS,
12820               p_last_int_calc_date  => l_last_interest_cal_date,
12821               x_msg_count           => x_msg_count,
12822               x_msg_data            => x_msg_data);
12823 
12824             x_return_status := OKL_API.G_RET_STS_ERROR;
12825         END;
12826       ELSIF (G_INTEREST_CALCULATION_BASIS = G_INT_CALC_BASIS_REAMORT) THEN
12827         BEGIN
12828           print_debug ('contract id : '|| G_CONTRACT_ID );
12829 
12830           IF ((NVL(r_contracts_csr.date_last_interim_interest_cal, G_CONTRACT_START_DATE) > (trunc(sysdate) + l_print_lead_days)) OR
12831               ((NVL(r_contracts_csr.date_last_interim_interest_cal, G_CONTRACT_START_DATE) > nvl(p_to_date, trunc(SYSDATE)))) OR
12832               ((NVL(r_contracts_csr.date_last_interim_interest_cal, G_CONTRACT_START_DATE) > G_CONTRACT_END_DATE))) THEN
12833               print_error_message('Reamort Date is past the system date (with print lead days included) or is past the To Date or is past the Contract End Date.');
12834               print_debug('Reamort Date is past the system date (with print lead days included) or is past the To Date or is past the Contract End Date.');
12835           ELSE
12836             initiate_request(
12837                      p_api_version    => 1.0,
12838                      p_init_msg_list  => OKL_API.G_TRUE,
12839                      p_khr_id         => G_CONTRACT_ID,
12840                      x_return_status  => l_return_status,
12841                      x_msg_count      => l_msg_count,
12842                      x_msg_data       => l_msg_data);
12843 
12844             IF (l_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12845               print_error_message('Unexpected error raised in call to INITIATE_REQUEST');
12846        	    RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12847             ELSIF (l_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12848               print_error_message('Error raised in call to INITIATE_REQUEST');
12849         	    RAISE variable_interest_failed;
12850             END IF;
12851             print_debug('Variable interest calculation completed successfully for contract id : '|| G_CONTRACT_ID);
12852             COMMIT;
12853             g_no_of_successful_contracts := g_no_of_successful_contracts + 1;
12854           END IF;
12855         EXCEPTION
12856           WHEN OTHERS THEN
12857             g_no_of_rejected_contracts := g_no_of_rejected_contracts + 1;
12858             ROLLBACK;
12859             report_error (
12860               p_contract_number     => l_contract_number,
12861               p_product_name        => l_product_name,
12862               p_interest_calc_basis => G_INTEREST_CALCULATION_BASIS,
12863               p_last_int_calc_date  => l_last_interest_cal_date,
12864               x_msg_count           => x_msg_count,
12865               x_msg_data            => x_msg_data);
12866 
12867             x_return_status := OKL_API.G_RET_STS_ERROR;
12868         END;
12869       ELSIF (G_INTEREST_CALCULATION_BASIS = G_INT_CALC_BASIS_FLOAT) THEN
12870          BEGIN
12871            IF (l_last_interest_cal_date is not null
12872                and l_last_interest_cal_date > G_CONTRACT_START_DATE) THEN
12873              l_stm_date := l_last_interest_cal_date;
12874            ELSE
12875              l_stm_date := G_CONTRACT_START_DATE;
12876            END IF;
12877 
12878            print_debug('Stream Start Date: '||l_stm_date);
12879 
12880            l_end_of_process := FALSE;
12881            l_calculate_from_khr_start := 'Y';
12882 
12883            print_debug ('Stream Start Date: '||l_stm_date);
12884            print_debug ('Contract Id: '||G_CONTRACT_ID);
12885            print_debug ('To Date: '||p_to_date);
12886 
12887            l_end_of_process := FALSE;
12888            l_bill_date := null;
12889            l_due_date := null;
12890            LOOP
12891              IF ((G_DEAL_TYPE = 'LOAN' or G_DEAL_TYPE ='LOAN-REVOLVING') AND
12892                  ( NOT(l_end_of_process))) THEN
12893                 print_debug('Executing OKL_STREAM_GENERATOR_PVT.get_next_billing_date ');
12894                 print_debug('Billing Date : '|| nvl(l_last_interest_cal_date, G_CONTRACT_START_DATE) );
12895 
12896                 OKL_STREAM_GENERATOR_PVT.get_next_billing_date(
12897                     p_api_version            => p_api_version,
12898                     p_init_msg_list          => p_init_msg_list,
12899                     p_khr_id                 => G_CONTRACT_ID,
12900                     p_billing_date           => nvl(l_last_interest_cal_date, G_CONTRACT_START_DATE),
12901                     x_next_due_date          => l_due_date,
12902                     x_next_period_start_date => l_period_start_date,
12903                     x_next_period_end_date   => l_period_end_date,
12904                     x_return_status          => x_return_status,
12905                     x_msg_count              => x_msg_count,
12906                     x_msg_data               => x_msg_data);
12907 
12908                 IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12909                    print_error_message('Unexpected error raised in call to OKL_STREAM_GENERATOR_PVT.get_next_billing_date');
12910                    RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12911                 ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12912                    print_error_message('Error raised in call to OKL_STREAM_GENERATOR_PVT.get_next_billing_date');
12913        		       RAISE variable_interest_failed;
12914                 END IF;
12915 
12916                 print_debug(' Next Due Date : '|| l_due_date );
12917         				print_debug(' Next Period Start Date : '|| l_period_start_date );
12918         				print_debug(' Next Period End Date : ' || l_period_end_date );
12919         				print_debug(' Last Interest calculation date : '|| l_last_interest_cal_date);
12920 
12921              END IF;
12922 
12923              IF (trunc(l_due_date) = l_last_interest_cal_date OR
12924                  l_due_date is null OR
12925                  trunc(l_due_date) > (trunc(sysdate)+ l_print_lead_days) OR
12926                  trunc(l_due_date) > trunc(p_to_date)) THEN
12927                  --EXIT;
12928                 l_end_of_process := TRUE;
12929              END IF;
12930 
12931              print_debug('Stream Element Date: '||l_due_date);
12932 
12933              x_return_status := OKL_API.G_RET_STS_SUCCESS;
12934              ----------------------------------------------------
12935              -- Create new transaction header for every
12936              -- contract and bill_date combination
12937              ----------------------------------------------------
12938              print_debug('Bill Date: '||l_due_date);
12939 
12940              IF NOT(l_end_of_process) THEN
12941              ------------------------------------------------------------
12942                 print_debug ('Executing procedure variable_interest_float');
12943                 print_debug ('Contract ID : '|| G_CONTRACT_ID );
12944         				print_debug( 'Principal Basis : '|| G_PRINCIPAL_BASIS_CODE);
12945         				print_debug( 'Revenue Recognition Method : '|| G_REVENUE_RECOGNITION_METHOD );
12946         				print_debug( 'Calculation Basis : '|| G_INTEREST_CALCULATION_BASIS );
12947                 print_debug( 'Deal Type : '|| G_DEAL_TYPE);
12948                 print_debug( 'Currency Code : '|| G_CURRENCY_CODE );
12949                 print_debug( 'Start Date : '|| G_CONTRACT_START_DATE );
12950                 print_debug( 'Period Start Date : '|| l_period_start_date );
12951         				print_debug( 'Due Date : '|| l_due_date);
12952 
12953         				-- BUG 4748287
12954         				IF (G_PRINCIPAL_BASIS_CODE = 'SCHEDULED') THEN
12955         				   l_int_cal_start_date := l_period_start_date;
12956         				ELSE
12957                    l_calculate_from_khr_start := calculate_from_khr_start_date(p_khr_id => G_CONTRACT_ID,
12958                                                                                p_from_date => l_period_start_date);
12959 
12960         				   IF (l_calculate_from_khr_start = 'Y') THEN
12961                      l_int_cal_start_date := G_CONTRACT_START_DATE;
12962             				 print_debug('Float interest calculation will start from contract start date : ' || l_int_cal_start_date);
12963                    ELSE
12964                      l_int_cal_start_date := l_period_start_date;
12965             				 print_debug('Float interest calculation will start from billing period start date : ' || l_int_cal_start_date);
12966                    END IF;
12967         				END IF;
12968 
12969                 variable_interest_float(
12970                          p_api_version     => 1.0,
12971                          p_init_msg_list   => OKL_API.G_TRUE,
12972                          x_return_status   => x_return_status,
12973                          x_msg_count       => x_msg_count,
12974                          x_msg_data        => x_msg_data,
12975                          p_contract_id     => G_CONTRACT_ID,
12976                          p_principal_basis => G_PRINCIPAL_BASIS_CODE,
12977                          p_rev_rec_method  => G_REVENUE_RECOGNITION_METHOD,
12978                          p_deal_type       => G_DEAL_TYPE,
12979                          p_currency_code   => G_CURRENCY_CODE,
12980                          p_start_date      => l_int_cal_start_date,
12981                          p_due_date        => l_due_date);
12982 
12983                 IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
12984                    print_error_message('Unexpected error raised in call to VARIABLE_INTEREST_FLOAT');
12985          	       RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
12986                 ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
12987                    print_error_message('Error raised in call to VARIABLE_INTEREST_FLOAT');
12988        		       RAISE variable_interest_failed;
12989                 END IF;
12990 
12991                 print_debug ('Variable interest Calculation completed successfully for Billing period : '|| l_due_date);
12992              ELSE
12993                EXIT;
12994              END IF;
12995 
12996              FND_FILE.PUT_LINE (FND_FILE.LOG, '===============================================================================');
12997 
12998              UPDATE okl_k_headers khr
12999              SET    khr.date_last_interim_interest_cal =  l_due_date
13000              WHERE  khr.id = G_CONTRACT_ID;
13001 
13002              l_last_interest_cal_date := l_due_date;
13003 
13004              COMMIT;
13005 
13006              Print_debug('Processing complete for due date : '|| l_due_date);
13007            END LOOP;
13008            g_no_of_successful_contracts := g_no_of_successful_contracts + 1;
13009          EXCEPTION
13010            WHEN OTHERS THEN
13011              g_no_of_rejected_contracts := g_no_of_rejected_contracts + 1;
13012              x_return_status := OKL_API.G_RET_STS_ERROR;
13013              l_end_of_process := TRUE;
13014              report_error (
13015                p_contract_number     => l_contract_number,
13016                p_product_name        => l_product_name,
13017                p_interest_calc_basis => G_INTEREST_CALCULATION_BASIS,
13018                p_last_int_calc_date  => l_last_interest_cal_date,
13019                x_msg_count           => x_msg_count,
13020                x_msg_data            => x_msg_data);
13021              ROLLBACK;
13022          END;
13023        ELSIF (G_INTEREST_CALCULATION_BASIS = G_INT_CALC_BASIS_CATCHUP) THEN
13024          BEGIN
13025 
13026            l_end_of_process := FALSE;
13027            l_catchup_date := get_next_catchup_date(G_CONTRACT_ID);
13028            l_calculate_from_khr_start := 'Y';
13029 
13030            Print_Debug ('Principal Basis : '|| G_PRINCIPAL_BASIS_CODE);
13031            Print_Debug ('Catchup Date : '|| l_catchup_date);
13032 
13033            --change by pgomes on 17 nov 2005 for bug fix 4739869
13034            --IF (NOT(l_last_interest_cal_date is NOT NULL AND
13035            --  l_last_interest_cal_date >= l_catchup_date)) THEN
13036              LOOP
13037                IF (l_catchup_date > NVL(l_last_interest_cal_date, l_catchup_date - 1) AND
13038                    l_catchup_date  <= (trunc(sysdate)+ l_print_lead_days) AND
13039                    l_catchup_date <= NVL(p_to_date, l_catchup_date)) THEN
13040                   l_end_of_process := FALSE;
13041                ELSE
13042                   l_end_of_process := TRUE;
13043                END IF;
13044 
13045                EXIT WHEN l_end_of_process = TRUE;
13046 
13047                l_period_start_date := NVL(l_last_interest_cal_date + 1, G_CONTRACT_START_DATE);
13048 
13049                l_calculate_from_khr_start := calculate_from_khr_start_date(p_khr_id => G_CONTRACT_ID,
13050                                                                            p_from_date => l_period_start_date);
13051 
13052     				   IF (l_calculate_from_khr_start = 'Y') THEN
13053                  l_int_cal_start_date := G_CONTRACT_START_DATE;
13054         				 print_debug('Catchup Cleanup interest calculation will start from contract start date : ' || l_int_cal_start_date);
13055                ELSE
13056                  l_int_cal_start_date := l_period_start_date;
13057         				 print_debug('Catchup Cleanup interest calculation will start from catchup period start date : ' || l_int_cal_start_date);
13058                END IF;
13059 
13060                VARIABLE_INTEREST_CATCHUP(
13061                         p_api_version     => p_api_version,
13062                         p_init_msg_list   => Okl_Api.G_TRUE,
13063                         x_return_status   => x_return_status,
13064                         x_msg_count       => x_msg_count,
13065                         x_msg_data        => x_msg_data,
13066                         p_contract_id     => G_CONTRACT_ID,
13067                         p_principal_basis => G_PRINCIPAL_BASIS_CODE,
13068                         p_rev_rec_method  => G_REVENUE_RECOGNITION_METHOD,
13069                         p_deal_type       => G_DEAL_TYPE,
13070                         p_currency_code   => G_CURRENCY_CODE,
13071                         p_start_date      => l_int_cal_start_date,
13072                         p_due_date        => l_catchup_date);
13073 
13074                IF (x_return_status = Okl_Api.G_RET_STS_UNEXP_ERROR) THEN
13075                   print_error_message('Unexpected error raised in call to VARIABLE_INTEREST_CATCHUP');
13076                   RAISE Okl_Api.G_EXCEPTION_UNEXPECTED_ERROR;
13077                ELSIF (x_return_status = Okl_Api.G_RET_STS_ERROR) THEN
13078                   print_error_message('Error raised in call to VARIABLE_INTEREST_CATCHUP');
13079        		      RAISE variable_interest_failed;
13080                END IF;
13081 
13082                print_debug ('Updating contract - id : '|| G_CONTRACT_ID || 'with interest calculation date : '|| l_catchup_date);
13083 
13084                UPDATE okl_k_headers khr
13085                SET    khr.date_last_interim_interest_cal =  l_catchup_date
13086                where  khr.id = G_CONTRACT_ID;
13087 
13088                l_last_interest_cal_date := l_catchup_date;
13089 
13090                COMMIT;
13091 
13092                /*IF (l_catchup_date >= nvl(l_termination_date, l_contract_end_date) OR
13093 			       l_catchup_date > (trunc(sysdate)+ l_print_lead_days) OR
13094 				   l_catchup_date > l_last_interest_cal_date) THEN
13095                   l_end_of_process := TRUE;
13096                ELSE*/
13097 			      l_catchup_date := get_next_catchup_date(G_CONTRACT_ID);
13098   			   --END IF;
13099              END LOOP;
13100           --END IF;
13101           g_no_of_successful_contracts := g_no_of_successful_contracts + 1;
13102         EXCEPTION
13103            WHEN OTHERS THEN
13104              g_no_of_rejected_contracts := g_no_of_rejected_contracts + 1;
13105              x_return_status := OKL_API.G_RET_STS_ERROR;
13106              l_end_of_process := TRUE;
13107              report_error (
13108                p_contract_number     => l_contract_number,
13109                p_product_name        => l_product_name,
13110                p_interest_calc_basis => G_INTEREST_CALCULATION_BASIS,
13111                p_last_int_calc_date  => l_last_interest_cal_date,
13112                x_msg_count           => x_msg_count,
13113                x_msg_data            => x_msg_data);
13114              ROLLBACK;
13115         END;
13116       END IF;
13117       END IF;
13118 
13119       g_no_of_contracts_processed := g_no_of_contracts_processed + 1;
13120 
13121       l_vrc_report_tbl(g_no_of_contracts_processed).contract_number            := r_contracts_csr.contract_number;
13122       l_vrc_report_tbl(g_no_of_contracts_processed).contract_id                := G_CONTRACT_ID;
13123       l_vrc_report_tbl(g_no_of_contracts_processed).start_date                 := G_CONTRACT_START_DATE;
13124       l_vrc_report_tbl(g_no_of_contracts_processed).end_date                   := G_CONTRACT_END_DATE;
13125       l_vrc_report_tbl(g_no_of_contracts_processed).interest_calculation_basis := G_INTEREST_CALCULATION_BASIS;
13126       l_vrc_report_tbl(g_no_of_contracts_processed).days_in_a_month_code       := G_DAYS_IN_A_MONTH_CODE;
13127       l_vrc_report_tbl(g_no_of_contracts_processed).days_in_a_year_code        := G_DAYS_IN_A_YEAR_CODE;
13128       l_vrc_report_tbl(g_no_of_contracts_processed).rate_change_value          := l_rate_change_value;
13129       l_vrc_report_tbl(g_no_of_contracts_processed).process_status             := x_return_status;
13130 
13131       --Bug# 7277007
13132       IF (x_return_status = 'S') THEN
13133 
13134         l_var_int_params_found_yn := 'N';
13135         OPEN c_var_int_params_csr(p_chr_id => g_contract_id,
13136                                   p_req_id => g_request_id);
13137         FETCH c_var_int_params_csr INTO l_var_int_params_found_yn;
13138         CLOSE c_var_int_params_csr;
13139 
13140         IF (l_var_int_params_found_yn = 'Y') THEN
13141           IF g_rpt_summary_tbl.EXISTS(G_INTEREST_CALCULATION_BASIS) THEN
13142             g_rpt_summary_tbl(G_INTEREST_CALCULATION_BASIS).total_contract_num_success :=
13143             NVL(g_rpt_summary_tbl(G_INTEREST_CALCULATION_BASIS).total_contract_num_success,0) + 1;
13144           ELSE
13145             g_rpt_summary_tbl(G_INTEREST_CALCULATION_BASIS).total_contract_num_success := 1;
13146           END IF;
13147 
13148           l_counter := 1;
13149           IF g_rpt_success_icb_tbl.EXISTS(G_INTEREST_CALCULATION_BASIS) THEN
13150             l_counter := g_rpt_success_icb_tbl(G_INTEREST_CALCULATION_BASIS).LAST + 1;
13151           END IF;
13152 
13153           g_rpt_success_icb_tbl(G_INTEREST_CALCULATION_BASIS)(l_counter).contract_id          := G_CONTRACT_ID;
13154           g_rpt_success_icb_tbl(G_INTEREST_CALCULATION_BASIS)(l_counter).contract_number      := r_contracts_csr.contract_number;
13155           g_rpt_success_icb_tbl(G_INTEREST_CALCULATION_BASIS)(l_counter).days_in_a_month_code := G_DAYS_IN_A_MONTH_CODE;
13156           g_rpt_success_icb_tbl(G_INTEREST_CALCULATION_BASIS)(l_counter).days_in_a_year_code  := G_DAYS_IN_A_YEAR_CODE;
13157         END IF;
13158       END IF;
13159       --Bug# 7277007
13160 
13161       print_debug ('End Processing for Contract Number: ' ||r_contracts_csr.contract_number);
13162 
13163     END LOOP;
13164     print_debug('***Printing Report***');
13165     Print_Report(p_contract_number => p_contract_number);
13166     print_debug('***End of Processing***');
13167 
13168 
13169   EXCEPTION
13170     	------------------------------------------------------------
13171     	-- Exception handling
13172     	------------------------------------------------------------
13173     WHEN OTHERS THEN
13174       print_error_message('Exception raised in procedure VARIABLE_INTEREST');
13175       report_error (
13176         p_contract_number     => l_contract_number,
13177         p_product_name        => l_product_name,
13178         p_interest_calc_basis => G_INTEREST_CALCULATION_BASIS,
13179         p_last_int_calc_date  => l_last_interest_cal_date,
13180         x_msg_count           => x_msg_count,
13181         x_msg_data            => x_msg_data);
13182       x_return_status := OKL_API.G_RET_STS_ERROR;
13183       ROLLBACK;
13184    END variable_interest;
13185 END;