DBA Data[Home] [Help]

PACKAGE BODY: APPS.IEX_UTILITIES

Source


1 PACKAGE BODY IEX_UTILITIES AS
2 /* $Header: iexvutlb.pls 120.61.12020000.7 2013/02/20 19:51:21 ehuh ship $ */
3 
4   G_PKG_NAME	    CONSTANT VARCHAR2(30) := 'IEX_UTILITIES';
5   G_FILE_NAME     CONSTANT VARCHAR2(12) := 'iexvutlb.pls';
6   G_APPL_ID       NUMBER;
7   G_LOGIN_ID      NUMBER;
8   G_PROGRAM_ID    NUMBER;
9   G_USER_ID       NUMBER;
10   G_REQUEST_ID    NUMBER;
11 
12   PG_DEBUG NUMBER(2);
13   --Added by schekuri for bug#4368394 on 30-NOV-2005
14   G_VIEW_BY_LEVEL VARCHAR2(20);
15   -- start of bug 15933013
16 Function acct_total_acctd_amt(
17           p_cust_account_id     IN  number
18          ,p_org_id              IN  number
19          ,p_correspondence_date IN DATE  DEFAULT sysdate
20          ,p_grace_days          IN number  DEFAULT 0
21          ,p_dun_disputed_items  IN VARCHAR2  DEFAULT 'N'
22          )return number ;
23 
24 Function billto_total_acctd_amt(
25           p_site_use_id         IN  number
26          ,p_org_id              IN  number
27          ,p_correspondence_date IN DATE  DEFAULT sysdate
28          ,p_grace_days          IN number  DEFAULT 0
29          ,p_include_dis_items   IN VARCHAR2  DEFAULT 'N'
30          )return number;
31 
32 Procedure  acct_prf_amt(p_cust_account_id in number
33            , p_org_id in number
34            , x_min_currency_code          OUT NOCOPY varchar2
35            , x_min_dun_amount             OUT NOCOPY number
36            , x_min_dun_invoice_amount     OUT NOCOPY number   );
37 
38 Procedure  billto_prf_amt(p_site_use_id in number
39            , p_org_id in number
40            , x_min_currency_code      OUT NOCOPY varchar2
41            , x_min_dun_amount         OUT NOCOPY number
42            , x_min_dun_invoice_amount OUT NOCOPY number);
43 
44 Procedure acc_min_dunn_amt (p_cust_account_id        in number
45            , p_invoice_currency_code  in varchar2
46            , x_min_dun_amount         OUT NOCOPY number
47            , x_min_dun_invoice_amount OUT NOCOPY number);
48 
49 Function acc_tot_amt_due_rem(p_cust_account_id in number, p_invoice_currency_code in varchar2 -- for 3rd case
50            ,  p_min_dun_invoice_amount in number,p_org_id in number
51            ,  p_correspondence_date date,  p_grace_days in number
52            ,  p_include_dis_items varchar2)return number;
53 
54 Procedure billto_min_dunn_amt (p_site_use_id  in number
55            , p_invoice_currency_code in varchar2
56            , x_min_dun_amount    OUT NOCOPY number
57            , x_min_dun_invoice_amount OUT NOCOPY number);
58 
59 Function billto_tot_amt_due_rem (p_site_use_id number
60            , p_invoice_currency_code varchar2 ,p_min_dun_invoice_amount number
61            , p_org_id number, p_correspondence_date date
62            , p_grace_days number, p_include_dis_items varchar2)Return number;
63 
64 Function  amount_account(p_cust_account_id in number, p_org_id in number
65          , p_correspondence_date date
66          , p_grace_days in number, p_dun_disputed_items in varchar2
67          , p_min_currency_code in varchar2
68          , p_min_dun_amount in number,p_min_dun_invoice_amount in number)return number;
69 
70 Function amount_billto(p_site_use_id in number,p_org_id in number
71          , p_correspondence_date in date
72          , p_grace_days in number, p_dun_disputed_items in varchar2
73          , p_min_currency_code in varchar2, p_min_dun_amount in number
74          , p_min_dun_invoice_amount in number)return number;
75 -- end of bug 15933013
76 
77 -- start bug 7269278
78 Function Get_Manager_role(p_user_id in number) return varchar2 is
79 
80   l_manager varchar2(1) :=  'N';
81 
82   Cursor get_manager_role_c(l_user_id number) is
83      select nvl(rol.manager_flag,'N') manager_role
84        from jtf_rs_role_relations rel, jtf_rs_roles_b rol,jtf_rs_resource_extns ext
85       where rel.role_resource_id = ext.resource_id
86         and rol.role_id = rel.role_id
87         and rol.active_flag = 'Y'
88         and rol.role_code = 'IEX_MANAGER'
89         and rol.role_type_code = 'COLLECTIONS'
90         and (trunc(nvl(rel.start_date_active,sysdate)) <= trunc(sysdate) and trunc(nvl(rel.end_date_active,sysdate+1)) >= trunc(sysdate))
91         and ext.user_id =  nvl(l_user_id,0);
92 
93   begin
94 
95     Open get_manager_role_c(p_user_id);
96     Fetch get_manager_role_c into l_manager;
97     return l_manager;
98     Close get_manager_role_c;
99 
100    exception
101      when others then
102          iex_debug_pub.logmessage ('Exception from Get_Manage_Role  = ' ||SQLERRM||SQLCODE);
103          return l_manager;
104 
105 End Get_Manager_role;
106 -- end bug 7269278
107 
108 Function Delete_delinquncies(p_transaction_id number) return varchar2 is
109  delete_flag varchar2(1) :=  'N';
110 
111 begin
112 
113  Delete from iex_delinquencies_all where transaction_id = p_transaction_id;
114 delete_flag := 'Y';
115 commit;
116  return delete_flag;
117 
118 exception
119      when others then
120          iex_debug_pub.logmessage ('Exception from Get_Manage_Role  = ' ||SQLERRM||SQLCODE);
121          return delete_flag;
122 
123 End Delete_delinquncies;
124 
125 PROCEDURE ACCT_BALANCE
126       (p_api_version      IN  NUMBER := 1.0,
127        p_init_msg_list    IN  VARCHAR2,
128        p_commit           IN  VARCHAR2,
129        p_validation_level IN  NUMBER,
130        x_return_status    OUT NOCOPY VARCHAR2,
131        x_msg_count        OUT NOCOPY NUMBER,
132        x_msg_data         OUT NOCOPY VARCHAR2,
133 	   p_cust_acct_id     IN  Number,
134 	   x_balance          OUT NOCOPY Number)
135   IS
136     l_api_version     CONSTANT   NUMBER := 1.0;
137     l_api_name        CONSTANT   VARCHAR2(30) := 'Acct_Balance';
138     l_return_status   VARCHAR2(1);
139     l_msg_count       NUMBER;
140     l_msg_data        VARCHAR2(32767);
141 
142     amount  Number;
143     total   Number;
144 
145   BEGIN
146     SAVEPOINT	Acct_Balance_Pvt;
147 
148     amount    := 0;
149     total     := 0;
150     -- Standard call to check for call compatibility.
151     IF NOT FND_API.Compatible_API_Call (l_api_version,
152                                         p_api_version,
153                                         l_api_name,
154                                         G_PKG_NAME)    THEN
155 		RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
156     END IF;
157 
158 	-- Check p_init_msg_list
159     IF FND_API.to_Boolean( p_init_msg_list ) THEN
160       FND_MSG_PUB.initialize;
161     END IF;
162 
163     x_return_status := FND_API.G_RET_STS_SUCCESS;
164 
165 	SELECT nvl( SUM (acctd_amount_due_remaining), 0) AMOUNT
166 	into Amount
167 	FROM AR_PAYMENT_SCHEDULES
168 	WHERE customer_id = p_cust_acct_id
169 	AND customer_id+0 = p_cust_acct_id
170 	AND   class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP')
171 	AND   status = 'OP'	;
172 
173 	total := amount ;
174 
175 	SELECT nvl(SUM (acctd_amount_due_remaining), 0) AMOUNT
176 	into	amount
177 	FROM AR_PAYMENT_SCHEDULES
178 	WHERE customer_id = p_cust_acct_id
179 	AND customer_id+0 = p_cust_acct_id
180 	AND class = 'PMT'
181 	AND status = 'OP'
182 	AND acctd_amount_due_remaining <> 0;
183 
184 	--total := total - amount ;
185 	total := total + amount ;
186 
187 
188 	SELECT nvl(SUM (acctd_amount_due_remaining), 0) AMOUNT
189 	into amount
190 	FROM AR_PAYMENT_SCHEDULES
191 	WHERE customer_id = p_cust_acct_id
192 	AND customer_id+0 = p_cust_acct_id
193 	AND class = 'CM'
194 	AND status = 'OP';
195 
196 	--total := total - amount ;
197 	total := total + amount ;
198 	x_balance := total ;
199 
200 	-- Standard check of p_commit
201 	IF FND_API.To_Boolean(p_commit) THEN
202 		COMMIT WORK;
203 	END IF;
204 
205 	-- Standard call to get message count and if count is 1, get message info
206 	FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
207 
208   EXCEPTION
209 	WHEN FND_API.G_EXC_ERROR THEN
210         ROLLBACK TO Acct_Balance_PVT;
211 		x_return_status := FND_API.G_RET_STS_ERROR;
212 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
213 
214 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
215         ROLLBACK TO Acct_Balance_PVT;
216 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
217 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
218 
219 	WHEN OTHERS THEN
220         ROLLBACK TO Acct_Balance_PVT;
221 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
222 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
223 			FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
224 		END IF;
225 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
226 
227   END Acct_Balance;
228 
229 PROCEDURE Validate_any_id(p_api_version   IN  NUMBER := 1.0,
230                           p_init_msg_list IN  VARCHAR2,
231                           x_msg_count     OUT NOCOPY NUMBER,
232                           x_msg_data      OUT NOCOPY VARCHAR2,
233                           x_return_status OUT NOCOPY VARCHAR2,
234                           p_col_id        IN NUMBER,
235                           p_col_name      IN VARCHAR2,
236                           p_table_name    IN VARCHAR2)
237 IS
238 
239 TYPE refCur IS REF CURSOR;
240 valid_id  refCur;
241 
242     l_return_status VARCHAR2(1);
243     count_id        VARCHAR2(1);
244     l_api_version   CONSTANT NUMBER := p_api_version;
245     l_init_msg_list CONSTANT VARCHAR2(1) := p_init_msg_list;
246     l_api_name      CONSTANT VARCHAR2(20) := 'VALIDATE_ANY_ID';
247     vPlsql          VARCHAR2(2000);
248 
249     -- clchang updated for sql bind var 05/07/2003
250     vstr1           VARCHAR2(100);
251     vstr2           VARCHAR2(100);
252     vstr3           VARCHAR2(100);
253     vstr4           VARCHAR2(100);
254     vstr5           VARCHAR2(100);
255     vstr6           VARCHAR2(100);
256     vstr7           VARCHAR2(100);
257 
258 BEGIN
259 
260       -- Standard Start of API savepoint
261       SAVEPOINT Validate_any_id_PVT;
262 
263       -- Initialize API return status to SUCCESS
264       x_return_status := FND_API.G_RET_STS_SUCCESS;
265 
266     vstr1            := ' Select ''X'' ';
267     vstr2            := ' From ';
268     vstr3            := ' Where exists ';
269     vstr4            := '     (Select ' ;
270     vstr5            := ' From ';
271     vstr6            := '       Where ' ;
272     vstr7            := ' = :a1)';
273 
274 
275       -- Standard call to check for call compatibility.
276       IF NOT FND_API.Compatible_API_Call (l_api_version,
277                                           p_api_version,
278                                           l_api_name,
279                                           G_PKG_NAME)
280       THEN
281           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
282       END IF;
283 
284       -- Initialize message list if p_init_msg_list is set to TRUE.
285       IF FND_API.to_Boolean(p_init_msg_list)
286       THEN
287           FND_MSG_PUB.initialize;
288       END IF;
289 
290       -- API body
291        -- clchang updated for sql bind var 05/07/2003
292        vPlsql := vstr1 ||
293                  vstr2 || p_table_name ||
294                  vstr3 ||
295                  vstr4 || p_col_name ||
296                  vstr5 || p_table_name ||
297                  vstr6 || p_col_name || vstr7;
298      WriteLog('iexvutlb:validateid:plsql='||vPlsql);
299        /*
300        vPlsql :=
301              ' Select ''X'' ' ||
302              ' From ' || p_table_name || ' ' ||
303              ' Where exists ' ||
304              '     (Select ' || p_col_name ||
305              '     From ' || p_table_name ||
306              '     Where ' || p_col_name || ' = :a1)';
307              --dbms_output.put_line('plsql is ' || vPLSQL);
308        */
309        -- end
310         open valid_id for
311             vPlsql
312             using p_col_id;
313         FETCH valid_id INTO count_id;
314 
315      WriteLog('iexvutlb:validateid:count_id='||count_id);
316 
317         if valid_id%FOUND then
318             --dbms_output.put_line('FOUND!!');
319             WriteLog('iexvutlb:validateid:Found!');
320             l_return_status := FND_API.G_RET_STS_SUCCESS;
321         else
322             --dbms_output.put_line('NOT FOUND!!');
323             WriteLog('iexvutlb:validateid:NotFound!');
324             l_return_status := FND_API.G_RET_STS_ERROR;
325         end if;
326         CLOSE valid_id;
327 
328     x_return_status := l_return_status;
329 
330   EXCEPTION
331 	WHEN FND_API.G_EXC_ERROR THEN
332         ROLLBACK TO Validate_any_id_PVT;
333         x_return_status := FND_API.G_RET_STS_ERROR;
334 	FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
335 
336 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
337         ROLLBACK TO Validate_any_id_PVT;
338 	x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
339 	FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
340 
341 	WHEN OTHERS THEN
342         ROLLBACK TO Validate_any_id_PVT;
343 	x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
344 	IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
345 		FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
346 	END IF;
347 	FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
348 
349 END Validate_any_id;
350 
351 PROCEDURE Validate_any_varchar(p_api_version   IN  NUMBER := 1.0,
352                                p_init_msg_list IN  VARCHAR2,
353                                x_msg_count     OUT NOCOPY NUMBER,
354                                x_msg_data      OUT NOCOPY VARCHAR2,
355                                x_return_status OUT NOCOPY VARCHAR2,
356                                p_col_value     IN  VARCHAR2,
357                                p_col_name      IN  VARCHAR2,
358                                p_table_name    IN  VARCHAR2)
359 IS
360 
361 TYPE refCur IS REF CURSOR;
362 valid_id  refCur;
363 
364     l_return_status VARCHAR2(1);
365     count_id        VARCHAR2(1);
366     l_api_version   CONSTANT NUMBER := p_api_version;
367     l_init_msg_list CONSTANT VARCHAR2(1) := p_init_msg_list;
368     l_api_name      CONSTANT VARCHAR2(20) := 'VALIDATE_ANY_VARCHAR';
369 
370     l_col_value varchar2(240);
371     vPLSQL varchar2(1000);
372 
373     -- clchang updated for sql bind var 05/07/2003
374     vstr1           VARCHAR2(100);
375     vstr2           VARCHAR2(100);
376     vstr3           VARCHAR2(100);
377     vstr4           VARCHAR2(100);
378     vstr5           VARCHAR2(100);
379     vstr6           VARCHAR2(100);
380     vstr7           VARCHAR2(100);
381 
382 BEGIN
383 
384       -- Standard Start of API savepoint
385       SAVEPOINT Validate_any_varchar_PVT;
386 
387       -- Initialize API return status to SUCCESS
388       x_return_status := FND_API.G_RET_STS_SUCCESS;
389 
390 
391     vstr1            := ' Select ''X'' ';
392     vstr2            := ' From ';
393     vstr3            := ' Where exists ';
394     vstr4            := '     (Select ' ;
395     vstr5            := ' From ';
396     vstr6            := '       Where ' ;
397     vstr7            := ' = :a1)';
398 
399       -- Standard call to check for call compatibility.
400       IF NOT FND_API.Compatible_API_Call (l_api_version,
401                                           p_api_version,
402                                           l_api_name,
403                                           G_PKG_NAME)
404       THEN
405           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
406       END IF;
407 
408       -- Initialize message list if p_init_msg_list is set to TRUE.
409       IF FND_API.to_Boolean(p_init_msg_list)
410       THEN
411           FND_MSG_PUB.initialize;
412       END IF;
413 
414       -- API body
415         --dbms_output.put_line('col is ' || p_col_value);
416        -- clchang updated for sql bind var 05/07/2003
417        vPLSQL := vstr1 ||
418                  vstr2 || p_table_name ||
419                  vstr3 ||
420                  vstr4 || p_col_name ||
421                  vstr5 || p_table_name ||
422                  vstr6 || p_col_name || vstr7;
423        /*
424         vPLSQL := ' Select ''X''   ' ||
425                   ' From ' || p_table_name ||
426                   ' Where exists   ' ||
427                   '   (Select ' || p_col_name ||
428                   '    From ' || p_table_name ||
429                   '    Where ' || p_col_name || ' = :a1)';
430        */
431         --dbms_output.put_line('plsql is ' || vPLSQL);
432 
433         OPEN valid_id FOR
434             vPLSQL
435             using p_col_value;
436         FETCH valid_id INTO count_id;
437 
438         if valid_id%FOUND then
439             --dbms_output.put_line('FOUND!!');
440             l_return_status := FND_API.G_RET_STS_SUCCESS;
441         else
442             --dbms_output.put_line('NOT FOUND!!');
443             l_return_status := FND_API.G_RET_STS_ERROR;
444         end if;
445         CLOSE valid_id;
446 
447     x_return_status := l_return_status;
448 
449   EXCEPTION
450     WHEN FND_API.G_EXC_ERROR THEN
451         ROLLBACK TO Validate_any_varchar_PVT;
452         x_return_status := FND_API.G_RET_STS_ERROR;
453         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
454 
455     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
456         ROLLBACK TO Validate_any_varchar_PVT;
457         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
458         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
459 
460     WHEN OTHERS THEN
461         ROLLBACK TO Validate_any_varchar_PVT;
462         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
463         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
464             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
465         END IF;
466         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
467 
468 END Validate_any_varchar;
469 
470 PROCEDURE Validate_Lookup_CODE(p_api_version   IN  NUMBER := 1.0,
471                                p_init_msg_list IN  VARCHAR2,
472                                x_msg_count     OUT NOCOPY NUMBER,
473                                x_msg_data      OUT NOCOPY VARCHAR2,
474                                x_return_status OUT NOCOPY VARCHAR2,
475                                p_lookup_type   IN  VARCHAR2,
476                                p_lookup_code   IN  VARCHAR2,
477                                p_lookup_view   IN VARCHAR2)
478 IS
479 
480 TYPE refCur IS REF CURSOR;
481 valid_id  refCur;
482 
483     l_return_status VARCHAR2(1);
484     count_id        NUMBER       := 0;
485     l_api_version   CONSTANT NUMBER       := p_api_version;
486     l_init_msg_list CONSTANT VARCHAR2(1)  := p_init_msg_list;
487     l_api_name      CONSTANT VARCHAR2(20) := 'VALIDATE_LOOKUP_CODE';
488 
489     l_lookup_code varchar2(30);
490     l_lookup_type varchar2(30);
491     vPLSQL varchar2(1000);
492 
493     -- clchang updated for sql bind var 05/07/2003
494     vstr1    varchar2(1000);
495     vstr2    varchar2(1000);
496     vstr3    varchar2(1000);
497     vstr4    varchar2(1000);
498     vstr5    varchar2(1000);
499 
500 BEGIN
501 
502       -- Standard Start of API savepoint
503       SAVEPOINT Validate_any_varchar_PVT;
504 
505       -- Initialize API return status to SUCCESS
506       x_return_status := FND_API.G_RET_STS_SUCCESS;
507 
508     vstr1     := 'Select Count(LOOKUP_CODE) ';
509     vstr2     := 'From ';
510     vstr3     := 'Where LOOKUP_TYPE = :l_lookup_type ' ;
511     vstr4     := ' AND LOOKUP_CODE = :l_lookup_code ';
512     vstr5     := ' AND ENABLED_FLAG = ''Y''';
513 
514       -- Standard call to check for call compatibility.
515       IF NOT FND_API.Compatible_API_Call (l_api_version,
516                                           p_api_version,
517                                           l_api_name,
518                                           G_PKG_NAME)
519       THEN
520           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
521       END IF;
522 
523       -- Initialize message list if p_init_msg_list is set to TRUE.
524       IF FND_API.to_Boolean(p_init_msg_list)
525       THEN
526           FND_MSG_PUB.initialize;
527       END IF;
528 
529       -- API body
530       l_lookup_code := '''' || p_lookup_code || '''';
531       l_lookup_type := '''' || p_lookup_type || '''';
532 
533       WriteLog('iexvutlb:validatelookup:lookup_code='||l_lookup_code);
534       WriteLog('iexvutlb:validatelookup:lookup_type='||l_lookup_type);
535 
536         --dbms_output.put_line('col is ' || l_lookup_code);
537         -- clchang updated for sql bind var 05/07/2003
538         vPLSQL := vstr1 ||
539                   vstr2 || p_lookup_view || ' ' ||
540                   vstr3 ||
541                   vstr4 ||
542                   vstr5;
543        /*
544         vPLSQL :=
545               'Select Count(LOOKUP_CODE) '  ||
546               'From ' || p_lookup_view || ' ' ||
547               'Where LOOKUP_TYPE = ' || l_lookup_type  || ' AND ' ||
548               'LOOKUP_CODE = ' || l_lookup_code || ' AND ' ||
549               'ENABLED_FLAG = ''Y''';
550        */
551         --
552 
553         --dbms_output.put_line('plsql is ' || vPLSQL);
554        /*
555         OPEN valid_id FOR
556             vPLSQL;
557        */
558 
559 
560        select count(lookup_code)
561          into count_id
562          from iex_lookups_v
563         where lookup_type = p_lookup_type
564           and lookup_code = p_lookup_code
565           and enabled_flag = 'Y';
566 
567       /*
568         open valid_id for
569             vPlsql
570             using l_lookup_type, l_lookup_code;
571 
572         FETCH valid_id INTO count_id;
573 
574         CLOSE valid_id ;
575       */
576 
577      WriteLog('iexvutlb:validatelookup:count_id='||count_id);
578 
579         IF (count_id > 0) then
580                 l_return_status := FND_API.G_RET_STS_SUCCESS;
581         ELSE
582                 l_return_status := FND_API.G_RET_STS_ERROR;
583         END IF ;
584     x_return_status := l_return_status;
585 
586   EXCEPTION
587     WHEN FND_API.G_EXC_ERROR THEN
588         ROLLBACK TO Validate_any_varchar_PVT;
589         x_return_status := FND_API.G_RET_STS_ERROR;
590         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
591 
592     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
593         ROLLBACK TO Validate_any_varchar_PVT;
594         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
595         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
596 
597     WHEN OTHERS THEN
598         ROLLBACK TO Validate_any_varchar_PVT;
599         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
600         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
601             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
602         END IF;
603         FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
604 
605 END Validate_LOOKUP_CODE;
606 
607 -- added by jypark 03052002
608 --Begin bug#5373412 schekuri 10-Jul-2006
609 --Removed the following procedures and added a single consolidate procedure get_assigned_collector
610 /*PROCEDURE get_access_resources(p_api_version      IN  NUMBER := 1.0,
611                                p_init_msg_list    IN  VARCHAR2,
612                                p_commit           IN  VARCHAR2,
613                                p_validation_level IN  NUMBER,
614                                x_msg_count        OUT NOCOPY NUMBER,
615                                x_msg_data         OUT NOCOPY VARCHAR2,
616                                x_return_status    OUT NOCOPY VARCHAR2,
617                                p_party_id         IN  VARCHAR2,
618                                x_resource_tab     OUT NOCOPY resource_tab_type) IS
619 --Territory Assignment Changes
620   CURSOR c_get_person IS
621     SELECT DISTINCT ac.employee_id
622     FROM  hz_customer_profiles hp,ar_collectors ac
623     WHERE  hp.collector_id = ac.collector_id
624     AND    ac.employee_id is not null
625     AND    hp.party_id = p_party_id;
626 
627   CURSOR c_get_resource(p_person_id NUMBER) IS
628     SELECT resource_id, source_id, user_id, source_name, user_name
629 	FROM jtf_rs_resource_extns
630 	WHERE source_id = p_person_id;
631 	--AND start_date_active <= sysdate
632 	--AND end_date_active > sysdate;
633 
634   l_resource_row c_get_resource%rowtype;
635   l_api_version   CONSTANT NUMBER        := p_api_version;
636   l_api_name      CONSTANT VARCHAR2(100) := 'GET_ACCESS_RESOURCES';
637   l_init_msg_list CONSTANT VARCHAR2(1)   := p_init_msg_list;
638   l_return_status VARCHAR2(1);
639   l_msg_count     NUMBER;
640   l_msg_data      VARCHAR2(32767);
641   idx             NUMBER := 0;
642 BEGIN
643 
644    IF PG_DEBUG < 10  THEN
645      iex_debug_pub.logmessage ('**** BEGIN get_access_resources ************');
646      iex_debug_pub.logmessage ('get_person cursor = ' ||
647         'SELECT DISTINCT hp.employee_id
648          FROM  hz_customer_profiles hp,ar_collectors ac
649          WHERE m.person_id = ac.employee_id
650          AND  hp.collector_id = ac.collector_id
651          and ac.employee_id is not null
652          AND hp.party_id = p_party_id ' ||
653         'SELECT resource_id, source_id, user_id, source_name, user_name ' ||
654 	'FROM jtf_rs_resource_extns ' ||
655 	'WHERE source_id = p_person_id');
656    END IF;
657   SAVEPOINT	Access_Resources_Pvt;
658 
659   -- Standard call to check for call compatibility.
660   IF NOT FND_API.Compatible_API_Call (l_api_version,
661                                       p_api_version,
662                                       l_api_name,
663                                       G_PKG_NAME)    THEN
664 	RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
665   END IF;
666 
667   -- Check p_init_msg_list
668   IF FND_API.to_Boolean( p_init_msg_list ) THEN
669     FND_MSG_PUB.initialize;
670   END IF;
671 
672   x_return_status := FND_API.G_RET_STS_SUCCESS;
673 
674   FOR r_person IN c_get_person LOOP
675      IF PG_DEBUG < 10  THEN
676        iex_debug_pub.logmessage ('employee_id = ' || r_person.employee_id);
677      END IF;
678     OPEN c_get_resource(r_person.employee_id);
679 	FETCH c_get_resource INTO l_resource_row;
680 	IF c_get_resource%FOUND THEN
681 	  idx := idx + 1;
682         IF PG_DEBUG < 10  THEN
683            iex_debug_pub.logmessage ('idx= ' || idx);
684            iex_debug_pub.logmessage ('l_resource_row.resource_id = ' || l_resource_row.resource_id);
685            iex_debug_pub.logmessage ('l_resource_row.user_name = ' || l_resource_row.user_name);
686            iex_debug_pub.logmessage ('l_resource_row.source_name = ' || l_resource_row.source_name);
687         END IF;
688 	  x_resource_tab(idx).resource_id := l_resource_row.resource_id;
689 	  x_resource_tab(idx).user_id := l_resource_row.user_id;
690 	  x_resource_tab(idx).person_id := l_resource_row.source_id;
691 	  x_resource_tab(idx).user_name := l_resource_row.user_name;
692 	  x_resource_tab(idx).person_name := l_resource_row.source_name;
693 	END IF;
694 	CLOSE c_get_resource;
695   End LOOP;
696 
697   -- Standard check of p_commit
698   IF FND_API.To_Boolean(p_commit) THEN
699    COMMIT WORK;
700   END IF;
701 
702   -- Standard call to get message count and if count is 1, get message info
703   FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
704 
705      IF PG_DEBUG < 10  THEN
706        iex_debug_pub.logmessage ('**** END get_access_resources ************');
707      END IF;
708 
709   EXCEPTION
710 	WHEN FND_API.G_EXC_ERROR THEN
711         ROLLBACK TO Access_Resources_Pvt;
712 		x_return_status := FND_API.G_RET_STS_ERROR;
713 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
714 
715 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
716         ROLLBACK TO Access_Resources_Pvt;
717 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
718 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
719 
720 	WHEN OTHERS THEN
721         ROLLBACK TO Access_Resources_Pvt;
722 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
723 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
724 			FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
725 		END IF;
726 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
727 
728 END get_access_resources;
729 
730 PROCEDURE get_assign_resources(p_api_version      IN  NUMBER := 1.0,
731                                p_init_msg_list    IN  VARCHAR2,
732                                p_commit           IN  VARCHAR2,
733                                p_validation_level IN  NUMBER,
734                                x_msg_count        OUT NOCOPY NUMBER,
735                                x_msg_data         OUT NOCOPY VARCHAR2,
736                                x_return_status    OUT NOCOPY VARCHAR2,
737                                p_party_id         IN  VARCHAR2,
738                                x_resource_tab     OUT NOCOPY resource_tab_type) IS
739 /* cursor rewritten to avoid full table scan iex_strategy_work_items
740   CURSOR c_get_person IS
741     SELECT acc.person_id, acc.salesforce_id, count(work_item_id)
742     FROM  as_accesses acc, jtf_rs_resource_extns rs, iex_strategy_work_items wi
743     WHERE acc.customer_id = p_party_id and rs.resource_id = acc.salesforce_id
744       and acc.salesforce_id = wi.resource_id(+)
745       and wi.status_code(+) = 'OPEN'
746       and acc.sales_lead_id is null and acc.lead_id is null
747       and rs.user_id is not null
748       group by acc.salesforce_id, acc.person_id ORDER BY 3;
749 */
750 /*
751 --Territory Assignment Changes
752   CURSOR c_get_person IS
753    (
754     SELECT ac.employee_id, ac.resource_id, count(work_item_id)
755     FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_strategy_work_items wi,
756           ar_collectors ac
757     WHERE hp.party_id      = p_party_id
758       and hp.cust_account_id = -1
759       and rs.resource_id   = ac.resource_id
760       and hp.collector_id  = ac.collector_id
761       and ac.resource_id   = wi.resource_id
762       and wi.status_code   = 'OPEN'
763       and rs.user_id is not null
764       and    ac.employee_id is not null
765       group by ac.resource_id, ac.employee_id
766     union all
767     SELECT ac.employee_id, ac.resource_id, 0
768     FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs,ar_collectors ac
769     WHERE hp.party_id       = p_party_id
770       and hp.cust_account_id = -1
771       and rs.resource_id    = ac.resource_id
772       and hp.collector_id   = ac.collector_id
773       and rs.user_id is not null and
774       not exists (select null from iex_strategy_work_items wi
775             where ac.resource_id = wi.resource_id
776       and wi.status_code = 'OPEN')
777       and    ac.employee_id is not null
778        group by ac.resource_id, ac.employee_id
779       ) order by 3;
780 */
781 
782 /* We use hz_customer_profiles and
783    Load balancing when the assigned with Group Resource
784 */
785 /*cursor c_get_person IS
786 SELECT ac.employee_id, ac.resource_id, 0
787 FROM  hz_customer_profiles hp, ar_collectors ac
788 WHERE hp.party_id = p_party_id
789   and hp.cust_account_id = -1
790   and hp.collector_id  = ac.collector_id
791   and ac.resource_type = 'RS_RESOURCE'
792   -- Bug4483896. Fixed by lkkumar. Check for inactive_date. Start.
793   and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
794   and nvl(ac.status,'A') = 'A'
795   -- Bug4483896. Fixed by lkkumar. Check for inactive_date. End.
796 union all
797 ( SELECT jtg.person_id, jtg.resource_id, count(work_item_id)
798     FROM  hz_customer_profiles hp,  iex_strategy_work_items wi,
799           ar_collectors ac, jtf_rs_group_members jtg
800     WHERE hp.party_id  = P_PARTY_ID
801       and hp.cust_account_id = -1
802       and hp.collector_id  = ac.collector_id
803       and ac.resource_type = 'RS_GROUP'
804       and ac.resource_id  = jtg.group_id
805       and jtg.resource_id = wi.resource_id
806       and wi.status_code   = 'OPEN'
807       -- Bug4483896. Fixed by lkkumar. Check for inactive_date. Start.
808       and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
809       and nvl(ac.status,'A') = 'A'
810       group by jtg.resource_id, jtg.person_id
811 UNION ALL
812     SELECT jtg.person_id, jtg.resource_id, 0
813     FROM  hz_customer_profiles hp, ar_collectors ac,
814       jtf_rs_group_members jtg
815     WHERE hp.party_id  = p_party_id
816       and hp.cust_account_id = -1
817       and hp.collector_id   = ac.collector_id
818       and ac.resource_type = 'RS_GROUP'
819       and ac.resource_id = jtg.group_id
820       and not exists (select null from iex_strategy_work_items wi
821             where jtg.resource_id = wi.resource_id
822       and wi.status_code = 'OPEN')
823       -- Bug4483896. Fixed by lkkumar. Check for inactive_date. Start.
824       and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
825       and nvl(ac.status,'A') = 'A'
826       -- Bug4483896. Fixed by lkkumar. Check for inactive_date. End.
827        group by jtg.resource_id, jtg.person_id
828       ) order by 3;
829 
830 /*
831   CURSOR c_get_person IS
832     SELECT DISTINCT person_id, salesforce_id
833     FROM  as_accesses acc
834     WHERE acc.customer_id = p_party_id;
835 */
836 
837  /* l_api_version   CONSTANT NUMBER       := p_api_version;
838   l_api_name CONSTANT VARCHAR2(100) := 'GET_ASSIGN_RESOURCES';
839   l_init_msg_list VARCHAR2(1);
840   l_return_status VARCHAR2(1);
841   l_msg_count NUMBER;
842   l_msg_data VARCHAR2(32767);
843   idx NUMBER := 0;
844 BEGIN
845 
846      iex_debug_pub.logmessage ('**** BEGIN on all
847       get_access_resources ************');
848   l_init_msg_list := p_init_msg_list;
849      iex_debug_pub.logmessage ('get_person cursor = ' ||
850      'SELECT ac.employee_id, ac.resource_id, count(work_item_id) ' ||
851      ' FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_strategy_work_items wi, '||
852      ' ar_collectors ac ' ||
853      ' WHERE hp.party_id      = p_party_id '    ||
854      ' and rs.resource_id   = ac.resource_id'   ||
855      ' and hp.collector_id  = ac.collector_id'  ||
856      ' and ac.resource_id   = wi.resource_id'   ||
857      ' and wi.status_code   = OPEN '   ||
858      ' and rs.user_id is not null'||
859      ' group by ac.resource_id, ac.employee_id ');
860 
861   SAVEPOINT	get_assign_resources;
862 
863   -- Standard call to check for call compatibility.
864   IF NOT FND_API.Compatible_API_Call (l_api_version,
865                                       p_api_version,
866                                       l_api_name,
867                                       G_PKG_NAME)    THEN
868 	RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
869   END IF;
870 
871   -- Check p_init_msg_list
872   IF FND_API.to_Boolean( p_init_msg_list ) THEN
873     FND_MSG_PUB.initialize;
874   END IF;
875 
876   x_return_status := FND_API.G_RET_STS_SUCCESS;
877 
878   FOR r_person IN c_get_person LOOP
879      idx := idx + 1;
880      iex_debug_pub.logmessage ('idx= ' || idx);
881      iex_debug_pub.logmessage ('r_person.salesforce_id = ' || r_person.resource_id);
882 	  x_resource_tab(idx).resource_id := r_person.resource_id;
883 	  x_resource_tab(idx).person_id := r_person.employee_id;
884   End LOOP;*/
885 
886   --use bulk collect for performance as per kasreeni's request
887   --jsanju 04/13/2004
888   /*
889     OPEN c_get_person ;
890     FETCH c_get_person BULK COLLECT INTO x_resource_tab;
891     CLOSE c_get_person;
892   */
893 
894   /*
895   -- Standard check of p_commit
896   IF FND_API.To_Boolean(p_commit) THEN
897    COMMIT WORK;
898   END IF;
899 
900   -- Standard call to get message count and if count is 1, get message info
901   FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
902 
903      iex_debug_pub.logmessage ('**** END get_access_resources ************');
904 
905   EXCEPTION
906 	WHEN FND_API.G_EXC_ERROR THEN
907         ROLLBACK TO get_assign_resources;
908 		x_return_status := FND_API.G_RET_STS_ERROR;
909 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
910 
911 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
912         ROLLBACK TO get_assign_resources;
913 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
914 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
915 
916 	WHEN OTHERS THEN
917         ROLLBACK TO get_assign_resources;
918 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
919 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
920 			FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
921 		END IF;
922 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
923 
924 END get_assign_resources;
925 
926 PROCEDURE get_assign_account_resources(p_api_version      IN  NUMBER := 1.0,
927                                p_init_msg_list    IN  VARCHAR2,
928                                p_commit           IN  VARCHAR2,
929                                p_validation_level IN  NUMBER,
930                                x_msg_count        OUT NOCOPY NUMBER,
931                                x_msg_data         OUT NOCOPY VARCHAR2,
932                                x_return_status    OUT NOCOPY VARCHAR2,
933                                p_account_id         IN  VARCHAR2,
934                                x_resource_tab     OUT NOCOPY resource_tab_type) IS
935 --Territory Assignment Changes
936 /*  CURSOR c_get_person IS
937    (
938     SELECT ac.employee_id, ac.resource_id, count(work_item_id)
939     FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_strategy_work_items wi,
940           ar_collectors ac
941     WHERE hp.cust_account_id = p_account_id
942       and hp.site_use_id is null
943       and rs.resource_id   = ac.resource_id
944       and hp.collector_id  = ac.collector_id
945       and ac.resource_id   = wi.resource_id
946       and wi.status_code   = 'OPEN'
947       and rs.user_id is not null
948       and    ac.employee_id is not null
949       group by ac.resource_id, ac.employee_id
950     union all
951     SELECT ac.employee_id, ac.resource_id, 0
952     FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs,ar_collectors ac
953     WHERE hp.cust_account_id       = p_account_id
954       and hp.site_use_id is null
955       and rs.resource_id    = ac.resource_id
956       and hp.collector_id   = ac.collector_id
957       and rs.user_id is not null and
958       not exists (select null from iex_strategy_work_items wi
959             where ac.resource_id = wi.resource_id
960       and wi.status_code = 'OPEN')
961       and    ac.employee_id is not null
962        group by ac.resource_id, ac.employee_id
963       ) order by 3;
964 */
965 
966 /* We use hz_customer_profiles and
967    Load balancing when the assigned with Group Resource
968 */
969 /*CURSOR c_get_person IS
970 SELECT ac.employee_id, ac.resource_id, 0
971 FROM  hz_customer_profiles hp, ar_collectors ac
972 WHERE hp.cust_account_id = p_account_id
973   and hp.site_use_id is null
974   and hp.collector_id  = ac.collector_id
975   and ac.resource_type = 'RS_RESOURCE'
976 union all
977 ( SELECT jtg.person_id, jtg.resource_id, count(work_item_id)
978     FROM  hz_customer_profiles hp,  iex_strategy_work_items wi,
979           ar_collectors ac, jtf_rs_group_members jtg
980     WHERE hp.cust_account_id  = p_account_id
981       and hp.site_use_id is NULL
982       and hp.collector_id  = ac.collector_id
983       and ac.resource_type = 'RS_GROUP'
984       and ac.resource_id  = jtg.group_id
985       and jtg.resource_id = wi.resource_id
986       and wi.status_code   = 'OPEN'
987       group by jtg.resource_id, jtg.person_id
988 UNION ALL
989     SELECT jtg.person_id, jtg.resource_id, 0
990     FROM  hz_customer_profiles hp, ar_collectors ac,
991       jtf_rs_group_members jtg
992     WHERE hp.cust_account_id  = p_account_id
993       and hp.site_use_id is null
994       and hp.collector_id   = ac.collector_id
995       and ac.resource_type = 'RS_GROUP'
996       and ac.resource_id = jtg.group_id
997       and not exists (select null from iex_strategy_work_items wi
998             where jtg.resource_id = wi.resource_id
999       and wi.status_code = 'OPEN')
1000        group by jtg.resource_id, jtg.person_id
1001       ) order by 3;*/
1002 
1003 /*
1004   CURSOR c_get_person IS
1005     SELECT DISTINCT person_id, salesforce_id
1006     FROM  as_accesses acc
1007     WHERE acc.customer_id = p_party_id;
1008 */
1009 
1010  /* l_api_version   CONSTANT NUMBER       := p_api_version;
1011   l_api_name CONSTANT VARCHAR2(100) := 'GET_ASSIGN_RESOURCES';
1012   l_init_msg_list VARCHAR2(1);
1013   l_return_status VARCHAR2(1);
1014   l_msg_count NUMBER;
1015   l_msg_data VARCHAR2(32767);
1016   idx NUMBER := 0;
1017 BEGIN
1018 
1019      iex_debug_pub.logmessage ('**** BEGIN on all
1020       get_access_resources ************');
1021   l_init_msg_list := p_init_msg_list;
1022      iex_debug_pub.logmessage ('get_person cursor = ' ||
1023      'SELECT ac.employee_id, ac.resource_id, count(work_item_id) ' ||
1024      ' FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_strategy_work_items wi, '||
1025      ' ar_collectors ac ' ||
1026      ' WHERE hp.party_id      = p_party_id '    ||
1027      ' and rs.resource_id   = ac.resource_id'   ||
1028      ' and hp.collector_id  = ac.collector_id'  ||
1029      ' and ac.resource_id   = wi.resource_id'   ||
1030      ' and wi.status_code   = OPEN '   ||
1031      ' and rs.user_id is not null'||
1032      ' group by ac.resource_id, ac.employee_id ');
1033 
1034   SAVEPOINT	get_assign_account_resources;
1035 
1036   -- Standard call to check for call compatibility.
1037   IF NOT FND_API.Compatible_API_Call (l_api_version,
1038                                       p_api_version,
1039                                       l_api_name,
1040                                       G_PKG_NAME)    THEN
1041 	RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
1042   END IF;
1043 
1044   -- Check p_init_msg_list
1045   IF FND_API.to_Boolean( p_init_msg_list ) THEN
1046     FND_MSG_PUB.initialize;
1047   END IF;
1048 
1049   x_return_status := FND_API.G_RET_STS_SUCCESS;
1050 
1051   FOR r_person IN c_get_person LOOP
1052      idx := idx + 1;
1053      iex_debug_pub.logmessage ('idx= ' || idx);
1054      iex_debug_pub.logmessage ('r_person.salesforce_id = ' || r_person.resource_id);
1055 	  x_resource_tab(idx).resource_id := r_person.resource_id;
1056 	  x_resource_tab(idx).person_id := r_person.employee_id;
1057   End LOOP;*/
1058 
1059   --use bulk collect for performance as per kasreeni's request
1060   --jsanju 04/13/2004
1061   /*
1062     OPEN c_get_person ;
1063     FETCH c_get_person BULK COLLECT INTO x_resource_tab;
1064     CLOSE c_get_person;
1065   */
1066 
1067 
1068   -- Standard check of p_commit
1069  /* IF FND_API.To_Boolean(p_commit) THEN
1070    COMMIT WORK;
1071   END IF;
1072 
1073   -- Standard call to get message count and if count is 1, get message info
1074   FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1075 
1076      iex_debug_pub.logmessage ('**** END get_access_resources ************');
1077 
1078   EXCEPTION
1079 	WHEN FND_API.G_EXC_ERROR THEN
1080         ROLLBACK TO get_assign_account_resources;
1081 		x_return_status := FND_API.G_RET_STS_ERROR;
1082 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1083 
1084 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1085         ROLLBACK TO get_assign_account_resources;
1086 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1087 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1088 
1089 	WHEN OTHERS THEN
1090         ROLLBACK TO get_assign_account_resources;
1091 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1092 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
1093 			FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
1094 		END IF;
1095 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1096 
1097 END get_assign_account_resources;
1098 
1099 PROCEDURE get_case_resources(p_api_version      IN  NUMBER := 1.0,
1100                                p_init_msg_list    IN  VARCHAR2,
1101                                p_commit           IN  VARCHAR2,
1102                                p_validation_level IN  NUMBER,
1103                                x_msg_count        OUT NOCOPY NUMBER,
1104                                x_msg_data         OUT NOCOPY VARCHAR2,
1105                                x_return_status    OUT NOCOPY VARCHAR2,
1106                                p_party_id         IN  VARCHAR2,
1107                                x_resource_tab     OUT NOCOPY resource_tab_type) IS
1108 --Territory Assignment Changes
1109   CURSOR c_get_person IS
1110     SELECT ac.employee_id, ac.resource_id, count(cas_id)
1111     FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_cases_vl wi,ar_collectors ac
1112     WHERE hp.party_id = p_party_id
1113       and rs.resource_id = ac.resource_id
1114       and hp.collector_id = ac.collector_id
1115       and ac.resource_id = wi.owner_resource_id(+)
1116       and rs.user_id is not null
1117       and    ac.employee_id is not null
1118       group by ac.resource_id, ac.employee_id ORDER BY 3;*/
1119 
1120 /*
1121   CURSOR c_get_person IS
1122     SELECT DISTINCT person_id, salesforce_id
1123     FROM  as_accesses acc
1124     WHERE acc.customer_id = p_party_id;
1125 */
1126 
1127 /*  l_api_version   CONSTANT NUMBER       := p_api_version;
1128   l_api_name CONSTANT VARCHAR2(100) := 'GET_CASE_RESOURCES';
1129   l_init_msg_list CONSTANT VARCHAR2(1)  := p_init_msg_list;
1130   l_return_status VARCHAR2(1);
1131   l_msg_count NUMBER;
1132   l_msg_data VARCHAR2(32767);
1133   idx NUMBER := 0;
1134 BEGIN
1135 
1136      iex_debug_pub.logmessage ('**** BEGIN get_case_resources ************');
1137      iex_debug_pub.logmessage ('get_person cursor = ' ||
1138      'SELECT ac.employee_id, ac.resource_id, count(cas_id)
1139       FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_cases_vl wi,ar_collectors ac
1140       WHERE hp.party_id = p_party_id
1141       and rs.resource_id = ac.resource_id
1142       and hp.collector_id = ac.collector_id
1143       and ac.resource_id = wi.owner_resource_id(+)
1144       and rs.user_id is not null
1145       group by ac.resource_id, ac.employee_id ORDER BY 3');
1146 
1147   SAVEPOINT	get_case_resources;
1148 
1149   -- Standard call to check for call compatibility.
1150   IF NOT FND_API.Compatible_API_Call (l_api_version,
1151                                       p_api_version,
1152                                       l_api_name,
1153                                       G_PKG_NAME)    THEN
1154 	RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
1155   END IF;
1156 
1157   -- Check p_init_msg_list
1158   IF FND_API.to_Boolean( p_init_msg_list ) THEN
1159     FND_MSG_PUB.initialize;
1160   END IF;
1161 
1162   x_return_status := FND_API.G_RET_STS_SUCCESS;
1163 
1164   FOR r_person IN c_get_person LOOP
1165      idx := idx + 1;
1166      iex_debug_pub.logmessage ('idx= ' || idx);
1167      iex_debug_pub.logmessage ('r_person.salesforce_id = ' || r_person.resource_id);
1168 	  x_resource_tab(idx).resource_id := r_person.resource_id;
1169 	  x_resource_tab(idx).person_id := r_person.employee_id;
1170   End LOOP;
1171 
1172   -- Standard check of p_commit
1173   IF FND_API.To_Boolean(p_commit) THEN
1174    COMMIT WORK;
1175   END IF;
1176 
1177   -- Standard call to get message count and if count is 1, get message info
1178   FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1179 
1180      iex_debug_pub.logmessage ('**** END get_case_resources ************');
1181 
1182   EXCEPTION
1183 	WHEN FND_API.G_EXC_ERROR THEN
1184         ROLLBACK TO get_case_resources;
1185 		x_return_status := FND_API.G_RET_STS_ERROR;
1186 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1187 
1188 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1189         ROLLBACK TO get_case_resources;
1190 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1191 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1192 
1193 	WHEN OTHERS THEN
1194         ROLLBACK TO get_case_resources;
1195 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1196 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
1197 			FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
1198 		END IF;
1199 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1200 
1201 END get_case_resources;*/
1202 --End bug#5373412 schekuri 10-Jul-2006
1203 
1204 
1205 
1206 /*
1207 || Overview:   builds a dynamic where clause based on name / condition / value array
1208 ||
1209 || Parameter:  array of name / condition / value like
1210 ||            'PARTY_NAME', '=', 'Anna Kournikova'
1211 ||            'AMOUNT_OVERDUE', '>=', '5000'
1212 ||
1213 || Return value: String with "Where party_name = 'Anna Kournikova' AND
1214 ||                                  amount_overdue >= 5000"
1215 ||
1216 || Source Tables: NA
1217 ||
1218 || Target Tables: NA
1219 ||
1220 || Creation date:  01/28/2003 5:53PM
1221 ||
1222 || Major Modifications: when              who                       what
1223 ||                      01/28/2003 5:53PM raverma                created
1224 */
1225 function buildWhereClause(P_CONDITIONS IN IEX_UTILITIES.Condition_TBL) return VARCHAR2
1226 IS
1227 
1228 l_conditions IEX_UTILITIES.Condition_TBL;
1229 l_return     VARCHAR2(5000);
1230 l_count      NUMBER := 0;
1231 
1232 --clchang updated for sql bind var 05/07/2003
1233 vstr  varchar2(10);
1234 
1235 Begin
1236 l_conditions := p_conditions;
1237 l_count      := 0;
1238 vstr   := 'WHERE ';
1239 
1240      for J in 1..P_CONDITIONS.COUNT
1241      loop
1242 
1243          if J <> P_CONDITIONS.COUNT then
1244             l_return := l_return || P_CONDITIONS(J).COL_NAME || ' ' || P_CONDITIONS(J).CONDITION || ' ' || P_CONDITIONS(J).VALUE || ' AND ';
1245          else
1246             l_return := l_return || P_CONDITIONS(J).COL_NAME || ' ' || P_CONDITIONS(J).CONDITION || ' ' || P_CONDITIONS(J).VALUE;
1247          end if;
1248      --dbms_output.put_line(l_return);
1249      end loop;
1250 
1251      --clchang updated for sql bind var 05/07/2003
1252      -- return 'WHERE ' || l_return;
1253      return vstr ||l_return ;
1254 
1255 End buildWhereClause;
1256 
1257 -- Begin- Andre 07/28/2004 - Add bill to assignmnet
1258 
1259 -- This procedure will return access to a bill to site use instead of site use id
1260 -- this assumes use of the script to transfer collector from customer profiles
1261 -- to as_accesses, this will place the site_use_id into the attribute1 column
1262 --Begin bug#5373412 schekuri 10-Jul-2006
1263 --Removed the following procedures and added a single consolidate procedure get_assigned_collector
1264 /*PROCEDURE get_billto_resources(p_api_version      IN  NUMBER := 1.0,
1265                                p_init_msg_list    IN  VARCHAR2,
1266                                p_commit           IN  VARCHAR2,
1267                                p_validation_level IN  NUMBER,
1268                                x_msg_count        OUT NOCOPY NUMBER,
1269                                x_msg_data         OUT NOCOPY VARCHAR2,
1270                                x_return_status    OUT NOCOPY VARCHAR2,
1271                                p_site_use_id      IN  VARCHAR2,
1272                                x_resource_tab     OUT NOCOPY resource_tab_type) IS
1273 
1274 
1275 --Territory Assignment Changes
1276 /*  CURSOR c_get_person IS
1277    (
1278     SELECT ac.employee_id, ac.resource_id
1279     FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs,
1280            ar_collectors ac
1281     WHERE hp.site_use_id    = p_site_use_id
1282       and rs.resource_id    = ac.resource_id
1283       and hp.collector_id   = ac.collector_id
1284       and rs.user_id is not null
1285       and    ac.employee_id is not null
1286       group by ac.resource_id, ac.employee_id
1287     union all
1288     SELECT ac.employee_id, ac.resource_id, 0
1289     FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs,ar_collectors ac
1290     WHERE hp.site_use_id = p_site_use_id
1291       and rs.resource_id = ac.resource_id
1292       and hp.collector_id = ac.collector_id
1293       and rs.user_id is not null and
1294       not exists (select null from iex_strategy_work_items wi
1295             where ac.resource_id = wi.resource_id
1296       and wi.status_code = 'OPEN')
1297       and    ac.employee_id is not null
1298        group by ac.resource_id, ac.employee_id
1299       ) order by 3;
1300 */
1301 /* We use hz_customer_profiles and
1302    Load balancing when the assigned with Group Resource
1303 */
1304 /*CURSOR c_get_person is
1305 SELECT ac.employee_id, ac.resource_id, 0
1306 FROM  hz_customer_profiles hp, ar_collectors ac
1307 WHERE hp.site_use_id = p_site_use_id
1308   and hp.collector_id  = ac.collector_id
1309   and ac.resource_type = 'RS_RESOURCE'
1310 union all
1311 ( SELECT jtg.person_id, jtg.resource_id, count(work_item_id)
1312     FROM  hz_customer_profiles hp,  iex_strategy_work_items wi,
1313           ar_collectors ac, jtf_rs_group_members jtg
1314     WHERE hp.site_use_id  = p_site_use_id
1315       and hp.collector_id  = ac.collector_id
1316       and ac.resource_type = 'RS_GROUP'
1317       and ac.resource_id  = jtg.group_id
1318       and jtg.resource_id = wi.resource_id
1319       and wi.status_code   = 'OPEN'
1320       group by jtg.resource_id, jtg.person_id
1321 UNION ALL
1322     SELECT jtg.person_id, jtg.resource_id, 0
1323     FROM  hz_customer_profiles hp, ar_collectors ac,
1324       jtf_rs_group_members jtg
1325     WHERE hp.site_use_id  = p_site_use_id
1326       and hp.collector_id   = ac.collector_id
1327       and ac.resource_type = 'RS_GROUP'
1328       and ac.resource_id = jtg.group_id
1329       and not exists (select null from iex_strategy_work_items wi
1330             where jtg.resource_id = wi.resource_id
1331       and wi.status_code = 'OPEN')
1332        group by jtg.resource_id, jtg.person_id
1333       ) order by 3;
1334 
1335 
1336   l_api_version   CONSTANT NUMBER       := p_api_version;
1337   l_api_name CONSTANT VARCHAR2(100) := 'GET_BILLTO_RESOURCES';
1338   l_init_msg_list CONSTANT VARCHAR2(1)  := p_init_msg_list;
1339   l_return_status VARCHAR2(1);
1340   l_msg_count NUMBER;
1341   l_msg_data VARCHAR2(32767);
1342   idx NUMBER := 0;
1343 BEGIN
1344 
1345      iex_debug_pub.logmessage ('**** BEGIN on all
1346       get_billto_resources ************');
1347      iex_debug_pub.logmessage ('get_person cursor = ' ||
1348       ' SELECT ac.employee_id, ac.resource_id, count(work_item_id)
1349        FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_strategy_work_items wi,ar_collectors ac
1350        WHERE hp.site_use_id    = p_site_use_id
1351        and rs.resource_id    = ac.resource_id
1352        and ac.resource_id    = wi.resource_id
1353        and hp.collector_id   = ac.collector_id
1354        and wi.status_code    = OPEN
1355        and rs.user_id is not null
1356        group by ac.resource_id, ac.employee_id');
1357 
1358 
1359   SAVEPOINT	get_assign_resources;
1360 
1361   -- Standard call to check for call compatibility.
1362   IF NOT FND_API.Compatible_API_Call (l_api_version,
1363                                       p_api_version,
1364                                       l_api_name,
1365                                       G_PKG_NAME)    THEN
1366 	RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
1367   END IF;
1368 
1369   -- Check p_init_msg_list
1370   IF FND_API.to_Boolean( p_init_msg_list ) THEN
1371     FND_MSG_PUB.initialize;
1372   END IF;
1373 
1374   x_return_status := FND_API.G_RET_STS_SUCCESS;
1375 
1376   FOR r_person IN c_get_person LOOP
1377      idx := idx + 1;
1378      iex_debug_pub.logmessage ('idx= ' || idx);
1379      iex_debug_pub.logmessage ('r_person.salesforce_id = ' || r_person.resource_id);
1380 	  x_resource_tab(idx).resource_id := r_person.resource_id;
1381 	  x_resource_tab(idx).person_id := r_person.employee_id;
1382   End LOOP;
1383 
1384   -- Standard check of p_commit
1385   IF FND_API.To_Boolean(p_commit) THEN
1386    COMMIT WORK;
1387   END IF;
1388 
1389   -- Standard call to get message count and if count is 1, get message info
1390   FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1391 
1392      iex_debug_pub.logmessage ('**** END get_billto_resources ************');
1393 
1394   EXCEPTION
1395 	WHEN FND_API.G_EXC_ERROR THEN
1396         ROLLBACK TO get_assign_resources;
1397 		x_return_status := FND_API.G_RET_STS_ERROR;
1398 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1399 
1400 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1401         ROLLBACK TO get_assign_resources;
1402 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1403 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1404 
1405 	WHEN OTHERS THEN
1406         ROLLBACK TO get_assign_resources;
1407 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1408 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
1409 			FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
1410 		END IF;
1411 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
1412 
1413 END get_billto_resources;*/
1414 -- End- Andre 07/28/2004 - Add bill to assignmnet
1415 --End bug#5373412 schekuri 10-Jul-2006
1416 
1417 
1418 -- Begin- Andre 09/15/2004 - Function to get lookup meaning - performance enhancement as per Ramakant Alat
1419 FUNCTION get_lookup_meaning (p_lookup_type  IN VARCHAR2,
1420                              p_lookup_code  IN VARCHAR2)
1421  RETURN VARCHAR2 IS
1422 l_meaning iex_lookups_v.meaning%TYPE;
1423 l_hash_value NUMBER;
1424 BEGIN
1425   IF p_lookup_code IS NOT NULL AND
1426      p_lookup_type IS NOT NULL THEN
1427 
1428     l_hash_value := DBMS_UTILITY.get_hash_value(
1429                                          p_lookup_type||'@*?'||p_lookup_code,
1430                                          1000,
1431                                          25000);
1432 
1433     IF pg_lookups_rec.EXISTS(l_hash_value) THEN
1434         l_meaning := pg_lookups_rec(l_hash_value);
1435     ELSE
1436 
1437      SELECT meaning
1438      INTO   l_meaning
1439      FROM   iex_lookups_v
1440      WHERE  lookup_type = p_lookup_type
1441       AND  lookup_code = p_lookup_code ;
1442 
1443      pg_lookups_rec(l_hash_value) := l_meaning;
1444 
1445     END IF;
1446 
1447   END IF;
1448 
1449   return(l_meaning);
1450 
1451 EXCEPTION
1452  WHEN no_data_found  THEN
1453   return(null);
1454  WHEN OTHERS THEN
1455   raise;
1456 END;
1457 -- End- Andre 09/15/2004 - Function to get lookup meaning - performance enhancement as per Ramakant Alat
1458 
1459 PROCEDURE put_param_value (p_param_value  IN VARCHAR2,
1460                           p_param_key  OUT NOCOPY NUMBER) IS
1461 l_hash_value NUMBER;
1462 BEGIN
1463   IF p_param_value IS NOT NULL THEN
1464 
1465     l_hash_value := DBMS_UTILITY.get_hash_value(
1466                                          p_param_value,
1467                                          1000,
1468                                          25000);
1469 
1470     IF pg_param_tab.EXISTS(l_hash_value) THEN
1471         p_param_key := l_hash_value;
1472     ELSE
1473         pg_param_tab(l_hash_value) := p_param_value;
1474         p_param_key := l_hash_value;
1475 
1476     END IF;
1477 
1478   END IF;
1479 END;
1480 
1481 
1482 PROCEDURE get_param_value(p_param_key IN NUMBER,
1483                           p_param_value OUT NOCOPY VARCHAR2) IS
1484 BEGIN
1485   IF pg_param_tab.EXISTS(p_param_key) THEN
1486     p_param_value := pg_param_tab(p_param_key);
1487   ELSE
1488     p_param_value := 'N/A';
1489   END IF;
1490 END;
1491 
1492 
1493 PROCEDURE delete_param_value(p_param_key IN NUMBER) IS
1494 BEGIN
1495   IF pg_param_tab.EXISTS(p_param_key) THEN
1496     pg_param_tab.DELETE(p_param_key);
1497   ELSE
1498     NULL;
1499   END IF;
1500 END;
1501 
1502 /*
1503    Overview : Check if the dunning letter flag before send out a dunning letter.
1504               It checks the billto level first then account level; at last customer level.
1505    Parameter: p_party_id:  if customer level then pass the party_id
1506               p_cust_account_id : if account level then pass the cust_account_id
1507               p_site_use_id : if bill_to level then pass the customer_site_use_id
1508               p_delinquency_id : if delinquency level then pass the delinquency_id
1509    Return:  'Y' if ok to send dunning letter
1510             'N' if no dunning letter should be sent
1511    creation date: 06/02/2004
1512    author:  ctlee
1513 */
1514 FUNCTION DunningProfileCheck
1515 (
1516   p_party_id             IN  number
1517   , p_cust_account_id    IN  number
1518   , p_site_use_id        IN  number
1519   , p_delinquency_id     IN  number
1520 )
1521 return varchar2
1522 IS
1523     l_dunning_letters varchar2(10);
1524     l_party_id number;
1525     l_cust_account_id number;
1526     l_site_use_id number;
1527     l_delinquency_id number;
1528 
1529     CURSOR get_party_account_id_cur (p_customer_site_use_id number) is
1530         SELECT  ca.party_id party_id, ca.cust_account_id cust_account_id
1531               FROM hz_cust_site_uses site_uses, hz_cust_acct_sites acct_sites, hz_cust_accounts ca
1532               WHERE site_uses.site_use_id = p_customer_site_use_id
1533               AND acct_sites.cust_acct_site_id = site_uses.cust_acct_site_id
1534               AND ca.cust_account_id = acct_sites.cust_account_id;
1535 
1536     cursor c_billto (p_site_use_id number) is
1537       select dunning_letters from hz_customer_profiles
1538       where site_use_id = p_site_use_id and status = 'A';
1539 
1540     CURSOR get_party_id_cur (p_cust_account_id number) is
1541         SELECT party_id  FROM HZ_CUST_ACCOUNTS
1542             WHERE cust_account_id = p_cust_account_id ;
1543 
1544     cursor c_account (p_cust_account_id number) is
1545       select dunning_letters from hz_customer_profiles
1546       where cust_account_id = p_cust_account_id and status = 'A' and site_use_id is null;
1547 
1548     cursor c_party (p_party_id number) is
1549       select dunning_letters from hz_customer_profiles
1550       -- begin bug 4587842 ctlee 09/06/2005
1551       where party_id = p_party_id and status = 'A'
1552       and site_use_id is null and cust_account_id = -1;
1553       -- where party_id = p_party_id and status = 'A' and site_use_id is null and cust_account_id is null;
1554       -- end bug 4587842 ctlee 09/06/2005
1555 
1556     cursor c_get_billto (p_delinquency_id number) is
1557       select customer_site_use_id from iex_delinquencies_all
1558       where delinquency_id = p_delinquency_id;
1559 BEGIN
1560 
1561     l_party_id  := p_party_id;
1562     l_cust_account_id  := p_cust_account_id;
1563     l_site_use_id  := p_site_use_id;
1564     l_delinquency_id  := p_delinquency_id;
1565 
1566     -- default to no dunning letter to send, if there is no record that match
1567     l_dunning_letters := 'Y';
1568 
1569     -- get bill_to id to check, because there is no delinquency level in customer_profile
1570     if (l_delinquency_id is not null) Then
1571       OPEN c_get_billto (l_delinquency_id);
1572       FETCH c_get_billto INTO l_site_use_id;
1573       CLOSE c_get_billto;
1574     end if;
1575 
1576     if (l_site_use_id is not null) Then
1577       -- set up accout and party id in case there is no record for this bill to
1578       OPEN get_party_account_id_cur (l_site_use_id);
1579       FETCH get_party_account_id_cur INTO l_party_id, l_cust_account_id;
1580       CLOSE get_party_account_id_cur;
1581 
1582       open c_billto(l_site_use_id);
1583       loop
1584         fetch c_billto into l_dunning_letters;
1585         if c_billto%notfound then
1586            exit;
1587         else
1588 	   -- Commented the if condition for Bug#6649352 bibeura 12-Dec-2007
1589            -- if l_dunning_letters = 'N' then
1590              return l_dunning_letters;
1591            -- end if;
1592         end if;
1593       end loop;
1594       close c_billto;
1595     end if;
1596 
1597     if (l_cust_account_id is not null) Then
1598       -- set up party id in case there is no record for this account to
1599       OPEN get_party_id_cur (l_cust_account_id);
1600       FETCH get_party_id_cur INTO l_party_id;
1601       CLOSE get_party_id_cur;
1602 
1603       open c_account(l_cust_account_id);
1604       loop
1605         fetch c_account into l_dunning_letters;
1606         if c_account%notfound then
1607            exit;
1608         else
1609     	--Bug5348445. Fix By LKKUMAR on 21-Jun-2006. Start.
1610 	--   if l_dunning_letters = 'N' then
1611              return l_dunning_letters;
1612 	--   end if;
1613     	--Bug5348445. Fix By LKKUMAR on 21-Jun-2006. End.
1614         end if;
1615       end loop;
1616       close c_account;
1617     end if;
1618 
1619     if (l_party_id is not null) Then
1620       open c_party(l_party_id);
1621       loop
1622         fetch c_party into l_dunning_letters;
1623         if c_party%notfound then
1624            exit;
1625         else
1626 	   -- Commented the if condition for Bug#6649352 bibeura 12-Dec-2007
1627            -- if l_dunning_letters = 'N' then
1628              return l_dunning_letters;
1629            -- end if;
1630         end if;
1631       end loop;
1632       close c_party;
1633     end if;
1634 
1635     return l_dunning_letters;
1636 
1637 EXCEPTION
1638  WHEN OTHERS THEN
1639     return l_dunning_letters;
1640 END DunningProfileCheck;
1641 
1642 FUNCTION DunningMinAmountCheck
1643 (
1644     p_cust_account_id       IN number
1645   , p_site_use_id           IN number
1646   , p_delinquency_id        IN number
1647   , p_org_id                IN NUMBER
1648   , p_grace_days            IN number  DEFAULT 0
1649   , p_dun_disputed_items    IN VARCHAR2  DEFAULT 'N'
1650   , p_correspondence_date   IN DATE  DEFAULT sysdate
1651   , p_running_level         IN varchar2
1652 )
1653 return varchar2 is
1654     l_cust_prof_chk         varchar2(30);
1655     l_func_curr_prf_chk     varchar2(30);
1656     l_api_name              CONSTANT VARCHAR2(30) := 'DunningMinAmountCheck';
1657     l_prf_amt_chk           varchar2(1):='N'; -- value will be 'Y' if profile amt exists at that level
1658     l_dunning_letters       VARCHAR2(1):='Y'; -- initial value will be 'Y'
1659 
1660     l_cust_account_id       number;
1661     l_site_use_id           number;
1662     l_delinquency_id        number;
1663     l_org_id                NUMBER;
1664     l_grace_days            number;
1665     l_dun_disputed_items    VARCHAR2(1);
1666     l_correspondence_date   DATE;
1667     l_running_level         varchar2(30);
1668 
1669 
1670     l_acct_total_acctd_amount   number:=0;
1671     l_billto_total_acctd_amount number:=0;
1672     t_site_use_id               number;
1673 
1674     l_invoice_currency_code    varchar2(30);
1675 
1676     l_min_currency_code        varchar2(30);
1677     l_min_dun_amount           number;
1678     l_min_dun_invoice_amount   number;
1679     x_min_currency_code        varchar2(30);
1680     x_min_dun_amount           number;
1681     x_min_dun_invoice_amount   number;
1682 
1683 
1684     l_acc_tot_amt_due_rem     number:=0;
1685     l_billto_tot_amt_due_rem  number:=0;
1686 
1687     l_amount             number:=0;
1688 	  l_invoice_amount     number:=0;
1689 	  l_cm_ar_total_amount number:=0;
1690 
1691     cursor c_acc_dist_inv_cur (p_cust_account_id number,p_org_id number) is
1692 	       select distinct a.invoice_currency_code
1693          from ar_payment_schedules_all a, iex_delinquencies_all b
1694          where a.payment_schedule_id = b.payment_schedule_id
1695          and b.status in ('DELINQUENT', 'PREDELINQUENT')
1696 	       AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')
1697          and a.status = 'OP'
1698          and b.cust_account_id = p_cust_account_id
1699 	       and b.org_id = p_org_id
1700 	       order by 1;
1701 
1702 	cursor c_billto_dist_inv_cur (p_site_use_id number,p_org_id number) is
1703 	      select distinct a.invoice_currency_code
1704         from ar_payment_schedules_all a, iex_delinquencies_all b
1705         where a.payment_schedule_id = b.payment_schedule_id
1706         and b.status in ('DELINQUENT', 'PREDELINQUENT')
1707 	      AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')
1708         and a.status = 'OP'
1709         and b.customer_site_use_id = p_site_use_id
1710 	      and b.org_id = p_org_id
1711 	      order by 1;
1712 
1713 Begin
1714 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - "Begining of Minimum Dunning Amount check" ');
1715 FND_FILE.PUT_LINE(FND_FILE.LOG,'"Begining of Minimum Dunning Amount check" ');
1716     l_cust_prof_chk         := fnd_profile.value('IEX_DUNNING_CUST_PROF_CHECK');
1717     l_dunning_letters       :='Y';
1718     l_cust_account_id       :=p_cust_account_id;
1719     l_site_use_id           :=p_site_use_id;
1720     l_delinquency_id        :=p_delinquency_id;
1721     l_org_id                :=p_org_id;
1722     l_grace_days            :=p_grace_days;
1723     l_dun_disputed_items    :=p_dun_disputed_items;
1724     l_correspondence_date   :=p_correspondence_date;
1725     l_running_level         :=p_running_level;
1726 
1727     l_acct_total_acctd_amount   :=0;
1728     l_billto_total_acctd_amount :=0;
1729      /*
1730     If  IEX: Minimum Dunning Amount Profile Check is null then Running level is assigned to it.
1731     */
1732     if l_cust_prof_chk  is NULL then
1733     FND_FILE.PUT_LINE(FND_FILE.LOG, ' IEX: Minimum Dunning Amount Profile Check is Null, so using dunning level');
1734     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' IEX: Minimum Dunning Amount Profile Check is NULL , so using dunning level');
1735             if  l_running_level = 'DELINQUENCY' then
1736                 l_cust_prof_chk := 'BILL_TO';
1737             else
1738                 l_cust_prof_chk := l_running_level;
1739             end if;
1740    elsif   l_cust_prof_chk = 'NONE' then
1741             FND_FILE.PUT_LINE(FND_FILE.LOG, ' Profile - IEX: Minimum Dunning Amount Profile Check = '||l_cust_prof_chk||' so no minimum dunning amount check will be done');
1742             FND_FILE.PUT_LINE(FND_FILE.LOG, ' Returning value "Y"');
1743             WriteLog(G_PKG_NAME || ' ' || l_api_name || 'Profile - IEX: Minimum Dunning Amount Profile Check-->'||l_cust_prof_chk||' so no minimum dunning amount check will be done');
1744             return l_dunning_letters; -- default value is Y
1745    else /*  If  IEX: Minimum Dunning Amount Profile Check  = NONE then letter will be sent without
1746             checking for profile amount */
1747             FND_FILE.PUT_LINE(FND_FILE.LOG, ' Profile - IEX: Minimum Dunning Amount Profile Check= '||l_cust_prof_chk);
1748             WriteLog(G_PKG_NAME || ' ' || l_api_name || '-  Profile - IEX: Minimum Dunning Amount Profile Check -->'||l_cust_prof_chk);
1749     end if;
1750 
1751     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Dunning Level        - '||l_running_level);
1752     FND_FILE.PUT_LINE(FND_FILE.LOG, 'cust account id      - '||l_cust_account_id);
1753     FND_FILE.PUT_LINE(FND_FILE.LOG, 'site use id          - '||l_site_use_id);
1754     FND_FILE.PUT_LINE(FND_FILE.LOG, 'delinquency id       - '||l_delinquency_id);
1755     FND_FILE.PUT_LINE(FND_FILE.LOG, 'org id               - '||l_org_id);
1756     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Grace Days           - '||l_grace_days);
1757     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Disputed Items       - '||l_dun_disputed_items);
1758     FND_FILE.PUT_LINE(FND_FILE.LOG, 'correspondence date  - '||l_correspondence_date);
1759 
1760     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Dunning Level       - '||l_running_level );
1761     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - cust account id     - '||l_cust_account_id);
1762     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - site use id         - '|| l_site_use_id);
1763     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delinquency_id      - '||l_delinquency_id);
1764     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org id              - '||l_org_id);
1765     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Grace Days          - '||l_grace_days);
1766     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Disputed Items      - '||l_dun_disputed_items);
1767     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - correspondence date - '||l_correspondence_date);
1768 
1769     --Checking if Total accounted amount due reamining is <=0
1770 if l_running_level='ACCOUNT' and l_cust_account_id is not null then
1771           if l_cust_prof_chk = 'BILL_TO'  or l_cust_prof_chk = 'BILLTOACCOUNT' then
1772              l_dunning_letters := 'E';
1773              FND_FILE.PUT_LINE(FND_FILE.LOG, ' When Dunning level is Account, value of profile "IEX: Minimum Dunning Amount Profile Check" can''t be "Bill To" or "Bill To and Account"');
1774              FND_FILE.PUT_LINE(FND_FILE.LOG, ', Returning value "E"');
1775              WriteLog(G_PKG_NAME || ' ' || l_api_name || '- Invalid value for profile  IEX: Minimum Dunning Amount Profile Check');
1776              return l_dunning_letters;
1777          else
1778             l_acct_total_acctd_amount := acct_total_acctd_amt(l_cust_account_id,l_org_id,l_correspondence_date,l_grace_days,l_dun_disputed_items);
1779               FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due reamining at Account level= '||l_acct_total_acctd_amount);
1780               WriteLog(G_PKG_NAME || ' ' || l_api_name || '- Total accounted amount at Account level -> '||l_acct_total_acctd_amount);
1781               if l_acct_total_acctd_amount<=0 then
1782                   l_dunning_letters := 'N';
1783                   FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is less than or equal to zero, so returning value "N"');
1784                   return l_dunning_letters;
1785               end if;
1786          end if;
1787 elsif l_running_level = 'BILL_TO' and l_site_use_id is not null
1788                        or
1789       l_running_level = 'DELINQUENCY' and l_delinquency_id is not null then
1790         if l_cust_prof_chk = 'BILL_TO'  or l_cust_prof_chk = 'BILLTOACCOUNT' then
1791              l_billto_total_acctd_amount := billto_total_acctd_amt(l_site_use_id,l_org_id,l_correspondence_date,l_grace_days,l_dun_disputed_items);
1792             FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due reamining at Billto level= '||l_billto_total_acctd_amount);
1793             WriteLog(G_PKG_NAME || ' ' || l_api_name || '- Total Accounted Amount at Billto level -> '|| l_billto_total_acctd_amount);
1794             if l_billto_total_acctd_amount <=0 then
1795                 l_dunning_letters := 'N';
1796                 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is less than or equal to zero, so returning value "N"');
1797                 return l_dunning_letters;
1798            end if;
1799          elsif l_cust_prof_chk = 'ACCOUNT' then
1800               l_acct_total_acctd_amount := acct_total_acctd_amt(l_cust_account_id,l_org_id,l_correspondence_date,l_grace_days,l_dun_disputed_items);
1801                FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due reamining at ACCOUNT level -> '||l_acct_total_acctd_amount);
1802                WriteLog(G_PKG_NAME || ' ' || l_api_name || '- Total accounted Amount at Account level -> '|| l_acct_total_acctd_amount);
1803               if l_acct_total_acctd_amount<=0 then
1804                   l_dunning_letters := 'N';
1805                   FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is less than or equal to zero, so returning value "N"');
1806                   return l_dunning_letters;
1807              end if;
1808          end if;
1809 End if;
1810 -- If IEX: Check Dunning amount at functional currency profile is Yes
1811 l_func_curr_prf_chk   :=  nvl(fnd_profile.value('IEX_CHK_DUNN_AT_FUNC_CURR'), 'Y');
1812 if l_func_curr_prf_chk = 'Y' then
1813 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Profile - IEX: Check Dunning amount at functional currency is YES');
1814 else
1815 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Profile - IEX: Check Dunning amount at functional currency is NO');
1816 end if;
1817 
1818 if l_func_curr_prf_chk = 'Y' then
1819 FND_FILE.PUT_LINE(FND_FILE.LOG,'Checking Dunning amount at Functional Currency');
1820 WriteLog(G_PKG_NAME || ' ' || l_api_name || '- IEX: Check Dunning amount at functional currency is Yes');
1821 l_amount := 0;
1822 l_invoice_amount := 0;
1823 l_cm_ar_total_amount := 0;
1824     if l_running_level='ACCOUNT' and l_cust_account_id is not null then
1825     acct_prf_amt(l_cust_account_id,l_org_id, x_min_currency_code, x_min_dun_amount,x_min_dun_invoice_amount);
1826 	                  l_min_currency_code      := x_min_currency_code;
1827                     l_min_dun_amount         := x_min_dun_amount;
1828                     l_min_dun_invoice_amount := x_min_dun_invoice_amount;
1829                      WriteLog(G_PKG_NAME || ' ' || l_api_name || '- Minimum Dunning amount at Account level -> '||l_min_dun_amount);
1830                   if l_min_dun_amount IS NOT NULL then
1831                      FND_FILE.PUT_LINE(FND_FILE.LOG, 'Minimum Dunning amount at Account level=          '||l_min_dun_amount);
1832                      FND_FILE.PUT_LINE(FND_FILE.LOG, 'Minimum Dunning Invoice amount at Account level=  '||l_min_dun_invoice_amount);
1833                         l_amount:= amount_account(l_cust_account_id ,l_org_id,l_correspondence_date,l_grace_days,l_dun_disputed_items,
1834                         l_min_currency_code , l_min_dun_amount,l_min_dun_invoice_amount);
1835                   	    FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due remaining at Account level=  '||l_amount);
1836                         WriteLog(G_PKG_NAME || ' ' || l_api_name || '- Total amount due remaining at Account level -> '||l_amount);
1837                         if (l_amount < l_min_dun_amount)then
1838                           l_dunning_letters := 'N';
1839 	                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is less than Minimum dunning amount, so returning value "N"');
1840 	                        return l_dunning_letters;
1841 	                      else
1842 	                       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is greater than Minimum Dunning amount, so letter will be sent');
1843 	                     end if;
1844                  else
1845                    FND_FILE.PUT_LINE(FND_FILE.LOG, 'Minimum Dunning amount does not exists at Account level so send Dunning letter');
1846                  end if;
1847 
1848    elsif  (l_running_level = 'BILL_TO' and l_site_use_id is not null)
1849                                or
1850           (l_running_level = 'DELINQUENCY' and l_delinquency_id is not null) then
1851            if l_cust_prof_chk = 'BILL_TO' then
1852                  billto_prf_amt(l_site_use_id, l_org_id, x_min_currency_code, x_min_dun_amount, x_min_dun_invoice_amount);
1853                  l_min_currency_code      := x_min_currency_code;
1854                  l_min_dun_amount         := x_min_dun_amount;
1855                  l_min_dun_invoice_amount := x_min_dun_invoice_amount;
1856                  WriteLog(G_PKG_NAME || ' ' || l_api_name || '- Minimum dunning amount at Billto level  -> '||l_min_dun_amount);
1857                  If l_min_dun_amount is not null then
1858                  FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning amount at Billto level        = '||l_min_dun_amount);
1859                  FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning Invoice amount at Billto level= '||l_min_dun_invoice_amount);
1860                     l_amount:= amount_billto(l_site_use_id, l_org_id, l_correspondence_date,l_grace_days, l_dun_disputed_items, l_min_currency_code
1861                   , l_min_dun_amount,l_min_dun_invoice_amount);
1862                   FND_FILE.PUT_LINE(FND_FILE.LOG,'Total amount due remaining at Billto level=  '||l_amount);
1863                   WriteLog(G_PKG_NAME || ' ' || l_api_name || '- Total amount due remaining at Billto level -> '||l_amount);
1864                        if (l_amount < l_min_dun_amount) then
1865                           l_dunning_letters := 'N';
1866 	                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is less than Minimum dunning amount, so returning value "N"');
1867 	                         return l_dunning_letters;
1868 	                      else
1869 	                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is greater than Minimum dunning amount, so letter will be sent');
1870                       end if;
1871                  else
1872                   FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning amount does not exists at Billto level so send Dunning letter');
1873                  End if;
1874 
1875           elsif  l_cust_prof_chk = 'BILLTOACCOUNT' then
1876                  billto_prf_amt(l_site_use_id,l_org_id, x_min_currency_code, x_min_dun_amount, x_min_dun_invoice_amount);
1877                  l_min_currency_code      := x_min_currency_code;
1878                  l_min_dun_amount         := x_min_dun_amount;
1879                  l_min_dun_invoice_amount := x_min_dun_invoice_amount;
1880                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum dunning amount at Billto level -> '||l_min_dun_amount);
1881                 If l_min_dun_amount is not null then
1882                    FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning amount at Billto level        =  '||l_min_dun_amount);
1883                    FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning Invoice amount at Billto level=  '||l_min_dun_invoice_amount);
1884                      l_amount:= amount_billto(l_site_use_id, l_org_id, l_correspondence_date
1885                     ,l_grace_days, l_dun_disputed_items, l_min_currency_code, l_min_dun_amount
1886                     ,l_min_dun_invoice_amount);
1887                     FND_FILE.PUT_LINE(FND_FILE.LOG,'Total amount due remaining at Billto level=  '||l_amount);
1888                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Total amount due remaining at Billto level -> '||l_amount);
1889                       if (l_amount < l_min_dun_amount) then
1890 	                         l_dunning_letters := 'N';
1891 	                         FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is less than Minimum dunning amount, so returning value "N"');
1892 	                         return l_dunning_letters;
1893 	                    else
1894                       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is greater than Minimum dunning amount, so letter will be sent');
1895 	                    end if;
1896 	              else -- If profile amount doesnt exists at billto level check for account level
1897                  FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning amount does not exists at Billto level, so check at Account level');
1898                  acct_prf_amt(l_cust_account_id,l_org_id, x_min_currency_code, x_min_dun_amount,x_min_dun_invoice_amount);
1899 	               l_min_currency_code      := x_min_currency_code;
1900                  l_min_dun_amount         := x_min_dun_amount;
1901                  l_min_dun_invoice_amount := x_min_dun_invoice_amount;
1902                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum dunning amount at Account level -> '||l_min_dun_amount);
1903                   if l_min_dun_amount IS NOT NULL then
1904                   FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning amount at Account level        = '||l_min_dun_amount);
1905                   FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning Invoice amount at Account level= '||l_min_dun_invoice_amount);
1906                         l_amount:= amount_account(l_cust_account_id ,l_org_id,l_correspondence_date,l_grace_days, l_dun_disputed_items
1907                       , l_min_currency_code, l_min_dun_amount, l_min_dun_invoice_amount);
1908                   	    FND_FILE.PUT_LINE(FND_FILE.LOG,'Total amount due remaining at Account level= '||l_amount);
1909                   	    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total amount due remaining at Account level -> '||l_amount);
1910                         if (l_amount < l_min_dun_amount) then
1911                   	      l_dunning_letters := 'N';
1912 	                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is less than Minimum dunning amount, so returning value "N"');
1913 	                        return l_dunning_letters;
1914 	                     else
1915                           FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is greater than Minimum dunning amount, so letter will be sent');
1916 	                     end if;
1917 	                else
1918 	                  FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning profile amount does not exist at Account level so send Dunning letter');
1919                  end if;
1920                 End if;
1921           elsif  l_cust_prof_chk = 'ACCOUNT' then
1922                  acct_prf_amt(l_cust_account_id,l_org_id, x_min_currency_code, x_min_dun_amount,x_min_dun_invoice_amount);
1923                  l_min_currency_code      := x_min_currency_code;
1924                  l_min_dun_amount         := x_min_dun_amount;
1925                  l_min_dun_invoice_amount := x_min_dun_invoice_amount;
1926                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum dunning amount at Account level -> '||l_min_dun_amount);
1927                  if l_min_dun_amount IS NOT NULL then
1928                  FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning amount at Account level        = '||l_min_dun_amount);
1929                  FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning Invoice amount at Account level= '||l_min_dun_invoice_amount);
1930                         l_amount:= amount_account(l_cust_account_id ,l_org_id,l_correspondence_date,l_grace_days, l_dun_disputed_items
1931                       , l_min_currency_code, l_min_dun_amount, l_min_dun_invoice_amount);
1932                       FND_FILE.PUT_LINE(FND_FILE.LOG,'Total amount due remaining at Account level= '||l_amount);
1933                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total amount due remaining at Account level -> '||l_amount);
1934                   	    if (l_amount < l_min_dun_amount)  then
1935 	                         l_dunning_letters := 'N';
1936 	                         return l_dunning_letters;
1937 	                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is less than Minimum dunning amount, so returning value "N"');
1938 	                     else
1939                           FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total amount due is greater than Minimum dunning amount, so letter will be sent');
1940                        end if;
1941 	               else
1942                   FND_FILE.PUT_LINE(FND_FILE.LOG,'Minimum dunning profile amount does not exist at Account level so send Dunning letter');
1943                 end if;
1944           end if; -- end of l_cust_prof_chk
1945    end if; -- end if of if p_running_level='ACCOUNT' and l_cust_account_id is not null then
1946 ELSE
1947 -- if IEX: Check Dunning amount at functional currency is NO
1948 -- follwing Code for distinct invoice currency codes will be executed
1949 FND_FILE.PUT_LINE(FND_FILE.LOG,'Checking Dunning amount for distinct invoice currencies');
1950 if l_running_level='ACCOUNT' and l_cust_account_id is not null then
1951      open c_acc_dist_inv_cur (l_cust_account_id,l_org_id);
1952            loop
1953 		             fetch c_acc_dist_inv_cur into l_invoice_currency_code;
1954 		             if c_acc_dist_inv_cur%notfound then
1955 		             exit;
1956 		             end if;
1957 		             FND_FILE.PUT_LINE(FND_FILE.LOG, ' Checking Minimum Dunning amount at Account level for Invoice Currency code '||l_invoice_currency_code);
1958        	         acc_min_dunn_amt (l_cust_account_id,l_invoice_currency_code,x_min_dun_amount,x_min_dun_invoice_amount);
1959        	         l_min_dun_amount         := x_min_dun_amount;
1960        	         l_min_dun_invoice_amount := x_min_dun_invoice_amount;
1961 
1962                  if l_min_dun_amount is not null then
1963                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Dunning amount at Account level for Invoice Currency Code-> '||l_invoice_currency_code);
1964                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum Dunning Amount at Account level         -> '||l_min_dun_amount);
1965 	               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum Dunning Invoice amount at Account level -> '||l_min_dun_invoice_amount);
1966 
1967                  FND_FILE.PUT_LINE(FND_FILE.LOG, ' Minimum Dunning Amount        = '||l_min_dun_amount);
1968 	               FND_FILE.PUT_LINE(FND_FILE.LOG, ' Minimum Dunning Invoice amount= '||l_min_dun_invoice_amount);
1969 
1970                           l_acc_tot_amt_due_rem :=  acc_tot_amt_due_rem(l_cust_account_id, l_invoice_currency_code
1971                                            , l_min_dun_invoice_amount, l_org_id, l_correspondence_date,l_grace_days, l_dun_disputed_items);
1972                           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount Due Remaining at Account level -> '||l_acc_tot_amt_due_rem);
1973                           FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount Due Remaining at Account level= '||l_acc_tot_amt_due_rem);
1974                           if   l_acc_tot_amt_due_rem < l_min_dun_amount then
1975                                l_dunning_letters := 'N';
1976                                FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount Due is less than Minimum Dunning Amount, so returning value "N"');
1977                                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount Due Remaining < Minimum Dunning Amount, so cant send dunning letters');
1978                                return l_dunning_letters;
1979                           else
1980                               FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount Due is greater than Minimum Dunning Amount, so letter will be sent');
1981                               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount Due Remaining > Minimum Dunning Amount');
1982                           end if;
1983                 else
1984                 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Minimum Dunning amount does not exist at Account level for Invoice currency code '||l_invoice_currency_code);
1985                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum Dunning profile  amount does not exist at Account level ');
1986                 end if;
1987           end loop;
1988           close c_acc_dist_inv_cur;
1989 elsif  (l_running_level = 'BILL_TO' and l_site_use_id is not null)
1990                                or
1991        (l_running_level = 'DELINQUENCY' and l_delinquency_id is not null) then
1992            if l_cust_prof_chk = 'BILL_TO' then
1993                open c_billto_dist_inv_cur(l_site_use_id, l_org_id) ;
1994                loop
1995 		             fetch c_billto_dist_inv_cur into l_invoice_currency_code;
1996                        if c_billto_dist_inv_cur%notfound then
1997                        exit;
1998                        end if;
1999                        FND_FILE.PUT_LINE(FND_FILE.LOG, ' Checking Minimum Dunning amount at Billto level for Invoice Currency code '||l_invoice_currency_code);
2000                        t_site_use_id := get_BR_BillTOID(l_site_use_id);
2001                        billto_min_dunn_amt (p_site_use_id, l_invoice_currency_code, x_min_dun_amount, x_min_dun_invoice_amount);
2002                        l_min_dun_amount         := x_min_dun_amount;
2003        	               l_min_dun_invoice_amount := x_min_dun_invoice_amount;
2004 
2005                  if l_min_dun_amount is not null then
2006        	               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Invoice Currency Code                          -> '|| l_invoice_currency_code);
2007                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum dunning amount at Billto level         -> '|| l_min_dun_amount);
2008                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum dunning invoice amount at Billto level -> '|| l_min_dun_invoice_amount);
2009 
2010                        FND_FILE.PUT_LINE(FND_FILE.LOG, ' Minimum dunning amount         = '|| l_min_dun_amount);
2011                        FND_FILE.PUT_LINE(FND_FILE.LOG, ' Minimum dunning invoice amount = '|| l_min_dun_invoice_amount);
2012 
2013                        l_billto_tot_amt_due_rem  := billto_tot_amt_due_rem(l_site_use_id, l_invoice_currency_code,
2014                        l_min_dun_invoice_amount,l_org_id,l_correspondence_date,l_grace_days, l_dun_disputed_items);
2015 
2016                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due remaining at Billto level= '||l_billto_tot_amt_due_rem);
2017                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount due remaining at Billto level -> '||l_billto_tot_amt_due_rem);
2018                           if l_billto_tot_amt_due_rem < l_min_dun_amount then
2019                               l_dunning_letters := 'N';
2020                               FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount Due is less than Minimum Dunning Amount, so returning value "N"');
2021                               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - '||' Total Amount due remaining  < Minimum dunning amount');
2022                               return l_dunning_letters;
2023                           else
2024                               FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due is greater than Minimum Dunning Amount, so letter will be sent');
2025                               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount Due Remaining > Minimum Dunning Amount');
2026                           end if;
2027                 else
2028                 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Minimum Dunning amount does not exist at Billto level for Invoice currency code '||l_invoice_currency_code);
2029                 WriteLog(G_PKG_NAME || ' ' || l_api_name ||' - '||'Minimum Dunning profile amount does not exist at Billto level ');
2030                 end if;
2031              end loop;
2032              close c_billto_dist_inv_cur;
2033         elsif l_cust_prof_chk = 'BILLTOACCOUNT' then
2034                open c_billto_dist_inv_cur(l_site_use_id, l_org_id);
2035                loop
2036 		             fetch c_billto_dist_inv_cur into l_invoice_currency_code;
2037                        if c_billto_dist_inv_cur%notfound then
2038                        exit;
2039                        end if;
2040                        FND_FILE.PUT_LINE(FND_FILE.LOG,' Checking Minimum Dunning amount at Billto level for Invoice Currency code '||l_invoice_currency_code);
2041                        t_site_use_id := get_BR_BillTOID(l_site_use_id);
2042                        billto_min_dunn_amt (l_site_use_id, l_invoice_currency_code, x_min_dun_amount, x_min_dun_invoice_amount);
2043                        l_min_dun_amount         := x_min_dun_amount;
2044        	               l_min_dun_invoice_amount := x_min_dun_invoice_amount;
2045 
2046                        if l_min_dun_amount is not null then
2047                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Invoice Currency Code                          -> '|| l_invoice_currency_code);
2048                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum Dunning Amount at Billto level         -> '||l_min_dun_amount);
2049                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum Dunning Invoice Amount at Billto level -> '||l_min_dun_invoice_amount);
2050 
2051                        FND_FILE.PUT_LINE(FND_FILE.LOG,' Minimum dunning amount        =  '|| l_min_dun_amount);
2052                        FND_FILE.PUT_LINE(FND_FILE.LOG,' Minimum dunning invoice amount=  '|| l_min_dun_invoice_amount);
2053                        l_prf_amt_chk := 'Y';
2054                        l_billto_tot_amt_due_rem  := billto_tot_amt_due_rem(l_site_use_id, l_invoice_currency_code,
2055                        l_min_dun_invoice_amount,l_org_id,l_correspondence_date,l_grace_days, l_dun_disputed_items);
2056                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due remaining at Billto level= '||l_billto_tot_amt_due_rem);
2057                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount due remaining at Billto level -> '||l_billto_tot_amt_due_rem);
2058                                     if l_billto_tot_amt_due_rem < l_min_dun_amount then
2059                                        l_dunning_letters := 'N';
2060                                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due is less than Minimum Dunning Amount, so returning value is "N"');
2061                                        WriteLog(G_PKG_NAME || ' ' || l_api_name || 'Total Amount due remaining < Minimum Dunning Amount,  so cant send dunning letters');
2062                                        return l_dunning_letters;
2063                                     else
2064                                       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due is greater than Minimum Dunning Amount, so letter will be sent');
2065                                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount Due Remaining > Minimum Dunning Amount');
2066                                     end if;
2067                        else
2068                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Minimum Dunning amount does not exist at Billto level for Invoice currency code '||l_invoice_currency_code);
2069                        WriteLog(G_PKG_NAME || ' ' || l_api_name ||'Minimum Dunning Profile amount doesnt exist at Billto level ');
2070                        end if;
2071               end loop;
2072                      If     l_prf_amt_chk = 'Y' and l_dunning_letters  = 'Y' then
2073                             return l_dunning_letters;
2074                      elsif  l_prf_amt_chk = 'Y' and l_dunning_letters  = 'N' then
2075                             return l_dunning_letters;
2076                      else  --check at account level if profile amts doesn't exist for all the currencies at billto level
2077                             FND_FILE.PUT_LINE(FND_FILE.LOG,'Hence Check Minimum Dunning Profile amount at Account level');
2078                             open c_acc_dist_inv_cur (l_cust_account_id, l_org_id);
2079                             loop
2080 		                        fetch c_acc_dist_inv_cur into l_invoice_currency_code;
2081 		                        if c_acc_dist_inv_cur%notfound then
2082 		                        exit;
2083 		                        end if;
2084 		                        FND_FILE.PUT_LINE(FND_FILE.LOG, ' Checking Minimum Dunning amount at Account level for Invoice Currency code '||l_invoice_currency_code);
2085        	                    acc_min_dunn_amt (l_cust_account_id,l_invoice_currency_code,x_min_dun_amount,x_min_dun_invoice_amount);
2086        	                    l_min_dun_amount         := x_min_dun_amount;
2087        	                    l_min_dun_invoice_amount := x_min_dun_invoice_amount;
2088 
2089 	                             if l_min_dun_amount is not null then
2090 	                             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Invoice Currency Code                           -> '|| l_invoice_currency_code);
2091                                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum Dunning Amount at Account level         -> '||l_min_dun_amount);
2092                                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum Dunning invoice amount at Account level -> '||l_min_dun_invoice_amount);
2093 
2094                                FND_FILE.PUT_LINE(FND_FILE.LOG, ' Minimum Dunning Amount        =  '|| l_min_dun_amount);
2095                                FND_FILE.PUT_LINE(FND_FILE.LOG, ' Minimum Dunning invoice amount=  '|| l_min_dun_invoice_amount);
2096 	                                  l_acc_tot_amt_due_rem :=  acc_tot_amt_due_rem(l_cust_account_id, l_invoice_currency_code
2097                                   , l_min_dun_invoice_amount,l_org_id,l_correspondence_date,l_grace_days, l_dun_disputed_items);
2098                                   WriteLog(G_PKG_NAME || ' ' || l_api_name ||' - Total Amount due remaining at Account level -> '||l_acc_tot_amt_due_rem);
2099                                   FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due remaining at Account level= '||l_acc_tot_amt_due_rem);
2100 
2101                                   if   l_acc_tot_amt_due_rem < l_min_dun_amount then
2102                                        l_dunning_letters := 'N';
2103                                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due is less than Minimum Dunning Amount, so returning value is "N"');
2104                                        WriteLog(G_PKG_NAME || ' ' || l_api_name || 'Total Amount due remaining  < Minimum Dunning Amount,so cant send dunning letters');
2105                                        return l_dunning_letters;
2106                                   else
2107                                       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due is greater than Minimum Dunning Amount, so letter will be sent');
2108                                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount Due Remaining > Minimum Dunning Amount');
2109                                   end if;
2110                               else
2111                                 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Minimum Dunning amount does not exist at Account level for Invoice currency code '||l_invoice_currency_code);
2112                                 WriteLog(G_PKG_NAME || ' ' || l_api_name ||'Minimum Dunning Profile amount doesnt exist at Account level ');
2113                               end if;
2114                           end loop;
2115                           close c_acc_dist_inv_cur;
2116                      End if;
2117         elsif  l_cust_prof_chk = 'ACCOUNT' then
2118                open c_acc_dist_inv_cur (l_cust_account_id,l_org_id);
2119            loop
2120 		             fetch c_acc_dist_inv_cur into l_invoice_currency_code;
2121 		             if c_acc_dist_inv_cur%notfound then
2122 		             exit;
2123 		             end if;
2124 		             FND_FILE.PUT_LINE(FND_FILE.LOG, ' Dunning amount at Account level for Invoice Currency code '||l_invoice_currency_code);
2125        	         acc_min_dunn_amt (l_cust_account_id,l_invoice_currency_code,x_min_dun_amount,x_min_dun_invoice_amount);
2126        	         l_min_dun_amount         := x_min_dun_amount;
2127        	         l_min_dun_invoice_amount := x_min_dun_invoice_amount;
2128 
2129 	               if l_min_dun_amount is not null then
2130 	               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Invoice Currency Code                           -> '|| l_invoice_currency_code);
2131                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum Dunning Amount at Account level         -> '||l_min_dun_amount);
2132                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Minimum Dunning invoice amount at Account level -> '||l_min_dun_invoice_amount);
2133 
2134                  FND_FILE.PUT_LINE(FND_FILE.LOG, ' Minimum Dunning Amount        =  '|| l_min_dun_amount);
2135                  FND_FILE.PUT_LINE(FND_FILE.LOG, ' Minimum Dunning invoice amount=  '|| l_min_dun_invoice_amount);
2136 	                        l_acc_tot_amt_due_rem :=  acc_tot_amt_due_rem(l_cust_account_id, l_invoice_currency_code
2137                                            , l_min_dun_invoice_amount, l_org_id,l_correspondence_date,l_grace_days, l_dun_disputed_items);
2138                           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  '||'Total Amount due remaining at Account level -> '||l_acc_tot_amt_due_rem);
2139                           FND_FILE.PUT_LINE(FND_FILE.LOG,'Total Amount due remaining at Account level= '||l_acc_tot_amt_due_rem);
2140                           if   l_acc_tot_amt_due_rem < l_min_dun_amount then
2141                                l_dunning_letters := 'N';
2142                                FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due is less than Minimum Dunning Amount, so returning value is "N"');
2143                                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount due remaining  < Minimum dunning amount, so cant send dunning letters');
2144                                return l_dunning_letters;
2145                          else
2146                               FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Amount due is greater than Minimum Dunning Amount, so letter will be sent');
2147                               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Total Amount Due Remaining > Minimum Dunning Amount');
2148                          end if;
2149                 else
2150                   FND_FILE.PUT_LINE(FND_FILE.LOG, 'Minimum Dunning amount does not exist at Account level for Invoice currency code '||l_invoice_currency_code);
2151                   WriteLog(G_PKG_NAME || ' ' || l_api_name ||'Minimum Dunning Profile amount doesnt exist at Account level ');
2152                 end if;
2153          end loop;
2154               close c_acc_dist_inv_cur;
2155     End if;   ---end if of if l_cust_prof_chk = 'BILL_TO' then
2156   End if;   -- end if of if l_running_level='ACCOUNT' and l_cust_account_id is not null then
2157 END if;  --end if of if l_check_dunn_profile = 'Y' then
2158   IF l_dunning_letters = 'Y' then
2159   FND_FILE.PUT_LINE(FND_FILE.LOG, 'Returning value= '||l_dunning_letters);
2160   END IF;
2161   return l_dunning_letters;
2162 Exception
2163 when others then
2164 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE -> '||SQLCODE);
2165 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM -> '||SQLERRM);
2166    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2167    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2168 End  DunningMinAmountCheck;
2169 /*
2170 Total accounted amount due remaining at Account level
2171 - Called to check total amt due >= 0*/
2172 Function acct_total_acctd_amt(
2173           p_cust_account_id     IN  number
2174          ,p_org_id              IN  number
2175          ,p_correspondence_date IN DATE  DEFAULT sysdate
2176          ,p_grace_days          IN number  DEFAULT 0
2177          ,p_dun_disputed_items  IN VARCHAR2  DEFAULT 'N'
2178          )return number is
2179 
2180           l_acct_tot_acctd_amt_rem    number;
2181           l_acct_cm_tot_acctd_amt_rem number;
2182           l_acct_total_acctd_amount   number;
2183           l_api_name               CONSTANT VARCHAR2(30) := 'acct_total_acctd_amt';
2184 
2185         cursor c_acct_tot_acctd_amt_rem (
2186                  p_cust_account_id number,
2187                  p_org_id number,
2188                  p_corr_date date,
2189                  p_grace_days number,
2190                  p_include_dis_items varchar) is
2191         select nvl(sum(aps.acctd_amount_due_remaining),0)
2192         from ar_payment_schedules_all aps,iex_delinquencies_all dd
2193         where dd.payment_schedule_id = aps.payment_schedule_id
2194         and aps.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')
2195         and aps.status='OP'
2196         and (trunc(aps.due_date) + p_grace_days) <= p_correspondence_date
2197         and nvl(aps.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(aps.amount_in_dispute,0), 0)
2198         and aps.customer_id=p_cust_account_id
2199         and aps.amount_due_remaining > 0
2200         and aps.org_id=p_org_id;
2201 
2202         cursor c_acct_cm_tot_acctd_amt_rem (
2203                p_cust_account_id number,
2204                p_org_id number) is
2205         select nvl(sum(acctd_amount_due_remaining),0)
2206         from  ar_payment_schedules_all
2207         where class IN ('CM','PMT')
2208         and   status = 'OP'
2209         and   customer_id = p_cust_account_id
2210         and   org_id = p_org_id;
2211 
2212 Begin
2213      l_acct_tot_acctd_amt_rem    := 0;
2214      l_acct_cm_tot_acctd_amt_rem := 0;
2215      l_acct_total_acctd_amount   := 0;
2216 
2217      open c_acct_tot_acctd_amt_rem(p_cust_account_id,p_org_id,p_correspondence_date,p_grace_days,p_dun_disputed_items);
2218 	   fetch c_acct_tot_acctd_amt_rem into l_acct_tot_acctd_amt_rem;
2219 	   close c_acct_tot_acctd_amt_rem;
2220 
2221 	   open c_acct_cm_tot_acctd_amt_rem(p_cust_account_id,p_org_id);
2222 	   fetch c_acct_cm_tot_acctd_amt_rem into l_acct_cm_tot_acctd_amt_rem;
2223 	   close c_acct_cm_tot_acctd_amt_rem;
2224 
2225      l_acct_total_acctd_amount:=nvl(l_acct_tot_acctd_amt_rem,0)+nvl(l_acct_cm_tot_acctd_amt_rem,0);
2226 
2227      return l_acct_total_acctd_amount;
2228 Exception
2229 when others then
2230 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE - '||SQLCODE);
2231 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM - '||SQLERRM);
2232    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2233    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2234 End acct_total_acctd_amt;
2235 
2236 /*
2237 Total accounted amount due remaining at billto level
2238 - Called to check total amt due >= 0*/
2239 Function billto_total_acctd_amt(
2240           p_site_use_id         IN  number
2241          ,p_org_id              IN  number
2242          ,p_correspondence_date IN DATE  DEFAULT sysdate
2243          ,p_grace_days          IN number  DEFAULT 0
2244          ,p_include_dis_items   IN VARCHAR2  DEFAULT 'N'
2245          )return number is
2246 
2247           l_api_name               CONSTANT VARCHAR2(30) := 'billto_total_acctd_amt';
2248           l_billto_tot_acctd_amt_rem    number:=0;
2249           l_billto_cm_tot_acctd_amt_rem number:=0;
2250           l_billto_total_acctd_amount   number:=0;
2251 
2252        cursor c_billto_tot_acctd_amt_rem (p_site_use_id number,p_org_id number,
2253        p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
2254        select nvl(sum(aps.acctd_amount_due_remaining),0)
2255        from ar_payment_schedules_all aps,iex_delinquencies_all dd
2256        where dd.payment_schedule_id = aps.payment_schedule_id
2257        and aps.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')
2258        and aps.status='OP'
2259        and (trunc(aps.due_date) + p_grace_days) <= p_corr_date
2260        and nvl(aps.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(aps.amount_in_dispute,0), 0)
2261        and aps.customer_site_use_id=p_site_use_id
2262        and aps.amount_due_remaining > 0
2263        and aps.org_id=p_org_id;
2264 
2265        cursor c_billto_cm_tot_acctd_amt_rem (p_site_use_id number,p_org_id number) is
2266        select nvl(sum(acctd_amount_due_remaining),0)
2267        from  ar_payment_schedules_all
2268        where class IN ('CM','PMT')
2269        and   status = 'OP'
2270        and   customer_site_use_id = p_site_use_id
2271        and org_id = p_org_id;
2272 
2273 Begin
2274           open c_billto_tot_acctd_amt_rem(p_site_use_id,p_org_id,p_correspondence_date,p_grace_days,p_include_dis_items);
2275 	        fetch c_billto_tot_acctd_amt_rem into l_billto_tot_acctd_amt_rem;
2276 	        close c_billto_tot_acctd_amt_rem;
2277 
2278 	        open c_billto_cm_tot_acctd_amt_rem(p_site_use_id,p_org_id);
2279 	        fetch c_billto_cm_tot_acctd_amt_rem into l_billto_cm_tot_acctd_amt_rem;
2280 	        close c_billto_cm_tot_acctd_amt_rem;
2281 
2282           l_billto_total_acctd_amount := nvl(l_billto_tot_acctd_amt_rem,0)+nvl(l_billto_cm_tot_acctd_amt_rem,0);
2283 
2284           return l_billto_total_acctd_amount;
2285 Exception
2286 when others then
2287 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE - '||SQLCODE);
2288 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM - '||SQLERRM);
2289    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2290    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2291 End billto_total_acctd_amt;
2292 
2293 /* To get Minimum dunning amount and Minimum dunning invoice amount at account level*/
2294 Procedure  acct_prf_amt(p_cust_account_id in number
2295            , p_org_id in number
2296            , x_min_currency_code          OUT NOCOPY varchar2
2297            , x_min_dun_amount             OUT NOCOPY number
2298            , x_min_dun_invoice_amount     OUT NOCOPY number)
2299 is
2300 
2301            l_api_name               CONSTANT VARCHAR2(30) := 'acct_prf_amt';
2302            cursor c_account (p_cust_account_id number,p_org_id number) is
2303            select currency_code, nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
2304            from hz_cust_profile_amts
2305            where cust_account_id = p_cust_account_id and currency_code = (
2306            SELECT  sob.currency_code FROM ar_system_parameters_all sp, gl_sets_of_books sob
2307            WHERE   sob.set_of_books_id = sp.set_of_books_id
2308 	         and sp.org_id = p_org_id)
2309            and site_use_id is null;
2310 
2311            l_min_dun_amount number;
2312            l_min_dun_invoice_amount number;
2313            l_min_currency_code varchar2(15);
2314 Begin
2315         open c_account(p_cust_account_id,p_org_id);
2316 	      fetch c_account into l_min_currency_code, l_min_dun_amount, l_min_dun_invoice_amount;
2317 	      close c_account;
2318 
2319 	      x_min_currency_code            := l_min_currency_code;
2320         x_min_dun_amount               := l_min_dun_amount;
2321         x_min_dun_invoice_amount       := l_min_dun_invoice_amount;
2322 Exception
2323 when others then
2324 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE -> '||SQLCODE);
2325 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM -> '||SQLERRM);
2326    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2327    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2328 End acct_prf_amt;
2329 
2330 /* To get Minimum dunning amount and Minimum dunning invoice amount at Billto level*/
2331 Procedure  billto_prf_amt(p_site_use_id in number
2332            , p_org_id in number
2333            , x_min_currency_code      OUT NOCOPY varchar2
2334            , x_min_dun_amount         OUT NOCOPY number
2335            , x_min_dun_invoice_amount OUT NOCOPY number)
2336 is
2337 
2338           l_api_name               CONSTANT VARCHAR2(30) := 'billto_prf_amt';
2339           cursor c_billto (p_customer_site_use_id number,p_org_id number) is
2340           select currency_code, nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0) from hz_cust_profile_amts
2341           where site_use_id = p_customer_site_use_id and currency_code = (
2342           SELECT  sob.currency_code FROM ar_system_parameters_all sp, gl_sets_of_books sob
2343           WHERE   sob.set_of_books_id = sp.set_of_books_id
2344 	        and sp.org_id = p_org_id);
2345 
2346 	        l_min_dun_amount number;
2347           l_min_dun_invoice_amount number;
2348           l_min_currency_code varchar2(15);
2349 Begin
2350           open c_billto(p_site_use_id,p_org_id);
2351           fetch c_billto into l_min_currency_code, l_min_dun_amount, l_min_dun_invoice_amount;
2352           close c_billto;
2353 
2354           x_min_currency_code            := l_min_currency_code;
2355           x_min_dun_amount               := l_min_dun_amount;
2356           x_min_dun_invoice_amount       := l_min_dun_invoice_amount;
2357 Exception
2358 when others then
2359 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE - '||SQLCODE);
2360 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM - '||SQLERRM);
2361    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2362    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2363 end billto_prf_amt;
2364 
2365 /* Minimum dunning amount and Minimum dunning invoice amount at account level
2366 for specific currency*/
2367 Procedure acc_min_dunn_amt (p_cust_account_id        in number
2368                           , p_invoice_currency_code  in varchar2
2369                           , x_min_dun_amount         OUT NOCOPY number
2370                           , x_min_dun_invoice_amount OUT NOCOPY number)
2371 is
2372          l_api_name               CONSTANT VARCHAR2(30) := 'acc_min_dunn_amt';
2373          cursor c_acc_min_dunn_amt (p_cust_account_id number, p_invoice_currency_code varchar2) is
2374 	       select nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
2375 	       from hz_cust_profile_amts
2376 	       where cust_account_id = p_cust_account_id
2377 	       and currency_code = p_invoice_currency_code
2378 	       and site_use_id is null;
2379 
2380 	       l_min_dun_amount     number;
2381          l_min_dun_invoice_amount number;
2382 Begin
2383             open c_acc_min_dunn_amt (p_cust_account_id, p_invoice_currency_code);
2384 		        fetch c_acc_min_dunn_amt into l_min_dun_amount, l_min_dun_invoice_amount;
2385 		        x_min_dun_amount                := l_min_dun_amount;
2386 		        x_min_dun_invoice_amount        := l_min_dun_invoice_amount;
2387             close c_acc_min_dunn_amt;
2388 Exception
2389 when others then
2390 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE - '||SQLCODE);
2391 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM - '||SQLERRM);
2392    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2393    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2394 End acc_min_dunn_amt;
2395 
2396 /* Total amount due remaining in functional currency at account level */
2397 Function acc_tot_amt_due_rem(p_cust_account_id number, p_invoice_currency_code varchar2 -- for 3rd case
2398                            ,  p_min_dun_invoice_amount number,p_org_id number
2399                            ,  p_correspondence_date date,  p_grace_days number
2400                            ,  p_include_dis_items varchar2)
2401 return number
2402 is
2403 
2404         l_api_name               CONSTANT VARCHAR2(30) := 'acc_tot_amt_due_rem';
2405         cursor c_acc_tot_amt_due_rem (p_cust_account_id number, p_invoice_currency_code varchar2, p_min_dun_invoice_amount number
2406         , p_org_id number,p_correspondence_date date,  p_grace_days number,  p_include_dis_items varchar2)
2407         is
2408 	      select nvl(sum(a.amount_due_remaining),0)
2409         from ar_payment_schedules_all a, iex_delinquencies_all b
2410         where a.payment_schedule_id = b.payment_schedule_id
2411         and b.status in ('DELINQUENT', 'PREDELINQUENT')
2412 	      AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
2413         and a.status = 'OP'
2414 	      and (trunc(a.due_date) + p_grace_days) <= p_correspondence_date
2415 	      and nvl(a.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(a.amount_in_dispute,0), 0)
2416         and b.cust_account_id = p_cust_account_id
2417         and a.invoice_currency_code = p_invoice_currency_code
2418         and a.amount_due_remaining >= p_min_dun_invoice_amount
2419 	      and b.org_id = p_org_id;
2420 
2421         cursor c_cm_ar_amount_account_curr (p_cust_account_id number, p_invoice_currency_code varchar2, p_org_id number)
2422         is
2423         select nvl(amount_due_remaining,0)  from  ar_payment_schedules_all where
2424         class IN ('CM','PMT')
2425         and   status = 'OP'
2426         and   invoice_currency_code = p_invoice_currency_code
2427         and   customer_id = p_cust_account_id
2428         and   org_id = p_org_id;
2429 
2430         l_tot_amt_due_rem number:=0;
2431         l_cm_ar_amount number:=0;
2432         l_cm_ar_total_amount number:=0;
2433 Begin
2434         open c_acc_tot_amt_due_rem (p_cust_account_id, p_invoice_currency_code, p_min_dun_invoice_amount
2435                                      , p_org_id, p_correspondence_date,  p_grace_days,  p_include_dis_items );
2436         fetch c_acc_tot_amt_due_rem into l_tot_amt_due_rem;
2437         close c_acc_tot_amt_due_rem;
2438 
2439         open c_cm_ar_amount_account_curr(p_cust_account_id, p_invoice_currency_code, p_org_id);
2440               loop
2441               fetch c_cm_ar_amount_account_curr into l_cm_ar_amount;
2442 	            if c_cm_ar_amount_account_curr%notfound then
2443 		             exit;
2444 		          end if;
2445 	            l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
2446 	            end loop;
2447 	      close c_cm_ar_amount_account_curr;
2448 		    FND_FILE.PUT_LINE(FND_FILE.LOG,'Total Invoice amount                        = '||l_tot_amt_due_rem);
2449         FND_FILE.PUT_LINE(FND_FILE.LOG,'Credit memos and open account Receipts total= '||l_cm_ar_total_amount);
2450 
2451         l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_cm_ar_total_amount,0);-- substracting sum of credit memo amount and ar receipt amount from total amount due
2452 	                                                                       --(but here i used + sign because the credit memo and account recipt amount will be negitive values)
2453 
2454       Return l_tot_amt_due_rem;
2455 Exception
2456 when others then
2457 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE - '||SQLCODE);
2458 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM - '||SQLERRM);
2459    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2460    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2461 End acc_tot_amt_due_rem;
2462 
2463 /* Minimum dunning amount and Minimum dunning invoice amount at billto level
2464 for specific currency*/
2465 Procedure billto_min_dunn_amt (p_site_use_id  in number
2466                              , p_invoice_currency_code in varchar2
2467                              , x_min_dun_amount    OUT NOCOPY number
2468                              , x_min_dun_invoice_amount OUT NOCOPY number)
2469 is
2470          l_api_name               CONSTANT VARCHAR2(30) := 'billto_min_dunn_amt';
2471          cursor c_billto_min_dunn_amt (p_site_use_id number, p_invoice_currency_code varchar2) is
2472 	       select nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
2473 	       from hz_cust_profile_amts
2474 	       where site_use_id = p_site_use_id
2475 	       and currency_code = p_invoice_currency_code;
2476 
2477 	       l_min_dun_amount     number;
2478          l_min_dun_invoice_amount number;
2479 Begin
2480         open c_billto_min_dunn_amt(p_site_use_id, p_invoice_currency_code);
2481 		    fetch c_billto_min_dunn_amt into l_min_dun_amount, l_min_dun_invoice_amount;
2482 		    close c_billto_min_dunn_amt;
2483 
2484         x_min_dun_amount         := l_min_dun_amount;
2485         x_min_dun_invoice_amount := l_min_dun_invoice_amount;
2486 Exception
2487 when others then
2488 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE - '||SQLCODE);
2489 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM - '||SQLERRM);
2490    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2491    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2492 end billto_min_dunn_amt;
2493 
2494 /* Total amount due remaining in functional currency at billto level */
2495 Function billto_tot_amt_due_rem (p_site_use_id number, p_invoice_currency_code varchar2  --for 3rd case
2496                                , p_min_dun_invoice_amount number,p_org_id number, p_correspondence_date date
2497                                , p_grace_days number, p_include_dis_items varchar2)
2498 Return number
2499 is
2500         l_api_name               CONSTANT VARCHAR2(30) := 'billto_tot_amt_due_rem';
2501         cursor c_billto_tot_amt_due_rem (p_site_use_id number, p_invoice_currency_code varchar2
2502         , p_min_dun_invoice_amount number,p_org_id number, p_correspondence_date date, p_grace_days number
2503         , p_include_dis_items varchar2)
2504         is
2505 	      select nvl(sum(a.amount_due_remaining),0)
2506         from ar_payment_schedules_all a, iex_delinquencies_all b
2507         where a.payment_schedule_id = b.payment_schedule_id
2508         and b.status in ('DELINQUENT', 'PREDELINQUENT')
2509 	      AND a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change)
2510         and a.status = 'OP'
2511         and (trunc(a.due_date) + p_grace_days) <= p_correspondence_date
2512 	      and nvl(a.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(a.amount_in_dispute,0), 0)
2513         and b.customer_site_use_id = p_site_use_id
2514         and a.invoice_currency_code = p_invoice_currency_code
2515         and a.amount_due_remaining >= p_min_dun_invoice_amount
2516 	      and b.org_id = p_org_id;
2517 
2518         cursor c_cm_ar_amount_billto_curr (p_site_use_id number, p_invoice_currency_code varchar2, p_org_id number) is
2519         select nvl(amount_due_remaining,0)
2520         from  ar_payment_schedules_all
2521         where class IN ('CM' ,'PMT')
2522         and status = 'OP'
2523         and invoice_currency_code = p_invoice_currency_code
2524         and CUSTOMER_SITE_USE_ID = p_site_use_id
2525         and org_id = p_org_id;
2526 
2527         l_tot_amt_due_rem number:=0;
2528         l_cm_ar_amount number:=0;
2529         l_cm_ar_total_amount number:=0;
2530 Begin
2531 
2532         open c_billto_tot_amt_due_rem (p_site_use_id, p_invoice_currency_code,p_min_dun_invoice_amount
2533         , p_org_id, p_correspondence_date, p_grace_days, p_include_dis_items);
2534 		    fetch c_billto_tot_amt_due_rem into l_tot_amt_due_rem;
2535 		    close c_billto_tot_amt_due_rem;
2536 
2537         open c_cm_ar_amount_billto_curr(p_site_use_id, p_invoice_currency_code,p_org_id);
2538 	            loop
2539 	                 fetch c_cm_ar_amount_billto_curr into l_cm_ar_amount;
2540 	                  if c_cm_ar_amount_billto_curr%notfound then
2541 		                  exit;
2542 		                end if;
2543       	            l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
2544              end loop;
2545 	      close c_cm_ar_amount_billto_curr;
2546 
2547         FND_FILE.PUT_LINE(FND_FILE.LOG,'Total Invoice amount=                         '||l_tot_amt_due_rem);
2548         FND_FILE.PUT_LINE(FND_FILE.LOG,'Credit memos and open account Receipts total= '||l_cm_ar_total_amount);
2549 		    l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_cm_ar_total_amount,0);-- substracting sum of credit memo amount and ar receipt amount from total amount due
2550 	                                                                       --(but here i used + sign because the credit memo and account recipt amount will be negitive values)
2551 
2552         Return l_tot_amt_due_rem;
2553 Exception
2554 when others then
2555 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE - '||SQLCODE);
2556 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM - '||SQLERRM);
2557    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2558    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2559 End billto_tot_amt_due_rem;
2560 
2561 Function  amount_account(p_cust_account_id in number, p_org_id in number,p_correspondence_date date
2562        , p_grace_days in number, p_dun_disputed_items in varchar2, p_min_currency_code in varchar2
2563        , p_min_dun_amount in number,p_min_dun_invoice_amount in number)-- for 2nd case
2564 return number
2565 IS
2566       l_api_name               CONSTANT VARCHAR2(30) := 'amount_account';
2567       cursor c_amount_account (p_cust_account_id number, p_org_id number, p_correspondence_date date, p_grace_days number, p_include_dis_items varchar2) is
2568       select nvl(a.amount_due_remaining,0), a.invoice_currency_code, class
2569       from ar_payment_schedules_all a, iex_delinquencies_all b
2570       where a.payment_schedule_id = b.payment_schedule_id
2571       and b.status in ('DELINQUENT', 'PREDELINQUENT')
2572 	    AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
2573       and a.status = 'OP'
2574 	    and (trunc(a.due_date) + p_grace_days) <= p_correspondence_date
2575 	    and nvl(a.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(a.amount_in_dispute,0), 0)
2576       and b.cust_account_id = p_cust_account_id
2577 	    and b.org_id = p_org_id;
2578 
2579 	    cursor c_cm_ar_amount_account (p_cust_account_id number,p_org_id number) is
2580       select nvl(amount_due_remaining,0) , invoice_currency_code from  ar_payment_schedules_all
2581       where   class IN ('CM','PMT')
2582       and status = 'OP'
2583       and customer_id = p_cust_account_id
2584       and org_id = p_org_id;
2585 
2586 	   l_amount_due_remaining   number:=0;
2587      l_invoice_currency_code  varchar2(15);
2588      l_class                  varchar2(20);
2589      l_convert_amount         number:=0;
2590      l_invoice_amount         number:=0;
2591      l_amount                 number:=0;
2592 
2593      l_cm_ar_total_amount     number:=0;
2594      l_cm_ar_amount           number:=0;
2595      l_cm_ar_currency_code    varchar2(15);
2596      l_rate_type              varchar2(100);
2597 Begin
2598 l_rate_type          :=  nvl(fnd_profile.value('IEX_COLLECTIONS_RATE_TYPE'), 'Corporate');
2599 FND_FILE.PUT_LINE(FND_FILE.LOG, 'IEX: Collections Rate Type =  '||l_rate_type);
2600 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Functional Currency code=     '||p_min_currency_code);
2601           open c_amount_account(p_cust_account_id,p_org_id, p_correspondence_date, p_grace_days, p_dun_disputed_items);
2602 	        loop
2603 		             fetch c_amount_account into l_amount_due_remaining, l_invoice_currency_code, l_class;
2604 		                 if c_amount_account%notfound then
2605 		                 exit;
2606 		                 end if;
2607 		                 if (l_invoice_currency_code <> p_min_currency_code) then
2608 		                    begin
2609 		                           l_convert_amount := gl_currency_api.convert_amount(
2610 		                                               x_from_currency =>   l_invoice_currency_code
2611 		                                              ,x_to_currency =>     p_min_currency_code
2612 		                                              ,x_conversion_date => sysdate
2613 		                                              ,x_conversion_type => l_rate_type
2614 		                                              ,x_amount =>          l_amount_due_remaining);
2615 	             	         exception
2616 		                          when others then
2617 			                        FND_FILE.PUT_LINE(FND_FILE.LOG,'error in currency conversion..pl check whether exchange rates are defined');
2618 			                        FND_FILE.PUT_LINE(FND_FILE.LOG,sqlerrm);
2619 			                        return l_amount;
2620                          end;
2621 		                  		    l_invoice_amount := nvl(l_convert_amount,0);
2622 		                          if l_invoice_amount > p_min_dun_invoice_amount then
2623 		                             l_amount:=nvl(l_amount,0) + nvl(l_invoice_amount,0);
2624 		                          end if;
2625 
2626 	                	 else
2627 
2628 		                         l_invoice_amount := nvl(l_amount_due_remaining,0);
2629 		                         if l_invoice_amount > p_min_dun_invoice_amount then
2630 		                            l_amount:=nvl(l_amount,0) + nvl(l_invoice_amount,0);
2631 		                         end if;
2632                 		 end if;
2633 	             end loop;
2634 	      close c_amount_account;
2635 	             FND_FILE.PUT_LINE(FND_FILE.LOG, 'Total Invoice amount=                '||l_amount);
2636         open c_cm_ar_amount_account(p_cust_account_id,p_org_id);
2637 	            loop
2638 	            fetch c_cm_ar_amount_account into l_cm_ar_amount,l_cm_ar_currency_code;
2639 	                  if c_cm_ar_amount_account%notfound then
2640 		              --     FND_FILE.PUT_LINE(FND_FILE.LOG, 'No open Account Receipts and credit memos');
2641 		                exit;
2642 		                end if;
2643 		                if (l_cm_ar_currency_code <> p_min_currency_code) then
2644 	                  begin
2645 		                      l_convert_amount := gl_currency_api.convert_amount(
2646 		                                          x_from_currency =>   l_cm_ar_currency_code
2647 		                                         ,x_to_currency =>     p_min_currency_code
2648 		                                         ,x_conversion_date => sysdate
2649 		                                         ,x_conversion_type => l_rate_type
2650 		                                         ,x_amount =>          l_cm_ar_amount);
2651 		                     l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_convert_amount,0);
2652 		                     exception
2653 		                     when others then
2654 			                      FND_FILE.PUT_LINE(FND_FILE.LOG,'error in currency conversion..pl check whether exchange rates are defined');
2655                             FND_FILE.PUT_LINE(FND_FILE.LOG,sqlerrm);
2656 			                      return l_amount;
2657                         end;
2658 	               else
2659 		                    l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
2660 	               end if;
2661 	           end loop;
2662 	           close c_cm_ar_amount_account;
2663       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Credit memos and open account Receipts total=  '||l_cm_ar_total_amount);
2664 
2665            l_amount := nvl(l_amount,0) + nvl(l_cm_ar_total_amount,0) ;-- substracting sum of credit memo amount and ar receipt amount from total amount due
2666 	                                              --(but here i used + sign because the credit memo and account recipt amount will be negitive values)
2667            Return l_amount;
2668   Exception
2669 when others then
2670    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE - '||SQLCODE);
2671    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM - '||SQLERRM);
2672    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2673    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2674 End amount_account;
2675 
2676 Function amount_billto(p_site_use_id in number,p_org_id in number,p_correspondence_date in date -- for 2nd case
2677 ,p_grace_days in number, p_dun_disputed_items in varchar2, p_min_currency_code in varchar2, p_min_dun_amount in number
2678 ,p_min_dun_invoice_amount in number)
2679 return number
2680 is
2681         l_api_name               CONSTANT VARCHAR2(30) := 'amount_billto';
2682         cursor c_amount_billto (p_site_use_id number, p_org_id number, p_correspondence_date date, p_grace_days number, p_include_dis_items varchar2) is
2683         select nvl(a.amount_due_remaining, 0), a.invoice_currency_code, class
2684         from ar_payment_schedules_all a, iex_delinquencies_all b     --Changed to ar_payment_schedules_all for bug#5652343 by gnramasa on 07-Mar-2007
2685         where a.payment_schedule_id = b.payment_schedule_id
2686         and b.status in ('DELINQUENT', 'PREDELINQUENT')
2687 	      AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR') -- Bills Receivables change
2688         and a.status = 'OP'
2689 	      and (trunc(a.due_date) + p_grace_days) <= p_correspondence_date
2690 	      and nvl(a.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(a.amount_in_dispute,0), 0)
2691         and b.customer_site_use_id = p_site_use_id
2692 	      and b.org_id = p_org_id;
2693 
2694 	      cursor c_cm_ar_amount_billto (p_site_use_id number,p_org_id number) is
2695         select nvl(amount_due_remaining,0), invoice_currency_code
2696         from  ar_payment_schedules_all
2697         where   class IN ('CM' ,'PMT')
2698         and status = 'OP'
2699         and CUSTOMER_SITE_USE_ID = p_site_use_id
2700         and org_id = p_org_id;
2701 
2702      l_amount_due_remaining   number;
2703      l_invoice_currency_code  varchar2(15);
2704      l_class                  varchar2(20);
2705      l_convert_amount         number;
2706      l_invoice_amount         number;
2707      l_amount                 number;
2708 
2709      l_cm_ar_total_amount     number;
2710      l_cm_ar_amount           number;
2711      l_cm_ar_currency_code    varchar2(15);
2712      l_rate_type              varchar2(100);
2713 Begin
2714 l_rate_type          :=  nvl(fnd_profile.value('IEX_COLLECTIONS_RATE_TYPE'), 'Corporate');
2715 FND_FILE.PUT_LINE(FND_FILE.LOG, 'IEX: Collections Rate Type =  '||l_rate_type);
2716 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Functional Currency code=     '||p_min_currency_code);
2717 
2718          open c_amount_billto(p_site_use_id, p_org_id, p_correspondence_date, p_grace_days, p_dun_disputed_items);
2719 	       loop
2720 		     fetch c_amount_billto into l_amount_due_remaining, l_invoice_currency_code, l_class;
2721 		                 if c_amount_billto%notfound then
2722 		                 exit;
2723 		                 end if;
2724 		                 if (l_invoice_currency_code <> p_min_currency_code) then
2725 		                 begin
2726 		                              l_convert_amount := gl_currency_api.convert_amount(
2727 		                                                 x_from_currency =>   l_invoice_currency_code
2728 		                                                ,x_to_currency =>     p_min_currency_code
2729 		                                                ,x_conversion_date => sysdate
2730 		                                                ,x_conversion_type => l_rate_type
2731 		                                                ,x_amount =>          l_amount_due_remaining);
2732 
2733 		                    exception
2734 		                    when others then
2735 			                         FND_FILE.PUT_LINE(FND_FILE.LOG,'error in currency conversion..pl check whether exchange rates are defined');
2736 			                         FND_FILE.PUT_LINE(FND_FILE.LOG,sqlerrm);
2737 			                         return l_amount;
2738                         end;
2739 		                       l_invoice_amount := nvl(l_convert_amount,0);
2740 		                       if l_invoice_amount > p_min_dun_invoice_amount then
2741 		                          l_amount:=nvl(l_amount,0) + nvl(l_invoice_amount,0);
2742 		                       end if;
2743 
2744 		               else
2745 		                      l_invoice_amount := nvl(l_amount_due_remaining,0);
2746 		                      if l_invoice_amount > p_min_dun_invoice_amount then
2747 		                         l_amount:=nvl(l_amount,0) + nvl(l_invoice_amount,0);
2748 		                      end if;
2749               		 end if;
2750 	      end loop;
2751 	      close c_amount_billto;
2752 	      FND_FILE.PUT_LINE(FND_FILE.LOG,'Total Invoice amount=                     '||l_amount);
2753 
2754      open c_cm_ar_amount_billto(p_site_use_id,p_org_id);
2755 		 loop
2756 		 fetch c_cm_ar_amount_billto into l_cm_ar_amount,l_cm_ar_currency_code;
2757 		             if c_cm_ar_amount_billto%notfound then
2758 				         exit;
2759 		             end if;
2760 		             if (l_cm_ar_currency_code <> p_min_currency_code) then
2761 		             begin
2762 			                l_convert_amount := gl_currency_api.convert_amount(
2763 			                x_from_currency => l_cm_ar_currency_code
2764 			              , x_to_currency =>   p_min_currency_code
2765 			              , x_conversion_date => sysdate
2766 			              , x_conversion_type => l_rate_type
2767 			              , x_amount => l_cm_ar_amount);
2768 		            exception
2769 		            when others then
2770 			             FND_FILE.PUT_LINE(FND_FILE.LOG,'error in currency conversion..pl check whether exchange rates are defined');
2771 			             FND_FILE.PUT_LINE(FND_FILE.LOG,sqlerrm);
2772 			             return l_amount;
2773                end;
2774   			               l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_convert_amount,0);
2775 		            else
2776 			                 l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
2777 		            end if;
2778 		end loop;
2779 		close c_cm_ar_amount_billto;
2780     FND_FILE.PUT_LINE(FND_FILE.LOG,'Total of open Account Receipts and credit memos=   '||l_cm_ar_total_amount);
2781 
2782 	 l_amount := nvl(l_amount,0) + nvl(l_cm_ar_total_amount,0) ;-- substracting sum of credit memo amount and ar receipt amount from total amount due
2783 								    --(but here i used + sign because the credit memo and account recipt amount will be negitive values)
2784 Return l_amount;
2785 Exception
2786 when others then
2787    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLCODE - '||SQLCODE);
2788    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  SQLERRM - '||SQLERRM);
2789    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLCODE-->'||SQLCODE);
2790    FND_FILE.PUT_LINE(FND_FILE.LOG, 'SQLERRM-->'||SQLERRM);
2791 End amount_billto;
2792 /*
2793     Overview: This function is to determine if the required min_dunning and min_invoice_dunning amount are
2794               met before sending the dunning letter.
2795    Parameter: p_cust_account_id : if account level then pass the cust_account_id
2796               p_site_use_id : if bill_to level then pass the customer_site_use_id
2797    Return:  'Y' if ok to send dunning letter
2798             'N' if no dunning letter should be sent
2799    creation date: 06/02/2004
2800    author:  ctlee
2801    Note: it is not available in the customer and delinquency level
2802  */
2803 /*FUNCTION DunningMinAmountCheck
2804 (
2805   p_cust_account_id    IN  number
2806   , p_site_use_id        IN  number
2807   , p_org_id IN NUMBER --Added for Bug 10401991 17-Jan-2011 barathsr
2808   , p_grace_days            IN number  DEFAULT 0
2809   , p_dun_disputed_items    IN VARCHAR2  DEFAULT 'N'
2810   , p_correspondence_date   IN DATE  DEFAULT sysdate
2811 
2812 )
2813 
2814 return varchar2 is
2815 
2816     l_dunning_letters varchar2(10);
2817     l_cust_account_id number;
2818     l_site_use_id  number;
2819     l_min_dunning_amount number;
2820     l_min_dunning_invoice_amount number;
2821     l_min_currency_code varchar2(15);
2822 
2823     l_rate_type varchar2(100);
2824     l_amount number;
2825     l_invoice_amount number;
2826     l_convert_amount number;
2827     l_amount_due_remaining number;
2828     l_invoice_currency_code varchar2(15);
2829     l_class varchar2(20);
2830     l_cm_ar_amount number;
2831     l_cm_ar_total_amount number;
2832     l_cm_ar_currency_code varchar2(15);
2833     --Begin Bug 10401991 14-Feb-2011 barathsr
2834     l_org_id number;
2835     l_billto_tot_acctd_amt_rem number;
2836    l_billto_cm_tot_acctd_amt_rem number;
2837    l_billto_total_acctd_amount number;
2838    l_acct_tot_acctd_amt_rem number;
2839    l_acct_cm_tot_acctd_amt_rem number;
2840    l_acct_total_acctd_amount number;
2841    --End Bug 10401991 14-Feb-2011 barathsr
2842 
2843 
2844 
2845     -- there is no status to check if active or not,
2846     -- field expiration_date is null only - not used
2847     -- because there is more than 1 record for the same site_use_id, so we pick the functional currency one
2848     --Begin Bug 10401991 17-Jan-2011 barathsr -- Included org_id parameter wherever applicable.
2849     cursor c_billto (p_customer_site_use_id number,p_org_id number) is
2850       select currency_code, nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0) from hz_cust_profile_amts
2851         where site_use_id = p_customer_site_use_id and currency_code = (
2852           SELECT  sob.currency_code FROM ar_system_parameters_all sp, gl_sets_of_books sob
2853           WHERE   sob.set_of_books_id = sp.set_of_books_id
2854 	  and sp.org_id = p_org_id);
2855 
2856     -- only open status
2857     cursor c_amount_billto (p_site_use_id number,p_org_id number, p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
2858       select nvl(a.amount_due_remaining, 0), a.invoice_currency_code, class
2859         from ar_payment_schedules_all a, iex_delinquencies_all b     --Changed to ar_payment_schedules_all for bug#5652343 by gnramasa on 07-Mar-2007
2860         where a.payment_schedule_id = b.payment_schedule_id
2861         and b.status in ('DELINQUENT', 'PREDELINQUENT')
2862 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR') -- Bills Receivables change
2863         and a.status = 'OP'
2864 	and (trunc(a.due_date) + p_grace_days) <= p_corr_date
2865 	and nvl(a.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(a.amount_in_dispute,0), 0)
2866         and b.customer_site_use_id = p_site_use_id
2867 	and b.org_id = p_org_id;
2868 
2869     cursor c_cm_ar_amount_billto (p_site_use_id number,p_org_id number) is
2870       select nvl(amount_due_remaining,0), invoice_currency_code
2871       from  ar_payment_schedules_all
2872       where   class IN ('CM' ,'PMT')
2873       and status = 'OP'
2874       and CUSTOMER_SITE_USE_ID = p_site_use_id
2875       and org_id = p_org_id;
2876 
2877     cursor c_cm_ar_amount_billto_curr (p_site_use_id number,p_invoice_currency_code varchar,p_org_id number) is
2878       select nvl(amount_due_remaining,0)
2879       from  ar_payment_schedules_all
2880       where class IN ('CM' ,'PMT')
2881       and status = 'OP'
2882       and invoice_currency_code = p_invoice_currency_code
2883       and CUSTOMER_SITE_USE_ID = p_site_use_id
2884       and org_id = p_org_id;
2885 
2886 
2887 
2888 
2889     cursor c_account (p_cust_account_id number,p_org_id number) is
2890       select currency_code, nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
2891       from hz_cust_profile_amts
2892       where cust_account_id = p_cust_account_id and currency_code = (
2893           SELECT  sob.currency_code FROM ar_system_parameters_all sp, gl_sets_of_books sob
2894           WHERE   sob.set_of_books_id = sp.set_of_books_id
2895 	  and sp.org_id = p_org_id)
2896       and site_use_id is null;
2897 
2898     -- only open status
2899     cursor c_amount_account (p_cust_account_id number,p_org_id number, p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
2900       select nvl(a.amount_due_remaining,0), a.invoice_currency_code, class
2901         from ar_payment_schedules_all a, iex_delinquencies_all b   --Changed to ar_payment_schedules_all for bug#5652343 by gnramasa on 07-Mar-2007
2902         where a.payment_schedule_id = b.payment_schedule_id
2903         and b.status in ('DELINQUENT', 'PREDELINQUENT')
2904 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
2905         and a.status = 'OP'
2906 	and (trunc(a.due_date) + p_grace_days) <= p_corr_date
2907 	and nvl(a.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(a.amount_in_dispute,0), 0)
2908         and b.cust_account_id = p_cust_account_id
2909 	and b.org_id = p_org_id;
2910 
2911 	--Start bug 7026222 gnramasa 20th July 08
2912 	l_check_dunn_profile	varchar2(10);
2913 	l_tot_amt_due_rem       number;
2914 
2915     cursor c_billto_dist_inv_cur (p_site_use_id number,p_org_id number) is
2916 	select distinct a.invoice_currency_code
2917         from ar_payment_schedules_all a, iex_delinquencies_all b
2918         where a.payment_schedule_id = b.payment_schedule_id
2919         and b.status in ('DELINQUENT', 'PREDELINQUENT')
2920 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
2921         and a.status = 'OP'
2922         and b.customer_site_use_id = p_site_use_id
2923 	and b.org_id = p_org_id
2924 	order by 1;
2925 
2926     cursor c_billto_min_dunn_amt (p_site_use_id number, p_currency_code varchar) is
2927 	select nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
2928 	from hz_cust_profile_amts
2929 	where site_use_id = p_site_use_id
2930 	and currency_code = p_currency_code;
2931 
2932     cursor c_billto_tot_amt_due_rem (p_site_use_id number, p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number, p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
2933 	select sum(nvl(a.amount_due_remaining,0))
2934         from ar_payment_schedules_all a, iex_delinquencies_all b
2935         where a.payment_schedule_id = b.payment_schedule_id
2936         and b.status in ('DELINQUENT', 'PREDELINQUENT')
2937 	AND a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change)
2938         and a.status = 'OP'
2939         and (trunc(a.due_date) + p_grace_days) <= p_corr_date
2940 	and nvl(a.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(a.amount_in_dispute,0), 0)
2941         and b.customer_site_use_id = p_site_use_id
2942         and a.invoice_currency_code = p_currency_code
2943         and a.amount_due_remaining >= p_min_dun_inv_amt
2944 	and b.org_id = p_org_id;
2945 
2946     cursor c_acc_dist_inv_cur (p_cust_account_id number,p_org_id number) is
2947 	select distinct a.invoice_currency_code
2948         from ar_payment_schedules_all a, iex_delinquencies_all b
2949         where a.payment_schedule_id = b.payment_schedule_id
2950         and b.status in ('DELINQUENT', 'PREDELINQUENT')
2951 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
2952         and a.status = 'OP'
2953         and b.cust_account_id = p_cust_account_id
2954 	and b.org_id = p_org_id
2955 	order by 1;
2956 
2957     cursor c_acc_min_dunn_amt (p_cust_account_id number, p_currency_code varchar) is
2958 	select nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
2959 	from hz_cust_profile_amts
2960 	where cust_account_id = p_cust_account_id
2961 	and currency_code = p_currency_code
2962 	and site_use_id is null;
2963 
2964     cursor c_acc_tot_amt_due_rem (p_cust_account_id number, p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number, p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
2965 	select sum(nvl(a.amount_due_remaining,0))
2966         from ar_payment_schedules_all a, iex_delinquencies_all b
2967         where a.payment_schedule_id = b.payment_schedule_id
2968         and b.status in ('DELINQUENT', 'PREDELINQUENT')
2969 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
2970         and a.status = 'OP'
2971 	and (trunc(a.due_date) + p_grace_days) <= p_corr_date
2972 	and nvl(a.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(a.amount_in_dispute,0), 0)
2973         and b.cust_account_id = p_cust_account_id
2974         and a.invoice_currency_code = p_currency_code
2975         and a.amount_due_remaining >= p_min_dun_inv_amt
2976 	and b.org_id = p_org_id;
2977 
2978     cursor c_cm_ar_amount_account (p_cust_account_id number,p_org_id number) is
2979       select nvl(amount_due_remaining,0) , invoice_currency_code from  ar_payment_schedules_all
2980       where   class IN ('CM','PMT')
2981       and status = 'OP'
2982       and customer_id = p_cust_account_id
2983       and org_id = p_org_id;
2984 
2985     cursor c_cm_ar_amount_account_curr (p_cust_account_id number,p_invoice_currency_code varchar,p_org_id number) is
2986       select nvl(amount_due_remaining,0)  from  ar_payment_schedules_all where
2987       class IN ('CM','PMT')
2988       and   status = 'OP'
2989       and   invoice_currency_code = p_invoice_currency_code
2990       and   customer_id = p_cust_account_id
2991       and org_id = p_org_id;
2992 
2993     cursor c_acct_tot_acctd_amt_rem (p_cust_account_id number,p_org_id number, p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
2994        select nvl(sum(aps.acctd_amount_due_remaining),0)
2995        from ar_payment_schedules_all aps,iex_delinquencies_all dd
2996        where dd.payment_schedule_id = aps.payment_schedule_id
2997        and aps.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
2998        and aps.status='OP'
2999        and (trunc(aps.due_date) + p_grace_days) <= p_corr_date
3000       and nvl(aps.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(aps.amount_in_dispute,0), 0)
3001        and aps.customer_id=p_cust_account_id
3002        and aps.amount_due_remaining > 0
3003        and aps.org_id=p_org_id;
3004 
3005      cursor c_acct_cm_tot_acctd_amt_rem (p_cust_account_id number,p_org_id number) is
3006        select nvl(sum(acctd_amount_due_remaining),0)
3007        from  ar_payment_schedules_all
3008        where class IN ('CM','PMT')
3009        and   status = 'OP'
3010        and   customer_id = p_cust_account_id
3011 
3012        and org_id = p_org_id;
3013 
3014     cursor c_billto_tot_acctd_amt_rem (p_site_use_id number,p_org_id number, p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
3015        select nvl(sum(aps.acctd_amount_due_remaining),0)
3016        from ar_payment_schedules_all aps,iex_delinquencies_all dd
3017        where dd.payment_schedule_id = aps.payment_schedule_id
3018        and aps.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
3019        and aps.status='OP'
3020        and (trunc(aps.due_date) + p_grace_days) <= p_corr_date
3021        and nvl(aps.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(aps.amount_in_dispute,0), 0)
3022        and aps.customer_site_use_id=p_site_use_id
3023        and aps.amount_due_remaining > 0
3024        and aps.org_id=p_org_id;
3025 
3026      cursor c_billto_cm_tot_acctd_amt_rem (p_site_use_id number,p_org_id number) is
3027        select nvl(sum(acctd_amount_due_remaining),0)
3028        from  ar_payment_schedules_all
3029        where class IN ('CM','PMT')
3030        and   status = 'OP'
3031        and   customer_site_use_id = p_site_use_id
3032 
3033        and org_id = p_org_id;
3034 
3035        --End Bug 10401991 17-Jan-2011 barathsr -- Included org_id parameter wherever applicable.
3036 
3037 
3038 
3039 	--End bug 7026222 gnramasa 20th July 08
3040   t_site_use_id number;  -- Bills Receivables
3041 
3042 BEGIN
3043 
3044 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Inside minimum dunning amount check ');
3045 
3046     -- default to no dunning letter to send
3047     l_dunning_letters := 'Y';
3048     l_amount  := 0 ;
3049     l_invoice_amount  := 0 ;
3050     l_convert_amount  := 0 ;
3051     l_amount_due_remaining  := 0 ;
3052     FND_FILE.PUT_LINE(FND_FILE.LOG, 'cust_account_id-->'||p_cust_account_id);
3053     FND_FILE.PUT_LINE(FND_FILE.LOG, 'site_use_id-->'||p_site_use_id);
3054     FND_FILE.PUT_LINE(FND_FILE.LOG, 'org_id-->'||p_org_id);
3055 
3056 
3057     l_cust_account_id := p_cust_account_id;
3058     l_site_use_id   := p_site_use_id;
3059     l_org_id := p_org_id;    --Added for Bug 10401991 17-Jan-2011 barathsr
3060 
3061 
3062     l_min_dunning_amount  := 0;
3063     l_min_dunning_invoice_amount  := 0;
3064     l_cm_ar_amount := 0;
3065 
3066 
3067     l_rate_type :=  nvl(fnd_profile.value('IEX_COLLECTIONS_RATE_TYPE'), 'Corporate');
3068 
3069     --Start bug 7026222 gnramasa 20th July 08
3070     l_check_dunn_profile := nvl(fnd_profile.value('IEX_CHK_DUNN_AT_FUNC_CURR'), 'Y');
3071      --FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_check_dunn_prf_val-->'||l_check_dunn_profile);
3072    --  FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_rate_type-->'||l_rate_type);
3073    --Begin Bug 10401991 14-Feb-2011 barathsr
3074    l_billto_tot_acctd_amt_rem:=0;
3075    l_billto_cm_tot_acctd_amt_rem:=0;
3076    l_billto_total_acctd_amount:=0;
3077    l_acct_tot_acctd_amt_rem:=0;
3078    l_acct_cm_tot_acctd_amt_rem:=0;
3079    l_acct_total_acctd_amount:=0;
3080 
3081     FND_FILE.PUT_LINE(FND_FILE.LOG, 'DunningMinAmountCheck - p_correspondence_date = '||p_correspondence_date);
3082     FND_FILE.PUT_LINE(FND_FILE.LOG, 'DunningMinAmountCheck - p_grace_days = '||p_grace_days);
3083     FND_FILE.PUT_LINE(FND_FILE.LOG, 'DunningMinAmountCheck - p_dun_disputed_items = '||p_dun_disputed_items);
3084 
3085     WriteLog('DunningMinAmountCheck - p_correspondence_date = '||p_correspondence_date);
3086     WriteLog('DunningMinAmountCheck - p_grace_days = '||p_grace_days);
3087     WriteLog('DunningMinAmountCheck - p_dun_disputed_items = '||p_dun_disputed_items);
3088 
3089 
3090        if l_site_use_id is not null then
3091         open c_billto_tot_acctd_amt_rem(l_site_use_id,l_org_id,p_correspondence_date,p_grace_days,p_dun_disputed_items);
3092 	fetch c_billto_tot_acctd_amt_rem into l_billto_tot_acctd_amt_rem;
3093 	close c_billto_tot_acctd_amt_rem;
3094 
3095 	open c_billto_cm_tot_acctd_amt_rem(l_site_use_id,l_org_id);
3096 	fetch c_billto_cm_tot_acctd_amt_rem into l_billto_cm_tot_acctd_amt_rem;
3097 	close c_billto_cm_tot_acctd_amt_rem;
3098 
3099 
3100 
3101      l_billto_total_acctd_amount := nvl(l_billto_tot_acctd_amt_rem,0)+nvl(l_billto_cm_tot_acctd_amt_rem,0);
3102 
3103         FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_billto_tot_acctd_amt_rem : '||l_billto_tot_acctd_amt_rem);
3104 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_billto_cm_tot_acctd_amt_rem : '||l_billto_cm_tot_acctd_amt_rem);
3105 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_billto_total_acctd_amount : '||l_billto_total_acctd_amount);
3106 
3107         if l_billto_total_acctd_amount <= 0 then
3108         l_dunning_letters:='N';
3109 	return l_dunning_letters;
3110         end if;
3111      elsif l_cust_account_id is not null then
3112         open c_acct_tot_acctd_amt_rem(l_cust_account_id,l_org_id,p_correspondence_date,p_grace_days,p_dun_disputed_items);
3113 	fetch c_acct_tot_acctd_amt_rem into l_acct_tot_acctd_amt_rem;
3114 	close c_acct_tot_acctd_amt_rem;
3115 
3116 	open c_acct_cm_tot_acctd_amt_rem(l_cust_account_id,l_org_id);
3117 	fetch c_acct_cm_tot_acctd_amt_rem into l_acct_cm_tot_acctd_amt_rem;
3118 	close c_acct_cm_tot_acctd_amt_rem;
3119 
3120       l_acct_total_acctd_amount:=nvl(l_acct_tot_acctd_amt_rem,0)+nvl(l_acct_cm_tot_acctd_amt_rem,0);
3121 
3122 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_acct_tot_acctd_amt_rem : '||l_acct_tot_acctd_amt_rem);
3123 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_acct_cm_tot_acctd_amt_rem : '||l_acct_cm_tot_acctd_amt_rem);
3124 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_acct_total_acctd_amount : '||l_acct_total_acctd_amount);
3125 
3126         if l_acct_total_acctd_amount <= 0 then
3127         l_dunning_letters:='N';
3128 	 return l_dunning_letters;
3129         end if;
3130 
3131      end if;
3132     --End Bug 10401991 14-Feb-2011 barathsr
3133     --If the profile 'IEX: Check Dunning amount at function currency' is set to 'Yes' then the current functionality will continue
3134     --and if the profile is set to 'No' then we can check amount at currency level. By default the profile value is 'Yes'
3135     if l_check_dunn_profile = 'Y' then
3136 	    -- determine the min dunning and min dunning invoice amount first
3137 	    FND_FILE.PUT_LINE(FND_FILE.LOG, 'IEX: Check Dunning amount at functional currency is Yes');
3138 	    if (l_site_use_id is not null) Then
3139             --Begin Bug 10401991 17-Jan-2011 barathsr -- Included org_id parameter to all the cursors wherever applicable.
3140         t_site_use_id := get_BR_BillTOID(l_site_use_id); -- Bills Receivables
3141 	      open c_billto(t_site_use_id,l_org_id);  -- Bills Receivables
3142         -- open c_billto(l_site_use_id,l_org_id);  -- Bills Receivables
3143 	      fetch c_billto into l_min_currency_code, l_min_dunning_amount, l_min_dunning_invoice_amount;
3144 	      close c_billto;
3145 
3146 	    elsif  (l_cust_account_id is not null ) Then
3147 	      -- no need to set up party id because there is no party level record in hz_cust_profile_amts
3148 	      open c_account(l_cust_account_id,l_org_id);
3149 	      fetch c_account into l_min_currency_code, l_min_dunning_amount, l_min_dunning_invoice_amount;
3150 	      close c_account;
3151 	    end if;
3152 
3153 	     FND_FILE.PUT_LINE(FND_FILE.LOG,'cust_acct_id-->'||l_cust_account_id);
3154 	     FND_FILE.PUT_LINE(FND_FILE.LOG,'l_min_currency_code-->'||l_min_currency_code);
3155              FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_min_dunn_amount-->'||l_min_dunning_amount);
3156 	     FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_min_dunn_inv_amount-->'||l_min_dunning_invoice_amount);
3157 
3158 	    -- no amout record to check
3159 	    if (l_min_currency_code is null) then
3160 	      return l_dunning_letters;
3161 	    end if;
3162 
3163 	    l_amount := 0;
3164 	    l_invoice_amount := 0;
3165 	    l_cm_ar_total_amount := 0;
3166 
3167 
3168 	    -- get the delinquency amount and convert it to the profile currency code
3169 	    -- do it line by line because each line may have different currency code
3170 	    if (l_site_use_id is not null) Then
3171 	      open c_amount_billto(l_site_use_id,l_org_id,p_correspondence_date,p_grace_days,p_dun_disputed_items);
3172 	      loop
3173 		fetch c_amount_billto into l_amount_due_remaining, l_invoice_currency_code, l_class;
3174 		if c_amount_billto%notfound then
3175 		  exit;
3176 		end if;
3177 		if (l_invoice_currency_code <> l_min_currency_code) then
3178 		begin
3179 		  l_convert_amount := gl_currency_api.convert_amount(
3180 		     x_from_currency => l_invoice_currency_code
3181 		     ,x_to_currency => l_min_currency_code
3182 		     ,x_conversion_date => sysdate
3183 		     ,x_conversion_type => l_rate_type
3184 		     ,x_amount => l_amount_due_remaining);
3185 	--	  l_amount := nvl(l_amount,0) + nvl(l_convert_amount,0);
3186 		exception
3187 		         when others then
3188 			    FND_FILE.PUT_LINE(FND_FILE.LOG,'error in currency conversion..pl check whether exchange rates are defined');
3189 			    FND_FILE.PUT_LINE(FND_FILE.LOG,sqlerrm);
3190 			     l_dunning_letters:='N';
3191 			     return l_dunning_letters;
3192                 end;
3193 		  -- also calculate the invoice amount
3194 		--  if (l_class = 'INV') then
3195 		    l_invoice_amount := nvl(l_convert_amount,0);
3196 		    if l_invoice_amount > l_min_dunning_invoice_amount then
3197 		      l_amount:=nvl(l_amount,0) + nvl(l_invoice_amount,0);
3198 		    end if;
3199 	--	  else
3200 	--	      l_amount:=nvl(l_amount,0)+nvl(l_convert_amount,0);
3201 	--	  end if;
3202 		else
3203 		 -- l_amount := nvl(l_amount,0) + nvl(l_amount_due_remaining,0);
3204 		  -- also calculate the invoice amount
3205 	--	  if (l_class = 'INV') then
3206 		    l_invoice_amount := nvl(l_amount_due_remaining,0);
3207 		    if l_invoice_amount > l_min_dunning_invoice_amount then
3208 		      l_amount:=nvl(l_amount,0) + nvl(l_invoice_amount,0);
3209 		    end if;
3210 	--	  else
3211          --		      l_amount := nvl(l_amount,0) + nvl(l_amount_due_remaining,0);
3212 	--	  end if;
3213 		end if;
3214 	      end loop;
3215 	      close c_amount_billto;
3216 	      WriteLog('l_amount = '||l_amount);
3217               WriteLog('l_invoice_amount = '||l_invoice_amount);
3218 
3219 
3220 		      open c_cm_ar_amount_billto(l_site_use_id,l_org_id);
3221 		       loop
3222 		       fetch c_cm_ar_amount_billto into l_cm_ar_amount,l_cm_ar_currency_code;
3223 		       if c_cm_ar_amount_billto%notfound then
3224 				   WriteLog('No open Account Receipts and credit memos');
3225 				   exit;
3226 		       end if;
3227 		       if (l_cm_ar_currency_code <> l_min_currency_code) then
3228 		       begin
3229 			  l_convert_amount := gl_currency_api.convert_amount(
3230 			     x_from_currency => l_cm_ar_currency_code
3231 			     ,x_to_currency => l_min_currency_code
3232 			     ,x_conversion_date => sysdate
3233 			     ,x_conversion_type => l_rate_type
3234 			     ,x_amount => l_cm_ar_amount);
3235 		       exception
3236 		         when others then
3237 			    FND_FILE.PUT_LINE(FND_FILE.LOG,'error in currency conversion..pl check whether exchange rates are defined');
3238 			    FND_FILE.PUT_LINE(FND_FILE.LOG,sqlerrm);
3239 			     l_dunning_letters:='N';
3240 			     return l_dunning_letters;
3241                        end;
3242 			  l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_convert_amount,0);
3243 		      else
3244 			l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
3245 		      end if;
3246 		      end loop;
3247 		      close c_cm_ar_amount_billto;
3248 
3249 
3250 
3251 		 WriteLog('l_ar_total_amount = '||l_cm_ar_total_amount);
3252 
3253 		 l_amount := nvl(l_amount,0) + nvl(l_cm_ar_total_amount,0) ;-- substracting sum of credit memo amount and ar receipt amount from total amount due
3254 								    --(but here i used + sign because the credit memo and account recipt amount will be negitive values)
3255 
3256 	    elsif  (l_cust_account_id is not null ) Then   -- account level calculation
3257 	      open c_amount_account(l_cust_account_id,l_org_id,p_correspondence_date,p_grace_days,p_dun_disputed_items);
3258 	      loop
3259 		fetch c_amount_account into l_amount_due_remaining, l_invoice_currency_code, l_class;
3260 		 FND_FILE.PUT_LINE(FND_FILE.LOG,'l_inv_curr_code-->'||l_invoice_currency_code);
3261 		if c_amount_account%notfound then
3262 		  exit;
3263 		end if;
3264 		if (l_invoice_currency_code <> l_min_currency_code) then
3265 		FND_FILE.PUT_LINE(FND_FILE.LOG,'curr not equal..converting...');
3266 		begin
3267 		  l_convert_amount := gl_currency_api.convert_amount(
3268 		     x_from_currency => l_invoice_currency_code
3269 		     ,x_to_currency => l_min_currency_code
3270 		     ,x_conversion_date => sysdate
3271 		     ,x_conversion_type => l_rate_type
3272 		     ,x_amount => l_amount_due_remaining);
3273 		--  l_amount := nvl(l_amount,0) + nvl(l_convert_amount,0);
3274 
3275 	        exception
3276 		         when others then
3277 			    FND_FILE.PUT_LINE(FND_FILE.LOG,'error in currency conversion..pl check whether exchange rates are defined');
3278 			    FND_FILE.PUT_LINE(FND_FILE.LOG,sqlerrm);
3279 			     l_dunning_letters:='N';
3280 			     return l_dunning_letters;
3281                 end;
3282 		  -- also calculate the invoice amount
3283 	--	   if (l_class = 'INV') then
3284 		    l_invoice_amount := nvl(l_convert_amount,0);
3285 		    if l_invoice_amount > l_min_dunning_invoice_amount then
3286 		      l_amount:=nvl(l_amount,0) + nvl(l_invoice_amount,0);
3287 		    end if;
3288 	--	  else
3289 	--	      l_amount:=nvl(l_amount,0)+nvl(l_convert_amount,0);
3290 	--	  end if;
3291 		else
3292 		 -- l_amount := nvl(l_amount,0) + nvl(l_amount_due_remaining,0);
3293 		  -- also calculate the invoice amount
3294 	--	  if (l_class = 'INV') then
3295 		    l_invoice_amount := nvl(l_amount_due_remaining,0);
3296 		    if l_invoice_amount > l_min_dunning_invoice_amount then
3297 		      l_amount:=nvl(l_amount,0) + nvl(l_invoice_amount,0);
3298 		    end if;
3299 	--	  else
3300 	--	      l_amount := nvl(l_amount,0) + nvl(l_amount_due_remaining,0);
3301 	--	  end if;
3302 		end if;
3303 	      end loop;
3304 	      close c_amount_account;
3305 	      WriteLog('l_amount = '||l_amount);
3306 	       FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_amount-->'||l_amount);
3307           --    WriteLog('l_invoice_amount = '||l_invoice_amount);
3308 	   --    FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_inv_amount-->'||l_invoice_amount);
3309 
3310 
3311 	      open c_cm_ar_amount_account(l_cust_account_id,l_org_id);
3312 	       loop
3313 	       fetch c_cm_ar_amount_account into l_cm_ar_amount,l_cm_ar_currency_code;
3314 	       if c_cm_ar_amount_account%notfound then
3315 		   WriteLog('No open Account Receipts and credit memos');
3316 		   FND_FILE.PUT_LINE(FND_FILE.LOG, 'No open Account Receipts and credit memos');
3317 		   exit;
3318 		end if;
3319 	       if (l_cm_ar_currency_code <> l_min_currency_code) then
3320 	         begin
3321 		  l_convert_amount := gl_currency_api.convert_amount(
3322 		     x_from_currency => l_cm_ar_currency_code
3323 		     ,x_to_currency => l_min_currency_code
3324 		     ,x_conversion_date => sysdate
3325 		     ,x_conversion_type => l_rate_type
3326 		     ,x_amount => l_cm_ar_amount);
3327 		  l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_convert_amount,0);
3328 		 exception
3329 		         when others then
3330 			    FND_FILE.PUT_LINE(FND_FILE.LOG,'error in currency conversion..pl check whether exchange rates are defined');
3331                             FND_FILE.PUT_LINE(FND_FILE.LOG,sqlerrm);
3332 			     l_dunning_letters:='N';
3333 			     return l_dunning_letters;
3334                        end;
3335 	      else
3336 		l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
3337 	      end if;
3338 	      end loop;
3339 	      close c_cm_ar_amount_account;
3340 
3341 
3342 
3343 	 WriteLog('l_cm_ar_total_amount = '||l_cm_ar_total_amount);
3344 	 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_cm_ar_total_amount-->'||l_cm_ar_total_amount);
3345 
3346          l_amount := nvl(l_amount,0) + nvl(l_cm_ar_total_amount,0) ;-- substracting sum of credit memo amount and ar receipt amount from total amount due
3347 	                                              --(but here i used + sign because the credit memo and account recipt amount will be negitive values)
3348 
3349 
3350 	    end if;
3351 
3352           FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_total_amount-->'||l_amount);
3353 
3354 	    -- determine the flag
3355 	    if (l_amount < l_min_dunning_amount) --or l_invoice_amount < l_min_dunning_invoice_amount
3356 	    then
3357 	      l_dunning_letters := 'N';
3358 	      FND_FILE.PUT_LINE(FND_FILE.LOG, 'cant send dunning letters');
3359 	    end if;
3360     else
3361 
3362 	if (l_site_use_id is not null) Then
3363 	      l_dunning_letters := 'N';  --initially set it no
3364 	      open c_billto_dist_inv_cur(l_site_use_id,l_org_id);
3365 	      loop
3366 		fetch c_billto_dist_inv_cur into l_invoice_currency_code;
3367 		if c_billto_dist_inv_cur%notfound then
3368 		  exit;
3369 		end if;
3370 
3371     t_site_use_id := get_BR_BillTOID(l_site_use_id); -- Bills Receivables
3372 		open c_billto_min_dunn_amt (t_site_use_id, l_invoice_currency_code);     -- Bills Receivables
3373     -- open c_billto_min_dunn_amt (l_site_use_id, l_invoice_currency_code);  -- Bills Receivables
3374 		fetch c_billto_min_dunn_amt into l_min_dunning_amount, l_min_dunning_invoice_amount;
3375 		close c_billto_min_dunn_amt;
3376 
3377 		if l_min_dunning_amount is null then
3378 			l_min_dunning_amount := 0;
3379 		end if;
3380 
3381 		if l_min_dunning_invoice_amount is null then
3382 			l_min_dunning_invoice_amount := 0;
3383 		end if;
3384 
3385 		open c_billto_tot_amt_due_rem (l_site_use_id, l_invoice_currency_code, l_min_dunning_invoice_amount,l_org_id,p_correspondence_date,p_grace_days,p_dun_disputed_items);
3386 		fetch c_billto_tot_amt_due_rem into l_tot_amt_due_rem;
3387 		close c_billto_tot_amt_due_rem;
3388 
3389 	       open c_cm_ar_amount_billto_curr(l_site_use_id,l_invoice_currency_code,l_org_id);
3390 	       loop
3391 	       fetch c_cm_ar_amount_billto_curr into l_cm_ar_amount;
3392 	       if c_cm_ar_amount_billto_curr%notfound then
3393 		   WriteLog('No open Account Receipts and credit memos');
3394 		   exit;
3395 		end if;
3396 
3397 
3398 
3399 		l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
3400 
3401 	      end loop;
3402 	      close c_cm_ar_amount_billto_curr;
3403 		--If any currency group satisfies the condition then we have to send the dunning letter,
3404 		--so no need to check for other currencies.
3405 
3406 		 l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_cm_ar_total_amount,0);-- substracting sum of credit memo amount and ar receipt amount from total amount due
3407 	                                                                       --(but here i used + sign because the credit memo and account recipt amount will be negitive values)
3408 
3409 
3410 		if l_tot_amt_due_rem >= l_min_dunning_amount then
3411 			l_dunning_letters := 'Y';
3412 			exit;
3413 		end if;
3414 	      end loop;
3415 	      close c_billto_dist_inv_cur;
3416 	elsif (l_cust_account_id is not null ) Then   -- account level calculation
3417 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'acct lvl calc');
3418 	      l_dunning_letters := 'N';  --initially set it no
3419 	      open c_acc_dist_inv_cur(l_cust_account_id,l_org_id);
3420 	      loop
3421 		fetch c_acc_dist_inv_cur into l_invoice_currency_code;
3422 		if c_acc_dist_inv_cur%notfound then
3423 		  exit;
3424 		end if;
3425 
3426 		FND_FILE.PUT_LINE(FND_FILE.LOG, 'curr_code-->'||l_invoice_currency_code);
3427 
3428 		open c_acc_min_dunn_amt (l_cust_account_id, l_invoice_currency_code);
3429 		fetch c_acc_min_dunn_amt into l_min_dunning_amount, l_min_dunning_invoice_amount;
3430 		close c_acc_min_dunn_amt;
3431 
3432               FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_min_dun_amt-->'||l_min_dunning_amount);
3433 	      FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_min_dun_inv_amt-->'||l_min_dunning_invoice_amount);
3434 
3435 
3436 		if l_min_dunning_amount is null then
3437 			l_min_dunning_amount := 0;
3438 		end if;
3439 
3440 		if l_min_dunning_invoice_amount is null then
3441 			l_min_dunning_invoice_amount := 0;
3442 		end if;
3443 
3444 		open c_acc_tot_amt_due_rem (l_cust_account_id, l_invoice_currency_code, l_min_dunning_invoice_amount,l_org_id,p_correspondence_date,p_grace_days,p_dun_disputed_items);
3445 		fetch c_acc_tot_amt_due_rem into l_tot_amt_due_rem;
3446 		close c_acc_tot_amt_due_rem;
3447 
3448                 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_tot_amt_due_rem-->'||l_tot_amt_due_rem);
3449 
3450 	       open c_cm_ar_amount_account_curr(l_cust_account_id,l_invoice_currency_code,l_org_id);
3451 	       loop
3452 	       fetch c_cm_ar_amount_account_curr into l_cm_ar_amount;
3453 	       if c_cm_ar_amount_account_curr%notfound then
3454 		   WriteLog('No open Account Receipts and credit memos');
3455 		    FND_FILE.PUT_LINE(FND_FILE.LOG,'No open Account Receipts and credit memos');
3456 		   exit;
3457 		end if;
3458 
3459 	--       FND_FILE.PUT_LINE(FND_FILE.LOG,'l_cm_ar_tot_amt-->'||l_cm_ar_total_amount);
3460 		l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
3461 
3462 	--	FND_FILE.PUT_LINE(FND_FILE.LOG,'l_cm_ar_amt -->'||l_cm_ar_amount);
3463                FND_FILE.PUT_LINE(FND_FILE.LOG,'l_cm_ar_tot_amt after adding-->'||l_cm_ar_total_amount);
3464 
3465 	      end loop;
3466 	      close c_cm_ar_amount_account_curr;
3467 		--If any currency group satisfies the condition then we have to send the dunning letter,
3468 		--so no need to check for other currencies.
3469 
3470 		FND_FILE.PUT_LINE(FND_FILE.LOG,'l_cm_ar_tot_amt before adding to tot_amt-->'||l_cm_ar_total_amount);
3471 		FND_FILE.PUT_LINE(FND_FILE.LOG,'l_tot_amt before adding-->'||l_tot_amt_due_rem);
3472 		 l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_cm_ar_total_amount,0);-- substracting sum of credit memo amount and ar receipt amount from total amount due
3473 	                                                                       --(but here i used + sign because the credit memo and account recipt amount will be negitive values)
3474 
3475                   FND_FILE.PUT_LINE(FND_FILE.LOG,'l_tot_amt_due_rem-->'||l_tot_amt_due_rem);
3476 		--If any currency group satisfies the condition then we have to send the dunning letter,
3477 		--so no need to check for other currencies.
3478 		if l_tot_amt_due_rem >= l_min_dunning_amount then
3479 			l_dunning_letters := 'Y';
3480 	--		FND_FILE.PUT_LINE(FND_FILE.LOG, 'send dunning letter');
3481 			exit;
3482 		end if;
3483 	      end loop;
3484 	      close c_acc_dist_inv_cur;
3485 	end if;
3486     end if;  --if l_check_dunn_profile = 'Y' then
3487     --End Bug 10401991 17-Jan-2011 barathsr -- Included org_id parameter to all cursors wherever applicable.
3488 
3489 --End bug 7026222 gnramasa 20th July 08
3490 
3491     return l_dunning_letters;
3492 EXCEPTION
3493  WHEN OTHERS THEN
3494     return l_dunning_letters;
3495 End DunningMinAmountCheck;
3496 */
3497 /*
3498     Overview: This function is to determine if the required min_dunning and min_invoice_dunning amount are
3499               met before sending the dunning letter.
3500    Parameter: p_cust_account_id : if account level then pass the cust_account_id
3501               p_site_use_id : if bill_to level then pass the customer_site_use_id
3502    Return:  'Y' if ok to send dunning letter
3503             'N' if no dunning letter should be sent
3504    creation date: 11th Dec 09
3505    author:  gnramasa
3506    Note: it is not available in the customer and delinquency level
3507  */
3508 Procedure StagedDunningMinAmountCheck
3509 (
3510   p_cust_account_id         IN number
3511   , p_site_use_id           IN number
3512   , p_party_id              IN number
3513   , p_dunning_plan_id       IN number
3514   , p_grace_days            IN number
3515   , p_dun_disputed_items    IN VARCHAR2
3516   , p_correspondence_date   IN DATE
3517   , p_running_level         IN VARCHAR2
3518   , p_org_id                IN NUMBER
3519   , p_inc_inv_curr          OUT NOCOPY INC_INV_CURR_TBL
3520   , p_dunning_letters       OUT NOCOPY varchar2
3521 )
3522 
3523 IS
3524     l_dunning_letters varchar2(10);
3525     l_cust_account_id number;
3526     l_site_use_id  number;
3527     l_party_id     number;
3528     l_min_dunning_amount number;
3529     l_min_dunning_invoice_amount number;
3530     l_min_currency_code varchar2(15);
3531 
3532     l_rate_type varchar2(100);
3533     l_invoice_amount number;
3534     l_convert_amount number;
3535     l_amount_due_remaining number;
3536     l_invoice_currency_code varchar2(15);
3537     l_class varchar2(20);
3538     l_cm_ar_amount number;
3539     L_CM_AR_TOTAL_AMOUNT number;
3540     l_org_id number;
3541     --Begin Bug 10401991 14-Feb-2011 barathsr
3542    l_billto_tot_acctd_amt_rem number;
3543    l_billto_cm_tot_acctd_amt_rem number;
3544    l_billto_tot_amt_rem_BR number;
3545    l_billto_cm_tot_amt_rem_BR number;
3546    l_billto_total_acctd_amount number;
3547    l_acct_tot_acctd_amt_rem number;
3548    l_acct_cm_tot_acctd_amt_rem number;
3549    l_acct_total_acctd_amount number;
3550    --End Bug 10401991 14-Feb-2011 barathsr
3551     -- there is no status to check if active or not,
3552     -- field expiration_date is null only - not used
3553     -- because there is more than 1 record for the same site_use_id, so we pick the functional currency one
3554     cursor c_billto (p_customer_site_use_id number,p_org_id number) is
3555       select currency_code, nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0) from hz_cust_profile_amts
3556         where site_use_id = p_customer_site_use_id and currency_code = (
3557           SELECT  sob.currency_code FROM ar_system_parameters_all sp, gl_sets_of_books sob
3558           WHERE   sob.set_of_books_id = sp.set_of_books_id
3559 	  and sp.org_id = p_org_id );
3560 
3561     -- only open status
3562     cursor c_amount_billto (p_site_use_id number,p_org_id number) is
3563       select nvl(a.amount_due_remaining, 0), a.invoice_currency_code, class
3564         from ar_payment_schedules_all a, iex_delinquencies_all b     --Changed to ar_payment_schedules_all for bug#5652343 by gnramasa on 07-Mar-2007
3565         where a.payment_schedule_id = b.payment_schedule_id
3566         and b.status in ('DELINQUENT', 'PREDELINQUENT')
3567 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
3568         and a.status = 'OP'
3569         and b.customer_site_use_id = p_site_use_id
3570 	and b.org_id=p_org_id;
3571 
3572 
3573       cursor c_cm_ar_amount_billto_curr (p_site_use_id number,p_invoice_currency_code varchar,p_org_id number) is
3574       select nvl(amount_due_remaining,0)
3575       from  ar_payment_schedules_all
3576       where  class IN ('CM' ,'PMT')
3577       and status = 'OP'
3578       and invoice_currency_code = p_invoice_currency_code
3579       and CUSTOMER_SITE_USE_ID = p_site_use_id
3580       and org_id = p_org_id;
3581 
3582     cursor c_account (p_cust_account_id number,p_org_id number) is
3583       select currency_code, nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
3584       from hz_cust_profile_amts
3585       where cust_account_id = p_cust_account_id and currency_code = (
3586           SELECT  sob.currency_code FROM ar_system_parameters_all sp, gl_sets_of_books sob
3587           WHERE   sob.set_of_books_id = sp.set_of_books_id
3588 	  and sp.org_id = p_org_id) and site_use_id is null;
3589 
3590     -- only open status
3591     cursor c_amount_account (p_cust_account_id number,p_org_id number) is
3592       select nvl(a.amount_due_remaining,0), a.invoice_currency_code, class
3593         from ar_payment_schedules_all a, iex_delinquencies_all b   --Changed to ar_payment_schedules_all for bug#5652343 by gnramasa on 07-Mar-2007
3594         where a.payment_schedule_id = b.payment_schedule_id
3595         and b.status in ('DELINQUENT', 'PREDELINQUENT')
3596 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
3597         and a.status = 'OP'
3598         and b.cust_account_id = p_cust_account_id
3599 	and b.org_id = p_org_id;
3600 
3601 	--Start bug 7026222 gnramasa 20th July 08
3602 	l_check_dunn_profile	varchar2(10);
3603 	l_tot_amt_due_rem       number;
3604 
3605 	cursor c_billto_dist_inv_cur (p_site_use_id number,p_org_id number) is
3606 	select distinct a.invoice_currency_code
3607         from ar_payment_schedules_all a, iex_delinquencies_all b
3608         where a.payment_schedule_id = b.payment_schedule_id
3609         --and b.status in ('DELINQUENT', 'PREDELINQUENT')
3610 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
3611         and a.status = 'OP'
3612         and b.customer_site_use_id = p_site_use_id
3613 	and b.org_id = p_org_id
3614 	order by 1;
3615 
3616 	cursor c_billto_min_dunn_amt (p_site_use_id number, p_currency_code varchar) is
3617 	select nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
3618 	from hz_cust_profile_amts
3619 	where site_use_id = p_site_use_id
3620 	and currency_code = p_currency_code;
3621 
3622 	cursor c_billto_tot_amt_due_rem (p_site_use_id number, p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number) is
3623 	select sum(nvl(a.amount_due_remaining,0))
3624         from ar_payment_schedules_all a, iex_delinquencies_all b
3625         where a.payment_schedule_id = b.payment_schedule_id
3626         and b.status in ('DELINQUENT', 'PREDELINQUENT')
3627 	AND a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
3628         and a.status = 'OP'
3629         and b.customer_site_use_id = p_site_use_id
3630         and a.invoice_currency_code = p_currency_code
3631         and a.amount_due_remaining >= p_min_dun_inv_amt
3632 	and b.org_id = p_org_id;
3633 
3634 	cursor c_acc_dist_inv_cur (p_cust_account_id number,p_org_id number) is
3635 	select distinct a.invoice_currency_code
3636         from ar_payment_schedules_all a, iex_delinquencies_all b
3637         where a.payment_schedule_id = b.payment_schedule_id
3638         --and b.status in ('DELINQUENT', 'PREDELINQUENT')
3639 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
3640         and a.status = 'OP'
3641         and b.cust_account_id = p_cust_account_id
3642 	and b.org_id = p_org_id
3643 	order by 1;
3644 
3645 	cursor c_cus_dist_inv_cur (p_party_id number,p_org_id number) is
3646 	select distinct a.invoice_currency_code
3647         from ar_payment_schedules_all a, iex_delinquencies_all b
3648         where a.payment_schedule_id = b.payment_schedule_id
3649         --and b.status in ('DELINQUENT', 'PREDELINQUENT')
3650 	AND   a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
3651         and a.status = 'OP'
3652         and b.party_cust_id = p_party_id
3653 	and b.org_id = p_org_id
3654 	order by 1;
3655 
3656 	cursor c_acc_min_dunn_amt (p_cust_account_id number, p_currency_code varchar) is
3657 	select nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
3658 	from hz_cust_profile_amts
3659 	where cust_account_id = p_cust_account_id
3660 	and currency_code = p_currency_code
3661 	and site_use_id is null;
3662 
3663 	cursor c_acc_tot_amt_due_rem (p_cust_account_id number, p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number) is
3664 	select sum(nvl(a.amount_due_remaining,0))
3665         from ar_payment_schedules_all a, iex_delinquencies_all b
3666         where a.payment_schedule_id = b.payment_schedule_id
3667         and b.status in ('DELINQUENT', 'PREDELINQUENT')
3668 	AND a.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
3669         and a.status = 'OP'
3670         and b.cust_account_id = p_cust_account_id
3671         and a.invoice_currency_code = p_currency_code
3672         and a.amount_due_remaining >= p_min_dun_inv_amt
3673 	and b.org_id = p_org_id;
3674 
3675 	--End bug 7026222 gnramasa 20th July 08
3676 
3677 	cursor c_dunningplan_lines(p_dunn_plan_id number) is
3678 	    select ag_dn_xref_id,
3679 		   dunning_level,
3680 		   template_id,
3681 		   xdo_template_id,
3682 		   fm_method,
3683 		   upper(callback_flag) callback_flag,
3684 		   callback_days,
3685 		   range_of_dunning_level_from,
3686 		   range_of_dunning_level_to,
3687 		   min_days_between_dunning
3688 	    from iex_ag_dn_xref
3689 	    where dunning_plan_id = p_dunn_plan_id
3690 	    order by AG_DN_XREF_ID;
3691 
3692 	l_dunningplan_lines	    c_dunningplan_lines%rowtype;
3693 	l_amount                    number;
3694 	i                           number := 0;
3695 	l_stage                     number;
3696 	l_api_name                  varchar2(100);
3697 
3698 --	l_inc_inv_curr              IEX_UTILITIES.INC_INV_CURR_TBL;
3699 
3700 	cursor c_bill_dunning_trx_null_dun_ct (p_site_use_id number, p_min_days_bw_dun number,
3701                                           p_corr_date date, p_grace_days number, p_include_dis_items varchar,
3702 					  p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number) is
3703 	    select nvl(sum(amount_due_remaining),0) from (
3704 	    select arp.amount_due_remaining amount_due_remaining
3705 	    from iex_delinquencies_all del,
3706 		 ar_payment_schedules_all arp
3707 	    where del.payment_schedule_id = arp.payment_schedule_id
3708 	    and del.status in ('DELINQUENT','PREDELINQUENT')
3709 	    and del.customer_site_use_id = p_site_use_id
3710 	    and del.staged_dunning_level is NULL
3711 	    and (trunc(arp.due_date) + p_min_days_bw_dun) <= p_corr_date
3712 	    and (trunc(arp.due_date) + p_grace_days) <= p_corr_date
3713 	    and nvl(arp.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(arp.amount_in_dispute,0), 0)
3714 	    and arp.invoice_currency_code = p_currency_code
3715             and arp.amount_due_remaining >= p_min_dun_inv_amt
3716 	    and del.org_id = p_org_id
3717 	    union all  --Added for Bug 10401991 03-Feb-2011 barathsr
3718 	    select arp.amount_due_remaining amount_due_remaining
3719 	    from iex_delinquencies_all del,
3720 		 ar_payment_schedules_all arp
3721 	    where del.payment_schedule_id = arp.payment_schedule_id
3722 	    and del.status = 'CURRENT'
3723 	    and del.customer_site_use_id = p_site_use_id
3724 	    and del.staged_dunning_level is NULL
3725 	    and arp.status = 'OP'
3726 	    -- and arp.class = 'INV'
3727       and (arp.class = 'INV' or arp.class = 'BR') -- Bills Receivables change
3728 	    and (trunc(arp.due_date) + p_min_days_bw_dun) <= p_corr_date
3729 	    and (trunc(arp.due_date) + p_grace_days) <= p_corr_date
3730 	    and arp.amount_in_dispute >= decode(p_include_dis_items, 'Y', arp.amount_due_remaining, (arp.amount_due_original + 1))
3731 	    and arp.invoice_currency_code = p_currency_code
3732             and arp.amount_due_remaining >= p_min_dun_inv_amt
3733 	    and del.org_id = p_org_id
3734 	    );
3735 
3736 	    cursor c_bill_dunning_trx_ct (p_site_use_id number, p_stage_no number,
3737 					 p_min_days_bw_dun number, p_corr_date date, p_include_dis_items varchar,
3738 					 p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number) is
3739 	    select nvl(sum(amount_due_remaining),0) from (
3740 	    select arp.amount_due_remaining amount_due_remaining
3741 	    from iex_delinquencies_all del
3742 		 ,ar_payment_schedules_all arp
3743 	    where
3744 	    del.payment_schedule_id = arp.payment_schedule_id and
3745 	    del.status in ('DELINQUENT','PREDELINQUENT')
3746 	    and del.customer_site_use_id = p_site_use_id
3747 	    and del.staged_dunning_level = p_stage_no
3748 	    and nvl(arp.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(arp.amount_in_dispute,0), 0)
3749 	    and nvl(((select trunc(correspondence_date) from iex_dunnings
3750 			 where dunning_id =
3751 			    (select max(iet.DUNNING_ID) from iex_dunning_transactions iet,
3752 			                                         iex_dunnings dunn
3753 			     where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
3754 			     and dunn.dunning_id = iet.dunning_id
3755 			     and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
3756 						OR (dunn.dunning_mode = 'FINAL'))
3757 			     and iet.STAGE_NUMBER = p_stage_no
3758 			     and dunn.delivery_status is null
3759 			  --   group by iet.dunning_id  bug 9508149
3760 			    )
3761 			 )
3762 		       + p_min_days_bw_dun
3763 		      )
3764 		     , p_corr_date
3765 		    )
3766 		    <= p_corr_date
3767 	    and arp.invoice_currency_code = p_currency_code
3768             and arp.amount_due_remaining >= p_min_dun_inv_amt
3769 	    and del.org_id = p_org_id
3770 	    union all  --Added for Bug 10401991 03-Feb-2011 barathsr
3771 	    select arp.amount_due_remaining amount_due_remaining
3772 	    from iex_delinquencies_all del
3773 		 ,ar_payment_schedules_all arp
3774 	    where
3775 	    del.payment_schedule_id = arp.payment_schedule_id and
3776 	    del.status = 'CURRENT'
3777 	    and del.customer_site_use_id = p_site_use_id
3778 	    and del.staged_dunning_level = p_stage_no
3779 	    and arp.status = 'OP'
3780 	    -- and arp.class = 'INV'
3781       and (arp.class = 'INV' or arp.class = 'BR') -- Bills Receivables change
3782 	    and arp.amount_in_dispute >= decode(p_include_dis_items, 'Y', arp.amount_due_remaining, (arp.amount_due_original + 1))
3783 	    and nvl(
3784 		(
3785 		 (select trunc(correspondence_date) from iex_dunnings
3786 		  where dunning_id =
3787 		   (select max(iet.DUNNING_ID) from iex_dunning_transactions iet,
3788 							 iex_dunnings dunn
3789 		     where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
3790 		     and dunn.dunning_id = iet.dunning_id
3791 		     and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
3792 					OR (dunn.dunning_mode = 'FINAL'))
3793 		     and iet.STAGE_NUMBER = p_stage_no
3794 		     and dunn.delivery_status is null
3795 		   --  group by iet.dunning_id  bug 9508149
3796 		     ))
3797 		    + p_min_days_bw_dun )
3798 		    , p_corr_date )
3799 		    <= p_corr_date
3800 	     and arp.invoice_currency_code = p_currency_code
3801              and arp.amount_due_remaining >= p_min_dun_inv_amt
3802 	     and del.org_id = p_org_id
3803 	     );
3804 
3805 	     cursor c_acc_dunning_trx_null_dun_ct (p_cust_acct_id number, p_min_days_bw_dun number,
3806                                           p_corr_date date, p_grace_days number, p_include_dis_items varchar,
3807 					  p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number) is
3808 	    select nvl(sum(amount_due_remaining),0) from (
3809 	    select arp.amount_due_remaining amount_due_remaining
3810 	    from iex_delinquencies_all del,
3811 		 ar_payment_schedules_all arp
3812 	    where del.payment_schedule_id = arp.payment_schedule_id
3813 	    and del.status in ('DELINQUENT','PREDELINQUENT')
3814 	    and del.cust_account_id = p_cust_acct_id
3815 	    and del.staged_dunning_level is NULL
3816 	    and (trunc(arp.due_date) + p_min_days_bw_dun) <= p_corr_date
3817 	    and (trunc(arp.due_date) + p_grace_days) <= p_corr_date
3818 	    and nvl(arp.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(arp.amount_in_dispute,0), 0)
3819 	    and arp.invoice_currency_code = p_currency_code
3820             and arp.amount_due_remaining >= p_min_dun_inv_amt
3821 	    and del.org_id = p_org_id
3822 	    union all    --Added for Bug 10401991 03-Feb-2011 barathsr
3823 	    select arp.amount_due_remaining amount_due_remaining
3824 	    from iex_delinquencies_all del,
3825 		 ar_payment_schedules_all arp
3826 	    where del.payment_schedule_id = arp.payment_schedule_id
3827 	    and del.status = 'CURRENT'
3828 	    and del.cust_account_id = p_cust_acct_id
3829 	    and del.staged_dunning_level is NULL
3830 	    and arp.status = 'OP'
3831 	    -- and arp.class = 'INV'
3832       and (arp.class = 'INV' or arp.class = 'BR') -- Bills Receivables change
3833 	    and (trunc(arp.due_date) + p_min_days_bw_dun) <= p_corr_date
3834 	    and (trunc(arp.due_date) + p_grace_days) <= p_corr_date
3835 	    and arp.amount_in_dispute >= decode(p_include_dis_items, 'Y', arp.amount_due_remaining, (arp.amount_due_original + 1))
3836 	    and arp.invoice_currency_code = p_currency_code
3837             and arp.amount_due_remaining >= p_min_dun_inv_amt
3838 	    and del.org_id = p_org_id
3839 	    );
3840 
3841 	    cursor c_acc_dunning_trx_ct (p_cust_acct_id number, p_stage_no number,
3842 					 p_min_days_bw_dun number, p_corr_date date, p_include_dis_items varchar,
3843 					 p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number) is
3844 	    select nvl(sum(amount_due_remaining),0) from (
3845 	    select arp.amount_due_remaining amount_due_remaining
3846 	    from iex_delinquencies_all del
3847 		 ,ar_payment_schedules_all arp
3848 	    where
3849 	    del.payment_schedule_id = arp.payment_schedule_id and
3850 	    del.status in ('DELINQUENT','PREDELINQUENT')
3851 	    and del.cust_account_id = p_cust_acct_id
3852 	    and del.staged_dunning_level = p_stage_no
3853 	    and nvl(arp.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(arp.amount_in_dispute,0), 0)
3854 	    and nvl(
3855 		     (
3856 			(select trunc(correspondence_date) from iex_dunnings
3857 			 where dunning_id =
3858 			    (select max(iet.DUNNING_ID) from iex_dunning_transactions iet,
3859 			                                         iex_dunnings dunn
3860 			     where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
3861 			     and dunn.dunning_id = iet.dunning_id
3862 			     and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
3863 						OR (dunn.dunning_mode = 'FINAL'))
3864 			     and iet.STAGE_NUMBER = p_stage_no
3865 			     and dunn.delivery_status is null
3866 			--     group by iet.dunning_id  bug 9508149
3867 			    )
3868 			 )
3869 		       + p_min_days_bw_dun
3870 		      )
3871 		     , p_corr_date
3872 		    )
3873 		    <= p_corr_date
3874 	    and arp.invoice_currency_code = p_currency_code
3875             and arp.amount_due_remaining >= p_min_dun_inv_amt
3876 	    and del.org_id = p_org_id
3877 	    union all   --Added for Bug 10401991 03-Feb-2011 barathsr
3878 	    select arp.amount_due_remaining amount_due_remaining
3879 	    from iex_delinquencies_all del
3880 		 ,ar_payment_schedules_all arp
3881 	    where
3882 	    del.payment_schedule_id = arp.payment_schedule_id and
3883 	    del.status = 'CURRENT'
3884 	    and del.cust_account_id = p_cust_acct_id
3885 	    and del.staged_dunning_level = p_stage_no
3886 	    and arp.status = 'OP'
3887 	    -- and arp.class = 'INV'
3888       and (arp.class = 'INV' or arp.class = 'BR') -- Bills Receivables change
3889 	    and arp.amount_in_dispute >= decode(p_include_dis_items, 'Y', arp.amount_due_remaining, (arp.amount_due_original + 1))
3890 	    and nvl(
3891 		(
3892 		 (select trunc(correspondence_date) from iex_dunnings
3893 		  where dunning_id =
3894 		   (select max(iet.DUNNING_ID) from iex_dunning_transactions iet,
3895 							 iex_dunnings dunn
3896 		     where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
3897 		     and dunn.dunning_id = iet.dunning_id
3898 		     and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
3899 					OR (dunn.dunning_mode = 'FINAL'))
3900 		     and iet.STAGE_NUMBER = p_stage_no
3901 		     and dunn.delivery_status is null
3902 		   --  group by iet.dunning_id  bug 9508149
3903 		     ))
3904 		    + p_min_days_bw_dun )
3905 		    , p_corr_date )
3906 		    <= p_corr_date
3907 	     and arp.invoice_currency_code = p_currency_code
3908              and arp.amount_due_remaining >= p_min_dun_inv_amt
3909 	     and del.org_id = p_org_id
3910 	     );
3911 
3912 	   cursor c_cus_dunning_trx_null_dun_ct (p_party_id number, p_min_days_bw_dun number,
3913                                           p_corr_date date, p_grace_days number, p_include_dis_items varchar,
3914 					  p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number) is
3915 	    select nvl(sum(amount_due_remaining),0) from (
3916 	    select arp.amount_due_remaining amount_due_remaining
3917 	    from iex_delinquencies_all del,
3918 		 ar_payment_schedules_all arp
3919 	    where del.payment_schedule_id = arp.payment_schedule_id
3920 	    and del.status in ('DELINQUENT','PREDELINQUENT')
3921 	    and del.party_cust_id = p_party_id
3922 	    and del.staged_dunning_level is NULL
3923 	    and (trunc(arp.due_date) + p_min_days_bw_dun) <= p_corr_date
3924 	    and (trunc(arp.due_date) + p_grace_days) <= p_corr_date
3925 	    and nvl(arp.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(arp.amount_in_dispute,0), 0)
3926 	    and arp.invoice_currency_code = p_currency_code
3927             and arp.amount_due_remaining >= p_min_dun_inv_amt
3928 	    and del.org_id = p_org_id
3929 	    union all   --Added for Bug 10401991 03-Feb-2011 barathsr
3930 	    select arp.amount_due_remaining amount_due_remaining
3931 	    from iex_delinquencies_all del,
3932 		 ar_payment_schedules_all arp
3933 	    where del.payment_schedule_id = arp.payment_schedule_id
3934 	    and del.status = 'CURRENT'
3935 	    and del.party_cust_id = p_party_id
3936 	    and del.staged_dunning_level is NULL
3937 	    and arp.status = 'OP'
3938 	    -- and arp.class = 'INV'
3939       and (arp.class = 'INV' or arp.class = 'BR') -- Bills Receivables change
3940 	    and (trunc(arp.due_date) + p_min_days_bw_dun) <= p_corr_date
3941 	    and (trunc(arp.due_date) + p_grace_days) <= p_corr_date
3942 	    and arp.amount_in_dispute >= decode(p_include_dis_items, 'Y', arp.amount_due_remaining, (arp.amount_due_original + 1))
3943 	    and arp.invoice_currency_code = p_currency_code
3944             and arp.amount_due_remaining >= p_min_dun_inv_amt
3945 	    and del.org_id = p_org_id
3946 	    );
3947 
3948 	    cursor c_cus_dunning_trx_ct (p_party_id number, p_stage_no number,
3949 					 p_min_days_bw_dun number, p_corr_date date, p_include_dis_items varchar,
3950 					 p_currency_code varchar, p_min_dun_inv_amt number,p_org_id number) is
3951 	    select nvl(sum(amount_due_remaining),0) from (
3952 	    select arp.amount_due_remaining amount_due_remaining
3953 	    from iex_delinquencies_all del
3954 		 ,ar_payment_schedules_all arp
3955 	    where
3956 	    del.payment_schedule_id = arp.payment_schedule_id and
3957 	    del.status in ('DELINQUENT','PREDELINQUENT')
3958 	    and del.party_cust_id = p_party_id
3959 	    and del.staged_dunning_level = p_stage_no
3960 	    and nvl(arp.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(arp.amount_in_dispute,0), 0)
3961 	    and nvl(
3962 		     (
3963 			(select trunc(correspondence_date) from iex_dunnings
3964 			 where dunning_id =
3965 			    (select max(iet.DUNNING_ID) from iex_dunning_transactions iet,
3966 			                                         iex_dunnings dunn
3967 			     where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
3968 			     and dunn.dunning_id = iet.dunning_id
3969 			     and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
3970 						OR (dunn.dunning_mode = 'FINAL'))
3971 			     and iet.STAGE_NUMBER = p_stage_no
3972 			     and dunn.delivery_status is null
3973 			  --   group by iet.dunning_id  bug 9508149
3974 			    )
3975 			 )
3976 		       + p_min_days_bw_dun
3977 		      )
3978 		     , p_corr_date
3979 		    )
3980 		    <= p_corr_date
3981 	    and arp.invoice_currency_code = p_currency_code
3982             and arp.amount_due_remaining >= p_min_dun_inv_amt
3983 	    and del.org_id = p_org_id
3984 	    union all   --Added for Bug 10401991 03-Feb-2011 barathsr
3985 	    select arp.amount_due_remaining amount_due_remaining
3986 	    from iex_delinquencies_all del
3987 		 ,ar_payment_schedules_all arp
3988 	    where
3989 	    del.payment_schedule_id = arp.payment_schedule_id and
3990 	    del.status = 'CURRENT'
3991 	    and del.party_cust_id = p_party_id
3992 	    and del.staged_dunning_level = p_stage_no
3993 	    and arp.status = 'OP'
3994 	    -- and arp.class = 'INV'
3995       and (arp.class = 'INV' or arp.class = 'BR') -- Bills Receivables change
3996 	    and arp.amount_in_dispute >= decode(p_include_dis_items, 'Y', arp.amount_due_remaining, (arp.amount_due_original + 1))
3997 	    and nvl(
3998 		(
3999 		 (select trunc(correspondence_date) from iex_dunnings
4000 		  where dunning_id =
4001 		   (select max(iet.DUNNING_ID) from iex_dunning_transactions iet,
4002 							 iex_dunnings dunn
4003 		     where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
4004 		     and dunn.dunning_id = iet.dunning_id
4005 		     and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
4006 					OR (dunn.dunning_mode = 'FINAL'))
4007 		     and iet.STAGE_NUMBER = p_stage_no
4008 		     and dunn.delivery_status is null
4009 		   --  group by iet.dunning_id bug 9508149
4010 		     ))
4011 		    + p_min_days_bw_dun )
4012 		    , p_corr_date )
4013 		    <= p_corr_date
4014 	     and arp.invoice_currency_code = p_currency_code
4015              and arp.amount_due_remaining >= p_min_dun_inv_amt
4016 	     and del.org_id = p_org_id
4017 	     );
4018 
4019 
4020      cursor c_cm_ar_amount_account_curr (p_cust_account_id number,p_invoice_currency_code varchar,p_org_id number) is
4021       select nvl(amount_due_remaining,0)  from  ar_payment_schedules_all  where
4022       class IN ('CM','PMT')
4023       and   status = 'OP'
4024       and   invoice_currency_code = p_invoice_currency_code
4025       and   customer_id = p_cust_account_id
4026       and   org_id = p_org_id;
4027 
4028 
4029     --Begin Bug 10401991 14-Feb-2011 barathsr
4030       cursor c_acct_tot_acctd_amt_rem (p_cust_account_id number,p_org_id number) is
4031        select nvl(sum(aps.acctd_amount_due_remaining),0)
4032        from ar_payment_schedules_all aps,iex_delinquencies_all dd
4033        where dd.payment_schedule_id  = aps.payment_schedule_id
4034        and aps.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')  -- Bills Receivables change
4035        and aps.status='OP'
4036        and aps.customer_id=p_cust_account_id
4037        and aps.amount_due_remaining > 0
4038        and aps.org_id=p_org_id;
4039 
4040      cursor c_acct_cm_tot_acctd_amt_rem (p_cust_account_id number,p_org_id number) is
4041        select nvl(sum(acctd_amount_due_remaining),0)
4042        from  ar_payment_schedules_all
4043        where class IN ('CM','PMT')
4044        and   status = 'OP'
4045        and   customer_id = p_cust_account_id
4046 
4047        and org_id = p_org_id;
4048 
4049     cursor c_billto_tot_acctd_amt_rem (p_site_use_id number,p_org_id number) is
4050        select nvl(sum(aps.acctd_amount_due_remaining),0)
4051        from ar_payment_schedules_all aps,iex_delinquencies_all dd
4052        where dd.payment_schedule_id  = aps.payment_schedule_id
4053        and aps.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')   -- Bills Receivables change
4054        and aps.status='OP'
4055        and aps.customer_site_use_id=p_site_use_id
4056        and aps.amount_due_remaining > 0
4057        and aps.org_id=p_org_id;
4058 
4059      cursor c_billto_cm_tot_acctd_amt_rem (p_site_use_id number,p_org_id number) is
4060        select nvl(sum(acctd_amount_due_remaining),0)
4061        from  ar_payment_schedules_all
4062        where class IN ('CM','PMT')
4063        and   status = 'OP'
4064        and   customer_site_use_id = p_site_use_id
4065 
4066        and org_id = p_org_id;
4067 
4068     --End Bug 10401991 14-Feb-2011 barathsr
4069 
4070     t_site_use_id       number;  -- Bills Receivables
4071     tt_site_use_id      number;  -- Bills Receivables
4072     tt_code       varchar2(30);  -- Bills Receivables
4073 
4074 BEGIN
4075 
4076     iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - Start');
4077     -- default to no dunning letter to send
4078     l_dunning_letters := 'Y';
4079     l_amount  := 0 ;
4080     l_invoice_amount  := 0 ;
4081     l_convert_amount  := 0 ;
4082     l_amount_due_remaining  := 0 ;
4083 
4084     l_cust_account_id := p_cust_account_id;
4085     l_site_use_id   := p_site_use_id;
4086     l_party_id := p_party_id;
4087     l_org_id := p_org_id;
4088     l_min_dunning_amount  := 0;
4089     l_min_dunning_invoice_amount  := 0;
4090 
4091     FND_FILE.PUT_LINE(FND_FILE.LOG, 'p_cust_account_id : '||p_cust_account_id);
4092     FND_FILE.PUT_LINE(FND_FILE.LOG, 'p_site_use_id : '||p_site_use_id);
4093     FND_FILE.PUT_LINE(FND_FILE.LOG, 'p_party_id : '|| p_party_id);
4094     FND_FILE.PUT_LINE(FND_FILE.LOG, 'p_dunning_plan_id : '||p_dunning_plan_id);
4095     FND_FILE.PUT_LINE(FND_FILE.LOG, 'p_grace_days : '||p_grace_days);
4096     FND_FILE.PUT_LINE(FND_FILE.LOG, 'p_dun_disputed_items : '||p_dun_disputed_items);
4097     FND_FILE.PUT_LINE(FND_FILE.LOG, 'p_correspondence_date :'||p_correspondence_date );
4098     FND_FILE.PUT_LINE(FND_FILE.LOG, 'p_running_level : '||p_running_level);
4099     FND_FILE.PUT_LINE(FND_FILE.LOG, 'p_org_id : '||p_org_id);
4100 
4101      WriteLog('p_cust_account_id : '||p_cust_account_id);
4102      WriteLog('p_site_use_id : '||p_site_use_id);
4103      WriteLog('p_party_id : '|| p_party_id);
4104      WriteLog('p_dunning_plan_id : '||p_dunning_plan_id);
4105      WriteLog('p_grace_days : '||p_grace_days);
4106      WriteLog('p_dun_disputed_items : '||p_dun_disputed_items);
4107      WriteLog('p_correspondence_date :'||p_correspondence_date );
4108      WriteLog('p_running_level : '||p_running_level);
4109      WriteLog('p_org_id : '||p_org_id);
4110 
4111     l_inc_inv_curr.delete;
4112 
4113     l_api_name	:= 'IEX_UTILITIES.StagedDunningMinAmountCheck';
4114 
4115     l_rate_type :=  nvl(fnd_profile.value('IEX_COLLECTIONS_RATE_TYPE'), 'Corporate');
4116   --Begin Bug 10401991 14-Feb-2011 barathsr
4117    l_billto_tot_acctd_amt_rem:=0;
4118    l_billto_cm_tot_acctd_amt_rem:=0;
4119    l_billto_tot_amt_rem_BR:=0;    -- BillsReceivables
4120    l_billto_cm_tot_amt_rem_BR:=0; -- BillsReceivables
4121    l_billto_total_acctd_amount:=0;
4122    l_acct_tot_acctd_amt_rem:=0;
4123    l_acct_cm_tot_acctd_amt_rem:=0;
4124    l_acct_total_acctd_amount:=0;
4125 
4126      if l_site_use_id is not null then
4127         open c_billto_tot_acctd_amt_rem(l_site_use_id,l_org_id);
4128 	fetch c_billto_tot_acctd_amt_rem into l_billto_tot_acctd_amt_rem;
4129 	close c_billto_tot_acctd_amt_rem;
4130 
4131 	open c_billto_cm_tot_acctd_amt_rem(l_site_use_id,l_org_id);
4132 	fetch c_billto_cm_tot_acctd_amt_rem into l_billto_cm_tot_acctd_amt_rem;
4133 	close c_billto_cm_tot_acctd_amt_rem;
4134 
4135         l_billto_total_acctd_amount := nvl(l_billto_tot_acctd_amt_rem,0)+nvl(l_billto_cm_tot_acctd_amt_rem,0);
4136 
4137         -- Bills Receivables bug 16303059 begin....
4138         begin
4139           tt_site_use_id := 0;
4140           select site_use_code into tt_code from hz_cust_site_uses_all where site_use_id = l_site_use_id;
4141 
4142           if tt_code = 'BILL_TO' then
4143              tt_site_use_id := get_BR_DrweeSiteID(l_site_use_id);  -- Bills Receivables
4144 
4145              if nvl(tt_site_use_id,0) <> 0 then
4146 	        open  c_billto_tot_acctd_amt_rem(tt_site_use_id,l_org_id);
4147     	        fetch c_billto_tot_acctd_amt_rem into l_billto_tot_amt_rem_BR;
4148 	        close c_billto_tot_acctd_amt_rem;
4149 
4150 	        open  c_billto_cm_tot_acctd_amt_rem(tt_site_use_id,l_org_id);
4151     	        fetch c_billto_cm_tot_acctd_amt_rem into l_billto_cm_tot_amt_rem_BR;
4152 	        close c_billto_cm_tot_acctd_amt_rem;
4153 
4154                 l_billto_total_acctd_amount := l_billto_total_acctd_amount + nvl(l_billto_tot_amt_rem_BR,0) + nvl(l_billto_cm_tot_amt_rem_BR,0);
4155              end if;
4156            end if;
4157 
4158      	   FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_billto_tot_amt_rem_BR :    '||l_billto_tot_amt_rem_BR);
4159 	   FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_billto_cm_tot_amt_rem_BR : '||l_billto_cm_tot_amt_rem_BR);
4160 
4161            exception
4162              when others then null;
4163         end;
4164         -- Bills Receivables bug 16303059 end....
4165 
4166      	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_billto_tot_acctd_amt_rem : '||l_billto_tot_acctd_amt_rem);
4167 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_billto_cm_tot_acctd_amt_rem : '||l_billto_cm_tot_acctd_amt_rem);
4168 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_billto_total_acctd_amount : '||l_billto_total_acctd_amount);
4169         if l_billto_total_acctd_amount <= 0 then
4170         l_dunning_letters:='N';
4171 	p_dunning_letters := l_dunning_letters;
4172 	return ;
4173         end if;
4174      elsif l_cust_account_id is not null then
4175 	 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_cust_account_id : '||l_cust_account_id);
4176         open c_acct_tot_acctd_amt_rem(l_cust_account_id,l_org_id);
4177 	fetch c_acct_tot_acctd_amt_rem into l_acct_tot_acctd_amt_rem;
4178 	close c_acct_tot_acctd_amt_rem;
4179 
4180 	open c_acct_cm_tot_acctd_amt_rem(l_cust_account_id,l_org_id);
4181 	fetch c_acct_cm_tot_acctd_amt_rem into l_acct_cm_tot_acctd_amt_rem;
4182 	close c_acct_cm_tot_acctd_amt_rem;
4183 
4184         l_acct_total_acctd_amount:=nvl(l_acct_tot_acctd_amt_rem,0)+nvl(l_acct_cm_tot_acctd_amt_rem,0);
4185       	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_acct_tot_acctd_amt_rem : '||l_acct_tot_acctd_amt_rem);
4186 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_acct_cm_tot_acctd_amt_rem : '||l_acct_cm_tot_acctd_amt_rem);
4187 	FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_acct_total_acctd_amount : '||l_acct_total_acctd_amount);
4188 
4189 
4190         if l_acct_total_acctd_amount <= 0 then
4191 	 FND_FILE.PUT_LINE(FND_FILE.LOG, 'setting l_dunning_letters to : '||l_dunning_letters);
4192          l_dunning_letters:='N';
4193 	 p_dunning_letters := l_dunning_letters;
4194 	 return ;
4195         end if;
4196 
4197      end if;
4198       --End Bug 10401991 14-Feb-2011 barathsr
4199 
4200     if (l_site_use_id is not null) Then
4201 	      --l_dunning_letters := 'N';  --initially set it no
4202 
4203 	      open c_billto_dist_inv_cur(l_site_use_id,l_org_id);
4204 	      loop
4205 		fetch c_billto_dist_inv_cur into l_invoice_currency_code;
4206 		exit when c_billto_dist_inv_cur%notfound;
4207                 /*
4208                 if c_billto_dist_inv_cur%notfound then
4209 		  exit;
4210 		end if;
4211 		*/
4212                 t_site_use_id := get_BR_BillTOID(l_site_use_id);  -- Bills Receivables
4213 		open c_billto_min_dunn_amt (t_site_use_id, l_invoice_currency_code);  -- Bills Receivables
4214                 -- open c_billto_min_dunn_amt (l_site_use_id, l_invoice_currency_code);  -- Bills Receivables
4215 		fetch c_billto_min_dunn_amt into l_min_dunning_amount, l_min_dunning_invoice_amount;
4216 		close c_billto_min_dunn_amt;
4217 
4218 		if l_min_dunning_amount is null then
4219 			l_min_dunning_amount := 0;
4220 		end if;
4221 
4222 		if l_min_dunning_invoice_amount is null then
4223 			l_min_dunning_invoice_amount := 0;
4224 		end if;
4225 		l_amount		:= 0;
4226 		l_tot_amt_due_rem	:= 0;
4227                 FND_FILE.PUT_LINE(FND_FILE.LOG, '******* iexvutlb.pls : Stage Dunning Plan ID ==> '||p_dunning_plan_id);
4228 
4229 		open c_dunningplan_lines (p_dunning_plan_id);
4230 		loop
4231 
4232 	           fetch c_dunningplan_lines into l_dunningplan_lines;
4233                    exit when c_dunningplan_lines%NOTFOUND;
4234                    /*
4235 		   --start added to fix 13519559 12/23/2011 snuthala
4236 	           if c_dunningplan_lines%NOTFOUND then
4237 		       FND_FILE.PUT_LINE(FND_FILE.LOG, '*******HHHHHH Stage Dunning Plan '||p_dunning_plan_id||' has no dunning stages defined *****');
4238 		       WriteLog('Staged Dunning Plan '||p_dunning_plan_id||' has no as no dunning stages defined');
4239 		       exit;
4240 		   end if;
4241 		   --exit when c_dunningplan_lines%notfound;
4242 		   --end added to fix 13519559 12/23/2011 snuthala
4243                    */
4244 
4245 	   	   for i in l_dunningplan_lines.range_of_dunning_level_from..l_dunningplan_lines.range_of_dunning_level_to
4246 		   loop
4247 			l_stage	:= i-1;
4248 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_stage :'||l_stage);
4249 
4250 			if i = 1 then
4251 				open c_bill_dunning_trx_null_dun_ct (l_site_use_id,
4252 				                            l_dunningplan_lines.min_days_between_dunning,
4253 		   					    p_correspondence_date,
4254 							    p_grace_days,
4255 							    p_dun_disputed_items,
4256 							    l_invoice_currency_code,
4257 							    l_min_dunning_invoice_amount,
4258 							    l_org_id);
4259 				 fetch c_bill_dunning_trx_null_dun_ct into l_amount;
4260 				 close c_bill_dunning_trx_null_dun_ct;
4261 			else
4262 
4263 				 open c_bill_dunning_trx_ct (l_site_use_id,
4264 							   l_stage,
4265 							   l_dunningplan_lines.min_days_between_dunning,
4266 							   p_correspondence_date,
4267 							   p_dun_disputed_items,
4268 							   l_invoice_currency_code,
4269 							   l_min_dunning_invoice_amount,
4270 							   l_org_id);
4271 				 fetch c_bill_dunning_trx_ct into l_amount;
4272 				 close c_bill_dunning_trx_ct;
4273 			end if;
4274                         l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_amount,0);
4275 
4276                         -- BillsReceivables bug 16303059 starting....
4277                         if nvl(tt_site_use_id,0) <> 0 then
4278 			   if i = 1 then
4279 				open c_bill_dunning_trx_null_dun_ct (tt_site_use_id,
4280 				                            l_dunningplan_lines.min_days_between_dunning,
4281 		   					    p_correspondence_date,
4282 							    p_grace_days,
4283 							    p_dun_disputed_items,
4284 							    l_invoice_currency_code,
4285 							    l_min_dunning_invoice_amount,
4286 							    l_org_id);
4287 				 fetch c_bill_dunning_trx_null_dun_ct into l_amount;
4288 				 close c_bill_dunning_trx_null_dun_ct;
4289 			   else
4290 
4291 				 open c_bill_dunning_trx_ct (tt_site_use_id,
4292 							   l_stage,
4293 							   l_dunningplan_lines.min_days_between_dunning,
4294 							   p_correspondence_date,
4295 							   p_dun_disputed_items,
4296 							   l_invoice_currency_code,
4297 							   l_min_dunning_invoice_amount,
4298 							   l_org_id);
4299 				 fetch c_bill_dunning_trx_ct into l_amount;
4300 				 close c_bill_dunning_trx_ct;
4301 			   end if;
4302                            l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_amount,0);
4303                          end if;
4304                         -- BillsReceivables bug 16303059 ending....
4305 
4306 
4307 		    end loop;
4308 		end loop;
4309 		close c_dunningplan_lines;
4310 	        WriteLog('l_amount = '||l_amount);
4311                 WriteLog('l_invoice_amount = '||l_invoice_amount);
4312 
4313 		--Begin Bug 10401991 03-Feb-2011 barathsr
4314 		open c_cm_ar_amount_billto_curr(l_site_use_id,l_invoice_currency_code,l_org_id);
4315 		loop
4316 		       fetch c_cm_ar_amount_billto_curr into l_cm_ar_amount;
4317 		       exit when c_cm_ar_amount_billto_curr%notfound;
4318                        /*
4319 		       if c_cm_ar_amount_billto_curr%notfound then
4320 			   WriteLog('No open Account Receipts and credit memos');
4321 			   exit;
4322 			end if;
4323                         */
4324 		        l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
4325 
4326 		 end loop;
4327 		 close c_cm_ar_amount_billto_curr;
4328 		 --End Bug 10401991 03-Feb-2011 barathsr
4329 
4330 
4331 		 /*   open c_cm_ar_amount_billto_curr(l_site_use_id,l_invoice_currency_code,l_org_id);
4332 		 fetch c_cm_ar_amount_billto_curr into l_cm_ar_amount;
4333 		 if c_cm_ar_amount_billto_curr%notfound then
4334 			  l_cm_ar_amount := 0;
4335 		 end if;
4336 		 close c_cm_ar_amount_billto_curr; */
4337 
4338 		 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_cm_ar_total_amount-->'||l_cm_ar_total_amount);
4339 		 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_tot_amt_due_rem-->   '||l_tot_amt_due_rem);
4340                  WriteLog('l_cm_ar_amount = '||l_cm_ar_amount);
4341 
4342 		 -- substracting credit memo amount and ar receipr amount from total amount due
4343 		 --(but here i used + sign because the credit memo and account recipt amount will be negitive values)
4344 
4345 		 l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_cm_ar_total_amount,0);--Added for Bug 10401991 02-Feb-2011 barathsr
4346 		 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Final l_tot_amt_due_rem-->   '||l_tot_amt_due_rem);
4347 
4348 		--If any currency group satisfies the condition then we have to send the dunning letter,
4349 		--so no need to check for other currencies.
4350 		if l_tot_amt_due_rem >= l_min_dunning_amount then
4351 			--l_dunning_letters := 'Y';
4352 			i := i +1;
4353 			l_inc_inv_curr (i) := l_invoice_currency_code;
4354 		end if;
4355 	      end loop;
4356 	      close c_billto_dist_inv_cur;
4357 
4358 	elsif (l_cust_account_id is not null ) Then   -- account level calculation
4359 	      --l_dunning_letters := 'N';  --initially set it no
4360 	      iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - p_running_level :'||p_running_level);
4361 	      if p_running_level = 'ACCOUNT' then
4362 		      open c_acc_dist_inv_cur(l_cust_account_id,l_org_id);
4363 		      loop
4364 			fetch c_acc_dist_inv_cur into l_invoice_currency_code;
4365 			if c_acc_dist_inv_cur%notfound then
4366 			  exit;
4367 			end if;
4368 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_invoice_currency_code :'||l_invoice_currency_code);
4369 
4370 			open c_acc_min_dunn_amt (l_cust_account_id, l_invoice_currency_code);
4371 			fetch c_acc_min_dunn_amt into l_min_dunning_amount, l_min_dunning_invoice_amount;
4372 			/*
4373 			if c_acc_dist_inv_cur%notfound then
4374 				i := i +1;
4375 				l_inc_inv_curr (i) := l_invoice_currency_code;
4376 			end if;
4377 			*/
4378 			close c_acc_min_dunn_amt;
4379 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_min_dunning_amount :'||l_min_dunning_amount);
4380 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_min_dunning_invoice_amount :'||l_min_dunning_invoice_amount);
4381 
4382 			if l_min_dunning_amount is null then
4383 				l_min_dunning_amount := 0;
4384 			end if;
4385 
4386 			if l_min_dunning_invoice_amount is null then
4387 				l_min_dunning_invoice_amount := 0;
4388 			end if;
4389 
4390 			l_amount		:= 0;
4391 			l_tot_amt_due_rem	:= 0;
4392 
4393 			      open c_dunningplan_lines (p_dunning_plan_id);
4394 				 loop
4395 					 fetch c_dunningplan_lines into l_dunningplan_lines;
4396 					 --start added to fix 13519559 12/23/2011 snuthala
4397 					 if c_dunningplan_lines%notfound then
4398 						  FND_FILE.PUT_LINE(FND_FILE.LOG, '****** Stage Dunning Plan '||p_dunning_plan_id||' has no dunning stages defined *****');
4399 						  WriteLog('Stage Dunning Plan '||p_dunning_plan_id||' has no dunning stages defined');
4400 						  exit;
4401 					 end if;
4402 					 --exit when c_dunningplan_lines%notfound;
4403 					 --end added to fix 13519559 12/23/2011 snuthala
4404 
4405 					 for i in l_dunningplan_lines.range_of_dunning_level_from..l_dunningplan_lines.range_of_dunning_level_to
4406 					      loop
4407 							WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - i: ' || i);
4408 							l_stage	:= i-1;
4409 							iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_stage :'||l_stage);
4410 
4411 							if i = 1 then
4412 								open c_acc_dunning_trx_null_dun_ct (l_cust_account_id,
4413 											    l_dunningplan_lines.min_days_between_dunning,
4414 											    p_correspondence_date,
4415 											    p_grace_days,
4416 											    p_dun_disputed_items,
4417 											    l_invoice_currency_code,
4418 											    l_min_dunning_invoice_amount,
4419 											    l_org_id);
4420 								 fetch c_acc_dunning_trx_null_dun_ct into l_amount;
4421 								 close c_acc_dunning_trx_null_dun_ct;
4422 								 iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_amount: ' || l_amount);
4423 							else
4424 
4425 								 open c_acc_dunning_trx_ct (l_cust_account_id,
4426 											   l_stage,
4427 											   l_dunningplan_lines.min_days_between_dunning,
4428 											   p_correspondence_date,
4429 											   p_dun_disputed_items,
4430 											   l_invoice_currency_code,
4431 					 						   l_min_dunning_invoice_amount,
4432 											   l_org_id);
4433 								 fetch c_acc_dunning_trx_ct into l_amount;
4434 								 close c_acc_dunning_trx_ct;
4435 								 iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_amount: ' || l_amount);
4436 							end if;
4437 							l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_amount,0);
4438 						end loop;
4439 				end loop;
4440 				close c_dunningplan_lines;
4441 
4442 
4443 		      open c_cm_ar_amount_account_curr(l_cust_account_id,l_invoice_currency_code,l_org_id);
4444 		       loop
4445 		       fetch c_cm_ar_amount_account_curr into l_cm_ar_amount;
4446 		       if c_cm_ar_amount_account_curr%notfound then
4447 			   WriteLog('No open Account Receipts and credit memos');
4448 			   exit;
4449 			end if;
4450 
4451 			l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
4452 
4453 		      end loop;
4454 		      close c_cm_ar_amount_account_curr;
4455 		      l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_cm_ar_total_amount,0);
4456 			--If any currency group satisfies the condition then we have to send the dunning letter,
4457 			--so no need to check for other currencies.
4458 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_tot_amt_due_rem: ' || l_tot_amt_due_rem);
4459 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_min_dunning_amount: ' || l_min_dunning_amount);
4460 			if l_tot_amt_due_rem >= l_min_dunning_amount then
4461 				--l_dunning_letters := 'Y';
4462 				i := i +1;
4463 				l_inc_inv_curr (i) := l_invoice_currency_code;
4464 			end if;
4465 		      end loop;
4466 		      close c_acc_dist_inv_cur;
4467 
4468 		elsif p_running_level = 'CUSTOMER' then
4469 			open c_cus_dist_inv_cur(l_party_id,l_org_id);
4470 		      loop
4471 			fetch c_cus_dist_inv_cur into l_invoice_currency_code;
4472 			if c_cus_dist_inv_cur%notfound then
4473 			  exit;
4474 			end if;
4475 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_invoice_currency_code :'||l_invoice_currency_code);
4476 
4477 			open c_acc_min_dunn_amt (l_cust_account_id, l_invoice_currency_code);
4478 			fetch c_acc_min_dunn_amt into l_min_dunning_amount, l_min_dunning_invoice_amount;
4479 			/*
4480 			if c_acc_dist_inv_cur%notfound then
4481 				i := i +1;
4482 				l_inc_inv_curr (i) := l_invoice_currency_code;
4483 			end if;
4484 			*/
4485 			close c_acc_min_dunn_amt;
4486 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_min_dunning_amount :'||l_min_dunning_amount);
4487 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_min_dunning_invoice_amount :'||l_min_dunning_invoice_amount);
4488 
4489 			if l_min_dunning_amount is null then
4490 				l_min_dunning_amount := 0;
4491 			end if;
4492 
4493 			if l_min_dunning_invoice_amount is null then
4494 				l_min_dunning_invoice_amount := 0;
4495 			end if;
4496 
4497 			l_amount		:= 0;
4498 			l_tot_amt_due_rem	:= 0;
4499 
4500 			      open c_dunningplan_lines (p_dunning_plan_id);
4501 				 loop
4502 					 fetch c_dunningplan_lines into l_dunningplan_lines;
4503 					 --Start added to fix 13519559 12/23/2011 anunthala
4504 					  if c_dunningplan_lines%notfound then
4505 						  FND_FILE.PUT_LINE(FND_FILE.LOG, '****** Stage Dunning Plan '||p_dunning_plan_id||' has no dunning stages defined *****');
4506 						  WriteLog('Stage Dunning Plan '||p_dunning_plan_id||' has no dunning stages defined');
4507 						  exit;
4508 				          end if;
4509 					  --exit when c_dunningplan_lines%notfound;
4510 					 --end added to fix 13519559 12/23/2011 snuthala
4511 
4512 					 for i in l_dunningplan_lines.range_of_dunning_level_from..l_dunningplan_lines.range_of_dunning_level_to
4513 					      loop
4514 							WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - i: ' || i);
4515 							l_stage	:= i-1;
4516 							iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_stage :'||l_stage);
4517 
4518 							if i = 1 then
4519 								open c_cus_dunning_trx_null_dun_ct (l_party_id,
4520 											    l_dunningplan_lines.min_days_between_dunning,
4521 											    p_correspondence_date,
4522 											    p_grace_days,
4523 											    p_dun_disputed_items,
4524 											    l_invoice_currency_code,
4525 											    l_min_dunning_invoice_amount,
4526 											    l_org_id);
4527 								 fetch c_cus_dunning_trx_null_dun_ct into l_amount;
4528 								 close c_cus_dunning_trx_null_dun_ct;
4529 								 iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_amount: ' || l_amount);
4530 							else
4531 
4532 								 open c_cus_dunning_trx_ct (l_party_id,
4533 											   l_stage,
4534 											   l_dunningplan_lines.min_days_between_dunning,
4535 											   p_correspondence_date,
4536 											   p_dun_disputed_items,
4537 											   l_invoice_currency_code,
4538 											   l_min_dunning_invoice_amount,
4539 											   l_org_id);
4540 								 fetch c_cus_dunning_trx_ct into l_amount;
4541 								 close c_cus_dunning_trx_ct;
4542 								 iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_amount: ' || l_amount);
4543 							end if;
4544 							l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_amount,0);
4545 						end loop;
4546 				end loop;
4547 				close c_dunningplan_lines;
4548 
4549 		       open c_cm_ar_amount_account_curr(l_cust_account_id,l_invoice_currency_code,l_org_id);
4550 		       loop
4551 		       fetch c_cm_ar_amount_account_curr into l_cm_ar_amount;
4552 		       if c_cm_ar_amount_account_curr%notfound then
4553 			   WriteLog('No open Account Receipts and credit memos');
4554 			   exit;
4555 			end if;
4556 
4557 			l_cm_ar_total_amount := nvl(l_cm_ar_total_amount,0) + nvl(l_cm_ar_amount,0);
4558 
4559 		      end loop;
4560 		      close c_cm_ar_amount_account_curr;
4561 		       l_tot_amt_due_rem := nvl(l_tot_amt_due_rem,0) + nvl(l_cm_ar_total_amount,0);
4562 
4563 			--If any currency group satisfies the condition then we have to send the dunning letter,
4564 			--so no need to check for other currencies.
4565 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_tot_amt_due_rem: ' || l_tot_amt_due_rem);
4566 			iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_min_dunning_amount: ' || l_min_dunning_amount);
4567 			if l_tot_amt_due_rem >= l_min_dunning_amount then
4568 				--l_dunning_letters := 'Y';
4569 				i := i +1;
4570 				l_inc_inv_curr (i) := l_invoice_currency_code;
4571 			end if;
4572 		      end loop;
4573 		      close c_cus_dist_inv_cur;
4574 		end if;
4575 	end if;
4576 
4577     iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - l_inc_inv_curr.count: '|| l_inc_inv_curr.count);
4578     if l_inc_inv_curr.count = 0 then
4579 	l_dunning_letters := 'N';
4580     else
4581 	l_dunning_letters := 'Y';
4582     end if;
4583 
4584     p_inc_inv_curr := l_inc_inv_curr;
4585     p_dunning_letters := l_dunning_letters;
4586 
4587     iex_debug_pub.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - End');
4588 
4589 EXCEPTION
4590  WHEN OTHERS THEN
4591     raise;
4592 End StagedDunningMinAmountCheck;
4593 
4594 Procedure MaxStageForanDelinquency (  p_delinquency_id   IN  number
4595                                     , p_stage_number     OUT NOCOPY number)
4596 is
4597 l_stage_number	number;
4598 begin
4599 	select max(iet.stage_number)
4600 	into l_stage_number
4601 	from iex_dunning_transactions iet,
4602 	iex_dunnings dunn,
4603 	iex_delinquencies_all del
4604 	where iet.payment_schedule_id = del.payment_schedule_id
4605 	and del.delinquency_id = p_delinquency_id
4606 	and dunn.dunning_id = iet.dunning_id
4607 	and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
4608 	      OR (dunn.dunning_mode = 'FINAL'))
4609 	and dunn.delivery_status is null;
4610 
4611 	p_stage_number	:= l_stage_number;
4612 
4613 EXCEPTION
4614  WHEN OTHERS THEN
4615     raise;
4616 end MaxStageForanDelinquency;
4617 
4618 Procedure WriteLog      (  p_msg                     IN VARCHAR2)
4619 IS
4620 BEGIN
4621      IF (FND_LOG.LEVEL_EVENT >= PG_DEBUG) THEN
4622          iex_debug_pub.LogMessage (p_msg);
4623      END IF;
4624 
4625 END WriteLog;
4626 
4627 -- Begin- Andre 11/22/2005 - bug4740016 - Cache for SQL populated data.
4628 FUNCTION get_cache_value (p_Identifier  IN VARCHAR2,
4629                              p_PopulateSql  IN VARCHAR2)
4630  RETURN VARCHAR2 IS
4631 l_return varchar2(80);
4632 l_hash_value NUMBER;
4633 BEGIN
4634   IF p_Identifier IS NOT NULL THEN
4635 
4636     l_hash_value := DBMS_UTILITY.get_hash_value(
4637                                          p_Identifier||'@*?',
4638                                          1000,
4639                                          25000);
4640 
4641     IF pg_iexcache_rec.EXISTS(l_hash_value) THEN
4642         l_return := pg_iexcache_rec(l_hash_value);
4643     ELSE
4644        IF p_PopulateSql IS NOT NULL then
4645 	-- simple select statement
4646 	      EXECUTE IMMEDIATE p_PopulateSql
4647 	      INTO l_return;
4648           pg_iexcache_rec(l_hash_value) := l_return;
4649        ELSE
4650           pg_iexcache_rec(l_hash_value) := Null;
4651        END IF;
4652 
4653     END IF;
4654 
4655   END IF;
4656 
4657   return(l_return);
4658 
4659 EXCEPTION
4660  WHEN no_data_found  THEN
4661   return(null);
4662  WHEN OTHERS THEN
4663   raise;
4664 END;
4665 -- End- Andre 11/22/2005 - bug4740016 - Cache for SQL populated data.
4666 
4667 --Begin bug#4368394 schekuri 30-Nov-2005
4668 --Added the following to provide a way to get the view by level of collections header
4669 --in the database view itself
4670 PROCEDURE SET_VIEW_BY_LEVEL(p_view_by in VARCHAR2) IS
4671 BEGIN
4672     G_VIEW_BY_LEVEL:=p_view_by;
4673 END SET_VIEW_BY_LEVEL;
4674 
4675 FUNCTION GET_VIEW_BY_LEVEL RETURN VARCHAR2 IS
4676 BEGIN
4677    IF G_VIEW_BY_LEVEL IS NULL THEN
4678 	   RETURN 'PARTY';
4679    ELSE
4680 	   RETURN G_VIEW_BY_LEVEL;
4681    END IF;
4682 END GET_VIEW_BY_LEVEL;
4683 --End bug#4368394 schekuri 30-Nov-2005
4684 
4685 
4686 --Begin bug#4773082 ctlee 1-Dec-2005 performance issue
4687 FUNCTION get_amount_due_remaining (p_customer_trx_id  IN number)
4688 return number is
4689 amount_due_remaining number;
4690  BEGIN
4691    select sum(amount_due_remaining) into amount_due_remaining from ar_payment_schedules_all
4692    where customer_trx_id = p_customer_trx_id;
4693    return amount_due_remaining;
4694 EXCEPTION
4695  WHEN OTHERS THEN
4696     return amount_due_remaining;
4697 END get_amount_due_remaining;
4698 --End bug#4773082 ctlee 1-Dec-2005
4699 
4700 --Begin bug#4864641 ctlee 6-Dec-2005 performance issue
4701 FUNCTION get_amount_due_original (p_customer_trx_id  IN number)
4702 return number is
4703 amount_due_original number;
4704  BEGIN
4705    select sum(amount_due_original) into amount_due_original from ar_payment_schedules_all
4706    where customer_trx_id = p_customer_trx_id;
4707    return amount_due_original;
4708 EXCEPTION
4709  WHEN OTHERS THEN
4710     return amount_due_original;
4711 END get_amount_due_original;
4712 --End bug#4864641 ctlee 6-Dec-2005 performance issue
4713 
4714 --Begin bug#5373412 schekuri 10-Jul-2006
4715 --Added the following procedure to consolidate the functionality of procedures
4716 --get_billto_resources, get_assign_account_resources, get_assign_resources and get_access_resources
4717 --into a single procedure.
4718 -- This procedure will return the resource assigned to a customer, account, site, case
4719 PROCEDURE get_assigned_collector(p_api_version    IN  NUMBER := 1.0,
4720                                p_init_msg_list    IN  VARCHAR2,
4721                                p_commit           IN  VARCHAR2,
4722                                p_validation_level IN  NUMBER,
4723                                p_level            IN  VARCHAR2,
4724                                p_level_id         IN  VARCHAR2,
4725                                x_msg_count        OUT NOCOPY NUMBER,
4726                                x_msg_data         OUT NOCOPY VARCHAR2,
4727                                x_return_status    OUT NOCOPY VARCHAR2,
4728                                x_resource_tab     OUT NOCOPY resource_tab_type) IS
4729 
4730 /* ------ SQLs assembled at run time -----------------------------------
4731 CURSOR c_billto_collector is
4732 SELECT ac.employee_id, ac.resource_id, 0
4733 FROM  hz_customer_profiles hp, ar_collectors ac
4734 WHERE hp.site_use_id = p_site_use_id
4735   and hp.collector_id  = ac.collector_id
4736   and ac.resource_type = 'RS_RESOURCE'
4737   and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4738   and nvl(ac.status,'A') = 'A'
4739   and nvl(hp.status,'A') = 'A'
4740 union all
4741 ( SELECT jtg.person_id, jtg.resource_id, count(work_item_id)
4742     FROM  hz_customer_profiles hp,  iex_strategy_work_items wi,
4743           ar_collectors ac, jtf_rs_group_members jtg
4744     WHERE hp.site_use_id  = p_site_use_id
4745       and hp.collector_id  = ac.collector_id
4746       and ac.resource_type = 'RS_GROUP'
4747       and ac.resource_id  = jtg.group_id
4748       and jtg.resource_id = wi.resource_id
4749       and wi.status_code   = 'OPEN'
4750       and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4751       and nvl(ac.status,'A') = 'A'
4752       and nvl(hp.status,'A') = 'A'
4753       and nvl(jtg.delete_flag,'N') = 'N'
4754       group by jtg.resource_id, jtg.person_id
4755 UNION ALL
4756     SELECT jtg.person_id, jtg.resource_id, 0
4757     FROM  hz_customer_profiles hp, ar_collectors ac,
4758       jtf_rs_group_members jtg
4759     WHERE hp.site_use_id  = p_site_use_id
4760       and hp.collector_id   = ac.collector_id
4761       and ac.resource_type = 'RS_GROUP'
4762       and ac.resource_id = jtg.group_id
4763       and not exists (select null from iex_strategy_work_items wi
4764             where jtg.resource_id = wi.resource_id
4765       and wi.status_code = 'OPEN')
4766       and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4767       and nvl(ac.status,'A') = 'A'
4768       and nvl(hp.status,'A') = 'A'
4769       and nvl(jtg.delete_flag,'N') = 'N'
4770       group by jtg.resource_id, jtg.person_id
4771       ) order by 3;
4772 
4773 CURSOR c_account_collector IS
4774 SELECT ac.employee_id, ac.resource_id, 0
4775 FROM  hz_customer_profiles hp, ar_collectors ac
4776 WHERE hp.cust_account_id = p_account_id
4777   and hp.site_use_id is null
4778   and hp.collector_id  = ac.collector_id
4779   and ac.resource_type = 'RS_RESOURCE'
4780   and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4781   and nvl(ac.status,'A') = 'A'
4782   and nvl(hp.status,'A') = 'A'
4783 union all
4784 ( SELECT jtg.person_id, jtg.resource_id, count(work_item_id)
4785     FROM  hz_customer_profiles hp,  iex_strategy_work_items wi,
4786           ar_collectors ac, jtf_rs_group_members jtg
4787     WHERE hp.cust_account_id  = p_account_id
4788       and hp.site_use_id is NULL
4789       and hp.collector_id  = ac.collector_id
4790       and ac.resource_type = 'RS_GROUP'
4791       and ac.resource_id  = jtg.group_id
4792       and jtg.resource_id = wi.resource_id
4793       and wi.status_code   = 'OPEN'
4794       and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4795       and nvl(ac.status,'A') = 'A'
4796       and nvl(hp.status,'A') = 'A'
4797       and nvl(jtg.delete_flag,'N') = 'N'
4798       group by jtg.resource_id, jtg.person_id
4799 UNION ALL
4800     SELECT jtg.person_id, jtg.resource_id, 0
4801     FROM  hz_customer_profiles hp, ar_collectors ac,
4802       jtf_rs_group_members jtg
4803     WHERE hp.cust_account_id  = p_account_id
4804       and hp.site_use_id is null
4805       and hp.collector_id   = ac.collector_id
4806       and ac.resource_type = 'RS_GROUP'
4807       and ac.resource_id = jtg.group_id
4808       and not exists (select null from iex_strategy_work_items wi
4809             where jtg.resource_id = wi.resource_id
4810       and wi.status_code = 'OPEN')
4811       and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4812       and nvl(ac.status,'A') = 'A'
4813       and nvl(hp.status,'A') = 'A'
4814       and nvl(jtg.delete_flag,'N') = 'N'
4815       group by jtg.resource_id, jtg.person_id
4816       ) order by 3;
4817 
4818 cursor c_party_collector IS
4819 SELECT ac.employee_id, ac.resource_id, 0
4820 FROM  hz_customer_profiles hp, ar_collectors ac
4821 WHERE hp.party_id = p_party_id
4822   and hp.cust_account_id = -1
4823   and hp.collector_id  = ac.collector_id
4824   and ac.resource_type = 'RS_RESOURCE'
4825   and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4826   and nvl(ac.status,'A') = 'A'
4827   and nvl(hp.status,'A') = 'A'
4828 union all
4829 ( SELECT jtg.person_id, jtg.resource_id, count(work_item_id)
4830     FROM  hz_customer_profiles hp,  iex_strategy_work_items wi,
4831           ar_collectors ac, jtf_rs_group_members jtg
4832     WHERE hp.party_id  = P_PARTY_ID
4833       and hp.cust_account_id = -1
4834       and hp.collector_id  = ac.collector_id
4835       and ac.resource_type = 'RS_GROUP'
4836       and ac.resource_id  = jtg.group_id
4837       and jtg.resource_id = wi.resource_id
4838       and wi.status_code   = 'OPEN'
4839       and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4840       and nvl(ac.status,'A') = 'A'
4841       and nvl(hp.status,'A') = 'A'
4842       and nvl(jtg.delete_flag,'N') = 'N'
4843       group by jtg.resource_id, jtg.person_id
4844 UNION ALL
4845     SELECT jtg.person_id, jtg.resource_id, 0
4846     FROM  hz_customer_profiles hp, ar_collectors ac,
4847       jtf_rs_group_members jtg
4848     WHERE hp.party_id  = p_party_id
4849       and hp.cust_account_id = -1
4850       and hp.collector_id   = ac.collector_id
4851       and ac.resource_type = 'RS_GROUP'
4852       and ac.resource_id = jtg.group_id
4853       and not exists (select null from iex_strategy_work_items wi
4854             where jtg.resource_id = wi.resource_id
4855       and wi.status_code = 'OPEN')
4856       and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4857       and nvl(ac.status,'A') = 'A'
4858       and nvl(hp.status,'A') = 'A'
4859       and nvl(jtg.delete_flag,'N') = 'N'
4860       group by jtg.resource_id, jtg.person_id
4861       ) order by 3;
4862 
4863   CURSOR c_case_collector IS
4864     SELECT ac.employee_id, ac.resource_id, count(cas_id)
4865     FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_cases_vl wi,ar_collectors ac
4866     WHERE hp.party_id = p_party_id
4867       and rs.resource_id = ac.resource_id
4868       and hp.collector_id = ac.collector_id
4869       and ac.resource_id = wi.owner_resource_id(+)
4870       and rs.user_id is not null
4871       and ac.employee_id is not null
4872       and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate)
4873       and nvl(ac.status,'A') = 'A'
4874       and nvl(hp.status,'A') = 'A'
4875       group by ac.resource_id, ac.employee_id ORDER BY 3;
4876 */
4877 
4878   l_api_version   CONSTANT NUMBER     := p_api_version;
4879   l_api_name CONSTANT VARCHAR2(100)   := 'get_assigned_collector';
4880   l_init_msg_list CONSTANT VARCHAR2(1):= p_init_msg_list;
4881   l_return_status VARCHAR2(1);
4882   l_msg_count NUMBER;
4883   l_msg_data VARCHAR2(32767);
4884   idx NUMBER := 0;
4885   l_count NUMBER := 0;
4886 
4887   l_select1 VARCHAR2(3000);
4888   l_select2 VARCHAR2(3000);
4889   l_select3 VARCHAR2(3000);
4890   l_select4 VARCHAR2(3000);
4891   --Begin Bug#5229763 schekuri 27-Jul-2006
4892   l_select5 VARCHAR2(3000);
4893   l_select6 VARCHAR2(3000);
4894   --End Bug#5229763 schekuri 27-Jul-2006
4895 
4896   l_where1 VARCHAR2(3000);
4897   l_where2 VARCHAR2(3000);
4898   l_where3 VARCHAR2(3000);
4899   l_where4 VARCHAR2(3000);
4900   --Begin Bug#5229763 schekuri 27-Jul-2006
4901   l_where5 VARCHAR2(3000);
4902   l_where6 VARCHAR2(3000);
4903   --End Bug#5229763 schekuri 27-Jul-2006
4904 
4905   l_group2 VARCHAR2(3000);
4906   l_group3 VARCHAR2(3000);
4907   l_group4 VARCHAR2(3000);
4908   --Begin Bug#5229763 schekuri 27-Jul-2006
4909   l_group5 VARCHAR2(3000);
4910   l_group6 VARCHAR2(3000);
4911   --End Bug#5229763 schekuri 27-Jul-2006
4912 
4913   l_order VARCHAR2(3000) := ' ORDER BY 3';
4914   l_union VARCHAR2(3000) := ' UNION ALL ';
4915 
4916   l_query VARCHAR2(32767);
4917 
4918   TYPE c_cur_type IS REF CURSOR;
4919   c_collector c_cur_type;
4920 
4921 BEGIN
4922 
4923   iex_debug_pub.logmessage ('**** BEGIN get_assigned_collector ************');
4924 
4925 
4926   SAVEPOINT	get_assigned_collector;
4927 
4928   -- Standard call to check for call compatibility.
4929   IF NOT FND_API.Compatible_API_Call (l_api_version,
4930                                       p_api_version,
4931                                       l_api_name,
4932                                       G_PKG_NAME)    THEN
4933 	RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
4934   END IF;
4935 
4936   -- Check p_init_msg_list
4937   IF FND_API.to_Boolean( p_init_msg_list ) THEN
4938     FND_MSG_PUB.initialize;
4939   END IF;
4940 
4941   x_return_status := FND_API.G_RET_STS_SUCCESS;
4942 
4943   --Start Bug 7134688 gnramasa 17th June 08
4944 
4945   -- Initialize SQL statements - REMEMBER CHANGING 1 MEANS CHANGING ALL
4946   l_select1 :=              'SELECT ac.employee_id, ac.resource_id, 0 ';
4947   l_select1 := l_select1 || 'FROM  hz_customer_profiles hp, ar_collectors ac,jtf_rs_resource_extns rs, ';
4948   l_select1 := l_select1 || ' jtf_rs_role_relations jtr, jtf_rs_roles_b jtrr '; -- Added by bibeura for bug 12562473
4949   l_where1  :=              'WHERE ';
4950   l_where1  := l_where1  || '      hp.collector_id  = ac.collector_id ';
4951   l_where1  := l_where1  || '  and ac.resource_type = ''RS_RESOURCE'' ';
4952   l_where1  := l_where1  || '  and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate) ';
4953   l_where1  := l_where1  || '  and nvl(ac.status,''A'') = ''A'' ';
4954   l_where1  := l_where1  || '  and nvl(hp.status,''A'') = ''A'' ';
4955   l_where1  := l_where1  || '  and rs.resource_id = ac.resource_id ';
4956   l_where1  := l_where1  || '  and trunc(nvl(rs.end_date_active,sysdate)) >= trunc(sysdate) ';
4957   l_where1  := l_where1  || '  and jtr.role_resource_id = rs.resource_id '; -- Added by bibeura for bug 12562473
4958   l_where1  := l_where1  || '  and jtr.role_resource_type = ''RS_INDIVIDUAL'' '; -- Added by bibeura for bug 13954147
4959   l_where1  := l_where1  || '  and jtrr.role_type_code = ''COLLECTIONS'' '; -- Added by bibeura for bug 12562473
4960   l_where1  := l_where1  || '  and jtr.role_id = jtrr.role_id '; -- Added by bibeura for bug 12562473
4961   l_where1  := l_where1  || '  and NVL(jtr.delete_flag,''N'') = ''N'' '; -- Added by bibeura for bug 12562473
4962   l_where1  := l_where1  || '  and TRUNC(NVL(jtr.end_date_active,sysdate)) >= TRUNC(sysdate) '; -- Added by bibeura for bug 12562473
4963 
4964   l_select2 :=              'SELECT jtg.person_id, jtg.resource_id, count(work_item_id) ';
4965   l_select2 := l_select2 || 'FROM hz_customer_profiles hp,  iex_strategy_work_items wi, ';
4966   l_select2 := l_select2 || '     ar_collectors ac, jtf_rs_group_members jtg, jtf_rs_resource_extns rs ';
4967   l_select2 := l_select2 || '     , jtf_rs_role_relations jtr,JTF_RS_ROLES_b jtrr ';
4968   l_where2  :=              'WHERE ';
4969   l_where2  := l_where2  || '      hp.collector_id  = ac.collector_id ';
4970   l_where2  := l_where2  || '  and ac.resource_type = ''RS_GROUP'' ';
4971   l_where2  := l_where2  || '  and ac.resource_id  = jtg.group_id ';
4972   l_where2  := l_where2  || '  and jtg.resource_id = wi.resource_id ';
4973   -- Start bug 13954147 bibeura
4974   --l_where2  := l_where2  || '  and jtg.group_member_id = jtr.role_resource_id ';
4975   l_where2  := l_where2  || '  and jtg.resource_id = jtr.role_resource_id ';
4976   l_where2  := l_where2  || '  and jtr.role_resource_type = ''RS_INDIVIDUAL'' ';
4977   -- End bug 13954147 bibeura
4978   l_where2  := l_where2  || '  and jtr.role_id=jtrr.role_id ';
4979   l_where2  := l_where2  || '  and jtrr.role_type_code=''COLLECTIONS'' ';
4980   l_where2  := l_where2  || '  and wi.status_code   = ''OPEN'' ';
4981   l_where2  := l_where2  || '  and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate) ';
4982   l_where2  := l_where2  || '  and nvl(ac.status,''A'') = ''A'' ';
4983   l_where2  := l_where2  || '  and nvl(hp.status,''A'') = ''A'' ';
4984   l_where2  := l_where2  || '  and nvl(jtg.delete_flag,''N'') = ''N'' ';
4985   l_where2  := l_where2  || '  AND nvl(jtr.delete_flag,''N'') = ''N'' ';
4986   l_where2  := l_where2  || '  and jtg.resource_id = rs.resource_id ';
4987   l_where2  := l_where2  || '  and trunc(nvl(rs.end_date_active,sysdate)) >= trunc(sysdate) ';
4988   l_where2  := l_where2  || '  and trunc(nvl(jtr.end_date_active,sysdate)) >= trunc(sysdate) ';
4989   l_group2  :=              'group by jtg.resource_id, jtg.person_id ';
4990 
4991   l_select3 :=              'SELECT jtg.person_id, jtg.resource_id, 0 ';
4992   l_select3 := l_select3 || 'FROM hz_customer_profiles hp, ar_collectors ac,  ';
4993   l_select3 := l_select3 || '     jtf_rs_group_members jtg, jtf_rs_resource_extns rs ';
4994   l_select3 := l_select3 || '     , jtf_rs_role_relations jtr,JTF_RS_ROLES_b jtrr ';
4995   l_where3  :=              ' WHERE ';
4996   l_where3  := l_where3  || '      hp.collector_id   = ac.collector_id ';
4997   l_where3  := l_where3  || '  and ac.resource_type = ''RS_GROUP'' ';
4998   l_where3  := l_where3  || '  and ac.resource_id = jtg.group_id    ';
4999   -- Start bug 13954147 bibeura
5000   --l_where3  := l_where3  || '  and jtg.group_member_id = jtr.role_resource_id ';
5001   l_where3  := l_where3  || '  and jtg.resource_id = jtr.role_resource_id ';
5002   l_where3  := l_where3  || '  and jtr.role_resource_type = ''RS_INDIVIDUAL'' ';
5003   -- End bug 13954147 bibeura
5004   l_where3  := l_where3  || '  and jtr.role_id=jtrr.role_id ';
5005   l_where3  := l_where3  || '  and jtrr.role_type_code=''COLLECTIONS'' ';
5006   l_where3  := l_where3  || '  and not exists (select null from iex_strategy_work_items wi ';
5007   l_where3  := l_where3  || '                  where jtg.resource_id = wi.resource_id ';
5008   l_where3  := l_where3  || '                    and wi.status_code = ''OPEN'') ';
5009   l_where3  := l_where3  || ' and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate) ';
5010   l_where3  := l_where3  || ' and nvl(ac.status,''A'') = ''A'' ';
5011   l_where3  := l_where3  || ' and nvl(hp.status,''A'') = ''A'' ';
5012   l_where3  := l_where3  || ' and nvl(jtg.delete_flag,''N'') = ''N'' ';
5013   l_where3  := l_where3  || ' and nvl(jtr.delete_flag,''N'') = ''N'' ';
5014   l_where3  := l_where3  || '  and jtg.resource_id = rs.resource_id ';
5015   l_where3  := l_where3  || '  and trunc(nvl(rs.end_date_active,sysdate)) >= trunc(sysdate) ';
5016   l_where3  := l_where3  || '  and trunc(nvl(jtr.end_date_active,sysdate)) >= trunc(sysdate) ';
5017   l_group3  :=              ' group by jtg.resource_id, jtg.person_id ';
5018 
5019   l_select4 :=              'SELECT ac.employee_id, ac.resource_id, count(cas_id) ';
5020   --Begin Bug#6962575 29-Jul-2008 barathsr
5021  -- l_select4 := l_select4 || '  FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_cases_vl wi,ar_collectors ac ';
5022  l_select4 := l_select4 || '  FROM  hz_customer_profiles hp, jtf_rs_resource_extns rs, iex_cases_all_b wi,ar_collectors ac ';
5023   --End Bug#6962575 29-Jul-2008 barathsr
5024   l_where4  :=              '  WHERE hp.party_id = :1 ';
5025   l_where4  := l_where4  || '    and rs.resource_id = ac.resource_id ';
5026   l_where4  := l_where4  || '    and hp.collector_id = ac.collector_id ';
5027   l_where4  := l_where4  || '    and ac.resource_id = wi.owner_resource_id(+) ';
5028   l_where4  := l_where4  || '    and rs.user_id is not null ';
5029   l_where4  := l_where4  || '    and ac.employee_id is not null ';
5030   l_where4  := l_where4  || '    and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate) ';
5031   l_where2  := l_where2  || '  and trunc(nvl(rs.end_date_active,sysdate)) >= trunc(sysdate) ';
5032   l_where4  := l_where4  || '    and nvl(ac.status,''A'') = ''A'' ';
5033   l_where4  := l_where4  || '    and nvl(hp.status,''A'') = ''A'' ';
5034   l_group4  := l_group4  || '    group by ac.resource_id, ac.employee_id ORDER BY 3 ';
5035 
5036   --Begin Bug#5229763 schekuri 27-Jul-2006
5037   --Added following sql's for getting resource for task creation in dunning callback concurrent program
5038     l_select5 :=              ' SELECT jtg.person_id, jtg.resource_id, count(t.task_id) ';
5039   l_select5 := l_select5 || ' FROM hz_customer_profiles hp,  jtf_tasks_vl t, jtf_task_statuses_vl s, ';
5040   l_select5 := l_select5 || '     ar_collectors ac, jtf_rs_group_members jtg, jtf_rs_resource_extns rs ';
5041   l_select5 := l_select5 || '     , jtf_rs_role_relations jtr,JTF_RS_ROLES_b jtrr ';
5042   l_where5  :=              ' WHERE ';
5043   l_where5  := l_where5  || '      hp.collector_id  = ac.collector_id ';
5044   l_where5  := l_where5  || '  and ac.resource_type = ''RS_GROUP'' ';
5045   l_where5  := l_where5  || '  and ac.resource_id  = jtg.group_id ';
5046   l_where5  := l_where5  || '  and jtg.resource_id = t.owner_id ';
5047   -- Start bug 13954147 bibeura
5048   --l_where5  := l_where5  || '  and jtg.group_member_id = jtr.role_resource_id ';
5049   l_where5  := l_where5  || '  and jtg.resource_id = jtr.role_resource_id ';
5050   l_where5  := l_where5  || '  and jtr.role_resource_type = ''RS_INDIVIDUAL'' ';
5051   -- End bug 13954147 bibeura
5052   l_where5  := l_where5  || '  and jtr.role_id=jtrr.role_id ';
5053   l_where5  := l_where5  || '  and jtrr.role_type_code=''COLLECTIONS'' ';
5054   l_where5  := l_where5  || '  and t.task_name = ''Dunning Callback'' ';
5055   l_where5  := l_where5  || '  and t.task_status_id = s.task_status_id ';
5056   l_where5  := l_where5  || '  and upper(s.name) = ''OPEN'' ';
5057   l_where5  := l_where5  || '  and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate) ';
5058   l_where5  := l_where5  || '  and nvl(ac.status,''A'') = ''A'' ';
5059   l_where5  := l_where5  || '  and nvl(hp.status,''A'') = ''A'' ';
5060   l_where5  := l_where5  || '  and nvl(jtg.delete_flag,''N'') = ''N'' ';
5061   l_where5  := l_where5  || '  and nvl(jtr.delete_flag,''N'') = ''N'' ';
5062   l_where5  := l_where5  || '  and jtg.resource_id = rs.resource_id ';
5063   l_where5  := l_where5  || '  and trunc(nvl(rs.end_date_active,sysdate)) >= trunc(sysdate) ';
5064   l_where5  := l_where5  || '  and trunc(nvl(jtr.end_date_active,sysdate)) >= trunc(sysdate) ';
5065   l_group5  :=              'group by jtg.resource_id, jtg.person_id ';
5066 
5067   l_select6 :=              'SELECT jtg.person_id, jtg.resource_id, 0 ';
5068   l_select6 := l_select6 || ' FROM hz_customer_profiles hp, ar_collectors ac,  ';
5069   l_select6 := l_select6 || '     jtf_rs_group_members jtg, jtf_rs_resource_extns rs ';
5070   l_select6 := l_select6 || '     , jtf_rs_role_relations jtr,JTF_RS_ROLES_b jtrr ';
5071   l_where6  :=              ' WHERE ';
5072   l_where6  := l_where6  || '      hp.collector_id   = ac.collector_id ';
5073   l_where6  := l_where6  || '  and ac.resource_type = ''RS_GROUP'' ';
5074   l_where6  := l_where6  || '  and ac.resource_id = jtg.group_id    ';
5075   -- Start bug 13954147 bibeura
5076   --l_where6  := l_where6  || '  and jtg.group_member_id = jtr.role_resource_id ';
5077   l_where6  := l_where6  || '  and jtg.resource_id = jtr.role_resource_id ';
5078   l_where6  := l_where6  || '  and jtr.role_resource_type = ''RS_INDIVIDUAL'' ';
5079   -- End bug 13954147 bibeura
5080   l_where6  := l_where6  || '  and jtr.role_id=jtrr.role_id ';
5081   l_where6  := l_where6  || '  and jtrr.role_type_code=''COLLECTIONS'' ';
5082   l_where6  := l_where6  || '  and not exists (select 1 from jtf_tasks_vl t, jtf_task_statuses_vl s ';
5083   l_where6  := l_where6  || '  where jtg.resource_id = t.owner_id ';
5084   l_where6  := l_where6  || '  and t.task_name = ''Dunning Callback'' ';
5085   l_where6  := l_where6  || '  and t.task_status_id = s.task_status_id ';
5086   l_where6  := l_where6  || '  and upper(s.name) = ''OPEN'') ';
5087   l_where6  := l_where6  || ' and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate) ';
5088   l_where6  := l_where6  || ' and nvl(ac.status,''A'') = ''A'' ';
5089   l_where6  := l_where6  || ' and nvl(hp.status,''A'') = ''A'' ';
5090   l_where6  := l_where6  || ' and nvl(jtg.delete_flag,''N'') = ''N'' ';
5091   l_where6  := l_where6  || ' and nvl(jtr.delete_flag,''N'') = ''N'' ';
5092   l_where6  := l_where6  || ' and jtg.resource_id = rs.resource_id ';
5093   l_where6  := l_where6  || ' and trunc(nvl(rs.end_date_active,sysdate)) >= trunc(sysdate) ';
5094   l_where6  := l_where6  || ' and trunc(nvl(jtr.end_date_active,sysdate)) >= trunc(sysdate) ';
5095   l_group6  :=              ' group by jtg.resource_id, jtg.person_id ';
5096   --End Bug#5229763 schekuri 27-Jul-2006
5097   --End Bug 7134688 gnramasa 17th June 08
5098 
5099   if p_level = 'PARTY' then
5100      l_query := l_select1 || l_where1 || ' and hp.party_id = :1 and hp.cust_account_id = -1 ' ;
5101      l_query := l_query || l_union || '( ' || l_select2 || l_where2 || ' and hp.party_id = :1 and hp.cust_account_id = -1 ' || l_group2;
5102      l_query := l_query || l_union || l_select3 || l_where3 || ' and hp.party_id = :1 and hp.cust_account_id = -1 ' || l_group3 || ' )' || l_order;
5103   end if;
5104   if p_level = 'ACCOUNT' then
5105      l_query := l_select1 || l_where1 || ' and hp.cust_account_id = :1 and hp.site_use_id is null ' ;
5106      l_query := l_query || l_union || '( ' || l_select2 || l_where2 || ' and hp.cust_account_id = :1 and hp.site_use_id is null ' || l_group2;
5107      l_query := l_query || l_union || l_select3 || l_where3 || ' and hp.cust_account_id = :1 and hp.site_use_id is null ' || l_group3 || ' )' || l_order;
5108   end if;
5109   if p_level = 'BILLTO' then
5110      l_query := l_select1 || l_where1 || ' and hp.site_use_id = :1 ' ;
5111      l_query := l_query || l_union || '( ' || l_select2 || l_where2 || ' and hp.site_use_id = :1 ' || l_group2;
5112      l_query := l_query || l_union || l_select3 || l_where3 || ' and hp.site_use_id = :1 ' || l_group3 || ' )' || l_order;
5113   end if;
5114   if p_level = 'CASE' then
5115      l_query := l_select4 || l_where4 || l_group4 ;
5116   end if;
5117   --Begin Bug#5229763 schekuri 27-Jul-2006
5118   --Added following for getting resource for task creation in dunning callback concurrent program
5119   if p_level = 'DUNNING_PARTY' then
5120      l_query := l_select1 || l_where1 || ' and hp.party_id = :1 and hp.cust_account_id = -1 ' ;
5121      l_query := l_query || l_union || '( ' || l_select5 || l_where5 || ' and hp.party_id = :1 and hp.cust_account_id = -1 ' || l_group5;
5122      l_query := l_query || l_union || l_select6 || l_where6 || ' and hp.party_id = :1 and hp.cust_account_id = -1 ' || l_group6 || ' )' || l_order;
5123   end if;
5124   if p_level = 'DUNNING_ACCOUNT' then
5125      l_query := l_select1 || l_where1 || ' and hp.cust_account_id = :1 and hp.site_use_id is null ' ;
5126      l_query := l_query || l_union || '( ' || l_select5 || l_where5 || ' and hp.cust_account_id = :1 and hp.site_use_id is null ' || l_group5;
5127      l_query := l_query || l_union || l_select6 || l_where6 || ' and hp.cust_account_id = :1 and hp.site_use_id is null ' || l_group6 || ' )' || l_order;
5128   end if;
5129   if p_level = 'DUNNING_BILLTO' then
5130      l_query := l_select1 || l_where1 || ' and hp.site_use_id = :1 ' ;
5131      l_query := l_query || l_union || '( ' || l_select5 || l_where5 || ' and hp.site_use_id = :1 ' || l_group5;
5132      l_query := l_query || l_union || l_select6 || l_where6 || ' and hp.site_use_id = :1 ' || l_group6 || ' )' || l_order;
5133   end if;
5134   if p_level = 'DUNNING_PARTY_ACCOUNT' then
5135      l_query := l_select1 || l_where1 || ' and hp.party_id = :1 and hp.cust_account_id <> -1 and hp.site_use_id is null ' ;
5136      l_query := l_query || l_union || '( ' || l_select5 || l_where5 || ' and hp.party_id = :1 and hp.cust_account_id <> -1 and hp.site_use_id is null ' || l_group5;
5137      l_query := l_query || l_union || l_select6 || l_where6 || ' and hp.party_id = :1 and hp.cust_account_id <> -1 and hp.site_use_id is null ' || l_group6 || ' )' || l_order;
5138   end if;
5139   --End Bug#5229763 schekuri 27-Jul-2006
5140 
5141   -- End SQL statements
5142 
5143   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':Parameters: ');
5144   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':p_level: ' || p_level);
5145   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':p_level_id: ' || p_level_id);
5146   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':Data query is: ' || l_query);
5147 
5148   --if p_level = 'PARTY' or p_level = 'ACCOUNT' or p_level = 'BILLTO' then
5149   if p_level <> 'CASE' then              --Modified for Bug#5229763 schekuri 27-Jul-2006
5150      OPEN c_collector FOR l_query USING p_level_id, p_level_id, p_level_id;
5151   else
5152      OPEN c_collector FOR l_query USING p_level_id;
5153   end if;
5154 
5155   LOOP
5156      idx := idx + 1;
5157           -- Begin fix bug #5360791-JYPARK-06/28/2006-Change fetch variable order
5158  	  -- FETCH c_collector INTO x_resource_tab(idx).resource_id,
5159           --                  x_resource_tab(idx).person_id,
5160           --                   l_count;
5161  	  FETCH c_collector INTO x_resource_tab(idx).person_id,
5162                             x_resource_tab(idx).resource_id,
5163                             l_count;
5164           -- End fix bug #5360791-JYPARK-06/28/2006-Change fetch variable order
5165      if c_collector%notfound then
5166 	       exit;
5167      end if;
5168 
5169      iex_debug_pub.logmessage (G_PKG_NAME || '.' || l_api_name || 'idx= ' || idx);
5170      iex_debug_pub.logmessage (G_PKG_NAME || '.' || l_api_name || 'collector_resource_id = ' || x_resource_tab(idx).person_id);
5171   End LOOP;
5172 
5173   CLOSE c_collector;
5174 
5175   -- Standard check of p_commit
5176   IF FND_API.To_Boolean(p_commit) THEN
5177    COMMIT WORK;
5178   END IF;
5179 
5180   -- Standard call to get message count and if count is 1, get message info
5181   FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5182 
5183   iex_debug_pub.logmessage ('**** END get_assigned_collector ************');
5184 
5185   EXCEPTION
5186 	WHEN FND_API.G_EXC_ERROR THEN
5187       ROLLBACK TO get_assigned_collector;
5188 		x_return_status := FND_API.G_RET_STS_ERROR;
5189 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5190 
5191 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
5192       ROLLBACK TO get_assigned_collector;
5193 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5194 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5195 
5196 	WHEN OTHERS THEN
5197       ROLLBACK TO get_assigned_collector;
5198 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5199 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
5200 			FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
5201 		END IF;
5202 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5203 
5204 END get_assigned_collector;
5205 --End bug#5373412 schekuri 10-Jul-2006
5206 
5207 --Start adding for bug 9162623 gnramasa 2nd Dec 09
5208 -- This procedure will return the resource assigned to a customer, account, site
5209 PROCEDURE get_dunning_resource(p_api_version    IN  NUMBER := 1.0,
5210                                p_init_msg_list    IN  VARCHAR2,
5211                                p_commit           IN  VARCHAR2,
5212                                p_validation_level IN  NUMBER,
5213                                p_level            IN  VARCHAR2,
5214                                p_level_id         IN  VARCHAR2,
5215                                x_msg_count        OUT NOCOPY NUMBER,
5216                                x_msg_data         OUT NOCOPY VARCHAR2,
5217                                x_return_status    OUT NOCOPY VARCHAR2,
5218                                x_resource_tab     OUT NOCOPY resource_tab_type) IS
5219 
5220   l_api_version   CONSTANT NUMBER     := p_api_version;
5221   l_api_name CONSTANT VARCHAR2(100)   := 'get_dunning_resource';
5222   l_init_msg_list CONSTANT VARCHAR2(1):= p_init_msg_list;
5223   l_return_status VARCHAR2(1);
5224   l_msg_count NUMBER;
5225   l_msg_data VARCHAR2(32767);
5226   idx NUMBER := 0;
5227   l_count NUMBER := 0;
5228 
5229   l_select1 VARCHAR2(3000);
5230   l_select2 VARCHAR2(3000);
5231 
5232   l_where1 VARCHAR2(3000);
5233   l_where2 VARCHAR2(3000);
5234 
5235   l_union VARCHAR2(3000) := ' UNION ALL ';
5236 
5237   l_query VARCHAR2(32767);
5238 
5239   TYPE c_cur_type IS REF CURSOR;
5240   c_collector c_cur_type;
5241 
5242 BEGIN
5243 
5244   iex_debug_pub.logmessage ('**** BEGIN get_dunning_resource ************');
5245 
5246 
5247   SAVEPOINT	get_dunning_resource;
5248 
5249   -- Standard call to check for call compatibility.
5250   IF NOT FND_API.Compatible_API_Call (l_api_version,
5251                                       p_api_version,
5252                                       l_api_name,
5253                                       G_PKG_NAME)    THEN
5254 	RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5255   END IF;
5256 
5257   -- Check p_init_msg_list
5258   IF FND_API.to_Boolean( p_init_msg_list ) THEN
5259     FND_MSG_PUB.initialize;
5260   END IF;
5261 
5262   x_return_status := FND_API.G_RET_STS_SUCCESS;
5263 
5264   -- Initialize SQL statements - REMEMBER CHANGING 1 MEANS CHANGING ALL
5265   l_select1 :=              'SELECT ac.employee_id, ac.resource_id ';
5266   l_select1 := l_select1 || 'FROM  hz_customer_profiles hp, ar_collectors ac,jtf_rs_resource_extns rs ';
5267   l_where1  :=              'WHERE ';
5268   l_where1  := l_where1  || '      hp.collector_id  = ac.collector_id ';
5269   l_where1  := l_where1  || '  and ac.resource_type = ''RS_RESOURCE'' ';
5270   l_where1  := l_where1  || '  and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate) ';
5271   l_where1  := l_where1  || '  and nvl(ac.status,''A'') = ''A'' ';
5272   l_where1  := l_where1  || '  and nvl(hp.status,''A'') = ''A'' ';
5273   l_where1  := l_where1  || '  and ac.resource_id = rs.resource_id ';
5274   l_where1  := l_where1  || '  and trunc(nvl(rs.end_date_active,sysdate)) >= trunc(sysdate) ';
5275 
5276   l_select2 :=              'SELECT ac.employee_id, rs.resource_id ';
5277   l_select2 := l_select2 || 'FROM  hz_customer_profiles hp, ar_collectors ac,jtf_rs_resource_extns rs ';
5278   l_where2  :=              'WHERE ';
5279   l_where2  := l_where2  || '      hp.collector_id  = ac.collector_id ';
5280   l_where2  := l_where2  || '  and ac.resource_type = ''RS_GROUP'' ';
5281   l_where2  := l_where2  || '  and trunc(nvl(ac.inactive_date,sysdate)) >= trunc(sysdate) ';
5282   l_where2  := l_where2  || '  and nvl(ac.status,''A'') = ''A'' ';
5283   l_where2  := l_where2  || '  and nvl(hp.status,''A'') = ''A'' ';
5284   l_where2  := l_where2  || '  and ac.employee_id = rs.source_id ';
5285   l_where2  := l_where2  || '  and trunc(nvl(rs.end_date_active,sysdate)) >= trunc(sysdate) ';
5286 
5287   if p_level = 'DUNNING_PARTY' then
5288      l_query := l_select1 || l_where1 || ' and hp.party_id = :1 and hp.cust_account_id = -1 ' ;
5289      l_query := l_query || l_union || l_select2 || l_where2 || ' and hp.party_id = :1 and hp.cust_account_id = -1 ';
5290   end if;
5291   if p_level = 'DUNNING_ACCOUNT' then
5292      l_query := l_select1 || l_where1 || ' and hp.cust_account_id = :1 and hp.site_use_id is null ' ;
5293      l_query := l_query || l_union || l_select2 || l_where2 || ' and hp.cust_account_id = :1 and hp.site_use_id is null ' ;
5294   end if;
5295   if p_level = 'DUNNING_BILLTO' then
5296      l_query := l_select1 || l_where1 || ' and hp.site_use_id = :1 ' ;
5297      l_query := l_query || l_union || l_select2 || l_where2 || ' and hp.site_use_id = :1 ' ;
5298   end if;
5299   if p_level = 'DUNNING_PARTY_ACCOUNT' then
5300      l_query := l_select1 || l_where1 || ' and hp.party_id = :1 and hp.cust_account_id <> -1 and hp.site_use_id is null ' ;
5301      l_query := l_query || l_union || l_select2 || l_where2 || ' and hp.party_id = :1 and hp.cust_account_id <> -1 and hp.site_use_id is null ' ;
5302   end if;
5303 
5304   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':Parameters: ');
5305   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':p_level: ' || p_level);
5306   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':p_level_id: ' || p_level_id);
5307   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':Data query is: ' || l_query);
5308 
5309   OPEN c_collector FOR l_query USING p_level_id, p_level_id;
5310 
5311   LOOP
5312      idx := idx + 1;
5313  	  FETCH c_collector INTO x_resource_tab(idx).person_id,
5314                             x_resource_tab(idx).resource_id;
5315      if c_collector%notfound then
5316 	       exit;
5317      end if;
5318 
5319      iex_debug_pub.logmessage (G_PKG_NAME || '.' || l_api_name || 'idx= ' || idx);
5320      iex_debug_pub.logmessage (G_PKG_NAME || '.' || l_api_name || 'collector_resource_id = ' || x_resource_tab(idx).person_id);
5321   End LOOP;
5322 
5323   CLOSE c_collector;
5324 
5325   -- Standard check of p_commit
5326   IF FND_API.To_Boolean(p_commit) THEN
5327    COMMIT WORK;
5328   END IF;
5329 
5330   -- Standard call to get message count and if count is 1, get message info
5331   FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5332 
5333   iex_debug_pub.logmessage ('**** END get_dunning_resource ************');
5334 
5335   EXCEPTION
5336 	WHEN FND_API.G_EXC_ERROR THEN
5337       ROLLBACK TO get_dunning_resource;
5338 		x_return_status := FND_API.G_RET_STS_ERROR;
5339 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5340 
5341 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
5342       ROLLBACK TO get_dunning_resource;
5343 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5344 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5345 
5346 	WHEN OTHERS THEN
5347       ROLLBACK TO get_dunning_resource;
5348 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5349 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
5350 			FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
5351 		END IF;
5352 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5353 
5354 END get_dunning_resource;
5355 --End adding for bug 9162623 gnramasa 2nd Dec 09
5356 
5357 --Start adding for staged dunning gnramasa 7th Dec 09
5358 -- This procedure will return the grace days of a customer, account, site
5359 PROCEDURE get_grace_days (p_api_version    IN  NUMBER := 1.0,
5360                                p_init_msg_list    IN  VARCHAR2,
5361                                p_commit           IN  VARCHAR2,
5362                                p_validation_level IN  NUMBER,
5363                                p_level            IN  VARCHAR2,
5364 			       p_party_id         IN  NUMBER,
5365 			       p_account_id       IN  NUMBER,
5366 			       p_site_use_id      IN  NUMBER,
5367                                x_msg_count        OUT NOCOPY NUMBER,
5368                                x_msg_data         OUT NOCOPY VARCHAR2,
5369                                x_return_status    OUT NOCOPY VARCHAR2,
5370                                x_grace_days       OUT NOCOPY NUMBER) IS
5371 
5372   l_api_version   CONSTANT NUMBER     := p_api_version;
5373   l_api_name CONSTANT VARCHAR2(100)   := 'get_grace_days';
5374   l_init_msg_list CONSTANT VARCHAR2(1):= p_init_msg_list;
5375   l_return_status VARCHAR2(1);
5376   l_msg_count NUMBER;
5377   l_msg_data VARCHAR2(32767);
5378 
5379   cursor c_gracedays_party_level (p_party_id number) is
5380   select nvl(payment_grace_days ,0)
5381   from hz_customer_profiles
5382   where party_id = p_party_id
5383   and cust_account_id = -1;
5384 
5385   cursor c_gracedays_acc_level (p_party_id number, p_cust_acct_id number) is
5386   select nvl(payment_grace_days ,0)
5387   from hz_customer_profiles
5388   where party_id = p_party_id
5389   and cust_account_id = p_cust_acct_id
5390   and site_use_id is null;
5391 
5392   cursor c_gracedays_billto_level (p_party_id number, p_cust_acct_id number, p_site_use_id number) is
5393   select nvl(payment_grace_days ,0)
5394   from hz_customer_profiles
5395   where party_id = p_party_id
5396   and cust_account_id = p_cust_acct_id
5397   and site_use_id = p_site_use_id;
5398 
5399   l_grace_days	number := 0;
5400 
5401 BEGIN
5402 
5403   iex_debug_pub.logmessage ('**** BEGIN get_grace_days ************');
5404 
5405 
5406   SAVEPOINT	get_grace_days;
5407 
5408   -- Standard call to check for call compatibility.
5409   IF NOT FND_API.Compatible_API_Call (l_api_version,
5410                                       p_api_version,
5411                                       l_api_name,
5412                                       G_PKG_NAME)    THEN
5413 	RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5414   END IF;
5415 
5416   -- Check p_init_msg_list
5417   IF FND_API.to_Boolean( p_init_msg_list ) THEN
5418     FND_MSG_PUB.initialize;
5419   END IF;
5420 
5421   x_return_status := FND_API.G_RET_STS_SUCCESS;
5422 
5423   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':Parameters: ');
5424   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':p_level: ' || p_level);
5425   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':p_party_id: ' || p_party_id);
5426   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':p_account_id: ' || p_account_id);
5427   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':p_site_use_id: ' || p_site_use_id);
5428 
5429   if p_level = 'PARTY' then
5430      open c_gracedays_party_level (p_party_id);
5431      fetch c_gracedays_party_level into l_grace_days;
5432      close c_gracedays_party_level;
5433   end if;
5434   if p_level = 'ACCOUNT' then
5435      open c_gracedays_acc_level (p_party_id, p_account_id);
5436      fetch c_gracedays_acc_level into l_grace_days;
5437      close c_gracedays_acc_level;
5438   end if;
5439   if p_level = 'BILL_TO' then
5440      open c_gracedays_billto_level (p_party_id, p_account_id, p_site_use_id);
5441      fetch c_gracedays_billto_level into l_grace_days;
5442      close c_gracedays_billto_level;
5443   end if;
5444   iex_debug_pub.LogMessage(G_PKG_NAME || '.' || l_api_name || ':l_grace_days: ' || l_grace_days);
5445 
5446   x_grace_days	:= l_grace_days;
5447 
5448   -- Standard check of p_commit
5449   IF FND_API.To_Boolean(p_commit) THEN
5450    COMMIT WORK;
5451   END IF;
5452 
5453   -- Standard call to get message count and if count is 1, get message info
5454   FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5455 
5456   iex_debug_pub.logmessage ('**** END get_grace_days ************');
5457 
5458   EXCEPTION
5459 	WHEN FND_API.G_EXC_ERROR THEN
5460       ROLLBACK TO get_grace_days;
5461 		x_return_status := FND_API.G_RET_STS_ERROR;
5462 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5463 
5464 	WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
5465       ROLLBACK TO get_grace_days;
5466 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5467 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5468 
5469 	WHEN OTHERS THEN
5470       ROLLBACK TO get_grace_days;
5471 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5472 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
5473 			FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME, l_api_name);
5474 		END IF;
5475 		FND_MSG_PUB.Count_And_Get(p_count => x_msg_count, p_data => x_msg_data);
5476 
5477 END get_grace_days;
5478 --End adding for staged dunning gnramasa 7th Dec 09
5479 
5480 --Begin bug 6723556 gnramasa 11th Jan 08
5481 --If all the tranactions that belong to a contract has a status not equal to CURRENT or CLOSE
5482 --then return contract status as DELINQUENT else return as CURRENT
5483 
5484 FUNCTION CheckContractStatus
5485 (
5486   p_contract_number    IN  VARCHAR2
5487 )
5488 return varchar2 is
5489 l_contract_status  VARCHAR2(10) := 'CURRENT';
5490 l_count            NUMBER := 0;
5491 BEGIN
5492 iex_debug_pub.logmessage ('Start CheckContractStatus');
5493 iex_debug_pub.logmessage ('p_contract_number :' || p_contract_number);
5494 
5495 IF p_contract_number IS NOT NULL then
5496 	select count(1) into l_count
5497 	from iex_delinquencies_all del,ra_customer_trx_lines_all trl
5498         where del.TRANSACTION_ID = trl.CUSTOMER_TRX_ID
5499           and del.status not in ('CURRENT', 'CLOSE')
5500           and trl.INTERFACE_LINE_CONTEXT = 'OKL_CONTRACTS'
5501           and trl.INTERFACE_LINE_ATTRIBUTE6 = p_contract_number;
5502 
5503 	if l_count >1 then
5504 		l_contract_status := 'DELINQUENT';
5505 	else
5506 		l_contract_status := 'CURRENT';
5507 	end if;
5508 END IF;
5509 iex_debug_pub.logmessage ('CheckContractStatus : l_contract_status :' || l_contract_status);
5510 iex_debug_pub.logmessage ('End CheckContractStatus');
5511 return l_contract_status;
5512 EXCEPTION
5513  WHEN OTHERS THEN
5514     iex_debug_pub.logmessage ('CheckContractStatus: In other exception');
5515     iex_debug_pub.logmessage ('CheckContractStatus : l_contract_status :' || l_contract_status);
5516     return l_contract_status;
5517 END;
5518 --End bug 6723556 gnramasa 11th Jan 08
5519 
5520 --Begin bug 6627832 gnramasa 21st Jan 08
5521 FUNCTION ValidateXMLRequestId
5522 (
5523   p_xml_request_id    IN  number
5524 ) return boolean is
5525 l_req_count number;
5526 begin
5527       select count(1)
5528       into l_req_count
5529       from iex_xml_request_histories
5530       where xml_request_id=p_xml_request_id
5531       and length(document)>0;
5532       if l_req_count>0 then
5533       return true;
5534       else
5535       return false;
5536       end if;
5537 exception
5538 when others then
5539 return false;
5540 end;
5541 --End bug 6627832 gnramasa 21st Jan 08
5542 
5543 --Begin bug 6717279 by gnramasa 25th Aug 08
5544 -- this function will copy the value to pl/sql table.
5545 Procedure copy_cust_acct_value
5546  (
5547    p_fe_cust_acct_rec IN DBMS_SQL.NUMBER_TABLE
5548  ) is
5549 	l_count   number;
5550 begin
5551 	iex_debug_pub.logmessage ('Begin copy_cust_acct_value');
5552 	l_count := p_fe_cust_acct_rec.count;
5553 	iex_debug_pub.logmessage ('copy_cust_acct_value, l_count: ' || l_count);
5554 	p_be_cust_acct_rec.delete;
5555 	for i in 1..l_count loop
5556 		p_be_cust_acct_rec(i) := p_fe_cust_acct_rec(i);
5557 		iex_debug_pub.logmessage ('p_be_cust_acct_rec('||i||') : ' || p_be_cust_acct_rec(i));
5558 	end loop;
5559 	iex_debug_pub.logmessage ('End copy_cust_acct_value');
5560 End copy_cust_acct_value;
5561 
5562 --this function accepts cust_account_id. If this value exists in the pl/sql table
5563 --then it will return 'Y', else 'N'
5564 FUNCTION cust_acct_id_check
5565 (
5566   p_cust_acct_id    IN  number
5567 )
5568 	return varchar is
5569 	l_count   number;
5570 begin
5571 	iex_debug_pub.logmessage ('Begin cust_acct_id_check');
5572 	iex_debug_pub.logmessage ('cust_acct_id_check, p_cust_acct_id: ' || p_cust_acct_id);
5573 	l_count := p_be_cust_acct_rec.count;
5574 	iex_debug_pub.logmessage ('cust_acct_id_check, l_count: ' || l_count);
5575 	for i in 1..l_count loop
5576 		if p_be_cust_acct_rec(i) = p_cust_acct_id then
5577 			iex_debug_pub.logmessage ('cust_acct_id_check, value exists in pl/sql table, so returning Y');
5578 			return 'Y';  -- value exists in pl/sql table, so return 'Y'
5579 		end if;
5580 	end loop;
5581 	iex_debug_pub.logmessage ('End cust_acct_id_check');
5582 	iex_debug_pub.logmessage ('cust_acct_id_check, value doesn''t exists in pl/sql table, so returning N');
5583 	return 'N'; -- value doesn't exists in pl/sql table, so return 'N'
5584 End cust_acct_id_check;
5585 --End bug 6717279 by gnramasa 25th Aug 08
5586 
5587 --Begin bug#6717849 by schekuri 27-Jul-2009
5588 --Created for multi level strategy enhancement
5589 
5590 FUNCTION VALIDATE_RUNNING_LEVEL
5591 (
5592       p_running_level IN  varchar2
5593 )
5594 return varchar2 is
5595 l_return_value VARCHAR2(1);
5596 begin
5597 	select nvl(decode(P_RUNNING_LEVEL,'CUSTOMER',USING_CUSTOMER_LEVEL,
5598 	                                'ACCOUNT',USING_ACCOUNT_LEVEL,
5599 					'BILL_TO',USING_BILLTO_LEVEL,
5600 					'DELINQUENCY',USING_DELINQUENCY_LEVEL,'N'),'N')
5601 	INTO l_return_value
5602 	from IEX_QUESTIONNAIRE_ITEMS;
5603 
5604 	return l_return_value;
5605 
5606 end;
5607 
5608 FUNCTION GET_PARTY_RUNNING_LEVEL
5609 (
5610       p_party_id IN  NUMBER,
5611       p_org_id IN NUMBER DEFAULT NULL
5612 )
5613 return varchar2 is
5614 	cursor c_party_bus_level(p_party_id number) is
5615 	select value_varchar2 from hz_party_preferences
5616 	where module = 'COLLECTIONS'
5617 	and category='COLLECTIONS LEVEL'
5618 	and preference_code='PARTY_ID'
5619 	and party_id=p_party_id;
5620 
5621         cursor c_ou_bus_level(p_org_id number) is
5622 	select preference_value
5623 	from iex_app_preferences_b
5624 	where preference_name='COLLECTIONS STRATEGY LEVEL'
5625 	and org_id is not null
5626 	and org_id=p_org_id
5627 	and enabled_flag='Y';
5628 
5629         cursor c_system_bus_level is
5630 	select preference_value
5631 	from iex_app_preferences_b
5632 	where preference_name='COLLECTIONS STRATEGY LEVEL'
5633 	and org_id is null
5634 	and enabled_flag='Y';
5635 
5636 	l_running_level varchar2(20);
5637 	l_using_party_business_level varchar2(1);
5638 	l_using_ou_business_level varchar2(1);
5639 
5640 
5641 	cursor c_questionnaire is
5642 	select DEFINE_PARTY_RUNNING_LEVEL,
5643 	       DEFINE_OU_RUNNING_LEVEL
5644 	from IEX_QUESTIONNAIRE_ITEMS;
5645 
5646 	cursor c_unique_ous(p_partyid number) is
5647 	select distinct org_id
5648 	from iex_delinquencies_all
5649 	where status in ('DELINQUENT','PREDELINQUENT')
5650 	and party_cust_id=p_partyid;
5651 
5652 	l_org_id number;
5653 
5654 
5655 
5656 begin
5657 
5658         open c_questionnaire;
5659 	fetch c_questionnaire into l_using_party_business_level,l_using_ou_business_level;
5660 	close c_questionnaire;
5661 
5662 	if l_using_party_business_level='Y' then
5663 
5664 	if p_party_id is not null then
5665 		open c_party_bus_level(p_party_id);
5666 		fetch c_party_bus_level into l_running_level;
5667 		close c_party_bus_level;
5668 		if l_running_level is not null then
5669 			return l_running_level;
5670 		end if;
5671 	end if;
5672 
5673 	end if;
5674 
5675 	if l_using_ou_business_level='Y' then
5676 
5677 	if p_org_id is not null then
5678 		open c_ou_bus_level(p_org_id);
5679 		fetch c_ou_bus_level into l_running_level;
5680 		close c_ou_bus_level;
5681 		if l_running_level is not null then
5682 			return l_running_level;
5683 		end if;
5684 	else
5685 	if p_party_id is not null then
5686 
5687 		open c_unique_ous(p_party_id);
5688 		loop
5689 			fetch c_unique_ous into l_org_id;
5690 			if c_unique_ous%rowcount>1 then
5691 				l_org_id:=null;
5692 				exit;
5693 			end if;
5694 			exit when c_unique_ous%notfound;
5695 		end loop;
5696 		close c_unique_ous;
5697 
5698 		if l_org_id is not null then
5699 			open c_ou_bus_level(p_org_id);
5700 			fetch c_ou_bus_level into l_running_level;
5701 			close c_ou_bus_level;
5702 			if l_running_level is not null then
5703 				return l_running_level;
5704 			end if;
5705 		end if;
5706 
5707 	end if;
5708 
5709 	end if;
5710 
5711 	end if;
5712 
5713 	open c_system_bus_level;
5714 	fetch c_system_bus_level into l_running_level;
5715 	close c_system_bus_level;
5716 
5717 	return l_running_level;
5718 
5719 
5720 end;
5721 --End bug#6717849 by schekuri 27-Jul-2009
5722 -- added for bug 13594457 by sunagesh on 23-jan-2012
5723 FUNCTION REPLACE_SPECIAL_CHARS(P_XML_DATA IN VARCHAR2)
5724 RETURN VARCHAR2
5725  IS
5726 
5727     l_api_name              CONSTANT VARCHAR2(30) := 'REPLACE_SPECIAL_CHARS';
5728     l_xml    VARCHAR2(32767);
5729 
5730  BEGIN
5731     iex_debug_pub.logmessage('Started '||G_PKG_NAME || '.' || l_api_name || ' +');
5732     l_xml := REPLACE(P_XML_DATA,'&','&');
5733     l_xml := REPLACE(l_xml,'&amp;','&');
5734     RETURN l_xml;
5735 
5736  EXCEPTION
5737     WHEN OTHERS THEN
5738        iex_debug_pub.logmessage('Eror in '||G_PKG_NAME || '.' || l_api_name|| ' -');
5739        RAISE;
5740  END REPLACE_SPECIAL_CHARS;
5741  -- end bug 13594457 by sunagesh on 23-jan-2012
5742 
5743 Function get_BR_BillTOID (p_id in number)return number is
5744 
5745       cursor c_code(p_site_use_id number) is
5746         select site_use_code from hz_cust_site_uses where site_use_id = p_site_use_id;
5747 
5748       cursor c_id(p_site_use_id number) is
5749         select site_use_id from hz_cust_site_uses where site_use_code = 'BILL_TO'
5750             and cust_acct_site_id = (select cs.cust_acct_site_id from hz_cust_site_uses cs where cs.site_use_id =  p_site_use_id)
5751             and status = 'A';
5752 
5753       x_id number;
5754       x_code varchar2(30);
5755 
5756     Begin
5757        x_id := p_id;
5758 
5759        open c_code(p_id);
5760        fetch c_code into x_code;
5761        close c_code;
5762 
5763        if x_code = 'DRAWEE' then
5764           open c_id(p_id);
5765           fetch c_id into x_id;
5766           close c_id;
5767        end if;
5768 
5769        return x_id;
5770 
5771      exception
5772         when others then return x_id;
5773 End  get_BR_BillTOID;
5774 
5775 Function get_BR_DrweeSiteID (p_id in number)return number is
5776 
5777     cursor c_id(p_site_use_id number) is
5778         select site_use_id from hz_cust_site_uses where site_use_code = 'DRAWEE'
5779             and cust_acct_site_id = (select cs.cust_acct_site_id from hz_cust_site_uses cs where cs.site_use_id =  p_site_use_id)
5780             and status = 'A';
5781 
5782       x_id number;
5783       x_code varchar2(30);
5784 
5785     Begin
5786       x_id := p_id;
5787 
5788       open c_id(p_id);
5789       fetch c_id into x_id;
5790       close c_id;
5791 
5792       return x_id;
5793 
5794      exception
5795         when others then return x_id;
5796 End get_BR_DrweeSiteID;
5797 
5798 BEGIN
5799   G_APPL_ID := FND_GLOBAL.Prog_Appl_Id;
5800   G_LOGIN_ID      := FND_GLOBAL.Conc_Login_Id;
5801   G_PROGRAM_ID    := FND_GLOBAL.Conc_Program_Id;
5802   G_USER_ID       := FND_GLOBAL.User_Id;
5803   G_REQUEST_ID    := FND_GLOBAL.Conc_Request_Id;
5804 
5805   PG_DEBUG  := TO_NUMBER(NVL(FND_PROFILE.value('IEX_DEBUG_LEVEL'), '20'));
5806 
5807 END IEX_UTILITIES;