DBA Data[Home] [Help]

PACKAGE BODY: APPS.LNS_DISTRIBUTIONS_PUB

Source


1 PACKAGE BODY LNS_DISTRIBUTIONS_PUB AS
2 /* $Header: LNS_DIST_PUBP_B.pls 120.75.12020000.6 2013/03/07 16:32:04 scherkas ship $ */
3 
4 /*========================================================================+
5  |  Package Global Constants
6  +=======================================================================*/
7  G_DEBUG_COUNT               NUMBER := 0;
8  G_DEBUG                     BOOLEAN := FALSE;
9 
10  G_PKG_NAME                  CONSTANT VARCHAR2(30) := 'LNS_DISTRIBUTIONS_PUB';
11  g_cr_return_status              VARCHAR2(10);
12  g_last_accrual_report          CLOB;
13  g_last_all_statements         CLOB;
14  g_cp_statements		 CLOB;
15  g_passed_loan_cnt		  NUMBER;
16  g_failed_loan_cnt		  NUMBER;
17  G_EXC_WARNING		 EXCEPTION;
18 
19 --------------------------------------------
20 -- internal package routines
21 --------------------------------------------
22 procedure logMessage(log_level in number
23                     ,module    in varchar2
24                     ,message   in varchar2)
25 is
26 
27 begin
28 
29     IF log_level >= FND_LOG.G_CURRENT_RUNTIME_LEVEL THEN
30         FND_LOG.STRING(log_level, module, message);
31         if FND_GLOBAL.Conc_Request_Id is not null then
32             fnd_file.put_line(FND_FILE.LOG, message);
33         end if;
34     END IF;
35 end;
36 
37 procedure cancel_disbursements(p_init_msg_list          in varchar2
38                               ,p_commit                 in varchar2
39                               ,p_loan_id                in number
40                               ,x_return_status          OUT NOCOPY VARCHAR2
41                               ,x_msg_count              OUT NOCOPY NUMBER
42                               ,x_msg_data               OUT NOCOPY VARCHAR2)
43 is
44 
45   l_api_name         varchar2(50);
46   l_event_id         number;
47   l_budget_req_approval   varchar2(1);
48   l_funds_reserved_flag   varchar2(1);
49   l_gl_date               date;
50   l_budget_event_exists   number;
51   l_status_code           varchar2(25);
52   l_return_status         varchar2(1);
53   l_packet_id             number;
54   l_msg_count             number;
55   l_msg_data              VARCHAR2(2000);
56   l_version               number;
57   l_loan_header_rec       LNS_LOAN_HEADER_PUB.loan_header_rec_type;
58   l_disbursement_id       number;
59 
60     cursor c_events(p_loan_id number) is
61     select event_id
62         from xla_transaction_entities xlee
63             ,xla_events xle
64       where xle.application_id = 206
65         and xle.entity_id = xlee.entity_id
66         and xlee.source_id_int_1 = p_loan_id
67         and xle.budgetary_control_flag = 'Y'
68         and xle.event_type_code = 'FUTURE_DISBURSEMENT_CANCELLED'
69         and xle.process_status_code <> 'P';
70 
71     cursor c_budget_req(p_loan_id number) is
72     select nvl(p.BDGT_REQ_FOR_APPR_FLAG, 'N')
73           ,nvl(h.funds_reserved_flag, 'N')
74           ,nvl(h.gl_date, sysdate)
75       from lns_loan_headers h,
76            lns_loan_products p
77       where p.loan_product_id = h.product_id
78         and h.loan_id = p_loan_id;
79 
80     cursor c_obj_vers(p_loan_id number) is
81     select object_version_number
82       from lns_loan_headers
83      where loan_id = p_loan_id;
84 
85     cursor c_disbursements(p_loan_id number) is
86     select disb_header_id
87       from lns_disb_headers
88      where loan_id = p_loan_id
89        and disbursement_number = 1;
90 
91 begin
92 
93       SAVEPOINT cancel_disbursements;
94       l_api_name := 'cancel_disbursements';
95       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
96       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id '  || p_loan_id);
97 
98       -- Initialize message list IF p_init_msg_list is set to TRUE.
99       IF FND_API.to_Boolean( p_init_msg_list ) THEN
100           FND_MSG_PUB.initialize;
101       END IF;
102 
103       -- Initialize API return status to SUCCESS
104       x_return_status         := FND_API.G_RET_STS_SUCCESS;
105 
106       -- first complete accounting for any unprocessed events / documents for the loan transaction
107       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling lns_distributions_pub.onlineAccounting...');
108       lns_distributions_pub.onlineAccounting(p_loan_id            => p_loan_id
109                                             ,p_init_msg_list      => fnd_api.g_false
110                                             ,p_accounting_mode    => 'F'
111                                             ,p_transfer_flag      => 'Y'
112                                             ,p_offline_flag       => 'N'
113                                             ,p_gl_posting_flag    => 'N'
114                                             ,x_return_status      => l_return_status
115                                             ,x_msg_count          => l_msg_count
116                                             ,x_msg_data           => l_msg_data);
117       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
118       if l_return_status <> 'S' then
119             RAISE FND_API.G_EXC_ERROR;
120       end if;
121 
122 
123 
124       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'fetching l_disbusement_id ');
125       open c_disbursements(p_loan_id);
126       fetch c_disbursements into l_disbursement_id;
127       close c_disbursements;
128       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_disbusement_id ' || l_disbursement_id);
129 
130       if (lns_utility_pub.IS_FED_FIN_ENABLED = 'Y' OR LNS_UTILITY_PUB.IS_ENCUM_FIN_ENABLED = 'Y') then
131 
132        logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Invoking LNS_DISTRIBUTIONS_PUB.generateCancelDistributions...');
133 	     LNS_DISTRIBUTIONS_PUB.generateCancelDistributions(p_api_version     => 1
134 								,p_init_msg_list  => 'F'
135 								,p_commit         => 'F'
136 								,p_loan_id        => p_loan_id
137 								,x_return_status  => l_return_status
138 								,x_msg_count      => l_msg_count
139 								,x_msg_data       =>  l_msg_data);
140 
141 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'GenerateCancelDistribs - l_return_status = ' || l_return_status);
142 
143 	    IF l_return_status <> 'S' THEN
144 		logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' generateCancelDistributions failed with error '||l_msg_data);
145 		RAISE FND_API.G_EXC_ERROR;
146 	    END IF;
147 
148             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'federal enabled');
149             open c_budget_req(p_loan_id);
150             fetch c_budget_req into l_budget_req_approval, l_funds_reserved_flag, l_gl_date;
151             close c_budget_req;
152             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_budget_req_approval '  || l_budget_req_approval);
153             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_funds_reserved_flag '  || l_funds_reserved_flag);
154 
155             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_XLA_EVENTS.create_event...');
156 
157             LNS_XLA_EVENTS.create_event(p_loan_id         => p_loan_id
158                                     ,p_disb_header_id  => -1
159                                     ,p_loan_amount_adj_id => -1
160                                     ,p_event_type_code => 'FUTURE_DISBURSEMENT_CANCELLED'
161                                     ,p_event_date      => l_gl_date
162                                     ,p_event_status    => 'U'
163                                     ,p_init_msg_list   => fnd_api.g_false
164                                     ,p_commit          => fnd_api.g_false
165                                     ,p_bc_flag         => 'Y'
166                                     ,x_event_id        => l_event_id
167                                     ,x_return_status   => l_return_status
168                                     ,x_msg_count       => l_msg_count
169                                     ,x_msg_data        => l_msg_data);
170             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
171             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
172 
173             IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
174                 FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCOUNTING_EVENT_ERROR');
175                 FND_MSG_PUB.ADD;
176                 logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
177                 RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
178             END IF;
179 
180             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'stamping new event_id on distributions');
181             update lns_distributions
182             set event_id = l_event_id
183             ,last_update_date = sysdate
184 	          ,object_Version_number = object_version_number + 1
185             where distribution_type = 'ORIGINATION'
186             and loan_id           = p_loan_id
187 	    and activity = 	'LNS_REMAIN_DISB_CANCEL';
188 
189             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updated event_id '||l_event_id||' succesfully for '||SQL%ROWCOUNT||' rows');
190 
191             if (l_funds_reserved_flag = 'Y') then
192 
193                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'inserting into PSA_BC_XLA_EVENTS_GT - event => ' || l_event_id);
194                 insert into PSA_BC_XLA_EVENTS_GT (event_id, result_code)
195                 values (l_event_id, 'FAIL');
196 
197                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling PSA_BC_XLA_PUB.Budgetary_Control  '  || l_event_id);
198                 -- always pass P_BC_MODE = reserve as per shaniqua williams
199                 PSA_BC_XLA_PUB.Budgetary_Control(p_api_version      => 1.0
200                                                 ,p_init_msg_list    => FND_API.G_FALSE
201                                                 ,x_return_status    => l_return_status
202                                                 ,x_msg_count        => l_msg_count
203                                                 ,x_msg_data         => l_msg_data
204                                                 ,p_application_id   => 206
205                                                 ,p_bc_mode          => 'R'
206                                                 ,p_override_flag    => null
207                                                 ,p_user_id          => null
208                                                 ,p_user_resp_id     => null
209                                                 ,x_status_code      => l_status_code
210                                                 ,x_packet_ID        => l_packet_id);
211 
212                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || '  BC status is = ' || l_return_status);
213                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || '  l_status_code = ' || l_status_code);
214                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || '  l_packet_id = ' || l_packet_id);
215 
216                 -- we want to commit ONLY in the case of SUCCESS or ADVISORY
217                 if (l_return_status <> 'S') then
218 
219                     x_return_status         := FND_API.G_RET_STS_ERROR;
220                     FND_MESSAGE.SET_NAME('LNS', 'LNS_API_OTHERS_EXCEP');
221                     FND_MESSAGE.SET_TOKEN('ERROR' ,'Call to PSA_BC_XLA_PUB.Budgetary_Control failed with Status Code = ' || l_status_code);
222                     FND_MSG_PUB.ADD;
223                     logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
224                     RAISE FND_API.G_EXC_ERROR;
225 
226                 else
227                     -- caller handle success status
228                     null;
229 
230                 end if; -- BC_API.RETURN_STATUS
231 
232             end if; -- l_funds_reserved_flag
233 
234       end if;
235 
236       x_return_status         := l_return_status;
237       IF FND_API.to_Boolean(p_commit)
238       THEN
239         COMMIT WORK;
240       END IF;
241 
242       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
243 
244 EXCEPTION
245 
246     WHEN FND_API.G_EXC_ERROR THEN
247         ROLLBACK TO cancel_disbursements;
248         x_return_status := FND_API.G_RET_STS_ERROR;
249         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
250         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
251 
252     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
253         ROLLBACK TO cancel_disbursements;
254         x_return_status := FND_API.G_RET_STS_ERROR;
255         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
256         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
257 
258     WHEN OTHERS THEN
259         ROLLBACK TO cancel_disbursements;
260         x_return_status := FND_API.G_RET_STS_ERROR;
261         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
262         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
263 
264 end cancel_disbursements;
265 
266 /*=========================================================================
267 || FUNCTION GENERATE_BC_REPORT
268 ||
269 || DESCRIPTION
270 ||         this function generatesthe BC report and returns the sequence_id
271 ||          needed for the rpt
272 ||
273 || PARAMETERS   p_loan_id => loan identifier
274 ||              p_loan_amount_adj_id => Loan Amount Adjustment Identifier default NULL
275 ||              p_source => Report generation for LoanApproval/LoanAdjustment default NULL
276 ||
277 || Return value:  sequence for BC report
278 ||
279 || Source Tables:
280 ||
281 || Target Tables: NA
282 ||
283 || KNOWN ISSUES
284 ||
285 || NOTES
286 ||
287 || MODIFICATION HISTORY
288 || Date                  Author            Description of Changes
289 || 10-01-2005            raverma             Created
290  *=======================================================================*/
291 FUNCTION GENERATE_BC_REPORT(p_loan_id number
292 			  , p_source varchar2 default NULL
293                           , p_loan_amount_adj_id number default NULL
294                          ) RETURN NUMBER IS
295 
296 	l_api_name             varchar2(50);
297 	l_count                NUMBER;
298  	l_event_id             number;
299 	l_distribution_id      number;
300 	l_errbuf               VARCHAR2(3000);
301 	l_retcode              NUMBER;
302 	l_ledger_id            number;
303 	l_application_id       number;
304 	l_event_flag           varchar2(1);
305 	l_sequence_id          number;
306   	l_loan_amount_adj_id   number;
307   	l_return_status         VARCHAR2(1);
308 	l_msg_count             NUMBER;
309 	l_msg_data              VARCHAR2(32767);
310 
311 
312 	cursor c_event (c_loan_id number, c_loan_amount_adj_id number) is
313     select xle.event_id, xll.source_distribution_id_num_1, ledger_id
314     from xla_transaction_entities xlee
315         ,xla_events xle
316         ,xla_distribution_links   xll
317     where xle.application_id = 206
318         and xle.entity_id = xlee.entity_id
319         and xlee.source_id_int_1 = c_loan_id
320     --    and nvl(xlee.source_id_int_3, -1) = nvl(c_loan_amount_adj_id, -1)
321         and xle.budgetary_control_flag = 'Y'
322         and xll.event_id =xle.event_id
323 	order by event_id desc;
324 
325   cursor c_loan_adj(c_loan_id number) is
326    select max(ladj.loan_amount_adj_id)
327     from lns_loan_amount_adjs ladj
328          ,xla_transaction_entities xlee
329          ,xla_events xle
330     where ladj.loan_id = c_loan_id
331       and xlee.entity_id = xle.entity_id
332       and xle.event_type_code in ('DIRECT_LOAN_ADJ_APPROVED', 'DIRECT_LOAN_ADJ_REVERSED')
333       and xlee.source_id_int_1 = ladj.loan_id
334       and xlee.source_id_int_3 = ladj.loan_amount_adj_id
335       and ladj.status in ('PENDING', 'APPROVED')
336     order by ladj.loan_amount_adj_id desc;
337 
338 BEGIN
339 
340     l_sequence_id    := -1;
341     l_application_id := 206;
342     l_event_flag     := 'E';
343     l_api_name       := 'generate_bc_report';
344 
345     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
346     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id '  || p_loan_id);
347     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_amount_adj_id '  || p_loan_amount_adj_id);
348     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_source '  || p_source);
349 
350     -- steps 1. delete from PSA_BC_REPORT_EVENTS_GT
351     --       2. insert into PSA_BC_REPORT_EVENTS_GT
352     --       3. generate sequence
353     --       4. call Create_BC_Transaction_report API
354     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'deleting from PSA_BC_REPORT_EVENTS_GT');
355     DELETE FROM PSA_BC_REPORT_EVENTS_GT;
356 
357     IF p_source = 'LOAN_AMOUNT_ADJUSTMENT' THEN
358       IF p_loan_amount_adj_id IS NULL THEN
359         -- Retrieve the Pending Loan Amount Adjustment Id of the loan
360         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Retrieve the pending loan_amount_adj_id based on the input loan_id');
361 
362         lns_utility_pub.validate_any_id(p_api_version    =>  1.0
363                                       ,p_init_msg_list  =>  'F'
364                                       ,x_msg_count      =>  l_msg_count
365                                       ,x_msg_data       =>  l_msg_data
366                                       ,x_return_status  =>  l_return_status
367                                       ,p_col_id         =>  p_loan_id
368                                       ,p_col_name       =>  'LOAN_ID'
369                                       ,p_table_name     =>  'LNS_LOAN_HEADERS');
370 
371         if l_return_status <> FND_API.G_RET_STS_SUCCESS then
372             FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
373             FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_ID');
374             FND_MESSAGE.SET_TOKEN('VALUE', p_loan_id);
375             FND_MSG_PUB.ADD;
376             RAISE FND_API.G_EXC_ERROR;
377         end if;
378 
379         OPEN c_loan_adj(p_loan_id);
380         FETCH c_loan_adj INTO l_loan_amount_adj_id;
381         CLOSE c_loan_adj;
382 
383         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_loan_amount_adj_id = ' || l_loan_amount_adj_id);
384 
385 	-- if l_loan_amount_adj_id IS NULL then no adjustment fundsCheck happened till now and so generate the report
386 	-- for the Direct Loan Approved
387 
388 
389       ELSE  -- ELSE IF p_loan_amount_adj_id IS NOT NULL
390         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Validating input p_loan_amount_adj_id');
391 
392         lns_utility_pub.validate_any_id(p_api_version    =>  1.0
393                                       ,p_init_msg_list  =>  'F'
394                                       ,x_msg_count      =>  l_msg_count
395                                       ,x_msg_data       =>  l_msg_data
396                                       ,x_return_status  =>  l_return_status
397                                       ,p_col_id         =>  p_loan_amount_adj_id
398                                       ,p_col_name       =>  'LOAN_AMOUNT_ADJ_ID'
399                                       ,p_table_name     =>  'LNS_LOAN_AMOUNT_ADJS');
400 
401         if l_return_status <> FND_API.G_RET_STS_SUCCESS then
402             FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
403             FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_AMOUNT_ADJ_ID');
404             FND_MESSAGE.SET_TOKEN('VALUE', p_loan_amount_adj_id);
405             FND_MSG_PUB.ADD;
406             RAISE FND_API.G_EXC_ERROR;
407         end if;
408 
409         l_loan_amount_adj_id  :=  p_loan_amount_adj_id;
410 
411       END IF;   -- IF p_loan_amount_adj_id IS NULL
412 
413     END IF;
414 
415 
416 
417     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'opening c_event...');
418     open c_event(p_loan_id, l_loan_amount_adj_id);
419      LOOP
420 		fetch c_event into
421 				 	 l_event_id
422           				,l_distribution_id
423 					,l_ledger_id;
424       EXIT WHEN c_event%NOTFOUND;
425 
426         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
427         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_id = ' || l_distribution_id);
428         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_ledger_id = ' || l_ledger_id);
429 
430 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'inserting into psa table...');
431 		INSERT INTO PSA_BC_REPORT_EVENTS_GT
432 			(event_id
433 			,SOURCE_DISTRIBUTION_ID_NUM_1
434 			,SOURCE_DISTRIBUTION_ID_NUM_2)
435 		values(l_event_id
436 			,l_distribution_id
437 			,null);
438 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Done');
439     end loop;
440     close c_event;
441 
442     select PSA_BC_XML_REPORT_S.nextval
443     into l_sequence_id
444     from dual;
445 
446     SELECT count(*) INTO l_count
447     FROM PSA_BC_REPORT_EVENTS_GT;
448     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'rows found ' || l_count);
449 
450     IF l_count > 0 then
451 
452         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'calling PSA_BC_XML_REPORT_PUB.Create_BC_Transaction_Report...');
453         -- Call the XML Genertion Procedure
454         PSA_BC_XML_REPORT_PUB.Create_BC_Transaction_Report(l_errbuf
455                                                         ,l_retcode
456                                                         ,l_ledger_id
457                                                         ,l_application_id
458                                                         ,l_event_flag
459                                                         ,l_sequence_id);
460         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_errbuf = ' || l_errbuf);
461         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_retcode = ' || l_retcode);
462     END IF;
463 
464     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_sequence_id = ' || l_sequence_id);
465     return l_sequence_id;
466 
467 END GENERATE_BC_REPORT;
468 
469 /*=========================================================================
470 || PROCEDURE budgetary_control
471 ||
472 || DESCRIPTION
473 ||         this procedure does funds check / funds reserve
474 ||
475 ||
476 || PARAMETERS   p_loan_id => loan identifier
477 ||              p_budgetary_control_mode => 'C' Check ; 'R' Reserve
478 ||
479 || Return value:  x_budgetary_status_code
480 ||                    SUCCESS   = FUNDS CHECK / RESERVE SUCCESSFUL
481 ||                    PARTIAL   = AT LEAST ONE EVENT FAILED
482 ||                    FAIL      = FUNDS CHECK / RESERVE FAILED
483 ||                    XLA_ERROR = XLA SetUp ERROR
484 ||                    ADVISORY  = BUDGETARY WARNING
485 ||
486 || Source Tables: NA
487 ||
488 || Target Tables: NA
489 ||
490 || MODIFICATION HISTORY
491 || Date                  Author            Description of Changes
492 || 10-01-2005            raverma             Created
493  *=======================================================================*/
494 procedure budgetary_control(p_init_msg_list          in varchar2
495                             ,p_commit                 in varchar2
496                             ,p_loan_id                in number
497                             ,p_budgetary_control_mode in varchar2
498                             ,x_budgetary_status_code  out nocopy varchar2
499                             ,x_return_status          OUT NOCOPY VARCHAR2
500                             ,x_msg_count              OUT NOCOPY NUMBER
501                             ,x_msg_data               OUT NOCOPY VARCHAR2)
502 is
503     l_api_name              varchar2(50);
504     l_msg_count             NUMBER;
505     l_msg_data              VARCHAR2(2000);
506     l_return_Status         VARCHAR2(1);
507     l_status_code           varchar2(50);
508     l_packet_id             number;
509     l_event_id              number;
510     l_version               number;
511     l_budget_req_approval   varchar2(1);
512     l_funds_reserved_flag   varchar2(1);
513     l_gl_date               date;
514     l_budget_event_exists   number;
515     l_loan_header_rec       LNS_LOAN_HEADER_PUB.loan_header_rec_type;
516     l_disbursement_id       number;
517     x_event_id              number;
518 
519     cursor c_budget_req(p_loan_id number) is
520     select nvl(p.BDGT_REQ_FOR_APPR_FLAG, 'N')
521           ,nvl(h.funds_reserved_flag, 'N')
522           ,h.loan_start_date    -- fix for bug 16068385
523         from lns_loan_headers h,
524                 lns_loan_products p
525         where p.loan_product_id = h.product_id
526         and h.loan_id = p_loan_id;
527 
528     -- get budgetary control events only
529     cursor c_events(p_loan_id number) is
530     select event_id
531             from xla_transaction_entities xlee
532                 ,xla_events xle
533         where xle.application_id = 206
534         and xle.entity_id = xlee.entity_id
535             and xlee.source_id_int_1 = p_loan_id
536             and xle.budgetary_control_flag = 'Y'
537             and xle.event_type_code = 'DIRECT_LOAN_APPROVED'
538             and xle.process_status_code <> 'P'
539         order by event_id desc;
540 
541     cursor c_disbursements(p_loan_id number) is
542     select disb_header_id
543       from lns_disb_headers
544      where loan_id = p_loan_id
545        and disbursement_number = 1;
546 
547 		cursor c_obj_vers(p_loan_id number) is
548 		select object_version_number
549 			from lns_loan_headers
550 		 where loan_id = p_loan_id;
551 
552     cursor c_budget_event(p_loan_id number) is
553     select count(1)
554       from xla_transaction_entities xlee
555           ,xla_events xle
556       where xle.application_id = 206
557         and xle.entity_id = xlee.entity_id
558         and xlee.source_id_int_1 = p_loan_id
559        -- and xlee.source_id_int_2 = p_disb_header_id
560         and xle.budgetary_control_flag = 'Y';
561 
562 begin
563 
564     SAVEPOINT budgetary_control_pvt;
565     l_api_name := 'budgetary_control';
566     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
567     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = '  || p_loan_id);
568     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_budgetary_control_mode = ' || p_budgetary_control_mode);
569 
570     -- Initialize message list IF p_init_msg_list is set to TRUE.
571     IF FND_API.to_Boolean( p_init_msg_list ) THEN
572         FND_MSG_PUB.initialize;
573     END IF;
574 
575     -- Initialize API return status to SUCCESS
576     x_return_status         := FND_API.G_RET_STS_SUCCESS;
577 
578     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'fetching l_disbusement_id ');
579     open c_disbursements(p_loan_id);
580     fetch c_disbursements into l_disbursement_id;
581     close c_disbursements;
582     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_disbusement_id = ' || l_disbursement_id);
583 
584     -- Bug#6711479 We can't check funds without valid disbursement
585     IF (l_disbursement_id IS NULL) THEN
586         FND_MESSAGE.SET_NAME('LNS', 'LNS_CHK_FUND_DISB_INVALID');
587         FND_MSG_PUB.ADD;
588         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
589         FND_MESSAGE.SET_NAME('LNS', 'LNS_CREATE_DISB_SCHED');
590         FND_MSG_PUB.ADD;
591         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
592         RAISE FND_API.G_EXC_ERROR;
593     END IF;
594 
595     if ((lns_utility_pub.IS_FED_FIN_ENABLED = 'Y' OR lns_utility_pub.IS_ENCUM_FIN_ENABLED = 'Y') AND l_disbursement_id IS NOT NULL) then
596 
597         -- check if budget event exists
598         -- find if budgetary event already exists, if not, create the event
599         open c_budget_event(p_loan_id);
600         fetch c_budget_event into l_budget_event_exists;
601         close c_budget_event;
602         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_budget_event_exists = ' || l_budget_event_exists);
603 
604         open c_budget_req(p_loan_id);
605         fetch c_budget_req into l_budget_req_approval, l_funds_reserved_flag, l_gl_date;
606         close c_budget_req;
607         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_budget_req_approval = '  || l_budget_req_approval);
608         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_funds_reserved_flag = '  || l_funds_reserved_flag);
609 
610         if l_budget_event_exists = 0 then
611             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_XLA_EVENTS.create_event...');
612 
613             LNS_XLA_EVENTS.create_event(p_loan_id         => p_loan_id
614                                     ,p_disb_header_id  => -1
615                                     ,p_loan_amount_adj_id => -1
616                                     ,p_event_type_code => 'DIRECT_LOAN_APPROVED'
617                                     ,p_event_date      => l_gl_date
618                                     ,p_event_status    => 'U'
619                                     ,p_init_msg_list   => fnd_api.g_false
620                                     ,p_commit          => fnd_api.g_false
621                                     ,p_bc_flag         => 'Y'
622                                     ,x_event_id        => x_event_id
623                                     ,x_return_status   => x_return_status
624                                     ,x_msg_count       => x_msg_count
625                                     ,x_msg_data        => x_msg_data);
626             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'x_return_status = ' || x_return_status);
627             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'x_event_id ' || x_event_id);
628 
629             IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
630                 FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCOUNTING_EVENT_ERROR');
631                 FND_MSG_PUB.ADD;
632                 logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
633                 RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
634             END IF;
635 
636 	    -- stamp the eventID onto the lns_distributions table
637             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'stamping eventID on lns_distributions');
638 
639             update lns_distributions
640             set event_id = x_event_id
641                 ,last_update_date = sysdate
642             where distribution_type = 'ORIGINATION'
643             and loan_id           = p_loan_id
644           --  and loan_amount_adj_id IS NULL;
645 	          and activity = 'LNS_APPROVAL';
646 
647             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updated event_id succesfully for '||SQL%ROWCOUNT||' rows');
648 
649         end if; -- budget event already created
650 
651         -- now process the event
652         if l_funds_reserved_flag <> 'Y' then
653             --and p_budgetary_control_mode = 'R' then
654             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'getting events');
655 
656             open c_events(p_loan_id);
657         --    LOOP
658             fetch c_events into l_event_id;
659          --       EXIT WHEN c_events%NOTFOUND;
660             IF l_event_id IS NOT NULL THEN
661 
662                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
663 
664 		-- Bug#9328437, First time, when we do fundsCheck, the event_id creates and updates in lns_distributions table.
665 		-- However if we do fundsCheck/fundsReserver later, existed distribtuions are deleted and again
666 		-- defaulted, which has event_id as NULL. So, update the event_id if it is already created whose event_id is NULL
667 		        logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'stamping eventID on lns_distributions whose eventID is NULL');
668             	update lns_distributions
669             	set event_id = l_event_id
670                 	,last_update_date = sysdate
671                 where distribution_type = 'ORIGINATION'
672                 and event_id IS NULL
673                 and loan_id  = p_loan_id;
674 
675 		        logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updated event_id succesfully for '||SQL%ROWCOUNT||' rows');
676                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'inserting into  PSA_BC_XLA_EVENTS_GT ');
677                 insert
678                 into PSA_BC_XLA_EVENTS_GT (event_id, result_code)
679                 values (l_event_id, 'FAIL');
680 
681                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling PSA_BC_XLA_PUB.Budgetary_Control  '  || l_event_id);
682                 PSA_BC_XLA_PUB.Budgetary_Control(p_api_version      => 1.0
683                                                 ,p_init_msg_list    => FND_API.G_FALSE
684                                                 ,x_return_status    => l_return_status
685                                                 ,x_msg_count        => l_msg_count
686                                                 ,x_msg_data         => l_msg_data
687                                                 ,p_application_id   => 206
688                                                 ,p_bc_mode          => p_budgetary_control_mode
689                                                 ,p_override_flag    => null
690                                                 ,p_user_id          => null
691                                                 ,p_user_resp_id     => null
692                                                 ,x_status_code      => l_status_code
693                                                 ,x_packet_ID        => l_packet_id);
694         --    end loop;
695 	        END IF;
696             close c_events;
697 
698             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || '  BC status is = ' || l_return_status);
699             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || '  l_status_code = ' || l_status_code);
700             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || '  l_packet_id = ' || l_packet_id);
701 
702             if (l_return_status <> 'S' ) then
703 
704                 l_return_status         := FND_API.G_RET_STS_ERROR;
705                 FND_MESSAGE.SET_NAME('LNS', 'LNS_API_OTHERS_EXCEP');
706                 FND_MESSAGE.SET_TOKEN('ERROR' ,'Call to PSA_BC_XLA_PUB.Budgetary_Control failed with Status Code = ' || l_status_code);
707                 FND_MSG_PUB.ADD;
708                 logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
709                 RAISE FND_API.G_EXC_ERROR;
710 
711             else
712                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_budget_req_approval = '  || l_budget_req_approval);
713 
714                 if ( l_budget_req_approval = 'N' and p_budgetary_control_mode = 'R'
715                     and (l_status_code = 'FAIL' or l_status_code = 'PARTIAL' or l_status_code = 'XLA_ERROR')) then
716 
717                     x_budgetary_status_code  := l_status_code;
718                     x_return_status := l_return_status;
719 
720                     /*
721                     FND_MESSAGE.SET_NAME('LNS', 'LNS_APPROVAL_NO_BUDGET');
722                         FND_MSG_PUB.ADD_DETAIL(p_message_type => FND_MSG_PUB.G_WARNING_MSG );
723                         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
724                     */
725 
726                     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, ' BudgetReserve is not mandatory for LoanApproval, so returning to invoked method');
727 
728                     FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
729 
730                     return;
731 
732                 end if;
733 
734 /*
735                 if l_status_code NOT IN ('SUCCESS','ADVISORY') then
736                     IF  (l_status_code = 'PARTIAL') THEN
737                         FND_MESSAGE.SET_NAME('LNS', 'LNS_FUND_CHK_PARTIAL');
738                         FND_MSG_PUB.ADD;
739                         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
740                         RAISE FND_API.G_EXC_ERROR;
741                     ELSE
742                         FND_MESSAGE.SET_NAME('LNS', 'LNS_API_OTHERS_EXCEP');
743                         FND_MESSAGE.SET_TOKEN('ERROR' ,'Call to PSA_BC_XLA_PUB.Budgetary_Control failed with Status Code = ' || l_status_code);
744                         FND_MSG_PUB.ADD;
745                         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
746                         RAISE FND_API.G_EXC_ERROR;
747                     END IF;
748                 end if;
749 */
750                 if p_budgetary_control_mode = 'R' then
751                     if (l_status_code = 'ADVISORY' or l_status_code = 'SUCCESS') then
752                         l_loan_header_rec.FUNDS_RESERVED_FLAG := 'Y';
753                     else
754                         FND_MESSAGE.SET_NAME('LNS', 'LNS_FUND_RSRV_FAILED');
755                         FND_MSG_PUB.ADD;
756                         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
757                     end if;
758                 end if;
759 
760                 open c_obj_vers(p_loan_id);
761                 fetch c_obj_vers into l_version;
762                 close c_obj_vers;
763 
764                 l_loan_header_rec.loan_id             := p_loan_id;
765                 l_loan_header_rec.FUNDS_CHECK_DATE    := sysdate;
766                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || ' - updating loan');
767                 LNS_LOAN_HEADER_PUB.UPDATE_LOAN(P_OBJECT_VERSION_NUMBER => l_version
768                                             ,P_LOAN_HEADER_REC       => l_loan_header_rec
769                                             ,P_INIT_MSG_LIST         => FND_API.G_FALSE
770                                             ,X_RETURN_STATUS         => l_return_status
771                                             ,X_MSG_COUNT             => l_msg_count
772                                             ,X_MSG_DATA              => l_msg_data);
773                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'update loan status = ' || l_return_status);
774 
775                 if l_return_status <> 'S' then
776                     FND_MESSAGE.SET_NAME('LNS', 'LNS_UPD_LOAN_FAIL');
777                     FND_MSG_PUB.ADD;
778                     logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
779                     RAISE FND_API.G_EXC_ERROR;
780                 end if;
781 
782             end if; -- BC_API.RETURN_STATUS
783 
784         end if; -- l_funds_reserved_flag
785         x_budgetary_status_code  := l_status_code;
786         x_return_status          := l_return_status;
787 
788         IF (l_return_status = 'S' AND FND_API.to_Boolean(p_commit))
789         THEN
790             COMMIT WORK;
791         END IF;
792 
793  	end if;  -- no budgetary control-- end if (lns_utility_pub.IS_FED_FIN_ENABLED = 'Y' AND l_disbursement_id IS NOT NULL) then
794 
795     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
796 
797 EXCEPTION
798 
799     WHEN FND_API.G_EXC_ERROR THEN
800         ROLLBACK TO budgetary_control_pvt;
801         x_return_status := FND_API.G_RET_STS_ERROR;
802         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
803         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
804 
805     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
806         ROLLBACK TO budgetary_control_pvt;
807         x_return_status := FND_API.G_RET_STS_ERROR;
808         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
809         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
810 
811     WHEN OTHERS THEN
812         ROLLBACK TO budgetary_control_pvt;
813         x_return_status := FND_API.G_RET_STS_ERROR;
814         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
815         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
816 
817 end budgetary_control;
818 
819 
820 /*=========================================================================
821 || PRIVATE PROCEDURE do_insert_distributions
822 ||
823 || DESCRIPTION
824 ||         this procedure insert records into lns_distributions table
825 ||
826 || PARAMETERS   p_distributions_tbl => table -f distribution records
827 ||
828 || Return value:  NA
829 ||
830 || Source Tables:
831 ||
832 || Target Tables: LNS_DISTRIBUTIONS
833 ||
834 || KNOWN ISSUES
835 ||
836 || NOTES
837 ||
838 || MODIFICATION HISTORY
839 || Date                  Author            Description of Changes
840 || 04-20-2005            raverma             Created
841  *=======================================================================*/
842 procedure do_insert_distributions(p_distributions_tbl in lns_distributions_pub.distribution_tbl
843                                  ,p_loan_id           in number)
844 
845 is
846    l_total_distributions  number;
847    l_api_name             varchar2(25);
848 begin
849     l_api_name  := 'do_insert_distributions';
850 
851     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
852     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'rows received  = ' || p_distributions_tbl.count);
853 
854      l_total_distributions := p_distributions_tbl.count;
855 
856      if l_total_distributions > 0 then
857 
858          for k in 1..l_total_distributions
859          loop
860             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Inserting row : ' || k);
861             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'LINE_TYPE  = ' || p_distributions_tbl(k).line_type);
862             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'ACC_NAME  = ' || p_distributions_tbl(k).account_name);
863             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'CC_ID  = ' || p_distributions_tbl(k).code_combination_id);
864             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'ACC_TYPE  = ' || p_distributions_tbl(k).account_type);
865             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'PERCENT  = ' || p_distributions_tbl(k).distribution_percent);
866             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'AMOUNT  = ' || p_distributions_tbl(k).distribution_amount);
867             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'DIST_TYPE  = ' || p_distributions_tbl(k).distribution_type);
868 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'DISB_HEADER_ID  = ' || p_distributions_tbl(k).disb_header_id);
869 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'LOAN_AMOUNT_ADJ_ID  = ' || p_distributions_tbl(k).loan_amount_adj_id);
870 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'LOAN_LINE_ID  = ' || p_distributions_tbl(k).loan_line_id);
871 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'ACTIVITY  = ' || p_distributions_tbl(k).activity);
872 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'ACCRUAL_PERIOD  = ' || p_distributions_tbl(k).accrual_period);
873 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'ACCRUAL_DATE  = ' || p_distributions_tbl(k).accrual_date);
874 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'PROJECT_ID  = ' || p_distributions_tbl(k).project_id);
875       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'AWARD_ID  = ' || p_distributions_tbl(k).award_id);
876 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'TASK_ID  = ' || p_distributions_tbl(k).task_id);
877 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'EXPENDITURE_TYPE  = ' || p_distributions_tbl(k).expenditure_type);
878 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'EXPENDITURE_DATE  = ' || p_distributions_tbl(k).EXPENDITURE_ITEM_DATE);
879 
880 
881 
882             Insert into lns_distributions
883             (DISTRIBUTION_ID
884             ,LOAN_ID
885             ,LINE_TYPE
886             ,ACCOUNT_NAME
887             ,CODE_COMBINATION_ID
888             ,ACCOUNT_TYPE
889             ,DISTRIBUTION_PERCENT
890             ,DISTRIBUTION_AMOUNT
891             ,DISTRIBUTION_TYPE
892             ,EVENT_ID
893             ,CREATION_DATE
894             ,CREATED_BY
895             ,LAST_UPDATE_DATE
896             ,LAST_UPDATED_BY
897             ,OBJECT_VERSION_NUMBER
898             ,DISB_HEADER_ID
899             ,LOAN_AMOUNT_ADJ_ID
900             ,LOAN_LINE_ID
901 	    ,ACTIVITY
902 	    ,ACCRUAL_PERIOD
903 	    ,ACCRUAL_DATE
904 	    ,ACCRUAL_COMPLETED_FLAG
905       ,PROJECT_ID
906       ,AWARD_ID
907       ,TASK_ID
908       ,EXPENDITURE_TYPE
909       ,EXPENDITURE_ITEM_DATE)
910             values
911             (LNS_DISTRIBUTIONS_S.nextval
912             ,p_loan_id
913             ,p_distributions_tbl(k).line_type
914             ,p_distributions_tbl(k).account_name
915             ,p_distributions_tbl(k).code_combination_id
916             ,p_distributions_tbl(k).account_type
917             ,p_distributions_tbl(k).distribution_percent
918             ,p_distributions_tbl(k).distribution_amount
919             ,p_distributions_tbl(k).distribution_type
920             ,p_distributions_tbl(k).event_id
921             ,lns_utility_pub.creation_date
922             ,lns_utility_pub.created_by
923             ,lns_utility_pub.last_update_date
924             ,lns_utility_pub.last_updated_by
925             ,1
926             ,p_distributions_tbl(k).disb_header_id
927             ,p_distributions_tbl(k).loan_amount_adj_id
928             ,p_distributions_tbl(k).loan_line_id
929 	    ,p_distributions_tbl(k).activity
930 	    ,p_distributions_tbl(k).accrual_period
931 	    ,p_distributions_tbl(k).accrual_date
932 	    ,p_distributions_tbl(k).accrual_completed_flag
933         ,p_distributions_tbl(k).project_id
934       ,p_distributions_tbl(k).award_id
935 	    ,p_distributions_tbl(k).task_id
936 	    ,p_distributions_tbl(k).expenditure_type
937 	    ,p_distributions_tbl(k).EXPENDITURE_ITEM_DATE);
938 
939             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, '****************************************** ');
940          end loop;
941 
942      else
943 
944        FND_MESSAGE.SET_NAME('LNS', 'LNS_DEFAULT_DIST_NOT_FOUND');
945        FND_MSG_PUB.ADD;
946        logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
947        RAISE FND_API.G_EXC_ERROR;
948 
949      end if;
950     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
951 
952 end do_insert_distributions;
953 
954 /*=========================================================================
955 || PRIVATE PROCEDURE defaultDistributionsCatch
956 ||
957 || DESCRIPTION
958 ||      ths procedure is the "catchAll" logic for accounting set-up
959 ||      it will ensure that a valid distributions_tbl is built for
960 ||     INTEREST_INCOME, INTEREST_RECEIVABLE, and PRINCIPAL_RECEIVABLE
961 ||
962 ||  as well if the parameter p_include_loan_receivables = 'Y' then
963 ||  it will also pull
964 ||      LOAN_RECEIVABLE and LOAN_CLEARING
965 ||
966 || PSEUDO CODE/LOGIC
967 ||
968 || PARAMETERS p_include_loan_receivables 'Y' to include loan_receivable/clearing
969 ||                                       'X' to exclude loan_clearing
970 ||
971 || Return value: x_distribution_tbl           distribution table set to write to database
972 ||
973 || Source Tables: lns_default_distribs
974 ||
975 || Target Tables: NA
976 ||
977 || KNOWN ISSUES
978 ||
979 || NOTES
980 ||
981 ||
982 || MODIFICATION HISTORY
983 || Date                  Author            Description of Changes
984 || 02-18-2004            raverma             Created
985  *=======================================================================*/
986 procedure defaultDistributionsCatch(p_api_version                IN NUMBER
987                                    ,p_init_msg_list              IN VARCHAR2
988                                    ,p_commit                     IN VARCHAR2
989                                    ,p_loan_id                    IN NUMBER
990                                    ,p_disb_header_id             IN NUMBER
991                                    ,p_loan_amount_adj_id         IN NUMBER DEFAULT NULL
992                                    ,p_include_loan_receivables   IN VARCHAR2
993                                    ,p_distribution_type          IN VARCHAR2
994                                    ,x_distribution_tbl           OUT NOCOPY lns_distributions_pub.distribution_tbl
995                                    ,x_return_status              OUT NOCOPY VARCHAR2
996                                    ,x_msg_count                  OUT NOCOPY NUMBER
997                                    ,x_msg_data                   OUT NOCOPY VARCHAR2)
998 
999 is
1000 /*------------------------------------------------------------------------+
1001  | Local Variable Declarations and initializations                        |
1002  +-----------------------------------------------------------------------*/
1003     l_api_name               varchar2(50);
1004     l_msg_count              NUMBER;
1005     l_msg_data               VARCHAR2(2000);
1006     l_return_Status          VARCHAR2(1);
1007     l_class                  varchar2(30);
1008     l_loan_type_id           number;
1009     i                        number := 0;
1010     l_line_type              varchar2(30);
1011     l_account_name           varchar2(30);
1012     l_code_combination_id    number;
1013     l_account_type           varchar2(30);
1014     l_distribution_percent   number;
1015     l_distribution_type      varchar2(30);
1016     l_funded_amount          number;
1017     l_adj_reversal           varchar2(1);
1018     l_loan_receivables_count number;
1019     l_loan_payables_count    number;
1020     l_distributions          lns_distributions_pub.distribution_tbl;
1021     l_running_amount1        number;
1022     l_running_amount2        number;
1023     l_running_amount3        number;
1024     l_running_amount4        number;
1025     k                        number;
1026     n                        number;
1027     l                        number;
1028     m                        number;
1029     l_ledger_details         lns_distributions_pub.gl_ledger_details;
1030     Type refCur is ref cursor;
1031     sql_Cur                  refCur;
1032     vSqlCur                 varchar2(1000);
1033     vPLSQL                  VARCHAR2(1000);
1034    l_expenditure_type            pa_expenditure_types.expenditure_type%TYPE;
1035    l_expenditure_organization_id number;
1036    l_expenditure_item_date       date;
1037    l_project_id                  pa_projects_all.project_id%TYPE;
1038    l_task_id                     pa_tasks.task_id%TYPE;
1039    l_award_id	               gms_awards.award_id%TYPE;
1040 
1041 /*------------------------------------------------------------------------+
1042  | Cursor Declarations                                                    |
1043  +-----------------------------------------------------------------------*/
1044 		-- R12 for loan_types
1045     cursor c_loan_info(p_loan_id NUMBER)
1046     is
1047     select h.loan_class_code
1048           ,t.loan_type_id
1049         --  ,h.funded_amount
1050 	  ,h.requested_amount   -- Bug#9755933
1051       from lns_loan_headers_all h
1052 					,lns_loan_types t
1053      where h.loan_id = p_loan_id
1054 		   and h.loan_type_id = t.loan_type_id;
1055 
1056     cursor c_loan_info2(p_loan_id NUMBER, p_disb_header_id number)
1057     is
1058     select h.loan_class_code
1059           ,t.loan_type_id
1060           ,d.header_amount
1061       from lns_loan_headers_all h
1062 					,lns_loan_types t
1063 					,lns_disb_headers d
1064      where h.loan_id = p_loan_id
1065 		   and h.loan_type_id = t.loan_type_id
1066 			 and h.loan_id = d.loan_id
1067 			 and d.disb_header_id = p_disb_header_id;
1068 
1069     cursor c_loan_info3(c_loan_id NUMBER, c_loan_amount_adj_id number)
1070     is
1071     select h.loan_class_code
1072           ,t.loan_type_id
1073           ,ladj.adjustment_amount
1074       from lns_loan_headers_all h
1075 		,lns_loan_types t
1076 		,LNS_LOAN_AMOUNT_ADJS ladj
1077      where h.loan_id = p_loan_id
1078 	and h.loan_type_id = t.loan_type_id
1079 	and h.loan_id = ladj.loan_id
1080         and ladj.status = 'PENDING'
1081 	and ladj.loan_amount_adj_id = c_loan_amount_adj_id;
1082 
1083 
1084     cursor c_num_receivables(p_loan_class varchar2, p_loan_type_id number)
1085     is
1086     select count(1)
1087       from lns_default_distribs
1088      where loan_class = p_loan_class
1089        AND loan_type_id  = p_loan_type_id
1090        and account_name = 'LOAN_RECEIVABLE'
1091        and distribution_type = 'ORIGINATION'
1092        and account_type      = 'DR';
1093 
1094     cursor c_num_payables(p_loan_class varchar2, p_loan_type_id number)
1095     is
1096     select count(1)
1097       from lns_default_distribs
1098      where loan_class = p_loan_class
1099        AND loan_type_id  = p_loan_type_id
1100        and account_name = 'LOAN_PAYABLE'
1101        and distribution_type = 'FUNDING'
1102        and account_type      = 'DR';
1103 
1104 begin
1105      SAVEPOINT defaultDistributionsCatch;
1106      l_api_name := 'defaultDistributionsCatch';
1107      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
1108 
1109      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
1110      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_disb_header_id = ' || p_disb_header_id);
1111      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_amount_adj_id = ' || p_loan_amount_adj_id);
1112      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_include_loan_receivables = ' || p_include_loan_receivables);
1113      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_distribution_type = ' || p_distribution_type);
1114 
1115      -- Initialize message list IF p_init_msg_list is set to TRUE.
1116      IF FND_API.to_Boolean( p_init_msg_list ) THEN
1117          FND_MSG_PUB.initialize;
1118      END IF;
1119 
1120      -- Initialize API return status to SUCCESS
1121      x_return_status := FND_API.G_RET_STS_SUCCESS;
1122 
1123      n := 0;
1124      k := 0;
1125      l := 0;
1126      m := 0;
1127      l_running_amount1 := 0;
1128      l_running_amount2 := 0;
1129      l_running_amount3 := 0;
1130      l_running_amount4 := 0;
1131      l_ledger_details   := lns_distributions_pub.getLedgerDetails;
1132 
1133      -- get class and type for the loan
1134      l_adj_reversal := 'N';
1135      if p_loan_amount_adj_id is not null then
1136         OPEN c_loan_info3(p_loan_id, p_loan_amount_adj_id);
1137         FETCH c_loan_info3 INTO l_class, l_loan_type_id, l_funded_amount;
1138         close c_loan_info3;
1139         if l_funded_amount < 0 then
1140           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Before reversal, l_funded_amount = ' || l_funded_amount);
1141           l_adj_reversal  :=  'Y';
1142           l_funded_amount := -(l_funded_amount);
1143           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'After reversal, l_funded_amount = ' || l_funded_amount);
1144         end if;
1145      elsif p_disb_header_id is null then
1146         OPEN c_loan_info(p_loan_id);
1147         FETCH c_loan_info INTO l_class, l_loan_type_id, l_funded_amount;
1148         close c_loan_info;
1149      elsif p_disb_header_id is not null then
1150         OPEN c_loan_info2(p_loan_id, p_disb_header_id);
1151         FETCH c_loan_info2 INTO l_class, l_loan_type_id, l_funded_amount;
1152         close c_loan_info2;
1153      end if;
1154      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_class = ' || l_class);
1155      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_type_id = ' || l_loan_type_id);
1156      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_funded_amount = ' || l_funded_amount);
1157 
1158      open c_num_receivables(l_class, l_loan_type_id);
1159      fetch c_num_receivables into l_loan_receivables_count;
1160      close c_num_receivables;
1161      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_receivables_count = ' || l_loan_receivables_count);
1162 
1163      open c_num_payables(l_class, l_loan_type_id);
1164      fetch c_num_payables into l_loan_payables_count;
1165      close c_num_payables;
1166 
1167      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_payables_count = ' || l_loan_payables_count);
1168 
1169      -- now see if any default distributions exist for this loan
1170      -- 2-24-2005 raverma -- add loan_payable IF loan_class = DIRECT OR
1171      --                                             loan is not MFAR
1172      -- Bug#5295575 Modified the query to work for an organization instead
1173      -- of working for all organzations by replacing  lns_default_distribs_all
1174      -- with lns_default_distribs table
1175 
1176 
1177      Begin
1178          vPLSQL := 'SELECT d.line_type                 ' ||
1179                    '      ,d.account_name              ' ||
1180                    '      ,d.code_combination_id       ' ||
1181                    '      ,d.account_type              ' ||
1182                    '      ,d.distribution_percent      ' ||
1183                    '      ,d.distribution_type         ' ||
1184                    '      ,d.project_id                ' ||
1185                    '      ,d.award_id                  ' ||
1186                    '      ,d.task_id                   ' ||
1187                    '      ,d.expenditure_type          ' ||
1188                    '      ,d.expenditure_item_date     ' ||
1189                    'FROM lns_default_distribs  d       ' ||
1190                    'WHERE ((d.loan_class = :p_loan_class_code AND d.loan_type_id  = :p_loan_type_id) ) ' ||
1191                    '  AND account_name IN (''PRINCIPAL_RECEIVABLE'', ''INTEREST_RECEIVABLE'', ''INTEREST_INCOME'' ';
1192 
1193         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'include receivabvles ' || p_include_loan_receivables);
1194         -- these are only appropriate for class=DIRECT or loan <> MFAR
1195         if p_include_loan_receivables = 'Y' then
1196             vPLSQL := vPLSQL || ' ,''LOAN_RECEIVABLE'', ''LOAN_CLEARING'', ''LOAN_LIABILITY'', ''LOAN_PAYABLE'')';
1197         else
1198             vPLSQL := vPLSQL || ' )';
1199         end if;
1200 
1201         if p_distribution_type is not null then
1202 --            vPLSQL := vPLSQL || ' AND d.distribution_type = ' || '''' || p_distribution_type || '''';
1203 
1204             if p_distribution_type = 'ORIGINATION' then
1205                 vPLSQL := vPLSQL || ' AND d.distribution_type in (''ORIGINATION'',''FUNDING'')';
1206             else
1207                 vPLSQL := vPLSQL || ' AND d.distribution_type = ' || '''' || p_distribution_type || '''';
1208             end if;
1209 
1210         end if;
1211 
1212         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'sql: ' || vPLSQL);
1213 
1214         open sql_cur for
1215                 vPLSQL
1216             using l_class, l_loan_type_id;
1217         LOOP
1218             fetch sql_cur into  l_line_type
1219                             ,l_account_name
1220                             ,l_code_combination_id
1221                             ,l_account_type
1222                             ,l_distribution_percent
1223                             ,l_distribution_type
1224                             ,l_project_id
1225                             ,l_award_id
1226                             ,l_task_id
1227                             ,l_expenditure_type
1228                             ,l_expenditure_item_date;
1229             exit when sql_cur%NOTFOUND;
1230 
1231             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_adj_reversal = ' || l_adj_reversal);
1232 
1233 
1234             if (l_adj_reversal = 'Y' and l_distribution_type = 'ORIGINATION') then
1235               logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_type = ' || l_account_type);
1236               if l_account_type = 'DR' then
1237                 l_account_type := 'CR';
1238               elsif l_account_type = 'CR' then
1239                 l_account_type := 'DR';
1240               end if;
1241             end if;
1242 
1243             i := i + 1;
1244 
1245             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Record ' || i);
1246             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_line_type = ' || l_line_type);
1247             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_name = ' || l_account_name);
1248             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
1249             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_type = ' || l_account_type);
1250             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_percent = ' || l_distribution_percent);
1251             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_type = ' || l_distribution_type);
1252             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_project_id = ' || l_project_id);
1253             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_award_id = ' || l_award_id);
1254             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_task_id = ' || l_task_id);
1255             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_type = ' || l_expenditure_type);
1256             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_item_date = ' || l_expenditure_item_date);
1257 
1258 
1259 
1260             l_distributions(i).line_type              := l_line_type;
1261             l_distributions(i).account_name           := l_account_name;
1262             l_distributions(i).code_combination_id    := l_code_combination_id;
1263             l_distributions(i).account_type           := l_account_type;
1264             l_distributions(i).distribution_percent   := l_distribution_percent;
1265             l_distributions(i).distribution_type      := l_distribution_type;
1266             l_distributions(i).project_id             := l_project_id;
1267             l_distributions(i).award_id               := l_award_id;
1268             l_distributions(i).task_id                := l_task_id;
1269             l_distributions(i).EXPENDITURE_ITEM_DATE       := l_EXPENDITURE_ITEM_DATE;
1270             l_distributions(i).expenditure_type       := l_expenditure_type;
1271 
1272 
1273             if l_account_name = 'LOAN_RECEIVABLE' and l_distribution_type = 'ORIGINATION' then
1274 
1275                 k := k + 1;
1276                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan receivables line ' || k);
1277 
1278                 if k <> l_loan_receivables_count then
1279                     l_distributions(i).distribution_amount    := round(l_distribution_percent * l_funded_amount, l_ledger_details.currency_precision) / 100;
1280                     l_running_amount1 := l_running_amount1 + l_distributions(i).distribution_amount;
1281                 else
1282                     l_distributions(i).distribution_amount    := l_funded_amount - l_running_amount1;
1283                 end if;
1284 
1285                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions(i).distribution_amount = ' || l_distributions(i).distribution_amount);
1286                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_running_amount1 = ' || l_running_amount1);
1287 
1288             end if;
1289 
1290             if (l_account_name = 'LOAN_CLEARING' or l_account_name = 'LOAN_PAYABLE') and l_distribution_type = 'ORIGINATION' then
1291 
1292                 n := n + 1;
1293                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan clearing line ' || n);
1294 
1295                 if n <> l_loan_receivables_count then
1296                     l_distributions(i).distribution_amount    := round(l_distribution_percent * l_funded_amount, l_ledger_details.currency_precision) / 100;
1297                     l_running_amount2 := l_running_amount2 + l_distributions(i).distribution_amount;
1298                 else
1299                     l_distributions(i).distribution_amount    := l_funded_amount - l_running_amount2;
1300                 end if;
1301 
1302                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions(i).distribution_amount = ' || l_distributions(i).distribution_amount);
1303                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_running_amount2 = ' || l_running_amount2);
1304 
1305             end if;
1306 
1307             if (l_account_name = 'LOAN_PAYABLE' and l_distribution_type = 'FUNDING') then
1308 
1309                 l := l + 1;
1310                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan payable funding line ' || l);
1311 
1312                 if l <> l_loan_payables_count then
1313                     l_distributions(i).distribution_amount    := round(l_distribution_percent * l_funded_amount, l_ledger_details.currency_precision) / 100;
1314                     l_running_amount3 := l_running_amount3 + l_distributions(i).distribution_amount;
1315                 else
1316                     l_distributions(i).distribution_amount    := l_funded_amount - l_running_amount3;
1317                 end if;
1318 
1319                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions(i).distribution_amount = ' || l_distributions(i).distribution_amount);
1320                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_running_amount3 = ' || l_running_amount3);
1321 
1322             end if;
1323 
1324 	        if (l_account_name = 'LOAN_LIABILITY' and l_distribution_type = 'FUNDING') then
1325 	        --if (l_line_type = 'PRIN' and l_distribution_type = 'FUNDING') then
1326                  logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - loan liability funding line found');
1327                  l_distributions(i).distribution_amount    := l_funded_amount;
1328             end if;
1329 
1330         end loop;
1331         close sql_cur;
1332 
1333      exception
1334        when no_data_found then
1335            FND_MESSAGE.SET_NAME('LNS', 'LNS_DEFAULT_DIST_NOT_FOUND');
1336            FND_MSG_PUB.ADD;
1337            logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
1338            RAISE FND_API.G_EXC_ERROR;
1339      End; -- c_default_info cursor
1340 
1341      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'distribs2 count is ' || l_distributions.count);
1342      x_distribution_tbl := l_distributions;
1343 
1344      IF FND_API.to_Boolean(p_commit)
1345      THEN
1346          COMMIT WORK;
1347      END IF;
1348 
1349      FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
1350 
1351      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
1352 
1353 EXCEPTION
1354     WHEN FND_API.G_EXC_ERROR THEN
1355         ROLLBACK TO defaultDistributionsCatch;
1356         x_return_status := FND_API.G_RET_STS_ERROR;
1357         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
1358         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
1359 
1360     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1361         ROLLBACK TO defaultDistributionsCatch;
1362         x_return_status := FND_API.G_RET_STS_ERROR;
1363         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
1364         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
1365 
1366     WHEN OTHERS THEN
1367         ROLLBACK TO defaultDistributionsCatch;
1368         x_return_status := FND_API.G_RET_STS_ERROR;
1369         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
1370         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
1371 
1372 end defaultDistributionsCatch;
1373 
1374 
1375 
1376 /*=========================================================================
1377 || PUBLIC PROCEDURE create_event
1378 ||
1379 || DESCRIPTION
1380 || Overview: will write to xla_events table and update lns_distributions
1381 ||           this can handle a set of accounting event records
1382 ||
1383 || PSEUDO CODE/LOGIC
1384 ||
1385 || PARAMETERS
1386 || Parameter: p_acc_event_tbl => table of accounting records
1387 ||           ,p_event_type_code    => seeded code for loans "APPROVED", "DISBURSEMENT_FUNDED",
1388 ||						"FUTURE_DISBURSEMENT_CANCELLED", "DIRECT_LOAN_ADJ_APPROVED",
1389 ||						"DIRECT_LOAN_ADJ_REVERSED", "APPROVED", "ERS_LOAN_ADD_REC_APPROVED"
1390 ||           ,p_event_date         => most likely GL_DATE
1391 ||           ,p_event_status       => event Status
1392 ||             CONSTANT  = 'U';   -- event status:unprocessed
1393 ||             CONSTANT  = 'I';   -- event status:incomplete
1394 ||             CONSTANT  = 'N';   -- event status:noaction
1395 ||
1396 || Return value:
1397 ||               standard
1398 || KNOWN ISSUES
1399 ||
1400 || NOTES
1401 ||
1402 || MODIFICATION HISTORY
1403 || Date                  Author            Description of Changes
1404 || 8/3/2005             raverma           Created
1405 ||
1406  *=======================================================================*/
1407 procedure create_event(p_acc_event_tbl      in  LNS_DISTRIBUTIONS_PUB.acc_event_tbl
1408                       ,p_init_msg_list      in  varchar2
1409                       ,p_commit             in  varchar2
1410                       ,x_return_status      out nocopy varchar2
1411                       ,x_msg_count          out nocopy number
1412                       ,x_msg_data           out nocopy varchar2)
1413 
1414 is
1415     l_api_name            varchar2(25);
1416     l_loan_class			     varchar2(30);
1417     l_loan_type_id        number;
1418     l_distributions       LNS_DISTRIBUTIONS_PUB.distribution_tbl;
1419     l_msg_count           NUMBER;
1420     l_msg_data            VARCHAR2(2000);
1421     l_return_Status       VARCHAR2(1);
1422     l_event_id            number;
1423     l_activity		VARCHAR2(30);
1424     l_event_type_code	VARCHAR2(30);
1425 
1426     cursor c_loan_info(p_loan_id number) is
1427     select h.loan_class_code
1428                     ,h.loan_type_id
1429         from lns_loan_headers_all h
1430     where h.loan_id = p_loan_id;
1431 
1432 begin
1433     l_api_name           := 'create_event';
1434     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
1435     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_acc_event_tbl count = ' || p_acc_event_tbl.count);
1436 
1437     -- Standard Start of API savepoint
1438     SAVEPOINT create_event;
1439 
1440     -- Initialize message list IF p_init_msg_list is set to TRUE.
1441     IF FND_API.to_Boolean(p_init_msg_list) THEN
1442         FND_MSG_PUB.initialize;
1443     END IF;
1444 
1445     -- Initialize API return status to SUCCESS
1446     x_return_status := FND_API.G_RET_STS_SUCCESS;
1447 
1448     -- ---------------------------------------------------------------------
1449     -- Api body
1450     -- ---------------------------------------------------------------------
1451     for k in 1..p_acc_event_tbl.count loop
1452 
1453         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan_id = ' || p_acc_event_tbl(k).loan_id);
1454         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_event_type_code = ' || p_acc_event_tbl(k).event_type_code);
1455         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_acc_event_tbl('||k||').disb_header_id = ' || p_acc_event_tbl(k).disb_header_id);
1456         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_acc_event_tbl('||k||').loan_amount_adj_id = ' || p_acc_event_tbl(k).loan_amount_adj_id);
1457 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_acc_event_tbl('||k||').loan_line_id = ' || p_acc_event_tbl(k).loan_line_id);
1458         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_event_date = ' || p_acc_event_tbl(k).event_date);
1459         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_event_status = ' || p_acc_event_tbl(k).event_status);
1460         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_bc_flag = ' || p_acc_event_tbl(k).budgetary_control_flag);
1461 
1462 
1463         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_XLA_EVENTS.create_event...');
1464         LNS_XLA_EVENTS.create_event(p_loan_id         => p_acc_event_tbl(k).loan_id
1465                                     ,p_disb_header_id  => p_acc_event_tbl(k).disb_header_id
1466                                     ,p_loan_amount_adj_id => p_acc_event_tbl(k).loan_amount_adj_id
1467 				                    ,p_loan_line_id 	=> p_acc_event_tbl(k).loan_line_id
1468                                     ,p_event_type_code => p_acc_event_tbl(k).event_type_code
1469                                     ,p_event_date      => p_acc_event_tbl(k).event_date
1470                                     ,p_event_status    => p_acc_event_tbl(k).event_status
1471                                     ,p_bc_flag         => p_acc_event_tbl(k).budgetary_control_flag
1472                                     ,p_init_msg_list   => p_init_msg_list
1473                                     ,p_commit          => p_commit
1474                                     ,x_event_id        => l_event_id
1475                                     ,x_return_status   => x_return_status
1476                                     ,x_msg_count       => x_msg_count
1477                                     ,x_msg_data        => x_msg_data);
1478         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
1479         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'x_return_status = ' || x_return_status);
1480 
1481         IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
1482             FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCOUNTING_EVENT_ERROR');
1483             FND_MSG_PUB.ADD;
1484             logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
1485             RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
1486         ELSE
1487             -- update the distributions table with proper event_id for valid disb_header_id/loan_amount_adj_id
1488             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updating lns_distributions...');
1489 
1490 	    l_event_type_code := p_acc_event_tbl(k).event_type_code;
1491 
1492 	    IF (l_event_type_code = 'DIRECT_LOAN_APPROVED' OR  l_event_type_code = 'APPROVED') THEN
1493 	    	l_activity := 'LNS_APPROVAL';
1494 	    ELSIF  l_event_type_code = 'DISBURSEMENT_FUNDED' THEN
1495 		l_activity := 'DISBURSEMENT';
1496 	    ELSIF  l_event_type_code = 'FUTURE_DISBURSEMENT_CANCELLED' THEN
1497 		l_activity := 'LNS_REMAIN_DISB_CANCEL';
1498 	    ELSIF  l_event_type_code = 'DIRECT_LOAN_ADJ_APPROVED' THEN
1499 		l_activity := 'LOAN_AMOUNT_ADJUSTMENT';
1500 	    ELSIF  l_event_type_code = 'ERS_LOAN_ADD_REC_APPROVED' THEN
1501 		l_activity := 'ERS_ADD_REC';
1502 	    END IF;
1503 
1504 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_activity is '||l_activity);
1505 
1506             update lns_distributions
1507   	    set event_id = l_event_id
1508 		,last_update_date = sysdate
1509 		,object_version_number = object_version_number + 1
1510             where loan_id = p_acc_event_tbl(k).loan_id
1511 		and activity = l_activity
1512 		and nvl(disb_header_id, -1) = nvl(p_acc_event_tbl(k).disb_header_id,-1)
1513 	   	and nvl(loan_amount_adj_id, -1) = nvl(p_acc_event_tbl(k).loan_amount_adj_id, -1);
1514 
1515             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'In LNS_DISTRIBUTIONS_PUB.createEvent(), updation of event_id is done for '||SQL%ROWCOUNT||' rows');
1516 
1517         end if;
1518 
1519 	end loop;
1520     -- ---------------------------------------------------------------------
1521     -- End of API body
1522     -- ---------------------------------------------------------------------
1523     FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
1524 
1525     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
1526 
1527 EXCEPTION
1528     WHEN FND_API.G_EXC_ERROR THEN
1529             ROLLBACK TO create_event;
1530             x_return_status := FND_API.G_RET_STS_ERROR;
1531             x_msg_count := l_msg_count;
1532             x_msg_data  := l_msg_data;
1533             FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1534             logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
1535 
1536     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1537             ROLLBACK TO create_event;
1538             x_return_status := FND_API.G_RET_STS_ERROR;
1539             x_msg_count := l_msg_count;
1540             x_msg_data  := l_msg_data;
1541             FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1542             logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
1543 
1544     WHEN OTHERS THEN
1545             ROLLBACK TO create_event;
1546             x_return_status := FND_API.G_RET_STS_ERROR;
1547             x_msg_count := l_msg_count;
1548             x_msg_data  := l_msg_data;
1549             FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1550             logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
1551 
1552 end create_event;
1553 
1554 
1555 
1556 
1557 /*=========================================================================
1558 || PRIVATE function getNaturalSwapAccount
1559 ||
1560 || DESCRIPTION
1561 ||         this procedure will return the swap the segment from loans setup
1562 ||
1563 || PSEUDO CODE/LOGIC
1564 ||
1565 || PARAMETERS   p_loan_id = loan_id
1566 ||
1567 || Return value:  new swap segment value
1568 ||
1569 || Source Tables: lns_system_options
1570 ||
1571 || Target Tables: NA
1572 ||
1573 || KNOWN ISSUES
1574 ||
1575 || NOTES
1576 ||
1577 || MODIFICATION HISTORY
1578 || Date                  Author            Description of Changes
1579 || 04-19-2005            raverma             Created
1580  *=======================================================================*/
1581 function getNaturalSwapAccount(p_loan_id number) return varchar2
1582 is
1583 
1584     -- this is cursor is for reading configuration for multi-fund swap natural account
1585     cursor c_mfar_nat_acct (p_loan_id number) is
1586     select MFAR_NATURAL_ACCOUNT_REC
1587     from lns_default_distribs_all d
1588         ,lns_loan_headers_all h
1589     where account_name = 'MFAR_FUND_ACCOUNT_CHANGE'
1590       and h.loan_id = p_loan_id
1591       and h.loan_class_code = d.loan_class
1592       and h.loan_type_id  = d.loan_type_id
1593       and h.org_id = d.org_id;
1594 
1595     l_segment_value   varchar2(60);
1596 
1597 begin
1598 
1599     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Opening c_mfar_nat_acct...');
1600     open c_mfar_nat_acct(p_loan_id);
1601     fetch c_mfar_nat_acct into l_segment_value;
1602     close c_mfar_nat_acct;
1603     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Done');
1604     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_segment_value = ' || l_segment_value);
1605 
1606 	return l_segment_value;
1607 
1608 Exception
1609     When others then
1610         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, 'failed to retrieve replacement natural account');
1611         FND_MESSAGE.SET_NAME('LNS', 'LNS_MFAR_CONFIGURATION_ERROR');
1612         FND_MSG_PUB.ADD;
1613         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
1614         RAISE FND_API.G_EXC_ERROR;
1615 
1616 end getNaturalSwapAccount;
1617 
1618 /*=========================================================================
1619 || PRIVATE PROCEDURE swap_code_combination
1620 ||
1621 || DESCRIPTION
1622 ||         this procedure will swap the segment at given segment number
1623 ||         with given value and create and return the new cc_id
1624 ||
1625 || PSEUDO CODE/LOGIC
1626 ||
1627 || PARAMETERS   p_chart_of_accounts_id => chart of accounts id
1628 ||              p_original_cc_id       => original cc_id
1629 ||              p_swap_segment_number  => segment number to swap
1630 ||              p_swap_segment_value   => segment value to swap with
1631 ||
1632 || Return value:  new code_combination_id
1633 ||
1634 || Source Tables:
1635 ||
1636 || Target Tables: NA
1637 ||
1638 || KNOWN ISSUES
1639 ||
1640 || NOTES
1641 ||
1642 || MODIFICATION HISTORY
1643 || Date                  Author            Description of Changes
1644 || 04-19-2005            raverma             Created
1645  *=======================================================================*/
1646 function swap_code_combination(p_chart_of_accounts_id in number
1647                               ,p_original_cc_id       in number
1648                               ,p_swap_segment_number  in number
1649                               ,p_swap_segment_value   in varchar
1650                               ) return number
1651 
1652 is
1653     l_original_segments   FND_FLEX_EXT.SEGMENTARRAY;
1654     l_new_segments        FND_FLEX_EXT.SEGMENTARRAY;
1655     l_num_segments        number;
1656     l_api_name            varchar2(50);
1657     l_new_cc_id           number;
1658 
1659 begin
1660     l_api_name  := 'swap_code_combination';
1661     l_new_cc_id := -1;
1662 
1663     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
1664     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_chart_of_accounts_id  = ' || p_chart_of_accounts_id);
1665     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_original_cc_id  = ' || p_original_cc_id);
1666     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_swap_segment_number  = ' || p_swap_segment_number);
1667     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_swap_segment_value  = ' || p_swap_segment_value);
1668 
1669     -- build the original code combination segments into array
1670     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling FND_FLEX_EXT.GET_SEGMENTS...');
1671     IF (NOT FND_FLEX_EXT.GET_SEGMENTS('SQLGL'
1672                                      ,'GL#'
1673                                      ,p_chart_of_accounts_id
1674                                      ,p_original_cc_id
1675                                      ,l_num_segments
1676                                      ,l_original_segments))
1677     Then
1678         FND_MESSAGE.SET_NAME('LNS', 'LNS_ERR_BUILDING_SEGMENTS');
1679         FND_MSG_PUB.ADD;
1680         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
1681         RAISE FND_API.G_EXC_ERROR;
1682     END IF;
1683 
1684     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Original segments:');
1685     for n in 1..l_num_segments loop
1686         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'seg#' || n || ' = ' || l_original_segments(n));
1687     end loop;
1688 
1689     -- get the replacement accounts from lns_default_distribs
1690     FOR n IN 1..l_num_segments LOOP
1691         IF (n = p_swap_segment_number) THEN
1692             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'found the account to swap = ' || l_original_segments(n));
1693             l_new_segments(n) := p_swap_segment_value;
1694         else
1695             l_new_segments(n) := l_original_segments(n);
1696         END IF;
1697     END LOOP;
1698 
1699     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'New segments:');
1700     for n in 1..l_num_segments loop
1701         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'seg#' || n || ' = ' || l_new_segments(n));
1702     end loop;
1703 
1704     -------------------------- Get new ccid -------------------------------
1705     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling FND_FLEX_EXT.GET_COMBINATION_ID...');
1706     iF (NOT FND_FLEX_EXT.GET_COMBINATION_ID(
1707                             'SQLGL',
1708                             'GL#',
1709                             p_chart_of_accounts_id,
1710                             SYSDATE,
1711                             l_num_segments,
1712                             l_new_segments,
1713                             l_new_cc_id))
1714     Then
1715         FND_MESSAGE.SET_NAME('LNS', 'LNS_CODE_COMBINATION_ERROR');
1716         FND_MSG_PUB.ADD;
1717         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
1718         RAISE FND_API.G_EXC_ERROR;
1719 
1720     END IF;
1721     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'new cc_id = ' || l_new_cc_id);
1722     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
1723 
1724     return l_new_cc_id;
1725 
1726 exception
1727     when others then
1728         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, 'failed to create new code combination');
1729         RAISE FND_API.G_EXC_ERROR;
1730 end swap_code_combination;
1731 
1732 
1733 /*=========================================================================
1734 || PRIVATE PROCEDURE  transformDistribution
1735 ||
1736 || DESCRIPTION
1737 ||         this function is currently not used nor finished
1738 ||         the idea was to include this function into the transaction_object as
1739 ||         part of the accounting sources within AAD
1740 ||
1741 || PSEUDO CODE/LOGIC
1742 ||
1743 || PARAMETERS
1744 ||
1745 || Return value:  new code_combination_id
1746 ||
1747 || Source Tables:
1748 ||
1749 || Target Tables: NA
1750 ||
1751 || KNOWN ISSUES
1752 ||
1753 || NOTES
1754 ||
1755 || MODIFICATION HISTORY
1756 || Date                  Author            Description of Changes
1757 || 06-19-2005            raverma             Created
1758  *=======================================================================*/
1759 function transformDistribution(p_distribution_id   number
1760                                 ,p_distribution_type varchar2
1761                                 ,p_loan_id           number) return number
1762 is
1763 
1764 	l_new_cc_id  		       number;
1765     l_ledger_details   		 lns_distributions_pub.gl_ledger_details;
1766     l_natural_account_rec  varchar2(25);  -- the lns_def_distribs replacement  for Loans Receivable
1767     l_nat_acct_seg_number  number;
1768 	l_api_name					   varchar2(25);
1769 
1770 	-- gets the swap natural account value for LOAN_RECEIVABLE
1771     cursor c_mfar_nat_acct (p_loan_id number) is
1772     select MFAR_NATURAL_ACCOUNT_REC
1773     from lns_default_distribs d
1774         ,lns_loan_headers h
1775     where account_name = 'MFAR_FUND_ACCOUNT_CHANGE'
1776       and h.loan_id = p_loan_id
1777       and h.loan_class_code = d.loan_class
1778       and h.loan_type_id  = d.loan_type_id;
1779 
1780 begin
1781 
1782     l_ledger_details   := lns_distributions_pub.getLedgerDetails;
1783     -- given a code_combination
1784     if p_distribution_type = 'LOAN_RECEIVABLE' then
1785 
1786         -- build new cc_id
1787         Begin
1788             -- swap account is established from set-up
1789             open c_mfar_nat_acct(p_loan_id);
1790             fetch c_mfar_nat_acct into l_natural_account_rec;
1791             close c_mfar_nat_acct;
1792 
1793         Exception
1794             When others then
1795                 FND_MESSAGE.SET_NAME('LNS', 'LNS_MFAR_CONFIGURATION_ERROR');
1796                 FND_MSG_PUB.ADD;
1797                 logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
1798                 RAISE FND_API.G_EXC_ERROR;
1799         End;
1800         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'swap natural account with ' || l_natural_account_rec);
1801         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'COA ' || l_ledger_details.chart_of_accounts_id);
1802 
1803         -- Get natural account segment number to swap
1804         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling FND_FLEX_APIS.GET_QUALIFIER_SEGNUM...');
1805         IF (NOT FND_FLEX_APIS.GET_QUALIFIER_SEGNUM(appl_id         => 101
1806                                                 ,key_flex_code   => 'GL#'
1807                                                 ,structure_number=> l_ledger_details.chart_of_accounts_id
1808                                                 ,flex_qual_name  => 'GL_ACCOUNT'
1809                                                 ,segment_number  => l_nat_acct_seg_number))
1810         THEN
1811             FND_MESSAGE.SET_NAME('LNS', 'LNS_NO_NATURAL_ACCOUNT_SEGMENT');
1812             FND_MSG_PUB.ADD;
1813             logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
1814             RAISE FND_API.G_EXC_ERROR;
1815 
1816         END IF;
1817         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'natural acct segment is ' || l_nat_acct_seg_number);
1818 
1819         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling swap_code_combination...');
1820         l_new_cc_id := swap_code_combination(p_chart_of_accounts_id => l_ledger_details.chart_of_accounts_id
1821                                             ,p_original_cc_id       => p_distribution_id
1822                                             ,p_swap_segment_number  => l_nat_acct_seg_number
1823                                             ,p_swap_segment_value   => l_natural_account_rec);
1824 
1825     elsif p_distribution_type = 'LOAN_CLEARING' then
1826         -- get adjustment cc_id
1827         l_new_cc_id := 123;
1828     end if;
1829 
1830     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_new_cc_id = ' || l_new_cc_id);
1831     return l_new_cc_id;
1832 
1833 end transformDistribution;
1834 
1835 
1836 /*=========================================================================
1837 || function getDefaultDistributions
1838 ||
1839 || DESCRIPTION
1840 ||      This function returns default distribution entities
1841 ||
1842 || PSEUDO CODE/LOGIC
1843 ||
1844 || PARAMETERS
1845 ||   p_loan_class = loan class
1846 ||   p_loan_type = loan_type
1847 ||   p_account_type  = 'CR' or 'DR'
1848 ||   p_account_name  = 'LOAN_RECEIVABLE' 'LOAN_CLEARING', 'PRINCIPAL_RECIEVABLE',
1849 ||                     'INTEREST_RECEIVABLE', 'INTEREST_INCOME'
1850 ||                      'FEE_RECEIVABLE', 'FEE_INCOME'
1851 ||
1852 ||   p_line_type     = 'ORIG', 'PRIN', 'INT', 'CLEAR' , 'FEE'
1853 ||   p_distribution_type = 'ORIGINATION' , 'BILLING', 'FUNDING'
1854 ||
1855 || Return value:  table of distribution entities
1856 ||
1857 || Source Tables: lns_distributions
1858 ||
1859 || Target Tables:
1860 ||
1861 || KNOWN ISSUES
1862 ||
1863 || NOTES
1864 ||
1865 ||
1866 || MODIFICATION HISTORY
1867 || Date                  Author            Description of Changes
1868 || 06-28-2004            raverma             Created
1869 ||
1870  *=======================================================================*/
1871 function getDefaultDistributions(p_loan_class        in varchar2
1872                                 ,p_loan_type_id      in number
1873                                 ,p_account_type      in varchar2
1874                                 ,p_account_name      in varchar2
1875                                 ,p_line_type         in varchar2
1876                                 ,p_distribution_type in varchar2) return LNS_DISTRIBUTIONS_PUB.default_distributions_tbl
1877 is
1878     x_distribution_tbl         LNS_DISTRIBUTIONS_PUB.default_distributions_tbl;
1879     l_index                		 number := 1;
1880     l_loan_id              		 number;
1881     l_loan_class           		 varchar2(30);
1882     l_loan_type_id         		 number;
1883     l_line_type            		 varchar2(30);
1884     l_account_name         		 varchar2(30);
1885     l_code_combination_id  		 number;
1886     l_distribution_percent 		 number;
1887     l_distribution_type        varchar2(30);
1888     l_fee_id                   number;
1889     l_org_id                   number;
1890     l_mfar_natural_account_rec varchar2(60);
1891     l_expenditure_type            pa_expenditure_types.expenditure_type%TYPE;
1892     l_EXPENDITURE_ITEM_DATE       date;
1893     l_project_id                  pa_projects_all.project_id%TYPE;
1894     l_task_id                     pa_tasks.task_id%TYPE;
1895     l_award_id	               gms_awards.award_id%TYPE;
1896 
1897 
1898     cursor c_get_distribution(p_loan_class   varchar2
1899                              ,p_loan_type_id number
1900                              ,p_acct_type    varchar2
1901                              ,p_acct_name 	 varchar2
1902                              ,p_line_type    varchar2
1903                              ,p_distribution_type varchar2) is
1904        select loan_class
1905              ,loan_type_id
1906              ,line_type
1907              ,account_name
1908              ,code_combination_id
1909              ,distribution_percent
1910              ,distribution_type
1911              ,FEE_ID
1912              ,ORG_ID
1913              ,MFAR_NATURAL_ACCOUNT_REC
1914              ,PROJECT_ID
1915              ,TASK_ID
1916              ,AWARD_ID
1917              ,EXPENDITURE_TYPE
1918              ,EXPENDITURE_ITEM_DATE
1919        from lns_default_distribs
1920        where loan_class = p_loan_class
1921          and loan_type_id  = p_loan_type_id
1922          and account_type = p_acct_type
1923          and account_name = p_acct_name
1924          and line_type = p_line_type
1925          and distribution_type = p_distribution_type
1926          and distribution_percent > 0
1927     order by code_combination_id;
1928 
1929     l_api_name              varchar2(30);
1930 
1931 begin
1932 
1933     l_api_name  := 'getDefaultDistributions';
1934     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
1935     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan_class = ' || p_loan_class);
1936     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan typeID = ' || p_loan_type_id);
1937     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'account type = ' || p_account_type);
1938     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'account name = ' || p_account_name);
1939     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'line tpye = ' || p_line_type);
1940     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'distribution type = ' || p_distribution_type);
1941 
1942     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'opening c_get_distribution...');
1943     OPEN c_get_distribution (p_loan_class
1944                             ,p_loan_type_id
1945                             ,p_account_type
1946                             ,p_account_name
1947                             ,p_line_type
1948                             ,p_distribution_type);
1949     LOOP
1950         FETCH C_Get_Distribution into
1951             l_loan_class
1952             ,l_loan_type_id
1953             ,l_line_type
1954             ,l_account_name
1955             ,l_code_combination_id
1956             ,l_distribution_percent
1957             ,l_distribution_type
1958             ,l_fee_id
1959             ,l_org_id
1960             ,l_mfar_natural_account_rec
1961             ,l_project_id
1962             ,l_task_id
1963             ,l_award_id
1964             ,l_expenditure_type
1965             ,l_expenditure_item_date;
1966         EXIT WHEN C_Get_Distribution%NOTFOUND;
1967 
1968         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Record ' || l_index);
1969         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_class = ' || l_loan_class);
1970         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_type_id = ' || l_loan_type_id);
1971         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_line_type = ' || l_line_type);
1972         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_name = ' || l_account_name);
1973         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
1974         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_percent = ' || l_distribution_percent);
1975         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_type = ' || l_distribution_type);
1976         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_fee_id = ' || l_fee_id);
1977         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_org_id = ' || l_org_id);
1978         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_mfar_natural_account_rec = ' || l_mfar_natural_account_rec);
1979         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_project_id = ' || l_project_id);
1980         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_award_id = ' || l_award_id);
1981         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_task_id = ' || l_task_id);
1982         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_type = ' || l_expenditure_type);
1983         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_item_date = ' || l_expenditure_item_date);
1984 
1985         x_distribution_tbl(l_index).line_type                   := l_line_type;
1986         x_distribution_tbl(l_index).account_name                := l_account_name;
1987         x_distribution_tbl(l_index).code_combination_id         := l_code_combination_id;
1988         x_distribution_tbl(l_index).distribution_percent        := l_distribution_percent;
1989         x_distribution_tbl(l_index).distribution_type           := l_distribution_type;
1990         x_distribution_tbl(l_index).fee_id                      := l_fee_id;
1991         x_distribution_tbl(l_index).org_id                      := l_org_id;
1992         x_distribution_tbl(l_index).project_id                  := l_project_id;
1993         x_distribution_tbl(l_index).task_id                     := l_task_id;
1994         x_distribution_tbl(l_index).award_id                    := l_award_id;
1995         x_distribution_tbl(l_index).expenditure_type            := l_expenditure_type;
1996         x_distribution_tbl(l_index).expenditure_item_date       := l_expenditure_item_date;
1997 
1998 
1999         l_line_type                 := null;
2000         l_account_name              := null;
2001         l_code_combination_id       := null;
2002         l_distribution_percent      := null;
2003         l_distribution_type         := null;
2004         l_fee_id                    := null;
2005         l_org_id                    := null;
2006         l_mfar_natural_account_rec  := null;
2007         l_project_id                := null;
2008         l_task_id                   := null;
2009         l_award_id                  := null;
2010         l_expenditure_type          := null;
2011         l_expenditure_item_date     := null;
2012 
2013         l_index := l_index + 1;
2014 
2015     END LOOP;
2016 
2017     CLOSE C_Get_Distribution;
2018 
2019     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'found: ' || x_distribution_tbl.count || ' distributions');
2020     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
2021     return x_distribution_tbl;
2022 
2023 end getDefaultDistributions;
2024 
2025 /*=========================================================================
2026 || function getDistributions
2027 ||
2028 || DESCRIPTION
2029 ||      This function returns distribution entities
2030 ||
2031 || PSEUDO CODE/LOGIC
2032 ||
2033 || PARAMETERS
2034 ||   p_loan_id = loan_id
2035 ||   p_account_type  = 'CR' or 'DR'
2036 ||   p_account_name  = 'LOAN_RECEIVABLE' 'LOAN_CLEARING', 'PRINCIPAL_RECIEVABLE',
2037 ||                     'INTEREST_RECEIVABLE', 'INTEREST_INCOME'
2038 ||                      'FEE_RECEIVABLE', 'FEE_INCOME'
2039 ||   p_line_type     = 'ORIG', 'PRIN', 'INT', 'CLEAR' , 'FEE'
2040 ||   p_distribution_type = 'ORIGINATION' , 'BILLING'  , ' FUNDING'
2041 ||
2042 || Return value:  table of distribution entities
2043 ||
2044 || Source Tables: lns_distributions
2045 ||
2046 || Target Tables:
2047 ||
2048 || KNOWN ISSUES
2049 ||
2050 || NOTES
2051 ||
2052 ||
2053 || MODIFICATION HISTORY
2054 || Date                  Author            Description of Changes
2055 || 04-26-2004            raverma             Created
2056 ||
2057  *=======================================================================*/
2058 function getDistributions(p_loan_id           in number
2059                          ,p_account_type      in varchar2
2060                          ,p_account_name      in varchar2
2061                          ,p_line_type         in varchar2
2062                          ,p_distribution_type in varchar2) return LNS_DISTRIBUTIONS_PUB.distribution_tbl
2063 
2064 is
2065 
2066     l_api_name             varchar2(30);
2067     x_distribution_tbl     lns_distributions_pub.distribution_tbl;
2068     l_index                number;
2069     l_loan_id              number;
2070     l_distribution_id      number;
2071     l_line_type            varchar2(30);
2072     l_account_name         varchar2(30);
2073     l_code_combination_id  number;
2074     l_distribution_percent number;
2075     l_distribution_amount  number;
2076     l_distribution_type    varchar2(30);
2077     l_event_id             number;
2078     l_expenditure_type            pa_expenditure_types.expenditure_type%TYPE;
2079     l_expenditure_item_date       date;
2080     l_project_id                  pa_projects_all.project_id%TYPE;
2081     l_task_id                     pa_tasks.task_id%TYPE;
2082     l_award_id	               gms_awards.award_id%TYPE;
2083 
2084 
2085     cursor c_get_distribution(x_loan_id number
2086                              ,x_acct_type varchar2
2087                              ,x_acct_name varchar2
2088                              ,x_line_type varchar2
2089                              ,x_distribution_type varchar2) is
2090        select d.distribution_id
2091              ,d.loan_id
2092              ,d.line_type
2093              ,d.account_name
2094              ,d.code_combination_id
2095              ,d.distribution_percent
2096              ,d.distribution_amount
2097              ,d.distribution_type
2098              ,d.event_id
2099              ,d.project_id
2100              ,d.task_id
2101              ,d.award_id
2102              ,d.expenditure_type
2103              ,d.expenditure_item_date
2104        from lns_distributions d
2105        where d.loan_id = x_loan_id
2106          and d.account_type = x_acct_type
2107          and d.account_name = x_acct_name
2108          and d.line_type = x_line_type
2109          and d.distribution_type = x_distribution_type
2110          and d.distribution_percent >= 0
2111         order by d.code_combination_id;
2112 
2113 begin
2114 
2115     l_api_name    := 'getDistributions';
2116     l_index       := 0;
2117 
2118     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
2119     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
2120     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_account_type = ' || p_account_type);
2121     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_account_name = ' || p_account_name);
2122     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_line_type = ' || p_line_type);
2123     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_distribution_type = ' || p_distribution_type);
2124     x_distribution_tbl.delete;
2125 
2126     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'opening c_get_distribution...');
2127     OPEN c_get_distribution (p_loan_id
2128                             ,p_account_type
2129                             ,p_account_name
2130                             ,p_line_type
2131                             ,p_distribution_type);
2132     LOOP
2133         FETCH C_Get_Distribution into
2134             l_distribution_id
2135             ,l_loan_id
2136             ,l_line_type
2137             ,l_account_name
2138             ,l_code_combination_id
2139             ,l_distribution_percent
2140             ,l_distribution_amount
2141             ,l_distribution_type
2142             ,l_event_id
2143             ,l_project_id
2144             ,l_task_id
2145             ,l_award_id
2146             ,l_expenditure_type
2147             ,l_expenditure_item_date;
2148         EXIT WHEN C_Get_Distribution%NOTFOUND;
2149         l_index := l_index + 1;
2150 
2151         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Record ' || l_index);
2152         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_id = ' || l_distribution_id);
2153         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_id = ' || l_loan_id);
2154         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_line_type = ' || l_line_type);
2155         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_name = ' || l_account_name);
2156         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
2157         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_percent = ' || l_distribution_percent);
2158         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_amount = ' || l_distribution_amount);
2159         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_type = ' || l_distribution_type);
2160         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
2161         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_project_id = ' || l_project_id);
2162         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_award_id = ' || l_award_id);
2163         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_task_id = ' || l_task_id);
2164         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_type = ' || l_expenditure_type);
2165         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_item_date = ' || l_expenditure_item_date);
2166 
2167         x_distribution_tbl(l_index).distribution_id        := l_distribution_id;
2168         x_distribution_tbl(l_index).loan_id                := l_loan_id;
2169         x_distribution_tbl(l_index).line_type              := l_line_type;
2170         x_distribution_tbl(l_index).account_name           := l_account_name;
2171         x_distribution_tbl(l_index).code_combination_id    := l_code_combination_id;
2172         x_distribution_tbl(l_index).distribution_percent   := l_distribution_percent;
2173         x_distribution_tbl(l_index).distribution_amount    := l_distribution_amount;
2174         x_distribution_tbl(l_index).distribution_type      := l_distribution_type;
2175         x_distribution_tbl(l_index).event_id               := l_event_id;
2176         x_distribution_tbl(l_index).account_type           := p_account_type;
2177         x_distribution_tbl(l_index).project_id             := l_project_id;
2178         x_distribution_tbl(l_index).task_id                := l_task_id;
2179         x_distribution_tbl(l_index).award_id               := l_award_id;
2180         x_distribution_tbl(l_index).expenditure_type       := l_expenditure_type;
2181         x_distribution_tbl(l_index).expenditure_item_date  := l_expenditure_item_date;
2182         l_distribution_id       := null;
2183         l_loan_id               := null;
2184         l_line_type             := null;
2185         l_account_name          := null;
2186         l_code_combination_id   := null;
2187         l_distribution_percent  := null;
2188         l_distribution_amount   := null;
2189         l_distribution_type     := null;
2190         l_event_id              := null;
2191         l_project_id            := null;
2192         l_task_id               := null;
2193         l_award_id              := null;
2194         l_expenditure_type      := null;
2195         l_expenditure_item_date := null;
2196 
2197     END LOOP;
2198 
2199     CLOSE C_Get_Distribution;
2200 
2201     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'found: ' || x_distribution_tbl.count || ' distributions');
2202     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
2203     return x_distribution_tbl;
2204 
2205 end getDistributions;
2206 
2207 function getDistributions(p_distribution_id in number) return LNS_DISTRIBUTIONS_PUB.distribution_rec
2208 
2209 is
2210 
2211     x_distribution_rec     lns_distributions_pub.distribution_rec;
2212     l_api_name             varchar2(30);
2213 
2214     cursor c_get_distribution(x_distribution_id number) is
2215        select distribution_id
2216              ,loan_id
2217              ,line_type
2218              ,account_name
2219              ,code_combination_id
2220              ,distribution_percent
2221              ,distribution_amount
2222              ,distribution_type
2223              ,account_type
2224              ,account_name
2225              ,event_id
2226              ,project_id
2227              ,task_id
2228              ,award_id
2229              ,expenditure_type
2230              ,expenditure_item_date
2231        from lns_distributions
2232        where distribution_id = x_distribution_id
2233          and distribution_percent >= 0;
2234 
2235 begin
2236     l_api_name    := 'getDistributions';
2237 
2238     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
2239     OPEN c_get_distribution (p_distribution_id);
2240       FETCH C_Get_Distribution into
2241            x_distribution_rec.distribution_id
2242           ,x_distribution_rec.loan_id
2243           ,x_distribution_rec.line_type
2244           ,x_distribution_rec.account_name
2245           ,x_distribution_rec.code_combination_id
2246           ,x_distribution_rec.distribution_percent
2247           ,x_distribution_rec.distribution_amount
2248           ,x_distribution_rec.distribution_type
2249           ,x_distribution_rec.account_type
2250           ,x_distribution_rec.account_name
2251           ,x_distribution_rec.event_id
2252           ,x_distribution_rec.project_id
2253           ,x_distribution_rec.task_id
2254           ,x_distribution_rec.award_id
2255           ,x_distribution_rec.expenditure_type
2256           ,x_distribution_rec.expenditure_item_date ;
2257     CLOSE C_Get_Distribution;
2258 
2259     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'distribution_id = ' || x_distribution_rec.distribution_id);
2260     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan_id = ' || x_distribution_rec.loan_id);
2261     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'line_type = ' || x_distribution_rec.line_type);
2262     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'account_name = ' || x_distribution_rec.account_name);
2263     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'code_combination_id = ' || x_distribution_rec.code_combination_id);
2264     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'distribution_percent = ' || x_distribution_rec.distribution_percent);
2265     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'distribution_amount = ' || x_distribution_rec.distribution_amount);
2266     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'distribution_type = ' || x_distribution_rec.distribution_type);
2267     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'account_type = ' || x_distribution_rec.account_type);
2268     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'account_name = ' || x_distribution_rec.account_name);
2269     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'event_id = ' || x_distribution_rec.event_id);
2270     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_project_id = ' || x_distribution_rec.project_id);
2271     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_award_id = ' || x_distribution_rec.award_id);
2272     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_task_id = ' || x_distribution_rec.task_id);
2273     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_type = ' || x_distribution_rec.expenditure_type);
2274     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_item_date = ' || x_distribution_rec.expenditure_item_date);
2275 
2276     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
2277     return x_distribution_rec;
2278 
2279 end getDistributions;
2280 
2281 /*=========================================================================
2282 || function getDistributions
2283 ||
2284 || DESCRIPTION
2285 ||      This function returns distribution entities
2286 ||
2287 || PSEUDO CODE/LOGIC
2288 ||
2289 || PARAMETERS
2290 ||   p_loan_id = loan_id
2291 ||   p_loan_line_id = loan_line_id
2292 ||   p_account_type  = 'CR' or 'DR'
2293 ||   p_account_name  = 'LOAN_RECEIVABLE' 'LOAN_CLEARING', 'PRINCIPAL_RECIEVABLE',
2294 ||                     'INTEREST_RECEIVABLE', 'INTEREST_INCOME'
2295 ||                      'FEE_RECEIVABLE', 'FEE_INCOME'
2296 ||   p_line_type     = 'ORIG', 'PRIN', 'INT', 'CLEAR' , 'FEE'
2297 ||   p_distribution_type = 'ORIGINATION' , 'BILLING'  , ' FUNDING'
2298 ||
2299 || Return value:  table of distribution entities
2300 ||
2301 || Source Tables: lns_distributions
2302 ||
2303 || Target Tables:
2304 ||
2305 || KNOWN ISSUES
2306 ||
2307 || NOTES
2308 ||
2309 ||
2310 || MODIFICATION HISTORY
2311 || Date                  Author            Description of Changes
2312 || 04-01-2010            raverma             Created
2313 ||
2314  *=======================================================================*/
2315 function getDistributions(p_loan_id           in number
2316                          ,p_loan_line_id      in number
2317                          ,p_account_type      in varchar2
2318                          ,p_account_name      in varchar2
2319                          ,p_line_type         in varchar2
2320                          ,p_distribution_type in varchar2) return LNS_DISTRIBUTIONS_PUB.distribution_tbl
2321 
2322 is
2323 
2324     l_api_name             varchar2(30);
2325     x_distribution_tbl     lns_distributions_pub.distribution_tbl;
2326     l_index                number;
2327     l_loan_id              number;
2328     l_distribution_id      number;
2329     l_line_type            varchar2(30);
2330     l_account_name         varchar2(30);
2331     l_account_type         varchar2(30);
2332     l_code_combination_id  number;
2333     l_distribution_percent number;
2334     l_distribution_amount  number;
2335     l_distribution_type    varchar2(30);
2336     l_event_id             number;
2337     l_expenditure_type            pa_expenditure_types.expenditure_type%TYPE;
2338     l_expenditure_item_date       date;
2339     l_project_id                  pa_projects_all.project_id%TYPE;
2340     l_task_id                     pa_tasks.task_id%TYPE;
2341     l_award_id	               gms_awards.award_id%TYPE;
2342 
2343 
2344     cursor c_get_distribution(x_loan_id number
2345                              ,x_loan_line_id number
2346                              ,x_acct_type varchar2
2347                              ,x_acct_name varchar2
2348                              ,x_line_type varchar2
2349                              ,x_distribution_type varchar2) is
2350        select d.distribution_id
2351              ,d.loan_id
2352              ,d.line_type
2353              ,d.account_name
2354              ,d.account_type
2355              ,d.code_combination_id
2356              ,d.distribution_percent
2357              ,d.distribution_amount
2358              ,d.distribution_type
2359              ,d.event_id
2360              ,d.project_id
2361              ,d.task_id
2362              ,d.award_id
2363              ,d.expenditure_type
2364              ,d.expenditure_item_date
2365        from lns_distributions d
2366        where d.loan_id = x_loan_id
2367          and d.loan_line_id = x_loan_line_id
2368          and d.account_type = x_acct_type
2369          and d.account_name = x_acct_name
2370          and d.line_type = x_line_type
2371          and d.distribution_type = x_distribution_type
2372          and d.distribution_percent > 0
2373         order by d.code_combination_id;
2374 
2375 begin
2376 
2377     l_api_name    := 'getDistributions';
2378     l_index       := 0;
2379 
2380     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
2381     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
2382     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_line_id = ' || p_loan_line_id);
2383     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_account_type = ' || p_account_type);
2384     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_account_name = ' || p_account_name);
2385     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_line_type = ' || p_line_type);
2386     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_distribution_type = ' || p_distribution_type);
2387     x_distribution_tbl.delete;
2388 
2389     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'opening c_get_distribution...');
2390     OPEN c_get_distribution (p_loan_id
2391                             ,p_loan_line_id
2392                             ,p_account_type
2393                             ,p_account_name
2394                             ,p_line_type
2395                             ,p_distribution_type);
2396     LOOP
2397         FETCH C_Get_Distribution into
2398             l_distribution_id
2399             ,l_loan_id
2400             ,l_line_type
2401             ,l_account_name
2402             ,l_account_type
2403             ,l_code_combination_id
2404             ,l_distribution_percent
2405             ,l_distribution_amount
2406             ,l_distribution_type
2407             ,l_event_id
2408             ,l_project_id
2409             ,l_task_id
2410             ,l_award_id
2411             ,l_expenditure_type
2412             ,l_expenditure_item_date;
2413         EXIT WHEN C_Get_Distribution%NOTFOUND;
2414         l_index := l_index + 1;
2415 
2416         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Record ' || l_index);
2417         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_id = ' || l_distribution_id);
2418         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_id = ' || l_loan_id);
2419         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_line_type = ' || l_line_type);
2420         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_name = ' || l_account_name);
2421         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_type = ' || l_account_type);
2422         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
2423         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_percent = ' || l_distribution_percent);
2424         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_amount = ' || l_distribution_amount);
2425         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_type = ' || l_distribution_type);
2426         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
2427         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_project_id = ' || l_project_id);
2428         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_award_id = ' || l_award_id);
2429         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_task_id = ' || l_task_id);
2430         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_type = ' || l_expenditure_type);
2431         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_item_date = ' || l_expenditure_item_date);
2432 
2433 
2434         x_distribution_tbl(l_index).distribution_id        := l_distribution_id;
2435         x_distribution_tbl(l_index).loan_id                := l_loan_id;
2436         x_distribution_tbl(l_index).line_type              := l_line_type;
2437         x_distribution_tbl(l_index).account_name           := l_account_name;
2438         x_distribution_tbl(l_index).account_type           := l_account_type;
2439         x_distribution_tbl(l_index).code_combination_id    := l_code_combination_id;
2440         x_distribution_tbl(l_index).distribution_percent   := l_distribution_percent;
2441         x_distribution_tbl(l_index).distribution_amount    := l_distribution_amount;
2442         x_distribution_tbl(l_index).distribution_type      := l_distribution_type;
2443         x_distribution_tbl(l_index).event_id               := l_event_id;
2444         x_distribution_tbl(l_index).project_id             := l_project_id;
2445         x_distribution_tbl(l_index).task_id                := l_task_id;
2446         x_distribution_tbl(l_index).award_id               := l_award_id;
2447         x_distribution_tbl(l_index).expenditure_type       := l_expenditure_type;
2448         x_distribution_tbl(l_index).expenditure_item_date  := l_expenditure_item_date;
2449 
2450         l_distribution_id       := null;
2451         l_loan_id               := null;
2452         l_line_type             := null;
2453         l_account_name          := null;
2454         l_account_type          := null;
2455         l_code_combination_id   := null;
2456         l_distribution_percent  := null;
2457         l_distribution_amount   := null;
2458         l_distribution_type     := null;
2459         l_event_id              := null;
2460         l_project_id            := null;
2461         l_task_id               := null;
2462         l_award_id              := null;
2463         l_expenditure_type      := null;
2464         l_expenditure_item_date := null;
2465 
2466 
2467     END LOOP;
2468 
2469     CLOSE C_Get_Distribution;
2470 
2471     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'found: ' || x_distribution_tbl.count || ' distributions');
2472     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
2473     return x_distribution_tbl;
2474 
2475 end getDistributions;
2476 
2477 
2478 /*=========================================================================
2479 || PUBLIC PROCEDURE getLedgerDetails
2480 ||
2481 || DESCRIPTION
2482 ||      This procedure gets details about the General Ledger
2483 ||      THIS FUNCTION IS THE MAIN INTERFACE INTO GENERAL LEDGER
2484 ||
2485 ||
2486 || PSEUDO CODE/LOGIC
2487 ||
2488 || PARAMETERS
2489 ||
2490 || Return value:
2491 ||  type gl_ledger_details is record(SET_OF_BOOKS_ID      NUMBER(15)
2492 ||                                  ,NAME                 VARCHAR2(30)
2493 ||                                  ,SHORT_NAME           VARCHAR2(20)
2494 ||                                  ,CHART_OF_ACCOUNTS_ID NUMBER(15)
2495 ||                                  ,PERIOD_SET_NAME      VARCHAR2(15));
2496 ||
2497 || Source Tables: LNS_SYSTEM_OPTIONS, GL_SETS_OF_BOOKS
2498 ||
2499 || Target Tables: NA
2500 ||
2501 || KNOWN ISSUES
2502 ||
2503 || NOTES
2504 ||
2505 ||
2506 || MODIFICATION HISTORY
2507 || Date                  Author            Description of Changes
2508 || 02-18-2004            raverma             Created
2509 ||
2510  *=======================================================================*/
2511 function getLedgerDetails return lns_distributions_pub.gl_ledger_details
2512 is
2513     cursor c_ledger
2514     is
2515     SELECT  so.set_of_books_id
2516            ,sb.name
2517            ,sb.short_name
2518            ,sb.chart_of_accounts_id
2519            ,sb.period_set_name
2520            ,sb.currency_code
2521            ,fndc.precision
2522       FROM lns_system_options so,
2523            gl_ledgers sb,
2524            fnd_currencies fndc
2525      WHERE sb.ledger_id = so.set_of_books_id
2526        and sb.currency_code = fndc.currency_code;
2527 
2528     l_ledger_details lns_distributions_pub.gl_ledger_details;
2529 
2530 begin
2531 
2532     begin
2533         open c_ledger;
2534         fetch c_ledger into  l_ledger_details.set_of_books_id
2535                             ,l_ledger_details.name
2536                             ,l_ledger_details.short_name
2537                             ,l_ledger_details.chart_of_accounts_id
2538                             ,l_ledger_details.period_set_name
2539                             ,l_ledger_details.currency_code
2540                             ,l_ledger_details.currency_precision;
2541         close c_ledger;
2542 
2543         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Ledger details:');
2544         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'set_of_books_id = ' || l_ledger_details.set_of_books_id);
2545         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'name = ' || l_ledger_details.name);
2546         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'short_name = ' || l_ledger_details.short_name);
2547         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'chart_of_accounts_id = ' || l_ledger_details.chart_of_accounts_id);
2548         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'period_set_name = ' || l_ledger_details.period_set_name);
2549         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'currency_code = ' || l_ledger_details.currency_code);
2550         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'currency_precision = ' || l_ledger_details.currency_precision);
2551 
2552         return l_ledger_details;
2553 
2554     exception
2555         when others then
2556             FND_MESSAGE.SET_NAME('LNS', 'LNS_LEDGER_DETAILS_FAIL');
2557             FND_MSG_PUB.ADD;
2558             LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
2559             RAISE FND_API.G_EXC_ERROR;
2560     end;
2561 
2562 end getLedgerDetails;
2563 
2564 /*=========================================================================
2565 || PUBLIC FUNCTION calculateDistributionAmount
2566 ||
2567 || DESCRIPTION
2568 ||      calculatest the distribution amount based on the distribution percentage
2569 ||      this api assumes the defaultDistributions API has been called to
2570 ||      store the distributions on LNS_DISTRIBUTIONS
2571 ||
2572 || PSEUDO CODE/LOGIC
2573 ||
2574 || PARAMETERS
2575 ||           p_distribution_id = pk to LNS_DISTRIBUTIONS
2576 ||
2577 || Return value: amount of distribution based from loan funded amount
2578 ||
2579 || Source Tables: lns_distributions, lns_loan_headers
2580 ||
2581 || Target Tables: NA
2582 ||
2583 || KNOWN ISSUES
2584 ||
2585 || NOTES
2586 ||
2587 ||
2588 || MODIFICATION HISTORY
2589 || Date                  Author            Description of Changes
2590 || 06/15/04 2:48:PM       raverma           Created
2591 || 09/07/04               raverma           enhance to know about all distributions on loan
2592 ||                                          bug #3736979
2593  *=======================================================================*/
2594 function calculateDistributionAmount(p_distribution_id in number) return number
2595 
2596 is
2597     l_api_name              varchar2(50);
2598     l_distribution_amount   number;
2599     l_ledger_details        lns_distributions_pub.gl_ledger_details;
2600     l_distribution_rec      lns_distributions_pub.distribution_rec;
2601     l_distribution_tbl      lns_distributions_pub.distribution_tbl;
2602     l_loan_id               number;
2603     l_max_distribution_id   number;
2604 
2605     cursor c_get_distribution(p_distribution_id number) is
2606     select round(lnh.funded_amount * lnd.distribution_percent / 100, curr.precision)
2607       from lns_distributions lnd
2608           ,lns_loan_headers lnh
2609           ,fnd_currencies  curr
2610      where lnh.loan_id = lnd.loan_id
2611        and curr.currency_code = lnh.loan_currency
2612        and lnd.distribution_id = p_distribution_id;
2613 
2614     -- cursor to find if this is the last distribution on the loan
2615     cursor c_max_dist(p_loan_id number
2616                      ,p_distribution_type varchar
2617                      ,p_account_type varchar2)    is
2618          select max(distribution_id)
2619            from lns_distributions lnd
2620                ,lns_loan_headers lnh
2621           where lnh.loan_id = lnd.loan_id
2622             and lnd.distribution_type = p_distribution_type
2623             and lnd.account_type = p_account_type
2624             and lnh.loan_id = p_loan_id;
2625 
2626     cursor c_last_distribution(p_loan_id number
2627                               ,p_distribution_id number
2628                               ,p_distribution_type varchar
2629                               ,p_account_type varchar2) is
2630     select
2631     lnh.funded_amount -
2632     (round(lnh.funded_amount *
2633     (select sum(distribution_percent) / 100
2634        from lns_distributions
2635       where distribution_id <> p_distribution_id
2636         and distribution_type = p_distribution_type
2637         and account_type = p_account_type
2638         and loan_id = p_loan_id), curr.precision))
2639       from lns_distributions lnd
2640           ,lns_loan_headers lnh
2641           ,fnd_currencies  curr
2642      where lnh.loan_id = lnd.loan_id
2643        and lnh.loan_id = p_loan_id
2644        and curr.currency_code = lnh.loan_currency;
2645 
2646 begin
2647 
2648     l_api_name := 'calculateDistributionAmount';
2649     --logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
2650     l_ledger_details   := lns_distributions_pub.getLedgerDetails;
2651     l_distribution_rec := lns_distributions_pub.getDistributions(p_distribution_id);
2652 
2653     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loanID = ' || l_distribution_rec.loan_id);
2654     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'DIST_ID = ' || p_distribution_id);
2655     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'disttype = ' || l_distribution_rec.distribution_type);
2656     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'accounttype = ' || l_distribution_rec.account_type);
2657 
2658     if l_distribution_rec.distribution_amount is null then
2659         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling lns_distributions_pub.getDistributions...');
2660          l_distribution_tbl := lns_distributions_pub.getDistributions(p_loan_id           => l_distribution_rec.loan_id
2661                                                                      ,p_account_type      => l_distribution_rec.account_type
2662                                                                      ,p_account_name      => l_distribution_rec.account_name
2663                                                                      ,p_line_type         => l_distribution_rec.line_type
2664                                                                      ,p_distribution_type => l_distribution_rec.distribution_type);
2665         open c_max_dist(l_distribution_rec.loan_id
2666                        ,l_distribution_rec.distribution_type
2667                        ,l_distribution_rec.account_type);
2668         fetch c_max_dist into l_max_distribution_id;
2669         close c_max_dist;
2670 
2671         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_max_distribution_id = ' ||l_max_distribution_id);
2672 
2673         -- check to see if this is the last distribution
2674         if l_max_distribution_id = p_distribution_id and l_distribution_tbl.count > 1 then
2675            logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'last distribution');
2676             open c_last_distribution(l_distribution_rec.loan_id
2677                                     ,l_distribution_rec.distribution_id
2678                                     ,l_distribution_rec.distribution_type
2679                                     ,l_distribution_rec.account_type);
2680             fetch c_last_distribution into l_distribution_amount;
2681             close c_last_distribution;
2682         else
2683         --logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
2684             open c_get_distribution(p_distribution_id);
2685             fetch c_get_distribution into l_distribution_amount;
2686             close c_get_distribution;
2687 
2688         end if;
2689     else
2690         l_distribution_amount :=  l_distribution_rec.distribution_amount;
2691     end if;
2692 
2693     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_amount = ' ||l_distribution_amount);
2694     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
2695     return l_distribution_amount;
2696 
2697 end calculateDistributionAmount;
2698 
2699 /*========================================================================
2700 || PUBLIC FUNCTION calculateDistributionAmount
2701 ||
2702 || DESCRIPTION
2703 ||      calculatest the distribution amount based on the distribution percentage
2704 ||      this api assumes the defaultDistributions API has been called to
2705 ||      store the distributions on LNS_DISTRIBUTIONS
2706 ||
2707 || PSEUDO CODE/LOGIC
2708 ||
2709 || PARAMETERS
2710 ||           p_distribution_id = pk to LNS_DISTRIBUTIONS
2711 ||           p_accounted_flag = 'Y' to get amount in set_of_books currency
2712 ||                              'N' to get amount in loan currency
2713 ||
2714 || Return value: amount of distribution based from loan funded amount
2715 ||
2716 || Source Tables: lns_distributions, lns_loan_headers
2717 ||
2718 || Target Tables: NA
2719 ||
2720 || KNOWN ISSUES
2721 ||
2722 || NOTES
2723 ||
2724 ||
2725 || MODIFICATION HISTORY
2726 || Date                  Author            Description of Changes
2727 || 06/15/04 2:48:PM       raverma           Created
2728 || 09/07/04               raverma           enhance to know about all distributions on loan
2729 ||                                          bug #3736979
2730  *=======================================================================*/
2731 function calculateDistributionAmount(p_distribution_id in number
2732                                     ,p_accounted_flag  in varchar2) return number
2733 
2734 is
2735     l_api_name              varchar2(50);
2736     l_distribution_amount   number;
2737     l_return                number;
2738     l_ledger_details        lns_distributions_pub.gl_ledger_details;
2739     l_distribution_rec      lns_distributions_pub.distribution_rec;
2740     l_distribution_tbl      lns_distributions_pub.distribution_tbl;
2741     l_loan_id               number;
2742     l_max_distribution_id   number;
2743     l_currency_code         varchar2(10);
2744     l_exchange_rate_type    varchar2(30);
2745     l_exchange_rate         number;
2746     l_exchange_date         date;
2747 
2748     cursor c_exchange_info(p_loan_id number) is
2749     select lnh.exchange_rate_type
2750           ,lnh.exchange_rate
2751           ,lnh.exchange_date
2752           ,lnh.loan_currency
2753       from lns_loan_headers lnh
2754      where loan_id = p_loan_id;
2755 
2756     cursor c_get_distribution(p_distribution_id number) is
2757     select round(lnh.funded_amount * lnd.distribution_percent / 100, curr.precision)
2758       from lns_distributions lnd
2759           ,lns_loan_headers lnh
2760           ,fnd_currencies  curr
2761      where lnh.loan_id = lnd.loan_id
2762        and curr.currency_code = lnh.loan_currency
2763        and lnd.distribution_id = p_distribution_id;
2764 
2765     cursor c_last_distribution(p_loan_id number
2766                               ,p_distribution_id number
2767                               ,p_distribution_type varchar
2768                               ,p_account_type varchar2) is
2769     select
2770     lnh.funded_amount -
2771     (round(lnh.funded_amount *
2772     (select sum(distribution_percent) / 100
2773        from lns_distributions
2774       where distribution_id <> p_distribution_id
2775         and distribution_type = p_distribution_type
2776         and account_type = p_account_type
2777         and loan_id = p_loan_id), curr.precision))
2778       from lns_distributions lnd
2779           ,lns_loan_headers lnh
2780           ,fnd_currencies  curr
2781      where lnh.loan_id = lnd.loan_id
2782        and lnh.loan_id = p_loan_id
2783        and curr.currency_code = lnh.loan_currency;
2784 
2785 begin
2786 
2787     l_api_name := 'calculateDistributionAmount';
2788 
2789     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
2790     l_ledger_details   := lns_distributions_pub.getLedgerDetails;
2791     l_distribution_rec := lns_distributions_pub.getDistributions(p_distribution_id);
2792 
2793     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loanID = ' || l_distribution_rec.loan_id);
2794     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'DIST_ID = ' || p_distribution_id);
2795     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'disttype = ' || l_distribution_rec.distribution_type);
2796     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'accounttype = ' || l_distribution_rec.account_type);
2797     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'accounted flag = ' || p_accounted_flag);
2798 
2799     if p_accounted_flag = 'Y' then
2800 
2801         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loanID = ' || l_distribution_rec.loan_id);
2802         open c_exchange_info(l_distribution_rec.loan_id);
2803         fetch c_exchange_info into
2804             l_exchange_rate_type
2805            ,l_exchange_rate
2806            ,l_exchange_date
2807            ,l_currency_code;
2808         close c_exchange_info;
2809         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'exchange rate type = ' || l_exchange_rate_type);
2810         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'exchange rate = ' || l_exchange_rate);
2811         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'exchange date = ' || l_exchange_date);
2812         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'currency = ' || l_currency_code);
2813         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'currency2 = ' || l_ledger_details.CURRENCY_CODE);
2814         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'amount = ' || l_distribution_rec.distribution_amount);
2815 
2816         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling lns_utility_pub.convertAmount...');
2817         l_return    := lns_utility_pub.convertAmount(p_from_amount   => l_distribution_rec.distribution_amount
2818                                                     ,p_from_currency => l_currency_code  -- loan currency
2819                                                     ,p_to_currency   => l_ledger_details.CURRENCY_CODE  -- set of books currency
2820                                                     ,p_exchange_type => l_exchange_rate_type
2821                                                     ,p_exchange_date => l_exchange_date
2822                                                     ,p_exchange_rate => l_exchange_rate);
2823     else
2824         l_return := l_distribution_rec.distribution_amount;
2825     end if;
2826 
2827     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'accounted amount = ' || l_return);
2828     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
2829 
2830     return l_return;
2831 
2832 end calculateDistributionAmount;
2833 
2834 
2835 function calculateDistAmount(p_distribution_id in number
2836                             ,p_accounted_flag  in varchar2) return varchar2
2837 is
2838 
2839     l_api_name              varchar2(50);
2840     l_return                varchar2(100);
2841     l_currency              varchar2(10);
2842     l_char                  varchar2(25);
2843     l_amount                number;
2844 
2845     cursor c_currency1(p_distribution_id number) is
2846     select lnh.loan_currency
2847       from lns_loan_headers lnh
2848            ,lns_distributions lnd
2849      where lnh.loan_id = lnd.loan_id
2850        and lnd.distribution_id = p_distribution_id;
2851 
2852     cursor c_currency2 is
2853     SELECT sb.currency_code
2854       FROM lns_system_options so,
2855            gl_sets_of_books sb
2856      WHERE sb.set_of_books_id = so.set_of_books_id;
2857 
2858 begin
2859     l_api_name := 'calculateDistAmount';
2860     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
2861     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'DIST_ID = ' || p_distribution_id);
2862 
2863     if p_accounted_flag = 'Y' then
2864         open c_currency2;
2865         fetch c_currency2 into l_currency;
2866         close c_currency2;
2867     else
2868         open c_currency1(p_distribution_id);
2869         fetch c_currency1 into l_currency;
2870         close c_currency1;
2871     end if;
2872 
2873     l_amount := lns_distributions_pub.calculateDistributionAmount(p_distribution_id => p_distribution_id
2874                                                                  ,p_accounted_flag  => p_accounted_flag);
2875     l_char := to_char(l_amount,  fnd_currency.safe_get_format_mask(l_currency,25));
2876 
2877     l_return := l_char || ' ' || l_currency;
2878     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'returned amount = ' || l_return);
2879     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
2880 
2881     return l_return;
2882 end;
2883 
2884 /*========================================================================
2885  | PUBLIC FUNCTION getFlexSegmentNumber
2886  |
2887  | DESCRIPTION
2888  |      returns the segmentNumber for a given segment attribute type
2889  |
2890  | PSEUDO CODE/LOGIC
2891  |
2892  | PARAMETERS
2893  |           p_segment_attribute_type = 'GL_BALANCING' 'GL_ACCOUNT' etc
2894  | Return value: value_set_id
2895  |
2896  | Source Tables: fnd_id_flex_segments s, fnd_segment_attribute_values sav,
2897  |                fnd_segment_attribute_types sat
2898  |                lns_system_options lso
2899  |                gl_sets_of_books gl
2900  |
2901  | Target Tables: NA
2902  |
2903  | KNOWN ISSUES
2904  |
2905  | NOTES
2906  |
2907  |
2908  | MODIFICATION HISTORY
2909  | Date                  Author            Description of Changes
2910  | 10/06/05 2:48:PM       raverma           Created
2911  *=======================================================================*/
2912 function getFlexSegmentNumber(p_flex_code in varchar2
2913                              ,p_application_id in number
2914 														 ,p_segment_attribute_type in varchar2) return number
2915 
2916 is
2917 	l_flex_seg_num number;
2918 
2919 	cursor c_segmentNumber(p_flex_code varchar2, p_application_id number, p_segment_attribute_type varchar2)
2920 	is
2921 		SELECT s.segment_num
2922 		  FROM fnd_id_flex_segments s
2923 			   , fnd_segment_attribute_values sav
2924 				 , fnd_segment_attribute_types sat
2925 			   , lns_system_options lso
2926 				 , gl_ledgers gl
2927 		  WHERE s.application_id = p_application_id
2928 		  and lso.set_of_books_id = gl.ledger_id
2929 		  AND s.id_flex_code = p_flex_code
2930 		  AND s.id_flex_num = gl.chart_of_accounts_id
2931 		  AND s.enabled_flag = 'Y'
2932 		  AND s.application_column_name = sav.application_column_name
2933 		  AND sav.application_id = p_application_id
2934 		  AND sav.id_flex_code = p_flex_code
2935 		  AND sav.id_flex_num = gl.chart_of_accounts_id
2936 		  AND sav.attribute_value = 'Y'
2937 		  AND sav.segment_attribute_type = sat.segment_attribute_type
2938 		  AND sat.application_id = p_application_id
2939 		  AND sat.id_flex_code = p_flex_code
2940 		  AND sat.unique_flag = 'Y'
2941       and sat.segment_attribute_type = p_segment_attribute_type;
2942 
2943 begin
2944 
2945 	l_flex_seg_num := -1;
2946 
2947 	open c_segmentNumber(p_flex_code , p_application_id , p_segment_attribute_type );
2948 	fetch c_segmentNumber into l_flex_seg_num;
2949 	close c_segmentNumber;
2950     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_flex_seg_num = ' || l_flex_seg_num);
2951 
2952 	return l_flex_seg_num;
2953 
2954 end getFlexSegmentNumber;
2955 
2956 /*========================================================================
2957  | PUBLIC FUNCTION getValueSetID
2958  |
2959  | DESCRIPTION
2960  |      returns a valueSetID for a given segment attribute
2961  |
2962  | PSEUDO CODE/LOGIC
2963  |
2964  | PARAMETERS
2965  |           p_segment_attribute_type = 'GL_BALANCING' 'GL_ACCOUNT' etc
2966  | Return value: value_set_id
2967  |
2968  | Source Tables: fnd_id_flex_segments s, fnd_segment_attribute_values sav,
2969  |                fnd_segment_attribute_types sat
2970  |                lns_system_options lso
2971  |                gl_sets_of_books gl
2972  |
2973  | Target Tables: NA
2974  |
2975  | KNOWN ISSUES
2976  |
2977  | NOTES
2978  |
2979  |
2980  | MODIFICATION HISTORY
2981  | Date                  Author            Description of Changes
2982  | 06/15/04 2:48:PM       raverma           Created
2983  |
2984  *=======================================================================*/
2985 function getValueSetID(p_segment_attribute_type in varchar) return number
2986 is
2987     l_value_set_id number;
2988 
2989     cursor c_valueSetID(p_segment_attribute_type varchar2) is
2990 		 SELECT s.flex_value_set_id
2991       FROM fnd_id_flex_segments s
2992       ,fnd_segment_attribute_values sav
2993       ,fnd_segment_attribute_types sat
2994 		  ,lns_system_options lso
2995 		  ,gl_ledgers gl
2996 		  WHERE s.application_id = 101
2997 		  and lso.set_of_books_id = gl.ledger_id
2998 		  AND s.id_flex_code = 'GL#'
2999 		  AND s.id_flex_num = gl.chart_of_accounts_id
3000 		  AND s.enabled_flag = 'Y'
3001 		  AND s.application_column_name = sav.application_column_name
3002 		  AND sav.application_id = 101
3003 		  AND sav.id_flex_code = 'GL#'
3004 		  AND sav.id_flex_num = gl.chart_of_accounts_id
3005 		  AND sav.attribute_value = 'Y'
3006 		  AND sav.segment_attribute_type = sat.segment_attribute_type
3007 		  AND sat.application_id = 101
3008 		  AND sat.id_flex_code = 'GL#'
3009 		  AND sat.unique_flag = 'Y'
3010 		  AND sat.segment_attribute_type = p_segment_attribute_type;
3011 
3012 begin
3013     open c_valueSetID(p_segment_attribute_type);
3014 	fetch c_valueSetID	into l_value_set_id;
3015 	close c_valueSetID;
3016     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_value_set_id = ' || l_value_set_id);
3017 
3018     return l_value_set_id;
3019 
3020 end getValueSetID;
3021 
3022 /*=========================================================================
3023  | PUBLIC procedure validateAccounting
3024  |
3025  | DESCRIPTION
3026  |        validates all accounting for a given loan
3027  |
3028  | PSEUDO CODE/LOGIC
3029  |
3030  | PARAMETERS
3031  |           p_loan_id => id of loan
3032  |
3033  | Return value: standard api values
3034  |
3035  | Source Tables: lns_Distritbutions
3036  |
3037  | Target Tables: NA
3038  |
3039  | KNOWN ISSUES
3040  |  E. The code combinations distribution percentages for each Loans Receivable
3041  |  and corresponding Loans Clearing account must be equal
3042  |
3043  | NOTES
3044  |
3045  |
3046  | MODIFICATION HISTORY
3047  | Date                  Author            Description of Changes
3048  | 06/28/04 2:48:PM       raverma           Created
3049  |
3050  *=======================================================================*/
3051 procedure validateAccounting(p_loan_id                    in  number
3052                             ,p_init_msg_list              IN VARCHAR2
3053                             ,x_return_status              OUT NOCOPY VARCHAR2
3054                             ,x_msg_count                  OUT NOCOPY NUMBER
3055                             ,x_msg_data                   OUT NOCOPY VARCHAR2)
3056 is
3057 
3058     --l_loan_liability_fund   LNS_DISTRIBUTIONS_PUB.distribution_tbl;
3059     l_loan_clearing_fund    LNS_DISTRIBUTIONS_PUB.distribution_tbl;
3060     l_loan_receivables_orig LNS_DISTRIBUTIONS_PUB.distribution_tbl;
3061     l_loan_clearing_orig    LNS_DISTRIBUTIONS_PUB.distribution_tbl;
3062     l_loan_receivables_bill LNS_DISTRIBUTIONS_PUB.distribution_tbl;
3063     l_prin_receivables_bill LNS_DISTRIBUTIONS_PUB.distribution_tbl;
3064     l_int_receivables_bill  LNS_DISTRIBUTIONS_PUB.distribution_tbl;
3065     l_int_income_bill       LNS_DISTRIBUTIONS_PUB.distribution_tbl;
3066 
3067     l_dist_percent_rec_orig   number;
3068     l_dist_percent_rec_bill   number;
3069     l_dist_percent_clear_orig number;
3070     l_dist_percent_int_income number;
3071     l_loan_class              varchar2(30);
3072     l_loan_status	      varchar2(30);
3073     l_num_receivables_ers     number;
3074     l_num_receivables_acc     number;
3075     l_index		      NUMBER;
3076 
3077     l_distribution_id           number;
3078     l_line_type                 varchar2(30);
3079     l_account_name              varchar2(30);
3080     l_account_type              varchar2(30);
3081     l_code_combination_id       number;
3082     l_distribution_percent      number;
3083     l_distribution_amount       number;
3084     l_distribution_type         varchar2(30);
3085     l_event_id			NUMBER;
3086 
3087 
3088     l_api_name              varchar2(30);
3089 
3090     cursor c_loan_class(p_loan_id number) is
3091     select loan_class_code, loan_status
3092         from lns_loan_headers_all
3093     where loan_id = p_loan_id;
3094 
3095     CURSOR c_get_prin_distr(C_LOAN_ID number) IS
3096       SELECT dist.distribution_id
3097              ,dist.line_type
3098              ,dist.account_name
3099              ,dist.account_type
3100              ,dist.code_combination_id
3101              ,dist.distribution_percent
3102              ,dist.distribution_amount
3103              ,dist.distribution_type
3104 	     ,dist.event_id
3105        from lns_distributions dist
3106        where dist.loan_id = C_LOAN_ID
3107          and dist.account_type = 'CR'
3108          and dist.account_name = 'LOAN_RECEIVABLE'
3109          and dist.line_type = 'PRIN'
3110          and dist.distribution_type = 'BILLING'
3111          and dist.distribution_percent > 0
3112          and nvl(dist.loan_line_id, -1) =
3113                 nvl((select max(loan_line_id)
3114                 from lns_loan_lines
3115                 where status = 'APPROVED'
3116                 and LOAN_ID = C_LOAN_ID
3117                 and original_flag = 'N'
3118                 and trunc(adjustment_date) <= trunc(sysdate)), -1)
3119         order by dist.distribution_id;
3120 
3121 
3122 begin
3123 
3124     l_api_name := 'validateAccounting1';
3125     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
3126 
3127     -- Initialize message list IF p_init_msg_list is set to TRUE.
3128     IF FND_API.to_Boolean( p_init_msg_list ) THEN
3129         FND_MSG_PUB.initialize;
3130     END IF;
3131 
3132     -- Initialize API return status to SUCCESS
3133     x_return_status := FND_API.G_RET_STS_SUCCESS;
3134 
3135     l_dist_percent_rec_orig   := 0;
3136     l_dist_percent_rec_bill   := 0;
3137     l_dist_percent_clear_orig := 0;
3138     l_dist_percent_int_income := 0;
3139 
3140     open c_loan_class(p_loan_id);
3141         fetch c_loan_class into l_loan_class, l_loan_status;
3142     close c_loan_class;
3143 
3144     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_class = ' || l_loan_class);
3145     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_status = ' || l_loan_status);
3146     -- get the distributions details
3147     /*
3148     l_loan_liability_fund := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
3149                                                                     ,p_account_type      => 'DR'
3150                                                                     ,p_account_name      => 'LOAN_LIABILITY'
3151                                                                     ,p_line_type         => 'ORIG'
3152                                                                     ,p_distribution_type => 'FUNDING');
3153         */
3154     if l_loan_class = 'ERS' then
3155 
3156         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 1...');
3157         l_loan_clearing_orig    := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
3158                                                                             ,p_account_type      => 'CR'
3159                                                                             ,p_account_name      => 'LOAN_CLEARING'
3160                                                                             ,p_line_type         => 'CLEAR'
3161                                                                             ,p_distribution_type => 'ORIGINATION');
3162     elsif l_loan_class = 'DIRECT' then
3163 
3164         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 2...');
3165         l_loan_clearing_orig := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
3166                                                                         ,p_account_type      => 'CR'
3167                                                                         ,p_account_name      => 'LOAN_PAYABLE'
3168                                                                         ,p_line_type         => 'CLEAR'
3169                                                                         ,p_distribution_type => 'ORIGINATION');
3170     end if;
3171 
3172     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 3...');
3173     l_loan_receivables_orig := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
3174                                                                         ,p_account_type      => 'DR'
3175                                                                         ,p_account_name      => 'LOAN_RECEIVABLE'
3176                                                                         ,p_line_type         => 'ORIG'
3177                                                                         ,p_distribution_type => 'ORIGINATION');
3178 
3179     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 4...');
3180     IF ((l_loan_class = 'ERS') AND (l_loan_status NOT IN ('INCOMPLETE', 'PENDING', 'APPROVED')) ) THEN
3181 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'FETCH ERS ACTIVE distributions');
3182 	l_index       := 0;
3183         OPEN c_get_prin_distr(p_loan_id);
3184         LOOP
3185             FETCH c_get_prin_distr INTO
3186                 l_distribution_id
3187                 ,l_line_type
3188                 ,l_account_name
3189                 ,l_account_type
3190                 ,l_code_combination_id
3191                 ,l_distribution_percent
3192                 ,l_distribution_amount
3193                 ,l_distribution_type
3194 		,l_event_id;
3195             EXIT WHEN c_get_prin_distr%NOTFOUND;
3196 
3197             l_index := l_index + 1;
3198             l_loan_receivables_bill(l_index).distribution_id        := l_distribution_id;
3199             l_loan_receivables_bill(l_index).loan_id                := p_loan_id;
3200             l_loan_receivables_bill(l_index).line_type              := l_line_type;
3201             l_loan_receivables_bill(l_index).account_name           := l_account_name;
3202             l_loan_receivables_bill(l_index).account_type           := l_account_type;
3203             l_loan_receivables_bill(l_index).code_combination_id    := l_code_combination_id;
3204             l_loan_receivables_bill(l_index).distribution_percent   := l_distribution_percent;
3205             l_loan_receivables_bill(l_index).distribution_amount    := l_distribution_amount;
3206             l_loan_receivables_bill(l_index).distribution_type      := l_distribution_type;
3207 	    l_loan_receivables_bill(l_index).event_id		    := l_event_id;
3208 
3209         END LOOP;
3210         CLOSE c_get_prin_distr;
3211 
3212         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Fetched ' || l_loan_receivables_bill.count || ' records');
3213 
3214     ELSE
3215     	l_loan_receivables_bill  := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
3216                                                                         ,p_account_type      => 'CR'
3217                                                                         ,p_account_name      => 'LOAN_RECEIVABLE'
3218                                                                         ,p_line_type         => 'PRIN'
3219                                                                         ,p_distribution_type => 'BILLING');
3220     END IF;
3221 
3222     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 5...');
3223     l_prin_receivables_bill := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
3224                                                                     ,p_account_type      => 'DR'
3225                                                                     ,p_account_name      => 'PRINCIPAL_RECEIVABLE'
3226                                                                     ,p_line_type         => 'PRIN'
3227                                                                     ,p_distribution_type => 'BILLING');
3228 
3229     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 6...');
3230     l_int_receivables_bill := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
3231                                                                     ,p_account_type      => 'DR'
3232                                                                     ,p_account_name      => 'INTEREST_RECEIVABLE'
3233                                                                     ,p_line_type         => 'INT'
3234                                                                     ,p_distribution_type => 'BILLING');
3235 
3236     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 7...');
3237     l_int_income_bill := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
3238                                                                 ,p_account_type      => 'CR'
3239                                                                 ,p_account_name      => 'INTEREST_INCOME'
3240                                                                 ,p_line_type         => 'INT'
3241                                                                 ,p_distribution_type => 'BILLING');
3242 
3243     if l_loan_class = 'ERS' then
3244 
3245         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'ERS VALIDATION');
3246 
3247         /*
3248         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'getting number of receivables on ers loan');
3249         open c_num_receivables_ers(p_loan_id);
3250         fetch c_num_receivables_ers into l_num_receivables_ers;
3251         close c_num_receivables_ers;
3252         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'num is: ' || l_num_receivables_ers);
3253 
3254         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'getting number of receivables ACCOUNTED');
3255         open c_num_receivables_acc(p_loan_id);
3256         fetch c_num_receivables_acc into l_num_receivables_acc;
3257         close c_num_receivables_acc;
3258         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'num is: ' || l_num_receivables_acc);
3259 
3260         if l_num_receivables_acc <> l_num_receivables_ers then
3261         FND_MESSAGE.Set_Name('LNS', 'LNS_AR_RECEIVABLES_UNACC');
3262         FND_MSG_PUB.Add;
3263         RAISE FND_API.G_EXC_ERROR;
3264         end if;
3265         */
3266 
3267 
3268 	-- Bug#7406404 - Once the loan becomes active, and after adding 'Additonal Receivables', then Prin Loan Receivable
3269 	-- new distributions might add and so these distributions can be different from Origination LoanReceivable
3270 	-- distributions. So once the loan becomes active, no need to compare Origination and Principal Loan Receivable dist.
3271 	IF l_loan_status IN ('INCOMPLETE', 'PENDING', 'APPROVED') THEN
3272 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'comparing origination receivables to billing receivables count');
3273 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan recivables origination Count = ' || l_loan_receivables_orig.count );
3274 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan recivables billing Count = ' || l_loan_receivables_bill.count);
3275 		if l_loan_receivables_orig.count <> l_loan_receivables_bill.count then
3276 		FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_INVALID_RECEIVABLES');
3277 		FND_MSG_PUB.Add;
3278 		LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3279 		RAISE FND_API.G_EXC_ERROR;
3280 		end if;
3281 
3282 		-- B. The account code combinations for the Loans Receivable accounts within
3283 		-- Origination must be the same as the account code combinations for the Loans
3284 		-- Receivable accounts within Billing
3285 		for j in 1..l_loan_receivables_orig.count loop
3286 
3287 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'comparing origination receivables to billing receivables cc_ids');
3288 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan recivables origination cc_id = ' || l_loan_receivables_orig(j).code_combination_id );
3289 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan recivables billing cc_id = ' || l_loan_receivables_bill(j).code_combination_id);
3290 		if l_loan_receivables_orig(j).code_combination_id <> l_loan_receivables_bill(j).code_combination_id  then
3291 			FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_LOAN_REC_CCIDS_UNMATCH');
3292 			FND_MSG_PUB.Add;
3293 			LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3294 			RAISE FND_API.G_EXC_ERROR;
3295 		end if;
3296 
3297 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking for duplicate IDs');
3298 		if j < l_loan_receivables_orig.count then
3299 			if (l_loan_receivables_orig(j).code_combination_id = l_loan_receivables_orig(j+1).code_combination_id)
3300 			then
3301 			logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'found duplicate IDs');
3302 			FND_MESSAGE.Set_Name('LNS', 'LNS_UNIQUE_CC_IDS');
3303 			FND_MSG_PUB.Add;
3304 			LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3305 			RAISE FND_API.G_EXC_ERROR;
3306 			end if;
3307 		end if;
3308 
3309 		-- F. The code combinations distribution percentages for each Loans Receivable
3310 		-- within Origination must equal the distribution percentage for each Loans
3311 		-- Receivable within Billing
3312 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'comparing origination receivables to billing receivables percentages');
3313 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan recivables origination percent = ' || l_loan_receivables_orig(j).distribution_percent );
3314 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan recivables billing percent = ' || l_loan_receivables_bill(j).distribution_percent);
3315 		if l_loan_receivables_orig(j).distribution_percent <> l_loan_receivables_bill(j).distribution_percent then
3316 			FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_LOAN_REC_PER_UNMATCH');
3317 			FND_MSG_PUB.Add;
3318 			LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3319 			RAISE FND_API.G_EXC_ERROR;
3320 		end if;
3321 
3322 		l_dist_percent_rec_orig   := l_dist_percent_rec_orig + l_loan_receivables_orig(j).distribution_percent;
3323 		l_dist_percent_rec_bill   := l_dist_percent_rec_bill + l_loan_receivables_bill(j).distribution_percent;
3324 		--l_dist_percent_clear_orig := l_dist_percent_clear_orig + l_loan_clearing_orig(j).distribution_percent;
3325 
3326 		end loop;
3327 
3328 	ELSE    -- ELSE of l_loan_status IN ('INCOMPLETE', 'PENDING', 'APPROVED') THEN
3329 		-- The dist percent must add to 100% of each account type
3330 		/*
3331 		for j in 1..l_loan_receivables_orig.count loop
3332 		    l_dist_percent_rec_orig   := l_dist_percent_rec_orig + l_loan_receivables_orig(j).distribution_percent;
3333 		end loop;
3334 	       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Origination LoanRec TotPercent: ' || l_dist_percent_rec_orig);
3335 		*/
3336 
3337 		for j in 1..l_loan_receivables_bill.count loop
3338 		    l_dist_percent_rec_bill   := l_dist_percent_rec_bill + l_loan_receivables_bill(j).distribution_percent;
3339 		end loop;
3340 
3341 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking ERS Prin Billing receivables total percentages');
3342     		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Prin Billing loan recivables total percent: ' || l_dist_percent_rec_bill);
3343 		if l_dist_percent_rec_bill <> 100 then
3344 			FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_BILL_REC_PER_INVALID');
3345 			FND_MSG_PUB.Add;
3346 			RAISE FND_API.G_EXC_ERROR;
3347 		end if;
3348 
3349 
3350 	END IF;
3351 
3352 	-- Bug#7406404 - Once loan becomes Active, no need to validate. B'coz for ERS loan, after adding additionalReceivable
3353 	-- there would be more no. of clear records for each receivable
3354 	IF (l_loan_status IN ('INCOMPLETE', 'PENDING', 'APPROVED')) THEN
3355 
3356 		-- Bug#10266158  - If the no. of Receivables and no. of Clear records are different then
3357 		-- check duplicate Id's separately for receivables and clear records
3358 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking for duplicate IDs for CLEAR records');
3359 		for p in 1..l_loan_clearing_orig.count loop
3360 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan clear origination cc_id at '||p||' = ' || l_loan_clearing_orig(p).code_combination_id );
3361 		if p < l_loan_clearing_orig.count then
3362 			if  (l_loan_clearing_orig(p).code_combination_id = l_loan_clearing_orig(p+1).code_combination_id) then
3363 			logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'found duplicate IDs');
3364 			FND_MESSAGE.Set_Name('LNS', 'LNS_UNIQUE_CC_IDS');
3365 			FND_MSG_PUB.Add;
3366 			LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3367 			RAISE FND_API.G_EXC_ERROR;
3368 			end if;
3369 		end if;
3370 		l_dist_percent_clear_orig := l_dist_percent_clear_orig + l_loan_clearing_orig(p).distribution_percent;
3371 		end loop;
3372 
3373 
3374 
3375 		-- C. The distribution percentage for the Loans Receivable accounts in both
3376 		-- Origination and Billing must add to 100%
3377 
3378 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking origination receivables total percentages');
3379 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan recivables total percent = ' || l_dist_percent_rec_orig);
3380 		if l_dist_percent_rec_orig <> 100 then
3381 		FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_ORIG_REC_PER_INVALID');
3382 		FND_MSG_PUB.Add;
3383 		LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3384 		RAISE FND_API.G_EXC_ERROR;
3385 		end if;
3386 
3387 		-- D. The distribution percentage for the Loans Clearing accounts in Origination must add to 100%
3388 
3389 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking origination clearing total percentages');
3390 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan clearing total percent = ' || l_dist_percent_clear_orig);
3391 		if l_dist_percent_clear_orig <> 100 then
3392 		FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_ORIG_CLR_PER_INVALID');
3393 		FND_MSG_PUB.Add;
3394 		LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3395 		RAISE FND_API.G_EXC_ERROR;
3396 		end if;
3397 	END IF;  -- IF (l_loan_status IN ('INCOMPLETE', 'PENDING', 'APPROVED'))
3398 
3399     end if;  -- if loan_class = 'ERS'
3400 
3401         /*
3402     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking billing receivables total percentages');
3403     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan recivables total percent: ' || l_dist_percent_rec_bill);
3404     if l_dist_percent_rec_bill <> 100 then
3405         FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_BILL_REC_PER_INVALID');
3406         FND_MSG_PUB.Add;
3407         RAISE FND_API.G_EXC_ERROR;
3408     end if;
3409 
3410 
3411     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking origination clearing  total percentages');
3412     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan clearing total percent = ' || l_dist_percent_clear_orig);
3413 
3414 
3415     if l_dist_percent_clear_orig <> 100 then
3416         FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_ORIG_CLR_PER_INVALID');
3417         FND_MSG_PUB.Add;
3418         RAISE FND_API.G_EXC_ERROR;
3419     end if;
3420     */
3421     --  G. In the current release of 11i, there must be only one Principal Receivable
3422     --  account
3423     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking principal receivables count');
3424     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'principal receivables count = ' || l_prin_receivables_bill.count);
3425     if l_prin_receivables_bill.count <> 1 then
3426         FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_MULT_PRIN_RECEIVABLE');
3427         FND_MSG_PUB.Add;
3428         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3429         RAISE FND_API.G_EXC_ERROR;
3430     end if;
3431 
3432     --  H. In the current release of 11i, there must be only one Interest Receivable
3433     --  account
3434     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking Interest receivables count');
3435     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Interest receivables count = ' || l_int_receivables_bill.count);
3436     if l_int_receivables_bill.count <> 1 then
3437         FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_MULT_INT_RECEIVABLE');
3438         FND_MSG_PUB.Add;
3439         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3440         RAISE FND_API.G_EXC_ERROR;
3441     end if;
3442 
3443     --  I. There may be multiple Interest Income accounts
3444     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking Interest Income count');
3445     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Interest Income count = ' || l_int_income_bill.count);
3446     if l_int_income_bill.count < 1 then
3447         FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_NO_INTEREST_INCOME');
3448         FND_MSG_PUB.Add;
3449         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3450         RAISE FND_API.G_EXC_ERROR;
3451     end if;
3452 
3453     --  J. The distribution percentages for Interest Income must add to 100%
3454     for j in 1..l_int_income_bill.count loop
3455         l_dist_percent_int_income := l_dist_percent_int_income + l_int_income_bill(j).distribution_percent;
3456     end loop;
3457 
3458     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking Interest Income percentage');
3459     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Interest Income percentage = ' || l_dist_percent_int_income);
3460     if l_dist_percent_int_income <> 100 then
3461         FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_INT_INCOME_PER_INVALID');
3462         FND_MSG_PUB.Add;
3463         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
3464         RAISE FND_API.G_EXC_ERROR;
3465     end if;
3466 
3467     FND_MSG_PUB.Count_And_Get(p_count => x_msg_count
3468                             ,p_data  => x_msg_data);
3469 
3470     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
3471 
3472 Exception
3473     WHEN FND_API.G_EXC_ERROR THEN
3474         x_return_status := FND_API.G_RET_STS_ERROR;
3475         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count
3476                                 ,p_data  => x_msg_data);
3477         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
3478 
3479     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
3480         x_return_status := FND_API.G_RET_STS_ERROR;
3481         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count
3482                                 ,p_data  => x_msg_data);
3483         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
3484 
3485     WHEN OTHERS THEN
3486         x_return_status := FND_API.G_RET_STS_ERROR;
3487         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count
3488                                 ,p_data  => x_msg_data);
3489         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
3490 
3491 end validateAccounting;
3492 
3493 
3494 /*========================================================================
3495  | PUBLIC procedure validateDefaultAccounting
3496  |
3497  | DESCRIPTION
3498  |        validates all accounting for a given loan loan_class and type
3499  |
3500  | PSEUDO CODE/LOGIC
3501  |
3502  | PARAMETERS
3503  |           p_loan_id => id of loan
3504 ||
3505  | Return value: standard api values
3506  |
3507  | Source Tables: lns_Distritbutions
3508  |
3509  | Target Tables: NA
3510  |
3511  | KNOWN ISSUES
3512     E. The code combinations distribution percentages for each Loans Receivable
3513     and corresponding Loans Clearing account must be equal
3514  |
3515  | NOTES
3516  |
3517  |
3518  | MODIFICATION HISTORY
3519  | Date                  Author            Description of Changes
3520  | 06/28/04 2:48:PM       raverma           Created
3521  | 06/29/04               raverma           added MFAR checking
3522 || 08/04/05               raverma           deprecate
3523  *=======================================================================*/
3524 procedure validateDefaultAccounting(p_loan_class                 in varchar2
3525                                    ,p_loan_type_id               in number
3526                                    ,p_init_msg_list              IN VARCHAR2
3527                                    ,x_return_status              OUT NOCOPY VARCHAR2
3528                                    ,x_msg_count                  OUT NOCOPY NUMBER
3529                                    ,x_msg_data                   OUT NOCOPY VARCHAR2)
3530 is
3531 begin
3532 
3533    -- Initialize API return status to SUCCESS
3534    x_return_status := FND_API.G_RET_STS_SUCCESS;
3535 
3536 end validateDefaultAccounting;
3537 
3538 /*========================================================================
3539  | PUBLIC procedure validateLoanLines
3540  |
3541  | DESCRIPTION
3542  |        verifies that the loan lines are either ALL MFAR or ALL NON-MFAR
3543  |
3544  | PSEUDO CODE/LOGIC
3545  |
3546  | PARAMETERS
3547  |           p_loan_id => id of loan
3548 ||
3549  | Return value: standard api values
3550  |
3551  | Source Tables: lns_Distritbutions
3552  |
3553  | Target Tables: NA
3554  |
3555  | KNOWN ISSUES
3556     E. The code combinations distribution percentages for each Loans Receivable
3557     and corresponding Loans Clearing account must be equal
3558  |
3559  | NOTES
3560  |
3561  |
3562  | MODIFICATION HISTORY
3563  | Date                  Author            Description of Changes
3564  | 12/20/04 2:48:PM       raverma           Created
3565  *=======================================================================*/
3566 procedure validateLoanLines(p_init_msg_list         IN VARCHAR2
3567                            ,p_loan_id               IN number
3568                            ,x_MFAR                  OUT NOCOPY boolean
3569                            ,x_return_status         OUT NOCOPY VARCHAR2
3570                            ,x_msg_count             OUT NOCOPY NUMBER
3571                            ,x_msg_data              OUT NOCOPY VARCHAR2)
3572 is
3573     l_api_name                      varchar2(25);
3574     l_return_status                 VARCHAR2(1);
3575     l_msg_count                     NUMBER;
3576     l_msg_data                      VARCHAR2(32767);
3577     l_trx_type_id                   number;
3578     l_psa_trx_type_id               number;
3579     l_mfar                          boolean;
3580     l_lines_count                   number;
3581     i                               number;
3582     l_multifund                     number;
3583 
3584     --find out if there is more than one line
3585     cursor c_loan_lines(p_loan_id number) is
3586     select count(1)
3587      from lns_loan_lines
3588     where loan_id = p_loan_id
3589       and reference_type = 'RECEIVABLE'
3590       and end_date is null;
3591 
3592     -- for loans with more than one line
3593     cursor c_validate_MFAR (p_loan_id number) is
3594     select ra.cust_trx_type_id, nvl(psa.psa_trx_type_id,-1)
3595       from lns_loan_lines  lines
3596           ,ra_customer_trx ra
3597           ,psa_trx_types_all psa
3598      where ra.customer_trx_id = lines.reference_id
3599        and psa.psa_trx_type_id (+)= ra.cust_trx_type_id
3600        and lines.reference_type = 'RECEIVABLE'
3601        and lines.end_date is null
3602        and lines.loan_id = p_loan_id
3603        group by ra.cust_trx_type_id, psa.psa_trx_type_id;
3604 
3605      -- cursor to identify MFAR trx 1 = MFAR, 0 <> MFAR
3606      -- assumes only one line is on the loan
3607      cursor c_multiFundTrx(p_loan_id in number)
3608      is
3609         select nvl(1,0)
3610           from ra_customer_trx ra
3611               ,psa_trx_types_all psa
3612               ,lns_loan_lines lines
3613          where ra.CUST_TRX_TYPE_ID = psa.psa_trx_type_id
3614            and ra.customer_trx_id = lines.reference_id
3615            and lines.end_date is null
3616            and lines.reference_type = 'RECEIVABLE'
3617            and lines.loan_id = p_loan_id
3618       group by lines.loan_id;
3619 
3620 begin
3621 
3622    l_api_name           := 'validateLoanLines';
3623    logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
3624 
3625    -- Standard Start of API savepoint
3626    SAVEPOINT validateLoanLines;
3627 
3628    -- Initialize message list IF p_init_msg_list is set to TRUE.
3629    IF FND_API.to_Boolean(p_init_msg_list) THEN
3630        FND_MSG_PUB.initialize;
3631    END IF;
3632 
3633    -- Initialize API return status to SUCCESS
3634    x_return_status := FND_API.G_RET_STS_SUCCESS;
3635 
3636    -- ---------------------------------------------------------------------
3637    -- Api body
3638    -- ---------------------------------------------------------------------
3639    l_lines_count := 0;
3640    i             := 0;
3641 
3642     open c_loan_lines(p_loan_id);
3643     fetch c_loan_lines into l_lines_count;
3644     close c_loan_lines;
3645 
3646     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'lines count is ' || l_lines_count);
3647     -- check if ALL are MFAR or all are NOT MFAR only if there is more
3648     --  than 1 line on the loan
3649     if l_lines_count > 1 then
3650 
3651         open c_validate_MFAR(p_loan_id);
3652         LOOP
3653 
3654             i := i + 1;
3655             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'processing ' || i || ' loan line');
3656             fetch c_validate_MFAR
3657             into l_trx_type_id
3658                 ,l_psa_trx_type_id;
3659 
3660             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'trx type ' || l_trx_type_id);
3661             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'psa trx type '|| l_psa_trx_type_id);
3662 
3663             exit when c_validate_MFAR%NOTFOUND;
3664 
3665             if i <> 1 then
3666                 if l_mfar then
3667                     if l_psa_trx_type_id = -1 then
3668                         RAISE FND_API.G_EXC_ERROR;
3669                     end if;
3670                 else
3671                     if l_psa_trx_type_id <> -1 then
3672                         RAISE FND_API.G_EXC_ERROR;
3673                     end if;
3674                 end if;
3675             else
3676                 if l_psa_trx_type_id = -1 then
3677                     -- the first line on the loan is NOT MFAR
3678                     -- all subsequent lines SHOULD be MFAR
3679                     l_mfar := false;
3680                     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'NON-MFAR');
3681                 else
3682                     l_mfar := true;
3683                     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'MFAR');
3684                 end if;
3685 
3686             end if;
3687         end loop;
3688 
3689     else
3690         -- we only have 1 line on the loan...verify is it is MFAR or not
3691         -- check to see if trx_type is refered to in psa_trx_type
3692         -- if so this is a multi-fund receivable
3693         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking for MFAR');
3694         begin
3695 
3696             open c_multiFundTrx(p_loan_id) ;
3697             fetch c_multiFundTrx into l_multifund;
3698             close c_multiFundTrx;
3699 
3700         exception
3701             when others then
3702                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'no rows found');
3703                  l_multifund := 0;
3704         end;
3705 
3706         if l_multifund = 1 then
3707             l_mfar := true;
3708         else
3709             l_mfar := false;
3710         end if;
3711 
3712     end if;
3713 
3714     -- this will be needed by defaultDistributions
3715     x_mfar := l_mfar;
3716    --logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, 'sql ' || vPLSQL);
3717 
3718    -- ---------------------------------------------------------------------
3719    -- End of API body
3720    -- ---------------------------------------------------------------------
3721 
3722    FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
3723 
3724    logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
3725 
3726 EXCEPTION
3727     WHEN FND_API.G_EXC_ERROR THEN
3728             ROLLBACK TO validateLoanLines;
3729             x_return_status := FND_API.G_RET_STS_ERROR;
3730             x_msg_count := l_msg_count;
3731             x_msg_data  := l_msg_data;
3732             FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
3733             logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
3734 
3735         WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
3736             ROLLBACK TO validateLoanLines;
3737             x_return_status := FND_API.G_RET_STS_ERROR;
3738             x_msg_count := l_msg_count;
3739             x_msg_data  := l_msg_data;
3740             FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
3741             logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
3742 
3743     WHEN OTHERS THEN
3744             ROLLBACK TO validateLoanLines;
3745             x_return_status := FND_API.G_RET_STS_ERROR;
3746             x_msg_count := l_msg_count;
3747             x_msg_data  := l_msg_data;
3748             FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
3749             logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
3750 
3751 end validateLoanLines;
3752 
3753 
3754 procedure create_DisbursementDistribs(p_api_version           IN NUMBER
3755 			                               ,p_init_msg_list         IN VARCHAR2
3756 			                               ,p_commit                IN VARCHAR2
3757 			                               ,p_loan_id               IN NUMBER
3758 						       ,p_disb_header_id        IN NUMBER
3759 					               ,p_loan_amount_adj_id    IN NUMBER     DEFAULT NULL
3760 						       ,p_activity_type         IN VARCHAR2   DEFAULT NULL
3761 						       ,p_project_id       IN NUMBER   DEFAULT NULL
3762                                            ,p_award_id         IN NUMBER   DEFAULT NULL
3763                                            ,p_task_id          IN NUMBER   DEFAULT NULL
3764                                            ,p_expenditure_type IN VARCHAR2   DEFAULT NULL
3765                                            ,p_EXPENDITURE_ITEM_DATE IN DATE   DEFAULT NULL
3766 			                               ,x_return_status         OUT NOCOPY VARCHAR2
3767 			                               ,x_msg_count             OUT NOCOPY NUMBER
3768 			                               ,x_msg_data              OUT NOCOPY VARCHAR2)
3769 
3770 is
3771     l_api_name                 varchar2(30);
3772     l_msg_count                NUMBER;
3773     l_msg_data                 VARCHAR2(2000);
3774     l_return_Status            VARCHAR2(1);
3775     l_distributions            lns_distributions_pub.distribution_tbl;
3776     l_exists                   number;
3777     l_disb_header_id           number;
3778     l_loan_amount_adj_id       number;
3779     l_distributions_count      number;
3780     i                          number;
3781     l_subsidy_rate             number;
3782     l_subsidy_exists           number;
3783     l_activity		  VARCHAR2(30);
3784 
3785 
3786 
3787     CURSOR c_distribs_exist(c_loan_id NUMBER, c_disb_header_id NUMBER, c_loan_amount_adj_id NUMBER, c_activity VARCHAR2) IS
3788       SELECT count(1)
3789       FROM   lns_distributions
3790       WHERE loan_id = c_loan_id
3791         AND nvl(disb_header_id, -1) = nvl(c_disb_header_id, -1)
3792 	      AND nvl(loan_amount_adj_id, -1) = nvl(c_loan_amount_adj_id, -1)
3793 	      AND activity  = c_activity
3794 	      AND distribution_type = 'ORIGINATION';
3795 
3796     cursor c_first_disb(p_loan_id number) is
3797     select disb_header_id
3798       from lns_disb_headers
3799       where loan_id = p_loan_id;
3800 
3801     cursor c_subsidy_rows_exist(p_loan_id number) is
3802     select count(1)
3803       from lns_distributions
3804      where loan_id = p_loan_id
3805        and line_type = 'SUBSIDY'
3806        and distribution_type = 'ORIGINATION'
3807        --and event_id is not null;
3808        and activity = 'LNS_APPROVAL';   -- At present, we allow the subsidy for LoanApproval only
3809 
3810     -- Bug#6711399 subsidy_rate is taken from 'loan header' table, which is
3811     -- defaulted from product at the loan creation time.
3812     cursor c_subsidy_rate (p_loan_id number) is
3813     SELECT
3814 	(nvl(subsidy_rate, 0)/100)
3815     FROM
3816 	lns_loan_headers_all
3817     WHERE
3818 	loan_id = p_loan_id;
3819 
3820     cursor c_loan_adj(c_loan_id number) is
3821       SELECT LOAN_AMOUNT_ADJ_ID
3822       FROM LNS_LOAN_AMOUNT_ADJS
3823       WHERE loan_id = c_loan_id
3824         AND status = 'PENDING';
3825 
3826 begin
3827 
3828      l_api_name   := 'create_DisbursementDistribs';
3829      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || ' - BEGIN');
3830 
3831      SAVEPOINT create_DisbursementDistribs;
3832 
3833      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
3834      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_disb_header_id = ' || p_disb_header_id);
3835      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_amount_adj_id = ' || p_loan_amount_adj_id);
3836      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_activity_type = ' || p_activity_type);
3837 
3838 
3839      -- Initialize message list IF p_init_msg_list is set to TRUE.
3840      IF FND_API.to_Boolean( p_init_msg_list ) THEN
3841          FND_MSG_PUB.initialize;
3842      END IF;
3843 
3844      -- Initialize API return status to SUCCESS
3845      x_return_status := FND_API.G_RET_STS_SUCCESS;
3846 
3847      l_disb_header_id := p_disb_header_id;
3848      l_activity       := p_activity_type;
3849 
3850      IF l_activity = 'LOAN_AMOUNT_ADJUSTMENT' THEN
3851        if p_loan_amount_adj_id is not null then
3852            logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_amt_adj_id = ' || p_loan_amount_adj_id);
3853            l_loan_amount_adj_id := p_loan_amount_adj_id;
3854        else
3855           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'finding Pending adjustment');
3856           open c_loan_adj(p_loan_id);
3857           fetch c_loan_adj into l_loan_amount_adj_id;
3858           close c_loan_adj;
3859           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Pending l_loan_amount_adj_id = ' || l_loan_amount_adj_id);
3860        end if;
3861 
3862      END IF;
3863 
3864 
3865     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'getting subsidy_rate ');
3866      open c_subsidy_rate(p_loan_id);
3867      fetch c_subsidy_rate into l_subsidy_rate;
3868      close c_subsidy_rate;
3869      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_subsidy_rate = ' || l_subsidy_rate);
3870 
3871      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_disb_header_id = ' || l_disb_header_id);
3872 
3873 
3874      OPEN  c_distribs_exist(p_loan_id, l_disb_header_id, l_loan_amount_adj_id, l_activity);
3875      FETCH c_distribs_exist INTO l_exists;
3876      CLOSE c_distribs_exist;
3877 
3878      if l_exists = 0 then
3879 
3880 
3881      	IF l_activity in ('DISBURSEMENT', 'LNS_SUBMIT_DISBURSEMENT', 'LNS_SUBMITTED_DISB_CANCEL', 'LOAN_AMOUNT_ADJUSTMENT') THEN
3882 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling defaultBookDistForActivity...');
3883 		defaultBookDistForActivity(p_api_version                => 1.0
3884 					,p_init_msg_list              => FND_API.G_TRUE
3885 					,p_commit                     => p_commit
3886 					,p_loan_id                    => p_loan_id
3887 					,p_disb_header_id             => l_disb_header_id
3888 					,p_loan_amount_adj_id         => l_loan_amount_adj_id
3889 				   	,p_activity		      => l_activity
3890                                    	,x_distribution_tbl           => l_distributions
3891 					,x_return_status              => l_return_status
3892 					,x_msg_count                  => l_msg_count
3893 					,x_msg_data                   => l_msg_data);
3894 
3895 		if l_return_status <> 'S' then
3896 			logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Error Invoking defaultBookDistForActivity..');
3897 			RAISE FND_API.G_EXC_ERROR;
3898 		end if;
3899 
3900 
3901 	ELSE
3902 		-- get the cc_ids and percentages for the each loan_class_code and loan_type_id
3903 		--break up the distribution amounts for the disbursement
3904 		-- insert into the distributions table
3905 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling defaultDistributionsCatch...');
3906 		defaultDistributionsCatch(p_api_version                => 1.0
3907 					,p_init_msg_list              => FND_API.G_TRUE
3908 					,p_commit                     => p_commit
3909 					,p_loan_id                    => p_loan_id
3910 					,p_disb_header_id             => l_disb_header_id
3911 					,p_loan_amount_adj_id         => l_loan_amount_adj_id
3912 					,p_include_loan_receivables   => 'Y'
3913 					,p_distribution_type          => 'ORIGINATION'
3914 					,x_distribution_tbl           => l_distributions
3915 					,x_return_status              => l_return_status
3916 					,x_msg_count                  => l_msg_count
3917 					,x_msg_data                   => l_msg_data);
3918 
3919 		if l_return_status <> 'S' then
3920 		RAISE FND_API.G_EXC_ERROR;
3921 		end if;
3922 	END IF;
3923 
3924         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributionsCatch.count = ' || l_distributions.count);
3925         for j in 1..l_distributions.count loop
3926 
3927             if (l_distributions(j).distribution_type = 'ORIGINATION') THEN
3928 
3929                 l_distributions(j).activity := l_activity;
3930 
3931                 IF p_activity_type IN ('LNS_APPROVAL', 'DISBURSEMENT', 'LNS_SUBMIT_DISBURSEMENT', 'LNS_SUBMITTED_DISB_CANCEL') THEN   -- Used for DirectLoanApproval and Disbursement
3932                     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'adding disb_header_id ' ||p_disb_header_id ||' to '|| j);
3933                     l_distributions(j).disb_header_id := p_disb_header_id;
3934 
3935                 ELSIF p_activity_type = 'LOAN_AMOUNT_ADJUSTMENT' THEN
3936                     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'adding l_loan_amount_adj_id ' ||l_loan_amount_adj_id ||' to '|| j);
3937                     l_distributions(j).loan_amount_adj_id := l_loan_amount_adj_id;
3938                 END IF;
3939 
3940             end if;
3941 
3942         end loop;
3943 
3944         l_distributions_count := l_distributions.count;
3945         i                     := l_distributions.count;
3946 
3947         if ((lns_utility_pub.IS_FED_FIN_ENABLED = 'Y') and (lns_utility_pub.IS_ENCUM_FIN_ENABLED = 'N')) then
3948 
3949             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'checking for existing subsidy rows');
3950             open  c_subsidy_rows_exist(p_loan_id);
3951             fetch c_subsidy_rows_exist into l_subsidy_exists;
3952             close c_subsidy_rows_exist;
3953 
3954             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_subsidy_exists = ' || l_subsidy_exists);
3955             if l_subsidy_exists = 0 then
3956 
3957                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'fed enabled adding subsidy rows ');
3958                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'subsidy rows do not exist ');
3959                 for j in 1..l_distributions_count loop
3960 
3961                     if (l_distributions(j).distribution_type = 'ORIGINATION') THEN
3962 
3963                         -- if (l_distributions(j).ACCOUNT_TYPE = 'ORIGINATION' AND
3964                         --     (l_distributions(j).ACCOUNT_NAME = 'LOAN_RECEIVABLE' OR
3965                         --      l_distributions(j).ACCOUNT_NAME = 'LOAN_PAYABLE' )) then
3966                         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'adding subsidy row # ' || j);
3967                         i := i + 1;
3968                         -- add rows for subsidy cost
3969 
3970                         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'account_name = ' || l_distributions(j).account_name);
3971                         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'CODE_COMBINATION_ID = ' || l_distributions(j).CODE_COMBINATION_ID);
3972                         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'account_type = ' || l_distributions(j).account_type);
3973                         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'DISTRIBUTION_PERCENT = ' || l_distributions(j).DISTRIBUTION_PERCENT);
3974                         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'DISTRIBUTION_TYPE = ' || l_distributions(j).DISTRIBUTION_TYPE);
3975                         l_distributions(i).LOAN_ID             := p_loan_id;
3976                         l_distributions(i).LINE_TYPE           := 'SUBSIDY';
3977                         l_distributions(i).ACCOUNT_NAME        := l_distributions(j).account_name;
3978                         l_distributions(i).CODE_COMBINATION_ID := l_distributions(j).CODE_COMBINATION_ID;
3979                         l_distributions(i).ACCOUNT_TYPE        := l_distributions(j).account_type;
3980                         l_distributions(i).DISTRIBUTION_PERCENT:= l_distributions(j).DISTRIBUTION_PERCENT;
3981                         l_distributions(i).distribution_amount := l_distributions(j).DISTRIBUTION_AMOUNT * l_subsidy_Rate;
3982                         l_distributions(i).DISTRIBUTION_TYPE   := l_distributions(j).DISTRIBUTION_TYPE;
3983                         l_distributions(i).EVENT_ID            := null;
3984                         l_distributions(i).ACTIVITY		:= 'LNS_APPROVAL';
3985 
3986                         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'running count = ' || l_distributions.count);
3987                         -- end if;
3988 
3989                     end if;
3990 
3991                 end loop;
3992 
3993             end if; -- l_subsidy_exists
3994 
3995         end if;
3996         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'total distributions adding = ' || l_distributions.count);
3997 
3998         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling do_insert_distributions...');
3999         do_insert_distributions(l_distributions, p_loan_id);
4000 
4001      end if;
4002 
4003      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'p_commit is '||p_commit);
4004      IF FND_API.to_Boolean(p_commit)
4005      THEN
4006          COMMIT;
4007 	  logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'Commited');
4008      END IF;
4009 
4010      FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
4011      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
4012 
4013 EXCEPTION
4014 
4015     WHEN FND_API.G_EXC_ERROR THEN
4016         ROLLBACK TO create_DisbursementDistribs;
4017         x_return_status := FND_API.G_RET_STS_ERROR;
4018         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
4019         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
4020 
4021     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
4022         ROLLBACK TO create_DisbursementDistribs;
4023         x_return_status := FND_API.G_RET_STS_ERROR;
4024         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
4025         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
4026 
4027     WHEN OTHERS THEN
4028         ROLLBACK TO create_DisbursementDistribs;
4029         x_return_status := FND_API.G_RET_STS_ERROR;
4030         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
4031         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
4032 
4033 end create_DisbursementDistribs;
4034 
4035 
4036 /*=========================================================================
4037 || PUBLIC PROCEDURE defaultDistributions
4038 ||
4039 || DESCRIPTION
4040 ||      This procedure defaults distributions (if set) for a particular
4041 ||       loan_class + loan_Type
4042 ||
4043 || PSEUDO CODE/LOGIC
4044 ||
4045 || PARAMETERS
4046 ||  Parameter:   p_loan_id => loan to default
4047 ||
4048 || Return value:  Standard  S = Success E = Error U = Unexpected
4049 ||
4050 || Source Tables: LNS_DEFAULT_DISTRIBUTIONS, lns_loan_headers_all
4051 ||
4052 || Target Tables: LNS_DISTRIBUTIONS
4053 ||
4054 || KNOWN ISSUES
4055 ||
4056 || NOTES
4057 ||
4058 || MODIFICATION HISTORY
4059 || Date                  Author            Description of Changes
4060 || 02-16-2004            raverma             Created
4061 || 03-16-2004            raverma             added in default for multi-fund loans inherit from receivables
4062 || 06-16-2004            raverma             changed rules on inheritance for MFAR transactions
4063 ||                                           get amounts for MFAR from PSA_MF_BALANCES_VIEW
4064 || 07-26-2004            raverma             delete rows before each call to accounting
4065 || 12-18-2004            raverma             look at lns_loan_lines
4066 || 12-18-2004            raverma             need to get loan class code
4067 || 04-19-2005            raverma             establish loan clearing as per bug #4313925
4068  *=======================================================================*/
4069 procedure defaultDistributions(p_api_version           IN NUMBER
4070                               ,p_init_msg_list         IN VARCHAR2
4071                               ,p_commit                IN VARCHAR2
4072                               ,p_loan_id               IN NUMBER
4073                               ,p_loan_class_code       IN VARCHAR2
4074                               ,x_return_status         OUT NOCOPY VARCHAR2
4075                               ,x_msg_count             OUT NOCOPY NUMBER
4076                               ,x_msg_data              OUT NOCOPY VARCHAR2)
4077 
4078 is
4079 /*------------------------------------------------------------------------+
4080  | Local Variable Declarations and initializations                        |
4081  +-----------------------------------------------------------------------*/
4082     l_api_name                 varchar2(30);
4083     l_msg_count                NUMBER;
4084     l_msg_data                 VARCHAR2(2000);
4085     l_return_Status            VARCHAR2(1);
4086     i                          number;
4087     n                          number;
4088     l_code_combination_id      number;
4089     l_code_combination_id_new_rec number;
4090     l_distributions            lns_distributions_pub.distribution_tbl;
4091     l_distributionsCLEAR_ORIG  lns_distributions_pub.distribution_tbl;
4092     l_distributionsREC_ORIG    lns_distributions_pub.distribution_tbl;
4093     l_distributionsREC_BILL    lns_distributions_pub.distribution_tbl;
4094     l_distributionsCatch       lns_distributions_pub.distribution_tbl;
4095     l_distributionsALL         lns_distributions_pub.distribution_tbl;
4096     l_distributions_count      number;
4097     l_distributionsCatch_count number;
4098     l_total_distributions      number;
4099     l_ers_distribution_amount  number;
4100     l_orig_distribution_amount number;
4101     l_ledger_details           lns_distributions_pub.gl_ledger_details;
4102     l_include_receivables      varchar2(1);
4103     l_sum                      number;
4104     l_multifund                number;
4105     l_multifund_exists         number;
4106     l_total_percent            number;
4107     l_total_receivable_amount  number;
4108     l_natural_account_rec      varchar2(25);  -- the lns_def_distribs replacement  for Loans Receivable
4109     l_nat_acct_seg_number      number;
4110     l_num_segments             number;
4111     l_adjustment_exists        boolean;
4112     l_funded_amount            number;
4113     l_total_amount_due         number;
4114     l_amount_adjusted          number;
4115     l_running_amount           number;
4116     l_running_percent          number;
4117     l_amount                   number;
4118     l_percent                  number;
4119     l_subsidy_rate             number;
4120     l_loan_class               varchar2(30);
4121     l_loan_type_id             number;
4122     l_loan_header_rec          LNS_LOAN_HEADER_PUB.loan_header_rec_type;
4123     adj_info                   xla_events_pub_pkg.t_event_source_info;
4124     inv_info                   xla_events_pub_pkg.t_event_source_info;
4125     l_adjustment_id            number;
4126     l_customer_trx_id          number;
4127     l_accounting_batch_id      NUMBER;
4128     l_errbuf                   VARCHAR2(10000);
4129     l_retcode                  NUMBER;
4130     l_request_id               NUMBER;
4131     l_legal_entity_id          number;
4132     l_version                  number;
4133     l_error_counter            number;
4134     l_event_array              xla_events_pub_pkg.t_array_event_info;
4135     l_error_message               varchar2(2000);
4136     l_invoice_number              varchar2(100);
4137     l_entity_code                 varchar2(30);
4138     l_transactions_count          number;
4139     l_entity_id                   number;
4140     l_source_id_int_1             number;
4141     l_upgrade_status              varchar2(1);
4142     l_trx_number                  varchar2(100);
4143     l_clearing_total_amount_due   number;
4144     l_receivable_total_amount_due number;
4145     l_transaction_number          VARCHAR2(240);
4146     l_sob_id                      number;
4147     l_EVENT_SOURCE_INFO           xla_events_pub_pkg.t_event_source_info;
4148     l_new_ccid_already_exists			VARCHAR2(1);
4149     l_loan_status		   varchar2(30);
4150     l_bill_dist_cnt		  NUMBER;
4151     l_is_natural_acct_exists	  VARCHAR2(1);
4152 
4153 /*------------------------------------------------------------------------+
4154  | Cursor Declarations                                                    |
4155  +-----------------------------------------------------------------------*/
4156 
4157 		 -- cursor to establish the loan receivables accounts
4158      -- 11-16-2005 added reference to XLA_POST_ACCT_PROGS_B as per
4159      --  xla team instructions (noela, ayse)
4160      cursor C_ERS_LOAN_RECEIVABLE(p_loan_id number) is
4161       select sum(lline.requested_amount)
4162 			      ,ael.code_combination_id
4163   	 	  from ra_customer_trx_all inv
4164             ,xla_transaction_entities ent
4165             ,xla_ae_headers aeh
4166             ,xla_ae_lines ael
4167 	    ,lns_loan_lines lline
4168 			 where ent.application_id = 222
4169 			   and lline.reference_id = ent.source_id_int_1
4170 			   and lline.loan_id = p_loan_id
4171 			  -- and lline.status = 'APPROVED'
4172 			   and (lline.end_date is null or trunc(lline.end_date) > trunc(sysdate))
4173 			   and inv.customer_trx_id = ent.source_id_int_1
4174 			   and ent.entity_code = 'TRANSACTIONS'
4175 			   and ent.entity_id = aeh.entity_id
4176          and ent.ledger_id = aeh.ledger_id
4177 			   and aeh.ae_header_id = ael.ae_header_id
4178 			   and aeh.accounting_entry_status_code = 'F'
4179          and ael.accounting_class_code IN
4180          (select xaa.accounting_class_code
4181             from XLA_ACCT_CLASS_ASSGNS xaa
4182                 ,XLA_ASSIGNMENT_DEFNS_B xad
4183                 ,XLA_POST_ACCT_PROGS_B xpa
4184            where xaa.program_code = 'GET_RECEIVABLE_CCID'
4185              and xpa.program_code = xaa.program_code
4186              and xaa.program_code = xad.program_code
4187              and xad.assignment_code = xaa.assignment_code
4188              and xad.enabled_flag = 'Y')
4189 			   and inv.customer_trx_id in
4190 				 (select reference_id
4191 		        from lns_loan_lines lines
4192 					 where reference_type = 'RECEIVABLE'
4193      		     and end_date is null
4194 		         and loan_id = p_loan_id)
4195 			group by ael.code_combination_id;
4196 
4197 		 -- cursor to establish the loan clearing accounts
4198      -- 11-16-2005 added reference to XLA_POST_ACCT_PROGS_B as per
4199      --  xla team instructions (noela, ayse)
4200      cursor C_ERS_LOAN_CLEARING(p_loan_id number) is
4201 			select sum(ael.entered_dr)
4202 				 		,ael.code_combination_id
4203 			  from ar_adjustments_all adj
4204             ,xla_transaction_entities ent
4205 				    ,xla_ae_headers aeh
4206 				    ,xla_ae_lines ael
4207 			where ent.application_id = 222
4208 				and adj.adjustment_id = ent.source_id_int_1
4209 				and ent.entity_code = 'ADJUSTMENTS'
4210 				and ent.entity_id = aeh.entity_id
4211 				and ent.ledger_id = aeh.ledger_id
4212 				and aeh.ae_header_id = ael.ae_header_id
4213 				and aeh.accounting_entry_status_code = 'F'
4214         and ael.accounting_class_code in
4215          (select xaa.accounting_class_code
4216             from XLA_ACCT_CLASS_ASSGNS xaa
4217                 ,XLA_ASSIGNMENT_DEFNS_B xad
4218                 ,XLA_POST_ACCT_PROGS_B xpa
4219            where xaa.program_code = 'LNS_ADJUSTMENT_DEBIT'     -- Bug#8231149
4220              and xpa.program_code = xaa.program_code
4221              and xaa.program_code = xad.program_code
4222              and xad.assignment_code = xaa.assignment_code
4223              and xad.enabled_flag = 'Y')
4224 				and adj.adjustment_id in
4225       (select rec_adjustment_id
4226 			   from lns_loan_lines lines
4227 				where reference_type = 'RECEIVABLE'
4228 			    and end_date is null
4229 			    and loan_id = p_loan_id)
4230 			group by ael.code_combination_id;
4231 
4232 		-- use this to get the loan_class and type
4233     cursor c_loan_class(p_loan_id number) is
4234     select h.loan_class_code
4235           ,t.loan_type_id
4236           ,decode(h.loan_status,'INCOMPLETE', h.requested_amount
4237 	  		       ,'PENDING', h.requested_amount
4238 			       ,h.funded_amount)
4239 	  ,h.legal_entity_id
4240 	  ,h.LOAN_STATUS
4241       from lns_loan_headers_all h
4242 					,lns_loan_types t
4243      where h.loan_id = p_loan_id
4244  		   and h.loan_type_id = t.loan_type_id;
4245 
4246 		-- use this to get all adjustments to be processed for the loan
4247 		cursor c_adj_ids (p_loan_id number) is
4248 		select adj.adjustment_id
4249           ,adj.adjustment_number
4250 			from ar_adjustments adj
4251 					,lns_loan_lines lines
4252 		 where lines.rec_adjustment_number = adj.adjustment_number
4253 			 and lines.end_date is null
4254 			 and lines.reference_type = 'RECEIVABLE'
4255 			 and lines.loan_id = p_loan_id;
4256 
4257     -- use this to get all receivables to be processed for the loan
4258     cursor c_inv_ids(p_loan_id number) is
4259     select lines.reference_id
4260           ,lines.reference_number
4261       from lns_loan_lines lines
4262      where lines.end_date is null
4263        and lines.reference_type = 'RECEIVABLE'
4264        and lines.loan_id = p_loan_id;
4265 
4266     -- cursor to update loan header
4267     cursor c_obj_vers(p_loan_id number) is
4268     select object_version_number
4269       from lns_loan_headers
4270      where loan_id = p_loan_id;
4271 
4272     -- cursor to get documents and check upgrade status
4273     cursor c_get_loan_documents(p_loan_id number) is
4274     select lines.reference_id, trx.trx_number
4275       from lns_loan_lines lines
4276           ,ra_customer_trx trx
4277      where lines.reference_type = 'RECEIVABLE'
4278        and lines.end_date is null
4279        and lines.loan_id = p_loan_id
4280        and lines.reference_id = trx.customer_trx_id;
4281 
4282     -- cursor to get accounting errors
4283     cursor c_acc_errors (p_loan_id number, p_accounting_batch_id number) is
4284     select xlt.transaction_number, xlt.entity_code, err.encoded_msg
4285       from xla_accounting_errors err
4286           ,xla_transaction_entities xlt
4287      where xlt.application_id = 222
4288        --and err.accounting_batch_id = nvl(p_accounting_batch_id, null)
4289        and xlt.entity_id = err.entity_id
4290        and xlt.entity_id in (select entity_id from xla_transaction_entities
4291                               where application_id = 222
4292                                 and entity_code IN ('TRANSACTIONS', 'ADJUSTMENTS')
4293                                 and ((source_id_int_1 in (select reference_id from lns_loan_lines where end_date is null and reference_type = 'RECEIVABLE' and loan_id = p_loan_id))
4294                                   OR (source_id_int_1 in (select rec_adjustment_id from lns_loan_lines where end_date is null and reference_type = 'RECEIVABLE' and loan_id = p_loan_id))));
4295       -- -----------------------------------------------------------------
4296       cursor c_entities(p_loan_id number) is
4297           select entity_id, entity_code, source_id_int_1, transaction_number
4298             from xla_transaction_entities
4299            where application_id = 222
4300              and entity_code IN ('TRANSACTIONS', 'ADJUSTMENTS')
4301              and ((source_id_int_1 in (select reference_id from lns_loan_lines where end_date is null and reference_type = 'RECEIVABLE' and loan_id = p_loan_id)
4302              OR   (source_id_int_1 in (select rec_adjustment_id from lns_loan_lines where end_date is null and reference_type = 'RECEIVABLE' and loan_id = p_loan_id))));
4303 
4304 	CURSOR cur_bill_dist_count(c_loan_id NUMBER) IS
4305 	  SELECT  count(1)
4306 	  FROM lns_distributions
4307 	  WHERE loan_id = p_loan_id
4308 	    AND account_name IN ('PRINCIPAL_RECEIVABLE', 'INTEREST_RECEIVABLE', 'INTEREST_INCOME');
4309 
4310 	CURSOR cur_default_ar_adj(c_loan_id NUMBER) IS
4311 	  SELECT rec.CODE_COMBINATION_ID
4312 	  FROM  lns_loan_headers lhdr,
4313 	  	lns_system_options sysop,
4314 	        ar_receivables_trx rec
4315 	  WHERE lhdr.loan_id = c_loan_id
4316 	    AND sysop.org_id = lhdr.org_id
4317 	    AND sysop.receivables_trx_id = rec.receivables_trx_id;
4318 
4319 begin
4320 
4321       SAVEPOINT defaultDistributions;
4322       l_api_name   := 'defaultDistributions';
4323       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
4324       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
4325       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'p_loan_class_code = ' || p_loan_class_code);
4326 
4327       -- Initialize message list IF p_init_msg_list is set to TRUE.
4328       IF FND_API.to_Boolean( p_init_msg_list ) THEN
4329           FND_MSG_PUB.initialize;
4330       END IF;
4331 
4332       -- Initialize API return status to SUCCESS
4333       x_return_status := FND_API.G_RET_STS_SUCCESS;
4334 
4335       -- initialize variables
4336       l_distributions_count      := 0;
4337       l_distributionsCatch_count := 0;
4338       l_total_distributions      := 0;
4339       l_ers_distribution_amount  := 0;
4340       i                          := 0;
4341       l_distributions_count      := 0;
4342       l_distributionsCatch_count := 0;
4343       l_total_distributions      := 0;
4344       l_orig_distribution_amount := 0;
4345       l_include_receivables      := 'Y';
4346       l_sum                      := 0;
4347       l_funded_amount            := 0;
4348       l_multifund_exists         := 0;
4349       n                          := 0;
4350       l_total_percent            := 0;
4351       l_total_receivable_amount  := 0;
4352       l_adjustment_exists        := false;
4353       l_running_amount           := 0;
4354       l_running_percent          := 0;
4355       l_total_amount_due         := 0;
4356       l_subsidy_rate             := 0;
4357       l_receivable_total_amount_due := 0;
4358       l_clearing_total_amount_due := 0;
4359 
4360       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Opening cursor c_loan_class...');
4361       open c_loan_class(p_loan_id);
4362       fetch c_loan_class
4363        into l_loan_class
4364            ,l_loan_type_id
4365            ,l_funded_amount
4366 	   ,l_legal_entity_id
4367 	   ,l_loan_status;
4368       close c_loan_class;
4369 
4370       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_loan_class = ' || l_loan_class);
4371       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_loan_type_id = ' || l_loan_type_id);
4372       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_funded_amount = ' || l_funded_amount);
4373       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_legal_entity_id = ' || l_legal_entity_id);
4374       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_loan_status = ' || l_loan_status);
4375 
4376 /*
4377       IF (p_loan_class_code = 'ERS'AND l_loan_status = 'INCOMPLETE') THEN
4378 	return;
4379       END IF;
4380 */
4381       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling lns_distributions_pub.validateDefaultAccounting...');
4382       lns_distributions_pub.validateDefaultAccounting(p_loan_class      => l_loan_class
4383                                                      ,p_loan_type_id    => l_loan_type_id
4384                                                      ,p_init_msg_list   => p_init_msg_list
4385                                                      ,x_return_status   => l_return_status
4386                                                      ,x_msg_count       => l_msg_count
4387                                                      ,x_msg_data        => l_msg_data);
4388 
4389       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_return_status = ' || l_return_status);
4390       if l_return_status <> FND_API.G_RET_STS_SUCCESS then
4391           FND_MESSAGE.SET_NAME('LNS', 'LNS_DEFAULT_DIST_NOT_FOUND');
4392           FND_MSG_PUB.ADD;
4393           LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
4394           RAISE FND_API.G_EXC_ERROR;
4395       end if;
4396 
4397       /* delete any rows for this loan before inheritance do not delete FEE_RECEIVABLE or FEE_INCOME rows*/
4398       /* Commented Bug#7406404 - Defaulting the laon distributions happens only at Loan Creation time and later only updation at loan level is changed.
4399       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Deleting any existing accounting rows except FEE_RECEIVABLE or FEE_INCOME...');
4400       delete from lns_distributions
4401       where loan_id = p_loan_id
4402         and account_name in ('PRINCIPAL_RECEIVABLE', 'INTEREST_RECEIVABLE', 'INTEREST_INCOME', 'LOAN_RECEIVABLE', 'LOAN_CLEARING', 'LOAN_LIABILITY', 'LOAN_PAYABLE');
4403         --and event_id is null;  --fix for bug 8815841: delete all rows including rows with event_id not null
4404       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Done');
4405 
4406       */
4407 
4408       -- first check if we are creating accounting for an ERS or DIRECT loan
4409       if p_loan_class_code = 'DIRECT' then
4410 
4411 
4412         /*
4413      -- Bug#6711399 Subsidy_rate defaulted from loanProduct to loan at the time of loanCreation
4414      --  in API LNS_LOAN_HEADER_PUB.do_create_loan.
4415 
4416 					-- we are creating accounting for DIRECT loan class
4417           logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' fetching subsidy rate');
4418           begin
4419                 open c_subsidy_rate(p_loan_id);
4420                 fetch c_subsidy_rate into l_subsidy_rate;
4421                 close c_subsidy_rate;
4422           exception
4423             when no_data_found then
4424                 FND_MESSAGE.SET_NAME('LNS', 'LNS_NO_SUBSIDY_RATE');
4425                 FND_MSG_PUB.ADD;
4426                 RAISE FND_API.G_EXC_ERROR;
4427           end;
4428 
4429           logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' l_subsidy_rate ' || l_subsidy_rate );
4430 
4431           open c_obj_vers(p_loan_id);
4432           fetch c_obj_vers into l_version;
4433           close c_obj_vers;
4434 
4435           l_loan_header_rec.subsidy_rate := l_subsidy_rate;
4436           l_loan_header_rec.loan_id             := p_loan_id;
4437           logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'updating loan');
4438           LNS_LOAN_HEADER_PUB.UPDATE_LOAN(P_OBJECT_VERSION_NUMBER => l_version
4439                                          ,P_LOAN_HEADER_REC       => l_loan_header_rec
4440                                          ,P_INIT_MSG_LIST         => p_init_msg_list
4441                                          ,X_RETURN_STATUS         => l_return_status
4442                                          ,X_MSG_COUNT             => l_msg_count
4443                                          ,X_MSG_DATA              => l_msg_data);
4444           logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' update loan status = ' || l_return_status);
4445           if l_return_status <> 'S' then
4446             FND_MESSAGE.SET_NAME('LNS', 'LNS_UPD_LOAN_FAIL');
4447             FND_MSG_PUB.ADD;
4448             RAISE FND_API.G_EXC_ERROR;
4449           end if;
4450    */
4451 		    logMessage(FND_LOG.level_statement, G_PKG_NAME, 'DIRECT LOAN INHERITANCE');
4452 
4453             -- we establish BILING only for this procedure
4454 	        -- inherit based on loan class + type ONLY
4455             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling defaultDistributionsCatch...');
4456 	        defaultDistributionsCatch(p_api_version                 => 1.0
4457                                     ,p_init_msg_list              => p_init_msg_list
4458                                     ,p_commit                     => FND_API.G_FALSE
4459                                     ,p_loan_id                    => p_loan_id
4460                                     ,p_disb_header_id             => null
4461                                     ,p_loan_amount_adj_id         => null
4462                                     ,p_include_loan_receivables   => 'Y'
4463                                     ,p_distribution_type          => 'BILLING'
4464                                     ,x_distribution_tbl           => l_distributionsCatch
4465                                     ,x_return_status              => l_return_status
4466                                     ,x_msg_count                  => l_msg_count
4467                                     ,x_msg_data                   => l_msg_data);
4468             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_return_status = ' || l_return_status);
4469             if l_return_status <> 'S' then
4470                 RAISE FND_API.G_EXC_ERROR;
4471             end if;
4472 
4473             -- we establish the distributions for the first DISBURSEMENT only
4474             -- in order to process Budgetary Control Information
4475             -- in SLA Transaction Line Object
4476             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling create_DisbursementDistribs...');
4477             create_DisbursementDistribs(p_api_version           => 1.0
4478                                       ,p_init_msg_list         => p_init_msg_list
4479                                       ,p_commit                => FND_API.G_FALSE
4480                                       ,p_loan_id               => p_loan_id
4481                                       ,p_disb_header_id        => null
4482                                       ,p_loan_amount_adj_id    => null
4483                                       ,p_activity_type         => 'LNS_APPROVAL'
4484                                       ,x_return_status         => l_return_status
4485                                       ,x_msg_count             => l_msg_count
4486                                       ,x_msg_data              => l_msg_data);
4487             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_return_status = ' || l_return_status);
4488             if l_return_status <> 'S' then
4489                 RAISE FND_API.G_EXC_ERROR;
4490             end if;
4491 
4492       elsif p_loan_class_code = 'ERS' then
4493 
4494 	    logMessage(FND_LOG.level_statement, G_PKG_NAME, 'ERS LOAN INHERITANCE');
4495 	    logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Deleting any existing ERS loan Booking distributions and Principal LOAN_RECEIVABLE');
4496 
4497       delete from lns_distributions
4498       where loan_id = p_loan_id
4499         and account_name in ('LOAN_RECEIVABLE', 'LOAN_CLEARING');
4500 
4501       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Deleted '||SQL%ROWCOUNT||' rows');
4502 
4503             -- this switch is for the CatchAll Procedure
4504             l_include_receivables := 'N';
4505             l_ledger_details := lns_distributions_pub.getLedgerDetails;
4506             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'chart_of_accounts_id = ' || l_ledger_details.chart_of_accounts_id);
4507 
4508             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Fetching documents to account...');
4509             open c_get_loan_documents(p_loan_id);
4510             loop
4511                 fetch c_get_loan_documents into l_source_id_int_1, l_trx_number;
4512                 exit when c_get_loan_documents%notfound;
4513 
4514                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_source_id_int_1 = ' || l_source_id_int_1);
4515                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_trx_number = ' || l_trx_number);
4516 
4517                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling arp_acct_event_pkg.upgrade_status_per_doc...');
4518                 -- check for upgrade status bug#4872154
4519                 arp_acct_event_pkg.upgrade_status_per_doc(p_init_msg_list     => p_init_msg_list
4520                                                         ,p_entity_code       => l_entity_code
4521                                                         ,p_source_int_id     => l_source_id_int_1
4522                                                         ,x_upgrade_status    => l_upgrade_status
4523                                                         ,x_return_status     => l_return_status
4524                                                         ,x_msg_count         => l_msg_count
4525                                                         ,x_msg_data          => l_msg_data);
4526                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_return_status = ' || l_return_status);
4527                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_upgrade_status = ' || l_upgrade_status);
4528 
4529                 if l_return_status <> 'S' then
4530                     FND_MESSAGE.SET_NAME('LNS', 'LNS_CHK_UPG_FAIL');
4531                     FND_MESSAGE.SET_TOKEN('DOC_NUM', l_trx_number);
4532                     FND_MSG_PUB.ADD;
4533                     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
4534                     RAISE FND_API.G_EXC_ERROR;
4535                 else
4536                     if l_upgrade_status <> 'Y' then
4537                         FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_TRX');
4538                         FND_MESSAGE.SET_TOKEN('DOC_NUM', l_trx_number);
4539                         FND_MSG_PUB.ADD;
4540                         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
4541                         RAISE FND_API.G_EXC_ERROR;
4542                     end if;
4543                 end if;
4544 
4545             end loop;
4546             close c_get_loan_documents;
4547 
4548             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Fetching entities xla_transaction_entities...');
4549             l_transactions_count := 0;
4550             open c_entities(p_loan_id);
4551             loop
4552                 fetch c_entities into l_entity_id, l_entity_code, l_source_id_int_1, l_transaction_number;
4553                 exit when c_entities%notfound;
4554 
4555                 l_transactions_count := l_transactions_count + 1;
4556                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Entity ' || l_transactions_count);
4557                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_entity_id = ' || l_entity_id);
4558                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_entity_code = ' || l_entity_code);
4559                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_source_id_int_1 = ' || l_source_id_int_1);
4560                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_transaction_number = ' || l_transaction_number);
4561 
4562                 insert into XLA_ACCT_PROG_DOCS_GT (entity_id) VALUES (l_entity_id);
4563                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Inserted into XLA_ACCT_PROG_DOCS_GT');
4564 
4565             end loop;
4566             close  c_entities ;
4567 
4568             select count(1) into l_transactions_count
4569             from XLA_ACCT_PROG_DOCS_GT;
4570             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Inserted transaction_entities  = ' || l_transactions_count);
4571 
4572             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling XLA_ACCOUNTING_PUB_PKG.accounting_program_doc_batch...');
4573             XLA_ACCOUNTING_PUB_PKG.accounting_program_doc_batch(p_application_id      => 222
4574                                                                 ,p_accounting_mode     => 'F'
4575                                                                 ,p_gl_posting_flag     => 'N'
4576                                                                 ,p_accounting_batch_id => l_accounting_batch_id
4577                                                                 ,p_errbuf              => l_errbuf
4578                                                                 ,p_retcode             => l_retcode);
4579             logMessage(FND_LOG.level_statement, G_PKG_NAME, ' l_retcode = ' || l_retcode);
4580             logMessage(FND_LOG.level_statement, G_PKG_NAME, ' l_accounting_batch_id = ' || l_accounting_batch_id);
4581 
4582             if l_retcode <> 0 then
4583 
4584                 logMessage(FND_LOG.level_unexpected, G_PKG_NAME, 'Online accounting failed with error: ' || l_errbuf);
4585 
4586                 /* query XLA_ACCOUNTING_ERRORS */
4587                 l_error_counter := 0;
4588                 open c_acc_errors(p_loan_id, l_accounting_batch_id);
4589 
4590                 LOOP
4591 
4592                     fetch c_acc_errors into
4593                         l_invoice_number,
4594                         l_entity_code,
4595                         l_error_message;
4596                     exit when c_acc_errors%NOTFOUND;
4597 
4598                     l_error_counter := l_error_counter + 1;
4599 
4600                     if l_error_counter = 1 then
4601                         FND_MESSAGE.SET_NAME('LNS', 'LNS_ONLINE_ACCOUNTING_FAILED');
4602                         FND_MSG_PUB.Add;
4603                         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
4604                     end if;
4605 
4606                     FND_MESSAGE.SET_NAME('LNS', 'LNS_ACC_DOC_FAIL');
4607                     FND_MESSAGE.SET_TOKEN('DOC_NUM', l_invoice_number);
4608                     FND_MESSAGE.SET_TOKEN('DOC_TYPE', l_entity_code);
4609                     FND_MESSAGE.SET_TOKEN('ACC_ERR', l_error_message);
4610                     FND_MSG_PUB.Add;
4611                     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
4612 
4613                 END LOOP;
4614 
4615                 close c_acc_errors;
4616 
4617                 RAISE FND_API.G_EXC_ERROR;
4618             else
4619                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Online accounting SUCCESS! ');
4620             end if;
4621 
4622             -- get the swap segment value
4623 	        l_natural_account_rec := getNaturalSwapAccount(p_loan_id);
4624 	        logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Swap natural account with ' || l_natural_account_rec);
4625 
4626 	    -- Bug#7406404 - Make ERS 'Replacement Natural Account' optional
4627 	    l_is_natural_acct_exists := 'N';
4628             IF (l_natural_account_rec IS NOT NULL) THEN
4629 		l_is_natural_acct_exists := 'Y';
4630 	    END IF;
4631 
4632 	    logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_is_natural_acct_exists is '||l_is_natural_acct_exists);
4633 
4634 	    IF (l_is_natural_acct_exists = 'Y') THEN
4635 		-- Get natural account segment number
4636 		logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling FND_FLEX_APIS.GET_QUALIFIER_SEGNUM...');
4637 		IF (NOT FND_FLEX_APIS.GET_QUALIFIER_SEGNUM(appl_id         => 101
4638 								,key_flex_code   => 'GL#'
4639 								,structure_number=> l_ledger_details.chart_of_accounts_id
4640 								,flex_qual_name  => 'GL_ACCOUNT'
4641 								,segment_number  => l_nat_acct_seg_number))
4642 		THEN
4643 			FND_MESSAGE.SET_NAME('LNS', 'LNS_NO_NATURAL_ACCOUNT_SEGMENT');
4644 			FND_MSG_PUB.ADD;
4645 			LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
4646 			RAISE FND_API.G_EXC_ERROR;
4647 		END IF;
4648 		logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Natural acct segment = ' || l_nat_acct_seg_number);
4649 	    END IF;
4650 
4651             -- here we establish the loan clearing first
4652             -- if adjustment activity is found in XLA then we take amounts, cc_ids from XLA tables for both CLEARING and RECEIVABLES
4653             Begin
4654 	            logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Opening cursor C_ERS_LOAN_CLEARING...');
4655                 i := 0;
4656 	            open C_ERS_LOAN_CLEARING(p_loan_id);
4657 	            Loop
4658                     -- reintialize these
4659                     l_code_combination_id     := null;
4660                     l_ers_distribution_amount := 0;
4661 
4662                     fetch C_ERS_LOAN_CLEARING into l_ers_distribution_amount, l_code_combination_id;
4663                     EXIT WHEN C_ERS_LOAN_CLEARING%NOTFOUND;
4664 
4665                     l_clearing_total_amount_due := l_clearing_total_amount_due + l_ers_distribution_amount;
4666 
4667                     -- bug #4313925 --
4668                     l_adjustment_exists := true;
4669                     i := i + 1;
4670 
4671                     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Loan Clearing Record ' || i);
4672                     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_ers_distribution_amount = ' || l_ers_distribution_amount);
4673                     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
4674                     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_clearing_total_amount_due = ' || l_clearing_total_amount_due);
4675 
4676                     l_distributionsCLEAR_ORIG(i).line_type            := 'CLEAR';
4677                     l_distributionsCLEAR_ORIG(i).account_name         := 'LOAN_CLEARING';
4678                     l_distributionsCLEAR_ORIG(i).code_combination_id  := l_code_combination_id;
4679                     l_distributionsCLEAR_ORIG(i).account_type         := 'CR';
4680                     l_distributionsCLEAR_ORIG(i).distribution_amount  := l_ers_distribution_amount;
4681                     l_distributionsCLEAR_ORIG(i).distribution_percent := null;
4682                     l_distributionsCLEAR_ORIG(i).distribution_type    := 'ORIGINATION';
4683 		    l_distributionsCLEAR_ORIG(i).activity  := 'LNS_APPROVAL';
4684 
4685 	            end loop; -- loan clearing loop
4686 	       exception
4687                 when others then
4688                     --logMessage(FND_LOG.LEVEL_UNEX, G_PKG_NAME, 'Failed to inherit receivables distributions');
4689                     FND_MESSAGE.SET_NAME('LNS', 'LNS_INHERIT_DIST_NOT_FOUND');
4690                     FND_MSG_PUB.ADD;
4691                     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
4692                     RAISE FND_API.G_EXC_ERROR;
4693 	       end;
4694 
4695            --logMessage(FND_LOG.level_statement, G_PKG_NAME, 'After loan clearing lines calculated. total amount due = ' || l_total_amount_due);
4696 
4697 	   IF ((NOT l_adjustment_exists) AND l_loan_status in ('INCOMPLETE', 'PENDING')) THEN
4698 	   	logMessage(FND_LOG.level_statement, G_PKG_NAME, 'No adjustment, so consider default adjustment');
4699 
4700 		l_adjustment_exists := true;
4701                 i := i + 1;
4702 
4703 		OPEN cur_default_ar_adj(p_loan_id);
4704 		FETCH cur_default_ar_adj INTO l_code_combination_id;
4705 		CLOSE cur_default_ar_adj;
4706 
4707 		logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Default Adjustment CCID is '||l_code_combination_id);
4708 
4709 		IF l_code_combination_id IS NULL THEN
4710 			FND_MESSAGE.SET_NAME('LNS', 'LNS_INHERIT_DIST_NOT_FOUND');
4711 			FND_MSG_PUB.ADD;
4712 			LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
4713 			RAISE FND_API.G_EXC_ERROR;
4714 		END IF;
4715 
4716  		    l_distributionsCLEAR_ORIG(i).line_type            := 'CLEAR';
4717                     l_distributionsCLEAR_ORIG(i).account_name         := 'LOAN_CLEARING';
4718                     l_distributionsCLEAR_ORIG(i).code_combination_id  := l_code_combination_id;
4719                     l_distributionsCLEAR_ORIG(i).account_type         := 'CR';
4720                     l_distributionsCLEAR_ORIG(i).distribution_amount  := l_funded_amount;
4721                     l_distributionsCLEAR_ORIG(i).distribution_percent := null;
4722                     l_distributionsCLEAR_ORIG(i).distribution_type    := 'ORIGINATION';
4723 		    l_distributionsCLEAR_ORIG(i).activity  := 'LNS_APPROVAL';
4724 
4725 		    l_clearing_total_amount_due := l_funded_amount;
4726 	   END IF;
4727 		logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Manual After loan clearing lines calculated. total clearing amount due = ' || l_clearing_total_amount_due);
4728 
4729 	       -- if the adjustment exists in PSA table it means loan is approved and adjustment was created for receivables
4730 	       i := 0;
4731 	       if l_adjustment_exists then
4732 	           logMessage(FND_LOG.level_statement, G_PKG_NAME, 'ACCOUNTED ADJUSTMENT EXISTS');
4733 	           Begin
4734 	               logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Opening cursor C_ERS_LOAN_RECEIVABLE...');
4735 	               open C_ERS_LOAN_RECEIVABLE(p_loan_id);
4736 	               Loop
4737 	                   -- reintialize these
4738 	                   l_code_combination_id         := null;
4739 	                   l_code_combination_id_new_rec := null;
4740 	                   l_ers_distribution_amount     := 0;
4741 
4742                        fetch C_ERS_LOAN_RECEIVABLE into l_ers_distribution_amount, l_code_combination_id;
4743 	                   EXIT WHEN C_ERS_LOAN_RECEIVABLE%NOTFOUND;
4744 
4745                        l_receivable_total_amount_due := l_receivable_total_amount_due + l_ers_distribution_amount;
4746 
4747                        logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Record:');
4748                        logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_ers_distribution_amount = ' || l_ers_distribution_amount);
4749                        logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
4750                        logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_receivable_total_amount_due = ' || l_receivable_total_amount_due);
4751 
4752 		       	if l_ers_distribution_amount > 0 then
4753 				-- Bug#7406404 - Make ERS 'Replacement Natural Account' optional
4754 				IF (l_is_natural_acct_exists = 'Y') THEN
4755 				-- here we need to rebuild the code_Combination_id as per swapping rules
4756 				-- replace the natual account segement with the natural account segment found in the set-up/configuration
4757 
4758 					logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling swap_code_combination...');
4759 					l_code_combination_id_new_rec :=
4760 					swap_code_combination(p_chart_of_accounts_id => l_ledger_details.chart_of_accounts_id
4761 								,p_original_cc_id       => l_code_combination_id
4762 								,p_swap_segment_number  => l_nat_acct_seg_number
4763 								,p_swap_segment_value   => l_natural_account_rec);
4764 
4765 				logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_code_combination_id_new_rec = ' || l_code_combination_id_new_Rec);
4766 				ELSE
4767 
4768 					l_code_combination_id_new_rec := l_code_combination_id;
4769 			    	END IF;
4770 
4771 	                        logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Assigning distributions...');
4772 
4773 			       -- Bug#10266158 (Handling Multi Receivable Invoices in a loan)
4774 			       -- After new cc_id, if it exists already in IF l_distributionsREC_ORIG  then  add the amount to the existed record
4775 				logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Add amount to the exist record if the new CC_ID already exists');
4776 				l_new_ccid_already_exists := 'N';
4777 				FOR p in 1..l_distributionsREC_ORIG.count  LOOP
4778 
4779 					logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsREC_ORIG('||p||').code_combination_id: '||l_distributionsREC_ORIG(p).code_combination_id);
4780 
4781 					IF (l_distributionsREC_ORIG(p).code_combination_id = l_code_combination_id_new_rec) THEN
4782 						l_distributionsREC_ORIG(p).distribution_amount := l_distributionsREC_ORIG(p).distribution_amount + l_ers_distribution_amount;
4783 						l_new_ccid_already_exists := 'Y';
4784 						logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Total amount after adding this is  '||l_distributionsREC_ORIG(p).distribution_amount||' to existed amount');
4785 
4786 						EXIT;
4787 					END IF;
4788 
4789 				END LOOP;
4790 
4791 	                       -- we need 2 records PER receivable account distribution
4792 			       IF (l_new_ccid_already_exists = 'N') THEN
4793 					i := i + 1;
4794 					l_distributionsREC_ORIG(i).line_type           := 'ORIG';
4795 					l_distributionsREC_ORIG(i).account_name        := 'LOAN_RECEIVABLE';
4796 					l_distributionsREC_ORIG(i).code_combination_id := l_code_combination_id_new_rec;
4797 					l_distributionsREC_ORIG(i).account_type        := 'DR';
4798 					l_distributionsREC_ORIG(i).distribution_amount := l_ers_distribution_amount;
4799 					l_distributionsREC_ORIG(i).distribution_type   := 'ORIGINATION';
4800 					l_distributionsREC_ORIG(i).activity  := 'LNS_APPROVAL';
4801 
4802 					logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Added LOAN_RECEIVABLE FOR ORIGINATION ' || l_code_combination_id_new_rec);
4803 					logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsREC_ORIG.count = ' || l_distributionsREC_ORIG.count);
4804 
4805 					l_distributionsREC_BILL(i).line_type           := 'PRIN';
4806 					l_distributionsREC_BILL(i).account_name        := 'LOAN_RECEIVABLE';
4807 					l_distributionsREC_BILL(i).code_combination_id := l_code_combination_id_new_rec;
4808 					l_distributionsREC_BILL(i).account_type        := 'CR';
4809 					l_distributionsREC_BILL(i).distribution_amount := null;
4810 					l_distributionsREC_BILL(i).distribution_type   := 'BILLING';
4811 
4812 					logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Added LOAN_RECEIVABLE FOR BILLING ' || l_code_combination_id_new_rec);
4813 					logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsREC_BILL.count = ' || l_distributionsREC_BILL.count);
4814 			       END IF;  -- IF l_new_ccid_already_exists = 'N'
4815 
4816 	                       l_sum := l_sum + l_ers_distribution_amount;
4817 	                       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_sum = ' || l_sum);
4818 	                   end if;
4819 
4820 	               end loop;
4821 
4822 	               close C_ERS_LOAN_RECEIVABLE;
4823 
4824 	           exception
4825 	                when others then
4826 --                        logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, 'failed to inherit receivables distributions');
4827                         FND_MESSAGE.SET_NAME('LNS', 'LNS_INHERIT_DIST_NOT_FOUND');
4828                         FND_MSG_PUB.ADD;
4829                         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
4830                         RAISE FND_API.G_EXC_ERROR;
4831 	           end;
4832 
4833 	       else
4834 	           logMessage(FND_LOG.level_statement, G_PKG_NAME, 'NO ACCOUNTED ADJUSTMENT EXISTS');
4835 	       end if;
4836 
4837            logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsREC_BILL.count = ' || l_distributionsREC_BILL.count);
4838            logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsREC_ORIG.count = ' || l_distributionsREC_ORIG.count);
4839 	       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsCLEAR_ORIG.count = ' || l_distributionsCLEAR_ORIG.count);
4840            --logMessage(FND_LOG.level_statement, G_PKG_NAME, 'TOTAL AMOUNT DUE = ' || l_total_amount_due);
4841            logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_funded_amount = ' || l_funded_amount);
4842 
4843 	       -- this logic is copied from PSA 04-19-2005
4844            logMessage(FND_LOG.level_statement, G_PKG_NAME, 'CALCULATING %AGES FOR LOANS RECEIVABLE...');
4845 
4846 	       for k in 1..l_distributionsREC_ORIG.count loop
4847 
4848                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Iteration ' || k);
4849                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calculating %ages for a loan with ERS Adjustments...');
4850 
4851                 if k <> l_distributionsREC_ORIG.count then
4852                     -- use the adjustment amounts to calculate percentages  -- this ensures percents but not cc_ids
4853                     -- this may or may not be an offending line karamach
4854 		    -- Bug#10266158 (Handling Multi Receivable Invoices in a loan)
4855 		    l_percent := round(l_distributionsREC_ORIG(k).distribution_amount / l_clearing_total_amount_due * 100,4);
4856                     --l_percent := round(l_distributionsCLEAR_ORIG(k).distribution_amount / l_clearing_total_amount_due * 100,4);
4857                     --l_percent := round(l_distributionsREC_ORIG(k).distribution_amount / l_receivable_total_amount_due * 100,4);
4858                     l_distributionsREC_ORIG(k).distribution_percent := l_percent;
4859                     l_distributionsREC_BILL(k).distribution_percent := l_percent;
4860                     -- ensure this amount is accurate it will get inserted into lns_distributions for loans booking
4861                     l_distributionsREC_ORIG(k).distribution_amount  := l_percent / 100 * l_funded_amount;
4862                 else
4863                     -- last row ensure that amounts = 100% and total = funded amount of loan
4864                     l_percent := 100 - l_running_percent;
4865                     l_distributionsREC_ORIG(k).distribution_percent := l_percent;
4866                     l_distributionsREC_BILL(k).distribution_percent := l_percent;
4867                     l_distributionsREC_ORIG(k).distribution_amount  := l_funded_amount - l_running_amount;
4868                 end if;
4869                 l_running_amount  := l_running_amount + l_distributionsREC_ORIG(k).distribution_amount;
4870                 l_running_percent := l_running_percent + l_percent;
4871 
4872                 l_percent := 0;
4873                 l_amount  := 0;
4874 
4875                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'distribution_percent = ' || l_distributionsREC_ORIG(k).distribution_percent);
4876                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'distribution_amount = ' || l_distributionsREC_ORIG(k).distribution_amount);
4877                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_running_percent = ' || l_running_percent);
4878                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_running_amount = ' || l_running_amount);
4879 
4880 	       end loop;
4881 
4882 	       l_running_percent := 0;
4883 	       l_running_amount  := 0;
4884 
4885 	       -- this logic is copied from PSA 04-19-2005
4886            logMessage(FND_LOG.level_statement, G_PKG_NAME, 'CALCULATING %AGES FOR LOANS CLEARING...');
4887 
4888 	       for k in 1..l_distributionsCLEAR_ORIG.count loop
4889 
4890 	            logMessage(FND_LOG.level_statement, G_PKG_NAME, 'iteration ' || k);
4891 
4892                 if k <> l_distributionsCLEAR_ORIG.count then
4893                     l_percent := round(l_distributionsCLEAR_ORIG(k).distribution_amount / l_clearing_total_amount_due * 100,4);
4894                     l_distributionsCLEAR_ORIG(k).distribution_percent  := l_percent;
4895                     l_distributionsCLEAR_ORIG(k).distribution_amount   := l_percent / 100 * l_funded_amount;
4896                 else
4897                     -- last row ensure that amounts = 100% and total = funded amount of loan
4898                     l_percent := 100 - l_running_percent;
4899                     l_distributionsCLEAR_ORIG(k).distribution_percent := 100 - l_running_percent;
4900                     l_distributionsCLEAR_ORIG(k).distribution_amount  := l_funded_amount - l_running_amount;
4901                 end if;
4902                 l_running_percent := l_running_percent + l_percent;
4903                 l_running_amount := l_running_amount + l_distributionsCLEAR_ORIG(k).distribution_amount;
4904 
4905                 l_percent := 0;
4906                 l_amount  := 0;
4907 
4908                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'distribution_percent = ' || l_distributionsCLEAR_ORIG(k).distribution_percent);
4909                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'distribution_amount = ' || l_distributionsCLEAR_ORIG(k).distribution_amount);
4910                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_running_percent = ' || l_running_percent);
4911                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_running_amount = ' || l_running_amount);
4912 
4913            end loop;
4914 
4915 	   l_bill_dist_cnt := 0;
4916 	   OPEN cur_bill_dist_count(p_loan_id);
4917 	   FETCH cur_bill_dist_count INTO l_bill_dist_cnt;
4918 	   CLOSE cur_bill_dist_count;
4919 
4920 	   logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_bill_dist_cnt is '||l_bill_dist_cnt);
4921 	   IF l_bill_dist_cnt < 3 THEN
4922 	       -- inherit remaining account_names based on loan class + type for
4923 	       -- principal / interest receivable, interest income
4924 
4925 	       delete from lns_distributions
4926 	        where loan_id = p_loan_id
4927 		  and account_name IN ('PRINCIPAL_RECEIVABLE', 'INTEREST_RECEIVABLE', 'INTEREST_INCOME');
4928 
4929 		logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Billing rows - deleted ||'||SQL%ROWCOUNT||' rows');
4930 
4931            	logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling defaultDistributionsCatch...');
4932 	       defaultDistributionsCatch(p_api_version                => 1.0
4933                                   ,p_init_msg_list              => FND_API.G_FALSE
4934                                   ,p_commit                     => FND_API.G_FALSE
4935 	                                ,p_loan_id                    => p_loan_id
4936                                   ,p_disb_header_id             => null
4937                                   ,p_loan_amount_adj_id         => null
4938 	                                ,p_include_loan_receivables   => l_include_receivables
4939                                   ,p_distribution_type          => null
4940 	                                ,x_distribution_tbl           => l_distributionsCatch
4941 	                                ,x_return_status              => l_return_status
4942 	                                ,x_msg_count                  => l_msg_count
4943 	                                ,x_msg_data                   => l_msg_data);
4944            	logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_return_status = ' || l_return_status);
4945            	if l_return_status <> 'S' then
4946                 	RAISE FND_API.G_EXC_ERROR;
4947            	end if;
4948 	   END IF;
4949 
4950       End if; --loan class
4951 
4952       l_distributionsCatch_count := l_distributionsCatch.count;
4953       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsCatch_count = ' || l_distributionsCatch_count);
4954 
4955       l_total_distributions      := l_distributions_count + l_distributionsCatch_count;
4956 
4957       n := 0;
4958       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Copying l_distributionsREC_ORIG to l_distributionsALL...');
4959       for j in 1..l_distributionsREC_ORIG.count loop
4960             n := n + 1;
4961             l_distributionsALL(n)     := l_distributionsREC_ORIG(j);
4962       end loop;
4963       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsALL.count = ' || l_distributionsALL.count);
4964 
4965       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Copying l_distributionsCLEAR_ORIG to l_distributionsALL...');
4966       for j in 1..l_distributionsCLEAR_ORIG.count loop
4967             n := n + 1;
4968             l_distributionsALL(n)     := l_distributionsCLEAR_ORIG(j);
4969       end loop;
4970       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsALL.count = ' || l_distributionsALL.count);
4971 
4972       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Copying l_distributionsREC_BILL to l_distributionsALL...');
4973       for j in 1..l_distributionsREC_BILL.count loop
4974             n := n + 1;
4975             l_distributionsALL(n)     := l_distributionsREC_BILL(j);
4976       end loop;
4977       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsALL.count = ' || l_distributionsALL.count);
4978 
4979       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Copying l_distributionsCatch to l_distributionsALL...');
4980       for j in 1..l_distributionsCatch.count
4981       loop
4982             n := n + 1;
4983             l_distributionsALL(n) := l_distributionsCatch(j);
4984       end loop;
4985       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsALL.count = ' || l_distributionsALL.count);
4986 
4987       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling do_insert_distributions...');
4988       do_insert_distributions(p_distributions_tbl => l_distributionsALL
4989                              ,p_loan_id           => p_loan_id);
4990 
4991       -- validate the accounting rows here
4992       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling lns_distributions_pub.validateAccounting...');
4993       lns_distributions_pub.validateAccounting(p_loan_id          => p_loan_id
4994                                               ,p_init_msg_list    => p_init_msg_list
4995                                               ,x_return_status    => l_return_status
4996                                               ,x_msg_count        => l_msg_count
4997                                               ,x_msg_data         => l_msg_data);
4998 
4999       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_return_status = ' || l_return_status);
5000       if l_return_status <> 'S' then
5001          FND_MESSAGE.SET_NAME('LNS', 'LNS_DEFAULT_DIST_NOT_FOUND');
5002          FND_MSG_PUB.ADD;
5003          LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
5004          RAISE FND_API.G_EXC_ERROR;
5005       end if;
5006 
5007       IF FND_API.to_Boolean(p_commit) THEN
5008           COMMIT WORK;
5009       END IF;
5010 
5011       FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
5012       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
5013 
5014 EXCEPTION
5015 
5016     WHEN FND_API.G_EXC_ERROR THEN
5017         ROLLBACK TO defaultDistributions;
5018         x_return_status := FND_API.G_RET_STS_ERROR;
5019         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
5020         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5021 
5022     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
5023         ROLLBACK TO defaultDistributions;
5024         x_return_status := FND_API.G_RET_STS_ERROR;
5025         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
5026         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5027 
5028     WHEN OTHERS THEN
5029         ROLLBACK TO defaultDistributions;
5030         x_return_status := FND_API.G_RET_STS_ERROR;
5031         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
5032         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5033 
5034 end defaultDistributions;
5035 
5036 /*=========================================================================
5037 || PUBLIC PROCEDURE onlineAccounting
5038 ||
5039 || DESCRIPTION
5040 ||      This procedure generates online-Accounting
5041 ||
5042 || PSEUDO CODE/LOGIC
5043 ||
5044 || PARAMETERS
5045 ||  Parameter:   p_loan_id => loan_ID
5046 ||               p_disb_header_id => null for ERS loan,
5047 ||                                  disb_header_id for DIRECT loan
5048 ||
5049 || Return value:  Standard  S = Success E = Error U = Unexpected
5050 ||
5051 || Source Tables:
5052 ||
5053 || Target Tables:
5054 ||
5055 || KNOWN ISSUES
5056 ||
5057 || NOTES
5058 ||
5059 || MODIFICATION HISTORY
5060 || Date                  Author            Description of Changes
5061 || 08-25-2005            raverma             Created
5062  *=======================================================================*/
5063 procedure onlineAccounting(p_loan_id            IN NUMBER
5064                             ,p_init_msg_list      IN VARCHAR2
5065                             ,p_accounting_mode    IN VARCHAR2
5066                             ,p_transfer_flag		  IN VARCHAR2
5067                             ,p_offline_flag       IN VARCHAR2
5068                             ,p_gl_posting_flag    IN VARCHAR2
5069                             ,x_return_status      OUT NOCOPY VARCHAR2
5070                             ,x_msg_count          OUT NOCOPY NUMBER
5071                             ,x_msg_data           OUT NOCOPY VARCHAR2)
5072 
5073 is
5074 	l_legal_entity_id	     number;
5075     l_accounting_batch_id  NUMBER;
5076 	l_errbuf               VARCHAR2(500);
5077 	l_retcode              NUMBER;
5078 	l_api_name		         varchar2(25);
5079 	l_loan_class           varchar2(30);
5080     l_transactions_count   number;
5081     l_error_counter        number;
5082     l_error_message        varchar2(2000);
5083     l_invoice_number       varchar2(100);
5084     l_entity_code          varchar2(30);
5085 
5086     cursor c_loan_info(p_loan_id number) is
5087     select h.legal_entity_id
5088 					,h.loan_class_code
5089       from lns_loan_headers h
5090      where h.loan_id = p_loan_id;
5091 
5092     -- this is only for loans entities
5093     cursor c_acc_errors (p_loan_id number, p_accounting_batch_id number) is
5094     select xlt.transaction_number, xlt.entity_code, err.encoded_msg
5095       from xla_accounting_errors err
5096           ,xla_Transaction_entities xlt
5097      where xlt.application_id = 206
5098        and err.accounting_batch_id = p_accounting_batch_id
5099        and err.entity_id = xlt.entity_id
5100        and xlt.entity_id in (select entity_id from xla_transaction_entities
5101                           where application_id = 206
5102                             and entity_code = 'LOANS'
5103                             and source_id_int_1 = p_loan_id
5104                             and source_id_int_2 IN
5105                              (select disb.disb_header_id
5106                                          from lns_disb_headers dh
5107                                              ,lns_distributions disb
5108                                         where disb.loan_id = p_loan_id
5109                                           and disb.disb_header_id = dh.disb_header_id
5110                                           and disb.account_name = 'LOAN_RECEIVABLE'
5111                                           and dh.status = 'FULLY_FUNDED'
5112                                           and not exists
5113                                             (select 'X'
5114                                                from xla_events xle
5115                                                     ,XLA_TRANSACTION_ENTITIES XLEE
5116                                                     ,xla_ae_headers aeh
5117                                               where XLE.application_id = 206
5118                                                 and XLE.event_id = disb.event_id
5119                                                 and XLE.entity_id = xlee.entity_id
5120                                                 and XLEE.source_id_int_1 = dh.loan_id
5121                                                 and XLEE.source_id_int_2 = dh.disb_header_id
5122                                                 and xlee.entity_id = aeh.entity_id
5123                                                 and xlee.ledger_id = aeh.ledger_id
5124                                                 and aeh.accounting_entry_status_code = 'F'
5125                                                 and xlee.entity_code = 'LOANS')
5126                                           or source_id_int_2 = -1)
5127 
5128                             and source_id_int_3 IN
5129                              (select disb.loan_amount_adj_id
5130                                          from lns_loan_amount_adjs ladj
5131                                              ,lns_distributions disb
5132                                         where disb.loan_id = p_loan_id
5133                                           and disb.loan_amount_adj_id = ladj.loan_amount_adj_id
5134                                           and disb.account_name = 'LOAN_RECEIVABLE'
5135                                           and ladj.status = 'APPROVED'
5136                                           and not exists
5137                                           (select 'X'
5138                                              from xla_events xle
5139                                                   ,XLA_TRANSACTION_ENTITIES XLEE
5140                                                   ,xla_ae_headers aeh
5141                                             where XLE.application_id = 206
5142                                               and XLE.event_id = disb.event_id
5143                                               and XLE.entity_id = xlee.entity_id
5144                                               and XLEE.source_id_int_1 = ladj.loan_id
5145                                               and XLEE.source_id_int_3 = ladj.loan_amount_adj_id
5146                                               and xlee.entity_id = aeh.entity_id
5147                                               and xlee.ledger_id = aeh.ledger_id
5148                                               and aeh.accounting_entry_status_code = 'F'
5149                                               and xlee.entity_code = 'LOANS')
5150                                           or source_id_int_3 = -1
5151                                           or source_id_int_3 IS NULL)
5152                                );
5153 
5154 begin
5155 
5156     SAVEPOINT onlineAccounting;
5157     l_api_name := 'onlineAccounting';
5158 
5159     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
5160     -- Initialize API return status to SUCCESS
5161     x_return_status := FND_API.G_RET_STS_SUCCESS;
5162     -- Initialize message list IF p_init_msg_list is set to TRUE.
5163     IF FND_API.to_Boolean( p_init_msg_list ) THEN
5164         FND_MSG_PUB.initialize;
5165     END IF;
5166 
5167     open c_loan_info(p_loan_id);
5168     fetch c_loan_info into l_legal_entity_id, l_loan_class;
5169     close c_loan_info;
5170 
5171     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'running on-line accounting for loan_id = ' || p_loan_id);
5172     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_accounting_mode = ' || p_accounting_mode);
5173     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_transfer_flag = ' || p_transfer_flag);
5174     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_gl_posting_flag = ' || p_gl_posting_flag);
5175     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_offline_flag = ' || p_offline_flag);
5176 
5177     if l_loan_class = 'ERS' then
5178 
5179         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'ERS loan accounting');
5180         -- at this point in time, the INVOICES and ADJUSTMENTS MUST have already been accounted for
5181         insert into XLA_ACCT_PROG_DOCS_GT
5182                 (entity_id)
5183             select entity_id from xla_transaction_entities
5184             where application_id = 206
5185             and entity_code = 'LOANS'
5186             and source_id_int_1 = p_loan_id
5187             and source_id_int_2 = -1
5188             and nvl(source_id_int_3, -1) = -1;
5189 
5190     else
5191 
5192         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'DIRECT loan accounting');
5193 
5194         -- can we make join thru lns_distributions
5195         insert into XLA_ACCT_PROG_DOCS_GT
5196                 (entity_id)
5197             select entity_id from xla_transaction_entities
5198             where application_id = 206
5199             and entity_code = 'LOANS'
5200             and source_id_int_1 = p_loan_id
5201             and (source_id_int_2 = -1
5202                  OR source_id_int_2 in (select disb.disb_header_id
5203                                         from lns_disb_headers dh
5204                                             ,lns_distributions disb
5205                                         where disb.loan_id = p_loan_id
5206                                         and disb.disb_header_id = dh.disb_header_id
5207                                         and disb.account_name = 'LOAN_RECEIVABLE'
5208                                         and ((disb.activity = 'LNS_SUBMIT_DISBURSEMENT') OR (disb.activity = 'DISBURSEMENT' AND dh.status = 'FULLY_FUNDED'))
5209 					)
5210                 )
5211             and (source_id_int_3 IS NULL  -- Before introducing MD loanAdjustment, source_id_int_3 values are NULL
5212                  OR source_id_int_3 = -1
5213                  OR source_id_int_3 in (select disb.loan_amount_adj_id
5214                                         from lns_loan_amount_adjs ladj
5215                                             ,lns_distributions disb
5216                                         where disb.loan_id = p_loan_id
5217                                         and disb.loan_amount_adj_id = ladj.loan_amount_adj_id
5218                                         and disb.account_name = 'LOAN_RECEIVABLE'
5219                                         and ladj.status = 'APPROVED')
5220                 );
5221     end if;
5222 
5223     select count(1) into l_transactions_count
5224     from XLA_ACCT_PROG_DOCS_GT;
5225     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'inserted transaction_entities ' || l_transactions_count);
5226     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'calling XLA_ACCOUNTING_PUB_PKG.accounting_program_doc_batch ');
5227     XLA_ACCOUNTING_PUB_PKG.accounting_program_doc_batch(p_application_id      => 206
5228                                                         ,p_accounting_mode     => p_accounting_mode
5229                                                         ,p_gl_posting_flag     => p_gl_posting_flag
5230                                                         ,p_accounting_batch_id => l_accounting_batch_id
5231                                                         ,p_errbuf              => l_errbuf
5232                                                         ,p_retcode             => l_retcode);
5233     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_retcode = ' || l_retcode);
5234     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_accounting_batch_id = ' || l_accounting_batch_id);
5235 
5236     if l_retcode = 0 then
5237 
5238         --FND_MESSAGE.SET_NAME('XLA', 'XLA_ONLINE_ACCT_SUCCESS');
5239         --FND_MSG_PUB.Add;
5240         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'online accounting SUCCESS! ');
5241 
5242     elsif l_retcode = 2 then
5243 
5244         FND_MESSAGE.SET_NAME('XLA', 'XLA_ONLINE_ACCTG_ERROR');
5245         FND_MSG_PUB.Add;
5246         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
5247         RAISE FND_API.G_EXC_ERROR;
5248 
5249     elsif l_retcode = 1 then
5250 
5251         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'online accounting failed ' || l_errbuf);
5252         /* query XLA_ACCOUNTING_ERRORS */
5253         l_error_counter := 0;
5254         open c_acc_errors(p_loan_id, l_accounting_batch_id);
5255 
5256         LOOP
5257 
5258             fetch c_acc_errors into
5259                 l_invoice_number,
5260                 l_entity_code,
5261                 l_error_message;
5262             exit when c_acc_errors%NOTFOUND;
5263 
5264             l_error_counter := l_error_counter + 1;
5265 
5266             if l_error_counter = 1 then
5267                 FND_MESSAGE.SET_NAME('XLA', 'XLA_ONLINE_ACCT_WARNING');
5268                 FND_MSG_PUB.Add;
5269                 LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
5270             end if;
5271 
5272             FND_MESSAGE.SET_NAME('LNS', 'LNS_ACC_DOC_FAIL');
5273             FND_MESSAGE.SET_TOKEN('DOC_NUM', l_invoice_number);
5274             FND_MESSAGE.SET_TOKEN('DOC_TYPE', l_entity_code);
5275             FND_MESSAGE.SET_TOKEN('ACC_ERR', l_error_message);
5276             FND_MSG_PUB.Add;
5277             LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
5278 
5279         END LOOP;
5280 
5281         close c_acc_errors;
5282 
5283         RAISE FND_API.G_EXC_ERROR;
5284     end if;
5285 
5286     FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
5287     commit;
5288     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
5289 
5290 EXCEPTION
5291 
5292     WHEN FND_API.G_EXC_ERROR THEN
5293         ROLLBACK TO onlineAccounting;
5294         x_return_status := FND_API.G_RET_STS_ERROR;
5295         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5296         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
5297 
5298     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
5299         ROLLBACK TO onlineAccounting;
5300         x_return_status := FND_API.G_RET_STS_ERROR;
5301         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5302         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
5303 
5304     WHEN OTHERS THEN
5305         ROLLBACK TO onlineAccounting;
5306         x_return_status := FND_API.G_RET_STS_ERROR;
5307         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5308         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
5309 
5310 end onlineAccounting;
5311 
5312 
5313 /*=========================================================================
5314 || PUBLIC PROCEDURE LNS_ACCOUNTING_CONCUR
5315 ||
5316 || DESCRIPTION
5317 ||      This procedure generates generates ERS distributions
5318 ||
5319 || PSEUDO CODE/LOGIC
5320 ||
5321 || PARAMETERS
5322 ||  Parameter:   p_loan_id => p_loan_ID
5323 ||
5324 || Return value:  Standard  CP parameters
5325 ||
5326 || Source Tables:
5327 ||
5328 || Target Tables:
5329 ||
5330 || KNOWN ISSUES
5331 ||
5332 || NOTES
5333 ||
5334 || MODIFICATION HISTORY
5335 || Date                  Author            Description of Changes
5336 || 01-05-2006            raverma             Created
5337 || 23-Dec-2008           mbolli             Changed the param name from loan_id
5338 ||                                            to p_loan_id
5339  *=======================================================================*/
5340 PROCEDURE LNS_ACCOUNTING_CONCUR(ERRBUF              OUT NOCOPY     VARCHAR2
5341                                ,RETCODE             OUT NOCOPY     VARCHAR2
5342                                ,P_LOAN_ID             IN             NUMBER)
5343 IS
5344    l_loan_class_code        varchar2(30);
5345    l_gl_date                date;
5346    l_api_name               varchar2(30);
5347    l_msg_count              NUMBER;
5348    l_msg_data               VARCHAR2(2000);
5349    l_return_Status          VARCHAR2(1);
5350    x_event_id               number;
5351    l_object_version_number  number;
5352    l_loan_header_rec        LNS_LOAN_HEADER_PUB.LOAN_HEADER_REC_TYPE;
5353    l_return                 boolean;
5354    l_do_billing             number;
5355    l_last_api_called        varchar2(100);
5356    l_request_id             number;
5357    l_org_id                 number;
5358    l_xml_output            BOOLEAN;
5359    l_iso_language          FND_LANGUAGES.iso_language%TYPE;
5360    l_iso_territory         FND_LANGUAGES.iso_territory%TYPE;
5361 
5362    cursor c_loan_info (c_loan_id number) is
5363    select loan_class_code
5364          ,gl_date
5365          ,OBJECT_VERSION_NUMBER
5366          ,org_id
5367      from lns_loan_headers
5368     where loan_id = c_loan_id;
5369 
5370     CURSOR do_billing_cur(C_LOAN_ID number) IS
5371     select nvl(count(1),0)
5372       from lns_fee_assignments
5373      where begin_installment_number = 0
5374        and end_installment_number = 0
5375        and end_date_active is null
5376        and billing_option = 'ORIGINATION'
5377        and loan_id = C_LOAN_ID;
5378 
5379 begin
5380 
5381     l_api_name   := 'LNS_ACCOUNTING_CONCUR';
5382 
5383     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, 'Generate Distributions process has started');
5384 
5385     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'LOAN_ID = ' || P_LOAN_ID);
5386     if P_LOAN_ID is null then
5387 
5388 --        LogMessage(FND_LOG.LEVEL_UNEXPECTED, 'ERROR: Loan must be set.');
5389     	FND_MESSAGE.SET_NAME('LNS', 'LNS_NO_LOAN');
5390 		FND_MSG_PUB.Add;
5391         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
5392         RAISE FND_API.G_EXC_ERROR;
5393 
5394     end if;
5395 
5396     open c_loan_info(P_LOAN_ID);
5397     fetch c_loan_info into l_loan_class_code, l_gl_date, l_object_version_number, l_org_id;
5398     close c_loan_info;
5399     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_class_code = ' || l_loan_class_code);
5400     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_gl_date = ' || l_gl_date);
5401     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_object_version_number = ' || l_object_version_number);
5402     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_org_id = ' || l_org_id);
5403 
5404 
5405     IF ((l_loan_class_code IS NULL) OR (l_loan_class_code <> 'ERS')) THEN
5406 	    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || ' - Only works for ERS loans.');
5407 	    return;
5408     END IF;
5409 
5410         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_XLA_EVENTS.create_event...');
5411         LNS_XLA_EVENTS.create_event(p_loan_id         =>  P_LOAN_ID
5412                                     ,p_disb_header_id  => -1
5413                                     ,p_loan_amount_adj_id => -1
5414                                     ,p_event_type_code => 'APPROVED'
5415                                     ,p_event_date      => l_gl_date
5416                                     ,p_event_status    => 'U'
5417                                     ,p_init_msg_list   => fnd_api.g_false
5418                                     ,p_commit          => fnd_api.g_false
5419                                     ,p_bc_flag         => 'N'
5420                                     ,x_event_id        => x_event_id
5421                                     ,x_return_status   => l_return_status
5422                                     ,x_msg_count       => l_msg_count
5423                                     ,x_msg_data        => l_msg_data);
5424         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'event_id = ' || x_event_id);
5425         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
5426 
5427         IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5428             FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCOUNTING_EVENT_ERROR');
5429             FND_MSG_PUB.ADD;
5430             --l_last_api_called := 'LNS_XLA_EVENTS.create_event';
5431             LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
5432             RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5433         END IF;
5434 
5435 
5436 
5437     -- we should do online accounting in batch mode here
5438     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling Lns_distributions_pub.defaultDistributions...');
5439     Lns_distributions_pub.defaultDistributions(p_api_version     => 1.0
5440                                                 ,p_init_msg_list   => FND_API.G_TRUE
5441                                                 ,p_commit          => FND_API.G_FALSE
5442                                                 ,p_loan_id         => P_LOAN_ID
5443                                                 ,p_loan_class_code => l_loan_class_code
5444                                                 ,x_return_status   => l_return_status
5445                                                 ,x_msg_count       => l_msg_count
5446                                                 ,x_msg_data        => l_msg_data);
5447     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
5448 
5449     IF l_return_status <> FND_API.G_RET_STS_SUCCESS  THEN
5450 --        logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Call to Lns_distributions_pub.defaultDistributions failed with status ' || l_return_status);
5451 --        fnd_file.put_line(FND_FILE.LOG, 'FAILED TO INHERIT DISTRIBUTIONS');
5452         --l_last_api_called := 'Lns_distributions_pub.defaultDistributions';
5453         RAISE FND_API.G_EXC_ERROR;
5454     ELSE
5455 
5456         if x_event_id is not null then
5457             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updating lns_distributions...');
5458             update lns_distributions
5459                 set event_id = x_event_id
5460             where loan_id = P_LOAN_ID
5461                 and account_name in ('LOAN_RECEIVABLE', 'LOAN_CLEARING')
5462                 and distribution_type = 'ORIGINATION'
5463 		and activity = 'LNS_APPROVAL'
5464 		and loan_line_id IS NULL;
5465             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Done');
5466         end if;
5467 
5468         -- finally update the loan header
5469         l_loan_header_rec.loan_id               := P_LOAN_ID;
5470         l_loan_header_rec.loan_status           := 'ACTIVE';
5471         l_loan_header_rec.secondary_status      := FND_API.G_MISS_CHAR;
5472         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Before call to LNS_LOAN_HEADER_PUB.update_loan');
5473         LNS_LOAN_HEADER_PUB.update_loan(p_init_msg_list         => FND_API.G_FALSE
5474                                         ,p_loan_header_rec       => l_loan_header_rec
5475                                         ,p_object_version_number => l_object_version_number
5476                                         ,x_return_status         => l_return_status
5477                                         ,x_msg_count             => l_msg_count
5478                                         ,x_msg_data              => l_msg_data);
5479         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
5480         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_msg_data = ' || l_msg_data);
5481 
5482     END IF;
5483 
5484     IF l_return_status <> FND_API.G_RET_STS_SUCCESS  THEN
5485         RAISE FND_API.G_EXC_ERROR;
5486     else
5487       -- now check if 0th installment needs billing
5488 
5489         /* check to start billing for 0-th installment */
5490         open do_billing_cur(l_loan_header_rec.loan_id);
5491         fetch do_billing_cur into l_do_billing;
5492         close do_billing_cur;
5493         LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_do_billing = ' || l_do_billing);
5494 
5495         if l_do_billing > 0 then
5496 
5497             LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Billing Concurrent Program to bill 0-th installment...');
5498             FND_REQUEST.SET_ORG_ID(l_org_id);
5499 
5500             -- Bug#6313716 : Invoke the function add_layout to specify the template type,code etc., before submitting request
5501             SELECT
5502             lower(iso_language),iso_territory
5503             INTO
5504             l_iso_language,l_iso_territory
5505             FROM
5506             FND_LANGUAGES
5507             WHERE
5508             language_code = USERENV('LANG');
5509 
5510             l_xml_output:=  fnd_request.add_layout(
5511                     template_appl_name  => 'LNS',
5512                     template_code       => 'LNSRPTBL',  --fix for bug 8830573
5513                     template_language   => l_iso_language,
5514                     template_territory  => l_iso_territory,
5515                     output_format       => 'PDF'
5516                     );
5517 
5518 
5519             l_request_id := FND_REQUEST.SUBMIT_REQUEST(
5520                             'LNS',
5521                             'LNS_BILLING',
5522                             '', '', FALSE,
5523                             null,
5524                             null,
5525                             null,
5526                             l_loan_header_rec.loan_id,
5527                             null,
5528                             null);
5529 
5530             if l_request_id = 0 then
5531                 l_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5532                 FND_MESSAGE.SET_NAME('LNS', 'LNS_BILLING_REQUEST_FAILED');
5533                 FND_MSG_PUB.Add;
5534                 l_last_api_called := 'FND_REQUEST.SUBMIT_REQUEST for 0th installment billing';
5535                 RAISE FND_API.G_EXC_ERROR;
5536             else
5537                 LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Successfully submited Billing Concurrent Program to bill 0-th installment. Request id = ' || l_request_id);
5538             end if;
5539 
5540             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'After call to submit request');
5541 
5542         end if;
5543 
5544     end if;
5545 
5546     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, ' ');
5547     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, '-------------------');
5548     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, 'Generate Distributions process has succeeded!');
5549 
5550 EXCEPTION
5551     WHEN others THEN
5552         l_return := FND_CONCURRENT.SET_COMPLETION_STATUS(
5553                         status  => 'ERROR',
5554                         message => 'Generate Distributions process has failed. Please review log file.');
5555         RETCODE := FND_API.G_RET_STS_ERROR;
5556         fnd_msg_pub.count_and_get(p_count => l_msg_count,   p_data => ERRBUF);
5557         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, ' ');
5558         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, '-------------------');
5559         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, 'Generate Distributions process has failed!');
5560 
5561 end LNS_ACCOUNTING_CONCUR;
5562 
5563 
5564 procedure createDistrForImport(p_api_version                IN NUMBER
5565                             ,p_init_msg_list              IN VARCHAR2
5566                             ,p_commit                     IN VARCHAR2
5567                             ,p_loan_id                    IN NUMBER
5568                             ,x_distribution_tbl           IN OUT NOCOPY lns_distributions_pub.distribution_tbl
5569                             ,x_return_status              OUT NOCOPY VARCHAR2
5570                             ,x_msg_count                  OUT NOCOPY NUMBER
5571                             ,x_msg_data                   OUT NOCOPY VARCHAR2)
5572 
5573 is
5574 /*------------------------------------------------------------------------+
5575  | Local Variable Declarations and initializations                        |
5576  +-----------------------------------------------------------------------*/
5577     l_api_name                 varchar2(30);
5578     l_msg_count                NUMBER;
5579     l_msg_data                 VARCHAR2(2000);
5580     l_return_Status            VARCHAR2(1);
5581     l_event_id                 NUMBER;
5582     l_gl_date                  DATE;
5583 
5584 /*------------------------------------------------------------------------+
5585  | Cursor Declarations                                                    |
5586  +-----------------------------------------------------------------------*/
5587 
5588     cursor c_loan_info (c_loan_id number) is
5589         select gl_date
5590         from lns_loan_headers
5591         where loan_id = c_loan_id;
5592 
5593 begin
5594 
5595     SAVEPOINT createDistrForImport;
5596     l_api_name   := 'createDistrForImport';
5597     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
5598 
5599     -- Initialize message list IF p_init_msg_list is set to TRUE.
5600     IF FND_API.to_Boolean( p_init_msg_list ) THEN
5601         FND_MSG_PUB.initialize;
5602     END IF;
5603 
5604     -- Initialize API return status to SUCCESS
5605     x_return_status := FND_API.G_RET_STS_SUCCESS;
5606 
5607     /* deleting any existing accounting rows */
5608     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' deleting any existing accounting rows');
5609     delete from lns_distributions
5610     where loan_id = p_loan_id;
5611 
5612     do_insert_distributions(p_distributions_tbl => x_distribution_tbl
5613                             ,p_loan_id           => p_loan_id);
5614 
5615     -- validate the accounting rows here
5616     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' validating Accounting');
5617     lns_distributions_pub.validateAccounting(p_loan_id          => p_loan_id
5618                                             ,p_init_msg_list    => p_init_msg_list
5619                                             ,x_return_status    => l_return_status
5620                                             ,x_msg_count        => l_msg_count
5621                                             ,x_msg_data         => l_msg_data);
5622 
5623     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'Accounting status is ' || l_return_status);
5624     if l_return_status <> 'S' then
5625         FND_MESSAGE.SET_NAME('LNS', 'LNS_DEFAULT_DIST_NOT_FOUND');
5626         FND_MSG_PUB.ADD;
5627         RAISE FND_API.G_EXC_ERROR;
5628     end if;
5629 
5630     /* For Import Loans, there is no need to create SLA events and accounting b'coz the imported loan accounting date
5631         might be in GL CLosed period
5632 
5633     open c_loan_info(P_LOAN_ID);
5634     fetch c_loan_info into l_gl_date;
5635     close c_loan_info;
5636     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_gl_date = ' || l_gl_date);
5637 
5638     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_XLA_EVENTS.create_event...');
5639     LNS_XLA_EVENTS.create_event(p_loan_id         =>  P_LOAN_ID
5640                                 ,p_disb_header_id  => -1
5641                                 ,p_loan_amount_adj_id => -1
5642                                 ,p_event_type_code => 'APPROVED'
5643                                 ,p_event_date      => l_gl_date
5644                                 ,p_event_status    => 'U'
5645                                 ,p_init_msg_list   => fnd_api.g_false
5646                                 ,p_commit          => fnd_api.g_false
5647                                 ,p_bc_flag         => 'N'
5648                                 ,x_event_id        => l_event_id
5649                                 ,x_return_status   => l_return_status
5650                                 ,x_msg_count       => l_msg_count
5651                                 ,x_msg_data        => l_msg_data);
5652     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
5653     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
5654 
5655     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5656         FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCOUNTING_EVENT_ERROR');
5657         FND_MSG_PUB.ADD;
5658         --l_last_api_called := 'LNS_XLA_EVENTS.create_event';
5659         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
5660         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5661     END IF;
5662 
5663     if l_event_id is not null then
5664         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updating lns_distributions...');
5665         update lns_distributions
5666             set event_id = l_event_id
5667         where loan_id = P_LOAN_ID
5668             and account_name in ('LOAN_RECEIVABLE', 'LOAN_CLEARING')
5669             and distribution_type = 'ORIGINATION'
5670 	    and activity = 'LNS_APPROVAL'
5671 	    and loan_line_id IS NULL;
5672         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Done');
5673     end if;
5674 
5675    */
5676 
5677     IF FND_API.to_Boolean(p_commit)
5678     THEN
5679         COMMIT WORK;
5680     END IF;
5681 
5682     FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
5683 
5684     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
5685 
5686 EXCEPTION
5687 
5688     WHEN FND_API.G_EXC_ERROR THEN
5689         x_return_status := FND_API.G_RET_STS_ERROR;
5690         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5691         ROLLBACK TO createDistrForImport;
5692 
5693     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
5694         x_return_status := FND_API.G_RET_STS_ERROR;
5695         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5696         ROLLBACK TO createDistrForImport;
5697 
5698     WHEN OTHERS THEN
5699         x_return_status := FND_API.G_RET_STS_ERROR;
5700         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5701         ROLLBACK TO createDistrForImport;
5702 
5703 end;
5704 
5705 
5706 
5707 /*=========================================================================
5708 || PROCEDURE DEFAULT_ADJUSTMENT_DISTRIBS
5709 ||
5710 || DESCRIPTION
5711 ||   This procedure does funds check / funds reserve for negative loanAdjustment
5712 ||
5713 ||
5714 || PARAMETERS   p_loan_amount_adj_id => loan adjustment identifier
5715 ||              p_loan_id            => loan_id is considered to retrieve
5716 ||                        pending adjustment if loan_amount_adj_id is NULL
5717 ||
5718 || Return value:  None
5719 ||
5720 || Source Tables: NA
5721 ||
5722 || Target Tables: NA
5723 ||
5724 || MODIFICATION HISTORY
5725 || Date                  Author            Description of Changes
5726 || 26-Mar-2010           mbolli              Created
5727  *=======================================================================*/
5728 PROCEDURE DEFAULT_ADJUSTMENT_DISTRIBS(p_init_msg_list          in varchar2
5729                             ,p_commit                 in varchar2
5730                             ,p_loan_amount_adj_id     in number  DEFAULT NULL
5731                             ,p_loan_id                in number
5732                             ,x_return_status          OUT NOCOPY VARCHAR2
5733                             ,x_msg_count              OUT NOCOPY NUMBER
5734                             ,x_msg_data               OUT NOCOPY VARCHAR2)
5735 is
5736     l_api_name              varchar2(50);
5737     l_msg_count             NUMBER;
5738     l_msg_data              VARCHAR2(2000);
5739     l_return_Status         VARCHAR2(1);
5740     l_loan_id               number;
5741     l_loan_amount_adj_id    number;
5742     l_adj_status		varchar2(30);
5743     l_adj_amount		number;
5744 
5745 
5746     cursor c_loan_adj_det(c_loan_amount_adj_id number) is
5747       SELECT LOAN_ID, STATUS, ADJUSTMENT_AMOUNT
5748       FROM LNS_LOAN_AMOUNT_ADJS
5749       WHERE loan_amount_adj_id = c_loan_amount_adj_id;
5750 
5751 
5752     cursor c_loan_adj(c_loan_id number) is
5753       SELECT LOAN_AMOUNT_ADJ_ID, STATUS, ADJUSTMENT_AMOUNT
5754       FROM LNS_LOAN_AMOUNT_ADJS
5755       WHERE loan_id = c_loan_id
5756         AND status = 'PENDING';
5757 
5758 BEGIN
5759 
5760     SAVEPOINT adjustment_distribs_pvt;
5761     l_api_name := 'DEFAULT_ADJUSTMENT_DISTRIBS';
5762     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
5763     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_amount_adj_id = '  || p_loan_amount_adj_id);
5764     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = '  || p_loan_id);
5765 
5766     -- Initialize message list IF p_init_msg_list is set to TRUE.
5767     IF FND_API.to_Boolean( p_init_msg_list ) THEN
5768         FND_MSG_PUB.initialize;
5769     END IF;
5770 
5771     -- Initialize API return status to SUCCESS
5772     x_return_status         := FND_API.G_RET_STS_SUCCESS;
5773 
5774     -- We can't default distributions without valid loan adjustment
5775     IF p_loan_amount_adj_id IS NULL THEN
5776         -- Retrieve the Pending Loan Amount Adjustment Id of the loan
5777         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Retrieve the pending loan_amount_adj_id based on the input loan_id');
5778 
5779         lns_utility_pub.validate_any_id(p_api_version    =>  1.0
5780                                       ,p_init_msg_list  =>  p_init_msg_list
5781                                       ,x_msg_count      =>  l_msg_count
5782                                       ,x_msg_data       =>  l_msg_data
5783                                       ,x_return_status  =>  l_return_status
5784                                       ,p_col_id         =>  p_loan_id
5785                                       ,p_col_name       =>  'LOAN_ID'
5786                                       ,p_table_name     =>  'LNS_LOAN_HEADERS');
5787 
5788         if l_return_status <> FND_API.G_RET_STS_SUCCESS then
5789             FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
5790             FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_ID');
5791             FND_MESSAGE.SET_TOKEN('VALUE', p_loan_id);
5792             FND_MSG_PUB.ADD;
5793             RAISE FND_API.G_EXC_ERROR;
5794         end if;
5795 
5796         OPEN c_loan_adj(p_loan_id);
5797         FETCH c_loan_adj INTO l_loan_amount_adj_id, l_adj_status, l_adj_amount;
5798         CLOSE c_loan_adj;
5799 
5800         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_loan_amount_adj_id = ' || l_loan_amount_adj_id);
5801         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_adj_status = ' || l_adj_status);
5802         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_adj_amount = ' || l_adj_amount);
5803 
5804 
5805         -- We can't default distributions without valid loan adjustment
5806         IF (l_loan_amount_adj_id IS NULL) THEN
5807             FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
5808             FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_AMOUNT_ADJ_ID');
5809             FND_MESSAGE.SET_TOKEN('VALUE', l_loan_amount_adj_id);
5810             FND_MSG_PUB.ADD;
5811             LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
5812             RAISE FND_API.G_EXC_ERROR;
5813         END IF;
5814 
5815 
5816         l_loan_id := p_loan_id;
5817 
5818     ELSE  -- ELSE OF p_loan_amount_adj_id IS NULL
5819         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Validating input p_loan_amount_adj_id');
5820 
5821         lns_utility_pub.validate_any_id(p_api_version    =>  1.0
5822                                       ,p_init_msg_list  =>  p_init_msg_list
5823                                       ,x_msg_count      =>  l_msg_count
5824                                       ,x_msg_data       =>  l_msg_data
5825                                       ,x_return_status  =>  l_return_status
5826                                       ,p_col_id         =>  p_loan_amount_adj_id
5827                                       ,p_col_name       =>  'LOAN_AMOUNT_ADJ_ID'
5828                                       ,p_table_name     =>  'LNS_LOAN_AMOUNT_ADJS');
5829 
5830         if l_return_status <> FND_API.G_RET_STS_SUCCESS then
5831             FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
5832             FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_AMOUNT_ADJ_ID');
5833             FND_MESSAGE.SET_TOKEN('VALUE', p_loan_amount_adj_id);
5834             FND_MSG_PUB.ADD;
5835             RAISE FND_API.G_EXC_ERROR;
5836         end if;
5837 
5838 
5839         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'fetching l_loan_adj details');
5840 
5841         open c_loan_adj_det(p_loan_amount_adj_id);
5842         fetch c_loan_adj_det into l_loan_id, l_adj_status, l_adj_amount;
5843         close c_loan_adj_det;
5844 
5845         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_loan_id = ' || l_loan_id);
5846         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_adj_status = ' || l_adj_status);
5847         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_adj_amount = ' || l_adj_amount);
5848 
5849         l_loan_amount_adj_id  :=  p_loan_amount_adj_id;
5850 
5851     END IF;   -- IF p_loan_amount_adj_id IS NULL
5852 
5853     IF l_adj_status in ('APPROVED', 'REJECTED', 'DELETED') THEN
5854       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'The distributions of adjustment with status '||l_adj_status||' cant be deleted');
5855 
5856       FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
5857       FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_AMOUNT_ADJ_ID');
5858       FND_MESSAGE.SET_TOKEN('VALUE', l_loan_amount_adj_id);
5859       FND_MSG_PUB.ADD;
5860       RAISE FND_API.G_EXC_ERROR;
5861 
5862     ELSE
5863       /* delete any rows for this loan before inheritance do not delete FEE_RECEIVABLE or FEE_INCOME rows*/
5864       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Deleting any existing adjustment accounting rows for '||l_loan_id||'-'||l_loan_amount_adj_id);
5865 
5866       delete from lns_distributions
5867       where loan_id = l_loan_id
5868         and loan_amount_adj_id = l_loan_amount_adj_id
5869         and account_name in ('LOAN_RECEIVABLE', 'LOAN_PAYABLE');
5870 
5871       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Deleted '||SQL%ROWCOUNT||' rows succesfully');
5872 
5873     END IF;
5874 
5875     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' Calling create_DisbursementDistribs');
5876     LNS_DISTRIBUTIONS_PUB.create_DisbursementDistribs(p_api_version  => 1
5877 			                               ,p_init_msg_list  => 'F'
5878 			                               ,p_commit         => 'T'
5879 			                               ,p_loan_id        =>  l_loan_id
5880                                      ,p_disb_header_id =>  NULL
5881                                      ,p_loan_amount_adj_id => l_loan_amount_adj_id
5882                                      ,p_activity_type  =>  'LOAN_AMOUNT_ADJUSTMENT'
5883 			                               ,x_return_status  =>  l_return_status
5884 			                               ,x_msg_count      =>  l_msg_count
5885 			                               ,x_msg_data       =>  l_msg_data);
5886     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' The return status is '||l_return_status);
5887 
5888     IF l_return_status <> 'S' THEN
5889       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' CreationDisbursementDistribs failed with error '||l_msg_data);
5890       RAISE FND_API.G_EXC_ERROR;
5891     END IF;
5892 
5893 
5894     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
5895 
5896 EXCEPTION
5897 
5898     WHEN FND_API.G_EXC_ERROR THEN
5899         ROLLBACK TO adjustment_distribs_pvt;
5900         x_return_status := FND_API.G_RET_STS_ERROR;
5901         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5902         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5903 
5904     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
5905         ROLLBACK TO adjustment_distribs_pvt;
5906         x_return_status := FND_API.G_RET_STS_ERROR;
5907         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5908         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5909 
5910     WHEN OTHERS THEN
5911         ROLLBACK TO adjustment_distribs_pvt;
5912         x_return_status := FND_API.G_RET_STS_ERROR;
5913         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
5914         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5915  END DEFAULT_ADJUSTMENT_DISTRIBS;
5916 
5917 /*=========================================================================
5918 || PROCEDURE LOAN_ADJUSTMENT_BUDGET_CONTROL
5919 ||
5920 || DESCRIPTION
5921 ||   This procedure does funds check / funds reserve for negative loanAdjustment
5922 ||
5923 ||
5924 || PARAMETERS   p_loan_amount_adj_id => loan adjustment identifier
5925 ||              p_loan_id            => loan_id is considered if loan_amount_adj_id is NULL
5926 ||              p_budgetary_control_mode => 'C' Check ; 'R' Reserve
5927 ||
5928 || Return value:  x_budgetary_status_code
5929 ||                    SUCCESS   = FUNDS CHECK / RESERVE SUCCESSFUL
5930 ||                    PARTIAL   = AT LEAST ONE EVENT FAILED
5931 ||                    FAIL      = FUNDS CHECK / RESERVE FAILED
5932 ||                    XLA_ERROR = XLA SetUp ERROR
5933 ||                    ADVISORY  = BUDGETARY WARNING
5934 ||
5935 || Source Tables: NA
5936 ||
5937 || Target Tables: NA
5938 ||
5939 || MODIFICATION HISTORY
5940 || Date                  Author            Description of Changes
5941 || 24-Mar-2010           mbolli              Created
5942  *=======================================================================*/
5943 PROCEDURE LOAN_ADJUSTMENT_BUDGET_CONTROL(p_init_msg_list          in varchar2
5944                             ,p_commit                 in varchar2
5945                             ,p_loan_amount_adj_id     in number  DEFAULT NULL
5946                             ,p_loan_id                in number
5947                             ,p_budgetary_control_mode in varchar2
5948                             ,x_budgetary_status_code  out nocopy varchar2
5949                             ,x_return_status          OUT NOCOPY VARCHAR2
5950                             ,x_msg_count              OUT NOCOPY NUMBER
5951                             ,x_msg_data               OUT NOCOPY VARCHAR2)
5952 is
5953     l_api_name              varchar2(50);
5954     l_msg_count             NUMBER;
5955     l_msg_data              VARCHAR2(2000);
5956     l_return_Status         VARCHAR2(1);
5957     l_status_code           varchar2(50);
5958     l_packet_id             number;
5959     l_event_id              number;
5960     l_version               number;
5961     l_budget_req_approval   varchar2(1);
5962     l_funds_reserved_flag   varchar2(1);
5963     l_gl_date               date;
5964     l_budget_event_exists   number;
5965     l_loan_header_rec       LNS_LOAN_HEADER_PUB.loan_header_rec_type;
5966     l_loan_id               number;
5967     l_loan_amount_adj_id    number;
5968     l_adj_status		varchar2(30);
5969     l_adj_amount		number;
5970     x_event_id              number;
5971     l_event_type            varchar2(30);
5972 
5973     cursor c_budget_req(c_loan_amount_adj_id number) is
5974     select nvl(p.BDGT_REQ_FOR_APPR_FLAG, 'N')
5975                ,nvl(ladj.funds_reserved_flag, 'N')
5976                ,ladj.EFFECTIVE_DATE    -- fix for bug 16068385
5977         from lns_loan_headers h,
5978                 lns_loan_products p,
5979                 lns_loan_amount_adjs ladj
5980         where p.loan_product_id = h.product_id
5981           and ladj.loan_id = h.loan_id
5982           and ladj.loan_amount_adj_id = c_loan_amount_adj_id;
5983 
5984     -- get budgetary control events only
5985     cursor c_events(c_loan_amount_adj_id number, c_event_type varchar2) is
5986     select event_id
5987             from xla_transaction_entities xlee
5988                 ,xla_events xle
5989         where xle.application_id = 206
5990         and xle.entity_id = xlee.entity_id
5991             and xlee.source_id_int_3 = c_loan_amount_adj_id
5992             and xle.event_type_code = c_event_type
5993             and xle.budgetary_control_flag = 'Y'
5994             and xle.process_status_code <> 'P'
5995         order by event_id desc;
5996 
5997 
5998     cursor c_loan_adj_det(c_loan_amount_adj_id number) is
5999       SELECT LOAN_ID, STATUS, ADJUSTMENT_AMOUNT
6000       FROM LNS_LOAN_AMOUNT_ADJS
6001       WHERE loan_amount_adj_id = c_loan_amount_adj_id;
6002 
6003 
6004     cursor c_loan_adj(c_loan_id number) is
6005       SELECT LOAN_AMOUNT_ADJ_ID, STATUS, ADJUSTMENT_AMOUNT
6006       FROM LNS_LOAN_AMOUNT_ADJS
6007       WHERE loan_id = c_loan_id
6008         AND status = 'PENDING';
6009 
6010 	cursor c_obj_vers(p_loan_id number) is
6011 	  	select object_version_number
6012 		from lns_loan_headers
6013 		where loan_id = p_loan_id;
6014 
6015 	cursor c_obj_vers_adj(c_loan_amount_adj_id number) is
6016 	  	select object_version_number
6017 		from lns_loan_amount_adjs
6018 		where loan_amount_adj_id = c_loan_amount_adj_id;
6019 
6020 
6021     cursor c_budget_event(c_loan_adj_id number, c_event_type varchar2) is
6022     select count(1)
6023       from xla_transaction_entities xlee
6024           ,xla_events xle
6025       where xle.application_id = 206
6026         and xle.entity_id = xlee.entity_id
6027         and xlee.source_id_int_3 = c_loan_adj_id
6028         and xle.event_type_code = c_event_type
6029         and xle.budgetary_control_flag = 'Y'
6030         and xle.process_status_code <> 'P';
6031 
6032 begin
6033 
6034     SAVEPOINT loan_adj_reverse_bc_pvt;
6035     l_api_name := 'LOAN_ADJUSTMENT_BUDGET_CONTROL';
6036     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
6037     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_amount_adj_id = '  || p_loan_amount_adj_id);
6038     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = '  || p_loan_id);
6039     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_budgetary_control_mode = ' || p_budgetary_control_mode);
6040 
6041     -- Initialize message list IF p_init_msg_list is set to TRUE.
6042     IF FND_API.to_Boolean( p_init_msg_list ) THEN
6043         FND_MSG_PUB.initialize;
6044     END IF;
6045 
6046     -- Initialize API return status to SUCCESS
6047     x_return_status         := FND_API.G_RET_STS_SUCCESS;
6048 
6049     -- We can't check funds without valid loan adjustment
6050     IF p_loan_amount_adj_id IS NULL THEN
6051         -- Retrieve the Pending Loan Amount Adjustment Id of the loan
6052         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Retrieve the pending loan_amount_adj_id based on the input loan_id');
6053 
6054         lns_utility_pub.validate_any_id(p_api_version    =>  1.0
6055                                       ,p_init_msg_list  =>  p_init_msg_list
6056                                       ,x_msg_count      =>  l_msg_count
6057                                       ,x_msg_data       =>  l_msg_data
6058                                       ,x_return_status  =>  l_return_status
6059                                       ,p_col_id         =>  p_loan_id
6060                                       ,p_col_name       =>  'LOAN_ID'
6061                                       ,p_table_name     =>  'LNS_LOAN_HEADERS');
6062 
6063         if l_return_status <> FND_API.G_RET_STS_SUCCESS then
6064             FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
6065             FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_ID');
6066             FND_MESSAGE.SET_TOKEN('VALUE', p_loan_id);
6067             FND_MSG_PUB.ADD;
6068             RAISE FND_API.G_EXC_ERROR;
6069         end if;
6070 
6071         OPEN c_loan_adj(p_loan_id);
6072         FETCH c_loan_adj INTO l_loan_amount_adj_id, l_adj_status, l_adj_amount;
6073         CLOSE c_loan_adj;
6074 
6075         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_loan_amount_adj_id = ' || l_loan_amount_adj_id);
6076 
6077         -- We can't check funds without valid loan adjustment
6078         IF (l_loan_amount_adj_id IS NULL) THEN
6079             FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
6080             FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_AMOUNT_ADJ_ID');
6081             FND_MESSAGE.SET_TOKEN('VALUE', l_loan_amount_adj_id);
6082             FND_MSG_PUB.ADD;
6083             LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6084             RAISE FND_API.G_EXC_ERROR;
6085         END IF;
6086 
6087 
6088         l_loan_id := p_loan_id;
6089 
6090     ELSE  -- ELSE OF p_loan_amount_adj_id IS NULL
6091         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Validating input p_loan_amount_adj_id');
6092 
6093         lns_utility_pub.validate_any_id(p_api_version    =>  1.0
6094                                       ,p_init_msg_list  =>  p_init_msg_list
6095                                       ,x_msg_count      =>  l_msg_count
6096                                       ,x_msg_data       =>  l_msg_data
6097                                       ,x_return_status  =>  l_return_status
6098                                       ,p_col_id         =>  p_loan_amount_adj_id
6099                                       ,p_col_name       =>  'LOAN_AMOUNT_ADJ_ID'
6100                                       ,p_table_name     =>  'LNS_LOAN_AMOUNT_ADJS');
6101 
6102         if l_return_status <> FND_API.G_RET_STS_SUCCESS then
6103             FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
6104             FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_AMOUNT_ADJ_ID');
6105             FND_MESSAGE.SET_TOKEN('VALUE', p_loan_amount_adj_id);
6106             FND_MSG_PUB.ADD;
6107             RAISE FND_API.G_EXC_ERROR;
6108         end if;
6109 
6110 
6111         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'fetching l_loan_adj details');
6112 
6113         open c_loan_adj_det(p_loan_amount_adj_id);
6114         fetch c_loan_adj_det into l_loan_id, l_adj_status, l_adj_amount;
6115         close c_loan_adj_det;
6116 
6117         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_loan_id = ' || l_loan_id);
6118         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_adj_status = ' || l_adj_status);
6119         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_adj_amount = ' || l_adj_amount);
6120 
6121 
6122         IF l_adj_status <> 'PENDING' THEN
6123             FND_MESSAGE.SET_NAME('LNS', 'LNS_CHK_PENDING_ADJ');
6124             FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_ID');
6125             FND_MESSAGE.SET_TOKEN('VALUE', l_loan_id);
6126             FND_MSG_PUB.ADD;
6127             RAISE FND_API.G_EXC_ERROR;
6128         END IF;
6129 
6130         l_loan_amount_adj_id  :=  p_loan_amount_adj_id;
6131 
6132     END IF;   -- IF p_loan_amount_adj_id IS NULL
6133 
6134     -- If it is negative adjustment then the event is reversal else it is adj approved
6135     l_event_type    :=  'DIRECT_LOAN_ADJ_APPROVED';
6136     IF l_adj_amount < 0 THEN
6137       l_event_type  :=  'DIRECT_LOAN_ADJ_REVERSED';
6138     END IF;
6139 
6140     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_event_type = ' || l_event_type);
6141 
6142     if ((lns_utility_pub.IS_FED_FIN_ENABLED = 'Y' or lns_utility_pub.IS_ENCUM_FIN_ENABLED = 'Y')  AND l_loan_amount_adj_id IS NOT NULL) then
6143 
6144         -- check if budget event exists
6145         -- find if budgetary event already exists, if not, create the event
6146         open c_budget_event(l_loan_amount_adj_id, l_event_type);
6147         fetch c_budget_event into l_budget_event_exists;
6148         close c_budget_event;
6149         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_budget_event_exists = ' || l_budget_event_exists);
6150 
6151         open c_budget_req(l_loan_amount_adj_id);
6152         fetch c_budget_req into l_budget_req_approval, l_funds_reserved_flag, l_gl_date;
6153         close c_budget_req;
6154 
6155         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_budget_req_approval = '  || l_budget_req_approval);
6156         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_funds_reserved_flag = '  || l_funds_reserved_flag);
6157 
6158         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_XLA_EVENTS.create_event...');
6159 
6160         LNS_XLA_EVENTS.create_event(p_loan_id         => p_loan_id
6161                                     ,p_disb_header_id  => -1
6162                                     ,p_loan_amount_adj_id => l_loan_amount_adj_id
6163                                     ,p_event_type_code => l_event_type
6164                                     ,p_event_date      => l_gl_date
6165                                     ,p_event_status    => 'U'
6166                                     ,p_init_msg_list   => fnd_api.g_false
6167                                     ,p_commit          => fnd_api.g_false
6168                                     ,p_bc_flag         => 'Y'
6169                                     ,x_event_id        => l_event_id
6170                                     ,x_return_status   => x_return_status
6171                                     ,x_msg_count       => x_msg_count
6172                                     ,x_msg_data        => x_msg_data);
6173         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'x_return_status = ' || x_return_status);
6174         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'x_event_id ' || l_event_id);
6175 
6176         IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
6177                 FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCOUNTING_EVENT_ERROR');
6178                 FND_MSG_PUB.ADD;
6179                 logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6180                 RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6181         END IF;
6182 
6183 	-- stamp the eventID onto the lns_distributions table
6184         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'stamping eventID on lns_distributions');
6185 
6186 
6187 
6188         update lns_distributions
6189         set event_id = l_event_id
6190               ,last_update_date = sysdate
6191         where distribution_type = 'ORIGINATION'
6192            and loan_id             = p_loan_id
6193            and loan_amount_adj_id  =  l_loan_amount_adj_id
6194 	       and activity = 'LOAN_AMOUNT_ADJUSTMENT';
6195 
6196         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updated event_id succesfully for '||SQL%ROWCOUNT||' rows');
6197 
6198         -- now process the event
6199         if (l_funds_reserved_flag <> 'Y')then
6200             --and p_budgetary_control_mode = 'R' then
6201 
6202 
6203            IF l_event_id IS NOT NULL THEN
6204 
6205                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
6206 
6207                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'inserting into  PSA_BC_XLA_EVENTS_GT ');
6208                 INSERT  INTO  PSA_BC_XLA_EVENTS_GT (event_id, result_code)
6209                 			values (l_event_id, 'FAIL');
6210 
6211                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling PSA_BC_XLA_PUB.Budgetary_Control  '  || l_event_id);
6212                 PSA_BC_XLA_PUB.Budgetary_Control(p_api_version      => 1.0
6213                                                 ,p_init_msg_list    => FND_API.G_FALSE
6214                                                 ,x_return_status    => l_return_status
6215                                                 ,x_msg_count        => l_msg_count
6216                                                 ,x_msg_data         => l_msg_data
6217                                                 ,p_application_id   => 206
6218                                                 ,p_bc_mode          => p_budgetary_control_mode
6219                                                 ,p_override_flag    => null
6220                                                 ,p_user_id          => null
6221                                                 ,p_user_resp_id     => null
6222                                                 ,x_status_code      => l_status_code
6223                                                 ,x_packet_ID        => l_packet_id);
6224 	        END IF;
6225 
6226            logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'BC status is = ' || l_return_status);
6227            logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_status_code = ' || l_status_code);
6228            logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_packet_id = ' || l_packet_id);
6229 
6230            if (l_return_status <> 'S' ) then
6231 
6232                 l_return_status         := FND_API.G_RET_STS_ERROR;
6233                 FND_MESSAGE.SET_NAME('LNS', 'LNS_API_OTHERS_EXCEP');
6234                 FND_MESSAGE.SET_TOKEN('ERROR' ,'Call to PSA_BC_XLA_PUB.Budgetary_Control failed with Status Code = ' || l_status_code);
6235                 FND_MSG_PUB.ADD;
6236                 logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6237                 RAISE FND_API.G_EXC_ERROR;
6238 
6239            else
6240                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_budget_req_approval = '  || l_budget_req_approval);
6241 
6242                 if ( l_budget_req_approval = 'N' and p_budgetary_control_mode = 'R'
6243                     and (l_status_code = 'FAIL' or l_status_code = 'PARTIAL' or l_status_code = 'XLA_ERROR')) then
6244 
6245                     x_budgetary_status_code  := l_status_code;
6246                     x_return_status          := l_return_status;
6247 
6248                     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, ' BudgetReserve is not mandatory for LoanAdjustment Approval, so returning to invoked method');
6249 
6250                     FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
6251 
6252                     return;
6253 
6254                 end if;
6255 
6256 /*
6257                 if l_status_code NOT IN ('SUCCESS','ADVISORY') then
6258                     IF  (l_status_code = 'PARTIAL') THEN
6259                         FND_MESSAGE.SET_NAME('LNS', 'LNS_FUND_CHK_PARTIAL');
6260                         FND_MSG_PUB.ADD;
6261                         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6262                         RAISE FND_API.G_EXC_ERROR;
6263                     ELSE
6264                         FND_MESSAGE.SET_NAME('LNS', 'LNS_API_OTHERS_EXCEP');
6265                         FND_MESSAGE.SET_TOKEN('ERROR' ,'Call to PSA_BC_XLA_PUB.Budgetary_Control failed with Status Code = ' || l_status_code);
6266                         FND_MSG_PUB.ADD;
6267                         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6268                         RAISE FND_API.G_EXC_ERROR;
6269                     END IF;
6270                 end if;
6271 */
6272                 -- For FundsReserve, we update the fundsCheckDate from UI
6273                 IF  p_budgetary_control_mode = 'C'  THEN
6274                     open c_obj_vers(p_loan_id);
6275                     fetch c_obj_vers into l_version;
6276                     close c_obj_vers;
6277 
6278                     l_loan_header_rec.loan_id             := p_loan_id;
6279                     l_loan_header_rec.FUNDS_CHECK_DATE    := sysdate;
6280                     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'updating loan');
6281                     LNS_LOAN_HEADER_PUB.UPDATE_LOAN(P_OBJECT_VERSION_NUMBER => l_version
6282                                 ,P_LOAN_HEADER_REC       => l_loan_header_rec
6283                                 ,P_INIT_MSG_LIST         => FND_API.G_FALSE
6284                                 ,X_RETURN_STATUS         => l_return_status
6285                                 ,X_MSG_COUNT             => l_msg_count
6286                                 ,X_MSG_DATA              => l_msg_data);
6287                     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'update loan status = ' || l_return_status);
6288 
6289                     if l_return_status <> 'S' then
6290                         FND_MESSAGE.SET_NAME('LNS', 'LNS_UPD_LOAN_FAIL');
6291                         FND_MSG_PUB.ADD;
6292                         logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6293                         RAISE FND_API.G_EXC_ERROR;
6294                     end if;
6295                 END IF;
6296 
6297                 x_budgetary_status_code  := l_status_code;
6298             	x_return_status          := l_return_status;
6299 
6300             end if; -- BC_API.RETURN_STATUS
6301 
6302         end if; -- l_funds_reserved_flag
6303 
6304 
6305         IF (l_return_status = 'S' AND FND_API.to_Boolean(p_commit))
6306         THEN
6307             COMMIT WORK;
6308         END IF;
6309 
6310  	end if;  -- no budgetary control-- end if (lns_utility_pub.IS_FED_FIN_ENABLED = 'Y' AND l_disbursement_id IS NOT NULL) then
6311 
6312     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
6313 
6314 EXCEPTION
6315 
6316     WHEN FND_API.G_EXC_ERROR THEN
6317         ROLLBACK TO loan_adj_reverse_bc_pvt;
6318         x_return_status := FND_API.G_RET_STS_ERROR;
6319         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
6320         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
6321 
6322     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
6323         ROLLBACK TO loan_adj_reverse_bc_pvt;
6324         x_return_status := FND_API.G_RET_STS_ERROR;
6325         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
6326         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
6327 
6328     WHEN OTHERS THEN
6329         ROLLBACK TO loan_adj_reverse_bc_pvt;
6330         x_return_status := FND_API.G_RET_STS_ERROR;
6331         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
6332         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
6333 
6334 END LOAN_ADJUSTMENT_BUDGET_CONTROL;
6335 
6336 
6337 /*=========================================================================
6338  | PUBLIC procedure validateAddRecAccounting
6339  |
6340  | DESCRIPTION
6341  |        validates accounting records for a given additional receivable
6342  |
6343  | PSEUDO CODE/LOGIC
6344  |
6345  | PARAMETERS
6346  |           p_loan_id => id of loan
6347  |           p_loan_line_id => loan line id
6348  |
6349  | Return value: standard api values
6350  |
6351  | Source Tables: lns_Distritbutions
6352  |
6353  | Target Tables: NA
6354  |
6355  | KNOWN ISSUES
6356  |
6357  | NOTES
6358  |
6359  |
6360  | MODIFICATION HISTORY
6361  | Date             Author            Description of Changes
6362  | 04-01-2010       scherkas          Created
6363  |
6364  *=======================================================================*/
6365 procedure validateAddRecAccounting(p_loan_id                    in  number
6366                                    ,p_loan_line_id              IN NUMBER
6367                                    ,p_init_msg_list             IN VARCHAR2
6368                                    ,x_return_status             OUT NOCOPY VARCHAR2
6369                                    ,x_msg_count                 OUT NOCOPY NUMBER
6370                                    ,x_msg_data                  OUT NOCOPY VARCHAR2)
6371 is
6372 
6373     l_loan_receivables_orig LNS_DISTRIBUTIONS_PUB.distribution_tbl;
6374     l_loan_clearing_orig    LNS_DISTRIBUTIONS_PUB.distribution_tbl;
6375     l_loan_receivables_bill LNS_DISTRIBUTIONS_PUB.distribution_tbl;
6376     l_dist_percent_rec_bill number;
6377     l_api_name              varchar2(30);
6378 
6379 begin
6380 
6381     l_api_name := 'validateAddRecAccounting';
6382     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
6383 
6384     -- Initialize message list IF p_init_msg_list is set to TRUE.
6385     IF FND_API.to_Boolean( p_init_msg_list ) THEN
6386         FND_MSG_PUB.initialize;
6387     END IF;
6388 
6389     -- Initialize API return status to SUCCESS
6390     x_return_status := FND_API.G_RET_STS_SUCCESS;
6391 
6392     l_dist_percent_rec_bill   := 0;
6393 
6394     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 1...');
6395     l_loan_clearing_orig    := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
6396                                                                         ,p_loan_line_id      => p_loan_line_id
6397                                                                         ,p_account_type      => 'CR'
6398                                                                         ,p_account_name      => 'LOAN_CLEARING'
6399                                                                         ,p_line_type         => 'CLEAR'
6400                                                                         ,p_distribution_type => 'ORIGINATION');
6401     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_clearing_orig count = ' || l_loan_clearing_orig.count);
6402 
6403     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 2...');
6404     l_loan_receivables_orig := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
6405                                                                         ,p_loan_line_id      => p_loan_line_id
6406                                                                         ,p_account_type      => 'DR'
6407                                                                         ,p_account_name      => 'LOAN_RECEIVABLE'
6408                                                                         ,p_line_type         => 'ORIG'
6409                                                                         ,p_distribution_type => 'ORIGINATION');
6410     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_receivables_orig count = ' || l_loan_receivables_orig.count);
6411 
6412     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_DISTRIBUTIONS_PUB.getDistributions 3...');
6413     l_loan_receivables_bill  := LNS_DISTRIBUTIONS_PUB.getDistributions(p_loan_id           => p_loan_id
6414                                                                         ,p_loan_line_id      => p_loan_line_id
6415                                                                         ,p_account_type      => 'CR'
6416                                                                         ,p_account_name      => 'LOAN_RECEIVABLE'
6417                                                                         ,p_line_type         => 'PRIN'
6418                                                                         ,p_distribution_type => 'BILLING');
6419     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_receivables_bill count = ' || l_loan_receivables_bill.count);
6420 
6421     for j in 1..l_loan_receivables_bill.count loop
6422         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_loan_receivables_bill(j).CODE_COMBINATION_ID || ' - ' ||
6423             l_loan_receivables_bill(j).distribution_percent || '%');
6424         l_dist_percent_rec_bill := l_dist_percent_rec_bill + l_loan_receivables_bill(j).distribution_percent;
6425     end loop;
6426 
6427     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_dist_percent_rec_bill = ' || l_dist_percent_rec_bill);
6428     if l_dist_percent_rec_bill <> 100 then
6429         FND_MESSAGE.Set_Name('LNS', 'LNS_ACC_BILL_REC_PER_INVALID');
6430         FND_MSG_PUB.Add;
6431         RAISE FND_API.G_EXC_ERROR;
6432     end if;
6433 
6434     FND_MSG_PUB.Count_And_Get(p_count => x_msg_count
6435                             ,p_data  => x_msg_data);
6436 
6437     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
6438 
6439 Exception
6440     WHEN FND_API.G_EXC_ERROR THEN
6441         x_return_status := FND_API.G_RET_STS_ERROR;
6442         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count
6443                                 ,p_data  => x_msg_data);
6444         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
6445 
6446     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
6447         x_return_status := FND_API.G_RET_STS_ERROR;
6448         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count
6449                                 ,p_data  => x_msg_data);
6450         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
6451 
6452     WHEN OTHERS THEN
6453         x_return_status := FND_API.G_RET_STS_ERROR;
6454         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count
6455                                 ,p_data  => x_msg_data);
6456         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
6457 
6458 end;
6459 
6460 
6461 
6462 /*=========================================================================
6463  | PUBLIC procedure createDistrForAddRec
6464  |
6465  | DESCRIPTION
6466  |        This procedure creates accounting records for an additional receivable
6467  |
6468  | PSEUDO CODE/LOGIC
6469  |
6470  | PARAMETERS
6471  |           p_loan_id => id of loan
6472  |           p_loan_line_id => loan line id
6473  |
6474  | Return value: standard api values
6475  |
6476  | Source Tables: lns_Distritbutions
6477  |
6478  | Target Tables: NA
6479  |
6480  | KNOWN ISSUES
6481  |
6482  | NOTES
6483  |
6484  |
6485  | MODIFICATION HISTORY
6486  | Date             Author            Description of Changes
6487  | 04-01-2010       scherkas          Created
6488  |
6489  *=======================================================================*/
6490 procedure createDistrForAddRec(p_api_version                IN NUMBER
6491                               ,p_init_msg_list              IN VARCHAR2
6492                               ,p_commit                     IN VARCHAR2
6493                               ,p_loan_id                    IN NUMBER
6494                               ,p_loan_line_id               IN NUMBER
6495                               ,x_return_status              OUT NOCOPY VARCHAR2
6496                               ,x_msg_count                  OUT NOCOPY NUMBER
6497                               ,x_msg_data                   OUT NOCOPY VARCHAR2)
6498 is
6499 /*------------------------------------------------------------------------+
6500  | Local Variable Declarations and initializations                        |
6501  +-----------------------------------------------------------------------*/
6502     l_api_name                 varchar2(30);
6503     l_msg_count                NUMBER;
6504     l_msg_data                 VARCHAR2(2000);
6505     l_return_Status            VARCHAR2(1);
6506     i                          number;
6507     n                          number;
6508     y                          number;
6509     l_code_combination_id      number;
6510     l_code_combination_id_new_rec number;
6511     l_distributionsCLEAR_ORIG  lns_distributions_pub.distribution_tbl;
6512     l_distributionsREC_ORIG    lns_distributions_pub.distribution_tbl;
6513     l_distributionsREC_BILL    lns_distributions_pub.distribution_tbl;
6514     l_distributionsALL         lns_distributions_pub.distribution_tbl;
6515     l_ers_distribution_amount  number;
6516     l_ledger_details           lns_distributions_pub.gl_ledger_details;
6517     l_sum                      number;
6518     l_natural_account_rec      varchar2(25);  -- the lns_def_distribs replacement  for Loans Receivable
6519     l_nat_acct_seg_number      number;
6520     l_adjustment_exists        boolean;
6521     l_funded_amount            number;
6522     l_billed_amount            number;
6523     l_adj_date                 date;
6524     l_running_percent          number;
6525     l_percent                  number;
6526     l_accounting_batch_id      NUMBER;
6527     l_errbuf                   VARCHAR2(10000);
6528     l_retcode                  NUMBER;
6529     l_error_counter            number;
6530     l_error_message               varchar2(2000);
6531     l_invoice_number              varchar2(100);
6532     l_entity_code                 varchar2(30);
6533     l_transactions_count          number;
6534     l_entity_id                   number;
6535     l_source_id_int_1             number;
6536     l_upgrade_status              varchar2(1);
6537     l_trx_number                  varchar2(100);
6538     l_transaction_number          VARCHAR2(240);
6539     l_gl_date                     date;
6540     l_found_match                 boolean;
6541     l_event_id                    number;
6542 
6543     l_loan_id                   number;
6544     l_distribution_id           number;
6545     l_line_type                 varchar2(30);
6546     l_account_name              varchar2(30);
6547     l_account_type              varchar2(30);
6548     l_distribution_percent      number;
6549     l_distribution_amount       number;
6550     l_distribution_type         varchar2(30);
6551     l_is_natural_acct_exists	Varchar2(1);
6552 
6553 /*------------------------------------------------------------------------+
6554  | Cursor Declarations                                                    |
6555  +-----------------------------------------------------------------------*/
6556 
6557     -- cursor to get documents and check upgrade status
6558     cursor c_get_line_documents(p_loan_line_id number) is
6559     select lines.reference_id, trx.trx_number
6560       from lns_loan_lines lines
6561           ,ra_customer_trx trx
6562      where lines.reference_type = 'RECEIVABLE'
6563        and lines.end_date is null
6564        and lines.loan_line_id = p_loan_line_id
6565        and lines.reference_id = trx.customer_trx_id;
6566 
6567     cursor c_entities(p_loan_line_id number) is
6568         select entity_id, entity_code, source_id_int_1, transaction_number
6569             from xla_transaction_entities
6570         where application_id = 222
6571             and entity_code IN ('TRANSACTIONS', 'ADJUSTMENTS')
6572             and ((source_id_int_1 in (select reference_id from lns_loan_lines where end_date is null and reference_type = 'RECEIVABLE' and loan_line_id = p_loan_line_id)
6573             OR   (source_id_int_1 in (select rec_adjustment_id from lns_loan_lines where end_date is null and reference_type = 'RECEIVABLE' and loan_line_id = p_loan_line_id))));
6574 
6575     -- cursor to get accounting errors
6576     cursor c_acc_errors (p_loan_line_id number, p_accounting_batch_id number) is
6577     select xlt.transaction_number, xlt.entity_code, err.encoded_msg
6578       from xla_accounting_errors err
6579           ,xla_transaction_entities xlt
6580      where xlt.application_id = 222
6581        --and err.accounting_batch_id = nvl(p_accounting_batch_id, null)
6582        and xlt.entity_id = err.entity_id
6583        and xlt.entity_id in (select entity_id from xla_transaction_entities
6584                               where application_id = 222
6585                                 and entity_code IN ('TRANSACTIONS', 'ADJUSTMENTS')
6586                                 and ((source_id_int_1 in (select reference_id from lns_loan_lines where end_date is null and reference_type = 'RECEIVABLE' and loan_line_id = p_loan_line_id))
6587                                   OR (source_id_int_1 in (select rec_adjustment_id from lns_loan_lines where end_date is null and reference_type = 'RECEIVABLE' and loan_line_id = p_loan_line_id))));
6588 
6589     -- cursor to establish the loan clearing accounts
6590     cursor C_ERS_LOAN_CLEARING(p_loan_line_id number) is
6591         select sum(ael.entered_dr)
6592                ,ael.code_combination_id
6593         from ar_adjustments_all adj
6594             ,xla_transaction_entities ent
6595             ,xla_ae_headers aeh
6596             ,xla_ae_lines ael
6597         where ent.application_id = 222
6598             and adj.adjustment_id = ent.source_id_int_1
6599             and ent.entity_code = 'ADJUSTMENTS'
6600             and ent.entity_id = aeh.entity_id
6601             and ent.ledger_id = aeh.ledger_id
6602             and aeh.ae_header_id = ael.ae_header_id
6603             and aeh.accounting_entry_status_code = 'F'
6604             and ael.accounting_class_code in
6605             (select xaa.accounting_class_code
6606                 from XLA_ACCT_CLASS_ASSGNS xaa
6607                     ,XLA_ASSIGNMENT_DEFNS_B xad
6608                     ,XLA_POST_ACCT_PROGS_B xpa
6609             where xaa.program_code = 'LNS_ADJUSTMENT_DEBIT'     -- Bug#8231149
6610                 and xpa.program_code = xaa.program_code
6611                 and xaa.program_code = xad.program_code
6612                 and xad.assignment_code = xaa.assignment_code
6613                 and xad.enabled_flag = 'Y')
6614                 and adj.adjustment_id in
6615                 (select rec_adjustment_id
6616                  from lns_loan_lines
6617                  where reference_type = 'RECEIVABLE'
6618                  and end_date is null
6619                  and loan_line_id = p_loan_line_id)
6620             group by ael.code_combination_id;
6621 
6622     cursor C_ERS_LOAN_RECEIVABLE(p_loan_line_id number) is
6623         select sum(ael.entered_dr)
6624                 ,ael.code_combination_id
6625         from ra_customer_trx_all inv
6626             ,xla_transaction_entities ent
6627             ,xla_ae_headers aeh
6628             ,xla_ae_lines ael
6629         where ent.application_id = 222
6630             and inv.customer_trx_id = ent.source_id_int_1
6631             and ent.entity_code = 'TRANSACTIONS'
6632             and ent.entity_id = aeh.entity_id
6633             and ent.ledger_id = aeh.ledger_id
6634             and aeh.ae_header_id = ael.ae_header_id
6635             and aeh.accounting_entry_status_code = 'F'
6636             and ael.accounting_class_code IN
6637             (select xaa.accounting_class_code
6638             from XLA_ACCT_CLASS_ASSGNS xaa
6639                 ,XLA_ASSIGNMENT_DEFNS_B xad
6640                 ,XLA_POST_ACCT_PROGS_B xpa
6641             where xaa.program_code = 'GET_RECEIVABLE_CCID'
6642                 and xpa.program_code = xaa.program_code
6643                 and xaa.program_code = xad.program_code
6644                 and xad.assignment_code = xaa.assignment_code
6645                 and xad.enabled_flag = 'Y')
6646                 and inv.customer_trx_id in
6647 				 (select reference_id
6648 		          from lns_loan_lines
6649 				  where reference_type = 'RECEIVABLE'
6650      		      and end_date is null
6651 		          and loan_line_id = p_loan_line_id)
6652 			group by ael.code_combination_id;
6653 
6654     cursor c_get_funded_amount(p_loan_id number, p_code_combination_id number, p_adj_date date) is
6655         select nvl(sum(dist.distribution_amount), 0)
6656         from lns_distributions dist,
6657             lns_loan_lines lines
6658         where dist.distribution_type = 'ORIGINATION'
6659             and dist.line_type = 'ORIG'
6660             and dist.account_name = 'LOAN_RECEIVABLE'
6661             and dist.account_type = 'DR'
6662             and dist.loan_id = p_loan_id
6663             and dist.code_combination_id = p_code_combination_id
6664             and dist.LOAN_LINE_ID = lines.LOAN_LINE_ID(+)
6665             and lines.loan_id(+) = dist.loan_id
6666             and trunc(lines.ADJUSTMENT_DATE(+)) <= trunc(p_adj_date)
6667             and lines.status(+) = 'APPROVED';
6668 
6669     cursor c_get_billed_amount(p_loan_id number, p_code_combination_id number, p_adj_date date) is
6670         select nvl(sum(dist.amount), 0)
6671         from lns_amortization_lines lines,
6672             lns_amortization_scheds am,
6673             RA_CUST_TRX_LINE_GL_DIST_ALL dist
6674         where am.loan_id = p_loan_id
6675             and (am.REVERSED_FLAG is null or am.REVERSED_FLAG = 'N')
6676             and am.REAMORTIZATION_AMOUNT is null
6677             and am.loan_id = lines.loan_id
6678             and am.amortization_schedule_id = lines.amortization_schedule_id
6679             and dist.CUSTOMER_TRX_ID = lines.cust_trx_id
6680             and dist.CUSTOMER_TRX_LINE_ID = lines.cust_trx_line_id
6681             and dist.code_combination_id = p_code_combination_id
6682             and trunc(am.due_date) <= trunc(p_adj_date);
6683 
6684     cursor c_adj_date(p_loan_line_id number) is
6685         select ADJUSTMENT_DATE, adj.gl_date
6686         from lns_loan_lines lines, ar_adjustments_all adj
6687         where lines.LOAN_LINE_ID = p_loan_line_id
6688             and lines.REC_ADJUSTMENT_ID = adj.ADJUSTMENT_ID;
6689 
6690     CURSOR c_get_prin_distr(C_LOAN_ID number, C_ADJ_DATE date, C_LOAN_LINE_ID number) IS
6691        select dist.distribution_id
6692              ,dist.loan_id
6693              ,dist.line_type
6694              ,dist.account_name
6695              ,dist.account_type
6696              ,dist.code_combination_id
6697              ,dist.distribution_percent
6698              ,dist.distribution_amount
6699              ,dist.distribution_type
6700        from lns_distributions dist
6701        where dist.loan_id = C_LOAN_ID
6702          and dist.account_type = 'CR'
6703          and dist.account_name = 'LOAN_RECEIVABLE'
6704          and dist.line_type = 'PRIN'
6705          and dist.distribution_type = 'BILLING'
6706          and dist.distribution_percent > 0
6707          and nvl(dist.loan_line_id, -1) =
6708                 nvl((select max(loan_line_id)
6709                 from lns_loan_lines
6710                 where status = 'APPROVED'
6711                 and LOAN_ID = C_LOAN_ID
6712 		-- Added below one line condition b'coz we want the last loan_line_id distributions
6713 		-- but here this code executes after the current loan_line_id is approved so it returns
6714 		-- the current loan_line_id , which is incorrect.
6715 		and loan_line_id NOT IN (C_LOAN_LINE_ID)
6716                 and original_flag = 'N'
6717                 and trunc(adjustment_date) <= trunc(C_ADJ_DATE)), -1)
6718         order by dist.distribution_id;
6719 
6720 begin
6721 
6722     SAVEPOINT createDistrForAddRec;
6723     l_api_name   := 'createDistrForAddRec';
6724     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
6725 
6726     -- Initialize message list IF p_init_msg_list is set to TRUE.
6727     IF FND_API.to_Boolean( p_init_msg_list ) THEN
6728         FND_MSG_PUB.initialize;
6729     END IF;
6730 
6731     -- Initialize API return status to SUCCESS
6732     x_return_status := FND_API.G_RET_STS_SUCCESS;
6733 
6734     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Input p_loan_id = ' || p_loan_id);
6735     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Input p_loan_line_id = ' || p_loan_line_id);
6736 
6737     if P_LOAN_ID is null then
6738 
6739         FND_MESSAGE.SET_NAME( 'LNS', 'LNS_API_MISSING_COLUMN' );
6740         FND_MESSAGE.SET_TOKEN( 'COLUMN', 'P_LOAN_ID' );
6741         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6742         RAISE FND_API.G_EXC_ERROR;
6743 
6744     end if;
6745 
6746     if P_LOAN_LINE_ID is null then
6747 
6748         FND_MESSAGE.SET_NAME( 'LNS', 'LNS_API_MISSING_COLUMN' );
6749         FND_MESSAGE.SET_TOKEN( 'COLUMN', 'P_LOAN_LINE_ID' );
6750         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6751         RAISE FND_API.G_EXC_ERROR;
6752 
6753     end if;
6754 
6755     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Starting ERS INHERITANCE');
6756 
6757     l_ledger_details := lns_distributions_pub.getLedgerDetails;
6758     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'chart_of_accounts_id = ' || l_ledger_details.chart_of_accounts_id);
6759 
6760     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Fetching documents to account...');
6761     open c_get_line_documents(p_loan_line_id);
6762     loop
6763         fetch c_get_line_documents into l_source_id_int_1, l_trx_number;
6764         exit when c_get_line_documents%notfound;
6765 
6766         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_source_id_int_1 = ' || l_source_id_int_1);
6767         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_trx_number = ' || l_trx_number);
6768 
6769         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling arp_acct_event_pkg.upgrade_status_per_doc...');
6770         -- check for upgrade status bug#4872154
6771         arp_acct_event_pkg.upgrade_status_per_doc(p_init_msg_list     => p_init_msg_list
6772                                                 ,p_entity_code       => l_entity_code
6773                                                 ,p_source_int_id     => l_source_id_int_1
6774                                                 ,x_upgrade_status    => l_upgrade_status
6775                                                 ,x_return_status     => l_return_status
6776                                                 ,x_msg_count         => l_msg_count
6777                                                 ,x_msg_data          => l_msg_data);
6778         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_return_status = ' || l_return_status);
6779         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_upgrade_status = ' || l_upgrade_status);
6780 
6781         if l_return_status <> 'S' then
6782             FND_MESSAGE.SET_NAME('LNS', 'LNS_CHK_UPG_FAIL');
6783             FND_MESSAGE.SET_TOKEN('DOC_NUM', l_trx_number);
6784             FND_MSG_PUB.ADD;
6785             LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6786             RAISE FND_API.G_EXC_ERROR;
6787         else
6788             if l_upgrade_status <> 'Y' then
6789                 FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_TRX');
6790                 FND_MESSAGE.SET_TOKEN('DOC_NUM', l_trx_number);
6791                 FND_MSG_PUB.ADD;
6792                 LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6793                 RAISE FND_API.G_EXC_ERROR;
6794             end if;
6795         end if;
6796 
6797     end loop;
6798     close c_get_line_documents;
6799 
6800     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Fetching entities xla_transaction_entities...');
6801     l_transactions_count := 0;
6802     open c_entities(p_loan_line_id);
6803     loop
6804         fetch c_entities into l_entity_id, l_entity_code, l_source_id_int_1, l_transaction_number;
6805         exit when c_entities%notfound;
6806 
6807         l_transactions_count := l_transactions_count + 1;
6808         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Entity ' || l_transactions_count);
6809         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_entity_id = ' || l_entity_id);
6810         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_entity_code = ' || l_entity_code);
6811         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_source_id_int_1 = ' || l_source_id_int_1);
6812         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_transaction_number = ' || l_transaction_number);
6813 
6814         insert into XLA_ACCT_PROG_DOCS_GT (entity_id) VALUES (l_entity_id);
6815         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Inserted into XLA_ACCT_PROG_DOCS_GT');
6816 
6817     end loop;
6818     close  c_entities ;
6819 
6820     select count(1) into l_transactions_count
6821     from XLA_ACCT_PROG_DOCS_GT;
6822     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Inserted transaction_entities  = ' || l_transactions_count);
6823 
6824     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling XLA_ACCOUNTING_PUB_PKG.accounting_program_doc_batch...');
6825     XLA_ACCOUNTING_PUB_PKG.accounting_program_doc_batch(p_application_id      => 222
6826                                                         ,p_accounting_mode     => 'F'
6827                                                         ,p_gl_posting_flag     => 'N'
6828                                                         ,p_accounting_batch_id => l_accounting_batch_id
6829                                                         ,p_errbuf              => l_errbuf
6830                                                         ,p_retcode             => l_retcode);
6831     logMessage(FND_LOG.level_statement, G_PKG_NAME, ' l_retcode = ' || l_retcode);
6832     logMessage(FND_LOG.level_statement, G_PKG_NAME, ' l_accounting_batch_id = ' || l_accounting_batch_id);
6833 
6834     if l_retcode <> 0 then
6835 
6836         logMessage(FND_LOG.level_unexpected, G_PKG_NAME, 'Online accounting failed with error: ' || l_errbuf);
6837 
6838         /* query XLA_ACCOUNTING_ERRORS */
6839         l_error_counter := 0;
6840         open c_acc_errors(p_loan_line_id, l_accounting_batch_id);
6841 
6842         LOOP
6843 
6844             fetch c_acc_errors into
6845                 l_invoice_number,
6846                 l_entity_code,
6847                 l_error_message;
6848             exit when c_acc_errors%NOTFOUND;
6849 
6850             l_error_counter := l_error_counter + 1;
6851 
6852             if l_error_counter = 1 then
6853                 FND_MESSAGE.SET_NAME('LNS', 'LNS_ONLINE_ACCOUNTING_FAILED');
6854                 FND_MSG_PUB.Add;
6855                 LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6856             end if;
6857 
6858             FND_MESSAGE.SET_NAME('LNS', 'LNS_ACC_DOC_FAIL');
6859             FND_MESSAGE.SET_TOKEN('DOC_NUM', l_invoice_number);
6860             FND_MESSAGE.SET_TOKEN('DOC_TYPE', l_entity_code);
6861             FND_MESSAGE.SET_TOKEN('ACC_ERR', l_error_message);
6862             FND_MSG_PUB.Add;
6863             LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6864 
6865         END LOOP;
6866 
6867         close c_acc_errors;
6868 
6869         RAISE FND_API.G_EXC_ERROR;
6870     else
6871         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Online accounting SUCCESS! ');
6872     end if;
6873 
6874     -- get the swap segment value
6875     l_natural_account_rec := getNaturalSwapAccount(p_loan_id);
6876     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Swap natural account with ' || l_natural_account_rec);
6877 
6878     -- Bug#7406404 - Make ERS 'Replacement Natural Account' optional
6879     l_is_natural_acct_exists := 'N';
6880     IF (l_natural_account_rec IS NOT NULL) THEN
6881 	l_is_natural_acct_exists := 'Y';
6882     END IF;
6883 
6884     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_is_natural_acct_exists is '||l_is_natural_acct_exists);
6885 
6886     IF (l_is_natural_acct_exists = 'Y') THEN
6887 	-- Get natural account segment number
6888 	logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling FND_FLEX_APIS.GET_QUALIFIER_SEGNUM...');
6889 	IF (NOT FND_FLEX_APIS.GET_QUALIFIER_SEGNUM(appl_id         => 101
6890 							,key_flex_code   => 'GL#'
6891 							,structure_number=> l_ledger_details.chart_of_accounts_id
6892 							,flex_qual_name  => 'GL_ACCOUNT'
6893 							,segment_number  => l_nat_acct_seg_number))
6894 	THEN
6895 		FND_MESSAGE.SET_NAME('LNS', 'LNS_NO_NATURAL_ACCOUNT_SEGMENT');
6896 		FND_MSG_PUB.ADD;
6897 		LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6898 		RAISE FND_API.G_EXC_ERROR;
6899 	END IF;
6900 	logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Natural acct segment = ' || l_nat_acct_seg_number);
6901     END IF;
6902 
6903 
6904     -- here we establish the loan clearing first
6905     -- if adjustment activity is found in XLA then we take amounts, cc_ids from XLA tables for both CLEARING and RECEIVABLES
6906     Begin
6907         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Opening cursor C_ERS_LOAN_CLEARING...');
6908         i := 0;
6909         open C_ERS_LOAN_CLEARING(p_loan_line_id);
6910         Loop
6911             -- reintialize these
6912             l_code_combination_id     := null;
6913             l_ers_distribution_amount := 0;
6914 
6915             fetch C_ERS_LOAN_CLEARING into l_ers_distribution_amount, l_code_combination_id;
6916             EXIT WHEN C_ERS_LOAN_CLEARING%NOTFOUND;
6917 
6918             l_adjustment_exists := true;
6919             i := i + 1;
6920 
6921             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Loan Clearing Record ' || i);
6922             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_ers_distribution_amount = ' || l_ers_distribution_amount);
6923             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
6924 
6925             l_distributionsCLEAR_ORIG(i).line_type            := 'CLEAR';
6926             l_distributionsCLEAR_ORIG(i).account_name         := 'LOAN_CLEARING';
6927             l_distributionsCLEAR_ORIG(i).code_combination_id  := l_code_combination_id;
6928             l_distributionsCLEAR_ORIG(i).account_type         := 'CR';
6929             l_distributionsCLEAR_ORIG(i).distribution_amount  := l_ers_distribution_amount;
6930             l_distributionsCLEAR_ORIG(i).distribution_percent := 100;
6931             l_distributionsCLEAR_ORIG(i).distribution_type    := 'ORIGINATION';
6932             l_distributionsCLEAR_ORIG(i).loan_line_id         := p_loan_line_id;
6933 	    l_distributionsCLEAR_ORIG(i).activity		  := 'ERS_ADD_REC';
6934 
6935         end loop; -- loan clearing loop
6936     exception
6937         when others then
6938             --logMessage(FND_LOG.LEVEL_UNEX, G_PKG_NAME, 'Failed to inherit receivables distributions');
6939             FND_MESSAGE.SET_NAME('LNS', 'LNS_INHERIT_DIST_NOT_FOUND');
6940             FND_MSG_PUB.ADD;
6941             LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
6942             RAISE FND_API.G_EXC_ERROR;
6943     end;
6944 
6945     -- if the adjustment exists in PSA table it means loan is approved and adjustment was created for receivables
6946     i := 0;
6947     if l_adjustment_exists then
6948 
6949         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'ACCOUNTED ADJUSTMENT EXISTS');
6950 
6951         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Getting adjustment date...');
6952         open c_adj_date(p_loan_line_id);
6953         fetch c_adj_date into l_adj_date, l_gl_date;
6954         close c_adj_date;
6955         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_adj_date = ' || l_adj_date);
6956 
6957         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Fetching existent LOAN_RECEIVABLE PRIN BILLING records...');
6958         y := 0;
6959         l_sum := 0;
6960         OPEN c_get_prin_distr(p_loan_id, l_adj_date, p_loan_line_id);
6961 
6962 	logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Opened c_get_prin_distr');
6963         LOOP
6964 
6965             FETCH c_get_prin_distr into
6966                 l_distribution_id
6967                 ,l_loan_id
6968                 ,l_line_type
6969                 ,l_account_name
6970                 ,l_account_type
6971                 ,l_code_combination_id
6972                 ,l_distribution_percent
6973                 ,l_distribution_amount
6974                 ,l_distribution_type;
6975             EXIT WHEN c_get_prin_distr%NOTFOUND;
6976 
6977             y := y + 1;
6978             l_distributionsREC_BILL(y).distribution_id        := l_distribution_id;
6979             l_distributionsREC_BILL(y).loan_id                := l_loan_id;
6980             l_distributionsREC_BILL(y).line_type              := l_line_type;
6981             l_distributionsREC_BILL(y).account_name           := l_account_name;
6982             l_distributionsREC_BILL(y).account_type           := l_account_type;
6983             l_distributionsREC_BILL(y).code_combination_id    := l_code_combination_id;
6984             l_distributionsREC_BILL(y).distribution_percent   := l_distribution_percent;
6985             l_distributionsREC_BILL(y).distribution_amount    := l_distribution_amount;
6986             l_distributionsREC_BILL(y).distribution_type      := l_distribution_type;
6987 
6988 
6989             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Record ' || y);
6990             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_id = ' || l_distribution_id);
6991             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_id = ' || l_loan_id);
6992             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_line_type = ' || l_line_type);
6993             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_name = ' || l_account_name);
6994             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_type = ' || l_account_type);
6995             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
6996             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_percent = ' || l_distribution_percent);
6997             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_amount = ' || l_distribution_amount);
6998             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_type = ' || l_distribution_type);
6999 
7000             l_distributionsREC_BILL(y).DISTRIBUTION_PERCENT := null;
7001             l_distributionsREC_BILL(y).loan_line_id := p_loan_line_id;
7002 
7003             open c_get_funded_amount(p_loan_id, l_distributionsREC_BILL(y).CODE_COMBINATION_ID, l_adj_date);
7004             fetch c_get_funded_amount into l_funded_amount;
7005             close c_get_funded_amount;
7006             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_funded_amount = ' || l_funded_amount);
7007 
7008             open c_get_billed_amount(p_loan_id, l_distributionsREC_BILL(y).CODE_COMBINATION_ID, l_adj_date);
7009             fetch c_get_billed_amount into l_billed_amount;
7010             close c_get_billed_amount;
7011             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_billed_amount = ' || l_billed_amount);
7012 
7013             l_distributionsREC_BILL(y).DISTRIBUTION_AMOUNT := l_funded_amount - l_billed_amount;
7014             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'DISTRIBUTION_AMOUNT = ' || l_distributionsREC_BILL(y).DISTRIBUTION_AMOUNT);
7015 
7016             l_sum := l_sum + l_distributionsREC_BILL(y).DISTRIBUTION_AMOUNT;
7017             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_sum = ' || l_sum);
7018 
7019         END LOOP;
7020         CLOSE c_get_prin_distr;
7021 
7022         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Fetched ' || l_distributionsREC_BILL.count || ' records');
7023 
7024         Begin
7025             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Opening cursor C_ERS_LOAN_RECEIVABLE...');
7026             open C_ERS_LOAN_RECEIVABLE(p_loan_line_id);
7027             Loop
7028                 -- reintialize these
7029                 l_code_combination_id         := null;
7030                 l_code_combination_id_new_rec := null;
7031                 l_ers_distribution_amount     := 0;
7032 
7033                 fetch C_ERS_LOAN_RECEIVABLE into l_ers_distribution_amount, l_code_combination_id;
7034                 EXIT WHEN C_ERS_LOAN_RECEIVABLE%NOTFOUND;
7035 
7036                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Record:');
7037                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_ers_distribution_amount = ' || l_ers_distribution_amount);
7038                 logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
7039 
7040                 -- here we need to rebuild the code_Combination_id as per swapping rules
7041                 -- replace the natual account segement with the natural account segment found in the set-up/configuration
7042                 if l_ers_distribution_amount > 0 then
7043 
7044 		    -- Bug#7406404 - Make ERS 'Replacement Natural Account' optional
7045 		    IF (l_is_natural_acct_exists = 'Y') THEN
7046 		    	-- here we need to rebuild the code_Combination_id as per swapping rules
7047 		    	-- replace the natual account segement with the natural account segment found in the set-up/configuration
7048 			logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling swap_code_combination...');
7049 			l_code_combination_id_new_rec :=
7050 				swap_code_combination(p_chart_of_accounts_id => l_ledger_details.chart_of_accounts_id
7051 							,p_original_cc_id       => l_code_combination_id
7052 							,p_swap_segment_number  => l_nat_acct_seg_number
7053 							,p_swap_segment_value   => l_natural_account_rec);
7054 
7055 			logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_code_combination_id_new_rec = ' || l_code_combination_id_new_Rec);
7056 
7057 		    ELSE
7058 		    	l_code_combination_id_new_rec := l_code_combination_id;
7059 		    END IF;
7060 
7061                     -- adding LOAN_RECEIVABLE ORIGINATION record
7062                     i := i + 1;
7063 
7064                     l_ers_distribution_amount := l_distributionsCLEAR_ORIG(i).distribution_amount;
7065                     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'NEW l_ers_distribution_amount = ' || l_ers_distribution_amount);
7066 
7067                     l_distributionsREC_ORIG(i).line_type           := 'ORIG';
7068                     l_distributionsREC_ORIG(i).account_name        := 'LOAN_RECEIVABLE';
7069                     l_distributionsREC_ORIG(i).code_combination_id := l_code_combination_id_new_rec;
7070                     l_distributionsREC_ORIG(i).account_type        := 'DR';
7071                     l_distributionsREC_ORIG(i).distribution_amount := l_ers_distribution_amount;
7072                     l_distributionsREC_ORIG(i).distribution_percent := 100;
7073                     l_distributionsREC_ORIG(i).distribution_type   := 'ORIGINATION';
7074                     l_distributionsREC_ORIG(i).loan_line_id        := p_loan_line_id;
7075 		            l_distributionsREC_ORIG(i).activity		      := 'ERS_ADD_REC';
7076 
7077                     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Added LOAN_RECEIVABLE FOR ORIGINATION ' || l_code_combination_id_new_rec);
7078                     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsREC_ORIG.count = ' || l_distributionsREC_ORIG.count);
7079 
7080                     -- searching ccid amoung existent l_distributionsREC_BILL records
7081                     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Searching for ccid match...');
7082                     l_found_match := false;
7083                     for k in 1..y loop
7084                         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Record #' || k);
7085                         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'CODE_COMBINATION_ID = ' || l_distributionsREC_BILL(k).CODE_COMBINATION_ID);
7086 
7087                         if l_distributionsREC_BILL(k).CODE_COMBINATION_ID = l_code_combination_id_new_rec then
7088                             logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Found ccid match!!!');
7089                             l_distributionsREC_BILL(k).distribution_amount := l_distributionsREC_BILL(k).distribution_amount + l_ers_distribution_amount;
7090                             l_found_match := true;
7091                             exit;
7092                         end if;
7093                     end loop;
7094 
7095                     if l_found_match = false then
7096                         y := y + 1;
7097                         l_distributionsREC_BILL(y).line_type           := 'PRIN';
7098                         l_distributionsREC_BILL(y).account_name        := 'LOAN_RECEIVABLE';
7099                         l_distributionsREC_BILL(y).code_combination_id := l_code_combination_id_new_rec;
7100                         l_distributionsREC_BILL(y).account_type        := 'CR';
7101                         l_distributionsREC_BILL(y).distribution_amount := l_ers_distribution_amount;
7102                         l_distributionsREC_BILL(y).distribution_type   := 'BILLING';
7103                         l_distributionsREC_BILL(y).loan_line_id        := p_loan_line_id;
7104 
7105 
7106                         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Added LOAN_RECEIVABLE FOR BILLING ' || l_code_combination_id_new_rec);
7107                         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsREC_BILL.count = ' || l_distributionsREC_BILL.count);
7108                     end if;
7109 
7110                     l_sum := l_sum + l_ers_distribution_amount;
7111                     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_sum = ' || l_sum);
7112                 end if;
7113 
7114             end loop;
7115 
7116             close C_ERS_LOAN_RECEIVABLE;
7117 
7118         exception
7119             when others then
7120 --                        logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, 'failed to inherit receivables distributions');
7121                 FND_MESSAGE.SET_NAME('LNS', 'LNS_INHERIT_DIST_NOT_FOUND');
7122                 FND_MSG_PUB.ADD;
7123                 LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
7124                 RAISE FND_API.G_EXC_ERROR;
7125         end;
7126 
7127     else
7128         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'NO ACCOUNTED ADJUSTMENT EXISTS');
7129     end if;
7130 
7131     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsCLEAR_ORIG.count = ' || l_distributionsCLEAR_ORIG.count);
7132     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsREC_ORIG.count = ' || l_distributionsREC_ORIG.count);
7133     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsREC_BILL.count = ' || l_distributionsREC_BILL.count);
7134 
7135     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'CALCULATING %AGES FOR PRIN BILLING LOAN_RECEIVABLE...');
7136     l_running_percent := 0;
7137     for k in 1..l_distributionsREC_BILL.count loop
7138 
7139         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Iteration ' || k);
7140         l_percent := 0;
7141 
7142         if k <> l_distributionsREC_BILL.count then
7143             l_percent := round(l_distributionsREC_BILL(k).distribution_amount / l_sum * 100,4);
7144             l_distributionsREC_BILL(k).distribution_percent := l_percent;
7145         else
7146             -- last row ensure that amounts = 100% and total = funded amount of loan
7147             l_percent := 100 - l_running_percent;
7148             l_distributionsREC_BILL(k).distribution_percent := l_percent;
7149         end if;
7150         l_distributionsREC_BILL(k).distribution_amount  := null;
7151         l_running_percent := l_running_percent + l_percent;
7152 
7153         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'distribution_percent = ' || l_distributionsREC_BILL(k).distribution_percent);
7154         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'distribution_amount = ' || l_distributionsREC_BILL(k).distribution_amount);
7155         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_running_percent = ' || l_running_percent);
7156 
7157     end loop;
7158 
7159     n := 0;
7160     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Copying l_distributionsREC_ORIG to l_distributionsALL...');
7161     for j in 1..l_distributionsREC_ORIG.count loop
7162         n := n + 1;
7163         l_distributionsALL(n)     := l_distributionsREC_ORIG(j);
7164     end loop;
7165     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsALL.count = ' || l_distributionsALL.count);
7166 
7167     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Copying l_distributionsCLEAR_ORIG to l_distributionsALL...');
7168     for j in 1..l_distributionsCLEAR_ORIG.count loop
7169         n := n + 1;
7170         l_distributionsALL(n)     := l_distributionsCLEAR_ORIG(j);
7171     end loop;
7172     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsALL.count = ' || l_distributionsALL.count);
7173 
7174     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Copying l_distributionsREC_BILL to l_distributionsALL...');
7175     for j in 1..l_distributionsREC_BILL.count loop
7176         n := n + 1;
7177         l_distributionsALL(n)     := l_distributionsREC_BILL(j);
7178     end loop;
7179     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_distributionsALL.count = ' || l_distributionsALL.count);
7180 
7181     logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Calling do_insert_distributions...');
7182     do_insert_distributions(p_distributions_tbl => l_distributionsALL
7183                             ,p_loan_id           => p_loan_id);
7184 
7185     -- validate the accounting rows here
7186     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' validating Accounting');
7187     lns_distributions_pub.validateAddRecAccounting(p_loan_id          => p_loan_id
7188                                                 ,p_loan_line_id    => p_loan_line_id
7189                                                 ,p_init_msg_list    => p_init_msg_list
7190                                                 ,x_return_status    => l_return_status
7191                                                 ,x_msg_count        => l_msg_count
7192                                                 ,x_msg_data         => l_msg_data);
7193 
7194     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'Accounting status is ' || l_return_status);
7195     if l_return_status <> 'S' then
7196         RAISE FND_API.G_EXC_ERROR;
7197     end if;
7198 
7199     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_gl_date = ' || l_gl_date);
7200 
7201     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_XLA_EVENTS.create_event...');
7202     LNS_XLA_EVENTS.create_event(p_loan_id         =>  p_loan_id
7203                                 ,p_disb_header_id  => -1
7204                                 ,p_loan_amount_adj_id => -1
7205 				                ,p_loan_line_id		  => p_loan_line_id
7206                                 ,p_event_type_code => 'ERS_LOAN_ADD_REC_APPROVED'
7207                                 ,p_event_date      => l_gl_date
7208                                 ,p_event_status    => 'U'
7209                                 ,p_init_msg_list   => fnd_api.g_false
7210                                 ,p_commit          => fnd_api.g_false
7211                                 ,p_bc_flag         => 'N'
7212                                 ,x_event_id        => l_event_id
7213                                 ,x_return_status   => l_return_status
7214                                 ,x_msg_count       => l_msg_count
7215                                 ,x_msg_data        => l_msg_data);
7216     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
7217     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
7218 
7219     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7220         FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCOUNTING_EVENT_ERROR');
7221         FND_MSG_PUB.ADD;
7222         --l_last_api_called := 'LNS_XLA_EVENTS.create_event';
7223         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
7224         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7225     END IF;
7226 
7227     if l_event_id is not null then
7228         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updating lns_distributions...');
7229         update lns_distributions
7230             set event_id = l_event_id
7231         where loan_id = P_LOAN_ID
7232             and loan_line_id = p_loan_line_id
7233             and account_name in ('LOAN_RECEIVABLE', 'LOAN_CLEARING')
7234             and distribution_type = 'ORIGINATION'
7235 	    and activity = 'ERS_ADD_REC';
7236         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Done');
7237     end if;
7238 
7239     IF FND_API.to_Boolean(p_commit)
7240     THEN
7241         COMMIT WORK;
7242     END IF;
7243 
7244     FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
7245 
7246     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
7247 
7248 EXCEPTION
7249 
7250     WHEN FND_API.G_EXC_ERROR THEN
7251         x_return_status := FND_API.G_RET_STS_ERROR;
7252         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
7253         FND_MESSAGE.SET_NAME('LNS', 'LNS_ADD_REC_ACC_FAIL');
7254         FND_MSG_PUB.ADD;
7255         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
7256         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
7257         ROLLBACK TO createDistrForAddRec;
7258 
7259     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
7260         x_return_status := FND_API.G_RET_STS_ERROR;
7261         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
7262         FND_MESSAGE.SET_NAME('LNS', 'LNS_ADD_REC_ACC_FAIL');
7263         FND_MSG_PUB.ADD;
7264         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
7265         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
7266         ROLLBACK TO createDistrForAddRec;
7267 
7268     WHEN OTHERS THEN
7269         x_return_status := FND_API.G_RET_STS_ERROR;
7270         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
7271         FND_MESSAGE.SET_NAME('LNS', 'LNS_ADD_REC_ACC_FAIL');
7272         FND_MSG_PUB.ADD;
7273         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
7274         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
7275         ROLLBACK TO createDistrForAddRec;
7276 
7277 end createDistrForAddRec;
7278 
7279 /*=========================================================================
7280 || PUBLIC PROCEDURE generateCancelDistributions
7281 ||
7282 || DESCRIPTION
7283 ||      This procedure generates distributions for cancellation of the loan
7284 ||
7285 || PSEUDO CODE/LOGIC
7286 ||
7287 || PARAMETERS
7288 ||  Parameter:   p_loan_id => loan to default
7289 ||
7290 || Return value:  Standard  S = Success E = Error U = Unexpected
7291 ||
7292 || Source Tables: LNS_DISTRIBUTIONS, lns_loan_headers_all
7293 ||
7294 || Target Tables: LNS_DISTRIBUTIONS
7295 ||
7296 || KNOWN ISSUES
7297 ||
7298 || NOTES
7299 ||
7300 || MODIFICATION HISTORY
7301 || Date          Author      Description of Changes
7302 || 01-Jun-2010   Mbolli      Created
7303  *=======================================================================*/
7304 PROCEDURE generateCancelDistributions(p_api_version           IN NUMBER
7305                               ,p_init_msg_list         IN VARCHAR2
7306                               ,p_commit                IN VARCHAR2
7307                               ,p_loan_id               IN NUMBER
7308                               ,x_return_status         OUT NOCOPY VARCHAR2
7309                               ,x_msg_count             OUT NOCOPY NUMBER
7310                               ,x_msg_data              OUT NOCOPY VARCHAR2)
7311 is
7312 /*------------------------------------------------------------------------+
7313  | Local Variable Declarations and initializations                        |
7314  +-----------------------------------------------------------------------*/
7315     l_api_name                 VARCHAR2(30);
7316     l_msg_count                NUMBER;
7317     l_msg_data                 VARCHAR2(2000);
7318     l_return_Status            VARCHAR2(1);
7319 
7320     l_loan_class               VARCHAR2(15);
7321     l_requested_amount         NUMBER;
7322     l_funded_amount            NUMBER;
7323     l_cancel_amount            NUMBER;
7324 
7325     l_distributions            lns_distributions_pub.distribution_tbl;
7326     l_line_type                VARCHAR2(30);
7327     l_account_name             VARCHAR2(30);
7328     l_code_combination_id      NUMBER;
7329     l_account_type             VARCHAR2(30);
7330     l_distribution_percent     NUMBER;
7331     l_distribution_type        VARCHAR2(30);
7332     l_Cnt                      NUMBER;
7333     l_receivOrigCnt            NUMBER;
7334     l_receivSubsidyCnt         NUMBER;
7335     l_clearOrigCnt             NUMBER;
7336     l_clearSubsidyCnt          NUMBER;
7337     l_loan_receivables_count   NUMBER;
7338     l_ledger_details           lns_distributions_pub.gl_ledger_details;
7339 
7340     l_run_rec_org_amt          NUMBER;
7341     l_run_rec_sub_amt          NUMBER;
7342     l_run_clear_org_amt        NUMBER;
7343     l_run_clear_sub_amt        NUMBER;
7344     l_subsidy_rate		 NUMBER;
7345     l_subsidy_amount           NUMBER;
7346 
7347 
7348 /*------------------------------------------------------------------------+
7349  | Cursor Declarations                                                    |
7350  +-----------------------------------------------------------------------*/
7351 
7352     cursor c_get_orig_distributions(c_loan_id number) is
7353        select d.line_type
7354              ,d.account_name
7355              ,d.code_combination_id
7356              ,d.account_type
7357              ,d.distribution_percent
7358              ,d.distribution_type
7359        from lns_distributions d
7360        where d.loan_id = c_loan_id
7361          and d.distribution_type = 'ORIGINATION'
7362          and d.distribution_percent > 0
7363          and d.disb_header_id IS NULL
7364          and d.loan_amount_adj_id IS NULL
7365          and d.loan_line_id IS NULL
7366         order by d.code_combination_id;
7367 
7368     cursor c_loan_info(c_loan_id NUMBER)
7369     is
7370     select h.loan_class_code, h.requested_amount, h.funded_amount, (nvl(subsidy_rate, 0)/100)
7371         from lns_loan_headers_all h
7372         where h.loan_id = c_loan_id;
7373 
7374 
7375     cursor c_num_receivables(c_loan_id number)
7376     is
7377     select count(1)
7378       from lns_distributions
7379      where loan_id  = c_loan_id
7380        and account_name = 'LOAN_RECEIVABLE'
7381        and distribution_type = 'ORIGINATION'
7382        and account_type      = 'DR'
7383        and line_type  <> 'SUBSIDY';
7384 /*
7385     cursor c_num_payables(c_loan_id number)
7386     is
7387     select count(1)
7388       from lns_distributions
7389      where loan_id  = c_loan_id
7390        and account_name in ('LOAN_PAYABLE', 'LOAN_CLEARING')
7391        and distribution_type = 'ORIGINATION'
7392        and account_type      = 'CR'
7393        and line_type  <> 'SUBSIDY';
7394 */
7395 
7396 
7397 
7398 begin
7399 
7400       SAVEPOINT generateCancelDistributions;
7401       l_api_name   := 'generateCancelDistributions';
7402       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
7403       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
7404 
7405       -- Initialize message list IF p_init_msg_list is set to TRUE.
7406       IF FND_API.to_Boolean( p_init_msg_list ) THEN
7407           FND_MSG_PUB.initialize;
7408       END IF;
7409 
7410       -- Initialize API return status to SUCCESS
7411       x_return_status := FND_API.G_RET_STS_SUCCESS;
7412 
7413       -- initialize variables
7414 
7415       l_Cnt              := 0;
7416       l_receivOrigCnt    := 0;
7417       l_receivSubsidyCnt := 0;
7418       l_clearOrigCnt     := 0;
7419       l_clearSubsidyCnt  := 0;
7420       l_run_rec_org_amt  := 0;
7421       l_run_rec_sub_amt  := 0;
7422       l_run_clear_org_amt:= 0;
7423       l_run_clear_sub_amt:= 0;
7424       l_ledger_details   := lns_distributions_pub.getLedgerDetails;
7425 
7426       lns_utility_pub.validate_any_id(p_api_version    =>  1.0
7427                                       ,p_init_msg_list  =>  p_init_msg_list
7428                                       ,x_msg_count      =>  l_msg_count
7429                                       ,x_msg_data       =>  l_msg_data
7430                                       ,x_return_status  =>  l_return_status
7431                                       ,p_col_id         =>  p_loan_id
7432                                       ,p_col_name       =>  'LOAN_ID'
7433                                       ,p_table_name     =>  'LNS_LOAN_HEADERS');
7434 
7435       IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7436         FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_VALUE');
7437         FND_MESSAGE.SET_TOKEN('PARAMETER', 'LOAN_ID');
7438         FND_MESSAGE.SET_TOKEN('VALUE', p_loan_id);
7439         FND_MSG_PUB.ADD;
7440         RAISE FND_API.G_EXC_ERROR;
7441       END IF;
7442 
7443       OPEN c_loan_info(p_loan_id);
7444       FETCH c_loan_info INTO l_loan_class, l_requested_amount, l_funded_amount, l_subsidy_rate;
7445 
7446       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_loan_class = ' || l_loan_class);
7447       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_requested_amount = ' || l_requested_amount);
7448       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_funded_amount = ' || l_funded_amount);
7449       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_subsidy_rate = ' || l_subsidy_rate);
7450 
7451       IF l_loan_class = 'DIRECT' THEN
7452         l_cancel_amount := l_requested_amount - l_funded_amount;
7453       ELSE
7454         l_cancel_amount := l_requested_amount;
7455       END IF;
7456 
7457       CLOSE c_loan_info;
7458 
7459       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_cancel_amount = ' || l_cancel_amount);
7460 
7461       l_subsidy_amount := l_cancel_amount * l_subsidy_rate;
7462 
7463       logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_subsidy_amount = ' || l_subsidy_amount);
7464 
7465 
7466       -- 1. Retrieve the distributions of Loan Approved
7467 
7468       OPEN c_get_orig_distributions(p_loan_id);
7469       LOOP
7470 	FETCH c_get_orig_distributions INTO  l_line_type
7471 				,l_account_name
7472 				,l_code_combination_id
7473 				,l_account_type
7474 				,l_distribution_percent
7475 				,l_distribution_type;
7476 
7477 	EXIT WHEN  c_get_orig_distributions%NOTFOUND;
7478 
7479 
7480 	-- 1a. Switch the Debit and Credit
7481 
7482 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_type = ' || l_account_type);
7483 	if l_account_type = 'DR' then
7484 		l_account_type := 'CR';
7485 	elsif l_account_type = 'CR' then
7486 		l_account_type := 'DR';
7487 	end if;
7488 
7489 	l_Cnt := l_Cnt + 1;
7490 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Record ' || l_Cnt);
7491 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_line_type = ' || l_line_type);
7492 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_name = ' || l_account_name);
7493 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
7494 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_type = ' || l_account_type);
7495 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_percent = ' || l_distribution_percent);
7496 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_type = ' || l_distribution_type);
7497 
7498 	l_distributions(l_Cnt).line_type              := l_line_type;
7499 	l_distributions(l_Cnt).account_name           := l_account_name;
7500 	l_distributions(l_Cnt).code_combination_id    := l_code_combination_id;
7501 	l_distributions(l_Cnt).account_type           := l_account_type;
7502 	l_distributions(l_Cnt).distribution_percent   := l_distribution_percent;
7503 	l_distributions(l_Cnt).distribution_type      := l_distribution_type;
7504 	l_distributions(l_Cnt).activity		    := 'LNS_REMAIN_DISB_CANCEL';
7505 
7506 
7507 	-- 1b. Calculate and update the amount
7508 
7509 	open c_num_receivables(p_loan_id);
7510 	fetch c_num_receivables into l_loan_receivables_count;
7511 	close c_num_receivables;
7512 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_receivables_count = ' || l_loan_receivables_count);
7513 
7514 	if l_account_name = 'LOAN_RECEIVABLE'  then
7515 		if l_line_type = 'ORIG' then
7516 		l_receivOrigCnt := l_receivOrigCnt + 1;
7517 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan Orig receivables line ' || l_receivOrigCnt);
7518 
7519 		if l_receivOrigCnt <> l_loan_receivables_count then
7520 		l_distributions(l_Cnt).distribution_amount    := round(l_distribution_percent * l_cancel_amount, l_ledger_details.currency_precision) / 100;
7521 		l_run_rec_org_amt := l_run_rec_org_amt + l_distributions(l_Cnt).distribution_amount;
7522 		else
7523 		l_distributions(l_Cnt).distribution_amount    := l_cancel_amount - l_run_rec_org_amt;
7524 		end if;
7525 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions('||l_Cnt||').distribution_amount = ' || l_distributions(l_Cnt).distribution_amount);
7526 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_run_rec_org_amt = ' || l_run_rec_org_amt);
7527 
7528 		elsif l_line_type = 'SUBSIDY' then
7529 		l_receivSubsidyCnt := l_receivSubsidyCnt + 1;
7530 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan Subsidy receivables line ' || l_receivSubsidyCnt);
7531 
7532 		if l_receivSubsidyCnt <> l_loan_receivables_count then
7533 		l_distributions(l_Cnt).distribution_amount    := round(l_distribution_percent * l_subsidy_amount, l_ledger_details.currency_precision) / 100;
7534 		l_run_rec_sub_amt := l_run_rec_sub_amt + l_distributions(l_Cnt).distribution_amount;
7535 		else
7536 		l_distributions(l_Cnt).distribution_amount    := l_subsidy_amount - l_run_rec_sub_amt;
7537 		end if;
7538 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions('||l_Cnt||').distribution_amount = ' || l_distributions(l_Cnt).distribution_amount);
7539 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_run_rec_sub_amt = ' || l_run_rec_sub_amt);
7540 		end if;
7541 
7542 	end if;
7543 
7544 	if (l_account_name = 'LOAN_CLEARING' or l_account_name = 'LOAN_PAYABLE')  then
7545 		if l_line_type = 'CLEAR' then
7546 		l_clearOrigCnt := l_clearOrigCnt + 1;
7547 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan Orig clearing line ' || l_clearOrigCnt);
7548 		if l_clearOrigCnt <> l_loan_receivables_count then
7549 		l_distributions(l_Cnt).distribution_amount    := round(l_distribution_percent * l_cancel_amount, l_ledger_details.currency_precision) / 100;
7550 		l_run_clear_org_amt := l_run_clear_org_amt + l_distributions(l_Cnt).distribution_amount;
7551 		else
7552 		l_distributions(l_Cnt).distribution_amount    := l_cancel_amount - l_run_clear_org_amt;
7553 		end if;
7554 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions('||l_Cnt||').distribution_amount = ' || l_distributions(l_Cnt).distribution_amount);
7555 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_run_clear_sub_amt = ' || l_run_clear_org_amt);
7556 
7557 		elsif l_line_type = 'SUBSIDY' then
7558 
7559 		l_clearSubsidyCnt := l_clearSubsidyCnt + 1;
7560 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan Subsidy clear line ' || l_receivSubsidyCnt);
7561 
7562 		if l_clearSubsidyCnt <> l_loan_receivables_count then
7563 		l_distributions(l_Cnt).distribution_amount    := round(l_distribution_percent * l_subsidy_amount, l_ledger_details.currency_precision) / 100;
7564 		l_run_clear_sub_amt := l_run_clear_sub_amt + l_distributions(l_Cnt).distribution_amount;
7565 		else
7566 		l_distributions(l_Cnt).distribution_amount    := l_subsidy_amount - l_run_clear_sub_amt;
7567 		end if;
7568 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions('||l_Cnt||').distribution_amount = ' || l_distributions(l_Cnt).distribution_amount);
7569 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_run_clear_sub_amt = ' || l_run_clear_sub_amt);
7570 		end if;
7571 
7572 	end if;
7573       END LOOP;
7574       CLOSE c_get_orig_distributions;
7575 
7576       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'total cancelled distributions adding = ' || l_distributions.count);
7577 
7578       -- 4. Insert Distributions
7579 
7580       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling do_insert_distributions...');
7581       do_insert_distributions(l_distributions, p_loan_id);
7582 
7583 
7584       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'p_commit is '||p_commit);
7585       IF FND_API.to_Boolean(p_commit)
7586       THEN
7587         COMMIT;
7588 	logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'Commited');
7589       END IF;
7590 
7591       FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
7592       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
7593 
7594 EXCEPTION
7595 
7596     WHEN FND_API.G_EXC_ERROR THEN
7597         ROLLBACK TO generateCancelDistributions;
7598         x_return_status := FND_API.G_RET_STS_ERROR;
7599         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
7600         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
7601 
7602     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
7603         ROLLBACK TO generateCancelDistributions;
7604         x_return_status := FND_API.G_RET_STS_ERROR;
7605         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
7606         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
7607 
7608     WHEN OTHERS THEN
7609         ROLLBACK TO generateCancelDistributions;
7610         x_return_status := FND_API.G_RET_STS_ERROR;
7611         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
7612         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
7613 
7614 end generateCancelDistributions;
7615 
7616 
7617 procedure submit_disbursement_bc(p_init_msg_list        in varchar2
7618                               ,p_commit                 in varchar2
7619                               ,p_loan_id			          in NUMBER
7620                               ,p_disb_header_id         in number
7621                               ,p_activity               IN VARCHAR2
7622                               ,x_return_status          OUT NOCOPY VARCHAR2
7623                               ,x_msg_count              OUT NOCOPY NUMBER
7624                               ,x_msg_data               OUT NOCOPY VARCHAR2)
7625 is
7626 
7627   l_api_name         varchar2(50);
7628   l_event_id         number;
7629   l_budget_req_approval   varchar2(1);
7630   l_funds_reserved_flag   varchar2(1);
7631   l_gl_date               date;
7632   l_budget_event_exists   number;
7633   l_status_code           varchar2(25);
7634   l_return_status         varchar2(1);
7635   l_packet_id             number;
7636   l_msg_count             number;
7637   l_msg_data              VARCHAR2(2000);
7638   l_version               number;
7639   l_loan_header_rec       LNS_LOAN_HEADER_PUB.loan_header_rec_type;
7640   l_event_type_code       VARCHAR2(30);
7641   l_PAYMENT_REQUEST_DATE  date;
7642 
7643     cursor c_events(p_loan_id number) is
7644     select event_id
7645         from xla_transaction_entities xlee
7646             ,xla_events xle
7647       where xle.application_id = 206
7648         and xle.entity_id = xlee.entity_id
7649         and xlee.source_id_int_1 = p_loan_id
7650         and xle.budgetary_control_flag = 'Y'
7651         and xle.event_type_code = 'FUTURE_DISBURSEMENT_CANCELLED'
7652         and xle.process_status_code <> 'P';
7653 
7654     cursor c_budget_req(p_loan_id number) is
7655     select nvl(p.BDGT_REQ_FOR_APPR_FLAG, 'N')
7656           ,nvl(h.funds_reserved_flag, 'N')
7657           ,nvl(h.gl_date, sysdate)
7658       from lns_loan_headers h,
7659            lns_loan_products p
7660       where p.loan_product_id = h.product_id
7661         and h.loan_id = p_loan_id;
7662 
7663     cursor c_obj_vers(p_loan_id number) is
7664     select object_version_number
7665       from lns_loan_headers
7666      where loan_id = p_loan_id;
7667 
7668     cursor c_disbursements(p_loan_id number) is
7669     select disb_header_id
7670       from lns_disb_headers
7671      where loan_id = p_loan_id
7672        and disbursement_number = 1;
7673 
7674     cursor c_disb_info(p_disb_header_id number) is
7675     select PAYMENT_REQUEST_DATE
7676       from lns_disb_headers
7677      where disb_header_id = p_disb_header_id;
7678 
7679 begin
7680 
7681       SAVEPOINT submit_disbursement_bc;
7682       l_api_name := 'submit_disbursement_bc';
7683       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
7684       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id '  || p_loan_id);
7685       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_disb_header_id '  || p_disb_header_id);
7686       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_activity '  || p_activity);
7687 
7688       -- Initialize message list IF p_init_msg_list is set to TRUE.
7689       IF FND_API.to_Boolean( p_init_msg_list ) THEN
7690           FND_MSG_PUB.initialize;
7691       END IF;
7692 
7693       -- Initialize API return status to SUCCESS
7694       x_return_status         := FND_API.G_RET_STS_SUCCESS;
7695 
7696 
7697       IF p_activity = 'LNS_SUBMITTED_DISB_CANCEL' THEN
7698         -- first complete accounting for any unprocessed events / documents for the loan transaction
7699         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling lns_distributions_pub.onlineAccounting...');
7700         lns_distributions_pub.onlineAccounting(p_loan_id            => p_loan_id
7701                                               ,p_init_msg_list      => fnd_api.g_false
7702                                               ,p_accounting_mode    => 'F'
7703                                               ,p_transfer_flag      => 'Y'
7704                                               ,p_offline_flag       => 'N'
7705                                               ,p_gl_posting_flag    => 'N'
7706                                               ,x_return_status      => l_return_status
7707                                               ,x_msg_count          => l_msg_count
7708                                               ,x_msg_data           => l_msg_data);
7709         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
7710         if l_return_status <> 'S' then
7711               RAISE FND_API.G_EXC_ERROR;
7712         end if;
7713       END IF;
7714 
7715 /*
7716       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'fetching l_disbusement_id ');
7717       open c_disbursements(p_loan_id);
7718       fetch c_disbursements into l_disbursement_id;
7719       close c_disbursements;
7720       logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'l_disbusement_id ' || l_disbursement_id);
7721 */
7722 
7723       if (lns_utility_pub.IS_FED_FIN_ENABLED = 'Y') then
7724 
7725             -- create disbursement distribution records in lns_distributions for Disbursement Submission
7726             LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling create_DisbursementDistribs...');
7727             LNS_DISTRIBUTIONS_PUB.create_DisbursementDistribs(
7728               p_api_version           => 1.0,
7729               p_init_msg_list         => FND_API.G_FALSE,
7730               p_commit                => FND_API.G_FALSE,
7731               p_loan_id                => p_loan_id,
7732               p_disb_header_id       => p_disb_header_id,
7733               p_activity_type        => p_activity,
7734               x_return_status       => l_return_status,
7735               x_msg_count          => l_msg_count,
7736               x_msg_data            => l_msg_data);
7737 
7738             LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Return status: ' || l_return_status);
7739             IF l_return_status <> 'S' THEN
7740               LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, 'Call to LNS_DISTRIBUTIONS_PUB.create_DisbursementDistribs for Disb Submit failed');
7741               RAISE FND_API.G_EXC_ERROR;
7742             END IF;
7743 
7744             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'federal enabled');
7745             open c_budget_req(p_loan_id);
7746             fetch c_budget_req into l_budget_req_approval, l_funds_reserved_flag, l_gl_date;
7747             close c_budget_req;
7748             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_budget_req_approval '  || l_budget_req_approval);
7749             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_funds_reserved_flag '  || l_funds_reserved_flag);
7750 
7751             -- fix for bug 16068385
7752             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'fetching PAYMENT_REQUEST_DATE ');
7753             open c_disb_info(p_disb_header_id);
7754             fetch c_disb_info into l_PAYMENT_REQUEST_DATE;
7755             close c_disb_info;
7756             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || 'PAYMENT_REQUEST_DATE = ' || l_PAYMENT_REQUEST_DATE);
7757 
7758             IF p_activity = 'LNS_SUBMIT_DISBURSEMENT' THEN
7759               l_event_type_code :=  'DISBURSEMENT_SUBMITTED';
7760             ELSIF p_activity = 'LNS_SUBMITTED_DISB_CANCEL' THEN
7761               l_event_type_code :=  'SUBMITTED_DISB_CANCELLED';
7762             END IF;
7763 
7764             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_XLA_EVENTS.create_event...');
7765 
7766             LNS_XLA_EVENTS.create_event(p_loan_id         => p_loan_id
7767                                     ,p_disb_header_id  => p_disb_header_id
7768                                     ,p_loan_amount_adj_id => -1
7769                                     ,p_event_type_code => l_event_type_code
7770                                     ,p_event_date      => l_PAYMENT_REQUEST_DATE
7771                                     ,p_event_status    => 'U'
7772                                     ,p_init_msg_list   => fnd_api.g_false
7773                                     ,p_commit          => fnd_api.g_false
7774                                     ,p_bc_flag         => 'Y'
7775                                     ,x_event_id        => l_event_id
7776                                     ,x_return_status   => l_return_status
7777                                     ,x_msg_count       => l_msg_count
7778                                     ,x_msg_data        => l_msg_data);
7779             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
7780             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_id = ' || l_event_id);
7781 
7782             IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7783                 FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCOUNTING_EVENT_ERROR');
7784                 FND_MSG_PUB.ADD;
7785                 logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
7786                 RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7787             END IF;
7788 
7789             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'stamping new event_id on distributions');
7790             update lns_distributions
7791             set event_id = l_event_id
7792                 ,last_update_date = sysdate
7793                 ,object_Version_number = object_version_number + 1
7794             where distribution_type = 'ORIGINATION'
7795               and loan_id           = p_loan_id
7796               and disb_header_id    = p_disb_header_id
7797 	            and activity = 	p_activity;
7798          --   and event_id  is  null
7799          --   and (disb_header_id is null and loan_amount_adj_id is null);
7800             logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updated event_id '||l_event_id||' succesfully for '||SQL%ROWCOUNT||' rows');
7801 
7802             if l_funds_reserved_flag = 'Y' then
7803 
7804                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'inserting into PSA_BC_XLA_EVENTS_GT - event => ' || l_event_id);
7805                 insert into PSA_BC_XLA_EVENTS_GT (event_id, result_code)
7806                 values (l_event_id, 'FAIL');
7807 
7808                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling PSA_BC_XLA_PUB.Budgetary_Control  '  || l_event_id);
7809                 -- always pass P_BC_MODE = reserve as per shaniqua williams
7810                 PSA_BC_XLA_PUB.Budgetary_Control(p_api_version      => 1.0
7811                                                 ,p_init_msg_list    => FND_API.G_FALSE
7812                                                 ,x_return_status    => l_return_status
7813                                                 ,x_msg_count        => l_msg_count
7814                                                 ,x_msg_data         => l_msg_data
7815                                                 ,p_application_id   => 206
7816                                                 ,p_bc_mode          => 'R'
7817                                                 ,p_override_flag    => null
7818                                                 ,p_user_id          => null
7819                                                 ,p_user_resp_id     => null
7820                                                 ,x_status_code      => l_status_code
7821                                                 ,x_packet_ID        => l_packet_id);
7822 
7823                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || '  BC status is = ' || l_return_status);
7824                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || '  l_status_code = ' || l_status_code);
7825                 logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || '  l_packet_id = ' || l_packet_id);
7826 
7827                 -- we want to commit ONLY in the case of SUCCESS or ADVISORY
7828                 if (l_return_status <> 'S') then
7829 
7830                     x_return_status         := FND_API.G_RET_STS_ERROR;
7831                     FND_MESSAGE.SET_NAME('LNS', 'LNS_API_OTHERS_EXCEP');
7832                     FND_MESSAGE.SET_TOKEN('ERROR' ,'Call to PSA_BC_XLA_PUB.Budgetary_Control failed with Status Code = ' || l_status_code);
7833                     FND_MSG_PUB.ADD;
7834                     logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
7835                     RAISE FND_API.G_EXC_ERROR;
7836 
7837                 else
7838                     -- caller handle success status
7839                     null;
7840 
7841                 end if; -- BC_API.RETURN_STATUS
7842 
7843 
7844             end if; -- l_funds_reserved_flag
7845 
7846       end if;
7847 
7848       x_return_status         := l_return_status;
7849       IF FND_API.to_Boolean(p_commit)
7850       THEN
7851         COMMIT WORK;
7852       END IF;
7853 
7854       logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
7855 
7856 EXCEPTION
7857 
7858     WHEN FND_API.G_EXC_ERROR THEN
7859         ROLLBACK TO cancel_disbursements;
7860         x_return_status := FND_API.G_RET_STS_ERROR;
7861         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
7862         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
7863 
7864     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
7865         ROLLBACK TO cancel_disbursements;
7866         x_return_status := FND_API.G_RET_STS_ERROR;
7867         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
7868         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
7869 
7870     WHEN OTHERS THEN
7871         ROLLBACK TO cancel_disbursements;
7872         x_return_status := FND_API.G_RET_STS_ERROR;
7873         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
7874         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
7875 
7876 end submit_disbursement_bc;
7877 
7878 /*========================================================================
7879  | PRIVATE PROCEDURE BUILD_ACCRUAL_REPORT
7880  |
7881  | DESCRIPTION
7882  |      This procedure builds accrual report.
7883  |
7884  | CALLED FROM PROCEDURES/FUNCTIONS (local to this package body)
7885  |
7886  | CALLS PROCEDURES/FUNCTIONS (local to this package body)
7887  |      LogMessage
7888  |
7889  | PARAMETERS
7890  |      P_BORROWER_ID         IN             Borrower ID
7891  |	P_LEDGER_ID			IN		Ledger Id
7892  |	P_ORG_ID			IN		Org Id
7893  |      P_LOAN_ID             IN             Loan Id
7894  |	P_PERIOD_NAME		IN	      Inputs period-name for which the periodend accrual
7895  |      P_ACCRUAL_DATE        IN             Accrual Date
7896  |    	P_MODE				IN   Draft / Final
7897  |       X_REPORT_XML          OUT NOCOPY     Return full report xml
7898  |
7899  | KNOWN ISSUES
7900  |      None
7901  |
7902  | NOTES
7903  |      Any interesting aspect of the code in the package body which needs
7904  |      to be stated.
7905  |
7906  | MODIFICATION HISTORY
7907  | Date                  Author            Description of Changes
7908  | 15-OCT-2010            mbolli          Created
7909  |
7910  *=======================================================================*/
7911 PROCEDURE BUILD_ACCRUAL_REPORT(
7912         P_BORROWER_ID         IN       NUMBER,
7913 	P_LEDGER_ID		      IN 	NUMBER,
7914 	P_ORG_ID		      IN	NUMBER,
7915         P_LOAN_ID                    IN       NUMBER,
7916 	P_PERIOD_NAME	      IN      VARCHAR2,
7917         P_ACCRUAL_DATE        IN      DATE,
7918 	P_MODE			      IN	VARCHAR2,
7919 	P_CP_STATEMENTS      IN      CLOB,
7920         P_STATEMENTS_XML   IN       CLOB)
7921 IS
7922 
7923 /*-----------------------------------------------------------------------+
7924  | Local Variable Declarations and initializations                       |
7925  +-----------------------------------------------------------------------*/
7926 
7927     l_api_name      CONSTANT VARCHAR2(30) := 'BUILD_ACCRUAL_REPORT';
7928     l_new_line      varchar2(1);
7929     l_header        varchar2(1000);
7930     l_footer        varchar2(100);
7931     l_parameters    varchar2(1000);
7932     l_org           VARCHAR2(360);
7933     l_accrual_date  VARCHAR2(60);
7934     l_org_name      VARCHAR2(240);
7935     l_org_id        NUMBER;
7936     l_borrower	VARCHAR2(360);
7937     l_loan            VARCHAR2(60);
7938     l_ledger_name	VARCHAR2(30);
7939     l_append		VARCHAR2(250);
7940 /*-----------------------------------------------------------------------+
7941  | Cursor Declarations                                                   |
7942  +-----------------------------------------------------------------------*/
7943     /* query for borrower name */
7944     CURSOR borrower_cur(P_BORROWER_ID number) IS
7945     select party_name from hz_parties party where party_id = P_BORROWER_ID;
7946 
7947     /* query for loan number */
7948     CURSOR loan_cur(P_LOAN_ID number) IS
7949     select loan_number from lns_loan_headers where loan_id = P_LOAN_ID;
7950 
7951     /* query for org name */
7952     CURSOR org_cur(C_ORG_ID number) IS
7953     select name
7954     from hr_all_organization_units_tl
7955     where ORGANIZATION_ID = C_ORG_ID and
7956     language(+) = userenv('LANG');
7957 
7958     /* query for ledger name */
7959     CURSOR cur_ledger(C_LEDGER_ID number) IS
7960     select name
7961     from gl_ledgers
7962     where ledger_id = C_LEDGER_ID;
7963 
7964 BEGIN
7965 
7966     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, ' ');
7967     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' +');
7968 
7969     /* init report clob */
7970     dbms_lob.createtemporary(g_last_accrual_report, FALSE, DBMS_LOB.CALL);
7971     dbms_lob.open(g_last_accrual_report, dbms_lob.lob_readwrite);
7972 
7973     l_new_line := '
7974 ';
7975     l_header := '<?xml version="1.0" encoding="UTF-8"?>' || l_new_line || '<ACCRUALBATCH>';
7976     l_footer := l_new_line || '</ACCRUALBATCH>' || l_new_line;
7977     l_parameters := l_new_line || '<PARAMETERS>';
7978 
7979     /* adding org name to parameter list */
7980     IF P_LEDGER_ID IS NOT NULL THEN
7981 	open cur_ledger(p_ledger_id);
7982 	fetch cur_ledger into l_ledger_name;
7983 	close cur_ledger;
7984     END IF;
7985     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_ledger_name: ' || l_ledger_name);
7986     l_parameters := l_parameters || l_new_line || '<LEDGER_NAME>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_ledger_name) || '</LEDGER_NAME>';
7987 
7988 
7989     /* adding org name to parameter list */
7990     IF P_ORG_ID IS NOT NULL THEN
7991 	open org_cur(p_org_id);
7992 	fetch org_cur into l_org_name;
7993 	close org_cur;
7994      END IF;
7995      LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_org_name: ' || l_org_name);
7996      l_parameters := l_parameters || l_new_line || '<ORG_NAME>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_org_name) || '</ORG_NAME>';
7997 
7998 
7999     /* adding borrower to parameter list */
8000     if P_BORROWER_ID is not null then
8001         open borrower_cur(P_BORROWER_ID);
8002         fetch borrower_cur into l_borrower;
8003         close borrower_cur;
8004     end if;
8005     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_borrower: ' || l_borrower);
8006     l_parameters := l_parameters || l_new_line || '<BORROWER_NAME>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_borrower) || '</BORROWER_NAME>';
8007 
8008     /* adding loan to parameter list */
8009     if P_LOAN_ID is not null then
8010         open loan_cur(P_LOAN_ID);
8011         fetch loan_cur into l_loan;
8012         close loan_cur;
8013     end if;
8014     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan: ' || l_loan);
8015     l_parameters := l_parameters || l_new_line || '<LOAN_NUMBER>' || l_loan || '</LOAN_NUMBER>';
8016 
8017 
8018    /* adding accrual_period to parameter list */
8019     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_period_name: ' || p_period_name);
8020     l_parameters := l_parameters || l_new_line || '<PERIOD>' ||p_period_name|| '</PERIOD>';
8021 
8022     /* adding accrual_date to parameter list */
8023     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_accrual_date: ' || p_accrual_date);
8024     l_parameters := l_parameters || l_new_line || '<ACCRUAL_DATE>' || to_char(p_accrual_date,'YYYY-MM-DD')|| '</ACCRUAL_DATE>';
8025 
8026     /* adding mode to parameter list */
8027     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_mode: ' || p_mode);
8028     l_parameters := l_parameters || l_new_line || '<MODE>' ||p_mode|| '</MODE>';
8029 
8030     l_parameters := l_parameters || l_new_line || '<REPORT_GENERATION_DATE>' || to_char(sysdate,'YYYY-MM-DD') || '</REPORT_GENERATION_DATE>';
8031 
8032     l_parameters := l_parameters || l_new_line || '</PARAMETERS>' || l_new_line;
8033     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_parameters: ' || l_parameters);
8034 
8035 
8036     /* add header to accrual report */
8037     DBMS_LOB.write(g_last_accrual_report, length(l_header), 1, l_header);
8038     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Added header to report');
8039 
8040     /* add parameters to accrual report */
8041     dbms_lob.writeAppend(g_last_accrual_report, length(l_parameters), l_parameters);
8042     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Added parameters to report');
8043 
8044     /* add P_CP_STATEMENTS to accrual report */
8045     l_append := l_new_line ||  P_CP_STATEMENTS || l_new_line;
8046     dbms_lob.writeAppend(g_last_accrual_report, length(l_append), l_append);
8047     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Added P_CP_STATEMENTS to report');
8048 
8049 
8050     l_append := l_new_line ||  '<LOANS_SUCCESSED>'|| g_passed_loan_cnt ||'</LOANS_SUCCESSED>';
8051     dbms_lob.writeAppend(g_last_accrual_report, length(l_append), l_append);
8052 
8053     l_append := l_new_line || '<LOANS_FAILED>'|| g_failed_loan_cnt ||'</LOANS_FAILED>';
8054     dbms_lob.writeAppend(g_last_accrual_report, length(l_append), l_append);
8055 
8056     l_append := l_new_line || '<LOANS>'|| l_new_line;
8057     dbms_lob.writeAppend(g_last_accrual_report, length(l_append), l_append);
8058 
8059 
8060     /* add all statements to billing report */
8061     if dbms_lob.getlength(P_STATEMENTS_XML) > 0 then
8062         DBMS_LOB.Append(g_last_accrual_report, P_STATEMENTS_XML);
8063         LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Added statements to report');
8064     end if;
8065 
8066     l_append := l_new_line || '</LOANS>';
8067     dbms_lob.writeAppend(g_last_accrual_report, length(l_append), l_append);
8068 
8069     /* add footer to billing report */
8070     dbms_lob.writeAppend(g_last_accrual_report, length(l_footer), l_footer);
8071     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Added footer to report');
8072 
8073     /* print report to output file */
8074     LNS_REP_UTILS.PRINT_CLOB(g_last_accrual_report);  -- fix for bug 6938098
8075     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Printed report into output file.');
8076 
8077     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' -');
8078 
8079 EXCEPTION
8080     WHEN OTHERS THEN
8081         LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Failed to generate accrual report');
8082         g_cr_return_status := 'WARNING';
8083 END BUILD_ACCRUAL_REPORT;
8084 
8085 
8086 /*========================================================================
8087  | PRIVATE PROCEDURE BUILD_ACCRUAL_STMT
8088  |
8089  | DESCRIPTION
8090  |      This procedure builds error statement.
8091  |
8092  | CALLED FROM PROCEDURES/FUNCTIONS (local to this package body)
8093  |
8094  | CALLS PROCEDURES/FUNCTIONS (local to this package body)
8095  |      LogMessage
8096  |
8097  | PARAMETERS
8098  |       P_LOAN_ID             IN             Loans ID
8099  |       P_ACCRUAL_DATE     IN             Accrual Date
8100  |	 P_LAST_ACCRUED_DATE  IN		Last Accrual Date for this loan
8101  |       P_INT_ACCRUED       IN            Interest Accrued
8102  |	 P_INT_ACCRUED_DETAILS  IN	Interest Accrued Details Str
8103  |	 P_ACCRUED_DIST_DET   IN	 Accrued Distribution Details
8104  |	 P_RESULT			IN   'S/W/E' (Success/Warning/Error)
8105  |	 P_ERR_COUNT		IN	Error count if Warning/Error
8106  |       X_STATEMENT_XML       OUT NOCOPY     Return full report xml
8107  |
8108  | KNOWN ISSUES
8109  |      None
8110  |
8111  | NOTES
8112  |      Any interesting aspect of the code in the package body which needs
8113  |      to be stated.
8114  |
8115  | MODIFICATION HISTORY
8116  | Date                  Author            Description of Changes
8117  | 15-OCT-2010           MBOLLI             Created
8118  |
8119  *=======================================================================*/
8120 PROCEDURE BUILD_ACCRUAL_STMT(
8121         P_LOAN_ID           			IN     NUMBER,
8122 	P_PERIOD_NAME			IN	VARCHAR2,
8123         P_ACCRUAL_DATE      		IN     DATE,
8124 	--P_LAST_ACCRUED_DATE	IN	DATE,
8125         P_INT_ACCRUED       		IN     NUMBER,
8126 	--P_INT_ACCRUED_DETAILS 	IN	VARCHAR2,
8127 	--P_ACCRUED_DIST_DET		IN	CLOB,
8128 	P_RESULT				IN	VARCHAR2,
8129         P_ERR_COUNT			IN     NUMBER,
8130         X_STATEMENT_XML     		IN	OUT NOCOPY      CLOB)
8131 IS
8132 
8133 /*-----------------------------------------------------------------------+
8134  | Local Variable Declarations and initializations                       |
8135  +-----------------------------------------------------------------------*/
8136 
8137     l_api_name          CONSTANT VARCHAR2(30) := 'BUILD_ACCRUAL_STMT';
8138     l_new_line          VARCHAR2(1);
8139     l_statement        VARCHAR2(2000);
8140     l_statement2       VARCHAR2(2000);
8141     l_in_statement    CLOB;
8142     l_err_msg	     VARCHAR2(2000);
8143     l_borrower	     VARCHAR2(360);
8144     l_loan_num         VARCHAR2(60);
8145     l_currency           VARCHAR2(15);
8146     l_accr_int_amount     VARCHAR2(50);
8147     l_last_payment_no	   NUMBER;
8148     l_last_bill_due_date   DATE;
8149     l_loan_start_date	   DATE;
8150     l_index               NUMBER;
8151     l_indexNo           NUMBER;
8152     l_error             VARCHAR2(500);
8153 /*-----------------------------------------------------------------------+
8154  | Cursor Declarations                                                   |
8155  +-----------------------------------------------------------------------*/
8156 
8157     /* query for loan number */
8158     CURSOR loan_cur(C_LOAN_ID number, C_INT_ACCRUED number) IS
8159         SELECT
8160 		party.party_name
8161 		,loan.loan_number
8162         	,loan.LOAN_CURRENCY
8163         	,to_char(C_INT_ACCRUED, FND_CURRENCY.SAFE_GET_FORMAT_MASK(loan.LOAN_CURRENCY,50))
8164 		,loan.last_payment_number
8165 		,decode(loan.current_phase, 'OPEN', to_char(loan.open_loan_start_date,'YYYY-MM-DD'), to_char(loan.loan_start_date,'YYYY-MM-DD'))
8166         FROM
8167 		lns_loan_headers loan,
8168 		hz_parties party
8169         WHERE party.party_id = loan.PRIMARY_BORROWER_ID
8170 	     AND loan.loan_id = C_LOAN_ID;
8171 
8172 
8173  -- CURSOR to retrieve the last accrual date for the loan
8174    	CURSOR cur_last_accrual_date(c_loan_id NUMBER)   IS
8175     	SELECT
8176     		max(ldist.accrual_date)
8177     	FROM
8178     		lns_distributions ldist
8179     	WHERE ldist.loan_id = c_loan_id
8180 	     AND ldist.distribution_type = 'ACCRUAL'
8181   	     AND ldist. activity = 'INTEREST_ACCRUAL';
8182 
8183    -- CURSOR to retrieve the last accrual date for the loan
8184    	CURSOR cur_last_bill_duel_date(c_loan_id NUMBER)   IS
8185     	SELECT
8186     		to_char(max(amort.due_date),'YYYY-MM-DD')
8187     	FROM
8188     		LNS_AMORTIZATION_SCHEDS  amort
8189     	WHERE amort.loan_id = c_loan_id
8190 	     AND amort.reversed_flag = 'N';
8191 
8192 BEGIN
8193 
8194     l_index := 0;
8195     l_indexNo := 1;
8196     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, ' ');
8197     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' +');
8198 
8199     l_new_line := '
8200 ';
8201 
8202     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Passed input parameters:');
8203     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_LOAN_ID: ' || P_LOAN_ID);
8204     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_PERIOD_NAME: ' || P_PERIOD_NAME);
8205     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_ACCRUAL_DATE: ' || P_ACCRUAL_DATE);
8206     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_INT_ACCRUED: ' || P_INT_ACCRUED);
8207     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_RESULT: ' || P_RESULT);
8208     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_ERR_COUNT: ' || P_ERR_COUNT);
8209 
8210 
8211     /* init l_in_statement clob */
8212     dbms_lob.createtemporary(l_in_statement, FALSE, DBMS_LOB.CALL);
8213     dbms_lob.open(l_in_statement, dbms_lob.lob_readwrite);
8214 
8215     DBMS_LOB.write(l_in_statement, length(X_STATEMENT_XML), 1, X_STATEMENT_XML);
8216 
8217 
8218     /* init statement xml */
8219     DBMS_LOB.createtemporary(X_STATEMENT_XML, FALSE, DBMS_LOB.CALL);
8220     DBMS_LOB.open(X_STATEMENT_XML, DBMS_LOB.lob_readwrite);
8221 
8222 
8223     /* query for loan number  */
8224     open loan_cur(P_LOAN_ID, P_INT_ACCRUED);
8225     fetch loan_cur into l_borrower, l_loan_num, l_currency, l_accr_int_amount, l_last_payment_no, l_loan_start_date;
8226     close loan_cur;
8227 
8228     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_num: ' || l_loan_num);
8229     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_accr_int_amount: ' || l_accr_int_amount);
8230 
8231     OPEN cur_last_bill_duel_date(P_LOAN_ID);
8232     FETCH cur_last_bill_duel_date INTO l_last_bill_due_date;
8233     CLOSE cur_last_bill_duel_date;
8234 
8235     /*
8236     IF l_last_bill_due_date IS NULL  THEN
8237 	l_last_bill_due_date := l_loan_start_date;
8238     END IF;
8239     */
8240 
8241     /* build statement */
8242     l_statement := '<LOAN>';
8243 
8244     l_statement := l_statement || l_new_line || '<LOAN_ID>' || P_LOAN_ID || '</LOAN_ID>';
8245     l_statement := l_statement || l_new_line || '<BORROWER_NAME>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_borrower) || '</BORROWER_NAME>';
8246     l_statement := l_statement || l_new_line || '<LOAN_NUMBER>' || l_loan_num || '</LOAN_NUMBER>';
8247     l_statement := l_statement || l_new_line || '<LOAN_START_DATE>'||to_char(l_loan_start_date,'YYYY-MM-DD')||'</LOAN_START_DATE>';
8248     l_statement := l_statement || l_new_line || '<LAST_PAYMENT_NUMBER>'||l_last_payment_no||'</LAST_PAYMENT_NUMBER>';
8249     l_statement := l_statement || l_new_line || '<LAST_BILL_DUE_DATE>'||to_char(l_last_bill_due_date,'YYYY-MM-DD')||'</LAST_BILL_DUE_DATE>';
8250    -- l_statement := l_statement || l_new_line || '<LAST_ACCRUAL_DATE>' || P_LAST_ACCRUED_DATE || '</LAST_ACCRUAL_DATE>';
8251     l_statement := l_statement || l_new_line || '<ACCRUAL_PERIOD>' || P_PERIOD_NAME || '</ACCRUAL_PERIOD>';
8252     l_statement := l_statement || l_new_line || '<ACCRUAL_DATE>' || to_char(P_ACCRUAL_DATE,'YYYY-MM-DD') || '</ACCRUAL_DATE>';
8253     l_statement := l_statement || l_new_line || '<LOAN_CURRENCY>' || l_currency || '</LOAN_CURRENCY>';
8254     l_statement := l_statement || l_new_line || '<RESULT>'||P_RESULT||'</RESULT>';
8255     l_statement := l_statement || l_new_line || '<INTEREST_ACCRUED>' || l_accr_int_amount || '</INTEREST_ACCRUED>';
8256     --l_statement := l_statement || l_new_line || '<INTEREST_ACCRUED_DETAILS>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(P_INT_ACCRUED_DETAILS) || '</INTEREST_ACCRUED_DETAILS>';
8257     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_statement: ' || l_statement);
8258     dbms_lob.write(X_STATEMENT_XML, length(l_statement), 1, l_statement);
8259     dbms_lob.append(X_STATEMENT_XML, l_in_statement);
8260 
8261     l_statement2 := '';
8262 
8263 
8264   --  l_statement := l_statement || l_new_line || '<ACCRUAL_DISTRIBUTIONS>';
8265   --  l_statement := l_statement || l_new_line ||P_ACCRUED_DIST_DET;
8266   --  l_statement := l_statement || l_new_line || '</ACCRUAL_DISTRIBUTIONS>';
8267 
8268     l_statement2 := l_statement2 || l_new_line;
8269 
8270      IF P_RESULT in ( 'E', 'W')  THEN
8271 	WHILE (l_indexNo <= P_ERR_COUNT ) LOOP
8272 		fnd_msg_pub.get(l_indexNo, 'F', l_error, l_index);
8273 		l_error := LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_error);
8274 		l_err_msg:= l_err_msg || l_error;
8275 		l_indexNo := l_indexNo + 1;
8276 	END LOOP;
8277 
8278 	IF P_RESULT = 'E' THEN
8279 		l_statement2 :=  l_statement2 || l_new_line ||'<LOAN_ERROR>'|| l_err_msg ||'</LOAN_ERROR>';
8280 		l_statement2 :=  l_statement2 || l_new_line ||'<LOAN_WARNING></LOAN_WARNING>';
8281 	ELSIF P_RESULT = 'W' THEN
8282 		l_statement2 := l_statement2 || l_new_line|| '<LOAN_ERROR></LOAN_ERROR>';
8283 		l_statement2 := l_statement2 || l_new_line|| '<LOAN_WARNING>'|| l_err_msg ||'</LOAN_WARNING>';
8284 	END IF;
8285     END IF;
8286 
8287     l_statement2 := l_statement2 || l_new_line || '</LOAN>';
8288     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_statement2: ' || l_statement2);
8289 
8290 
8291 
8292     /* updating clob */
8293     DBMS_LOB.writeAppend(X_STATEMENT_XML, length(l_statement2), l_statement2);
8294 
8295     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' -');
8296 
8297 EXCEPTION
8298     WHEN OTHERS THEN
8299         LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Failed to generate error statement for loan ' || l_loan_num);
8300 
8301 END BUILD_ACCRUAL_STMT;
8302 
8303 
8304 /*========================================================================
8305  | PRIVATE PROCEDURE BUILD_ACCRUAL_ERR_STMT
8306  |
8307  | DESCRIPTION
8308  |      This procedure builds error statement.
8309  |
8310  | CALLED FROM PROCEDURES/FUNCTIONS (local to this package body)
8311  |
8312  | CALLS PROCEDURES/FUNCTIONS (local to this package body)
8313  |      LogMessage
8314  |
8315  | PARAMETERS
8316  |       P_ACCRUAL_DATE     IN             Accrual Date
8317  |       P_RESULT       IN            Result - W/E  (Warning / Error)
8318  |	 P_ERR_COUNT		IN	Error Count
8319  |       X_REPORT_XML          OUT NOCOPY     Return full report xml
8320  |
8321  | KNOWN ISSUES
8322  |      None
8323  |
8324  | NOTES
8325  |      Any interesting aspect of the code in the package body which needs
8326  |      to be stated.
8327  |
8328  | MODIFICATION HISTORY
8329  | Date                  Author            Description of Changes
8330  | 15-OCT-2010           MBOLLI             Created
8331  |
8332  *=======================================================================*/
8333 PROCEDURE BUILD_ACCRUAL_ERR_STMT(
8334         P_ACCRUAL_DATE      		IN     DATE,
8335 	P_RESULT				IN	VARCHAR2,
8336         P_ERR_COUNT			IN     NUMBER,
8337         X_STATEMENT_XML     		OUT NOCOPY      CLOB)
8338 IS
8339 
8340 /*-----------------------------------------------------------------------+
8341  | Local Variable Declarations and initializations                       |
8342  +-----------------------------------------------------------------------*/
8343 
8344     l_api_name          CONSTANT VARCHAR2(30) := 'BUILD_ACCRUAL_ERR_STMT';
8345     l_new_line          varchar2(1);
8346     l_statement         varchar2(2000);
8347     l_err_msg	     varchar2(2000);
8348     l_index             number;
8349     l_indexNo           number;
8350     l_error             varchar2(500);
8351 /*-----------------------------------------------------------------------+
8352  | Cursor Declarations                                                   |
8353  +-----------------------------------------------------------------------*/
8354 
8355 
8356 BEGIN
8357 
8358     l_index := 0;
8359     l_indexNo := 1;
8360     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, ' ');
8361     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' +');
8362 
8363     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_ACCRUAL_DATE = ' || P_ACCRUAL_DATE);
8364     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_RESULT = ' || P_RESULT);
8365     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_ERR_COUNT = ' || P_ERR_COUNT);
8366 
8367     l_new_line := '
8368 ';
8369 
8370     /* build error statement */
8371 
8372     WHILE (l_indexNo <= P_ERR_COUNT ) LOOP
8373         fnd_msg_pub.get(l_indexNo, 'F', l_error, l_index);
8374         l_error := LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_error);
8375 	LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_error: ' || l_error);
8376 	l_err_msg := l_err_msg || l_error;
8377         l_indexNo := l_indexNo + 1;
8378     END LOOP;
8379 
8380     IF P_RESULT = 'E' THEN
8381     	l_statement := '<ERROR>'|| l_err_msg ||'</ERROR>';
8382 	l_statement := l_statement || l_new_line|| '<WARNING></WARNING>';
8383     ELSIF P_RESULT = 'W' THEN
8384     	l_statement := l_statement || l_new_line|| '<ERROR></ERROR>';
8385 	l_statement := l_statement || l_new_line|| '<WARNING>'|| l_err_msg ||'</WARNING>';
8386     END IF;
8387 
8388     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_statement: ' || l_statement);
8389 
8390     /* init statement xml */
8391     DBMS_LOB.createtemporary(X_STATEMENT_XML, FALSE, DBMS_LOB.CALL);
8392     DBMS_LOB.open(X_STATEMENT_XML, DBMS_LOB.lob_readwrite);
8393 
8394     /* building clob */
8395     DBMS_LOB.write(X_STATEMENT_XML, length(l_statement), 1, l_statement);
8396 
8397     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' -');
8398 
8399 EXCEPTION
8400     WHEN OTHERS THEN
8401         LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Failed to generate error statement');
8402 
8403 END BUILD_ACCRUAL_ERR_STMT;
8404 
8405 
8406 PROCEDURE create_AccrualDistribs(p_api_version           IN NUMBER
8407 			                               ,p_init_msg_list         IN  VARCHAR2
8408 			                               ,p_commit                IN  VARCHAR2
8409 			                               ,p_loan_id               IN  NUMBER
8410 						       ,p_period_name		IN  VARCHAR2
8411 						       ,p_accrual_date          IN  DATE
8412 						       ,p_accrued_amount        IN  NUMBER
8413 						       ,p_activity_type         IN  VARCHAR2
8414 						       ,p_accounting_mode  IN  VARCHAR2
8415 			                               ,x_return_status         OUT NOCOPY VARCHAR2
8416 			                               ,x_msg_count             OUT NOCOPY NUMBER
8417 			                               ,x_msg_data              OUT NOCOPY VARCHAR2)
8418 
8419 is
8420     l_api_name                 varchar2(30);
8421     l_msg_count                NUMBER;
8422     l_msg_data                 VARCHAR2(2000);
8423     l_return_Status            VARCHAR2(1);
8424     l_distributions                lns_distributions_pub.distribution_tbl;
8425     l_distributions_count      NUMBER;
8426     l_activity		        VARCHAR2(30);
8427     l_exists                   	NUMBER;
8428     l_accrued_amt	         NUMBER;
8429     l_line_type                     VARCHAR2(30);
8430     l_account_name             VARCHAR2(30);
8431     l_code_combination_id     NUMBER;
8432     l_account_type               VARCHAR2(30);
8433     l_distribution_percent      NUMBER;
8434     l_distribution_type           VARCHAR2(30);
8435     l_int_receivables_count    NUMBER;
8436     l_int_incomes_count        NUMBER;
8437     l_accrued_amount           NUMBER;
8438 
8439     l_rec_cnt			  NUMBER;
8440     l_int_rec_line_cnt		  NUMBER;
8441     l_int_income_line_cnt	  NUMBER;
8442     l_int_rec_running_amt 	  NUMBER;
8443     l_int_income_running_amt  NUMBER;
8444     l_ledger_details         	   lns_distributions_pub.gl_ledger_details;
8445     l_loan_num		   	   VARCHAR2(30);
8446 
8447 
8448 
8449     /* query for loan number */
8450     CURSOR loan_cur(C_LOAN_ID number) IS
8451         SELECT
8452 		loan.loan_number
8453         FROM
8454 		lns_loan_headers loan
8455         WHERE
8456 		 loan.loan_id = C_LOAN_ID;
8457 
8458     CURSOR c_accrual_date_distrbs_exists(c_loan_id NUMBER, c_accrual_date VARCHAR2) IS
8459       SELECT count(1)
8460       FROM   lns_distributions ldist
8461       WHERE ldist.loan_id = c_loan_id
8462 	   AND ldist.accrual_date >= c_accrual_date
8463            AND ldist.distribution_type = 'ACCRUAL'
8464 	   AND ldist.accrual_completed_flag = 'Y';
8465 
8466     CURSOR c_get_bill_int_distrbs(c_loan_id number) IS
8467        select ldist.line_type
8468              ,ldist.account_name
8469              ,ldist.code_combination_id
8470              ,ldist.account_type
8471              ,ldist.distribution_percent
8472              ,ldist.distribution_type
8473        from lns_distributions ldist
8474        where ldist.loan_id = c_loan_id
8475          and ldist.line_type = 'INT'
8476          and ldist.distribution_type = 'BILLING'
8477          and ldist.distribution_percent >= 0
8478         order by ldist.account_type, ldist.code_combination_id;
8479 
8480     CURSOR c_num_int_receivables(c_loan_id number) IS
8481     select count(1)
8482       from lns_distributions ldist
8483      where  ldist.loan_id = c_loan_id
8484          and ldist.line_type = 'INT'
8485          and ldist.distribution_type = 'BILLING'
8486          and ldist.distribution_percent >= 0
8487 	 and ldist.account_type = 'DR'
8488 	 and ldist.account_name = 'INTEREST_RECEIVABLE';
8489 
8490     CURSOR c_num_int_incomes(c_loan_id number) IS
8491     select count(1)
8492       from lns_distributions ldist
8493      where  ldist.loan_id = c_loan_id
8494          and ldist.line_type = 'INT'
8495          and ldist.distribution_type = 'BILLING'
8496          and ldist.distribution_percent >= 0
8497 	 and ldist.account_type = 'CR'
8498 	 and ldist.account_name = 'INTEREST_INCOME';
8499 
8500 
8501 
8502 begin
8503 
8504      l_api_name   := 'create_AccrualDistribs';
8505      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || ' - BEGIN');
8506 
8507      SAVEPOINT create_AccrualDistribs;
8508 
8509      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
8510      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_period_name = ' || p_period_name);
8511      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_accrual_date = ' || p_accrual_date);
8512      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_accrued_amount = ' || p_accrued_amount);
8513      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_accounting_mode = ' || p_accounting_mode);
8514 
8515 
8516 
8517 
8518      -- Initialize message list IF p_init_msg_list is set to TRUE.
8519      IF FND_API.to_Boolean( p_init_msg_list ) THEN
8520          FND_MSG_PUB.initialize;
8521      END IF;
8522 
8523      -- Initialize API return status to SUCCESS
8524      x_return_status := FND_API.G_RET_STS_SUCCESS;
8525 
8526      --l_activity       := 'INTEREST_ACCRUAL';
8527      l_activity         :=  p_activity_type;
8528 
8529      OPEN  c_accrual_date_distrbs_exists(p_loan_id, p_accrual_date);
8530      FETCH c_accrual_date_distrbs_exists INTO l_exists;
8531      CLOSE c_accrual_date_distrbs_exists;
8532 
8533      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Accrual Dist exists later or equal are: '||l_exists);
8534 
8535      IF  l_exists = 0 THEN
8536         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Retrieving Billing Interest Distributions...');
8537 
8538 
8539         l_rec_cnt := 0;
8540         l_int_rec_line_cnt := 0;
8541         l_int_income_line_cnt := 0;
8542         l_int_rec_running_amt := 0;
8543         l_int_income_running_amt := 0;
8544         l_ledger_details   := lns_distributions_pub.getLedgerDetails;
8545         ------------------------------
8546         l_accrued_amount  := p_accrued_amount;
8547         -------------------------------
8548 
8549 	OPEN  c_num_int_receivables(p_loan_id);
8550      	FETCH c_num_int_receivables into l_int_receivables_count;
8551      	CLOSE c_num_int_receivables;
8552      	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_int_receivables_count = ' || l_int_receivables_count);
8553 
8554 	OPEN  c_num_int_incomes(p_loan_id);
8555      	FETCH c_num_int_incomes into l_int_incomes_count;
8556      	CLOSE c_num_int_incomes;
8557      	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_int_incomes_count = ' || l_int_incomes_count);
8558 
8559         OPEN c_get_bill_int_distrbs(p_loan_id);
8560 	LOOP
8561         FETCH c_get_bill_int_distrbs INTO
8562                   l_line_type
8563                   ,l_account_name
8564                   ,l_code_combination_id
8565                   ,l_account_type
8566                   ,l_distribution_percent
8567                   ,l_distribution_type;
8568 
8569 	EXIT WHEN c_get_bill_int_distrbs%NOTFOUND;
8570 
8571 
8572         l_distribution_type := 'ACCRUAL';
8573 
8574         l_rec_cnt  :=  l_rec_cnt + 1;
8575         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Record ' || l_rec_cnt);
8576         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_line_type = ' || l_line_type);
8577         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_name = ' || l_account_name);
8578         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
8579         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_type = ' || l_account_type);
8580         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_percent = ' || l_distribution_percent);
8581         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_type = ' || l_distribution_type);
8582 
8583 
8584         l_distributions(l_rec_cnt).line_type              := l_line_type;
8585         l_distributions(l_rec_cnt).account_name           := l_account_name;
8586         l_distributions(l_rec_cnt).code_combination_id    := l_code_combination_id;
8587         l_distributions(l_rec_cnt).account_type           := l_account_type;
8588         l_distributions(l_rec_cnt).distribution_percent   := l_distribution_percent;
8589         l_distributions(l_rec_cnt).distribution_type      := l_distribution_type;
8590 
8591 	IF p_accounting_mode = 'FINAL'  THEN
8592 		l_distributions(l_rec_cnt).accrual_completed_flag      := 'Y';
8593 	ELSE
8594 		l_distributions(l_rec_cnt).accrual_completed_flag      := 'N';
8595 	END IF;
8596 
8597 
8598         IF l_account_name = 'INTEREST_RECEIVABLE'  THEN
8599           l_int_rec_line_cnt := l_int_rec_line_cnt + 1;
8600           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Interest receivable line ' || l_int_rec_line_cnt);
8601 
8602           if l_int_rec_line_cnt <> l_int_receivables_count then
8603               l_distributions(l_rec_cnt).distribution_amount    := round(l_distribution_percent * l_accrued_amount, l_ledger_details.currency_precision) / 100;
8604               l_int_rec_running_amt := l_int_rec_running_amt + l_distributions(l_rec_cnt).distribution_amount;
8605           else
8606               l_distributions(l_rec_cnt).distribution_amount    := l_accrued_amount - l_int_rec_running_amt;
8607           end if;
8608 
8609           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions(i).distribution_amount = ' || l_distributions(l_rec_cnt).distribution_amount);
8610           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_int_rec_running_amt = ' || l_int_rec_running_amt);
8611         END IF;
8612 
8613 
8614         IF l_account_name = 'INTEREST_INCOME'  THEN
8615           l_int_income_line_cnt := l_int_income_line_cnt + 1;
8616           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Interset Income line ' || l_int_income_line_cnt);
8617 
8618           if l_int_income_line_cnt <> l_int_incomes_count then
8619               l_distributions(l_rec_cnt).distribution_amount    := round(l_distribution_percent * l_accrued_amount, l_ledger_details.currency_precision) / 100;
8620               l_int_income_running_amt := l_int_income_running_amt + l_distributions(l_rec_cnt).distribution_amount;
8621           else
8622               l_distributions(l_rec_cnt).distribution_amount    := l_accrued_amount - l_int_income_running_amt;
8623           end if;
8624 
8625           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions(l_rec_cnt).distribution_amount = ' || l_distributions(l_rec_cnt).distribution_amount);
8626           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_int_income_running_amt = ' || l_int_income_running_amt);
8627         END IF;
8628 
8629         END LOOP;
8630 
8631         CLOSE c_get_bill_int_distrbs;
8632 
8633         if l_return_status <> 'S' then
8634             RAISE FND_API.G_EXC_ERROR;
8635         end if;
8636 
8637         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributionsCatch.count = ' || l_distributions.count);
8638         for j in 1..l_distributions.count loop
8639             l_distributions(j).activity     := l_activity;
8640             l_distributions(j).accrual_date := p_accrual_date;
8641 	    l_distributions(j).accrual_period := p_period_name;
8642         end loop;
8643 
8644         l_distributions_count := l_distributions.count;
8645 
8646         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'total distributions adding = ' || l_distributions.count);
8647 
8648         logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling do_insert_distributions...');
8649         do_insert_distributions(l_distributions, p_loan_id);
8650 
8651      ELSE     -- IF l_exists == 0
8652 
8653     	OPEN loan_cur(p_loan_id);
8654 	FETCH loan_cur INTO l_loan_num;
8655 	CLOSE loan_cur;
8656 
8657 	FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCRUED_ALREADY');
8658 	FND_MESSAGE.SET_TOKEN('LOAN_NUMBER', l_loan_num);
8659 	FND_MESSAGE.SET_TOKEN('LAST_ACCRUAL_DATE', p_accrual_date);
8660 	FND_MSG_PUB.Add;
8661 	LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
8662 
8663 	RAISE FND_API.G_EXC_ERROR;
8664 
8665      END IF;    -- IF l_exists == 0
8666 
8667      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'p_commit is '||p_commit);
8668      IF FND_API.to_Boolean(p_commit)
8669      THEN
8670          COMMIT;
8671         logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'Commited');
8672      END IF;
8673 
8674      FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
8675      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
8676 
8677 EXCEPTION
8678 
8679     WHEN FND_API.G_EXC_ERROR THEN
8680         ROLLBACK TO create_AccrualDistribs;
8681         x_return_status := FND_API.G_RET_STS_ERROR;
8682         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
8683         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
8684 
8685     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
8686         ROLLBACK TO create_AccrualDistribs;
8687         x_return_status := FND_API.G_RET_STS_ERROR;
8688         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
8689         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
8690 
8691     WHEN OTHERS THEN
8692         ROLLBACK TO create_AccrualDistribs;
8693         x_return_status := FND_API.G_RET_STS_ERROR;
8694         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
8695         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
8696 
8697 END create_AccrualDistribs;
8698 
8699 /*========================================================================
8700  | PRIVATE PROCEDURE calc_accrued_interest
8701  |
8702  | DESCRIPTION
8703  |      This procedure calculates accrual interest.
8704  |
8705  | CALLED FROM PROCEDURES/FUNCTIONS (local to this package body)
8706  |
8707  | CALLS PROCEDURES/FUNCTIONS (local to this package body)
8708  |      LogMessage
8709  |
8710  | PARAMETERS
8711  |       p_loan_id     IN              Input Loan Id
8712  |       p_accrual_date       IN       Accrual date
8713  |	 x_accrued_interest		IN  Accrued Interest
8714  |       x_accrued_interest_det          OUT NOCOPY     Accrued Interest details
8715  |
8716  | KNOWN ISSUES
8717  |      None
8718  |
8719  | NOTES
8720  |      Any interesting aspect of the code in the package body which needs
8721  |      to be stated.
8722  |
8723  | MODIFICATION HISTORY
8724  | Date                  Author            Description of Changes
8725  | 15-OCT-2010           MBOLLI             Created
8726  |
8727  *=======================================================================*/
8728 -- This procedure calculates accrued interest from lastBill dueDate to the input accrual date
8729 PROCEDURE calc_accrued_interest(p_loan_id IN VARCHAR2
8730                                ,p_accrual_date 		    IN DATE
8731                                ,x_accrued_interest 	    OUT NOCOPY NUMBER
8732 			       ,x_statement		     IN    OUT NOCOPY CLOB)
8733 
8734 IS
8735 
8736 	l_api_name	   VARCHAR2(30);
8737 	l_loan_details        LNS_FINANCIALS.LOAN_DETAILS_REC;
8738 	l_rate_tbl            LNS_FINANCIALS.RATE_SCHEDULE_TBL;
8739 	l_annualized_rate     NUMBER;
8740 	l_accr_norm_interest  NUMBER;
8741 	l_last_int_billed_date DATE;
8742 	l_current_phase       VARCHAR2(30);
8743 
8744 	l_accrued_interest	       NUMBER;
8745 	l_add_prin_interest            NUMBER;
8746     	l_add_int_interest              NUMBER;
8747 	l_penal_prin_interest          NUMBER;
8748 	l_penal_int_interest            NUMBER;
8749 	l_penal_interest                 NUMBER;
8750 
8751 
8752 	l_accr_int_detail_str  		VARCHAR2(3000);
8753 	l_accr_norm_int_detail_str  VARCHAR2(2000);
8754 	l_add_prin_int_detail_str     VARCHAR2(2000);
8755 	l_add_int_int_detail_str       VARCHAR2(2000);
8756 	l_penal_prin_int_detail_str   VARCHAR2(2000);
8757 	l_penal_int_int_detail_str     VARCHAR2(2000);
8758 	l_penal_int_detail_str          VARCHAR2(2000);
8759 
8760 	l_last_inst_number		NUMBER;
8761 	l_new_line				VARCHAR2(1);
8762 
8763 
8764     -- this cursor will get the last time the loan interest was billed and if not then loan start date
8765     CURSOR c_last_interest_billed(c_loan_id NUMBER, c_last_inst_no NUMBER) is
8766     SELECT trunc(decode(c_last_inst_no,
8767           0,
8768           decode(lnh.current_phase, 'TERM', lnh.loan_start_date, 'OPEN', lnh.open_loan_start_date),
8769 	  -1,
8770 	  decode(lnh.current_phase, 'TERM', lnh.loan_start_date, 'OPEN', lnh.open_loan_start_date),
8771           (select max(due_date)
8772             from lns_amortization_scheds
8773             where reversed_flag = 'N'
8774               and loan_id = lnh.loan_id
8775               and phase = lnh.current_phase)))
8776     FROM lns_loan_headers lnh
8777     WHERE lnh.loan_id = c_loan_id;
8778 
8779 
8780      CURSOR c_loan_info(c_loan_id number) is
8781      SELECT nvl(h.current_phase, 'TERM')
8782      FROM lns_loan_headers h
8783      WHERE h.loan_id = c_loan_id;
8784 
8785 
8786 BEGIN
8787     -- Standard Start of API savepoint
8788     SAVEPOINT shiftLoan;
8789     l_api_name           := 'calc_accrued_interest';
8790 
8791     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
8792     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - p_loan_id ' || p_loan_id);
8793     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - p_accrual_date ' || p_accrual_date);
8794 
8795 
8796   -- Initialization
8797 
8798     l_new_line := '
8799 ';
8800 
8801     l_accr_norm_interest := 0;
8802     l_add_prin_interest := 0;
8803     l_add_int_interest := 0;
8804     l_penal_prin_interest := 0;
8805     l_penal_int_interest := 0;
8806     l_penal_interest := 0;
8807     l_accrued_interest := 0;
8808 
8809     l_accr_int_detail_str := null;
8810     l_accr_norm_int_detail_str := null;
8811     l_add_prin_int_detail_str := null;
8812     l_add_int_int_detail_str := null;
8813     l_penal_prin_int_detail_str := null;
8814     l_penal_int_int_detail_str := null;
8815     l_penal_int_detail_str := null;
8816 
8817 
8818 
8819 
8820 
8821     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - getting current phase');
8822     open c_loan_info(p_loan_id);
8823     fetch c_loan_info into l_current_phase;
8824     close c_loan_info;
8825     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - current phase ' || l_current_phase);
8826 
8827     l_loan_details  := lns_financials.getLoanDetails(p_loan_id        => p_loan_id
8828                                                     ,p_based_on_terms => 'CURRENT'
8829                                                     ,p_phase          => l_current_phase);
8830 
8831     l_rate_tbl      := lns_financials.getRateSchedule(p_loan_id, l_current_phase);
8832     l_last_inst_number := LNS_BILLING_UTIL_PUB.LAST_PAYMENT_NUMBER_EXT_2(p_loan_id);
8833 
8834     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - l_last_inst_number: ' || l_last_inst_number);
8835 
8836     OPEN c_last_interest_billed(p_loan_id, l_last_inst_number);
8837     FETCH c_last_interest_billed INTO l_last_int_billed_date;
8838     CLOSE c_last_interest_billed;
8839 
8840     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - l_last_int_accrued_date: ' || l_last_int_billed_date);
8841 
8842     if l_rate_tbl.count = 1 then
8843         l_annualized_rate := l_rate_tbl(1).annual_rate;
8844     else
8845         l_annualized_rate := lns_financials.getWeightedRate(p_loan_details => l_loan_details
8846                                                         ,p_start_date   => l_last_int_billed_date
8847                                                         ,p_end_date     => p_accrual_date
8848                                                         ,p_rate_tbl     => l_rate_tbl);
8849     end if;
8850     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - l_annualized_rate: ' || l_annualized_rate);
8851 
8852 
8853     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || ': Calculating accrued interest...');
8854     LNS_FINANCIALS.CALC_NORM_INTEREST(p_loan_id => p_loan_id,
8855                         p_calc_method => l_loan_details.CALCULATION_METHOD,
8856                         p_period_start_date => l_last_int_billed_date,
8857                         p_period_end_date => p_accrual_date,
8858                         p_interest_rate => l_annualized_rate,
8859                         p_day_count_method => l_loan_details.day_count_method,
8860                         p_payment_freq => l_loan_details.PAYMENT_FREQUENCY,
8861                         p_compound_freq => l_loan_details.INTEREST_COMPOUNDING_FREQ,
8862                         p_adj_amount => 0,
8863                         x_norm_interest => l_accr_norm_interest,
8864                         x_norm_int_details => l_accr_norm_int_detail_str);
8865 
8866 			l_accr_norm_interest  := round(l_accr_norm_interest, l_loan_details.currency_precision);
8867 
8868    logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - l_accr_norm_interest: ' || l_accr_norm_interest);
8869 
8870    IF (l_last_inst_number >= 0) THEN
8871 
8872 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || ': Calculating additional interest on unpaid principal...');
8873 			-- calculate additional interest on unpaid principal
8874 	LNS_FINANCIALS.CALC_ADD_INTEREST(p_loan_id => p_loan_id,
8875 					p_calc_method => l_loan_details.CALCULATION_METHOD,
8876 					p_period_start_date => l_last_int_billed_date,
8877 					p_period_end_date => p_accrual_date,
8878 					p_interest_rate => l_annualized_rate,
8879 					p_day_count_method =>  l_loan_details.day_count_method,
8880 					p_payment_freq => l_loan_details.PAYMENT_FREQUENCY,
8881 					p_compound_freq =>  l_loan_details.INTEREST_COMPOUNDING_FREQ,
8882 					p_prev_grace_end_date => l_last_int_billed_date,
8883 					p_penal_int_rate => l_loan_details.PENAL_INT_RATE,
8884 					p_grace_start_date =>l_last_int_billed_date,
8885 					p_grace_end_date => (l_last_int_billed_date + l_loan_details.PENAL_INT_GRACE_DAYS),
8886 					p_target => 'UNPAID_PRIN',
8887 					x_add_interest => l_add_prin_interest,
8888 					x_penal_interest => l_penal_prin_interest,
8889 					x_add_int_details => l_add_prin_int_detail_str,
8890 					x_penal_int_details => l_penal_prin_int_detail_str);
8891 
8892 	l_add_prin_interest  := round(l_add_prin_interest, l_loan_details.currency_precision);
8893 	logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - l_add_prin_interest: ' || l_add_prin_interest);
8894 
8895 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || ': Calculating additional interest on unpaid interest...');
8896 			-- calculate additional interest on unpaid interest
8897 	LNS_FINANCIALS.CALC_ADD_INTEREST(p_loan_id => p_loan_id,
8898 					p_calc_method =>  l_loan_details.CALCULATION_METHOD,
8899 					p_period_start_date => l_last_int_billed_date,
8900 					p_period_end_date => p_accrual_date,
8901 					p_interest_rate => l_annualized_rate,
8902 					p_day_count_method => l_loan_details.day_count_method,
8903 					p_payment_freq => l_loan_details.PAYMENT_FREQUENCY,
8904 					p_compound_freq => l_loan_details.INTEREST_COMPOUNDING_FREQ,
8905 					p_penal_int_rate => l_loan_details.PENAL_INT_RATE,
8906 					p_prev_grace_end_date => l_last_int_billed_date,
8907 					p_grace_start_date => l_last_int_billed_date,
8908 					p_grace_end_date => (l_last_int_billed_date + l_loan_details.PENAL_INT_GRACE_DAYS),
8909 					p_target => 'UNPAID_INT',
8910 					x_add_interest => l_add_int_interest,
8911 					x_penal_interest => l_penal_int_interest,
8912 					x_add_int_details => l_add_int_int_detail_str,
8913 					x_penal_int_details => l_penal_int_int_detail_str);
8914 
8915 
8916 	l_add_int_interest  := round(l_add_int_interest, l_loan_details.currency_precision);
8917 	logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - l_add_int_interest: ' || l_add_int_interest);
8918 
8919 	l_penal_interest := round(l_penal_prin_interest + l_penal_int_interest, l_loan_details.currency_precision);
8920 
8921 	logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - l_penal_interest: ' || l_penal_interest);
8922 
8923 	if l_penal_prin_int_detail_str is not null and l_penal_int_int_detail_str is not null then
8924 		l_penal_int_detail_str := l_penal_prin_int_detail_str || ' +<br>' || l_penal_int_int_detail_str;
8925 	else
8926 		l_penal_int_detail_str := l_penal_prin_int_detail_str || l_penal_int_int_detail_str;
8927 	end if;
8928    END IF;  -- if l_last_inst_number >= 0
8929 
8930    l_accrued_interest := l_accr_norm_interest + l_add_prin_interest + l_add_int_interest + l_penal_interest;
8931 
8932    logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - Total Accrued Interest is: ' || l_accrued_interest);
8933 
8934    l_accr_norm_int_detail_str := REPLACE(l_accr_norm_int_detail_str,'<br>',' ');
8935 
8936    l_accr_int_detail_str := 'Normal Interest = '||l_accr_norm_int_detail_str;
8937 
8938 
8939    IF l_add_prin_int_detail_str IS NOT NULL THEN
8940    	l_add_prin_int_detail_str := REPLACE(l_add_prin_int_detail_str,'<br>',' ');
8941 	l_accr_int_detail_str := l_accr_int_detail_str ||' +<br> Unpaid Principal Int = '|| l_add_prin_int_detail_str;
8942    END IF;
8943 
8944    IF l_add_int_int_detail_str IS NOT NULL THEN
8945    	l_add_int_int_detail_str := REPLACE(l_add_int_int_detail_str,'<br>',' ');
8946 	l_accr_int_detail_str := l_accr_int_detail_str ||' +<br> Unpaid Interest Int = '|| l_add_int_int_detail_str;
8947    END IF;
8948 
8949    IF l_penal_int_detail_str IS NOT NULL THEN
8950    	l_penal_int_detail_str := REPLACE(l_penal_int_detail_str,'<br>',' ');
8951 	l_accr_int_detail_str := l_accr_int_detail_str ||' +<br> Penal Interest = '|| l_penal_int_detail_str;
8952    END IF;
8953 
8954    l_accr_int_detail_str := REPLACE(l_accr_int_detail_str,'<br>',' ');
8955 
8956    logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - Total Interest String : ' || l_accr_int_detail_str);
8957 
8958     x_statement := x_statement || l_new_line || '<ACCRUED_NORMAL_INTEREST>' || l_accr_norm_interest || '</ACCRUED_NORMAL_INTEREST>';
8959 
8960     x_statement := x_statement || l_new_line || '<ACCRUED_ADDITIONAL_PRINCIPAL_INTEREST>' || l_add_prin_interest || '</ACCRUED_ADDITIONAL_PRINCIPAL_INTEREST>';
8961 
8962     x_statement := x_statement || l_new_line || '<ACCRUED_ADDITIONAL_INTEREST_INTEREST>' || l_add_int_interest || '</ACCRUED_ADDITIONAL_INTEREST_INTEREST>';
8963 
8964     x_statement := x_statement || l_new_line || '<ACCRUED_PENAL_INTEREST>' || l_penal_interest || '</ACCRUED_PENAL_INTEREST>';
8965 
8966    -- x_statement := x_statement || l_new_line || '<INTEREST_ACCRUED>' || l_accrued_interest || '</INTEREST_ACCRUED>';
8967 
8968     x_statement := x_statement || l_new_line || '<ACCRUED_NORMAL_INTEREST_DETAILS>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_accr_norm_int_detail_str) || '</ACCRUED_NORMAL_INTEREST_DETAILS>';
8969 
8970     x_statement := x_statement || l_new_line || '<ACCRUED_ADDITIONAL_PRINCIPAL_INTEREST>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_add_prin_int_detail_str) || '</ACCRUED_ADDITIONAL_PRINCIPAL_INTEREST>';
8971 
8972     x_statement := x_statement || l_new_line || '<ACCRUED_ADDITIONAL_INTEREST_INTEREST>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_add_int_int_detail_str) || '</ACCRUED_ADDITIONAL_INTEREST_INTEREST>';
8973 
8974     x_statement := x_statement || l_new_line || '<ACCRUED_PENAL_INTEREST_DETAILS>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_penal_int_detail_str) || '</ACCRUED_PENAL_INTEREST_DETAILS>';
8975 
8976     x_statement := x_statement || l_new_line || '<INTEREST_ACCRUED_DETAILS>' || LNS_REP_UTILS.REPLACE_SPECIAL_CHARS(l_accr_int_detail_str) || '</INTEREST_ACCRUED_DETAILS>';
8977 
8978 
8979 
8980 
8981    x_accrued_interest := l_accrued_interest;
8982   -- x_accrued_interest_det := l_accr_int_detail_str;
8983 
8984    logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
8985 
8986 END calc_accrued_interest;
8987 
8988 PROCEDURE do_int_accrual_reversal(p_api_version           IN NUMBER
8989 			                               ,p_init_msg_list         	IN  VARCHAR2
8990 			                               ,p_commit                	IN  VARCHAR2
8991 			                               ,p_loan_id               	IN  NUMBER
8992 						       ,p_period_name		IN  VARCHAR2
8993                                      		       ,p_accrual_date          IN  DATE
8994 						       ,p_accounting_mode	IN  VARCHAR2
8995 						       ,x_statement_xml       IN   OUT NOCOPY  CLOB
8996 			                               ,x_return_status         OUT NOCOPY VARCHAR2
8997 			                               ,x_msg_count            OUT NOCOPY NUMBER
8998 			                               ,x_msg_data              OUT NOCOPY VARCHAR2)
8999  IS
9000 
9001     l_api_name                 varchar2(30);
9002     l_msg_count                NUMBER;
9003     l_msg_data                 VARCHAR2(2000);
9004     l_return_Status            VARCHAR2(1);
9005     l_last_accrued_date     DATE;
9006     l_accrual_date             DATE;
9007     l_accrued_int_amount  NUMBER;
9008     l_accr_int_amount	      VARCHAR2(50);
9009     l_accrued_int_detail_str	VARCHAR2(2000);
9010     l_loan_num                 VARCHAR2(60);
9011     l_currency		      VARCHAR2(15);
9012     l_event_id                   NUMBER;
9013     l_new_line                   VARCHAR2(1);
9014     l_accr_dist_count	      NUMBER;
9015     l_borrower		      VARCHAR2(360);
9016     l_account_name	      VARCHAR2(30);
9017     l_cc_id			      NUMBER;
9018     l_account_type	      VARCHAR2(30);
9019     l_distribution_percent   NUMBER;
9020     l_distribution_amount   NUMBER;
9021     l_distribution_type	      VARCHAR2(30);
9022     l_disable_int_accrual_flag  VARCHAR2(1);
9023     l_org_name			VARCHAR2(240);
9024     l_ledger_name		VARCHAR2(30);
9025 
9026     l_retcode		      NUMBER;
9027     l_accounting_batch_id	NUMBER;
9028     l_error_counter		NUMBER;
9029     l_loan_number		VARCHAR2(30);
9030     l_errbuf                   	VARCHAR2(10000);
9031     l_entity_code                 VARCHAR2(30);
9032     l_error_message            VARCHAR2(2000);
9033 
9034 
9035 
9036 
9037 /* query for loan number */
9038     CURSOR loan_cur(C_LOAN_ID number) IS
9039         SELECT
9040 		loan.loan_number, nvl(loan.disable_int_accrual_flag, 'N'), ou.name, gl.name
9041         FROM
9042 		lns_loan_headers_all loan, lns_system_options_all lsysopt, hr_operating_units ou, gl_ledgers gl
9043         WHERE loan.loan_id = C_LOAN_ID
9044           AND loan.org_id = lsysopt.org_id
9045           AND lsysopt.set_of_books_id = gl.ledger_id
9046           AND loan.org_id = ou.organization_id;
9047 
9048 
9049    -- CURSOR to retrieve the last accrual accounted date for the loan
9050    	CURSOR cur_last_accrual_date(c_loan_id NUMBER)   IS
9051     	SELECT
9052     		max(ldist.accrual_date)
9053     	FROM
9054     		lns_distributions ldist
9055     	WHERE ldist.loan_id = c_loan_id
9056 	     AND ldist.distribution_type = 'ACCRUAL'
9057   	     AND ldist. activity = 'INTEREST_ACCRUAL'
9058 	     AND ldist.accrual_completed_flag = 'Y';
9059 
9060 
9061     CURSOR cur_get_accr_dist_det(c_loan_id NUMBER, c_accrual_date DATE) IS
9062     SELECT
9063  	 account_name
9064 	,code_combination_id
9065 	,account_type
9066 	,distribution_percent
9067 	,distribution_amount
9068 	,distribution_type
9069     FROM
9070     	lns_distributions ldist
9071     WHERE ldist.loan_id = c_loan_id
9072          AND ldist.accrual_date = c_accrual_date
9073 	 AND ldist.distribution_type = 'ACCRUAL'
9074   	 AND ldist. activity = 'INTEREST_ACCRUAL'
9075     ORDER BY ldist.account_type;
9076 
9077   -- cursor to get accounting errors
9078     CURSOR cur_acc_errors(c_event_id NUMBER)   IS
9079     SELECT xlt.transaction_number, xlt.entity_code, err.encoded_msg
9080     FROM xla_accounting_errors err
9081           ,xla_transaction_entities xlt
9082     WHERE xlt.application_id = 206
9083       AND xlt.entity_id = err.entity_id
9084       AND err.event_id = C_EVENT_ID;
9085 
9086     CURSOR c_get_chart_acc_id(c_loan_id NUMBER) is
9087     SELECT sb.chart_of_accounts_id
9088 	FROM lns_loan_headers lhdr,
9089 	  lns_system_options so,
9090 	  gl_ledgers sb,
9091 	  fnd_currencies fndc
9092 	WHERE lhdr.loan_id = c_loan_id
9093 	     AND lhdr.org_id = so.org_id
9094 	     AND sb.ledger_id   = so.set_of_books_id
9095 	     AND sb.currency_code = fndc.currency_code;
9096 
9097 
9098    -- Retrieves the closing status of the accrual period for the given loan
9099     CURSOR cur_gl_period_status(C_LOAN_ID Number, C_PERIOD_NAME Varchar2) IS
9100     SELECT
9101   	glps.closing_status
9102     FROM
9103   	GL_PERIOD_STATUSES glps, LNS_SYSTEM_OPTIONS sysopt, LNS_LOAN_HEADERS lhdr
9104     WHERE lhdr.loan_id = C_LOAN_ID
9105       AND lhdr.org_id =  sysopt.org_id
9106       AND sysopt.set_of_books_id = glps.ledger_id
9107       AND glps.application_id = 101
9108       AND glps.period_name = C_PERIOD_NAME;
9109 
9110    --    Retrieve the loans's sla event and its status of drafted accruals
9111 	CURSOR cur_get_draft_events(c_loan_id NUMBER)  IS
9112 	SELECT distinct ldist.event_id, evnt.event_status_code
9113 	FROM lns_distributions ldist, xla_events evnt
9114 	WHERE ldist.event_id = evnt.event_id
9115 	AND ldist.loan_id = C_LOAN_ID
9116 	AND ldist.activity = 'INTEREST_ACCRUAL'
9117 	AND ldist.distribution_type = 'ACCRUAL'
9118 	AND ldist.accrual_completed_flag <> 'Y';
9119 
9120 
9121     l_chart_of_accounts_id	number;
9122     l_original_segments		FND_FLEX_EXT.SEGMENTARRAY;
9123     l_num_segments		number;
9124     l_code_combination_value	varchar2(4000);
9125     l_period_closing_status          Varchar2(1);
9126     l_exist_event_id			NUMBER;
9127     l_event_status_code		VARCHAR2(1);
9128 
9129 BEGIN
9130 
9131      l_api_name   := 'do_int_accrual_reversal';
9132      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, l_api_name || ' - BEGIN');
9133 
9134      SAVEPOINT do_int_accrual_reversal;
9135 
9136      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
9137      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_period_name = ' || p_period_name);
9138      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_accrual_date = ' || p_accrual_date);
9139      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_accounting_mode = ' || p_accounting_mode);
9140 
9141 
9142 
9143 
9144      -- Initialize message list IF p_init_msg_list is set to TRUE.
9145      IF FND_API.to_Boolean( p_init_msg_list ) THEN
9146          FND_MSG_PUB.initialize;
9147      END IF;
9148 
9149      -- Initialize API return status to SUCCESS
9150      x_return_status := FND_API.G_RET_STS_SUCCESS;
9151 
9152 
9153     l_new_line := '
9154 ';
9155 
9156     l_accr_dist_count := 0;
9157 
9158          -- START OF BODY OF API
9159 
9160 
9161     dbms_lob.createtemporary(X_STATEMENT_XML, FALSE, DBMS_LOB.CALL);
9162     dbms_lob.open(X_STATEMENT_XML, dbms_lob.lob_readwrite);
9163 
9164     x_statement_xml := x_statement_xml || l_new_line;
9165 
9166     OPEN loan_cur(p_loan_id);
9167     FETCH loan_cur INTO l_loan_num, l_disable_int_accrual_flag, l_org_name, l_ledger_name;
9168     CLOSE loan_cur;
9169 
9170     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Loan Number is '||l_loan_num);
9171     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_disable_int_accrual_flag is '||l_disable_int_accrual_flag);
9172     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_org_name is '||l_org_name);
9173     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_ledger_name is '||l_ledger_name);
9174 
9175     x_statement_xml := x_statement_xml || l_new_line || '<ORGANIZATION_NAME>' || l_org_name || '</ORGANIZATION_NAME>';
9176     x_statement_xml := x_statement_xml || l_new_line || '<LEDGER_NAME>' || l_ledger_name || '</LEDGER_NAME>';
9177 
9178 
9179 
9180     OPEN cur_last_accrual_date(p_loan_id);
9181     FETCH cur_last_accrual_date INTO l_last_accrued_date;
9182     CLOSE cur_last_accrual_date;
9183 
9184     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Last Accrued Date for this loan is: '||l_last_accrued_date);
9185 
9186     x_statement_xml := x_statement_xml || l_new_line || '<LAST_ACCRUAL_DATE>' || l_last_accrued_date || '</LAST_ACCRUAL_DATE>';
9187 
9188     IF l_disable_int_accrual_flag = 'Y' THEN
9189 		FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCRUAL_DISABLED');
9190 		FND_MESSAGE.SET_TOKEN('LOAN_NUMBER', l_loan_num);
9191 		FND_MSG_PUB.Add;
9192 		LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
9193 
9194 		RAISE FND_API.G_EXC_ERROR;
9195     END IF;
9196 
9197     IF (l_last_accrued_date IS NOT NULL  AND p_accrual_date <= l_last_accrued_date) THEN
9198 
9199 	FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCRUED_ALREADY');
9200 	FND_MESSAGE.SET_TOKEN('LOAN_NUMBER', l_loan_num);
9201 	FND_MESSAGE.SET_TOKEN('LAST_ACCRUAL_DATE', l_last_accrued_date);
9202 	FND_MSG_PUB.Add;
9203 	LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
9204 
9205 	RAISE FND_API.G_EXC_ERROR;
9206     END IF;
9207 
9208 
9209 -- 0. Calculate the accrued interest
9210     l_accrual_date := p_accrual_date + 1;       -- Accrual Int should include the int for the accrual_date also
9211 
9212     logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_accrual_date = ' || l_accrual_date);
9213 
9214     BEGIN
9215     		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Invoke the API calc_accrued_interest');
9216     		calc_accrued_interest(p_loan_id => p_loan_id
9217                                         ,p_accrual_date => l_accrual_date
9218                                         ,x_accrued_interest => l_accrued_int_amount
9219 					,x_statement => x_statement_xml);
9220     EXCEPTION
9221     		WHEN OTHERS THEN
9222 		RAISE FND_API.G_EXC_ERROR;
9223     END;
9224 
9225      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_accrued_int_amount = ' || l_accrued_int_amount);
9226   --   logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_accrued_int_detail_str = ' || l_accrued_int_detail_str);
9227      --l_accrued_int_detail_str := REPLACE(l_accrued_int_detail_str,'<br>',' ');
9228      --logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_accrued_int_detail_str = ' || l_accrued_int_detail_str);
9229 
9230 
9231 
9232 	logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Delete existed accrual rows on this accrual date if they are not Final accrued ');
9233 
9234      -- Delete the SLA event if it is NOT Final or Related Error
9235 
9236 	OPEN cur_get_draft_events(p_loan_id);
9237 	LOOP
9238 	FETCH cur_get_draft_events INTO l_exist_event_id, l_event_status_code;
9239 	EXIT WHEN cur_get_draft_events%NOTFOUND;
9240 
9241 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_exist_event_id = ' || l_exist_event_id);
9242 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_event_status_code = ' || l_event_status_code);
9243 
9244 	IF l_event_status_code in ('P', 'R') THEN
9245 		FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCRUAL_FINAL_ACCOUNTED');
9246 		FND_MESSAGE.SET_TOKEN('LOAN_NUMBER', l_loan_num);
9247 	--	FND_MESSAGE.SET_TOKEN('LAST_ACCRUAL_DATE', l_last_accrued_date);
9248 		FND_MSG_PUB.Add;
9249 		LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
9250 
9251 		RAISE FND_API.G_EXC_ERROR;
9252 	ELSE
9253 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Deleting the event_id '||l_exist_event_id);
9254 	  	LNS_XLA_EVENTS.delete_event(p_loan_id => P_loan_id
9255 		              ,p_disb_header_id => -1
9256                       ,p_loan_amount_adj_id => -1
9257 		              ,p_loan_line_id  => -1
9258                       ,p_event_id =>  l_exist_event_id
9259                       ,p_init_msg_list => 'F'
9260                       ,p_commit  =>  'F'
9261                       ,x_return_status => l_return_status
9262                       ,x_msg_count   => l_msg_count
9263                       ,x_msg_data   =>  l_msg_data);
9264 
9265 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_return_status = ' || l_return_status);
9266 		IF l_return_status <> 'S' THEN
9267 			LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, 'Deleting event_id failed');
9268 
9269 			RAISE FND_API.G_EXC_ERROR;
9270 		END IF;
9271 
9272 	END IF;
9273 
9274 	END LOOP;
9275 	CLOSE cur_get_draft_events;
9276 
9277 	-- l_last_accrued_date is the last accrued date for that loan which is Final Accounted in SLA
9278 	-- So delete all the above distributions above that date
9279 	DELETE FROM lns_distributions ldist
9280 	WHERE ldist.loan_id = P_LOAN_ID
9281 	     AND ldist.activity = 'INTEREST_ACCRUAL'
9282 	     AND ldist.distribution_type = 'ACCRUAL'
9283 	     AND ldist.accrual_completed_flag <> 'Y'
9284 	     AND NOT EXISTS
9285 	     	(SELECT 'X' FROM xla_events evnt
9286 			WHERE evnt.event_id = ldist.event_id
9287 			     AND evnt.event_status_code in  ('P', 'R'));
9288 
9289 
9290         logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Deleted '||SQL%ROWCOUNT||' accrual rows succesfully');
9291 
9292 	-- 1. Create distributions for the Interest Invoice with the accruedInterest calculation
9293 
9294 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Invoking create_AccrualDistribs');
9295 	create_AccrualDistribs(p_api_version  => 1
9296 							,p_init_msg_list    => 'T'
9297 							,p_commit           => 'T'
9298 							,p_loan_id          => p_loan_id
9299 							,p_period_name	 => p_period_name
9300 							,p_accrual_date     => p_accrual_date
9301 							,p_accrued_amount   => l_accrued_int_amount
9302 							,p_activity_type    => 'INTEREST_ACCRUAL'
9303 							,p_accounting_mode => p_accounting_mode
9304 							,x_return_status    => l_return_Status
9305 							,x_msg_count        => l_msg_count
9306 							,x_msg_data         => l_msg_data);
9307 
9308 	logMessage(FND_LOG.level_statement, G_PKG_NAME, 'l_return_status = ' || l_return_status);
9309 	if l_return_status <> 'S' then
9310 		RAISE FND_API.G_EXC_ERROR;
9311 	end if;
9312 
9313 
9314 	-- 2. Generate an Accrual Event
9315 
9316 
9317 	IF (p_accounting_mode = 'FINAL') THEN
9318 
9319 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Generating Accrual Event');
9320 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling LNS_XLA_EVENTS.create_event...');
9321 
9322 		LNS_XLA_EVENTS.create_event(p_loan_id          => p_loan_id
9323 					,p_disb_header_id  => -1
9324 					,p_loan_amount_adj_id => -1
9325 					,p_event_type_code => 'LOAN_ACCRUAL'
9326 					,p_event_date      => p_accrual_date
9327 					,p_event_status    => 'U'
9328 					,p_init_msg_list   => fnd_api.g_false
9329 					,p_commit          => fnd_api.g_false
9330 					,p_bc_flag         => 'N'
9331 					,x_event_id        => l_event_id
9332 					,x_return_status   => l_return_status
9333 					,x_msg_count       => l_msg_count
9334 					,x_msg_data        => l_msg_data);
9335 
9336 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'x_return_status = ' || l_return_status);
9337 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'x_event_id ' || l_event_id);
9338 
9339 		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
9340 			FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCOUNTING_EVENT_ERROR');
9341 			FND_MSG_PUB.ADD;
9342 			logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
9343 			RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
9344 		END IF;
9345 
9346 	--3. stamp the eventID onto the lns_distributions table
9347 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'stamping eventID on lns_distributions');
9348 
9349 
9350 
9351 		update lns_distributions
9352 		set event_id = l_event_id
9353 		,last_update_date = sysdate
9354 		where distribution_type = 'ACCRUAL'
9355 		and loan_id             = p_loan_id
9356 		and accrual_date        = p_accrual_date
9357 		--and accrual_period     = NVL(p_period_name, accrual_period)
9358 		and activity = 'INTEREST_ACCRUAL';
9359 
9360 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Updated event_id succesfully for '||SQL%ROWCOUNT||' rows');
9361 
9362 	END IF;  -- END IF  accounting_mode = 'FINAL'
9363 
9364 	LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Retrieving accrual distribution records for XML output report');
9365 
9366 	OPEN c_get_chart_acc_id(p_loan_id);
9367 	FETCH c_get_chart_acc_id into l_chart_of_accounts_id;
9368 	CLOSE c_get_chart_acc_id;
9369 
9370 	logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Chart of Accounts id : '||l_chart_of_accounts_id);
9371 
9372 	x_statement_xml := x_statement_xml || l_new_line || '<ACCRUAL_DISTRIBUTIONS>';
9373 
9374 	OPEN cur_get_accr_dist_det(p_loan_id, p_accrual_date);
9375 	LOOP
9376 		FETCH cur_get_accr_dist_det
9377 			INTO
9378 				  l_account_name
9379 				, l_cc_id
9380 				, l_account_type
9381 				, l_distribution_percent
9382 				, l_distribution_amount
9383 				, l_distribution_type;
9384 		EXIT WHEN cur_get_accr_dist_det%NOTFOUND;
9385 
9386 		IF (NOT FND_FLEX_EXT.GET_SEGMENTS('SQLGL'
9387 					     ,'GL#'
9388 					     ,l_chart_of_accounts_id
9389 					     ,l_cc_id
9390 					     ,l_num_segments
9391 					     ,l_original_segments))  THEN
9392 			logMessage(FND_LOG.level_statement, G_PKG_NAME, 'ERROR getting code combination value');
9393 
9394 		ELSE
9395 			logMessage(FND_LOG.level_statement, G_PKG_NAME, 'Success getting code combination value');
9396 		END IF;
9397 
9398 		l_code_combination_value := '';
9399 		for n in 1..l_num_segments loop
9400 			if l_code_combination_value is null then
9401 				l_code_combination_value	:=	l_original_segments(n);
9402 			else
9403 				l_code_combination_value	:=	l_code_combination_value || '-' || l_original_segments(n);
9404 			end if;
9405 		end loop;
9406 
9407 
9408 		x_statement_xml := x_statement_xml || l_new_line || '<ACCRUAL_DISTRIBUTION>';
9409 		x_statement_xml := x_statement_xml || l_new_line || '<ACCOUNT_NAME>'|| l_account_name ||'</ACCOUNT_NAME>';
9410 		x_statement_xml := x_statement_xml || l_new_line || '<CODE_COMBINATION_ID>'|| l_code_combination_value || '</CODE_COMBINATION_ID>';
9411 		x_statement_xml := x_statement_xml || l_new_line || '<ACCOUNT_TYPE>'|| l_account_type ||'</ACCOUNT_TYPE>';
9412 		x_statement_xml := x_statement_xml || l_new_line || '<DISTRIBUTION_PERCENT>'|| l_distribution_percent ||'</DISTRIBUTION_PERCENT>';
9413 		x_statement_xml := x_statement_xml || l_new_line || '<DISTRIBUTION_AMOUNT>'|| l_distribution_amount ||'</DISTRIBUTION_AMOUNT>';
9414 		x_statement_xml := x_statement_xml || l_new_line || '<DISTRIBUTION_TYPE>'|| l_distribution_type ||'</DISTRIBUTION_TYPE>';
9415 		x_statement_xml := x_statement_xml || l_new_line || '</ACCRUAL_DISTRIBUTION>';
9416 
9417 	END LOOP;
9418 	    	x_statement_xml := x_statement_xml || l_new_line || '</ACCRUAL_DISTRIBUTIONS>';
9419 
9420 	CLOSE cur_get_accr_dist_det;
9421 
9422 
9423 
9424     -- Generate the statement
9425 
9426      BUILD_ACCRUAL_STMT(P_LOAN_ID => P_LOAN_ID
9427      			 ,P_PERIOD_NAME			=> P_PERIOD_NAME
9428                          ,P_ACCRUAL_DATE 		=> P_ACCRUAL_DATE
9429                          ,P_INT_ACCRUED  			=> nvl(l_accrued_int_amount, -1)
9430 			 ,P_RESULT				=> 'S'
9431 			 ,P_ERR_COUNT 			=> 0			-- No error messages
9432                          ,X_STATEMENT_XML 		=> x_statement_xml);
9433 
9434 
9435 	/*  Building clob */
9436     --DBMS_LOB.write(X_STATEMENT_XML, length(l_statement), 1, l_statement);
9437 
9438 
9439     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'p_commit is '||p_commit);
9440      IF FND_API.to_Boolean(p_commit)
9441      THEN
9442          COMMIT;
9443         logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || 'Commited');
9444      END IF;
9445 
9446      FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
9447      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
9448 
9449 EXCEPTION
9450 
9451     WHEN G_EXC_WARNING THEN
9452         ROLLBACK TO do_int_accrual_reversal;
9453         x_return_status := FND_API.G_RET_STS_ERROR;
9454         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
9455 	LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Rollbacked loan_id ' || P_LOAN_ID);
9456         g_cr_return_status := 'WARNING';
9457         /* building error statement */
9458        BUILD_ACCRUAL_STMT(P_LOAN_ID => P_LOAN_ID
9459      			 ,P_PERIOD_NAME			=> P_PERIOD_NAME
9460                          ,P_ACCRUAL_DATE 		=> P_ACCRUAL_DATE
9461                          ,P_INT_ACCRUED  			=> nvl(l_accrued_int_amount, 0)
9462 			 ,P_RESULT				=> 'W'
9463 			 ,P_ERR_COUNT 			=> x_msg_count
9464                          ,X_STATEMENT_XML 		=> X_STATEMENT_XML);
9465 
9466     WHEN FND_API.G_EXC_ERROR THEN
9467         ROLLBACK TO do_int_accrual_reversal;
9468         x_return_status := FND_API.G_RET_STS_ERROR;
9469         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
9470 	LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Rollbacked loan_id ' || P_LOAN_ID);
9471         g_cr_return_status := 'WARNING';
9472         /* building error statement */
9473        BUILD_ACCRUAL_STMT(P_LOAN_ID => P_LOAN_ID
9474      			 ,P_PERIOD_NAME			=> P_PERIOD_NAME
9475                          ,P_ACCRUAL_DATE 		=> P_ACCRUAL_DATE
9476                          ,P_INT_ACCRUED  			=> nvl(l_accrued_int_amount, 0)
9477 			 ,P_RESULT				=> 'E'
9478 			 ,P_ERR_COUNT 			=> x_msg_count
9479                          ,X_STATEMENT_XML 		=> X_STATEMENT_XML);
9480 
9481     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
9482         ROLLBACK TO do_int_accrual_reversal;
9483         x_return_status := FND_API.G_RET_STS_ERROR;
9484         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
9485         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
9486 	LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Rollbacked loan_id ' || P_LOAN_ID);
9487         g_cr_return_status := 'WARNING';
9488         /* building error statement */
9489         BUILD_ACCRUAL_STMT(P_LOAN_ID => P_LOAN_ID
9490      			 ,P_PERIOD_NAME			=> P_PERIOD_NAME
9491                          ,P_ACCRUAL_DATE 		=> P_ACCRUAL_DATE
9492                          ,P_INT_ACCRUED  			=> nvl(l_accrued_int_amount, 0)
9493 			 ,P_RESULT				=> 'E'
9494 			 ,P_ERR_COUNT 			=> x_msg_count
9495                          ,X_STATEMENT_XML 		=> X_STATEMENT_XML);
9496 
9497     WHEN OTHERS THEN
9498         ROLLBACK TO do_int_accrual_reversal;
9499         x_return_status := FND_API.G_RET_STS_ERROR;
9500         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
9501         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
9502 	LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Rollbacked loan_id ' || P_LOAN_ID);
9503         g_cr_return_status := 'WARNING';
9504         /* building error statement */
9505         BUILD_ACCRUAL_STMT(P_LOAN_ID => P_LOAN_ID
9506      			 ,P_PERIOD_NAME			=> P_PERIOD_NAME
9507                          ,P_ACCRUAL_DATE 		=> P_ACCRUAL_DATE
9508                          ,P_INT_ACCRUED  			=> nvl(l_accrued_int_amount, 0)
9509 			 ,P_RESULT				=> 'E'
9510 			 ,P_ERR_COUNT 			=> x_msg_count
9511                          ,X_STATEMENT_XML 		=> X_STATEMENT_XML);
9512 
9513 END do_int_accrual_reversal;
9514 
9515 /*========================================================================
9516  | PUBLIC PROCEDURE ACCRUE_LOANS_INTEREST
9517  |
9518  | DESCRIPTION
9519  |      This procedure process all available loans
9520  |
9521  | CALLED FROM PROCEDURES/FUNCTIONS (local to this package body)
9522  |      LNS_ACCRUAL_ACCOUNTING_CONCUR
9523  |
9524  | CALLS PROCEDURES/FUNCTIONS (local to this package body)
9525  |      LogMessage
9526  |
9527  | PARAMETERS
9528  |      P_API_VERSION		    IN          Standard in parameter
9529  |      P_INIT_MSG_LIST		  IN          Standard in parameter
9530  |      P_COMMIT			      IN          Standard in parameter
9531  |      P_VALIDATION_LEVEL	IN          Standard in parameter
9532  |      P_BORROWER_ID            IN          Inputs Borrower Id
9533  |	P_LEDGER_ID			IN	      Inputs Ledger id
9534  |	P_ORG_ID			IN	      Inputs Organization Id
9535  |      P_LOAN_ID			IN	      Inputs Loan Id
9536  |	P_PERIOD_NAME		IN	      Inputs period-name for which the periodend accrual
9537  |      P_ACCRUAL_DATE      IN          Inputs Accrual date
9538  |      P_MODE              IN          Inputs Draft or Final Mode
9539  |      X_RETURN_STATUS		  OUT NOCOPY  Standard out parameter
9540  |      X_MSG_COUNT			    OUT NOCOPY  Standard out parameter
9541  |      X_MSG_DATA	    	  OUT NOCOPY  Standard out parameter
9542  |
9543  | KNOWN ISSUES
9544  |      None
9545  |
9546  | NOTES
9547  |      Any interesting aspect of the code in the package body which needs
9548  |      to be stated.
9549  |
9550  | MODIFICATION HISTORY
9551  | Date                  Author            Description of Changes
9552  | 15-OCT-2010           MBOLLI            Created
9553  |
9554  *=======================================================================*/
9555 PROCEDURE ACCRUE_LOANS_INTEREST(
9556     P_API_VERSION		IN          NUMBER,
9557     P_INIT_MSG_LIST		IN          VARCHAR2,
9558     P_COMMIT			IN          VARCHAR2,
9559     P_VALIDATION_LEVEL	IN          NUMBER,
9560     P_BORROWER_ID       IN          NUMBER,
9561     P_LEDGER_ID		IN	     NUMBER,
9562     P_ORG_ID			IN	     NUMBER,
9563     P_LOAN_ID           	IN          NUMBER,
9564     P_PERIOD_NAME        IN	     VARCHAR2,
9565     P_ACCRUAL_DATE      IN         DATE,
9566     P_MODE            IN          VARCHAR2,
9567     X_RETURN_STATUS		OUT NOCOPY  VARCHAR2,
9568     X_MSG_COUNT			OUT NOCOPY  NUMBER,
9569     X_MSG_DATA	    	OUT NOCOPY  VARCHAR2)
9570 IS
9571 
9572 /*-----------------------------------------------------------------------+
9573  | Local Variable Declarations and initializations                       |
9574  +-----------------------------------------------------------------------*/
9575 
9576     l_api_name                      CONSTANT VARCHAR2(30) := 'ACCRUE_LOANS_INTEREST';
9577     l_api_version                   CONSTANT NUMBER := 1.0;
9578     l_return_status                 VARCHAR2(1);
9579     l_msg_count                     NUMBER;
9580     l_msg_data                      VARCHAR2(32767);
9581     l_org_id                        NUMBER;
9582     l_accrual_date                  DATE;
9583     l_new_line                      varchar2(1);
9584     l_error_statements_xml          clob;
9585     l_error_header                  varchar2(20);
9586     l_error_footer                  varchar2(20);
9587     l_success_header                varchar2(20);
9588     l_success_footer                varchar2(20);
9589     l_single_statement_xml          clob;
9590     l_Count					NUMBER;
9591     l_Count1				NUMBER;
9592     l_start					DATE;
9593     l_end					DATE;
9594     l_loan_id				NUMBER;
9595     l_borrower_id				NUMBER;
9596     l_ledger_id				NUMBER;
9597     l_gl_period_status			VARCHAR2(1);
9598     l_gl_period_name			gl_period_statuses.PERIOD_NAME%TYPE;
9599 
9600     l_loans_to_accrue_tbl		g_number_tbl;
9601 
9602     L_EXC_WARNING 		EXCEPTION;
9603     l_is_period_end			VARCHAR2(1);
9604 
9605 
9606 /*-----------------------------------------------------------------------+
9607  | Cursor Declarations                                                   |
9608  +-----------------------------------------------------------------------*/
9609 
9610     /* get all loans whose interest is going to accrue earlier to accrual_date */
9611     CURSOR cur_loans_to_accrue_int(c_accrual_date DATE, C_LOAN_ID NUMBER, C_BORROWER_ID NUMBER, C_ORG_ID NUMBER, C_LEDGER_ID NUMBER) IS
9612               SELECT
9613                 head.LOAN_ID
9614               FROM
9615                 LNS_LOAN_HEADERS head, LNS_SYSTEM_OPTIONS sysopt
9616               WHERE
9617 		          head.org_id = sysopt.org_id
9618 		  AND sysopt.set_of_books_id = nvl(C_LEDGER_ID, sysopt.set_of_books_id)
9619                   AND c_accrual_date >= NVL((select max(due_date) from LNS_AMORTIZATION_SCHEDS aschd
9620 		   						where aschd.loan_id = head.loan_id and aschd.reversed_flag = 'N')
9621 							 ,decode(head.current_phase, 'OPEN',head.open_loan_start_date, head.loan_start_date))
9622                    AND  head.loan_status in ('ACTIVE', 'DEFAULT', 'DELINQUENT')
9623                    AND  head.loan_id = NVL(C_LOAN_ID, head.loan_id)
9624                    AND  head.PRIMARY_BORROWER_ID = nvl(C_BORROWER_ID, head.PRIMARY_BORROWER_ID)
9625 		   AND  head.org_id = nvl(C_ORG_ID, head.org_id)
9626 		   AND  NVL(head.current_phase, 'TERM') = 'TERM'
9627               ORDER BY head.LOAN_ID;
9628 
9629 
9630     CURSOR cur_gl_period_status(C_ACCRUAL_DATE date, C_LEDGER_ID Number) IS
9631     SELECT
9632   	glps.period_name, glps.closing_status
9633     FROM
9634   	GL_PERIOD_STATUSES glps
9635     WHERE glps.start_date <= C_ACCRUAL_DATE
9636          AND glps.end_date >= C_ACCRUAL_DATE
9637          AND glps.ledger_id = C_LEDGER_ID
9638          AND glps.application_id = 101;
9639 
9640     CURSOR  cur_gl_period_last_date(c_period_name VARCHAR2, c_ledger_id NUMBER)  IS
9641     SELECT
9642 	to_char(glpstat.end_date,'YYYY-MM-DD')
9643     FROM
9644 	gl_period_statuses glpstat
9645     WHERE
9646     	glpstat.application_id =  101
9647         AND glpstat.set_of_books_id = c_ledger_id
9648         AND glpstat.period_name = c_period_name
9649         AND glpstat.adjustment_period_flag = 'N';
9650 
9651 
9652 
9653 BEGIN
9654 
9655     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' +');
9656 
9657     -- Standard start of API savepoint
9658     SAVEPOINT ACCRUE_LOANS_INTEREST_PVT;
9659     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Savepoint is established');
9660 
9661     -- Standard call to check for call compatibility
9662     IF NOT FND_API.Compatible_API_Call(l_api_version, p_api_version, l_api_name, G_PKG_NAME) THEN
9663         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
9664     END IF;
9665 
9666     -- Initialize message list if p_init_msg_list is set to TRUE
9667     IF FND_API.To_Boolean(p_init_msg_list) THEN
9668       FND_MSG_PUB.initialize;
9669     END IF;
9670 
9671     -- Initialize API return status to success
9672     l_return_status := FND_API.G_RET_STS_SUCCESS;
9673     g_passed_loan_cnt := 0;
9674     g_failed_loan_cnt := 0;
9675 
9676     -- START OF BODY OF API
9677 
9678     /* init all statements clob */
9679     dbms_lob.createtemporary(g_last_all_statements, FALSE, DBMS_LOB.CALL);
9680     dbms_lob.open(g_last_all_statements, dbms_lob.lob_readwrite);
9681 
9682     dbms_lob.createtemporary(g_cp_statements, FALSE, DBMS_LOB.CALL);
9683     dbms_lob.open(g_cp_statements, dbms_lob.lob_readwrite);
9684 
9685     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Passed input parameters:');
9686     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_BORROWER_ID: ' || P_BORROWER_ID);
9687     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_LEDGER_ID: ' || P_LEDGER_ID);
9688     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_ORG_ID: ' || P_ORG_ID);
9689     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_LOAN_ID: ' || P_LOAN_ID);
9690     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_PERIOD_NAME: ' || P_PERIOD_NAME);
9691     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_ACCRUAL_DATE: ' || P_ACCRUAL_DATE);
9692     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'P_MODE: ' || P_MODE);
9693 
9694     /* making decision what to do */
9695     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Validating parameters:');
9696 
9697     -- P_Ledger_id is a mandatory parameter
9698     IF P_LEDGER_ID is NOT NULL THEN
9699         l_loan_id     := NULL;
9700         l_borrower_id := null;
9701 	l_org_id := null;
9702 	l_ledger_id := P_LEDGER_ID;
9703 
9704          LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Ledger ID: ' || l_ledger_id);
9705 
9706     ELSE
9707 
9708 	FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_PARAMS');
9709         FND_MSG_PUB.Add;
9710         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
9711         RAISE FND_API.G_EXC_ERROR;
9712 
9713     END IF;
9714 
9715 
9716 
9717     IF P_LOAN_ID IS NOT NULL THEN   -- if loan_id is passed - ignore borrower_id parameter
9718 
9719         l_loan_id := P_LOAN_ID;
9720         l_borrower_id := null;
9721 	l_org_id := null;
9722 
9723         LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Loan ID: ' || l_loan_id);
9724 
9725 
9726     elsif P_ORG_ID is NOT NULL then
9727         l_loan_id     := NULL;
9728         l_borrower_id := null;
9729 	l_org_id := P_ORG_ID;
9730 
9731          LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Org ID: ' || l_org_id);
9732 
9733     elsif P_BORROWER_ID is NOT null then
9734         l_loan_id     := NULL;
9735         l_borrower_id := P_BORROWER_ID;
9736 	l_org_id := null;
9737 
9738          LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Borrower ID: ' || l_borrower_id);
9739 
9740     end if;
9741 
9742      IF  (P_PERIOD_NAME is NOT NULL) THEN
9743 	l_is_period_end := 'Y';
9744 	LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'It is Period End Accrual - l_is_period_end: '||l_is_period_end );
9745      ELSIF (P_ACCRUAL_DATE is NOT NULL) THEN
9746      	l_is_period_end := 'N';
9747 	l_accrual_date  :=  p_accrual_date;
9748 	LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'It is NOT Period End Accrual - l_is_period_end: '||l_is_period_end );
9749      ELSE
9750         FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_PARAMS');
9751         FND_MSG_PUB.Add;
9752         LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
9753         RAISE FND_API.G_EXC_ERROR;
9754      END IF;
9755 
9756      IF  l_is_period_end = 'Y' THEN
9757 
9758      	LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Retrieve the Last day of the period '||p_period_name);
9759 
9760 	OPEN  cur_gl_period_last_date(p_period_name, l_ledger_id);
9761 	FETCH cur_gl_period_last_date INTO l_accrual_date;
9762 	CLOSE cur_gl_period_last_date;
9763 
9764 	LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Last day of period '||p_period_name||' is '||l_accrual_date );
9765 
9766 	IF l_accrual_date is NULL  THEN
9767 		FND_MESSAGE.SET_NAME('LNS', 'LNS_INVALID_PERIOD');
9768 		FND_MESSAGE.SET_TOKEN('PERIOD_NAME',p_period_name);
9769 		FND_MSG_PUB.Add;
9770 		LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
9771 		RAISE FND_API.G_EXC_ERROR;
9772 	END IF;
9773 
9774      END IF;
9775 
9776     dbms_lob.createtemporary(l_error_statements_xml, FALSE, DBMS_LOB.CALL);
9777     dbms_lob.open(l_error_statements_xml, dbms_lob.lob_readwrite);
9778 
9779     -- 1. The accrual Period/Date should be in Open GL Period
9780 
9781     IF l_ledger_id IS NOT NULL  THEN
9782 	OPEN cur_gl_period_status(l_accrual_date , l_ledger_id);
9783 	FETCH cur_gl_period_status INTO l_gl_period_name, l_gl_period_status;
9784 	CLOSE cur_gl_period_status;
9785 
9786 	LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'The GL Period status is '||l_gl_period_status||' for period '||l_gl_period_name);
9787 
9788 	IF l_gl_period_status NOT IN ( 'O') THEN
9789 		FND_MESSAGE.SET_NAME('LNS', 'LNS_ACCRUE_GL_PERIOD_CLOSED');
9790 		FND_MESSAGE.SET_TOKEN('ACCRUAL_DATE', l_accrual_date);
9791 		FND_MSG_PUB.Add;
9792 		LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
9793 		LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Invoking BUILD_ACCRUAL_ERR_STMT() API');
9794 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
9795 		BUILD_ACCRUAL_ERR_STMT(P_ACCRUAL_DATE 		=> l_accrual_date
9796 							,P_RESULT				=> 'E'
9797 							,P_ERR_COUNT 			=> x_msg_count
9798                         				,X_STATEMENT_XML 		=> l_error_statements_xml);
9799 
9800 		dbms_lob.Append(g_cp_statements, l_error_statements_xml);
9801 		RAISE FND_API.G_EXC_ERROR;
9802 	END IF;
9803     END IF;
9804 
9805 
9806     /* quering for loans */
9807     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Searching for not billed yet loans to process...');
9808 
9809     open cur_loans_to_accrue_int(l_accrual_date, l_loan_id, l_borrower_id, l_org_id, l_ledger_id);
9810 
9811     l_Count1 := 0;
9812 
9813     LOOP
9814 
9815         l_Count1 := l_Count1+1;
9816 
9817         fetch cur_loans_to_accrue_int  into
9818             l_loans_to_accrue_tbl(l_Count1);
9819 
9820         exit when cur_loans_to_accrue_int%NOTFOUND;
9821 
9822         LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, ' ');
9823         LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Loan #' || l_Count1);
9824         LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'LOAN_ID: ' || l_loans_to_accrue_tbl(l_Count1));
9825      --   LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'LOAN_NUMBER: ' || l_loans_to_accrue_tbl(l_Count1).LOAN_NUMBER);
9826      --   LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'LOAN_DESCRIPTION: ' || l_loans_to_accrue_tbl(l_Count1).LOAN_DESCRIPTION);
9827 
9828     END LOOP;
9829 
9830     close cur_loans_to_accrue_int;
9831 
9832     l_Count := l_loans_to_accrue_tbl.count;
9833     LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, '______________');
9834     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, 'Total found ' || l_Count || ' loan(s) to process');
9835 
9836     if l_Count > 0 then
9837 
9838                 l_new_line := '
9839 ';
9840 
9841 	l_success_header := l_new_line || '<SUCCESS_LOANS>' || l_new_line;
9842         l_success_footer := l_new_line || '</SUCCESS_LOANS>' || l_new_line;
9843 
9844 	dbms_lob.writeAppend(g_last_all_statements, length(l_success_header), l_success_header);
9845 
9846 	/* Accrue all the selected loans */
9847         FOR l_Count1 IN 1..l_loans_to_accrue_tbl.COUNT LOOP
9848 
9849             LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, 'Processing loan #' || l_Count1||' - '||l_loans_to_accrue_tbl(l_Count1));
9850 
9851             LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Invoking LNS_DISTRIBUTIONS_PUB.do_int_accrual_reversal..');
9852 
9853             l_start := sysdate;
9854             LNS_DISTRIBUTIONS_PUB.do_int_accrual_reversal(p_api_version     => 1
9855                                                         ,p_init_msg_list     => 'T'
9856                                                         ,p_commit     => 'F'
9857                                                         ,p_loan_id => l_loans_to_accrue_tbl(l_Count1)
9858 							,p_period_name => p_period_name
9859                                                         ,p_accrual_date => l_accrual_date
9860 							,p_accounting_mode => p_mode
9861 							,X_STATEMENT_XML => l_single_statement_xml
9862                                                         ,x_return_status => l_return_status
9863                                                         ,x_msg_count   => l_msg_count
9864                                                         ,x_msg_data   =>  l_msg_data);
9865 
9866             l_end := sysdate;
9867             LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Total Accrual timing: ' || round((l_end - l_start)*86400, 2) || ' sec');
9868 
9869             IF l_return_status = 'S' THEN   /* append to all statements clob */
9870 
9871                 dbms_lob.Append(g_last_all_statements, l_single_statement_xml);
9872 		g_passed_loan_cnt	:= g_passed_loan_cnt +1;
9873 
9874             ELSE    /* otherwise append to errors clob */
9875 
9876                 dbms_lob.Append(l_error_statements_xml, l_single_statement_xml);
9877 		g_failed_loan_cnt	:= g_failed_loan_cnt +1;
9878 
9879             END IF;
9880 
9881         END LOOP;
9882 	dbms_lob.writeAppend(g_last_all_statements, length(l_success_footer), l_success_footer);
9883 
9884         /* if there are errors, add errors section */
9885         if dbms_lob.getlength(l_error_statements_xml) > 0 then
9886 
9887             l_error_header := l_new_line || '<ERROR_LOANS>' || l_new_line;
9888             l_error_footer := l_new_line || '</ERROR_LOANS>' || l_new_line;
9889             dbms_lob.writeAppend(g_last_all_statements, length(l_error_header), l_error_header);
9890             dbms_lob.Append(g_last_all_statements, l_error_statements_xml);
9891             dbms_lob.writeAppend(g_last_all_statements, length(l_error_footer), l_error_footer);
9892 
9893         end if;
9894 
9895     END IF;
9896 
9897     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, '______________');
9898     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, 'Total processed ' || (l_Count1-1) || ' loan(s)');
9899     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, 'Total successed  ' || g_passed_loan_cnt || ' loan(s)');
9900     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, 'Total Failed/Warning  ' || g_failed_loan_cnt || ' loan(s)');
9901 
9902     -- Note: If possible delete the lnsDistribution records and corresponding events for AccountingFailed loans and then commit the below
9903 
9904     if P_COMMIT = FND_API.G_TRUE then
9905         COMMIT WORK;
9906         LogMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Commited loans');
9907     end if;
9908 
9909     -- END OF BODY OF API
9910     x_return_status := FND_API.G_RET_STS_SUCCESS;
9911 
9912     -- Standard call to get message count and if count is 1, get message info
9913     FND_MSG_PUB.Count_And_Get(
9914                 p_encoded => FND_API.G_FALSE,
9915                 p_count => x_msg_count,
9916                 p_data => x_msg_data);
9917 
9918     LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' -');
9919 
9920 EXCEPTION
9921     WHEN FND_API.G_EXC_ERROR THEN
9922         ROLLBACK TO ACCRUE_LOANS_INTEREST_PVT;
9923         x_return_status := FND_API.G_RET_STS_ERROR;
9924         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
9925         LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Rollbacked loans');
9926         g_cr_return_status := 'ERROR';
9927     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
9928         ROLLBACK TO ACCRUE_LOANS_INTEREST_PVT;
9929         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
9930         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
9931         LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Rollbacked loans');
9932         g_cr_return_status := 'ERROR';
9933     WHEN OTHERS THEN
9934         ROLLBACK TO ACCRUE_LOANS_INTEREST_PVT;
9935         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
9936         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR)THEN
9937             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
9938         END IF;
9939         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
9940         LogMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, 'Rollbacked loans');
9941         g_cr_return_status := 'ERROR';
9942 
9943 END ACCRUE_LOANS_INTEREST;
9944 
9945 
9946 /*========================================================================
9947  | PUBLIC PROCEDURE LNS_ACCRUAL_ACCOUNTING_CONCUR
9948  |
9949  | DESCRIPTION
9950  |      This procedure got called from concurent manager to accrue loans interest
9951  |
9952  | CALLED FROM PROCEDURES/FUNCTIONS (local to this package body)
9953  |      None
9954  |
9955  | CALLS PROCEDURES/FUNCTIONS (local to this package body)
9956  |      LogMessage
9957  |
9958  | PARAMETERS
9959  |      ERRBUF              OUT     Returns errors to CM
9960  |      RETCODE             OUT     Returns error code to CM
9961  |      BORROWER_ID         IN      Inputs Borrower Id
9962  |	LEDGER_ID			IN Ledger
9963  |	ORG_ID				IN Operating Unit
9964  |      LOAN_ID             IN      Inputs Loan Id
9965  |      ACCRUAL_TYPE	IN	It tells whether the accrual is Period_end or daily_accrual
9966  |	PERIOD_DUMMY  IN  It is a dummy parameter used to enable the period param in CP if the accrual_type is 'PERIOD_END_ACCRUAL'
9967  |	PERIOD		   IN	    Inputs the Period for which the period-end accrual requires
9968  |	ACCRUAL_DATE_DUMMY  IN  It is a dummy parameter used to enable the accrual_date param in CP if the accrual_type is 'DAILY_ACCRUAL'
9969  |      ACCRUAL_DATE        IN      Inputs accrual Date
9970  |      P_MODE                IN    Mode - Preview or Final
9971  |
9972  | KNOWN ISSUES
9973  |      None
9974  |
9975  | NOTES
9976  |      Any interesting aspect of the code in the package body which needs
9977  |      to be stated.
9978  |
9979  | MODIFICATION HISTORY
9980  | Date                  Author            Description of Changes
9981  | 15-OCT-2010           MBOLLI            Created
9982  |
9983  *=======================================================================*/
9984 PROCEDURE LNS_ACCRUAL_ACCOUNTING_CONCUR(
9985 	    ERRBUF              OUT NOCOPY     VARCHAR2,
9986 	    RETCODE             OUT NOCOPY     VARCHAR2,
9987       	    BORROWER_ID   IN           NUMBER,
9988 	    LEDGER_ID		IN   NUMBER,
9989 	    ORG_ID		IN	NUMBER,
9990       	    LOAN_ID             IN           NUMBER,
9991 	    ACCRUAL_TYPE	IN	VARCHAR2,
9992 	    PERIOD_DUMMY	IN	VARCHAR2  DEFAULT NULL,
9993 	    PERIOD		IN		VARCHAR2,
9994 	    ACCRUAL_DATE_DUMMY IN VARCHAR2 DEFAULT NULL,
9995       	   ACCRUAL_DATE        IN           VARCHAR2,
9996       	   P_MODE                IN             VARCHAR2)
9997 IS
9998 
9999 /*-----------------------------------------------------------------------+
10000  | Local Variable Declarations and initializations                       |
10001  +-----------------------------------------------------------------------*/
10002 	l_msg_count	        number;
10003     l_return            boolean;
10004     l_api_name              varchar2(30);
10005     l_accrual_date	   DATE;
10006     l_date_format	varchar2(30);
10007 
10008 
10009 BEGIN
10010     l_api_name  := 'LNS_ACCRUAL_ACCOUNTING_CONCUR';
10011     g_cr_return_status := 'NORMAL';
10012 
10013 
10014     logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
10015 
10016     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, '<<--------Accruing loans...-------->>');
10017 
10018      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || '  ACCRUAL_DATE '||ACCRUAL_DATE);
10019 
10020     --l_accrual_date := trunc(fnd_date.canonical_to_date(ACCRUAL_DATE));
10021 
10022     --will give GSCC failure l_accrual_date := TO_DATE(ACCRUAL_DATE, 'DD-MON-RRRR');
10023     select FND_PROFILE.VALUE('ICX_DATE_FORMAT_MASK') into l_date_format from dual;
10024 
10025     select TO_DATE(ACCRUAL_DATE, l_date_format) into l_accrual_date from dual;
10026 
10027 
10028 
10029     /* do accrual for all loans and stores all statements in g_last_all_statements */
10030     ACCRUE_LOANS_INTEREST(
10031                   P_API_VERSION => 1.0,
10032                 P_INIT_MSG_LIST	=> FND_API.G_TRUE,
10033                 P_COMMIT => FND_API.G_TRUE,
10034                 P_VALIDATION_LEVEL => FND_API.G_VALID_LEVEL_FULL,
10035                 P_BORROWER_ID => BORROWER_ID,
10036 		P_LEDGER_ID	 =>  LEDGER_ID,
10037 		P_ORG_ID	 =>   ORG_ID,
10038                 P_LOAN_ID    =>  LOAN_ID,
10039 		P_PERIOD_NAME => PERIOD,
10040                 P_ACCRUAL_DATE =>  l_accrual_date,
10041                 P_MODE         => P_MODE,
10042                 X_RETURN_STATUS	=> RETCODE,
10043                 X_MSG_COUNT => l_msg_count,
10044                 X_MSG_DATA => ERRBUF);
10045 
10046     LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, 'Building accrual report');
10047 
10048     /* build accrual report and stores it in g_last_billing_report */
10049     BUILD_ACCRUAL_REPORT(P_BORROWER_ID => BORROWER_ID,
10050     			 P_LEDGER_ID  => LEDGER_ID,
10051     			 P_ORG_ID  =>  ORG_ID,
10052                          P_LOAN_ID     => LOAN_ID,
10053 			 P_PERIOD_NAME => PERIOD,
10054                          P_ACCRUAL_DATE => l_accrual_date,
10055 			 P_MODE			=>	p_mode,
10056 			 P_CP_STATEMENTS   => g_cp_statements,
10057                          P_STATEMENTS_XML => g_last_all_statements);
10058 
10059      LogMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, 'g_cr_return_status is: '||g_cr_return_status);
10060 
10061     if g_cr_return_status = 'WARNING' then
10062         l_return := FND_CONCURRENT.SET_COMPLETION_STATUS(
10063                         status => g_cr_return_status,
10064 			            message => 'All the loans eligible for accured interest were NOT successful. Please review log file.');
10065     elsif g_cr_return_status = 'ERROR' then
10066         l_return := FND_CONCURRENT.SET_COMPLETION_STATUS(
10067                         status => g_cr_return_status,
10068 			            message => 'Accrual process has failed. Please review log file.');
10069     end if;
10070 
10071      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
10072 
10073 END LNS_ACCRUAL_ACCOUNTING_CONCUR;
10074 
10075 /*=========================================================================
10076 || PUBLIC PROCEDURE defaultBookDistForActivity
10077 ||
10078 || DESCRIPTION
10079 ||      This procedure returns loan Booking distributions
10080 ||      For NegativeLoanAdjutment, it returns the distributions in reverse
10081 ||
10082 || PSEUDO CODE/LOGIC
10083 ||
10084 || PARAMETERS p_activity
10085 ||
10086 ||
10087 || Return value: x_distribution_tbl           distribution table set to write to database
10088 ||
10089 || Source Tables: lns_distributions
10090 ||
10091 || Target Tables: NA
10092 ||
10093 || KNOWN ISSUES
10094 ||
10095 || NOTES
10096 ||
10097 ||
10098 || MODIFICATION HISTORY
10099 || Date                  Author            Description of Changes
10100 || 24-Feb-2011            mbolli             Created
10101  *=======================================================================*/
10102 PROCEDURE defaultBookDistForActivity(p_api_version                IN NUMBER
10103                                    ,p_init_msg_list              IN VARCHAR2
10104                                    ,p_commit                     IN VARCHAR2
10105                                    ,p_loan_id                    IN NUMBER
10106                                    ,p_disb_header_id             IN NUMBER DEFAULT NULL
10107                                    ,p_loan_amount_adj_id         IN NUMBER DEFAULT NULL
10108 				   ,p_activity			 IN VARCHAR2
10109                                    ,x_distribution_tbl           OUT NOCOPY lns_distributions_pub.distribution_tbl
10110                                    ,x_return_status              OUT NOCOPY VARCHAR2
10111                                    ,x_msg_count                  OUT NOCOPY NUMBER
10112                                    ,x_msg_data                   OUT NOCOPY VARCHAR2)
10113 
10114 
10115 is
10116 /*------------------------------------------------------------------------+
10117  | Local Variable Declarations and initializations                        |
10118  +-----------------------------------------------------------------------*/
10119     l_api_name               varchar2(50);
10120     l_msg_count              NUMBER;
10121     l_msg_data               VARCHAR2(2000);
10122     l_return_Status          VARCHAR2(1);
10123     l_class                  varchar2(30);
10124     l_loan_type_id           number;
10125     l_index                  number := 0;
10126     l_line_type              varchar2(30);
10127     l_account_name           varchar2(30);
10128     l_code_combination_id    number;
10129     l_account_type           varchar2(30);
10130     l_distribution_id	     number;
10131     l_distribution_percent   number;
10132     l_distribution_amount    number;
10133     l_distribution_type      varchar2(30);
10134     l_funded_amount          number;
10135     l_adj_reversal           varchar2(1);
10136     l_loan_receivables_count number;
10137     l_loan_payables_count    number;
10138     l_distributions          lns_distributions_pub.distribution_tbl;
10139     l_dr_run_amount          number;
10140     l_cr_run_amount          number;
10141     drIndex                  number;
10142     crIndex                  number;
10143     l_ledger_details         lns_distributions_pub.gl_ledger_details;
10144     Type refCur is ref cursor;
10145     sql_Cur                  refCur;
10146     vSqlCur                 varchar2(1000);
10147     vPLSQL                  VARCHAR2(1000);
10148 
10149 /*------------------------------------------------------------------------+
10150  | Cursor Declarations                                                    |
10151  +-----------------------------------------------------------------------*/
10152 		-- R12 for loan_types
10153     cursor c_disbursement_info(p_loan_id NUMBER, p_disb_header_id number)
10154     is
10155     select d.header_amount
10156       from lns_disb_headers d
10157       where d.loan_id = p_loan_id
10158 	and d.disb_header_id = p_disb_header_id;
10159 
10160     cursor c_loan_adjustment_info(c_loan_id NUMBER, c_loan_amount_adj_id number)
10161     is
10162     select ladj.adjustment_amount
10163       from LNS_LOAN_AMOUNT_ADJS ladj
10164      where ladj.loan_id = p_loan_id
10165         and ladj.status = 'PENDING'
10166 	and ladj.loan_amount_adj_id = c_loan_amount_adj_id;
10167 
10168 
10169     cursor c_num_receivables(c_loan_id number, c_activity varchar2)
10170     is
10171     select count(1)
10172       from lns_distributions
10173      where loan_id = c_loan_id
10174        and activity = c_activity
10175        and account_type = 'DR';
10176 
10177     cursor c_num_payables(c_loan_id number, c_activity varchar2)
10178     is
10179     select count(1)
10180       from lns_distributions
10181      where loan_id = c_loan_id
10182        and activity = c_activity
10183        and account_type = 'CR';
10184 
10185 
10186     cursor c_get_distributions(c_loan_id number) is
10187        select d.distribution_id
10188 	     ,d.account_type
10189              ,d.line_type
10190              ,d.account_name
10191              ,d.code_combination_id
10192              ,d.distribution_percent
10193              ,d.distribution_amount
10194              ,d.distribution_type
10195        from lns_distributions d
10196        where d.loan_id = c_loan_id
10197          and d.activity = 'LNS_APPROVAL'
10198         order by d.account_type, d.code_combination_id;
10199 
10200 
10201 begin
10202      SAVEPOINT defaultBookDistForActivity;
10203      l_api_name := 'defaultBookDistForActivity';
10204      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
10205 
10206      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
10207      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_disb_header_id = ' || p_disb_header_id);
10208      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_amount_adj_id = ' || p_loan_amount_adj_id);
10209      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_activity = ' || p_activity);
10210 
10211      -- Initialize message list IF p_init_msg_list is set to TRUE.
10212      IF FND_API.to_Boolean( p_init_msg_list ) THEN
10213          FND_MSG_PUB.initialize;
10214      END IF;
10215 
10216      -- Initialize API return status to SUCCESS
10217      x_return_status := FND_API.G_RET_STS_SUCCESS;
10218 
10219      drIndex := 0;
10220      crIndex := 0;
10221      l_dr_run_amount := 0;
10222      l_cr_run_amount := 0;
10223      l_ledger_details   := lns_distributions_pub.getLedgerDetails;
10224 
10225      -- get fund amount
10226      l_adj_reversal := 'N';
10227      if p_activity = 'LOAN_AMOUNT_ADJUSTMENT' then
10228         OPEN c_loan_adjustment_info(p_loan_id, p_loan_amount_adj_id);
10229         FETCH c_loan_adjustment_info INTO l_funded_amount;
10230         close c_loan_adjustment_info;
10231         if l_funded_amount < 0 then
10232           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Before reversal, l_funded_amount = ' || l_funded_amount);
10233           l_adj_reversal  :=  'Y';
10234           l_funded_amount := -(l_funded_amount);
10235           logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'After reversal, l_funded_amount = ' || l_funded_amount);
10236         end if;
10237      elsif p_activity in ('DISBURSEMENT', 'DISBURSEMENT', 'LNS_SUBMIT_DISBURSEMENT', 'LNS_SUBMITTED_DISB_CANCEL') then
10238         OPEN c_disbursement_info(p_loan_id, p_disb_header_id);
10239         FETCH c_disbursement_info INTO l_funded_amount;
10240         close c_disbursement_info;
10241      end if;
10242 
10243      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_funded_amount = ' || l_funded_amount);
10244 
10245      open c_num_receivables(p_loan_id, p_activity);
10246      fetch c_num_receivables into l_loan_receivables_count;
10247      close c_num_receivables;
10248      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_receivables_count = ' || l_loan_receivables_count);
10249 
10250      open c_num_payables(p_loan_id, p_activity);
10251      fetch c_num_payables into l_loan_payables_count;
10252      close c_num_payables;
10253 
10254      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_loan_payables_count = ' || l_loan_payables_count);
10255 
10256      BEGIN
10257 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'opening c_get_distribution...');
10258 	OPEN c_get_distributions (p_loan_id);
10259 	LOOP
10260 		FETCH c_get_distributions into
10261 			l_distribution_id
10262 			,l_account_type
10263 			,l_line_type
10264 			,l_account_name
10265 			,l_code_combination_id
10266 			,l_distribution_percent
10267 			,l_distribution_amount
10268 			,l_distribution_type;
10269 		EXIT WHEN C_Get_Distributions%NOTFOUND;
10270 		l_index := l_index + 1;
10271 
10272 		if (l_adj_reversal = 'Y' and l_distribution_type = 'ORIGINATION') then
10273 			logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_type = ' || l_account_type);
10274 			if l_account_type = 'DR' then
10275 				l_account_type := 'CR';
10276 			elsif l_account_type = 'CR' then
10277 				l_account_type := 'DR';
10278 			end if;
10279 		end if;
10280 
10281 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Record ' || l_index);
10282 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_id = ' || l_distribution_id);
10283 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_type = ' || l_account_type);
10284 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_line_type = ' || l_line_type);
10285 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_account_name = ' || l_account_name);
10286 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_code_combination_id = ' || l_code_combination_id);
10287 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_percent = ' || l_distribution_percent);
10288 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_amount = ' || l_distribution_amount);
10289 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distribution_type = ' || l_distribution_type);
10290 
10291 
10292 		l_distributions(l_index).distribution_id        := l_distribution_id;
10293 		l_distributions(l_index).loan_id                := p_loan_id;
10294 		l_distributions(l_index).account_type           := l_account_type;
10295 		l_distributions(l_index).line_type              := l_line_type;
10296 		l_distributions(l_index).account_name           := l_account_name;
10297 		l_distributions(l_index).code_combination_id    := l_code_combination_id;
10298 		l_distributions(l_index).distribution_percent   := l_distribution_percent;
10299 		l_distributions(l_index).distribution_amount    := l_distribution_amount;
10300 		l_distributions(l_index).distribution_type      := l_distribution_type;
10301 		l_distributions(l_index).activity      		:= p_activity;
10302 
10303 		if l_account_name = 'LOAN_RECEIVABLE' and l_distribution_type = 'ORIGINATION' then
10304 			drIndex := drIndex + 1;
10305 			logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan receivables line ' || drIndex);
10306 
10307 			if drIndex <> l_loan_receivables_count then
10308 				l_distributions(l_index).distribution_amount    := round(l_distribution_percent * l_funded_amount, l_ledger_details.currency_precision) / 100;
10309 				l_dr_run_amount := l_dr_run_amount + l_distributions(l_index).distribution_amount;
10310 			else
10311 				l_distributions(l_index).distribution_amount    := l_funded_amount - l_dr_run_amount;
10312 			end if;
10313 
10314 			logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions('||l_index||').distribution_amount = ' || l_distributions(l_index).distribution_amount);
10315 			logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_dr_run_amount = ' || l_dr_run_amount);
10316 
10317 		end if;
10318 
10319 		if (l_account_name = 'LOAN_CLEARING' or l_account_name = 'LOAN_PAYABLE') and l_distribution_type = 'ORIGINATION' then
10320 
10321 			crIndex := crIndex + 1;
10322 			logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'loan clearing line ' || crIndex);
10323 
10324 			if crIndex <> l_loan_receivables_count then
10325 				l_distributions(l_index).distribution_amount    := round(l_distribution_percent * l_funded_amount, l_ledger_details.currency_precision) / 100;
10326 				l_cr_run_amount := l_cr_run_amount + l_distributions(l_index).distribution_amount;
10327 			else
10328 				l_distributions(l_index).distribution_amount    := l_funded_amount - l_cr_run_amount;
10329 			end if;
10330 
10331 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_distributions('||l_index||').distribution_amount = ' || l_distributions(l_index).distribution_amount);
10332 		logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_cr_run_amount = ' || l_cr_run_amount);
10333 
10334 		end if;
10335 
10336 	END LOOP;
10337 
10338 	CLOSE C_Get_Distributions;
10339 
10340 
10341      EXCEPTION
10342        when no_data_found then
10343            FND_MESSAGE.SET_NAME('LNS', 'LNS_DEFAULT_DIST_NOT_FOUND');
10344            FND_MSG_PUB.ADD;
10345            logMessage(FND_LOG.LEVEL_UNEXPECTED, G_PKG_NAME, FND_MSG_PUB.Get(p_encoded => 'F'));
10346            RAISE FND_API.G_EXC_ERROR;
10347      END; -- c_default_info cursor
10348 
10349      logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'distribs2 count is ' || l_distributions.count);
10350      x_distribution_tbl := l_distributions;
10351 
10352      IF FND_API.to_Boolean(p_commit)
10353      THEN
10354          COMMIT WORK;
10355      END IF;
10356 
10357      FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
10358 
10359      logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - END');
10360 
10361 EXCEPTION
10362     WHEN FND_API.G_EXC_ERROR THEN
10363         ROLLBACK TO defaultBookDistForActivity;
10364         x_return_status := FND_API.G_RET_STS_ERROR;
10365         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
10366         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
10367 
10368     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
10369         ROLLBACK TO defaultBookDistForActivity;
10370         x_return_status := FND_API.G_RET_STS_ERROR;
10371         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
10372         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
10373 
10374     WHEN OTHERS THEN
10375         ROLLBACK TO defaultBookDistForActivity;
10376         x_return_status := FND_API.G_RET_STS_ERROR;
10377         logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
10378         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
10379 
10380 END defaultBookDistForActivity;
10381 
10382 /*=========================================================================
10383 || procedure GENERATE_CCID_FOR_PROJECTS
10384 ||
10385 || DESCRIPTION
10386 ||      This procedure generates CCID corresponding to given Project,Task,Award,Expenditure Type details
10387 ||
10388 || PSEUDO CODE/LOGIC
10389 ||
10390 || PARAMETERS
10391 ||   p_loan_id = Loan Id
10392 ||   p_distribution_id = Distribution Id
10393 ||   p_project_id = Project ID corresponding to the Project selected
10394 ||   p_task_id = Task ID corresponding to the Task selected
10395 ||   p_award_id = Award ID corresponding to the Award selected
10396 ||   p_expenditure_type = expenditure Type
10397 ||   p_expenditure_date = expenditure date
10398 ||
10399 || Return value:  CCID corresponding to the Project, Task, Award, Expenditure Type combination
10400 ||                Concatenated Segment value
10401 || Source Tables: lns_distributions
10402 ||
10403 || Target Tables:
10404 ||
10405 || KNOWN ISSUES
10406 ||
10407 || NOTES
10408 ||
10409 ||
10410 || MODIFICATION HISTORY
10411 || Date                  Author            Description of Changes
10412 || 02-12-2011            gparuchu             Created
10413 ||
10414  *=======================================================================*/
10415 
10416 procedure GENERATE_CCID_FOR_PROJECTS(p_loan_id in number
10417                                    ,p_distribution_id in number
10418                                    ,p_project_id in number
10419                                    ,p_task_id in number
10420                                    ,p_award_id in number
10421                                    ,p_expenditure_type in varchar2
10422                                    ,p_expenditure_date date
10423                                    ,x_ccid                       OUT NOCOPY NUMBER
10424                                    ,x_conc_segment_values        OUT NOCOPY VARCHAR2
10425                                    ,x_return_status              OUT NOCOPY VARCHAR2
10426                                    ,x_msg_count                  OUT NOCOPY NUMBER
10427                                    ,x_msg_data                   OUT NOCOPY VARCHAR2)
10428 IS
10429 
10430 /*------------------------------------------------------------------------+
10431  | Local Variable Declarations and initializations                        |
10432  +-----------------------------------------------------------------------*/
10433    l_api_name              varchar2(50);
10434    l_charge_success        boolean;
10435    l_budget_success        boolean;
10436    l_accrual_success       boolean;
10437    l_variance_success      boolean;
10438    l_new_combination	   boolean;
10439    l_code_combination_id   number;
10440    l_budget_account_id     number;
10441    l_accrual_account_id    number;
10442    l_variance_account_id   number;
10443 
10444    l_charge_account_flex   varchar2(2000);
10445    l_budget_account_flex   varchar2(2000);
10446    l_accrual_account_flex  varchar2(2000);
10447    l_variance_account_flex varchar2(2000);
10448    l_charge_account_desc   varchar2(2000);
10449    l_budget_account_desc   varchar2(2000);
10450    l_accrual_account_desc  varchar2(2000);
10451    l_variance_account_desc varchar2(2000);
10452    l_WF_itemkey		   varchar2(240);
10453    l_FB_ERROR_MSG          varchar2(4000);
10454 
10455    l_expenditure_type            pa_expenditure_types.expenditure_type%TYPE;
10456    l_expenditure_organization_id number;
10457    l_expenditure_item_date       date;
10458    l_project_id                  pa_projects_all.project_id%TYPE;
10459    l_task_id                     pa_tasks.task_id%TYPE;
10460    l_award_id	               gms_awards.award_id%TYPE;
10461 
10462    isGrantsEnabled boolean;
10463    l_gms_award_set_id		 number;
10464    l_gms_status			 varchar2(100);
10465    l_coa_id number;
10466    x_return boolean;
10467 
10468    cursor C_COA_DETAILS is
10469    select chart_of_accounts_id
10470     from gl_sets_of_books gl_books
10471     where gl_books.set_of_books_id = (select set_of_books_id from lns_system_options);
10472 
10473    cursor C_LOAN_DETAILS(p_loan_id in number) is
10474    select org_id
10475    from lns_loan_headers lh
10476    where lh.loan_id = p_loan_id;
10477 
10478 
10479 
10480 begin
10481 
10482    -- Initialize API return status to SUCCESS
10483    x_return_status := FND_API.G_RET_STS_SUCCESS;
10484 
10485    l_api_name := 'GENERATE_CCID_FOR_PROJECTS';
10486    logMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME, l_api_name || ' - BEGIN');
10487    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_loan_id = ' || p_loan_id);
10488    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_distribution_id  = ' || p_distribution_id);
10489    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_project_id = ' || p_project_id);
10490    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_task_id = ' || p_task_id);
10491    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_award_id = ' || p_award_id);
10492    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_expenditure_type = ' || p_expenditure_type);
10493    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'p_expenditure_date = ' || p_expenditure_date);
10494 
10495 
10496 
10497    l_expenditure_type := p_expenditure_type;
10498    l_expenditure_item_date := p_expenditure_date;
10499    l_project_id := p_project_id;
10500    l_task_id := p_task_id;
10501    l_award_id := p_award_id;
10502 
10503    l_charge_success := true;
10504    l_budget_success := true;
10505    l_accrual_success := true;
10506    l_variance_success := true;
10507    l_code_combination_id := null;
10508    l_budget_account_id := null;
10509    l_accrual_account_id := null;
10510    l_variance_account_id := null;
10511 
10512    l_charge_account_flex := null;
10513    l_budget_account_flex := null;
10514    l_accrual_account_flex := null;
10515    l_variance_account_flex := null;
10516    l_charge_account_desc := null;
10517    l_budget_account_desc := null;
10518    l_accrual_account_desc := null;
10519    l_variance_account_desc := null;
10520 
10521 
10522    l_new_combination := false;
10523    l_WF_itemkey := null;
10524 
10525 
10526    l_gms_award_set_id	:= null;
10527    l_gms_status	:= null;
10528    isGrantsEnabled := false;
10529 
10530    l_coa_id := null;
10531 
10532 
10533    open C_LOAN_DETAILS(p_loan_id);
10534    fetch C_LOAN_DETAILS into l_expenditure_organization_id ;
10535    close C_LOAN_DETAILS ;
10536    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_expenditure_organization_id = ' || l_expenditure_organization_id );
10537 
10538    open C_COA_DETAILS;
10539    fetch C_COA_DETAILS into l_coa_id;
10540    close C_COA_DETAILS;
10541    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_coa_id = ' || l_coa_id);
10542 
10543    --Need to uncomment below line if need to enable DBMS OUTPU debug log
10544    --FND_FLEX_WORKFLOW.debug_on();
10545 
10546    -- need to call GMS_POR_API.Account_Generator_ADL before calling AccountGenerator Workflow.
10547    -- This API creates distributions in the Grants, if Grants in implemented/enabled and AwardID is not null.
10548 
10549    IF (GMS_OIE_INT_PKG.IsGrantsEnabled()) THEN
10550          isGrantsEnabled := true;
10551          logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'isGrantsEnabled = true');
10552        ELSE
10553          isGrantsEnabled := false;
10554          logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'isGrantsEnabled = false');
10555        END IF;
10556 
10557 
10558    if(isGrantsEnabled AND (l_award_id is not null))
10559     THEN
10560 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling GMS_POR_API.Account_Generator_ADL in CREATE mode');
10561       GMS_POR_API.Account_Generator_ADL
10562       (
10563          X_project_id	=> l_project_id,
10564          X_task_id	=> l_task_id,
10565          X_award_id	=> l_award_id,
10566          X_event	=> 'CREATE',
10567          X_award_set_id => l_gms_award_set_id,  --null
10568          X_status	=> l_gms_status );      -- null
10569    end if;
10570 
10571  logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling PO_REQ_WF_BUILD_ACCOUNT_INIT.start_workflow');
10572 
10573  x_return :=
10574 PO_REQ_WF_BUILD_ACCOUNT_INIT.start_workflow
10575 (
10576    x_charge_success       => l_charge_success,
10577    x_budget_success        => l_budget_success,
10578    x_accrual_success      => l_accrual_success,
10579    x_variance_success      => l_accrual_success,
10580    x_code_combination_id  => l_code_combination_id,
10581    x_budget_account_id     => l_budget_account_id,
10582    x_accrual_account_id   => l_accrual_account_id,
10583    x_variance_account_id   => l_variance_account_id,
10584    x_charge_account_flex  => l_charge_account_flex,
10585    x_budget_account_flex   => l_budget_account_flex,
10586    x_accrual_account_flex => l_accrual_account_flex,
10587    x_variance_account_flex => l_variance_account_flex,
10588    x_charge_account_desc  => l_charge_account_desc,
10589    x_budget_account_desc   => l_budget_account_desc,
10590    x_accrual_account_desc => l_accrual_account_desc,
10591    x_variance_account_desc => l_variance_account_desc,
10592    x_coa_id               => l_coa_id, --US FED->51549,OPERATIONS->101,
10593    x_bom_resource_id      => null,
10594    x_bom_cost_element_id  => null,
10595    x_category_id          => null,
10596    x_destination_type_code  => 'EXPENSE',
10597    x_deliver_to_location_id => null,
10598    x_destination_organization_id => null,
10599    x_destination_subinventory      => null,
10600    x_expenditure_type             => l_expenditure_type,
10601    x_expenditure_organization_id  => l_expenditure_organization_id,
10602    x_expenditure_item_date       => l_expenditure_item_date,
10603    x_item_id                     => null,
10604    x_line_type_id                => null,
10605    x_result_billable_flag        => null,
10606    x_preparer_id                 => null,
10607    x_project_id                  => l_project_id,
10608    x_document_type_code		 => null,
10609    x_blanket_po_header_id	 => null,
10610    x_source_type_code		 => null,
10611    x_source_organization_id	 => null,
10612    x_source_subinventory	 => null,
10613    x_task_id                     => l_task_id,
10614    x_deliver_to_person_id        => null,
10615    x_type_lookup_code            => null,
10616    x_suggested_vendor_id         => null,
10617    x_wip_entity_id               => null,
10618    x_wip_entity_type             => null,
10619    x_wip_line_id                 => null,
10620    x_wip_repetitive_schedule_id  => null,
10621    x_wip_operation_seq_num       => null,
10622    x_wip_resource_seq_num        => null,
10623    x_po_encumberance_flag        => null,
10624    x_gl_encumbered_date          => null,
10625    WF_itemkey		  => l_WF_itemkey, -- because of changes due to WF synch mode this input parameter is not used.
10626    x_new_combination	  => l_new_combination,
10627 
10628    header_att1  => null,
10629    header_att2  => null,
10630    header_att3  => null,
10631    header_att4  => null,
10632    header_att5  => null,
10633    header_att6  => null,
10634    header_att7  => null,
10635    header_att8  => null,
10636    header_att9  => null,
10637    header_att10 => null,
10638    header_att11 => null,
10639    header_att12 => null,
10640    header_att13 => null,
10641    header_att14 => null,
10642    header_att15 => null,
10643 
10644    line_att1   => null,
10645    line_att2   => null,
10646    line_att3   => null,
10647    line_att4   => null,
10648    line_att5   => null,
10649    line_att6   => null,
10650    line_att7   => null,
10651    line_att8   => null,
10652    line_att9   => null,
10653    line_att10  => null,
10654    line_att11  => null,
10655    line_att12  => null,
10656    line_att13  => null,
10657    line_att14  => null,
10658    line_att15  => null,
10659 
10660    distribution_att1   => null,
10661    distribution_att2   => null,
10662    distribution_att3   => null,
10663    distribution_att4   => null,
10664    distribution_att5   => null,
10665    distribution_att6   => null,
10666    distribution_att7   => null,
10667    distribution_att8   => null,
10668    distribution_att9   => null,
10669    distribution_att10  => null,
10670    distribution_att11  => null,
10671    distribution_att12  => null,
10672    distribution_att13  => null,
10673    distribution_att14  => null,
10674    distribution_att15  => null,
10675 
10676    FB_ERROR_MSG               => l_FB_ERROR_MSG,
10677    x_award_id	              => l_award_id,
10678    x_suggested_vendor_site_id => null,
10679    p_unit_price               => null,
10680    p_blanket_po_line_num      => null);
10681    --p_misc_loa	              => null);
10682 
10683    IF(x_return)
10684    THEN
10685    	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Returned status on calling PO_REQ_WF_BUILD_ACCOUNT_INIT.start_workflow - ' || 'True');
10686    ELSE
10687    	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Returned status on calling PO_REQ_WF_BUILD_ACCOUNT_INIT.start_workflow - ' || 'FALSE');
10688    END IF;
10689 
10690    x_ccid := l_code_combination_id;
10691    x_conc_segment_values := l_charge_account_flex;
10692    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_code_combination_id = ' || x_ccid);
10693    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_budget_account_id = ' || l_budget_account_id );
10694    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_variance_account_id = ' || l_variance_account_id);
10695    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_charge_account_flex = ' || x_conc_segment_values);
10696    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_budget_account_flex = ' || l_budget_account_flex);
10697    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_accrual_account_flex = ' || l_accrual_account_flex);
10698    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_variance_account_flex = ' || l_variance_account_flex);
10699    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_charge_account_desc = ' || l_charge_account_desc);
10700    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_budget_account_desc = ' || l_budget_account_desc);
10701    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_accrual_account_desc = ' || l_accrual_account_desc);
10702    logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'l_variance_account_desc = ' || l_variance_account_desc);
10703 
10704 
10705 
10706    if(isGrantsEnabled AND (l_award_id is not null))
10707     THEN
10708 	logMessage(FND_LOG.LEVEL_STATEMENT, G_PKG_NAME, 'Calling GMS_POR_API.Account_Generator_ADL in REMOVE mode');
10709       GMS_POR_API.Account_Generator_ADL
10710       (
10711          X_project_id	=> l_project_id,
10712          X_task_id	=> l_task_id,
10713          X_award_id	=> l_award_id,
10714          X_event	=> 'REMOVE',
10715          X_award_set_id => l_gms_award_set_id,  --should not be null
10716          X_status	=> l_gms_status );      -- null
10717    end if;
10718 
10719 
10720    --get the decoded fnd error message
10721    if (l_fb_error_msg is not null) then
10722       fnd_message.set_encoded(l_fb_error_msg);
10723       l_fb_error_msg := fnd_message.get;
10724    end if;
10725 
10726 
10727    WF_ENGINE_UTIL.CLEARCACHE;
10728    WF_ACTIVITY.CLEARCACHE;
10729    WF_ITEM_ACTIVITY_STATUS.CLEARCACHE;
10730    WF_ITEM.CLEARCACHE;
10731    WF_PROCESS_ACTIVITY.CLEARCACHE;
10732 
10733    --temp_proc('x_return - ' || x_return);
10734 
10735   EXCEPTION
10736 
10737     WHEN OTHERS THEN
10738 	x_return_status := FND_API.G_RET_STS_ERROR;
10739       logMessage(FND_LOG.LEVEL_ERROR, G_PKG_NAME, sqlerrm);
10740       FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data  => x_msg_data);
10741       RAISE;
10742 
10743   END GENERATE_CCID_FOR_PROJECTS;
10744 
10745 
10746 
10747 END LNS_DISTRIBUTIONS_PUB;