DBA Data[Home] [Help]

PACKAGE BODY: APPS.IEX_DUNNING_PVT

Source


1 PACKAGE BODY IEX_DUNNING_PVT AS
2     /* $Header: iexvdunb.pls 120.110.12020000.25 2013/02/21 12:55:35 sunagesh ship $ */
3 
4     G_PKG_NAME  CONSTANT VARCHAR2(30):= 'IEX_DUNNING_PVT';
5     G_FILE_NAME CONSTANT VARCHAR2(12) := 'iexvdunb.pls';
6 
7     PG_DEBUG NUMBER ;
8 
9     --Start adding for bug 9503251 gnramasa 2nd Apr 2010
10     FUNCTION staged_dunn_amt_due_remaining(p_dunning_id number) RETURN NUMBER;
11     --End adding for bug 9503251 gnramasa 2nd Apr 2010
12 
13     Procedure WriteLog      (  p_msg                     IN VARCHAR2           ,
14                                p_flag                    IN NUMBER DEFAULT NULL)
15     IS
16     BEGIN
17 
18          IF (FND_LOG.LEVEL_EVENT >= PG_DEBUG) THEN
19             iex_debug_pub.LogMessage (p_msg);
20          END IF;
21 
22     END WriteLog;
23 
24     /*
25         Returns location_id from hz_locations for specified site_use_id
26     */
27     FUNCTION GET_DUNNING_LOCATION(P_SITE_USE_ID NUMBER) RETURN NUMBER
28     IS
29     /*-----------------------------------------------------------------------+
30      | Local Variable Declarations and initializations                       |
31      +-----------------------------------------------------------------------*/
32         l_api_name          CONSTANT VARCHAR2(30) := 'GET_DUNNING_LOCATION';
33         l_return            NUMBER;
34 
35     /*-----------------------------------------------------------------------+
36      | Cursor Declarations                                                   |
37      +-----------------------------------------------------------------------*/
38         cursor get_data_crs(P_SITE_USE_ID number) is
39             select par_site.location_id
40             from
41                 HZ_CUST_SITE_USES_ALL site_use,
42                 HZ_CUST_ACCT_SITES_ALL acct_site,
43                 hz_party_sites par_site
44             where
45                 site_use.site_use_id = P_SITE_USE_ID and
46                 acct_site.cust_acct_site_id = site_use.cust_acct_site_id and
47                 par_site.party_site_id = acct_site.party_site_id;
48 
49     BEGIN
50 
51         l_return := null;
52 
53         WriteLog(l_api_name || ' input parameters:');
54         WriteLog('P_SITE_USE_ID: ' || P_SITE_USE_ID);
55 
56         if P_SITE_USE_ID is null then
57             WriteLog('Not all input parameters have value');
58             return l_return;
59         end if;
60 
61         OPEN get_data_crs(P_SITE_USE_ID);
62         FETCH get_data_crs INTO l_return;
63         CLOSE get_data_crs;
64 
65         WriteLog(l_api_name || ' returns ' || l_return);
66         return l_return;
67 
68     EXCEPTION
69         WHEN OTHERS THEN
70             WriteLog (l_api_name || ': In exception');
71             return l_return;
72     END;
73 
74     /*
75         Returns CUSTOMER location_id, contact party_id and contact_pont_id for specified party_id and contact_point_type the OLD WAY
76     */
77     Procedure GET_CUST_DUNNING_DATA_OW(p_api_version             IN NUMBER := 1.0,
78                                     p_init_msg_list           IN VARCHAR2 ,
79                                     p_commit                  IN VARCHAR2 ,
80                                     P_PARTY_ID                IN NUMBER,
81                                     P_CONTACT_POINT_TYPE      IN VARCHAR2,
82                                     X_LOCATION_ID             OUT NOCOPY NUMBER,
83                                     X_CONTACT_ID              OUT NOCOPY NUMBER,
84                                     X_CONTACT_POINT_ID        OUT NOCOPY NUMBER,
85                                     x_return_status           OUT NOCOPY VARCHAR2,
86                                     x_msg_count               OUT NOCOPY NUMBER,
87                                     x_msg_data                OUT NOCOPY VARCHAR2)
88     IS
89     /*-----------------------------------------------------------------------+
90      | Local Variable Declarations and initializations                       |
91      +-----------------------------------------------------------------------*/
92         l_api_name                  CONSTANT VARCHAR2(30) := 'GET_CUST_DUNNING_DATA_OW';
93         l_primary_flag              VARCHAR2(1);
94         l_purpose_flag              varchar2(1);
95         l_rel_party_id              NUMBER;
96         l_contact_id                NUMBER;
97         l_contact_point_id          NUMBER;
98         l_location_id               NUMBER;
99         l_order                     NUMBER;
100         l_rel_type                  VARCHAR2(30);
101         l_def_rel_type              VARCHAR2(30);
102 
103     /*-----------------------------------------------------------------------+
104      | Cursor Declarations                                                   |
105      +-----------------------------------------------------------------------*/
106 
107         -- get contact_id and contact_point_id
108         cursor get_old_contact_crs(P_REL_TYPE varchar2, P_PARTY_ID number, P_CONTACT_POINT_TYPE varchar2) is
109             select
110                 decode(P_REL_TYPE, rel.relationship_type,
111                         decode(point.contact_point_purpose,
112                           'DUNNING', decode(point.primary_by_purpose, 'Y', 1, decode(point.primary_flag, 'Y', 2, 3
113                                                                               )
114                                      ), 4
115                         ),
116                         decode(point.contact_point_purpose,
117                           'DUNNING', decode(point.primary_by_purpose, 'Y', 5, decode(point.primary_flag, 'Y', 6, 7
118                                                                               )
119                                      ), 8
120                         )
121                 ) Display_Order,
122                 rel.party_id,
123                 rel.subject_id,
124                 point.contact_point_id,
125                 rel.relationship_type
126             from HZ_RELATIONSHIPS rel,
127                 hz_contact_points point
128             where rel.object_id = P_PARTY_ID and
129                 rel.relationship_type in ('DUNNING', 'COLLECTIONS') and
130                 rel.status = 'A' and
131                 rel.party_id = point.owner_table_ID and
132                 point.owner_table_name = 'HZ_PARTIES' and
133                 upper(point.contact_point_type) = decode(P_CONTACT_POINT_TYPE, 'EMAIL', 'EMAIL', 'PHONE', 'PHONE', 'FAX', 'PHONE') and
134                 nvl(point.phone_line_type, 'EMAIL') = decode(P_CONTACT_POINT_TYPE, 'EMAIL', 'EMAIL', 'PHONE', 'GEN', 'FAX', 'FAX') and
135                 NVL(point.do_not_use_flag, 'N') = 'N' and
136                 (point.status = 'A' OR point.status <> 'I')
137             order by Display_Order;
138 
139         -- get contact_id
140         cursor get_old_contact_crs1(P_REL_TYPE varchar2, P_PARTY_ID number) is
141             select
142                 decode(P_REL_TYPE, rel.relationship_type, 1, 2) Display_Order,
143                 rel.party_id,
144                 rel.subject_id,
145                 rel.relationship_type
146             from HZ_RELATIONSHIPS rel
147             where rel.object_id = P_PARTY_ID and
148                 rel.relationship_type in ('DUNNING', 'COLLECTIONS') and
149                 rel.status = 'A'
150             order by Display_Order;
151 
152         -- get relationship location_id
153         cursor get_old_loc_crs(P_REL_PARTY_ID number) is
154             select location_id
155             from hz_party_sites
156             where party_id = P_REL_PARTY_ID and
157                 status in ('A', 'I');
158 
159         --start for bug 6500750 gnramasa 13-Nov-07
160         cursor get_site_loc(P_CONTACT_ID number) is
161             select location_id
162         --Start for bug 8771065 gnramasa 6th-Aug-09
163         --    from ast_locations_v where party_site_id =
164             from ast_locations_v where party_site_id in
165             	(select party_site_id
166         --		from hz_cust_acct_sites_all where cust_acct_site_id =
167     		from hz_cust_acct_sites_all where cust_acct_site_id in
168                           (select address_id
169                            from ar_contacts_v where contact_party_id = P_CONTACT_ID
170     		       AND address_id is not null
171     		       AND status = 'A'));
172          --End for bug 8771065 gnramasa 6th-Aug-09
173          --End for bug 6500750 gnramasa 13-Nov-07
174 
175         -- get organization location_id
176         cursor get_old_loc_crs1(P_ORG_PARTY_ID number) is
177             select location_id
178             from ast_locations_v
179             where party_id = P_ORG_PARTY_ID and
180                 primary_flag = 'Y';
181 
182     BEGIN
183 
184         IF FND_API.to_Boolean( p_init_msg_list )
185         THEN
186             FND_MSG_PUB.initialize;
187         END IF;
188 
189         x_return_status := FND_API.G_RET_STS_SUCCESS;
190 
191         WriteLog('----------' || l_api_name || '----------');
192         WriteLog(l_api_name || ': input parameters:');
193         WriteLog(l_api_name || ': P_PARTY_ID: ' || P_PARTY_ID);
194         WriteLog(l_api_name || ': P_CONTACT_POINT_TYPE: ' || P_CONTACT_POINT_TYPE);
195 
196         X_LOCATION_ID := null;
197         X_CONTACT_ID := null;
198         X_CONTACT_POINT_ID := null;
199 
200         -- verify input parameters and if they are not set return immediately
201         if P_PARTY_ID is null or P_CONTACT_POINT_TYPE is null then
202             WriteLog(l_api_name || ': Not all input parameters have value');
203             return;
204         end if;
205 
206         WriteLog(l_api_name || ': Searching location_id, contact_id and contact_point_id the old way...');
207 
208         l_def_rel_type := nvl(fnd_profile.value('IEX_DEF_CORRESP_REL_TYPE'), 'DUNNING');
209         WriteLog(l_api_name || ': IEX_DEF_CORRESP_REL_TYPE profile value: ' || l_def_rel_type);
210 
211         if P_CONTACT_POINT_TYPE = 'PRINTER' then
212 
213             WriteLog(l_api_name || ': For printer searching for contact only...');
214 
215             -- try to get contact_id the old way
216             OPEN get_old_contact_crs1(l_def_rel_type, P_PARTY_ID);
217             fetch get_old_contact_crs1 into l_order,
218                                     l_rel_party_id,
219                                     l_contact_id,
220                                     l_rel_type;
221             CLOSE get_old_contact_crs1;
222 
223             if l_rel_party_id is not null then
224                 WriteLog(l_api_name || ': Found ' || l_rel_type || ' contact:');
225                 WriteLog(l_api_name || ': l_rel_party_id: ' || l_rel_party_id);
226                 WriteLog(l_api_name || ': l_contact_id: ' || l_contact_id);
227             else
228                 WriteLog(l_api_name || ': No contact found');
229             end if;
230 
231         ELSE
232 
233             -- try to get contact_id and contact_point_id the old way
234             OPEN get_old_contact_crs(l_def_rel_type, P_PARTY_ID, P_CONTACT_POINT_TYPE);
235             fetch get_old_contact_crs into l_order,
236                                     l_rel_party_id,
237                                     l_contact_id,
238                                     l_contact_point_id,
239                                     l_rel_type;
240             CLOSE get_old_contact_crs;
241 
242             if l_rel_party_id is not null then
243               WriteLog(l_api_name || ': Found ' || l_rel_type || ' contact with ' || P_CONTACT_POINT_TYPE || ' contact point:');
244               WriteLog(l_api_name || ': l_rel_party_id: ' || l_rel_party_id);
245               WriteLog(l_api_name || ': l_contact_id: ' || l_contact_id);
246               WriteLog(l_api_name || ': l_contact_point_id: ' || l_contact_point_id);
247             else
248                 WriteLog(l_api_name || ': No contact and contact point found');
249             end if;
250 
251         END IF;
252 
253         if l_rel_party_id is not null then
254 
255             WriteLog(l_api_name || ': Searching for relationship location...');
256 
257             -- get relationship location_id
258             OPEN get_old_loc_crs(l_rel_party_id);
259             fetch get_old_loc_crs into l_location_id;
260             CLOSE get_old_loc_crs;
261 
262             if l_location_id is not null then
263                 WriteLog(l_api_name || ': Found relationship location: ' || l_location_id);
264             else
265                 WriteLog(l_api_name || ': No relationship location found');
266 
267     	    --start for bug 6500750 gnramasa 13-Nov-07
268     	    OPEN get_site_loc(l_contact_id);
269                 fetch get_site_loc into l_location_id;
270                 CLOSE get_site_loc;
271     		if l_location_id is not null then
272                         WriteLog(l_api_name || ': Found contact site location: ' || l_location_id);
273     		else
274                         WriteLog(l_api_name || ': No contact site location found');
275     	    --End for bug 6500750 gnramasa 13-Nov-07
276 
277     		    WriteLog(l_api_name || ': Searching for organization location...');
278 
279     		    -- get relationship location_id
280     		    OPEN get_old_loc_crs1(P_PARTY_ID);
281     		    fetch get_old_loc_crs1 into l_location_id;
282     		    CLOSE get_old_loc_crs1;
283 
284     		    if l_location_id is not null then
285     			WriteLog(l_api_name || ': Found organization location: ' || l_location_id);
286     		    else
287     			WriteLog(l_api_name || ': No organization location found');
288     		    end if;
289     		end if;
290 
291             end if;
292 
293         end if;
294 
295         X_LOCATION_ID := l_location_id;
296         X_CONTACT_ID := l_contact_id;
297         X_CONTACT_POINT_ID := l_contact_point_id;
298 
299         WriteLog(l_api_name || ': X_LOCATION_ID = ' || X_LOCATION_ID);
300         WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
301         WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
302 
303     EXCEPTION
304       WHEN FND_API.G_EXC_ERROR THEN
305           x_return_status := FND_API.G_RET_STS_ERROR;
306           FND_MSG_PUB.Count_And_Get
307           (  p_count          =>   x_msg_count,
308              p_data           =>   x_msg_data );
309           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception error='||SQLERRM);
310 
311       WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
312           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
313           FND_MSG_PUB.Count_And_Get
314           (  p_count          =>   x_msg_count,
315              p_data           =>   x_msg_data );
316           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception error='||SQLERRM);
317 
318       WHEN OTHERS THEN
319           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
320           FND_MSG_PUB.Count_And_Get
321           (  p_count          =>   x_msg_count,
322              p_data           =>   x_msg_data );
323           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception error='||SQLERRM);
324     END;
325 
326     /*
327         Returns ACCOUNT SITE location, contact party_id and contact_pont_id based on specified site_use_id and contact_point_type
328     */
329     Procedure GET_SITE_DUNNING_DATA(p_api_version             IN NUMBER := 1.0,
330                                     p_init_msg_list           IN VARCHAR2 ,
331                                     p_commit                  IN VARCHAR2 ,
332                                     P_SITE_USE_ID             IN NUMBER,
333                                     P_CONTACT_POINT_TYPE      IN VARCHAR2,
334                                     X_LOCATION_ID             OUT NOCOPY NUMBER,
335                                     X_CONTACT_ID              OUT NOCOPY NUMBER,
336                                     X_CONTACT_POINT_ID        OUT NOCOPY NUMBER,
337                                     x_return_status           OUT NOCOPY VARCHAR2,
338                                     x_msg_count               OUT NOCOPY NUMBER,
339                                     x_msg_data                OUT NOCOPY VARCHAR2)
340     IS
341     /*-----------------------------------------------------------------------+
342      | Local Variable Declarations and initializations                       |
343      +-----------------------------------------------------------------------*/
344         l_api_name              CONSTANT VARCHAR2(30) := 'GET_SITE_DUNNING_DATA';
345         l_order                 NUMBER;
346         l_per_party_id          NUMBER;
347         l_rel_party_id          NUMBER;
348         l_contact_point_id      NUMBER;
349         l_count                 NUMBER;
350         l_responsibility_type   VARCHAR2(30);
351         l_dun_contact_level  VARCHAR2(30); --Added for bug 6500750 gnramasa 13-Nov-07
352 
353     /*-----------------------------------------------------------------------+
354      | Cursor Declarations                                                   |
355      +-----------------------------------------------------------------------*/
356 
357         -- get contacts for a cust account site order by responsibility type
358         cursor get_data_crs(P_SITE_USE_ID number) is
359             select
360                 decode(role_resp.responsibility_type,
361                     'DUN', decode(role_resp.primary_flag, 'Y', 1, 2),
362                     'BILL_TO', decode(role_resp.primary_flag, 'Y', 3, 4),
363                     'INV', decode(role_resp.primary_flag, 'Y', 5, 6),
364                     'SHIP_TO', decode(role_resp.primary_flag, 'Y', 7, 8), 9
365                 ) Display_Order,
366                 role_resp.responsibility_type,
367                 party.party_id,
368                 sub_party.party_id
369             from
370                 HZ_CUST_SITE_USES_ALL site_use,
371                 HZ_CUST_ACCOUNT_ROLES acct_role,
372                 HZ_ROLE_RESPONSIBILITY role_resp,
373                 HZ_RELATIONSHIPS rel,
374                 hz_parties party,
375                 hz_parties sub_party
376             where
377                 site_use.site_use_id = P_SITE_USE_ID and
378                 acct_role.cust_acct_site_id = site_use.cust_acct_site_id and
379                 acct_role.status = 'A' and
380                 role_resp.cust_account_role_id = acct_role.cust_account_role_id and
381                 acct_role.party_id = party.party_id and
382                 party.status = 'A' and
383                 rel.party_id = party.party_id and
384                 rel.subject_type = 'PERSON' and
385                 rel.status = 'A' and
386                 decode(rel.object_type, 'PERSON', rel.directional_flag, 1) = decode(rel.object_type, 'PERSON', 'F', 1) and
387                 sub_party.party_id = rel.subject_id and
388                 sub_party.status = 'A'
389             order by Display_Order, sub_party.party_name;
390 
391         -- get CONTACT_POINT_ID for specified CONTACT_POINT_TYPE and party_id
392         cursor get_data_crs1(P_PARTY_ID number, P_CONTACT_POINT_TYPE varchar2) is
393             select
394                 decode(cont_point.contact_point_purpose,
395                     'DUNNING', decode(cont_point.primary_flag, 'Y', 1, decode(cont_point.primary_by_purpose, 'Y', 2, 3)),
396                     'COLLECTIONS', decode(cont_point.primary_flag, 'Y', 4, decode(cont_point.primary_by_purpose, 'Y', 5, 6)),
397                     'BUSINESS', decode(cont_point.primary_flag, 'Y', 7, decode(cont_point.primary_by_purpose, 'Y', 8, 9)),
398                     null, decode(cont_point.primary_flag, 'Y', 10, decode(cont_point.primary_by_purpose, 'Y', 11, 12))
399                 ) Display_Order
400                 ,cont_point.CONTACT_POINT_ID
401             from hz_contact_points cont_point
402             where
403                 cont_point.owner_table_id = P_PARTY_ID and
404                 cont_point.owner_table_name = 'HZ_PARTIES' and
405                 cont_point.contact_point_type = decode(P_CONTACT_POINT_TYPE, 'EMAIL', 'EMAIL', 'PHONE', 'PHONE', 'FAX', 'PHONE') and
406                 nvl(cont_point.phone_line_type, 'EMAIL') = decode(P_CONTACT_POINT_TYPE, 'EMAIL', 'EMAIL', 'PHONE', 'GEN', 'FAX', 'FAX') and
407                 NVL(cont_point.do_not_use_flag, 'N') = 'N' and
408                 (cont_point.status = 'A' OR cont_point.status <> 'I')
409             order by Display_Order;
410 
411         -- get CONTACT_POINT_ID for specified CONTACT_POINT_TYPE and party_site_id
412         cursor get_data_crs2(P_SITE_USE_ID number, P_CONTACT_POINT_TYPE varchar2) is
413             select
414                 decode(cont_point.contact_point_purpose,
415                     'DUNNING', decode(cont_point.primary_flag, 'Y', 1, decode(cont_point.primary_by_purpose, 'Y', 2, 3)),
416                     'COLLECTIONS', decode(cont_point.primary_flag, 'Y', 4, decode(cont_point.primary_by_purpose, 'Y', 5, 6)),
417                     'BUSINESS', decode(cont_point.primary_flag, 'Y', 7, decode(cont_point.primary_by_purpose, 'Y', 8, 9)),
418                     null, decode(cont_point.primary_flag, 'Y', 10, decode(cont_point.primary_by_purpose, 'Y', 11, 12))
419                 ) Display_Order
420                 ,cont_point.CONTACT_POINT_ID
421             from
422                 HZ_CUST_SITE_USES_ALL site_use,
423                 HZ_CUST_ACCT_SITES_ALL acct_site,
424                 hz_contact_points cont_point
425             where
426                 site_use.site_use_id = P_SITE_USE_ID and
427                 acct_site.cust_acct_site_id = site_use.cust_acct_site_id and
428                 cont_point.owner_table_id = acct_site.party_site_id and
429                 cont_point.owner_table_name = 'HZ_PARTY_SITES' and
430                 cont_point.contact_point_type = decode(P_CONTACT_POINT_TYPE, 'EMAIL', 'EMAIL', 'PHONE', 'PHONE', 'FAX', 'PHONE') and
431                 nvl(cont_point.phone_line_type, 'EMAIL') = decode(P_CONTACT_POINT_TYPE, 'EMAIL', 'EMAIL', 'PHONE', 'GEN', 'FAX', 'FAX') and
432                 NVL(cont_point.do_not_use_flag, 'N') = 'N' and
433                 (cont_point.status = 'A' OR cont_point.status <> 'I')
434             order by Display_Order;
435 
436         -- get LOCATION_ID for specified site_use_id
437         cursor get_data_crs3(P_SITE_USE_ID number) is
438             select par_site.location_id
439             from
440                 HZ_CUST_SITE_USES_ALL site_use,
441                 HZ_CUST_ACCT_SITES_ALL acct_site,
442                 hz_party_sites par_site
443             where
444                 site_use.site_use_id = P_SITE_USE_ID and
445                 acct_site.cust_acct_site_id = site_use.cust_acct_site_id and
446                 par_site.party_site_id = acct_site.party_site_id;
447 
448     BEGIN
449 
450         IF FND_API.to_Boolean( p_init_msg_list )
451         THEN
452             FND_MSG_PUB.initialize;
453         END IF;
454 
455         l_dun_contact_level := nvl(fnd_profile.value('IEX_DUNNING_CONTACT_SELECTION_METHOD'), 'ALL');  --Added for bug 6500750 gnramasa 13-Nov-07
456 
457         x_return_status := FND_API.G_RET_STS_SUCCESS;
458 
459         WriteLog('----------' || l_api_name || '----------');
460         WriteLog(l_api_name || ': input parameters:');
461         WriteLog(l_api_name || ': P_SITE_USE_ID: ' || P_SITE_USE_ID);
462         WriteLog(l_api_name || ': P_CONTACT_POINT_TYPE: ' || P_CONTACT_POINT_TYPE);
463 
464         X_LOCATION_ID := null;
465         X_CONTACT_ID := null;
466         X_CONTACT_POINT_ID := null;
467 
468         -- verify input parameters and if they are not set return immediately
469         if P_SITE_USE_ID is null or P_CONTACT_POINT_TYPE is null then
470             WriteLog(l_api_name || ': Not all input parameters have value');
471             return;
472         end if;
473 
474         WriteLog(l_api_name || ': Searching for ACCOUNT SITE location...');
475         OPEN get_data_crs3(P_SITE_USE_ID);
476         FETCH get_data_crs3 INTO X_LOCATION_ID;
477         CLOSE get_data_crs3;
478         WriteLog(l_api_name || ': X_LOCATION_ID = ' || X_LOCATION_ID);
479 
480         WriteLog(l_api_name || ': Searching for ACCOUNT SITE level contacts with ' || P_CONTACT_POINT_TYPE || ' contact point...');
481 
482         l_count := 0;
483         OPEN get_data_crs(P_SITE_USE_ID);
484         LOOP
485 
486             l_contact_point_id := null;
487             fetch get_data_crs into
488                 l_order,
489                 l_responsibility_type,
490                 l_rel_party_id,
491                 l_per_party_id;
492             exit when get_data_crs%NOTFOUND;
493 
494     	-- Start for bug 6500750 gnramasa 13-Nov-07
495     	if l_dun_contact_level = 'ALL' or l_dun_contact_level is null then
496     		WriteLog(l_api_name || ': l_dun_contact_level : ' || l_dun_contact_level);
497 
498     		l_count := l_count + 1;
499     		WriteLog(l_api_name || ': Found #' || l_count || ' contact = ' || l_per_party_id);
500     		WriteLog(l_api_name || ': l_rel_party_id = ' || l_rel_party_id);
501     		WriteLog(l_api_name || ': l_responsibility_type = ' || l_responsibility_type);
502 
503     		if P_CONTACT_POINT_TYPE = 'PRINTER' then
504 
505     		    WriteLog(l_api_name || ': For contact point PRINTER return first found contact');
506     		    X_CONTACT_ID := l_per_party_id;
507     		    X_CONTACT_POINT_ID := null;
508     		    WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
509     		    WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
510     		    return;
511 
512     		else
513 
514     		    OPEN get_data_crs1(l_rel_party_id, P_CONTACT_POINT_TYPE);
515     		    FETCH get_data_crs1 INTO l_order, l_contact_point_id;
516     		    CLOSE get_data_crs1;
517 
518     		    if l_contact_point_id is not null then
519 
520     			WriteLog(l_api_name || ': Found contact_point_id = ' || l_contact_point_id);
521     			X_CONTACT_ID := l_per_party_id;
522     			X_CONTACT_POINT_ID := l_contact_point_id;
523     			WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
524     			WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
525     			return;
526 
527     		    else
528 
529     			WriteLog(l_api_name || ': No contact points found for this contact');
530 
531     		    end if;
532 
533     		end if;
534     	elsif l_dun_contact_level ='DUNNING' then
535     	   WriteLog(l_api_name || ': l_dun_contact_level : ' || l_dun_contact_level);
536     	   if l_order in (1,2) then
537     		WriteLog(l_api_name || ': l_order : ' || l_order);
538     		l_count := l_count + 1;
539     		WriteLog(l_api_name || ': Found #' || l_count || ' contact = ' || l_per_party_id);
540     		WriteLog(l_api_name || ': l_rel_party_id = ' || l_rel_party_id);
541     		WriteLog(l_api_name || ': l_responsibility_type = ' || l_responsibility_type);
542 
543     		if P_CONTACT_POINT_TYPE = 'PRINTER' then
544 
545     		    WriteLog(l_api_name || ': For contact point PRINTER return first found contact');
546     		    X_CONTACT_ID := l_per_party_id;
547     		    X_CONTACT_POINT_ID := null;
548     		    WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
549     		    WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
550     		    return;
551 
552     		else
553 
554     		    OPEN get_data_crs1(l_rel_party_id, P_CONTACT_POINT_TYPE);
555     		    FETCH get_data_crs1 INTO l_order, l_contact_point_id;
556     		    CLOSE get_data_crs1;
557 
558     		    if l_contact_point_id is not null then
559 
560     			WriteLog(l_api_name || ': Found contact_point_id = ' || l_contact_point_id);
561     			X_CONTACT_ID := l_per_party_id;
562     			X_CONTACT_POINT_ID := l_contact_point_id;
563     			WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
564     			WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
565     			return;
566 
567     		    else
568 
569     			WriteLog(l_api_name || ': No contact points found for this contact');
570 
571     		    end if;
572 
573     		end if;
574     	    end if;  -- l_order
575     	end if;  -- l_dun_contact_level
576             -- End for bug 6500750 gnramasa 13-Nov-07
577 
578         END LOOP;
579         CLOSE get_data_crs;
580 
581         if l_count = 0 then
582             WriteLog(l_api_name || ': No ACCOUNT SITE level contacts found');
583         end if;
584 
585         -- if no ACCOUNT SITE contacts with contact point found - search for ACCOUNT SITE level contact points
586         if X_CONTACT_ID is null and X_CONTACT_POINT_ID is null then
587 
588             WriteLog(l_api_name || ': Searching for ACCOUNT SITE level ' || P_CONTACT_POINT_TYPE || ' contact point...');
589             OPEN get_data_crs2(P_SITE_USE_ID, P_CONTACT_POINT_TYPE);
590             FETCH get_data_crs2 INTO l_order, l_contact_point_id;
591             CLOSE get_data_crs2;
592 
593             if l_contact_point_id is not null then
594 
595                 WriteLog(l_api_name || ': Found contact_point_id = ' || l_contact_point_id);
596                 X_CONTACT_ID := null;
597                 X_CONTACT_POINT_ID := l_contact_point_id;
598                 WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
599                 WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
600                 return;
601 
602             else
603 
604                 WriteLog(l_api_name || ': No contact points found');
605 
606             end if;
607 
608         end if;
609 
610         WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
611         WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
612 
613         FND_MSG_PUB.Count_And_Get
614         (  p_count          =>   x_msg_count,
615            p_data           =>   x_msg_data );
616 
617     EXCEPTION
618       WHEN FND_API.G_EXC_ERROR THEN
619           x_return_status := FND_API.G_RET_STS_ERROR;
620           FND_MSG_PUB.Count_And_Get
621           (  p_count          =>   x_msg_count,
622              p_data           =>   x_msg_data );
623           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception error='||SQLERRM);
624 
625       WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
626           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
627           FND_MSG_PUB.Count_And_Get
628           (  p_count          =>   x_msg_count,
629              p_data           =>   x_msg_data );
630           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception error='||SQLERRM);
631 
632       WHEN OTHERS THEN
633           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
634           FND_MSG_PUB.Count_And_Get
635           (  p_count          =>   x_msg_count,
636              p_data           =>   x_msg_data );
637           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception error='||SQLERRM);
638     END;
639 
640     /*
641         Returns ACCOUNT location, contact party_id and contact_pont_id for specified cust_account_id and contact_point_type
642     */
643     Procedure GET_ACCT_DUNNING_DATA(p_api_version             IN NUMBER := 1.0,
644                                     p_init_msg_list           IN VARCHAR2 ,
645                                     p_commit                  IN VARCHAR2 ,
646                                     P_CUST_ACCT_ID            IN NUMBER,
647                                     P_CONTACT_POINT_TYPE      IN VARCHAR2,
648                                     X_LOCATION_ID             OUT NOCOPY NUMBER,
649                                     X_CONTACT_ID              OUT NOCOPY NUMBER,
650                                     X_CONTACT_POINT_ID        OUT NOCOPY NUMBER,
651                                     x_return_status           OUT NOCOPY VARCHAR2,
652                                     x_msg_count               OUT NOCOPY NUMBER,
653                                     x_msg_data                OUT NOCOPY VARCHAR2)
654     IS
655     /*-----------------------------------------------------------------------+
656      | Local Variable Declarations and initializations                       |
657      +-----------------------------------------------------------------------*/
658         l_api_name              CONSTANT VARCHAR2(30) := 'GET_ACCT_DUNNING_DATA';
659         l_order                 NUMBER;
660         l_per_party_id          NUMBER;
661         l_rel_party_id          NUMBER;
662         l_contact_point_id      NUMBER;
663         l_count                 NUMBER;
664         l_responsibility_type   VARCHAR2(30);
665         l_org_party_id          NUMBER;
666         l_bill_to_count         NUMBER;
667         l_display_order         NUMBER;
668         l_site_use_code         VARCHAR2(30);
669         l_location_id           NUMBER;
670         l_dun_contact_level     VARCHAR2(30); --Added for bug 6500750 gnramasa 13-Nov-07
671 
672     /*-----------------------------------------------------------------------+
673      | Cursor Declarations                                                   |
674      +-----------------------------------------------------------------------*/
675 
676         -- get contacts for a cust account order by responsibility type
677         cursor get_data_crs(P_CUST_ACCOUNT_ID number) is
678             select
679                 decode(role_resp.responsibility_type,
680                     'DUN', decode(role_resp.primary_flag, 'Y', 1, 2),
681                     'BILL_TO', decode(role_resp.primary_flag, 'Y', 3, 4),
682                     'INV', decode(role_resp.primary_flag, 'Y', 5, 6),
683                     'SHIP_TO', decode(role_resp.primary_flag, 'Y', 7, 8), 9
684                 ) Display_Order,
685                 role_resp.responsibility_type,
686                 party.party_id,
687                 sub_party.party_id,
688                 rel.object_id
689             from
690                 HZ_CUST_ACCOUNT_ROLES acct_role,
691                 HZ_ROLE_RESPONSIBILITY role_resp,
692                 HZ_RELATIONSHIPS rel,
693                 hz_parties party,
694                 hz_parties sub_party
695             where
696                 acct_role.cust_account_id = P_CUST_ACCOUNT_ID and
697                 acct_role.cust_acct_site_id is null and
698                 acct_role.status = 'A' and
699                 acct_role.cust_account_role_id = role_resp.cust_account_role_id and
700                 acct_role.party_id = party.party_id and
701                 party.status = 'A' and
702                 rel.party_id = party.party_id and
703                 rel.subject_type = 'PERSON' and
704                 rel.status = 'A' and
705                 decode(rel.object_type, 'PERSON', rel.directional_flag, 1) = decode(rel.object_type, 'PERSON', 'F', 1) and
706                 sub_party.party_id = rel.subject_id and
707                 sub_party.status = 'A'
708             order by Display_Order, sub_party.party_name;
709 
710         -- get CONTACT_POINT_ID for specified CONTACT_POINT_TYPE and party_id
711         cursor get_data_crs1(P_PARTY_ID number, P_CONTACT_POINT_TYPE varchar2) is
712             select
713                 decode(cont_point.contact_point_purpose,
714                     'DUNNING', decode(cont_point.primary_flag, 'Y', 1, decode(cont_point.primary_by_purpose, 'Y', 2, 3)),
715                     'COLLECTIONS', decode(cont_point.primary_flag, 'Y', 4, decode(cont_point.primary_by_purpose, 'Y', 5, 6)),
716                     'BUSINESS', decode(cont_point.primary_flag, 'Y', 7, decode(cont_point.primary_by_purpose, 'Y', 8, 9)),
717                     null, decode(cont_point.primary_flag, 'Y', 10, decode(cont_point.primary_by_purpose, 'Y', 11, 12))
718                 ) Display_Order
719                 ,cont_point.CONTACT_POINT_ID
720             from hz_contact_points cont_point
721             where
722                 cont_point.owner_table_id = P_PARTY_ID and
723                 cont_point.owner_table_name = 'HZ_PARTIES' and
724                 cont_point.contact_point_type = decode(P_CONTACT_POINT_TYPE, 'EMAIL', 'EMAIL', 'PHONE', 'PHONE', 'FAX', 'PHONE') and
725                 nvl(cont_point.phone_line_type, 'EMAIL') = decode(P_CONTACT_POINT_TYPE, 'EMAIL', 'EMAIL', 'PHONE', 'GEN', 'FAX', 'FAX') and
726                 NVL(cont_point.do_not_use_flag, 'N') = 'N' and
727                 (cont_point.status = 'A' OR cont_point.status <> 'I')
728             order by Display_Order;
729 
730         -- get party_id from cust_account_id
731         cursor get_party_crs(P_CUST_ACCOUNT_ID number) is
732             select party_id from hz_cust_accounts where cust_account_id = P_CUST_ACCOUNT_ID;
733 
734         -- get LOCATION_ID for specified cust_account_id
735         cursor get_data_crs2(P_CUST_ACCOUNT_ID number) is
736             select
737                 decode(site_use.site_use_code,
738                     'DUN', 1,
739                     'BILL_TO', decode(site_use.primary_flag, 'Y', 2, 3)) display_order,
740                 site_use.site_use_code,
741                 par_site.location_id
742             from
743                 hz_party_sites par_site,
744                 HZ_CUST_ACCT_SITES_ALL acct_site,
745                 HZ_CUST_SITE_USES_ALL site_use
746             where
747                 acct_site.cust_account_id = P_CUST_ACCOUNT_ID and
748                 acct_site.status = 'A' and
749                 acct_site.cust_acct_site_id = site_use.cust_acct_site_id and
750                 site_use.status = 'A' and
751                 par_site.party_site_id = acct_site.party_site_id and
752                 par_site.status in ('A', 'I')
753             order by display_order;
754 
755         -- get count on not primary bill-to locations
756         cursor get_data_crs3(P_CUST_ACCOUNT_ID number) is
757             select count(1)
758             from
759                 hz_party_sites par_site,
760                 HZ_CUST_ACCT_SITES_ALL acct_site,
761                 HZ_CUST_SITE_USES_ALL site_use
762             where
763                 acct_site.cust_account_id = P_CUST_ACCOUNT_ID and
764                 acct_site.status = 'A' and
765                 acct_site.cust_acct_site_id = site_use.cust_acct_site_id and
766                 site_use.status = 'A' and
767                 par_site.party_site_id = acct_site.party_site_id and
768                 par_site.status in ('A', 'I') and
769                 site_use.site_use_code = 'BILL_TO' and
770                 site_use.primary_flag <> 'Y';
771 
772         -- Start for bug 6500750 gnramasa 13-Nov-07
773 
774          cursor get_old_loc_crs1(P_ORG_PARTY_ID number) is
775             select location_id
776             from ast_locations_v
777             where party_id = P_ORG_PARTY_ID and
778                 primary_flag = 'Y';
779 
780         -- End for bug 6500750 gnramasa 13-Nov-07
781 
782     BEGIN
783 
784         IF FND_API.to_Boolean( p_init_msg_list )
785         THEN
786             FND_MSG_PUB.initialize;
787         END IF;
788 
789         l_dun_contact_level := nvl(fnd_profile.value('IEX_DUNNING_CONTACT_SELECTION_METHOD'), 'ALL');  --Added for bug 6500750 gnramasa 13-Nov-07
790 
791         x_return_status := FND_API.G_RET_STS_SUCCESS;
792 
793         WriteLog('----------' || l_api_name || '----------');
794         WriteLog(l_api_name || ': input parameters:');
795         WriteLog(l_api_name || ': P_CUST_ACCT_ID: ' || P_CUST_ACCT_ID);
796         WriteLog(l_api_name || ': P_CONTACT_POINT_TYPE: ' || P_CONTACT_POINT_TYPE);
797 
798         X_LOCATION_ID := null;
799         X_CONTACT_ID := null;
800         X_CONTACT_POINT_ID := null;
801 
802         -- verify input parameters and if they are not set return immediately
803         if P_CUST_ACCT_ID is null or P_CONTACT_POINT_TYPE is null then
804             WriteLog(l_api_name || ': Not all input parameters have value');
805             return;
806         end if;
807 
808         -- Start for bug 6500750 gnramasa 13-Nov-07
809         IF l_dun_contact_level = 'ALL' OR l_dun_contact_level IS NULL then
810 
811     	    WriteLog(l_api_name || ': l_dun_contact_level : ' || l_dun_contact_level);
812     	    WriteLog(l_api_name || ': Searching for ACCOUNT location...');
813     	    OPEN get_data_crs2(P_CUST_ACCT_ID);
814     	    LOOP
815     		FETCH get_data_crs2 INTO l_display_order,
816     					 l_site_use_code,
817     					 l_location_id;
818     		exit when (get_data_crs2%NOTFOUND or l_display_order is null);
819 
820     		WriteLog(l_api_name || ': Found location:');
821     		WriteLog(l_api_name || ': l_display_order: ' || l_display_order);
822     		WriteLog(l_api_name || ': l_site_use_code: ' || l_site_use_code);
823     		WriteLog(l_api_name || ': l_location_id: ' || l_location_id);
824 
825     		if l_display_order = 1 or l_display_order = 2 then  -- dunning or primary bill-to
826 
827     		    X_LOCATION_ID := l_location_id;
828     		    exit;
829 
830     		elsif l_display_order = 3 then    -- regular bill-to
831 
832     		    OPEN get_data_crs3(P_CUST_ACCT_ID);
833     		    FETCH get_data_crs3 INTO l_bill_to_count;
834     		    CLOSE get_data_crs3;
835 
836     		    -- if more then 1 regular bill-to then set error
837     		    if l_bill_to_count > 1 then
838     			X_LOCATION_ID := null;
839     			WriteLog(l_api_name || ': ERROR: Multiple Bill-To locations found');
840     			FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_MULT_LOC');
841     			FND_MESSAGE.Set_Token('USAGE', 'bill-to', FALSE);
842     			FND_MSG_PUB.Add;
843     			x_return_status := FND_API.G_RET_STS_ERROR;
844     		    else
845     			X_LOCATION_ID := l_location_id;
846     		    end if;
847     		    exit;
848 
849     		end if;
850 
851     	    END LOOP;
852     	    CLOSE get_data_crs2;
853 
854     	    WriteLog(l_api_name || ': X_LOCATION_ID = ' || X_LOCATION_ID);
855             end if;
856 
857         WriteLog(l_api_name || ': Searching for ACCOUNT level contacts with ' || P_CONTACT_POINT_TYPE || ' contact point...');
858 
859         l_count := 0;
860         OPEN get_data_crs(P_CUST_ACCT_ID);
861         LOOP
862 
863             l_contact_point_id := null;
864             fetch get_data_crs into
865                 l_order,
866                 l_responsibility_type,
867                 l_rel_party_id,
868                 l_per_party_id,
869                 l_org_party_id;
870             exit when get_data_crs%NOTFOUND;
871 
872     	IF l_dun_contact_level = 'ALL' OR l_dun_contact_level IS NULL then
873     	        WriteLog(l_api_name || ': l_dun_contact_level : ' || l_dun_contact_level);
874 
875     		l_count := l_count + 1;
876     		WriteLog(l_api_name || ': Found #' || l_count || ' contact = ' || l_per_party_id);
877     		WriteLog(l_api_name || ': l_rel_party_id = ' || l_rel_party_id);
878     		WriteLog(l_api_name || ': l_responsibility_type = ' || l_responsibility_type);
879 
880     		if P_CONTACT_POINT_TYPE = 'PRINTER' then
881 
882     		    WriteLog(l_api_name || ': For contact point PRINTER return first found contact');
883     		    X_CONTACT_ID := l_per_party_id;
884     		    X_CONTACT_POINT_ID := null;
885     		    WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
886     		    WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
887     		    return;
888 
889     		else
890 
891     		    OPEN get_data_crs1(l_rel_party_id, P_CONTACT_POINT_TYPE);
892     		    FETCH get_data_crs1 INTO l_order, l_contact_point_id;
893     		    CLOSE get_data_crs1;
894 
895     		    if l_contact_point_id is not null then
896 
897     			WriteLog(l_api_name || ': Found contact_point_id = ' || l_contact_point_id);
898     			X_CONTACT_ID := l_per_party_id;
899     			X_CONTACT_POINT_ID := l_contact_point_id;
900     			WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
901     			WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
902     			return;
903 
904     		    else
905 
906     			WriteLog(l_api_name || ': No contact points found for this contact');
907 
908     		    end if;
909 
910     		end if;
911     	ELSIF l_dun_contact_level='DUNNING' then
912 
913     	 WriteLog(l_api_name || ': l_dun_contact_level : ' || l_dun_contact_level);
914     	 if l_order in (1,2) then
915 
916     		l_count := l_count + 1;
917     		WriteLog(l_api_name || ': Found #' || l_count || ' contact = ' || l_per_party_id);
918     		WriteLog(l_api_name || ': l_rel_party_id = ' || l_rel_party_id);
919     		WriteLog(l_api_name || ': l_responsibility_type = ' || l_responsibility_type);
920 
921     		if P_CONTACT_POINT_TYPE = 'PRINTER' then
922 
923     		    WriteLog(l_api_name || ': For contact point PRINTER return first found contact');
924     		    X_CONTACT_ID := l_per_party_id;
925     		    X_CONTACT_POINT_ID := null;
926     		    WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
927     		    WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
928     		    --return;
929     		    exit;
930 
931     		else
932 
933     		    OPEN get_data_crs1(l_rel_party_id, P_CONTACT_POINT_TYPE);
934     		    FETCH get_data_crs1 INTO l_order, l_contact_point_id;
935     		    CLOSE get_data_crs1;
936 
937     		    if l_contact_point_id is not null then
938 
939     			WriteLog(l_api_name || ': Found contact_point_id = ' || l_contact_point_id);
940     			X_CONTACT_ID := l_per_party_id;
941     			X_CONTACT_POINT_ID := l_contact_point_id;
942     			WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
943     			WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
944     			--return;
945     			exit;
946 
947     		    else
948 
949     			WriteLog(l_api_name || ': No contact points found for this contact');
950 
951     		    end if;
952 
953     		end if;
954     	    end if;
955 
956     	END IF; --l_dun_contact_level
957         --End for bug 6500750 gnramasa 13-Nov-07
958 
959         END LOOP;
960         CLOSE get_data_crs;
961 
962         if l_count = 0 then
963             WriteLog(l_api_name || ': No ACCOUNT level contacts found');
964         end if;
965 
966         -- if no ACCOUNT contacts with contact point found - search for ACCOUNT SITE level contact points
967         if X_CONTACT_ID is null and X_CONTACT_POINT_ID is null then
968 
969             WriteLog(l_api_name || ': Searching for ACCOUNT level ' || P_CONTACT_POINT_TYPE || ' contact point...');
970 
971             OPEN get_party_crs(P_CUST_ACCT_ID);
972             FETCH get_party_crs INTO l_org_party_id;
973             CLOSE get_party_crs;
974 
975             WriteLog(l_api_name || ': l_org_party_id = ' || l_org_party_id);
976 
977             OPEN get_data_crs1(l_org_party_id, P_CONTACT_POINT_TYPE);
978             FETCH get_data_crs1 INTO l_order, l_contact_point_id;
979             CLOSE get_data_crs1;
980 
981             if l_contact_point_id is not null then
982 
983                 WriteLog(l_api_name || ': Found contact_point_id = ' || l_contact_point_id);
984                 X_CONTACT_ID := null;
985                 X_CONTACT_POINT_ID := l_contact_point_id;
986                 WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
987                 WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
988                 --return;
989 
990             else
991 
992                 WriteLog(l_api_name || ': No contact points found');
993 
994             end if;
995 
996         end if;
997 
998             -- Start for bug 6500750 gnramasa 13-Nov-07
999         if l_dun_contact_level = 'DUNNING' then
1000     	WriteLog(l_api_name || ': l_dun_contact_level : ' || l_dun_contact_level);
1001     	WriteLog(l_api_name || ': Searching for ACCOUNT location...');
1002     	    OPEN get_data_crs2(P_CUST_ACCT_ID);
1003     	    LOOP
1004     		FETCH get_data_crs2 INTO l_display_order,
1005     					         l_site_use_code,
1006     					         l_location_id;
1007     		exit when (get_data_crs2%NOTFOUND or l_display_order is null);
1008 
1009     		WriteLog(l_api_name || ': Found location:');
1010     		WriteLog(l_api_name || ': l_display_order: ' || l_display_order);
1011     		WriteLog(l_api_name || ': l_site_use_code: ' || l_site_use_code);
1012     		WriteLog(l_api_name || ': l_location_id: ' || l_location_id);
1013 
1014     		if l_display_order = 1 then  -- dunning
1015 
1016     		    X_LOCATION_ID := l_location_id;
1017     		    exit;
1018 
1019     		else  -- no dunning purpose address found, so send it to identifying address.
1020     		    WriteLog(l_api_name || ' no dunning purpose address found, so send it to Identifying address');
1021     		    -- get relationship location_id
1022     		    OPEN get_party_crs(P_CUST_ACCT_ID);
1023     		    FETCH get_party_crs INTO l_org_party_id;
1024     		    CLOSE get_party_crs;
1025 
1026     		    OPEN get_old_loc_crs1(l_org_party_id);
1027     		    fetch get_old_loc_crs1 into l_location_id;
1028     		    CLOSE get_old_loc_crs1;
1029 
1030     		    if l_location_id is not null then
1031     			WriteLog(l_api_name || ': Found organization location: ' || l_location_id);
1032     		    else
1033     			WriteLog(l_api_name || ': No organization location found');
1034     		    end if;
1035 
1036     		    X_LOCATION_ID := l_location_id;
1037     		    exit;
1038 
1039     	        end if;
1040 
1041               END LOOP;
1042         CLOSE get_data_crs2;
1043 
1044         WriteLog(l_api_name || ': X_LOCATION_ID = ' || X_LOCATION_ID);
1045 
1046         end if;
1047         --End for bug 6500750 gnramasa 13-Nov-07
1048 
1049         WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
1050         WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
1051 
1052         FND_MSG_PUB.Count_And_Get
1053         (  p_count          =>   x_msg_count,
1054            p_data           =>   x_msg_data );
1055 
1056     EXCEPTION
1057       WHEN FND_API.G_EXC_ERROR THEN
1058           x_return_status := FND_API.G_RET_STS_ERROR;
1059           FND_MSG_PUB.Count_And_Get
1060           (  p_count          =>   x_msg_count,
1061              p_data           =>   x_msg_data );
1062           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception error='||SQLERRM);
1063 
1064       WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1065           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1066           FND_MSG_PUB.Count_And_Get
1067           (  p_count          =>   x_msg_count,
1068              p_data           =>   x_msg_data );
1069           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception error='||SQLERRM);
1070 
1071       WHEN OTHERS THEN
1072           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1073           FND_MSG_PUB.Count_And_Get
1074           (  p_count          =>   x_msg_count,
1075              p_data           =>   x_msg_data );
1076           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception error='||SQLERRM);
1077     END;
1078 
1079     /*
1080         Returns CUSTOMER location_id, contact party_id and contact_pont_id for specified cust_account_id and contact_point_type
1081     */
1082     Procedure GET_CUST_DUNNING_DATA(p_api_version             IN NUMBER := 1.0,
1083                                     p_init_msg_list           IN VARCHAR2 ,
1084                                     p_commit                  IN VARCHAR2 ,
1085                                     P_PARTY_ID                IN NUMBER,
1086                                     P_CONTACT_POINT_TYPE      IN VARCHAR2,
1087                                     X_LOCATION_ID             OUT NOCOPY NUMBER,
1088                                     X_CONTACT_ID              OUT NOCOPY NUMBER,
1089                                     X_CONTACT_POINT_ID        OUT NOCOPY NUMBER,
1090                                     x_return_status           OUT NOCOPY VARCHAR2,
1091                                     x_msg_count               OUT NOCOPY NUMBER,
1092                                     x_msg_data                OUT NOCOPY VARCHAR2)
1093     IS
1094     /*-----------------------------------------------------------------------+
1095      | Local Variable Declarations and initializations                       |
1096      +-----------------------------------------------------------------------*/
1097         l_api_name                  CONSTANT VARCHAR2(30) := 'GET_CUST_DUNNING_DATA';
1098         l_cust_account_id           NUMBER;
1099         l_display_order             NUMBER;
1100         l_site_use_code             VARCHAR2(30);
1101         l_identifying_address_flag  VARCHAR2(1);
1102         l_primary_flag              VARCHAR2(1);
1103         l_count                     NUMBER;
1104         l_purpose_flag              varchar2(1);
1105         l_rel_party_id              NUMBER;
1106         l_contact_id                NUMBER;
1107         l_contact_point_id          NUMBER;
1108         l_location_id               NUMBER;
1109 
1110     /*-----------------------------------------------------------------------+
1111      | Cursor Declarations                                                   |
1112      +-----------------------------------------------------------------------*/
1113 
1114         -- get cust_account_id for the party identifying address
1115         cursor get_data_crs(P_PARTY_ID number) is
1116             select
1117                 decode(site_use.site_use_code,
1118                     'DUN', decode(par_site.identifying_address_flag, 'Y', 1, 'N', 4),
1119                     'BILL_TO', decode(par_site.identifying_address_flag,
1120                                   'Y', decode(site_use.primary_flag, 'Y', 2, 3),
1121                                   'N', decode(site_use.primary_flag, 'Y', 5, 6))) Display_Order ,
1122                 acct_site.cust_account_id,
1123                 site_use.site_use_code,
1124                 par_site.identifying_address_flag,
1125                 site_use.primary_flag
1126             from  HZ_CUST_SITE_USES_ALL site_use,
1127                 HZ_CUST_ACCT_SITES_ALL acct_site,
1128                 hz_party_sites par_site
1129             where  par_site.party_id = P_PARTY_ID and
1130                 par_site.status in ('A', 'I') and
1131                 par_site.party_site_id = acct_site.party_site_id and
1132                 acct_site.status = 'A' and
1133                 acct_site.cust_acct_site_id = site_use.cust_acct_site_id and
1134                 site_use.status = 'A'
1135             order by Display_Order;
1136 
1137         -- get count on locations
1138         cursor get_data_crs1(P_PARTY_ID number,
1139                              P_SITE_USE_CODE varchar2,
1140                              P_IDENT_FLAG varchar2,
1141                              P_PRIMARY_FLAG varchar2) is
1142             select count(1)
1143             from  HZ_CUST_SITE_USES_ALL site_use,
1144                 HZ_CUST_ACCT_SITES_ALL acct_site,
1145                 hz_party_sites par_site
1146             where  par_site.party_id = P_PARTY_ID and
1147                 par_site.status in ('A', 'I') and
1148                 par_site.party_site_id = acct_site.party_site_id and
1149                 acct_site.status = 'A' and
1150                 acct_site.cust_acct_site_id = site_use.cust_acct_site_id and
1151                 site_use.status = 'A' and
1152                 site_use.site_use_code = P_SITE_USE_CODE and
1153                 par_site.identifying_address_flag = P_IDENT_FLAG and
1154                 site_use.primary_flag = P_PRIMARY_FLAG;
1155     BEGIN
1156 
1157         IF FND_API.to_Boolean( p_init_msg_list )
1158         THEN
1159             FND_MSG_PUB.initialize;
1160         END IF;
1161 
1162         x_return_status := FND_API.G_RET_STS_SUCCESS;
1163 
1164         WriteLog('----------' || l_api_name || '----------');
1165         WriteLog(l_api_name || ': input parameters:');
1166         WriteLog(l_api_name || ': P_PARTY_ID: ' || P_PARTY_ID);
1167         WriteLog(l_api_name || ': P_CONTACT_POINT_TYPE: ' || P_CONTACT_POINT_TYPE);
1168 
1169         X_LOCATION_ID := null;
1170         X_CONTACT_ID := null;
1171         X_CONTACT_POINT_ID := null;
1172 
1173         -- verify input parameters and if they are not set return immediately
1174         if P_PARTY_ID is null or P_CONTACT_POINT_TYPE is null then
1175             WriteLog(l_api_name || ': Not all input parameters have value');
1176             return;
1177         end if;
1178 
1179         WriteLog(l_api_name || ': Searching for account...');
1180 
1181         -- searching for account
1182         OPEN get_data_crs(P_PARTY_ID);
1183         fetch get_data_crs into l_display_order,
1184                                 l_cust_account_id,
1185                                 l_site_use_code,
1186                                 l_identifying_address_flag,
1187                                 l_primary_flag;
1188         CLOSE get_data_crs;
1189 
1190         if l_cust_account_id is null then
1191             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_ACCOUNT');
1192             FND_MSG_PUB.ADD;
1193             RAISE FND_API.G_EXC_ERROR;
1194         end if;
1195 
1196         WriteLog(l_api_name || ': Found account:');
1197         WriteLog(l_api_name || ': l_display_order: ' || l_display_order);
1198         WriteLog(l_api_name || ': l_cust_account_id = ' || l_cust_account_id);
1199         WriteLog(l_api_name || ': l_site_use_code: ' || l_site_use_code);
1200         WriteLog(l_api_name || ': l_identifying_address_flag: ' || l_identifying_address_flag);
1201         WriteLog(l_api_name || ': l_primary_flag: ' || l_primary_flag);
1202 
1203         OPEN get_data_crs1(P_PARTY_ID, l_site_use_code, l_identifying_address_flag, l_primary_flag);
1204         FETCH get_data_crs1 INTO l_count;
1205         CLOSE get_data_crs1;
1206 
1207         WriteLog(l_api_name || ': Locations count = ' || l_count);
1208 
1209         -- if more then 1 regular bill-to then set error
1210         if l_count > 1 then
1211             WriteLog(l_api_name || ': ERROR: Multiple locations found');
1212             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_MULT_LOC');
1213             FND_MESSAGE.Set_Token('USAGE', l_site_use_code, FALSE);
1214             FND_MSG_PUB.Add;
1215             x_return_status := FND_API.G_RET_STS_ERROR;
1216         end if;
1217 
1218         -- call GET_ACCT_DUNNING_DATA for found account
1219         WriteLog(l_api_name || ': Calling GET_ACCT_DUNNING_DATA for account ' || l_cust_account_id);
1220         GET_ACCT_DUNNING_DATA(p_api_version => 1.0,
1221                               p_init_msg_list => FND_API.G_FALSE,
1222                               p_commit => FND_API.G_FALSE,
1223                               P_CUST_ACCT_ID => l_cust_account_id,
1224                               P_CONTACT_POINT_TYPE => P_CONTACT_POINT_TYPE,
1225                               X_LOCATION_ID => X_LOCATION_ID,
1226                               X_CONTACT_ID => X_CONTACT_ID,
1227                               X_CONTACT_POINT_ID => X_CONTACT_POINT_ID,
1228                               x_return_status => x_return_status,
1229                               x_msg_count => x_msg_count,
1230                               x_msg_data => x_msg_data);
1231 
1232         WriteLog('---------- continue ' || l_api_name || '----------');
1233         WriteLog(l_api_name || ': x_return_status: ' || x_return_status);
1234         WriteLog(l_api_name || ': x_msg_count: ' || x_msg_count);
1235 
1236         WriteLog(l_api_name || ': X_LOCATION_ID = ' || X_LOCATION_ID);
1237         WriteLog(l_api_name || ': X_CONTACT_ID = ' || X_CONTACT_ID);
1238         WriteLog(l_api_name || ': X_CONTACT_POINT_ID = ' || X_CONTACT_POINT_ID);
1239 
1240         FND_MSG_PUB.Count_And_Get
1241         (  p_count          =>   x_msg_count,
1242            p_data           =>   x_msg_data );
1243 
1244     EXCEPTION
1245       WHEN FND_API.G_EXC_ERROR THEN
1246           x_return_status := FND_API.G_RET_STS_ERROR;
1247           FND_MSG_PUB.Count_And_Get
1248           (  p_count          =>   x_msg_count,
1249              p_data           =>   x_msg_data );
1250           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception error='||SQLERRM);
1251 
1252       WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1253           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1254           FND_MSG_PUB.Count_And_Get
1255           (  p_count          =>   x_msg_count,
1256              p_data           =>   x_msg_data );
1257           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception error='||SQLERRM);
1258 
1259       WHEN OTHERS THEN
1260           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1261           FND_MSG_PUB.Count_And_Get
1262           (  p_count          =>   x_msg_count,
1263              p_data           =>   x_msg_data );
1264           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception error='||SQLERRM);
1265     END;
1266 
1267     -- get dafault dunning destination
1268     procedure GET_DEFAULT_DUN_DEST(p_api_version              IN NUMBER := 1.0,
1269                                  p_init_msg_list            IN VARCHAR2,
1270                                  p_commit                   IN VARCHAR2,
1271                                  p_level                    in varchar2,
1272                                  p_source_id                in number,
1273                                  p_send_method              in varchar2,
1274                                  X_LOCATION_ID              OUT NOCOPY NUMBER,
1275                                  X_CONTACT_ID               OUT NOCOPY NUMBER,
1276                                  X_CONTACT_POINT_ID         OUT NOCOPY NUMBER,
1277                                  x_return_status            OUT NOCOPY VARCHAR2,
1278                                  x_msg_count                OUT NOCOPY NUMBER,
1279                                  x_msg_data                 OUT NOCOPY VARCHAR2)
1280     is
1281 
1282         l_api_name                constant varchar2(25) := 'GET_DEFAULT_DUN_DEST';
1283         l_temp_site_use_id        number;
1284         l_party_id                number;
1285 
1286         cursor c_get_party_from_acc(p_cust_account_id number) is
1287             select party_id
1288             from hz_cust_accounts
1289             where cust_account_id = p_cust_account_id;
1290 
1291         cursor c_get_party_from_site(p_site_use_id number) is
1292             select cust.party_id
1293             from hz_cust_accounts cust,
1294             hz_cust_acct_sites_all acc_site,
1295             hz_cust_site_uses_all site_use
1296             where site_use.site_use_id = p_site_use_id and
1297             site_use.cust_acct_site_id = acc_site.cust_acct_site_id and
1298             acc_site.cust_account_id = cust.cust_account_id;
1299 
1300         cursor c_get_party_from_del(p_delinquency_id number) is
1301             select party_cust_id, customer_site_use_id
1302             from iex_delinquencies_all
1303             where delinquency_id = p_delinquency_id;
1304 
1305     begin
1306 
1307         IF FND_API.to_Boolean( p_init_msg_list )
1308         THEN
1309             FND_MSG_PUB.initialize;
1310         END IF;
1311 
1312         x_return_status := FND_API.G_RET_STS_SUCCESS;
1313 
1314         WriteLog('----------' || l_api_name || '----------');
1315         WriteLog(l_api_name || ': input parameters:');
1316         WriteLog(l_api_name || ': p_level: ' || p_level);
1317         WriteLog(l_api_name || ': p_source_id: ' || p_source_id);
1318         WriteLog(l_api_name || ': p_send_method: ' || p_send_method);
1319 
1320         if p_level = 'CUSTOMER' then
1321             l_party_id := p_source_id;
1322         elsif p_level = 'ACCOUNT' then
1323             WriteLog(l_api_name || ': getting party from account...');
1324             open c_get_party_from_acc(p_source_id);
1325             fetch c_get_party_from_acc into l_party_id;
1326             close c_get_party_from_acc;
1327         elsif p_level = 'BILL_TO' then
1328             WriteLog(l_api_name || ': getting party from site...');
1329             open c_get_party_from_site(p_source_id);
1330             fetch c_get_party_from_site into l_party_id;
1331             close c_get_party_from_site;
1332         elsif p_level = 'DELINQUENCY' then
1333             WriteLog(l_api_name || ': getting party from delinquency...');
1334             open c_get_party_from_del(p_source_id);
1335             fetch c_get_party_from_del into l_party_id, l_temp_site_use_id;
1336             close c_get_party_from_del;
1337         end if;
1338         WriteLog(l_api_name || ': party_id = ' || l_party_id);
1339 
1340         WriteLog(l_api_name || ': Calling GET_CUST_DUNNING_DATA_OW...');
1341         GET_CUST_DUNNING_DATA_OW(p_api_version => 1.0,
1342                               p_init_msg_list => FND_API.G_TRUE,
1343                               p_commit => FND_API.G_FALSE,
1344                               P_PARTY_ID => l_party_id,
1345                               P_CONTACT_POINT_TYPE => p_send_method,
1346                               X_LOCATION_ID => X_LOCATION_ID,
1347                               X_CONTACT_ID => X_CONTACT_ID,
1348                               X_CONTACT_POINT_ID => X_CONTACT_POINT_ID,
1349                               x_return_status => x_return_status,
1350                               x_msg_count => x_msg_count,
1351                               x_msg_data => x_msg_data);
1352 
1353         if (p_send_method = 'PRINTER' and (X_LOCATION_ID is null or X_CONTACT_ID is null)) or
1354            (p_send_method <> 'PRINTER' and (X_LOCATION_ID is null or X_CONTACT_ID is null or X_CONTACT_POINT_ID is null)) then
1355 
1356             WriteLog('---------- continue ' || l_api_name || '----------');
1357             X_LOCATION_ID := null;
1358             X_CONTACT_ID := null;
1359             X_CONTACT_POINT_ID := null;
1360 
1361             WriteLog(l_api_name || ': Did not find data the old way. Continue with new way');
1362             if p_level = 'CUSTOMER' then
1363 
1364                 WriteLog(l_api_name || ': Calling GET_CUST_DUNNING_DATA...');
1365                 GET_CUST_DUNNING_DATA(p_api_version => 1.0,
1366                                       p_init_msg_list => FND_API.G_TRUE,
1367                                       p_commit => FND_API.G_FALSE,
1368                                       P_PARTY_ID => p_source_id,
1369                                       P_CONTACT_POINT_TYPE => p_send_method,
1370                                       X_LOCATION_ID => X_LOCATION_ID,
1371                                       X_CONTACT_ID => X_CONTACT_ID,
1372                                       X_CONTACT_POINT_ID => X_CONTACT_POINT_ID,
1373                                       x_return_status => x_return_status,
1374                                       x_msg_count => x_msg_count,
1375                                       x_msg_data => x_msg_data);
1376 
1377             elsif p_level = 'ACCOUNT' then
1378 
1379                 WriteLog(l_api_name || ': Calling GET_ACCT_DUNNING_DATA...');
1380                 GET_ACCT_DUNNING_DATA(p_api_version => 1.0,
1381                                       p_init_msg_list => FND_API.G_TRUE,
1382                                       p_commit => FND_API.G_FALSE,
1383                                       P_CUST_ACCT_ID => p_source_id,
1384                                       P_CONTACT_POINT_TYPE => p_send_method,
1385                                       X_LOCATION_ID => X_LOCATION_ID,
1386                                       X_CONTACT_ID => X_CONTACT_ID,
1387                                       X_CONTACT_POINT_ID => X_CONTACT_POINT_ID,
1388                                       x_return_status => x_return_status,
1389                                       x_msg_count => x_msg_count,
1390                                       x_msg_data => x_msg_data);
1391 
1392             elsif p_level = 'BILL_TO' then
1393 
1394                 WriteLog(l_api_name || ': Calling GET_SITE_DUNNING_DATA...');
1395                 GET_SITE_DUNNING_DATA(p_api_version => 1.0,
1396                                       p_init_msg_list => FND_API.G_TRUE,
1397                                       p_commit => FND_API.G_FALSE,
1398                                       P_SITE_USE_ID => p_source_id,
1399                                       P_CONTACT_POINT_TYPE => p_send_method,
1400                                       X_LOCATION_ID => X_LOCATION_ID,
1401                                       X_CONTACT_ID => X_CONTACT_ID,
1402                                       X_CONTACT_POINT_ID => X_CONTACT_POINT_ID,
1403                                       x_return_status => x_return_status,
1404                                       x_msg_count => x_msg_count,
1405                                       x_msg_data => x_msg_data);
1406 
1407             elsif p_level = 'DELINQUENCY' then
1408 
1409                 WriteLog(l_api_name || ': site_use_id = ' || l_temp_site_use_id);
1410                 WriteLog(l_api_name || ': Calling GET_SITE_DUNNING_DATA...');
1411                 GET_SITE_DUNNING_DATA(p_api_version => 1.0,
1412                                       p_init_msg_list => FND_API.G_TRUE,
1413                                       p_commit => FND_API.G_FALSE,
1414                                       P_SITE_USE_ID => l_temp_site_use_id,
1415                                       P_CONTACT_POINT_TYPE => p_send_method,
1416                                       X_LOCATION_ID => X_LOCATION_ID,
1417                                       X_CONTACT_ID => X_CONTACT_ID,
1418                                       X_CONTACT_POINT_ID => X_CONTACT_POINT_ID,
1419                                       x_return_status => x_return_status,
1420                                       x_msg_count => x_msg_count,
1421                                       x_msg_data => x_msg_data);
1422 
1423             end if;
1424 
1425         end if;
1426 
1427         WriteLog('---------- continue ' || l_api_name || '----------');
1428         WriteLog(l_api_name || ': LOCATION_ID: ' || X_LOCATION_ID);
1429         WriteLog(l_api_name || ': CONTACT_ID: ' || X_CONTACT_ID);
1430         WriteLog(l_api_name || ': CONTACT_POINT_ID: ' || X_CONTACT_POINT_ID);
1431 
1432         WriteLog(l_api_name || ': x_return_status: ' || x_return_status);
1433         WriteLog(l_api_name || ': x_msg_count: ' || x_msg_count);
1434 
1435     EXCEPTION
1436       WHEN FND_API.G_EXC_ERROR THEN
1437           x_return_status := FND_API.G_RET_STS_ERROR;
1438           FND_MSG_PUB.Count_And_Get
1439           (  p_count          =>   x_msg_count,
1440              p_data           =>   x_msg_data );
1441           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception error='||SQLERRM);
1442 
1443       WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1444           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1445           FND_MSG_PUB.Count_And_Get
1446           (  p_count          =>   x_msg_count,
1447              p_data           =>   x_msg_data );
1448           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception error='||SQLERRM);
1449 
1450       WHEN OTHERS THEN
1451           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1452           FND_MSG_PUB.Count_And_Get
1453           (  p_count          =>   x_msg_count,
1454              p_data           =>   x_msg_data );
1455           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception error='||SQLERRM);
1456     END;
1457 
1458     -- get dafault dunning data
1459     procedure GET_DEFAULT_DUN_DATA(p_api_version              IN NUMBER := 1.0,
1460                                  p_init_msg_list            IN VARCHAR2,
1461                                  p_commit                   IN VARCHAR2,
1462                                  p_level                    in varchar2,
1463                                  p_source_id                in number,
1464                                  p_send_method              in varchar2,
1465                                  p_resend                   IN VARCHAR2 ,
1466                                  p_object_code              IN VARCHAR2 ,
1467                                  p_object_id                IN NUMBER,
1468                                  p_fulfillment_bind_tbl     in out nocopy IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL,
1469                                  x_return_status            OUT NOCOPY VARCHAR2,
1470                                  x_msg_count                OUT NOCOPY NUMBER,
1471                                  x_msg_data                 OUT NOCOPY VARCHAR2)
1472 
1473     is
1474 
1475         l_fulfillment_bind_tbl    IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
1476         l_bind_count              number;
1477         l_del_index               number;
1478         l_location_index          number;
1479         l_contact_index           number;
1480         l_site_use_index          number;
1481         l_cust_account_index      number;
1482         l_party_index             number;
1483         l_delinquency_id          number;
1484         l_customer_site_use_id    number;
1485         l_cust_account_id         number;
1486         l_party_id                number;
1487         l_location_id             number;
1488         l_contact_id              number;
1489         l_display                 number; --placeholder for display order
1490         l_api_name                constant varchar2(25) := 'GET_DEFAULT_DUN_DATA';
1491         Type refCur               is Ref Cursor;
1492         sql_cur                   refCur;
1493         vPLSQL                    VARCHAR2(2000);
1494         l_temp_site_use_id        number;
1495         l_contact_point_id        number;
1496         l_receipt_index           number;
1497         l_payment_index           number;
1498         l_promise_index           number;
1499         l_invoice_index           number;
1500         l_dispute_index           number;
1501         l_cm_request_index        number;
1502         l_adjustment_index        number;
1503         l_contact_point_index     number;
1504         l_temp_party_id           number;
1505         l_temp_acct_id            number;
1506         l_dispute_id              number;
1507 
1508         cursor c_get_del_info(p_delinquency_id number) is
1509             select party_cust_id, cust_account_id, customer_site_use_id
1510             from iex_delinquencies_all
1511             where delinquency_id = p_delinquency_id;
1512 
1513         cursor c_get_acct_info(p_cust_account_id number) is
1514             select party_id
1515             from hz_cust_accounts
1516             where cust_account_id = p_cust_account_id;
1517 
1518         cursor c_get_site_info(p_site_use_id number) is
1519             select cust.party_id, cust.cust_account_id
1520             from hz_cust_accounts cust,
1521             hz_cust_acct_sites_all acc_site,
1522             hz_cust_site_uses_all site_use
1523             where site_use.site_use_id = p_site_use_id and
1524             site_use.cust_acct_site_id = acc_site.cust_acct_site_id and
1525             acc_site.cust_account_id = cust.cust_account_id;
1526 
1527         cursor c_get_dispute(p_cm_request_id number) is
1528             select dispute_id
1529             from IEX_DISPUTES
1530             where cm_request_id = p_cm_request_id;
1531 
1532         --Added for bug 9550221 gnramasa 20th Apr 2010
1533         cursor c_get_acc_info_from_inv(p_cust_trx_id number) is
1534             select customer_id
1535             from ar_payment_schedules_all
1536             where customer_trx_id = p_cust_trx_id;
1537 
1538     begin
1539 
1540         IF FND_API.to_Boolean( p_init_msg_list )
1541         THEN
1542             FND_MSG_PUB.initialize;
1543         END IF;
1544 
1545         x_return_status := FND_API.G_RET_STS_SUCCESS;
1546 
1547         WriteLog('----------' || l_api_name || '----------');
1548         WriteLog(l_api_name || ': input parameters:');
1549         WriteLog(l_api_name || ': p_level: ' || p_level);
1550         WriteLog(l_api_name || ': p_source_id: ' || p_source_id);
1551 
1552         l_fulfillment_bind_tbl    := p_fulfillment_bind_tbl;
1553         l_del_index               := 0;
1554         l_site_use_index          := 0;
1555         l_cust_account_index      := 0;
1556         l_party_index             := 0;
1557         l_location_id             := 0;
1558         l_contact_id              := 0;
1559         l_location_index          := 0;
1560         l_contact_index           := 0;
1561         l_receipt_index           := 0;
1562         l_payment_index           := 0;
1563         l_promise_index           := 0;
1564         l_invoice_index           := 0;
1565         l_dispute_index           := 0;
1566         l_cm_request_index        := 0;
1567         l_adjustment_index        := 0;
1568         l_contact_point_index     := 0;
1569 
1570         WriteLog(l_api_name || ': input bind table:');
1571         -- index all bind variables
1572         l_bind_count := l_fulfillment_bind_tbl.count;
1573         for k in 1..l_bind_count loop
1574 
1575           l_fulfillment_bind_tbl(k).key_name := upper(l_fulfillment_bind_tbl(k).key_name);
1576 
1577           WriteLog(l_api_name || ' - #' || k || ' - ' ||
1578               l_fulfillment_bind_tbl(k).key_name || ' = ' || l_fulfillment_bind_tbl(k).key_value);
1579 
1580         end loop;
1581 
1582         -- Adding and filling missing bind vars
1583         WriteLog(l_api_name || ': Adding and filling missing bind vars...');
1584 
1585         if p_resend = 'Y' then
1586 
1587             l_bind_count := l_bind_count + 1;
1588             if p_object_code = 'IEX_INVOICES' then
1589 
1590                 l_fulfillment_bind_tbl(l_bind_count).key_name := 'INVOICE_ID';
1591                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1592                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_object_id;
1593                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1594 
1595             elsif p_object_code = 'IEX_PAYMENT' then
1596 
1597                 l_fulfillment_bind_tbl(l_bind_count).key_name := 'PAYMENT_ID';
1598                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1599                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_object_id;
1600                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1601 
1602             elsif p_object_code = 'IEX_ADJUSTMENT' then
1603 
1604                 l_fulfillment_bind_tbl(l_bind_count).key_name := 'ADJUSTMENT_ID';
1605                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1606                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_object_id;
1607                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1608 
1609             elsif p_object_code = 'IEX_PROMISE' then
1610 
1611                 l_fulfillment_bind_tbl(l_bind_count).key_name := 'PROMISE_DETAIL_ID';
1612                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1613                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_object_id;
1614                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1615 
1616             elsif p_object_code = 'IEX_REVERSAL' then
1617 
1618                 l_fulfillment_bind_tbl(l_bind_count).key_name := 'RECEIPT_ID';
1619                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1620                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_object_id;
1621                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1622 
1623             elsif p_object_code = 'IEX_DISPUTE' then
1624 
1625                 -- this case for resend of dispute corespondance
1626                 open c_get_dispute(p_object_id);
1627                 fetch c_get_dispute into l_dispute_id;
1628                 close c_get_dispute;
1629 
1630                 if l_dispute_id is not null then
1631                     l_fulfillment_bind_tbl(l_bind_count).key_name := 'DISPUTE_ID';
1632                     l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1633                     l_fulfillment_bind_tbl(l_bind_count).key_value := l_dispute_id;
1634                     WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1635                 end if;
1636 
1637             elsif p_object_code = 'IEX_ACCOUNT' then
1638 
1639                 l_fulfillment_bind_tbl(l_bind_count).key_name := 'ACCOUNT_ID';
1640                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1641                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_object_id;
1642                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1643 
1644             elsif p_object_code = 'IEX_BILLTO' then
1645 
1646                 l_fulfillment_bind_tbl(l_bind_count).key_name := 'CUSTOMER_SITE_USE_ID';
1647                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1648                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_object_id;
1649                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1650 
1651             elsif p_object_code = 'IEX_DELINQUENCY' then
1652 
1653                 l_fulfillment_bind_tbl(l_bind_count).key_name := 'DELINQUENCY_ID';
1654                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1655                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_object_id;
1656                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1657 
1658             elsif p_object_code = 'IEX_STRATEGY' then
1659 
1660                 IF (p_level = 'CUSTOMER') then
1661                     l_fulfillment_bind_tbl(l_bind_count).key_name := 'PARTY_ID';
1662                     l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1663                     l_fulfillment_bind_tbl(l_bind_count).key_value := p_source_id;
1664                     WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1665                 ELSIF (p_level = 'ACCOUNT') then
1666                     l_fulfillment_bind_tbl(l_bind_count).key_name := 'ACCOUNT_ID';
1667                     l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1668                     l_fulfillment_bind_tbl(l_bind_count).key_value := p_source_id;
1669                     WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1670                 ELSIF (p_level = 'BILL_TO') then
1671                     l_fulfillment_bind_tbl(l_bind_count).key_name := 'CUSTOMER_SITE_USE_ID';
1672                     l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1673                     l_fulfillment_bind_tbl(l_bind_count).key_value := p_source_id;
1674                     WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1675                 ELSIF (p_level = 'DELINQUENCY') then
1676                     l_fulfillment_bind_tbl(l_bind_count).key_name := 'DELINQUENCY_ID';
1677                     l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1678                     l_fulfillment_bind_tbl(l_bind_count).key_value := p_source_id;
1679                     WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1680                 END IF;
1681 
1682             end if;
1683 
1684         end if;
1685 
1686         -- index all bind variables
1687         l_bind_count := l_fulfillment_bind_tbl.count;
1688         for k in 1..l_bind_count loop
1689 
1690           if l_fulfillment_bind_tbl(k).key_name = 'DELINQUENCY_ID' then
1691                 l_del_index          := k;
1692           elsif l_fulfillment_bind_tbl(k).key_name = 'CUSTOMER_SITE_USE_ID' then
1693                 l_site_use_index     := k;
1694           elsif l_fulfillment_bind_tbl(k).key_name = 'ACCOUNT_ID' or l_fulfillment_bind_tbl(k).key_name = 'CUST_ACCOUNT_ID' then
1695                 l_fulfillment_bind_tbl(k).key_name := 'ACCOUNT_ID';
1696                 l_cust_account_index := k;
1697           elsif l_fulfillment_bind_tbl(k).key_name = 'PARTY_ID' then
1698                 l_party_index        := k;
1699           elsif l_fulfillment_bind_tbl(k).key_name = 'LOCATION_ID' then
1700                 l_location_index     := k;
1701           elsif l_fulfillment_bind_tbl(k).key_name = 'CONTACT_ID' then
1702                 l_contact_index      := k;
1703           elsif l_fulfillment_bind_tbl(k).key_name = 'CONTACT_POINT_ID' then
1704                 l_contact_point_index      := k;
1705           elsif l_fulfillment_bind_tbl(k).key_name = 'RECEIPT_ID' then
1706                 l_receipt_index      := k;
1707           elsif l_fulfillment_bind_tbl(k).key_name = 'PAYMENT_ID' then
1708                 l_payment_index      := k;
1709           elsif l_fulfillment_bind_tbl(k).key_name = 'PROMISE_DETAIL_ID' then
1710                 l_promise_index      := k;
1711           elsif l_fulfillment_bind_tbl(k).key_name = 'INVOICE_ID' then
1712                 l_invoice_index      := k;
1713           elsif l_fulfillment_bind_tbl(k).key_name = 'DISPUTE_ID' then
1714                 l_dispute_index      := k;
1715           elsif l_fulfillment_bind_tbl(k).key_name = 'ADJUSTMENT_ID' then
1716                 l_adjustment_index   := k;
1717           end if;
1718 
1719         end loop;
1720 
1721         -- filling missing but required bind vars
1722         if p_level = 'CUSTOMER' then
1723 
1724             if l_party_index = 0 then
1725                 l_bind_count := l_bind_count + 1;
1726                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'PARTY_ID';
1727                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1728                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_source_id;
1729                 l_party_index := l_bind_count;
1730                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1731             elsif l_party_index > 0 and l_fulfillment_bind_tbl(l_party_index).key_value is null then
1732                 l_fulfillment_bind_tbl(l_party_index).key_value := p_source_id;
1733                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_party_index).key_name || ' value in bind table');
1734             end if;
1735 
1736             WriteLog(l_api_name || ': PARTY_ID: ' || l_fulfillment_bind_tbl(l_party_index).key_value);
1737 
1738     	--Start bug 9550221 gnramasa 20th Apr 2010
1739     	--Invoice letter query id: 39 need cust_account_id. Add this incase collections business level is CUSTOMER.
1740     	if p_object_code = 'IEX_INVOICES' then
1741     	    open c_get_acc_info_from_inv (p_object_id);
1742     	    fetch c_get_acc_info_from_inv into l_temp_acct_id;
1743     	    close c_get_acc_info_from_inv;
1744 
1745     	    l_bind_count := l_bind_count + 1;
1746     	    l_fulfillment_bind_tbl(l_bind_count).key_name  := 'ACCOUNT_ID';
1747     	    l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1748     	    l_fulfillment_bind_tbl(l_bind_count).key_value := l_temp_acct_id;
1749     	    WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1750     	end if;
1751     	--End bug 9550221 gnramasa 20th Apr 2010
1752 
1753         elsif p_level = 'ACCOUNT' then
1754 
1755             if l_cust_account_index = 0 then
1756                 l_bind_count := l_bind_count + 1;
1757                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'ACCOUNT_ID';
1758                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1759                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_source_id;
1760                 l_cust_account_index := l_bind_count;
1761                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1762             elsif l_cust_account_index > 0 and l_fulfillment_bind_tbl(l_cust_account_index).key_value is null then
1763                 l_fulfillment_bind_tbl(l_cust_account_index).key_value := p_source_id;
1764                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_cust_account_index).key_name || ' value in bind table');
1765             end if;
1766 
1767             open c_get_acct_info(l_fulfillment_bind_tbl(l_cust_account_index).key_value);
1768             fetch c_get_acct_info into l_temp_party_id;
1769             close c_get_acct_info;
1770 
1771             if l_party_index = 0 then
1772                 l_bind_count := l_bind_count + 1;
1773                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'PARTY_ID';
1774                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1775                 l_fulfillment_bind_tbl(l_bind_count).key_value := l_temp_party_id;
1776                 l_party_index := l_bind_count;
1777                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1778             elsif l_party_index > 0 and l_fulfillment_bind_tbl(l_party_index).key_value is null then
1779                 l_fulfillment_bind_tbl(l_party_index).key_value := l_temp_party_id;
1780                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_party_index).key_name || ' value in bind table');
1781             end if;
1782 
1783             WriteLog(l_api_name || ': PARTY_ID: ' || l_fulfillment_bind_tbl(l_party_index).key_value);
1784             WriteLog(l_api_name || ': ACCOUNT_ID: ' || l_fulfillment_bind_tbl(l_cust_account_index).key_value);
1785 
1786         elsif p_level = 'BILL_TO' then
1787 
1788             if l_site_use_index = 0 then
1789                 l_bind_count := l_bind_count + 1;
1790                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'CUSTOMER_SITE_USE_ID';
1791                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1792                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_source_id;
1793                 l_site_use_index := l_bind_count;
1794                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1795             elsif l_site_use_index > 0 and l_fulfillment_bind_tbl(l_site_use_index).key_value is null then
1796                 l_fulfillment_bind_tbl(l_site_use_index).key_value := p_source_id;
1797                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_site_use_index).key_name || ' value in bind table');
1798             end if;
1799 
1800             open c_get_site_info(l_fulfillment_bind_tbl(l_site_use_index).key_value);
1801             fetch c_get_site_info into l_temp_party_id, l_temp_acct_id;
1802             close c_get_site_info;
1803 
1804             if l_party_index = 0 then
1805                 l_bind_count := l_bind_count + 1;
1806                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'PARTY_ID';
1807                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1808                 l_fulfillment_bind_tbl(l_bind_count).key_value := l_temp_party_id;
1809                 l_party_index := l_bind_count;
1810                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1811             elsif l_party_index > 0 and l_fulfillment_bind_tbl(l_party_index).key_value is null then
1812                 l_fulfillment_bind_tbl(l_party_index).key_value := l_temp_party_id;
1813                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_party_index).key_name || ' value in bind table');
1814             end if;
1815 
1816             if l_cust_account_index = 0 then
1817                 l_bind_count := l_bind_count + 1;
1818                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'ACCOUNT_ID';
1819                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1820                 l_fulfillment_bind_tbl(l_bind_count).key_value := l_temp_acct_id;
1821                 l_cust_account_index := l_bind_count;
1822                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1823             elsif l_cust_account_index > 0 and l_fulfillment_bind_tbl(l_cust_account_index).key_value is null then
1824                 l_fulfillment_bind_tbl(l_cust_account_index).key_value := l_temp_acct_id;
1825                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_cust_account_index).key_name || ' value in bind table');
1826             end if;
1827 
1828             WriteLog(l_api_name || ': PARTY_ID: ' || l_fulfillment_bind_tbl(l_party_index).key_value);
1829             WriteLog(l_api_name || ': ACCOUNT_ID: ' || l_fulfillment_bind_tbl(l_cust_account_index).key_value);
1830             WriteLog(l_api_name || ': CUSTOMER_SITE_USE_ID: ' || l_fulfillment_bind_tbl(l_site_use_index).key_value);
1831 
1832         elsif p_level = 'DELINQUENCY' then
1833 
1834             if l_del_index = 0 then
1835                 l_bind_count := l_bind_count + 1;
1836                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'DELINQUENCY_ID';
1837                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1838                 l_fulfillment_bind_tbl(l_bind_count).key_value := p_source_id;
1839                 l_del_index := l_bind_count;
1840                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1841             elsif l_del_index > 0 and l_fulfillment_bind_tbl(l_del_index).key_value is null then
1842                 l_fulfillment_bind_tbl(l_del_index).key_value := p_source_id;
1843                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_del_index).key_name || ' value in bind table');
1844             end if;
1845 
1846             open c_get_del_info(l_fulfillment_bind_tbl(l_del_index).key_value);
1847             fetch c_get_del_info into l_temp_party_id, l_temp_acct_id, l_temp_site_use_id;
1848             close c_get_del_info;
1849 
1850             if l_party_index = 0 then
1851                 l_bind_count := l_bind_count + 1;
1852                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'PARTY_ID';
1853                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1854                 l_fulfillment_bind_tbl(l_bind_count).key_value := l_temp_party_id;
1855                 l_party_index := l_bind_count;
1856                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1857             elsif l_party_index > 0 and l_fulfillment_bind_tbl(l_party_index).key_value is null then
1858                 l_fulfillment_bind_tbl(l_party_index).key_value := l_temp_party_id;
1859                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_party_index).key_name || ' value in bind table');
1860             end if;
1861 
1862             if l_cust_account_index = 0 then
1863                 l_bind_count := l_bind_count + 1;
1864                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'ACCOUNT_ID';
1865                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1866                 l_fulfillment_bind_tbl(l_bind_count).key_value := l_temp_acct_id;
1867                 l_cust_account_index := l_bind_count;
1868                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1869             elsif l_cust_account_index > 0 and l_fulfillment_bind_tbl(l_cust_account_index).key_value is null then
1870                 l_fulfillment_bind_tbl(l_cust_account_index).key_value := l_temp_acct_id;
1871                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_cust_account_index).key_name || ' value in bind table');
1872             end if;
1873 
1874             if l_site_use_index = 0 then
1875                 l_bind_count := l_bind_count + 1;
1876                 l_fulfillment_bind_tbl(l_bind_count).key_name  := 'CUSTOMER_SITE_USE_ID';
1877                 l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1878                 l_fulfillment_bind_tbl(l_bind_count).key_value := l_temp_site_use_id;
1879                 l_site_use_index := l_bind_count;
1880                 WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1881             elsif l_site_use_index > 0 and l_fulfillment_bind_tbl(l_site_use_index).key_value is null then
1882                 l_fulfillment_bind_tbl(l_site_use_index).key_value := l_temp_site_use_id;
1883                 WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_site_use_index).key_name || ' value in bind table');
1884             end if;
1885 
1886             WriteLog(l_api_name || ': PARTY_ID: ' || l_fulfillment_bind_tbl(l_party_index).key_value);
1887             WriteLog(l_api_name || ': ACCOUNT_ID: ' || l_fulfillment_bind_tbl(l_cust_account_index).key_value);
1888             WriteLog(l_api_name || ': CUSTOMER_SITE_USE_ID: ' || l_fulfillment_bind_tbl(l_site_use_index).key_value);
1889             WriteLog(l_api_name || ': DELINQUENCY_ID: ' || l_fulfillment_bind_tbl(l_del_index).key_value);
1890 
1891         end if;
1892 
1893         WriteLog(l_api_name || ': Calling GET_DEFAULT_DUN_DEST...');
1894         GET_DEFAULT_DUN_DEST(p_api_version => 1.0,
1895                              p_init_msg_list => FND_API.G_TRUE,
1896                              p_commit => FND_API.G_FALSE,
1897                              p_level => p_level,
1898                              p_source_id => p_source_id,
1899                              p_send_method => p_send_method,
1900                              X_LOCATION_ID => l_location_id,
1901                              X_CONTACT_ID => l_contact_id,
1902                              X_CONTACT_POINT_ID => l_contact_point_id,
1903                              x_return_status => x_return_status,
1904                              x_msg_count => x_msg_count,
1905                              x_msg_data => x_msg_data);
1906 
1907         WriteLog('---------- continue ' || l_api_name || '----------');
1908         WriteLog(l_api_name || ': LOCATION_ID: ' || l_location_id);
1909         WriteLog(l_api_name || ': CONTACT_ID: ' || l_contact_id);
1910         WriteLog(l_api_name || ': CONTACT_POINT_ID: ' || l_contact_point_id);
1911 
1912         if l_location_index = 0 then
1913              l_bind_count := l_bind_count + 1;
1914              l_fulfillment_bind_tbl(l_bind_count).key_name  := 'LOCATION_ID';
1915              l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1916              l_fulfillment_bind_tbl(l_bind_count).key_value := l_location_id;
1917              l_location_index := l_bind_count;
1918              WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1919         elsif l_location_index > 0 and l_fulfillment_bind_tbl(l_location_index).key_value is null then
1920              l_fulfillment_bind_tbl(l_location_index).key_value := l_location_id;
1921              WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_location_index).key_name || ' value in bind table');
1922         end if;
1923 
1924         if l_contact_index = 0 then
1925              l_bind_count := l_bind_count + 1;
1926              l_fulfillment_bind_tbl(l_bind_count).key_name  := 'CONTACT_ID';
1927              l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1928              l_fulfillment_bind_tbl(l_bind_count).key_value := l_contact_id;
1929              l_contact_index := l_bind_count;
1930              WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1931         elsif l_contact_index > 0 and l_fulfillment_bind_tbl(l_contact_index).key_value is null then
1932              l_fulfillment_bind_tbl(l_contact_index).key_value := l_contact_id;
1933              WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_contact_index).key_name || ' value in bind table');
1934         end if;
1935 
1936         if l_contact_point_index = 0 then
1937              l_bind_count := l_bind_count + 1;
1938              l_fulfillment_bind_tbl(l_bind_count).key_name  := 'CONTACT_POINT_ID';
1939              l_fulfillment_bind_tbl(l_bind_count).key_type  := 'NUMBER';
1940              l_fulfillment_bind_tbl(l_bind_count).key_value := l_contact_point_id;
1941              l_contact_point_index := l_bind_count;
1942              WriteLog(l_api_name || ': Added ' || l_fulfillment_bind_tbl(l_bind_count).key_name || ' to bind table');
1943         elsif l_contact_point_index > 0 and l_fulfillment_bind_tbl(l_contact_point_index).key_value is null then
1944              l_fulfillment_bind_tbl(l_contact_point_index).key_value := l_contact_point_id;
1945              WriteLog(l_api_name || ': Updated ' || l_fulfillment_bind_tbl(l_contact_point_index).key_name || ' value in bind table');
1946         end if;
1947 
1948         -- print out output bind table
1949         WriteLog(l_api_name || ': output bind table:');
1950         l_bind_count := l_fulfillment_bind_tbl.count;
1951         for k in 1..l_bind_count loop
1952             WriteLog(l_api_name || ' - #' || k || ' - ' ||
1953               l_fulfillment_bind_tbl(k).key_name || ' = ' || l_fulfillment_bind_tbl(k).key_value);
1954         end loop;
1955 
1956         p_fulfillment_bind_tbl := l_fulfillment_bind_tbl;
1957 
1958         WriteLog(l_api_name || ': x_return_status: ' || x_return_status);
1959         WriteLog(l_api_name || ': x_msg_count: ' || x_msg_count);
1960 
1961     EXCEPTION
1962       WHEN FND_API.G_EXC_ERROR THEN
1963           x_return_status := FND_API.G_RET_STS_ERROR;
1964           FND_MSG_PUB.Count_And_Get
1965           (  p_count          =>   x_msg_count,
1966              p_data           =>   x_msg_data );
1967           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception error='||SQLERRM);
1968 
1969       WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1970           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1971           FND_MSG_PUB.Count_And_Get
1972           (  p_count          =>   x_msg_count,
1973              p_data           =>   x_msg_data );
1974           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception error='||SQLERRM);
1975 
1976       WHEN OTHERS THEN
1977           x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1978           FND_MSG_PUB.Count_And_Get
1979           (  p_count          =>   x_msg_count,
1980              p_data           =>   x_msg_data );
1981           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception error='||SQLERRM);
1982     end;
1983 
1984     Procedure Validate_Delinquency(
1985         P_Init_Msg_List              IN   VARCHAR2     ,
1986         P_Delinquency_ID             IN   NUMBER,
1987         X_Return_Status              OUT NOCOPY  VARCHAR2,
1988         X_Msg_Count                  OUT NOCOPY  NUMBER,
1989         X_Msg_Data                   OUT NOCOPY  VARCHAR2
1990         )
1991     IS
1992       CURSOR C_GET_Del (IN_del_ID NUMBER) IS
1993         SELECT delinquency_id
1994           FROM iex_delinquencies
1995          WHERE delinquency_ID = IN_del_ID;
1996       --
1997       l_delinquency_id NUMBER;
1998 
1999     BEGIN
2000           -- Initialize message list IF p_init_msg_list is set to TRUE.
2001           IF FND_API.to_Boolean( p_init_msg_list )
2002           THEN
2003               FND_MSG_PUB.initialize;
2004           END IF;
2005 
2006           -- Initialize API return status to SUCCESS
2007           x_return_status := FND_API.G_RET_STS_SUCCESS;
2008 
2009           IF P_delinquency_ID is NULL
2010              or  P_delinquency_ID = FND_API.G_MISS_NUM
2011           THEN
2012                     FND_MESSAGE.Set_Name('IEX', 'API_INVALID_ID');
2013                     FND_MESSAGE.Set_Token('COLUMN', 'delinquency_ID', FALSE);
2014                     FND_MESSAGE.Set_Token('VALUE', p_delinquency_id, FALSE);
2015                     FND_MSG_PUB.Add;
2016                     x_return_status := FND_API.G_RET_STS_ERROR;
2017 
2018           ELSE
2019 
2020               OPEN C_Get_Del (p_delinquency_id);
2021               FETCH C_Get_Del INTO l_delinquency_ID;
2022 
2023               IF (C_Get_Del%NOTFOUND)
2024               THEN
2025                 IF FND_MSG_PUB.CHECK_MSG_LEVEL (FND_MSG_PUB.G_MSG_LVL_ERROR)
2026                 THEN
2027                     FND_MESSAGE.Set_Name('IEX', 'API_INVALID_ID');
2028                     FND_MESSAGE.Set_Token('COLUMN', 'delinquency_ID', FALSE);
2029                     FND_MESSAGE.Set_Token('VALUE', p_delinquency_id, FALSE);
2030                     FND_MSG_PUB.Add;
2031                 END IF;
2032                 x_return_status := FND_API.G_RET_STS_ERROR;
2033               END IF;
2034               CLOSE C_GET_Del;
2035           END IF;
2036 
2037           -- Standard call to get message count and IF count is 1, get message info.
2038           FND_MSG_PUB.Count_And_Get
2039           (  p_count          =>   x_msg_count,
2040              p_data           =>   x_msg_data );
2041 
2042     END Validate_Delinquency;
2043 
2044     Procedure Create_AG_DN_XREF
2045                (p_api_version             IN NUMBER := 1.0,
2046                 p_init_msg_list           IN VARCHAR2 ,
2047                 p_commit                  IN VARCHAR2 ,
2048                 P_AG_DN_XREF_REC          IN IEX_DUNNING_PUB.AG_DN_XREF_REC_TYPE,
2049                 x_return_status           OUT NOCOPY VARCHAR2,
2050                 x_msg_count               OUT NOCOPY NUMBER,
2051                 x_msg_data                OUT NOCOPY VARCHAR2,
2052                 x_AG_DN_XREF_ID           OUT NOCOPY NUMBER)
2053     IS
2054         l_api_name                    CONSTANT VARCHAR2(30) := 'Create_AG_DN';
2055         l_api_version_number          CONSTANT NUMBER   := 1.0;
2056         l_return_status               VARCHAR2(1);
2057         l_msg_count                   NUMBER;
2058         l_msg_data                    VARCHAR2(32767);
2059         l_rowid                       Varchar2(50);
2060         l_AG_DN_XREF_REC              IEX_DUNNING_PUB.AG_DN_XREF_REC_TYPE ;
2061         errmsg                        VARCHAR2(32767);
2062 
2063     BEGIN
2064           -- Standard Start of API savepoint
2065           SAVEPOINT CREATE_AG_DN_PVT;
2066 
2067           l_ag_dn_xref_rec := p_ag_dn_xref_rec;
2068 
2069           -- Standard call to check for call compatibility.
2070           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
2071                                                p_api_version,
2072                                                l_api_name,
2073                                                G_PKG_NAME)
2074           THEN
2075               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
2076           END IF;
2077 
2078           -- Initialize message list if p_init_msg_list is set to TRUE.
2079           IF FND_API.to_Boolean( p_init_msg_list )
2080           THEN
2081               FND_MSG_PUB.initialize;
2082           END IF;
2083 
2084           WriteLog(l_api_name || G_PKG_NAME || ' ' || l_api_name || ' - Start');
2085 
2086           -- Initialize API return status to SUCCESS
2087           x_return_status := FND_API.G_RET_STS_SUCCESS;
2088 
2089           --
2090           -- API body
2091           --
2092           WriteLog(l_api_name || G_PKG_NAME || ' ' || l_api_name || ' - CreateAgDn:Calling Validation');
2093 
2094           -- Invoke validation procedures
2095           -- Validate Data
2096           -- Validate Aging_Bucket_line
2097           -- Validate Template
2098           -- Validate Score Range (for the same bucket_line_id, don't overlap)
2099           WriteLog(l_api_name || G_PKG_NAME || ' ' || l_api_name || ' -CreateAgDn:InsertRow');
2100 
2101           -- Create AG_DN_XREF
2102           IEX_AG_DN_PKG.insert_row(
2103               px_rowid                         => l_rowid
2104             , px_AG_DN_XREF_id                 => x_AG_DN_XREF_id
2105             , p_last_update_date               => sysdate
2106             , p_last_updated_by                => FND_GLOBAL.USER_ID
2107             , p_creation_date                  => sysdate
2108             , p_created_by                     => FND_GLOBAL.USER_ID
2109             , p_last_update_login              => FND_GLOBAL.USER_ID
2110             , p_aging_bucket_id                => l_AG_DN_XREF_rec.aging_bucket_id
2111             , p_aging_bucket_line_id           => l_AG_DN_XREF_rec.aging_bucket_line_id
2112             , p_callback_flag                  => l_AG_DN_XREF_rec.callback_flag
2113             , p_callback_days                  => l_AG_DN_XREF_rec.callback_days
2114             , p_fm_method                      => l_AG_DN_XREF_rec.fm_method
2115             , p_dunning_level                  => l_AG_DN_XREF_rec.dunning_level
2116             , p_template_id                    => l_AG_DN_XREF_rec.template_id
2117             , p_xdo_template_id                => l_AG_DN_XREF_rec.xdo_template_id
2118             , p_score_range_low                => l_AG_DN_XREF_rec.score_range_low
2119             , p_score_range_high               => l_AG_DN_XREF_rec.score_range_high
2120             , p_object_version_number          => l_AG_DN_XREF_rec.object_version_number
2121          );
2122 
2123           --
2124           -- End of API body
2125           --
2126 
2127           -- Standard check for p_commit
2128           IF FND_API.to_Boolean( p_commit )
2129           THEN
2130               COMMIT WORK;
2131           END IF;
2132 
2133           WriteLog(l_api_name || G_PKG_NAME || ' ' || l_api_name || ' - End');
2134 
2135           FND_MSG_PUB.Count_And_Get
2136           (  p_count          =>   x_msg_count,
2137              p_data           =>   x_msg_data
2138           );
2139 
2140     EXCEPTION
2141               WHEN FND_API.G_EXC_ERROR THEN
2142                   x_return_status := FND_API.G_RET_STS_ERROR;
2143                   FND_MSG_PUB.Count_And_Get
2144                   (  p_count          =>   x_msg_count,
2145                      p_data           =>   x_msg_data );
2146                   ROLLBACK TO CREATE_AG_DN_PVT;
2147                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
2148 
2149               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
2150                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2151                   FND_MSG_PUB.Count_And_Get
2152                   (  p_count          =>   x_msg_count,
2153                      p_data           =>   x_msg_data );
2154                   ROLLBACK TO CREATE_AG_DN_PVT;
2155                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
2156 
2157               WHEN OTHERS THEN
2158                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2159                   FND_MSG_PUB.Count_And_Get
2160                   (  p_count          =>   x_msg_count,
2161                      p_data           =>   x_msg_data );
2162                   ROLLBACK TO CREATE_AG_DN_PVT;
2163                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
2164 
2165     END CREATE_AG_DN_XREF;
2166 
2167     Procedure Update_AG_DN_XREF
2168                (p_api_version             IN NUMBER := 1.0,
2169                 p_init_msg_list           IN VARCHAR2 ,
2170                 p_commit                  IN VARCHAR2 ,
2171                 P_AG_DN_XREF_REC          IN IEX_DUNNING_PUB.AG_DN_XREF_REC_TYPE,
2172                 p_AG_DN_XREF_ID           IN NUMBER,
2173                 x_return_status           OUT NOCOPY VARCHAR2,
2174                 x_msg_count               OUT NOCOPY NUMBER,
2175                 x_msg_data                OUT NOCOPY VARCHAR2)
2176 
2177     IS
2178         CURSOR C_get_AG_DN_XREF_Rec (IN_AG_DN_XREF_ID NUMBER) is
2179            select  ROWID,
2180                    AG_DN_XREF_ID,
2181                    AGING_BUCKET_ID,
2182                    AGING_BUCKET_LINE_ID,
2183                    CALLBACK_FLAG,
2184                    CALLBACK_DAYS,
2185                    FM_METHOD,
2186                    TEMPLATE_ID,
2187                    XDO_TEMPLATE_ID,
2188                    SCORE_RANGE_LOW,
2189                    SCORE_RANGE_HIGH,
2190                    DUNNING_LEVEL,
2191                    OBJECT_VERSION_NUMBER ,
2192                    LAST_UPDATE_DATE,
2193                    LAST_UPDATED_BY,
2194                    CREATION_DATE,
2195                    CREATED_BY ,
2196                    LAST_UPDATE_LOGIN
2197              from iex_AG_DN_XREF
2198             where AG_DN_XREF_id = in_AG_DN_XREF_id
2199             FOR UPDATE NOWAIT;
2200         --
2201         l_api_name                    CONSTANT VARCHAR2(30) := 'Update_AG_DN';
2202         l_api_version_number          CONSTANT NUMBER   := 1.0;
2203         l_return_status   VARCHAR2(1);
2204         l_msg_count       NUMBER;
2205         l_msg_data        VARCHAR2(32767);
2206         l_rowid                       Varchar2(50);
2207         l_AG_DN_XREF_REC              IEX_DUNNING_PUB.AG_DN_XREF_REC_TYPE ;
2208         l_AG_DN_XREF_id               NUMBER ;
2209         l_AG_DN_XREF_REF_REC          IEX_DUNNING_PUB.AG_DN_XREF_REC_TYPE;
2210         errmsg                        VARCHAR2(32767);
2211 
2212     BEGIN
2213 
2214           -- Standard Start of API savepoint
2215           SAVEPOINT UPDATE_AG_DN_PVT;
2216 
2217           l_AG_DN_XREF_REC       := p_AG_DN_XREF_rec;
2218 
2219           -- Standard call to check for call compatibility.
2220           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
2221                              	             p_api_version,
2222                                                l_api_name,
2223                                                G_PKG_NAME)
2224           THEN
2225               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
2226           END IF;
2227 
2228           -- Initialize message list if p_init_msg_list is set to TRUE.
2229           IF FND_API.to_Boolean( p_init_msg_list )
2230           THEN
2231               FND_MSG_PUB.initialize;
2232           END IF;
2233 
2234           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
2235           x_return_status := FND_API.G_RET_STS_SUCCESS;
2236           --
2237           -- Api body
2238           --
2239           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Open C_GET_AGDN_XREF_REC');
2240           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - agdnxrefid='||l_ag_dn_xref_rec.ag_dn_xref_id);
2241 
2242           Open C_Get_AG_DN_XREF_Rec(l_AG_DN_XREF_rec.AG_DN_XREF_ID);
2243           Fetch C_Get_AG_DN_XREF_Rec into
2244              l_rowid,
2245              l_AG_DN_XREF_ref_rec.AG_DN_XREF_ID,
2246              l_AG_DN_XREF_ref_rec.AGING_BUCKET_ID,
2247              l_AG_DN_XREF_ref_rec.aging_bucket_line_id,
2248              l_AG_DN_XREF_ref_rec.callback_FLAG,
2249              l_AG_DN_XREF_ref_rec.callback_DAYS,
2250              l_AG_DN_XREF_ref_rec.fm_method,
2251              l_AG_DN_XREF_ref_rec.template_id,
2252              l_AG_DN_XREF_ref_rec.xdo_template_id,
2253              l_AG_DN_XREF_ref_rec.score_range_low,
2254              l_AG_DN_XREF_ref_rec.score_range_high,
2255              l_AG_DN_XREF_ref_rec.dunning_level,
2256              l_AG_DN_XREF_ref_rec.object_version_number,
2257              l_AG_DN_XREF_ref_rec.LAST_UPDATE_DATE,
2258              l_AG_DN_XREF_ref_rec.LAST_UPDATED_BY,
2259              l_AG_DN_XREF_ref_rec.CREATION_DATE,
2260              l_AG_DN_XREF_ref_rec.CREATED_BY,
2261              l_AG_DN_XREF_ref_rec.LAST_UPDATE_LOGIN;
2262 
2263           If ( C_Get_AG_DN_XREF_REC%NOTFOUND) Then
2264             IF FND_MSG_PUB.Check_Msg_Level (FND_MSG_PUB.G_MSG_LVL_ERROR)
2265             THEN
2266                 FND_MESSAGE.Set_Name('AS', 'API_MISSING_UPDATE_TARGET');
2267                 FND_MESSAGE.Set_Token ('INFO', 'IEX_AG_DN_XREF', FALSE);
2268                 FND_MSG_PUB.Add;
2269             END IF;
2270             raise FND_API.G_EXC_ERROR;
2271           END IF;
2272 
2273           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close C_GET_AGDN_XREF_REC');
2274           Close C_Get_AG_DN_XREF_Rec;
2275 
2276           If (l_ag_Dn_xref_rec.last_update_date is NULL or
2277              l_ag_Dn_xref_rec.last_update_date = FND_API.G_MISS_Date )
2278           Then
2279               IF FND_MSG_PUB.Check_Msg_Level (FND_MSG_PUB.G_MSG_LVL_ERROR)
2280               THEN
2281                   FND_MESSAGE.Set_Name('IEX', 'API_MISSING_ID');
2282                   FND_MESSAGE.Set_Token('COLUMN', 'Last_Update_Date', FALSE);
2283                   FND_MSG_PUB.ADD;
2284               END IF;
2285               raise FND_API.G_EXC_ERROR;
2286           End if;
2287           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Transfer Data into target rec');
2288 
2289           -- Transfer Data into target record
2290           l_ag_dn_xref_rec.CREATION_DATE := l_ag_dn_xref_ref_rec.CREATION_DATE;
2291           l_ag_dn_xref_rec.CREATED_BY := l_ag_dn_xref_ref_rec.CREATED_BY;
2292 
2293           -- dont update aging_bucket_id and aging_bucket_line_id
2294           -- dont update dunning_level
2295 
2296           IF (l_ag_dn_xref_rec.callback_flag = FND_API.G_MISS_CHAR or
2297               l_ag_dn_xref_rec.callback_flag is null ) Then
2298              l_ag_dn_xref_rec.callback_flag := l_ag_dn_xref_REF_rec.callback_flag;
2299           END IF;
2300           IF (l_ag_dn_xref_rec.callback_days = FND_API.G_MISS_NUM or
2301               l_ag_dn_xref_rec.callback_days is null ) Then
2302              l_ag_dn_xref_rec.callback_days := l_ag_dn_xref_REF_rec.callback_days;
2303           END IF;
2304           IF (l_ag_dn_xref_rec.fm_method = FND_API.G_MISS_CHAR or
2305               l_ag_dn_xref_rec.fm_method is null) Then
2306              l_ag_dn_xref_rec.fm_method := l_ag_dn_xref_REF_rec.fm_method;
2307           END IF;
2308           IF (l_ag_dn_xref_rec.template_ID = FND_API.G_MISS_NUM or
2309               l_ag_dn_xref_rec.template_id is null ) Then
2310              l_ag_dn_xref_rec.template_ID := l_ag_dn_xref_ref_rec.template_ID;
2311           END IF;
2312           IF (l_ag_dn_xref_rec.xdo_template_ID = FND_API.G_MISS_NUM or
2313               l_ag_dn_xref_rec.xdo_template_id is null ) Then
2314              l_ag_dn_xref_rec.xdo_template_ID := l_ag_dn_xref_ref_rec.xdo_template_ID;
2315           END IF;
2316           IF (l_ag_dn_xref_rec.score_range_low = FND_API.G_MISS_NUM or
2317               l_ag_dn_xref_rec.score_range_low is null ) Then
2318              l_ag_dn_xref_rec.score_range_low := l_ag_dn_xref_ref_rec.score_range_low;
2319           END IF;
2320           IF (l_ag_dn_xref_rec.score_range_high = FND_API.G_MISS_NUM or
2321               l_ag_dn_xref_rec.score_range_high is null ) Then
2322              l_ag_dn_xref_rec.score_range_high := l_ag_dn_xref_ref_rec.score_range_high;
2323           END IF;
2324           IF (l_ag_dn_xref_rec.object_version_number = FND_API.G_MISS_NUM or
2325               l_ag_dn_xref_rec.object_version_number is null ) Then
2326              l_ag_dn_xref_rec.object_version_number := l_ag_dn_xref_ref_rec.object_version_number;
2327           END IF;
2328 
2329           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UpdateRow ');
2330 
2331           IEX_AG_DN_PKG.update_row(
2332               p_rowid                          => l_rowid
2333             , p_AG_DN_XREF_id                  => p_AG_DN_XREF_id
2334             , p_last_update_date               => sysdate
2335             , p_last_updated_by                => FND_GLOBAL.USER_ID
2336             , p_creation_date                  => l_AG_DN_XREF_rec.creation_date
2337             , p_created_by                     => l_AG_DN_XREF_rec.created_by
2338             , p_last_update_login              => FND_GLOBAL.USER_ID
2339             , p_aging_bucket_id                => l_AG_DN_XREF_rec.aging_bucket_id
2340             , p_aging_bucket_line_id           => l_AG_DN_XREF_rec.aging_bucket_line_id
2341             , p_callback_flag                  => l_AG_DN_XREF_rec.callback_flag
2342             , p_callback_days                  => l_AG_DN_XREF_rec.callback_days
2343             , p_fm_method                      => l_AG_DN_XREF_rec.fm_method
2344             , p_template_id                    => l_AG_DN_XREF_rec.template_id
2345             , p_xdo_template_id                => l_AG_DN_XREF_rec.xdo_template_id
2346             , p_score_range_low                => l_AG_DN_XREF_rec.score_range_low
2347             , p_score_range_high               => l_AG_DN_XREF_rec.score_range_high
2348             , p_dunning_level                  => l_AG_DN_XREF_rec.dunning_level
2349             , p_object_version_number          => l_ag_dn_xref_rec.object_version_number
2350          );
2351 
2352           --
2353           -- End of API body.
2354           --
2355 
2356           -- Standard check for p_commit
2357           IF FND_API.to_Boolean( p_commit )
2358           THEN
2359               COMMIT WORK;
2360           END IF;
2361 
2362           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UpdateAgDn:End ');
2363 
2364           FND_MSG_PUB.Count_And_Get
2365           (  p_count          =>   x_msg_count,
2366              p_data           =>   x_msg_data );
2367 
2368           EXCEPTION
2369               WHEN FND_API.G_EXC_ERROR THEN
2370                   x_return_status := FND_API.G_RET_STS_ERROR;
2371                   FND_MSG_PUB.Count_And_Get
2372                   (  p_count          =>   x_msg_count,
2373                      p_data           =>   x_msg_data );
2374                   ROLLBACK TO UPDATE_AG_DN_PVT;
2375                   errmsg := SQLERRM;
2376                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
2377 
2378               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
2379                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2380                   FND_MSG_PUB.Count_And_Get
2381                   (  p_count          =>   x_msg_count,
2382                      p_data           =>   x_msg_data );
2383                   ROLLBACK TO UPDATE_AG_DN_PVT;
2384                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
2385 
2386               WHEN OTHERS THEN
2387                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2388                   FND_MSG_PUB.Count_And_Get
2389                   (  p_count          =>   x_msg_count,
2390                      p_data           =>   x_msg_data );
2391                   ROLLBACK TO UPDATE_AG_DN_PVT;
2392                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
2393 
2394     END Update_AG_DN_XREF;
2395 
2396     Procedure Delete_AG_DN_XREF
2397                (p_api_version             IN NUMBER := 1.0,
2398                 p_init_msg_list           IN VARCHAR2 ,
2399                 p_commit                  IN VARCHAR2 ,
2400                 P_AG_DN_XREF_ID           IN NUMBER,
2401                 x_return_status           OUT NOCOPY VARCHAR2,
2402                 x_msg_count               OUT NOCOPY NUMBER,
2403                 x_msg_data                OUT NOCOPY VARCHAR2)
2404 
2405     IS
2406         CURSOR C_GET_AG_DN_XREF (IN_AG_DN_XREF_ID NUMBER) IS
2407           SELECT AG_DN_XREF_ID
2408             FROM IEX_AG_DN_XREF
2409            WHERE AG_DN_XREF_ID = IN_AG_DN_XREF_ID;
2410         --
2411         l_AG_DN_XREF_id         NUMBER;
2412         l_api_name              CONSTANT VARCHAR2(30) := 'Delete_AG_DN';
2413         l_api_version_number    CONSTANT NUMBER   := 1.0;
2414         l_return_status         VARCHAR2(1);
2415         l_msg_count             NUMBER;
2416         l_msg_data              VARCHAR2(32767);
2417         l_rowid                 Varchar2(50);
2418         errmsg                  VARCHAR2(32767);
2419 
2420     BEGIN
2421           -- Standard Start of API savepoint
2422           SAVEPOINT DELETE_AG_DN_PVT;
2423 
2424           -- Standard call to check for call compatibility.
2425           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
2426                                                p_api_version,
2427                                                l_api_name,
2428                                                G_PKG_NAME)
2429           THEN
2430               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
2431           END IF;
2432 
2433           -- Initialize message list if p_init_msg_list is set to TRUE.
2434           IF FND_API.to_Boolean( p_init_msg_list )
2435           THEN
2436               FND_MSG_PUB.initialize;
2437           END IF;
2438 
2439           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
2440           x_return_status := FND_API.G_RET_STS_SUCCESS;
2441           --
2442           -- Api body
2443           --
2444           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Open Cursor');
2445 
2446           Open C_Get_AG_DN_XREF(p_AG_DN_XREF_id);
2447           Fetch C_Get_AG_DN_XREF into
2448              l_AG_DN_XREF_ID;
2449 
2450           If ( C_Get_AG_DN_XREF%NOTFOUND) Then
2451             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - NotFound');
2452 
2453             IF FND_MSG_PUB.Check_Msg_Level (FND_MSG_PUB.G_MSG_LVL_ERROR)
2454             THEN
2455                 FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
2456                 FND_MESSAGE.Set_Token ('INFO', 'IEX_AG_DN_XREF', FALSE);
2457                 FND_MSG_PUB.Add;
2458             END IF;
2459             raise FND_API.G_EXC_ERROR;
2460           END IF;
2461 
2462           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - agdnxerfid='||l_ag_dn_xref_id);
2463           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close Cursor');
2464           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Delete Row');
2465           Close C_Get_AG_DN_XREF;
2466 
2467           -- Invoke table handler
2468           IEX_AG_DN_PKG.Delete_Row(
2469                  p_AG_DN_XREF_ID  => l_AG_DN_XREF_ID);
2470 
2471           IF x_return_status = FND_API.G_RET_STS_ERROR then
2472                     raise FND_API.G_EXC_ERROR;
2473           elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
2474                    raise FND_API.G_EXC_UNEXPECTED_ERROR;
2475           END IF;
2476 
2477           --
2478           -- End of API body
2479           --
2480 
2481           -- Standard check for p_commit
2482           IF FND_API.to_Boolean( p_commit )
2483           THEN
2484               COMMIT WORK;
2485           END IF;
2486 
2487           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End');
2488 
2489           FND_MSG_PUB.Count_And_Get
2490           (  p_count          =>   x_msg_count,
2491              p_data           =>   x_msg_data );
2492 
2493           EXCEPTION
2494               WHEN FND_API.G_EXC_ERROR THEN
2495                   x_return_status := FND_API.G_RET_STS_ERROR;
2496                   FND_MSG_PUB.Count_And_Get
2497                   (  p_count          =>   x_msg_count,
2498                      p_data           =>   x_msg_data );
2499                   ROLLBACK TO DELETE_AG_DN_PVT;
2500                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DeleteAgDn:error='||SQLERRM);
2501 
2502               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
2503                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2504                   FND_MSG_PUB.Count_And_Get
2505                   (  p_count          =>   x_msg_count,
2506                      p_data           =>   x_msg_data );
2507                   ROLLBACK TO DELETE_AG_DN_PVT;
2508                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DeleteAgDn:error='||SQLERRM);
2509 
2510               WHEN OTHERS THEN
2511                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2512                   FND_MSG_PUB.Count_And_Get
2513                   (  p_count          =>   x_msg_count,
2514                      p_data           =>   x_msg_data );
2515                   ROLLBACK TO DELETE_AG_DN_PVT;
2516                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DeleteAgDn:error='||SQLERRM);
2517 
2518     END Delete_AG_DN_XREF;
2519 
2520     Procedure Create_Dunning
2521                (p_api_version             IN NUMBER := 1.0,
2522                 p_init_msg_list           IN VARCHAR2 ,
2523                 p_commit                  IN VARCHAR2 ,
2524                 P_Dunning_REC             IN IEX_DUNNING_PUB.DUNNING_REC_TYPE,
2525                 x_return_status           OUT NOCOPY VARCHAR2,
2526                 x_msg_count               OUT NOCOPY NUMBER,
2527                 x_msg_data                OUT NOCOPY VARCHAR2,
2528                 x_Dunning_ID              OUT NOCOPY NUMBER)
2529     IS
2530         l_api_name                    CONSTANT VARCHAR2(30) := 'Create_Dunning';
2531         l_api_version_number          CONSTANT NUMBER   := 1.0;
2532         l_return_status               VARCHAR2(1);
2533         l_msg_count                   NUMBER;
2534         l_msg_data                    VARCHAR2(32767);
2535         l_rowid                       Varchar2(50);
2536         l_Dunning_REC                 IEX_DUNNING_PUB.Dunning_REC_TYPE ;
2537         errmsg                        VARCHAR2(32767);
2538 
2539     BEGIN
2540           -- Standard Start of API savepoint
2541           SAVEPOINT CREATE_DUNNING_PVT;
2542 
2543           l_dunning_rec := p_dunning_rec;
2544 
2545           -- Standard call to check for call compatibility.
2546           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
2547                                                p_api_version,
2548                                                l_api_name,
2549                                                G_PKG_NAME)
2550           THEN
2551               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
2552           END IF;
2553 
2554           -- Initialize message list if p_init_msg_list is set to TRUE.
2555           IF FND_API.to_Boolean( p_init_msg_list )
2556           THEN
2557               FND_MSG_PUB.initialize;
2558           END IF;
2559 
2560           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - START');
2561           x_return_status := FND_API.G_RET_STS_SUCCESS;
2562           --
2563           -- API body
2564           --
2565           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
2566           --Start adding for bug 8489610 by gnramasa 14-May-09
2567           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_rec.dunning_mode :'||l_dunning_rec.dunning_mode);
2568           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_rec.confirmation_mode : '||l_dunning_rec.confirmation_mode);
2569           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_rec.parent_dunning_id  : '||l_dunning_rec.parent_dunning_id);
2570           -- Create Dunning
2571           IEX_Dunnings_PKG.insert_row(
2572               px_rowid                         => l_rowid
2573             , px_dunning_id                    => x_dunning_id
2574             , p_last_update_date               => sysdate
2575             , p_last_updated_by                => FND_GLOBAL.USER_ID
2576             , p_creation_date                  => sysdate
2577             , p_created_by                     => FND_GLOBAL.USER_ID
2578             , p_last_update_login              => FND_GLOBAL.USER_ID
2579     	--			, p_request_id                     => FND_GLOBAL.CONC_REQUEST_ID
2580     	, p_request_id                     => l_dunning_rec.request_id
2581             , p_template_id                    => l_dunning_rec.template_id
2582             , p_callback_yn                    => l_dunning_rec.callback_yn
2583             , p_callback_date                  => l_dunning_rec.callback_date
2584             , p_campaign_sched_id              => l_dunning_rec.campaign_sched_id
2585             , p_status                         => l_dunning_rec.status
2586             , p_delinquency_id                 => l_dunning_rec.delinquency_id
2587             , p_ffm_request_id                 => l_dunning_rec.ffm_request_id
2588             , p_xml_request_id                 => l_dunning_rec.xml_request_id
2589             , p_xml_template_id                => l_dunning_rec.xml_template_id
2590             , p_object_id                      => l_dunning_rec.object_id
2591             , p_object_type                    => l_dunning_rec.object_type
2592             , p_dunning_object_id              => l_dunning_rec.dunning_object_id
2593             , p_dunning_level                  => l_dunning_rec.dunning_level
2594             , p_dunning_method                 => l_dunning_rec.dunning_method
2595             , p_amount_due_remaining           => l_dunning_rec.amount_due_remaining
2596             , p_currency_code                  => l_dunning_rec.currency_code
2597             , p_delivery_status                => l_dunning_rec.delivery_status
2598             , p_parent_dunning_id              => l_dunning_rec.PARENT_DUNNING_ID
2599             , p_dunning_plan_id                => l_dunning_rec.dunning_plan_id
2600             , p_contact_destination            => l_dunning_rec.contact_destination
2601             , p_contact_party_id               => l_dunning_rec.contact_party_id
2602     	, p_dunning_mode		   => l_dunning_rec.dunning_mode
2603     	, p_confirmation_mode              => l_dunning_rec.confirmation_mode
2604     	, p_org_id                         => l_dunning_rec.org_id
2605     	, p_ag_dn_xref_id                  => l_dunning_rec.ag_dn_xref_id
2606     	, p_correspondence_date            => nvl(l_dunning_rec.correspondence_date,trunc(sysdate))
2607     	, p_addt_xml_template_id           => l_dunning_rec.addt_xml_template_id	--added for bug 9970624 gnramasa 4th Aug 10
2608     	, p_addt_delivery_status           => l_dunning_rec.addt_delivery_status	--added for bug 9970624 gnramasa 4th Aug 10
2609     	, p_as_of_date                     => nvl(l_dunning_rec.as_of_date,trunc(sysdate))
2610           );
2611           --End adding for bug 8489610 by gnramasa 14-May-09
2612 
2613           IF x_return_status = FND_API.G_RET_STS_ERROR then
2614                     raise FND_API.G_EXC_ERROR;
2615           elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
2616                    raise FND_API.G_EXC_UNEXPECTED_ERROR;
2617           END IF;
2618 
2619           --
2620           -- End of API body
2621           --
2622 
2623           -- Standard check for p_commit
2624           IF FND_API.to_Boolean( p_commit )
2625           THEN
2626               COMMIT WORK;
2627           END IF;
2628 
2629           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
2630           FND_MSG_PUB.Count_And_Get
2631           (  p_count          =>   x_msg_count,
2632              p_data           =>   x_msg_data
2633           );
2634 
2635     EXCEPTION
2636               WHEN FND_API.G_EXC_ERROR THEN
2637                   x_return_status := FND_API.G_RET_STS_ERROR;
2638                   FND_MSG_PUB.Count_And_Get
2639                   (  p_count          =>   x_msg_count,
2640                      p_data           =>   x_msg_data );
2641                   ROLLBACK TO CREATE_DUNNING_PVT;
2642                   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'exception ' || SQLERRM);
2643 
2644               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
2645                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2646                   FND_MSG_PUB.Count_And_Get
2647                   (  p_count          =>   x_msg_count,
2648                      p_data           =>   x_msg_data );
2649                   ROLLBACK TO CREATE_DUNNING_PVT;
2650                   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'error ' || SQLERRM);
2651 
2652               WHEN OTHERS THEN
2653                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2654                   FND_MSG_PUB.Count_And_Get
2655                   (  p_count          =>   x_msg_count,
2656                      p_data           =>   x_msg_data );
2657                   ROLLBACK TO CREATE_DUNNING_PVT;
2658                   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'error ' || SQLERRM);
2659 
2660     END CREATE_DUNNING;
2661 
2662     Procedure Create_Staged_Dunning
2663                (p_api_version             IN NUMBER := 1.0,
2664                 p_init_msg_list           IN VARCHAR2 ,
2665                 p_commit                  IN VARCHAR2 ,
2666                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
2667     	    p_dunning_id	      IN NUMBER,
2668     	    p_correspondence_date     IN DATE,
2669     	    p_ag_dn_xref_id           IN NUMBER,
2670                 p_running_level           IN VARCHAR2,
2671     	    p_grace_days              IN NUMBER,
2672     	    p_include_dispute_items   IN VARCHAR2,
2673     	    p_dunning_mode            IN VARCHAR2,
2674     	    p_inc_inv_curr            IN IEX_UTILITIES.INC_INV_CURR_TBL,
2675                 x_return_status           OUT NOCOPY VARCHAR2,
2676                 x_msg_count               OUT NOCOPY NUMBER,
2677                 x_msg_data                OUT NOCOPY VARCHAR2)
2678     IS
2679         l_api_name                    CONSTANT VARCHAR2(30) := 'Create_Staged_Dunning';
2680         l_api_version_number          CONSTANT NUMBER   := 1.0;
2681         l_return_status               VARCHAR2(1);
2682         l_msg_count                   NUMBER;
2683         l_msg_data                    VARCHAR2(32767);
2684         l_rowid                       Varchar2(50);
2685         l_Dunning_REC                 IEX_DUNNING_PUB.Dunning_REC_TYPE ;
2686         errmsg                        VARCHAR2(32767);
2687 
2688         cursor c_dunning_plan_lines(p_ag_dn_xref_id number) is
2689         select ag_dn_xref_id,
2690                range_of_dunning_level_from,
2691     	   range_of_dunning_level_to,
2692     	   min_days_between_dunning
2693         from iex_ag_dn_xref
2694         where AG_DN_XREF_ID = p_ag_dn_xref_id
2695         order by AG_DN_XREF_ID;
2696 
2697         l_dunning_plan_lines	c_dunning_plan_lines%rowtype;
2698         Type refCur			is Ref Cursor;
2699         sql_cur			refCur;
2700         sql_cur1			refCur;
2701         sql_cur2			refCur;
2702         sql_cur3			refCur;
2703         vPLSQL			VARCHAR2(2000);
2704         vPLSQL1			VARCHAR2(2000);
2705         vPLSQL2			VARCHAR2(2000);
2706         vPLSQL3			VARCHAR2(2000);
2707         l_delinquency_id		number;
2708         l_transaction_id		number;
2709         l_customer_trx_id		number;
2710         l_payment_schedule_id	number;
2711         l_object_id			number;
2712 
2713         cursor c_dunn_plan_line_dtls (p_ag_dn_xref_id number) is
2714         select nvl(dunn.include_current ,'N'),
2715                nvl(dunn.include_unused_payments_flag,'N')
2716         from iex_ag_dn_xref xref,
2717              iex_dunning_plans_b dunn
2718         where AG_DN_XREF_ID = p_ag_dn_xref_id
2719         and xref.dunning_plan_id = dunn.dunning_plan_id;
2720 
2721         x_dunning_trx_id	number;
2722         l_stage	        number;
2723         l_include_curr_inv  varchar2(10);
2724         l_include_unapp_rec varchar2(10);
2725         l_curr_count        number := 0;
2726         iex_dunn_trx_counter number := 0;
2727         t_id number;
2728         t_code varchar2(50);
2729     BEGIN
2730           -- Standard Start of API savepoint
2731           SAVEPOINT CREATE_STAGED_DUNNING_PVT;
2732 
2733           -- Standard call to check for call compatibility.
2734           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
2735                                                p_api_version,
2736                                                l_api_name,
2737                                                G_PKG_NAME)
2738           THEN
2739               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
2740           END IF;
2741 
2742           -- Initialize message list if p_init_msg_list is set to TRUE.
2743           IF FND_API.to_Boolean( p_init_msg_list )
2744           THEN
2745               FND_MSG_PUB.initialize;
2746           END IF;
2747 
2748           l_curr_count := p_inc_inv_curr.count;
2749 
2750           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - START');
2751           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_dunning_id :'|| p_dunning_id);
2752           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_grace_days :'|| p_grace_days);
2753           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_include_dispute_items :'|| p_include_dispute_items);
2754           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_curr_count :'|| l_curr_count);
2755 
2756 
2757 
2758           x_return_status := FND_API.G_RET_STS_SUCCESS;
2759           --
2760           -- API body
2761           --
2762 
2763           OPEN c_dunning_plan_lines (p_ag_dn_xref_id);
2764           fetch c_dunning_plan_lines into l_dunning_plan_lines;
2765           close c_dunning_plan_lines;
2766 
2767           open c_dunn_plan_line_dtls (p_ag_dn_xref_id);
2768           fetch c_dunn_plan_line_dtls into l_include_curr_inv, l_include_unapp_rec;
2769           close c_dunn_plan_line_dtls;
2770 
2771           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.ag_dn_xref_id='||l_dunning_plan_lines.ag_dn_xref_id);
2772           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_plan_lines.range_of_dunning_level_from='||l_dunning_plan_lines.range_of_dunning_level_from);
2773           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_plan_lines.range_of_dunning_level_to='||l_dunning_plan_lines.range_of_dunning_level_to);
2774           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_plan_lines.min_days_between_dunning='||l_dunning_plan_lines.min_days_between_dunning);
2775 
2776           if (p_running_level = 'CUSTOMER') then
2777     		     l_object_id	:= p_delinquencies_tbl(1).party_cust_id;
2778         	elsif  (p_running_level = 'ACCOUNT') then
2779     	       l_object_id	:= p_delinquencies_tbl(1).cust_account_id;
2780     	    elsif  (p_running_level = 'BILL_TO') then
2781     		     l_object_id	:= p_delinquencies_tbl(1).customer_site_use_id;
2782 
2783              -- begin Bills Receivables
2784              begin
2785                t_id := l_object_id;
2786                select site_use_code into t_code from hz_cust_site_uses_all where site_use_id = l_object_id;
2787                if t_code = 'BILL_TO' then
2788                   t_id := iex_utilities.get_BR_DrweeSiteID(l_object_id);
2789                end if;
2790               exception
2791                 when others then t_id := l_object_id;
2792              end;
2793              -- end Bills Receivables
2794 
2795           end if;
2796 
2797 
2798     	    for i in l_dunning_plan_lines.range_of_dunning_level_from..l_dunning_plan_lines.range_of_dunning_level_to
2799     	    loop
2800     		    l_stage	:= i-1;
2801     		  if i = 1 then
2802     			   for j in 1..l_curr_count loop
2803     				     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_inc_inv_curr(' || j || ') : '|| p_inc_inv_curr(j));
2804 
2805     				     vPLSQL := 'select  del.delinquency_id, ' ||
2806     				        '          del.transaction_id, ' ||
2807     					'	   del.payment_schedule_id ' ||
2808     					'    from iex_delinquencies del, ' ||
2809     					'	 ar_payment_schedules arp ' ||
2810     					'    where del.payment_schedule_id = arp.payment_schedule_id ' ||
2811     					'    and del.status in (''DELINQUENT'',''PREDELINQUENT'') ' ||
2812     					'    and del.staged_dunning_level is NULL ' ||
2813     					'    and arp.invoice_currency_code = :p_inv_curr ' ||
2814     					'    and (trunc(arp.due_date) + :p_min_days_bw_dun) <= :p_corr_date ' ||
2815     					'    and (trunc(arp.due_date) + :p_gra_days) <= :p_corr_date ' ||
2816     					'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ';
2817 
2818 
2819 
2820     				if (p_running_level = 'CUSTOMER') then
2821     				      vPLSQL3		:= '    and del.party_cust_id = :p_party_id ' ||
2822     							   '    order by del.payment_schedule_id';
2823     				elsif  (p_running_level = 'ACCOUNT') then
2824     				      vPLSQL3		:= '    and del.cust_account_id = :p_cust_acct_id ' ||
2825     				      --Begin Bug 10401991 03-feb-2011 barathsr
2826     				                           '    and arp.amount_due_remaining >= NVL ( '||
2827     							   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
2828     							   '	FROM hz_cust_profile_amts '||
2829     							   '	WHERE site_use_id  IS NULL '||
2830     							   '	AND cust_account_id = arp.customer_id '||
2831     							   '	AND currency_code   = arp.invoice_currency_code),0) '||
2832     				                           '    order by del.payment_schedule_id';
2833     				      --End Bug 10401991 03-feb-2011 barathsr
2834     				elsif  (p_running_level = 'BILL_TO') then
2835     				      -- vPLSQL3		:= '    and del.customer_site_use_id  IN ( :p_site_use_id,24388) ' ||
2836                    vPLSQL3		:= '    and del.customer_site_use_id  IN ( :p_site_use_id,'||t_id||')' ||   -- Bills Receivabless
2837     				         --Begin Bug 10401991 03-feb-2011 barathsr
2838     				         '  and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
2839     							   '	from hz_cust_profile_amts '||
2840     							   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
2841     							   '	and currency_code = arp.invoice_currency_code),0) '||
2842     				                           '    order by del.payment_schedule_id';
2843     				       --End Bug 10401991 03-feb-2011 barathsr
2844     				end if;
2845     				vPLSQL	:= vPLSQL || vPLSQL3;
2846 
2847     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - vPLSQL :'||vPLSQL);
2848     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_plan_lines.min_days_between_dunning :'||l_dunning_plan_lines.min_days_between_dunning);
2849     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_correspondence_date :'||p_correspondence_date);
2850     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_include_dispute_items :'||p_include_dispute_items);
2851     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_grace_days:'||p_grace_days);
2852     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_object_id :'||l_object_id);
2853 
2854     				open sql_cur for vPLSQL using p_inc_inv_curr(j),
2855     							    l_dunning_plan_lines.min_days_between_dunning,
2856     							    p_correspondence_date,
2857     							    p_grace_days,
2858     							    p_correspondence_date,
2859     							    p_include_dispute_items,
2860     							    l_object_id;
2861     				loop
2862     				      fetch sql_cur into l_delinquency_id, l_transaction_id, l_payment_schedule_id;
2863     				      exit when sql_cur%notfound;
2864 
2865     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
2866     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_delinquency_id :'||l_delinquency_id);
2867     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_transaction_id :'||l_transaction_id);
2868     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_payment_schedule_id : '||l_payment_schedule_id);
2869 
2870     				      IEX_Dunnings_PKG.insert_staged_dunning_row(
2871     					  px_rowid                          => l_rowid
2872     					, px_dunning_trx_id                 => x_dunning_trx_id
2873     					, p_dunning_id                      => p_dunning_id
2874     					, p_cust_trx_id                     => l_transaction_id
2875     					, p_payment_schedule_id             => l_payment_schedule_id
2876     					, p_ag_dn_xref_id                   => p_ag_dn_xref_id
2877     					, p_stage_number                    => i
2878     					, p_created_by                      => FND_GLOBAL.USER_ID
2879     					, p_creation_date                   => sysdate
2880     					, p_last_updated_by                 => FND_GLOBAL.USER_ID
2881     					, p_last_update_date                => sysdate
2882     					, p_last_update_login               => FND_GLOBAL.USER_ID
2883     					, p_object_version_number	    => 1.0
2884     				      );
2885 
2886     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
2887 
2888     				      IF x_return_status = FND_API.G_RET_STS_ERROR then
2889     						raise FND_API.G_EXC_ERROR;
2890     				      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
2891     					       raise FND_API.G_EXC_UNEXPECTED_ERROR;
2892     				      END IF;
2893 
2894     				      /*
2895     				      if p_dunning_mode <> 'DRAFT' then
2896     					      update iex_delinquencies_all
2897     					      set staged_dunning_level = i
2898     					      where delinquency_id = l_delinquency_id;
2899     				      end if;
2900     				      */
2901 
2902     				      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
2903     				      x_dunning_trx_id	:= null;
2904     				end loop;
2905     				close sql_cur;
2906 
2907     				--Include past due fully disputed invoices
2908     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start Include past due fully disputed invoices');
2909     				vPLSQL1 := 'select del.delinquency_id, ' ||
2910     					   ' del.transaction_id, ' ||
2911     					   ' del.payment_schedule_id  ' ||
2912     				'    from iex_delinquencies del, ' ||
2913     				'	 ar_payment_schedules arp ' ||
2914     				'    where del.payment_schedule_id = arp.payment_schedule_id ' ||
2915     				'    and del.status = ''CURRENT'' ' ||
2916     				'    and del.staged_dunning_level is NULL ' ||
2917     				'    and arp.status = ''OP'' ' ||
2918     				'    and (arp.class = ''INV'' or arp.class = ''BR'') ' ||  -- Bills Receivables change
2919     				'    and arp.invoice_currency_code = :p_inv_curr ' ||
2920     				'    and (trunc(arp.due_date) + :p_min_days_bw_dun) <= :p_corr_date ' ||
2921     				'    and (trunc(arp.due_date) + :p_gra_days) <= :p_corr_date ' ||
2922     				'    and arp.amount_in_dispute >= decode(:p_include_dis_items, ''Y'', arp.amount_due_remaining, (arp.amount_due_original + 1)) ';
2923 
2924     				vPLSQL1	:= vPLSQL1 || vPLSQL3;
2925 
2926     				open sql_cur1 for vPLSQL1 using p_inc_inv_curr(j),
2927     							    l_dunning_plan_lines.min_days_between_dunning,
2928     							    p_correspondence_date,
2929     							    p_grace_days,
2930     							    p_correspondence_date,
2931     							    p_include_dispute_items,
2932     							    l_object_id;
2933     				loop
2934     				      fetch sql_cur1 into l_delinquency_id, l_transaction_id, l_payment_schedule_id;
2935     				      exit when sql_cur1%notfound;
2936 
2937     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
2938     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur1.l_delinquency_id :'||l_delinquency_id);
2939     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur1.l_transaction_id :'||l_transaction_id);
2940     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur1.l_payment_schedule_id : '||l_payment_schedule_id);
2941 
2942     				      IEX_Dunnings_PKG.insert_staged_dunning_row(
2943     					  px_rowid                          => l_rowid
2944     					, px_dunning_trx_id                 => x_dunning_trx_id
2945     					, p_dunning_id                      => p_dunning_id
2946     					, p_cust_trx_id                     => l_transaction_id
2947     					, p_payment_schedule_id             => l_payment_schedule_id
2948     					, p_ag_dn_xref_id                   => p_ag_dn_xref_id
2949     					, p_stage_number                    => i
2950     					, p_created_by                      => FND_GLOBAL.USER_ID
2951     					, p_creation_date                   => sysdate
2952     					, p_last_updated_by                 => FND_GLOBAL.USER_ID
2953     					, p_last_update_date                => sysdate
2954     					, p_last_update_login               => FND_GLOBAL.USER_ID
2955     					, p_object_version_number	    => 1.0
2956     				      );
2957 
2958     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
2959 
2960     				      IF x_return_status = FND_API.G_RET_STS_ERROR then
2961     						raise FND_API.G_EXC_ERROR;
2962     				      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
2963     					       raise FND_API.G_EXC_UNEXPECTED_ERROR;
2964     				      END IF;
2965 
2966     				      /*
2967     				      if p_dunning_mode <> 'DRAFT' then
2968     					      update iex_delinquencies_all
2969     					      set staged_dunning_level = i
2970     					      where delinquency_id = l_delinquency_id;
2971     				      end if;
2972     				      */
2973 
2974     				      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
2975     				      x_dunning_trx_id	:= null;
2976 
2977     				end loop;
2978     				close sql_cur1;
2979     			end loop;
2980     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End Include past due fully disputed invoices');
2981     		else
2982     			for k in 1..l_curr_count loop
2983     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_inc_inv_curr(' || k || ') : '|| p_inc_inv_curr(k));
2984 
2985     				vPLSQL := 'select del.delinquency_id, ' ||
2986     				'	   del.transaction_id, ' ||
2987     				'	   del.payment_schedule_id ' ||
2988     				'    from iex_delinquencies del ' ||
2989     				'	 ,ar_payment_schedules arp ' ||
2990     				'    where ' ||
2991     				'    del.payment_schedule_id = arp.payment_schedule_id and ' ||
2992     				'    del.status in (''DELINQUENT'',''PREDELINQUENT'') ' ||
2993     				'    and del.staged_dunning_level = :p_stage_no ' ||
2994     				'    and arp.invoice_currency_code = :p_inv_curr ' ||
2995     				'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
2996     				'    and nvl( ' ||
2997     				'	( ' ||
2998     				'	 (select trunc(correspondence_date) from iex_dunnings  ' ||
2999     				'	  where dunning_id = ' ||
3000     				'	   (select max(iet.DUNNING_ID) from iex_dunning_transactions iet, ' ||
3001     				'                                               iex_dunnings dunn ' ||
3002     				'	    where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id ' ||
3003     				'                    and dunn.dunning_id = iet.dunning_id ' ||
3004     				'                    and ((dunn.dunning_mode = ''DRAFT'' and dunn.confirmation_mode = ''CONFIRMED'') ' ||
3005     				'                            OR (dunn.dunning_mode = ''FINAL'')) ' ||
3006     				'	    and iet.STAGE_NUMBER = :p_stage_no and dunn.delivery_status is null)) ' ||
3007     				'	    + :p_min_days_bw_dun ) ' ||
3008     				'	    , :p_corr_date ) ' ||
3009     				'	    <= :p_corr_date ';
3010 
3011     				if (p_running_level = 'CUSTOMER') then
3012     				      vPLSQL3		:= '    and del.party_cust_id = :p_party_id ' ||
3013     							   '    order by del.payment_schedule_id';
3014     				elsif  (p_running_level = 'ACCOUNT') then
3015     				      vPLSQL3		:= '    and del.cust_account_id = :p_cust_acct_id ' ||
3016     				       --Begin Bug 10401991 03-feb-2011 barathsr
3017                                                                '    and arp.amount_due_remaining >= NVL ( '||
3018     							   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
3019     							   '	FROM hz_cust_profile_amts '||
3020     							   '	WHERE site_use_id  IS NULL '||
3021     							   '	AND cust_account_id = arp.customer_id '||
3022     							   '	AND currency_code   = arp.invoice_currency_code),0) '||
3023     				                           '    order by del.payment_schedule_id';
3024     				        --End Bug 10401991 03-feb-2011 barathsr
3025     				elsif  (p_running_level = 'BILL_TO') then
3026     				      -- vPLSQL3		:= '    and del.customer_site_use_id IN ( :p_site_use_id,24388) ' ||
3027                   vPLSQL3		:= '    and del.customer_site_use_id  IN ( :p_site_use_id,'||t_id||')' ||   -- Bills Receivabless
3028     				       --Begin Bug 10401991 03-feb-2011 barathsr
3029     				                           '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
3030     							   '	from hz_cust_profile_amts '||
3031     							   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
3032     							   '	and currency_code = arp.invoice_currency_code),0) '||
3033     				                           '    order by del.payment_schedule_id';
3034     				        --End Bug 10401991 03-feb-2011 barathsr
3035     				end if;
3036     				vPLSQL	:= vPLSQL || vPLSQL3;
3037 
3038     				open sql_cur for vPLSQL using l_stage,
3039     				                            p_inc_inv_curr(k),
3040     							    p_include_dispute_items,
3041     							    l_stage,
3042     							    l_dunning_plan_lines.min_days_between_dunning,
3043     							    p_correspondence_date,
3044     							    p_correspondence_date,
3045     							    l_object_id;
3046     				loop
3047     				      fetch sql_cur into l_delinquency_id, l_transaction_id, l_payment_schedule_id;
3048     				      exit when sql_cur%notfound;
3049 
3050     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
3051     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_delinquency_id :'||l_delinquency_id);
3052     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_transaction_id :'||l_transaction_id);
3053     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_payment_schedule_id : '||l_payment_schedule_id);
3054 
3055     				      IEX_Dunnings_PKG.insert_staged_dunning_row(
3056     					  px_rowid                          => l_rowid
3057     					, px_dunning_trx_id                 => x_dunning_trx_id
3058     					, p_dunning_id                      => p_dunning_id
3059     					, p_cust_trx_id                     => l_transaction_id
3060     					, p_payment_schedule_id             => l_payment_schedule_id
3061     					, p_ag_dn_xref_id                   => p_ag_dn_xref_id
3062     					, p_stage_number                    => i
3063     					, p_created_by                      => FND_GLOBAL.USER_ID
3064     					, p_creation_date                   => sysdate
3065     					, p_last_updated_by                 => FND_GLOBAL.USER_ID
3066     					, p_last_update_date                => sysdate
3067     					, p_last_update_login               => FND_GLOBAL.USER_ID
3068     					, p_object_version_number	    => 1.0
3069     				      );
3070 
3071     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
3072 
3073     				      IF x_return_status = FND_API.G_RET_STS_ERROR then
3074     						raise FND_API.G_EXC_ERROR;
3075     				      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
3076     					       raise FND_API.G_EXC_UNEXPECTED_ERROR;
3077     				      END IF;
3078 
3079     				      /*
3080     				      if p_dunning_mode <> 'DRAFT' then
3081     					      update iex_delinquencies_all
3082     					      set staged_dunning_level = i
3083     					      where delinquency_id = l_delinquency_id;
3084     				      end if;
3085     				      */
3086 
3087     				      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
3088     				      x_dunning_trx_id	:= null;
3089 
3090     				end loop;
3091     				close sql_cur;
3092 
3093     				--Include past due fully disputed invoices
3094     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start Include past due fully disputed invoices');
3095     				vPLSQL1 := 'select del.delinquency_id, ' ||
3096     					'	   del.transaction_id, ' ||
3097     					'	   del.payment_schedule_id ' ||
3098     					'    from iex_delinquencies del ' ||
3099     					'	 ,ar_payment_schedules arp ' ||
3100     					'    where  ' ||
3101     					'    del.payment_schedule_id = arp.payment_schedule_id and ' ||
3102     					'    del.status = ''CURRENT'' ' ||
3103     					'    and del.staged_dunning_level = :p_stage_no ' ||
3104     					'    and arp.status = ''OP'' ' ||
3105     					'    and (arp.class = ''INV'' or arp.class = ''BR'') ' ||    -- Bills Receivables change
3106     					'    and arp.invoice_currency_code = :p_inv_curr ' ||
3107     					'    and arp.amount_in_dispute >= decode(:p_include_dis_items, ''Y'', arp.amount_due_remaining, (arp.amount_due_original + 1)) ' ||
3108     					'    and nvl( ' ||
3109     					'	( ' ||
3110     					'	 (select trunc(correspondence_date) from iex_dunnings  ' ||
3111     					'	  where dunning_id = ' ||
3112     					'	   (select max(iet.DUNNING_ID) from iex_dunning_transactions iet, ' ||
3113     					'                                           iex_dunnings dunn ' ||
3114     					'	    where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id ' ||
3115     					'                    and dunn.dunning_id = iet.dunning_id ' ||
3116     					'                    and ((dunn.dunning_mode = ''DRAFT'' and dunn.confirmation_mode = ''CONFIRMED'') ' ||
3117     					'                            OR (dunn.dunning_mode = ''FINAL'')) ' ||
3118     					'	    and iet.STAGE_NUMBER = :p_stage_no and dunn.delivery_status is null)) ' ||
3119     					'	    + :p_min_days_bw_dun ) ' ||
3120     					'	    , :p_corr_date ) ' ||
3121     					'	    <= :p_corr_date';
3122 
3123     				vPLSQL1	:= vPLSQL1 || vPLSQL3;
3124 
3125     				open sql_cur1 for vPLSQL1 using l_stage,
3126     								p_inc_inv_curr(k),
3127     								p_include_dispute_items,
3128     								l_stage,
3129     								l_dunning_plan_lines.min_days_between_dunning,
3130     								p_correspondence_date,
3131     								p_correspondence_date,
3132     							        l_object_id;
3133     				loop
3134     				      fetch sql_cur1 into l_delinquency_id, l_transaction_id, l_payment_schedule_id;
3135     				      exit when sql_cur1%notfound;
3136 
3137     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
3138     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur1.l_delinquency_id :'||l_delinquency_id);
3139     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur1.l_transaction_id :'||l_transaction_id);
3140     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur1.l_payment_schedule_id : '||l_payment_schedule_id);
3141 
3142     				      IEX_Dunnings_PKG.insert_staged_dunning_row(
3143     					  px_rowid                          => l_rowid
3144     					, px_dunning_trx_id                 => x_dunning_trx_id
3145     					, p_dunning_id                      => p_dunning_id
3146     					, p_cust_trx_id                     => l_transaction_id
3147     					, p_payment_schedule_id             => l_payment_schedule_id
3148     					, p_ag_dn_xref_id                   => p_ag_dn_xref_id
3149     					, p_stage_number                    => i
3150     					, p_created_by                      => FND_GLOBAL.USER_ID
3151     					, p_creation_date                   => sysdate
3152     					, p_last_updated_by                 => FND_GLOBAL.USER_ID
3153     					, p_last_update_date                => sysdate
3154     					, p_last_update_login               => FND_GLOBAL.USER_ID
3155     					, p_object_version_number	    => 1.0
3156     				      );
3157 
3158     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
3159 
3160     				      IF x_return_status = FND_API.G_RET_STS_ERROR then
3161     						raise FND_API.G_EXC_ERROR;
3162     				      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
3163     					       raise FND_API.G_EXC_UNEXPECTED_ERROR;
3164     				      END IF;
3165 
3166     				      /*
3167     				      if p_dunning_mode <> 'DRAFT' then
3168     					      update iex_delinquencies_all
3169     					      set staged_dunning_level = i
3170     					      where delinquency_id = l_delinquency_id;
3171     				      end if;
3172     				      */
3173 
3174     				      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
3175     				      x_dunning_trx_id	:= null;
3176 
3177     				end loop;
3178     				close sql_cur1;
3179 
3180     			end loop;
3181     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End Include past due fully disputed invoices');
3182     		end if;
3183 
3184           end loop;
3185 
3186           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Insert current invoices');
3187           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - g_included_current_invs: '|| g_included_current_invs);
3188           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_include_curr_inv: '|| l_include_curr_inv);
3189           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_include_unapp_rec: '|| l_include_unapp_rec);
3190 
3191      if (g_included_current_invs = 'N') and (l_include_curr_inv = 'Y') then
3192     	    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start insert current invoices');
3193 
3194     		if (p_running_level = 'CUSTOMER') then
3195     			vPLSQL2 := 'select arp.customer_trx_id, ' ||
3196     				'	   arp.payment_schedule_id ' ||
3197     				'    from ar_payment_schedules arp, ' ||
3198     				'         hz_cust_accounts hca ' ||
3199     				'    where arp.customer_id = hca.cust_account_id ' ||
3200     				'    and hca.party_id = :p_party_id ' ||
3201     				'    and trunc(arp.due_date) > trunc(:p_corr_date) ' ||
3202     				'    and arp.status = ''OP'' ' ||
3203     				'    and arp.amount_due_remaining <> 0 ' ||--'    and arp.amount_due_remaining > 0 ' || Changed to fix 12552027 by snuthala 5/19/2011
3204     				'    and (arp.class = ''INV'' or arp.class = ''BR'') ' ||    -- Bills Receivables change
3205     				'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
3206     				'    and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'' ) ' ||
3207     				'    order by arp.payment_schedule_id';
3208     		elsif  (p_running_level = 'ACCOUNT') then
3209     		      vPLSQL2 := 'select arp.customer_trx_id, ' ||
3210     				'	   arp.payment_schedule_id ' ||
3211     				'    from ar_payment_schedules arp ' ||
3212     				'    where arp.customer_id = :p_cust_acct_id ' ||
3213     				'    and trunc(arp.due_date) > trunc(:p_corr_date) ' ||
3214     				'    and arp.status = ''OP'' ' ||
3215     				'    and arp.amount_due_remaining <> 0 ' ||--'    and arp.amount_due_remaining > 0 ' || Changed to fix 12552027 by snuthala 5/19/2011
3216     				'    and (arp.class = ''INV'' or arp.class = ''BR'') ' ||    -- Bills Receivables change
3217     				'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
3218     				'    and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'') ' ||
3219     				'    order by arp.payment_schedule_id';
3220     		elsif  (p_running_level = 'BILL_TO') then
3221     		      vPLSQL2 := 'select arp.customer_trx_id, ' ||
3222     				'	   arp.payment_schedule_id ' ||
3223     				'    from ar_payment_schedules arp ' ||
3224     				-- '    where arp.customer_site_use_id = :p_site_use_id ' ||   -- Bills Receivables
3225             '    where arp.customer_site_use_id IN ( :p_site_use_id, '||t_id||')' || -- Bills Receivables
3226     				'    and trunc(arp.due_date) > trunc(:p_corr_date) ' ||
3227     				'    and arp.status = ''OP'' ' ||
3228     				'    and arp.amount_due_remaining <> 0 ' ||--'    and arp.amount_due_remaining > 0 ' || Changed to fix 12552027 by snuthala 5/19/2011
3229     				'    and (arp.class = ''INV'' or arp.class = ''BR'') ' ||   -- Bills Receivables change
3230     				'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
3231     				'    and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'') ' ||
3232     				'    order by arp.payment_schedule_id';
3233     		end if;
3234     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - vPLSQL2 :'||vPLSQL2);
3235     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_object_id :'||l_object_id);
3236     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_correspondence_date :'||p_correspondence_date);
3237     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_include_dispute_items :'||p_include_dispute_items);
3238     		open sql_cur2 for vPLSQL2 using l_object_id,
3239     					    p_correspondence_date,
3240     					    p_include_dispute_items;
3241     		loop
3242     		      fetch sql_cur2 into l_customer_trx_id, l_payment_schedule_id;
3243     		      exit when sql_cur2%notfound;
3244 
3245     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_customer_trx_id :'||l_customer_trx_id);
3246     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_payment_schedule_id : '||l_payment_schedule_id);
3247 
3248     		      IEX_Dunnings_PKG.insert_staged_dunning_row(
3249     			  px_rowid                          => l_rowid
3250     			, px_dunning_trx_id                 => x_dunning_trx_id
3251     			, p_dunning_id                      => p_dunning_id
3252     			, p_cust_trx_id                     => l_customer_trx_id
3253     			, p_payment_schedule_id             => l_payment_schedule_id
3254     			, p_ag_dn_xref_id                   => p_ag_dn_xref_id
3255     			, p_stage_number                    => null
3256     			, p_created_by                      => FND_GLOBAL.USER_ID
3257     			, p_creation_date                   => sysdate
3258     			, p_last_updated_by                 => FND_GLOBAL.USER_ID
3259     			, p_last_update_date                => sysdate
3260     			, p_last_update_login               => FND_GLOBAL.USER_ID
3261     			, p_object_version_number	    => 1.0
3262     		      );
3263 
3264     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
3265 
3266     		      IF x_return_status = FND_API.G_RET_STS_ERROR then
3267     				raise FND_API.G_EXC_ERROR;
3268     		      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
3269     			       raise FND_API.G_EXC_UNEXPECTED_ERROR;
3270     		      END IF;
3271 
3272     		      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
3273     		      x_dunning_trx_id	:= null;
3274     		end loop;
3275     		close sql_cur2;
3276     /*****
3277     when inlude_current is set to y we have to include delinquent and predelinquent invoices also ignoring grace_days and p_min_days_bw_dun
3278     in the following query we pass 0 for grace_days and p_min_days_bw_dun
3279     Changed the logic such that only delinquent invoices not eligible for stage 1 will be picked up in current when passing 0 for grace_days and p_min_days_bw_dun
3280     **/
3281 
3282 
3283 
3284     				vPLSQL := 'select  del.delinquency_id, ' ||
3285     				        '          del.transaction_id, ' ||
3286     					'	   del.payment_schedule_id ' ||
3287     					'    from iex_delinquencies del, ' ||
3288     					'	 ar_payment_schedules arp ' ||
3289     					'    where del.payment_schedule_id = arp.payment_schedule_id ' ||
3290     					'    and del.status in (''DELINQUENT'',''PREDELINQUENT'') ' ||
3291     					'    and del.staged_dunning_level is NULL ' ||
3292     					'    and (trunc(arp.due_date) + :p_min_days_bw_dun) > :p_corr_date ' ||
3293     				  '    and (trunc(arp.due_date) + :p_gra_days) > :p_corr_date ' ||
3294     					'    and (trunc(arp.due_date) + 0) < :p_corr_date ' ||
3295             --'    and (trunc(arp.due_date) + 0) <= :p_corr_date ' ||
3296     					'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ';
3297     				if (p_running_level = 'CUSTOMER') then
3298     				      vPLSQL3		:= '    and del.party_cust_id = :p_party_id ' ||
3299 							   '    and del.payment_schedule_id not in (select payment_schedule_id from  iex_dunning_transactions where dunning_id = :p_dunning_id and PAYMENT_SCHEDULE_ID =  del.payment_schedule_id ) ' ||
3300     							   '    order by del.payment_schedule_id';
3301     				elsif  (p_running_level = 'ACCOUNT') then
3302     				      vPLSQL3		:= '    and del.cust_account_id = :p_cust_acct_id ' ||
3303     				      --Begin Bug 10401991 03-feb-2011 barathsr
3304     				                           '    and arp.amount_due_remaining >= NVL ( '||
3305     							   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
3306     							   '	FROM hz_cust_profile_amts '||
3307     							   '	WHERE site_use_id  IS NULL '||
3308     							   '	AND cust_account_id = arp.customer_id '||
3309     							   '	AND currency_code   = arp.invoice_currency_code),0) '||
3310 							   '    and del.payment_schedule_id not in (select payment_schedule_id from  iex_dunning_transactions where dunning_id = :p_dunning_id and PAYMENT_SCHEDULE_ID =  del.payment_schedule_id ) ' ||
3311     				                           '    order by del.payment_schedule_id';
3312     				      --End Bug 10401991 03-feb-2011 barathsr
3313     				elsif  (p_running_level = 'BILL_TO') then
3314     				      -- vPLSQL3		:= '    and del.customer_site_use_id iN ( :p_site_use_id,24388) ' ||
3315                   vPLSQL3		:= '    and del.customer_site_use_id  IN ( :p_site_use_id, '||t_id||')' ||   -- Bills Receivables
3316     				       --Begin Bug 10401991 03-feb-2011 barathsr
3317     				                           '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
3318     							   '	from hz_cust_profile_amts '||
3319     							   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
3320     							   '	and currency_code = arp.invoice_currency_code),0) '||
3321 							   '    and del.payment_schedule_id not in (select payment_schedule_id from  iex_dunning_transactions where dunning_id = :p_dunning_id and PAYMENT_SCHEDULE_ID =  del.payment_schedule_id ) ' ||
3322     				                           '    order by del.payment_schedule_id';
3323     				       --End Bug 10401991 03-feb-2011 barathsr
3324     				end if;
3325     				vPLSQL	:= vPLSQL || vPLSQL3;
3326 
3327     				open sql_cur for vPLSQL using l_dunning_plan_lines.min_days_between_dunning,
3328                         p_correspondence_date,
3329                         p_grace_days,
3330                         p_correspondence_date,
3331     				            p_correspondence_date,
3332     							      p_include_dispute_items,
3333     							      l_object_id,
3334 							          p_dunning_id;
3335     				loop
3336     				      fetch sql_cur into l_delinquency_id, l_transaction_id, l_payment_schedule_id;
3337     				      exit when sql_cur%notfound;
3338 
3339     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
3340     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_delinquency_id :'||l_delinquency_id);
3341     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_transaction_id :'||l_transaction_id);
3342     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_payment_schedule_id : '||l_payment_schedule_id);
3343 
3344                                           select count(*) into iex_dunn_trx_counter from iex_dunning_transactions where dunning_id = p_dunning_id and PAYMENT_SCHEDULE_ID = l_payment_schedule_id;
3345 
3346     				      if iex_dunn_trx_counter = 0 then
3347 
3348     					      IEX_Dunnings_PKG.insert_staged_dunning_row(
3349     						  px_rowid                          => l_rowid
3350     						, px_dunning_trx_id                 => x_dunning_trx_id
3351     						, p_dunning_id                      => p_dunning_id
3352     						, p_cust_trx_id                     => l_transaction_id
3353     						, p_payment_schedule_id             => l_payment_schedule_id
3354     						, p_ag_dn_xref_id                   => p_ag_dn_xref_id
3355     						, p_stage_number                    => null
3356     						, p_created_by                      => FND_GLOBAL.USER_ID
3357     						, p_creation_date                   => sysdate
3358     						, p_last_updated_by                 => FND_GLOBAL.USER_ID
3359     						, p_last_update_date                => sysdate
3360     						, p_last_update_login               => FND_GLOBAL.USER_ID
3361     						, p_object_version_number	    => 1.0
3362     					      );
3363 
3364     					      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
3365 
3366     					      IF x_return_status = FND_API.G_RET_STS_ERROR then
3367     							raise FND_API.G_EXC_ERROR;
3368     					      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
3369     						       raise FND_API.G_EXC_UNEXPECTED_ERROR;
3370     					      END IF;
3371 
3372     					      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
3373     					      x_dunning_trx_id	:= null;
3374     				      end if;
3375     				end loop;
3376     				close sql_cur;
3377 
3378 
3379     	--Setting the variable to 'Y', so that current invoices won't be include in further stage letters for this
3380     	--customer/account/Bill to/Delinquency
3381     	g_included_current_invs:= 'Y';
3382     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End insert current invoices');
3383           end if;
3384 
3385           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Insert unapplied receipts and On Account Credit memos');
3386           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - g_included_unapplied_rec: '|| g_included_unapplied_rec);
3387           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_include_unapp_rec: '|| l_include_unapp_rec);
3388 
3389           if (g_included_unapplied_rec = 'N') and (l_include_unapp_rec = 'Y') then
3390     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start insert unapplied receipts');
3391 
3392     		if (p_running_level = 'CUSTOMER') then
3393     			vPLSQL2 := 'select arp.payment_schedule_id ' ||
3394     				'    from ar_payment_schedules arp, ' ||
3395     				'         hz_cust_accounts hca ' ||
3396     				'    where arp.customer_id = hca.cust_account_id ' ||
3397     				'    and hca.party_id = :p_party_id ' ||
3398     				'    and arp.status = ''OP'' ' ||
3399     			        '    and arp.amount_due_remaining <> 0 ' ||
3400     			        '    and arp.class = ''PMT'' ' ||
3401     			        '    order by arp.payment_schedule_id';
3402     		elsif  (p_running_level = 'ACCOUNT') then
3403     		      vPLSQL2 := 'select arp.payment_schedule_id ' ||
3404     				    ' from ar_payment_schedules arp ' ||
3405     				    ' where arp.customer_id = :p_cust_acct_id ' ||
3406     				    ' and arp.status = ''OP'' ' ||
3407     				    ' and arp.amount_due_remaining <> 0 ' ||
3408     				    ' and arp.class = ''PMT'' ' ||
3409     				    ' order by arp.payment_schedule_id';
3410     		elsif  (p_running_level = 'BILL_TO') then
3411     		      vPLSQL2 := 'select arp.payment_schedule_id ' ||
3412     				    ' from ar_payment_schedules arp ' ||
3413     				    -- ' where arp.customer_site_use_id IN ( :p_site_use_id,24388) ' ||
3414                 ' where arp.customer_site_use_id  IN ( :p_site_use_id, '||t_id||')' ||   -- Bills Receivables
3415     				    ' and arp.status = ''OP'' ' ||
3416     				    ' and arp.amount_due_remaining <> 0 ' ||
3417     				    ' and arp.class = ''PMT'' ' ||
3418     				    ' order by arp.payment_schedule_id';
3419     		end if;
3420 
3421     		open sql_cur2 for vPLSQL2 using l_object_id;
3422     		loop
3423     		      fetch sql_cur2 into l_payment_schedule_id;
3424     		      exit when sql_cur2%notfound;
3425 
3426     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_payment_schedule_id : '||l_payment_schedule_id);
3427 
3428     		      IEX_Dunnings_PKG.insert_staged_dunning_row(
3429     			  px_rowid                          => l_rowid
3430     			, px_dunning_trx_id                 => x_dunning_trx_id
3431     			, p_dunning_id                      => p_dunning_id
3432     			--, p_cust_trx_id                     => l_customer_trx_id
3433     			, p_payment_schedule_id             => l_payment_schedule_id
3434     			, p_ag_dn_xref_id                   => p_ag_dn_xref_id
3435     			, p_stage_number                    => null
3436     			, p_created_by                      => FND_GLOBAL.USER_ID
3437     			, p_creation_date                   => sysdate
3438     			, p_last_updated_by                 => FND_GLOBAL.USER_ID
3439     			, p_last_update_date                => sysdate
3440     			, p_last_update_login               => FND_GLOBAL.USER_ID
3441     			, p_object_version_number	    => 1.0
3442     		      );
3443 
3444     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
3445 
3446     		      IF x_return_status = FND_API.G_RET_STS_ERROR then
3447     				raise FND_API.G_EXC_ERROR;
3448     		      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
3449     			       raise FND_API.G_EXC_UNEXPECTED_ERROR;
3450     		      END IF;
3451 
3452     		      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
3453     		      x_dunning_trx_id	:= null;
3454 
3455     		end loop;
3456     		close sql_cur2;
3457 
3458     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End insert unapplied receipts');
3459 
3460     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start insert On Account Credit memos');
3461 
3462     	if (p_running_level = 'CUSTOMER') then
3463     			vPLSQL2 := 'select arp.customer_trx_id customer_trx_id, ' ||
3464     			        '          arp.payment_schedule_id ' ||
3465     				'    from ar_payment_schedules arp, ' ||
3466     				'         hz_cust_accounts hca ' ||
3467     				'    where arp.customer_id = hca.cust_account_id ' ||
3468     				'    and hca.party_id = :p_party_id ' ||
3469     				'    and arp.amount_due_remaining <> 0 ' ||
3470     				'    and arp.class =''CM'' ' ||
3471     				'    and arp.status=''OP'' ';
3472     		elsif  (p_running_level = 'ACCOUNT') then
3473     		      vPLSQL2 := 'select arp.customer_trx_id customer_trx_id, ' ||
3474     			            '    arp.payment_schedule_id ' ||
3475     				    ' from ar_payment_schedules arp ' ||
3476     				    ' where arp.customer_id = :p_cust_acct_id ' ||
3477     				    '    and arp.amount_due_remaining <> 0 ' ||
3478     				    '    and arp.class =''CM'' ' ||
3479     				    '    and arp.status=''OP'' ';
3480     		elsif  (p_running_level = 'BILL_TO') then
3481     		      vPLSQL2 := 'select arp.customer_trx_id customer_trx_id, ' ||
3482     			            '    arp.payment_schedule_id ' ||
3483     				    ' from ar_payment_schedules arp ' ||
3484     				    -- ' where arp.customer_site_use_id IN ( :p_site_use_id,24388) ' ||
3485                 ' where arp.customer_site_use_id  IN ( :p_site_use_id, '||t_id||')' ||   -- Bills Receivabless
3486     				    '    and arp.amount_due_remaining <> 0 ' ||
3487     				    '    and arp.class =''CM'' ' ||
3488     				    '    and arp.status=''OP'' ';
3489     		end if;
3490 
3491     		open sql_cur2 for vPLSQL2 using l_object_id;
3492     		loop
3493     		      fetch sql_cur2 into l_customer_trx_id, l_payment_schedule_id;
3494     		      exit when sql_cur2%notfound;
3495 
3496     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_customer_trx_id :'||l_customer_trx_id);
3497     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_payment_schedule_id : '||l_payment_schedule_id);
3498 
3499     		      IEX_Dunnings_PKG.insert_staged_dunning_row(
3500     			  px_rowid                          => l_rowid
3501     			, px_dunning_trx_id                 => x_dunning_trx_id
3502     			, p_dunning_id                      => p_dunning_id
3503     			, p_cust_trx_id                     => l_customer_trx_id
3504     			, p_payment_schedule_id             => l_payment_schedule_id
3505     			, p_ag_dn_xref_id                   => p_ag_dn_xref_id
3506     			, p_stage_number                    => null
3507     			, p_created_by                      => FND_GLOBAL.USER_ID
3508     			, p_creation_date                   => sysdate
3509     			, p_last_updated_by                 => FND_GLOBAL.USER_ID
3510     			, p_last_update_date                => sysdate
3511     			, p_last_update_login               => FND_GLOBAL.USER_ID
3512     			, p_object_version_number	    => 1.0
3513     		      );
3514 
3515     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
3516 
3517     		      IF x_return_status = FND_API.G_RET_STS_ERROR then
3518     				raise FND_API.G_EXC_ERROR;
3519     		      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
3520     			       raise FND_API.G_EXC_UNEXPECTED_ERROR;
3521     		      END IF;
3522 
3523     		      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
3524     		      x_dunning_trx_id	:= null;
3525     	      end loop;
3526     	      close sql_cur2;
3527 
3528     	--Setting the variable to 'Y', so that current invoices won't be include in further stage letters for this
3529     	--customer/account/Bill to/Delinquency
3530     	g_included_unapplied_rec:= 'Y';
3531     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End insert On Account Credit memos');
3532           end if;
3533 
3534           --
3535           -- End of API body
3536           --
3537 
3538           -- Standard check for p_commit
3539           IF FND_API.to_Boolean( p_commit )
3540           THEN
3541               COMMIT WORK;
3542           END IF;
3543 
3544           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
3545           FND_MSG_PUB.Count_And_Get
3546           (  p_count          =>   x_msg_count,
3547              p_data           =>   x_msg_data
3548           );
3549 
3550     EXCEPTION
3551               WHEN FND_API.G_EXC_ERROR THEN
3552                   x_return_status := FND_API.G_RET_STS_ERROR;
3553                   FND_MSG_PUB.Count_And_Get
3554                   (  p_count          =>   x_msg_count,
3555                      p_data           =>   x_msg_data );
3556                   ROLLBACK TO CREATE_STAGED_DUNNING_PVT;
3557                   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'exception ' || SQLERRM);
3558 
3559               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
3560                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
3561                   FND_MSG_PUB.Count_And_Get
3562                   (  p_count          =>   x_msg_count,
3563                      p_data           =>   x_msg_data );
3564                   ROLLBACK TO CREATE_STAGED_DUNNING_PVT;
3565                   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'error ' || SQLERRM);
3566 
3567               WHEN OTHERS THEN
3568                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
3569                   FND_MSG_PUB.Count_And_Get
3570                   (  p_count          =>   x_msg_count,
3571                      p_data           =>   x_msg_data );
3572                   ROLLBACK TO CREATE_STAGED_DUNNING_PVT;
3573                   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'error ' || SQLERRM);
3574 
3575     END CREATE_STAGED_DUNNING;
3576 
3577     Procedure Update_Dunning
3578                (p_api_version             IN NUMBER := 1.0,
3579                 p_init_msg_list           IN VARCHAR2 ,
3580                 p_commit                  IN VARCHAR2 ,
3581                 P_Dunning_REC             IN IEX_DUNNING_PUB.DUNNING_REC_TYPE,
3582                 x_return_status           OUT NOCOPY VARCHAR2,
3583                 x_msg_count               OUT NOCOPY NUMBER,
3584                 x_msg_data                OUT NOCOPY VARCHAR2)
3585 
3586     IS
3587         --Start adding for bug 8489610 by gnramasa 14-May-09
3588         --Start adding for bug 9970624 gnramasa 4th Aug 10
3589         CURSOR C_get_DUNNING_Rec (IN_DUNNING_ID NUMBER) is
3590            select  ROWID,
3591                    DUNNING_ID,
3592                    TEMPLATE_ID,
3593                    CALLBACK_YN,
3594                    CALLBACK_DATE,
3595                    CAMPAIGN_SCHED_ID,
3596                    STATUS,
3597                    DELINQUENCY_ID,
3598                    FFM_REQUEST_ID,
3599                    XML_REQUEST_ID,
3600                    XML_TEMPLATE_ID,
3601                    OBJECT_ID,
3602                    OBJECT_TYPE,
3603                    DUNNING_OBJECT_ID,
3604                    DUNNING_LEVEL,
3605                    DUNNING_METHOD,
3606                    AMOUNT_DUE_REMAINING,
3607                    CURRENCY_CODE,
3608                    LAST_UPDATE_DATE,
3609                    LAST_UPDATED_BY,
3610                    CREATION_DATE,
3611                    CREATED_BY ,
3612                    LAST_UPDATE_LOGIN,
3613                    delivery_status,
3614                    PARENT_DUNNING_ID,
3615                    financial_charge,   -- bug 3955222
3616                    letter_name,   -- bug 3955222
3617                    interest_amt,   -- bug 3955222
3618                    dunning_plan_id,   -- bug 3955222
3619                    contact_destination,   -- bug 3955222
3620                    contact_party_id,   -- bug 3955222
3621     	       dunning_mode,
3622     	       confirmation_mode,
3623     	       request_id,
3624     	       ag_dn_xref_id,
3625     	       correspondence_date,
3626     	       addt_xml_template_id,
3627     	       addt_delivery_status
3628              from iex_DUNNINGS
3629             where dunning_id = in_dunning_id
3630             FOR UPDATE NOWAIT;
3631         --
3632         l_api_name                    CONSTANT VARCHAR2(30) := 'Update_DUNNING';
3633         l_api_version_number          CONSTANT NUMBER   := 1.0;
3634         l_return_status               VARCHAR2(1);
3635         l_msg_count                   NUMBER;
3636         l_msg_data                    VARCHAR2(32767);
3637         l_rowid                       Varchar2(50);
3638         l_DUNNING_REC                 IEX_DUNNING_PUB.DUNNING_REC_TYPE ;
3639         l_dunning_id                  NUMBER ;
3640         l_DUNNING_REF_REC             IEX_DUNNING_PUB.DUNNING_REC_TYPE;
3641         errmsg                        VARCHAR2(32767);
3642 
3643     BEGIN
3644 
3645           -- Standard Start of API savepoint
3646           SAVEPOINT UPDATE_dunning_PVT;
3647 
3648           l_dunning_rec := p_dunning_rec;
3649 
3650           -- Standard call to check for call compatibility.
3651           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
3652                              	             p_api_version,
3653                                                l_api_name,
3654                                                G_PKG_NAME)
3655           THEN
3656               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
3657           END IF;
3658 
3659           -- Initialize message list if p_init_msg_list is set to TRUE.
3660           IF FND_API.to_Boolean( p_init_msg_list )
3661           THEN
3662               FND_MSG_PUB.initialize;
3663           END IF;
3664 
3665           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - START');
3666           x_return_status := FND_API.G_RET_STS_SUCCESS;
3667           --
3668           -- Api body
3669           --
3670           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Open C_GET_DUNNING_REC');
3671           WriteLog('l_dunning_rec.dunning_ID: '||l_dunning_rec.dunning_ID);
3672           WriteLog('l_dunning_rec.parent_dunning_ID: '||l_dunning_rec.parent_dunning_ID);
3673 
3674           Open C_Get_DUNNING_Rec(l_dunning_rec.dunning_ID);
3675           Fetch C_Get_DUNNING_Rec into
3676              l_rowid,
3677              l_DUNNING_REF_REC.DUNNING_ID,
3678              l_DUNNING_REF_REC.template_id,
3679              l_DUNNING_REF_REC.callback_YN,
3680              l_DUNNING_REF_REC.callback_Date,
3681              l_DUNNING_REF_REC.campaign_sched_id,
3682              l_DUNNING_REF_REC.status,
3683              l_DUNNING_REF_REC.delinquency_id,
3684              l_DUNNING_REF_REC.ffm_request_id,
3685              l_DUNNING_REF_REC.xml_request_id,
3686              l_DUNNING_REF_REC.xml_template_id,
3687              l_DUNNING_REF_REC.object_id,
3688              l_DUNNING_REF_REC.object_type,
3689              l_DUNNING_REF_REC.dunning_object_id,
3690              l_DUNNING_REF_REC.dunning_level,
3691              l_DUNNING_REF_REC.dunning_method,
3692              l_DUNNING_REF_REC.amount_due_remaining,
3693              l_DUNNING_REF_REC.currency_code,
3694              l_DUNNING_REF_REC.LAST_UPDATE_DATE,
3695              l_DUNNING_REF_REC.LAST_UPDATED_BY,
3696              l_DUNNING_REF_REC.CREATION_DATE,
3697              l_DUNNING_REF_REC.CREATED_BY,
3698              l_DUNNING_REF_REC.LAST_UPDATE_LOGIN,
3699              l_DUNNING_REF_REC.delivery_status,
3700              l_DUNNING_REF_REC.parent_dunning_id,
3701              l_DUNNING_REF_REC.financial_charge,  -- bug 3955222
3702              l_DUNNING_REF_REC.letter_name,  -- bug 3955222
3703              l_DUNNING_REF_REC.interest_amt,  -- bug 3955222
3704              l_DUNNING_REF_REC.dunning_plan_id,  -- bug 3955222
3705              l_DUNNING_REF_REC.contact_destination,  -- bug 3955222
3706              l_DUNNING_REF_REC.contact_party_id,  -- bug 3955222
3707     	 l_DUNNING_REF_REC.dunning_mode,
3708     	 l_DUNNING_REF_REC.confirmation_mode,
3709     	 l_DUNNING_REF_REC.request_id,
3710     	 l_DUNNING_REF_REC.ag_dn_xref_id,
3711     	 l_DUNNING_REF_REC.correspondence_date,
3712     	 l_DUNNING_REF_REC.addt_xml_template_id,
3713     	 l_DUNNING_REF_REC.addt_delivery_status;
3714 
3715           If ( C_GET_DUNNING_REC%NOTFOUND) Then
3716             IF FND_MSG_PUB.Check_Msg_Level (FND_MSG_PUB.G_MSG_LVL_ERROR)
3717             THEN
3718                 FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
3719                 FND_MESSAGE.Set_Token ('INFO', 'iex_DUNNINGs', FALSE);
3720                 FND_MSG_PUB.Add;
3721             END IF;
3722             raise FND_API.G_EXC_ERROR;
3723           END IF;
3724 
3725           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CLOSE C_GET_DUNNING_REC');
3726           Close C_Get_DUNNING_REC;
3727     -- Start bug 5924158 05/06/07 by gnramasa
3728        /*
3729           If (l_dunning_rec.last_update_date is NULL or
3730              l_dunning_rec.last_update_date = FND_API.G_MISS_Date )
3731           Then
3732               IF FND_MSG_PUB.Check_Msg_Level (FND_MSG_PUB.G_MSG_LVL_ERROR)
3733               THEN
3734                   FND_MESSAGE.Set_Name('IEX', 'API_MISSING_ID');
3735                   FND_MESSAGE.Set_Token('COLUMN', 'Last_Update_Date', FALSE);
3736                   FND_MSG_PUB.ADD;
3737               END IF;
3738               raise FND_API.G_EXC_ERROR;
3739           End if;
3740     */
3741     -- End bug 5924158 05/06/07 by gnramasa
3742           -- Transfer Data into target record
3743           l_dunning_rec.CREATION_DATE       := l_dunning_ref_rec.CREATION_DATE;
3744           l_dunning_rec.CREATED_BY          := l_dunning_ref_rec.CREATED_BY;
3745           l_dunning_rec.delinquency_id      := l_dunning_ref_rec.delinquency_id;
3746           --l_dunning_rec.ffm_request_id := l_dunning_ref_rec.ffm_request_id;
3747           l_dunning_rec.dunning_method      := l_dunning_ref_rec.dunning_method;
3748 
3749           --Start bug 9503251 gnramasa 22nd Apr 2010
3750           IF (l_dunning_rec.amount_due_remaining = FND_API.G_MISS_NUM OR
3751               l_dunning_rec.amount_due_remaining is null) Then
3752              l_dunning_rec.amount_due_remaining := l_dunning_ref_rec.amount_due_remaining;
3753           END IF;
3754           IF (l_dunning_rec.currency_code = FND_API.G_MISS_CHAR OR
3755               l_dunning_rec.currency_code is null) Then
3756              l_dunning_rec.currency_code := l_dunning_ref_rec.currency_code;
3757           END IF;
3758           --End bug 9503251 gnramasa 22nd Apr 2010
3759 
3760           l_dunning_rec.dunning_object_id 	 := l_dunning_ref_rec.dunning_object_id;
3761           l_dunning_rec.dunning_level 			 := l_dunning_ref_rec.dunning_level;
3762           l_dunning_rec.financial_charge 		 := l_dunning_ref_rec.financial_charge;  -- bug 3955222
3763           l_dunning_rec.letter_name 				 := l_dunning_ref_rec.letter_name;  -- bug 3955222
3764           l_dunning_rec.interest_amt 				 := l_dunning_ref_rec.interest_amt;  -- bug 3955222
3765           l_dunning_rec.dunning_plan_id 		 := l_dunning_ref_rec.dunning_plan_id;  -- bug 3955222
3766           --l_dunning_rec.delivery_status   	 := l_dunning_ref_rec.delivery_status;
3767           --l_dunning_rec.parent_dunning_id    := l_dunning_ref_rec.parent_dunning_id;
3768 
3769           -- dont update dunning_id and delinquency_id
3770           -- dont update dunning_method
3771           -- dont update dunning_object_id and dunning_level
3772 
3773           IF (l_dunning_rec.xml_request_id = FND_API.G_MISS_NUM OR
3774               l_dunning_rec.xml_request_id is null) Then
3775              l_dunning_rec.xml_request_id := l_dunning_ref_rec.xml_request_id;
3776           END IF;
3777           IF (l_dunning_rec.xml_template_id = FND_API.G_MISS_NUM OR
3778               l_dunning_rec.xml_template_id is null) Then
3779              l_dunning_rec.xml_template_id := l_dunning_ref_rec.xml_template_id;
3780           END IF;
3781           IF (l_dunning_rec.addt_xml_template_id = FND_API.G_MISS_NUM OR
3782               l_dunning_rec.addt_xml_template_id is null) Then
3783              l_dunning_rec.addt_xml_template_id := l_dunning_ref_rec.addt_xml_template_id;
3784           END IF;
3785           IF (l_dunning_rec.ffm_request_id = FND_API.G_MISS_NUM OR
3786               l_dunning_rec.ffm_request_id is null) Then
3787              l_dunning_rec.ffm_request_id := l_dunning_ref_rec.ffm_request_id;
3788           END IF;
3789           IF (l_dunning_rec.callback_YN = FND_API.G_MISS_CHAR or
3790               l_dunning_rec.callback_YN is null ) Then
3791              l_dunning_rec.callback_YN := l_dunning_ref_rec.callback_YN;
3792           END IF;
3793           IF (l_dunning_rec.callback_date = FND_API.G_MISS_DATE or
3794               l_dunning_rec.callback_date is null ) Then
3795              l_dunning_rec.callback_date := l_dunning_ref_rec.callback_date;
3796           END IF;
3797           IF (l_dunning_rec.status = FND_API.G_MISS_CHAR or
3798               l_dunning_rec.status is null ) Then
3799              l_dunning_rec.status := l_dunning_ref_rec.status;
3800           END IF;
3801           IF (l_dunning_rec.template_ID = FND_API.G_MISS_NUM or
3802               l_dunning_rec.template_id is null ) Then
3803              l_dunning_rec.template_ID := l_dunning_ref_rec.template_ID;
3804           END IF;
3805           IF (l_dunning_rec.campaign_sched_id = FND_API.G_MISS_NUM or
3806               l_dunning_rec.campaign_sched_id is null ) Then
3807              l_dunning_rec.campaign_sched_id := l_dunning_ref_rec.campaign_sched_id;
3808           END IF;
3809            IF (l_dunning_rec.object_ID = FND_API.G_MISS_NUM or
3810               l_dunning_rec.object_id is null ) Then
3811              l_dunning_rec.object_ID := l_dunning_ref_rec.object_ID;
3812           END IF;
3813           IF (l_dunning_rec.object_type = FND_API.G_MISS_CHAR or
3814               l_dunning_rec.object_type is null ) Then
3815              l_dunning_rec.object_type := l_dunning_ref_rec.object_type;
3816           END IF;
3817           IF (l_dunning_rec.delivery_status = FND_API.G_MISS_CHAR or
3818               l_dunning_rec.delivery_status is null ) Then
3819              l_dunning_rec.delivery_status := l_dunning_ref_rec.delivery_status;
3820           END IF;
3821           IF (l_dunning_rec.addt_delivery_status = FND_API.G_MISS_CHAR or
3822               l_dunning_rec.addt_delivery_status is null ) Then
3823              l_dunning_rec.addt_delivery_status := l_dunning_ref_rec.addt_delivery_status;
3824           END IF;
3825 	      IF (l_dunning_rec.PARENT_DUNNING_ID = FND_API.G_MISS_NUM or
3826               l_dunning_rec.PARENT_DUNNING_ID is null ) Then
3827              l_dunning_rec.PARENT_DUNNING_ID := l_dunning_ref_rec.PARENT_DUNNING_ID;
3828           END IF;
3829 
3830           -- begin bug 3955222 ctlee 10/05/2005
3831           IF (l_dunning_rec.contact_destination = FND_API.G_MISS_CHAR or
3832               l_dunning_rec.contact_destination is null ) Then
3833              l_dunning_rec.contact_destination := l_dunning_ref_rec.contact_destination;
3834           END IF;
3835 
3836           IF (l_dunning_rec.contact_party_id = FND_API.G_MISS_NUM or
3837               l_dunning_rec.contact_party_id is null ) Then
3838              l_dunning_rec.contact_party_id := l_dunning_ref_rec.contact_party_id;
3839           END IF;
3840 
3841           IF (l_dunning_rec.dunning_mode = FND_API.G_MISS_CHAR or
3842               l_dunning_rec.dunning_mode is null ) Then
3843              l_dunning_rec.dunning_mode := l_dunning_ref_rec.dunning_mode;
3844           END IF;
3845 
3846           IF (l_dunning_rec.confirmation_mode = FND_API.G_MISS_CHAR or
3847               l_dunning_rec.confirmation_mode is null ) Then
3848              l_dunning_rec.confirmation_mode := l_dunning_ref_rec.confirmation_mode;
3849           END IF;
3850 
3851           IF (l_dunning_rec.request_id = FND_API.G_MISS_NUM or
3852               l_dunning_rec.request_id is null ) Then
3853              l_dunning_rec.request_id := l_dunning_ref_rec.request_id;
3854           END IF;
3855 
3856           IF (l_dunning_rec.ag_dn_xref_id = FND_API.G_MISS_NUM or
3857               l_dunning_rec.ag_dn_xref_id is null ) Then
3858              l_dunning_rec.ag_dn_xref_id := l_dunning_ref_rec.ag_dn_xref_id;
3859           END IF;
3860 
3861           IF (l_dunning_rec.correspondence_date = FND_API.G_MISS_DATE or
3862               l_dunning_rec.correspondence_date is null ) Then
3863              l_dunning_rec.correspondence_date := l_dunning_ref_rec.correspondence_date;
3864           END IF;
3865 
3866           -- end bug 3955222 ctlee 10/05/2005
3867           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Update Row');
3868           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunningid='||l_dunning_rec.dunning_id );
3869           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delivery_status= ' || l_dunning_rec.delivery_status);
3870           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - addt_delivery_status= ' || l_dunning_rec.addt_delivery_status);
3871 
3872           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_rec.dunning_mode= ' || l_dunning_rec.dunning_mode);
3873           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_rec.confirmation_mode= ' || l_dunning_rec.confirmation_mode);
3874 
3875               -- Invoke table handler
3876               IEX_DUNNINGS_PKG.Update_Row(
3877                  p_rowid                          => l_rowid
3878                , p_dunning_id                     => l_dunning_rec.dunning_id
3879                , p_last_update_date               => sysdate
3880                , p_last_updated_by                => FND_GLOBAL.USER_ID
3881                , p_creation_date                  => l_dunning_rec.creation_date
3882                , p_created_by                     => l_dunning_rec.created_by
3883                , p_last_update_login              => FND_GLOBAL.USER_ID
3884     					 --, p_request_id                     => FND_GLOBAL.CONC_REQUEST_ID
3885     	   , p_request_id                     => l_dunning_rec.request_id
3886                , p_template_id                    => l_dunning_rec.template_id
3887                , p_callback_yn                    => l_dunning_rec.callback_yn
3888                , p_callback_date                  => l_dunning_rec.callback_date
3889                , p_campaign_sched_id              => l_dunning_rec.campaign_sched_id
3890                , p_status                         => l_dunning_rec.status
3891                , p_delinquency_id                 => l_dunning_rec.delinquency_id
3892                , p_ffm_request_id                 => l_dunning_rec.ffm_request_id
3893                , p_xml_request_id                 => l_dunning_rec.xml_request_id
3894                , p_xml_template_id                => l_dunning_rec.xml_template_id
3895                , p_object_id                      => l_dunning_rec.object_id
3896                , p_object_type                    => l_dunning_rec.object_type
3897                , p_dunning_object_id              => l_dunning_rec.dunning_object_id
3898                , p_dunning_level                  => l_dunning_rec.dunning_level
3899                , p_dunning_method                 => l_dunning_rec.dunning_method
3900                , p_amount_due_remaining           => l_dunning_rec.amount_due_remaining
3901                , p_currency_code                  => l_dunning_rec.currency_code
3902                , p_delivery_status                => l_dunning_rec.delivery_status
3903                , p_parent_dunning_id              => l_dunning_rec.PARENT_DUNNING_ID
3904                , p_financial_charge               => l_dunning_rec.financial_charge   -- bug 3955222
3905                , p_letter_name                    => l_dunning_rec.letter_name   -- bug 3955222
3906                , p_interest_amt                   => l_dunning_rec.interest_amt   -- bug 3955222
3907                , p_dunning_plan_id                => l_dunning_rec.dunning_plan_id   -- bug 3955222
3908                , p_contact_destination            => l_dunning_rec.contact_destination   -- bug 3955222
3909                , p_contact_party_id               => l_dunning_rec.contact_party_id   -- bug 3955222
3910     	   , p_dunning_mode		      => l_dunning_rec.dunning_mode
3911     	   , p_confirmation_mode              => l_dunning_rec.confirmation_mode
3912     	   , p_ag_dn_xref_id                  => l_dunning_rec.ag_dn_xref_id
3913     	   , p_correspondence_date            => l_dunning_rec.correspondence_date
3914     	   , p_addt_xml_template_id           => l_dunning_rec.addt_xml_template_id
3915     	   , p_addt_delivery_status           => l_dunning_rec.addt_delivery_status
3916 
3917               );
3918     	  --End adding for bug 9970624 gnramasa 4th Aug 10
3919     	  --End adding for bug 8489610 by gnramasa 14-May-09
3920 
3921           IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
3922               RAISE FND_API.G_EXC_ERROR;
3923           elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
3924               raise FND_API.G_EXC_UNEXPECTED_ERROR;
3925           END IF;
3926 
3927           --
3928           -- End of API body.
3929           --
3930 
3931           -- Standard check for p_commit
3932           IF FND_API.to_Boolean( p_commit )
3933           THEN
3934               COMMIT WORK;
3935           END IF;
3936 
3937           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
3938 
3939           FND_MSG_PUB.Count_And_Get
3940           (  p_count          =>   x_msg_count,
3941              p_data           =>   x_msg_data );
3942 
3943           EXCEPTION
3944               WHEN FND_API.G_EXC_ERROR THEN
3945                   x_return_status := FND_API.G_RET_STS_ERROR;
3946                   FND_MSG_PUB.Count_And_Get
3947                   (  p_count          =>   x_msg_count,
3948                      p_data           =>   x_msg_data );
3949                   ROLLBACK TO UPDATE_DUNNING_PVT;
3950                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception error='||SQLERRM);
3951 
3952               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
3953                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
3954                   FND_MSG_PUB.Count_And_Get
3955                   (  p_count          =>   x_msg_count,
3956                      p_data           =>   x_msg_data );
3957                   ROLLBACK TO UPDATE_DUNNING_PVT;
3958                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception error='||SQLERRM);
3959 
3960               WHEN OTHERS THEN
3961                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
3962                   FND_MSG_PUB.Count_And_Get
3963                   (  p_count          =>   x_msg_count,
3964                      p_data           =>   x_msg_data );
3965                   ROLLBACK TO UPDATE_DUNNING_PVT;
3966                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception error='||SQLERRM);
3967 
3968     END Update_DUNNING;
3969 
3970     /*=========================================================================
3971        clchang update 10/16/2002 -
3972         Send Dunning can be in Customer, Account and Delinquency levels in 11.5.9;
3973         Send_Level_Dunning is for Customer and Account level;
3974         Send_Dunning keeps the same, and is for Delinquency Level;
3975        clchang update 04/21/2003 -
3976         new level 'BILL_TO' in 11.5.10.
3977     *=========================================================================*/
3978     Procedure Send_Level_Dunning
3979                (p_api_version             IN NUMBER := 1.0,
3980                 p_init_msg_list           IN VARCHAR2 ,
3981                 p_commit                  IN VARCHAR2 ,
3982                 p_running_level           IN VARCHAR2,
3983                 p_dunning_plan_id         in number,
3984                 p_resend_flag             IN VARCHAR2,
3985                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
3986                 p_parent_request_id       IN NUMBER,
3987     	    	p_dunning_mode	      IN VARCHAR2,     -- added by gnramasa for bug 8489610 14-May-09
3988     	    	p_confirmation_mode	      IN   VARCHAR2,   -- added by gnramasa for bug 8489610 14-May-09
3989     	    	p_correspondence_date     IN DATE,
3990                 x_return_status           OUT NOCOPY VARCHAR2,
3991                 x_msg_count               OUT NOCOPY NUMBER,
3992                 x_msg_data                OUT NOCOPY VARCHAR2)
3993 
3994     IS
3995         CURSOR C_GET_DEL (IN_del_ID NUMBER) IS
3996           SELECT delinquency_ID
3997             FROM IEX_DELINQUENCIES
3998            WHERE delinquency_ID = in_del_ID;
3999         --
4000         -- begin bug 4914799 ctlee 12/30/2005 add p_dunning_plan_id
4001         CURSOR C_GET_SCORE (IN_ID NUMBER, IN_CODE VARCHAR2, p_dunning_plan_id number) IS
4002           SELECT a.score_value
4003             FROM IEX_SCORE_HISTORIES a
4004                  , IEX_DUNNING_PLANS_VL c  -- bug 4914799 ctlee 12/30/2005
4005            WHERE a.score_object_ID = in_ID
4006              AND a.score_object_code = IN_CODE
4007              and c.score_id = a.score_id   -- bug 4914799 ctlee 12/30/2005
4008              and c.dunning_plan_id = p_dunning_plan_id -- bug 4914799 ctlee 12/30/2005
4009              AND a.creation_date = (select max(b.creation_date)
4010                                       from iex_score_histories b
4011                                      where b.score_object_id = in_id
4012                                        AND b.score_object_code = IN_CODE
4013     				   AND b.score_id = a.score_id );
4014         -- end bug 4914799 ctlee 12/30/2005 add p_dunning_plan_id
4015 
4016         CURSOR C_GET_TEMPLATE (l_line_id NUMBER,
4017                                l_score NUMBER, in_LEVEL VARCHAR2, p_dunning_plan_id number) IS
4018           SELECT x.ag_dn_xref_id,
4019                  x.template_id,
4020                  x.xdo_template_id,
4021                  x.fm_method,
4022                  upper(x.callback_flag),
4023                  x.callback_days
4024             FROM IEX_AG_DN_XREF x,
4025                  ar_aging_buckets ar,
4026                  iex_dunning_plans_vl d
4027            WHERE x.aging_bucket_line_ID = l_line_ID
4028              and x.dunning_plan_id = p_dunning_plan_id
4029              AND l_score between x.score_range_low and x.score_range_high
4030              AND x.aging_bucket_id = ar.aging_bucket_id
4031              and ar.aging_bucket_id = d.aging_bucket_id
4032              AND ar.status = 'A'
4033              AND x.dunning_level = IN_LEVEL ;
4034 
4035          CURSOR C_TEMPLATE_STATUS (l_template_id number) is
4036          select 'Active'
4037          from xdo_templates_vl xdo
4038          where xdo.template_id = l_template_id
4039          and trunc(sysdate) >= TRUNC (NVL(xdo.start_date, sysdate))
4040          and trunc(sysdate) < TRUNC(NVL(xdo.end_date, sysdate + 1));
4041 
4042          CURSOR C_TEMPLATE_NAME (l_template_id number) is
4043          select template_name
4044          from xdo_templates_vl xdo
4045          where xdo.template_id = l_template_id;
4046 
4047          l_template_name	varchar2(500);
4048 
4049         --Start bug 7197038 gnramasa 8th july 08
4050          -- cursor for checking if the number of delinquencies NOT disputed
4051         /*
4052         CURSOR C_DISPUTED_AMOUNT(P_PARTY_ID NUMBER, P_CUST_ACCOUNT_ID NUMBER, P_SITE_USE_ID NUMBER ) IS
4053          select sum(a.amount_in_dispute) - sum(a.amount_due_remaining)
4054           from iex_delinquencies d
4055               ,ar_payment_schedules a
4056          where a.payment_schedule_id  = d.payment_schedule_id
4057            and d.party_cust_id        = nvl(p_party_id, d.party_cust_id)
4058            and d.cust_account_id      = nvl(P_CUST_ACCOUNT_ID, d.cust_account_id )
4059            and d.customer_site_use_id = nvl(p_site_use_id, d.customer_site_use_id )
4060            and d.status IN ('DELINQUENT', 'PREDELINQUENT');
4061          */
4062          CURSOR C_DISPUTED_AMOUNT_PARTY(P_PARTY_ID NUMBER) IS
4063          select sum(a.amount_in_dispute) - sum(a.amount_due_remaining)
4064           from iex_delinquencies d
4065               ,ar_payment_schedules a
4066          where a.payment_schedule_id  = d.payment_schedule_id
4067            and d.party_cust_id        = p_party_id
4068            and d.status IN ('DELINQUENT', 'PREDELINQUENT');
4069 
4070         CURSOR C_DISPUTED_AMOUNT_ACCOUNT(P_CUST_ACCOUNT_ID NUMBER) IS
4071          select sum(a.amount_in_dispute) - sum(a.amount_due_remaining)
4072           from iex_delinquencies d
4073               ,ar_payment_schedules a
4074          where a.payment_schedule_id  = d.payment_schedule_id
4075            and d.cust_account_id      = P_CUST_ACCOUNT_ID
4076            and d.status IN ('DELINQUENT', 'PREDELINQUENT');
4077 
4078         CURSOR C_DISPUTED_AMOUNT_BILLTO(P_SITE_USE_ID NUMBER ) IS
4079          select sum(a.amount_in_dispute) - sum(a.amount_due_remaining)
4080           from iex_delinquencies d
4081               ,ar_payment_schedules a
4082          where a.payment_schedule_id  = d.payment_schedule_id
4083            and d.customer_site_use_id = p_site_use_id
4084            and d.status IN ('DELINQUENT', 'PREDELINQUENT');
4085 
4086         --End bug 7197038 gnramasa 8th july 08
4087 
4088         -- Start for the bug#8408162 by PNAVEENK on 7-4-2009
4089         cursor c_fully_promised_party(p_party_id number) is
4090         SELECT count(1)
4091     		FROM ar_payment_schedules_all ps, iex_delinquencies_all del
4092     		WHERE del.party_cust_id=p_party_id
4093     	        AND ps.payment_schedule_id = del.payment_schedule_id
4094     	        AND ps.status = 'OP'
4095     	        AND del.status IN ('DELINQUENT', 'PREDELINQUENT')
4096     		and not exists(select 1
4097     	        from iex_promise_details pd where pd.delinquency_id=del.delinquency_id
4098     		and pd.status='COLLECTABLE'
4099     		and pd.state='PROMISE'
4100     	        group by pd.delinquency_id
4101     		having sum(nvl(pd.promise_amount,0))>=ps.amount_due_remaining);
4102        cursor c_fully_promised_account(p_cust_account_id number) is
4103        SELECT count(1)
4104     		FROM ar_payment_schedules_all ps, iex_delinquencies_all del
4105     		WHERE del.cust_account_id=p_cust_account_id
4106     	        AND ps.payment_schedule_id = del.payment_schedule_id
4107     	        AND ps.status = 'OP'
4108     	        AND del.status IN ('DELINQUENT', 'PREDELINQUENT')
4109     		and not exists(select 1
4110     	        from iex_promise_details pd where pd.delinquency_id=del.delinquency_id
4111     		and pd.status='COLLECTABLE'
4112     		and pd.state='PROMISE'
4113     	        group by pd.delinquency_id
4114     		having sum(nvl(pd.promise_amount,0))>=ps.amount_due_remaining);
4115        cursor c_fully_promised_billto(p_site_use_id number) is
4116        SELECT count(1)
4117     		FROM ar_payment_schedules_all ps, iex_delinquencies_all del
4118     		WHERE del.customer_site_use_id= p_site_use_id
4119     	        AND ps.payment_schedule_id = del.payment_schedule_id
4120     	        AND ps.status = 'OP'
4121     	        AND del.status IN ('DELINQUENT', 'PREDELINQUENT')
4122     		and not exists(select 1
4123     	        from iex_promise_details pd where pd.delinquency_id=del.delinquency_id
4124     		and pd.status='COLLECTABLE'
4125     		and pd.state='PROMISE'
4126     	        group by pd.delinquency_id
4127     		having sum(nvl(pd.promise_amount,0))>=ps.amount_due_remaining);
4128 
4129         -- End for the bug#8408162 by PNAVEENK on 7-4-2009
4130         l_DUNNING_id            NUMBER;
4131         l_delinquency_id        NUMBER;
4132         l_party_cust_id         NUMBER;
4133         l_account_id            NUMBER;
4134         l_customer_site_use_id  NUMBER;
4135         l_noskip                NUMBER := 0;
4136         l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
4137         l_DUNNING_tbl           IEX_DUNNING_PUB.DUNNING_TBL_TYPE;
4138         l_dunning_rec_upd       IEX_DUNNING_PUB.DUNNING_REC_TYPE;
4139         l_score                 NUMBER;
4140         l_bucket_line_id        NUMBER;
4141         l_campaign_sched_id     NUMBER;
4142         l_template_id           NUMBER;
4143         l_xdo_template_id       NUMBER;
4144         l_method                VARCHAR2(10);
4145         l_callback_flag         VARCHAR2(1);
4146         l_callback_days         NUMBER;
4147         l_callback_date         DATE;
4148         l_request_id            NUMBER;
4149         l_outcome_code          varchar2(20);
4150         l_api_name              CONSTANT VARCHAR2(30) := 'Send_Level_Dunning';
4151         l_api_version_number    CONSTANT NUMBER   := 1.0;
4152         l_return_status         VARCHAR2(1);
4153         l_msg_count             NUMBER;
4154         l_msg_data              VARCHAR2(32767);
4155         errmsg                  VARCHAR2(32767);
4156         --
4157         nIdx                    NUMBER := 0;
4158         TYPE Del_ID_TBL_type is Table of IEX_DELINQUENCIES_ALL.DELINQUENCY_ID%TYPE
4159                                 INDEX BY BINARY_INTEGER;
4160         Del_Tbl                 Del_ID_TBL_TYPE;
4161         l_bind_tbl              IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
4162         l_bind_rec              IEX_DUNNING_PVT.FULFILLMENT_BIND_REC;
4163         l_org_id                NUMBER ;
4164         l_object_Code           VARCHAR2(25);
4165         l_object_id             NUMBER;
4166         --l_delid_tbl             IEX_DUNNING_PUB.DelId_NumList;
4167         l_del_tbl               IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE;
4168         l_curr_code             VARCHAR2(15);
4169         l_amount                NUMBER;
4170         l_write                 NUMBER;
4171         l_ffm_cnt               NUMBER := 0;
4172         l_dunn_cnt              NUMBER := 0;
4173         l_curr_dmethod          VARCHAR2(10);
4174         -- begin raverma 03/09/06 add contact point selection
4175         l_location_id           number;
4176         l_amount_disputed       number;
4177         l_contact_id            number;
4178         l_warning_flag          varchar2(1);
4179         l_contact_point_id      number;
4180 
4181         l_delinquency_id_check        NUMBER;
4182         l_party_cust_id_check         NUMBER;
4183         l_account_id_check            NUMBER;
4184         l_customer_site_use_id_check  NUMBER;
4185         l_contact_destination         varchar2(240);  -- bug 3955222
4186         l_contact_party_id            number; -- bug 3955222
4187         l_fully_promised              number := 1; -- bug# 8408162
4188         l_allow_send                  varchar2(1) := 'Y';  -- bug#8408162
4189         l_status                      varchar2(10);
4190         --Start adding for bug 9156833 gnramasa 27th Nov 09
4191         l_validation_level		  NUMBER ;
4192         l_resource_tab		  iex_utilities.resource_tab_type;
4193         l_resource_id		  NUMBER;
4194         --End adding for bug 9156833 gnramasa 27th Nov 09
4195         l_turnoff_coll_on_bankru	  varchar2(10);
4196         l_no_of_bankruptcy		  number;
4197         l_template_status		  varchar2(10);
4198 
4199         cursor c_no_of_bankruptcy (p_par_id number)
4200         is
4201         select nvl(count(*),0)
4202         from iex_bankruptcies
4203         where party_id = p_par_id
4204         and (disposition_code in ('GRANTED','NEGOTIATION')
4205              OR (disposition_code is NULL));
4206 
4207         Type refCur             is Ref Cursor;
4208         sql_cur                 refCur;
4209         sql_cur1                refCur;
4210         sql_cur2                refCur;
4211         sql_cur3                refCur;
4212         vPLSQL                  VARCHAR2(4000);
4213         vPLSQL1                 VARCHAR2(4000);
4214         vPLSQL2                 VARCHAR2(4000);
4215         vPLSQL3                 VARCHAR2(4000);
4216         l_acc_dunning_trx_null_dun_ct number;
4217         l_skip_this_dunn_planlineid   number;
4218         l_first_satified_dunnplanid   number;
4219         l_grace_days                  number := 0;
4220         l_use_grace_days              varchar2(10);
4221         l_dun_disputed_items          varchar2(10);
4222         L_AG_DN_XREF_ID               number;
4223         l_inv_curr			  varchar2(20);
4224         l_amt_due_remaining		  number;
4225         l_transaction_id              number;
4226         l_payment_schedule_id         number;
4227         l_rowid                       Varchar2(50);
4228        -- l_inc_inv_curr                IEX_UTILITIES.INC_INV_CURR_TBL;
4229         l_dunn_letters                varchar2(10);
4230         l_include_current             varchar2(1);
4231         l_total_amount_due_remaining  number;
4232         l_cust_acct_cm_tot_amt_rem number;
4233 
4234         cursor c_dunning_plan_dtl (p_dunn_plan_id number) is
4235         select nvl(dunn.INCLUDE_CURRENT,'N'),
4236                nvl(dunn.grace_days ,'N'),
4237                nvl(dunn.dun_disputed_items, 'N')
4238         from iex_dunning_plans_b dunn
4239         where dunning_plan_id = p_dunn_plan_id;
4240 
4241        cursor c_cust_acct_amt_due_rem(p_party_id number,p_org_id number, p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
4242         select nvl(sum(aps.acctd_amount_due_remaining),0)
4243            from ar_payment_schedules_all aps,iex_delinquencies_all dd,hz_cust_accounts hzca
4244            where dd.payment_schedule_id = aps.payment_schedule_id
4245            and aps.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP', 'BR')    -- Bills Receivables change
4246            and aps.status='OP'
4247            and (trunc(aps.due_date) + p_grace_days) <= p_corr_date
4248            and nvl(aps.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(aps.amount_in_dispute,0), 0)
4249            and aps.amount_due_remaining > 0
4250            and aps.customer_id=hzca.cust_account_id
4251            and aps.org_id=p_org_id
4252            and hzca.party_id = p_party_id;
4253 
4254          cursor c_cust_acct_cm_tot_amt_rem (p_party_id number,p_org_id number) is
4255            select nvl(sum(acctd_amount_due_remaining),0)
4256            from  ar_payment_schedules_all aps,hz_cust_accounts hzca
4257            where aps.class IN ('CM','PMT')
4258            and   aps.status = 'OP'
4259            and   aps.customer_id = hzca.cust_account_id
4260            and   aps.org_id= p_org_id
4261            and   hzca.party_id = p_party_id;
4262 
4263            l_dun_yn VARCHAR2(1):= 'Y';
4264     BEGIN
4265           -- Standard Start of API savepoint
4266           SAVEPOINT Send_Level_DUNNING_PVT;
4267 
4268           --Bug#4679639 schekuri 20-OCT-2005
4269           --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
4270           --l_org_id := fnd_profile.value('ORG_ID');
4271           l_org_id:= mo_global.get_current_org_id;
4272           WriteLog(' org_id in send_level_dunning ' || l_org_id);
4273 
4274           -- Standard call to check for call compatibility.
4275           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
4276                                                p_api_version,
4277                                                l_api_name,
4278                                                G_PKG_NAME)
4279           THEN
4280               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
4281           END IF;
4282 
4283           -- Initialize message list if p_init_msg_list is set to TRUE.
4284           IF FND_API.to_Boolean( p_init_msg_list )
4285           THEN
4286               FND_MSG_PUB.initialize;
4287           END IF;
4288 
4289           if (p_resend_flag = 'Y') then
4290               -- don't write into FILE
4291               l_write := 0;
4292           else
4293               l_write := 1;
4294           end if;
4295 
4296           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
4297           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - running_level = ' || p_running_level);
4298           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - resend_flag =   ' || p_resend_flag);
4299           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_parent_request_id ' || p_parent_request_id);
4300           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delcnt= ' || p_delinquencies_tbl.count);
4301 
4302           -- Initialize API return status to SUCCESS
4303           x_return_status := FND_API.G_RET_STS_SUCCESS;
4304           --
4305           -- Api body
4306           --
4307           l_turnoff_coll_on_bankru	:= nvl(fnd_profile.value('IEX_TURNOFF_COLLECT_BANKRUPTCY'),'N');
4308           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_turnoff_coll_on_bankru: ' || l_turnoff_coll_on_bankru);
4309 
4310           l_party_cust_id := p_delinquencies_tbl(1).party_cust_id;
4311           l_account_id := p_delinquencies_tbl(1).cust_account_id;
4312           l_customer_site_use_id := p_delinquencies_tbl(1).customer_site_use_id;
4313 
4314           if (p_running_level = 'CUSTOMER') then
4315               l_object_Code                     := 'PARTY';
4316               l_object_id                       := p_delinquencies_tbl(1).party_cust_id;
4317               l_del_tbl(1).party_cust_id        := p_delinquencies_tbl(1).party_cust_id;
4318               l_del_tbl(1).cust_account_id      := 0;
4319               l_del_tbl(1).customer_site_use_id := 0;
4320               l_amount                          := party_amount_due_remaining(l_object_id);
4321               l_curr_code                       := party_currency_code(l_object_id);
4322               --Start bug 7197038 gnramasa 8th july 08
4323     	  /*
4324     	  open C_DISPUTED_AMOUNT(P_PARTY_ID          => p_delinquencies_tbl(1).party_cust_id
4325                                     ,P_CUST_ACCOUNT_ID   => null
4326                                     ,P_SITE_USE_ID       => null);
4327     	  */
4328     	  --open C_DISPUTED_AMOUNT_PARTY(p_delinquencies_tbl(1).party_cust_id);
4329               open c_fully_promised_party (p_delinquencies_tbl(1).party_cust_id);  -- Added for bug# 8408162
4330           elsif (p_running_level = 'ACCOUNT') then
4331               l_object_Code                     := 'IEX_ACCOUNT';
4332               l_object_id                       := p_delinquencies_tbl(1).cust_account_id;
4333               l_del_tbl(1).party_cust_id        := p_delinquencies_tbl(1).party_cust_id;
4334               l_del_tbl(1).cust_account_id      := p_delinquencies_tbl(1).cust_account_id;
4335               l_del_tbl(1).customer_site_use_id := 0;
4336               l_amount                          := acct_amount_due_remaining(l_object_id);
4337               l_curr_code                       := acct_currency_code(l_object_id);
4338               /*
4339     	  open C_DISPUTED_AMOUNT(P_PARTY_ID          => null
4340                                     ,P_CUST_ACCOUNT_ID   => p_delinquencies_tbl(1).party_cust_id
4341                                     ,P_SITE_USE_ID       => null);
4342     	  */
4343     	  --open C_DISPUTED_AMOUNT_ACCOUNT(p_delinquencies_tbl(1).cust_account_id);
4344               open c_fully_promised_account (p_delinquencies_tbl(1).cust_account_id); -- Added for bug#8408162
4345           elsif (p_running_level = 'BILL_TO') then
4346               l_object_Code                     := 'IEX_BILLTO';
4347               l_object_id                       := p_delinquencies_tbl(1).customer_site_use_id;
4348               l_del_tbl(1).party_cust_id        := p_delinquencies_tbl(1).party_cust_id;
4349               l_del_tbl(1).cust_account_id      := p_delinquencies_tbl(1).cust_account_id;
4350               l_del_tbl(1).customer_site_use_id := p_delinquencies_tbl(1).customer_site_use_id;
4351               l_amount                          := site_amount_due_remaining(l_object_id);
4352               l_curr_code                       := site_currency_code(l_object_id);
4353               /*
4354     	  open C_DISPUTED_AMOUNT(P_PARTY_ID          => null
4355                                     ,P_CUST_ACCOUNT_ID   => p_delinquencies_tbl(1).customer_site_use_id
4356                                     ,P_SITE_USE_ID       => null);
4357     	  */
4358     	  --open C_DISPUTED_AMOUNT_BILLTO(p_delinquencies_tbl(1).customer_site_use_id);
4359               open c_fully_promised_billto (p_delinquencies_tbl(1).customer_site_use_id); -- Added for bug#8408162
4360           end if;
4361 
4362           /*==================================================================
4363            * l_noskip is used to trace the del data is all disputed or not;
4364            * if any one del not disputed, then l_noskip=1;
4365            * if l_noskip=0, then means all del are disputed,
4366            *    => for this customer/account, skip it;
4367            * if l_fully_promised =0 and l_allow_send = 'N' then l_noskip=0
4368            *==================================================================*/
4369           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - counting disputed delinquencies ');
4370           --fetch C_DISPUTED_AMOUNT into l_amount_disputed;
4371           --    close C_DISPUTED_AMOUNT;
4372         if (p_running_level = 'CUSTOMER') then
4373     		--fetch C_DISPUTED_AMOUNT_PARTY into l_amount_disputed;
4374     		--close C_DISPUTED_AMOUNT_PARTY;
4375     		fetch c_fully_promised_party into l_fully_promised;  -- Added for bug# 8408162
4376     		close c_fully_promised_party;
4377           elsif (p_running_level = 'ACCOUNT') then
4378     		--fetch C_DISPUTED_AMOUNT_ACCOUNT into l_amount_disputed;
4379     		--close C_DISPUTED_AMOUNT_ACCOUNT;
4380     		fetch c_fully_promised_account into l_fully_promised; -- Added for bug# 8408162
4381     		close c_fully_promised_account;
4382           elsif (p_running_level = 'BILL_TO') then
4383     		--fetch C_DISPUTED_AMOUNT_BILLTO into l_amount_disputed;
4384     		--close C_DISPUTED_AMOUNT_BILLTO;
4385     		fetch c_fully_promised_billto into l_fully_promised; -- Added for bug# 8408162
4386     		close c_fully_promised_billto;
4387           end if;
4388 
4389           --End bug 7197038 gnramasa 8th july 08
4390           select fnd_profile.value(nvl('IEX_ALLOW_DUN_FULL_PROMISE','N')) into l_allow_send from dual; -- Added for bug#8408162
4391 
4392           if l_turnoff_coll_on_bankru = 'Y' then
4393     	open c_no_of_bankruptcy (p_delinquencies_tbl(1).party_cust_id);
4394     	fetch c_no_of_bankruptcy into l_no_of_bankruptcy;
4395     	close c_no_of_bankruptcy;
4396           end if;
4397           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_no_of_bankruptcy: ' || l_no_of_bankruptcy);
4398 
4399           if (l_amount_disputed >= 0) OR (p_resend_flag = 'Y' ) or (l_fully_promised = 0 and l_allow_send = 'Y')
4400               OR (l_turnoff_coll_on_bankru = 'Y' and l_no_of_bankruptcy >0 ) then  -- bug#8408162
4401                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - setting no skip = 0 ');
4402                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_amount_disputed ' || l_amount_disputed);
4403                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_resend_flag = ' || p_resend_flag);
4404                l_noskip := 0;
4405           ELSE
4406                l_noskip := 1;
4407           end if;
4408 
4409           --WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount disputed less delinquency amount = ' || l_amount_disputed);
4410           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_code='||l_object_code);
4411           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id='||l_object_id);
4412           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id='||l_party_cust_id);
4413           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount_due_remaining='||l_amount);
4414           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - currency_code='||l_curr_code);
4415           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_noskip='||l_noskip);
4416 
4417           IF (l_noskip > 0) THEN
4418 
4419              -- init the msg (not including the msg from dispute api)
4420              FND_MSG_PUB.initialize;
4421 
4422               /*===========================================
4423                * Get Score From IEX_SCORE_HISTORIES
4424                * If NotFound => Call API to getScore;
4425                *===========================================*/
4426     	         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get Score');
4427     	         Open C_Get_SCORE(l_object_id, l_object_Code, p_dunning_plan_id);
4428     	         Fetch C_Get_SCORE into l_score;
4429 
4430     	         If ( C_GET_SCORE%NOTFOUND) Then
4431     	              FND_MESSAGE.Set_Name('IEX', 'IEX_NO_SCORE');
4432     	              FND_MSG_PUB.Add;
4433     	              FND_FILE.PUT_LINE(FND_FILE.LOG, 'Missing Score');
4434     	              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Missing Score');
4435     	              Close C_Get_SCORE;
4436     	              RAISE FND_API.G_EXC_ERROR;
4437     	         END IF;
4438     	         Close C_Get_SCORE;
4439     	         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get Score='||l_score);
4440 
4441               /*===================================================
4442                * in 11.5.11, support aging bucket line for all level;
4443                * clchang added 11/20/04.
4444                * Get Aging_Bucket_Line_id for each party/acct/site
4445                *===================================================*/
4446 
4447                WriteLog('iexvdunb:SendLevelDunn:GetAgingBucketLineId');
4448 
4449                     AGING_DEL(
4450                       p_api_version              => p_api_version
4451                     , p_init_msg_list            => p_init_msg_list
4452                     , p_commit                   => p_commit
4453                     , p_delinquency_id           => null
4454                     , p_dunning_plan_id          => p_dunning_plan_id
4455                     , p_bucket                   => null
4456                     , p_object_code              => l_object_code
4457                     , p_object_id                => l_object_id
4458                     , x_return_status            => x_return_status
4459                     , x_msg_count                => x_msg_count
4460                     , x_msg_data                 => x_msg_data
4461                     , x_aging_bucket_line_id     => l_bucket_line_id);
4462 
4463              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - AgingDel status='||x_return_status);
4464              If ( x_return_status <> FND_API.G_RET_STS_SUCCESS) Then
4465                   FND_MESSAGE.Set_Name('IEX', 'IEX_NO_AGINGBUCKETLINE');
4466                   FND_MSG_PUB.Add;
4467                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - AgingBucketLineId notfound');
4468                   FND_FILE.PUT_LINE(FND_FILE.LOG, 'AgingBucketLineId NotFound');
4469                   RAISE FND_API.G_EXC_ERROR;
4470              END IF;
4471              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - lineid='||l_bucket_line_id);
4472 
4473               /*===========================================
4474                * Get Template_ID From iex_ag_dn_xref
4475                *===========================================*/
4476                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - RUNNING LEVEL = '||p_running_level);
4477                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bucket_line_id = '||l_bucket_line_id);
4478                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - score = '||l_score);
4479                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_plan_id = '||p_dunning_plan_id);
4480                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template');
4481                Open C_Get_TEMPLATE(l_bucket_line_id, l_score, p_running_level, p_dunning_plan_id);
4482                Fetch C_Get_TEMPLATE into
4483     	  		           L_AG_DN_XREF_ID,
4484                            l_template_id,
4485                            l_xdo_template_id,
4486                            l_method,
4487                            l_callback_flag,
4488                            l_callback_days;
4489 
4490                If ( C_GET_TEMPLATE%NOTFOUND) Then
4491                     --FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
4492                     --FND_MESSAGE.Set_Token ('INFO', 'Template_ID', FALSE);
4493                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
4494                     FND_MSG_PUB.Add;
4495                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Missing corresponding template');
4496     	              FND_FILE.PUT_LINE(FND_FILE.LOG, 'Missing corresponding template : SEND_LEVEL_DUNNING');
4497     	              RAISE FND_API.G_EXC_ERROR;
4498              END IF;
4499 
4500                --WriteLog('iexvdunb:SendLevelDunn:close C_GET_TEMPLATE');
4501                Close C_Get_TEMPLATE;
4502 
4503             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get ffm_template_id='||l_template_id);
4504             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get xdo_template_id='||l_xdo_template_id);
4505 
4506     	/*===========================================
4507                * Check the status of the template
4508                *===========================================*/
4509 
4510                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template status');
4511                Open C_TEMPLATE_STATUS(l_xdo_template_id);
4512                Fetch C_TEMPLATE_STATUS into l_template_status;
4513 
4514                If ( C_TEMPLATE_STATUS%NOTFOUND) Then
4515 
4516     		open C_TEMPLATE_NAME (l_xdo_template_id);
4517     		Fetch C_TEMPLATE_NAME into l_template_name;
4518     		close C_TEMPLATE_NAME;
4519 
4520     		FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
4521                     FND_MSG_PUB.Add;
4522                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
4523     	        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
4524     	        RAISE FND_API.G_EXC_ERROR;
4525     	   END IF;
4526                Close C_TEMPLATE_STATUS;
4527     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
4528 
4529              /*===========================================
4530               * Check template
4531               *  in 11.5.11, IEX supports fulfillment and xml publisher.
4532               *  if the current setup for delivery id FFM,
4533               *  then template_id is necessary;
4534               *  if XML, xdo_template_id is necessary;
4535               *===========================================*/
4536 
4537              l_curr_dmethod := IEX_SEND_XML_PVT.getCurrDeliveryMethod;
4538              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - curr d_method='||l_curr_dmethod);
4539              if ( (l_curr_dmethod is null or l_curr_dmethod = '') or
4540                   (l_curr_dmethod = 'FFM' and l_template_id is null)  or
4541                   (l_curr_dmethod = 'XML' and l_xdo_template_id is null ) ) then
4542                   FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
4543                   FND_MSG_PUB.Add;
4544                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Missing corresponding template');
4545                   FND_FILE.PUT_LINE(FND_FILE.LOG, 'Missing corresponding template');
4546                   RAISE FND_API.G_EXC_ERROR;
4547 
4548              end if;
4549     	 l_validation_level := FND_API.G_VALID_LEVEL_FULL;
4550     	open c_dunning_plan_dtl (p_dunning_plan_id);
4551     		 fetch c_dunning_plan_dtl into l_include_current,l_use_grace_days, l_dun_disputed_items;
4552     		 close c_dunning_plan_dtl;
4553     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_include_current :'|| l_include_current);
4554     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_use_grace_days :'|| l_use_grace_days);
4555     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_dun_disputed_items :'|| l_dun_disputed_items);
4556 
4557     		 if l_use_grace_days = 'Y' then
4558     			 iex_utilities.get_grace_days(p_api_version => p_api_version,
4559     					       p_init_msg_list     => FND_API.G_TRUE,
4560     					       p_commit            => FND_API.G_FALSE,
4561     					       p_validation_level  => l_validation_level,
4562     					       p_level             => p_running_level,
4563     					       p_party_id          => l_party_cust_id,
4564     					       p_account_id        => l_account_id,
4565     					       p_site_use_id       => l_customer_site_use_id,
4566     					       x_msg_count         => l_msg_count,
4567     					       x_msg_data          => l_msg_data,
4568     					       x_return_status     => l_return_status,
4569     					       x_grace_days        => l_grace_days);
4570     			 IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4571     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get grace days');
4572     			     x_return_status := FND_API.G_RET_STS_ERROR;
4573     			 END IF;
4574     		 end if;
4575     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_grace_days :'|| l_grace_days);
4576 
4577     		 --Start adding for bug 9156833 gnramasa 27th Nov 09
4578     		 l_validation_level := FND_API.G_VALID_LEVEL_FULL;
4579 
4580     	       /*===========================================
4581               * Check profile before send dunning
4582               *===========================================*/
4583              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  begin check customer profile');
4584 
4585               -- ctlee - check the hz_customer_profiles.dunning_letter
4586                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_party_cust_id = ' || l_party_cust_id);
4587                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_account_id = ' || l_account_id);
4588                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_customer_site_use_id = ' || l_customer_site_use_id);
4589                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_delinquency_id = ' || l_delinquency_id);
4590                 -- ctlee - check the hz_customer_profiles.dunning_letter
4591                 l_party_cust_id_check := l_party_cust_id;
4592                 l_account_id_check := l_account_id;
4593                 l_customer_site_use_id_check := l_customer_site_use_id;
4594                 l_delinquency_id_check := l_delinquency_id;
4595 
4596                if (p_running_level = 'CUSTOMER') then
4597                   l_account_id_check := null;
4598                   l_customer_site_use_id_check := null;
4599                   l_delinquency_id_check := null;
4600                elsif  (p_running_level = 'ACCOUNT') then
4601                   l_customer_site_use_id_check := null;
4602                   l_delinquency_id_check := null;
4603                elsif  (p_running_level = 'BILL_TO') then
4604                   l_delinquency_id_check := null;
4605                end if;
4606 
4607                if ( iex_utilities.DunningProfileCheck (
4608                        p_party_id => l_party_cust_id_check
4609                        , p_cust_account_id => l_account_id_check
4610                        , p_site_use_id => l_customer_site_use_id_check
4611                        , p_delinquency_id => l_delinquency_id_check     ) = 'N'
4612                   ) then
4613                     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_PROFILE_NO');
4614                     FND_MSG_PUB.Add;
4615     	              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Send dunning in customer profile set to no ');
4616                     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Send dunning in customer profile set to no ');
4617                     x_return_status := FND_API.G_RET_STS_ERROR;
4618                     GOTO end_api;
4619                end if;
4620             /*  if (p_running_level <> 'CUSTOMER') then
4621                -- ctlee - check the hz_customer_profiles_amt min_dunning_invoice_amount and min_dunning_amount
4622                if ( iex_utilities.DunningMinAmountCheck (
4623                           p_cust_account_id => l_account_id_check
4624                         , p_site_use_id => l_customer_site_use_id_check
4625                         , p_org_id => l_org_id
4626                         , p_dun_disputed_items => l_dun_disputed_items
4627     		                , p_correspondence_date => p_correspondence_date
4628     		         )       = 'N' then  --Added for Bug 10401991 20-Jan-2011 barathsr
4629     		    */
4630         if (p_running_level <> 'CUSTOMER') then
4631             l_dun_yn := iex_utilities.DunningMinAmountCheck (
4632                           p_cust_account_id => l_account_id
4633                         , p_site_use_id => l_customer_site_use_id
4634                         , p_delinquency_id => l_delinquency_id
4635                         , p_org_id => l_org_id
4636                         , p_grace_days => l_grace_days
4637     		                , p_dun_disputed_items => l_dun_disputed_items
4638     		                , p_correspondence_date => p_correspondence_date
4639     		                , p_running_level=> p_running_level
4640     		                ) ;
4641              if  l_dun_yn = 'N' then
4642                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Required min Dunning amount in customer profile ');
4643                  FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
4644                  FND_MSG_PUB.Add;
4645                  x_return_status := FND_API.G_RET_STS_ERROR;
4646                  GOTO end_api;
4647             elsif l_dun_yn = 'E' then
4648                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - When Dunning level is Account, value of profile "IEX: Minimum Dunning Amount Profile Check" can''t be "Bill To" or "Bill To and Account".  ');
4649                  FND_MESSAGE.Set_Name('IEX', 'IEX_DUN_CUST_PRF_INVALID');
4650                  FND_MSG_PUB.Add;
4651                  x_return_status := FND_API.G_RET_STS_ERROR;
4652                  GOTO end_api;
4653             end if;
4654         else
4655     	     open c_cust_acct_amt_due_rem(l_object_id,l_org_id,p_correspondence_date, l_grace_days,l_dun_disputed_items);
4656     	     Fetch c_cust_acct_amt_due_rem into l_amt_due_remaining;
4657     	     close c_cust_acct_amt_due_rem;
4658 
4659     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Accounted Amount due remaining at customer level ' || l_amt_due_remaining);
4660 
4661                  open  c_cust_acct_cm_tot_amt_rem(l_object_id,l_org_id);
4662     	     Fetch c_cust_acct_cm_tot_amt_rem into l_cust_acct_cm_tot_amt_rem;
4663     	     close c_cust_acct_cm_tot_amt_rem;
4664 
4665     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  cm/ar Amount due remaining at customer level ' || l_cust_acct_cm_tot_amt_rem);
4666 
4667                   l_total_amount_due_remaining :=   l_amt_due_remaining + l_cust_acct_cm_tot_amt_rem; --(l_cust_acct_cm_tot_amt_rem is -ve value so using + sign)
4668                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  final Amount due remaining at customer level ' || l_total_amount_due_remaining);
4669 
4670     		     if l_total_amount_due_remaining <= 0 then
4671     			     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
4672     			     FND_MSG_PUB.Add;
4673     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Amount due remaining is less than 0 ');
4674     			     FND_FILE.PUT_LINE(FND_FILE.LOG, ' Amount due remaining is less than 0 ');
4675     			     x_return_status := FND_API.G_RET_STS_ERROR;
4676     			     GOTO end_api;
4677     		     end if;
4678 
4679                end if;
4680              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  end check customer profile');
4681 
4682     	 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  p_dunning_mode :'|| p_dunning_mode);
4683 
4684     	 --If dunning mode is draft then don't close the previous duning records.
4685              vPLSQL1 := 'select count(*) from ( ' ||
4686     							'    select del.delinquency_id, ' ||
4687     							'	   del.transaction_id, ' ||
4688     							'	   del.payment_schedule_id  ' ||
4689     							'    from iex_delinquencies del, ' ||
4690     							'	 ar_payment_schedules arp ' ||
4691     							'    where del.payment_schedule_id = arp.payment_schedule_id ' ||
4692     							'    and del.status in (''DELINQUENT'',''PREDELINQUENT'') ' ||
4693     							'    and (trunc(arp.due_date) + :p_grace_days) <= :p_corr_date ' ||
4694     							'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ';
4695  --Commenting include current because only if delinquent invoice count is > 0 we send dunning else skip
4696     				/*	if upper(l_include_current) = 'Y' then    -- Bills Receivables
4697               -- if l_include_current = 'y' then
4698     					   vPLSQL2 := '    union all ' ||
4699     						   'select null, arp.customer_trx_id, ' ||
4700     						   'arp.payment_schedule_id ' ||
4701     				                   'from ar_payment_schedules arp ' ||
4702     					           ', hz_cust_accounts hca ' ||    -- Bills Receivables
4703     				                   'where arp.customer_id = hca.cust_account_id ' ||   -- Bills Receivables
4704     				                   'and arp.status = ''OP'' ' || -- Bills Receivables
4705                                 --                   'where arp.status = ''OP'' ' || -- Bills Receivables
4706     				                   'and arp.amount_due_remaining <> 0 ' ||
4707     						   'and (arp.class = ''INV'' or arp.class = ''BR'') ' ||  -- Bills Receivables change
4708     				                   'and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
4709                                      		    --'and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'' )  and  hca.party_id = :p_party_id ' ;  -- Bills Receivables
4710                                             'and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'' ) ' ; -- Bills Receivables
4711               else
4712     				       vPLSQL2 := ' ';
4713     				  end if;*/
4714 
4715               vPLSQL2 := ' ';
4716 
4717               if (p_running_level = 'CUSTOMER') then
4718     					      vPLSQL3		:= vPLSQL1 || '    and del.party_cust_id = :p_party_id ' ;
4719 
4720                     /*if upper(l_include_current) = 'Y' then
4721                        vPLSQL3		:=  vPLSQL3		|| vPLSQL2 || ' and   hca.party_id = :p_party_id ' ;
4722                     end if;*/
4723                              --' and  hca.party_id = :p_party_id )'; commented and added to vPLSQL2 to fix 13473188 by snuthala 7/12/2011
4724     					elsif  (p_running_level = 'ACCOUNT') then
4725     					      vPLSQL3		:= vPLSQL1 || '    and del.cust_account_id = :p_cust_acct_id ' ||
4726     					                           --Begin Bug 10401991 03-feb-2011 barathsr
4727     					                           '    and arp.amount_due_remaining >= NVL ( '||
4728     								   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
4729     								   '	FROM hz_cust_profile_amts '||
4730     								   '	WHERE site_use_id  IS NULL '||
4731     								   '	AND cust_account_id = arp.customer_id '||
4732     								   '	AND currency_code   = arp.invoice_currency_code),0) ';
4733     								 /* if upper(l_include_current) = 'Y' then
4734                        vPLSQL3		:=  vPLSQL3		||  vPLSQL2 ||
4735     								   '    and  arp.customer_id = :p_cust_acct_id '||
4736     								   '    and arp.amount_due_remaining >= NVL ( '||
4737     								   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
4738     								   '	FROM hz_cust_profile_amts '||
4739     								   '	WHERE site_use_id  IS NULL '||
4740     								   '	AND cust_account_id = arp.customer_id '||
4741     								   '	AND currency_code   = arp.invoice_currency_code),0)';
4742                     end if;*/
4743     					elsif  (p_running_level = 'BILL_TO') then
4744     					      vPLSQL3		:= vPLSQL1 || '    and del.customer_site_use_id = :p_site_use_id ' ||
4745     					                           '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
4746     								   '	from hz_cust_profile_amts '||
4747     								   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
4748     								   '	and currency_code = arp.invoice_currency_code),0)' ;
4749     								   /*if upper(l_include_current) = 'Y' then
4750                        vPLSQL3		:=  vPLSQL3		||  vPLSQL2 ||
4751     								   '    and  arp.customer_site_use_id = :p_site_use_id ' ||
4752     								   '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
4753     								   '	from hz_cust_profile_amts '||
4754     								   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
4755     								   '	and currency_code = arp.invoice_currency_code),0)';
4756 
4757                     end if;*/
4758                        					end if;                 --End Bug 10401991 03-feb-2011 barathsr
4759                 vPLSQL3 := vPLSQL3 || ' )';
4760     					  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - vPLSQL3 :'||vPLSQL3);
4761     					 /*if upper(l_include_current) = 'Y' then
4762     					                       open sql_cur3 for vPLSQL3 using
4763     								    0,
4764     								    p_correspondence_date,
4765     								    l_dun_disputed_items,
4766     								    l_object_id,
4767     	                  l_dun_disputed_items,
4768     								    l_object_id;
4769 
4770     				           else*/
4771     							/*if p_running_level = 'CUSTOMER'	then
4772 
4773 							    open sql_cur3 for vPLSQL3 using
4774     								    l_grace_days,
4775     								    p_correspondence_date,
4776     								    l_dun_disputed_items,
4777 								    --l_object_id, commented to fix 13473188 by snuthala 7/12/2011
4778     								    l_object_id;
4779 						            else*/
4780 								   open sql_cur3 for vPLSQL3 using
4781     								    l_grace_days,
4782     								    p_correspondence_date,
4783     								    l_dun_disputed_items,
4784 								        --l_object_id,
4785     								    l_object_id;
4786                 --end if;
4787 
4788 
4789     					 --end if;
4790 
4791     					fetch sql_cur3 into l_acc_dunning_trx_null_dun_ct;
4792     					close sql_cur3;
4793 
4794     					WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_acc_dunning_trx_null_dun_ct :'||l_acc_dunning_trx_null_dun_ct);
4795     					if l_acc_dunning_trx_null_dun_ct <> 0 then
4796     						WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Transaction exist , so will continue...');
4797     						l_skip_this_dunn_planlineid := 0;
4798     						if l_first_satified_dunnplanid is null then
4799     							l_first_satified_dunnplanid := 1;
4800 
4801     						else
4802     							l_first_satified_dunnplanid := 0;
4803     						end if;
4804     						 else
4805     						 GOTO END_API;
4806     					 end if;
4807 
4808     	 --Start adding for bug 8489610 by gnramasa 14-May-09
4809     	 if p_dunning_mode <> 'DRAFT' then
4810     		  /*===========================================
4811     		   * Close OPEN Dunnings for each party/account
4812     		   *===========================================*/
4813     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning');
4814 
4815     		 /* if p_dunning_mode = 'DRAFT' then
4816     			l_status := 'CLOSE';
4817     		  else
4818     			l_status := 'OPEN';
4819     		  end if;
4820                      */
4821     		  Close_DUNNING(
4822     			p_api_version              => p_api_version
4823     		      , p_init_msg_list            => p_init_msg_list
4824     		      , p_commit                   => p_commit
4825     		      , p_delinquencies_tbl        => l_del_tbl
4826     		      , p_running_level            => p_running_level
4827     		      --, p_status                   => l_status
4828     		      , x_return_status            => x_return_status
4829     		      , x_msg_count                => x_msg_count
4830     		      , x_msg_data                 => x_msg_data);
4831 
4832     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning status='|| x_return_status);
4833 
4834     		  IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4835     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Close Dunning');
4836     			FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cannot Close Dunning');
4837     			x_return_status := FND_API.G_RET_STS_ERROR;
4838     			GOTO end_api;
4839     		  END IF;
4840     		  --WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndCloseDunn');
4841     	 end if;
4842 
4843               /*===========================================
4844                * Create Dunning Record
4845                *===========================================*/
4846               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get CallbackDate');
4847               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag='||l_callback_flag);
4848               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDays='||l_callback_days);
4849 
4850                 /*===================================================
4851                  * clchang updated 02/13/2003
4852                  * callback_days could be null if callback_yn = 'N';
4853                  * and if callback_yn = 'N', not get callback_date;
4854                  *==================================================*/
4855                  IF (l_callback_flag = 'Y') THEN
4856 
4857     		             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is Y: GetCallbackDate');
4858     		             Get_Callback_Date(p_init_msg_list          => FND_API.G_FALSE
4859     		                              ,p_callback_days          => l_callback_days
4860     		                              ,x_callback_date          => l_callback_date
4861     		                              ,x_return_status          => x_return_status
4862     		                              ,x_msg_count              => x_msg_count
4863     		                              ,x_msg_data               => x_msg_data);
4864 
4865     		             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetCallbackDate status='|| x_return_status);
4866 
4867     		             IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4868     		               FND_MESSAGE.Set_Name('IEX', 'IEX_NO_CALLBACKDATE');
4869     		               FND_MSG_PUB.Add;
4870     		               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot find callback date');
4871     		               FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cannot find callback date');
4872     		               x_return_status := FND_API.G_RET_STS_ERROR;
4873     		               GOTO end_api;
4874     		             END IF;
4875 
4876                  ELSE
4877                      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is N: NOTGetCallbackDate');
4878 
4879                  END IF;
4880 
4881                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDate='||l_callback_date);
4882                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Create Dunning');
4883                  l_dunning_rec.dunning_level := p_running_level;
4884                  l_dunning_rec.dunning_object_id := l_object_id;
4885                  l_dunning_rec.callback_yn := l_callback_flag;
4886                  l_dunning_rec.callback_date := l_callback_date;
4887                  l_dunning_rec.ag_dn_xref_id	:= l_ag_dn_xref_id;
4888 
4889     	     if p_dunning_mode = 'DRAFT' then
4890     		l_dunning_rec.status := 'CLOSE';
4891     	     else
4892     		l_dunning_rec.status := 'OPEN';
4893     	     end if;
4894 
4895                  l_dunning_rec.dunning_method := l_method;
4896 
4897                  if (l_curr_dmethod = 'FFM') then
4898                      l_dunning_rec.template_id:= l_template_id;
4899                      l_dunning_rec.ffm_request_id := l_request_id;
4900                  else
4901                      l_dunning_rec.xml_template_id:= l_xdo_template_id;
4902                      l_dunning_rec.xml_request_id := l_request_id;
4903                  end if;
4904                  l_dunning_rec.object_type := l_object_code;
4905                  l_dunning_rec.object_id := l_object_id;
4906                  l_dunning_rec.amount_due_remaining := l_amount;
4907                  l_dunning_rec.currency_code := l_curr_code;
4908                  l_dunning_rec.dunning_plan_id := p_dunning_plan_id;
4909                  l_dunning_rec.contact_destination := l_contact_destination;  -- bug 3955222
4910                  l_dunning_rec.contact_party_id := l_contact_party_id;  -- bug 3955222
4911 
4912     	     if p_parent_request_id is not null then
4913     		l_dunning_rec.request_id := p_parent_request_id;
4914     	     else
4915     		l_dunning_rec.request_id := FND_GLOBAL.Conc_Request_Id;
4916     	     end if;
4917 
4918     	     --l_dunning_rec.request_id           := FND_GLOBAL.Conc_Request_Id;
4919     	     l_dunning_rec.dunning_mode := p_dunning_mode;
4920     	     l_dunning_rec.confirmation_mode := p_confirmation_mode;
4921                  l_dunning_rec.org_id := l_org_id;  -- added for bug 9151851
4922     	     l_dunning_rec.as_of_date := p_correspondence_date;
4923 
4924                  WriteLog( ' before create dunning org_id ' || l_org_id);
4925                  CREATE_DUNNING(
4926                        p_api_version              => p_api_version
4927                      , p_init_msg_list            => p_init_msg_list
4928                      , p_commit                   => p_commit
4929                      , p_dunning_rec              => l_dunning_rec
4930                      , x_dunning_id               => l_dunning_id
4931                      , x_return_status            => x_return_status
4932                      , x_msg_count                => x_msg_count
4933                      , x_msg_data                 => x_msg_data);
4934 
4935                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| x_return_status);
4936 
4937                   IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4938                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
4939                        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cannot Create Dunning');
4940                        x_return_status := FND_API.G_RET_STS_ERROR;
4941                        GOTO end_api;
4942                   END IF;
4943 
4944                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningId='||l_dunning_id);
4945                   FND_FILE.PUT_LINE(FND_FILE.LOG, 'Create Dunning Id='|| l_dunning_id);
4946 
4947     		  INSERT_DUNNING_TRANSACTION(
4948     				p_api_version              => p_api_version
4949     			      , p_init_msg_list            => p_init_msg_list
4950     			      , p_commit                   => p_commit
4951     			      , p_delinquencies_tbl        => l_del_tbl
4952     			      , p_ag_dn_xref_id	           => l_ag_dn_xref_id
4953     			      , p_dunning_id               => l_dunning_id
4954     			      , p_correspondence_date      => p_correspondence_date
4955     			      , p_running_level            => p_running_level
4956     			      , p_grace_days               => l_grace_days
4957     			      , p_include_dispute_items    => l_dun_disputed_items
4958     			      , x_return_status            => x_return_status
4959     			      , x_msg_count                => x_msg_count
4960     			      , x_msg_data                 => x_msg_data
4961                               ,p_workitem_id               => null);   -- bug 14772139
4962 
4963                   l_dunn_cnt := l_dunn_cnt + 1;
4964 
4965               /*===========================================
4966                * Send letter thru fulfillment
4967                *===========================================*/
4968              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND_FFM');
4969              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org_id='||l_org_id);
4970              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id='||l_party_cust_id);
4971              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - method='||l_method);
4972 
4973              l_bind_tbl(1).key_name := 'party_id';
4974              l_bind_tbl(1).key_type := 'NUMBER';
4975              l_bind_tbl(1).key_value := l_party_cust_id;
4976     	 --Begin Bug 10401991 20-Jan-2011 barathsr
4977              l_bind_tbl(2).key_name := 'org_id';
4978              l_bind_tbl(2).key_type := 'NUMBER';
4979              l_bind_tbl(2).key_value := l_org_id;
4980     	 --End Bug 10401991 20-Jan-2011 barathsr
4981              l_bind_tbl(3).key_name := 'account_id';
4982              l_bind_tbl(3).key_type := 'NUMBER';
4983              l_bind_tbl(3).key_value := l_account_id;
4984              -- new bind rec since 11.5.10 (for BILL_TO)
4985              l_bind_tbl(4).key_name := 'customer_site_use_id';
4986              l_bind_tbl(4).key_type := 'NUMBER';
4987              l_bind_tbl(4).key_value := l_customer_site_use_id;
4988              l_bind_tbl(5).key_name := 'DUNNING_ID';
4989              l_bind_tbl(5).key_type := 'NUMBER';
4990              l_bind_tbl(5).key_value := l_dunning_id;
4991 
4992     	 --Start adding for bug 9156833 gnramasa 27th Nov 09
4993     	 l_validation_level := FND_API.G_VALID_LEVEL_FULL;
4994 
4995     	 if (p_running_level = 'BILL_TO') then
4996     		iex_utilities.get_dunning_resource(p_api_version => p_api_version,
4997     				       p_init_msg_list     => FND_API.G_TRUE,
4998     				       p_commit            => FND_API.G_FALSE,
4999     				       p_validation_level  => l_validation_level,
5000     				       p_level             => 'DUNNING_BILLTO',
5001     				       p_level_id          => l_customer_site_use_id,
5002     				       x_msg_count         => l_msg_count,
5003     				       x_msg_data          => l_msg_data,
5004     				       x_return_status     => l_return_status,
5005     				       x_resource_tab      => l_resource_tab);
5006     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5007     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
5008     		     x_return_status := FND_API.G_RET_STS_ERROR;
5009     		     GOTO end_get_resource;
5010     		END IF;
5011     	  end if;
5012 
5013     	  if l_resource_tab.count<1 and (p_running_level = 'ACCOUNT') then
5014     		  iex_utilities.get_dunning_resource(p_api_version => p_api_version,
5015     				       p_init_msg_list     => FND_API.G_TRUE,
5016     				       p_commit            => FND_API.G_FALSE,
5017     				       p_validation_level  => l_validation_level,
5018     				       p_level             => 'DUNNING_ACCOUNT',
5019     				       p_level_id          => l_account_id,
5020     				       x_msg_count         => l_msg_count,
5021     				       x_msg_data          => l_msg_data,
5022     				       x_return_status     => l_return_status,
5023     				       x_resource_tab      => l_resource_tab);
5024     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5025     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
5026     		     x_return_status := FND_API.G_RET_STS_ERROR;
5027     		     GOTO end_get_resource;
5028     		END IF;
5029     	  end if;
5030 
5031     	  if l_resource_tab.count<1 and (p_running_level = 'CUSTOMER') then
5032     		iex_utilities.get_dunning_resource(p_api_version => p_api_version,
5033     				       p_init_msg_list     => FND_API.G_TRUE,
5034     				       p_commit            => FND_API.G_FALSE,
5035     				       p_validation_level  => l_validation_level,
5036     				       p_level             => 'DUNNING_PARTY',
5037     				       p_level_id          => l_party_cust_id,
5038     				       x_msg_count         => l_msg_count,
5039     				       x_msg_data          => l_msg_data,
5040     				       x_return_status     => l_return_status,
5041     				       x_resource_tab      => l_resource_tab);
5042     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5043     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
5044     		     x_return_status := FND_API.G_RET_STS_ERROR;
5045     		     GOTO end_get_resource;
5046     		END IF;
5047 
5048     		if l_resource_tab.count<1 and (p_running_level = 'CUSTOMER') then
5049     			iex_utilities.get_dunning_resource(p_api_version => p_api_version,
5050     						         p_init_msg_list     => FND_API.G_TRUE,
5051     							 p_commit            => FND_API.G_FALSE,
5052     							 p_validation_level  => l_validation_level,
5053     							 p_level             => 'DUNNING_PARTY_ACCOUNT',
5054     							 p_level_id          => l_party_cust_id,
5055     							 x_msg_count         => l_msg_count,
5056     							 x_msg_data          => l_msg_data,
5057     							 x_return_status     => l_return_status,
5058     							 x_resource_tab      => l_resource_tab);
5059     			IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5060     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
5061     			     x_return_status := FND_API.G_RET_STS_ERROR;
5062     			     GOTO end_get_resource;
5063     			END IF;
5064     		end if;
5065     	  end if;
5066 
5067     	  <<end_get_resource>>
5068     	  if l_resource_tab.count>0 then
5069     	    l_resource_id := l_resource_tab(1).resource_id;
5070     	  end if;
5071     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_resource_id: ' || l_resource_id);
5072     	  --End adding for bug 9156833 gnramasa 27th Nov 09
5073               WriteLog( ' before send_xml org_id ' || l_org_id);
5074             /**
5075              * in 11.5.11, IEX supports fulfillment and xml publisher.
5076              * it depends on the set up in IEX ADMIN/SETUP.
5077              */
5078              if (l_curr_dmethod = 'FFM') then
5079 
5080               Send_Fulfillment(p_api_version              => p_api_version
5081                               ,p_init_msg_list            => FND_API.G_FALSE
5082                               ,p_commit                   => FND_API.G_TRUE
5083                               ,p_fulfillment_bind_tbl     => l_bind_tbl
5084                               ,p_template_id              => l_template_id
5085                               ,p_method                   => l_method
5086                               ,p_party_id                 => l_party_cust_id
5087                               ,x_request_id               => l_request_id
5088                               ,x_return_status            => x_return_status
5089                               ,x_msg_count                => x_msg_count
5090                               ,x_msg_data                 => x_msg_data
5091                               ,x_contact_destination      => l_contact_destination
5092                               ,x_contact_party_id         => l_contact_party_id
5093     													);
5094              else
5095 
5096               Send_XML(p_api_version              => p_api_version
5097                       ,p_init_msg_list            => FND_API.G_FALSE
5098                       ,p_commit                   => FND_API.G_TRUE
5099                       ,p_resend                   => 'N'
5100                       ,p_request_id               => null
5101                       ,p_fulfillment_bind_tbl     => l_bind_tbl
5102                       ,p_template_id              => l_xdo_template_id
5103                       ,p_method                   => l_method
5104                       ,p_party_id                 => l_party_cust_id
5105                       ,p_level                    => p_running_level
5106                       ,p_source_id                => l_object_id
5107                       ,p_object_code              => l_object_code
5108                       ,p_object_id                => l_object_id
5109     		  ,p_resource_id              => l_resource_id --Added for bug 9156833 gnramasa 27th Nov 09
5110     		  ,p_dunning_mode             => p_dunning_mode
5111     		  ,p_parent_request_id        => p_parent_request_id
5112                       ,p_org_id                   => l_org_id
5113     		  ,x_request_id               => l_request_id
5114                       ,x_return_status            => x_return_status
5115                       ,x_msg_count                => x_msg_count
5116                       ,x_msg_data                 => x_msg_data
5117                       ,x_contact_destination      => l_contact_destination
5118                       ,x_contact_party_id         => l_contact_party_id);
5119              end if;
5120 
5121              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND status='|| x_return_status);
5122     	 --End adding for bug 8489610 by gnramasa 14-May-09
5123 
5124              IF x_return_status <> FND_API.G_RET_STS_SUCCESS and x_return_status <> 'W'  THEN
5125                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Sending process failed');
5126                  FND_FILE.PUT_LINE(FND_FILE.LOG, 'Sending process failed ');
5127                  x_return_status := FND_API.G_RET_STS_ERROR;
5128                  GOTO end_api;
5129              elsif x_return_status = 'W' then
5130                  l_warning_flag := 'W';
5131              END IF;
5132 
5133               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id = ' ||l_request_id);
5134               FND_FILE.PUT_LINE(FND_FILE.LOG, 'Request Id = ' || l_request_id);
5135               l_ffm_cnt := l_ffm_cnt + 1;
5136 
5137                 l_dunning_rec_upd.dunning_id := l_dunning_id;
5138                 if (l_curr_dmethod = 'FFM') then
5139                     l_dunning_rec_upd.ffm_request_id := l_request_id;
5140                 else
5141                     l_dunning_rec_upd.xml_request_id := l_request_id;
5142                 end if;
5143 
5144                 IEX_DUNNING_PVT.Update_DUNNING(
5145                     p_api_version              => 1.0
5146                     , p_init_msg_list            => FND_API.G_FALSE
5147                     , p_commit                   => FND_API.G_TRUE
5148                     , p_dunning_rec              => l_dunning_rec_upd
5149                     , x_return_status            => l_return_status
5150                     , x_msg_count                => l_msg_count
5151                     , x_msg_data                 => l_msg_data
5152                 );
5153 
5154               <<end_api>>
5155     	      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_skip_this_dunn_planlineid: '|| l_skip_this_dunn_planlineid);
5156     		  if l_skip_this_dunn_planlineid = 1 then
5157     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Transaction doesn''t exist , so skipping...');
5158     			goto end_api;
5159     		  end if;
5160 
5161               if (x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
5162                   FND_MSG_PUB.Count_And_Get
5163                   (  p_count          =>   x_msg_count,
5164                      p_data           =>   x_msg_data );
5165                   for i in 1..x_msg_count loop
5166                     errmsg := FND_MSG_PUB.Get(p_msg_index => i,
5167                                               p_encoded => 'F');
5168                     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Error:'||errmsg);
5169                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  errmsg=' || errmsg);
5170                   end loop;
5171               end if;
5172               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api');
5173 
5174          ELSE -- l_noskip = 0
5175               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - all del disputed');
5176               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - skip this party/accnt/site');
5177     	  if (l_turnoff_coll_on_bankru = 'Y' and l_no_of_bankruptcy >0 ) then
5178     		FND_FILE.PUT_LINE(FND_FILE.LOG, 'Profile IEX: Turn Off Collections Activity for Bankruptcy is Yes and bankruptcy record is exist, so will skip send dunning' );
5179     	  else
5180     		FND_FILE.PUT_LINE(FND_FILE.LOG, 'all delinquencies disputed' );
5181     	  end if;
5182               FND_FILE.PUT_LINE(FND_FILE.LOG, 'skip this party/account/site' );
5183               FND_MSG_PUB.Count_And_Get(  p_count          =>   x_msg_count,
5184                                           p_data           =>   x_msg_data );
5185               x_return_status := 'SKIP'; --FND_API.G_EXC_ERROR;
5186 
5187          end if; -- end of if (l_noskip>0)
5188 
5189          if l_warning_flag = 'W' then
5190           x_return_status := 'W';
5191          end if;
5192 
5193          --
5194          -- End of API body
5195          --
5196 
5197          COMMIT WORK;
5198 
5199          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
5200 
5201          FND_MSG_PUB.Count_And_Get
5202          (  p_count          =>   x_msg_count,
5203             p_data           =>   x_msg_data );
5204 
5205          EXCEPTION
5206              WHEN FND_API.G_EXC_ERROR THEN
5207                  COMMIT WORK;
5208                  x_return_status := FND_API.G_RET_STS_ERROR;
5209                  FND_MSG_PUB.Count_And_Get
5210                  (  p_count          =>   x_msg_count,
5211                     p_data           =>   x_msg_data );
5212                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
5213                  FND_FILE.PUT_LINE(FND_FILE.LOG, 'expect exception' );
5214                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
5215 
5216              WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
5217                  COMMIT WORK;
5218                  x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5219                  FND_MSG_PUB.Count_And_Get
5220                  (  p_count          =>   x_msg_count,
5221                     p_data           =>   x_msg_data );
5222                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
5223                  FND_FILE.PUT_LINE(FND_FILE.LOG, 'unexpect exception' );
5224                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
5225 
5226              WHEN OTHERS THEN
5227                  COMMIT WORK;
5228                  x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5229                  FND_MSG_PUB.Count_And_Get
5230                  (  p_count          =>   x_msg_count,
5231                     p_data           =>   x_msg_data );
5232                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
5233                  FND_FILE.PUT_LINE(FND_FILE.LOG, 'unexpect exception' );
5234                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
5235 
5236     END Send_Level_Dunning;
5237 
5238     /*=========================================================================
5239        gnramasa create 12th Nov 09
5240         Send Staged Dunning can be in Customer, Account, Bill to and Delinquency levels in R12;
5241         Send_Level_Staged_Dunning is for Customer, Account level and Bill to level;
5242         Send_Staged_Dunning keeps the same, and is for Delinquency Level;
5243     *=========================================================================*/
5244     Procedure Send_Level_Staged_Dunning
5245                (p_api_version             IN NUMBER := 1.0,
5246                 p_init_msg_list           IN VARCHAR2 ,
5247                 p_commit                  IN VARCHAR2 ,
5248                 p_running_level           IN VARCHAR2,
5249                 p_dunning_plan_id         in number,
5250     	          p_correspondence_date     IN DATE,
5251                 p_resend_flag             IN VARCHAR2,
5252                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
5253                 p_parent_request_id       IN NUMBER,
5254     	          p_dunning_mode	      IN VARCHAR2,
5255     	          p_single_staged_letter    IN VARCHAR2 DEFAULT 'N',    -- added by gnramasa for bug stageddunning 28-Dec-09
5256     	          p_confirmation_mode	      IN VARCHAR2,
5257                 x_return_status           OUT NOCOPY VARCHAR2,
5258                 x_msg_count               OUT NOCOPY NUMBER,
5259                 x_msg_data                OUT NOCOPY VARCHAR2)
5260 
5261     IS
5262         CURSOR C_GET_DEL (IN_del_ID NUMBER) IS
5263           SELECT delinquency_ID
5264             FROM IEX_DELINQUENCIES_ALL
5265            WHERE delinquency_ID = in_del_ID;
5266         --
5267         -- begin bug 4914799 ctlee 12/30/2005 add p_dunning_plan_id
5268         CURSOR C_GET_SCORE (IN_ID NUMBER, IN_CODE VARCHAR2, p_dunning_plan_id number) IS
5269           SELECT a.score_value
5270             FROM IEX_SCORE_HISTORIES a
5271                  , IEX_DUNNING_PLANS_VL c  -- bug 4914799 ctlee 12/30/2005
5272            WHERE a.score_object_ID = in_ID
5273              AND a.score_object_code = IN_CODE
5274              and c.score_id = a.score_id   -- bug 4914799 ctlee 12/30/2005
5275              and c.dunning_plan_id = p_dunning_plan_id -- bug 4914799 ctlee 12/30/2005
5276              AND a.creation_date = (select max(b.creation_date)
5277                                       from iex_score_histories b
5278                                      where b.score_object_id = in_id
5279                                        AND b.score_object_code = IN_CODE
5280     				   AND b.score_id = a.score_id );
5281         -- end bug 4914799 ctlee 12/30/2005 add p_dunning_plan_id
5282 
5283         CURSOR C_GET_TEMPLATE (l_line_id NUMBER,
5284                                l_score NUMBER, in_LEVEL VARCHAR2, p_dunning_plan_id number) IS
5285           SELECT x.template_id,
5286                  x.xdo_template_id,
5287                  x.fm_method,
5288                  upper(x.callback_flag),
5289                  x.callback_days
5290             FROM IEX_AG_DN_XREF x,
5291                  ar_aging_buckets ar,
5292                  iex_dunning_plans_vl d
5293            WHERE x.aging_bucket_line_ID = l_line_ID
5294              and x.dunning_plan_id = p_dunning_plan_id
5295              AND l_score between x.score_range_low and x.score_range_high
5296              AND x.aging_bucket_id = ar.aging_bucket_id
5297              and ar.aging_bucket_id = d.aging_bucket_id
5298              AND ar.status = 'A'
5299              AND x.dunning_level = IN_LEVEL ;
5300 
5301          CURSOR C_TEMPLATE_STATUS (l_template_id number) is
5302          select 'Active'
5303          from xdo_templates_vl xdo
5304          where xdo.template_id = l_template_id
5305          and trunc(sysdate) >= TRUNC (NVL(xdo.start_date, sysdate))
5306          and trunc(sysdate) < TRUNC(NVL(xdo.end_date, sysdate + 1));
5307 
5308          l_template_status		  varchar2(10);
5309 
5310          CURSOR C_TEMPLATE_NAME (l_template_id number) is
5311          select template_name
5312          from xdo_templates_vl xdo
5313          where xdo.template_id = l_template_id;
5314 
5315          l_template_name	varchar2(500);
5316 
5317         cursor c_dunningplan_lines(p_dunn_plan_id number, p_orderby varchar2) is
5318         select ag_dn_xref_id,
5319                dunning_level,
5320                template_id,
5321                xdo_template_id,
5322                fm_method,
5323                upper(callback_flag) callback_flag,
5324                callback_days,
5325     	   range_of_dunning_level_from,
5326     	   range_of_dunning_level_to,
5327     	   min_days_between_dunning,
5328     	   invoice_copies
5329         from iex_ag_dn_xref
5330         where dunning_plan_id = p_dunn_plan_id
5331         order by AG_DN_XREF_ID ;
5332 
5333         Type refCur             is Ref Cursor;
5334         sql_cur                 refCur;
5335         sql_cur1                refCur;
5336         sql_cur2                refCur;
5337         sql_cur3                refCur;
5338         vPLSQL                  VARCHAR2(4000);
5339         vPLSQL1                 VARCHAR2(4000);
5340         vPLSQL2                 VARCHAR2(4000);
5341         vPLSQL3                 VARCHAR2(4000);
5342         l_orderby		    varchar2(20);
5343         l_no_of_rows            number;
5344         l_include_current       varchar2(1);
5345         cursor c_dunning_plan_dtl (p_dunn_plan_id number) is
5346         select nvl(dunn.INCLUDE_CURRENT,'N'),
5347                nvl(dunn.grace_days ,'N'),
5348                nvl(dunn.dun_disputed_items, 'N')
5349         from iex_dunning_plans_b dunn
5350         where dunning_plan_id = p_dunn_plan_id;
5351 
5352         l_dunningplan_lines	    c_dunningplan_lines%rowtype;
5353 
5354         l_DUNNING_id            NUMBER;
5355         l_delinquency_id        NUMBER;
5356         l_party_cust_id         NUMBER;
5357         l_account_id            NUMBER;
5358         l_customer_site_use_id  NUMBER;
5359         l_noskip                NUMBER := 0;
5360         l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
5361         l_DUNNING_tbl           IEX_DUNNING_PUB.DUNNING_TBL_TYPE;
5362         l_dunning_rec_upd       IEX_DUNNING_PUB.DUNNING_REC_TYPE;
5363         l_score                 NUMBER;
5364         l_bucket_line_id        NUMBER;
5365         l_campaign_sched_id     NUMBER;
5366         l_template_id           NUMBER;
5367         l_xdo_template_id       NUMBER;
5368         l_method                VARCHAR2(10);
5369         l_callback_flag         VARCHAR2(1);
5370         l_callback_days         NUMBER;
5371         l_callback_date         DATE;
5372         l_request_id            NUMBER;
5373         l_outcome_code          varchar2(20);
5374         l_api_name              CONSTANT VARCHAR2(30) := 'Send_Level_Staged_Dunning';
5375         l_api_version_number    CONSTANT NUMBER   := 1.0;
5376         l_return_status         VARCHAR2(1);
5377         l_msg_count             NUMBER;
5378         l_msg_data              VARCHAR2(32767);
5379         errmsg                  VARCHAR2(32767);
5380         --
5381         nIdx                    NUMBER := 0;
5382         TYPE Del_ID_TBL_type is Table of IEX_DELINQUENCIES_ALL.DELINQUENCY_ID%TYPE
5383                                 INDEX BY BINARY_INTEGER;
5384         Del_Tbl                 Del_ID_TBL_TYPE;
5385         l_bind_tbl              IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
5386         l_bind_rec              IEX_DUNNING_PVT.FULFILLMENT_BIND_REC;
5387         l_org_id                NUMBER ;
5388         l_object_Code           VARCHAR2(25);
5389         l_object_id             NUMBER;
5390         --l_delid_tbl             IEX_DUNNING_PUB.DelId_NumList;
5391         l_del_tbl               IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE;
5392         l_curr_code             VARCHAR2(15);
5393         l_amount                NUMBER;
5394         l_write                 NUMBER;
5395         l_ffm_cnt               NUMBER := 0;
5396         l_dunn_cnt              NUMBER := 0;
5397         l_curr_dmethod          VARCHAR2(10);
5398         -- begin raverma 03/09/06 add contact point selection
5399         l_location_id           number;
5400         l_amount_disputed       number;
5401         l_contact_id            number;
5402         l_warning_flag          varchar2(1);
5403         l_contact_point_id      number;
5404 
5405         l_delinquency_id_check        NUMBER;
5406         l_party_cust_id_check         NUMBER;
5407         l_account_id_check            NUMBER;
5408         l_customer_site_use_id_check  NUMBER;
5409         l_contact_destination         varchar2(240);  -- bug 3955222
5410         l_contact_party_id            number; -- bug 3955222
5411         l_fully_promised              number := 1; -- bug# 8408162
5412         l_allow_send                  varchar2(1) := 'Y';  -- bug#8408162
5413         l_status                      varchar2(10);
5414         l_ag_dn_xref_id	          number;
5415         l_atleast_one_trx		  varchar2(10);
5416         l_stage			  number;
5417         l_acc_dunning_trx_null_dun_ct number;
5418         l_acc_dunning_trx_ct	  number;
5419         l_skip_this_dunn_planlineid   number;
5420         l_first_satified_dunnplanid   number;
5421         l_grace_days                  number := 0;
5422         l_use_grace_days              varchar2(10);
5423         l_dun_disputed_items          varchar2(10);
5424         l_inc_inv_curr                IEX_UTILITIES.INC_INV_CURR_TBL;
5425         l_dunn_letters                varchar2(10);
5426 
5427         --Start adding for bug 9156833 gnramasa 27th Nov 09
5428         l_validation_level		  NUMBER ;
5429         l_resource_tab		  iex_utilities.resource_tab_type;
5430         l_resource_id		  NUMBER;
5431         --End adding for bug 9156833 gnramasa 27th Nov 09
5432         l_turnoff_coll_on_bankru	  varchar2(10);
5433         l_no_of_bankruptcy		  number;
5434         l_min_days_between_dunn_99	  number;
5435 
5436         cursor c_no_of_bankruptcy (p_par_id number)
5437         is
5438         select nvl(count(*),0)
5439         from iex_bankruptcies
5440         where party_id = p_par_id
5441         and (disposition_code in ('GRANTED','NEGOTIATION')
5442              OR (disposition_code is NULL));
5443 
5444         cursor c_min_days_between_dunn_99 (p_dunn_plan_id number, p_stage_no number, p_score_val number)
5445         is
5446         select min_days_between_dunning
5447         from iex_ag_dn_xref
5448         where dunning_plan_id = p_dunn_plan_id
5449         and p_stage_no between range_of_dunning_level_from and range_of_dunning_level_to
5450         and p_score_val between score_range_low and score_range_high;
5451 
5452         l_inv_xdo_template_id	number;
5453         l_invoice_copies    varchar(10);
5454         t_id  number;
5455         t_code varchar2(50);
5456 
5457     BEGIN
5458           -- Standard Start of API savepoint
5459           SAVEPOINT Send_Level_Staged_Dunning_PVT;
5460 
5461           --Bug#4679639 schekuri 20-OCT-2005
5462           --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
5463           --l_org_id := fnd_profile.value('ORG_ID');
5464           l_org_id:= mo_global.get_current_org_id;
5465           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_org_id = ' || l_org_id);
5466 
5467           -- Standard call to check for call compatibility.
5468           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
5469                                                p_api_version,
5470                                                l_api_name,
5471                                                G_PKG_NAME)
5472           THEN
5473               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5474           END IF;
5475 
5476           -- Initialize message list if p_init_msg_list is set to TRUE.
5477           IF FND_API.to_Boolean( p_init_msg_list )
5478           THEN
5479               FND_MSG_PUB.initialize;
5480           END IF;
5481 
5482           if (p_resend_flag = 'Y') then
5483               -- don't write into FILE
5484               l_write := 0;
5485           else
5486               l_write := 1;
5487           end if;
5488 
5489           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
5490           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - running_level = ' || p_running_level);
5491           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - resend_flag =   ' || p_resend_flag);
5492           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_parent_request_id ' || p_parent_request_id);
5493           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delcnt= ' || p_delinquencies_tbl.count);
5494           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_single_staged_letter= ' || p_single_staged_letter);
5495 
5496 
5497 
5498           -- Initialize API return status to SUCCESS
5499           x_return_status := FND_API.G_RET_STS_SUCCESS;
5500           --
5501           -- Api body
5502           --
5503           l_turnoff_coll_on_bankru	:= nvl(fnd_profile.value('IEX_TURNOFF_COLLECT_BANKRUPTCY'),'N');
5504           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_turnoff_coll_on_bankru: ' || l_turnoff_coll_on_bankru);
5505 
5506           l_party_cust_id := p_delinquencies_tbl(1).party_cust_id;
5507           l_account_id := p_delinquencies_tbl(1).cust_account_id;
5508           l_customer_site_use_id := p_delinquencies_tbl(1).customer_site_use_id;
5509 
5510           --Initialize the variable to N
5511           g_included_current_invs	:= 'N';
5512           g_included_unapplied_rec  := 'N';
5513 
5514           if (p_running_level = 'CUSTOMER') then
5515               l_object_Code                     := 'PARTY';
5516               l_object_id                       := p_delinquencies_tbl(1).party_cust_id;
5517               l_del_tbl(1).party_cust_id        := p_delinquencies_tbl(1).party_cust_id;
5518               l_del_tbl(1).cust_account_id      := 0;
5519               l_del_tbl(1).customer_site_use_id := 0;
5520               --l_amount                          := party_amount_due_remaining(l_object_id);
5521               --l_curr_code                       := party_currency_code(l_object_id);
5522               --Start bug 7197038 gnramasa 8th july 08
5523     	       /*
5524     	       open C_DISPUTED_AMOUNT(P_PARTY_ID          => p_delinquencies_tbl(1).party_cust_id
5525                                     ,P_CUST_ACCOUNT_ID   => null
5526                                     ,P_SITE_USE_ID       => null);
5527     	       */
5528     	        --open C_DISPUTED_AMOUNT_PARTY(p_delinquencies_tbl(1).party_cust_id);
5529               --open c_fully_promised_party (p_delinquencies_tbl(1).party_cust_id);  -- Added for bug# 8408162
5530           elsif (p_running_level = 'ACCOUNT') then
5531               l_object_Code                     := 'IEX_ACCOUNT';
5532               l_object_id                       := p_delinquencies_tbl(1).cust_account_id;
5533               l_del_tbl(1).party_cust_id        := p_delinquencies_tbl(1).party_cust_id;
5534               l_del_tbl(1).cust_account_id      := p_delinquencies_tbl(1).cust_account_id;
5535               l_del_tbl(1).customer_site_use_id := 0;
5536               --l_amount                          := acct_amount_due_remaining(l_object_id);
5537               --l_curr_code                       := acct_currency_code(l_object_id);
5538               /*
5539     	        open C_DISPUTED_AMOUNT(P_PARTY_ID          => null
5540                                     ,P_CUST_ACCOUNT_ID   => p_delinquencies_tbl(1).party_cust_id
5541                                     ,P_SITE_USE_ID       => null);
5542     	       */
5543     	        --open C_DISPUTED_AMOUNT_ACCOUNT(p_delinquencies_tbl(1).cust_account_id);
5544               --open c_fully_promised_account (p_delinquencies_tbl(1).cust_account_id); -- Added for bug#8408162
5545           elsif (p_running_level = 'BILL_TO') then
5546               l_object_Code                     := 'IEX_BILLTO';
5547               l_object_id                       := p_delinquencies_tbl(1).customer_site_use_id;
5548               l_del_tbl(1).party_cust_id        := p_delinquencies_tbl(1).party_cust_id;
5549               l_del_tbl(1).cust_account_id      := p_delinquencies_tbl(1).cust_account_id;
5550               l_del_tbl(1).customer_site_use_id := p_delinquencies_tbl(1).customer_site_use_id;
5551 
5552               -- begin Bills Receivables
5553               begin
5554                  t_id := l_object_id;
5555                  select site_use_code into t_code from hz_cust_site_uses_all where site_use_id = l_object_id;
5556                  if t_code = 'BILL_TO' then
5557                     t_id := iex_utilities.get_BR_DrweeSiteID(l_object_id);
5558                 end if;
5559               exception
5560                 when others then t_id := l_object_id;
5561               end;
5562               -- end Bills Receivables
5563 
5564               --l_amount                          := site_amount_due_remaining(l_object_id);
5565               --l_curr_code                       := site_currency_code(l_object_id);
5566               /*
5567     	        open C_DISPUTED_AMOUNT(P_PARTY_ID          => null
5568                                     ,P_CUST_ACCOUNT_ID   => p_delinquencies_tbl(1).customer_site_use_id
5569                                     ,P_SITE_USE_ID       => null);
5570     	        */
5571     	           --open C_DISPUTED_AMOUNT_BILLTO(p_delinquencies_tbl(1).customer_site_use_id);
5572               --open c_fully_promised_billto (p_delinquencies_tbl(1).customer_site_use_id); -- Added for bug#8408162
5573           end if;
5574 
5575           if l_turnoff_coll_on_bankru = 'Y' then
5576     	       open c_no_of_bankruptcy (p_delinquencies_tbl(1).party_cust_id);
5577     	       fetch c_no_of_bankruptcy into l_no_of_bankruptcy;
5578     	       close c_no_of_bankruptcy;
5579           end if;
5580           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_no_of_bankruptcy: ' || l_no_of_bankruptcy);
5581 
5582           --if (l_amount_disputed >= 0) OR (p_resend_flag = 'Y' ) or (l_fully_promised = 0 and l_allow_send = 'Y') then  -- bug#8408162
5583           if (p_resend_flag = 'Y' OR (l_turnoff_coll_on_bankru = 'Y' and l_no_of_bankruptcy >0 ) ) then
5584                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - setting no skip = 0 ');
5585                --WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_amount_disputed ' || l_amount_disputed);
5586                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_resend_flag = ' || p_resend_flag);
5587                l_noskip := 0;
5588     			ELSE
5589                l_noskip := 1;
5590           end if;
5591 
5592           --WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount disputed less delinquency amount = ' || l_amount_disputed);
5593           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_code='||l_object_code);
5594           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id='||l_object_id);
5595           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id='||l_party_cust_id);
5596           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount_due_remaining='||l_amount);
5597           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - currency_code='||l_curr_code);
5598           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_noskip='||l_noskip);
5599 
5600           IF (l_noskip > 0) THEN
5601 
5602              -- init the msg (not including the msg from dispute api)
5603              FND_MSG_PUB.initialize;
5604 
5605               /*===========================================
5606                * Get Score From IEX_SCORE_HISTORIES
5607                * If NotFound => Call API to getScore;
5608                *===========================================*/
5609     	         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get Score');
5610     	         Open C_Get_SCORE(l_object_id, l_object_Code, p_dunning_plan_id);
5611     	         Fetch C_Get_SCORE into l_score;
5612 
5613     	         If ( C_GET_SCORE%NOTFOUND) Then
5614     	              FND_MESSAGE.Set_Name('IEX', 'IEX_NO_SCORE');
5615     	              FND_MSG_PUB.Add;
5616     	              FND_FILE.PUT_LINE(FND_FILE.LOG, 'Missing Score');
5617     	              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Missing Score');
5618     	              Close C_Get_SCORE;
5619     	              RAISE FND_API.G_EXC_ERROR;
5620     	         END IF;
5621     	         Close C_Get_SCORE;
5622     	         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get Score='||l_score);
5623 
5624     		l_validation_level := FND_API.G_VALID_LEVEL_FULL;
5625 
5626     		 open c_dunning_plan_dtl (p_dunning_plan_id);
5627     		 fetch c_dunning_plan_dtl into l_include_current,l_use_grace_days, l_dun_disputed_items;
5628     		 close c_dunning_plan_dtl;
5629     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_include_current :'|| l_include_current);
5630     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_use_grace_days :'|| l_use_grace_days);
5631     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_dun_disputed_items :'|| l_dun_disputed_items);
5632 
5633     		 if l_use_grace_days = 'Y' then
5634     			 iex_utilities.get_grace_days(p_api_version => p_api_version,
5635     					       p_init_msg_list     => FND_API.G_TRUE,
5636     					       p_commit            => FND_API.G_FALSE,
5637     					       p_validation_level  => l_validation_level,
5638     					       p_level             => p_running_level,
5639     					       p_party_id          => l_del_tbl(1).party_cust_id,
5640     					       p_account_id        => l_del_tbl(1).cust_account_id,
5641     					       p_site_use_id       => l_del_tbl(1).customer_site_use_id,
5642     					       x_msg_count         => l_msg_count,
5643     					       x_msg_data          => l_msg_data,
5644     					       x_return_status     => l_return_status,
5645     					       x_grace_days        => l_grace_days);
5646     			 IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5647     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get grace days');
5648     			     x_return_status := FND_API.G_RET_STS_ERROR;
5649     			 END IF;
5650     		 end if;
5651     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_grace_days :'|| l_grace_days);
5652 
5653     		 --Start adding for bug 9156833 gnramasa 27th Nov 09
5654     		 l_validation_level := FND_API.G_VALID_LEVEL_FULL;
5655 
5656     		 if (p_running_level = 'BILL_TO') then
5657     			iex_utilities.get_dunning_resource(p_api_version => p_api_version,
5658     					       p_init_msg_list     => FND_API.G_TRUE,
5659     					       p_commit            => FND_API.G_FALSE,
5660     					       p_validation_level  => l_validation_level,
5661     					       p_level             => 'DUNNING_BILLTO',
5662     					       p_level_id          => l_customer_site_use_id,
5663     					       x_msg_count         => l_msg_count,
5664     					       x_msg_data          => l_msg_data,
5665     					       x_return_status     => l_return_status,
5666     					       x_resource_tab      => l_resource_tab);
5667     			IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5668     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
5669     			     x_return_status := FND_API.G_RET_STS_ERROR;
5670     			     GOTO end_get_resource;
5671     			END IF;
5672     		  end if;
5673 
5674     		  if l_resource_tab.count<1 and (p_running_level = 'ACCOUNT') then
5675     			  iex_utilities.get_dunning_resource(p_api_version => p_api_version,
5676     					       p_init_msg_list     => FND_API.G_TRUE,
5677     					       p_commit            => FND_API.G_FALSE,
5678     					       p_validation_level  => l_validation_level,
5679     					       p_level             => 'DUNNING_ACCOUNT',
5680     					       p_level_id          => l_account_id,
5681     					       x_msg_count         => l_msg_count,
5682     					       x_msg_data          => l_msg_data,
5683     					       x_return_status     => l_return_status,
5684     					       x_resource_tab      => l_resource_tab);
5685     			IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5686     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
5687     			     x_return_status := FND_API.G_RET_STS_ERROR;
5688     			     GOTO end_get_resource;
5689     			END IF;
5690     		  end if;
5691 
5692     		  if l_resource_tab.count<1 and (p_running_level = 'CUSTOMER') then
5693     			iex_utilities.get_dunning_resource(p_api_version => p_api_version,
5694     					       p_init_msg_list     => FND_API.G_TRUE,
5695     					       p_commit            => FND_API.G_FALSE,
5696     					       p_validation_level  => l_validation_level,
5697     					       p_level             => 'DUNNING_PARTY',
5698     					       p_level_id          => l_party_cust_id,
5699     					       x_msg_count         => l_msg_count,
5700     					       x_msg_data          => l_msg_data,
5701     					       x_return_status     => l_return_status,
5702     					       x_resource_tab      => l_resource_tab);
5703     			IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5704     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
5705     			     x_return_status := FND_API.G_RET_STS_ERROR;
5706     			     GOTO end_get_resource;
5707     			END IF;
5708 
5709     			if l_resource_tab.count<1 and (p_running_level = 'CUSTOMER') then
5710     				iex_utilities.get_dunning_resource(p_api_version => p_api_version,
5711     								 p_init_msg_list     => FND_API.G_TRUE,
5712     								 p_commit            => FND_API.G_FALSE,
5713     								 p_validation_level  => l_validation_level,
5714     								 p_level             => 'DUNNING_PARTY_ACCOUNT',
5715     								 p_level_id          => l_party_cust_id,
5716     								 x_msg_count         => l_msg_count,
5717     								 x_msg_data          => l_msg_data,
5718     								 x_return_status     => l_return_status,
5719     								 x_resource_tab      => l_resource_tab);
5720     				IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
5721     				     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
5722     				     x_return_status := FND_API.G_RET_STS_ERROR;
5723     				     GOTO end_get_resource;
5724     				END IF;
5725     			end if;
5726     		  end if;
5727 
5728     		  <<end_get_resource>>
5729     		  if l_resource_tab.count>0 then
5730     		    l_resource_id := l_resource_tab(1).resource_id;
5731     		  end if;
5732     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_resource_id: ' || l_resource_id);
5733     		  --End adding for bug 9156833 gnramasa 27th Nov 09
5734 
5735     	    --Start bug 9696806 gnramasa 27th May 10
5736     		open c_min_days_between_dunn_99 (p_dunning_plan_id, 99, l_score);
5737     		fetch c_min_days_between_dunn_99 into l_min_days_between_dunn_99;
5738     		close c_min_days_between_dunn_99;
5739     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_min_days_between_dunn_99 :'|| l_min_days_between_dunn_99);
5740 
5741     		if (p_running_level = 'CUSTOMER') then
5742     		        update iex_delinquencies del
5743     			set staged_dunning_level = 98
5744     			where del.party_cust_id = l_object_id
5745     			and staged_dunning_level = 99
5746     			and status in ('DELINQUENT','PREDELINQUENT')
5747     			and nvl(
5748     				 (
5749     				    (select trunc(correspondence_date) from iex_dunnings
5750     				     where dunning_id =
5751     					(select max(iet.DUNNING_ID)
5752     					from iex_dunning_transactions iet,
5753     					     iex_dunnings dunn
5754     					 where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
5755     						    and dunn.dunning_id = iet.dunning_id
5756     						    and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
5757     							    OR (dunn.dunning_mode = 'FINAL'))
5758     					 and iet.STAGE_NUMBER = 99
5759     					 and dunn.delivery_status is null
5760     					)
5761     				     )
5762     				   + l_min_days_between_dunn_99
5763     				  )
5764     				     , p_correspondence_date
5765     			      )
5766     			      <= p_correspondence_date ;
5767 
5768     		elsif  (p_running_level = 'ACCOUNT') then
5769     		        update iex_delinquencies del
5770     			set staged_dunning_level = 98
5771     			where del.cust_account_id = l_object_id
5772     			and staged_dunning_level = 99
5773     			and status in ('DELINQUENT','PREDELINQUENT')
5774     			and nvl(
5775     				 (
5776     				    (select trunc(correspondence_date) from iex_dunnings
5777     				     where dunning_id =
5778     					(select max(iet.DUNNING_ID)
5779     					from iex_dunning_transactions iet,
5780     					     iex_dunnings dunn
5781     					 where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
5782     						    and dunn.dunning_id = iet.dunning_id
5783     						    and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
5784     							    OR (dunn.dunning_mode = 'FINAL'))
5785     					 and iet.STAGE_NUMBER = 99
5786     					 and dunn.delivery_status is null
5787     					)
5788     				     )
5789     				   + l_min_days_between_dunn_99
5790     				  )
5791     				     , p_correspondence_date
5792     			      )
5793     			      <= p_correspondence_date ;
5794 
5795     		elsif  (p_running_level = 'BILL_TO') then
5796     			update iex_delinquencies del
5797     			set staged_dunning_level = 98
5798     			where del.customer_site_use_id = l_object_id
5799     			and staged_dunning_level = 99
5800     			and status in ('DELINQUENT','PREDELINQUENT')
5801     			and nvl(
5802     				 (
5803     				    (select trunc(correspondence_date) from iex_dunnings
5804     				     where dunning_id =
5805     					(select max(iet.DUNNING_ID)
5806     					from iex_dunning_transactions iet,
5807     					     iex_dunnings dunn
5808     					 where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
5809     						    and dunn.dunning_id = iet.dunning_id
5810     						    and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
5811     							    OR (dunn.dunning_mode = 'FINAL'))
5812     					 and iet.STAGE_NUMBER = 99
5813     					 and dunn.delivery_status is null
5814     					)
5815     				     )
5816     				   + l_min_days_between_dunn_99
5817     				  )
5818     				     , p_correspondence_date
5819     			      )
5820     			      <= p_correspondence_date ;
5821     		end if;
5822 
5823     	    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Updated : ' || SQL%ROWCOUNT || ' number of row''s staged_dunning_level from 99 to 98');
5824     	    commit;
5825     	    --End bug 9696806 gnramasa 27th May 10
5826 
5827     	    l_account_id_check := l_account_id;
5828     	    l_customer_site_use_id_check := l_customer_site_use_id;
5829     	   if (p_running_level = 'CUSTOMER') or (p_running_level = 'ACCOUNT') then
5830     	      l_customer_site_use_id_check := null;
5831     	   end if;
5832     		   -- check the hz_customer_profiles_amt min_dunning_invoice_amount and min_dunning_amount
5833 
5834     		   iex_utilities.StagedDunningMinAmountCheck (
5835     			    p_cust_account_id => l_account_id_check
5836     			    , p_site_use_id => l_customer_site_use_id_check
5837     			    , p_party_id => l_party_cust_id
5838     			    , p_dunning_plan_id => p_dunning_plan_id
5839     			    , p_grace_days => l_grace_days
5840     			    , p_dun_disputed_items => l_dun_disputed_items
5841     			    , p_correspondence_date => p_correspondence_date
5842     			    , p_running_level => p_running_level
5843     			    , p_org_id => l_org_id  --Added for Bug 10401991 20-Jan-2011 barathsr
5844     			    , p_inc_inv_curr => l_inc_inv_curr
5845     			    , p_dunning_letters => l_dunn_letters);
5846 
5847     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_dunn_letters: ' || l_dunn_letters);
5848 
5849     		   if l_dunn_letters = 'N' then
5850     			FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
5851     			FND_MSG_PUB.Add;
5852     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Required min Dunning amount in customer profile ');
5853     			FND_FILE.PUT_LINE(FND_FILE.LOG, 'Required min Dunning amount in customer profile ');
5854     			x_return_status := FND_API.G_RET_STS_ERROR;
5855     			GOTO end_api;
5856     		   end if;
5857 
5858     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  end check customer profile');
5859 
5860     	 if upper(p_single_staged_letter) = 'N' then
5861     		l_orderby	:= 'DESC';
5862     	 else
5863     		l_orderby	:= 'DESC';
5864     	 end if;
5865 
5866     	 vPLSQL := '  select ag_dn_xref_id, ' ||
5867     		' dunning_level, ' ||
5868     	        ' template_id, ' ||
5869     		' xdo_template_id, ' ||
5870     		' fm_method, ' ||
5871     		' upper(callback_flag) callback_flag, ' ||
5872     		' callback_days, ' ||
5873     		' range_of_dunning_level_from, ' ||
5874     		' range_of_dunning_level_to, ' ||
5875     		' min_days_between_dunning, ' ||
5876     		' invoice_copies ' ||
5877     		' from iex_ag_dn_xref ' ||
5878     		' where dunning_plan_id = :p_dunning_plan_id ' ||
5879     		' AND :p_score between score_range_low and score_range_high ' ||
5880     		' order by range_of_dunning_level_from ' || l_orderby;
5881 
5882     	open sql_cur for vPLSQL using p_dunning_plan_id, l_score;
5883 
5884     	 loop
5885     		 fetch sql_cur into l_dunningplan_lines;
5886     		 exit when sql_cur%notfound;
5887 
5888     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.ag_dn_xref_id='||l_dunningplan_lines.ag_dn_xref_id);
5889     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.dunning_level='||l_dunningplan_lines.dunning_level);
5890     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.template_id='||l_dunningplan_lines.template_id);
5891     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.xdo_template_id='||l_dunningplan_lines.xdo_template_id);
5892     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.fm_method='||l_dunningplan_lines.fm_method);
5893     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.callback_flag='||l_dunningplan_lines.callback_flag);
5894     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.callback_days='||l_dunningplan_lines.callback_days);
5895     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.range_of_dunning_level_from='||l_dunningplan_lines.range_of_dunning_level_from);
5896     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.range_of_dunning_level_to='||l_dunningplan_lines.range_of_dunning_level_to);
5897     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.min_days_between_dunning='||l_dunningplan_lines.min_days_between_dunning);
5898     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.invoice_copies='||l_dunningplan_lines.invoice_copies);
5899 
5900     		 l_ag_dn_xref_id			:= l_dunningplan_lines.ag_dn_xref_id;
5901     		 l_template_id				:= l_dunningplan_lines.template_id;
5902     		 l_xdo_template_id		:= l_dunningplan_lines.xdo_template_id;
5903     		 l_method			      	:= l_dunningplan_lines.fm_method;
5904     		 l_callback_flag			:= l_dunningplan_lines.callback_flag;
5905     		 l_callback_days			:= l_dunningplan_lines.callback_days;
5906     		 l_invoice_copies			:= l_dunningplan_lines.invoice_copies;
5907 
5908     	  /*===========================================
5909                * Check the status of the template
5910                *===========================================*/
5911 
5912                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template status');
5913                Open C_TEMPLATE_STATUS(l_dunningplan_lines.xdo_template_id);
5914                Fetch C_TEMPLATE_STATUS into l_template_status;
5915 
5916                If ( C_TEMPLATE_STATUS%NOTFOUND) Then
5917 
5918     		open C_TEMPLATE_NAME (l_dunningplan_lines.xdo_template_id);
5919     		Fetch C_TEMPLATE_NAME into l_template_name;
5920     		close C_TEMPLATE_NAME;
5921 
5922     		FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
5923                     FND_MSG_PUB.Add;
5924                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
5925     	        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
5926     	        RAISE FND_API.G_EXC_ERROR;
5927     	   END IF;
5928                Close C_TEMPLATE_STATUS;
5929     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
5930 
5931     		 /*===========================================
5932     		  * Check template
5933     		  *  in 11.5.11, IEX supports fulfillment and xml publisher.
5934     		  *  if the current setup for delivery id FFM,
5935     		  *  then template_id is necessary;
5936     		  *  if XML, xdo_template_id is necessary;
5937     		  *===========================================*/
5938 
5939     		 l_curr_dmethod := IEX_SEND_XML_PVT.getCurrDeliveryMethod;
5940     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - curr d_method='||l_curr_dmethod);
5941     		 if ( (l_curr_dmethod is null or l_curr_dmethod = '') or
5942     		      (l_curr_dmethod = 'FFM' and l_template_id is null)  or
5943     		      (l_curr_dmethod = 'XML' and l_xdo_template_id is null ) ) then
5944     		      FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
5945     		      FND_MSG_PUB.Add;
5946     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Missing corresponding template');
5947     		      FND_FILE.PUT_LINE(FND_FILE.LOG, 'Missing corresponding template');
5948     		      RAISE FND_API.G_EXC_ERROR;
5949 
5950     		 end if;
5951 
5952     		       /*===========================================
5953     		  * Check profile before send dunning
5954     		  *===========================================*/
5955     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  begin check customer profile');
5956 
5957     		  -- ctlee - check the hz_customer_profiles.dunning_letter
5958     		   FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_party_cust_id = ' || l_party_cust_id);
5959     		   FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_account_id = ' || l_account_id);
5960     		   FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_customer_site_use_id = ' || l_customer_site_use_id);
5961     		   FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_delinquency_id = ' || l_delinquency_id);
5962     		    -- ctlee - check the hz_customer_profiles.dunning_letter
5963     		    l_party_cust_id_check := l_party_cust_id;
5964     		    l_account_id_check := l_account_id;
5965     		    l_customer_site_use_id_check := l_customer_site_use_id;
5966     		    l_delinquency_id_check := l_delinquency_id;
5967     		   if (p_running_level = 'CUSTOMER') then
5968     		      l_account_id_check := null;
5969     		      l_customer_site_use_id_check := null;
5970     		      l_delinquency_id_check := null;
5971     		   elsif  (p_running_level = 'ACCOUNT') then
5972     		      l_customer_site_use_id_check := null;
5973     		      l_delinquency_id_check := null;
5974     		   elsif  (p_running_level = 'BILL_TO') then
5975     		      l_delinquency_id_check := null;
5976     		   end if;
5977     		   if ( iex_utilities.DunningProfileCheck (
5978     			   p_party_id => l_party_cust_id_check
5979     			   , p_cust_account_id => l_account_id_check
5980     			   , p_site_use_id => l_customer_site_use_id_check
5981     			   , p_delinquency_id => l_delinquency_id_check     ) = 'N'
5982     		      ) then
5983     			FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_PROFILE_NO');
5984     			FND_MSG_PUB.Add;
5985     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Send dunning in customer profile set to no ');
5986     			FND_FILE.PUT_LINE(FND_FILE.LOG, 'Send dunning in customer profile set to no ');
5987     			x_return_status := FND_API.G_RET_STS_ERROR;
5988     			GOTO end_api;
5989     		   end if;
5990 
5991     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  p_dunning_mode :'|| p_dunning_mode);
5992     		 --If dunning mode is draft then don't close the previous duning records.
5993 
5994     		 for i in l_dunningplan_lines.range_of_dunning_level_from..l_dunningplan_lines.range_of_dunning_level_to
5995     		      loop
5996 
5997     				l_stage	:= i-1;
5998     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_stage :'||l_stage);
5999 
6000     			      l_skip_this_dunn_planlineid := 1;
6001 
6002     				if i = 1 then
6003 
6004     					 vPLSQL1 := 'select count(*) from ( ' ||
6005     							'    select del.delinquency_id, ' ||
6006     							'	   del.transaction_id, ' ||
6007     							'	   del.payment_schedule_id  ' ||
6008     							'    from iex_delinquencies del, ' ||
6009     							'	 ar_payment_schedules arp ' ||
6010     							'    where del.payment_schedule_id = arp.payment_schedule_id ' ||
6011     							'    and del.status in (''DELINQUENT'',''PREDELINQUENT'') ' ||
6012     							'    and del.staged_dunning_level is NULL ' ||
6013     							'    and (trunc(arp.due_date) + :p_min_days_bw_dun) <= :p_corr_date ' ||
6014     							'    and (trunc(arp.due_date) + :p_grace_days) <= :p_corr_date ' ||
6015     							'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ';
6016 
6017     				if l_include_current = 'Y' then
6018     				vPLSQL2 := '   ';
6019     				/*vPLSQL2 := '    union all ' || --Added for Bug 10401991 07-Feb-2011 barathsr
6020     						   'select null, arp.customer_trx_id, ' ||
6021     						   'arp.payment_schedule_id ' ||
6022     				                   'from ar_payment_schedules arp, ' ||
6023     					           'hz_cust_accounts hca ' ||
6024     				                   'where arp.customer_id = hca.cust_account_id ' ||
6025     				                   'and arp.status = ''OP'' ' ||
6026     				                   'and arp.amount_due_remaining <> 0 ' ||--'    and arp.amount_due_remaining > 0 ' || Changed to fix 12552027 by snuthala 5/19/2011
6027     						   'and arp.class = ''INV'' ' ||
6028     				                   'and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
6029                                      		   'and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'' ) ' ;*/
6030 
6031     				else
6032     					vPLSQL2 := '  ';
6033 
6034                                     end if;
6035     					if (p_running_level = 'CUSTOMER') then
6036     					      vPLSQL3		:= vPLSQL1 || '    and del.party_cust_id = :p_party_id )';
6037     					elsif  (p_running_level = 'ACCOUNT') then
6038     					      vPLSQL3		:= vPLSQL1 || '    and del.cust_account_id = :p_cust_acct_id ' ||
6039     					                           --Begin Bug 10401991 03-feb-2011 barathsr
6040     					                           '    and arp.amount_due_remaining >= NVL ( '||
6041     								   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
6042     								   '	FROM hz_cust_profile_amts '||
6043     								   '	WHERE site_use_id  IS NULL '||
6044     								   '	AND cust_account_id = arp.customer_id '||
6045     								   '	AND currency_code   = arp.invoice_currency_code),0))';
6046     					elsif  (p_running_level = 'BILL_TO') then
6047     					      -- vPLSQL3		:= vPLSQL1 || '    and del.customer_site_use_id IN ( :p_site_use_id,24388) ' ||
6048                      vPLSQL3		:= vPLSQL1 || '    and del.customer_site_use_id IN ( :p_site_use_id,'||t_id||')' ||   -- Bills Receivabless
6049     					                           '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
6050     								   '	from hz_cust_profile_amts '||
6051     								   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
6052     								   '	and currency_code = arp.invoice_currency_code),0))';
6053     					end if;                 --End Bug 10401991 03-feb-2011 barathsr
6054 
6055     					/*if l_include_current = 'Y' then
6056     						open sql_cur3 for vPLSQL3 using 0,
6057     								    p_correspondence_date,
6058     								    0,
6059     								    p_correspondence_date,
6060     								    l_dun_disputed_items,
6061     								    l_object_id;
6062     								    --0,
6063     								    --p_correspondence_date,
6064     								    --0,
6065     								    --p_correspondence_date,
6066     								 --   l_dun_disputed_items,
6067     								   -- l_object_id;
6068     					else*/
6069     						open sql_cur3 for vPLSQL3 using l_dunningplan_lines.min_days_between_dunning,
6070     								    p_correspondence_date,
6071     								    l_grace_days,
6072     								    p_correspondence_date,
6073     								    l_dun_disputed_items,
6074     								    l_object_id;
6075                                      --,l_object_id;
6076     					--end if;
6077     					fetch sql_cur3 into l_acc_dunning_trx_null_dun_ct;
6078     					close sql_cur3;
6079 
6080     					WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_acc_dunning_trx_null_dun_ct :'||l_acc_dunning_trx_null_dun_ct);
6081     					if l_acc_dunning_trx_null_dun_ct <> 0 then
6082     						WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Transaction exist for this stage, so will continue...');
6083     						l_skip_this_dunn_planlineid := 0;
6084     						if l_first_satified_dunnplanid is null then
6085     							l_first_satified_dunnplanid := 1;
6086     						else
6087     							l_first_satified_dunnplanid := 0;
6088     						end if;
6089     						  goto STAGE_DUNN;
6090     					 end if;
6091 
6092     				else
6093     				      vPLSQL1 := 'select count(*) from ( ' ||
6094     							'    select del.delinquency_id, ' ||
6095     							'	   del.transaction_id, ' ||
6096     							'	   del.payment_schedule_id ' ||
6097     							'   from iex_delinquencies del ' ||
6098     							'	 ,ar_payment_schedules arp ' ||
6099     							'    where ' ||
6100     							'    del.payment_schedule_id = arp.payment_schedule_id and ' ||
6101     							'    del.status in (''DELINQUENT'',''PREDELINQUENT'') ' ||
6102     							'    and del.staged_dunning_level = :p_stage_no ' ||
6103     							'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
6104     							'    and nvl( ' ||
6105     							'	     ( ' ||
6106     							'		(select trunc(correspondence_date) from iex_dunnings ' ||
6107     							'		 where dunning_id = ' ||
6108     							'		    (select max(iet.DUNNING_ID) from iex_dunning_transactions iet, ' ||
6109     							'                                                    iex_dunnings dunn ' ||
6110     							'		     where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id ' ||
6111     							'                    and dunn.dunning_id = iet.dunning_id ' ||
6112     							'                    and ((dunn.dunning_mode = ''DRAFT'' and dunn.confirmation_mode = ''CONFIRMED'') ' ||
6113     							'                            OR (dunn.dunning_mode = ''FINAL'')) ' ||
6114     							'		     and iet.STAGE_NUMBER = :p_stage_no ' ||
6115     							'                    and dunn.delivery_status is null' ||
6116     							'		    ) ' ||
6117     							'		 ) ' ||
6118     							'	       + :p_min_days_bw_dun ' ||
6119     							'	      ) ' ||
6120     							'	     , :p_corr_date ' ||
6121     							'	    ) ' ||
6122     							'	    <= :p_corr_date ';
6123     					--WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - vPLSQL1 :'||vPLSQL1);
6124 
6125     					if l_include_current = 'Y' then
6126 
6127        					vPLSQL2 := ' ';
6128 
6129     						/*vPLSQL2 :=         '    union all ' || --Added for Bug 10401991 07-Feb-2011 barathsr
6130     						   'select null, arp.customer_trx_id, ' ||
6131     						   'arp.payment_schedule_id ' ||
6132     				                   'from ar_payment_schedules arp, ' ||
6133     					           'hz_cust_accounts hca ' ||
6134     				                   'where arp.customer_id = hca.cust_account_id ' ||
6135     				                   'and arp.status = ''OP'' ' ||
6136     				                   'and arp.amount_due_remaining <> 0 ' ||--'    and arp.amount_due_remaining > 0 ' || Changed to fix 12552027 by snuthala 5/19/2011
6137     						   'and arp.class = ''INV'' ' ||
6138     				                   'and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
6139                                      		   'and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'' ) ' ;
6140     					/*vPLSQL2 := '    union all' ||  --Added for Bug 10401991 07-Feb-2011 barathsr
6141     							'    select del.delinquency_id, ' ||
6142     							'	   del.transaction_id, ' ||
6143     							'	   del.payment_schedule_id ' ||
6144     							'    from iex_delinquencies del ' ||
6145     							'	 ,ar_payment_schedules arp ' ||
6146     							'    where ' ||
6147     							'    del.payment_schedule_id = arp.payment_schedule_id and ' ||
6148     							'    del.status = ''CURRENT'' ' ||
6149     							'    and del.staged_dunning_level = :p_stage_no ' ||
6150     							'    and arp.status = ''OP'' ' ||
6151     							'    and arp.class = ''INV'' ' ||
6152     							'    and arp.amount_in_dispute >= decode(:p_include_dis_items, ''Y'', arp.amount_due_remaining, (arp.amount_due_original + 1)) ' ||
6153     							'    and nvl( ' ||
6154     							'	( ' ||
6155     							'	 (select trunc(correspondence_date) from iex_dunnings ' ||
6156     							'	  where dunning_id = ' ||
6157     							'	   (select max(iet.DUNNING_ID) from iex_dunning_transactions iet, ' ||
6158     							'                                           iex_dunnings dunn ' ||
6159     							'	    where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id ' ||
6160     							'                    and dunn.dunning_id = iet.dunning_id ' ||
6161     							'                    and ((dunn.dunning_mode = ''DRAFT'' and dunn.confirmation_mode = ''CONFIRMED'') ' ||
6162     							'                            OR (dunn.dunning_mode = ''FINAL'')) ' ||
6163     							'	    and iet.STAGE_NUMBER = :p_stage_no and dunn.delivery_status is null)) ' ||
6164     							'	    + :p_min_days_bw_dun ) ' ||
6165     							'	    , :p_corr_date ) ' ||
6166     							'	    <= :p_corr_date ' ;*/
6167     					else
6168     					vPLSQL2 := '    ';
6169     					end if;
6170     					--WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - vPLSQL2 :'||vPLSQL2);
6171 
6172     					if (p_running_level = 'CUSTOMER') then
6173     					      vPLSQL3		:= vPLSQL1 || '    and del.party_cust_id = :p_party_id  )';
6174 --					      || vPLSQL2 ||   '    and hca.party_id = :p_party_id )';
6175     					elsif  (p_running_level = 'ACCOUNT') then
6176     					      vPLSQL3		:= vPLSQL1 || '    and del.cust_account_id = :p_cust_acct_id ' ||
6177     					       --Begin Bug 10401991 03-feb-2011 barathsr
6178     					                           '    and arp.amount_due_remaining >= NVL ( '||
6179     								   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
6180     								   '	FROM hz_cust_profile_amts '||
6181     								   '	WHERE site_use_id  IS NULL '||
6182     								   '	AND cust_account_id = arp.customer_id '||
6183     								   '	AND currency_code   = arp.invoice_currency_code),0)) ';
6184 								   /*||
6185     								   vPLSQL2 ||
6186     								   '    and arp.customer_id = :p_cust_acct_id '||
6187     								   '    and arp.amount_due_remaining >= NVL ( '||
6188     								   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
6189     								   '	FROM hz_cust_profile_amts '||
6190     								   '	WHERE site_use_id  IS NULL '||
6191     								   '	AND cust_account_id = arp.customer_id '||
6192     								   '	AND currency_code   = arp.invoice_currency_code),0))';*/
6193     					elsif  (p_running_level = 'BILL_TO') then
6194     					      -- vPLSQL3		:= vPLSQL1 || '    and del.customer_site_use_id in ( :p_site_use_id , 24388) ' ||
6195                     vPLSQL3		:= vPLSQL1 || '    and del.customer_site_use_id in ( :p_site_use_id , '||t_id||')' ||   -- Bills Receivabless
6196     					                           '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
6197     								   '	from hz_cust_profile_amts '||
6198     								   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
6199     								   '	and currency_code = arp.invoice_currency_code),0))';/* ||
6200     								   vPLSQL2 ||
6201     								   '    and arp.customer_site_use_id = :p_site_use_id ' ||
6202     								   '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
6203     								   '	from hz_cust_profile_amts '||
6204     								   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
6205     								   '	and currency_code = arp.invoice_currency_code),0))';*/
6206     					end if;    --End Bug 10401991 03-feb-2011 barathsr
6207     					--WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - vPLSQL3 :'||vPLSQL3);
6208 
6209     					/*if l_include_current = 'Y' then
6210     					open sql_cur3 for vPLSQL3 using l_stage,
6211     								    l_dun_disputed_items,
6212     								    l_stage,
6213     								    l_dunningplan_lines.min_days_between_dunning,
6214     								    p_correspondence_date,
6215     								    p_correspondence_date,
6216     								    l_object_id,
6217     								    l_dun_disputed_items,
6218     								    l_object_id;
6219                                             else*/
6220     					open sql_cur3 for vPLSQL3 using l_stage,
6221     								    l_dun_disputed_items,
6222     								    l_stage,
6223     								    l_dunningplan_lines.min_days_between_dunning,
6224     								    p_correspondence_date,
6225     								    p_correspondence_date,
6226     								    l_object_id;
6227 								    --, l_object_id;
6228                                           --  end if;
6229 
6230     					fetch sql_cur3 into l_acc_dunning_trx_ct;
6231     					close sql_cur3;
6232 
6233     					  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_acc_dunning_trx_ct :'||l_acc_dunning_trx_ct);
6234     					 if l_acc_dunning_trx_ct <> 0 then
6235     						WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Transaction exist for this stage, so will continue...');
6236     						l_skip_this_dunn_planlineid := 0;
6237     						if l_first_satified_dunnplanid is null then
6238     							l_first_satified_dunnplanid := 1;
6239     						else
6240     							l_first_satified_dunnplanid := 0;
6241     						end if;
6242     						goto STAGE_DUNN;
6243     				         end if;
6244 
6245     				end if;
6246 
6247     		      end loop;
6248     		    <<STAGE_DUNN>>
6249     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_skip_this_dunn_planlineid: '|| l_skip_this_dunn_planlineid);
6250     		  if l_skip_this_dunn_planlineid = 1 then
6251     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Transaction doesn''t exist for this stage, so skipping...');
6252     			goto c_dunning_plan_lines;
6253     		  end if;
6254 
6255     		 if ((upper(p_single_staged_letter) = 'N') OR (upper(p_single_staged_letter) = 'Y' and (l_first_satified_dunnplanid = 1)) ) then
6256     		 FND_FILE.PUT_LINE(FND_FILE.LOG,'inside if condn');
6257     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_single_staged_letter is N or p_single_staged_letter is Y and dunning_id NULL');
6258     			 --Start adding for bug 8489610 by gnramasa 14-May-09
6259     			 if p_dunning_mode <> 'DRAFT' then
6260     				  /*===========================================
6261     				   * Close OPEN Dunnings for each party/account
6262     				   *===========================================*/
6263     				  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning');
6264 
6265     				 /* if p_dunning_mode = 'DRAFT' then
6266     					l_status := 'CLOSE';
6267     				  else
6268     					l_status := 'OPEN';
6269     				  end if;
6270     				 */
6271     				  Close_Staged_Dunning(
6272     					p_api_version              => p_api_version
6273     				      , p_init_msg_list            => p_init_msg_list
6274     				      , p_commit                   => p_commit
6275     				      , p_delinquencies_tbl        => l_del_tbl
6276     				      , p_ag_dn_xref_id	           => l_ag_dn_xref_id
6277     				      , p_running_level            => p_running_level
6278     				      --, p_status                   => l_status
6279     				      , x_return_status            => x_return_status
6280     				      , x_msg_count                => x_msg_count
6281     				      , x_msg_data                 => x_msg_data);
6282 
6283     				  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning status='|| x_return_status);
6284                                       FND_FILE.PUT_LINE(FND_FILE.LOG,'After close dunning');
6285 
6286     				  IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
6287     					WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Close Dunning');
6288     					FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cannot Close Dunning');
6289     					x_return_status := FND_API.G_RET_STS_ERROR;
6290     					GOTO end_api;
6291     				  END IF;
6292     				  --WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndCloseDunn');
6293     			 end if;
6294 
6295     			  /*===========================================
6296     			   * Create Dunning Record
6297     			   *===========================================*/
6298     			  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get CallbackDate');
6299     			  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag='||l_callback_flag);
6300     			  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDays='||l_callback_days);
6301 
6302     			    /*===================================================
6303     			     * clchang updated 02/13/2003
6304     			     * callback_days could be null if callback_yn = 'N';
6305     			     * and if callback_yn = 'N', not get callback_date;
6306     			     *==================================================*/
6307     			     IF (l_callback_flag = 'Y') THEN
6308 
6309     					     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is Y: GetCallbackDate');
6310     					     Get_Callback_Date(p_init_msg_list          => FND_API.G_FALSE
6311     							      ,p_callback_days          => l_callback_days
6312     							      , p_correspondence_date   => p_correspondence_date
6313     							      ,x_callback_date          => l_callback_date
6314     							      ,x_return_status          => x_return_status
6315     							      ,x_msg_count              => x_msg_count
6316     							      ,x_msg_data               => x_msg_data);
6317 
6318     					     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetCallbackDate status='|| x_return_status);
6319 
6320     					     IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
6321     					       FND_MESSAGE.Set_Name('IEX', 'IEX_NO_CALLBACKDATE');
6322     					       FND_MSG_PUB.Add;
6323     					       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot find callback date');
6324     					       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cannot find callback date');
6325     					       x_return_status := FND_API.G_RET_STS_ERROR;
6326     					       GOTO end_api;
6327     					     END IF;
6328 
6329     			     ELSE
6330     				 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is N: NOTGetCallbackDate');
6331 
6332     			     END IF;
6333     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_invoice_copies: l_invoice_copies');
6334     			     l_inv_xdo_template_id := null;
6335                                   if nvl(l_invoice_copies,'N') = 'Y' then
6336     				 l_inv_xdo_template_id := fnd_profile.value('IEX_INVOICE_FULFILLMENT_TEMPLATE');
6337     				 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Template ID for Invoice : '||l_inv_xdo_template_id);
6338 
6339     			     /*===========================================
6340     			      * Check the status of the template
6341     			      *===========================================*/
6342 
6343     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Invoice Template status');
6344     			      Open C_TEMPLATE_STATUS(l_inv_xdo_template_id);
6345     			      Fetch C_TEMPLATE_STATUS into l_template_status;
6346 
6347     			      If ( C_TEMPLATE_STATUS%NOTFOUND) Then
6348 
6349     				  open C_TEMPLATE_NAME (l_inv_xdo_template_id);
6350     				  Fetch C_TEMPLATE_NAME into l_template_name;
6351     				  close C_TEMPLATE_NAME;
6352 
6353     				  FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
6354     				  FND_MSG_PUB.Add;
6355     				  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
6356     				  FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
6357     				  RAISE FND_API.G_EXC_ERROR;
6358     			      END IF;
6359     			      Close C_TEMPLATE_STATUS;
6360     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
6361 
6362     			      ELSE
6363     				 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - invoice_copies is N: Dont Send Invoice');
6364     			     end if;
6365 
6366     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDate='||l_callback_date);
6367     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Create Dunning');
6368     			     l_dunning_rec.dunning_level := p_running_level;
6369     			     l_dunning_rec.dunning_object_id := l_object_id;
6370     			     l_dunning_rec.callback_yn := l_callback_flag;
6371     			     l_dunning_rec.callback_date := l_callback_date;
6372 
6373     			     if p_dunning_mode = 'DRAFT' then
6374     				l_dunning_rec.status := 'CLOSE';
6375     			     else
6376     				l_dunning_rec.status := 'OPEN';
6377     			     end if;
6378 
6379     			     l_dunning_rec.dunning_method := l_method;
6380 
6381     			     if (l_curr_dmethod = 'FFM') then
6382     				 l_dunning_rec.template_id:= l_template_id;
6383     				 l_dunning_rec.ffm_request_id := l_request_id;
6384     			     else
6385     				 l_dunning_rec.xml_template_id:= l_xdo_template_id;
6386     				 l_dunning_rec.xml_request_id := l_request_id;
6387     				 l_dunning_rec.addt_xml_template_id := l_inv_xdo_template_id;
6388     			     end if;
6389     			     l_dunning_rec.object_type := l_object_code;
6390     			     l_dunning_rec.object_id := l_object_id;
6391     			     l_dunning_rec.amount_due_remaining := l_amount;
6392     			     l_dunning_rec.currency_code := l_curr_code;
6393     			     l_dunning_rec.dunning_plan_id := p_dunning_plan_id;
6394     			     l_dunning_rec.contact_destination := l_contact_destination;  -- bug 3955222
6395     			     l_dunning_rec.contact_party_id := l_contact_party_id;  -- bug 3955222
6396 
6397     			     if p_parent_request_id is not null then
6398     				l_dunning_rec.request_id := p_parent_request_id;
6399     			     else
6400     				l_dunning_rec.request_id := FND_GLOBAL.Conc_Request_Id;
6401     			     end if;
6402 
6403     			     --l_dunning_rec.request_id           := FND_GLOBAL.Conc_Request_Id;
6404     			     l_dunning_rec.dunning_mode := p_dunning_mode;
6405     			     l_dunning_rec.confirmation_mode := p_confirmation_mode;
6406     			     l_dunning_rec.ag_dn_xref_id	:= l_dunningplan_lines.ag_dn_xref_id;
6407     			     l_dunning_rec.correspondence_date	:= p_correspondence_date;
6408     			     l_dunning_rec.org_id := l_org_id;
6409     			     l_dunning_rec.as_of_date := p_correspondence_date;
6410 
6411     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' before create dunning org_id ' || l_org_id);
6412     			     FND_FILE.PUT_LINE(FND_FILE.LOG,'call to create dunning');
6413 
6414     			     CREATE_DUNNING(
6415     				   p_api_version              => p_api_version
6416     				 , p_init_msg_list            => p_init_msg_list
6417     				 , p_commit                   => p_commit
6418     				 , p_dunning_rec              => l_dunning_rec
6419     				 , x_dunning_id               => l_dunning_id
6420     				 , x_return_status            => x_return_status
6421     				 , x_msg_count                => x_msg_count
6422     				 , x_msg_data                 => x_msg_data);
6423 
6424     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| x_return_status);
6425 
6426     			      IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
6427     				   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
6428     				   FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cannot Create Dunning');
6429     				   x_return_status := FND_API.G_RET_STS_ERROR;
6430     				   GOTO end_api;
6431     			      END IF;
6432 
6433     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningId='||l_dunning_id);
6434     			      FND_FILE.PUT_LINE(FND_FILE.LOG, 'Create Dunning Id='|| l_dunning_id);
6435     			      l_dunn_cnt := l_dunn_cnt + 1;
6436     		 end if; --if ((upper(p_single_staged_letter) = 'N') OR (upper(p_single_staged_letter) = 'Y' and (l_first_satified_dunnplanid = 1)) ) then
6437 
6438                           FND_FILE.PUT_LINE(FND_FILE.LOG,'calling create staged dunning');
6439     		  Create_Staged_Dunning(
6440     				p_api_version              => p_api_version
6441     			      , p_init_msg_list            => p_init_msg_list
6442     			      , p_commit                   => p_commit
6443     			      , p_delinquencies_tbl        => l_del_tbl
6444     			      , p_ag_dn_xref_id	           => l_ag_dn_xref_id
6445     			      , p_dunning_id               => l_dunning_id
6446     			      , p_correspondence_date      => p_correspondence_date
6447     			      , p_running_level            => p_running_level
6448     			      , p_grace_days               => l_grace_days
6449     			      , p_include_dispute_items    => l_dun_disputed_items
6450     			      , p_dunning_mode		   => p_dunning_mode
6451     			      , p_inc_inv_curr             => l_inc_inv_curr
6452     			      , x_return_status            => x_return_status
6453     			      , x_msg_count                => x_msg_count
6454     			      , x_msg_data                 => x_msg_data);
6455 
6456     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Create Stage Dunning transactions status='|| x_return_status);
6457     		  FND_FILE.PUT_LINE(FND_FILE.LOG,'create staged dunning-->'||x_return_status);
6458 
6459     		      IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
6460     			   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Stage Dunning transactions');
6461     			   FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cannot Create Stage Dunning transactions');
6462     			   x_return_status := FND_API.G_RET_STS_ERROR;
6463     			   GOTO end_api;
6464     		      END IF;
6465 
6466     		 if (upper(p_single_staged_letter) = 'N') then
6467 
6468     			  /*===========================================
6469     			   * Send letter thru fulfillment
6470     			   *===========================================*/
6471     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND_FFM');
6472     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org_id='||l_org_id);
6473     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id='||l_party_cust_id);
6474     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - method='||l_method);
6475 
6476     			 l_bind_tbl(1).key_name := 'party_id';
6477     			 l_bind_tbl(1).key_type := 'NUMBER';
6478     			 l_bind_tbl(1).key_value := l_party_cust_id;
6479     			 --Begin Bug 10401991 20-Jan-2011 barathsr
6480     			 l_bind_tbl(2).key_name := 'org_id';
6481     			 l_bind_tbl(2).key_type := 'NUMBER';
6482     			 l_bind_tbl(2).key_value := l_org_id;
6483     			 --End Bug 10401991 20-Jan-2011 barathsr
6484     			 l_bind_tbl(3).key_name := 'account_id';
6485     			 l_bind_tbl(3).key_type := 'NUMBER';
6486     			 l_bind_tbl(3).key_value := l_account_id;
6487     			 -- new bind rec since 11.5.10 (for BILL_TO)
6488     			 l_bind_tbl(4).key_name := 'customer_site_use_id';
6489     			 l_bind_tbl(4).key_type := 'NUMBER';
6490     			 l_bind_tbl(4).key_value := l_customer_site_use_id;
6491     			 l_bind_tbl(5).key_name := 'DUNNING_ID';
6492     			 l_bind_tbl(5).key_type := 'NUMBER';
6493     			 l_bind_tbl(5).key_value := l_dunning_id;
6494 
6495     			 WriteLog( G_PKG_NAME || ' ' || l_api_name ||' before send_xml org_id ' || l_org_id);
6496 
6497     			/**
6498     			 * in 11.5.11, IEX supports fulfillment and xml publisher.
6499     			 * it depends on the set up in IEX ADMIN/SETUP.
6500     			 */
6501     			 if (l_curr_dmethod = 'FFM') then
6502 
6503     			  Send_Fulfillment(p_api_version              => p_api_version
6504     					  ,p_init_msg_list            => FND_API.G_FALSE
6505     					  ,p_commit                   => FND_API.G_TRUE
6506     					  ,p_fulfillment_bind_tbl     => l_bind_tbl
6507     					  ,p_template_id              => l_template_id
6508     					  ,p_method                   => l_method
6509     					  ,p_party_id                 => l_party_cust_id
6510     					  ,x_request_id               => l_request_id
6511     					  ,x_return_status            => x_return_status
6512     					  ,x_msg_count                => x_msg_count
6513     					  ,x_msg_data                 => x_msg_data
6514     					  ,x_contact_destination      => l_contact_destination
6515     					  ,x_contact_party_id         => l_contact_party_id);
6516     			 else
6517 
6518     			     FND_FILE.PUT_LINE(FND_FILE.LOG,'send fulfillment');
6519 
6520     			  Send_XML(p_api_version              => p_api_version
6521     				  ,p_init_msg_list            => FND_API.G_FALSE
6522     				  ,p_commit                   => FND_API.G_TRUE
6523     				  ,p_resend                   => 'N'
6524     				  ,p_request_id               => null
6525     				  ,p_fulfillment_bind_tbl     => l_bind_tbl
6526     				  ,p_template_id              => l_xdo_template_id
6527     				  ,p_method                   => l_method
6528     				  ,p_party_id                 => l_party_cust_id
6529     				  ,p_level                    => p_running_level
6530     				  ,p_source_id                => l_object_id
6531     				  ,p_object_code              => l_object_code
6532     				  ,p_object_id                => l_object_id
6533     				  ,p_resource_id              => l_resource_id --Added for bug 9156833 gnramasa 27th Nov 09
6534     				  ,p_dunning_mode             => p_dunning_mode
6535     				  ,p_parent_request_id        => p_parent_request_id
6536     				  ,p_org_id                   => l_org_id
6537     				  ,p_addt_template_id	      => l_inv_xdo_template_id
6538     				  ,x_request_id               => l_request_id
6539     				  ,x_return_status            => x_return_status
6540     				  ,x_msg_count                => x_msg_count
6541     				  ,x_msg_data                 => x_msg_data
6542     				  ,x_contact_destination      => l_contact_destination
6543     				  ,x_contact_party_id         => l_contact_party_id);
6544     			 end if;
6545 
6546     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND status='|| x_return_status);
6547     			 --End adding for bug 8489610 by gnramasa 14-May-09
6548 
6549     			 IF x_return_status <> FND_API.G_RET_STS_SUCCESS and x_return_status <> 'W'  THEN
6550     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Sending process failed');
6551     			     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Sending process failed ');
6552     			     x_return_status := FND_API.G_RET_STS_ERROR;
6553     			     GOTO end_api;
6554     			 elsif x_return_status = 'W' then
6555     			     l_warning_flag := 'W';
6556     			 END IF;
6557 
6558     			  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id = ' ||l_request_id);
6559     			  FND_FILE.PUT_LINE(FND_FILE.LOG, 'Request Id = ' || l_request_id);
6560     			  l_ffm_cnt := l_ffm_cnt + 1;
6561 
6562     			    l_dunning_rec_upd.dunning_id := l_dunning_id;
6563     			    if (l_curr_dmethod = 'FFM') then
6564     				l_dunning_rec_upd.ffm_request_id := l_request_id;
6565     			    else
6566     				l_dunning_rec_upd.xml_request_id := l_request_id;
6567     			    end if;
6568 
6569     			    l_amount	:= staged_dunn_amt_due_remaining(l_dunning_id);
6570     			    if (p_running_level = 'CUSTOMER') then
6571     				  l_curr_code                       := party_currency_code(l_object_id);
6572     			      elsif (p_running_level = 'ACCOUNT') then
6573     				  l_curr_code                       := acct_currency_code(l_object_id);
6574     			      elsif (p_running_level = 'BILL_TO') then
6575     				  l_curr_code                       := site_currency_code(l_object_id);
6576     			      end if;
6577 
6578     			      l_dunning_rec_upd.amount_due_remaining := l_amount;
6579     			      l_dunning_rec_upd.currency_code := l_curr_code;
6580     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_rec_upd.amount_due_remaining = ' ||l_dunning_rec_upd.amount_due_remaining);
6581     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_rec_upd.currency_code = ' ||l_dunning_rec_upd.currency_code);
6582 
6583     			    IEX_DUNNING_PVT.Update_DUNNING(
6584     				p_api_version              => 1.0
6585     				, p_init_msg_list            => FND_API.G_FALSE
6586     				, p_commit                   => FND_API.G_TRUE
6587     				, p_dunning_rec              => l_dunning_rec_upd
6588     				, x_return_status            => l_return_status
6589     				, x_msg_count                => l_msg_count
6590     				, x_msg_data                 => l_msg_data
6591     			    );
6592     		 end if; --if (upper(p_single_staged_letter) = 'N') then
6593 
6594     	<<c_dunning_plan_lines>>
6595     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - c_dunning_plan_lines');
6596     	end loop;
6597     	close sql_cur;
6598 
6599     	 if ( (upper(p_single_staged_letter) = 'Y') and (l_dunning_id is not null) ) then
6600 
6601     		  /*===========================================
6602     		   * Send letter thru fulfillment
6603     		   *===========================================*/
6604     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND_FFM');
6605     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org_id='||l_org_id);
6606     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id='||l_party_cust_id);
6607     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - method='||l_method);
6608 
6609     		 if (l_curr_dmethod = 'FFM') then
6610     			 select template_id
6611     			 into l_xdo_template_id
6612     			 from iex_dunnings
6613     			 where dunning_id = l_dunning_id;
6614     		else
6615     			select xml_template_id
6616     			 into l_xdo_template_id
6617     			 from iex_dunnings
6618     			 where dunning_id = l_dunning_id;
6619     		end if;
6620     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_xdo_template_id='||l_xdo_template_id);
6621 
6622     		 l_bind_tbl(1).key_name := 'party_id';
6623     		 l_bind_tbl(1).key_type := 'NUMBER';
6624     		 l_bind_tbl(1).key_value := l_party_cust_id;
6625     		 --Begin Bug 10401991 20-Jan-2011 barathsr
6626     		 l_bind_tbl(2).key_name := 'org_id';
6627     		 l_bind_tbl(2).key_type := 'NUMBER';
6628     		 l_bind_tbl(2).key_value := l_org_id;
6629     		 --End Bug 10401991 20-Jan-2011 barathsr
6630     		 l_bind_tbl(3).key_name := 'account_id';
6631     		 l_bind_tbl(3).key_type := 'NUMBER';
6632     		 l_bind_tbl(3).key_value := l_account_id;
6633     		 -- new bind rec since 11.5.10 (for BILL_TO)
6634     		 l_bind_tbl(4).key_name := 'customer_site_use_id';
6635     		 l_bind_tbl(4).key_type := 'NUMBER';
6636     		 l_bind_tbl(4).key_value := l_customer_site_use_id;
6637     		 l_bind_tbl(5).key_name := 'DUNNING_ID';
6638     		 l_bind_tbl(5).key_type := 'NUMBER';
6639     		 l_bind_tbl(5).key_value := l_dunning_id;
6640 
6641     		/**
6642     		 * in 11.5.11, IEX supports fulfillment and xml publisher.
6643     		 * it depends on the set up in IEX ADMIN/SETUP.
6644     		 */
6645     		 if (l_curr_dmethod = 'FFM') then
6646 
6647     		  Send_Fulfillment(p_api_version              => p_api_version
6648     				  ,p_init_msg_list            => FND_API.G_FALSE
6649     				  ,p_commit                   => FND_API.G_TRUE
6650     				  ,p_fulfillment_bind_tbl     => l_bind_tbl
6651     				  ,p_template_id              => l_template_id
6652     				  ,p_method                   => l_method
6653     				  ,p_party_id                 => l_party_cust_id
6654     				  ,x_request_id               => l_request_id
6655     				  ,x_return_status            => x_return_status
6656     				  ,x_msg_count                => x_msg_count
6657     				  ,x_msg_data                 => x_msg_data
6658     				  ,x_contact_destination      => l_contact_destination
6659     				  ,x_contact_party_id         => l_contact_party_id
6660     														);
6661     		 else
6662 
6663     		  Send_XML(p_api_version              => p_api_version
6664     			  ,p_init_msg_list            => FND_API.G_FALSE
6665     			  ,p_commit                   => FND_API.G_TRUE
6666     			  ,p_resend                   => 'N'
6667     			  ,p_request_id               => null
6668     			  ,p_fulfillment_bind_tbl     => l_bind_tbl
6669     			  ,p_template_id              => l_xdo_template_id
6670     			  ,p_method                   => l_method
6671     			  ,p_party_id                 => l_party_cust_id
6672     			  ,p_level                    => p_running_level
6673     			  ,p_source_id                => l_object_id
6674     			  ,p_object_code              => l_object_code
6675     			  ,p_object_id                => l_object_id
6676     			  ,p_resource_id              => l_resource_id --Added for bug 9156833 gnramasa 27th Nov 09
6677     			  ,p_dunning_mode             => p_dunning_mode
6678     			  ,p_parent_request_id        => p_parent_request_id
6679     			  ,p_org_id                   => l_org_id
6680     			  ,p_addt_template_id	      => l_inv_xdo_template_id
6681     			  ,x_request_id               => l_request_id
6682     			  ,x_return_status            => x_return_status
6683     			  ,x_msg_count                => x_msg_count
6684     			  ,x_msg_data                 => x_msg_data
6685     			  ,x_contact_destination      => l_contact_destination
6686     			  ,x_contact_party_id         => l_contact_party_id);
6687     		 end if;
6688 
6689     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND status='|| x_return_status);
6690     		 --End adding for bug 8489610 by gnramasa 14-May-09
6691 
6692     		 IF x_return_status <> FND_API.G_RET_STS_SUCCESS and x_return_status <> 'W'  THEN
6693     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Sending process failed');
6694     		     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Sending process failed ');
6695     		     x_return_status := FND_API.G_RET_STS_ERROR;
6696     		     GOTO end_api;
6697     		 elsif x_return_status = 'W' then
6698     		     l_warning_flag := 'W';
6699     		 END IF;
6700 
6701     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id = ' ||l_request_id);
6702     		  FND_FILE.PUT_LINE(FND_FILE.LOG, 'Request Id = ' || l_request_id);
6703     		  l_ffm_cnt := l_ffm_cnt + 1;
6704 
6705     		    l_dunning_rec_upd.dunning_id := l_dunning_id;
6706     		    if (l_curr_dmethod = 'FFM') then
6707     			l_dunning_rec_upd.ffm_request_id := l_request_id;
6708     		    else
6709     			l_dunning_rec_upd.xml_request_id := l_request_id;
6710     		    end if;
6711 
6712     		    l_amount	:= staged_dunn_amt_due_remaining(l_dunning_id);
6713     		    if (p_running_level = 'CUSTOMER') then
6714     			  l_curr_code                       := party_currency_code(l_object_id);
6715     		      elsif (p_running_level = 'ACCOUNT') then
6716     			  l_curr_code                       := acct_currency_code(l_object_id);
6717     		      elsif (p_running_level = 'BILL_TO') then
6718     			  l_curr_code                       := site_currency_code(l_object_id);
6719     		      end if;
6720 
6721     		      l_dunning_rec_upd.amount_due_remaining := l_amount;
6722     		      l_dunning_rec_upd.currency_code := l_curr_code;
6723     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_rec_upd.amount_due_remaining == ' ||l_dunning_rec_upd.amount_due_remaining);
6724     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_rec_upd.currency_code == ' ||l_dunning_rec_upd.currency_code);
6725 
6726     		    IEX_DUNNING_PVT.Update_DUNNING(
6727     			p_api_version              => 1.0
6728     			, p_init_msg_list            => FND_API.G_FALSE
6729     			, p_commit                   => FND_API.G_TRUE
6730     			, p_dunning_rec              => l_dunning_rec_upd
6731     			, x_return_status            => l_return_status
6732     			, x_msg_count                => l_msg_count
6733     			, x_msg_data                 => l_msg_data
6734     		    );
6735     	 end if; --if ( (upper(p_single_staged_letter) = 'Y') and (l_dunning_id is not null) ) then
6736 
6737               <<end_api>>
6738 
6739     	  --Start bug 9696806 gnramasa 27th May 10
6740     		if p_dunning_mode = 'DRAFT'  then
6741     			if (p_running_level = 'CUSTOMER') then
6742     				update iex_delinquencies del
6743     				set staged_dunning_level = 99
6744     				where del.party_cust_id = l_object_id
6745     				and staged_dunning_level = 98
6746     				and status in ('DELINQUENT','PREDELINQUENT')
6747     				and exists (select count(iet.DUNNING_ID)
6748     						from iex_dunning_transactions iet,
6749     						     iex_dunnings dunn
6750     						 where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
6751     							    and dunn.dunning_id = iet.dunning_id
6752     							    and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
6753     								    OR (dunn.dunning_mode = 'FINAL'))
6754     						 and iet.STAGE_NUMBER = 99
6755     						 and dunn.delivery_status is null
6756     					    );
6757 
6758     			elsif  (p_running_level = 'ACCOUNT') then
6759     				update iex_delinquencies del
6760     				set staged_dunning_level = 99
6761     				where del.cust_account_id = l_object_id
6762     				and staged_dunning_level = 98
6763     				and status in ('DELINQUENT','PREDELINQUENT')
6764     				and exists (select count(iet.DUNNING_ID)
6765     						from iex_dunning_transactions iet,
6766     						     iex_dunnings dunn
6767     						 where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
6768     							    and dunn.dunning_id = iet.dunning_id
6769     							    and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
6770     								    OR (dunn.dunning_mode = 'FINAL'))
6771     						 and iet.STAGE_NUMBER = 99
6772     						 and dunn.delivery_status is null
6773     					    );
6774 
6775     			elsif  (p_running_level = 'BILL_TO') then
6776     				update iex_delinquencies del
6777     				set staged_dunning_level = 99
6778     				where del.customer_site_use_id = l_object_id
6779     				and staged_dunning_level = 98
6780     				and status in ('DELINQUENT','PREDELINQUENT')
6781     				and exists (select count(iet.DUNNING_ID)
6782     						from iex_dunning_transactions iet,
6783     						     iex_dunnings dunn
6784     						 where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
6785     							    and dunn.dunning_id = iet.dunning_id
6786     							    and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
6787     								    OR (dunn.dunning_mode = 'FINAL'))
6788     						 and iet.STAGE_NUMBER = 99
6789     						 and dunn.delivery_status is null
6790     					    );
6791     			end if;
6792 
6793     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Updated : ' || SQL%ROWCOUNT || ' number of row''s staged_dunning_level from 98 to 99');
6794     		    commit;
6795     		end if;
6796 
6797     	  --End bug 9696806 gnramasa 27th May 10
6798 
6799               if (x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
6800                   FND_MSG_PUB.Count_And_Get
6801                   (  p_count          =>   x_msg_count,
6802                      p_data           =>   x_msg_data );
6803                   for i in 1..x_msg_count loop
6804                     errmsg := FND_MSG_PUB.Get(p_msg_index => i,
6805                                               p_encoded => 'F');
6806                     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Error:'||errmsg);
6807                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  errmsg=' || errmsg);
6808                   end loop;
6809               end if;
6810               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api');
6811 
6812          ELSE -- l_noskip = 0
6813               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - all del disputed');
6814               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - skip this party/accnt/site');
6815               if (l_turnoff_coll_on_bankru = 'Y' and l_no_of_bankruptcy >0 ) then
6816     		FND_FILE.PUT_LINE(FND_FILE.LOG, 'Profile IEX: Turn Off Collections Activity for Bankruptcy is Yes and bankruptcy record is exist, so will skip send dunning' );
6817     	  else
6818     		FND_FILE.PUT_LINE(FND_FILE.LOG, 'all delinquencies disputed' );
6819     	  end if;
6820               FND_FILE.PUT_LINE(FND_FILE.LOG, 'skip this party/account/site' );
6821               FND_MSG_PUB.Count_And_Get(  p_count          =>   x_msg_count,
6822                                           p_data           =>   x_msg_data );
6823               x_return_status := 'SKIP'; --FND_API.G_EXC_ERROR;
6824 
6825          end if; -- end of if (l_noskip>0)
6826 
6827          if l_warning_flag = 'W' then
6828           x_return_status := 'W';
6829          end if;
6830 
6831          --
6832          -- End of API body
6833          --
6834 
6835          COMMIT WORK;
6836 
6837          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
6838 
6839          FND_MSG_PUB.Count_And_Get
6840          (  p_count          =>   x_msg_count,
6841             p_data           =>   x_msg_data );
6842 
6843          EXCEPTION
6844              WHEN FND_API.G_EXC_ERROR THEN
6845                  COMMIT WORK;
6846                  x_return_status := FND_API.G_RET_STS_ERROR;
6847                  FND_MSG_PUB.Count_And_Get
6848                  (  p_count          =>   x_msg_count,
6849                     p_data           =>   x_msg_data );
6850                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
6851                  FND_FILE.PUT_LINE(FND_FILE.LOG, 'expect exception' );
6852                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
6853 
6854              WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
6855                  COMMIT WORK;
6856                  x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6857                  FND_MSG_PUB.Count_And_Get
6858                  (  p_count          =>   x_msg_count,
6859                     p_data           =>   x_msg_data );
6860                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
6861                  FND_FILE.PUT_LINE(FND_FILE.LOG, 'unexpect exception' );
6862                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
6863 
6864              WHEN OTHERS THEN
6865                  COMMIT WORK;
6866                  x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6867                  FND_MSG_PUB.Count_And_Get
6868                  (  p_count          =>   x_msg_count,
6869                     p_data           =>   x_msg_data );
6870                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
6871                  FND_FILE.PUT_LINE(FND_FILE.LOG, 'unexpect exception' );
6872                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
6873 
6874     END Send_Level_Staged_Dunning;
6875 
6876     /*==========================================================================
6877      * clchang updated 09/19/2002 -
6878      *     insert ffm_request_id into iex_dunnings after CALL_FFM successfully;
6879      *     Create_Dunning and Update_Dunning also updated;
6880      *
6881      *==========================================================================*/
6882   Procedure Send_Dunning
6883                (p_api_version             IN NUMBER := 1.0,
6884                 p_init_msg_list           IN VARCHAR2 ,
6885                 p_commit                  IN VARCHAR2 ,
6886                 p_dunning_plan_id         in number,
6887                 p_resend_flag             IN VARCHAR2,
6888                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
6889                 p_parent_request_id       IN NUMBER,
6890     	   		p_dunning_mode	      IN VARCHAR2,     -- added by gnramasa for bug 8489610 14-May-09
6891     	        p_confirmation_mode	      IN   VARCHAR2,   -- added by gnramasa for bug 8489610 14-May-09
6892     	        p_correspondence_date     IN DATE,
6893                 x_return_status           OUT NOCOPY VARCHAR2,
6894                 x_msg_count               OUT NOCOPY NUMBER,
6895                 x_msg_data                OUT NOCOPY VARCHAR2)
6896     IS
6897         CURSOR C_GET_DEL (IN_del_ID NUMBER) IS
6898           SELECT delinquency_ID,
6899                  party_cust_id,
6900                  cust_account_id,
6901                  customer_site_use_id,
6902                  score_value
6903             FROM IEX_DELINQUENCIES
6904            WHERE delinquency_ID = in_del_ID;
6905         --
6906         CURSOR C_GET_SCORE (IN_ID NUMBER) IS
6907           SELECT a.score_value
6908             FROM IEX_SCORE_HISTORIES a
6909            WHERE a.score_object_ID = in_ID
6910              AND a.score_object_code = 'IEX_DELINQUENCY'
6911              AND a.creation_date = (select max(b.creation_date)
6912                                       from iex_score_histories b
6913                                      where b.score_object_id = in_id
6914                                        AND b.score_object_code = 'IEX_DELINQUENCY');
6915 
6916         --Start  bug 10226333 by gnramasa 4-Nov-10
6917         Cursor c_get_score_del(p_object_id number,  p_object_type varchar2) is
6918              select score_value
6919                     from iex_score_histories
6920                     where score_object_id = p_object_id
6921                     and score_object_code = p_object_type
6922                     order by creation_date desc;
6923 
6924           cursor c_del_object_type(p_dunn_plan_id number) is
6925           select isc.jtf_object_code
6926     	from iex_dunning_plans_vl ipd, IEX_SCORES isc
6927     	where ipd.dunning_plan_id = p_dunn_plan_id
6928     	and ipd.score_id=isc.score_id;
6929 
6930           l_del_object_type     varchar2(50);
6931           l_del_object_id       number;
6932 
6933           --End adding for bug 10226333 by gnramasa 4-Nov-10
6934 
6935         --
6936         CURSOR C_GET_TEMPLATE (l_line_id NUMBER,
6937                                l_score NUMBER, p_dunning_plan_id number) IS
6938           SELECT x.ag_dn_xref_id,
6939     	     	 x.template_id,
6940                  x.xdo_template_id,
6941                  x.fm_method,
6942                  upper(x.callback_flag),
6943                  x.callback_days,
6944                  ar.bucket_name
6945             FROM IEX_AG_DN_XREF x,
6946                  ar_aging_buckets ar,
6947                  iex_dunning_plans_vl d
6948            WHERE x.aging_bucket_line_ID = l_line_ID
6949              and x.dunning_plan_id = p_dunning_plan_id
6950              AND l_score between x.score_range_low and x.score_range_high
6951              AND x.aging_bucket_id = ar.aging_bucket_id
6952              and ar.aging_bucket_id = d.aging_bucket_id
6953              AND ar.status = 'A'
6954              AND x.dunning_level = 'DELINQUENCY' ;
6955 
6956          CURSOR C_TEMPLATE_STATUS (l_template_id number) is
6957          select 'Active'
6958          from xdo_templates_vl xdo
6959          where xdo.template_id = l_template_id
6960          and trunc(sysdate) >= TRUNC (NVL(xdo.start_date, sysdate))
6961          and trunc(sysdate) < TRUNC(NVL(xdo.end_date, sysdate + 1));
6962 
6963          l_template_status		  varchar2(10);
6964 
6965          CURSOR C_TEMPLATE_NAME (l_template_id number) is
6966          select template_name
6967          from xdo_templates_vl xdo
6968          where xdo.template_id = l_template_id;
6969 
6970          l_template_name	varchar2(500);
6971         --
6972         cursor c_amount (IN_ID number) is
6973          select nvl(ps.amount_due_remaining,0),
6974                 nvl(ps.invoice_currency_code,'USD')
6975            from ar_payment_schedules_all ps,
6976                 --iex_delinquencies_all del
6977                 iex_delinquencies del
6978           where ps.payment_schedule_id (+)= del.payment_schedule_id
6979             and del.delinquency_id = in_id;
6980         --
6981     cursor c_dunning_plan_dtl (p_dunn_plan_id number) is
6982         select nvl(dunn.grace_days ,'N'),
6983                nvl(dunn.dun_disputed_items, 'N')
6984         from iex_dunning_plans_b dunn
6985         where dunning_plan_id = p_dunn_plan_id;
6986 
6987        cursor c_billto (p_customer_site_use_id number,p_org_id number) is
6988           select currency_code,  nvl(min_dunning_invoice_amount,0) from hz_cust_profile_amts
6989             where site_use_id = p_customer_site_use_id and currency_code = (
6990               SELECT  sob.currency_code FROM ar_system_parameters_all sp, gl_sets_of_books sob
6991               WHERE   sob.set_of_books_id = sp.set_of_books_id
6992     	  and sp.org_id = p_org_id);
6993 
6994         -- add cursor c_billto_min_dunn_amt for bug 14797201
6995         cursor c_billto_min_dunn_amt (p_site_use_id number, p_currency_code varchar) is
6996     	select nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
6997     	from hz_cust_profile_amts
6998     	where site_use_id = p_site_use_id
6999     	and currency_code = p_currency_code;
7000 
7001         l_min_dunning_amount    NUMBER;  -- bug 14797201
7002         l_profile_dunn_amt      NUMBER;  -- bug 14797201
7003         l_profile_dunn_inv_amt  NUMBER;  -- bug 14797201
7004         l_AMOUNT                NUMBER;
7005         l_CURR_CODE             VARCHAR2(15);
7006         l_DUNNING_id            NUMBER;
7007         l_delinquency_id        NUMBER;
7008         l_party_cust_id         NUMBER;
7009         l_account_id            NUMBER;
7010         l_customer_site_use_id  NUMBER;
7011         l_location_id           number;
7012         l_dunning_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
7013         l_dunning_rec_upd       IEX_DUNNING_PUB.DUNNING_REC_TYPE;
7014         l_score                 NUMBER;
7015         l_bucket_line_id        NUMBER;
7016         l_campaign_sched_id     NUMBER;
7017         l_template_id           NUMBER;
7018         l_xdo_template_id       NUMBER;
7019         l_method                VARCHAR2(10);
7020         l_callback_flag         VARCHAR2(1);
7021         l_callback_days         NUMBER;
7022         l_callback_date         DATE;
7023         l_request_id            NUMBER;
7024         l_outcome_code          varchar2(20);
7025         l_api_name              CONSTANT VARCHAR2(30) := 'Send_Dunning';
7026         l_api_version_number    CONSTANT NUMBER   := 1.0;
7027         l_return_status         VARCHAR2(1);
7028         l_msg_count             NUMBER;
7029         l_msg_data              VARCHAR2(32767);
7030         errmsg                  VARCHAR2(32767);
7031         --
7032         nIdx                    NUMBER := 0;
7033         TYPE Del_ID_TBL_type is Table of IEX_DELINQUENCIES_ALL.DELINQUENCY_ID%TYPE
7034                                 INDEX BY BINARY_INTEGER;
7035         Del_Tbl                 Del_ID_TBL_TYPE;
7036         l_bind_tbl              IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
7037         l_bind_rec              IEX_DUNNING_PVT.FULFILLMENT_BIND_REC;
7038         l_org_id                NUMBER ;
7039         --l_delid_tbl             IEX_DUNNING_PUB.DelId_NumList;
7040         l_del_tbl               IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE;
7041         l_ffm_cnt               NUMBER := 0;
7042         l_dunn_cnt              NUMBER := 0;
7043         l_bucket                VARCHAR2(100);
7044 
7045         l_running_level         VARCHAR2(25):= 'DELINQUENCY';
7046         l_object_Code           VARCHAR2(25);
7047         l_object_id             NUMBER;
7048 
7049         l_curr_dmethod          VARCHAR2(10);
7050         l_contact_destination   varchar2(240);  -- bug 3955222
7051         l_contact_party_id      number; -- bug 3955222
7052         l_contact_id            number;
7053         l_warning_flag          varchar2(1);
7054         l_contact_point_id      number;
7055         l_fully_promised        number := 1;  -- Added for bug#8408162
7056         l_allow_send            varchar2(1) :='Y'; -- Added for bug#8408162
7057         l_status                varchar2(10);
7058         --Start adding for bug 9156833 gnramasa 27th Nov 09
7059         l_validation_level		  NUMBER ;
7060         l_resource_tab		  iex_utilities.resource_tab_type;
7061         l_resource_id		  NUMBER;
7062         --End adding for bug 9156833 gnramasa 27th Nov 09
7063         l_turnoff_coll_on_bankru	  varchar2(10);
7064         l_no_of_bankruptcy		  number;
7065         l_grace_days                  number := 0;
7066         l_use_grace_days              varchar2(10);
7067         l_dun_disputed_items          varchar2(10);
7068         l_ag_dn_xref_id                number;
7069         l_min_currency_code		   varchar2(10);
7070         l_min_dunning_invoice_amount   number;
7071         l_invoice_amount               number;
7072         l_check_dunn_profile           varchar2(1);
7073         l_convert_amount               number;
7074          l_rate_type varchar2(100);
7075          l_dispute_amount   number := 0;
7076         cursor c_no_of_bankruptcy (p_par_id number)
7077         is
7078         select nvl(count(*),0)
7079         from iex_bankruptcies
7080         where party_id = p_par_id
7081         and (disposition_code in ('GRANTED','NEGOTIATION')
7082              OR (disposition_code is NULL));
7083        l_dun_yn varchar2(1) := 'Y';
7084     BEGIN
7085           -- Standard Start of API savepoint
7086           SAVEPOINT Send_DUNNING_PVT;
7087 
7088           --Bug#4679639 schekuri 20-OCT-2005
7089           --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
7090           --l_org_id        := fnd_profile.value('ORG_ID');
7091           l_org_id:= mo_global.get_current_org_id;
7092           WriteLog(' org_id in send dunning '|| l_org_id);
7093           -- Standard call to check for call compatibility.
7094           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
7095                                                p_api_version,
7096                                                l_api_name,
7097                                                G_PKG_NAME)
7098           THEN
7099               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7100           END IF;
7101 
7102           -- Initialize message list if p_init_msg_list is set to TRUE.
7103           IF FND_API.to_Boolean( p_init_msg_list )
7104           THEN
7105               FND_MSG_PUB.initialize;
7106           END IF;
7107 
7108           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
7109 
7110           -- Initialize API return status to SUCCESS
7111           x_return_status := FND_API.G_RET_STS_SUCCESS;
7112 
7113           --
7114           -- Api body
7115           --
7116           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ' || p_resend_flag);
7117           l_turnoff_coll_on_bankru	:= nvl(fnd_profile.value('IEX_TURNOFF_COLLECT_BANKRUPTCY'),'N');
7118           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_turnoff_coll_on_bankru: ' || l_turnoff_coll_on_bankru);
7119 
7120           FOR i in 1..p_delinquencies_tbl.count
7121           LOOP
7122               l_delinquency_id := p_delinquencies_tbl(i).delinquency_id;
7123               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==================');
7124               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ' || l_delinquency_Id);
7125               FND_FILE.PUT_LINE(FND_FILE.LOG, 'delinquency_id='||l_delinquency_id );
7126 
7127               -- Validate Data
7128 
7129              /*=============================================================
7130               *  For each Delinquency,
7131               *=============================================================*/
7132 
7133              l_party_cust_id := p_delinquencies_tbl(i).party_cust_id;
7134              l_account_id := p_delinquencies_tbl(i).cust_account_id;
7135              l_customer_site_use_id := p_delinquencies_tbl(i).customer_site_use_id;
7136 
7137     	 --Start for bug 10226333 gnramasa 4th Nov 2010
7138     	 Open c_del_object_type (p_dunning_plan_id);
7139     	 Fetch c_del_object_type into l_del_object_type;
7140     	 If ( c_del_object_type%NOTFOUND ) Then
7141     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Delinquency scoring engine donot have level');
7142     		 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Delinquency scoring engine donot have level');
7143     		 x_return_status := FND_API.G_RET_STS_ERROR;
7144     		 CLOSE c_del_object_type;
7145     		 RAISE FND_API.G_EXC_ERROR;
7146     	 end if;
7147     	 CLOSE c_del_object_type;
7148 
7149     	 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_del_object_type: '|| l_del_object_type);
7150     	 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_del_object_type: '|| l_del_object_type);
7151 
7152     	 if l_del_object_type = 'IEX_INVOICES' then
7153     		select payment_schedule_id into l_del_object_id
7154     		from iex_delinquencies_all
7155     		where delinquency_id = l_delinquency_id;
7156     	 elsif l_del_object_type = 'IEX_DELINQUENCY' then
7157     		l_del_object_id	:= l_delinquency_id;
7158     	 end if;
7159     	 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_del_object_id: '|| l_del_object_id);
7160     	 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_del_object_id: '|| l_del_object_id);
7161 
7162      	 open c_get_score_del (l_del_object_id, l_del_object_type);
7163     	 fetch c_get_score_del into l_score;
7164 
7165     	 If ( c_get_score_del%NOTFOUND) Then
7166                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_SCORE');
7167                     FND_MSG_PUB.Add;
7168                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Score NotFound');
7169                     Close c_get_score_del;
7170                     x_return_status := FND_API.G_RET_STS_ERROR;
7171                     GOTO end_loop;
7172                END IF;
7173 
7174     	 close c_get_score_del;
7175 
7176     	 open c_dunning_plan_dtl (p_dunning_plan_id);
7177          fetch c_dunning_plan_dtl into l_use_grace_days, l_dun_disputed_items;
7178          close c_dunning_plan_dtl;
7179     	 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_use_grace_days :'|| l_use_grace_days);
7180     	 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_dun_disputed_items :'|| l_dun_disputed_items);
7181          --l_score := p_delinquencies_tbl(i).score_value;
7182          --End for bug 10226333 gnramasa 4th Nov 2010
7183          --WriteLog('iexvdunb.pls:SendDunn:open del='||l_delinquency_Id);
7184          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - '||l_party_cust_id);
7185          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - '||l_account_id);
7186          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - '||l_customer_site_use_id);
7187          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - '||l_score);
7188          -- Start for the bug#8408162 by PNAVEENK
7189          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Start Fully Promise Check');
7190          SELECT count(1) into l_fully_promised
7191     	           FROM ar_payment_schedules_all ps, iex_delinquencies_all del
7192     		   WHERE del.delinquency_id= l_delinquency_id
7193     	             AND ps.payment_schedule_id = del.payment_schedule_id
7194     	             AND ps.status = 'OP'
7195     	             AND del.status IN ('DELINQUENT', 'PREDELINQUENT')
7196     		     and not exists(select 1 from iex_promise_details pd where pd.delinquency_id=del.delinquency_id
7197     		                                                       and pd.status='COLLECTABLE'
7198     	                                    	                       and pd.state='PROMISE'
7199     	                                                               group by pd.delinquency_id
7200     		                                                       having sum(nvl(pd.promise_amount,0))>=ps.amount_due_remaining);
7201     	  select fnd_profile.value(nvl('IEX_ALLOW_DUN_FULL_PROMISE','N')) into l_allow_send from dual;
7202 
7203     	  if l_turnoff_coll_on_bankru = 'Y' then
7204     		open c_no_of_bankruptcy (l_party_cust_id);
7205     		fetch c_no_of_bankruptcy into l_no_of_bankruptcy;
7206     		close c_no_of_bankruptcy;
7207     	  end if;
7208     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_no_of_bankruptcy: ' || l_no_of_bankruptcy);
7209 
7210     	  IF ( l_fully_promised = 0 and l_allow_send = 'Y' OR (l_turnoff_coll_on_bankru = 'Y' and l_no_of_bankruptcy >0)) then
7211     	   goto end_loop;
7212     	  END IF;
7213 
7214     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' End Fully Promise Check');
7215 
7216           if l_dun_disputed_items = 'N' then
7217 
7218     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Start Dispute Check');
7219     		 select sum(a.amount_in_dispute) - sum(a.amount_due_remaining) into l_dispute_amount
7220     		 from iex_delinquencies d
7221     		 ,ar_payment_schedules a
7222     		 where a.payment_schedule_id  = d.payment_schedule_id
7223     	         and d.delinquency_id = l_delinquency_id;
7224 
7225              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_amount in dispute : ' || l_dispute_amount);
7226 
7227     	     IF ( l_dispute_amount <= 0) then
7228     	        goto end_loop;
7229     	     END IF;
7230     	   end if;
7231     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' End Dispute Check');
7232 
7233     	   -- End for the bug#8408162 by PNAVEENK
7234               /*================================================================
7235                * IsDispute ?
7236                * If yes => stop (exit);
7237                * else continue;
7238                *
7239                * it returns values :
7240                * 1) it returns 'F' if no dispute exists for the delinquency
7241                * 2) it returns 'T' if dispute exists and is pending
7242                * 3) it returns 'F' if dispute exists and its staus is "COMPLETE"
7243                *================================================================*/
7244 
7245               /*WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Chk IsDispute');
7246 
7247                 IEX_DISPUTE_PVT.Is_Delinquency_Dispute(
7248                   p_api_version              => p_api_version
7249                 , p_init_msg_list            => p_init_msg_list
7250                 , p_delinquency_id           => l_delinquency_id
7251                 , x_return_status            => x_return_status
7252                 , x_msg_count                => x_msg_count
7253                 , x_msg_data                 => x_msg_data);
7254 
7255                 IF x_return_status = 'T' THEN
7256                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Dispute exists and is pending');
7257                    FND_FILE.PUT_LINE(FND_FILE.LOG, 'Dispute exists and is pending' );
7258                    GOTO end_loop;
7259                 elsif x_return_status = 'F' THEN
7260                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Dispute or status is COMPLETE');
7261                 END IF;*/
7262 
7263                /*===========================================
7264                 * Get Score From IEX_SCORE_HISTORIES
7265                 * If NotFound => Call API to getScore;
7266                 *===========================================*/
7267 
7268                /*===========================================
7269                 * get Aging_Bucket_Line_Id for each Del
7270                 *===========================================*/
7271 
7272                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetAgingBucketLineId');
7273                 --WriteLog('iexvdunb:SendDunn:delid='||l_delinquency_id);
7274 
7275                   AGING_DEL(p_api_version              => p_api_version
7276     				               , p_init_msg_list            => p_init_msg_list
7277     				               , p_commit                   => p_commit
7278     				               , p_delinquency_id           => l_delinquency_id
7279     				               , p_dunning_plan_id          => p_dunning_plan_id
7280     				               , p_bucket                   => l_bucket
7281     				               , x_return_status            => x_return_status
7282     				               , x_msg_count                => x_msg_count
7283     				               , x_msg_data                 => x_msg_data
7284     				               , x_aging_bucket_line_id     => l_bucket_line_id);
7285 
7286                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - AgingDel status='||x_return_status);
7287 
7288                 IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7289                    --FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
7290                    --FND_MESSAGE.Set_Token ('INFO', 'iex:AginBucketLineId', FALSE);
7291                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_AGINGBUCKETLINE');
7292                     FND_MSG_PUB.Add;
7293                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Get AgingBucketLineId');
7294                     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cannot AgingBucketLineId' );
7295                     --msg
7296                     FND_MSG_PUB.Count_And_Get
7297                     (  p_count          =>   x_msg_count,
7298                        p_data           =>   x_msg_data );
7299                     for i in 1..x_msg_count loop
7300                         errmsg := FND_MSG_PUB.Get(p_msg_index => i,
7301                                                   p_encoded => 'F');
7302                         FND_FILE.PUT_LINE(FND_FILE.LOG, 'Error:'||errmsg);
7303                         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - errmsg=' || errmsg);
7304                     end loop;
7305 
7306                     GOTO end_loop;
7307                   END IF;
7308 
7309                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - lineid='||l_bucket_line_id);
7310                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndAgingDel');
7311 
7312                /*===========================================
7313                 * Get Template_ID From iex_ag_dn_xref
7314                 *===========================================*/
7315 
7316                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template');
7317 
7318                Open C_Get_TEMPLATE(l_bucket_line_ID, l_score, p_dunning_plan_id);
7319                Fetch C_Get_TEMPLATE into
7320     	        	 l_ag_dn_xref_id,
7321                      l_template_id,
7322                      l_xdo_template_id,
7323                      l_method,
7324                      l_callback_flag,
7325                      l_callback_days,
7326                      l_bucket;
7327 
7328                If ( C_GET_TEMPLATE%NOTFOUND) Then
7329                    FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
7330                    FND_MSG_PUB.Add;
7331                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Missing corresponding template');
7332                    FND_FILE.PUT_LINE(FND_FILE.LOG, 'Missing corresponding template' );
7333                    Close C_Get_TEMPLATE;
7334                    GOTO end_loop;
7335                END IF;
7336 
7337                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - close C_GET_TEMPLATE');
7338                Close C_Get_TEMPLATE;
7339 
7340                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get ffm_template_id='||l_template_id);
7341                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get xdo_template_id='||l_xdo_template_id);
7342                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get bucket='||l_bucket);
7343 
7344     	   /*===========================================
7345                * Check the status of the template
7346                *===========================================*/
7347 
7348                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template status');
7349                Open C_TEMPLATE_STATUS(l_xdo_template_id);
7350                Fetch C_TEMPLATE_STATUS into l_template_status;
7351 
7352                If ( C_TEMPLATE_STATUS%NOTFOUND) Then
7353 
7354     		  open C_TEMPLATE_NAME (l_xdo_template_id);
7355     		  Fetch C_TEMPLATE_NAME into l_template_name;
7356     	  	  close C_TEMPLATE_NAME;
7357 
7358     		  FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
7359                   FND_MSG_PUB.Add;
7360                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
7361     	          FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
7362     	          RAISE FND_API.G_EXC_ERROR;
7363     	       END IF;
7364                Close C_TEMPLATE_STATUS;
7365     	       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
7366 
7367               /*===========================================
7368                * Check template
7369                *  in 11.5.11, IEX supports fulfillment and xml publisher.
7370                *  if the current setup for delivery id FFM,
7371                *  then template_id is necessary;
7372                *  if XML, xdo_template_id is necessary;
7373                *===========================================*/
7374 
7375                l_curr_dmethod := IEX_SEND_XML_PVT.getCurrDeliveryMethod;
7376                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - curr d_method='||l_curr_dmethod);
7377                if ( (l_curr_dmethod is null or l_curr_dmethod = '') or
7378                     (l_curr_dmethod = 'FFM' and l_template_id is null)  or
7379                     (l_curr_dmethod = 'XML' and l_xdo_template_id is null ) ) then
7380                     --FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
7381                     --FND_MESSAGE.Set_Token ('INFO', 'Template_ID', FALSE);
7382                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
7383                     FND_MSG_PUB.Add;
7384                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Missing corresponding template');
7385                     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Missing corresponding template' );
7386                     x_return_status := FND_API.G_RET_STS_ERROR;
7387                     GOTO end_loop;
7388                end if;
7389 
7390     		 if l_use_grace_days = 'Y' then
7391     			 iex_utilities.get_grace_days(p_api_version => p_api_version,
7392     					       p_init_msg_list     => FND_API.G_TRUE,
7393     					       p_commit            => FND_API.G_FALSE,
7394     					       p_validation_level  => l_validation_level,
7395     					       p_level             => l_running_level,
7396     					       p_party_id          => l_party_cust_id,
7397     					       p_account_id        => l_account_id,
7398     					       p_site_use_id       => l_customer_site_use_id,
7399     					       x_msg_count         => l_msg_count,
7400     					       x_msg_data          => l_msg_data,
7401     					       x_return_status     => l_return_status,
7402     					       x_grace_days        => l_grace_days);
7403     			 IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7404     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get grace days');
7405     			     -- x_return_status := FND_API.G_RET_STS_ERROR; --  bug 14797201
7406     			 END IF;
7407     		 end if;
7408     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_grace_days :'|| l_grace_days);
7409 
7410               /*===========================================
7411                * Check profile before send dunning
7412                *===========================================*/
7413 
7414                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - begin check customer profile');
7415                 -- ctlee - check the hz_customer_profiles.dunning_letter
7416                if ( iex_utilities.DunningProfileCheck (
7417                        p_party_id => l_party_cust_id
7418                        , p_cust_account_id => l_account_id
7419                        , p_site_use_id => l_customer_site_use_id
7420                        , p_delinquency_id => l_delinquency_id     ) = 'N'
7421                   ) then
7422                     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_PROFILE_NO');
7423                     FND_MSG_PUB.Add;
7424                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send dunning in customer profile set to no ');
7425                     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Send dunning in customer profile set to no ');
7426                     GOTO end_loop;
7427                end if;
7428                /*     -- ctlee - check the hz_customer_profiles_amt min_dunning_invoice_amount and min_dunning_amount
7429                if ( iex_utilities.DunningMinAmountCheck (
7430                         p_cust_account_id => l_account_id
7431                         , p_site_use_id => l_customer_site_use_id
7432     		    , p_org_id => l_org_id)  = 'N'  --Added for Bug 10401991 20-Jan-2011 barathsr
7433                   ) then
7434                     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');*/
7435 
7436 
7437            -- Open c_billto (l_customer_site_use_id ,l_org_id); -- bug 14797201
7438            -- fetch c_billto into l_min_currency_code, l_min_dunning_invoice_amount; -- bug 14797201
7439            -- close c_billto;  -- bug 14797201
7440 
7441 -- start comment for bug 15933013
7442 /*
7443           Open C_AMOUNT(l_delinquency_id);
7444           Fetch C_AMOUNT into l_amount, l_curr_code;
7445 
7446           If ( C_AMOUNT%NOTFOUND) Then
7447                    FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
7448                    FND_MESSAGE.Set_Token ('INFO', 'iex:amount', FALSE);
7449                    FND_MSG_PUB.Add;
7450                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount notfound');
7451           END IF;
7452           close C_AMOUNT;
7453 
7454           /* bug 14797201 start....
7455           l_check_dunn_profile := nvl(fnd_profile.value('IEX_CHK_DUNN_AT_FUNC_CURR'), 'Y');
7456           l_rate_type :=  nvl(fnd_profile.value('IEX_COLLECTIONS_RATE_TYPE'), 'Corporate');
7457 
7458     	  if l_check_dunn_profile = 'Y' and (l_curr_code <> l_min_currency_code) then
7459     	     begin
7460     		  l_convert_amount := gl_currency_api.convert_amount(
7461     		     x_from_currency => l_curr_code
7462     		     ,x_to_currency => l_min_currency_code
7463     		     ,x_conversion_date => sysdate
7464     		     ,x_conversion_type => l_rate_type
7465     		     ,x_amount => l_amount);
7466     	--	  l_amount := nvl(l_amount,0) + nvl(l_convert_amount,0);
7467     		exception
7468     		         when others then
7469     			    FND_FILE.PUT_LINE(FND_FILE.LOG,'error in currency conversion..pl check whether exchange rates are defined');
7470     			    FND_FILE.PUT_LINE(FND_FILE.LOG,sqlerrm);
7471     			    GOTO end_loop;
7472             end;
7473     	    l_amount := nvl(l_convert_amount,0);
7474     	end if;
7475         */  -- bug 14797201 end....
7476 
7477      /*   open  c_billto_min_dunn_amt (l_customer_site_use_id, l_curr_code);  -- bug 14797201
7478     	fetch c_billto_min_dunn_amt into l_profile_dunn_amt, l_profile_dunn_inv_amt;  -- bug 14797201
7479         if c_billto_min_dunn_amt%NOTFOUND then
7480               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - c_billto_min_dunn_amt%NOTFOUND '); -- bug 14797201
7481               l_profile_dunn_amt := 0;  -- bug 14797201
7482               l_profile_dunn_inv_amt :=0;  -- bug 14797201
7483         end if;
7484     	close c_billto_min_dunn_amt;  -- bug 14797201
7485     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Delinquency Amount (l_amount) :'|| l_amount);  -- bug 14797201
7486     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_profile_dunn_amt :'|| l_profile_dunn_amt);  -- bug 14797201
7487     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_profile_dunn_inv_amt :'|| l_profile_dunn_inv_amt);  -- bug 14797201
7488 
7489         if ((l_amount < l_profile_dunn_amt ) or (l_amount < l_profile_dunn_inv_amt )) then  -- bug 14797201
7490             -- if l_amount < l_min_dunning_invoice_amount then  -- bug 14797201
7491       */ -- end comment for bug 15933013
7492 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  begin check customer profile');
7493                 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_party_cust_id = '        || l_party_cust_id);
7494                 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_account_id = '           || l_account_id);
7495                 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_customer_site_use_id = ' || l_customer_site_use_id);
7496                 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_delinquency_id = '       || l_delinquency_id);
7497 
7498              /*   l_party_cust_id_check        := l_party_cust_id;
7499                 l_account_id_check           := l_account_id;
7500                 l_customer_site_use_id_check := l_customer_site_use_id;
7501                 l_delinquency_id_check       := l_delinquency_id;
7502 
7503                if (l_running_level = 'CUSTOMER') then
7504                   l_account_id_check := null;
7505                   l_customer_site_use_id_check := null;
7506                   l_delinquency_id_check := null;
7507                elsif  (l_running_level = 'ACCOUNT') then
7508                   l_customer_site_use_id_check := null;
7509                   l_delinquency_id_check := null;
7510                elsif  (l_running_level = 'BILL_TO') then
7511                   l_delinquency_id_check := null;
7512                end if; */
7513          -- start code for bug 15933013
7514         l_dun_yn := IEX_UTILITIES.DunningMinAmountCheck (
7515                               p_cust_account_id       => l_account_id
7516                             , p_site_use_id           => l_customer_site_use_id
7517                             , p_delinquency_id        => l_delinquency_id
7518                             , p_org_id                => l_org_id
7519                             , p_grace_days            => l_grace_days
7520                             , p_dun_disputed_items    => l_dun_disputed_items
7521                             , p_correspondence_date   => p_correspondence_date
7522                             , p_running_level         => l_running_level
7523                              );
7524         IF    l_dun_yn = 'N' then
7525               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Required min Dunning amount in customer profile ');
7526               FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
7527               FND_MSG_PUB.Add;
7528               GOTO end_loop;
7529         ELSIF l_dun_yn = 'E' then
7530               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - When Dunning level is Account, value of profile "IEX: Minimum Dunning Amount Profile Check" can''t be "Bill To" or "Bill To and Account".  ');
7531               FND_MESSAGE.Set_Name('IEX', 'IEX_DUN_CUST_PRF_INVALID');
7532               FND_MSG_PUB.Add;
7533               GOTO end_loop;
7534         END IF;
7535              -- end code for bug 15933013
7536         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end check customer profile');
7537 
7538         l_del_tbl(1).party_cust_id        := p_delinquencies_tbl(i).party_cust_id;
7539         l_del_tbl(1).cust_account_id      := p_delinquencies_tbl(i).cust_account_id;
7540         l_del_tbl(1).customer_site_use_id := p_delinquencies_tbl(i).customer_site_use_id;
7541     	  l_del_tbl(1).delinquency_id       := l_delinquency_id;
7542 
7543          --Start adding for bug 8489610 by gnramasa 14-May-09
7544     	 if p_dunning_mode <> 'DRAFT' then
7545     		   /*===========================================
7546     		    * Close OPEN Dunnings for each Del
7547     		    *===========================================*/
7548 
7549     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning');
7550     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - runninglevel=DELINQUENCY');
7551     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
7552     		    --l_del_tbl(1).delinquency_id := l_delinquency_id;
7553 
7554     		      /*if p_dunning_mode = 'DRAFT' then
7555     			l_status := 'CLOSE';
7556     		      else
7557     			l_status := 'OPEN';
7558     		      end if;
7559     		      */
7560 
7561     		      Close_DUNNING(p_api_version              => p_api_version
7562     								, p_init_msg_list            => p_init_msg_list
7563     								, p_commit                   => p_commit
7564     								, p_delinquencies_tbl        => l_del_tbl
7565     								, p_running_level            => 'DELINQUENCY'
7566     								--, p_status                   => l_status
7567     								, x_return_status            => x_return_status
7568     								, x_msg_count                => x_msg_count
7569     								, x_msg_data                 => x_msg_data);
7570 
7571     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning status='|| x_return_status);
7572 
7573     		      IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7574     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Close Dunning');
7575     			 --msg
7576     			 GOTO end_loop;
7577     		      END IF;
7578     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndCloseDunn');
7579     	 end if;
7580 
7581                /*===========================================
7582                 * Create Dunning Record
7583                 *===========================================*/
7584 
7585                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get CallbackDate');
7586                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag='||l_callback_flag);
7587                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDays='||l_callback_days);
7588 
7589                /*===================================================
7590                 * clchang updated 02/13/2003
7591                 * callback_days could be null if callback_yn = 'N';
7592                 * and if callback_yn = 'N', not get callback_date;
7593                 *==================================================*/
7594                 IF (l_callback_flag = 'Y') THEN
7595                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is Y: NOTGetCallbackDate');
7596                    Get_Callback_Date(p_init_msg_list        => p_init_msg_list
7597     		                           , p_callback_days        => l_callback_days
7598     		                           , x_callback_date        => l_callback_date
7599     		                           , x_return_status        => x_return_status
7600     		                           , x_msg_count            => x_msg_count
7601     		                           , x_msg_data             => x_msg_data);
7602 
7603                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetCallbackDate status='|| x_return_status);
7604                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDate='||l_callback_date);
7605 
7606                    IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7607                      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Get CallbackDate');
7608                      GOTO end_loop;
7609                    END IF;
7610 
7611                 ELSE
7612                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is N: NOTGetCallbackDate');
7613                 END IF;
7614 
7615                 /* get the current amount_due_remaining and currency_code */
7616                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET AMOUNT');
7617 
7618                 Open C_AMOUNT(l_delinquency_id);
7619                 Fetch C_AMOUNT into
7620                     l_amount,
7621                     l_curr_code;
7622 
7623                 If ( C_AMOUNT%NOTFOUND) Then
7624                    FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
7625                    FND_MESSAGE.Set_Token ('INFO', 'iex:amount', FALSE);
7626                    FND_MSG_PUB.Add;
7627                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount notfound');
7628                 END IF;
7629 
7630                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - close C_AMOUNT');
7631                 Close C_AMOUNT;
7632 
7633                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get amount='||l_amount);
7634                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get currcode='||l_curr_code);
7635                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning');
7636                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
7637                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id='||l_delinquency_id);
7638 
7639                 l_dunning_rec.delinquency_id := l_delinquency_id;
7640                 l_dunning_rec.callback_yn := l_callback_flag;
7641                 l_dunning_rec.callback_date := l_callback_date;
7642 	        	l_dunning_rec.ag_dn_xref_id	:= l_ag_dn_xref_id;
7643 
7644     	     if p_dunning_mode = 'DRAFT' then
7645     		l_dunning_rec.status := 'CLOSE';
7646     	     else
7647     		l_dunning_rec.status := 'OPEN';
7648     	     end if;
7649 
7650                 l_dunning_rec.dunning_method:= l_method;
7651                 l_dunning_rec.template_id:= l_template_id;
7652                 l_dunning_rec.xml_template_id:= l_xdo_template_id;
7653                 l_dunning_rec.campaign_sched_id := l_campaign_sched_id;
7654                 l_dunning_rec.xml_request_id := l_request_id;
7655                 l_dunning_rec.dunning_object_id := l_delinquency_id;
7656                 l_dunning_rec.dunning_level := 'DELINQUENCY';
7657                 l_dunning_rec.object_type := 'IEX_DELINQUENCY';
7658                 l_dunning_rec.object_id := l_delinquency_id;
7659                 l_dunning_rec.amount_due_remaining := l_amount;
7660                 l_dunning_rec.currency_code := l_curr_code;
7661                 l_dunning_rec.dunning_plan_id := p_dunning_plan_id;
7662                 l_dunning_rec.contact_destination := l_contact_destination;  -- bug 3955222
7663                 l_dunning_rec.contact_party_id := l_contact_party_id;  -- bug 3955222
7664     	    --Start adding for bug 8489610 by gnramasa 14-May-09
7665     	    l_dunning_rec.dunning_mode := p_dunning_mode;
7666     	    l_dunning_rec.confirmation_mode := p_confirmation_mode;
7667 
7668     	    l_dunning_rec.org_id := l_org_id; -- added for bug 9151851
7669                 l_dunning_rec.as_of_date := p_correspondence_date;
7670     	     if p_parent_request_id is not null then
7671     		l_dunning_rec.request_id := p_parent_request_id;
7672     	     else
7673     		l_dunning_rec.request_id := FND_GLOBAL.Conc_Request_Id;
7674     	     end if;
7675                  WriteLog(' Before creating dunning org_id '|| l_org_id);
7676                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
7677 
7678                 CREATE_DUNNING(p_api_version              => p_api_version
7679     							            , p_init_msg_list            => p_init_msg_list
7680     							            , p_commit                   => p_commit
7681     							            , p_dunning_rec              => l_dunning_rec
7682     							            , x_dunning_id               => l_dunning_id
7683     							            , x_return_status            => x_return_status
7684     							            , x_msg_count                => x_msg_count
7685     							            , x_msg_data                 => x_msg_data);
7686 
7687                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| x_return_status);
7688 
7689                 IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7690                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
7691                   GOTO end_loop;
7692                   else
7693 
7694                    INSERT_DUNNING_TRANSACTION(
7695     				p_api_version              => p_api_version
7696     			      , p_init_msg_list            => p_init_msg_list
7697     			      , p_commit                   => p_commit
7698     			      , p_delinquencies_tbl        => l_del_tbl
7699     			      , p_ag_dn_xref_id	           => l_ag_dn_xref_id
7700     			      , p_dunning_id               => l_dunning_id
7701     			      , p_correspondence_date      => p_correspondence_date
7702     			      , p_running_level            => l_running_level
7703     			      , p_grace_days               => l_grace_days
7704     			      , p_include_dispute_items    => l_dun_disputed_items
7705     			      , x_return_status            => x_return_status
7706     			      , x_msg_count                => x_msg_count
7707     			      , x_msg_data                 => x_msg_data
7708                               ,p_workitem_id               => null);  -- bug 14772139
7709 
7710                 END IF;
7711 
7712                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningId='||l_dunning_id);
7713                 --FND_FILE.PUT_LINE(FND_FILE.LOG, 'Create Dunning Id=' ||l_dunning_id);
7714                 l_dunn_cnt := l_dunn_cnt + 1;
7715 
7716                /*===========================================
7717                 * Send Letter through Fulfillment
7718                 *===========================================*/
7719                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send_Ffm');
7720                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org_id = '|| l_org_id);
7721                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id = '|| l_party_cust_id);
7722                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - acct_id = '|| l_account_id);
7723                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - site_use_id = '|| l_customer_site_use_id);
7724                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bucket_line_id = '|| l_bucket_line_id);
7725                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delinquency_id = '|| l_delinquency_id);
7726 
7727                 l_bind_tbl(1).key_name := 'party_id';
7728                 l_bind_tbl(1).key_type := 'NUMBER';
7729                 l_bind_tbl(1).key_value := l_party_cust_id;
7730     	    --Begin Bug 10401991 20-Jan-2011 barathsr
7731                 l_bind_tbl(2).key_name := 'org_id';
7732                 l_bind_tbl(2).key_type := 'NUMBER';
7733                 l_bind_tbl(2).key_value := l_org_id;
7734     	    --End Bug 10401991 20-Jan-2011 barathsr
7735                 l_bind_tbl(3).key_name := 'bucket_line_id';
7736                 l_bind_tbl(3).key_type := 'NUMBER';
7737                 l_bind_tbl(3).key_value := l_bucket_line_id;
7738                 l_bind_tbl(4).key_name := 'account_id';
7739                 l_bind_tbl(4).key_type := 'NUMBER';
7740                 l_bind_tbl(4).key_value := l_account_id;
7741                 l_bind_tbl(5).key_name := 'delinquency_id';
7742                 l_bind_tbl(5).key_type := 'NUMBER';
7743                 l_bind_tbl(5).key_value := l_delinquency_id;
7744                 -- added for BILL_TO in 11.5.10.
7745                 l_bind_tbl(6).key_name := 'customer_site_use_id';
7746                 l_bind_tbl(6).key_type := 'NUMBER';
7747                 l_bind_tbl(6).key_value := l_customer_site_use_id;
7748                 l_bind_tbl(7).key_name := 'DUNNING_ID';
7749                 l_bind_tbl(7).key_type := 'NUMBER';
7750                 l_bind_tbl(7).key_value := l_dunning_id;
7751 
7752     	 --Start adding for bug 9156833 gnramasa 27th Nov 09
7753     	 l_validation_level := FND_API.G_VALID_LEVEL_FULL;
7754 
7755     	 iex_utilities.get_dunning_resource(p_api_version => p_api_version,
7756     			       p_init_msg_list     => FND_API.G_TRUE,
7757     			       p_commit            => FND_API.G_FALSE,
7758     			       p_validation_level  => l_validation_level,
7759     			       p_level             => 'DUNNING_BILLTO',
7760     			       p_level_id          => l_customer_site_use_id,
7761     			       x_msg_count         => l_msg_count,
7762     			       x_msg_data          => l_msg_data,
7763     			       x_return_status     => l_return_status,
7764     			       x_resource_tab      => l_resource_tab);
7765     	 IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7766     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
7767     	     x_return_status := FND_API.G_RET_STS_ERROR;
7768     	 END IF;
7769 
7770     	  if l_resource_tab.count>0 then
7771     	    l_resource_id := l_resource_tab(1).resource_id;
7772     	  end if;
7773     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_resource_id: ' || l_resource_id);
7774     	  --End adding for bug 9156833 gnramasa 27th Nov 09
7775 
7776                 if (l_curr_dmethod = 'FFM') then
7777                    Send_Fulfillment(p_api_version              => p_api_version
7778                                    ,p_init_msg_list            => FND_API.G_TRUE
7779                                    ,p_commit                   => FND_API.G_TRUE
7780                                    ,p_fulfillment_bind_tbl     => l_bind_tbl
7781                                    ,p_template_id              => l_template_id
7782                                    ,p_method                   => l_method
7783                                    ,p_party_id                 => l_party_cust_id
7784                                    ,x_request_id               => l_request_id
7785                                    ,x_return_status            => x_return_status
7786                                    ,x_msg_count                => x_msg_count
7787     						                   ,x_msg_data                 => x_msg_data
7788     							                 ,x_contact_destination      => l_contact_destination
7789     							                 ,x_contact_party_id         => l_contact_party_id );
7790                 else
7791                    l_running_level := 'DELINQUENCY';
7792                    l_object_code := 'IEX_DELINQUENCY';
7793                    l_object_id := l_delinquency_id;
7794 
7795                    Send_XML(p_api_version              => p_api_version
7796                            ,p_init_msg_list            => FND_API.G_TRUE
7797                            ,p_commit                   => FND_API.G_TRUE
7798                            ,p_resend                   => 'N'
7799                            ,p_request_id               => null
7800                            ,p_fulfillment_bind_tbl     => l_bind_tbl
7801                            ,p_template_id              => l_xdo_template_id
7802                            ,p_method                   => l_method
7803                            ,p_party_id                 => l_party_cust_id
7804                            ,p_level                    => l_running_level
7805                            ,p_source_id                => l_object_id
7806                            ,p_object_code              => l_object_code
7807                            ,p_object_id                => l_object_id
7808     		       ,p_resource_id              => l_resource_id --Added for bug 9156833 gnramasa 27th Nov 09
7809     		       ,p_dunning_mode             => p_dunning_mode
7810     		       ,p_parent_request_id        => p_parent_request_id
7811                            ,p_org_id                   => l_org_id
7812     		       ,x_request_id               => l_request_id
7813                            ,x_return_status            => x_return_status
7814                            ,x_msg_count                => x_msg_count
7815      		                   ,x_msg_data                 => x_msg_data
7816     		                   ,x_contact_destination      => l_contact_destination
7817     		                   ,x_contact_party_id         => l_contact_party_id);
7818 
7819                 end if;
7820 
7821                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send status = ' || x_return_status);
7822     	    --End adding for bug 8489610 by gnramasa 14-May-09
7823 
7824                 IF x_return_status <> FND_API.G_RET_STS_SUCCESS and x_return_status <> 'W' THEN
7825                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Sending Letters');
7826                    FND_MSG_PUB.Count_And_Get(p_count          =>   x_msg_count,
7827                                              p_data           =>   x_msg_data );
7828                    for i in 1..x_msg_count loop
7829                       errmsg := FND_MSG_PUB.Get(p_msg_index => i,
7830                                                 p_encoded => 'F');
7831                       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Error:'||errmsg);
7832                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - errmsg=' || errmsg);
7833                    end loop;
7834                    GOTO end_loop;
7835                 elsif x_return_status = 'W' then
7836                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - setting warning flag');
7837                   l_warning_flag := 'W';
7838                 end if;
7839 
7840                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||l_request_id);
7841 
7842                 l_dunning_rec_upd.dunning_id := l_dunning_id;
7843                 if (l_curr_dmethod = 'FFM') then
7844                     l_dunning_rec_upd.ffm_request_id := l_request_id;
7845                 else
7846                     l_dunning_rec_upd.xml_request_id := l_request_id;
7847                 end if;
7848 
7849                 IEX_DUNNING_PVT.Update_DUNNING(p_api_version              => 1.0
7850     													                , p_init_msg_list            => FND_API.G_TRUE
7851     													                , p_commit                   => FND_API.G_TRUE
7852     													                , p_dunning_rec              => l_dunning_rec_upd
7853     													                , x_return_status            => l_return_status
7854     													                , x_msg_count                => l_msg_count
7855     													                , x_msg_data                 => l_msg_data);
7856 
7857                 l_ffm_cnt := l_ffm_cnt + 1;
7858 
7859                /*===========================================
7860                 * Update Delinquency
7861                 * Set DUNN_YN = 'N'
7862                 *===========================================*/
7863                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UpdateDel');
7864 
7865                   nIdx := nIdx + 1;
7866                   del_tbl(nIdx) := l_delinquency_id;
7867 
7868                 <<end_loop>>
7869                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_loop');
7870                 NULL;
7871 
7872           END LOOP; -- end of DELINQUENCIES_TBL loop
7873 
7874          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========Summarty==========');
7875          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SendFFM Cnt='||l_ffm_cnt);
7876          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunn Cnt='||l_dunn_cnt);
7877          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========End Summarty==========');
7878 
7879           --
7880           -- End of API body
7881           --
7882           if l_warning_flag = 'W' then
7883             x_return_status := 'W';
7884           end if;
7885 
7886           COMMIT WORK;
7887 
7888           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return status = ' || x_return_status);
7889           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
7890 
7891           FND_MSG_PUB.Count_And_Get
7892           (  p_count          =>   x_msg_count,
7893              p_data           =>   x_msg_data );
7894 
7895           EXCEPTION
7896               WHEN FND_API.G_EXC_ERROR THEN
7897                   COMMIT WORK;
7898                   x_return_status := FND_API.G_RET_STS_ERROR;
7899                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
7900                   FND_MSG_PUB.Count_And_Get
7901                   (  p_count          =>   x_msg_count,
7902                      p_data           =>   x_msg_data );
7903 
7904               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
7905                   COMMIT WORK;
7906                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
7907                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
7908                   FND_MSG_PUB.Count_And_Get
7909                   (  p_count          =>   x_msg_count,
7910                      p_data           =>   x_msg_data );
7911 
7912               WHEN OTHERS THEN
7913                   COMMIT WORK;
7914                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
7915                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
7916                   FND_MSG_PUB.Count_And_Get
7917                   (  p_count          =>   x_msg_count,
7918                      p_data           =>   x_msg_data );
7919 
7920     END Send_Dunning;
7921 
7922     /*==========================================================================
7923      * gnramasa created 30th Dec 2009 -
7924      * Single Stage Letter is not menaingful option at delinquency level
7925      * Include current invoices, Unapplied receipts also not valid.
7926      *==========================================================================*/
7927     Procedure Send_Staged_Dunning
7928                (p_api_version             IN NUMBER := 1.0,
7929                 p_init_msg_list           IN VARCHAR2 ,
7930                 p_commit                  IN VARCHAR2 ,
7931                 p_dunning_plan_id         in number,
7932     	          p_correspondence_date     IN DATE,
7933                 p_resend_flag             IN VARCHAR2,
7934                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
7935                 p_parent_request_id       IN NUMBER,
7936     	          p_dunning_mode	      IN VARCHAR2,     -- added by gnramasa for bug 8489610 14-May-09
7937     	          p_single_staged_letter    IN VARCHAR2 DEFAULT 'N',    -- added by gnramasa for bug stageddunning 30-Dec-09
7938     	          p_confirmation_mode	      IN   VARCHAR2,   -- added by gnramasa for bug 8489610 14-May-09
7939                 x_return_status           OUT NOCOPY VARCHAR2,
7940                 x_msg_count               OUT NOCOPY NUMBER,
7941                 x_msg_data                OUT NOCOPY VARCHAR2)
7942     IS
7943         CURSOR C_GET_DEL (IN_del_ID NUMBER) IS
7944           SELECT delinquency_ID,
7945                  party_cust_id,
7946                  cust_account_id,
7947                  customer_site_use_id,
7948                  score_value
7949             FROM IEX_DELINQUENCIES
7950            WHERE delinquency_ID = in_del_ID;
7951         --
7952         CURSOR C_GET_SCORE (IN_ID NUMBER) IS
7953           SELECT a.score_value
7954             FROM IEX_SCORE_HISTORIES a
7955            WHERE a.score_object_ID = in_ID
7956              AND a.score_object_code = 'IEX_DELINQUENCY'
7957              AND a.creation_date = (select max(b.creation_date)
7958                                       from iex_score_histories b
7959                                      where b.score_object_id = in_id
7960                                        AND b.score_object_code = 'IEX_DELINQUENCY');
7961 
7962         --Start  bug 10226333 by gnramasa 4-Nov-10
7963         Cursor c_get_score_del(p_object_id number,  p_object_type varchar2) is
7964              select score_value
7965                     from iex_score_histories
7966                     where score_object_id = p_object_id
7967                     and score_object_code = p_object_type
7968                     order by creation_date desc;
7969 
7970           cursor c_del_object_type(p_dunn_plan_id number) is
7971           select isc.jtf_object_code
7972     	from iex_dunning_plans_vl ipd, IEX_SCORES isc
7973     	where ipd.dunning_plan_id = p_dunn_plan_id
7974     	and ipd.score_id=isc.score_id;
7975 
7976           l_del_object_type     varchar2(50);
7977           l_del_object_id       number;
7978 
7979           --End adding for bug 10226333 by gnramasa 4-Nov-10
7980 
7981         --
7982         CURSOR C_GET_TEMPLATE (l_line_id NUMBER,
7983                                l_score NUMBER, p_dunning_plan_id number) IS
7984           SELECT
7985                  x.template_id,
7986                  x.xdo_template_id,
7987                  x.fm_method,
7988                  upper(x.callback_flag),
7989                  x.callback_days,
7990                  ar.bucket_name
7991             FROM IEX_AG_DN_XREF x,
7992                  ar_aging_buckets ar,
7993                  iex_dunning_plans_vl d
7994            WHERE x.aging_bucket_line_ID = l_line_ID
7995              and x.dunning_plan_id = p_dunning_plan_id
7996              AND l_score between x.score_range_low and x.score_range_high
7997              AND x.aging_bucket_id = ar.aging_bucket_id
7998              and ar.aging_bucket_id = d.aging_bucket_id
7999              AND ar.status = 'A'
8000              AND x.dunning_level = 'DELINQUENCY' ;
8001 
8002          CURSOR C_TEMPLATE_STATUS (l_template_id number) is
8003          select 'Active'
8004          from xdo_templates_vl xdo
8005          where xdo.template_id = l_template_id
8006          and trunc(sysdate) >= TRUNC (NVL(xdo.start_date, sysdate))
8007          and trunc(sysdate) < TRUNC(NVL(xdo.end_date, sysdate + 1));
8008 
8009          l_template_status		  varchar2(10);
8010 
8011          CURSOR C_TEMPLATE_NAME (l_template_id number) is
8012          select template_name
8013          from xdo_templates_vl xdo
8014          where xdo.template_id = l_template_id;
8015 
8016          l_template_name	varchar2(500);
8017         --
8018         cursor c_amount (IN_ID number) is
8019          select ps.amount_due_remaining,
8020                 ps.invoice_currency_code
8021            from ar_payment_schedules_all ps,
8022                 --iex_delinquencies_all del
8023                 iex_delinquencies del
8024           where ps.payment_schedule_id (+)= del.payment_schedule_id
8025             and del.delinquency_id = in_id;
8026         --
8027 
8028         l_AMOUNT                NUMBER;
8029         l_CURR_CODE             VARCHAR2(15);
8030         l_DUNNING_id            NUMBER;
8031         l_delinquency_id        NUMBER;
8032         l_party_cust_id         NUMBER;
8033         l_account_id            NUMBER;
8034         l_customer_site_use_id  NUMBER;
8035         l_location_id           number;
8036         l_dunning_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
8037         l_dunning_rec_upd       IEX_DUNNING_PUB.DUNNING_REC_TYPE;
8038         l_score                 NUMBER;
8039         l_bucket_line_id        NUMBER;
8040         l_campaign_sched_id     NUMBER;
8041         l_template_id           NUMBER;
8042         l_xdo_template_id       NUMBER;
8043         l_method                VARCHAR2(10);
8044         l_callback_flag         VARCHAR2(1);
8045         l_callback_days         NUMBER;
8046         l_callback_date         DATE;
8047         l_request_id            NUMBER;
8048         l_outcome_code          varchar2(20);
8049         l_api_name              CONSTANT VARCHAR2(30) := 'Send_Staged_Dunning';
8050         l_api_version_number    CONSTANT NUMBER   := 1.0;
8051         l_return_status         VARCHAR2(1);
8052         l_msg_count             NUMBER;
8053         l_msg_data              VARCHAR2(32767);
8054         errmsg                  VARCHAR2(32767);
8055         --
8056         nIdx                    NUMBER := 0;
8057         TYPE Del_ID_TBL_type is Table of IEX_DELINQUENCIES_ALL.DELINQUENCY_ID%TYPE
8058                                 INDEX BY BINARY_INTEGER;
8059         Del_Tbl                 Del_ID_TBL_TYPE;
8060         l_bind_tbl              IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
8061         l_bind_rec              IEX_DUNNING_PVT.FULFILLMENT_BIND_REC;
8062         l_org_id                NUMBER ;
8063         --l_delid_tbl             IEX_DUNNING_PUB.DelId_NumList;
8064         l_del_tbl               IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE;
8065         l_ffm_cnt               NUMBER := 0;
8066         l_dunn_cnt              NUMBER := 0;
8067         l_bucket                VARCHAR2(100);
8068 
8069         l_running_level         VARCHAR2(25);
8070         l_object_Code           VARCHAR2(25);
8071         l_object_id             NUMBER;
8072 
8073         l_curr_dmethod          VARCHAR2(10);
8074         l_contact_destination   varchar2(240);  -- bug 3955222
8075         l_contact_party_id      number; -- bug 3955222
8076         l_contact_id            number;
8077         l_warning_flag          varchar2(1);
8078         l_contact_point_id      number;
8079         l_fully_promised        number := 1;  -- Added for bug#8408162
8080         l_allow_send            varchar2(1) :='Y'; -- Added for bug#8408162
8081         l_status                varchar2(10);
8082 
8083         Type refCur			  is Ref Cursor;
8084         sql_cur			  refCur;
8085         sql_cur1			  refCur;
8086         sql_cur2			  refCur;
8087         sql_cur3			  refCur;
8088         vPLSQL			  VARCHAR2(2000);
8089         vPLSQL1			  VARCHAR2(2000);
8090         vPLSQL2			  VARCHAR2(2000);
8091         vPLSQL3			  VARCHAR2(2000);
8092         l_orderby			  varchar2(20);
8093         l_no_of_rows		  number;
8094         l_ag_dn_xref_id	          number;
8095         l_atleast_one_trx		  varchar2(10);
8096         l_stage			  number;
8097         l_acc_dunning_trx_null_dun_ct number;
8098         l_acc_dunning_trx_ct	  number;
8099         l_skip_this_dunn_planlineid   number;
8100         l_first_satified_dunnplanid   number;
8101         l_grace_days                  number := 0;
8102         l_use_grace_days              varchar2(10);
8103         l_dun_disputed_items          varchar2(10);
8104         --l_inc_inv_curr                IEX_UTILITIES.INC_INV_CURR_TBL;
8105         l_dunn_letters                varchar2(10);
8106         l_inv_curr			  varchar2(20);
8107         l_amt_due_remaining		  number;
8108         l_profile_dunn_amt		  number;
8109         l_profile_dunn_inv_amt	  number;
8110         l_staged_dunning_level        number;
8111         l_transaction_id              number;
8112         l_payment_schedule_id         number;
8113         l_rowid                       Varchar2(50);
8114         X_DUNNING_TRX_ID              number;
8115 
8116         cursor c_dunning_plan_dtl (p_dunn_plan_id number) is
8117         select nvl(dunn.grace_days ,'N'),
8118                nvl(dunn.dun_disputed_items, 'N')
8119         from iex_dunning_plans_b dunn
8120         where dunning_plan_id = p_dunn_plan_id;
8121 
8122         cursor c_billto_min_dunn_amt (p_site_use_id number, p_currency_code varchar) is
8123     	select nvl(min_dunning_amount,0), nvl(min_dunning_invoice_amount,0)
8124     	from hz_cust_profile_amts
8125     	where site_use_id = p_site_use_id
8126     	and currency_code = p_currency_code;
8127 
8128         cursor c_inv_details (p_delinquency_id number) is
8129             select arp.invoice_currency_code,
8130     	       arp.amount_due_remaining,
8131     	       del.staged_dunning_level,
8132     	       del.transaction_id,
8133     	       del.payment_schedule_id
8134     	from iex_delinquencies del,
8135     	     ar_payment_schedules arp
8136     	where del.delinquency_id = p_delinquency_id
8137     	and del.payment_schedule_id = arp.payment_schedule_id;
8138 
8139         cursor c_dunningplan_lines (p_dunning_plan_id number, p_stage number, p_score number) is
8140     	select ag_dn_xref_id,
8141     	 dunning_level,
8142     	 template_id,
8143     	 xdo_template_id,
8144     	 fm_method,
8145     	 upper(callback_flag) callback_flag,
8146     	 callback_days,
8147     	 range_of_dunning_level_from,
8148     	 range_of_dunning_level_to,
8149     	 min_days_between_dunning ,
8150     	 invoice_copies
8151     	 from iex_ag_dn_xref
8152     	 where dunning_plan_id = p_dunning_plan_id
8153     	 --and range_of_dunning_level_from >= p_stage
8154     	 --and range_of_dunning_level_to <= p_stage
8155     	 and p_stage between range_of_dunning_level_from and range_of_dunning_level_to
8156     	 and p_score between score_range_low and score_range_high;
8157 
8158         cursor c_acc_dunning_trx_null_dun_ct (p_del_id number, p_min_days_bw_dun number,
8159                                               p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
8160         select count(*) from (
8161         select del.delinquency_id,
8162                del.transaction_id,
8163                del.payment_schedule_id
8164         from iex_delinquencies del,
8165              ar_payment_schedules arp
8166         where del.payment_schedule_id = arp.payment_schedule_id
8167         and del.status in ('DELINQUENT','PREDELINQUENT')
8168         and del.delinquency_id = p_del_id
8169         and del.staged_dunning_level is NULL
8170         and (trunc(arp.due_date) + p_min_days_bw_dun) <= p_corr_date
8171         and (trunc(arp.due_date) + p_grace_days) <= p_corr_date
8172         and nvl(arp.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(arp.amount_in_dispute,0), 0)
8173         /*
8174         union
8175         select del.delinquency_id,
8176                del.transaction_id,
8177                del.payment_schedule_id
8178         from iex_delinquencies del,
8179              ar_payment_schedules arp
8180         where del.payment_schedule_id = arp.payment_schedule_id
8181         and del.status = 'CURRENT'
8182         and del.delinquency_id = p_del_id
8183         and del.staged_dunning_level is NULL
8184         and arp.status = 'OP'
8185         and arp.class = 'INV'
8186         and (trunc(arp.due_date) + p_min_days_bw_dun) <= p_corr_date
8187         and (trunc(arp.due_date) + p_grace_days) <= p_corr_date
8188         and arp.amount_in_dispute >= decode(p_include_dis_items, 'Y', arp.amount_due_remaining, (arp.amount_due_original + 1))
8189         */
8190         );
8191 
8192         cursor c_acc_dunning_trx_ct (p_del_id number, p_stage_no number,
8193                                      p_min_days_bw_dun number, p_corr_date date, p_include_dis_items varchar) is
8194         select count(*) from (
8195         select del.delinquency_id,
8196                del.transaction_id,
8197                del.payment_schedule_id
8198         from iex_delinquencies del
8199              ,ar_payment_schedules arp
8200         where
8201         del.payment_schedule_id = arp.payment_schedule_id and
8202         del.status in ('DELINQUENT','PREDELINQUENT')
8203         and del.delinquency_id = p_del_id
8204         and del.staged_dunning_level = p_stage_no
8205         and nvl(arp.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(arp.amount_in_dispute,0), 0)
8206         and nvl(
8207                  (
8208     	        (select trunc(correspondence_date) from iex_dunnings
8209                      where dunning_id =
8210                         (select max(iet.DUNNING_ID) from iex_dunning_transactions iet,
8211     		                                     iex_dunnings dunn
8212                          where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
8213                          and dunn.dunning_id = iet.dunning_id
8214     		     and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
8215     					OR (dunn.dunning_mode = 'FINAL'))
8216     		     and iet.STAGE_NUMBER = p_stage_no
8217     		     and dunn.delivery_status is null
8218     		     --group by iet.dunning_id
8219     		    )
8220     		 )
8221     	       + p_min_days_bw_dun
8222     	      )
8223     	     , p_corr_date
8224     	    )
8225     	    <= p_corr_date
8226         /*
8227         union
8228         select del.delinquency_id,
8229                del.transaction_id,
8230                del.payment_schedule_id
8231         from iex_delinquencies del
8232              ,ar_payment_schedules arp
8233         where
8234         del.payment_schedule_id = arp.payment_schedule_id and
8235         del.status = 'CURRENT'
8236         and del.party_cust_id = p_party_id
8237         and del.cust_account_id = p_cust_acct_id
8238         and del.staged_dunning_level = p_stage_no
8239         and arp.status = 'OP'
8240         and arp.class = 'INV'
8241         and arp.amount_in_dispute >= decode(p_include_dis_items, 'Y', arp.amount_due_remaining, (arp.amount_due_original + 1))
8242         and nvl(
8243             (
8244     	 (select trunc(correspondence_date) from iex_dunnings
8245               where dunning_id =
8246                (select distinct DUNNING_ID from iex_dunning_transactions
8247                 where PAYMENT_SCHEDULE_ID = del.payment_schedule_id
8248                 and STAGE_NUMBER = p_stage_no))
8249     	    + p_min_days_bw_dun )
8250     	    , p_corr_date )
8251     	    <= p_corr_date
8252          */
8253          );
8254 
8255         l_dunningplan_lines	c_dunningplan_lines%rowtype;
8256 
8257         --Start adding for bug 9156833 gnramasa 27th Nov 09
8258         l_validation_level		  NUMBER ;
8259         l_resource_tab		  iex_utilities.resource_tab_type;
8260         l_resource_id		  NUMBER;
8261         --End adding for bug 9156833 gnramasa 27th Nov 09
8262         l_turnoff_coll_on_bankru	  varchar2(10);
8263         l_no_of_bankruptcy		  number;
8264         l_min_days_between_dunn_99	  number;
8265 
8266         cursor c_no_of_bankruptcy (p_par_id number)
8267         is
8268         select nvl(count(*),0)
8269         from iex_bankruptcies
8270         where party_id = p_par_id
8271         and (disposition_code in ('GRANTED','NEGOTIATION')
8272              OR (disposition_code is NULL));
8273 
8274         cursor c_min_days_between_dunn_99 (p_dunn_plan_id number, p_stage_no number, p_score_val number)
8275         is
8276         select min_days_between_dunning
8277         from iex_ag_dn_xref
8278         where dunning_plan_id = p_dunn_plan_id
8279         and p_stage_no between range_of_dunning_level_from and range_of_dunning_level_to
8280         and p_score_val between score_range_low and score_range_high;
8281 
8282         l_inv_xdo_template_id	number;
8283         l_invoice_copies		varchar(10);
8284 
8285     BEGIN
8286           -- Standard Start of API savepoint
8287           SAVEPOINT Send_Staged_Dunning_PVT;
8288 
8289           --Bug#4679639 schekuri 20-OCT-2005
8290           --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
8291           --l_org_id        := fnd_profile.value('ORG_ID');
8292           l_org_id:= mo_global.get_current_org_id;
8293           WriteLog(G_PKG_NAME || ' ' || l_api_name ||' org_id in send dunning '|| l_org_id);
8294 
8295           -- Standard call to check for call compatibility.
8296           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
8297                                                p_api_version,
8298                                                l_api_name,
8299                                                G_PKG_NAME)
8300           THEN
8301               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
8302           END IF;
8303 
8304           -- Initialize message list if p_init_msg_list is set to TRUE.
8305           IF FND_API.to_Boolean( p_init_msg_list )
8306           THEN
8307               FND_MSG_PUB.initialize;
8308           END IF;
8309 
8310           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
8311 
8312           -- Initialize API return status to SUCCESS
8313           x_return_status := FND_API.G_RET_STS_SUCCESS;
8314 
8315           --
8316           -- Api body
8317           --
8318           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ' || p_resend_flag);
8319           l_turnoff_coll_on_bankru	:= nvl(fnd_profile.value('IEX_TURNOFF_COLLECT_BANKRUPTCY'),'N');
8320           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_turnoff_coll_on_bankru: ' || l_turnoff_coll_on_bankru);
8321 
8322     	l_validation_level := FND_API.G_VALID_LEVEL_FULL;
8323 
8324     	 open c_dunning_plan_dtl (p_dunning_plan_id);
8325     	 fetch c_dunning_plan_dtl into l_use_grace_days, l_dun_disputed_items;
8326     	 close c_dunning_plan_dtl;
8327     	 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_use_grace_days :'|| l_use_grace_days);
8328     	 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_dun_disputed_items :'|| l_dun_disputed_items);
8329 
8330     	 FOR i in 1..p_delinquencies_tbl.count
8331     	      LOOP
8332     		  l_delinquency_id := p_delinquencies_tbl(i).delinquency_id;
8333     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==================');
8334     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ' || l_delinquency_Id);
8335     		  FND_FILE.PUT_LINE(FND_FILE.LOG, 'delinquency_id='||l_delinquency_id );
8336 
8337     		  -- Validate Data
8338 
8339     		 /*=============================================================
8340     		  *  For each Delinquency,
8341     		  *=============================================================*/
8342 
8343     		 l_party_cust_id := p_delinquencies_tbl(i).party_cust_id;
8344     		 l_account_id := p_delinquencies_tbl(i).cust_account_id;
8345     		 l_customer_site_use_id := p_delinquencies_tbl(i).customer_site_use_id;
8346 
8347     		 --Start for bug 10226333 gnramasa 4th Nov 2010
8348     		 Open c_del_object_type (p_dunning_plan_id);
8349     		 Fetch c_del_object_type into l_del_object_type;
8350     		 If ( c_del_object_type%NOTFOUND ) Then
8351     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Delinquency scoring engine donot have level');
8352     			 FND_FILE.PUT_LINE(FND_FILE.LOG, 'Delinquency scoring engine donot have level');
8353     			 close c_del_object_type;
8354     			 x_return_status := FND_API.G_RET_STS_ERROR;
8355     			 RAISE FND_API.G_EXC_ERROR;
8356     		 end if;
8357     		 CLOSE c_del_object_type;
8358 
8359     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_del_object_type: '|| l_del_object_type);
8360     		 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_del_object_type: '|| l_del_object_type);
8361 
8362     		 if l_del_object_type = 'IEX_INVOICES' then
8363     			select payment_schedule_id into l_del_object_id
8364     			from iex_delinquencies_all
8365     			where delinquency_id = l_delinquency_id;
8366     		 elsif l_del_object_type = 'IEX_DELINQUENCY' then
8367     			l_del_object_id	:= l_delinquency_id;
8368     		 end if;
8369     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_del_object_id: '|| l_del_object_id);
8370     		 FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_del_object_id: '|| l_del_object_id);
8371 
8372     		 open c_get_score_del (l_del_object_id, l_del_object_type);
8373     		 fetch c_get_score_del into l_score;
8374 
8375     		 If ( c_get_score_del%NOTFOUND) Then
8376     			FND_MESSAGE.Set_Name('IEX', 'IEX_NO_SCORE');
8377     			FND_MSG_PUB.Add;
8378     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Score NotFound');
8379     			Close c_get_score_del;
8380     			x_return_status := FND_API.G_RET_STS_ERROR;
8381     			-- GOTO end_loop_noCloseCursor; -- end_loop;  bug 14797201
8382     			GOTO end_loop;  -- restored from bug 14797201
8383     		   END IF;
8384 
8385     		 close c_get_score_del;
8386     		 --l_score := p_delinquencies_tbl(i).score_value;
8387     		 --End for bug 10226333 gnramasa 4th Nov 2010
8388 
8389     		  --WriteLog('iexvdunb.pls:SendDunn:open del='||l_delinquency_Id);
8390     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - '||l_party_cust_id);
8391     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - '||l_account_id);
8392     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - '||l_customer_site_use_id);
8393     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - '||l_score);
8394 
8395     		  if l_turnoff_coll_on_bankru = 'Y' then
8396     			open c_no_of_bankruptcy (l_party_cust_id);
8397     			fetch c_no_of_bankruptcy into l_no_of_bankruptcy;
8398     			close c_no_of_bankruptcy;
8399     		  end if;
8400     		  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_no_of_bankruptcy: ' || l_no_of_bankruptcy);
8401 
8402     		  IF (l_turnoff_coll_on_bankru = 'Y' and l_no_of_bankruptcy >0) then
8403     		   --goto end_loop_noCloseCursor; -- end_loop;  bug 14797201
8404                    goto end_loop;  -- restored from bug 14797201
8405     		  END IF;
8406 
8407     		 if l_use_grace_days = 'Y' then
8408     			 iex_utilities.get_grace_days(p_api_version => p_api_version,
8409     					       p_init_msg_list     => FND_API.G_TRUE,
8410     					       p_commit            => FND_API.G_FALSE,
8411     					       p_validation_level  => l_validation_level,
8412     					       p_level             => 'BILL_TO',  --get the grace days from the site level profile
8413     					       p_party_id          => l_party_cust_id,
8414     					       p_account_id        => l_account_id,
8415     					       p_site_use_id       => l_customer_site_use_id,
8416     					       x_msg_count         => l_msg_count,
8417     					       x_msg_data          => l_msg_data,
8418     					       x_return_status     => l_return_status,
8419     					       x_grace_days        => l_grace_days);
8420     			 IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
8421     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get grace days');
8422     			     -- x_return_status := FND_API.G_RET_STS_ERROR;  bug 14797201
8423     			 END IF;
8424     		 end if;
8425     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_grace_days :'|| l_grace_days);
8426 
8427     		 open c_inv_details (l_delinquency_id);
8428     		 fetch c_inv_details into l_inv_curr, l_amt_due_remaining, l_staged_dunning_level, l_transaction_id, l_payment_schedule_id;
8429     		 close c_inv_details;
8430     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_inv_curr :'|| l_inv_curr);
8431     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_amt_due_remaining :'|| l_amt_due_remaining);
8432     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_staged_dunning_level :'|| l_staged_dunning_level);
8433     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_transaction_id :'|| l_transaction_id);
8434     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_payment_schedule_id :'|| l_payment_schedule_id);
8435 
8436     		 if l_staged_dunning_level is null then
8437     			l_stage := 1;
8438     		 else
8439     			l_stage := l_staged_dunning_level + 1;
8440     		 end if;
8441     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_stage :'||l_stage);
8442 
8443     		 --Start bug 9696806 gnramasa 27th May 10
8444     		 open c_min_days_between_dunn_99 (p_dunning_plan_id, 99, l_score);
8445     		 fetch c_min_days_between_dunn_99 into l_min_days_between_dunn_99;
8446     		 close c_min_days_between_dunn_99;
8447     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_min_days_between_dunn_99 :'|| l_min_days_between_dunn_99);
8448 
8449     		 update iex_delinquencies del
8450     		 set staged_dunning_level = 98
8451     		 where delinquency_id = l_delinquency_id
8452     		 and staged_dunning_level = 99
8453     		 and status in ('DELINQUENT','PREDELINQUENT')
8454     		 and nvl(
8455     			 (
8456     			    (select trunc(correspondence_date) from iex_dunnings
8457     			     where dunning_id =
8458     				(select max(iet.DUNNING_ID)
8459     				from iex_dunning_transactions iet,
8460     				     iex_dunnings dunn
8461     				 where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
8462     					    and dunn.dunning_id = iet.dunning_id
8463     					    and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
8464     						    OR (dunn.dunning_mode = 'FINAL'))
8465     				 and iet.STAGE_NUMBER = 99
8466     				 and dunn.delivery_status is null
8467     				)
8468     			     )
8469     			   + l_min_days_between_dunn_99
8470     			  )
8471     			     , p_correspondence_date
8472     		      )
8473     		      <= p_correspondence_date ;
8474 
8475     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Updated : ' || SQL%ROWCOUNT || ' number of row''s staged_dunning_level from 99 to 98');
8476     	        commit;
8477     	        --End bug 9696806 gnramasa 27th May 10
8478 
8479                  l_dunn_letters := 'Y';    -- bug 14797201
8480     		 open c_billto_min_dunn_amt (l_customer_site_use_id, l_inv_curr);
8481     		 fetch c_billto_min_dunn_amt into l_profile_dunn_amt, l_profile_dunn_inv_amt;
8482     		 close c_billto_min_dunn_amt;
8483     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_profile_dunn_amt :'|| l_profile_dunn_amt);
8484     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_profile_dunn_inv_amt :'|| l_profile_dunn_inv_amt);
8485 
8486     		 if (l_amt_due_remaining < l_profile_dunn_amt ) or (l_amt_due_remaining < l_profile_dunn_inv_amt ) then
8487     			l_dunn_letters := 'N';
8488     		 end if;
8489 
8490     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_dunn_letters: ' || l_dunn_letters);
8491 
8492     		   if l_dunn_letters = 'N' then
8493     			FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
8494     			FND_MSG_PUB.Add;
8495     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Required min Dunning amount in customer profile ');
8496     			FND_FILE.PUT_LINE(FND_FILE.LOG, 'Required min Dunning amount in customer profile ');
8497     			x_return_status := FND_API.G_RET_STS_ERROR;
8498                         GOTO end_loop; -- GOTO end_api;  -- bug 14797201
8499     		   end if;
8500 
8501     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  end check customer profile');
8502 
8503     		open c_dunningplan_lines (p_dunning_plan_id, l_stage, l_score);
8504 
8505     		 loop
8506     			 fetch c_dunningplan_lines into l_dunningplan_lines;
8507     			 exit when c_dunningplan_lines%notfound;
8508 
8509     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.ag_dn_xref_id='||l_dunningplan_lines.ag_dn_xref_id);
8510     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.dunning_level='||l_dunningplan_lines.dunning_level);
8511     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.template_id='||l_dunningplan_lines.template_id);
8512     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.xdo_template_id='||l_dunningplan_lines.xdo_template_id);
8513     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.fm_method='||l_dunningplan_lines.fm_method);
8514     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.callback_flag='||l_dunningplan_lines.callback_flag);
8515     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.callback_days='||l_dunningplan_lines.callback_days);
8516     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.range_of_dunning_level_from='||l_dunningplan_lines.range_of_dunning_level_from);
8517     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.range_of_dunning_level_to='||l_dunningplan_lines.range_of_dunning_level_to);
8518     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.min_days_between_dunning='||l_dunningplan_lines.min_days_between_dunning);
8519     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunningplan_lines.invoice_copies='||l_dunningplan_lines.invoice_copies);
8520 
8521     			 l_ag_dn_xref_id			:= l_dunningplan_lines.ag_dn_xref_id;
8522     			 l_template_id				:= l_dunningplan_lines.template_id;
8523     			 l_xdo_template_id			:= l_dunningplan_lines.xdo_template_id;
8524     			 l_method				:= l_dunningplan_lines.fm_method;
8525     			 l_callback_flag			:= l_dunningplan_lines.callback_flag;
8526     			 l_callback_days			:= l_dunningplan_lines.callback_days;
8527     			 l_invoice_copies			:= l_dunningplan_lines.invoice_copies;
8528 
8529     			 /*===========================================
8530     			  * Check the status of the template
8531     			  *===========================================*/
8532 
8533     			  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template status');
8534     			  Open C_TEMPLATE_STATUS(l_dunningplan_lines.xdo_template_id);
8535     			  Fetch C_TEMPLATE_STATUS into l_template_status;
8536 
8537     			  If ( C_TEMPLATE_STATUS%NOTFOUND) Then
8538 
8539     				open C_TEMPLATE_NAME (l_dunningplan_lines.xdo_template_id);
8540     				Fetch C_TEMPLATE_NAME into l_template_name;
8541     				close C_TEMPLATE_NAME;
8542 
8543     				FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
8544     				FND_MSG_PUB.Add;
8545     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
8546     				FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
8547     				RAISE FND_API.G_EXC_ERROR;
8548     			  END IF;
8549     			  Close C_TEMPLATE_STATUS;
8550     			  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
8551 
8552     			for i in l_dunningplan_lines.range_of_dunning_level_from..l_dunningplan_lines.range_of_dunning_level_to
8553     			      loop
8554 
8555     					l_skip_this_dunn_planlineid := 1;
8556 
8557     					if l_stage = 1 then
8558 
8559     						 open c_acc_dunning_trx_null_dun_ct (l_delinquency_id,
8560     									    l_dunningplan_lines.min_days_between_dunning,
8561     									    p_correspondence_date,
8562     									    l_grace_days,
8563     									    l_dun_disputed_items);
8564     						 fetch c_acc_dunning_trx_null_dun_ct into l_acc_dunning_trx_null_dun_ct;
8565     						 close c_acc_dunning_trx_null_dun_ct;
8566 
8567     						 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_acc_dunning_trx_null_dun_ct :'||l_acc_dunning_trx_null_dun_ct);
8568     						 if l_acc_dunning_trx_null_dun_ct <> 0 then
8569     							WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Delinquency exist for this stage, so will continue...');
8570     							l_skip_this_dunn_planlineid := 0;
8571     							goto STAGE_DUNN;
8572     						 end if;
8573 
8574     					else
8575 
8576     						 open c_acc_dunning_trx_ct (l_delinquency_id,
8577     									   l_staged_dunning_level,
8578     									   l_dunningplan_lines.min_days_between_dunning,
8579     									   p_correspondence_date,
8580     									   l_dun_disputed_items);
8581     						 fetch c_acc_dunning_trx_ct into l_acc_dunning_trx_ct;
8582     						 close c_acc_dunning_trx_ct;
8583 
8584     						 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_acc_dunning_trx_ct :'||l_acc_dunning_trx_ct);
8585     						 if l_acc_dunning_trx_ct <> 0 then
8586     							WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Delinquency exist for this stage, so will continue...');
8587     							l_skip_this_dunn_planlineid := 0;
8588     							goto STAGE_DUNN;
8589     						 end if;
8590 
8591     					end if;
8592 
8593     			      end loop;
8594     			  <<STAGE_DUNN>>
8595     			  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_skip_this_dunn_planlineid: '|| l_skip_this_dunn_planlineid);
8596     			  if l_skip_this_dunn_planlineid = 1 then
8597     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Delinquency doesn''t exist for this stage, so skipping...');
8598     				goto c_dunning_plan_lines;
8599     			  end if;
8600 
8601     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get ffm_template_id='||l_template_id);
8602     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get xdo_template_id='||l_xdo_template_id);
8603     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get bucket='||l_bucket);
8604 
8605     		  /*===========================================
8606     		   * Check template
8607     		   *  in 11.5.11, IEX supports fulfillment and xml publisher.
8608     		   *  if the current setup for delivery id FFM,
8609     		   *  then template_id is necessary;
8610     		   *  if XML, xdo_template_id is necessary;
8611     		   *===========================================*/
8612 
8613     		   l_curr_dmethod := IEX_SEND_XML_PVT.getCurrDeliveryMethod;
8614     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - curr d_method='||l_curr_dmethod);
8615     		   if ( (l_curr_dmethod is null or l_curr_dmethod = '') or
8616     			(l_curr_dmethod = 'FFM' and l_template_id is null)  or
8617     			(l_curr_dmethod = 'XML' and l_xdo_template_id is null ) ) then
8618     			--FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
8619     			--FND_MESSAGE.Set_Token ('INFO', 'Template_ID', FALSE);
8620     			FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
8621     			FND_MSG_PUB.Add;
8622     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Missing corresponding template');
8623     			FND_FILE.PUT_LINE(FND_FILE.LOG, 'Missing corresponding template' );
8624     			x_return_status := FND_API.G_RET_STS_ERROR;
8625                         goto c_dunning_plan_lines; -- GOTO end_loop;  -- bug 14797201
8626     		   end if;
8627 
8628     		  /*===========================================
8629     		   * Check profile before send dunning
8630     		   *===========================================*/
8631 
8632     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - begin check customer profile');
8633     		    -- ctlee - check the hz_customer_profiles.dunning_letter
8634     		   if ( iex_utilities.DunningProfileCheck (
8635     			   p_party_id => l_party_cust_id
8636     			   , p_cust_account_id => l_account_id
8637     			   , p_site_use_id => l_customer_site_use_id
8638     			   , p_delinquency_id => l_delinquency_id     ) = 'N'
8639     		      ) then
8640     			FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_PROFILE_NO');
8641     			FND_MSG_PUB.Add;
8642     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send dunning in customer profile set to no ');
8643     			FND_FILE.PUT_LINE(FND_FILE.LOG, 'Send dunning in customer profile set to no ');
8644                         goto c_dunning_plan_lines; -- GOTO end_loop;  -- bug 14797201
8645     			GOTO end_loop;
8646     		   end if;
8647 
8648     		 --Start adding for bug 8489610 by gnramasa 14-May-09
8649     		 if p_dunning_mode <> 'DRAFT' then
8650     			   /*===========================================
8651     			    * Close OPEN Dunnings for each Del
8652     			    *===========================================*/
8653 
8654     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning');
8655     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - runninglevel=DELINQUENCY');
8656     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
8657     			      l_del_tbl(1).delinquency_id := l_delinquency_id;
8658 
8659     			      Close_Staged_Dunning(p_api_version             => p_api_version
8660     						, p_init_msg_list            => p_init_msg_list
8661     						, p_commit                   => p_commit
8662     						, p_delinquencies_tbl        => l_del_tbl
8663     						, p_ag_dn_xref_id	     => l_ag_dn_xref_id
8664     						, p_running_level            => 'DELINQUENCY'
8665     						--, p_status                   => l_status
8666     						, x_return_status            => x_return_status
8667     						, x_msg_count                => x_msg_count
8668     						, x_msg_data                 => x_msg_data);
8669 
8670     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning status='|| x_return_status);
8671 
8672     			      IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
8673     				 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Close Dunning');
8674     				 --msg
8675                                  goto c_dunning_plan_lines; -- GOTO end_loop;  -- bug 14797201
8676     			      END IF;
8677     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndCloseDunn');
8678     		 end if;
8679 
8680     		   /*===========================================
8681     		    * Create Dunning Record
8682     		    *===========================================*/
8683 
8684     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get CallbackDate');
8685     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag='||l_callback_flag);
8686     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDays='||l_callback_days);
8687 
8688     		   /*===================================================
8689     		    * clchang updated 02/13/2003
8690     		    * callback_days could be null if callback_yn = 'N';
8691     		    * and if callback_yn = 'N', not get callback_date;
8692     		    *==================================================*/
8693     		    IF (l_callback_flag = 'Y') THEN
8694     		       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is Y: NOTGetCallbackDate');
8695     		       Get_Callback_Date(p_init_msg_list        => p_init_msg_list
8696     						   , p_callback_days        => l_callback_days
8697     						   , p_correspondence_date  => p_correspondence_date
8698     						   , x_callback_date        => l_callback_date
8699     						   , x_return_status        => x_return_status
8700     						   , x_msg_count            => x_msg_count
8701     						   , x_msg_data             => x_msg_data);
8702 
8703     		       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetCallbackDate status='|| x_return_status);
8704     		       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDate='||l_callback_date);
8705 
8706     		       IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
8707     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Get CallbackDate');
8708                          goto c_dunning_plan_lines; -- GOTO end_loop;  -- bug 14797201
8709     		       END IF;
8710 
8711     		    ELSE
8712     		       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is N: NOTGetCallbackDate');
8713     		    END IF;
8714 
8715     		    /* get the current amount_due_remaining and currency_code */
8716     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET AMOUNT');
8717 
8718     		    Open C_AMOUNT(l_delinquency_id);
8719     		    Fetch C_AMOUNT into
8720     			l_amount,
8721     			l_curr_code;
8722 
8723     		    If ( C_AMOUNT%NOTFOUND) Then
8724     		       FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
8725     		       FND_MESSAGE.Set_Token ('INFO', 'iex:amount', FALSE);
8726     		       FND_MSG_PUB.Add;
8727     		       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount notfound');
8728     		    END IF;
8729 
8730     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - close C_AMOUNT');
8731     		    Close C_AMOUNT;
8732 
8733     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get amount='||l_amount);
8734     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get currcode='||l_curr_code);
8735     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning');
8736     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
8737     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id='||l_delinquency_id);
8738                         l_inv_xdo_template_id := null;
8739     		    if nvl(l_invoice_copies,'N') = 'Y' then
8740     			 l_inv_xdo_template_id := fnd_profile.value('IEX_INVOICE_FULFILLMENT_TEMPLATE');
8741     			 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Template ID for Invoice : '||l_inv_xdo_template_id);
8742 
8743     		    /*===========================================
8744     		   * Check the status of the template
8745     		   *===========================================*/
8746 
8747     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Invoice Template status');
8748     		   Open C_TEMPLATE_STATUS(l_inv_xdo_template_id);
8749     		   Fetch C_TEMPLATE_STATUS into l_template_status;
8750 
8751     		   If ( C_TEMPLATE_STATUS%NOTFOUND) Then
8752 
8753     			open C_TEMPLATE_NAME (l_inv_xdo_template_id);
8754     			Fetch C_TEMPLATE_NAME into l_template_name;
8755     			close C_TEMPLATE_NAME;
8756 
8757     			FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
8758     			FND_MSG_PUB.Add;
8759     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
8760     			FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
8761     			RAISE FND_API.G_EXC_ERROR;
8762     		   END IF;
8763     		   Close C_TEMPLATE_STATUS;
8764     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
8765     		  ELSE
8766             		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - invoice_copies is N: Dont Send Invoice');
8767                       end if;
8768 
8769     		    l_dunning_rec.delinquency_id := l_delinquency_id;
8770     		    l_dunning_rec.callback_yn := l_callback_flag;
8771     		    l_dunning_rec.callback_date := l_callback_date;
8772 
8773     		     if p_dunning_mode = 'DRAFT' then
8774     			l_dunning_rec.status := 'CLOSE';
8775     		     else
8776     			l_dunning_rec.status := 'OPEN';
8777     		     end if;
8778 
8779     		    l_dunning_rec.dunning_method:= l_method;
8780     		    l_dunning_rec.template_id:= l_template_id;
8781     		    l_dunning_rec.xml_template_id:= l_xdo_template_id;
8782     		    l_dunning_rec.addt_xml_template_id := l_inv_xdo_template_id;
8783     		    l_dunning_rec.campaign_sched_id := l_campaign_sched_id;
8784     		    l_dunning_rec.xml_request_id := l_request_id;
8785     		    l_dunning_rec.dunning_object_id := l_delinquency_id;
8786     		    l_dunning_rec.dunning_level := 'DELINQUENCY';
8787     		    l_dunning_rec.object_type := 'IEX_DELINQUENCY';
8788     		    l_dunning_rec.object_id := l_delinquency_id;
8789     		    l_dunning_rec.amount_due_remaining := l_amount;
8790     		    l_dunning_rec.currency_code := l_curr_code;
8791     		    l_dunning_rec.dunning_plan_id := p_dunning_plan_id;
8792     		    l_dunning_rec.contact_destination := l_contact_destination;  -- bug 3955222
8793     		    l_dunning_rec.contact_party_id := l_contact_party_id;  -- bug 3955222
8794     		    --Start adding for bug 8489610 by gnramasa 14-May-09
8795     		    l_dunning_rec.dunning_mode := p_dunning_mode;
8796     		    l_dunning_rec.confirmation_mode := p_confirmation_mode;
8797     		    l_dunning_rec.ag_dn_xref_id	:= l_ag_dn_xref_id;
8798     		    l_dunning_rec.correspondence_date	:= p_correspondence_date;
8799 
8800     		     if p_parent_request_id is not null then
8801     			l_dunning_rec.request_id := p_parent_request_id;
8802     		     else
8803     			l_dunning_rec.request_id := FND_GLOBAL.Conc_Request_Id;
8804     		     end if;
8805 
8806     		     l_dunning_rec.org_id := l_org_id;
8807     		     WriteLog(G_PKG_NAME || ' ' || l_api_name ||' Before creating dunning org_id '|| l_org_id);
8808 
8809     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
8810 
8811     		    CREATE_DUNNING(p_api_version                 => p_api_version
8812     				    , p_init_msg_list            => p_init_msg_list
8813     				    , p_commit                   => p_commit
8814     				    , p_dunning_rec              => l_dunning_rec
8815     				    , x_dunning_id               => l_dunning_id
8816     				    , x_return_status            => x_return_status
8817     				    , x_msg_count                => x_msg_count
8818     				    , x_msg_data                 => x_msg_data);
8819 
8820     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| x_return_status);
8821 
8822     		    IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
8823     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
8824                       goto c_dunning_plan_lines; -- GOTO end_loop;  -- bug 14797201
8825     		    END IF;
8826 
8827     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningId='||l_dunning_id);
8828     		    --FND_FILE.PUT_LINE(FND_FILE.LOG, 'Create Dunning Id=' ||l_dunning_id);
8829     		    l_dunn_cnt := l_dunn_cnt + 1;
8830 
8831     		    begin
8832     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
8833     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_delinquency_id :'||l_delinquency_id);
8834     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_transaction_id :'||l_transaction_id);
8835     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_payment_schedule_id : '||l_payment_schedule_id);
8836 
8837     			      IEX_Dunnings_PKG.insert_staged_dunning_row(
8838     				  px_rowid                          => l_rowid
8839     				, px_dunning_trx_id                 => x_dunning_trx_id
8840     				, p_dunning_id                      => l_dunning_id
8841     				, p_cust_trx_id                     => l_transaction_id
8842     				, p_payment_schedule_id             => l_payment_schedule_id
8843     				, p_ag_dn_xref_id                   => l_ag_dn_xref_id
8844     				, p_stage_number                    => l_stage
8845     				, p_created_by                      => FND_GLOBAL.USER_ID
8846     				, p_creation_date                   => sysdate
8847     				, p_last_updated_by                 => FND_GLOBAL.USER_ID
8848     				, p_last_update_date                => sysdate
8849     				, p_last_update_login               => FND_GLOBAL.USER_ID
8850     				, p_object_version_number	    => 1.0
8851     			      );
8852 
8853     			      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
8854 
8855     			      IF x_return_status = FND_API.G_RET_STS_ERROR then
8856     					raise FND_API.G_EXC_ERROR;
8857     			      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
8858     				       raise FND_API.G_EXC_UNEXPECTED_ERROR;
8859     			      END IF;
8860 
8861     			      /*
8862     			      if p_dunning_mode <> 'DRAFT' then
8863     				      update iex_delinquencies_all
8864     				      set staged_dunning_level = l_stage
8865     				      where delinquency_id = l_delinquency_id;
8866     			      end if;
8867     			      */
8868 
8869     			      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
8870     			      x_dunning_trx_id	:= null;
8871     		    end;
8872 
8873     		   /*===========================================
8874     		    * Send Letter through Fulfillment
8875     		    *===========================================*/
8876     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send_Ffm');
8877     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org_id = '|| l_org_id);
8878     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id = '|| l_party_cust_id);
8879     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - acct_id = '|| l_account_id);
8880     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - site_use_id = '|| l_customer_site_use_id);
8881     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bucket_line_id = '|| l_bucket_line_id);
8882     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delinquency_id = '|| l_delinquency_id);
8883 
8884     		    l_bind_tbl(1).key_name := 'party_id';
8885     		    l_bind_tbl(1).key_type := 'NUMBER';
8886     		    l_bind_tbl(1).key_value := l_party_cust_id;
8887     		    --Begin Bug 10401991 20-Jan-2011 barathsr
8888     		    l_bind_tbl(2).key_name := 'org_id';
8889     		    l_bind_tbl(2).key_type := 'NUMBER';
8890     		    l_bind_tbl(2).key_value := l_org_id;
8891     		    --End Bug 10401991 20-Jan-2011 barathsr
8892     		    l_bind_tbl(3).key_name := 'bucket_line_id';
8893     		    l_bind_tbl(3).key_type := 'NUMBER';
8894     		    l_bind_tbl(3).key_value := l_bucket_line_id;
8895     		    l_bind_tbl(4).key_name := 'account_id';
8896     		    l_bind_tbl(4).key_type := 'NUMBER';
8897     		    l_bind_tbl(4).key_value := l_account_id;
8898     		    l_bind_tbl(5).key_name := 'delinquency_id';
8899     		    l_bind_tbl(5).key_type := 'NUMBER';
8900     		    l_bind_tbl(5).key_value := l_delinquency_id;
8901     		    -- added for BILL_TO in 11.5.10.
8902     		    l_bind_tbl(6).key_name := 'customer_site_use_id';
8903     		    l_bind_tbl(6).key_type := 'NUMBER';
8904     		    l_bind_tbl(6).key_value := l_customer_site_use_id;
8905     		    l_bind_tbl(7).key_name := 'DUNNING_ID';
8906     		    l_bind_tbl(7).key_type := 'NUMBER';
8907     		    l_bind_tbl(7).key_value := l_dunning_id;
8908 
8909     		    --Start adding for bug 9156833 gnramasa 27th Nov 09
8910     		    l_validation_level := FND_API.G_VALID_LEVEL_FULL;
8911 
8912     		    iex_utilities.get_dunning_resource(p_api_version => p_api_version,
8913     				       p_init_msg_list     => FND_API.G_TRUE,
8914     				       p_commit            => FND_API.G_FALSE,
8915     				       p_validation_level  => l_validation_level,
8916     				       p_level             => 'DUNNING_BILLTO',
8917     				       p_level_id          => l_customer_site_use_id,
8918     				       x_msg_count         => l_msg_count,
8919     				       x_msg_data          => l_msg_data,
8920     				       x_return_status     => l_return_status,
8921     				       x_resource_tab      => l_resource_tab);
8922     		   IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
8923     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
8924     		     x_return_status := FND_API.G_RET_STS_ERROR;
8925     		   END IF;
8926 
8927     		   if l_resource_tab.count>0 then
8928     		    l_resource_id := l_resource_tab(1).resource_id;
8929     		   end if;
8930     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_resource_id: ' || l_resource_id);
8931     		   --End adding for bug 9156833 gnramasa 27th Nov 09
8932 
8933     		    if (l_curr_dmethod = 'FFM') then
8934     		       Send_Fulfillment(p_api_version              => p_api_version
8935     				       ,p_init_msg_list            => FND_API.G_TRUE
8936     				       ,p_commit                   => FND_API.G_TRUE
8937     				       ,p_fulfillment_bind_tbl     => l_bind_tbl
8938     				       ,p_template_id              => l_template_id
8939     				       ,p_method                   => l_method
8940     				       ,p_party_id                 => l_party_cust_id
8941     				       ,x_request_id               => l_request_id
8942     				       ,x_return_status            => x_return_status
8943     				       ,x_msg_count                => x_msg_count
8944     				       ,x_msg_data                 => x_msg_data
8945     				       ,x_contact_destination      => l_contact_destination
8946     				       ,x_contact_party_id         => l_contact_party_id );
8947     		    else
8948     		       l_running_level := 'DELINQUENCY';
8949     		       l_object_code := 'IEX_DELINQUENCY';
8950     		       l_object_id := l_delinquency_id;
8951 
8952     		       Send_XML(p_api_version              => p_api_version
8953     			       ,p_init_msg_list            => FND_API.G_TRUE
8954     			       ,p_commit                   => FND_API.G_TRUE
8955     			       ,p_resend                   => 'N'
8956     			       ,p_request_id               => null
8957     			       ,p_fulfillment_bind_tbl     => l_bind_tbl
8958     			       ,p_template_id              => l_xdo_template_id
8959     			       ,p_method                   => l_method
8960     			       ,p_party_id                 => l_party_cust_id
8961     			       ,p_level                    => l_running_level
8962     			       ,p_source_id                => l_object_id
8963     			       ,p_object_code              => l_object_code
8964     			       ,p_object_id                => l_object_id
8965     			       ,p_resource_id              => l_resource_id --Added for bug 9156833 gnramasa 27th Nov 09
8966     			       ,p_dunning_mode             => p_dunning_mode
8967     			       ,p_parent_request_id        => p_parent_request_id
8968     			       ,p_org_id                   => l_org_id
8969     			       ,p_addt_template_id	   => l_inv_xdo_template_id
8970     			       ,x_request_id               => l_request_id
8971     			       ,x_return_status            => x_return_status
8972     			       ,x_msg_count                => x_msg_count
8973     			       ,x_msg_data                 => x_msg_data
8974     			       ,x_contact_destination      => l_contact_destination
8975     			       ,x_contact_party_id         => l_contact_party_id);
8976 
8977     		    end if;
8978 
8979     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send status = ' || x_return_status);
8980     		    --End adding for bug 8489610 by gnramasa 14-May-09
8981 
8982     		    IF x_return_status <> FND_API.G_RET_STS_SUCCESS and x_return_status <> 'W' THEN
8983     		       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Sending Letters');
8984     		       FND_MSG_PUB.Count_And_Get(p_count          =>   x_msg_count,
8985     						 p_data           =>   x_msg_data );
8986     		       for i in 1..x_msg_count loop
8987     			  errmsg := FND_MSG_PUB.Get(p_msg_index => i,
8988     						    p_encoded => 'F');
8989     			  FND_FILE.PUT_LINE(FND_FILE.LOG, 'Error:'||errmsg);
8990     			  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - errmsg=' || errmsg);
8991     		       end loop;
8992                        goto c_dunning_plan_lines; -- GOTO end_loop;  -- bug 14797201
8993     		    elsif x_return_status = 'W' then
8994     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - setting warning flag');
8995     		      l_warning_flag := 'W';
8996     		    end if;
8997 
8998     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||l_request_id);
8999 
9000     		    l_dunning_rec_upd.dunning_id := l_dunning_id;
9001     		    if (l_curr_dmethod = 'FFM') then
9002     			l_dunning_rec_upd.ffm_request_id := l_request_id;
9003     		    else
9004     			l_dunning_rec_upd.xml_request_id := l_request_id;
9005     		    end if;
9006 
9007     		    IEX_DUNNING_PVT.Update_DUNNING(p_api_version              => 1.0
9008     						, p_init_msg_list            => FND_API.G_TRUE
9009     						, p_commit                   => FND_API.G_TRUE
9010     						, p_dunning_rec              => l_dunning_rec_upd
9011     						, x_return_status            => l_return_status
9012     						, x_msg_count                => l_msg_count
9013     						, x_msg_data                 => l_msg_data);
9014 
9015     		    l_ffm_cnt := l_ffm_cnt + 1;
9016 
9017     		   /*===========================================
9018     		    * Update Delinquency
9019     		    * Set DUNN_YN = 'N'
9020     		    *===========================================*/
9021     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UpdateDel');
9022 
9023     		      nIdx := nIdx + 1;
9024     		      del_tbl(nIdx) := l_delinquency_id;
9025 
9026     		    <<c_dunning_plan_lines>>
9027     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - c_dunning_plan_lines');
9028 
9029     	      END LOOP; -- end of DELINQUENCIES_TBL loop
9030 
9031               <<end_loop>>
9032 
9033               If c_dunningplan_lines%ISOPEN then   -- added by bug 14797201
9034                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - closing Cursor c_dunningplan_lines');
9035     	         close c_dunningplan_lines;
9036               end if;
9037 
9038               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No closing Cursor c_dunningplan_lines'); -- bug 14797201
9039     	      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_loop');
9040     	end loop;
9041 
9042          --Start bug 9696806 gnramasa 27th May 10
9043     	if p_dunning_mode = 'DRAFT'  then
9044     		update iex_delinquencies del
9045     		set staged_dunning_level = 99
9046     		where delinquency_id = l_delinquency_id
9047     		and staged_dunning_level = 98
9048     		and status in ('DELINQUENT','PREDELINQUENT')
9049     		and exists (select count(iet.DUNNING_ID)
9050     				from iex_dunning_transactions iet,
9051     				     iex_dunnings dunn
9052     				 where iet.PAYMENT_SCHEDULE_ID = del.payment_schedule_id
9053     					    and dunn.dunning_id = iet.dunning_id
9054     					    and ((dunn.dunning_mode = 'DRAFT' and dunn.confirmation_mode = 'CONFIRMED')
9055     						    OR (dunn.dunning_mode = 'FINAL'))
9056     				 and iet.STAGE_NUMBER = 99
9057     				 and dunn.delivery_status is null
9058     			    );
9059 
9060     	    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Updated : ' || SQL%ROWCOUNT || ' number of row''s staged_dunning_level from 98 to 99');
9061     	    commit;
9062     	end if;
9063 
9064         --End bug 9696806 gnramasa 27th May 10
9065 
9066          <<end_api>>
9067          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========Summarty==========');
9068          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SendFFM Cnt='||l_ffm_cnt);
9069          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunn Cnt='||l_dunn_cnt);
9070          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========End Summarty==========');
9071 
9072           --
9073           -- End of API body
9074           --
9075           if l_warning_flag = 'W' then
9076             x_return_status := 'W';
9077           end if;
9078 
9079           COMMIT WORK;
9080 
9081           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return status = ' || x_return_status);
9082           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
9083 
9084           FND_MSG_PUB.Count_And_Get
9085           (  p_count          =>   x_msg_count,
9086              p_data           =>   x_msg_data );
9087 
9088           EXCEPTION
9089               WHEN FND_API.G_EXC_ERROR THEN
9090                   COMMIT WORK;
9091                   x_return_status := FND_API.G_RET_STS_ERROR;
9092                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
9093                   FND_MSG_PUB.Count_And_Get
9094                   (  p_count          =>   x_msg_count,
9095                      p_data           =>   x_msg_data );
9096 
9097               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
9098                   COMMIT WORK;
9099                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
9100                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
9101                   FND_MSG_PUB.Count_And_Get
9102                   (  p_count          =>   x_msg_count,
9103                      p_data           =>   x_msg_data );
9104 
9105               WHEN OTHERS THEN
9106                   COMMIT WORK;
9107                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
9108                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
9109                   FND_MSG_PUB.Count_And_Get
9110                   (  p_count          =>   x_msg_count,
9111                      p_data           =>   x_msg_data );
9112 
9113     END Send_Staged_Dunning;
9114 
9115     /*=========================================================================
9116        clchang added 03/04/2003 -
9117          Resend_Level_Dunning and Resend_Dunning are called by FORM,
9118          and just for resend;
9119          Only one record once, not loop;
9120        clchang updated 04/21/2003 -
9121          added one new level 'BILL_TO' in 11.5.10.
9122     *=========================================================================*/
9123     Procedure Resend_Level_Dunning
9124                (p_api_version             IN NUMBER := 1.0,
9125                 p_init_msg_list           IN VARCHAR2 ,
9126                 p_commit                  IN VARCHAR2 ,
9127                 p_dunning_plan_id         in number,
9128                 p_running_level           IN VARCHAR2,
9129                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
9130                 p_org_id                  in number,
9131     	    	p_dunning_id              in Number,
9132     	    	x_request_id              OUT NOCOPY NUMBER,
9133                 x_return_status           OUT NOCOPY VARCHAR2,
9134                 x_msg_count               OUT NOCOPY NUMBER,
9135                 x_msg_data                OUT NOCOPY VARCHAR2)
9136 
9137     IS
9138         CURSOR C_GET_DEL (IN_del_ID NUMBER) IS
9139           SELECT delinquency_ID
9140             FROM IEX_DELINQUENCIES
9141            WHERE delinquency_ID = in_del_ID;
9142         --
9143         -- begin bug 4914799 ctlee 12/30/2005 add p_dunning_plan_id
9144         CURSOR C_GET_SCORE (IN_ID NUMBER, IN_CODE VARCHAR2, p_dunning_plan_id number) IS
9145           SELECT a.score_value
9146             FROM IEX_SCORE_HISTORIES a
9147                  , IEX_DUNNING_PLANS_VL c  -- bug 4914799 ctlee 12/30/2005
9148            WHERE a.score_object_ID = in_ID
9149              AND a.score_object_code = IN_CODE
9150              and c.score_id = a.score_id   -- bug 4914799 ctlee 12/30/2005
9151              and c.dunning_plan_id = p_dunning_plan_id -- bug 4914799 ctlee 12/30/2005
9152              AND a.creation_date = (select max(b.creation_date)
9153                                       from iex_score_histories b
9154                                      where b.score_object_id = in_id
9155                                        AND b.score_object_code = IN_CODE);
9156         -- end bug 4914799 ctlee 12/30/2005 add p_dunning_plan_id
9157         --
9158         CURSOR C_GET_TEMPLATE (l_line_id NUMBER,
9159                                l_score NUMBER, in_LEVEL VARCHAR2, p_dunning_plan_id number) IS
9160           SELECT x.ag_dn_xref_id,
9161                  x.template_id,
9162                  x.xdo_template_id,
9163                  x.fm_method,
9164                  upper(x.callback_flag),
9165                  x.callback_days
9166             FROM IEX_AG_DN_XREF x,
9167                  ar_aging_buckets ar,
9168                  iex_dunning_plans_vl d
9169            WHERE x.aging_bucket_line_ID = l_line_ID
9170              and x.dunning_plan_id = p_dunning_plan_id
9171              AND l_score between x.score_range_low and x.score_range_high
9172              AND x.aging_bucket_id = ar.aging_bucket_id
9173              and ar.aging_bucket_id = d.aging_bucket_id
9174              AND ar.status = 'A'
9175              AND x.dunning_level = IN_LEVEL ;
9176 
9177          CURSOR C_TEMPLATE_STATUS (l_template_id number) is
9178          select 'Active'
9179          from xdo_templates_vl xdo
9180          where xdo.template_id = l_template_id
9181          and trunc(sysdate) >= TRUNC (NVL(xdo.start_date, sysdate))
9182          and trunc(sysdate) < TRUNC(NVL(xdo.end_date, sysdate + 1));
9183 
9184          l_template_status		  varchar2(10);
9185 
9186          CURSOR C_TEMPLATE_NAME (l_template_id number) is
9187          select template_name
9188          from xdo_templates_vl xdo
9189          where xdo.template_id = l_template_id;
9190 
9191         cursor c_dunning_plan_dtl (p_dunn_plan_id number) is
9192         select nvl(dunn.grace_days ,'N'),
9193                nvl(dunn.dun_disputed_items, 'N')
9194         from iex_dunning_plans_b dunn
9195         where dunning_plan_id = p_dunn_plan_id;
9196 
9197         cursor c_as_of_date  (p_dunning_id number) is
9198         select  nvl(dunn.as_of_date,sysdate)
9199         from iex_dunnings dunn
9200         where dunning_id = p_dunning_id;
9201 
9202         cursor c_cust_acct_amt_due_rem(p_party_id number,p_org_id number, p_corr_date date, p_grace_days number, p_include_dis_items varchar) is
9203         select nvl(sum(aps.acctd_amount_due_remaining),0)
9204            from ar_payment_schedules_all aps,iex_delinquencies_all dd,hz_cust_accounts hzca
9205            where dd.payment_schedule_id = aps.payment_schedule_id
9206            and aps.class IN ('INV', 'GUAR', 'CB', 'DM', 'DEP')
9207            and aps.status='OP'
9208            and (trunc(aps.due_date) + p_grace_days) <= p_corr_date
9209            and nvl(aps.amount_in_dispute,0) = decode(p_include_dis_items, 'Y', nvl(aps.amount_in_dispute,0), 0)
9210            and aps.amount_due_remaining > 0
9211            and aps.customer_id=hzca.cust_account_id
9212            and aps.org_id=p_org_id
9213            and hzca.party_id = p_party_id;
9214 
9215          cursor c_cust_acct_cm_tot_amt_rem (p_party_id number,p_org_id number) is
9216            select nvl(sum(acctd_amount_due_remaining),0)
9217            from  ar_payment_schedules_all aps,hz_cust_accounts hzca
9218            where aps.class IN ('CM','PMT')
9219            and   aps.status = 'OP'
9220            and   aps.customer_id = hzca.cust_account_id
9221            and   aps.org_id= p_org_id
9222            and   hzca.party_id = p_party_id;
9223 
9224          l_template_name	varchar2(500);
9225         --
9226 
9227         l_DUNNING_id            NUMBER;
9228         l_delinquency_id        NUMBER;
9229         l_party_cust_id         NUMBER;
9230         l_account_id            NUMBER;
9231         l_customer_site_use_id  NUMBER;
9232         l_noskip                NUMBER := 0;
9233         l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
9234         l_DUNNING_tbl           IEX_DUNNING_PUB.DUNNING_TBL_TYPE;
9235         l_score                 NUMBER;
9236         l_bucket_line_id        NUMBER;
9237         l_campaign_sched_id     NUMBER;
9238         l_template_id           NUMBER;
9239         l_xdo_template_id       NUMBER;
9240         l_method                VARCHAR2(10);
9241         l_callback_flag         VARCHAR2(1);
9242         l_callback_days         NUMBER;
9243         l_callback_date         DATE;
9244         l_request_id            NUMBER;
9245         l_outcome_code          varchar2(20);
9246         l_api_name              CONSTANT VARCHAR2(30) := 'Resend_Level_Dunning';
9247         l_api_version_number    CONSTANT NUMBER   := 1.0;
9248         l_return_status         VARCHAR2(1);
9249         l_msg_count             NUMBER;
9250         l_msg_data              VARCHAR2(32767);
9251         errmsg                  VARCHAR2(32767);
9252         --
9253         nIdx                    NUMBER := 0;
9254         TYPE Del_ID_TBL_type is Table of IEX_DELINQUENCIES_ALL.DELINQUENCY_ID%TYPE
9255                                 INDEX BY BINARY_INTEGER;
9256         Del_Tbl                 Del_ID_TBL_TYPE;
9257         l_bind_tbl              IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
9258         l_bind_rec              IEX_DUNNING_PVT.FULFILLMENT_BIND_REC;
9259         l_org_id                NUMBER ;
9260         l_running_level         VARCHAR2(25);
9261         l_object_Code           VARCHAR2(25);
9262         l_object_id             NUMBER;
9263         --l_delid_tbl             IEX_DUNNING_PUB.DelId_NumList;
9264         l_del_tbl               IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE;
9265         l_curr_code             VARCHAR2(15);
9266         l_amount                NUMBER;
9267         l_write                 NUMBER;
9268         l_ffm_cnt               NUMBER := 0;
9269         l_dunn_cnt              NUMBER := 0;
9270         l_curr_dmethod          VARCHAR2(10);
9271 
9272         l_delinquency_id_check        NUMBER;
9273         l_party_cust_id_check         NUMBER;
9274         l_account_id_check            NUMBER;
9275         l_customer_site_use_id_check  NUMBER;
9276         l_contact_destination         varchar2(240);  -- bug 3955222
9277         l_contact_party_id            number; -- bug 3955222
9278         --Start adding for bug 9156833 gnramasa 27th Nov 09
9279         l_validation_level		  NUMBER ;
9280         l_resource_tab		  iex_utilities.resource_tab_type;
9281         l_resource_id		  NUMBER;
9282         --End adding for bug 9156833 gnramasa 27th Nov 09
9283         l_grace_days                  number := 0;
9284         l_use_grace_days              varchar2(10);
9285         l_dun_disputed_items          varchar2(10);
9286         l_ag_dn_xref_id		  number;
9287         l_as_of_date                   date;
9288         Type refCur             is Ref Cursor;
9289         sql_cur                 refCur;
9290         sql_cur1                refCur;
9291         sql_cur2                refCur;
9292         sql_cur3                refCur;
9293         vPLSQL                  VARCHAR2(4000);
9294         vPLSQL1                 VARCHAR2(4000);
9295         vPLSQL2                 VARCHAR2(4000);
9296         vPLSQL3                 VARCHAR2(4000);
9297         l_acc_dunning_trx_null_dun_ct number;
9298         l_skip_this_dunn_planlineid   number;
9299         l_first_satified_dunnplanid   number;
9300 
9301         l_inv_curr			  varchar2(20);
9302         l_amt_due_remaining		  number;
9303         l_transaction_id              number;
9304         l_payment_schedule_id         number;
9305         l_include_current             varchar2(1);
9306         l_total_amount_due_remaining  number;
9307         l_cust_acct_cm_tot_amt_rem number;
9308 
9309     BEGIN
9310           -- Standard Start of API savepoint
9311           SAVEPOINT Resend_Level_DUNNING_PVT;
9312 
9313           --Bug#4679639 schekuri 20-OCT-2005
9314           --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
9315           l_org_id:= mo_global.get_current_org_id;
9316 
9317           -- Standard call to check for call compatibility.
9318           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
9319                                                p_api_version,
9320                                                l_api_name,
9321                                                G_PKG_NAME)
9322           THEN
9323               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
9324           END IF;
9325 
9326           -- Initialize message list if p_init_msg_list is set to TRUE.
9327           IF FND_API.to_Boolean( p_init_msg_list )
9328           THEN
9329               FND_MSG_PUB.initialize;
9330           END IF;
9331 
9332           -- don't write into FILE
9333           l_write := 0;
9334 
9335           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
9336           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - running_level='||p_running_level);
9337 
9338           -- Initialize API return status to SUCCESS
9339           x_return_status := FND_API.G_RET_STS_SUCCESS;
9340 
9341           --
9342           -- Api body
9343           --
9344 
9345           l_party_cust_id := p_delinquencies_tbl(1).party_cust_id;
9346           l_account_id := p_delinquencies_tbl(1).cust_account_id;
9347           l_customer_site_use_id := p_delinquencies_tbl(1).customer_site_use_id;
9348 
9349           if (p_running_level = 'CUSTOMER') then
9350               l_object_Code := 'PARTY';
9351               l_object_id := p_delinquencies_tbl(1).party_cust_id;
9352               l_del_tbl(1).party_cust_id := p_delinquencies_tbl(1).party_cust_id;
9353               l_amount := party_amount_due_remaining(l_object_id);
9354               l_curr_code := party_currency_code(l_object_id);
9355           --
9356           elsif (p_running_level = 'ACCOUNT') then
9357               l_object_Code := 'IEX_ACCOUNT';
9358               l_object_id := p_delinquencies_tbl(1).cust_account_id;
9359               l_del_tbl(1).cust_account_id := p_delinquencies_tbl(1).cust_account_id;
9360               l_amount := acct_amount_due_remaining(l_object_id);
9361               l_curr_code := acct_currency_code(l_object_id);
9362           --
9363           elsif (p_running_level = 'BILL_TO') then
9364               l_object_Code := 'IEX_BILLTO';
9365               l_object_id := p_delinquencies_tbl(1).customer_site_use_id;
9366               l_del_tbl(1).customer_site_use_id := p_delinquencies_tbl(1).customer_site_use_id;
9367               l_amount := site_amount_due_remaining(l_object_id);
9368               l_curr_code := site_currency_code(l_object_id);
9369           end if;
9370 
9371           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_code='||l_object_code);
9372           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id='||l_object_id);
9373           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id='||l_party_cust_id);
9374           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount_due_remaining='||l_amount);
9375           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - currency_code='||l_curr_code);
9376 
9377           /*==================================================================
9378            * l_noskip is used to trace the del data is all disputed or not;
9379            * if any one del not disputed, then l_noskip=1;
9380            * if l_noskip=0, then means all del are disputed,
9381            *    => for this customer/account, skip it;
9382            *==================================================================*/
9383           l_noskip := 0;
9384 
9385           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delcnt='||p_delinquencies_tbl.count);
9386 
9387             FOR i in 1..p_delinquencies_tbl.count
9388             LOOP
9389 
9390               l_delinquency_id := p_delinquencies_tbl(i).delinquency_id;
9391 
9392              /*=============================================================
9393               *  For each Delinquency,
9394               *=============================================================*/
9395 
9396               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - open del='||l_delinquency_Id);
9397 
9398              /*=============================================================
9399               * IsDispute ?
9400               * If yes => stop (exit);
9401               * else continue;
9402               *
9403               * it returns values :
9404               * 1) it returns 'F' if no dispute exists for the delinquency
9405               * 2) it returns 'T' if dispute exists and is pending
9406               * 3) it returns 'F' if dispute exists and its staus is "COMPLETE"
9407               *===========================================================*/
9408 
9409               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ResendLevelDunn:Chk IsDispute');
9410 
9411                IEX_DISPUTE_PVT.Is_Delinquency_Dispute(p_api_version              => p_api_version
9412     					   , p_init_msg_list            => p_init_msg_list
9413     					   , p_delinquency_id           => l_delinquency_id
9414     					   , x_return_status            => x_return_status
9415     					   , x_msg_count                => x_msg_count
9416     					   , x_msg_data                 => x_msg_data);
9417 
9418                IF x_return_status = 'T' THEN
9419                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Dispute exists and is pending for del '|| l_delinquency_id);
9420                  GOTO end_del;
9421                elsif x_return_status = 'F' THEN
9422                   -- if one del is not disputed, then l_noskip=1;
9423                   l_noskip := 1;
9424                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Dispute or status is COMPLETE');
9425                END IF;
9426 
9427                nIdx := nIdx + 1;
9428                del_tbl(nIdx) := l_delinquency_id; --in order to update del)
9429 
9430               <<end_del>>
9431               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close C_GET_DEL');
9432 
9433            END LOOP; -- end of DELINQUENCIES_TBL loop
9434            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END LOOP');
9435 
9436           IF (l_noskip > 0) THEN
9437 
9438              -- init the msg (not including the msg from dispute api)
9439              FND_MSG_PUB.initialize;
9440 
9441               /*===========================================
9442                * Get Score From IEX_SCORE_HISTORIES
9443                * If NotFound => Call API to getScore;
9444                *===========================================*/
9445                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get Score');
9446                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - objectCode='||l_object_Code);
9447 
9448                Open C_Get_SCORE(l_object_id, l_object_Code, p_dunning_plan_id);
9449                Fetch C_Get_SCORE into l_score;
9450 
9451                If ( C_GET_SCORE%NOTFOUND) Then
9452                     --FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
9453                     --FND_MESSAGE.Set_Token ('INFO', 'Score', FALSE);
9454                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_SCORE');
9455                     FND_MSG_PUB.Add;
9456                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Score NotFound');
9457                     Close C_Get_SCORE;
9458                     x_return_status := FND_API.G_RET_STS_ERROR;
9459                     GOTO end_api;
9460                END IF;
9461 
9462                --WriteLog('iexvdunb:ResendLevelDunn:CLOSE C_GET_SCORE', l_write);
9463                Close C_Get_SCORE;
9464 
9465                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get Score='||l_score);
9466 
9467               /*===================================================
9468                * in 11.5.11, support aging bucket line for all level;
9469                * clchang added 11/20/04.
9470                * Get Aging_Bucket_Line_id for each party/acct/site
9471                *===================================================*/
9472 
9473                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetAgingBucketLineId');
9474 
9475                AGING_DEL(p_api_version              => p_api_version
9476     		                , p_init_msg_list            => p_init_msg_list
9477     		                , p_commit                   => p_commit
9478     		                , p_delinquency_id           => null
9479     		                , p_dunning_plan_id          => p_dunning_plan_id
9480     		                , p_bucket                   => null
9481     		                , p_object_code              => l_object_code
9482     		                , p_object_id                => l_object_id
9483     		                , x_return_status            => x_return_status
9484     		                , x_msg_count                => x_msg_count
9485     		                , x_msg_data                 => x_msg_data
9486     		                , x_aging_bucket_line_id     => l_bucket_line_id);
9487 
9488                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - AgingDel status='||x_return_status);
9489 
9490                If ( x_return_status <> FND_API.G_RET_STS_SUCCESS) Then
9491                     --FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
9492                     --FND_MESSAGE.Set_Token ('INFO', 'AgingBucketLineId', FALSE);
9493                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_AGINGBUCKETLINE');
9494                     FND_MSG_PUB.Add;
9495                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - AgingBucketLineId notfound');
9496                     x_return_status := FND_API.G_RET_STS_ERROR;
9497                     GOTO end_api;
9498                END IF;
9499 
9500                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - lineid='||l_bucket_line_id);
9501 
9502               /*===========================================
9503                * Get Template_ID From iex_ag_dn_xref
9504                *===========================================*/
9505 
9506                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template');
9507 
9508                Open C_Get_TEMPLATE(l_bucket_line_id, l_score, p_running_level, p_dunning_plan_id);
9509                Fetch C_Get_TEMPLATE into
9510     	      		       l_ag_dn_xref_id,
9511                            l_template_id,
9512                            l_xdo_template_id,
9513                            l_method,
9514                            l_callback_flag,
9515                            l_callback_days;
9516 
9517                If ( C_GET_TEMPLATE%NOTFOUND) Then
9518                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
9519                     FND_MSG_PUB.Add;
9520                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template notfound');
9521                     x_return_status := FND_API.G_RET_STS_ERROR;
9522                     GOTO end_api;
9523                END IF;
9524 
9525                Close C_Get_TEMPLATE;
9526 
9527                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get template_id='||l_template_id);
9528                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get xdo_template_id='||l_xdo_template_id, l_write);
9529 
9530     	   /*===========================================
9531                * Check the status of the template
9532                *===========================================*/
9533 
9534                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template status');
9535                Open C_TEMPLATE_STATUS(l_xdo_template_id);
9536                Fetch C_TEMPLATE_STATUS into l_template_status;
9537 
9538                If ( C_TEMPLATE_STATUS%NOTFOUND) Then
9539 
9540     		open C_TEMPLATE_NAME (l_xdo_template_id);
9541     		Fetch C_TEMPLATE_NAME into l_template_name;
9542     		close C_TEMPLATE_NAME;
9543 
9544     		FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
9545                     FND_MSG_PUB.Add;
9546                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
9547     	        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
9548     	        RAISE FND_API.G_EXC_ERROR;
9549     	   END IF;
9550                Close C_TEMPLATE_STATUS;
9551     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
9552 
9553               /*===========================================
9554                * Check template
9555                *  in 11.5.11, IEX supports fulfillment and xml publisher.
9556                *  if the current setup for delivery id FFM,
9557                *  then template_id is necessary;
9558                *  if XML, xdo_template_id is necessary;
9559                *===========================================*/
9560 
9561                l_curr_dmethod := IEX_SEND_XML_PVT.getCurrDeliveryMethod;
9562                WriteLog('iexvdunb:ResendLevelDunn:curr d_method='||l_curr_dmethod);
9563                if ( (l_curr_dmethod is null or l_curr_dmethod = '') or
9564                     (l_curr_dmethod = 'FFM' and l_template_id is null)  or
9565                     (l_curr_dmethod = 'XML' and l_xdo_template_id is null ) ) then
9566                     --FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
9567                     --FND_MESSAGE.Set_Token ('INFO', 'Template_ID', FALSE);
9568                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
9569                     FND_MSG_PUB.Add;
9570                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template notfound');
9571                     x_return_status := FND_API.G_RET_STS_ERROR;
9572                     GOTO end_api;
9573                end if;
9574 
9575     	   open c_dunning_plan_dtl (p_dunning_plan_id);
9576     		 fetch c_dunning_plan_dtl into l_use_grace_days, l_dun_disputed_items;
9577     		 close c_dunning_plan_dtl;
9578     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_use_grace_days :'|| l_use_grace_days);
9579     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_dun_disputed_items :'|| l_dun_disputed_items);
9580 
9581     		 if l_use_grace_days = 'Y' then
9582     			 iex_utilities.get_grace_days(p_api_version => p_api_version,
9583     					       p_init_msg_list     => FND_API.G_TRUE,
9584     					       p_commit            => FND_API.G_FALSE,
9585     					       p_validation_level  => l_validation_level,
9586     					       p_level             => p_running_level,
9587     					       p_party_id          => l_party_cust_id,
9588     					       p_account_id        => l_account_id,
9589     					       p_site_use_id       => l_customer_site_use_id,
9590     					       x_msg_count         => l_msg_count,
9591     					       x_msg_data          => l_msg_data,
9592     					       x_return_status     => l_return_status,
9593     					       x_grace_days        => l_grace_days);
9594     			 IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
9595     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get grace days');
9596     			     x_return_status := FND_API.G_RET_STS_ERROR;
9597     			 END IF;
9598     		 end if;
9599     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_grace_days :'|| l_grace_days);
9600 
9601               /*===========================================
9602                * Check profile before send dunning
9603                *===========================================*/
9604 
9605                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - begin check customer profile');
9606                 -- ctlee - check the hz_customer_profiles.dunning_letter
9607                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_party_cust_id = ' || l_party_cust_id);
9608                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_account_id = ' || l_account_id);
9609                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_customer_site_use_id = ' || l_customer_site_use_id);
9610                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_delinquency_id = ' || l_delinquency_id);
9611                 -- ctlee - check the hz_customer_profiles.dunning_letter
9612                 l_party_cust_id_check := l_party_cust_id;
9613                 l_account_id_check := l_account_id;
9614                 l_customer_site_use_id_check := l_customer_site_use_id;
9615                 l_delinquency_id_check := l_delinquency_id;
9616                if (p_running_level = 'CUSTOMER') then
9617                   l_account_id_check := null;
9618                   l_customer_site_use_id_check := null;
9619                   l_delinquency_id_check := null;
9620                elsif  (p_running_level = 'ACCOUNT') then
9621                   l_customer_site_use_id_check := null;
9622                   l_delinquency_id_check := null;
9623                elsif  (p_running_level = 'BILL_TO') then
9624                   l_delinquency_id_check := null;
9625                end if;
9626 
9627     	    open c_as_of_date (p_dunning_id);
9628     	    fetch c_as_of_date into l_as_of_date;
9629     	    close c_as_of_date;
9630                   WriteLog('iexvdunb:ResendLevelDunn: l_as_of_date : '||l_as_of_date);
9631                if ( iex_utilities.DunningProfileCheck (
9632                        p_party_id => l_party_cust_id_check
9633                        , p_cust_account_id => l_account_id_check
9634                        , p_site_use_id => l_customer_site_use_id_check
9635                        , p_delinquency_id => l_delinquency_id_check     ) = 'N'
9636                   ) then
9637                     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_PROFILE_NO');
9638                     FND_MSG_PUB.Add;
9639                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send dunning in customer profile set to no ');
9640                     x_return_status := FND_API.G_RET_STS_ERROR;
9641                     GOTO end_api;
9642                end if;
9643 
9644              /*if (p_running_level <> 'CUSTOMER') then
9645                -- ctlee - check the hz_customer_profiles_amt min_dunning_invoice_amount and min_dunning_amount
9646                if ( iex_utilities.DunningMinAmountCheck (
9647                           p_cust_account_id => l_account_id_check
9648                         , p_site_use_id => l_customer_site_use_id_check
9649                         , p_delinquency_id => l_delinquency_id_check
9650                  )  = 'N' --Added for Bug 10401991 20-Jan-2011 barathsr
9651                   ) then*/
9652                   -- start bug 15933013
9653               if (p_running_level <> 'CUSTOMER') then
9654                       if ( iex_utilities.DunningMinAmountCheck (
9655                           p_cust_account_id => l_account_id
9656                         , p_site_use_id => l_customer_site_use_id
9657                         , p_delinquency_id => l_delinquency_id
9658                         , p_org_id => l_org_id
9659                         , p_grace_days => l_grace_days
9660     		                , p_dun_disputed_items => l_dun_disputed_items
9661     		                , p_correspondence_date => l_as_of_date
9662     		                , p_running_level=> p_running_level
9663     		                 )  <> 'Y'
9664                   ) then -- end bug 15933013
9665                     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
9666                     FND_MSG_PUB.Add;
9667                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Required min Dunning amount in customer profile ');
9668     	              x_return_status := FND_API.G_RET_STS_ERROR;
9669                     GOTO end_api;
9670                end if;
9671                else
9672     	     open c_cust_acct_amt_due_rem(l_object_id,l_org_id,l_as_of_date, l_grace_days,l_dun_disputed_items);
9673     	     Fetch c_cust_acct_amt_due_rem into l_amt_due_remaining;
9674     	     close c_cust_acct_amt_due_rem;
9675 
9676     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Accounted Amount due remaining at customer level ' || l_amt_due_remaining);
9677 
9678                  open  c_cust_acct_cm_tot_amt_rem(l_object_id,l_org_id);
9679     	     Fetch c_cust_acct_cm_tot_amt_rem into l_cust_acct_cm_tot_amt_rem;
9680     	     close c_cust_acct_cm_tot_amt_rem;
9681 
9682     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  cm/ar Amount due remaining at customer level ' || l_cust_acct_cm_tot_amt_rem);
9683 
9684                   l_total_amount_due_remaining :=   l_amt_due_remaining + l_cust_acct_cm_tot_amt_rem; --(l_cust_acct_cm_tot_amt_rem is -ve value so using + sign)
9685                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  final Amount due remaining at customer level ' || l_total_amount_due_remaining);
9686 
9687     		     if l_total_amount_due_remaining <= 0 then
9688     			     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
9689     			     FND_MSG_PUB.Add;
9690     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Amount due remaining is less than 0 ');
9691     			     FND_FILE.PUT_LINE(FND_FILE.LOG, ' Amount due remaining is less than 0 ');
9692     			     x_return_status := FND_API.G_RET_STS_ERROR;
9693     			     GOTO end_api;
9694     		     end if;
9695 
9696                end if;
9697              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  end check customer profile');
9698 
9699     	 --If dunning mode is draft then don't close the previous duning records.
9700              vPLSQL1 := 'select count(*) from ( ' ||
9701     							'    select del.delinquency_id, ' ||
9702     							'	   del.transaction_id, ' ||
9703     							'	   del.payment_schedule_id  ' ||
9704     							'    from iex_delinquencies del, ' ||
9705     							'	 ar_payment_schedules arp ' ||
9706     							'    where del.payment_schedule_id = arp.payment_schedule_id ' ||
9707     							'    and del.status in (''DELINQUENT'',''PREDELINQUENT'') ' ||
9708     							'    and (trunc(arp.due_date) + :p_grace_days) <= :p_corr_date ' ||
9709     							'    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ';
9710 
9711     					if l_include_current = 'y' then
9712     					vPLSQL2 := '    union all ' || --Added for Bug 10401991 07-Feb-2011 barathsr
9713     						   'select null, arp.customer_trx_id, ' ||
9714     						   'arp.payment_schedule_id ' ||
9715     				                   'from ar_payment_schedules arp, ' ||
9716     					           'hz_cust_accounts hca ' ||
9717     				                   'where arp.customer_id = hca.cust_account_id ' ||
9718     				                   'and hca.party_id = :p_party_id ' ||
9719     				                   'and arp.status = ''OP'' ' ||
9720     				                   'and arp.amount_due_remaining <> 0 ' ||--'    and arp.amount_due_remaining > 0 ' || Changed to fix 12552027 by snuthala 5/19/2011
9721     						   'and arp.class = ''INV'' ' ||
9722     				                   'and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
9723                                      		   'and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'' ) ' ;
9724                                            else
9725     				       vPLSQL2 := ' ';
9726     				       end if;
9727     					if (p_running_level = 'CUSTOMER') then
9728     					      vPLSQL3		:= vPLSQL1 || '    and del.party_cust_id = :p_party_id ' || vPLSQL2 ||
9729     								   '    and del.party_cust_id = :p_party_id )';
9730     					elsif  (p_running_level = 'ACCOUNT') then
9731     					      vPLSQL3		:= vPLSQL1 || '    and del.cust_account_id = :p_cust_acct_id ' ||
9732     					                           --Begin Bug 10401991 03-feb-2011 barathsr
9733     					                           '    and arp.amount_due_remaining >= NVL ( '||
9734     								   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
9735     								   '	FROM hz_cust_profile_amts '||
9736     								   '	WHERE site_use_id  IS NULL '||
9737     								   '	AND cust_account_id = arp.customer_id '||
9738     								   '	AND currency_code   = arp.invoice_currency_code),0) '||
9739     								   vPLSQL2 ||
9740     								   '    and del.cust_account_id = :p_cust_acct_id '||
9741     								   '    and arp.amount_due_remaining >= NVL ( '||
9742     								   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
9743     								   '	FROM hz_cust_profile_amts '||
9744     								   '	WHERE site_use_id  IS NULL '||
9745     								   '	AND cust_account_id = arp.customer_id '||
9746     								   '	AND currency_code   = arp.invoice_currency_code),0))';
9747     					elsif  (p_running_level = 'BILL_TO') then
9748     					      vPLSQL3		:= vPLSQL1 || '    and del.customer_site_use_id = :p_site_use_id ' ||
9749     					                           '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
9750     								   '	from hz_cust_profile_amts '||
9751     								   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
9752     								   '	and currency_code = arp.invoice_currency_code),0) ' ||
9753     								   vPLSQL2 ||
9754     								   '    and del.customer_site_use_id = :p_site_use_id ' ||
9755     								   '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
9756     								   '	from hz_cust_profile_amts '||
9757     								   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
9758     								   '	and currency_code = arp.invoice_currency_code),0))';
9759     					end if;                 --End Bug 10401991 03-feb-2011 barathsr
9760     					WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - vPLSQL3 :'||vPLSQL3);
9761     					 if l_include_current = 'y' then
9762     					                       open sql_cur3 for vPLSQL3 using
9763     								    l_grace_days,
9764     								    l_as_of_date,
9765     								    l_dun_disputed_items,
9766     								    l_object_id,
9767     	                                                            l_grace_days,
9768     								    l_as_of_date,
9769     								    l_dun_disputed_items,
9770     								    l_object_id;
9771 
9772     				           else
9773     								     open sql_cur3 for vPLSQL3 using
9774     								    l_grace_days,
9775     								    l_as_of_date,
9776     								    l_dun_disputed_items,
9777     								    l_object_id,
9778     	                                                            l_object_id;
9779     					 end if;
9780     					fetch sql_cur3 into l_acc_dunning_trx_null_dun_ct;
9781     					close sql_cur3;
9782 
9783     					WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_acc_dunning_trx_null_dun_ct :'||l_acc_dunning_trx_null_dun_ct);
9784     					if l_acc_dunning_trx_null_dun_ct <> 0 then
9785     						WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Transaction exist , so will continue...');
9786     						l_skip_this_dunn_planlineid := 0;
9787     						if l_first_satified_dunnplanid is null then
9788     							l_first_satified_dunnplanid := 1;
9789 
9790     						else
9791     							l_first_satified_dunnplanid := 0;
9792     						end if;
9793     						 else
9794     						 GOTO END_API;
9795     					 end if;
9796 
9797                WriteLog('iexvdunb:ResendLevelDunn: end check customer profile');
9798 
9799               /*===========================================
9800                * Send Letter through Fulfillment
9801                *===========================================*/
9802 
9803                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND_FFM');
9804                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org_id='||l_org_id);
9805                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id='||l_party_cust_id);
9806                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - method='||l_method);
9807 
9808                l_bind_rec.key_name := 'party_id';
9809                l_bind_rec.key_type := 'NUMBER';
9810                l_bind_rec.key_value := l_party_cust_id;
9811                l_bind_tbl(1) := l_bind_rec;
9812     	   --Begin Bug 10401991 20-Jan-2011 barathsr
9813                l_bind_rec.key_name := 'org_id';
9814                l_bind_rec.key_type := 'NUMBER';
9815                l_bind_rec.key_value := l_org_id;
9816     	   --End Bug 10401991 20-Jan-2011 barathsr
9817                l_bind_tbl(2) := l_bind_rec;
9818                l_bind_rec.key_name := 'account_id';
9819                l_bind_rec.key_type := 'NUMBER';
9820                l_bind_rec.key_value := l_account_id;
9821                l_bind_tbl(3) := l_bind_rec;
9822                -- added for new level 'BILL_TO' since 11.5.10.
9823                l_bind_rec.key_name := 'customer_site_use_id';
9824                l_bind_rec.key_type := 'NUMBER';
9825                l_bind_rec.key_value := l_customer_site_use_id;
9826                l_bind_tbl(4) := l_bind_rec;
9827     	  	   l_bind_rec.key_name := 'DUNNING_ID';
9828                l_bind_rec.key_type := 'NUMBER';
9829     	       l_bind_rec.key_value := p_dunning_id;
9830                l_bind_tbl(5) := l_bind_rec;
9831 
9832     	   --Start adding for bug 9156833 gnramasa 27th Nov 09
9833     	 l_validation_level := FND_API.G_VALID_LEVEL_FULL;
9834 
9835     	 if (p_running_level = 'BILL_TO') then
9836     		iex_utilities.get_dunning_resource(p_api_version => p_api_version,
9837     				       p_init_msg_list     => FND_API.G_TRUE,
9838     				       p_commit            => FND_API.G_FALSE,
9839     				       p_validation_level  => l_validation_level,
9840     				       p_level             => 'DUNNING_BILLTO',
9841     				       p_level_id          => l_customer_site_use_id,
9842     				       x_msg_count         => l_msg_count,
9843     				       x_msg_data          => l_msg_data,
9844     				       x_return_status     => l_return_status,
9845     				       x_resource_tab      => l_resource_tab);
9846     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
9847     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
9848     		     x_return_status := FND_API.G_RET_STS_ERROR;
9849     		     GOTO end_get_resource;
9850     		END IF;
9851     	  end if;
9852 
9853     	  if l_resource_tab.count<1 and (p_running_level = 'ACCOUNT') then
9854     		  iex_utilities.get_dunning_resource(p_api_version => p_api_version,
9855     				       p_init_msg_list     => FND_API.G_TRUE,
9856     				       p_commit            => FND_API.G_FALSE,
9857     				       p_validation_level  => l_validation_level,
9858     				       p_level             => 'DUNNING_ACCOUNT',
9859     				       p_level_id          => l_account_id,
9860     				       x_msg_count         => l_msg_count,
9861     				       x_msg_data          => l_msg_data,
9862     				       x_return_status     => l_return_status,
9863     				       x_resource_tab      => l_resource_tab);
9864     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
9865     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
9866     		     x_return_status := FND_API.G_RET_STS_ERROR;
9867     		     GOTO end_get_resource;
9868     		END IF;
9869     	  end if;
9870 
9871     	  if l_resource_tab.count<1 and (p_running_level = 'CUSTOMER') then
9872     		iex_utilities.get_dunning_resource(p_api_version => p_api_version,
9873     				       p_init_msg_list     => FND_API.G_TRUE,
9874     				       p_commit            => FND_API.G_FALSE,
9875     				       p_validation_level  => l_validation_level,
9876     				       p_level             => 'DUNNING_PARTY',
9877     				       p_level_id          => l_party_cust_id,
9878     				       x_msg_count         => l_msg_count,
9879     				       x_msg_data          => l_msg_data,
9880     				       x_return_status     => l_return_status,
9881     				       x_resource_tab      => l_resource_tab);
9882     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
9883     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
9884     		     x_return_status := FND_API.G_RET_STS_ERROR;
9885     		     GOTO end_get_resource;
9886     		END IF;
9887 
9888     		if l_resource_tab.count<1 and (p_running_level = 'CUSTOMER') then
9889     			iex_utilities.get_dunning_resource(p_api_version => p_api_version,
9890     						         p_init_msg_list     => FND_API.G_TRUE,
9891     							 p_commit            => FND_API.G_FALSE,
9892     							 p_validation_level  => l_validation_level,
9893     							 p_level             => 'DUNNING_PARTY_ACCOUNT',
9894     							 p_level_id          => l_party_cust_id,
9895     							 x_msg_count         => l_msg_count,
9896     							 x_msg_data          => l_msg_data,
9897     							 x_return_status     => l_return_status,
9898     							 x_resource_tab      => l_resource_tab);
9899     			IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
9900     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
9901     			     x_return_status := FND_API.G_RET_STS_ERROR;
9902     			     GOTO end_get_resource;
9903     			END IF;
9904     		end if;
9905     	  end if;
9906 
9907     	  <<end_get_resource>>
9908     	  if l_resource_tab.count>0 then
9909     	    l_resource_id := l_resource_tab(1).resource_id;
9910     	  end if;
9911     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_resource_id: ' || l_resource_id);
9912     	  --End adding for bug 9156833 gnramasa 27th Nov 09
9913               WriteLog(' before send_xml org_id ' || p_org_id);
9914              /**
9915               * in 11.5.11, IEX supports fulfillment and xml publisher.
9916               * it depends on the set up in IEX ADMIN/SETUP.
9917               */
9918               if (l_curr_dmethod = 'FFM') then
9919 
9920                Send_Fulfillment(
9921                        p_api_version              => p_api_version
9922                      , p_init_msg_list            => p_init_msg_list
9923                      , p_commit                   => p_commit
9924                      , p_fulfillment_bind_tbl     => l_bind_tbl
9925                      , p_template_id              => l_template_id
9926                      , p_method                   => l_method
9927                      , p_party_id                 => l_party_cust_id
9928                      , x_request_id               => l_request_id
9929                      , x_return_status            => x_return_status
9930                      , x_msg_count                => x_msg_count
9931                      , x_msg_data                 => x_msg_data
9932                      , x_contact_destination      => l_contact_destination  -- bug 3955222
9933                      , x_contact_party_id         => l_contact_party_id  -- bug 3955222
9934                      );
9935               else
9936 
9937                Send_XML(
9938                        p_api_version              => p_api_version
9939                        , p_init_msg_list            => p_init_msg_list
9940                        , p_commit                   => FND_API.G_FALSE  --p_commit --bug 8567312
9941                        , p_resend                   => 'N'
9942                        , p_request_id               => null
9943                        , p_fulfillment_bind_tbl     => l_bind_tbl
9944                        , p_template_id              => l_xdo_template_id
9945                        , p_method                   => l_method
9946                        , p_party_id                 => l_party_cust_id
9947                        , p_level                    => p_running_level
9948                        , p_source_id                => l_object_id
9949                        , p_object_code              => l_object_code
9950                        , p_object_id                => l_object_id
9951     		   , p_resource_id              => l_resource_id --Added for bug 9156833 gnramasa 27th Nov 09
9952                        , p_org_id                   => p_org_id      -- added for bug 9151851
9953     		   , x_request_id               => l_request_id
9954                        , x_return_status            => x_return_status
9955                        , x_msg_count                => x_msg_count
9956                        , x_msg_data                 => x_msg_data
9957                        , x_contact_destination      => l_contact_destination  -- bug 3955222
9958                        , x_contact_party_id         => l_contact_party_id  -- bug 3955222
9959                        );
9960 
9961               end if;
9962 
9963               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND status='|| x_return_status);
9964 
9965                IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
9966                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Sending Letters', l_write);
9967                   x_return_status := FND_API.G_RET_STS_ERROR;
9968                   GOTO end_api;
9969                END IF;
9970 
9971                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||l_request_id, l_write);
9972                l_ffm_cnt := l_ffm_cnt + 1;
9973 
9974               /*===========================================
9975                * Close OPEN Dunnings for each party/account
9976                *===========================================*/
9977 
9978                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning', l_write);
9979                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - runninglevel='||p_running_level, l_write);
9980                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - del cnt='||l_del_tbl.count, l_write);
9981                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyid='||l_del_tbl(1).party_cust_id, l_write);
9982                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - accntid='||l_del_tbl(1).cust_account_id, l_write);
9983                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - siteid='||l_del_tbl(1).customer_site_use_id, l_write);
9984 
9985                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallCloseDunning', l_write);
9986 
9987                  Close_DUNNING(p_api_version              => p_api_version
9988     				                 , p_init_msg_list            => p_init_msg_list
9989     				                 , p_commit                   => p_commit
9990     				                 , p_delinquencies_tbl        => l_del_tbl
9991     				                 , p_running_level            => p_running_level
9992     				                 , x_return_status            => x_return_status
9993     				                 , x_msg_count                => x_msg_count
9994     				                 , x_msg_data                 => x_msg_data);
9995 
9996                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning status='|| x_return_status, l_write);
9997 
9998                  IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
9999                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Close Dunning', l_write);
10000                     x_return_status := FND_API.G_RET_STS_ERROR;
10001                     GOTO end_api;
10002                  END IF;
10003                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndCloseDunn', l_write);
10004 
10005               /*===========================================
10006                * Create Dunning Record
10007                *===========================================*/
10008 
10009                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get CallbackDate', l_write);
10010                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag='||l_callback_flag, l_write);
10011                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDays='||l_callback_days, l_write);
10012 
10013                 /*===================================================
10014                  * clchang updated 02/13/2003
10015                  * callback_days could be null if callback_yn = 'N';
10016                  * and if callback_yn = 'N', not get callback_date;
10017                  *==================================================*/
10018                  IF (l_callback_flag = 'Y') THEN
10019 
10020                      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is Y: GetCallbackDate',l_write);
10021                      Get_Callback_Date( p_init_msg_list          => p_init_msg_list
10022                                 , p_callback_days          => l_callback_days
10023                                 , x_callback_date          => l_callback_date
10024                                 , x_return_status          => x_return_status
10025                                 , x_msg_count              => x_msg_count
10026                                 , x_msg_data               => x_msg_data);
10027 
10028                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetCallbackDate status='|| x_return_status, l_write);
10029 
10030                     IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
10031                       FND_MESSAGE.Set_Name('IEX', 'IEX_NO_CALLBACKDATE');
10032                       FND_MSG_PUB.Add;
10033                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Get CallbackDate', l_write);
10034                       x_return_status := FND_API.G_RET_STS_ERROR;
10035                       GOTO end_api;
10036                     END IF;
10037 
10038                  ELSE
10039                      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is N: NOTGetCallbackDate',l_write);
10040 
10041                  END IF;
10042 
10043                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDate='||l_callback_date, l_write);
10044                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningRec', l_write);
10045                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - objectid='||l_object_id, l_write);
10046                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - objecttype='||p_running_level, l_write);
10047                  l_dunning_rec.dunning_level := p_running_level;
10048                  l_dunning_rec.dunning_object_id := l_object_id;
10049                  l_dunning_rec.callback_yn := l_callback_flag;
10050                  l_dunning_rec.callback_date := l_callback_date;
10051                  l_dunning_rec.status := 'OPEN';
10052                  l_dunning_rec.dunning_method := l_method;
10053                  if (l_curr_dmethod = 'FFM') then
10054                    l_dunning_rec.template_id:= l_template_id;
10055                    l_dunning_rec.ffm_request_id := l_request_id;
10056                  else
10057                    l_dunning_rec.xml_template_id:= l_xdo_template_id;
10058                    l_dunning_rec.xml_request_id := l_request_id;
10059                  end if;
10060                  l_dunning_rec.amount_due_remaining := l_amount;
10061                  l_dunning_rec.currency_code := l_curr_code;
10062                  l_dunning_rec.object_type := l_object_code;
10063                  l_dunning_rec.object_id := l_object_id;
10064                  l_dunning_rec.dunning_plan_id := p_dunning_plan_id;
10065                  l_dunning_rec.contact_destination := l_contact_destination;  -- bug 3955222
10066                  l_dunning_rec.contact_party_id := l_contact_party_id;  -- bug 3955222
10067                  l_dunning_rec.org_id := p_org_id;
10068 
10069     	     l_dunning_rec.as_of_date := l_as_of_date;
10070     	     l_dunning_rec.parent_dunning_id := p_dunning_id;
10071     	     WriteLog(' before creating dunning org_id ' || p_org_id);
10072     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Insert Row', l_write);
10073 
10074                  CREATE_DUNNING(
10075                        p_api_version              => p_api_version
10076                      , p_init_msg_list            => p_init_msg_list
10077                      , p_commit                   => p_commit
10078                      , p_dunning_rec              => l_dunning_rec
10079                      , x_dunning_id               => l_dunning_id
10080                      , x_return_status            => x_return_status
10081                      , x_msg_count                => x_msg_count
10082                      , x_msg_data                 => x_msg_data);
10083 
10084                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| x_return_status, l_write);
10085 
10086                   IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
10087                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning', l_write);
10088                        x_return_status := FND_API.G_RET_STS_ERROR;
10089                        GOTO end_api;
10090     	     else
10091 
10092     		 INSERT_DUNNING_TRANSACTION(
10093     				p_api_version              => p_api_version
10094     			      , p_init_msg_list            => p_init_msg_list
10095     			      , p_commit                   => p_commit
10096     			      , p_delinquencies_tbl        => l_del_tbl
10097     			      , p_ag_dn_xref_id	           => l_ag_dn_xref_id
10098     			      , p_dunning_id               => l_dunning_id
10099     			      , p_correspondence_date      => l_as_of_date
10100     			      , p_running_level            => p_running_level
10101     			      , p_grace_days               => l_grace_days
10102     			      , p_include_dispute_items    => l_dun_disputed_items
10103     			      , x_return_status            => x_return_status
10104     			      , x_msg_count                => x_msg_count
10105     			      , x_msg_data                 => x_msg_data
10106                               ,p_workitem_id               => null);  -- bug 14772139
10107                   END IF;
10108 
10109                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningId='||l_dunning_id, l_write);
10110                   l_dunn_cnt := l_dunn_cnt + 1;
10111 
10112               /*===========================================
10113                * Update Delinquency
10114                * Set DUNN_YN = 'N'
10115                *===========================================*/
10116 
10117                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========Summary===========');
10118                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - For RunningLevel='||p_running_level);
10119                  --WriteLog('iexvdunb:ResendLevelDunn:Resend - UpdateDel', l_write);
10120                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Resend - object_id='||l_object_id, l_write);
10121 
10122                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SendFFM Cnt='|| l_ffm_cnt, l_write);
10123                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunn Cnt='|| l_dunn_cnt, l_write);
10124                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========End Summary===========');
10125 
10126                <<end_api>>
10127                if (x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
10128                    ROLLBACK TO Resend_Level_DUNNING_PVT;
10129                    FND_MSG_PUB.Count_And_Get
10130                    (  p_count          =>   x_msg_count,
10131                       p_data           =>   x_msg_data );
10132                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api:error on this party/accnt/site', l_write);
10133                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api:status='||x_return_status, l_write);
10134                    --Resend need return the exact status
10135                    --x_return_status := 'SKIP'; --FND_API.G_EXC_ERROR;
10136                end if;
10137                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api', l_write);
10138 
10139           ELSE -- l_noskip = 0
10140                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - all del disputed', l_write);
10141                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - skip this party/accnt/site', l_write);
10142                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api:status='||x_return_status, l_write);
10143                FND_MSG_PUB.Count_And_Get
10144                (  p_count          =>   x_msg_count,
10145                   p_data           =>   x_msg_data );
10146                --Resend need return the exact status
10147                --x_return_status := 'SKIP'; --FND_API.G_EXC_ERROR;
10148 
10149           end if; -- end of if (l_noskip>0)
10150           --
10151           -- End of API body
10152           --
10153 
10154           x_request_id := l_request_id;
10155           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||x_request_id, l_write);
10156           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - status='||x_return_status, l_write);
10157 
10158           -- Standard check for p_commit
10159           IF FND_API.to_Boolean( p_commit )
10160           THEN
10161               COMMIT WORK;
10162           END IF;
10163 
10164           WriteLog('iexvdunb:ResendLevelDunn:END', l_write);
10165 
10166           FND_MSG_PUB.Count_And_Get
10167           (  p_count          =>   x_msg_count,
10168              p_data           =>   x_msg_data );
10169 
10170           EXCEPTION
10171               WHEN FND_API.G_EXC_ERROR THEN
10172                   x_return_status := FND_API.G_RET_STS_ERROR;
10173                   FND_MSG_PUB.Count_And_Get
10174                   (  p_count          =>   x_msg_count,
10175                      p_data           =>   x_msg_data );
10176                   ROLLBACK TO Resend_Level_DUNNING_PVT;
10177                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM, l_write);
10178 
10179               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
10180                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
10181                   FND_MSG_PUB.Count_And_Get
10182                   (  p_count          =>   x_msg_count,
10183                      p_data           =>   x_msg_data );
10184                   ROLLBACK TO Resend_Level_DUNNING_PVT;
10185                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM, l_write);
10186 
10187               WHEN OTHERS THEN
10188                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
10189                   FND_MSG_PUB.Count_And_Get
10190                   (  p_count          =>   x_msg_count,
10191                      p_data           =>   x_msg_data );
10192                   ROLLBACK TO Resend_Level_DUNNING_PVT;
10193                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM, l_write);
10194 
10195     END Resend_Level_Dunning;
10196 
10197     /*=========================================================================
10198        gnramasa added 12th Jan 2010 -
10199          Resend_Level_Staged_Dunning and Resend_Staged_Dunning are called by FORM,
10200          and just for resend;
10201          Only one record once, not loop;
10202     *=========================================================================*/
10203     Procedure Resend_Level_Staged_Dunning
10204                (p_api_version             IN NUMBER := 1.0,
10205                 p_init_msg_list           IN VARCHAR2 ,
10206                 p_commit                  IN VARCHAR2 ,
10207                 p_dunning_plan_id         in number,
10208     	    p_dunning_id              in number,
10209                 p_running_level           IN VARCHAR2,
10210                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
10211     	    p_org_id                  in number default null,
10212                 x_request_id              OUT NOCOPY NUMBER,
10213                 x_return_status           OUT NOCOPY VARCHAR2,
10214                 x_msg_count               OUT NOCOPY NUMBER,
10215                 x_msg_data                OUT NOCOPY VARCHAR2)
10216 
10217     IS
10218     /*
10219         CURSOR C_GET_DEL (IN_del_ID NUMBER) IS
10220           SELECT delinquency_ID
10221             FROM IEX_DELINQUENCIES
10222            WHERE delinquency_ID = in_del_ID;
10223         --
10224         -- begin bug 4914799 ctlee 12/30/2005 add p_dunning_plan_id
10225         CURSOR C_GET_SCORE (IN_ID NUMBER, IN_CODE VARCHAR2, p_dunning_plan_id number) IS
10226           SELECT a.score_value
10227             FROM IEX_SCORE_HISTORIES a
10228                  , IEX_DUNNING_PLANS_VL c  -- bug 4914799 ctlee 12/30/2005
10229            WHERE a.score_object_ID = in_ID
10230              AND a.score_object_code = IN_CODE
10231              and c.score_id = a.score_id   -- bug 4914799 ctlee 12/30/2005
10232              and c.dunning_plan_id = p_dunning_plan_id -- bug 4914799 ctlee 12/30/2005
10233              AND a.creation_date = (select max(b.creation_date)
10234                                       from iex_score_histories b
10235                                      where b.score_object_id = in_id
10236                                        AND b.score_object_code = IN_CODE);
10237         -- end bug 4914799 ctlee 12/30/2005 add p_dunning_plan_id
10238         --
10239         CURSOR C_GET_TEMPLATE (l_line_id NUMBER,
10240                                l_score NUMBER, in_LEVEL VARCHAR2, p_dunning_plan_id number) IS
10241           SELECT x.template_id,
10242                  x.xdo_template_id,
10243                  x.fm_method,
10244                  upper(x.callback_flag),
10245                  x.callback_days
10246             FROM IEX_AG_DN_XREF x,
10247                  ar_aging_buckets ar,
10248                  iex_dunning_plans_vl d
10249            WHERE x.aging_bucket_line_ID = l_line_ID
10250              and x.dunning_plan_id = p_dunning_plan_id
10251              AND l_score between x.score_range_low and x.score_range_high
10252              AND x.aging_bucket_id = ar.aging_bucket_id
10253              and ar.aging_bucket_id = d.aging_bucket_id
10254              AND ar.status = 'A'
10255              AND x.dunning_level = IN_LEVEL ;
10256     */
10257          CURSOR C_TEMPLATE_STATUS (l_template_id number) is
10258          select 'Active'
10259          from xdo_templates_vl xdo
10260          where xdo.template_id = l_template_id
10261          and trunc(sysdate) >= TRUNC (NVL(xdo.start_date, sysdate))
10262          and trunc(sysdate) < TRUNC(NVL(xdo.end_date, sysdate + 1));
10263 
10264          l_template_status		  varchar2(10);
10265 
10266          CURSOR C_TEMPLATE_NAME (l_template_id number) is
10267          select template_name
10268          from xdo_templates_vl xdo
10269          where xdo.template_id = l_template_id;
10270 
10271          l_template_name	varchar2(500);
10272         --
10273 
10274         l_DUNNING_id            NUMBER;
10275         l_delinquency_id        NUMBER;
10276         l_party_cust_id         NUMBER;
10277         l_account_id            NUMBER;
10278         l_customer_site_use_id  NUMBER;
10279         l_noskip                NUMBER := 0;
10280         l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
10281         l_DUNNING_tbl           IEX_DUNNING_PUB.DUNNING_TBL_TYPE;
10282         l_score                 NUMBER;
10283         l_bucket_line_id        NUMBER;
10284         l_campaign_sched_id     NUMBER;
10285         l_template_id           NUMBER;
10286         l_xdo_template_id       NUMBER;
10287         l_method                VARCHAR2(10);
10288         l_callback_flag         VARCHAR2(1);
10289         l_callback_days         NUMBER;
10290         l_callback_date         DATE;
10291         l_request_id            NUMBER;
10292         l_outcome_code          varchar2(20);
10293         l_api_name              CONSTANT VARCHAR2(30) := 'Resend_Level_Staged_Dunning';
10294         l_api_version_number    CONSTANT NUMBER   := 1.0;
10295         l_return_status         VARCHAR2(1);
10296         l_msg_count             NUMBER;
10297         l_msg_data              VARCHAR2(32767);
10298         errmsg                  VARCHAR2(32767);
10299         --
10300         nIdx                    NUMBER := 0;
10301         TYPE Del_ID_TBL_type is Table of IEX_DELINQUENCIES_ALL.DELINQUENCY_ID%TYPE
10302                                 INDEX BY BINARY_INTEGER;
10303         Del_Tbl                 Del_ID_TBL_TYPE;
10304         l_bind_tbl              IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
10305         l_bind_rec              IEX_DUNNING_PVT.FULFILLMENT_BIND_REC;
10306         l_org_id                NUMBER ;
10307         l_running_level         VARCHAR2(25);
10308         l_object_Code           VARCHAR2(25);
10309         l_object_id             NUMBER;
10310         --l_delid_tbl             IEX_DUNNING_PUB.DelId_NumList;
10311         l_del_tbl               IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE;
10312         l_curr_code             VARCHAR2(15);
10313         l_amount                NUMBER;
10314         l_write                 NUMBER;
10315         l_ffm_cnt               NUMBER := 0;
10316         l_dunn_cnt              NUMBER := 0;
10317         l_curr_dmethod          VARCHAR2(10);
10318 
10319         l_delinquency_id_check        NUMBER;
10320         l_party_cust_id_check         NUMBER;
10321         l_account_id_check            NUMBER;
10322         l_customer_site_use_id_check  NUMBER;
10323         l_contact_destination         varchar2(240);  -- bug 3955222
10324         l_contact_party_id            number; -- bug 3955222
10325 
10326         CURSOR C_GET_DUNNING (in_dunning_id NUMBER) IS
10327         SELECT dunning_object_id,
10328               delinquency_id,
10329               dunning_level,
10330     	  xml_template_id,
10331     	  ag_dn_xref_id,
10332     	  xml_request_id,
10333     	  addt_xml_template_id,
10334     	  dunning_method,
10335     	  amount_due_remaining,
10336     	  currency_code,
10337     	  nvl(as_of_date,sysdate)
10338          FROM iex_dunnings
10339         WHERE dunning_id = in_dunning_id;
10340 
10341         CURSOR C_CALLBACK_DETAILS (p_ag_dn_xref_id number) IS
10342           SELECT
10343                  --x.fm_method,
10344     	     upper(x.callback_flag),
10345                  x.callback_days
10346             FROM IEX_AG_DN_XREF x
10347            WHERE x.ag_dn_xref_id = p_ag_dn_xref_id;
10348 
10349         l_dunning_object_id       number;
10350         l_del_id                  number;
10351         l_dunning_level	      varchar2(20);
10352         l_ag_dn_xref_id	      number;
10353         l_xml_request_id	      number;
10354 
10355         --Start adding for bug 9156833 gnramasa 27th Nov 09
10356         l_validation_level		  NUMBER ;
10357         l_resource_tab		  iex_utilities.resource_tab_type;
10358         l_resource_id		  NUMBER;
10359         --End adding for bug 9156833 gnramasa 27th Nov 09
10360         l_inv_xdo_template_id	  number;
10361         l_as_of_date                  date;
10362         CURSOR c_get_resend_resource (p_xml_req_id number) is
10363           SELECT resource_id
10364           FROM iex_xml_request_histories
10365           WHERE xml_request_id = p_xml_req_id;
10366 
10367          cursor c_as_of_date  (p_dunning_id number) is
10368         select  nvl(dunn.as_of_date,sysdate)
10369         from iex_dunnings dunn
10370         where dunning_id = p_dunning_id;
10371 
10372         temp_dunning_id number; -- for bug 16290958
10373      BEGIN
10374           -- Standard Start of API savepoint
10375           SAVEPOINT Resend_Level_Stg_Dunn_PVT;
10376 
10377           --Bug#4679639 schekuri 20-OCT-2005
10378           --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
10379           l_org_id:= mo_global.get_current_org_id;
10380 
10381           -- Standard call to check for call compatibility.
10382           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
10383                                                p_api_version,
10384                                                l_api_name,
10385                                                G_PKG_NAME)
10386           THEN
10387               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
10388           END IF;
10389 
10390           -- Initialize message list if p_init_msg_list is set to TRUE.
10391           IF FND_API.to_Boolean( p_init_msg_list )
10392           THEN
10393               FND_MSG_PUB.initialize;
10394           END IF;
10395 
10396           -- don't write into FILE
10397           l_write := 0;
10398 
10399           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
10400           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - running_level='||p_running_level);
10401 
10402           -- Initialize API return status to SUCCESS
10403           x_return_status := FND_API.G_RET_STS_SUCCESS;
10404 
10405           --
10406           -- Api body
10407           --
10408 
10409           l_party_cust_id := p_delinquencies_tbl(1).party_cust_id;
10410           l_account_id := p_delinquencies_tbl(1).cust_account_id;
10411           l_customer_site_use_id := p_delinquencies_tbl(1).customer_site_use_id;
10412 
10413           if (p_running_level = 'CUSTOMER') then
10414               l_object_Code := 'PARTY';
10415               l_object_id := p_delinquencies_tbl(1).party_cust_id;
10416               l_del_tbl(1).party_cust_id := p_delinquencies_tbl(1).party_cust_id;
10417               --l_amount := staged_dunn_amt_due_remaining(p_dunning_id); --Changed for bug 9503251 gnramasa 22nd apr 2010
10418               --l_curr_code := party_currency_code(l_object_id);
10419           --
10420           elsif (p_running_level = 'ACCOUNT') then
10421               l_object_Code := 'IEX_ACCOUNT';
10422               l_object_id := p_delinquencies_tbl(1).cust_account_id;
10423               l_del_tbl(1).cust_account_id := p_delinquencies_tbl(1).cust_account_id;
10424               --l_amount := staged_dunn_amt_due_remaining(p_dunning_id); --Changed for bug 9503251 gnramasa 22nd apr 2010
10425               --l_curr_code := acct_currency_code(l_object_id);
10426           --
10427           elsif (p_running_level = 'BILL_TO') then
10428               l_object_Code := 'IEX_BILLTO';
10429               l_object_id := p_delinquencies_tbl(1).customer_site_use_id;
10430               l_del_tbl(1).customer_site_use_id := p_delinquencies_tbl(1).customer_site_use_id;
10431               --l_amount := staged_dunn_amt_due_remaining(p_dunning_id); --Changed for bug 9503251 gnramasa 22nd apr 2010
10432               --l_curr_code := site_currency_code(l_object_id);
10433           end if;
10434 
10435           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_code='||l_object_code);
10436           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id='||l_object_id);
10437           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id='||l_party_cust_id);
10438 
10439           /* In staged dunning resend, we are sending the previous output as it is to customer, so it is fine to
10440              copy the amount due remaining and curreny code from the parent/previous dunning record */
10441           open C_GET_DUNNING (p_dunning_id);
10442           fetch C_GET_DUNNING into l_dunning_object_id, l_del_id, l_dunning_level, l_xdo_template_id, l_ag_dn_xref_id,
10443                               l_xml_request_id, l_inv_xdo_template_id, l_method, l_amount, l_curr_code,l_as_of_date;
10444           close C_GET_DUNNING;
10445 
10446           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_object_id: ' || l_dunning_object_id);
10447           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_del_id: ' || l_del_id);
10448           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_level: ' || l_dunning_level);
10449           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_xdo_template_id: ' || l_xdo_template_id);
10450           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_ag_dn_xref_id: ' || l_ag_dn_xref_id);
10451           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_xml_request_id: ' || l_xml_request_id);
10452           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_inv_xdo_template_id: ' || l_inv_xdo_template_id);
10453           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_method: ' || l_method);
10454           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount_due_remaining='||l_amount);
10455           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - currency_code='||l_curr_code);
10456            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - as_of_date = '||l_as_of_date);
10457 
10458           /*===========================================
10459            * Check the status of the template
10460            *===========================================*/
10461 
10462            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template status');
10463            Open C_TEMPLATE_STATUS(l_xdo_template_id);
10464            Fetch C_TEMPLATE_STATUS into l_template_status;
10465 
10466            If ( C_TEMPLATE_STATUS%NOTFOUND) Then
10467 
10468     		open C_TEMPLATE_NAME (l_xdo_template_id);
10469     		Fetch C_TEMPLATE_NAME into l_template_name;
10470     		close C_TEMPLATE_NAME;
10471 
10472     		FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
10473                     FND_MSG_PUB.Add;
10474                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
10475     	        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
10476     	        RAISE FND_API.G_EXC_ERROR;
10477     	END IF;
10478             Close C_TEMPLATE_STATUS;
10479     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
10480 
10481            if l_inv_xdo_template_id is not null then
10482     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Invoice Template status');
10483            Open C_TEMPLATE_STATUS(l_inv_xdo_template_id);
10484            Fetch C_TEMPLATE_STATUS into l_template_status;
10485 
10486            If ( C_TEMPLATE_STATUS%NOTFOUND) Then
10487 
10488     		open C_TEMPLATE_NAME (l_inv_xdo_template_id);
10489     		Fetch C_TEMPLATE_NAME into l_template_name;
10490     		close C_TEMPLATE_NAME;
10491 
10492     		FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
10493                     FND_MSG_PUB.Add;
10494                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Addt Template: ''' || l_template_name || ''' is inactive');
10495     	        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Addt Template: ''' || l_template_name || ''' is inactive');
10496     	        RAISE FND_API.G_EXC_ERROR;
10497     	END IF;
10498             Close C_TEMPLATE_STATUS;
10499     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - addt template status= '||l_template_status);
10500         ELSE
10501     	 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - invoice_copies is N: Dont Send Invoice');
10502          end if;
10503           open C_CALLBACK_DETAILS (l_ag_dn_xref_id);
10504           --fetch C_CALLBACK_DETAILS into l_method, l_callback_flag, l_callback_days;
10505           fetch C_CALLBACK_DETAILS into l_callback_flag, l_callback_days;
10506           close C_CALLBACK_DETAILS;
10507 
10508           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_callback_flag: ' || l_callback_flag);
10509           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_callback_days: ' || l_callback_days);
10510 
10511           /*==================================================================
10512            * l_noskip is used to trace the del data is all disputed or not;
10513            * if any one del not disputed, then l_noskip=1;
10514            * if l_noskip=0, then means all del are disputed,
10515            *    => for this customer/account, skip it;
10516            *==================================================================*/
10517           l_noskip := 1;
10518 
10519     /*
10520           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delcnt='||p_delinquencies_tbl.count);
10521 
10522             FOR i in 1..p_delinquencies_tbl.count
10523             LOOP
10524 
10525               l_delinquency_id := p_delinquencies_tbl(i).delinquency_id;
10526     */
10527              /*=============================================================
10528               *  For each Delinquency,
10529               *=============================================================*/
10530 
10531     --          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - open del='||l_delinquency_Id);
10532 
10533              /*=============================================================
10534               * IsDispute ?
10535               * If yes => stop (exit);
10536               * else continue;
10537               *
10538               * it returns values :
10539               * 1) it returns 'F' if no dispute exists for the delinquency
10540               * 2) it returns 'T' if dispute exists and is pending
10541               * 3) it returns 'F' if dispute exists and its staus is "COMPLETE"
10542               *===========================================================*/
10543 
10544     /*          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ResendLevelDunn:Chk IsDispute');
10545 
10546                IEX_DISPUTE_PVT.Is_Delinquency_Dispute(p_api_version              => p_api_version
10547     																			           , p_init_msg_list            => p_init_msg_list
10548     																			           , p_delinquency_id           => l_delinquency_id
10549     																			           , x_return_status            => x_return_status
10550     																			           , x_msg_count                => x_msg_count
10551     																			           , x_msg_data                 => x_msg_data);
10552 
10553                IF x_return_status = 'T' THEN
10554                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Dispute exists and is pending for del '|| l_delinquency_id);
10555                  GOTO end_del;
10556                elsif x_return_status = 'F' THEN
10557                   -- if one del is not disputed, then l_noskip=1;
10558                   l_noskip := 1;
10559                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Dispute or status is COMPLETE');
10560                END IF;
10561 
10562                nIdx := nIdx + 1;
10563                del_tbl(nIdx) := l_delinquency_id; --in order to update del)
10564 
10565               <<end_del>>
10566               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close C_GET_DEL');
10567 
10568            END LOOP; -- end of DELINQUENCIES_TBL loop
10569            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END LOOP');
10570     */
10571           IF (l_noskip > 0) THEN
10572 
10573              -- init the msg (not including the msg from dispute api)
10574              --FND_MSG_PUB.initialize;
10575 
10576               /*===========================================
10577                * Get Score From IEX_SCORE_HISTORIES
10578                * If NotFound => Call API to getScore;
10579                *===========================================*/
10580     /*
10581     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get Score');
10582                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - objectCode='||l_object_Code);
10583 
10584                Open C_Get_SCORE(l_object_id, l_object_Code, p_dunning_plan_id);
10585                Fetch C_Get_SCORE into l_score;
10586 
10587                If ( C_GET_SCORE%NOTFOUND) Then
10588                     --FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
10589                     --FND_MESSAGE.Set_Token ('INFO', 'Score', FALSE);
10590                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_SCORE');
10591                     FND_MSG_PUB.Add;
10592                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Score NotFound');
10593                     Close C_Get_SCORE;
10594                     x_return_status := FND_API.G_RET_STS_ERROR;
10595                     GOTO end_api;
10596                END IF;
10597 
10598                --WriteLog('iexvdunb:ResendLevelDunn:CLOSE C_GET_SCORE', l_write);
10599                Close C_Get_SCORE;
10600 
10601                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get Score='||l_score);
10602     */
10603 
10604               /*===================================================
10605                * in 11.5.11, support aging bucket line for all level;
10606                * clchang added 11/20/04.
10607                * Get Aging_Bucket_Line_id for each party/acct/site
10608                *===================================================*/
10609     /*
10610                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetAgingBucketLineId');
10611 
10612                AGING_DEL(p_api_version              => p_api_version
10613     		                , p_init_msg_list            => p_init_msg_list
10614     		                , p_commit                   => p_commit
10615     		                , p_delinquency_id           => null
10616     		                , p_dunning_plan_id          => p_dunning_plan_id
10617     		                , p_bucket                   => null
10618     		                , p_object_code              => l_object_code
10619     		                , p_object_id                => l_object_id
10620     		                , x_return_status            => x_return_status
10621     		                , x_msg_count                => x_msg_count
10622     		                , x_msg_data                 => x_msg_data
10623     		                , x_aging_bucket_line_id     => l_bucket_line_id);
10624 
10625                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - AgingDel status='||x_return_status);
10626 
10627                If ( x_return_status <> FND_API.G_RET_STS_SUCCESS) Then
10628                     --FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
10629                     --FND_MESSAGE.Set_Token ('INFO', 'AgingBucketLineId', FALSE);
10630                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_AGINGBUCKETLINE');
10631                     FND_MSG_PUB.Add;
10632                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - AgingBucketLineId notfound');
10633                     x_return_status := FND_API.G_RET_STS_ERROR;
10634                     GOTO end_api;
10635                END IF;
10636 
10637                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - lineid='||l_bucket_line_id);
10638     */
10639               /*===========================================
10640                * Get Template_ID From iex_ag_dn_xref
10641                *===========================================*/
10642     /*
10643                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template');
10644 
10645                Open C_Get_TEMPLATE(l_bucket_line_id, l_score, p_running_level, p_dunning_plan_id);
10646                Fetch C_Get_TEMPLATE into
10647                            l_template_id,
10648                            l_xdo_template_id,
10649                            l_method,
10650                            l_callback_flag,
10651                            l_callback_days;
10652 
10653                If ( C_GET_TEMPLATE%NOTFOUND) Then
10654                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
10655                     FND_MSG_PUB.Add;
10656                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template notfound');
10657                     x_return_status := FND_API.G_RET_STS_ERROR;
10658                     GOTO end_api;
10659                END IF;
10660 
10661                Close C_Get_TEMPLATE;
10662 
10663                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get template_id='||l_template_id);
10664                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get xdo_template_id='||l_xdo_template_id, l_write);
10665     */
10666               /*===========================================
10667                * Check template
10668                *  in 11.5.11, IEX supports fulfillment and xml publisher.
10669                *  if the current setup for delivery id FFM,
10670                *  then template_id is necessary;
10671                *  if XML, xdo_template_id is necessary;
10672                *===========================================*/
10673 
10674                l_curr_dmethod := IEX_SEND_XML_PVT.getCurrDeliveryMethod;
10675                WriteLog('iexvdunb:ResendLevelDunn:curr d_method='||l_curr_dmethod);
10676                if ( (l_curr_dmethod is null or l_curr_dmethod = '') or
10677     	      (l_curr_dmethod = 'FFM' and l_template_id is null)  or
10678     	      (l_curr_dmethod = 'XML' and l_xdo_template_id is null ) ) then
10679                     --FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
10680                     --FND_MESSAGE.Set_Token ('INFO', 'Template_ID', FALSE);
10681                     FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
10682                     FND_MSG_PUB.Add;
10683                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template notfound');
10684                     x_return_status := FND_API.G_RET_STS_ERROR;
10685                     GOTO end_api;
10686                end if;
10687 
10688               /*===========================================
10689                * Check profile before send dunning
10690                *===========================================*/
10691 
10692                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - begin check customer profile');
10693                 -- ctlee - check the hz_customer_profiles.dunning_letter
10694                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_party_cust_id = ' || l_party_cust_id);
10695                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_account_id = ' || l_account_id);
10696                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_customer_site_use_id = ' || l_customer_site_use_id);
10697                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_delinquency_id = ' || l_delinquency_id);
10698                 -- ctlee - check the hz_customer_profiles.dunning_letter
10699                 l_party_cust_id_check := l_party_cust_id;
10700                 l_account_id_check := l_account_id;
10701                 l_customer_site_use_id_check := l_customer_site_use_id;
10702                 l_delinquency_id_check := l_delinquency_id;
10703                if (p_running_level = 'CUSTOMER') then
10704                   l_account_id_check := null;
10705                   l_customer_site_use_id_check := null;
10706                   l_delinquency_id_check := null;
10707                elsif  (p_running_level = 'ACCOUNT') then
10708                   l_customer_site_use_id_check := null;
10709                   l_delinquency_id_check := null;
10710                elsif  (p_running_level = 'BILL_TO') then
10711                   l_delinquency_id_check := null;
10712                end if;
10713 
10714           open c_as_of_date (p_dunning_id);
10715             fetch c_as_of_date into l_as_of_date;
10716             close c_as_of_date;
10717 
10718                if ( iex_utilities.DunningProfileCheck (
10719                        p_party_id => l_party_cust_id_check
10720                        , p_cust_account_id => l_account_id_check
10721                        , p_site_use_id => l_customer_site_use_id_check
10722                        , p_delinquency_id => l_delinquency_id_check     ) = 'N'
10723                   ) then
10724                     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_PROFILE_NO');
10725                     FND_MSG_PUB.Add;
10726                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send dunning in customer profile set to no ');
10727                     x_return_status := FND_API.G_RET_STS_ERROR;
10728                     GOTO end_api;
10729                end if;
10730 
10731     /*
10732                -- ctlee - check the hz_customer_profiles_amt min_dunning_invoice_amount and min_dunning_amount
10733                if ( iex_utilities.DunningMinAmountCheck (
10734                         p_cust_account_id => l_account_id_check
10735                         , p_site_use_id => l_customer_site_use_id_check)  = 'N'
10736                   ) then
10737                     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
10738                     FND_MSG_PUB.Add;
10739                     WriteLog('iexvdunb:ResendLevelDunn: Required min Dunning amount in customer profile ');
10740                     x_return_status := FND_API.G_RET_STS_ERROR;
10741                     GOTO end_api;
10742                end if;
10743 
10744                WriteLog('iexvdunb:ResendLevelDunn: end check customer profile');
10745 
10746     */
10747               /*===========================================
10748                * Send Letter through Fulfillment
10749                *===========================================*/
10750 
10751                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND_FFM');
10752                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org_id='||l_org_id);
10753                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_id='||l_party_cust_id);
10754                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - method='||l_method);
10755 
10756                l_bind_rec.key_name := 'party_id';
10757                l_bind_rec.key_type := 'NUMBER';
10758                l_bind_rec.key_value := l_party_cust_id;
10759                l_bind_tbl(1) := l_bind_rec;
10760     	   --Begin Bug 10401991 20-Jan-2011 barathsr
10761                l_bind_rec.key_name := 'org_id';
10762                l_bind_rec.key_type := 'NUMBER';
10763                l_bind_rec.key_value := l_org_id;
10764     	   --End Bug 10401991 20-Jan-2011 barathsr
10765                l_bind_tbl(2) := l_bind_rec;
10766                l_bind_rec.key_name := 'account_id';
10767                l_bind_rec.key_type := 'NUMBER';
10768                l_bind_rec.key_value := l_account_id;
10769                l_bind_tbl(3) := l_bind_rec;
10770                -- added for new level 'BILL_TO' since 11.5.10.
10771                l_bind_rec.key_name := 'customer_site_use_id';
10772                l_bind_rec.key_type := 'NUMBER';
10773                l_bind_rec.key_value := l_customer_site_use_id;
10774                l_bind_tbl(4) := l_bind_rec;
10775     	       l_bind_rec.key_name := 'DUNNING_ID';
10776                l_bind_rec.key_type := 'NUMBER';
10777                l_bind_rec.key_value := p_dunning_id;
10778                l_bind_tbl(5) := l_bind_rec;
10779 
10780            /*
10781     	   --Start adding for bug 9156833 gnramasa 27th Nov 09
10782     	 l_validation_level := FND_API.G_VALID_LEVEL_FULL;
10783 
10784     	 if (p_running_level = 'BILL_TO') then
10785     		iex_utilities.get_dunning_resource(p_api_version => p_api_version,
10786     				       p_init_msg_list     => FND_API.G_TRUE,
10787     				       p_commit            => FND_API.G_FALSE,
10788     				       p_validation_level  => l_validation_level,
10789     				       p_level             => 'DUNNING_BILLTO',
10790     				       p_level_id          => l_customer_site_use_id,
10791     				       x_msg_count         => l_msg_count,
10792     				       x_msg_data          => l_msg_data,
10793     				       x_return_status     => l_return_status,
10794     				       x_resource_tab      => l_resource_tab);
10795     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
10796     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
10797     		     x_return_status := FND_API.G_RET_STS_ERROR;
10798     		     GOTO end_get_resource;
10799     		END IF;
10800     	  end if;
10801 
10802     	  if l_resource_tab.count<1 and (p_running_level = 'ACCOUNT') then
10803     		  iex_utilities.get_dunning_resource(p_api_version => p_api_version,
10804     				       p_init_msg_list     => FND_API.G_TRUE,
10805     				       p_commit            => FND_API.G_FALSE,
10806     				       p_validation_level  => l_validation_level,
10807     				       p_level             => 'DUNNING_ACCOUNT',
10808     				       p_level_id          => l_account_id,
10809     				       x_msg_count         => l_msg_count,
10810     				       x_msg_data          => l_msg_data,
10811     				       x_return_status     => l_return_status,
10812     				       x_resource_tab      => l_resource_tab);
10813     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
10814     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
10815     		     x_return_status := FND_API.G_RET_STS_ERROR;
10816     		     GOTO end_get_resource;
10817     		END IF;
10818     	  end if;
10819 
10820     	  if l_resource_tab.count<1 and (p_running_level = 'CUSTOMER') then
10821     		iex_utilities.get_dunning_resource(p_api_version => p_api_version,
10822     				       p_init_msg_list     => FND_API.G_TRUE,
10823     				       p_commit            => FND_API.G_FALSE,
10824     				       p_validation_level  => l_validation_level,
10825     				       p_level             => 'DUNNING_PARTY',
10826     				       p_level_id          => l_party_cust_id,
10827     				       x_msg_count         => l_msg_count,
10828     				       x_msg_data          => l_msg_data,
10829     				       x_return_status     => l_return_status,
10830     				       x_resource_tab      => l_resource_tab);
10831     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
10832     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
10833     		     x_return_status := FND_API.G_RET_STS_ERROR;
10834     		     GOTO end_get_resource;
10835     		END IF;
10836 
10837     		if l_resource_tab.count<1 and (p_running_level = 'CUSTOMER') then
10838     			iex_utilities.get_dunning_resource(p_api_version => p_api_version,
10839     						         p_init_msg_list     => FND_API.G_TRUE,
10840     							 p_commit            => FND_API.G_FALSE,
10841     							 p_validation_level  => l_validation_level,
10842     							 p_level             => 'DUNNING_PARTY_ACCOUNT',
10843     							 p_level_id          => l_party_cust_id,
10844     							 x_msg_count         => l_msg_count,
10845     							 x_msg_data          => l_msg_data,
10846     							 x_return_status     => l_return_status,
10847     							 x_resource_tab      => l_resource_tab);
10848     			IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
10849     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
10850     			     x_return_status := FND_API.G_RET_STS_ERROR;
10851     			     GOTO end_get_resource;
10852     			END IF;
10853     		end if;
10854     	  end if;
10855 
10856     	  <<end_get_resource>>
10857     	  if l_resource_tab.count>0 then
10858     	    l_resource_id := l_resource_tab(1).resource_id;
10859     	  end if;
10860     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_resource_id: ' || l_resource_id);
10861     	  --End adding for bug 9156833 gnramasa 27th Nov 09
10862     	  */
10863 
10864     	   --Reuse the same resource id value from parent dunning/delivery record for resend too
10865     	   open c_get_resend_resource (l_xml_request_id);
10866     	   fetch c_get_resend_resource into l_resource_id;
10867     	   close c_get_resend_resource;
10868 
10869     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_resource_id: ' || l_resource_id);
10870 
10871     	   WriteLog(G_PKG_NAME || ' ' || l_api_name ||' before send_xml org_id ' || p_org_id);
10872 
10873              /**
10874               * in 11.5.11, IEX supports fulfillment and xml publisher.
10875               * it depends on the set up in IEX ADMIN/SETUP.
10876               */
10877               if (l_curr_dmethod = 'FFM') then
10878 
10879                Send_Fulfillment(
10880                        p_api_version              => p_api_version
10881                      , p_init_msg_list            => p_init_msg_list
10882                      , p_commit                   => p_commit
10883                      , p_fulfillment_bind_tbl     => l_bind_tbl
10884                      , p_template_id              => l_template_id
10885                      , p_method                   => l_method
10886                      , p_party_id                 => l_party_cust_id
10887                      , x_request_id               => l_request_id
10888                      , x_return_status            => x_return_status
10889                      , x_msg_count                => x_msg_count
10890                      , x_msg_data                 => x_msg_data
10891                      , x_contact_destination      => l_contact_destination  -- bug 3955222
10892                      , x_contact_party_id         => l_contact_party_id  -- bug 3955222
10893                      );
10894               else
10895 
10896                Send_XML(
10897                        p_api_version              => p_api_version
10898                        , p_init_msg_list            => p_init_msg_list
10899                        , p_commit                   => FND_API.G_FALSE  --p_commit --bug 8567312
10900                        , p_resend                   => 'Y'
10901                        , p_request_id               => l_xml_request_id
10902                        , p_fulfillment_bind_tbl     => l_bind_tbl
10903                        , p_template_id              => l_xdo_template_id
10904                        , p_method                   => l_method
10905                        , p_party_id                 => l_party_cust_id
10906                        , p_level                    => p_running_level
10907                        , p_source_id                => l_object_id
10908                        , p_object_code              => l_object_code
10909                        , p_object_id                => l_object_id
10910     		   , p_resource_id              => l_resource_id --Added for bug 9156833 gnramasa 27th Nov 09
10911     		   , p_org_id                   => p_org_id
10912     		   , p_addt_template_id	        => l_inv_xdo_template_id
10913                        , x_request_id               => l_request_id
10914                        , x_return_status            => x_return_status
10915                        , x_msg_count                => x_msg_count
10916                        , x_msg_data                 => x_msg_data
10917                        , x_contact_destination      => l_contact_destination  -- bug 3955222
10918                        , x_contact_party_id         => l_contact_party_id  -- bug 3955222
10919                        );
10920 
10921               end if;
10922 
10923               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND status='|| x_return_status);
10924 
10925                IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
10926                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Sending Letters', l_write);
10927                   x_return_status := FND_API.G_RET_STS_ERROR;
10928                   GOTO end_api;
10929                END IF;
10930 
10931                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||l_request_id, l_write);
10932                l_ffm_cnt := l_ffm_cnt + 1;
10933 
10934               /*===========================================
10935                * Close OPEN Dunnings for each party/account
10936                *===========================================*/
10937 
10938                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning', l_write);
10939                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - runninglevel='||p_running_level, l_write);
10940                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - del cnt='||l_del_tbl.count, l_write);
10941                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyid='||l_del_tbl(1).party_cust_id, l_write);
10942                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - accntid='||l_del_tbl(1).cust_account_id, l_write);
10943                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - siteid='||l_del_tbl(1).customer_site_use_id, l_write);
10944 
10945                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Call Close_Staged_Dunning', l_write);
10946 
10947                  Close_Staged_Dunning(p_api_version              => p_api_version
10948     				 , p_init_msg_list            => p_init_msg_list
10949     				 , p_commit                   => p_commit
10950     				 , p_delinquencies_tbl        => l_del_tbl
10951     				 , p_ag_dn_xref_id	      => l_ag_dn_xref_id
10952     				 , p_running_level            => p_running_level
10953     				 , x_return_status            => x_return_status
10954     				 , x_msg_count                => x_msg_count
10955     				 , x_msg_data                 => x_msg_data);
10956 
10957                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close_Staged_Dunning status='|| x_return_status, l_write);
10958 
10959                  IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
10960                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Close Dunning', l_write);
10961                     x_return_status := FND_API.G_RET_STS_ERROR;
10962                     GOTO end_api;
10963                  END IF;
10964                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End Close_Staged_Dunning', l_write);
10965 
10966               /*===========================================
10967                * Create Dunning Record
10968                *===========================================*/
10969 
10970                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get CallbackDate', l_write);
10971                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag='||l_callback_flag, l_write);
10972                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDays='||l_callback_days, l_write);
10973 
10974                 /*===================================================
10975                  * clchang updated 02/13/2003
10976                  * callback_days could be null if callback_yn = 'N';
10977                  * and if callback_yn = 'N', not get callback_date;
10978                  *==================================================*/
10979                  IF (l_callback_flag = 'Y') THEN
10980 
10981                      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is Y: GetCallbackDate',l_write);
10982                      Get_Callback_Date( p_init_msg_list          => p_init_msg_list
10983                                 , p_callback_days          => l_callback_days
10984                                 , x_callback_date          => l_callback_date
10985                                 , x_return_status          => x_return_status
10986                                 , x_msg_count              => x_msg_count
10987                                 , x_msg_data               => x_msg_data);
10988 
10989                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetCallbackDate status='|| x_return_status, l_write);
10990 
10991                     IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
10992                       FND_MESSAGE.Set_Name('IEX', 'IEX_NO_CALLBACKDATE');
10993                       FND_MSG_PUB.Add;
10994                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Get CallbackDate', l_write);
10995                       x_return_status := FND_API.G_RET_STS_ERROR;
10996                       GOTO end_api;
10997                     END IF;
10998 
10999                  ELSE
11000                      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is N: NOTGetCallbackDate',l_write);
11001 
11002                  END IF;
11003 
11004                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDate='||l_callback_date, l_write);
11005                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningRec', l_write);
11006                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - objectid='||l_object_id, l_write);
11007                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - objecttype='||p_running_level, l_write);
11008                  l_dunning_rec.dunning_level := p_running_level;
11009                  l_dunning_rec.dunning_object_id := l_object_id;
11010                  l_dunning_rec.callback_yn := l_callback_flag;
11011                  l_dunning_rec.callback_date := l_callback_date;
11012                  l_dunning_rec.status := 'OPEN';
11013                  l_dunning_rec.dunning_method := l_method;
11014                  if (l_curr_dmethod = 'FFM') then
11015                    l_dunning_rec.template_id:= l_template_id;
11016                    l_dunning_rec.ffm_request_id := l_request_id;
11017                  else
11018                    l_dunning_rec.xml_template_id:= l_xdo_template_id;
11019                    l_dunning_rec.xml_request_id := l_request_id;
11020     	       l_dunning_rec.addt_xml_template_id := l_inv_xdo_template_id;
11021                  end if;
11022                  l_dunning_rec.amount_due_remaining := l_amount;
11023                  l_dunning_rec.currency_code := l_curr_code;
11024                  l_dunning_rec.object_type := l_object_code;
11025                  l_dunning_rec.object_id := l_object_id;
11026                  l_dunning_rec.dunning_plan_id := p_dunning_plan_id;
11027                  l_dunning_rec.contact_destination := l_contact_destination;  -- bug 3955222
11028                  l_dunning_rec.contact_party_id := l_contact_party_id;  -- bug 3955222
11029     	     l_dunning_rec.ag_dn_xref_id    := l_ag_dn_xref_id;
11030     	     l_dunning_rec.org_id := p_org_id;
11031     	     l_dunning_rec.as_of_date := l_as_of_date;
11032     	     -- start bug 16290958
11033 	         --l_dunning_rec.parent_dunning_id := p_dunning_id; -- added for bug 9937306 by snuthala 11/25/2011
11034 	         temp_dunning_id := NULL;
11035            select parent_dunning_id into temp_dunning_id
11036            from iex_dunnings
11037            where dunning_id =  p_dunning_id;
11038            WriteLog('temp_dunning_id -- '||temp_dunning_id);
11039            IF  temp_dunning_id is not NULL then
11040               l_dunning_rec.parent_dunning_id := temp_dunning_id;
11041            else
11042              l_dunning_rec.parent_dunning_id := p_dunning_id;
11043             END IF;
11044             WriteLog('l_dunning_rec.parent_dunning_id : '||l_dunning_rec.parent_dunning_id);
11045 
11046            -- end bug 16290958
11047     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' before creating dunning org_id ' || p_org_id);
11048 
11049                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Insert Row', l_write);
11050 
11051                  CREATE_DUNNING(
11052                        p_api_version              => p_api_version
11053                      , p_init_msg_list            => p_init_msg_list
11054                      , p_commit                   => p_commit
11055                      , p_dunning_rec              => l_dunning_rec
11056                      , x_dunning_id               => l_dunning_id
11057                      , x_return_status            => x_return_status
11058                      , x_msg_count                => x_msg_count
11059                      , x_msg_data                 => x_msg_data);
11060 
11061                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| x_return_status, l_write);
11062 
11063                   IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
11064                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning', l_write);
11065                        x_return_status := FND_API.G_RET_STS_ERROR;
11066                        GOTO end_api;
11067                   END IF;
11068 
11069                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningId='||l_dunning_id, l_write);
11070                   l_dunn_cnt := l_dunn_cnt + 1;
11071 
11072               /*===========================================
11073                * Update Delinquency
11074                * Set DUNN_YN = 'N'
11075                *===========================================*/
11076 
11077                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========Summary===========');
11078                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - For RunningLevel='||p_running_level);
11079                  --WriteLog('iexvdunb:ResendLevelDunn:Resend - UpdateDel', l_write);
11080                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Resend - object_id='||l_object_id, l_write);
11081 
11082                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SendFFM Cnt='|| l_ffm_cnt, l_write);
11083                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunn Cnt='|| l_dunn_cnt, l_write);
11084                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========End Summary===========');
11085 
11086                <<end_api>>
11087                if (x_return_status <> FND_API.G_RET_STS_SUCCESS ) THEN
11088                    ROLLBACK TO Resend_Level_Stg_Dunn_PVT;
11089                    FND_MSG_PUB.Count_And_Get
11090                    (  p_count          =>   x_msg_count,
11091                       p_data           =>   x_msg_data );
11092                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api:error on this party/accnt/site', l_write);
11093                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api:status='||x_return_status, l_write);
11094                    --Resend need return the exact status
11095                    --x_return_status := 'SKIP'; --FND_API.G_EXC_ERROR;
11096                end if;
11097                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api', l_write);
11098 
11099           ELSE -- l_noskip = 0
11100                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - all del disputed', l_write);
11101                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - skip this party/accnt/site', l_write);
11102                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_api:status='||x_return_status, l_write);
11103                FND_MSG_PUB.Count_And_Get
11104                (  p_count          =>   x_msg_count,
11105                   p_data           =>   x_msg_data );
11106                --Resend need return the exact status
11107                --x_return_status := 'SKIP'; --FND_API.G_EXC_ERROR;
11108 
11109           end if; -- end of if (l_noskip>0)
11110           --
11111           -- End of API body
11112           --
11113 
11114           x_request_id := l_request_id;
11115           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||x_request_id, l_write);
11116           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - status='||x_return_status, l_write);
11117 
11118           -- Standard check for p_commit
11119           IF FND_API.to_Boolean( p_commit )
11120           THEN
11121               COMMIT WORK;
11122           END IF;
11123 
11124           WriteLog('iexvdunb:ResendLevelDunn:END', l_write);
11125 
11126           FND_MSG_PUB.Count_And_Get
11127           (  p_count          =>   x_msg_count,
11128              p_data           =>   x_msg_data );
11129 
11130           EXCEPTION
11131               WHEN FND_API.G_EXC_ERROR THEN
11132                   x_return_status := FND_API.G_RET_STS_ERROR;
11133                   FND_MSG_PUB.Count_And_Get
11134                   (  p_count          =>   x_msg_count,
11135                      p_data           =>   x_msg_data );
11136                   ROLLBACK TO Resend_Level_Stg_Dunn_PVT;
11137                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM, l_write);
11138 
11139               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
11140                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
11141                   FND_MSG_PUB.Count_And_Get
11142                   (  p_count          =>   x_msg_count,
11143                      p_data           =>   x_msg_data );
11144                   ROLLBACK TO Resend_Level_Stg_Dunn_PVT;
11145                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM, l_write);
11146 
11147               WHEN OTHERS THEN
11148                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
11149                   FND_MSG_PUB.Count_And_Get
11150                   (  p_count          =>   x_msg_count,
11151                      p_data           =>   x_msg_data );
11152                   ROLLBACK TO Resend_Level_Stg_Dunn_PVT;
11153                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM, l_write);
11154 
11155     END Resend_Level_Staged_Dunning;
11156 
11157     Procedure Resend_Dunning
11158                (p_api_version             IN NUMBER := 1.0,
11159                 p_init_msg_list           IN VARCHAR2 ,
11160                 p_commit                  IN VARCHAR2 ,
11161                 p_dunning_plan_id         in number,
11162                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
11163                 p_org_id                  in number,
11164     		    p_dunning_id              in Number,
11165     		    x_request_id              OUT NOCOPY NUMBER,
11166                 x_return_status           OUT NOCOPY VARCHAR2,
11167                 x_msg_count               OUT NOCOPY NUMBER,
11168                 x_msg_data                OUT NOCOPY VARCHAR2)
11169     IS
11170         CURSOR C_GET_DEL (IN_del_ID NUMBER) IS
11171           SELECT delinquency_ID,
11172                  party_cust_id,
11173                  cust_account_id,
11174                  customer_site_use_id,
11175                  score_value
11176             FROM IEX_DELINQUENCIES
11177            WHERE delinquency_ID = in_del_ID;
11178         --
11179         CURSOR C_GET_SCORE (IN_ID NUMBER) IS
11180           SELECT a.score_value
11181             FROM IEX_SCORE_HISTORIES a
11182            WHERE a.score_object_ID = in_ID
11183              AND a.score_object_code = 'IEX_DELINQUENCY'
11184              AND a.creation_date = (select max(b.creation_date)
11185                                       from iex_score_histories b
11186                                      where b.score_object_id = in_id
11187                                        AND b.score_object_code = 'IEX_DELINQUENCY');
11188         --
11189         --
11190         CURSOR C_GET_TEMPLATE (l_line_id NUMBER,
11191                                l_score NUMBER, p_dunning_plan_id number) IS
11192           SELECT x.ag_dn_xref_id,x.template_id,
11193                  x.xdo_template_id,
11194                  x.fm_method,
11195                  upper(x.callback_flag),
11196                  x.callback_days,
11197                  ar.bucket_name
11198             FROM IEX_AG_DN_XREF x,
11199                  ar_aging_buckets ar,
11200                  iex_dunning_plans_vl d
11201            WHERE x.aging_bucket_line_ID = l_line_ID
11202              and x.dunning_plan_id = p_dunning_plan_id
11203              AND l_score between x.score_range_low and x.score_range_high
11204              AND x.aging_bucket_id = ar.aging_bucket_id
11205              and ar.aging_bucket_id = d.aging_bucket_id
11206              AND ar.status = 'A'
11207              AND x.dunning_level = 'DELINQUENCY' ;
11208 
11209          CURSOR C_TEMPLATE_STATUS (l_template_id number) is
11210          select 'Active'
11211          from xdo_templates_vl xdo
11212          where xdo.template_id = l_template_id
11213          and trunc(sysdate) >= TRUNC (NVL(xdo.start_date, sysdate))
11214          and trunc(sysdate) < TRUNC(NVL(xdo.end_date, sysdate + 1));
11215 
11216          l_template_status		  varchar2(10);
11217 
11218          CURSOR C_TEMPLATE_NAME (l_template_id number) is
11219          select template_name
11220          from xdo_templates_vl xdo
11221          where xdo.template_id = l_template_id;
11222 
11223          l_template_name	varchar2(500);
11224         --
11225         cursor c_amount (IN_ID number) is
11226          select ps.amount_due_remaining,
11227                 ps.invoice_currency_code
11228            from ar_payment_schedules_all ps,
11229                 --iex_delinquencies_all del
11230                 iex_delinquencies del
11231           where ps.payment_schedule_id (+)= del.payment_schedule_id
11232             and del.delinquency_id = in_id;
11233         --
11234         cursor c_dunning_plan_dtl (p_dunn_plan_id number) is
11235         select nvl(dunn.grace_days ,'N'),
11236                nvl(dunn.dun_disputed_items, 'N')
11237         from iex_dunning_plans_b dunn
11238         where dunning_plan_id = p_dunn_plan_id;
11239 
11240         l_AMOUNT                NUMBER;
11241         l_CURR_CODE             VARCHAR2(15);
11242         l_DUNNING_id            NUMBER;
11243         l_delinquency_id        NUMBER;
11244         l_party_cust_id         NUMBER;
11245         l_account_id            NUMBER;
11246         l_customer_site_use_id  NUMBER;
11247         l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
11248         l_score                 NUMBER;
11249         l_bucket_line_id        NUMBER;
11250         l_campaign_sched_id     NUMBER;
11251         l_template_id           NUMBER;
11252         l_xdo_template_id       NUMBER;
11253         l_method                VARCHAR2(10);
11254         l_callback_flag         VARCHAR2(1);
11255         l_callback_days         NUMBER;
11256         l_callback_date         DATE;
11257         l_request_id            NUMBER;
11258         l_outcome_code          varchar2(20);
11259         l_api_name              CONSTANT VARCHAR2(30) := 'Resend_Dunning';
11260         l_api_version_number    CONSTANT NUMBER   := 1.0;
11261         l_return_status         VARCHAR2(1);
11262         l_msg_count             NUMBER;
11263         l_msg_data              VARCHAR2(32767);
11264         errmsg                  VARCHAR2(32767);
11265         --
11266         nIdx                    NUMBER := 0;
11267         TYPE Del_ID_TBL_type is Table of IEX_DELINQUENCIES_ALL.DELINQUENCY_ID%TYPE
11268                                 INDEX BY BINARY_INTEGER;
11269         Del_Tbl                 Del_ID_TBL_TYPE;
11270         l_bind_tbl              IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
11271         l_bind_rec              IEX_DUNNING_PVT.FULFILLMENT_BIND_REC;
11272         l_org_id                NUMBER ;
11273         --l_delid_tbl             IEX_DUNNING_PUB.DelId_NumList;
11274         l_del_tbl               IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE;
11275         l_ffm_cnt               NUMBER := 0;
11276         l_dunn_cnt              NUMBER := 0;
11277         l_bucket                VARCHAR2(100);
11278         i                       NUMBER := 0;
11279         l_running_level         VARCHAR2(25);
11280         l_object_Code           VARCHAR2(25);
11281         l_object_id             NUMBER;
11282         l_curr_dmethod          VARCHAR2(10);
11283         l_contact_destination         varchar2(240);  -- bug 3955222
11284         l_contact_party_id            number; -- bug 3955222
11285         --Start adding for bug 9156833 gnramasa 27th Nov 09
11286         l_validation_level		  NUMBER ;
11287         l_resource_tab		  iex_utilities.resource_tab_type;
11288         l_resource_id		  NUMBER;
11289         --End adding for bug 9156833 gnramasa 27th Nov 09
11290 
11291         l_grace_days                  number := 0;
11292         l_use_grace_days              varchar2(10);
11293         l_dun_disputed_items          varchar2(10);
11294         l_ag_dn_xref_id                NUMBER ;
11295         l_as_of_date                  date;
11296 
11297          cursor c_as_of_date  (p_dunning_id number) is
11298         select  nvl(dunn.as_of_date,sysdate)
11299         from iex_dunnings dunn
11300         where dunning_id = p_dunning_id;
11301 
11302     BEGIN
11303           -- Standard Start of API savepoint
11304           SAVEPOINT Resend_DUNNING_PVT;
11305 
11306           --Bug#4679639 schekuri 20-OCT-2005
11307           --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
11308           --l_org_id := fnd_profile.value('ORG_ID');
11309           l_org_id:= mo_global.get_current_org_id;
11310 
11311           -- Standard call to check for call compatibility.
11312           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
11313                                                p_api_version,
11314                                                l_api_name,
11315                                                G_PKG_NAME)
11316           THEN
11317               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
11318           END IF;
11319 
11320           -- Initialize message list if p_init_msg_list is set to TRUE.
11321           IF FND_API.to_Boolean( p_init_msg_list )
11322           THEN
11323               FND_MSG_PUB.initialize;
11324           END IF;
11325 
11326           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
11327 
11328           -- Initialize API return status to SUCCESS
11329           x_return_status := FND_API.G_RET_STS_SUCCESS;
11330 
11331           --dont write into FND_FILE
11332           --l_write := 0;
11333 
11334           --
11335           -- Api body
11336           --
11337 
11338           -- only one del record
11339           i := 1;
11340 
11341           l_delinquency_id := p_delinquencies_tbl(i).delinquency_id;
11342           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==================');
11343           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_Id);
11344 
11345           -- Validate Data
11346 
11347          /*=============================================================
11348           *  For each Delinquency,
11349           *=============================================================*/
11350 
11351           Open C_Get_DEL(l_delinquency_id);
11352           Fetch C_Get_DEL into
11353                    l_delinquency_id,
11354                    l_party_cust_id,
11355                    l_account_id,
11356                    l_customer_site_use_id,
11357                    l_score;
11358 
11359           If ( C_GET_DEL%NOTFOUND) Then
11360                WriteLog('iexvdunb.pls:ResendDunn:No Open Del');
11361 
11362           else
11363 
11364             WriteLog('iexvdunb.pls:ResendDunn:open del='||l_delinquency_Id);
11365 
11366             /*===============================================================
11367              * IsDispute ?
11368              * If yes => stop (exit);
11369              * else continue;
11370              *
11371              * it returns values :
11372              * 1) it returns 'F' if no dispute exists for the delinquency
11373              * 2) it returns 'T' if dispute exists and is pending
11374              * 3) it returns 'F' if dispute exists and its staus is "COMPLETE"
11375              *==============================================================*/
11376 
11377             WriteLog('iexvdunb.pls:ResendDunn:Chk IsDispute');
11378 
11379             IEX_DISPUTE_PVT.Is_Delinquency_Dispute(p_api_version              => p_api_version
11380     			 														            , p_init_msg_list            => p_init_msg_list
11381     			 														            , p_delinquency_id           => l_delinquency_id
11382     			 														            , x_return_status            => x_return_status
11383     			 														            , x_msg_count                => x_msg_count
11384     			 														            , x_msg_data                 => x_msg_data);
11385 
11386             IF x_return_status = 'T' THEN
11387                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Dispute exists and is pending');
11388                GOTO end_loop;
11389             elsif x_return_status = 'F' THEN
11390                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Dispute or status is COMPLETE');
11391             END IF;
11392 
11393             -- init msg (not from dispute api)
11394             FND_MSG_PUB.initialize;
11395 
11396            /*===========================================
11397             * Get Score From IEX_SCORE_HISTORIES
11398             * If NotFound => Call API to getScore;
11399             *===========================================*/
11400             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Score='|| l_score);
11401            /*===========================================
11402             * get Aging_Bucket_Line_Id for each Del
11403             *===========================================*/
11404 
11405            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetAgingBucketLineId');
11406            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
11407 
11408               AGING_DEL(p_api_version              => p_api_version
11409     			              , p_init_msg_list            => p_init_msg_list
11410     			              , p_commit                   => p_commit
11411     			              , p_delinquency_id           => l_delinquency_id
11412     			              , p_dunning_plan_id          => p_dunning_plan_id
11413     			              , p_bucket                   => l_bucket
11414     			              , x_return_status            => x_return_status
11415     			              , x_msg_count                => x_msg_count
11416     			              , x_msg_data                 => x_msg_data
11417     			              , x_aging_bucket_line_id     => l_bucket_line_id);
11418 
11419            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - AgingDel status='||x_return_status);
11420 
11421            IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
11422              FND_MESSAGE.Set_Name('IEX', 'IEX_NO_AGINGBUCKETLINE');
11423              FND_MSG_PUB.Add;
11424              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Get AgingBucketLineId');
11425              GOTO end_loop;
11426            END IF;
11427 
11428            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - lineid='||l_bucket_line_id);
11429            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndAgingDel');
11430 
11431            /*==========================================
11432            * Get Template_ID From iex_ag_dn_xref
11433            *===========================================*/
11434 
11435            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template');
11436 
11437            Open C_Get_TEMPLATE(l_bucket_line_ID, l_score, p_dunning_plan_id);
11438            Fetch C_Get_TEMPLATE into
11439                  l_ag_dn_xref_id,
11440                  l_template_id,
11441                  l_xdo_template_id,
11442                  l_method,
11443                  l_callback_flag,
11444                  l_callback_days,
11445                  l_bucket;
11446 
11447            If ( C_GET_TEMPLATE%NOTFOUND) Then
11448                FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
11449                FND_MSG_PUB.Add;
11450                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template notfound');
11451                Close C_Get_TEMPLATE;
11452                GOTO end_loop;
11453            END IF;
11454 
11455            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - close C_GET_TEMPLATE');
11456            Close C_Get_TEMPLATE;
11457 
11458            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get template_id='||l_template_id);
11459            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get xdo_template_id='||l_xdo_template_id);
11460            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get bucket='||l_bucket);
11461 
11462            /*===========================================
11463                * Check the status of the template
11464                *===========================================*/
11465 
11466                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template status');
11467                Open C_TEMPLATE_STATUS(l_xdo_template_id);
11468                Fetch C_TEMPLATE_STATUS into l_template_status;
11469 
11470                If ( C_TEMPLATE_STATUS%NOTFOUND) Then
11471 
11472     		open C_TEMPLATE_NAME (l_xdo_template_id);
11473     		Fetch C_TEMPLATE_NAME into l_template_name;
11474     		close C_TEMPLATE_NAME;
11475 
11476     		FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
11477                     FND_MSG_PUB.Add;
11478                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
11479     	        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
11480     	        RAISE FND_API.G_EXC_ERROR;
11481     	   END IF;
11482                Close C_TEMPLATE_STATUS;
11483     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
11484 
11485           /*===========================================
11486            * Check template
11487            *  in 11.5.11, IEX supports fulfillment and xml publisher.
11488            *  if the current setup for delivery id FFM,
11489            *  then template_id is necessary;
11490            *  if XML, xdo_template_id is necessary;
11491            *===========================================*/
11492 
11493            l_curr_dmethod := IEX_SEND_XML_PVT.getCurrDeliveryMethod;
11494            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - curr d_method='||l_curr_dmethod);
11495            if ( (l_curr_dmethod is null or l_curr_dmethod = '') or
11496                 (l_curr_dmethod = 'FFM' and l_template_id is null)  or
11497                 (l_curr_dmethod = 'XML' and l_xdo_template_id is null ) ) then
11498                 FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
11499                 FND_MSG_PUB.Add;
11500                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template notfound');
11501                 x_return_status := FND_API.G_RET_STS_ERROR;
11502                 GOTO end_loop;
11503            end if;
11504 
11505            open c_dunning_plan_dtl (p_dunning_plan_id);
11506     		 fetch c_dunning_plan_dtl into l_use_grace_days, l_dun_disputed_items;
11507     		 close c_dunning_plan_dtl;
11508     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_use_grace_days :'|| l_use_grace_days);
11509     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_dun_disputed_items :'|| l_dun_disputed_items);
11510 
11511     		 if l_use_grace_days = 'Y' then
11512     			 iex_utilities.get_grace_days(p_api_version => p_api_version,
11513     					       p_init_msg_list     => FND_API.G_TRUE,
11514     					       p_commit            => FND_API.G_FALSE,
11515     					       p_validation_level  => l_validation_level,
11516     					       p_level             => l_running_level,
11517     					       p_party_id          => l_party_cust_id,
11518     					       p_account_id        => l_account_id,
11519     					       p_site_use_id       => l_customer_site_use_id,
11520     					       x_msg_count         => l_msg_count,
11521     					       x_msg_data          => l_msg_data,
11522     					       x_return_status     => l_return_status,
11523     					       x_grace_days        => l_grace_days);
11524     			 IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
11525     			     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get grace days');
11526     			     x_return_status := FND_API.G_RET_STS_ERROR;
11527     			 END IF;
11528     		 end if;
11529     		 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_grace_days :'|| l_grace_days);
11530 
11531     	open c_as_of_date (p_dunning_id);
11532             fetch c_as_of_date into l_as_of_date;
11533             close c_as_of_date;
11534 
11535           /*===========================================
11536            * Check profile before send dunning
11537            *===========================================*/
11538 
11539            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - begin check customer profile');
11540             -- ctlee - check the hz_customer_profiles.dunning_letter
11541            if ( iex_utilities.DunningProfileCheck (
11542                    p_party_id => l_party_cust_id
11543                    , p_cust_account_id => l_account_id
11544                    , p_site_use_id => l_customer_site_use_id
11545                    , p_delinquency_id => l_delinquency_id     ) = 'N'
11546               ) then
11547                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_PROFILE_NO');
11548                 FND_MSG_PUB.Add;
11549                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send dunning in customer profile set to no ');
11550                 GOTO end_loop;
11551            end if;
11552 
11553            -- ctlee - check the hz_customer_profiles_amt min_dunning_invoice_amount and min_dunning_amount
11554         /*   if ( iex_utilities.DunningMinAmountCheck (
11555                     p_cust_account_id => l_account_id
11556                     , p_site_use_id => l_customer_site_use_id
11557     		, p_org_id => l_org_id, p_grace_days => l_grace_days
11558     		    , p_dun_disputed_items => l_dun_disputed_items)  = 'N'  --Added for Bug 10401991 20-Jan-2011 barathsr
11559               ) then
11560               */
11561               -- start bug 15933013
11562            if ( iex_utilities.DunningMinAmountCheck (
11563                       p_cust_account_id => l_account_id
11564                     , p_site_use_id => l_customer_site_use_id
11565                     , p_delinquency_id => l_delinquency_id
11566     		            , p_org_id => l_org_id
11567                     , p_grace_days => l_grace_days
11568     		            , p_dun_disputed_items => l_dun_disputed_items
11569                     , p_running_level => l_running_level) <> 'Y'
11570               ) then --end bug 15933013
11571                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
11572                 FND_MSG_PUB.Add;
11573                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Required min Dunning amount in customer profile ');
11574                 GOTO end_loop;
11575            end if;
11576 
11577            WriteLog('iexvdunb:ResendDunn: end check customer profile');
11578 
11579            /*===========================================
11580             * Send Letter through Fulfillment
11581             *===========================================*/
11582 
11583             WriteLog('iexvdunb.pls:ResendDunn:Send_Ffm');
11584             WriteLog('iexvdunb.pls:ResendDunn:orgid='||l_org_id);
11585             WriteLog('iexvdunb.pls:ResendDunn:partyid='||l_party_cust_id);
11586             WriteLog('iexvdunb.pls:ResendDunn:acctid='||l_account_id);
11587             WriteLog('iexvdunb.pls:ResendDunn:lineid='||l_bucket_line_id);
11588             WriteLog('iexvdunb.pls:ResendDunn:delid='||l_delinquency_id);
11589 
11590             l_bind_rec.key_name := 'party_id';
11591             l_bind_rec.key_type := 'NUMBER';
11592             l_bind_rec.key_value := l_party_cust_id;
11593             l_bind_tbl(1) := l_bind_rec;
11594     	--Begin Bug 10401991 20-Jan-2011 barathsr
11595             l_bind_rec.key_name := 'org_id';
11596             l_bind_rec.key_type := 'NUMBER';
11597             l_bind_rec.key_value := l_org_id;
11598     	--End Bug 10401991 20-Jan-2011 barathsr
11599             l_bind_tbl(2) := l_bind_rec;
11600             l_bind_rec.key_name := 'bucket_line_id';
11601             l_bind_rec.key_type := 'NUMBER';
11602             l_bind_rec.key_value := l_bucket_line_id;
11603             l_bind_tbl(3) := l_bind_rec;
11604             l_bind_rec.key_name := 'account_id';
11605             l_bind_rec.key_type := 'NUMBER';
11606             l_bind_rec.key_value := l_account_id;
11607             l_bind_tbl(4) := l_bind_rec;
11608             l_bind_rec.key_name := 'delinquency_id';
11609             l_bind_rec.key_type := 'NUMBER';
11610             l_bind_rec.key_value := l_delinquency_id;
11611             l_bind_tbl(5) := l_bind_rec;
11612             -- added for BILL_TO in 11.5.10
11613             l_bind_rec.key_name := 'customer_site_use_id';
11614             l_bind_rec.key_type := 'NUMBER';
11615             l_bind_rec.key_value := l_customer_site_use_id;
11616             l_bind_tbl(6) := l_bind_rec;
11617     		l_bind_rec.key_name := 'DUNNING_ID';
11618             l_bind_rec.key_type := 'NUMBER';
11619     		l_bind_rec.key_value := p_dunning_id;
11620             l_bind_tbl(7) := l_bind_rec;
11621 
11622     	 --Start adding for bug 9156833 gnramasa 27th Nov 09
11623     	 l_validation_level := FND_API.G_VALID_LEVEL_FULL;
11624 
11625     	 iex_utilities.get_dunning_resource(p_api_version => p_api_version,
11626     			       p_init_msg_list     => FND_API.G_TRUE,
11627     			       p_commit            => FND_API.G_FALSE,
11628     			       p_validation_level  => l_validation_level,
11629     			       p_level             => 'DUNNING_BILLTO',
11630     			       p_level_id          => l_customer_site_use_id,
11631     			       x_msg_count         => l_msg_count,
11632     			       x_msg_data          => l_msg_data,
11633     			       x_return_status     => l_return_status,
11634     			       x_resource_tab      => l_resource_tab);
11635     	 IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
11636     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
11637     	     x_return_status := FND_API.G_RET_STS_ERROR;
11638     	 END IF;
11639 
11640     	  if l_resource_tab.count>0 then
11641     	    l_resource_id := l_resource_tab(1).resource_id;
11642     	  end if;
11643     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_resource_id: ' || l_resource_id);
11644     	  --End adding for bug 9156833 gnramasa 27th Nov 09
11645               WriteLog( ' before send_xml org_id '|| p_org_id);
11646             /**
11647              * in 11.5.11, IEX supports fulfillment and xml publisher.
11648              * it depends on the set up in IEX ADMIN/SETUP.
11649              */
11650 
11651             if (l_curr_dmethod = 'FFM') then
11652 
11653               Send_Fulfillment(
11654                 p_api_version              => p_api_version
11655               , p_init_msg_list            => p_init_msg_list
11656               , p_commit                   => p_commit
11657               , p_fulfillment_bind_tbl     => l_bind_tbl
11658               , p_template_id              => l_template_id
11659               , p_method                   => l_method
11660               , p_party_id                 => l_party_cust_id
11661               , x_request_id               => l_request_id
11662               , x_return_status            => x_return_status
11663               , x_msg_count                => x_msg_count
11664               , x_msg_data                 => x_msg_data
11665               , x_contact_destination      => l_contact_destination  -- bug 3955222
11666               , x_contact_party_id         => l_contact_party_id  -- bug 3955222
11667               );
11668 
11669             else
11670               l_running_level := 'DELINQUENCY';
11671               l_object_code := 'IEX_DELINQUENCY';
11672               l_object_id := l_delinquency_id;
11673 
11674               Send_XML(
11675                 p_api_version              => p_api_version
11676               , p_init_msg_list            => p_init_msg_list
11677               , p_commit                   => p_commit
11678               , p_resend                   => 'N'
11679               , p_request_id               => null
11680               , p_fulfillment_bind_tbl     => l_bind_tbl
11681               , p_template_id              => l_xdo_template_id
11682               , p_method                   => l_method
11683               , p_party_id                 => l_party_cust_id
11684               , p_level                    => l_running_level
11685               , p_source_id                => l_object_id
11686               , p_object_code              => l_object_code
11687               , p_object_id                => l_object_id
11688     	  , p_resource_id              => l_resource_id --Added for bug 9156833 gnramasa 27th Nov 09
11689               , p_org_id                   => p_org_id   -- added for bug 9151851
11690     	  , x_request_id               => l_request_id
11691               , x_return_status            => x_return_status
11692               , x_msg_count                => x_msg_count
11693               , x_msg_data                 => x_msg_data
11694               , x_contact_destination      => l_contact_destination  -- bug 3955222
11695               , x_contact_party_id         => l_contact_party_id  -- bug 3955222
11696               );
11697            end if;
11698 
11699            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - send status='|| x_return_status);
11700 
11701            IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
11702              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Sending process failed');
11703              GOTO end_loop;
11704            END IF;
11705 
11706            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||l_request_id);
11707            l_ffm_cnt := l_ffm_cnt + 1;
11708 
11709            /*===========================================
11710             * Close OPEN Dunnings for each Del
11711             *===========================================*/
11712 
11713            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning');
11714            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - runninglevel=DELINQUENCY');
11715            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
11716            l_del_tbl(1).delinquency_id := l_delinquency_id;
11717 
11718            Close_DUNNING(
11719                p_api_version              => p_api_version
11720              , p_init_msg_list            => p_init_msg_list
11721              , p_commit                   => p_commit
11722              , p_delinquencies_tbl        => l_del_tbl
11723              , p_running_level            => 'DELINQUENCY'
11724              , x_return_status            => x_return_status
11725              , x_msg_count                => x_msg_count
11726              , x_msg_data                 => x_msg_data);
11727 
11728            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning status='|| x_return_status);
11729 
11730            IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
11731               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Close Dunning');
11732               GOTO end_loop;
11733            END IF;
11734            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndCloseDunn');
11735 
11736            /*===========================================
11737             * Create Dunning Record
11738             *===========================================*/
11739 
11740            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get CallbackDate');
11741            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag='||l_callback_flag);
11742            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDays='||l_callback_days);
11743 
11744           /*===================================================
11745            * clchang updated 02/13/2003
11746            * callback_days could be null if callback_yn = 'N';
11747            * and if callback_yn = 'N', not get callback_date;
11748            *==================================================*/
11749            IF (l_callback_flag = 'Y') THEN
11750               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is Y: NOTGetCallbackDate');
11751               Get_Callback_Date( p_init_msg_list          => p_init_msg_list
11752                           , p_callback_days          => l_callback_days
11753                           , x_callback_date          => l_callback_date
11754                           , x_return_status          => x_return_status
11755                           , x_msg_count              => x_msg_count
11756                           , x_msg_data               => x_msg_data);
11757 
11758               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetCallbackDate status='|| x_return_status);
11759               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDate='||l_callback_date);
11760 
11761               IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
11762                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Get CallbackDate');
11763                 GOTO end_loop;
11764               END IF;
11765 
11766            ELSE
11767               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is N: NOTGetCallbackDate');
11768            END IF;
11769 
11770            /* get the current amount_due_remaining and currency_code */
11771            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET AMOUNT');
11772 
11773            Open C_AMOUNT(l_delinquency_id);
11774            Fetch C_AMOUNT into
11775                l_amount,
11776                l_curr_code;
11777 
11778            If ( C_AMOUNT%NOTFOUND) Then
11779               FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
11780               FND_MESSAGE.Set_Token ('INFO', 'amount', FALSE);
11781               FND_MSG_PUB.Add;
11782               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount notfound');
11783            END IF;
11784 
11785            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - close C_AMOUNT');
11786            Close C_AMOUNT;
11787 
11788            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get amount='||l_amount);
11789            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get currcode='||l_curr_code);
11790            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning');
11791            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
11792            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id='||l_delinquency_id);
11793 
11794            l_dunning_rec.delinquency_id := l_delinquency_id;
11795            l_dunning_rec.callback_yn := l_callback_flag;
11796            l_dunning_rec.callback_date := l_callback_date;
11797            l_dunning_rec.status := 'OPEN';
11798            l_dunning_rec.dunning_method:= l_method;
11799            if (l_curr_dmethod = 'FFM') then
11800              l_dunning_rec.template_id:= l_template_id;
11801              l_dunning_rec.ffm_request_id := l_request_id;
11802            else
11803              l_dunning_rec.xml_template_id:= l_xdo_template_id;
11804              l_dunning_rec.xml_request_id := l_request_id;
11805            end if;
11806            l_dunning_rec.campaign_sched_id := l_campaign_sched_id;
11807            l_dunning_rec.dunning_object_id := l_delinquency_id;
11808            l_dunning_rec.dunning_level := 'DELINQUENCY';
11809            l_dunning_rec.amount_due_remaining := l_amount;
11810            l_dunning_rec.currency_code := l_curr_code;
11811            l_dunning_rec.object_type := 'IEX_DELINQUENCY';
11812            l_dunning_rec.object_id := l_delinquency_id;
11813            l_dunning_rec.dunning_plan_id := p_dunning_plan_id;
11814            l_dunning_rec.contact_destination := l_contact_destination;  -- bug 3955222
11815            l_dunning_rec.contact_party_id := l_contact_party_id;  -- bug 3955222
11816 
11817            l_dunning_rec.org_id := p_org_id;
11818            l_dunning_rec.as_of_date := l_as_of_date;
11819            l_dunning_rec.parent_dunning_id := p_dunning_id;
11820            WriteLog(' before creating dunning org_id ' || p_org_id);
11821            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
11822 
11823            CREATE_DUNNING(
11824              p_api_version              => p_api_version
11825            , p_init_msg_list            => p_init_msg_list
11826            , p_commit                   => p_commit
11827            , p_dunning_rec              => l_dunning_rec
11828            , x_dunning_id               => l_dunning_id
11829            , x_return_status            => x_return_status
11830            , x_msg_count                => x_msg_count
11831            , x_msg_data                 => x_msg_data);
11832 
11833            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| x_return_status);
11834 
11835            IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
11836              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
11837              GOTO end_loop;
11838     	 else
11839 
11840     	 INSERT_DUNNING_TRANSACTION(
11841     				p_api_version              => p_api_version
11842     			      , p_init_msg_list            => p_init_msg_list
11843     			      , p_commit                   => p_commit
11844     			      , p_delinquencies_tbl        => l_del_tbl
11845     			      , p_ag_dn_xref_id	           => l_ag_dn_xref_id
11846     			      , p_dunning_id               => l_dunning_id
11847     			      , p_correspondence_date      => l_as_of_date
11848     			      , p_running_level            => l_running_level
11849     			      , p_grace_days               => l_grace_days
11850     			      , p_include_dispute_items    => l_dun_disputed_items
11851     			      , x_return_status            => x_return_status
11852     			      , x_msg_count                => x_msg_count
11853     			      , x_msg_data                 => x_msg_data
11854                               ,p_workitem_id               => null);  -- bug 14772139
11855 
11856 
11857            END IF;
11858 
11859            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningId='||l_dunning_id);
11860            l_dunn_cnt := l_dunn_cnt + 1;
11861 
11862            /*===========================================
11863             * Update Delinquency
11864             * Set DUNN_YN = 'N'
11865             *===========================================*/
11866 
11867              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UpdateDel');
11868 
11869              nIdx := nIdx + 1;
11870              del_tbl(nIdx) := l_delinquency_id;
11871 
11872            <<end_loop>>
11873            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_loop');
11874            NULL;
11875 
11876          END IF;
11877 
11878          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close C_GET_DEL');
11879 
11880          Close C_Get_DEL;
11881 
11882          x_request_id := l_request_id;
11883 
11884          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========Summarty==========');
11885          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SendFFM Cnt='||l_ffm_cnt);
11886          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunn Cnt='||l_dunn_cnt);
11887          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||x_request_id);
11888          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========End Summarty==========');
11889 
11890           --
11891           -- End of API body
11892           --
11893 
11894           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return status='||x_return_status);
11895           IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
11896               RAISE FND_API.G_EXC_ERROR;
11897           elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
11898               raise FND_API.G_EXC_UNEXPECTED_ERROR;
11899           END IF;
11900 
11901           -- Standard check for p_commit
11902           IF FND_API.to_Boolean( p_commit )
11903           THEN
11904               COMMIT WORK;
11905           END IF;
11906 
11907           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return status='||x_return_status);
11908           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
11909 
11910           FND_MSG_PUB.Count_And_Get
11911           (  p_count          =>   x_msg_count,
11912              p_data           =>   x_msg_data );
11913 
11914           EXCEPTION
11915               WHEN FND_API.G_EXC_ERROR THEN
11916                   x_return_status := FND_API.G_RET_STS_ERROR;
11917                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
11918                   FND_MSG_PUB.Count_And_Get
11919                   (  p_count          =>   x_msg_count,
11920                      p_data           =>   x_msg_data );
11921                   errmsg := SQLERRM;
11922                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||errmsg);
11923                   ROLLBACK TO Resend_DUNNING_PVT;
11924 
11925               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
11926                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
11927                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
11928                   FND_MSG_PUB.Count_And_Get
11929                   (  p_count          =>   x_msg_count,
11930                      p_data           =>   x_msg_data );
11931                   errmsg := SQLERRM;
11932                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||errmsg);
11933                   ROLLBACK TO Resend_DUNNING_PVT;
11934 
11935               WHEN OTHERS THEN
11936                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
11937                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
11938                   FND_MSG_PUB.Count_And_Get
11939                   (  p_count          =>   x_msg_count,
11940                      p_data           =>   x_msg_data );
11941                   errmsg := SQLERRM;
11942                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||errmsg);
11943                   ROLLBACK TO Resend_DUNNING_PVT;
11944 
11945     END Resend_Dunning;
11946 
11947     Procedure Resend_Staged_Dunning
11948                (p_api_version             IN NUMBER := 1.0,
11949                 p_init_msg_list           IN VARCHAR2 ,
11950                 p_commit                  IN VARCHAR2 ,
11951                 p_dunning_plan_id         in number,
11952     	    p_dunning_id              in number,
11953                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
11954     	    p_org_id                  in number,
11955                 x_request_id              OUT NOCOPY NUMBER,
11956                 x_return_status           OUT NOCOPY VARCHAR2,
11957                 x_msg_count               OUT NOCOPY NUMBER,
11958                 x_msg_data                OUT NOCOPY VARCHAR2)
11959     IS
11960 
11961         CURSOR C_GET_DEL (IN_del_ID NUMBER) IS
11962           SELECT delinquency_ID,
11963                  party_cust_id,
11964                  cust_account_id,
11965                  customer_site_use_id,
11966                  score_value
11967             FROM IEX_DELINQUENCIES
11968            WHERE delinquency_ID = in_del_ID;
11969     /*
11970         --
11971         CURSOR C_GET_SCORE (IN_ID NUMBER) IS
11972           SELECT a.score_value
11973             FROM IEX_SCORE_HISTORIES a
11974            WHERE a.score_object_ID = in_ID
11975              AND a.score_object_code = 'IEX_DELINQUENCY'
11976              AND a.creation_date = (select max(b.creation_date)
11977                                       from iex_score_histories b
11978                                      where b.score_object_id = in_id
11979                                        AND b.score_object_code = 'IEX_DELINQUENCY');
11980         --
11981         --
11982         CURSOR C_GET_TEMPLATE (l_line_id NUMBER,
11983                                l_score NUMBER, p_dunning_plan_id number) IS
11984           SELECT x.template_id,
11985                  x.xdo_template_id,
11986                  x.fm_method,
11987                  upper(x.callback_flag),
11988                  x.callback_days,
11989                  ar.bucket_name
11990             FROM IEX_AG_DN_XREF x,
11991                  ar_aging_buckets ar,
11992                  iex_dunning_plans_vl d
11993            WHERE x.aging_bucket_line_ID = l_line_ID
11994              and x.dunning_plan_id = p_dunning_plan_id
11995              AND l_score between x.score_range_low and x.score_range_high
11996              AND x.aging_bucket_id = ar.aging_bucket_id
11997              and ar.aging_bucket_id = d.aging_bucket_id
11998              AND ar.status = 'A'
11999              AND x.dunning_level = 'DELINQUENCY' ;
12000     */
12001          CURSOR C_TEMPLATE_STATUS (l_template_id number) is
12002          select 'Active'
12003          from xdo_templates_vl xdo
12004          where xdo.template_id = l_template_id
12005          and trunc(sysdate) >= TRUNC (NVL(xdo.start_date, sysdate))
12006          and trunc(sysdate) < TRUNC(NVL(xdo.end_date, sysdate + 1));
12007 
12008          l_template_status		  varchar2(10);
12009 
12010          CURSOR C_TEMPLATE_NAME (l_template_id number) is
12011          select template_name
12012          from xdo_templates_vl xdo
12013          where xdo.template_id = l_template_id;
12014 
12015          l_template_name	varchar2(500);
12016 
12017         --
12018         cursor c_amount (IN_ID number) is
12019          select ps.amount_due_remaining,
12020                 ps.invoice_currency_code
12021            from ar_payment_schedules_all ps,
12022                 --iex_delinquencies_all del
12023                 iex_delinquencies del
12024           where ps.payment_schedule_id (+)= del.payment_schedule_id
12025             and del.delinquency_id = in_id;
12026         --
12027 
12028         l_AMOUNT                NUMBER;
12029         l_CURR_CODE             VARCHAR2(15);
12030         l_DUNNING_id            NUMBER;
12031         l_delinquency_id        NUMBER;
12032         l_party_cust_id         NUMBER;
12033         l_account_id            NUMBER;
12034         l_customer_site_use_id  NUMBER;
12035         l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
12036         l_score                 NUMBER;
12037         l_bucket_line_id        NUMBER;
12038         l_campaign_sched_id     NUMBER;
12039         l_template_id           NUMBER;
12040         l_xdo_template_id       NUMBER;
12041         l_method                VARCHAR2(10);
12042         l_callback_flag         VARCHAR2(1);
12043         l_callback_days         NUMBER;
12044         l_callback_date         DATE;
12045         l_request_id            NUMBER;
12046         l_outcome_code          varchar2(20);
12047         l_api_name              CONSTANT VARCHAR2(30) := 'Resend_Staged_Dunning';
12048         l_api_version_number    CONSTANT NUMBER   := 1.0;
12049         l_return_status         VARCHAR2(1);
12050         l_msg_count             NUMBER;
12051         l_msg_data              VARCHAR2(32767);
12052         errmsg                  VARCHAR2(32767);
12053         --
12054         nIdx                    NUMBER := 0;
12055         TYPE Del_ID_TBL_type is Table of IEX_DELINQUENCIES_ALL.DELINQUENCY_ID%TYPE
12056                                 INDEX BY BINARY_INTEGER;
12057         Del_Tbl                 Del_ID_TBL_TYPE;
12058         l_bind_tbl              IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
12059         l_bind_rec              IEX_DUNNING_PVT.FULFILLMENT_BIND_REC;
12060         l_org_id                NUMBER ;
12061         --l_delid_tbl             IEX_DUNNING_PUB.DelId_NumList;
12062         l_del_tbl               IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE;
12063         l_ffm_cnt               NUMBER := 0;
12064         l_dunn_cnt              NUMBER := 0;
12065         l_bucket                VARCHAR2(100);
12066         i                       NUMBER := 0;
12067         l_running_level         VARCHAR2(25) := 'DELINQUENCY';
12068         l_object_Code           VARCHAR2(25);
12069         l_object_id             NUMBER;
12070         l_curr_dmethod          VARCHAR2(10);
12071         l_contact_destination         varchar2(240);  -- bug 3955222
12072         l_contact_party_id            number; -- bug 3955222
12073 
12074         CURSOR C_GET_DUNNING (in_dunning_id NUMBER) IS
12075         SELECT dunning_object_id,
12076               delinquency_id,
12077               dunning_level,
12078     	  xml_template_id,
12079     	  ag_dn_xref_id,
12080     	  xml_request_id,
12081     	  addt_xml_template_id
12082          FROM iex_dunnings
12083         WHERE dunning_id = in_dunning_id;
12084 
12085         CURSOR C_CALLBACK_DETAILS (p_ag_dn_xref_id number) IS
12086           SELECT x.fm_method,
12087     	     upper(x.callback_flag),
12088                  x.callback_days
12089             FROM IEX_AG_DN_XREF x
12090            WHERE x.ag_dn_xref_id = p_ag_dn_xref_id;
12091 
12092         l_dunning_object_id       number;
12093         l_del_id                  number;
12094         l_dunning_level	      varchar2(20);
12095         l_ag_dn_xref_id	      number;
12096         l_xml_request_id	      number;
12097 
12098         --Start adding for bug 9156833 gnramasa 27th Nov 09
12099         l_validation_level		  NUMBER ;
12100         l_resource_tab		  iex_utilities.resource_tab_type;
12101         l_resource_id		  NUMBER;
12102         --End adding for bug 9156833 gnramasa 27th Nov 09
12103         l_inv_xdo_template_id	  number;
12104         l_as_of_date		  date;
12105 
12106         cursor c_as_of_date  (p_dunning_id number) is
12107         select  nvl(dunn.as_of_date,sysdate)
12108         from iex_dunnings dunn
12109         where dunning_id = p_dunning_id;
12110 
12111         temp_dunning_id number; -- added for bug 16290958
12112 
12113     BEGIN
12114           -- Standard Start of API savepoint
12115           SAVEPOINT Resend_Staged_Dunning_PVT;
12116 
12117           --Bug#4679639 schekuri 20-OCT-2005
12118           --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
12119           --l_org_id := fnd_profile.value('ORG_ID');
12120           l_org_id:= mo_global.get_current_org_id;
12121 
12122           -- Standard call to check for call compatibility.
12123           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
12124                                                p_api_version,
12125                                                l_api_name,
12126                                                G_PKG_NAME)
12127           THEN
12128               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
12129           END IF;
12130 
12131           -- Initialize message list if p_init_msg_list is set to TRUE.
12132           IF FND_API.to_Boolean( p_init_msg_list )
12133           THEN
12134               FND_MSG_PUB.initialize;
12135           END IF;
12136 
12137           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
12138 
12139           -- Initialize API return status to SUCCESS
12140           x_return_status := FND_API.G_RET_STS_SUCCESS;
12141 
12142           --dont write into FND_FILE
12143           --l_write := 0;
12144 
12145           --
12146           -- Api body
12147           --
12148           open C_GET_DUNNING (p_dunning_id);
12149           fetch C_GET_DUNNING into l_dunning_object_id, l_del_id, l_dunning_level, l_xdo_template_id, l_ag_dn_xref_id, l_xml_request_id, l_inv_xdo_template_id;
12150           close C_GET_DUNNING;
12151 
12152           open C_CALLBACK_DETAILS (l_ag_dn_xref_id);
12153           fetch C_CALLBACK_DETAILS into l_method, l_callback_flag, l_callback_days;
12154           close C_CALLBACK_DETAILS;
12155 
12156           -- only one del record
12157           i := 1;
12158 
12159           l_delinquency_id := p_delinquencies_tbl(i).delinquency_id;
12160           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==================');
12161           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_Id);
12162 
12163           -- Validate Data
12164 
12165          /*=============================================================
12166           *  For each Delinquency,
12167           *=============================================================*/
12168 
12169           Open C_Get_DEL(l_delinquency_id);
12170           Fetch C_Get_DEL into
12171                    l_delinquency_id,
12172                    l_party_cust_id,
12173                    l_account_id,
12174                    l_customer_site_use_id,
12175                    l_score;
12176 
12177           If ( C_GET_DEL%NOTFOUND) Then
12178                WriteLog('iexvdunb.pls:ResendDunn:No Open Del');
12179 
12180           else
12181 
12182             WriteLog('iexvdunb.pls:ResendDunn:open del='||l_delinquency_Id);
12183 
12184             /*===============================================================
12185              * IsDispute ?
12186              * If yes => stop (exit);
12187              * else continue;
12188              *
12189              * it returns values :
12190              * 1) it returns 'F' if no dispute exists for the delinquency
12191              * 2) it returns 'T' if dispute exists and is pending
12192              * 3) it returns 'F' if dispute exists and its staus is "COMPLETE"
12193              *==============================================================*/
12194 
12195     /*
12196             WriteLog('iexvdunb.pls:ResendDunn:Chk IsDispute');
12197 
12198             IEX_DISPUTE_PVT.Is_Delinquency_Dispute(p_api_version              => p_api_version
12199     			 														            , p_init_msg_list            => p_init_msg_list
12200     			 														            , p_delinquency_id           => l_delinquency_id
12201     			 														            , x_return_status            => x_return_status
12202     			 														            , x_msg_count                => x_msg_count
12203     			 														            , x_msg_data                 => x_msg_data);
12204 
12205             IF x_return_status = 'T' THEN
12206                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Dispute exists and is pending');
12207                GOTO end_loop;
12208             elsif x_return_status = 'F' THEN
12209                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Dispute or status is COMPLETE');
12210             END IF;
12211 
12212             -- init msg (not from dispute api)
12213             FND_MSG_PUB.initialize;
12214     */
12215            /*===========================================
12216             * Get Score From IEX_SCORE_HISTORIES
12217             * If NotFound => Call API to getScore;
12218             *===========================================*/
12219     --        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Score='|| l_score);
12220            /*===========================================
12221             * get Aging_Bucket_Line_Id for each Del
12222             *===========================================*/
12223     /*
12224            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetAgingBucketLineId');
12225            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
12226 
12227               AGING_DEL(p_api_version              => p_api_version
12228     			              , p_init_msg_list            => p_init_msg_list
12229     			              , p_commit                   => p_commit
12230     			              , p_delinquency_id           => l_delinquency_id
12231     			              , p_dunning_plan_id          => p_dunning_plan_id
12232     			              , p_bucket                   => l_bucket
12233     			              , x_return_status            => x_return_status
12234     			              , x_msg_count                => x_msg_count
12235     			              , x_msg_data                 => x_msg_data
12236     			              , x_aging_bucket_line_id     => l_bucket_line_id);
12237 
12238            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - AgingDel status='||x_return_status);
12239 
12240            IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
12241              FND_MESSAGE.Set_Name('IEX', 'IEX_NO_AGINGBUCKETLINE');
12242              FND_MSG_PUB.Add;
12243              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Get AgingBucketLineId');
12244              GOTO end_loop;
12245            END IF;
12246 
12247            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - lineid='||l_bucket_line_id);
12248            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndAgingDel');
12249     */
12250            /*==========================================
12251            * Get Template_ID From iex_ag_dn_xref
12252            *===========================================*/
12253     /*
12254            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template');
12255 
12256            Open C_Get_TEMPLATE(l_bucket_line_ID, l_score, p_dunning_plan_id);
12257            Fetch C_Get_TEMPLATE into
12258                  l_template_id,
12259                  l_xdo_template_id,
12260                  l_method,
12261                  l_callback_flag,
12262                  l_callback_days,
12263                  l_bucket;
12264 
12265            If ( C_GET_TEMPLATE%NOTFOUND) Then
12266                FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
12267                FND_MSG_PUB.Add;
12268                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template notfound');
12269                Close C_Get_TEMPLATE;
12270                GOTO end_loop;
12271            END IF;
12272 
12273            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - close C_GET_TEMPLATE');
12274            Close C_Get_TEMPLATE;
12275 
12276            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get template_id='||l_template_id);
12277            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get xdo_template_id='||l_xdo_template_id);
12278            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get bucket='||l_bucket);
12279 
12280     */
12281           /*===========================================
12282            * Check template
12283            *  in 11.5.11, IEX supports fulfillment and xml publisher.
12284            *  if the current setup for delivery id FFM,
12285            *  then template_id is necessary;
12286            *  if XML, xdo_template_id is necessary;
12287            *===========================================*/
12288 
12289            l_curr_dmethod := IEX_SEND_XML_PVT.getCurrDeliveryMethod;
12290            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - curr d_method='||l_curr_dmethod);
12291            if ( (l_curr_dmethod is null or l_curr_dmethod = '') or
12292                 (l_curr_dmethod = 'FFM' and l_template_id is null)  or
12293                 (l_curr_dmethod = 'XML' and l_xdo_template_id is null ) ) then
12294                 FND_MESSAGE.Set_Name('IEX', 'IEX_NO_TEMPLATE');
12295                 FND_MSG_PUB.Add;
12296                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template notfound');
12297                 x_return_status := FND_API.G_RET_STS_ERROR;
12298                 GOTO end_loop;
12299            end if;
12300 
12301            /*===========================================
12302                * Check the status of the template
12303                *===========================================*/
12304 
12305                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template status');
12306                Open C_TEMPLATE_STATUS(l_xdo_template_id);
12307                Fetch C_TEMPLATE_STATUS into l_template_status;
12308 
12309                If ( C_TEMPLATE_STATUS%NOTFOUND) Then
12310 
12311     		open C_TEMPLATE_NAME (l_xdo_template_id);
12312     		Fetch C_TEMPLATE_NAME into l_template_name;
12313     		close C_TEMPLATE_NAME;
12314 
12315     		FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
12316                     FND_MSG_PUB.Add;
12317                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
12318     	        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
12319     	        RAISE FND_API.G_EXC_ERROR;
12320     	   END IF;
12321                Close C_TEMPLATE_STATUS;
12322     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
12323 
12324     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Invoice Template status');
12325     	    if l_inv_xdo_template_id is not null then
12326                Open C_TEMPLATE_STATUS(l_inv_xdo_template_id);
12327                Fetch C_TEMPLATE_STATUS into l_template_status;
12328 
12329                If ( C_TEMPLATE_STATUS%NOTFOUND) Then
12330 
12331     		open C_TEMPLATE_NAME (l_inv_xdo_template_id);
12332     		Fetch C_TEMPLATE_NAME into l_template_name;
12333     		close C_TEMPLATE_NAME;
12334 
12335     		FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
12336                     FND_MSG_PUB.Add;
12337                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
12338     	        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
12339     	        RAISE FND_API.G_EXC_ERROR;
12340     	   END IF;
12341                Close C_TEMPLATE_STATUS;
12342     	   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
12343            ELSE
12344     	 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - invoice_copies is N: Dont Send Invoice');
12345           end if;
12346 
12347             open c_as_of_date (p_dunning_id);
12348             fetch c_as_of_date into l_as_of_date;
12349             close c_as_of_date;
12350 
12351           /*===========================================
12352            * Check profile before send dunning
12353            *===========================================*/
12354 
12355            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - begin check customer profile');
12356             -- ctlee - check the hz_customer_profiles.dunning_letter
12357            if ( iex_utilities.DunningProfileCheck (
12358                    p_party_id => l_party_cust_id
12359                    , p_cust_account_id => l_account_id
12360                    , p_site_use_id => l_customer_site_use_id
12361                    , p_delinquency_id => l_delinquency_id     ) = 'N'
12362               ) then
12363                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_PROFILE_NO');
12364                 FND_MSG_PUB.Add;
12365                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Send dunning in customer profile set to no ');
12366                 GOTO end_loop;
12367            end if;
12368 
12369     /*
12370            -- ctlee - check the hz_customer_profiles_amt min_dunning_invoice_amount and min_dunning_amount
12371            if ( iex_utilities.DunningMinAmountCheck (
12372                     p_cust_account_id => l_account_id
12373                     , p_site_use_id => l_customer_site_use_id)  = 'N'
12374               ) then
12375                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_DUNNING_AMOUNT_MIN');
12376                 FND_MSG_PUB.Add;
12377                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Required min Dunning amount in customer profile ');
12378                 GOTO end_loop;
12379            end if;
12380 
12381            WriteLog('iexvdunb:ResendDunn: end check customer profile');
12382     */
12383 
12384            /*===========================================
12385             * Send Letter through Fulfillment
12386             *===========================================*/
12387 
12388             WriteLog('iexvdunb.pls:ResendDunn:Send_Ffm');
12389             WriteLog('iexvdunb.pls:ResendDunn:orgid='||l_org_id);
12390             WriteLog('iexvdunb.pls:ResendDunn:partyid='||l_party_cust_id);
12391             WriteLog('iexvdunb.pls:ResendDunn:acctid='||l_account_id);
12392             --WriteLog('iexvdunb.pls:ResendDunn:lineid='||l_bucket_line_id);
12393             WriteLog('iexvdunb.pls:ResendDunn:delid='||l_delinquency_id);
12394 
12395             l_bind_rec.key_name := 'party_id';
12396             l_bind_rec.key_type := 'NUMBER';
12397             l_bind_rec.key_value := l_party_cust_id;
12398             l_bind_tbl(1) := l_bind_rec;
12399     	--Begin Bug 10401991 20-Jan-2011 barathsr
12400             l_bind_rec.key_name := 'org_id';
12401             l_bind_rec.key_type := 'NUMBER';
12402             l_bind_rec.key_value := l_org_id;
12403     	--End Bug 10401991 20-Jan-2011 barathsr
12404             l_bind_tbl(2) := l_bind_rec;
12405             /*
12406     	l_bind_rec.key_name := 'bucket_line_id';
12407             l_bind_rec.key_type := 'NUMBER';
12408             l_bind_rec.key_value := l_bucket_line_id;
12409             l_bind_tbl(3) := l_bind_rec;
12410     	*/
12411             l_bind_rec.key_name := 'account_id';
12412             l_bind_rec.key_type := 'NUMBER';
12413             l_bind_rec.key_value := l_account_id;
12414             l_bind_tbl(3) := l_bind_rec;
12415             l_bind_rec.key_name := 'delinquency_id';
12416             l_bind_rec.key_type := 'NUMBER';
12417             l_bind_rec.key_value := l_delinquency_id;
12418             l_bind_tbl(4) := l_bind_rec;
12419             -- added for BILL_TO in 11.5.10
12420             l_bind_rec.key_name := 'customer_site_use_id';
12421             l_bind_rec.key_type := 'NUMBER';
12422             l_bind_rec.key_value := l_customer_site_use_id;
12423             l_bind_tbl(5) := l_bind_rec;
12424     	l_bind_rec.key_name := 'DUNNING_ID';
12425             l_bind_rec.key_type := 'NUMBER';
12426             l_bind_rec.key_value := p_dunning_id;
12427             l_bind_tbl(6) := l_bind_rec;
12428 
12429     	--Start adding for bug 9156833 gnramasa 27th Nov 09
12430     	 l_validation_level := FND_API.G_VALID_LEVEL_FULL;
12431 
12432     	 iex_utilities.get_dunning_resource(p_api_version => p_api_version,
12433     			       p_init_msg_list     => FND_API.G_TRUE,
12434     			       p_commit            => FND_API.G_FALSE,
12435     			       p_validation_level  => l_validation_level,
12436     			       p_level             => 'DUNNING_BILLTO',
12437     			       p_level_id          => l_customer_site_use_id,
12438     			       x_msg_count         => l_msg_count,
12439     			       x_msg_data          => l_msg_data,
12440     			       x_return_status     => l_return_status,
12441     			       x_resource_tab      => l_resource_tab);
12442     	 IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
12443     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
12444     	     x_return_status := FND_API.G_RET_STS_ERROR;
12445     	 END IF;
12446 
12447     	  if l_resource_tab.count>0 then
12448     	    l_resource_id := l_resource_tab(1).resource_id;
12449     	  end if;
12450     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_resource_id: ' || l_resource_id);
12451     	  --End adding for bug 9156833 gnramasa 27th Nov 09
12452 
12453     	WriteLog( G_PKG_NAME || ' ' || l_api_name || ' before send_xml org_id '|| p_org_id);
12454 
12455             /**
12456              * in 11.5.11, IEX supports fulfillment and xml publisher.
12457              * it depends on the set up in IEX ADMIN/SETUP.
12458              */
12459 
12460             if (l_curr_dmethod = 'FFM') then
12461 
12462               Send_Fulfillment(
12463                 p_api_version              => p_api_version
12464               , p_init_msg_list            => p_init_msg_list
12465               , p_commit                   => p_commit
12466               , p_fulfillment_bind_tbl     => l_bind_tbl
12467               , p_template_id              => l_template_id
12468               , p_method                   => l_method
12469               , p_party_id                 => l_party_cust_id
12470               , x_request_id               => l_request_id
12471               , x_return_status            => x_return_status
12472               , x_msg_count                => x_msg_count
12473               , x_msg_data                 => x_msg_data
12474               , x_contact_destination      => l_contact_destination  -- bug 3955222
12475               , x_contact_party_id         => l_contact_party_id  -- bug 3955222
12476               );
12477 
12478             else
12479               l_running_level := 'DELINQUENCY';
12480               l_object_code := 'IEX_DELINQUENCY';
12481               l_object_id := l_delinquency_id;
12482 
12483               Send_XML(
12484                 p_api_version              => p_api_version
12485               , p_init_msg_list            => p_init_msg_list
12486               , p_commit                   => p_commit
12487               , p_resend                   => 'Y'
12488               , p_request_id               => l_xml_request_id
12489               , p_fulfillment_bind_tbl     => l_bind_tbl
12490               , p_template_id              => l_xdo_template_id
12491               , p_method                   => l_method
12492               , p_party_id                 => l_party_cust_id
12493               , p_level                    => l_running_level
12494               , p_source_id                => l_object_id
12495               , p_object_code              => l_object_code
12496               , p_object_id                => l_object_id
12497     	  , p_resource_id              => l_resource_id --Added for bug 9156833 gnramasa 27th Nov 09
12498     	  , p_org_id                   => p_org_id
12499     	  , p_addt_template_id	       => l_inv_xdo_template_id
12500               , x_request_id               => l_request_id
12501               , x_return_status            => x_return_status
12502               , x_msg_count                => x_msg_count
12503               , x_msg_data                 => x_msg_data
12504               , x_contact_destination      => l_contact_destination  -- bug 3955222
12505               , x_contact_party_id         => l_contact_party_id  -- bug 3955222
12506               );
12507            end if;
12508 
12509            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - send status='|| x_return_status);
12510 
12511            IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
12512              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Sending process failed');
12513              GOTO end_loop;
12514            END IF;
12515 
12516            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||l_request_id);
12517            l_ffm_cnt := l_ffm_cnt + 1;
12518 
12519            /*===========================================
12520             * Close OPEN Dunnings for each Del
12521             *===========================================*/
12522 
12523            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning');
12524            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - runninglevel=DELINQUENCY');
12525            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
12526            l_del_tbl(1).delinquency_id := l_delinquency_id;
12527 
12528            Close_Staged_Dunning(
12529                p_api_version              => p_api_version
12530              , p_init_msg_list            => p_init_msg_list
12531              , p_commit                   => p_commit
12532              , p_delinquencies_tbl        => l_del_tbl
12533     	 , p_ag_dn_xref_id	     => l_ag_dn_xref_id
12534              , p_running_level            => 'DELINQUENCY'
12535              , x_return_status            => x_return_status
12536              , x_msg_count                => x_msg_count
12537              , x_msg_data                 => x_msg_data);
12538 
12539            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CloseDunning status='|| x_return_status);
12540 
12541            IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
12542               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Close Dunning');
12543               GOTO end_loop;
12544            END IF;
12545            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EndCloseDunn');
12546 
12547            /*===========================================
12548             * Create Dunning Record
12549             *===========================================*/
12550 
12551            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get CallbackDate');
12552            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag='||l_callback_flag);
12553            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDays='||l_callback_days);
12554 
12555           /*===================================================
12556            * clchang updated 02/13/2003
12557            * callback_days could be null if callback_yn = 'N';
12558            * and if callback_yn = 'N', not get callback_date;
12559            *==================================================*/
12560            IF (l_callback_flag = 'Y') THEN
12561               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is Y: NOTGetCallbackDate');
12562               Get_Callback_Date( p_init_msg_list          => p_init_msg_list
12563                           , p_callback_days          => l_callback_days
12564                           , x_callback_date          => l_callback_date
12565                           , x_return_status          => x_return_status
12566                           , x_msg_count              => x_msg_count
12567                           , x_msg_data               => x_msg_data);
12568 
12569               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetCallbackDate status='|| x_return_status);
12570               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackDate='||l_callback_date);
12571 
12572               IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
12573                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Not Get CallbackDate');
12574                 GOTO end_loop;
12575               END IF;
12576 
12577            ELSE
12578               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CallbackFlag is N: NOTGetCallbackDate');
12579            END IF;
12580 
12581            /* get the current amount_due_remaining and currency_code */
12582            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET AMOUNT');
12583 
12584            Open C_AMOUNT(l_delinquency_id);
12585            Fetch C_AMOUNT into
12586                l_amount,
12587                l_curr_code;
12588 
12589            If ( C_AMOUNT%NOTFOUND) Then
12590               FND_MESSAGE.Set_Name('IEX', 'API_MISSING_UPDATE_TARGET');
12591               FND_MESSAGE.Set_Token ('INFO', 'amount', FALSE);
12592               FND_MSG_PUB.Add;
12593               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - amount notfound');
12594            END IF;
12595 
12596            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - close C_AMOUNT');
12597            Close C_AMOUNT;
12598 
12599            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get amount='||l_amount);
12600            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get currcode='||l_curr_code);
12601            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning');
12602            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
12603            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id='||l_delinquency_id);
12604 
12605            l_dunning_rec.delinquency_id := l_delinquency_id;
12606            l_dunning_rec.callback_yn := l_callback_flag;
12607            l_dunning_rec.callback_date := l_callback_date;
12608            l_dunning_rec.status := 'OPEN';
12609            l_dunning_rec.dunning_method:= l_method;
12610            if (l_curr_dmethod = 'FFM') then
12611              l_dunning_rec.template_id:= l_template_id;
12612              l_dunning_rec.ffm_request_id := l_request_id;
12613            else
12614              l_dunning_rec.xml_template_id:= l_xdo_template_id;
12615              l_dunning_rec.xml_request_id := l_request_id;
12616     	 l_dunning_rec.addt_xml_template_id := l_inv_xdo_template_id;
12617            end if;
12618            l_dunning_rec.campaign_sched_id := l_campaign_sched_id;
12619            l_dunning_rec.dunning_object_id := l_delinquency_id;
12620            l_dunning_rec.dunning_level := 'DELINQUENCY';
12621            l_dunning_rec.amount_due_remaining := l_amount;
12622            l_dunning_rec.currency_code := l_curr_code;
12623            l_dunning_rec.object_type := 'IEX_DELINQUENCY';
12624            l_dunning_rec.object_id := l_delinquency_id;
12625            l_dunning_rec.dunning_plan_id := p_dunning_plan_id;
12626            l_dunning_rec.contact_destination := l_contact_destination;  -- bug 3955222
12627            l_dunning_rec.contact_party_id := l_contact_party_id;  -- bug 3955222
12628            l_dunning_rec.ag_dn_xref_id	:= l_ag_dn_xref_id;
12629            l_dunning_rec.org_id := p_org_id;
12630            l_dunning_rec.as_of_date := l_as_of_date;
12631 
12632            -- start bug 16290958
12633             --l_dunning_rec.parent_dunning_id := p_dunning_id; -- bug 997306 by snuthala 11/25/2011
12634     	     temp_dunning_id := NULL;
12635            select parent_dunning_id into temp_dunning_id
12636            from iex_dunnings
12637            where dunning_id =  p_dunning_id;
12638            WriteLog('temp_dunning_id -- '||temp_dunning_id);
12639            IF  temp_dunning_id is not NULL then
12640               l_dunning_rec.parent_dunning_id := temp_dunning_id;
12641            else
12642              l_dunning_rec.parent_dunning_id := p_dunning_id;
12643             END IF;
12644             WriteLog('l_dunning_rec.parent_dunning_id : '||l_dunning_rec.parent_dunning_id);
12645            -- end bug 1629058
12646            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' before creating dunning org_id ' || p_org_id);
12647 
12648            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
12649 
12650            CREATE_DUNNING(
12651              p_api_version              => p_api_version
12652            , p_init_msg_list            => p_init_msg_list
12653            , p_commit                   => p_commit
12654            , p_dunning_rec              => l_dunning_rec
12655            , x_dunning_id               => l_dunning_id
12656            , x_return_status            => x_return_status
12657            , x_msg_count                => x_msg_count
12658            , x_msg_data                 => x_msg_data);
12659 
12660            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| x_return_status);
12661 
12662            IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
12663              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
12664              GOTO end_loop;
12665            END IF;
12666 
12667            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningId='||l_dunning_id);
12668            l_dunn_cnt := l_dunn_cnt + 1;
12669 
12670            /*===========================================
12671             * Update Delinquency
12672             * Set DUNN_YN = 'N'
12673             *===========================================*/
12674 
12675              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UpdateDel');
12676 
12677              nIdx := nIdx + 1;
12678              del_tbl(nIdx) := l_delinquency_id;
12679 
12680            <<end_loop>>
12681            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_loop');
12682            NULL;
12683 
12684          END IF;
12685 
12686          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close C_GET_DEL');
12687 
12688          Close C_Get_DEL;
12689 
12690          x_request_id := l_request_id;
12691 
12692          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========Summarty==========');
12693          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SendFFM Cnt='||l_ffm_cnt);
12694          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunn Cnt='||l_dunn_cnt);
12695          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - request_id='||x_request_id);
12696          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========End Summarty==========');
12697 
12698           --
12699           -- End of API body
12700           --
12701 
12702           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return status='||x_return_status);
12703           IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
12704               RAISE FND_API.G_EXC_ERROR;
12705           elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
12706               raise FND_API.G_EXC_UNEXPECTED_ERROR;
12707           END IF;
12708 
12709           -- Standard check for p_commit
12710           IF FND_API.to_Boolean( p_commit )
12711           THEN
12712               COMMIT WORK;
12713           END IF;
12714 
12715           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return status='||x_return_status);
12716           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
12717 
12718           FND_MSG_PUB.Count_And_Get
12719           (  p_count          =>   x_msg_count,
12720              p_data           =>   x_msg_data );
12721 
12722           EXCEPTION
12723               WHEN FND_API.G_EXC_ERROR THEN
12724                   x_return_status := FND_API.G_RET_STS_ERROR;
12725                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
12726                   FND_MSG_PUB.Count_And_Get
12727                   (  p_count          =>   x_msg_count,
12728                      p_data           =>   x_msg_data );
12729                   errmsg := SQLERRM;
12730                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||errmsg);
12731                   ROLLBACK TO Resend_Staged_Dunning_PVT;
12732 
12733               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
12734                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
12735                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
12736                   FND_MSG_PUB.Count_And_Get
12737                   (  p_count          =>   x_msg_count,
12738                      p_data           =>   x_msg_data );
12739                   errmsg := SQLERRM;
12740                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||errmsg);
12741                   ROLLBACK TO Resend_Staged_Dunning_PVT;
12742 
12743               WHEN OTHERS THEN
12744                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
12745                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
12746                   FND_MSG_PUB.Count_And_Get
12747                   (  p_count          =>   x_msg_count,
12748                      p_data           =>   x_msg_data );
12749                   errmsg := SQLERRM;
12750                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||errmsg);
12751                   ROLLBACK TO Resend_Staged_Dunning_PVT;
12752 
12753     END Resend_Staged_Dunning;
12754 
12755     /* clchang added (for 11.5.9)
12756        no iex aging in 11.5.9;
12757        in send_dunning, aging_bucket_line_id is not from iex_delinquencies;
12758        we need to get by ourselves;
12759 
12760        updated for 11.5.11  - 11/22/04
12761        dunning support aging in 11.5.11 at all levels.
12762        added 2 more parameters: p_object_code, and p_object_id.
12763        so this procedure can age not just del level, but all levels.
12764      */
12765     Procedure AGING_DEL(
12766                 p_api_version             IN NUMBER := 1.0,
12767                 p_init_msg_list           IN VARCHAR2 ,
12768                 p_commit                  IN VARCHAR2 ,
12769                 p_delinquency_id          IN NUMBER,
12770                 p_dunning_plan_id         in number,
12771                 p_bucket                  IN VARCHAR2,
12772                 p_object_code             IN VARCHAR2,
12773                 p_object_id               IN NUMBER,
12774                 x_return_status           OUT NOCOPY VARCHAR2,
12775                 x_msg_count               OUT NOCOPY NUMBER,
12776                 x_msg_data                OUT NOCOPY VARCHAR2,
12777                 x_AGING_Bucket_line_ID    OUT NOCOPY NUMBER)
12778 
12779     IS
12780     -- begin bug 4914799, add max function and check del status
12781     -- begin bug 9393778 gnramasa 19th Feb 10, add trunc function
12782         CURSOR C_GET_PARTY_DAYS (in_party_id number) IS
12783           --SELECT max(sysdate - ar.due_date) days
12784           SELECT max(trunc(sysdate) - trunc(ar.due_date)) days
12785             FROM iex_delinquencies del,
12786                  ar_payment_schedules ar
12787            WHERE del.party_cust_id = in_party_id
12788              AND del.payment_schedule_id = ar.payment_schedule_id
12789              and del.status in ('DELINQUENT', 'PREDELINQUENT');
12790         --
12791         CURSOR C_GET_ACCT_DAYS (in_acct_id number) IS
12792           --SELECT max(sysdate - ar.due_date) days
12793           SELECT max(trunc(sysdate) - trunc(ar.due_date)) days
12794             FROM iex_delinquencies del,
12795                  ar_payment_schedules ar
12796            WHERE del.cust_account_id = in_acct_id
12797              AND del.payment_schedule_id = ar.payment_schedule_id
12798              and del.status in ('DELINQUENT', 'PREDELINQUENT');
12799         --
12800         CURSOR C_GET_SITE_DAYS (in_site_id number) IS
12801           --SELECT max(sysdate - ar.due_date) days
12802           SELECT max(trunc(sysdate) - trunc(ar.due_date)) days
12803             FROM iex_delinquencies del,
12804                  ar_payment_schedules ar
12805            WHERE del.customer_site_use_id = in_site_id
12806              AND del.payment_schedule_id = ar.payment_schedule_id
12807              and del.status in ('DELINQUENT', 'PREDELINQUENT');
12808         --
12809         CURSOR C_GET_DAYS (IN_DEL_ID NUMBER) IS
12810           --SELECT (sysdate - ar.due_date) days
12811           SELECT (trunc(sysdate) - trunc(ar.due_date)) days
12812             FROM iex_delinquencies del,
12813                  ar_payment_schedules ar
12814            WHERE delinquency_ID = in_DEL_ID
12815              AND del.payment_schedule_id = ar.payment_schedule_id
12816              and del.status in ('DELINQUENT', 'PREDELINQUENT');
12817     -- end bug 4914799, add max function and check del status
12818         --
12819 
12820         CURSOR C_GET_BUCKET_LINE (IN_DAYS NUMBER, p_dunning_plan_id  number) IS
12821            SELECT l.aging_bucket_line_id
12822              FROM ar_aging_bucket_lines l,
12823                   ar_aging_buckets b,
12824                   iex_dunning_plans_vl d
12825              WHERE d.dunning_plan_id = p_dunning_plan_id
12826                 and  d.aging_bucket_id = b.aging_bucket_id
12827                 and  b.aging_bucket_id = l.aging_bucket_id
12828                 --AND round(IN_DAYS) between l.days_start and l.days_to
12829     	    AND IN_DAYS between l.days_start and l.days_to
12830                 and exists (select 1 from iex_ag_dn_xref x
12831                              where d.dunning_plan_id = x.dunning_plan_id
12832                              and d.aging_bucket_id = x.aging_bucket_id
12833                              and x.aging_bucket_line_id = l.aging_bucket_line_id);
12834         -- end bug 9393778 gnramasa 19th Feb 10, add trunc function
12835         --
12836     l_api_name          CONSTANT VARCHAR2(30) := 'AGING_DEL';
12837     l_api_version       NUMBER := 1.0;
12838     l_commit            VARCHAR2(5) ;
12839     --
12840     l_days              NUMBER;
12841     l_bucket_line_id    NUMBER;
12842     --
12843     l_msg_count         NUMBER;
12844     l_msg_data          VARCHAR2(1000);
12845     l_return_status     VARCHAR2(1000);
12846     --
12847     nIdx                NUMBER := 0;
12848 
12849     errmsg                        VARCHAR2(32767);
12850 
12851     BEGIN
12852          -- Standard Start of API savepoint
12853          SAVEPOINT AGING_DEL_PVT;
12854 
12855          l_commit  := FND_API.G_TRUE;
12856 
12857         -- Initialize message list IF p_init_msg_list is set to TRUE.
12858         IF FND_API.to_Boolean( p_init_msg_list )
12859         THEN
12860             FND_MSG_PUB.initialize;
12861         END IF;
12862 
12863         -- Initialize API return status to SUCCESS
12864         l_return_status := FND_API.G_RET_STS_SUCCESS;
12865 
12866         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_object_code='||p_object_code);
12867         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_object_id='||p_object_id);
12868 
12869         IF ( p_object_Code = 'PARTY') then
12870           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Party Level');
12871           Open C_Get_PARTY_DAYS(p_object_id);
12872           Fetch C_Get_PARTY_DAYS into l_days;
12873           If ( C_GET_PARTY_DAYS%NOTFOUND) Then
12874                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PaymentSchedId NotFound');
12875                 FND_MESSAGE.Set_Name('IEX', 'IEX_NO_PAYMENTSCHEDULE');
12876                 FND_MSG_PUB.Add;
12877                 l_return_status := FND_API.G_RET_STS_ERROR;
12878                 Close C_Get_PARTY_DAYS;
12879                 GOTO end_get_line;
12880           end if;
12881           --
12882         ELSIF ( p_object_Code = 'IEX_ACCOUNT') then
12883           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Acct Level');
12884           Open C_Get_ACCT_DAYS(p_object_id);
12885           Fetch C_Get_ACCT_DAYS into l_days;
12886           If ( C_GET_ACCT_DAYS%NOTFOUND) Then
12887                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PaymentSchedId NotFound');
12888                 FND_MESSAGE.Set_Name('IEX', 'IEX_NO_PAYMENTSCHEDULE');
12889                 FND_MSG_PUB.Add;
12890                 l_return_status := FND_API.G_RET_STS_ERROR;
12891                 Close C_Get_ACCT_DAYS;
12892                 GOTO end_get_line;
12893           end if;
12894           --
12895         ELSIF ( p_object_Code = 'IEX_BILLTO') then
12896           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - BillTO Level');
12897           Open C_Get_SITE_DAYS(p_object_id);
12898           Fetch C_Get_SITE_DAYS into l_days;
12899           If ( C_GET_SITE_DAYS%NOTFOUND) Then
12900                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PaymentSchedId NotFound');
12901                 FND_MESSAGE.Set_Name('IEX', 'IEX_NO_PAYMENTSCHEDULE');
12902                 FND_MSG_PUB.Add;
12903                 l_return_status := FND_API.G_RET_STS_ERROR;
12904                 Close C_Get_SITE_DAYS;
12905                 GOTO end_get_line;
12906           end if;
12907           --
12908         ELSE
12909           -- delinquency level
12910 
12911           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||p_delinquency_id);
12912           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bucket='||p_bucket);
12913 
12914           Open C_Get_DAYS(p_delinquency_id);
12915           Fetch C_Get_DAYS into l_days;
12916           If ( C_GET_DAYS%NOTFOUND) Then
12917                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PaymentSchedId NotFound');
12918                 FND_MESSAGE.Set_Name('IEX', 'IEX_NO_PAYMENTSCHEDULE');
12919                 FND_MSG_PUB.Add;
12920                 l_return_status := FND_API.G_RET_STS_ERROR;
12921                 Close C_Get_DAYS;
12922                 GOTO end_get_line;
12923           end if;
12924           --
12925         END IF;
12926           --
12927                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - days='||l_days);
12928                FND_FILE.PUT_LINE(FND_FILE.LOG, 'l_days = ' || l_days);
12929 
12930                Open C_Get_BUCKET_LINE(l_days, p_dunning_plan_id);
12931                Fetch C_Get_BUCKET_LINE into l_bucket_line_id;
12932                If ( C_GET_BUCKET_LINE%NOTFOUND) Then
12933                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - BucketLine NotFound');
12934                   FND_MESSAGE.Set_Name('IEX', 'IEX_NO_BUCKET_LINE');
12935                   FND_MSG_PUB.Add;
12936                   l_return_status := FND_API.G_RET_STS_ERROR;
12937                   Close C_Get_BUCKET_LINE;
12938                   GOTO end_get_line;
12939                else
12940                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bucketlineid='||l_bucket_line_id);
12941                end if;
12942           --
12943 
12944         <<end_get_line>>
12945         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_get_line');
12946         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - status=' || l_return_status);
12947 
12948         x_return_status := l_return_status;
12949         if (x_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
12950             l_bucket_line_id := 0;
12951         END IF;
12952         x_aging_bucket_line_id := l_bucket_line_id;
12953 
12954         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return_status:'||x_return_status);
12955         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - lineId:'||x_aging_bucket_line_id);
12956 
12957         FND_MSG_PUB.Count_And_Get
12958         (  p_count          =>   x_msg_count,
12959            p_data           =>   x_msg_data );
12960 
12961         EXCEPTION
12962               WHEN FND_API.G_EXC_ERROR THEN
12963                   x_return_status := FND_API.G_RET_STS_ERROR;
12964                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
12965                   errmsg := SQLERRM;
12966                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||errmsg);
12967                   ROLLBACK TO AGING_DEL_PVT;
12968                   FND_MSG_PUB.Count_And_Get
12969                   (  p_count          =>   x_msg_count,
12970                      p_data           =>   x_msg_data);
12971 
12972               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
12973     		   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
12974                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
12975                   errmsg := SQLERRM;
12976                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||errmsg);
12977                   ROLLBACK TO AGING_DEL_PVT;
12978                   FND_MSG_PUB.Count_And_Get
12979                   (  p_count          =>   x_msg_count,
12980                      p_data           =>   x_msg_data);
12981 
12982               WHEN OTHERS THEN
12983                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
12984                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
12985                   errmsg := SQLERRM;
12986                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||errmsg);
12987                   ROLLBACK TO AGING_DEL_PVT;
12988                   FND_MSG_PUB.Count_And_Get
12989                   (  p_count          =>   x_msg_count,
12990                      p_data           =>   x_msg_data);
12991 
12992     END AGING_DEL;
12993 
12994     /* begin raverma 10222001
12995        changed spec to work with delinquencies, receipts, promises, disputes,
12996       added:
12997       p_key_name (should be like 'delinquency_id')
12998       p_key_id   (should be like 10001)
12999      */
13000     Procedure Call_FFM(
13001                 p_api_version             IN NUMBER := 1.0,
13002                 p_init_msg_list           IN VARCHAR2 ,
13003                 p_commit                  IN VARCHAR2 ,
13004                 p_key_name                IN VARCHAR2,
13005                 p_key_id                  IN NUMBER,
13006                 p_template_id             IN NUMBER,
13007                 p_method                  IN VARCHAR2,
13008                 p_party_id                IN NUMBER,
13009                 x_return_status           OUT NOCOPY VARCHAR2,
13010                 x_msg_count               OUT NOCOPY NUMBER,
13011                 x_msg_data                OUT NOCOPY VARCHAR2,
13012                 x_REQUEST_ID              OUT NOCOPY NUMBER)
13013 
13014     IS
13015         CURSOR C_GET_CONTENTS (IN_TEMPLATE_ID NUMBER) IS
13016           SELECT  --content_NUMBER,
13017                  upper(substr(content_name,instr(content_name,'.')+1,length(content_name)-instr(content_name,'.'))) DocType,
13018                  mes_doc_ID
13019             FROM JTF_FM_TEMPLATE_CONTENTS
13020            WHERE template_ID = in_template_ID
13021              AND nvl(upper(f_deletedflag),'0') <>'D'
13022            --bug 3090268
13023            --ORDER BY content_number;
13024            ORDER BY creation_date;
13025         --
13026         CURSOR C_GET_ORG_EMAIL (IN_PARTY_ID NUMBER) IS
13027           SELECT email_address
13028             FROM HZ_PARTIES
13029            WHERE party_ID = in_party_ID;
13030         --
13031         CURSOR C_GET_CONTACT_EMAIL (IN_PARTY_ID NUMBER) IS
13032           SELECT email_address
13033             FROM HZ_CONTACT_POINTS
13034            WHERE owner_table_ID = in_party_ID
13035              AND Contact_point_type = 'EMAIL'
13036              AND primary_flag = 'Y';
13037         --
13038         CURSOR C_GET_CONTENT_TYPE (IN_MES_DOC_ID NUMBER) IS
13039           SELECT mes.query_id
13040             FROM jtf_FM_query_mes mes,
13041                  jtf_FM_query q
13042            WHERE mes.MES_DOC_ID = in_mes_doc_id
13043              AND mes.query_id = q.query_id;
13044         --
13045     l_api_name          CONSTANT VARCHAR2(30) := 'Call_FFM';
13046     l_api_version       NUMBER := 1.0;
13047     l_commit            VARCHAR2(5) ;
13048     --
13049     l_Content_tbl       IEX_SEND_FFM_PVT.CONTENT_TBL_TYPE;
13050     l_Content_rec       IEX_SEND_FFM_PVT.CONTENT_REC_TYPE;
13051     l_content_id        NUMBER;
13052     l_doc_type          VARCHAR2(50);
13053     l_bind_var          JTF_FM_REQUEST_GRP.G_VARCHAR_TBL_TYPE;
13054     l_bind_var_type     JTF_FM_REQUEST_GRP.G_VARCHAR_TBL_TYPE;
13055     l_bind_val          JTF_FM_REQUEST_GRP.G_VARCHAR_TBL_TYPE;
13056     --
13057     l_content_nm        VARCHAR2(100);
13058     l_party_id          NUMBER;
13059     l_user_id           NUMBER;
13060     l_server_id         NUMBER;
13061     l_request_id        NUMBER;
13062     l_subject           VARCHAR2(100);
13063     --
13064     l_msg_count         NUMBER;
13065     l_msg_data          VARCHAR2(1000);
13066     l_return_status     VARCHAR2(1000);
13067     --
13068     l_content_xml1      VARCHAR2(1000);
13069     l_content_xml       VARCHAR2(10000);
13070     --
13071     l_email             VARCHAR2(2000);
13072     l_printer       VARCHAR2(2000);
13073     l_request_type      VARCHAR2(10);
13074     l_query_id          NUMBER;
13075     G_MISS_NUM          CONSTANT NUMBER := 9.99E125;
13076     nIdx                NUMBER := 0;
13077 
13078     errmsg                        VARCHAR2(32767);
13079 
13080     BEGIN
13081 
13082         SAVEPOINT CALL_FFM_PVT;
13083 
13084         IF FND_API.to_Boolean( p_init_msg_list )
13085         THEN
13086             FND_MSG_PUB.initialize;
13087         END IF;
13088 
13089         l_return_status := FND_API.G_RET_STS_SUCCESS;
13090 
13091         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - start');
13092         if (p_template_id is null) then
13093             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No TEMPLATE_ID');
13094             FND_MESSAGE.Set_Name('IEX', 'API_FAIL_SEND_FFM');
13095             FND_MESSAGE.Set_Token ('INFO', 'No Template_ID');
13096             FND_MSG_PUB.Add;
13097             l_return_status := FND_API.G_RET_STS_ERROR;
13098             GOTO end_call_ffm;
13099         end if;
13100         if (p_party_id is null) then
13101             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No PARTY_ID');
13102             FND_MESSAGE.Set_Name('IEX', 'API_FAIL_SEND_FFM');
13103             FND_MESSAGE.Set_Token ('INFO', 'No Party_Id');
13104             FND_MSG_PUB.Add;
13105             l_return_status := FND_API.G_RET_STS_ERROR;
13106             GOTO end_call_ffm;
13107         end if;
13108         if (p_method is null) then
13109             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No METHOD');
13110             FND_MESSAGE.Set_Name('IEX', 'API_FAIL_SEND_FFM');
13111             FND_MESSAGE.Set_Token ('INFO', 'No Method');
13112             FND_MSG_PUB.Add;
13113             l_return_status := FND_API.G_RET_STS_ERROR;
13114             GOTO end_call_ffm;
13115         end if;
13116 
13117         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - TEMPLATE_ID='||p_template_id);
13118         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PARTY_ID='||p_party_id);
13119         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - METHOD='||p_method);
13120 
13121        /*=======================================
13122         * get the primary contact email first;
13123         * if not found, get org email address;
13124         =======================================*/
13125         -- clchang added 06/13/2002 for bug 2344867 (FM support EMAIL and PRINT)
13126         if (upper(p_method) = 'EMAIL') then
13127         --
13128           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get Email');
13129 
13130           Open C_Get_CONTACT_EMAIL(p_party_id);
13131           Fetch C_Get_CONTACT_EMAIL into l_email;
13132           If ( C_GET_CONTACT_EMAIL%NOTFOUND) Then
13133              Open C_Get_ORG_EMAIL(p_party_id);
13134              Fetch C_Get_ORG_EMAIL into l_email;
13135              If ( C_GET_ORG_EMAIL%NOTFOUND) Then
13136                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Customer NotFound');
13137                 FND_MESSAGE.Set_Name('IEX', 'API_FAIL_SEND_FFM');
13138                 FND_MESSAGE.Set_Token ('INFO', 'Customer NotFound');
13139                 FND_MSG_PUB.Add;
13140                 l_return_status := FND_API.G_RET_STS_ERROR;
13141                 Close C_Get_ORG_EMAIL;
13142                 Close C_Get_CONTACT_EMAIL;
13143                 GOTO end_call_ffm;
13144              end if;
13145              --
13146              If ( l_email is null ) Then
13147                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Email');
13148                 FND_MESSAGE.Set_Name('IEX', 'API_FAIL_SEND_FFM');
13149                 FND_MESSAGE.Set_Token ('INFO', 'No Email_Address');
13150                 FND_MSG_PUB.Add;
13151                 l_return_status := FND_API.G_RET_STS_ERROR;
13152                 Close C_Get_ORG_EMAIL;
13153                 Close C_Get_CONTACT_EMAIL;
13154                 GOTO end_call_ffm;
13155              end if;
13156              --
13157              Close C_Get_ORG_EMAIL;
13158           end if;
13159 
13160           If ( l_email is null ) Then
13161              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Email');
13162              FND_MESSAGE.Set_Name('IEX', 'API_FAIL_SEND_FFM');
13163              FND_MESSAGE.Set_Token ('INFO', 'No Email_Address');
13164              FND_MSG_PUB.Add;
13165              l_return_status := FND_API.G_RET_STS_ERROR;
13166              Close C_Get_CONTACT_EMAIL;
13167              GOTO end_call_ffm;
13168           END if;
13169 
13170           Close C_Get_CONTACT_EMAIL;
13171 
13172         elsif (upper(p_method) = 'PRINTER' or upper(p_method)='PRINT' ) then
13173           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get Printer');
13174           l_printer := NVL(fnd_profile.value('IEX_FFM_PRINTER'), '');
13175           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Printer:'||l_printer);
13176           if (l_printer = '' or l_printer is null) then
13177              IF (FND_LOG.LEVEL_EVENT >= PG_DEBUG) THEN
13178                 IEX_DEBUG_PUB.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - No Printer');
13179              END IF;
13180              FND_MESSAGE.Set_Name('IEX', 'API_FAIL_SEND_FFM');
13181              FND_MESSAGE.Set_Token ('INFO', 'No Printer');
13182              FND_MSG_PUB.Add;
13183              l_return_status := FND_API.G_RET_STS_ERROR;
13184              GOTO end_call_ffm;
13185           end if;
13186         END IF; -- end of p_method=EMAIL
13187 
13188         IF (FND_LOG.LEVEL_EVENT >= PG_DEBUG) THEN
13189            IEX_DEBUG_PUB.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - Get Contents');
13190         END IF;
13191 
13192         Open C_Get_CONTENTS(p_template_id);
13193         LOOP
13194              Fetch C_Get_CONTENTS into l_doc_type, l_content_id;
13195 
13196              If ( C_GET_CONTENTS%NOTFOUND ) Then
13197                   if (nIdx = 0) then
13198                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Contents');
13199                       FND_MESSAGE.Set_Name('IEX', 'API_FAIL_SEND_FFM');
13200                       FND_MESSAGE.Set_Token ('INFO', 'No Contents for selected template ');
13201                       FND_MSG_PUB.Add;
13202                       l_return_status := FND_API.G_RET_STS_ERROR;
13203                   end if;
13204                   exit;
13205              else
13206                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Content_Id='||l_content_id);
13207 
13208                   IF (FND_LOG.LEVEL_EVENT >= PG_DEBUG) THEN
13209                      IEX_DEBUG_PUB.LogMessage(G_PKG_NAME || ' ' || l_api_name || ' - Get Content Type');
13210                   END IF;
13211 
13212                   nIdx := nIdx + 1;
13213 
13214                   Open C_Get_CONTENT_TYPE(l_content_id);
13215                   Fetch C_Get_CONTENT_TYPE into l_query_id;
13216                   If ( C_GET_CONTENT_TYPE%NOTFOUND) Then
13217                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Content Type:DATA');
13218                       l_request_type := 'DATA';
13219                   else   -- l_query_id is not null
13220                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Content Type:QUERY');
13221 
13222                       l_request_type := 'QUERY';
13223                   end if;
13224                   Close C_Get_CONTENT_TYPE;
13225 
13226                   l_content_rec.content_id :=  l_content_id;
13227                   l_content_rec.request_type := l_request_type; -- 'DATA' or 'QUERY'
13228                   l_content_rec.media_type := p_method;         --'EMAIL', 'FAX'
13229                   l_content_rec.document_type := l_doc_type; --'HTML';  -- 'WORD';
13230                   l_content_rec.user_note := ' ';
13231                   l_content_rec.email  := l_email;
13232                   l_content_rec.printer  := l_printer;
13233                   l_content_rec.file_path := NULL;
13234                   l_content_rec.fax  := '9999999999';
13235                   ------------------------------------
13236 
13237                   -- raverma 10222001 change this to work for any NUMBER id passed
13238                   l_bind_var(nIdx)      := p_key_name;
13239                   l_bind_var_type(nIdx) := 'NUMBER'; -- 'VARCHAR2'
13240                   l_bind_val(nIdx)      := p_key_id;
13241                   l_content_tbl(nIdx) := l_content_rec;
13242 
13243              end if;
13244 
13245         END LOOP;
13246 
13247         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close C_GET_CONTENTS');
13248         Close C_Get_CONTENTS;
13249         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - TotalContents='||nIdx);
13250         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CurrUser='||FND_GLOBAL.USER_ID);
13251         l_content_nm := nIdx; -- Num of Contents you want send out NOCOPY
13252         l_user_id    := FND_GLOBAL.USER_ID; --1001247; -- IEXTEST
13253         l_server_id  := NULL;  -- Using Default Server
13254         l_subject    := NVL(FND_PROFILE.value('IEX_FULFILL_SUBJECT'), '');
13255 
13256         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - subject=;||l_subject');
13257         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CAll SEND_FFM');
13258 
13259         IEX_SEND_FFM_PVT.Send_FFM(p_api_version_number  => l_api_version,
13260                                   p_init_msg_list       => p_init_msg_list,
13261                                   p_commit              => l_commit,
13262                                   p_content_nm          => l_content_nm,
13263                                   p_user_id             => l_user_id,
13264                                   p_server_id           => l_server_id,
13265                                   p_party_id            => p_party_id,
13266                                   p_subject             => l_subject,
13267                                   p_content_tbl         => l_content_tbl,
13268                                   p_bind_var            => l_bind_var,
13269                                   p_bind_val            => l_bind_val,
13270                                   p_bind_var_type       => l_bind_var_type,
13271                                   x_request_id          => l_request_id,
13272                                   x_return_status       => l_return_status,
13273                                   x_msg_count           => l_msg_count,
13274                                   x_msg_data            => l_msg_data);
13275 
13276         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - after send_ffm:'||l_return_status);
13277 
13278         IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
13279             l_return_status := FND_API.G_RET_STS_ERROR;
13280     	   x_msg_count := l_msg_count;
13281     	   x_msg_data := l_msg_data;
13282             --handle error_msg in main procedure (send_dunning)
13283         END IF;
13284 
13285         <<end_call_ffm>>
13286         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_call_ffm');
13287         x_request_id := l_request_id;
13288         x_return_status := l_return_status;
13289         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return_status:'||x_return_status);
13290 
13291         FND_MSG_PUB.Count_And_Get
13292         (  p_count          =>   x_msg_count,
13293            p_data           =>   x_msg_data );
13294 
13295         EXCEPTION
13296               WHEN FND_API.G_EXC_ERROR THEN
13297                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
13298                   ROLLBACK TO CALL_FFM_PVT;
13299                   x_return_status := FND_API.G_RET_STS_ERROR;
13300                   FND_MSG_PUB.Count_And_Get
13301                   (  p_count          =>   x_msg_count,
13302                      p_data           =>   x_msg_data
13303                    );
13304 
13305               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
13306                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
13307                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
13308                   ROLLBACK TO CALL_FFM_PVT;
13309                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
13310                   FND_MSG_PUB.Count_And_Get
13311                   (  p_count          =>   x_msg_count,
13312                      p_data           =>   x_msg_data
13313                    );
13314 
13315               WHEN OTHERS THEN
13316                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
13317                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
13318                   ROLLBACK TO CALL_FFM_PVT;
13319                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
13320                   FND_MSG_PUB.Count_And_Get
13321                   (  p_count          =>   x_msg_count,
13322                      p_data           =>   x_msg_data
13323                    );
13324 
13325     END Call_FFM;
13326 
13327     Procedure Get_Callback_Date(
13328                 p_init_msg_list           IN VARCHAR2 ,
13329                 p_callback_days              IN   NUMBER,
13330     	    p_correspondence_date	 IN DATE default null,
13331                 x_callback_date              OUT NOCOPY  DATE,
13332                 X_Return_Status              OUT NOCOPY  VARCHAR2,
13333                 X_Msg_Count                  OUT NOCOPY  NUMBER,
13334                 X_Msg_Data                   OUT NOCOPY  VARCHAR2)
13335     IS
13336        l_result         DATE;
13337        l_result2        NUMBER;
13338        v_cursor         NUMBER;
13339        v_create_string  varchar2(1000);
13340        v_numrows        NUMBER;
13341        l_callback_days  NUMBER ;
13342        errmsg           varchar2(32767);
13343     	 l_api_name       varchar2(30);
13344 
13345        -- fixed for sql bind var 05/07/2003
13346        vstr1            varchar2(100) ;
13347        vstr2            varchar2(100)  ;
13348        vstr3            varchar2(100) ;
13349 
13350        vstr4            varchar2(100) ;
13351        vstr5            varchar2(100) ;
13352        l_correspondence_date	date;
13353 
13354     BEGIN
13355 
13356        l_callback_days   := p_callback_days;
13357        l_correspondence_date := nvl(p_correspondence_date, sysdate);
13358 
13359        l_api_name     := 'get_callback_date';
13360        ----vstr1          := 'SELECT SYSDATE + ';
13361        vstr1          := 'SELECT  to_date('' ';
13362        ----vstr2          := ' , TO_NUMBER(TO_CHAR(SYSDATE + ' ;
13363        vstr2          := ' , TO_NUMBER(TO_CHAR(to_date('' ' ;
13364        vstr3          := ' ,' || '''D''' || ')) FROM DUAL ';
13365 
13366        ----vstr4          := 'SELECT SYSDATE + ' ;
13367        vstr4          := 'SELECT to_date('' ' ;
13368        vstr5          := ' FROM DUAL ';
13369 
13370        -- Initialize message list IF p_init_msg_list is set to TRUE.
13371        IF FND_API.to_Boolean( p_init_msg_list )
13372        THEN
13373           FND_MSG_PUB.initialize;
13374        END IF;
13375 
13376        -- Initialize API return status to SUCCESS
13377        x_return_status := FND_API.G_RET_STS_SUCCESS;
13378 
13379        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
13380 
13381       v_cursor := DBMS_SQL.OPEN_CURSOR;
13382 
13383       -- clchang updated for sql bind var 05/07/2003
13384       ----v_create_string := vstr1 || l_callback_days || vstr2 || l_callback_days ||
13385       ----                   vstr3;
13386 
13387       v_create_string := vstr1 || l_correspondence_date || ''',''DD-MON-RR'') + ' || l_callback_days || vstr2
13388                         || l_correspondence_date || ''',''DD-MON-RR'') + ' || l_callback_days || vstr3;
13389      /*
13390       v_create_string := 'SELECT SYSDATE + ' || l_callback_days ||
13391                          ', TO_NUMBER(TO_CHAR(SYSDATE + ' || l_callback_days || ',' || '''D''' || ')) FROM DUAL ';
13392      */
13393       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - string='||v_create_string);
13394 
13395       DBMS_SQL.parse(v_cursor, v_create_string, 1);
13396       DBMS_SQL.DEFINE_COLUMN(v_cursor, 1, l_result);
13397       DBMS_SQL.DEFINE_COLUMN(v_cursor, 2, l_result2);
13398 
13399       v_numrows := DBMS_SQL.EXECUTE(v_cursor);
13400       v_numrows := DBMS_SQL.FETCH_ROWS(v_cursor);
13401       DBMS_SQL.COLUMN_VALUE(v_cursor, 1, l_result);
13402       DBMS_SQL.COLUMN_VALUE(v_cursor, 2, l_result2);
13403       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_result='||l_result);
13404       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_result2='||l_result2);
13405 
13406       DBMS_SQL.CLOSE_CURSOR(v_cursor);
13407 
13408       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close Cursor');
13409 
13410       -- If Weekend => Monday
13411       -- 6 => Firday
13412       -- 1 => Sunday
13413 
13414       if (l_result2 = 7) then
13415           l_callback_days := l_callback_days + 2;
13416       elsif (l_result2 = 1) then
13417           l_callback_days := l_callback_days + 1;
13418       end if;
13419 
13420       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - callbackdays='||l_callback_days);
13421 
13422       v_cursor := DBMS_SQL.OPEN_CURSOR;
13423       -- clchang updated for sql bind var 05/07/2003
13424       ----v_create_string := vstr4 || l_callback_days || vstr5;
13425       v_create_string := vstr4 || l_correspondence_date || ''',''DD-MON-RR'') + ' || l_callback_days || vstr5;
13426       --v_create_string := 'SELECT SYSDATE + ' || l_callback_days || ' FROM DUAL ';
13427 
13428       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - createstring='||v_create_string);
13429 
13430       DBMS_SQL.parse(v_cursor, v_create_string, 1);
13431       DBMS_SQL.DEFINE_COLUMN(v_cursor, 1, l_result);
13432 
13433       v_numrows := DBMS_SQL.EXECUTE(v_cursor);
13434       v_numrows := DBMS_SQL.FETCH_ROWS(v_cursor);
13435       DBMS_SQL.COLUMN_VALUE(v_cursor, 1, l_result);
13436       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - result='||l_result);
13437 
13438       DBMS_SQL.CLOSE_CURSOR(v_cursor);
13439       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close Cursor2');
13440 
13441       x_callback_date := l_result;
13442       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - callback_date='||x_callback_date);
13443 
13444       -- Standard call to get message count and IF count is 1, get message info.
13445 
13446      FND_MSG_PUB.Count_And_Get
13447      (  p_count          =>   x_msg_count,
13448         p_data           =>   x_msg_data );
13449 
13450     EXCEPTION
13451       WHEN OTHERS THEN
13452         x_return_status := FND_API.G_RET_STS_ERROR;
13453         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - exception');
13454         errmsg := SQLERRM;
13455         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - errmsg='||errmsg);
13456 
13457     END GET_CALLBACK_DATE;
13458 
13459     /*
13460     || Overview:  This procedure is an extension of Call_FFM. Call_FFM only allows one bind variable/value
13461     ||            This will allow you to pass in unlimited bind variables in a name/value pair structure
13462     ||
13463     || Parameter: p_FULFILLMENT_BIND_TBL = name/value pairs for bind variables
13464     ||            p_template_id   = fulfillment template
13465     ||            p_method = Fulfillment Type, currently only 'EMAIL' is supported
13466     ||            p_party_id  = pk to hz_parties
13467     ||
13468     || Source Tables:  JTF_FM_TEMPLATE_CONTENTS, HZ_PARTIES, HZ_CONTACT_POINTS,
13469     ||                 jtf_FM_query_mes
13470     ||                 jtf_FM_query
13471     ||
13472     || Target Tables:
13473     ||
13474     || Creation date:       03/07/02 11:36:AM
13475     ||
13476     || Major Modifications: when               who                   what
13477     ||                      03/07/02 11:36:AM  raverma               created
13478     ||                      08/06/02           pjgomes               added parameter p_email
13479     ||                      08/19/02 02:00:PM  pjgomes               Changed default value of p_email to NULL
13480     ||   07/10/03 clchang    p_email could be email/fax
13481     ||   05/06/03 clchang    added 4 parameters p_object_code,p_object_id,
13482     ||                                          p_level,p_source_id
13483     ||                       if p_object_code is null, work as before.
13484     ||                       if null, create dunning after sending ffm;
13485     ||                       p_level could be CUSTOMER,ACCOUNT,BILL_TO,DELINQUENCY.
13486     */
13487     Procedure Send_Fulfillment(p_api_version             IN NUMBER := 1.0,
13488                                p_init_msg_list           IN VARCHAR2 ,
13489                                p_commit                  IN VARCHAR2 ,
13490                                p_FULFILLMENT_BIND_TBL    IN IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL,
13491                                p_template_id             IN NUMBER,
13492                                p_method                  IN VARCHAR2,
13493                                p_party_id                IN NUMBER,
13494                                p_user_id                 IN NUMBER ,
13495                                p_email                   IN VARCHAR2 ,
13496                                p_level                   IN VARCHAR2 ,
13497                                p_source_id               IN NUMBER,
13498                                p_object_code             IN VARCHAR2 ,
13499                                p_object_id               IN NUMBER,
13500                                x_return_status           OUT NOCOPY VARCHAR2,
13501                                x_msg_count               OUT NOCOPY NUMBER,
13502                                x_msg_data                OUT NOCOPY VARCHAR2,
13503                                x_REQUEST_ID              OUT NOCOPY NUMBER,
13504                                x_contact_destination     OUT NOCOPY varchar2,  -- bug 3955222
13505                                x_contact_party_id        OUT NOCOPY NUMBER)  -- bug 3955222
13506     IS
13507         CURSOR C_GET_CONTENTS (IN_TEMPLATE_ID NUMBER) IS
13508           SELECT  --content_NUMBER,
13509              upper(substr(content_name,instr(content_name,'.')+1,length(content_name)-instr(content_name,'.'))) DocType,
13510                  mes_doc_ID
13511             FROM JTF_FM_TEMPLATE_CONTENTS
13512            WHERE template_ID = in_template_ID
13513              AND nvl(upper(f_deletedflag),'0') <>'D'
13514            --bug 3090268
13515            --ORDER BY content_number;
13516            ORDER BY creation_date;
13517         --
13518         CURSOR C_GET_ORG_EMAIL (IN_PARTY_ID NUMBER) IS
13519           SELECT email_address
13520             FROM HZ_PARTIES
13521            WHERE party_ID = in_party_ID;
13522         --
13523         CURSOR C_GET_CONTACT_EMAIL (IN_PARTY_ID NUMBER) IS
13524           SELECT email_address
13525             FROM HZ_CONTACT_POINTS
13526            WHERE owner_table_ID = in_party_ID
13527              AND Contact_point_type = 'EMAIL'
13528              AND primary_flag = 'Y';
13529         --
13530         CURSOR C_GET_CONTENT_TYPE (IN_MES_DOC_ID NUMBER) IS
13531           SELECT mes.query_id
13532             FROM jtf_FM_query_mes mes,
13533                  jtf_FM_query q
13534            WHERE mes.MES_DOC_ID = in_mes_doc_id
13535              AND mes.query_id = q.query_id;
13536         --
13537     l_api_name          CONSTANT VARCHAR2(30) := 'Send_Fulfillment';
13538     l_api_version       NUMBER := 1.0;
13539     l_commit            VARCHAR2(5) ;
13540     --
13541     l_Content_tbl       IEX_SEND_FFM_PVT.CONTENT_TBL_TYPE;
13542     l_Content_rec       IEX_SEND_FFM_PVT.CONTENT_REC_TYPE;
13543     l_content_id        NUMBER;
13544     l_doc_type          VARCHAR2(50);
13545     l_bind_var          JTF_FM_REQUEST_GRP.G_VARCHAR_TBL_TYPE;
13546     l_bind_var_type     JTF_FM_REQUEST_GRP.G_VARCHAR_TBL_TYPE;
13547     l_bind_val          JTF_FM_REQUEST_GRP.G_VARCHAR_TBL_TYPE;
13548     l_bind_cnt_tbl      NUMBER;
13549     --
13550     l_content_nm    VARCHAR2(100);
13551     l_party_id      NUMBER;
13552     l_user_id       NUMBER;
13553     l_server_id     NUMBER;
13554     l_request_id    NUMBER;
13555     l_subject       VARCHAR2(100);
13556     --
13557     l_msg_count     NUMBER;
13558     l_msg_data      VARCHAR2(1000);
13559     l_return_status VARCHAR2(1000);
13560     --
13561     l_content_xml1  VARCHAR2(1000);
13562     l_content_xml   VARCHAR2(10000);
13563     --
13564     l_email         VARCHAR2(2000);
13565     l_printer       VARCHAR2(2000);
13566     l_fax           VARCHAR2(2000);
13567     l_contact       VARCHAR2(2000);
13568     l_request_type  VARCHAR2(10);
13569     l_query_id      NUMBER;
13570     l_keep_content  NUMBER;
13571 
13572     --G_MISS_NUM     CONSTANT    NUMBER       := 9.99E125;
13573 
13574     nIdx           NUMBER := 0;
13575     nOrgIdx        NUMBER := 0;
13576     errmsg         VARCHAR2(30000);
13577 
13578     nOrgFound      NUMBER := 0;
13579     l_org_id       NUMBER ;
13580 
13581      l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
13582      l_dunning_id            NUMBER;
13583 
13584      l_contact_party_id    number;  --#bug 3955222
13585 
13586     BEGIN
13587 
13588          SAVEPOINT Send_Fulfillment_PVT;
13589 
13590         l_commit := p_commit;
13591 
13592         --Bug#4679639 schekuri 20-OCT-2005
13593         --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
13594         l_org_id:= mo_global.get_current_org_id;
13595 
13596         IF FND_API.to_Boolean( p_init_msg_list )
13597         THEN
13598             FND_MSG_PUB.initialize;
13599         END IF;
13600 
13601         l_return_status := FND_API.G_RET_STS_SUCCESS;
13602 
13603         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SEND_FFM:');
13604         if (p_template_id is null) then
13605             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No TEMPLATE_ID');
13606             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_TEMPLATE');
13607             FND_MSG_PUB.Add;
13608             l_return_status := FND_API.G_RET_STS_ERROR;
13609             GOTO end_call_ffm;
13610         end if;
13611         if (p_party_id is null AND (p_email IS NULL OR p_email = FND_API.G_MISS_CHAR)) then
13612             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No PARTY_ID or EMAIL');
13613             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_PARTY');
13614             FND_MSG_PUB.Add;
13615             l_return_status := FND_API.G_RET_STS_ERROR;
13616             GOTO end_call_ffm;
13617         end if;
13618         if (p_method is null) then
13619             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No METHOD');
13620             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_METHOD');
13621             FND_MSG_PUB.Add;
13622             l_return_status := FND_API.G_RET_STS_ERROR;
13623             GOTO end_call_ffm;
13624         end if;
13625 
13626         --clchang updated 07/18/2003 subject cannot be hardcoded
13627         -- bug 3058620
13628         l_subject    := NVL(FND_PROFILE.value('IEX_FULFILL_SUBJECT'), '');
13629         if (l_subject is null or l_subject = '') then
13630             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No FFM Subject',0);
13631             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_SUBJECT');
13632             FND_MSG_PUB.Add;
13633             l_return_status := FND_API.G_RET_STS_ERROR;
13634             GOTO end_call_ffm;
13635         end if;
13636 
13637         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - TEMPLATE_ID='||p_template_id);
13638         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PARTY_ID='||p_party_id);
13639         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EMAIL='||p_email);
13640         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - METHOD='||p_method);
13641         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - SUBJECT='||l_subject);
13642 
13643        /*=======================================
13644         * get the primary contact email first;
13645         * if not found, get org email address;
13646         =======================================*/
13647 
13648         if(p_email IS NULL OR p_email = FND_API.G_MISS_CHAR) THEN
13649 
13650            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Call GetContactInfo');
13651 
13652            GetContactInfo(
13653                        p_api_version              => p_api_version
13654                      , p_init_msg_list            => p_init_msg_list
13655                      , p_commit                   => p_commit
13656                      , p_method                   => p_method
13657                      , p_party_id                 => p_party_id
13658                      , p_dunning_level            => p_level
13659                      , p_cust_site_use_id         => null
13660                      , x_return_status            => l_return_status
13661                      , x_msg_count                => l_msg_count
13662                      , x_msg_data                 => l_msg_data
13663                      , x_contact                  => l_contact
13664                      , x_contact_party_id         => l_contact_party_id  -- bug 3955222
13665            );
13666 
13667           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  status='||l_return_status);
13668 
13669           IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
13670              l_return_status := FND_API.G_RET_STS_ERROR;
13671              x_msg_count := l_msg_count;
13672              x_msg_data := l_msg_data;
13673              --handle error_msg in main procedure
13674              GOTO end_call_ffm;
13675           END IF;
13676 
13677           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ContactInfo:'||l_contact);
13678 
13679         END IF;
13680 
13681         -- user could pass fax/email by p_email parameter,
13682         -- then dont call GetContactInfo
13683         --
13684         IF (p_method = 'EMAIL') THEN
13685           if(p_email IS NULL OR p_email = FND_API.G_MISS_CHAR) THEN
13686             l_email := l_contact;
13687           else
13688             l_email := p_email;
13689           end if;
13690           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EMAIL:'||l_email);
13691             l_printer := 'DEVPRT';
13692             l_fax := '99999999';
13693         --
13694         ELSIF (p_method = 'PRINTER' or p_method = 'PRINT') THEN
13695           -- p_email could be fax or email
13696           if(p_email IS NULL OR p_email = FND_API.G_MISS_CHAR) THEN
13697             l_printer := l_contact;
13698           else
13699             l_printer := p_email;
13700           end if;
13701           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PRINTER:'||l_printer);
13702             l_email := '';
13703             l_fax := '99999999';
13704         --
13705         ELSIF (p_method = 'FAX') THEN
13706           -- clchang 07/09/03 updated
13707           -- p_email could be fax or email
13708           if(p_email IS NULL OR p_email = FND_API.G_MISS_CHAR) THEN
13709             l_fax := l_contact;
13710           else
13711             l_fax := p_email;
13712           end if;
13713           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - FAX:'||l_fax);
13714             --l_fax := l_contact;
13715             l_printer := 'DEVPRT';
13716             l_email := '';
13717         END IF;
13718 
13719         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template_id=' || p_template_id);
13720 
13721         Open C_Get_CONTENTS(p_template_id);
13722         LOOP
13723              Fetch C_Get_CONTENTS into l_doc_type, l_content_id;
13724 
13725              If ( C_GET_CONTENTS%NOTFOUND ) Then
13726                   if (nIdx = 0) then
13727                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Contents NotFound');
13728                       FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_FFMCONTENT');
13729                       FND_MSG_PUB.Add;
13730                       l_return_status := FND_API.G_RET_STS_ERROR;
13731                   end if;
13732                   GOTO end_call_ffm;
13733                   --exit;
13734              else
13735                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Content_id='||l_content_id);
13736                   nIdx := nIdx + 1;
13737                   l_keep_content := 1;
13738                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - nIdx='||nIdx);
13739 
13740                   Open C_Get_CONTENT_TYPE(l_content_id);
13741                   Fetch C_Get_CONTENT_TYPE into l_query_id;
13742                   If ( C_GET_CONTENT_TYPE%NOTFOUND) Then
13743                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ContentType=DATA');
13744                       l_request_type := 'DATA';
13745 
13746                   else   -- l_query_id is not null
13747                       WriteLog('iexvdunb.pls:SEND_FFM:ContentType=QUERY');
13748                      /*=================================================================
13749                       * the following part is special for IEXFmAcctDelQuery and IEXFmAcctPreDelQuery;
13750                       * if IEXFmAcctDelQuery (query_id 2002),
13751                       *    if no rows selected based on the bind data,
13752                       *    skip IEXFmAcctDel.htm content;
13753                       * if IEXFmAcctPreDelQuery (query_id 2003),
13754                       *    if no rows selected based on the bind data,
13755                       *    skip IEXFmPart2.htm and IEXFmAcctPreDel.htm contents;
13756                       * the reason we handle it is because
13757                       *    FFM engine set status FAILURE if no rows selected for one content.
13758                       *    then our template will be FAILURE
13759                       *    just because one content has no table data;
13760                       *===========================================================*/
13761 
13762                       --check skip or not only if our sample doc and sample queries
13763                       --if (l_query_id = 2002 or l_query_id = 2003) then
13764                       if ( (l_content_id = 2002 and l_query_id = 2002 ) or
13765                            (l_content_id = 2004 and l_query_id = 2003 ))
13766                       then
13767                           CHK_QUERY_DATA( l_query_id, p_FULFILLMENT_BIND_TBL, l_keep_content);
13768                           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_keep_content='||l_keep_content);
13769                           if (l_keep_content = 0 ) then
13770                               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - skip this content');
13771                               Close C_Get_CONTENT_TYPE;
13772                               GOTO end_content;
13773                           end if;
13774                       end if;
13775                       -- end of checking
13776 
13777                       l_request_type := 'QUERY';
13778                   end if;
13779                   Close C_Get_CONTENT_TYPE;
13780 
13781                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CLOSE ContentType');
13782 
13783                   l_content_rec.content_id    := l_content_id;
13784                   l_content_rec.request_type  := l_request_type; -- 'DATA' or 'QUERY'
13785                   l_content_rec.media_type    := p_method;         --'EMAIL', 'FAX'
13786                   l_content_rec.document_type := l_doc_type; --'HTML';  -- 'WORD';
13787                   l_content_rec.user_note     := ' ';
13788                   l_content_rec.email         := l_email;
13789                   l_content_rec.printer       := l_printer;
13790                   l_content_rec.file_path     := NULL;
13791                   l_content_rec.fax           := l_fax;
13792                   ------------------------------------
13793 
13794                   -- this is dumb because i am assuming all binds for 1 content, not mutliple contents
13795                   l_bind_cnt_tbl := p_FULFILLMENT_BIND_TBL.count;
13796                   WriteLog('iexvdunb.pls:SEND_FFM:bind_tbl_cnt'||l_bind_cnt_tbl);
13797                   nOrgFound := 0;
13798                   for j in 1..l_bind_cnt_tbl
13799                   loop
13800                     l_bind_var(j)      := p_FULFILLMENT_BIND_TBL(j).Key_name;
13801                     l_bind_var_type(j) := p_FULFILLMENT_BIND_TBL(j).Key_Type;
13802                     l_bind_val(j)      := p_FULFILLMENT_BIND_TBL(j).Key_Value;
13803 
13804                     -- clchang updated 07/08/2003 for bug 3026860
13805                     if (upper(l_bind_var(j)) = 'ORG_ID') then
13806                         nOrgFound := 1;
13807                     end if;
13808                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind_var:found org_id? '||nOrgFound);
13809 
13810                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind_var='||l_bind_var(j));
13811                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind_var_type='||l_bind_var_type(j));
13812                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind_val='||l_bind_val(j));
13813                   end loop;
13814 
13815                   -- clchang updated 07/08/2003 for bug 3026860
13816                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - after loop of bind_var:found org_id? '||nOrgFound);
13817                   if (nOrgFound = 0) then
13818                     nOrgIdx := l_bind_cnt_tbl + 1;
13819                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind_var:add org_id at index '||nOrgIdx);
13820                     l_bind_var(nOrgIdx)      := 'org_id';
13821                     l_bind_var_type(nOrgIdx) := 'NUMBER';
13822                     l_bind_val(nOrgIdx)      := l_org_id;
13823                   end if;
13824 
13825                   l_content_tbl(nIdx) := l_content_rec;
13826 
13827                   <<end_content>>
13828                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_content');
13829                   if (l_content_id = 2002 and l_keep_content = 0 and l_query_id = 2002 ) then
13830                       nIdx := nIdx - 1;
13831                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - skip this content');
13832                   elsif (l_content_id = 2004 and l_keep_content = 0 and l_query_id = 2003 ) then
13833                       nIdx := nIdx - 2;
13834                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - skip this content and IEXFmPart2.htm');
13835                   end if;
13836              end if;
13837 
13838         END LOOP;
13839 
13840         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - total contents='||nIdx);
13841 
13842         Close C_Get_CONTENTS;
13843 
13844         l_content_nm := nIdx; -- Num of Contents you want send out NOCOPY
13845         if  (p_user_id is null) then
13846              l_user_id    := FND_GLOBAL.USER_ID; --1001247; -- IEXTEST
13847              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_user_id is null');
13848         else
13849              l_user_id := p_user_id;
13850         end if;
13851         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - curruser='||l_user_id);
13852 
13853         l_server_id  := NULL;  -- Using Default Server
13854 
13855         --
13856         -- If any errors(like template no contents), dont call send_ffm;
13857         --
13858         IF l_return_status = FND_API.G_RET_STS_SUCCESS THEN
13859 
13860             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Call SEND_FFM');
13861             IEX_SEND_FFM_PVT.Send_FFM(
13862                                   p_api_version_number => l_api_version,
13863                                   p_init_msg_list   => p_init_msg_list,
13864                                   p_commit          => l_commit,
13865                                   p_content_nm      => l_content_nm,
13866                                   p_user_id         => l_user_id,
13867                                   p_server_id       => l_server_id,
13868                                   p_party_id        => p_party_id,
13869                                   p_subject         => l_subject,
13870                                   p_content_tbl     => l_content_tbl,
13871                                   p_bind_var        => l_bind_var,
13872                                   p_bind_val        => l_bind_val,
13873                                   p_bind_var_type   => l_bind_var_type,
13874                                   x_request_id      => l_request_id,
13875                                   x_return_status   => l_return_status,
13876                                   x_msg_count       => l_msg_count,
13877                                   x_msg_data        => l_msg_data);
13878 
13879            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - After SEND_FFM:'||l_return_status);
13880 
13881            IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
13882              l_return_status := FND_API.G_RET_STS_ERROR;
13883              x_msg_count := l_msg_count;
13884              x_msg_data := l_msg_data;
13885              --handle error_msg in main procedure (send_dunning)
13886              GOTO end_call_ffm;
13887            END IF;
13888 
13889         END IF;
13890         --
13891         -- updated by clchang 05/06/04 for bug 3088968
13892         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - level='||p_level);
13893         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - source_id='||p_source_id);
13894         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object='||p_object_code);
13895         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id='||p_object_id);
13896         IF( p_object_code is null ) THEN
13897             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - no object');
13898             x_contact_destination := l_contact; -- bug 3955222
13899             x_contact_party_id := l_contact_party_id; -- bug 3955222
13900         ELSIF( p_object_code = 'PARTY' or p_object_code = 'IEX_ACCOUNT' or
13901                p_object_code = 'IEX_BILLTO' or
13902                p_object_code = 'IEX_DELINQUENCY' or
13903                p_object_code = 'IEX_STRATEGY') THEN
13904             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning rec=> dont create rec');
13905             x_contact_destination := l_contact; -- bug 3955222
13906             x_contact_party_id := l_contact_party_id; -- bug 3955222
13907         ELSE
13908             l_dunning_rec.dunning_level := p_level;
13909             l_dunning_rec.dunning_object_id := p_source_id;
13910             l_dunning_rec.callback_yn := 'N';
13911             l_dunning_rec.status := 'OPEN';
13912             l_dunning_rec.dunning_method:= p_method;
13913             l_dunning_rec.template_id:= p_template_id;
13914             l_dunning_rec.ffm_request_id := l_request_id;
13915             l_dunning_rec.object_type := p_object_code;
13916             l_dunning_rec.object_id := p_object_id;
13917             l_dunning_rec.contact_destination := l_contact;   -- bug 3955222
13918             l_dunning_rec.contact_party_id := l_contact_party_id;   -- bug 3955222
13919 
13920             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
13921             CREATE_DUNNING(
13922                        p_api_version              => p_api_version
13923                      , p_init_msg_list            => p_init_msg_list
13924                      , p_commit                   => p_commit
13925                      , p_dunning_rec              => l_dunning_rec
13926                      , x_dunning_id               => l_dunning_id
13927                      , x_return_status            => x_return_status
13928                      , x_msg_count                => x_msg_count
13929                      , x_msg_data                 => x_msg_data);
13930 
13931             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| x_return_status);
13932             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_id='||l_dunning_id);
13933 
13934             IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
13935                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
13936                l_return_status := FND_API.G_RET_STS_ERROR;
13937                x_msg_count := l_msg_count;
13938                x_msg_data := l_msg_data;
13939             END IF;
13940         END IF; -- end of p_object
13941 
13942         <<end_call_ffm>>
13943         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_call_ffm');
13944         x_request_id := l_request_id;
13945         x_return_status := l_return_status;
13946 
13947         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return_status:'||x_return_status);
13948 
13949         FND_MSG_PUB.Count_And_Get
13950         (  p_count          =>   x_msg_count,
13951            p_data           =>   x_msg_data );
13952 
13953         EXCEPTION
13954               WHEN FND_API.G_EXC_ERROR THEN
13955                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
13956                    errmsg := SQLERRM;
13957                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
13958                    ROLLBACK TO SEND_FULFILLMENT_PVT;
13959                    x_return_status := FND_API.G_RET_STS_ERROR;
13960                    FND_MSG_PUB.Count_And_Get
13961                    (  p_count          =>   x_msg_count,
13962                       p_data           =>   x_msg_data
13963                    );
13964 
13965               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
13966                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
13967                    errmsg := SQLERRM;
13968                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
13969                    ROLLBACK TO SEND_FULFILLMENT_PVT;
13970                    x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
13971                    FND_MSG_PUB.Count_And_Get
13972                    (  p_count          =>   x_msg_count,
13973                       p_data           =>   x_msg_data
13974                    );
13975 
13976               WHEN OTHERS THEN
13977                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
13978                    errmsg := SQLERRM;
13979                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
13980                    ROLLBACK TO SEND_FULFILLMENT_PVT;
13981                    x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
13982                    FND_MSG_PUB.Count_And_Get
13983                    (  p_count          =>   x_msg_count,
13984                       p_data           =>   x_msg_data
13985                    );
13986 
13987     END Send_Fulfillment;
13988 
13989     /*
13990     || Overview:  This procedure is new for 11.5.11. To replace Fulfillment
13991     ||            with XML Publisher.
13992     ||            similar as Send_Fulfillment.
13993     ||
13994     ||   11/08/04 clchang    added for 11.5.11.
13995     ||
13996     */
13997     Procedure Send_XML(p_api_version             IN NUMBER := 1.0,
13998                        p_init_msg_list           IN VARCHAR2 ,
13999                        p_commit                  IN VARCHAR2 ,
14000                        p_resend                  IN VARCHAR2 ,
14001                        p_request_id              IN NUMBER,
14002                        p_FULFILLMENT_BIND_TBL    IN IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL,
14003                        p_template_id             IN NUMBER,
14004                        p_method                  IN VARCHAR2,
14005                        p_party_id                IN NUMBER,
14006                        p_user_id                 IN NUMBER ,
14007                        p_email                   IN VARCHAR2 ,
14008                        p_level                   IN VARCHAR2 ,
14009                        p_source_id               IN NUMBER,
14010                        p_object_code             IN VARCHAR2 ,
14011                        p_object_id               IN NUMBER,
14012                        p_resource_id             IN NUMBER,
14013     		   p_dunning_mode            IN VARCHAR2 DEFAULT NULL,  -- added by gnramasa for bug 8489610 14-May-09
14014     		   p_parent_request_id       IN NUMBER DEFAULT NULL,
14015                        p_org_id                  IN NUMBER DEFAULT NULL, -- added for bug 9151851
14016     		   p_correspondence_date     IN DATE DEFAULT NULL,
14017     		   p_addt_template_id	     IN NUMBER DEFAULT NULL, --added for bug 9970642 gnramasa 4th Aug 10
14018     		   x_return_status           OUT NOCOPY VARCHAR2,
14019                        x_msg_count               OUT NOCOPY NUMBER,
14020                        x_msg_data                OUT NOCOPY VARCHAR2,
14021                        x_REQUEST_ID              OUT NOCOPY NUMBER,
14022                        x_contact_destination     OUT NOCOPY varchar2,  -- bug 3955222
14023                        x_contact_party_id        OUT NOCOPY NUMBER)  -- bug 3955222
14024 
14025     IS
14026         -- new cursor to get tmp query for xml publisher design 11.5.11
14027         CURSOR C_GET_QUERY (IN_TEMPLATE_ID NUMBER, IN_LEVEL VARCHAR2) IS
14028           SELECT q.query_id
14029             FROM iex_query_temp_xref xref,
14030                  iex_xml_queries q
14031            WHERE xref.template_id = IN_TEMPLATE_ID
14032              AND xref.query_id = q.query_id
14033              AND q.query_level = IN_LEVEL;
14034         --
14035         -- new cursor to get tmp query for xml publisher design 11.5.11
14036         CURSOR C_GET_RS (IN_USER_ID NUMBER) IS
14037           SELECT j.resource_id
14038             FROM jtf_rs_resource_extns j
14039            WHERE j.user_id = in_user_id;
14040         --
14041         CURSOR C_GET_ORG_EMAIL (IN_PARTY_ID NUMBER) IS
14042           SELECT email_address
14043             FROM HZ_PARTIES
14044            WHERE party_ID = in_party_ID;
14045         --
14046         CURSOR C_GET_CONTACT_EMAIL (IN_PARTY_ID NUMBER) IS
14047           SELECT email_address
14048             FROM HZ_CONTACT_POINTS
14049            WHERE owner_table_ID = in_party_ID
14050              AND Contact_point_type = 'EMAIL'
14051              AND primary_flag = 'Y';
14052 
14053         cursor c_get_contact_point(p_contact_point_id number, p_contact_type varchar2) is
14054         select decode(p_contact_type , 'EMAIL', c.email_address,
14055                                        'PHONE', c.phone_country_code || c.phone_area_code || c.phone_number,
14056                                          'FAX', c.phone_country_code || c.phone_area_code || c.phone_number, null)
14057          from hz_contact_points c
14058         where contact_point_id = p_contact_point_id;
14059 
14060         --Start for bug 9970642 gnramasa 4th Aug 10
14061         cursor c_get_resend_data(p_request_id number) is
14062             select QUERY_TEMP_ID, ADDT_QUERY_TEMP_ID, DESTINATION
14063             from IEX_XML_REQUEST_HISTORIES
14064             where XML_REQUEST_ID = p_request_id;
14065 
14066        --Bug5233002. Fix by LKKUMAR on 31-May-2006. Start.
14067        CURSOR C_GET_RES_USER_ID  IS
14068           SELECT j.user_id
14069             FROM jtf_rs_resource_extns j
14070            WHERE j.resource_id = p_resource_id;
14071        l_resource_user_id NUMBER;
14072        --Bug5233002. Fix by LKKUMAR on 31-May-2006. End.
14073 
14074        CURSOR c_get_resend_query_data(p_query_temp_id number) is
14075               select query_id from IEX_QUERY_TEMP_XREF
14076     	  where query_temp_id = p_query_temp_id;
14077 
14078         l_fulfillment_bind_tbl  IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
14079         --
14080     		l_api_name          CONSTANT VARCHAR2(30) := 'Send_XML';
14081     		l_api_version       NUMBER := 1.0;
14082     		l_commit            VARCHAR2(5) ;
14083     		--
14084     		--
14085     		l_party_id      NUMBER;
14086     		l_user_id       NUMBER;
14087     		l_server_id     NUMBER;
14088     		l_request_id    NUMBER;
14089     		l_subject       VARCHAR2(100);
14090     		--
14091     		l_msg_count     NUMBER;
14092     		l_msg_data      VARCHAR2(1000);
14093     		l_return_status VARCHAR2(10);
14094     		--
14095     		l_content_xml1  VARCHAR2(1000);
14096     		l_content_xml   VARCHAR2(10000);
14097     		--
14098     		l_email         VARCHAR2(2000);
14099     		l_printer       VARCHAR2(2000);
14100     		l_fax           VARCHAR2(2000);
14101     		l_contact       VARCHAR2(2000);
14102     		l_request_type  VARCHAR2(10);
14103     		l_query_id      NUMBER;
14104     		l_keep_content  NUMBER;
14105 
14106     		nIdx           NUMBER := 0;
14107     		nOrgIdx        NUMBER := 0;
14108     		errmsg         VARCHAR2(30000);
14109     		nOrgFound      NUMBER := 0;
14110     		l_org_id       NUMBER ;
14111     		l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
14112     		l_DUNNING_upd_rec       IEX_DUNNING_PUB.DUNNING_REC_TYPE;
14113     		l_dunning_id            NUMBER;
14114 
14115     		l_level        VARCHAR2(20);
14116     		l_temp_level   VARCHAR2(20);
14117     		l_dest         VARCHAR2(2000);
14118     		l_resource_id  NUMBER;
14119     		l_resend       VARCHAR2(5);
14120     		l_contact_party_id number;   --#bug 39555222
14121         l_customer_site_use_id  number;
14122         l_contact_point_id      number;
14123         l_info                  varchar2(500);
14124         l_location_id           number;
14125         l_cust_account_id       number;
14126         l_delinquency_id        number;
14127         Type refCur             is Ref Cursor;
14128         sql_cur                 refCur;
14129         vSQL                    VARCHAR2(2000);
14130         l_contact_id            number;
14131 
14132         l_msg_count1            NUMBER;
14133         l_msg_data1             VARCHAR2(1000);
14134         l_return_status1        VARCHAR2(10);
14135         l_msg                   varchar2(32000);
14136         l_app                   varchar2(50);
14137         l_msg_name              varchar2(30);
14138         l_count                 number;
14139         k                       number;
14140         -- start for bug 8916424 PNAVEENK
14141         b_user_id              NUMBER;
14142         l_defined              boolean;
14143 
14144         cursor c_user_level_profile(p_resource_id number) is
14145         select user_id
14146         from jtf_rs_resource_extns
14147         where resource_id = p_resource_id;
14148         -- end for bug 8916424
14149 
14150         l_dunning_type		varchar2(20);
14151         l_addt_query_id		number;
14152         l_bind_count		number;
14153         l_rowid			varchar2(50);
14154         x_dunning_trx_id		number;
14155         l_transaction_id		number;
14156         l_payment_schedule_id	number;
14157         l_query_temp_id      NUMBER;
14158         l_addt_query_temp_id number;
14159          CURSOR C_TEMPLATE_STATUS (l_template_id number) is
14160          select 'Active'
14161          from xdo_templates_vl xdo
14162          where xdo.template_id = l_template_id
14163          and trunc(sysdate) >= TRUNC (NVL(xdo.start_date, sysdate))
14164          and trunc(sysdate) < TRUNC(NVL(xdo.end_date, sysdate + 1));
14165 
14166          l_template_status		  varchar2(10);
14167 
14168          CURSOR C_TEMPLATE_NAME (l_template_id number) is
14169          select template_name
14170          from xdo_templates_vl xdo
14171          where xdo.template_id = l_template_id;
14172 
14173          l_template_name	varchar2(500);
14174 
14175      BEGIN
14176 
14177         SAVEPOINT Send_XML_PVT;
14178         WriteLog('----------' || l_api_name || '----------');
14179         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Input parameters:');
14180         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - LEVEL = '|| p_level);
14181         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - RESEND = '|| p_resend);
14182         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - TEMPLATE_ID = '|| p_template_id);
14183         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PARTY_ID = '|| p_party_id);
14184         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EMAIL = ' ||p_email);
14185         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - METHOD = ' ||p_method);
14186         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - source_id ='||p_source_id);
14187         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object ='||p_object_code);
14188         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - object_id ='||p_object_id);
14189         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind values count = ' || p_fulfillment_bind_tbl.count);
14190         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org_id = ' || p_org_id);
14191         l_commit := p_commit;
14192 
14193         --Bug#4679639 schekuri 20-OCT-2005
14194         --Value of profile ORG_ID shouldn't be used for getting ORG_ID after MOAC implementation
14195         --l_org_id        := fnd_profile.value('ORG_ID');
14196         l_org_id:= mo_global.get_current_org_id;
14197 
14198         -- clchang added 11/08/04 for 11.5.11
14199         l_level := p_level;
14200         l_resource_id := p_resource_id;
14201         l_resend      := p_resend;
14202         IF (l_level is null) then
14203             l_level := 'CUSTOMER';
14204         END IF;
14205         l_resend := p_resend;
14206         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - level=' || l_level);
14207         IF (l_resend is null) then
14208             l_resend := 'N';
14209         END IF;
14210         -- end clchang added 11/08/04 for 11.5.11
14211 
14212         FND_MSG_PUB.initialize;
14213 
14214         l_return_status := FND_API.G_RET_STS_SUCCESS;
14215 
14216         if (p_object_code is null) then
14217             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No OBJECT_ID',0);
14218             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_OBJECT');
14219             FND_MSG_PUB.Add;
14220             l_return_status := FND_API.G_RET_STS_ERROR;
14221             GOTO end_call_ffm;
14222         end if;
14223 
14224         if (p_template_id is null) then
14225             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No TEMPLATE_ID',0);
14226             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_TEMPLATE');
14227             FND_MSG_PUB.Add;
14228             l_return_status := FND_API.G_RET_STS_ERROR;
14229             GOTO end_call_ffm;
14230         end if;
14231 
14232     	/*===========================================
14233     	* Check the status of the template
14234     	*===========================================*/
14235 
14236     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GET Template status');
14237     	Open C_TEMPLATE_STATUS(p_template_id);
14238     	Fetch C_TEMPLATE_STATUS into l_template_status;
14239 
14240     	If ( C_TEMPLATE_STATUS%NOTFOUND) Then
14241 
14242     		open C_TEMPLATE_NAME (p_template_id);
14243     		Fetch C_TEMPLATE_NAME into l_template_name;
14244     		close C_TEMPLATE_NAME;
14245 
14246     		FND_MESSAGE.Set_Name('IEX', 'IEX_TEMPLATE_INACTIVE');
14247     		FND_MSG_PUB.Add;
14248     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Template: ''' || l_template_name || ''' is inactive');
14249     		FND_FILE.PUT_LINE(FND_FILE.LOG, 'Template: ''' || l_template_name || ''' is inactive');
14250     		l_return_status := FND_API.G_RET_STS_ERROR;
14251     		GOTO end_call_ffm;
14252     	END IF;
14253     	Close C_TEMPLATE_STATUS;
14254     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - template status= '||l_template_status);
14255 
14256         if (p_party_id is null AND (p_email IS NULL OR p_email = FND_API.G_MISS_CHAR)) then
14257             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No PARTY_ID or EMAIL',0);
14258             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_PARTY');
14259             FND_MSG_PUB.Add;
14260             l_return_status := FND_API.G_RET_STS_ERROR;
14261             GOTO end_call_ffm;
14262         end if;
14263 
14264         if (p_method is null) then
14265             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No METHOD',0);
14266             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_METHOD');
14267             FND_MSG_PUB.Add;
14268             l_return_status := FND_API.G_RET_STS_ERROR;
14269             GOTO end_call_ffm;
14270         end if;
14271 
14272         --clchang updated 07/18/2003 subject cannot be hardcoded
14273         -- bug 3058620
14274         -- start for bug 8916424 PNAVEENK
14275 
14276            open c_user_level_profile(l_resource_id);
14277            fetch c_user_level_profile into b_user_id;
14278            close c_user_level_profile;
14279 
14280            fnd_profile.get_specific(
14281                            NAME_Z => 'IEX_FULFILL_SUBJECT',
14282                            USER_ID_Z   => b_user_id,
14283                            RESPONSIBILITY_ID_Z=>NULL,
14284                            APPLICATION_ID_Z =>NULL,
14285                            VAL_Z   => l_subject,
14286                            DEFINED_Z  => l_defined,
14287                            ORG_ID_Z=>NULL,
14288                            SERVER_ID_Z=>NULL);
14289            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' User level Fulfillment Subject Profile value: ' || l_subject);
14290 
14291            if l_subject is null then
14292                     l_subject := NVL(FND_PROFILE.value('IEX_FULFILL_SUBJECT'), '');
14293            end if;
14294 
14295         -- end for bug 8916424
14296 
14297         if (l_subject is null or l_subject = '') then
14298             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No XML Subject');
14299             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_SUBJECT');
14300             FND_MSG_PUB.Add;
14301             l_return_status := FND_API.G_RET_STS_ERROR;
14302             GOTO end_call_ffm;
14303         end if;
14304 
14305         if  (p_user_id is null) then
14306              l_user_id    := FND_GLOBAL.USER_ID;
14307              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_user_id is null');
14308         else
14309              l_user_id := p_user_id;
14310         end if;
14311         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_user_id = '||l_user_id);
14312 
14313         -- chk resource_id
14314         if (l_resource_id is null) then
14315           Open C_Get_RS(l_user_id);
14316           Fetch C_Get_RS into l_resource_id;
14317           Close C_Get_RS;
14318         end if;
14319         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - resource_id = ' || l_resource_id);
14320 
14321         if (l_resource_id is null) then
14322             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Resource for user '||l_user_id);
14323             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_RESOURCE');
14324             FND_MSG_PUB.Add;
14325             l_return_status := FND_API.G_RET_STS_ERROR;
14326             GOTO end_call_ffm;
14327         end if;
14328         l_fulfillment_bind_tbl := p_fulfillment_bind_tbl;
14329         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind values count = ' || l_fulfillment_bind_tbl.count);
14330         -- for resend=Y look for dunning_id and assign it to PARENT_DUNNING_ID
14331         if l_resend = 'Y'  then
14332          for k in 1..l_fulfillment_bind_tbl.count loop
14333                 if upper(l_fulfillment_bind_tbl(k).key_name) = 'DUNNING_ID' then
14334 		            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_fulfillment_bind_tbl(k).key_value = ' ||  l_fulfillment_bind_tbl(k).key_value);
14335                     l_dunning_rec.PARENT_DUNNING_ID := l_fulfillment_bind_tbl(k).key_value;
14336 		            exit;
14337                 end if;
14338             end loop;
14339         end if;
14340         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PARENT_DUNNING_ID = ' || l_dunning_rec.PARENT_DUNNING_ID);
14341 
14342       If p_request_id is not null then
14343     	select nvl(plan.dunning_type,'DAYS_OVERDUE')
14344     	into l_dunning_type
14345     	from IEX_DUNNING_PLANS_B plan, iex_dunnings dunn
14346     	where dunn.xml_request_id = p_request_id
14347     	and plan.dunning_plan_id = dunn.dunning_plan_id;
14348       end if;
14349 
14350         if l_resend = 'Y' and p_request_id is not null then
14351 
14352             --Don't create dunning record for resend from here. It will be created in from calling proc.
14353     	if l_dunning_type <> 'STAGED_DUNNING' then
14354     		l_dunning_rec.dunning_level := l_level;
14355     		--Added for bug 9547105 gnramasa 20th Apr 2010
14356     		if l_level = 'DELINQUENCY' then
14357     			l_dunning_rec.delinquency_id := p_source_id;
14358     		end if;
14359     		l_dunning_rec.dunning_object_id := p_source_id;
14360     		l_dunning_rec.callback_yn := 'N';
14361     		l_dunning_rec.status := 'OPEN';
14362     		l_dunning_rec.dunning_method:= p_method;
14363     		l_dunning_rec.xml_template_id:= p_template_id;
14364     		--l_dunning_rec.xml_request_id := l_request_id;
14365     		l_dunning_rec.object_type := p_object_code;
14366     		l_dunning_rec.object_id := p_object_id;
14367     		l_dunning_rec.contact_destination := l_contact;   -- bug 3955222
14368     		l_dunning_rec.contact_party_id := l_contact_party_id;   -- bug 3955222
14369 
14370     		l_dunning_rec.org_id := p_org_id; -- added for bug 9151851
14371 
14372     		if p_parent_request_id is not null then
14373     			l_dunning_rec.request_id := p_parent_request_id;
14374     		else
14375     			l_dunning_rec.request_id := FND_GLOBAL.Conc_Request_Id;
14376     		end if;
14377 
14378     		l_dunning_rec.dunning_mode := p_dunning_mode;
14379     		l_dunning_rec.correspondence_date	:= p_correspondence_date;
14380 
14381     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
14382     		WriteLog('before create dunning org_id ' || p_org_id);
14383     		CREATE_DUNNING(p_api_version              => 1.0
14384     			      ,p_init_msg_list            => FND_API.G_FALSE
14385     			      ,p_commit                   => FND_API.G_TRUE
14386     			      ,p_dunning_rec              => l_dunning_rec
14387     			      ,x_dunning_id               => l_dunning_id
14388     			      ,x_return_status            => l_return_status1
14389     			      ,x_msg_count                => l_msg_count1
14390     			      ,x_msg_data                 => l_msg_data1);
14391 
14392     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| l_return_status1);
14393     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_id='||l_dunning_id);
14394 
14395     		IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
14396     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
14397     		END IF;
14398 
14399     		if p_object_code = 'IEX_INVOICES' then
14400     			    BEGIN
14401     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_object_id: ' || p_object_id);
14402 
14403     				select customer_trx_id, payment_schedule_id
14404     				into l_transaction_id, l_payment_schedule_id
14405     				from ar_payment_schedules_all
14406     				where customer_trx_id = p_object_id;
14407     			    EXCEPTION
14408     				WHEN OTHERS THEN
14409     				    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' SQL stmt throws exception ');
14410     			    END;
14411 
14412     			    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_transaction_id: ' || l_transaction_id);
14413     			    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_payment_schedule_id: ' || l_payment_schedule_id);
14414     			    --insert invoice list in to iex_dunning_transactions table for all correspondence.
14415     			    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Calling IEX_Dunnings_PKG.insert_staged_dunning_row');
14416     			    IEX_Dunnings_PKG.insert_staged_dunning_row(
14417     					  px_rowid                          => l_rowid
14418     					, px_dunning_trx_id                 => x_dunning_trx_id
14419     					, p_dunning_id                      => l_dunning_id
14420     					, p_cust_trx_id                     => l_transaction_id
14421     					, p_payment_schedule_id             => l_payment_schedule_id
14422     					, p_ag_dn_xref_id                   => null
14423     					, p_stage_number                    => null
14424     					, p_created_by                      => FND_GLOBAL.USER_ID
14425     					, p_creation_date                   => sysdate
14426     					, p_last_updated_by                 => FND_GLOBAL.USER_ID
14427     					, p_last_update_date                => sysdate
14428     					, p_last_update_login               => FND_GLOBAL.USER_ID
14429     					, p_object_version_number	    => 1.0
14430     				      );
14431     			    if x_dunning_trx_id is null then
14432     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot insert record in to iex_dunning_transactions table');
14433     			    else
14434     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Insert record in to iex_dunning_transactions table is success. x_dunning_trx_id ' || x_dunning_trx_id);
14435     			    end if;
14436     		    end if;
14437 
14438     		    l_bind_count := l_fulfillment_bind_tbl.count;
14439     		    l_fulfillment_bind_tbl(l_bind_count + 1).key_name := 'DUNNING_ID';
14440     		    l_fulfillment_bind_tbl(l_bind_count + 1).key_type := 'NUMBER';
14441     		    l_fulfillment_bind_tbl(l_bind_count + 1).key_value := l_dunning_id;
14442 
14443     	end if; --if l_dunning_type <> 'STAGED_DUNNING' then
14444 
14445     	Open c_get_resend_data(p_request_id);
14446             Fetch c_get_resend_data into l_query_temp_id, l_addt_query_temp_id, l_dest;
14447             Close c_get_resend_data;
14448 
14449     	Open c_get_resend_query_data(l_query_temp_id);
14450     	Fetch c_get_resend_query_data into l_query_id;
14451             Close c_get_resend_query_data;
14452 
14453     	if l_addt_query_temp_id is not null and l_addt_query_temp_id >0 then
14454     	Open c_get_resend_query_data(l_addt_query_temp_id);
14455     	Fetch c_get_resend_query_data into l_addt_query_id;
14456             Close c_get_resend_query_data;
14457             end if;
14458 
14459             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_query_id = ' || l_query_id);
14460     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_addt_query_id = ' || l_addt_query_id);
14461             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dest = ' || l_dest);
14462 
14463             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Call SEND_COPY');
14464             WriteLog(' before send_copy org_id ' || p_org_id);
14465             BEGIN
14466     		IEX_SEND_XML_PVT.Send_COPY(p_api_version_number => l_api_version
14467     				  ,p_init_msg_list   => FND_API.G_FALSE
14468     				  ,p_commit          => FND_API.G_TRUE
14469     				  ,p_resend          => l_resend
14470     				  ,p_request_id      => p_request_id
14471     				  ,p_user_id         => l_user_id
14472     				  ,p_party_id        => p_party_id
14473     				  ,p_subject         => l_subject
14474     				  ,p_template_id     => p_template_id
14475     				  ,p_resource_id     => l_resource_id
14476     				  ,p_query_id        => l_query_id
14477     				  ,p_method          => p_method
14478     				  ,p_dest            => l_dest
14479     				  ,p_bind_tbl        => l_fulfillment_bind_tbl
14480     				  ,p_level           => l_level
14481     				  ,p_source_id       => p_source_id
14482     				  ,p_object_type     => p_object_code
14483     				  ,p_object_id       => p_object_id
14484     				  ,p_dunning_mode    => p_dunning_mode  -- added by gnramasa for bug 8489610 14-May-09
14485     				  ,p_parent_request_id => p_parent_request_id  -- added by gnramasa for bug 8489610 14-May-09
14486     				  ,p_org_id          => p_org_id -- added for bug 9151851
14487     				  ,p_addt_template_id  => p_addt_template_id
14488     				  ,p_addt_query_id    => l_addt_query_id
14489     				  ,x_request_id      => l_request_id
14490     				  ,x_return_status   => l_return_status
14491     				  ,x_msg_count       => l_msg_count
14492     				  ,x_msg_data        => l_msg_data);
14493 
14494     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - After SEND_COPY:'||l_return_status);
14495 
14496     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS or l_request_id is null THEN
14497     			l_return_status := FND_API.G_RET_STS_ERROR;
14498     			x_msg_count := l_msg_count;
14499     			x_msg_data := l_msg_data;
14500     		ELSE --xml creation is success, so update the dunning_id rec with xml_request_id
14501     			--For staged dunning, dunning record will be created with request_id from resend procedure.
14502     			if l_dunning_type <> 'STAGED_DUNNING' then
14503     				 if l_request_id is not null then
14504     					--l_dunning_upd_rec.DUNNING_ID := l_dunning_id;
14505     					for i in 1..l_fulfillment_bind_tbl.count loop
14506     					    if l_fulfillment_bind_tbl(i).key_name = 'DUNNING_ID' then
14507     						l_dunning_upd_rec.DUNNING_ID := to_number(l_fulfillment_bind_tbl(i).KEY_VALUE);
14508     						exit;
14509     					    end if;
14510     					end loop;
14511     					l_dunning_upd_rec.xml_request_id := l_request_id;
14512     					WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_upd_rec.DUNNING_ID: ' || l_dunning_upd_rec.DUNNING_ID);
14513     					WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_upd_rec.xml_request_id: ' || l_dunning_upd_rec.xml_request_id);
14514 
14515     					if l_dunning_upd_rec.xml_request_id is not null then
14516     					    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Update dunning Row with xml request id');
14517 
14518     					    IEX_DUNNING_PVT.Update_DUNNING(
14519     						   p_api_version              => 1.0
14520     						 , p_init_msg_list            => FND_API.G_FALSE
14521     						 , p_commit                   => FND_API.G_TRUE
14522     						 , p_dunning_rec              => l_dunning_upd_rec
14523     						 , x_return_status            => l_return_status1
14524     						 , x_msg_count                => l_msg_count1
14525     						 , x_msg_data                 => l_msg_data1);
14526 
14527     					    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Update Dunning status='|| l_return_status1);
14528     					end if;
14529 
14530     				 end if; --if l_request_id is not null then
14531     			end if;  --if l_dunning_type <> 'STAGED_DUNNING' then
14532     		END IF;
14533 
14534             EXCEPTION
14535                 WHEN OTHERS THEN
14536                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' throws exception');
14537                     l_return_status := FND_API.G_RET_STS_ERROR;
14538                     FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_DELIVERY');
14539                     FND_MSG_PUB.Add;
14540             END;
14541 
14542         else    -- either resending after error or sending for the first time
14543 
14544             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Calling GET_DEFAULT_DUN_DATA...');
14545 
14546             GET_DEFAULT_DUN_DATA(p_api_version => 1.0,
14547                                p_init_msg_list => FND_API.G_TRUE,
14548                                p_commit => FND_API.G_FALSE,
14549                                p_level => l_level,
14550                                p_source_id => p_source_id,
14551                                p_send_method => p_method,
14552                                p_resend => l_resend,
14553                                p_object_code => p_object_code,
14554                                p_object_id => p_object_id,
14555                                p_fulfillment_bind_tbl => l_fulfillment_bind_tbl,
14556                                x_return_status => l_return_status,
14557                                x_msg_count => l_msg_count,
14558                                x_msg_data => l_msg_data);
14559 
14560             WriteLog('---------- continue ' || l_api_name || '----------');
14561             WriteLog(G_PKG_NAME || ' ' || l_api_name || ': l_return_status: ' || l_return_status);
14562             WriteLog(G_PKG_NAME || ' ' || l_api_name || ': l_msg_count: ' || l_msg_count);
14563 
14564             IF l_return_status <> FND_API.G_RET_STS_SUCCESS then
14565                 GOTO end_call_ffm;
14566             end if;
14567 
14568             --reviewing default dunning data
14569             for k in 1..l_fulfillment_bind_tbl.count loop
14570                 if l_fulfillment_bind_tbl(k).key_name  = 'CONTACT_POINT_ID' then
14571                     l_contact_point_id := l_fulfillment_bind_tbl(k).key_value;
14572                 elsif l_fulfillment_bind_tbl(k).key_name  = 'LOCATION_ID' then
14573                     l_location_id := l_fulfillment_bind_tbl(k).key_value;
14574                 end if;
14575             end loop;
14576 
14577             -- checking for location
14578             IF l_location_id is null then
14579                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ': No location found');
14580                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_ADDRESS');
14581                 FND_MSG_PUB.Add;
14582                 l_return_status := FND_API.G_RET_STS_ERROR;
14583                 GOTO end_call_ffm;
14584             end if;
14585 
14586             -- setting destination
14587             IF (p_method = 'PRINTER' or p_method = 'PRINT') THEN
14588 
14589                if(p_email IS NULL OR p_email = FND_API.G_MISS_CHAR) THEN
14590                --Bug5233002. Fix by LKKUMAR on 31-May-2006. Start.
14591                OPEN  C_GET_RES_USER_ID;
14592     				   FETCH C_GET_RES_USER_ID into l_resource_user_id;
14593     				   CLOSE C_GET_RES_USER_ID;
14594                l_printer := NVL(fnd_profile.value_specific(NAME => 'IEX_PRT_IPP_PRINTER_NAME',USER_ID => l_resource_user_id),Null);
14595                 --Bug5233002. Fix by LKKUMAR on 31-May-2006. End.
14596     	   IF (l_printer is null) then
14597                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ': Setting printer from profile');
14598                 l_printer := NVL(fnd_profile.value('IEX_PRT_IPP_PRINTER_NAME'), '');
14599     	   END IF;
14600 
14601                    IF (l_printer = '' or l_printer is null)  THEN
14602                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Printer',0);
14603                        FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_PRINTER');
14604                        FND_MSG_PUB.Add;
14605                        l_return_status := FND_API.G_RET_STS_ERROR;
14606                        GOTO end_call_ffm;
14607                     END IF;
14608 
14609                 else
14610                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ': Setting printer as passed');
14611                     l_printer := p_email;
14612                 end if;
14613 
14614                 l_dest := l_printer;
14615                 l_email := '';
14616                 l_fax := '';
14617                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ': Will use printer: ' || l_dest);
14618 
14619             ELSE -- method is not PRINTER
14620 
14621                 if(p_email IS NULL OR p_email = FND_API.G_MISS_CHAR) THEN
14622 
14623                     if l_contact_point_id is null then
14624                        if p_method = 'EMAIL' then
14625                            WriteLog(G_PKG_NAME || ' ' || l_api_name || ': No email found');
14626                            FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_EMAIL');
14627                            FND_MSG_PUB.Add;
14628                        ELSIF p_method = 'FAX' THEN
14629                            WriteLog(G_PKG_NAME || ' ' || l_api_name || ': No fax found');
14630                            FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_FAX');
14631                            FND_MSG_PUB.Add;
14632                        end if;
14633 
14634                        l_return_status := FND_API.G_RET_STS_ERROR;
14635                        GOTO end_call_ffm;
14636                     end if;
14637 
14638                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ': Setting destination from defaulting data');
14639                     open c_get_contact_point(l_contact_point_id, p_method);
14640                     fetch c_get_contact_point into l_contact;
14641                     close c_get_contact_point;
14642 
14643                     l_dest := l_contact;
14644                 else
14645                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ': Setting destination as passed');
14646                     l_dest := p_email;
14647                 end if;
14648 
14649                 l_printer := '';
14650                 l_fax := '';
14651 
14652                 if p_method = 'EMAIL' then
14653                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ': Will use email: ' || l_dest);
14654                 ELSIF p_method = 'FAX' THEN
14655                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ': Will use fax: ' || l_dest);
14656                 end if;
14657             END IF;
14658             -- for the following object,
14659             -- create dunning with ACCOUNT level, but xml template is CUSTOMER level;
14660             --
14661             l_temp_level := l_level;
14662             IF ( p_object_code = 'IEX_REVERSAL' or
14663               p_object_code = 'IEX_ADJUSTMENT' or
14664               p_object_code = 'IEX_PROMISE' or
14665               p_object_code = 'IEX_PAYMENT' or
14666               p_object_code = 'IEX_CNSLD' or
14667               p_object_code = 'IEX_INVOICES' or
14668               p_object_code = 'IEX_DISPUTE' ) then
14669                 l_temp_level := 'CUSTOMER';
14670             end if;
14671 
14672             -- get query_id
14673             Open C_Get_QUERY(p_template_id, l_temp_level);
14674             LOOP
14675              Fetch C_Get_QUERY into l_query_id;
14676              If ( C_GET_QUERY%NOTFOUND ) Then
14677                   if (nIdx = 0) then
14678                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Query NotFound');
14679                       FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_QUERY');
14680                       FND_MSG_PUB.Add;
14681                       l_return_status := FND_API.G_RET_STS_ERROR;
14682                       GOTO end_call_ffm;
14683                   end if;
14684                   exit;
14685              else
14686                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - query_id='||l_query_id);
14687                   nIdx := nIdx + 1;
14688              end if;
14689             END LOOP;
14690     	close C_Get_QUERY;
14691             --------------------------------------------
14692     	-- get invoice query_id
14693     	if p_addt_template_id is not null then
14694     		Open C_Get_QUERY(p_addt_template_id, 'CUSTOMER');
14695     		LOOP
14696     		 Fetch C_Get_QUERY into l_addt_query_id;
14697     		 If ( C_GET_QUERY%NOTFOUND ) Then
14698     		      if (nIdx = 0) then
14699     			  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Query NotFound for invoice copy');
14700     			  --FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_QUERY');
14701     			  --FND_MSG_PUB.Add;
14702     			  --l_return_status := FND_API.G_RET_STS_ERROR;
14703     			  --GOTO end_call_ffm;
14704     		      end if;
14705     		      exit;
14706     		 else
14707     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_addt_query_id='||l_addt_query_id);
14708     		      nIdx := nIdx + 1;
14709     		 end if;
14710     		END LOOP;
14711     		close C_Get_QUERY;
14712     	end if;
14713     	----------------------------------------------------
14714 
14715             l_server_id  := NULL;  -- Using Default Server
14716             IF l_return_status = FND_API.G_RET_STS_SUCCESS THEN
14717     	    --Create dunning record, before calling send_copy
14718     	   IF ( p_object_code = 'IEX_REVERSAL' or
14719     		p_object_code = 'IEX_ADJUSTMENT' or
14720     		p_object_code = 'IEX_PROMISE' or
14721     		p_object_code = 'IEX_PAYMENT' or
14722     		p_object_code = 'IEX_CNSLD' or
14723     		p_object_code = 'IEX_INVOICES' or
14724     		p_object_code = 'IEX_DISPUTE' ) THEN
14725 
14726     		    --l_dunning_rec.dunning_level := p_level;
14727     		    l_dunning_rec.dunning_level := l_level;
14728     		    --Added for bug 9547105 gnramasa 20th Apr 2010
14729     		    if l_level = 'DELINQUENCY' then
14730     			l_dunning_rec.delinquency_id := p_source_id;
14731     		    end if;
14732     		    l_dunning_rec.dunning_object_id := p_source_id;
14733     		    l_dunning_rec.callback_yn := 'N';
14734     		    --Start for bug 9781971 gnramasa 8th June 10
14735     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_dunning_mode: ' || p_dunning_mode);
14736     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_object_code: ' || p_object_code);
14737     		    if p_dunning_mode = 'DRAFT' and p_object_code = 'IEX_INVOICES' then
14738     			l_dunning_rec.status := 'CLOSE';
14739     		    else
14740     			l_dunning_rec.status := 'OPEN';
14741     		    end if;
14742     		    --End for bug 9781971 gnramasa 8th June 10
14743     		    l_dunning_rec.dunning_method:= p_method;
14744     		    l_dunning_rec.xml_template_id:= p_template_id;
14745     		    --l_dunning_rec.xml_request_id := l_request_id;
14746     		    l_dunning_rec.object_type := p_object_code;
14747     		    l_dunning_rec.object_id := p_object_id;
14748     		    l_dunning_rec.contact_destination := l_contact;   -- bug 3955222
14749     		    l_dunning_rec.contact_party_id := l_contact_party_id;   -- bug 3955222
14750     		    l_dunning_rec.org_id := p_org_id;  -- added for bug 9151851
14751 
14752     		    if p_parent_request_id is not null then
14753     			l_dunning_rec.request_id := p_parent_request_id;
14754     		    else
14755     			l_dunning_rec.request_id := FND_GLOBAL.Conc_Request_Id;
14756     		    end if;
14757 
14758     		    l_dunning_rec.dunning_mode := p_dunning_mode;
14759     		    l_dunning_rec.correspondence_date	:= p_correspondence_date;
14760 
14761     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
14762     		    WriteLog(' before create dunning org_id ' || p_org_id);
14763     		    CREATE_DUNNING(p_api_version              => 1.0
14764     				  ,p_init_msg_list            => FND_API.G_FALSE
14765     				  ,p_commit                   => FND_API.G_TRUE
14766     				  ,p_dunning_rec              => l_dunning_rec
14767     				  ,x_dunning_id               => l_dunning_id
14768     				  ,x_return_status            => l_return_status1
14769     				  ,x_msg_count                => l_msg_count1
14770     				  ,x_msg_data                 => l_msg_data1);
14771 
14772     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| l_return_status1);
14773     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_id='||l_dunning_id);
14774 
14775     		    IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
14776     		       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
14777     		    END IF;
14778 
14779     		    if p_object_code = 'IEX_INVOICES' then
14780     			    BEGIN
14781     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_object_id: ' || p_object_id);
14782 
14783     				select customer_trx_id, payment_schedule_id
14784     				into l_transaction_id, l_payment_schedule_id
14785     				from ar_payment_schedules_all
14786     				where customer_trx_id = p_object_id;
14787     			    EXCEPTION
14788     				WHEN OTHERS THEN
14789     				    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' SQL stmt throws exception ');
14790     			    END;
14791 
14792     			    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_transaction_id: ' || l_transaction_id);
14793     			    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_payment_schedule_id: ' || l_payment_schedule_id);
14794     			    --insert invoice list in to iex_dunning_transactions table for all correspondence.
14795     			    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Calling IEX_Dunnings_PKG.insert_staged_dunning_row');
14796     			    IEX_Dunnings_PKG.insert_staged_dunning_row(
14797     					  px_rowid                          => l_rowid
14798     					, px_dunning_trx_id                 => x_dunning_trx_id
14799     					, p_dunning_id                      => l_dunning_id
14800     					, p_cust_trx_id                     => l_transaction_id
14801     					, p_payment_schedule_id             => l_payment_schedule_id
14802     					, p_ag_dn_xref_id                   => null
14803     					, p_stage_number                    => null
14804     					, p_created_by                      => FND_GLOBAL.USER_ID
14805     					, p_creation_date                   => sysdate
14806     					, p_last_updated_by                 => FND_GLOBAL.USER_ID
14807     					, p_last_update_date                => sysdate
14808     					, p_last_update_login               => FND_GLOBAL.USER_ID
14809     					, p_object_version_number	    => 1.0
14810     				      );
14811     			    if x_dunning_trx_id is null then
14812     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot insert record in to iex_dunning_transactions table');
14813     			    else
14814     				WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Insert record in to iex_dunning_transactions table is success. x_dunning_trx_id ' || x_dunning_trx_id);
14815     			    end if;
14816     		    end if;
14817 
14818     		    l_bind_count := l_fulfillment_bind_tbl.count;
14819     		    l_fulfillment_bind_tbl(l_bind_count + 1).key_name := 'DUNNING_ID';
14820     		    l_fulfillment_bind_tbl(l_bind_count + 1).key_type := 'NUMBER';
14821     		    l_fulfillment_bind_tbl(l_bind_count + 1).key_value := l_dunning_id;
14822 
14823               END IF; -- object_type if
14824 
14825                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Call SEND_COPY');
14826                 WriteLog( ' before send_copy org_id ' || p_org_id);
14827                 BEGIN
14828                     IEX_SEND_XML_PVT.Send_COPY(p_api_version_number => l_api_version
14829                                           ,p_init_msg_list   => FND_API.G_FALSE
14830                                           ,p_commit          => FND_API.G_TRUE
14831                                           ,p_resend          => l_resend
14832                                           ,p_request_id      => p_request_id
14833                                           ,p_user_id         => l_user_id
14834                                           ,p_party_id        => p_party_id
14835                                           ,p_subject         => l_subject
14836                                           ,p_template_id     => p_template_id
14837                                           ,p_resource_id     => l_resource_id
14838                                           ,p_query_id        => l_query_id
14839                                           ,p_method          => p_method
14840                                           ,p_dest            => l_dest
14841                                           ,p_bind_tbl        => l_fulfillment_bind_tbl
14842                                           ,p_level           => l_level
14843                                           ,p_source_id       => p_source_id
14844                                           ,p_object_type     => p_object_code
14845                                           ,p_object_id       => p_object_id
14846     				      ,p_dunning_mode    => p_dunning_mode  -- added by gnramasa for bug 8489610 14-May-09
14847     				      ,p_parent_request_id => p_parent_request_id  -- added by gnramasa for bug 8489610 14-May-09
14848                                           ,p_org_id          => p_org_id  -- added for bug 9151851
14849     				      ,p_addt_template_id  => p_addt_template_id
14850     				      ,p_addt_query_id    => l_addt_query_id
14851     				      ,x_request_id      => l_request_id
14852                                           ,x_return_status   => l_return_status
14853                                           ,x_msg_count       => l_msg_count
14854                                           ,x_msg_data        => l_msg_data);
14855 
14856                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - After SEND_COPY:'||l_return_status);
14857 
14858                    IF l_return_status <> FND_API.G_RET_STS_SUCCESS or l_request_id is null THEN
14859                      l_return_status := FND_API.G_RET_STS_ERROR;
14860                      x_msg_count := l_msg_count;
14861                      x_msg_data := l_msg_data;
14862     	       ELSE --xml creation is success, so update the dunning_id rec with xml_request_id
14863     		 if l_request_id is not null then
14864     			--l_dunning_upd_rec.DUNNING_ID := l_dunning_id;
14865     			for i in 1..l_fulfillment_bind_tbl.count loop
14866     			    if l_fulfillment_bind_tbl(i).key_name = 'DUNNING_ID' then
14867     				l_dunning_upd_rec.DUNNING_ID := to_number(l_fulfillment_bind_tbl(i).KEY_VALUE);
14868     				exit;
14869     			    end if;
14870     			end loop;
14871     			l_dunning_upd_rec.xml_request_id := l_request_id;
14872     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_upd_rec.DUNNING_ID: ' || l_dunning_upd_rec.DUNNING_ID);
14873     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_dunning_upd_rec.xml_request_id: ' || l_dunning_upd_rec.xml_request_id);
14874 
14875     			if l_dunning_upd_rec.xml_request_id is not null then
14876     			    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Update dunning Row with xml request id');
14877 
14878     			    IEX_DUNNING_PVT.Update_DUNNING(
14879     				   p_api_version              => 1.0
14880     				 , p_init_msg_list            => FND_API.G_FALSE
14881     				 , p_commit                   => FND_API.G_TRUE
14882     				 , p_dunning_rec              => l_dunning_upd_rec
14883     				 , x_return_status            => l_return_status1
14884     				 , x_msg_count                => l_msg_count1
14885     				 , x_msg_data                 => l_msg_data1);
14886 
14887     			    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Update Dunning status='|| l_return_status1);
14888     			end if;
14889 
14890     		    end if;
14891                    END IF;
14892 
14893                 EXCEPTION
14894                     WHEN OTHERS THEN
14895                         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' throws exception');
14896                         l_return_status := FND_API.G_RET_STS_ERROR;
14897                         FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_DELIVERY');
14898                         FND_MSG_PUB.Add;
14899                 END;
14900 
14901             END IF; -- IF l_return_status = FND_API.G_RET_STS_SUCCESS THEN
14902 
14903         end if;  --if l_resend = 'Y' and p_request_id is not null then
14904 
14905         <<end_call_ffm>>
14906 
14907         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_return_status='||l_return_status);
14908 
14909         IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
14910 
14911             l_msg := FND_MSG_PUB.Get(p_msg_index => 1, p_encoded => 'T');
14912             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  l_msg: ' || l_msg);
14913             FND_MESSAGE.PARSE_ENCODED(l_msg, l_app, l_msg_name);
14914             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Error name: ' || l_msg_name);
14915 
14916             l_dunning_rec.DELIVERY_STATUS := l_msg_name;
14917 
14918         end if;
14919 
14920         --if l_resend = 'N' then
14921 
14922             /* We need to update the delivary status for all correspondence.
14923     	   So commenting the if condition */
14924     	/*
14925     	IF(p_object_code = 'PARTY' or
14926                p_object_code = 'IEX_ACCOUNT' or
14927                p_object_code = 'IEX_BILLTO' or
14928                p_object_code = 'IEX_DELINQUENCY' or
14929                p_object_code = 'IEX_STRATEGY') THEN
14930     	*/
14931 
14932     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' -  Update dunning with delivery status: ' || l_dunning_rec.DELIVERY_STATUS);
14933 
14934 
14935     	if l_dunning_rec.DELIVERY_STATUS is not null then
14936 
14937     		for i in 1..l_fulfillment_bind_tbl.count loop
14938     		    if l_fulfillment_bind_tbl(i).key_name = 'DUNNING_ID' then
14939     			l_dunning_rec.DUNNING_ID := to_number(l_fulfillment_bind_tbl(i).KEY_VALUE);
14940     			exit;
14941     		    end if;
14942     		end loop;
14943 
14944     		if l_dunning_rec.DUNNING_ID is not null then
14945     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UpdateRow');
14946 
14947     		    IEX_DUNNING_PVT.Update_DUNNING(
14948     			   p_api_version              => 1.0
14949     			 , p_init_msg_list            => FND_API.G_FALSE
14950     			 , p_commit                   => FND_API.G_TRUE
14951     			 , p_dunning_rec              => l_dunning_rec
14952     			 , x_return_status            => l_return_status1
14953     			 , x_msg_count                => l_msg_count1
14954     			 , x_msg_data                 => l_msg_data1);
14955 
14956     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UpdateDunning status='|| l_return_status1);
14957     		end if;
14958     	end if;
14959 
14960     	/* moving this piece of code before calling GET_DEFAULT_DUN_DATA...
14961     	i.e create dunning record before going for delivery */
14962             /*
14963     	ELSE  -- always create dunning record
14964 
14965                 --l_dunning_rec.dunning_level := p_level;
14966                 l_dunning_rec.dunning_level := l_level;
14967     	    --Added for bug 9547105 gnramasa 20th Apr 2010
14968     	    if l_level = 'DELINQUENCY' then
14969     		l_dunning_rec.delinquency_id := p_source_id;
14970     	    end if;
14971                 l_dunning_rec.dunning_object_id := p_source_id;
14972                 l_dunning_rec.callback_yn := 'N';
14973     	    --Start for bug 9781971 gnramasa 8th June 10
14974     	    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_dunning_mode: ' || p_dunning_mode);
14975     	    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_object_code: ' || p_object_code);
14976     	    if p_dunning_mode = 'DRAFT' and p_object_code = 'IEX_INVOICES' then
14977     		l_dunning_rec.status := 'CLOSE';
14978     	    else
14979     		l_dunning_rec.status := 'OPEN';
14980     	    end if;
14981     	    --End for bug 9781971 gnramasa 8th June 10
14982                 l_dunning_rec.dunning_method:= p_method;
14983                 l_dunning_rec.xml_template_id:= p_template_id;
14984                 l_dunning_rec.xml_request_id := l_request_id;
14985                 l_dunning_rec.object_type := p_object_code;
14986                 l_dunning_rec.object_id := p_object_id;
14987     	    l_dunning_rec.contact_destination := l_contact;   -- bug 3955222
14988     	    l_dunning_rec.contact_party_id := l_contact_party_id;   -- bug 3955222
14989     	    l_dunning_rec.org_id := p_org_id;  -- added for bug 9151851
14990 
14991     	    if p_parent_request_id is not null then
14992     		l_dunning_rec.request_id := p_parent_request_id;
14993     	    else
14994     		l_dunning_rec.request_id := FND_GLOBAL.Conc_Request_Id;
14995     	    end if;
14996 
14997     	    l_dunning_rec.dunning_mode := p_dunning_mode;
14998     	    l_dunning_rec.correspondence_date	:= p_correspondence_date;
14999 
15000                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
15001                 WriteLog(' before create dunning org_id ' || p_org_id);
15002                 CREATE_DUNNING(p_api_version              => 1.0
15003                               ,p_init_msg_list            => FND_API.G_FALSE
15004                               ,p_commit                   => FND_API.G_TRUE
15005                               ,p_dunning_rec              => l_dunning_rec
15006                               ,x_dunning_id               => l_dunning_id
15007                               ,x_return_status            => l_return_status1
15008                               ,x_msg_count                => l_msg_count1
15009                               ,x_msg_data                 => l_msg_data1);
15010 
15011                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| l_return_status1);
15012                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_id='||l_dunning_id);
15013 
15014                 IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
15015                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
15016                 END IF;
15017     		*/ -- uo to here
15018             --END IF; -- end of p_object
15019 
15020         --else  -- if resend - always create new dunning record
15021 
15022             /*
15023     	--Don't create dunning record for resend from here. It will be created in from calling proc.
15024     	if l_dunning_type <> 'STAGED_DUNNING' then
15025     		l_dunning_rec.dunning_level := l_level;
15026     		--Added for bug 9547105 gnramasa 20th Apr 2010
15027     		if l_level = 'DELINQUENCY' then
15028     			l_dunning_rec.delinquency_id := p_source_id;
15029     		end if;
15030     		l_dunning_rec.dunning_object_id := p_source_id;
15031     		l_dunning_rec.callback_yn := 'N';
15032     		l_dunning_rec.status := 'OPEN';
15033     		l_dunning_rec.dunning_method:= p_method;
15034     		l_dunning_rec.xml_template_id:= p_template_id;
15035     		l_dunning_rec.xml_request_id := l_request_id;
15036     		l_dunning_rec.object_type := p_object_code;
15037     		l_dunning_rec.object_id := p_object_id;
15038     		l_dunning_rec.contact_destination := l_contact;   -- bug 3955222
15039     		l_dunning_rec.contact_party_id := l_contact_party_id;   -- bug 3955222
15040 
15041     		l_dunning_rec.org_id := p_org_id; -- added for bug 9151851
15042 
15043     		if p_parent_request_id is not null then
15044     			l_dunning_rec.request_id := p_parent_request_id;
15045     		else
15046     			l_dunning_rec.request_id := FND_GLOBAL.Conc_Request_Id;
15047     		end if;
15048 
15049     		l_dunning_rec.dunning_mode := p_dunning_mode;
15050     		l_dunning_rec.correspondence_date	:= p_correspondence_date;
15051 
15052     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
15053     		WriteLog('before create dunning org_id ' || p_org_id);
15054     		CREATE_DUNNING(p_api_version              => 1.0
15055     			      ,p_init_msg_list            => FND_API.G_FALSE
15056     			      ,p_commit                   => FND_API.G_TRUE
15057     			      ,p_dunning_rec              => l_dunning_rec
15058     			      ,x_dunning_id               => l_dunning_id
15059     			      ,x_return_status            => l_return_status1
15060     			      ,x_msg_count                => l_msg_count1
15061     			      ,x_msg_data                 => l_msg_data1);
15062 
15063     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CreateDunning status='|| l_return_status1);
15064     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_id='||l_dunning_id);
15065 
15066     		IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
15067     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Dunning');
15068     		END IF;
15069     	end if; --if l_dunning_type <> 'STAGED_DUNNING' then
15070     	*/
15071 
15072         --end if;
15073         --End for bug 9970624 gnramasa 4th Aug 10
15074 
15075         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_call_ffm');
15076 
15077         --bug 8567312
15078         --commit work;
15079         IF FND_API.to_Boolean( p_commit )
15080           THEN
15081               COMMIT WORK;
15082           END IF;
15083 
15084         x_request_id    := l_request_id;
15085         x_return_status := l_return_status;
15086 
15087         FND_MSG_PUB.Count_And_Get
15088         (  p_count          =>   x_msg_count,
15089            p_data           =>   x_msg_data );
15090 
15091         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_return_status: '||x_return_status);
15092         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_msg_count: '||x_msg_count);
15093         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_msg_data: '||x_msg_data);
15094 
15095         EXCEPTION
15096               WHEN FND_API.G_EXC_ERROR THEN
15097                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
15098                    errmsg := SQLERRM;
15099                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15100     --               ROLLBACK TO SEND_XML_PVT;
15101                    x_return_status := FND_API.G_RET_STS_ERROR;
15102                    FND_MSG_PUB.Count_And_Get
15103                   (  p_count          =>   x_msg_count,
15104                      p_data           =>   x_msg_data
15105                   );
15106 
15107               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
15108                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
15109                    errmsg := SQLERRM;
15110                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15111     --               ROLLBACK TO SEND_XML_PVT;
15112                    x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
15113                    FND_MSG_PUB.Count_And_Get
15114                   (  p_count          =>   x_msg_count,
15115                      p_data           =>   x_msg_data
15116                   );
15117 
15118               WHEN OTHERS THEN
15119                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
15120                    errmsg := SQLERRM;
15121                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15122     --               ROLLBACK TO SEND_XML_PVT;
15123                    x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
15124                    FND_MSG_PUB.Count_And_Get
15125                   (  p_count          =>   x_msg_count,
15126                      p_data           =>   x_msg_data
15127                   );
15128 
15129     END Send_XML;
15130 
15131     /*========================================================================
15132      * clchang updated 07/08/2003
15133      *                 for the new design of using 'Contact Purpose'.
15134      *                 - contact point is based on purpose, primary,
15135      *                   type, status;
15136      *                   Get the contact point for contact_point_purpose is
15137      *                   'DUNNING';
15138      *                   If null, get the contact point for all type;
15139      *                 - get contact point for one specific party,
15140      *                   if null, get relation party_id of relationship_type
15141      *                   is 'DUNNING', and get contact point by the relationship
15142      *                   org id;
15143      *
15144      * clchang updated 01/17/2004
15145      *                 - the party_id could be rel_party_id, person_party_id, or
15146      *                   org_party_id.
15147      *                   1. chk the party_type by chk_party_type;
15148      *                   2. if rel_party_id, call GetContactPoint first;
15149      *                      if null, (if null, same as #3)
15150      *                      => get org_party_id for this rel
15151      *                      => get org_party_id with DUNNING relationship_type
15152      *                      => call GetContactPoint
15153      *                      if null => get org_party_id directly
15154      *                   3. if org_party_id,
15155      *                      => get org_party_id with DUNNING relationship_type
15156      *                      => call GetContactPoint
15157      *                      if null => get org_party_id directly
15158      *                              => call GetContactPoint
15159      *                   4. if person_party_id,
15160      *                      => call GetContactPoint (person has no dunning rel)
15161      *
15162      *=======================================================================*/
15163 
15164     Procedure GetContactInfo ( p_api_version             IN NUMBER := 1.0,
15165                                p_init_msg_list           IN VARCHAR2 ,
15166                                p_commit                  IN VARCHAR2 ,
15167                                p_method                  IN VARCHAR2,
15168                                p_party_id                IN NUMBER,
15169                                p_dunning_level           IN VARCHAR2,
15170                                p_cust_site_use_id        IN VARCHAR2,
15171                                x_return_status           OUT NOCOPY VARCHAR2,
15172                                x_msg_count               OUT NOCOPY NUMBER,
15173                                x_msg_data                OUT NOCOPY VARCHAR2,
15174                                x_contact                 OUT NOCOPY VARCHAR2,
15175                                x_contact_party_id        OUT NOCOPY number)
15176 
15177     IS
15178         --
15179         CURSOR C_GET_ORG_EMAIL (IN_PARTY_ID NUMBER) IS
15180           SELECT email_address
15181             FROM HZ_PARTIES
15182            WHERE party_ID = in_party_ID;
15183         --
15184         CURSOR C_GET_DUNNING_ORG (IN_PARTY_ID NUMBER) IS
15185           SELECT party_id
15186             FROM HZ_RELATIONSHIPS
15187            WHERE object_id = in_party_ID
15188              AND relationship_type = 'DUNNING'
15189              AND status = 'A';
15190         --
15191         CURSOR C_GET_ORG_PARTY (IN_REL_PARTY_ID NUMBER) IS
15192           SELECT r.object_id --org party id
15193             FROM HZ_PARTIES p, HZ_RELATIONSHIPS r
15194            WHERE r.party_id = in_rel_party_ID
15195              AND p.party_id = r.object_id
15196              AND p.party_type = 'ORGANIZATION';
15197         --
15198         CURSOR C_GET_PARTY_TYPE (IN_PARTY_ID NUMBER) IS
15199           SELECT p.party_type
15200             FROM HZ_PARTIES p
15201            WHERE p.party_id = in_party_ID;
15202         --
15203     		l_api_name          CONSTANT VARCHAR2(30) := 'GetContactInfo';
15204     		l_api_version       NUMBER := 1.0;
15205     		l_commit            VARCHAR2(5);
15206     		l_party_id      NUMBER;
15207     		l_dunning_party_id  NUMBER;
15208     		l_party_type    VARCHAR2(30);
15209     		nIdx            NUMBER;
15210     		l_msg_count     NUMBER;
15211     		l_msg_data      VARCHAR2(1000);
15212     		errmsg          VARCHAR2(32767);
15213     		l_return_status VARCHAR2(1000);
15214     		l_email         VARCHAR2(2000);
15215     		l_printer       VARCHAR2(2000);
15216     		l_fax           VARCHAR2(2000);
15217     		l_primary       VARCHAR2(10);
15218 
15219     BEGIN
15220 
15221          -- Standard Start of API savepoint
15222          SAVEPOINT GetContactInfo_PVT;
15223 
15224          l_commit     := p_commit;
15225          x_contact_party_id := p_party_id; -- default to origal party_id until updated #3955222
15226 
15227         -- Initialize message list IF p_init_msg_list is set to TRUE.
15228         IF FND_API.to_Boolean( p_init_msg_list )
15229         THEN
15230             FND_MSG_PUB.initialize;
15231         END IF;
15232 
15233         -- Initialize API return status to SUCCESS
15234         l_return_status := FND_API.G_RET_STS_SUCCESS;
15235         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
15236 
15237         if (p_party_id is null) then
15238             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No PARTY_ID');
15239             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_PARTY');
15240             FND_MSG_PUB.Add;
15241             l_return_status := FND_API.G_RET_STS_ERROR;
15242             GOTO end_getcontact;
15243         end if;
15244         if (p_method is null) then
15245             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No METHOD');
15246             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_METHOD');
15247             FND_MSG_PUB.Add;
15248             l_return_status := FND_API.G_RET_STS_ERROR;
15249             GOTO end_getcontact;
15250         end if;
15251 
15252         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Party_id='||p_party_id);
15253         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - method='||p_method);
15254 
15255        /*=======================================
15256         * get the primary contact email first;
15257         * if not found, get org email address;
15258         =======================================*/
15259         if instr( p_method, 'PRINT' ) > 0 then
15260           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get Printer');
15261           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - userid= '||FND_GLOBAL.USER_ID);
15262           l_printer := NVL(fnd_profile.value('IEX_FFM_PRINTER'), '');
15263           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Printer:'||l_printer);
15264           if (l_printer = '' or l_printer is null) then
15265              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Printer');
15266              FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_PRINTER');
15267              FND_MSG_PUB.Add;
15268              l_return_status := FND_API.G_RET_STS_ERROR;
15269              GOTO end_getcontact;
15270           end if;
15271           x_contact := l_printer;
15272 
15273         else
15274           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get party type');
15275           Open C_Get_PARTY_TYPE(p_party_id);
15276           Fetch C_Get_PARTY_TYPE into l_party_type;
15277           If ( C_GET_PARTY_TYPE%NOTFOUND ) Then
15278              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - cannot find party type');
15279              FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_PARTYTYPE');
15280              FND_MSG_PUB.Add;
15281              l_return_status := FND_API.G_RET_STS_ERROR;
15282              Close C_Get_PARTY_TYPE;
15283              GOTO end_getcontact;
15284           END IF;
15285           Close C_Get_PARTY_TYPE;
15286           --
15287           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - party_type=' ||l_party_type);
15288           --
15289           -- if organization, need to get the org party id  with dunning type first.
15290           --
15291           IF (l_party_type = 'PERSON' or l_party_type = 'PARTY_RELATIONSHIP') then
15292             GetContactPoint(
15293                        p_api_version              => p_api_version
15294                      , p_init_msg_list            => p_init_msg_list
15295                      , p_commit                   => p_commit
15296                      , p_method                   => p_method
15297                      , p_party_id                 => p_party_id
15298                      , x_return_status            => l_return_status
15299                      , x_msg_count                => l_msg_count
15300                      , x_msg_data                 => l_msg_data
15301                      , x_contact                  => x_contact
15302             );
15303 
15304             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - status='||l_return_status);
15305             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - contact='||x_contact);
15306           END IF;
15307 
15308           -- person doesnt have dunning type
15309           -- so, we only check person contact point by GetContactPoint.
15310           IF (l_party_type = 'PERSON' and
15311               (x_contact is null or l_return_status <> FND_API.G_RET_STS_SUCCESS))
15312           then
15313               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - person contact NotFound');
15314               FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_CONTACTINFO');
15315               FND_MSG_PUB.Add;
15316               l_return_status := FND_API.G_RET_STS_ERROR;
15317               GOTO end_getcontact;
15318           end if;
15319           --
15320           -- if relationship or organization,
15321           -- get the org_party_id with relationship type DUNNING first,
15322           --
15323           -- one party_is could have more than one rel party id with type DUNNING.
15324           -- using LOOP to fetch data until Contact Point is found.
15325           --
15326           nIdx := 0;
15327           if (l_party_type = 'ORGANIZATION') then
15328               l_party_id := p_party_id;
15329           else
15330               -- get org_party_id
15331               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get_org_party');
15332               Open C_Get_ORG_PARTY(p_party_id);
15333               Fetch C_Get_ORG_PARTY into l_party_id;
15334               If ( C_GET_ORG_PARTY%NOTFOUND ) Then
15335                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - cannot find org party');
15336                  FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_ORG');
15337                  FND_MSG_PUB.Add;
15338                  l_return_status := FND_API.G_RET_STS_ERROR;
15339                  Close C_Get_ORG_PARTY;
15340                  GOTO end_getcontact;
15341               end if;
15342               x_contact_party_id := l_party_id; -- default to org party_id until updated #3955222
15343               Close C_Get_ORG_PARTY;
15344           end if;
15345           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - org_party_id='||l_party_id);
15346           --
15347           if (l_party_type <> 'PERSON' and
15348               (x_contact is null or l_return_status <> FND_API.G_RET_STS_SUCCESS))
15349           THEN
15350 
15351               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get dunning party_id');
15352               Open C_Get_DUNNING_ORG(l_party_id);
15353 
15354                 Fetch C_Get_DUNNING_ORG into l_dunning_party_id;
15355 
15356                 If ( C_GET_DUNNING_ORG%NOTFOUND or l_dunning_party_id is null) Then
15357                   if (nIdx = 0 ) then
15358                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No Dunning PartyId');
15359                     l_return_status := FND_API.G_RET_STS_ERROR;
15360                   end if;
15361 
15362                 ELSE
15363                   nIdx := nIdx + 1;
15364                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - rel party_id = '||l_dunning_party_id );
15365                   l_return_status := FND_API.G_RET_STS_SUCCESS;
15366                   GetContactPoint(
15367                        p_api_version              => p_api_version
15368                      , p_init_msg_list            => p_init_msg_list
15369                      , p_commit                   => p_commit
15370                      , p_method                   => p_method
15371                      , p_party_id                 => l_dunning_party_id
15372                      , x_return_status            => l_return_status
15373                      , x_msg_count                => l_msg_count
15374                      , x_msg_data                 => l_msg_data
15375                      , x_contact                  => x_contact
15376                   );
15377                   x_contact_party_id := l_dunning_party_id; -- default to dunning party_id until updated #3955222
15378 
15379                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - status='||l_return_status);
15380                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - contact='||x_contact);
15381 
15382                   if (x_contact is not null and
15383                       l_return_status = FND_API.G_RET_STS_SUCCESS) THEN
15384                       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Found ContactPint!');
15385                   end if;
15386 
15387                end if;
15388 
15389               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_contact='||x_contact);
15390               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - close c_get_dunning_org');
15391               Close C_Get_DUNNING_ORG;
15392 
15393               -- if cannot find the contact point for dunning party id,
15394               -- try to get the contact point by the org party id (no dunning type).
15395               --
15396               if (x_contact is null or
15397                   l_return_status <> FND_API.G_RET_STS_SUCCESS)
15398               THEN
15399               --
15400                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No ContactPoint for Duning Party');
15401                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get party_id contactpoint');
15402                   -- get ContactPoint by org_party_id directyly (no Dunning type)
15403                   GetContactPoint(
15404                        p_api_version              => p_api_version
15405                      , p_init_msg_list            => p_init_msg_list
15406                      , p_commit                   => p_commit
15407                      , p_method                   => p_method
15408                      , p_party_id                 => l_party_id
15409                      , x_return_status            => l_return_status
15410                      , x_msg_count                => l_msg_count
15411                      , x_msg_data                 => l_msg_data
15412                      , x_contact                  => x_contact
15413                      );
15414                  x_contact_party_id := l_party_id; -- default to origal party_id until updated #3955222
15415                end if;
15416                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_contact='||x_contact);
15417 
15418           end if; -- ( end of if x_contact of original party_id is null)
15419         --
15420         END IF;  -- ( end of method <> printer)
15421 
15422         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_contact:'||x_contact);
15423 
15424         <<end_getcontact>>
15425         x_return_status := l_return_status;
15426         if (x_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
15427             x_contact := '';
15428         END IF;
15429 
15430         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return_status:'||x_return_status);
15431         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ContactInfo:'||x_contact);
15432 
15433         FND_MSG_PUB.Count_And_Get
15434         (  p_count          =>   x_msg_count,
15435            p_data           =>   x_msg_data );
15436 
15437         EXCEPTION
15438               WHEN FND_API.G_EXC_ERROR THEN
15439                   ROLLBACK TO GetContactInfo_PVT;
15440                   x_return_status := FND_API.G_RET_STS_ERROR;
15441                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exp Exception');
15442                   errmsg := SQLERRM;
15443                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15444                   FND_MSG_PUB.Count_And_Get
15445                   (  p_count          =>   x_msg_count,
15446                      p_data           =>   x_msg_data
15447                   );
15448 
15449               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
15450                   ROLLBACK TO GetContactInfo_PVT;
15451                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
15452                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExp Exception');
15453                   errmsg := SQLERRM;
15454                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15455                   FND_MSG_PUB.Count_And_Get
15456                   (  p_count          =>   x_msg_count,
15457                      p_data           =>   x_msg_data
15458                   );
15459 
15460               WHEN OTHERS THEN
15461                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
15462                   ROLLBACK TO GetContactInfo_PVT;
15463                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
15464                   errmsg := SQLERRM;
15465                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15466                   FND_MSG_PUB.Count_And_Get
15467                   (  p_count          =>   x_msg_count,
15468                      p_data           =>   x_msg_data
15469                   );
15470 
15471     END GetContactInfo;
15472 
15473     -- new procedure clchang added 07/08/2003 in 11.5.10
15474     -- only for Fax and Email method
15475     Procedure GetContactPoint ( p_api_version             IN NUMBER := 1.0,
15476                                p_init_msg_list           IN VARCHAR2 ,
15477                                p_commit                  IN VARCHAR2 ,
15478                                p_method                  IN VARCHAR2,
15479                                p_party_id                IN NUMBER,
15480                                x_return_status           OUT NOCOPY VARCHAR2,
15481                                x_msg_count               OUT NOCOPY NUMBER,
15482                                x_msg_data                OUT NOCOPY VARCHAR2,
15483                                x_contact                 OUT NOCOPY VARCHAR2)
15484     IS
15485         --
15486         -- clchang updated 07/08/2003 to get fax and email on the new design
15487         -- of using 'Contact Purpose'
15488         -- (since 11.5.10)
15489         --
15490         CURSOR C_GET_CONTACT_EMAIL (IN_PARTY_ID NUMBER, IN_TYPE VARCHAR2) IS
15491           SELECT email_address,
15492                  decode(primary_by_purpose, 'Y',1,2) purpose,
15493                  decode(primary_flag, 'Y',1,2) primary
15494             FROM HZ_CONTACT_POINTS
15495            WHERE owner_table_ID = in_party_ID
15496              AND owner_table_name = 'HZ_PARTIES'
15497              --AND Contact_point_type = 'EMAIL'
15498              AND upper(Contact_point_type) = IN_TYPE
15499              AND Contact_point_purpose = 'DUNNING'
15500              AND NVL(do_not_use_flag, 'N') = 'N'
15501              AND (status = 'A' OR status <> 'I')
15502            order by purpose, primary;
15503         --
15504         CURSOR C_GET_CONTACT_EMAIL2 (IN_PARTY_ID NUMBER, IN_TYPE VARCHAR2) IS
15505           SELECT email_address,
15506                  decode(primary_flag, 'Y',1,2) primary
15507             FROM HZ_CONTACT_POINTS
15508            WHERE owner_table_ID = in_party_ID
15509              AND owner_table_name = 'HZ_PARTIES'
15510              --AND Contact_point_type = 'EMAIL'
15511              AND upper(Contact_point_type) = IN_TYPE
15512              AND NVL(do_not_use_flag, 'N') = 'N'
15513              AND (status = 'A' OR status <> 'I')
15514            order by primary;
15515         --
15516         CURSOR C_GET_CONTACT_FAX (IN_PARTY_ID NUMBER) IS
15517           SELECT phone_country_code || phone_area_code||phone_number faxnum,
15518                  decode(primary_by_purpose, 'Y',1,2) purpose,
15519                  decode(primary_flag, 'Y', 1, 2) primary
15520             FROM HZ_CONTACT_POINTS
15521            WHERE owner_table_ID = in_party_ID
15522              AND owner_table_name = 'HZ_PARTIES'
15523              AND upper(Contact_point_type) = 'PHONE'
15524              AND upper(phone_line_type) = 'FAX'
15525              AND Contact_point_purpose = 'DUNNING'
15526              AND NVL(do_not_use_flag, 'N') = 'N'
15527              AND (status = 'A' OR status <> 'I')
15528            order by purpose, primary;
15529         --
15530         CURSOR C_GET_CONTACT_FAX2 (IN_PARTY_ID NUMBER) IS
15531           SELECT phone_country_code || phone_area_code||phone_number faxnum,
15532                  decode(primary_flag, 'Y', 1, 2) primary
15533             FROM HZ_CONTACT_POINTS
15534            WHERE owner_table_ID = in_party_ID
15535              AND owner_table_name = 'HZ_PARTIES'
15536              AND upper(Contact_point_type) = 'PHONE'
15537              AND upper(phone_line_type) = 'FAX'
15538              AND NVL(do_not_use_flag, 'N') = 'N'
15539              AND (status = 'A' OR status <> 'I')
15540            order by primary;
15541         --
15542         --
15543     l_api_name          CONSTANT VARCHAR2(30) := 'GetContactPoint';
15544     l_api_version       NUMBER := 1.0;
15545     l_commit            VARCHAR2(5) ;
15546     --
15547     l_party_id      NUMBER;
15548     --
15549     l_msg_count     NUMBER;
15550     l_msg_data      VARCHAR2(1000);
15551     errmsg          VARCHAR2(32767);
15552     l_return_status VARCHAR2(1000);
15553     --
15554     --
15555     l_email         VARCHAR2(2000);
15556     l_printer       VARCHAR2(2000);
15557     l_fax           VARCHAR2(2000);
15558     l_primary       VARCHAR2(10);
15559     l_purpose       VARCHAR2(10);
15560     --
15561 
15562     BEGIN
15563 
15564          -- Standard Start of API savepoint
15565          SAVEPOINT GetContactPoint_PVT;
15566 
15567          l_commit    := p_commit;
15568 
15569         -- Initialize message list IF p_init_msg_list is set to TRUE.
15570         IF FND_API.to_Boolean( p_init_msg_list )
15571         THEN
15572             FND_MSG_PUB.initialize;
15573         END IF;
15574 
15575         -- Initialize API return status to SUCCESS
15576         l_return_status := FND_API.G_RET_STS_SUCCESS;
15577 
15578         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
15579 
15580         if (p_party_id is null) then
15581             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No PARTY_ID');
15582             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_PARTY');
15583             FND_MSG_PUB.Add;
15584             l_return_status := FND_API.G_RET_STS_ERROR;
15585             GOTO end_getcontact;
15586         end if;
15587         if (p_method is null) then
15588             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - No METHOD');
15589             FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_METHOD');
15590             FND_MSG_PUB.Add;
15591             l_return_status := FND_API.G_RET_STS_ERROR;
15592             GOTO end_getcontact;
15593         end if;
15594 
15595         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Party_id='||p_party_id);
15596         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - method='||p_method);
15597        /*=======================================
15598         * get the primary contact email first;
15599         * if not found, get org email address;
15600         =======================================*/
15601         if (upper(p_method) = 'EMAIL') then
15602         --
15603           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - get Email');
15604           Open C_Get_CONTACT_EMAIL(p_party_id, 'EMAIL');
15605           Fetch C_Get_CONTACT_EMAIL into l_email, l_purpose, l_primary;
15606 
15607           -- 1. there's record in contact table with type = EMAIL,
15608           --    but the email is null;
15609           -- 2. or no record in contact table with type = EMAIL;
15610 
15611           If ( C_GET_CONTACT_EMAIL%NOTFOUND OR l_email is null) Then
15612 
15613              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Email NotFound in C_GET_CONTACT_EMAIL');
15614              Open C_Get_CONTACT_EMAIL2(p_party_id, 'EMAIL');
15615              Fetch C_Get_CONTACT_EMAIL2 into l_email, l_primary;
15616 
15617              If ( C_GET_CONTACT_EMAIL2%NOTFOUND) Then
15618                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Customer NotFound');
15619                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_EMAIL');
15620                 FND_MSG_PUB.Add;
15621                 l_return_status := FND_API.G_RET_STS_ERROR;
15622                 Close C_Get_CONTACT_EMAIL2;
15623                 Close C_Get_CONTACT_EMAIL;
15624                 GOTO end_getcontact;
15625              end if;
15626              --
15627              If ( l_email is null ) Then
15628                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EmailAddress NotFound in C_GET_ORG_EMAIL');
15629                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_EMAIL');
15630                 FND_MSG_PUB.Add;
15631                 l_return_status := FND_API.G_RET_STS_ERROR;
15632                 Close C_Get_CONTACT_EMAIL2;
15633                 Close C_Get_CONTACT_EMAIL;
15634                 GOTO end_getcontact;
15635              end if;
15636              --
15637              Close C_Get_CONTACT_EMAIL2;
15638           end if;
15639 
15640           If ( l_email is null ) Then
15641                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - EmailAddress is null');
15642                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_EMAIL');
15643                 FND_MSG_PUB.Add;
15644              l_return_status := FND_API.G_RET_STS_ERROR;
15645              Close C_Get_CONTACT_EMAIL;
15646              GOTO end_getcontact;
15647           end if;
15648 
15649           x_contact := l_email;
15650 
15651           Close C_Get_CONTACT_EMAIL;
15652           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - email='||l_email);
15653 
15654         --
15655         --
15656         elsif (upper(p_method) = 'FAX') then
15657         --
15658           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get Fax');
15659           Open C_Get_CONTACT_FAX(p_party_id);
15660           Fetch C_Get_CONTACT_FAX into l_fax, l_purpose, l_primary;
15661 
15662          If ( C_GET_CONTACT_FAX%NOTFOUND OR l_fax is null) Then
15663 
15664              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Fax NotFound in C_GET_CONTACT_FAX');
15665              Open C_Get_CONTACT_FAX2(p_party_id);
15666              Fetch C_Get_CONTACT_FAX2 into l_fax, l_primary;
15667 
15668              If ( C_GET_CONTACT_FAX2%NOTFOUND) Then
15669                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Customer NotFound');
15670                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_FAX');
15671                 FND_MSG_PUB.Add;
15672                 l_return_status := FND_API.G_RET_STS_ERROR;
15673                 Close C_Get_CONTACT_FAX2;
15674                 Close C_Get_CONTACT_FAX;
15675                 GOTO end_getcontact;
15676              end if;
15677              --
15678              If ( l_fax is null ) Then
15679                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Fax NotFound in C_GET_CONTACT_FAX');
15680                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_FAX');
15681                 FND_MSG_PUB.Add;
15682                 l_return_status := FND_API.G_RET_STS_ERROR;
15683                 Close C_Get_CONTACT_FAX2;
15684                 Close C_Get_CONTACT_FAX;
15685                 GOTO end_getcontact;
15686              end if;
15687              --
15688              Close C_Get_CONTACT_FAX2;
15689           end if;
15690 
15691           If ( l_fax is null ) Then
15692                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - FAX NotFound');
15693                 FND_MESSAGE.Set_Name('IEX', 'IEX_SEND_FAILED_NO_FAX');
15694                 FND_MSG_PUB.Add;
15695              l_return_status := FND_API.G_RET_STS_ERROR;
15696              Close C_Get_CONTACT_FAX;
15697              GOTO end_getcontact;
15698           end if;
15699 
15700           x_contact := l_fax;
15701 
15702           Close C_Get_CONTACT_FAX;
15703           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - fax= '||l_fax);
15704 
15705         --
15706         END IF; -- end of p_method=EMAIL
15707 
15708         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - email:'||l_email);
15709         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - fax:'||l_fax);
15710 
15711         <<end_getcontact>>
15712         x_return_status := l_return_status;
15713         if (x_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
15714             x_contact := '';
15715         END IF;
15716 
15717         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return_status:'||x_return_status);
15718         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ContactInfo:'||x_contact);
15719 
15720         FND_MSG_PUB.Count_And_Get
15721         (  p_count          =>   x_msg_count,
15722            p_data           =>   x_msg_data );
15723 
15724         EXCEPTION
15725               WHEN FND_API.G_EXC_ERROR THEN
15726                  ROLLBACK TO GetContactPoint_PVT;
15727                  x_return_status := FND_API.G_RET_STS_ERROR;
15728                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exp Exception');
15729                  errmsg := SQLERRM;
15730                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15731                  FND_MSG_PUB.Count_And_Get
15732                  (  p_count          =>   x_msg_count,
15733                     p_data           =>   x_msg_data
15734                  );
15735 
15736               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
15737                  ROLLBACK TO GetContactPoint_PVT;
15738                  x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
15739                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExp Exception');
15740                  errmsg := SQLERRM;
15741                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15742                  FND_MSG_PUB.Count_And_Get
15743                  (  p_count          =>   x_msg_count,
15744                     p_data           =>   x_msg_data
15745                  );
15746 
15747               WHEN OTHERS THEN
15748                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
15749                  ROLLBACK TO GetContactPoint_PVT;
15750                  x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
15751                  errmsg := SQLERRM;
15752                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15753                  FND_MSG_PUB.Count_And_Get
15754                  (  p_count          =>   x_msg_count,
15755                     p_data           =>   x_msg_data
15756                  );
15757     END GetContactPoint;
15758 
15759     Procedure CHK_QUERY_DATA(  p_query_id                IN NUMBER,
15760                                p_FULFILLMENT_BIND_TBL    IN IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL,
15761                                x_keep_flag               OUT NOCOPY NUMBER)
15762     IS
15763         CURSOR C_GET_QUERY (IN_ID NUMBER) IS
15764           SELECT upper(query_string)
15765             FROM jtf_fm_queries_all
15766            WHERE query_id = IN_ID
15767              AND nvl(upper(f_deletedflag),'0') <>'D';
15768        --
15769 
15770     		l_bind_var          JTF_FM_REQUEST_GRP.G_VARCHAR_TBL_TYPE;
15771     		l_bind_var_type     JTF_FM_REQUEST_GRP.G_VARCHAR_TBL_TYPE;
15772     		l_bind_val          JTF_FM_REQUEST_GRP.G_VARCHAR_TBL_TYPE;
15773     		l_bind_cnt_tbl      NUMBER;
15774     		l_keep_flag         NUMBER := 1;
15775     		l_query             VARCHAR2(4000);
15776     		l_part_query        VARCHAR2(4000);
15777     		l_party_id          NUMBER;
15778     		l_org_id            NUMBER;
15779     		l_account_id        NUMBER;
15780     		l_del_id            NUMBER;
15781     		l_result            NUMBER;
15782     		v_cursor            NUMBER;
15783     		v_create_string     varchar2(1000);
15784     		v_numrows           NUMBER;
15785     		errmsg              varchar2(32767);
15786     		l_found             NUMBER;
15787     		l_len               NUMBER;
15788 
15789     		-- clchang updated for sql bind var 05/07/2003
15790     		vstr1               VARCHAR2(100) ;
15791     		l_api_name          CONSTANT VARCHAR2(30) := 'CHK_QUERY_DATA';
15792 
15793     BEGIN
15794 
15795       WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - start');
15796       WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - queryid='||p_query_id);
15797       vstr1           := 'SELECT COUNT(*) ';
15798 
15799       l_bind_cnt_tbl := p_FULFILLMENT_BIND_TBL.count;
15800       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind_tbl_cnt'||l_bind_cnt_tbl);
15801 
15802       for j in 1..l_bind_cnt_tbl
15803       loop
15804           l_bind_var(j)      := p_FULFILLMENT_BIND_TBL(j).Key_name;
15805           l_bind_var_type(j) := p_FULFILLMENT_BIND_TBL(j).Key_Type;
15806           l_bind_val(j)      := p_FULFILLMENT_BIND_TBL(j).Key_Value;
15807           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind_var='||l_bind_var(j));
15808           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind_var_type='||l_bind_var_type(j));
15809           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - bind_val='||l_bind_val(j));
15810           if (l_bind_var(j) = 'party_id' ) then
15811               l_party_id := l_bind_val(j);
15812           elsif (l_bind_var(j) = 'org_id' ) then
15813               l_org_id := l_bind_val(j);
15814           elsif (l_bind_var(j) = 'account_id' ) then
15815               l_account_id := l_bind_val(j);
15816           elsif (l_bind_var(j) = 'delinquency_id' ) then
15817               l_del_id := l_bind_val(j);
15818           end if;
15819       end loop;
15820 
15821       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyid='||l_party_id);
15822       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - orgid='||l_org_id);
15823       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - acctid='||l_account_id);
15824       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_del_id);
15825 
15826       OPEN C_GET_QUERY (p_query_id);
15827       FETCH C_GET_QUERY INTO l_query;
15828       If ( C_GET_QUERY%NOTFOUND ) Then
15829            WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - NoQUERY');
15830            l_keep_flag := 1;
15831            GOTO end_query;
15832       else
15833            WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - string='||l_query);
15834            l_len := LENGTH(l_query);
15835            l_found := INSTR(l_query, 'FROM');
15836            l_part_query := SUBSTR(l_query, l_found, (l_len-l_found+1));
15837            -- clchang updated for sql bind var 05/07/2003
15838            --l_query := 'SELECT COUNT(*) ' || l_part_query;
15839            l_query := vstr1 || l_part_query;
15840            WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - new string='||l_query);
15841 
15842            l_query := replace(l_query, ':PARTY_ID', to_char(l_party_id) );
15843            WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - string1='||l_query);
15844            l_query := replace(l_query, ':ORG_ID', to_char(l_org_id) );
15845            WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - string2='||l_query);
15846            l_query := replace(l_query, ':DELINQUENCY_ID', to_char(l_del_id) );
15847            WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - string3='||l_query);
15848            l_query := replace(l_query, ':ACCOUNT_ID', to_Char(l_account_id) );
15849            WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - final string='||l_query);
15850       end if;
15851       CLOSE C_GET_QUERY;
15852 
15853       v_cursor := DBMS_SQL.OPEN_CURSOR;
15854       v_create_string := l_query;
15855       DBMS_SQL.parse(v_cursor, v_create_string, 1);
15856       DBMS_SQL.DEFINE_COLUMN(v_cursor, 1, l_result);
15857       v_numrows := DBMS_SQL.EXECUTE(v_cursor);
15858       v_numrows := DBMS_SQL.FETCH_ROWS(v_cursor);
15859       DBMS_SQL.COLUMN_VALUE(v_cursor, 1, l_result);
15860       WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - result='||l_result);
15861 
15862       DBMS_SQL.CLOSE_CURSOR(v_cursor);
15863 
15864       if (l_result > 0) then
15865           l_keep_flag := 1;
15866       else
15867           l_keep_flag := 0;
15868       end if;
15869 
15870       <<end_query>>
15871       x_keep_flag := l_keep_flag;
15872       WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - x_keep_flag='||l_keep_flag);
15873       WriteLog (G_PKG_NAME || ' ' || l_api_name || ' - end');
15874 
15875         EXCEPTION
15876               WHEN FND_API.G_EXC_ERROR THEN
15877                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
15878                   errmsg := SQLERRM;
15879                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15880                   x_keep_flag := 1;
15881 
15882               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
15883                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
15884                   errmsg := SQLERRM;
15885                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15886                   x_keep_flag := 1;
15887 
15888               WHEN OTHERS THEN
15889                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
15890                   errmsg := SQLERRM;
15891                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
15892                   x_keep_flag := 1;
15893 
15894     END CHK_QUERY_DATA;
15895 
15896     PROCEDURE Close_Dunning
15897                (p_api_version             IN NUMBER,
15898                 p_init_msg_list           IN VARCHAR2 ,
15899                 p_commit                  IN VARCHAR2 ,
15900                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
15901                 p_running_level           IN VARCHAR2,
15902     	    --p_dunning_id              IN NUMBER default NULL,   -- added by gnramasa for bug 8489610 14-May-09
15903     	    --p_status                  IN VARCHAR2 , -- added by gnramasa for bug 8489610 14-May-09
15904                 x_return_status           OUT NOCOPY VARCHAR2,
15905                 x_msg_count               OUT NOCOPY NUMBER,
15906                 x_msg_data                OUT NOCOPY VARCHAR2)
15907 
15908     IS
15909       --Start adding for bug 8489610 by gnramasa 14-May-09
15910         CURSOR C_GET_DUNNING (IN_ID NUMBER, IN_TYPE VARCHAR2) IS
15911           SELECT dunning_ID
15912             FROM IEX_DUNNINGS
15913            WHERE
15914              STATUS = 'OPEN'
15915              AND dunning_level = IN_TYPE
15916              AND dunning_object_id = IN_ID;
15917     --	 AND decode(nvl(dunning_mode,'FINAL'), 'DRAFT',confirmation_mode, 'FINAL','CONFIRMED')='CONFIRMED'
15918     --	 AND dunning_id <> nvl(p_dunning_id,-1) ;
15919       --End adding for bug 8489610 by gnramasa 14-May-09
15920         --
15921         l_DUNNING_id            NUMBER;
15922         l_delinquency_id        NUMBER;
15923         l_dunning_object_id     NUMBER;
15924         l_dunning_level         VARCHAR2(30);
15925         l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
15926         l_api_name              CONSTANT VARCHAR2(30) := 'Close_Dunning';
15927         l_api_version_number    CONSTANT NUMBER   := 1.0;
15928         l_return_status         VARCHAR2(1);
15929         l_msg_count             NUMBER;
15930         l_msg_data              VARCHAR2(32767);
15931         errmsg                  VARCHAR2(32767);
15932         nIdx                    NUMBER := 0;
15933         nCnt                    NUMBER := 0;
15934         --
15935         TYPE Dunning_ID_TBL_type is Table of IEX_DUNNINGS.DUNNING_ID%TYPE
15936     				        INDEX BY BINARY_INTEGER;
15937         dunning_tbl             Dunning_ID_TBL_TYPE;
15938         --
15939     BEGIN
15940           SAVEPOINT CLOSE_DUNNING_PVT;
15941 
15942           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
15943                                                p_api_version,
15944                                                l_api_name,
15945                                                G_PKG_NAME)
15946           THEN
15947               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
15948           END IF;
15949 
15950           IF FND_API.to_Boolean( p_init_msg_list )
15951           THEN
15952               FND_MSG_PUB.initialize;
15953           END IF;
15954 
15955           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - start');
15956           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - running_level='||p_running_level);
15957 
15958           x_return_status := FND_API.G_RET_STS_SUCCESS;
15959           l_dunning_level := p_running_level;
15960 
15961           if (p_running_level = 'CUSTOMER') then
15962               l_dunning_object_id := p_delinquencies_tbl(1).party_cust_id;
15963           elsif (p_running_level = 'ACCOUNT') THEN
15964               l_dunning_object_id := p_delinquencies_tbl(1).cust_account_id;
15965           elsif (p_running_level = 'BILL_TO') THEN
15966               l_dunning_object_id := p_delinquencies_tbl(1).customer_site_use_id;
15967           else
15968               l_dunning_object_id := p_delinquencies_tbl(1).delinquency_id;
15969           end if;
15970 
15971           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_level='||l_dunning_level);
15972           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_object_id='||l_dunning_object_id);
15973 
15974              --=============================================================
15975              --  Suppose one del has at most one open dunning.
15976              --  If we find out NOCOPY more than one open dunning, close all.
15977              --=============================================================
15978              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetDunning');
15979 
15980               nIdx := 1;
15981               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - del cnt=' ||p_delinquencies_tbl.count);
15982 
15983               FOR i in 1..p_delinquencies_tbl.count
15984               LOOP
15985                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Loop:i=' ||i);
15986 
15987                  nCnt := 0;
15988                  OPEN C_GET_DUNNING (l_dunning_object_id, l_dunning_level);
15989                  LOOP
15990                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - nCnt='||nCnt);
15991                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - nIdx='||nIdx);
15992                     FETCH C_GET_DUNNING INTO l_dunning_id;
15993                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunningId='||l_dunning_id);
15994                     dunning_tbl(nIdx) := l_dunning_id;
15995                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunn='||dunning_tbl(nIdx));
15996 
15997                     If ( C_GET_DUNNING%NOTFOUND ) Then
15998                         if (nCnt = 0) then
15999                           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - NoOpenDunning');
16000                         end if;
16001                         GOTO end_dunning_loop;
16002                     else
16003                         nCnt := nCnt + 1;
16004                         nIdx := nIdx+1;
16005                     end if;
16006                   END LOOP;
16007 
16008                   <<end_dunning_loop>>
16009                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End_Dunning_Loop');
16010 
16011               CLOSE C_GET_DUNNING;
16012               END LOOP;
16013 
16014               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunnCnt='||nIdx||';'||dunning_tbl.count);
16015 
16016     	  FORALL i in 1..dunning_tbl.count
16017     				  UPDATE IEX_DUNNINGS
16018     				     SET CALLBACK_YN = 'N',
16019     	                STATUS = 'CLOSE',
16020     	                LAST_UPDATE_DATE = sysdate
16021                 WHERE Dunning_id = dunning_tbl(i);
16022               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End');
16023 
16024           --
16025           -- End of API body
16026           --
16027 
16028           -- Standard check for p_commit
16029           IF FND_API.to_Boolean( p_commit )
16030           THEN
16031               COMMIT WORK;
16032           END IF;
16033 
16034           FND_MSG_PUB.Count_And_Get
16035           (  p_count          =>   x_msg_count,
16036              p_data           =>   x_msg_data );
16037 
16038           EXCEPTION
16039               WHEN FND_API.G_EXC_ERROR THEN
16040                  ROLLBACK TO CLOSE_DUNNING_PVT;
16041                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
16042                   errmsg := SQLERRM;
16043                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
16044     					   x_return_status := FND_API.G_RET_STS_ERROR;
16045     					   FND_MSG_PUB.Count_And_Get
16046     					   (  p_count          =>   x_msg_count,
16047     					      p_data           =>   x_msg_data
16048     					    );
16049 
16050               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
16051                  ROLLBACK TO CLOSE_DUNNING_PVT;
16052                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
16053                   errmsg := SQLERRM;
16054                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
16055     					   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
16056     					   FND_MSG_PUB.Count_And_Get
16057     					   (  p_count          =>   x_msg_count,
16058     					      p_data           =>   x_msg_data
16059     					    );
16060 
16061               WHEN OTHERS THEN
16062                  ROLLBACK TO CLOSE_DUNNING_PVT;
16063                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
16064                   errmsg := SQLERRM;
16065                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
16066     					   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
16067     					   FND_MSG_PUB.Count_And_Get
16068     					   (  p_count          =>   x_msg_count,
16069     					      p_data           =>   x_msg_data
16070     					    );
16071 
16072     END Close_Dunning;
16073 
16074     PROCEDURE Close_Staged_Dunning
16075                (p_api_version             IN NUMBER,
16076                 p_init_msg_list           IN VARCHAR2 ,
16077                 p_commit                  IN VARCHAR2 ,
16078                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
16079     	    p_ag_dn_xref_id           IN NUMBER,
16080                 p_running_level           IN VARCHAR2,
16081     	    --p_dunning_id              IN NUMBER default NULL,   -- added by gnramasa for bug 8489610 14-May-09
16082     	    --p_status                  IN VARCHAR2 , -- added by gnramasa for bug 8489610 14-May-09
16083                 x_return_status           OUT NOCOPY VARCHAR2,
16084                 x_msg_count               OUT NOCOPY NUMBER,
16085                 x_msg_data                OUT NOCOPY VARCHAR2)
16086 
16087     IS
16088       --Start adding for bug 8489610 by gnramasa 14-May-09
16089         CURSOR C_GET_DUNNING (IN_ID NUMBER, IN_TYPE VARCHAR2, IN_DUNN_PLAN_LINE_ID NUMBER) IS
16090           SELECT dunning_ID
16091             FROM IEX_DUNNINGS
16092            WHERE
16093              STATUS = 'OPEN'
16094              AND dunning_level = IN_TYPE
16095              AND dunning_object_id = IN_ID
16096     	 AND (ag_dn_xref_id = IN_DUNN_PLAN_LINE_ID OR
16097     	      ag_dn_xref_id IS NULL);
16098       --End adding for bug 8489610 by gnramasa 14-May-09
16099 
16100         l_DUNNING_id            NUMBER;
16101         l_delinquency_id        NUMBER;
16102         l_dunning_object_id     NUMBER;
16103         l_dunning_level         VARCHAR2(30);
16104         l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
16105         l_api_name              CONSTANT VARCHAR2(30) := 'Close_Staged_Dunning';
16106         l_api_version_number    CONSTANT NUMBER   := 1.0;
16107         l_return_status         VARCHAR2(1);
16108         l_msg_count             NUMBER;
16109         l_msg_data              VARCHAR2(32767);
16110         errmsg                  VARCHAR2(32767);
16111         nIdx                    NUMBER := 0;
16112         nCnt                    NUMBER := 0;
16113         --
16114         TYPE Dunning_ID_TBL_type is Table of IEX_DUNNINGS.DUNNING_ID%TYPE
16115     				        INDEX BY BINARY_INTEGER;
16116         dunning_tbl             Dunning_ID_TBL_TYPE;
16117         --
16118     BEGIN
16119           SAVEPOINT Close_Staged_Dunning_PVT;
16120 
16121           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
16122                                                p_api_version,
16123                                                l_api_name,
16124                                                G_PKG_NAME)
16125           THEN
16126               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
16127           END IF;
16128 
16129           IF FND_API.to_Boolean( p_init_msg_list )
16130           THEN
16131               FND_MSG_PUB.initialize;
16132           END IF;
16133 
16134           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - start');
16135           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - running_level='||p_running_level);
16136 
16137           x_return_status := FND_API.G_RET_STS_SUCCESS;
16138           l_dunning_level := p_running_level;
16139 
16140           if (p_running_level = 'CUSTOMER') then
16141               l_dunning_object_id := p_delinquencies_tbl(1).party_cust_id;
16142           elsif (p_running_level = 'ACCOUNT') THEN
16143               l_dunning_object_id := p_delinquencies_tbl(1).cust_account_id;
16144           elsif (p_running_level = 'BILL_TO') THEN
16145               l_dunning_object_id := p_delinquencies_tbl(1).customer_site_use_id;
16146           else
16147               l_dunning_object_id := p_delinquencies_tbl(1).delinquency_id;
16148           end if;
16149 
16150           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_level='||l_dunning_level);
16151           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_object_id='||l_dunning_object_id);
16152           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_ag_dn_xref_id='||p_ag_dn_xref_id);
16153 
16154              --=============================================================
16155              --  Suppose one del has at most one open dunning.
16156              --  If we find out NOCOPY more than one open dunning, close all.
16157              --=============================================================
16158              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - GetDunning');
16159 
16160               nIdx := 1;
16161               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - del cnt=' ||p_delinquencies_tbl.count);
16162 
16163               FOR i in 1..p_delinquencies_tbl.count
16164               LOOP
16165                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Loop:i=' ||i);
16166 
16167                  nCnt := 0;
16168                  OPEN C_GET_DUNNING (l_dunning_object_id, l_dunning_level, p_ag_dn_xref_id);
16169                  LOOP
16170                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - nCnt='||nCnt);
16171                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - nIdx='||nIdx);
16172                     FETCH C_GET_DUNNING INTO l_dunning_id;
16173                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunningId='||l_dunning_id);
16174                     dunning_tbl(nIdx) := l_dunning_id;
16175                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunn='||dunning_tbl(nIdx));
16176 
16177                     If ( C_GET_DUNNING%NOTFOUND ) Then
16178                         if (nCnt = 0) then
16179                           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - NoOpenDunning');
16180                         end if;
16181                         GOTO end_dunning_loop;
16182                     else
16183                         nCnt := nCnt + 1;
16184                         nIdx := nIdx+1;
16185                     end if;
16186                   END LOOP;
16187 
16188                   <<end_dunning_loop>>
16189                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End_Dunning_Loop');
16190 
16191               CLOSE C_GET_DUNNING;
16192               END LOOP;
16193 
16194               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunnCnt='||nIdx||';'||dunning_tbl.count);
16195 
16196     	  FORALL i in 1..dunning_tbl.count
16197     				  UPDATE IEX_DUNNINGS
16198     				     SET CALLBACK_YN = 'N',
16199     	                STATUS = 'CLOSE',
16200     	                LAST_UPDATE_DATE = sysdate
16201                 WHERE Dunning_id = dunning_tbl(i);
16202               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End');
16203 
16204           --
16205           -- End of API body
16206           --
16207 
16208           -- Standard check for p_commit
16209           IF FND_API.to_Boolean( p_commit )
16210           THEN
16211               COMMIT WORK;
16212           END IF;
16213 
16214           FND_MSG_PUB.Count_And_Get
16215           (  p_count          =>   x_msg_count,
16216              p_data           =>   x_msg_data );
16217 
16218           EXCEPTION
16219               WHEN FND_API.G_EXC_ERROR THEN
16220                  ROLLBACK TO Close_Staged_Dunning_PVT;
16221                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
16222                   errmsg := SQLERRM;
16223                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
16224     					   x_return_status := FND_API.G_RET_STS_ERROR;
16225     					   FND_MSG_PUB.Count_And_Get
16226     					   (  p_count          =>   x_msg_count,
16227     					      p_data           =>   x_msg_data
16228     					    );
16229 
16230               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
16231                  ROLLBACK TO Close_Staged_Dunning_PVT;
16232                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
16233                   errmsg := SQLERRM;
16234                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
16235     					   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
16236     					   FND_MSG_PUB.Count_And_Get
16237     					   (  p_count          =>   x_msg_count,
16238     					      p_data           =>   x_msg_data
16239     					    );
16240 
16241               WHEN OTHERS THEN
16242                  ROLLBACK TO Close_Staged_Dunning_PVT;
16243                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
16244                   errmsg := SQLERRM;
16245                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
16246     					   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
16247     					   FND_MSG_PUB.Count_And_Get
16248     					   (  p_count          =>   x_msg_count,
16249     					      p_data           =>   x_msg_data
16250     					    );
16251 
16252     END Close_Staged_Dunning;
16253 
16254     Procedure Daily_Dunning
16255                (p_api_version             IN NUMBER := 1.0,
16256                 p_init_msg_list           IN VARCHAR2 ,
16257                 p_commit                  IN VARCHAR2 ,
16258                 p_running_level           IN VARCHAR2,
16259                 x_return_status           OUT NOCOPY VARCHAR2,
16260                 x_msg_count               OUT NOCOPY NUMBER,
16261                 x_msg_data                OUT NOCOPY VARCHAR2)
16262     IS
16263         --Start adding for bug 8489610 by gnramasa 14-May-09
16264         CURSOR C_GET_DUNNING (IN_LEVEL VARCHAR2) IS
16265           SELECT dunning_ID,
16266                  delinquency_id,
16267                  dunning_object_id,
16268                  to_char(callback_date, 'YYYYMMDD')
16269             FROM IEX_DUNNINGS
16270            WHERE STATUS = 'OPEN'
16271             AND CALLBACK_YN = 'Y'
16272             AND dunning_level = IN_LEVEL
16273             AND to_char(callback_date, 'YYYYMMDD') <= to_char(sysdate,'YYYYMMDD');
16274     	--AND decode(nvl(dunning_mode,'FINAL'), 'DRAFT',confirmation_mode, 'FINAL','CONFIRMED')='CONFIRMED';
16275         --End adding for bug 8489610 by gnramasa 14-May-09
16276         --
16277         CURSOR C_CHK_DEL (IN_del_ID NUMBER) IS
16278           SELECT 1
16279             FROM IEX_DELINQUENCIES d
16280            WHERE d.delinquency_ID = in_del_ID
16281              AND STATUS in ('DELINQUENT', 'PREDELINQUENT');
16282         --
16283         CURSOR C_CHK_ACCOUNT (IN_ACCT_ID NUMBER) IS
16284           SELECT 1
16285             FROM IEX_DELINQUENCIES d
16286            WHERE d.cust_account_ID = in_ACCT_ID
16287              AND STATUS in ('DELINQUENT', 'PREDELINQUENT');
16288         --
16289         CURSOR C_CHK_CUSTOMER (IN_PARTY_ID NUMBER) IS
16290           SELECT 1
16291             FROM IEX_DELINQUENCIES d
16292            WHERE d.party_cust_id = in_party_id
16293              AND STATUS in ('DELINQUENT', 'PREDELINQUENT');
16294         --
16295         CURSOR C_CHK_SITE (IN_SITE_ID NUMBER) IS
16296           SELECT 1
16297             FROM IEX_DELINQUENCIES d
16298            WHERE d.customer_site_use_id = in_SITE_ID
16299              AND STATUS in ('DELINQUENT', 'PREDELINQUENT');
16300         --
16301         l_DUNNING_id            NUMBER;
16302         l_delinquency_id        NUMBER;
16303         l_callback_date         varchar2(10);
16304         l_DUNNING_rec           IEX_DUNNING_PUB.DUNNING_REC_TYPE;
16305         l_curr_date             varchar2(10);
16306         l_task_id               NUMBER;
16307         l_api_name              CONSTANT VARCHAR2(30) := 'Daily_Dunning';
16308         l_api_version_number    CONSTANT NUMBER   := 1.0;
16309         l_return_status         VARCHAR2(1);
16310         l_msg_count             NUMBER;
16311         l_msg_data              VARCHAR2(32767);
16312         errmsg                  VARCHAR2(32767);
16313         nIdx                    NUMBER := 0;
16314         nCnt                    NUMBER := 0;
16315         l_chk                   NUMBER := 0;
16316         l_task_cnt              NUMBER := 0;
16317         l_skip                  NUMBER := 0;
16318         --
16319         TYPE Dunning_ID_TBL_type is Table of IEX_DUNNINGS.DUNNING_ID%TYPE
16320     				        INDEX BY BINARY_INTEGER;
16321         dunning_tbl             Dunning_ID_TBL_TYPE;
16322         l_dunning_object_id     NUMBER;
16323 
16324     --Begin bug 7317666 21-Nov-2008 barathsr
16325         l_task_query varchar2(4000);
16326         TYPE c_cur_type IS REF CURSOR;
16327         c_invalid_tasks c_cur_type;
16328         l_inv_task_id JTF_TASKS_B.TASK_ID%TYPE;
16329         l_object_version_number JTF_TASKS_B.OBJECT_VERSION_NUMBER%TYPE;
16330     --End bug 7317666 21-Nov-2008 barathsr
16331 
16332     BEGIN
16333           -- Standard Start of API savepoint
16334           SAVEPOINT DAILY_DUNNING_PVT;
16335 
16336           -- Standard call to check for call compatibility.
16337           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
16338                                                p_api_version,
16339                                                l_api_name,
16340                                                G_PKG_NAME)
16341           THEN
16342               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
16343           END IF;
16344 
16345           -- Initialize message list if p_init_msg_list is set to TRUE.
16346           IF FND_API.to_Boolean( p_init_msg_list )
16347           THEN
16348               FND_MSG_PUB.initialize;
16349           END IF;
16350 
16351           -- Debug Message
16352           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start') ;
16353           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - running_level='||p_running_level) ;
16354 
16355           -- Initialize API return status to SUCCESS
16356           x_return_status := FND_API.G_RET_STS_SUCCESS;
16357 
16358           l_curr_date := to_char(sysdate, 'YYYYMMDD');
16359           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CurrDate='||l_curr_date) ;
16360           FND_FILE.PUT_LINE(FND_FILE.LOG, 'current date=' || l_curr_date);
16361           --
16362           -- Api body
16363           --
16364 
16365           nIdx := 0;
16366           Open C_Get_DUNNING (p_running_level);
16367           LOOP
16368 
16369              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ================') ;
16370              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Open C_Get_Dunning');
16371 
16372                Fetch C_Get_DUNNING into
16373                        l_dunning_id,
16374                        l_delinquency_id,
16375                        l_dunning_object_id,
16376                        l_callback_date;
16377 
16378                If ( C_GET_DUNNING%NOTFOUND ) Then
16379                     if (nIdx = 0) then
16380                         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - NoOpenDunning with callback_yn=Y');
16381                         FND_FILE.PUT_LINE(FND_FILE.LOG, 'NoOpenDunning with callback_yn=Y');
16382 
16383                     end if;
16384                     exit;
16385                ELSE
16386 
16387                     l_skip := 0;
16388                     x_return_status := FND_API.G_RET_STS_SUCCESS;
16389                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningID='||l_dunning_id) ;
16390                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunningObjectID='||l_dunning_object_id) ;
16391                     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Callback_Date='||l_callback_date) ;
16392                     FND_FILE.PUT_LINE(FND_FILE.LOG, '*****dunning_id='||l_dunning_id||'*****');
16393 
16394                     /*=========================================
16395                      * bug 2816550 - clchan updatd 02/21/2003
16396                      * for this current dunning,
16397                      * if the associated delinquenty is closed, no callback;
16398                      *=======================================================*/
16399                      IF (p_running_level = 'CUSTOMER') THEN
16400                          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Chk Customer:'||l_dunning_object_id) ;
16401                          Open C_CHK_CUSTOMER(l_dunning_object_id);
16402                          Fetch C_CHK_CUSTOMER into l_chk;
16403 
16404                          If ( C_CHK_CUSTOMER%NOTFOUND) Then
16405                               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - All Del Closed for this customer');
16406                               FND_FILE.PUT_LINE(FND_FILE.LOG, 'All Delinquencies Closed for this customer');
16407                               Close C_CHK_CUSTOMER;
16408                               l_skip := 1;
16409                         else
16410                             l_skip := 0;
16411                             Close C_CHK_CUSTOMER;
16412                             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - can continue') ;
16413                         end if;
16414                      --
16415                      ELSIF (p_running_level = 'ACCOUNT') THEN
16416                          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Chk Account:'||l_dunning_object_id) ;
16417                          Open C_CHK_Account(l_dunning_object_id);
16418                          Fetch C_CHK_Account into l_chk;
16419 
16420                          If ( C_CHK_Account%NOTFOUND) Then
16421                               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - All Del Closed for this Account');
16422                               FND_FILE.PUT_LINE(FND_FILE.LOG, 'All Delinquencies Closed for this account');
16423                               Close C_CHK_Account;
16424                               --GOTO end_dunning_if;
16425                               l_skip := 1;
16426                         else
16427                             l_skip := 0;
16428                             Close C_CHK_Account;
16429                             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - can continue') ;
16430                         end if;
16431                      --
16432                      ELSIF (p_running_level = 'BILL_TO') THEN
16433                          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Chk Bill To:'||l_dunning_object_id) ;
16434                          Open C_CHK_Site(l_dunning_object_id);
16435                          Fetch C_CHK_Site into l_chk;
16436 
16437                          If ( C_CHK_Site%NOTFOUND) Then
16438                               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - All Del Closed for this site');
16439                               FND_FILE.PUT_LINE(FND_FILE.LOG, 'All Delinquencies Closed for this site');
16440                               Close C_CHK_Site;
16441                               --GOTO end_dunning_if;
16442                               l_skip := 1;
16443                         else
16444                             l_skip := 0;
16445                             Close C_CHK_Site;
16446                             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - can continue') ;
16447                         end if;
16448                      --
16449                      ELSIF (p_running_level = 'DELINQUENCY') THEN
16450                          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Chk DEL:'||l_delinquency_id) ;
16451                          Open C_CHK_DEL(l_delinquency_id);
16452                          Fetch C_CHK_DEL into l_chk;
16453 
16454                          If ( C_CHK_DEL%NOTFOUND) Then
16455                               WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Del Closed for this del');
16456                               FND_FILE.PUT_LINE(FND_FILE.LOG, 'Delinquency Closed');
16457                               Close C_CHK_DEL;
16458                               --GOTO end_dunning_if;
16459                               l_skip := 1;
16460                         else
16461                             l_skip := 0;
16462                             Close C_CHK_DEL;
16463                             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - can continue') ;
16464                         end if;
16465                      END IF; -- end of chk running_level
16466 
16467                   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_skip='||l_skip) ;
16468                   IF (l_skip = 0) THEN
16469 
16470                      nIdx := nIdx + 1;
16471                      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - OPEN DUNNING:Num'||nIdx||'=========') ;
16472                      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - New_Task');
16473 
16474                      New_Task(
16475                        p_api_version              => p_api_version
16476                      , p_init_msg_list            => p_init_msg_list
16477                      , p_commit                   => p_commit
16478                      , p_delinquency_id           => l_delinquency_id
16479                      , p_dunning_id               => l_dunning_id
16480                      , p_dunning_object_id        => l_dunning_object_id
16481                      , p_dunning_level            => p_running_level
16482                      , x_task_id                  => l_task_id
16483                      , x_return_status            => x_return_status
16484                      , x_msg_count                => x_msg_count
16485                      , x_msg_data                 => x_msg_data
16486                      );
16487 
16488                      IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
16489                         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot create new Task');
16490                         FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cannot create new task');
16491                         FND_MSG_PUB.Count_And_Get
16492                         (  p_count          =>   x_msg_count,
16493                            p_data           =>   x_msg_data );
16494                         for i in 1..x_msg_count loop
16495                             errmsg := FND_MSG_PUB.Get(p_msg_index => i,
16496                                                       p_encoded => 'F');
16497                             FND_FILE.PUT_LINE(FND_FILE.LOG, 'Error:'||errmsg);
16498                             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - errmsg=' || errmsg);
16499                         end loop;
16500                         l_skip := 1;
16501                      else
16502                        l_skip := 0;
16503                        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - taskid='||l_task_id);
16504                        --FND_FILE.PUT_LINE(FND_FILE.LOG, 'task_id='||l_task_id);
16505                        l_task_cnt := l_task_cnt + 1;
16506                      END IF;  -- end of create_task
16507 
16508                  /*======================
16509                   * Update Dunning
16510                   *=====================*/
16511                    IF (l_skip = 0) THEN
16512                        nCnt := nCnt + 1;
16513                        dunning_tbl(nCnt) := l_dunning_id;
16514                    END IF;
16515 
16516                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_if (l_skip)');
16517                 END IF; -- end of (l_skip)
16518 
16519                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_if (FoundDunningData)');
16520                END IF; -- end of (FoundDunningData)
16521 
16522                <<end_dunning_loop>>
16523                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - end_dunning_loop');
16524                NULL;
16525 
16526           end loop;  -- end of CURSOR loop
16527 
16528           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - update_dunnings cnt='||nCnt);
16529 
16530           IF (nCnt > 0) THEN
16531 
16532              FORALL i in 1..dunning_tbl.count
16533     			   UPDATE IEX_DUNNINGS
16534                 SET CALLBACK_YN = 'N',
16535                     LAST_UPDATE_DATE = sysdate
16536               WHERE Dunning_id = dunning_tbl(i);
16537 
16538           END IF;
16539 
16540           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Close C_GET_DUNNING');
16541           Close C_Get_DUNNING;
16542 
16543           --
16544           -- End of API body
16545           --
16546 
16547           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========SUMMARY=========');
16548           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - TotalOpenDunn='||nIdx);
16549           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - TaskCreatedNum='||l_task_cnt);
16550           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunnUpdatedNum='||nCnt);
16551           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - DunnUpdatedNum='||dunning_tbl.count);
16552           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ==========END SUMMARY=========');
16553 
16554           -- Standard check for p_commit
16555           IF FND_API.to_Boolean( p_commit )
16556           THEN
16557               COMMIT WORK;
16558           END IF;
16559 
16560           --Begin bug 7317666 21-Nov-2008 barathsr
16561           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Cancelling the Dunning callback tasks correpsonding to current objects...');
16562           l_task_query := 'select tsk.task_id,'
16563                    ||'tsk.object_version_number'
16564                    ||' from jtf_tasks_b tsk,'
16565                    ||' jtf_task_types_tl typ,'
16566                    ||' jtf_task_statuses_b st,'
16567                    ||' jtf_task_references_b ref,'
16568                    ||' iex_dunnings dun'
16569                    ||' where tsk.task_type_id=typ.task_type_id'
16570                    ||' and typ.name=''Callback'''
16571                    ||' and tsk.task_status_id=st.task_status_id'
16572                    ||' and  nvl(st.closed_flag,   ''N'') <>''Y'''
16573                    ||' and  nvl(st.cancelled_flag,   ''N'')<>''Y'''
16574                    ||' and  nvl(st.completed_flag,   ''N'')<>''Y'''
16575                    ||' and tsk.task_id=ref.task_id'
16576                    ||' and ref.object_type_code=''IEX_DUNNING'''
16577                    ||' and ref.object_id=dun.dunning_id'
16578                    ||' and dun.dunning_level='''||p_running_level||'''';
16579 
16580           IF (p_running_level = 'CUSTOMER') THEN
16581           l_task_query:=l_task_query||' and not exists(select 1 from iex_delinquencies_all del '
16582                       ||' where  del.status in (''DELINQUENT'',''PREDELINQUENT'') '
16583                       ||' and dun.dunning_object_id=del.party_cust_id)';
16584           ELSIF(p_running_level = 'ACCOUNT') THEN
16585           l_task_query:=l_task_query||' and not exists(select 1 from iex_delinquencies_all del '
16586                       ||' where  del.status in (''DELINQUENT'',''PREDELINQUENT'') '
16587                       ||' and dun.dunning_object_id=del.cust_account_id)';
16588           ELSIF(p_running_level = 'BILL_TO') THEN
16589           l_task_query:=l_task_query||' and not exists(select 1 from iex_delinquencies_all del '
16590                       ||' where  del.status in (''DELINQUENT'',''PREDELINQUENT'') '
16591                       ||' and dun.dunning_object_id=del.customer_site_use_id)';
16592           ELSE
16593           l_task_query:=l_task_query||' and not exists(select 1 from iex_delinquencies_all del '
16594                       ||' where  del.status in (''DELINQUENT'',''PREDELINQUENT'') '
16595                       ||' and dun.dunning_object_id=del.delinquency_id)';
16596           END IF;
16597           WriteLog(G_PKG_NAME || ' ' || l_api_name || 'Query: '||l_task_query);
16598 
16599     	OPEN c_invalid_tasks for l_task_query;
16600     	LOOP
16601     		FETCH c_invalid_tasks INTO l_inv_task_id,l_object_version_number;
16602     		EXIT WHEN c_invalid_tasks%NOTFOUND;
16603     		WriteLog(G_PKG_NAME || ' ' || l_api_name || 'Cancelling callback Task Id:'||l_inv_task_id);
16604                     IF l_inv_task_id IS NOT NULL THEN
16605     			JTF_TASKS_PUB.UPDATE_TASK(
16606     			P_API_VERSION           	=> p_api_version,
16607     		        P_INIT_MSG_LIST         	=> p_init_msg_list,
16608     		        P_COMMIT                	=> p_commit,
16609     			P_OBJECT_VERSION_NUMBER	=> l_object_version_number,
16610     			P_TASK_ID 			=> l_inv_task_id,
16611     			P_TASK_STATUS_NAME		=> 'Cancelled',
16612     			x_return_status		        => x_return_status,
16613     			x_msg_count			=> x_msg_count,
16614     			x_msg_data			=> x_msg_data);
16615     			WriteLog(G_PKG_NAME || ' ' || l_api_name || 'Cancelling callback Task return status:'||x_return_status);
16616     		END IF;
16617 
16618     	END LOOP;
16619     	WriteLog(G_PKG_NAME || ' ' || l_api_name || 'Completed cancelling Dunning callback tasks correpsonding to current objects...');
16620 
16621           IF FND_API.to_Boolean( p_commit )
16622           THEN
16623               COMMIT WORK;
16624           END IF;
16625           --End bug 7317666 21-Nov-2008 barathsr
16626 
16627           -- clchang added 08/15/2003
16628           -- make return_status = 'S';
16629           x_return_status := FND_API.G_RET_STS_SUCCESS;
16630           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - return status='||x_return_status);
16631           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
16632 
16633           FND_MSG_PUB.Count_And_Get
16634           (  p_count          =>   x_msg_count,
16635              p_data           =>   x_msg_data );
16636 
16637           EXCEPTION
16638               WHEN FND_API.G_EXC_ERROR THEN
16639                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
16640                    errmsg := SQLERRM;
16641                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
16642                    ROLLBACK TO DAILY_DUNNING_PVT;
16643 		   x_return_status := FND_API.G_RET_STS_ERROR;
16644                    FND_MSG_PUB.Count_And_Get
16645                    (  p_count          =>   x_msg_count,
16646                       p_data           =>   x_msg_data
16647                     );
16648 
16649               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
16650                    ROLLBACK TO DAILY_DUNNING_PVT;
16651 		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
16652                    errmsg := SQLERRM;
16653                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
16654                    x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
16655                    FND_MSG_PUB.Count_And_Get
16656                    (  p_count          =>   x_msg_count,
16657                       p_data           =>   x_msg_data
16658                     );
16659 
16660               WHEN OTHERS THEN
16661                    ROLLBACK TO DAILY_DUNNING_PVT;
16662 		   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Others Exception');
16663                    errmsg := SQLERRM;
16664                    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exception errmsg='||errmsg);
16665                    x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
16666                    FND_MSG_PUB.Count_And_Get
16667                    (  p_count          =>   x_msg_count,
16668                       p_data           =>   x_msg_data
16669                     );
16670 
16671     END Daily_Dunning;
16672 
16673     Procedure NEW_TASK(
16674                 p_api_version             IN NUMBER := 1.0,
16675                 p_init_msg_list           IN VARCHAR2 ,
16676                 p_commit                  IN VARCHAR2 ,
16677                 p_delinquency_id          IN NUMBER,
16678                 p_dunning_id              IN NUMBER,
16679                 p_dunning_object_id       IN NUMBER,
16680                 p_dunning_level           IN VARCHAR2,
16681                 x_return_status           OUT NOCOPY VARCHAR2,
16682                 x_msg_count               OUT NOCOPY NUMBER,
16683                 x_msg_data                OUT NOCOPY VARCHAR2,
16684                 x_TASK_ID                 OUT NOCOPY NUMBER)
16685     IS
16686         CURSOR C_GET_DEL (IN_del_ID NUMBER) IS
16687           SELECT d.delinquency_ID,
16688                  d.party_cust_id,
16689                  d.cust_account_id,
16690                  a.account_number,
16691                  d.customer_site_use_id,
16692                  ar.trx_number,
16693                  ar.payment_schedule_id,
16694                  h.party_name
16695             FROM IEX_DELINQUENCIES d,
16696                  HZ_PARTIES h,
16697                  HZ_CUST_ACCOUNTS a,
16698                  AR_PAYMENT_SCHEDULES ar
16699            WHERE d.delinquency_ID = in_del_ID
16700              AND h.party_id = d.party_cust_id
16701              AND d.cust_account_id = a.cust_account_id
16702              AND ar.payment_schedule_id = d.payment_schedule_id
16703              AND ar.class = 'INV';
16704         --
16705         CURSOR C_GET_SITE (IN_SITE_ID NUMBER) IS
16706           SELECT d.party_cust_id,
16707                  d.cust_account_id,
16708                  a.account_number,
16709                  d.customer_site_use_id,
16710                  h.party_name,
16711                  u.location    -- added for bug 14738490
16712             FROM IEX_DELINQUENCIES d,
16713                  HZ_PARTIES h,
16714                  HZ_CUST_ACCOUNTS a,
16715                  HZ_CUST_SITE_USES u -- -- added for bug 14738490
16716            WHERE d.customer_site_use_id = in_SITE_ID
16717            AND   u.site_use_id  = d.customer_site_use_id
16718            AND   h.party_id = d.party_cust_id
16719            AND   d.cust_account_id = a.cust_account_id;
16720         --
16721         CURSOR C_GET_ACCOUNT (IN_ACCT_ID NUMBER) IS
16722           SELECT d.party_cust_id,
16723                  d.cust_account_id,
16724                  a.account_number,
16725                  h.party_name
16726             FROM IEX_DELINQUENCIES d,
16727                  HZ_PARTIES h,
16728                  HZ_CUST_ACCOUNTS a
16729            WHERE d.cust_account_ID = in_ACCT_ID
16730     	 AND h.party_id = d.party_cust_id
16731              AND d.cust_account_id = a.cust_account_id;
16732         --
16733         CURSOR C_GET_CUSTOMER (IN_PARTY_ID NUMBER) IS
16734           SELECT d.party_cust_id,
16735                  h.party_name
16736             FROM IEX_DELINQUENCIES d,
16737                  HZ_PARTIES h
16738            WHERE d.party_cust_id = in_party_id
16739              AND h.party_id = d.party_cust_id;
16740         --
16741         l_delinquency_id        NUMBER;
16742         l_dunning_id            NUMBER ;
16743         l_party_cust_id         NUMBER;
16744         l_account_id            NUMBER;
16745         l_account_num           VARCHAR2(30); --NUMBER;
16746         l_customer_site_use_id  NUMBER;
16747         l_payment_schedule_id   NUMBER;
16748         l_trx_number            varchar2(30);
16749         l_resource_id           NUMBER;
16750         l_party_name            varchar2(360);
16751         --
16752         l_task_name             varchar2(80) ;
16753         l_task_type             varchar2(30) ;
16754         l_task_status           varchar2(30) ;
16755         l_description           varchar2(4000);
16756         l_task_priority_name    varchar2(30) ;
16757         l_task_priority_id      number;
16758         l_owner_id              number;
16759         l_owner                 varchar2(4000);
16760         l_owner_type_code       varchar2(4000);
16761         l_customer_id           number;
16762         l_address_id            number;
16763         l_source_object_type_code  varchar2(30);
16764         l_source_object_id         number;
16765         --l_source_object_name       varchar2(80);
16766 	l_source_object_name       varchar2(360); -- added for bug 14036760
16767         --
16768         l_task_notes_tbl           JTF_TASKS_PUB.TASK_NOTES_TBL;
16769         l_miss_task_assign_tbl     JTF_TASKS_PUB.TASK_ASSIGN_TBL;
16770         l_miss_task_depends_tbl    JTF_TASKS_PUB.TASK_DEPENDS_TBL;
16771         l_miss_task_rsrc_req_tbl   JTF_TASKS_PUB.TASK_RSRC_REQ_TBL;
16772         l_task_refer_rec           JTF_TASKS_PUB.TASK_REFER_REC;
16773         l_task_refer_tbl           JTF_TASKS_PUB.TASK_REFER_TBL;
16774         l_miss_task_dates_tbl      JTF_TASKS_PUB.TASK_DATES_TBL;
16775         l_miss_task_recur_rec      JTF_TASKS_PUB.TASK_RECUR_REC;
16776         l_miss_task_contacts_tbl   JTF_TASKS_PUB.TASK_CONTACTS_TBL;
16777         --
16778         errmsg                 varchar2(30000);
16779 
16780         --Added for bug#5229763 schekuri 27-Jul-2006
16781         l_resource_tab iex_utilities.resource_tab_type;
16782         l_return_status VARCHAR2(1);
16783         l_msg_count NUMBER;
16784         l_msg_data VARCHAR2(32767);
16785         l_validation_level NUMBER ;
16786         l_default_rs_id  NUMBER := fnd_profile.value('IEX_STRY_DEFAULT_RESOURCE');
16787         l_api_version   NUMBER       := 1.0;
16788     		l_api_name varchar2(25) := 'NEW_TASK';
16789        --fix start for bug 14036760 by sunagesh on 08-05-12
16790 	l_taskname   varchar2(30);
16791 	l_statusname varchar2(30);       -- fix end for bug 14036760 on 08-05-12
16792   l_location   varchar2(40); -- added for bug 14738490
16793       BEGIN
16794 
16795         -- Initialize API return status to SUCCESS
16796         l_validation_level := FND_API.G_VALID_LEVEL_FULL;
16797         x_return_status := FND_API.G_RET_STS_SUCCESS;
16798         l_dunning_id := p_dunning_id;
16799 
16800         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||p_delinquency_id);
16801         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunningobjectid='||p_dunning_object_id);
16802         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunningLevel='||p_dunning_level);
16803 
16804         WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - OPEN CURSOR');
16805 
16806         IF (p_dunning_level = 'ACCOUNT')
16807         THEN
16808             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - OPEN ACCOUNT CURSOR');
16809             Open C_Get_ACCOUNT(p_dunning_object_id);
16810             Fetch C_Get_ACCOUNT into
16811                l_party_cust_id,
16812                l_account_id,
16813                l_account_num,
16814                l_party_name;
16815 
16816             If ( C_GET_ACCOUNT%NOTFOUND) Then
16817                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ACCOUNT NotFound');
16818                 x_return_status := FND_API.G_RET_STS_ERROR;
16819                 Close C_Get_ACCOUNT;
16820                 GOTO end_new_task;
16821             end if;
16822             Close C_Get_ACCOUNT;
16823             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get ACCNT Data');
16824         --
16825         ELSIF (p_dunning_level = 'CUSTOMER')
16826         THEN
16827             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - OPEN CUSTOMER CURSOR');
16828             Open C_Get_CUSTOMER(p_dunning_object_id);
16829             Fetch C_Get_CUSTOMER into
16830                l_party_cust_id,
16831                l_party_name;
16832 
16833             If ( C_GET_CUSTOMER%NOTFOUND) Then
16834                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - CUSTOMER NotFound');
16835                 x_return_status := FND_API.G_RET_STS_ERROR;
16836                 Close C_Get_CUSTOMER;
16837                 GOTO end_new_task;
16838             end if;
16839             Close C_Get_CUSTOMER;
16840             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get CUSTOMER Data');
16841         --
16842         -- added for new level 'BILL_TO' in 11.5.10
16843         ELSIF (p_dunning_level = 'BILL_TO')
16844         THEN
16845             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - OPEN BILL_TO CURSOR');
16846             Open C_Get_SITE(p_dunning_object_id);
16847             Fetch C_Get_SITE into
16848                l_party_cust_id,
16849                l_account_id,
16850                l_account_num,
16851                l_customer_site_use_id,
16852                l_party_name,
16853                l_location;
16854 
16855             If ( C_GET_SITE%NOTFOUND) Then
16856                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - ACCOUNT NotFound');
16857                 x_return_status := FND_API.G_RET_STS_ERROR;
16858                 Close C_Get_SITE;
16859                 GOTO end_new_task;
16860             end if;
16861             Close C_Get_SITE;
16862             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get SITE Data');
16863         --
16864         ELSIF (p_dunning_level = 'DELINQUENCY')
16865         THEN
16866             Open C_Get_DEL(p_delinquency_id);
16867             Fetch C_Get_DEL into
16868                l_delinquency_id,
16869                l_party_cust_id,
16870                l_account_id,
16871                l_account_num,
16872                l_customer_site_use_id,
16873                l_trx_number,
16874                l_payment_schedule_id,
16875                l_party_name;
16876 
16877             If ( C_GET_DEL%NOTFOUND) Then
16878                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Del NotFound');
16879                 x_return_status := FND_API.G_RET_STS_ERROR;
16880                 Close C_Get_DEL;
16881                 GOTO end_new_task;
16882             end if;
16883             Close C_Get_DEL;
16884             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Get Del Data');
16885        END IF;
16886 
16887         If ( l_party_cust_id is null ) Then
16888              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - PartyCustId NotFound');
16889              x_return_status := FND_API.G_RET_STS_ERROR;
16890              GOTO end_new_task;
16891         end if;
16892 
16893       -- clchang updated 09/20/2002 for bug 2242346
16894       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Call GET_RESOURCE');
16895       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyid='||l_party_cust_id);
16896       --Begin Bug#5229763 schekuri 27-Jul-2006
16897       --Called iex_utilities.get_assigned_collector to get the resource from hz_customer_profiles table
16898       --instead of as_accesses. Removed the call to "get_resource".
16899       if l_customer_site_use_id is not null then
16900     	iex_utilities.get_assigned_collector(p_api_version => l_api_version,
16901                                    p_init_msg_list     => FND_API.G_TRUE,
16902                                    p_commit            => FND_API.G_FALSE,
16903                                    p_validation_level  => l_validation_level,
16904                                    p_level             => 'DUNNING_BILLTO',
16905                                    p_level_id          => l_customer_site_use_id,
16906                                    x_msg_count         => l_msg_count,
16907                                    x_msg_data          => l_msg_data,
16908                                    x_return_status     => l_return_status,
16909                                    x_resource_tab      => l_resource_tab);
16910     	IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
16911     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
16912     	     x_return_status := FND_API.G_RET_STS_ERROR;
16913     	     GOTO end_new_task;
16914     	END IF;
16915       end if;
16916 
16917       if l_resource_tab.count<1 and l_account_id is not null then
16918     	  iex_utilities.get_assigned_collector(p_api_version => l_api_version,
16919                                    p_init_msg_list     => FND_API.G_TRUE,
16920                                    p_commit            => FND_API.G_FALSE,
16921                                    p_validation_level  => l_validation_level,
16922                                    p_level             => 'DUNNING_ACCOUNT',
16923                                    p_level_id          => l_account_id,
16924                                    x_msg_count         => l_msg_count,
16925                                    x_msg_data          => l_msg_data,
16926                                    x_return_status     => l_return_status,
16927                                    x_resource_tab      => l_resource_tab);
16928     	IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
16929     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
16930     	     x_return_status := FND_API.G_RET_STS_ERROR;
16931     	     GOTO end_new_task;
16932     	END IF;
16933       end if;
16934 
16935       if l_resource_tab.count<1 and l_party_cust_id is not null then
16936     	iex_utilities.get_assigned_collector(p_api_version => l_api_version,
16937                                    p_init_msg_list     => FND_API.G_TRUE,
16938                                    p_commit            => FND_API.G_FALSE,
16939                                    p_validation_level  => l_validation_level,
16940                                    p_level             => 'DUNNING_PARTY',
16941                                    p_level_id          => l_party_cust_id,
16942                                    x_msg_count         => l_msg_count,
16943                                    x_msg_data          => l_msg_data,
16944                                    x_return_status     => l_return_status,
16945                                    x_resource_tab      => l_resource_tab);
16946     	IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
16947     	     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
16948     	     x_return_status := FND_API.G_RET_STS_ERROR;
16949     	     GOTO end_new_task;
16950     	END IF;
16951 
16952     	if l_resource_tab.count<1 and p_dunning_level = 'CUSTOMER' then
16953     		iex_utilities.get_assigned_collector(p_api_version => l_api_version,
16954     													               p_init_msg_list     => FND_API.G_TRUE,
16955     																				 p_commit            => FND_API.G_FALSE,
16956     																				 p_validation_level  => l_validation_level,
16957     																				 p_level             => 'DUNNING_PARTY_ACCOUNT',
16958     																				 p_level_id          => l_party_cust_id,
16959     																				 x_msg_count         => l_msg_count,
16960     																				 x_msg_data          => l_msg_data,
16961     																				 x_return_status     => l_return_status,
16962     																				 x_resource_tab      => l_resource_tab);
16963     		IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
16964     		     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource');
16965     		     x_return_status := FND_API.G_RET_STS_ERROR;
16966     		     GOTO end_new_task;
16967     		END IF;
16968     	end if;
16969       end if;
16970 
16971       if l_resource_tab.count>0 then
16972         l_resource_id := l_resource_tab(1).resource_id;
16973       else
16974         if l_default_rs_id is not null then
16975            l_resource_id := l_default_rs_id;
16976         else
16977            x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
16978            WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot get resource from customer profile and there is no default resource set');
16979            FND_FILE.PUT_LINE(FND_FILE.LOG, 'No collector has been assigned to this customer '||l_party_name);
16980            FND_FILE.PUT_LINE(FND_FILE.LOG, 'No default collector available to assign to callback.  Please update default collector.');
16981            GOTO end_new_task;
16982         end if;
16983       end if;
16984       --End Bug#5229763 schekuri 27-Jul-2006
16985 
16986       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - resource_id='||l_resource_id);
16987       WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - dunning_id='||l_dunning_id);
16988 
16989              --fix start for bug 14036760 by sunagesh on 08-05-12
16990                 SELECT jvl.name  into l_taskname
16991 		FROM  jtf_task_types_vl jvl , jtf_task_types_tl jtl
16992 		WHERE jvl.task_type_id= jtl.task_type_id
16993 		AND   jtl.language='US'
16994 		AND   jtl.name = 'Callback'
16995 		AND trunc(NVL (jvl.end_date_active, SYSDATE)) >= trunc(SYSDATE)
16996 		AND trunc(NVL (jvl.start_date_active, SYSDATE)) <= trunc(SYSDATE);
16997 
16998 		SELECT jvl.name into l_statusname
16999 		FROM  jtf_task_statuses_vl jvl , jtf_task_statuses_tl jtl
17000 		WHERE jvl.task_status_id= jtl.task_status_id
17001 		AND   jtl.language='US'
17002 	        AND   jtl.name = 'Open'
17003 	        AND trunc(NVL (jvl.end_date_active, SYSDATE)) >= trunc(SYSDATE)
17004                 AND trunc(NVL (jvl.start_date_active, SYSDATE)) <= trunc(SYSDATE);
17005 
17006                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_taskname '||l_taskname);
17007 		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_statusname '||l_statusname);
17008              --fix end for bug 14036760 by sunagesh on 08-05-12
17009 
17010              l_task_name   := 'Dunning Callback';
17011             -- l_task_status := 'Open'; -- commented for bug 14036760
17012 	     l_task_status :=   l_statusname;  -- added for bug 14036760
17013              --l_task_type   := 'Approval'; --'Callback';
17014              --l_task_type   := 'Callback'; -- commented for bug 14036760
17015 	     l_task_type   :=    l_taskname;           -- added for bug 14036760
17016              l_description := 'Oracle Collections Daily Dunnings';
17017              --l_task_priority_name := ;
17018              --l_task_priority_id := ;
17019              l_owner_type_code := 'RS_EMPLOYEE';
17020              l_owner_id := l_resource_id;
17021              l_customer_id := l_party_cust_id;
17022 
17023              -- clchang updated 04/09/2003 bug 2872385
17024              -- source object code should be based on the dunning level;
17025              -- ( in order to be seen in Collections Task tab )
17026              -- p.s. Collectons Task tab is based on the ViewBy;
17027              --      ViewBy is PARTY => only see tasks with source_object_code PARTY
17028              --      ViewBy is ACCOUNT => see tasks with source_object_code ACCOUNT
17029              --      ViewBy is DELINQUENCY => only see tasks with source_object_code DELINQUENCY
17030 
17031              --
17032              -- clchang updated 04/21/2003 for BILL_TO
17033              --
17034              --
17035              --
17036              IF (p_dunning_level = 'CUSTOMER') THEN
17037                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyid='||l_party_cust_id);
17038                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyname='||l_party_name);
17039                  --
17040                  l_source_object_type_code := 'PARTY';
17041                  l_source_object_id := l_party_cust_id;
17042                  l_source_object_name := l_party_name;
17043                  --
17044                  l_task_refer_rec.object_id := l_dunning_id;
17045                  l_task_refer_rec.object_name := substr(l_dunning_id,1,80);
17046                  l_task_refer_rec.object_type_code := 'IEX_DUNNING';
17047                  l_task_refer_tbl(1) := l_task_refer_rec;
17048 
17049              ELSIF (p_dunning_level = 'ACCOUNT') THEN
17050                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyid='||l_party_cust_id);
17051                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyname='||l_party_name);
17052                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - accntnum='||l_account_num);
17053                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - accntid='||l_account_id);
17054                  --
17055                  l_source_object_type_code := 'IEX_ACCOUNT';
17056                  l_source_object_id := l_account_id;
17057                  l_source_object_name := l_account_num;
17058                  --
17059                  l_task_refer_rec.object_id := l_party_cust_id;
17060                  l_task_refer_rec.object_name := substr(l_party_name,1,80);
17061                  l_task_refer_rec.object_type_code := 'PARTY';
17062                  l_task_refer_tbl(1) := l_task_refer_rec;
17063                  l_task_refer_rec.object_id := l_dunning_id;
17064                  l_task_refer_rec.object_name := substr(l_dunning_id,1,80);
17065                  l_task_refer_rec.object_type_code := 'IEX_DUNNING';
17066                  l_task_refer_tbl(2) := l_task_refer_rec;
17067 
17068              ELSIF (p_dunning_level = 'BILL_TO') THEN
17069                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyid='||l_party_cust_id);
17070                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyname='||l_party_name);
17071                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - accntnum='||l_account_num);
17072                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - accntid='||l_account_id);
17073                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - customer_site_use_id='||l_customer_site_use_id);
17074                  --
17075                  l_source_object_type_code := 'IEX_BILLTO';
17076                  l_source_object_id := l_customer_site_use_id;
17077                  l_source_object_name := l_customer_site_use_id;
17078                  --
17079                  l_task_refer_rec.object_id := l_party_cust_id;
17080                  l_task_refer_rec.object_name := substr(l_party_name,1,80);
17081                  l_task_refer_rec.object_type_code := 'PARTY';
17082                  l_task_refer_tbl(1) := l_task_refer_rec;
17083                  l_task_refer_rec.object_id := l_account_id;
17084                  l_task_refer_rec.object_name := substr(l_account_num,1,80);
17085                  l_task_refer_rec.object_type_code := 'IEX_ACCOUNT';
17086                  l_task_refer_tbl(2) := l_task_refer_rec;
17087                  l_task_refer_rec.object_id := l_dunning_id;
17088                  l_task_refer_rec.object_name :=  substr(l_dunning_id,1,80);
17089                  l_task_refer_rec.object_type_code := 'IEX_DUNNING';
17090                  l_task_refer_tbl(3) := l_task_refer_rec;
17091 
17092              ELSE
17093                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyid='||l_party_cust_id);
17094                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - partyname='||l_party_name);
17095                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - accntnum='||l_account_num);
17096                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - accntid='||l_account_id);
17097                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - customer_site_use_id='||l_customer_site_use_id);
17098                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - delid='||l_delinquency_id);
17099                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - trxnum='||l_trx_number);
17100                  WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - paymentshcheid='||l_payment_schedule_id);
17101                  --
17102                  l_source_object_type_code := 'IEX_DELINQUENCY';
17103                  l_source_object_id := l_delinquency_id;
17104                  l_source_object_name := l_delinquency_id;
17105                  --
17106                  l_task_refer_rec.object_id := l_party_cust_id;
17107                  l_task_refer_rec.object_name := substr(l_party_name,1,80); --bug 14738490
17108                  l_task_refer_rec.object_type_code := 'PARTY';
17109                  l_task_refer_tbl(1) := l_task_refer_rec;
17110                  l_task_refer_rec.object_id := l_account_id;
17111                  l_task_refer_rec.object_name := substr(l_account_num,1,80); --bug 14738490
17112                  l_task_refer_rec.object_type_code := 'IEX_ACCOUNT';
17113                  l_task_refer_tbl(2) := l_task_refer_rec;
17114                  l_task_refer_rec.object_id := l_customer_site_use_id;
17115                  --l_task_refer_rec.object_name :=l_customer_site_use_id; --bug 14738490
17116                  l_task_refer_rec.object_name :=substr(l_location,1,80);
17117                  l_task_refer_rec.object_type_code := 'IEX_BILLTO';
17118                  l_task_refer_tbl(3) := l_task_refer_rec;
17119                  l_task_refer_rec.object_id := l_payment_schedule_id;
17120                  l_task_refer_rec.object_name := substr(l_trx_number,1,80);
17121                  l_task_refer_rec.object_type_code := 'IEX_INVOICES';
17122                  l_task_refer_tbl(4) := l_task_refer_rec;
17123                  l_task_refer_rec.object_id := l_dunning_id;
17124                  l_task_refer_rec.object_name := substr(l_dunning_id,1,80);
17125                  l_task_refer_rec.object_type_code := 'IEX_DUNNING';
17126                  l_task_refer_tbl(5) := l_task_refer_rec;
17127 
17128              END IF;
17129 
17130              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - refer_tbl_cnt='||l_task_refer_tbl.count);
17131              WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Create Task');
17132 
17133              JTF_TASKS_PUB.CREATE_TASK(
17134                 p_api_version           => p_api_version,
17135                 p_init_msg_list         => p_init_msg_list,
17136                 p_commit                => p_commit,
17137                 p_task_name             => l_task_name,
17138                 p_task_type_name        => l_task_type,
17139                 p_task_status_name      => l_task_status,
17140                 p_owner_type_code       => l_owner_type_code,
17141                 p_owner_id              => l_owner_id,
17142                 p_description           => l_description,
17143                 p_customer_id           => l_customer_id,
17144                 p_source_object_type_code => l_source_object_type_code,
17145                 p_source_object_id      => l_source_object_id,
17146                 p_source_object_name    => l_source_object_name,
17147                 p_task_assign_tbl       => l_miss_task_assign_tbl,
17148                 p_task_depends_tbl      => l_miss_task_depends_tbl,
17149                 p_task_rsrc_req_tbl     => l_miss_task_rsrc_req_tbl,
17150                 p_task_refer_tbl        => l_task_refer_tbl,
17151                 p_task_dates_tbl        => l_miss_task_dates_tbl,
17152                 p_task_notes_tbl        => l_task_notes_tbl,
17153                 p_task_recur_rec        => l_miss_task_recur_rec,
17154                 p_task_contacts_tbl     => l_miss_task_contacts_tbl,
17155                 x_return_status         => x_return_status,
17156                 x_msg_count             => x_msg_count,
17157                 x_msg_data              => x_msg_data,
17158                 x_task_id               => x_task_id );
17159 
17160          <<end_new_task>>
17161          IF x_return_status <> FND_API.G_RET_STS_SUCCESS THEN
17162             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Cannot Create Task');
17163             FND_MSG_PUB.Count_And_Get
17164             (  p_count          =>   x_msg_count,
17165                p_data           =>   x_msg_data
17166             );
17167             for i in 1..x_msg_count loop
17168                errmsg := FND_MSG_PUB.Get(p_msg_index => i,
17169                                          p_encoded => 'F');
17170                WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - errmsg='||errmsg);
17171             end loop;
17172 
17173          ELSE
17174             WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Task-taskid='||x_task_id);
17175 
17176          END IF;
17177 
17178       END NEW_TASK;
17179 
17180     /*========================================================================
17181      * Clchang updated 09/19/2002 for Bug 2242346
17182      *   to create a callback,
17183      *      we got resource_id from iex_delinquencyies before;
17184      *      now, we get resource_id based on which agent owns the least tasks
17185      *           in PARTY level;
17186      *
17187      *      Based on the party_id:
17188      *      1. taskcount:
17189      *         get the count(task) for the existing resources in jtf_tasks_vl;
17190      *      2. notaskcount:
17191      *         get all available resource_id for this party,
17192      *         and put count as 0 for each resource;
17193      *      3. if taskcount = 0,
17194      *            if notaskcount > 0,
17195      *               task the first resource_id based on notask_cursor;
17196      *            if notaskcount = 0,
17197      *               get the default resource_id;
17198      *      4. if taskcount > 0,
17199      *            get the resource_id which has the least tasks;
17200      *
17201      *========================================================================*/
17202     --Removed all the code to replace the usage of this procedure with iex_utilities.get_assigned_collector
17203     --for bug#5229763 schekuri 27-Jul-2006
17204     --iex_utilities.get_assigned_collector uses hz_customer_profiles to get resource instead of as_accesses
17205     PROCEDURE Get_Resource(p_api_version   IN  NUMBER,
17206                            p_commit        IN  VARCHAR2,
17207                            p_init_msg_list           IN VARCHAR2 ,
17208                            p_party_id      IN  NUMBER,
17209                            x_resource_id   OUT NOCOPY NUMBER,
17210                            x_return_status OUT NOCOPY VARCHAR2,
17211                            x_msg_count     OUT NOCOPY NUMBER,
17212                            x_msg_data      OUT NOCOPY VARCHAR2)
17213     IS
17214      /* l_api_name                    VARCHAR2(50) ;
17215       l_RETURN_STATUS               VARCHAR2(30) ;
17216       l_MSG_COUNT                   NUMBER      ;
17217       l_MSG_DATA                    VARCHAR2(100) ;
17218       l_api_version                 NUMBER := 1.0;
17219 
17220       l_default_rs_id  number ;
17221       l_login  number;
17222       l_user   NUMBER ;
17223 
17224       CURSOR c_chk_party (p_party_id NUMBER) IS
17225           SELECT customer_id
17226             FROM jtf_tasks_vl
17227            WHERE customer_id = p_party_id;*/
17228 
17229       /*===================================================
17230       --  from iexvutlb.pls -  get_assign_resources procedure
17231       --  the resources should include manager;
17232       --------------------------------------------------------
17233 
17234       CURSOR c_get_person IS
17235         SELECT DISTINCT person_id, salesforce_id
17236         FROM  as_accesses acc, jtf_rs_resource_extns rs
17237         WHERE acc.customer_id = p_party_id and rs.resource_id = acc.salesforce_id
17238           and rs.user_id is not null;
17239 
17240       -- clchang 02/26/2003 updated
17241       -- updated the following cursors based on the above cursor;
17242       ----------------------------------------------------------------
17243 
17244       CURSOR c_party_resource_OLD(p_party_id NUMBER) IS
17245           SELECT DISTINCT rs.resource_id, 0
17246             FROM as_rpt_managers_v m, as_accesses acc, jtf_rs_resource_extns rs
17247            WHERE m.person_id = acc.person_id
17248              AND m.manager_person_id = rs.source_id
17249              AND acc.customer_id = p_party_id
17250              AND nvl(rs.end_date_active,sysdate) >= trunc(sysdate);
17251 
17252       CURSOR c_resource_task_count_OLD(p_party_id NUMBER) IS
17253           SELECT t.owner_id, count(t.owner_id)
17254             FROM jtf_tasks_vl t, jtf_task_statuses_vl s
17255            WHERE t.customer_id = p_party_id
17256              AND upper(t.owner_type_code) = 'RS_EMPLOYEE'
17257              AND t.task_name = 'Dunning Callback'
17258              AND t.task_status_id = s.task_status_id
17259              AND upper(s.name) = 'OPEN'
17260              AND t.owner_id in ( select DISTINCT rs.resource_id
17261                                  from as_rpt_managers_v m, as_accesses acc,
17262                                       jtf_rs_resource_extns rs
17263                                 where m.person_id = acc.person_id
17264                                   and m.manager_person_id = rs.source_id
17265                                   and acc.customer_id = p_party_id
17266                                   AND nvl(rs.end_date_active,sysdate) >= trunc(sysdate) )
17267            GROUP BY t.owner_id;
17268 
17269       CURSOR c_resource_notask_count_OLD(p_party_id NUMBER) IS
17270           SELECT DISTINCT rs.resource_id, 0
17271             FROM as_rpt_managers_v m, as_accesses acc, jtf_rs_resource_extns rs
17272            WHERE m.person_id = acc.person_id
17273              AND m.manager_person_id = rs.source_id
17274              AND acc.customer_id = p_party_id
17275              AND nvl(rs.end_date_active,sysdate) >= trunc(sysdate)
17276              AND rs.resource_id not in ( select distinct t2.owner_id
17277                                            from jtf_tasks_vl t2,
17278                                                 jtf_task_statuses_vl s2
17279                                           where t2.customer_id = p_party_id
17280                                            and upper(t2.owner_type_code) = 'RS_EMPLOYEE'
17281                                            AND t2.task_status_id = s2.task_status_id
17282                                            AND upper(s2.name) = 'OPEN'
17283                                            and t2.task_name = 'Dunning Callback');
17284 
17285       CURSOR c_resource_mintask(p_party_id NUMBER) IS
17286           SELECT t.owner_id  --, count(t.owner_id)
17287             FROM jtf_tasks_vl t, jtf_task_statuses_vl s
17288            WHERE t.customer_id = p_party_id
17289              AND upper(t.owner_type_code) = 'RS_EMPLOYEE'
17290              AND t.task_name = 'Dunning Callback'
17291              AND t.task_status_id = s.task_status_id
17292              AND upper(s.name) = 'OPEN'
17293            GROUP BY t.owner_id
17294           HAVING COUNT(t.owner_id) = (select min(count(t2.owner_id))
17295                                       from jtf_tasks_vl t2, jtf_task_statuses_vl s2
17296                                      WHERE t2.customer_id = p_party_id
17297                                        AND upper(t2.owner_type_code) = 'RS_EMPLOYEE'
17298                                        AND t2.task_name = 'Dunning Callback'
17299                                        AND t2.task_status_id = s2.task_status_id
17300                                        AND upper(s2.name) = 'OPEN'
17301                                      group by t2.owner_id );
17302       *=================================================== */
17303 
17304       /*CURSOR c_resource_mintask(p_party_id NUMBER) IS
17305           SELECT t.owner_id  --, count(t.owner_id)
17306             FROM jtf_tasks_vl t, jtf_task_statuses_vl s
17307            WHERE t.customer_id = p_party_id
17308              AND upper(t.owner_type_code) = 'RS_EMPLOYEE'
17309              AND t.task_name = 'Dunning Callback'
17310              AND t.task_status_id = s.task_status_id
17311              AND upper(s.name) = 'OPEN'
17312              AND t.owner_id in ( select DISTINCT rs.resource_id
17313                                  from as_accesses acc,
17314                                       jtf_rs_resource_extns rs
17315                                 where acc.customer_id = p_party_id
17316                                   and rs.resource_id = acc.salesforce_id
17317                                   and rs.category = 'EMPLOYEE'
17318                                   and rs.user_id is not null
17319                                   AND nvl(rs.end_date_active,sysdate) >= trunc(sysdate) )
17320            GROUP BY t.owner_id
17321           HAVING COUNT(t.owner_id) = (select min(count(t2.owner_id))
17322                                       from jtf_tasks_vl t2, jtf_task_statuses_vl s2
17323                                      WHERE t2.customer_id = p_party_id
17324                                        AND upper(t2.owner_type_code) = 'RS_EMPLOYEE'
17325                                        AND t2.task_name = 'Dunning Callback'
17326                                        AND t2.task_status_id = s2.task_status_id
17327                                        AND upper(s2.name) = 'OPEN'
17328                                        AND t2.owner_id in ( select DISTINCT rs.resource_id
17329                                            from as_accesses acc,
17330                                                 jtf_rs_resource_extns rs
17331                                           where acc.customer_id = p_party_id
17332                                             and rs.resource_id = acc.salesforce_id
17333                                             and rs.category = 'EMPLOYEE'
17334                                             and rs.user_id is not null
17335                                             AND nvl(rs.end_date_active,sysdate) >= trunc(sysdate) )
17336                                      group by t2.owner_id );
17337       --
17338       --
17339       CURSOR c_resource_task_count(p_party_id NUMBER) IS
17340           SELECT t.owner_id,  count(t.owner_id)
17341             FROM jtf_tasks_vl t, jtf_task_statuses_vl s
17342            WHERE t.customer_id = p_party_id
17343              AND upper(t.owner_type_code) = 'RS_EMPLOYEE'
17344              AND t.task_name = 'Dunning Callback'
17345              AND t.task_status_id = s.task_status_id
17346              AND upper(s.name) = 'OPEN'
17347              AND t.owner_id in ( select DISTINCT rs.resource_id
17348                                  from as_accesses acc,
17349                                       jtf_rs_resource_extns rs
17350                                 where acc.customer_id = p_party_id
17351                                   and rs.resource_id = acc.salesforce_id
17352                                   and rs.category = 'EMPLOYEE'
17353                                   and rs.user_id is not null
17354                                   AND nvl(rs.end_date_active,sysdate) >= trunc(sysdate) )
17355            GROUP BY t.owner_id;
17356       --
17357       CURSOR c_resource_notask_count(p_party_id NUMBER) IS
17358           SELECT DISTINCT rs.resource_id, 0
17359             FROM as_accesses acc, jtf_rs_resource_extns rs
17360            WHERE acc.customer_id = p_party_id
17361              AND nvl(rs.end_date_active,sysdate) >= trunc(sysdate)
17362              AND rs.resource_id = acc.salesforce_id
17363              and rs.category = 'EMPLOYEE'
17364              AND rs.user_id is not null
17365              AND rs.resource_id not in ( select distinct t2.owner_id
17366                                            from jtf_tasks_vl t2,
17367                                                 jtf_task_statuses_vl s2
17368                                           where t2.customer_id = p_party_id
17369                                            and upper(t2.owner_type_code) = 'RS_EMPLOYEE'
17370                                            AND t2.task_status_id = s2.task_status_id
17371                                            AND upper(s2.name) = 'OPEN'
17372                                            and t2.task_name = 'Dunning Callback');
17373 
17374       --
17375       TYPE number_tab_type IS TABLE OF NUMBER;
17376       l_p_rs_task_id_tab number_tab_type;
17377       l_p_rs_task_cnt_tab number_tab_type;
17378       l_p_rs_notask_id_tab number_tab_type;
17379       l_p_rs_notask_cnt_tab number_tab_type;
17380 
17381       l_errmsg varchar2(1000);
17382       i number := 0;
17383       l_party_id number := 0;
17384       l_task_count number := 0;
17385       l_notask_count number := 0;
17386       l_resource_id number := 0;*/
17387 
17388     BEGIN
17389 
17390       /*l_api_name   := 'Get_Resource';
17391       l_default_rs_id  := fnd_profile.value('IEX_STRY_DEFAULT_RESOURCE');
17392       l_login  := fnd_global.login_id;
17393       l_user   := FND_GLOBAL.USER_ID;
17394 
17395     --  IF PG_DEBUG < 10  THEN
17396       IF (FND_LOG.LEVEL_EVENT >= PG_DEBUG) THEN
17397          iex_debug_pub.LogMessage ('Get_Resource: ' || 'iexvdunb.pls:GetRS:starting');
17398       END IF;
17399 
17400       -- Standard Start of API savepoint
17401       SAVEPOINT GET_RESOURCE_PVT;
17402 
17403       -- Standard call to check for call compatibility.
17404       IF NOT FND_API.Compatible_API_Call (l_api_version,
17405                                           p_api_version,
17406                                           l_api_name,
17407                                           G_PKG_NAME)
17408       THEN
17409           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
17410       END IF;
17411 
17412       -- Initialize API return status to SUCCESS
17413       x_return_status := FND_API.G_RET_STS_SUCCESS;
17414 
17415       -- Api body
17416       --
17417 
17418       WriteLog('iexvdunb.pls:GetRS:party_id='||p_party_id);
17419 
17420       -- get all resources which have tasks for this party
17421       WriteLog('iexvdunb.pls:GetRS:Get Resources with tasks');
17422       OPEN c_resource_task_count(p_party_id);
17423       FETCH c_resource_task_count
17424        BULK COLLECT INTO l_p_rs_task_id_tab, l_p_rs_task_cnt_tab;
17425       CLOSE c_resource_task_count;
17426       WriteLog('iexvdunb.pls:GetRS:Close GetRs Task count');
17427 
17428       l_task_count := l_p_rs_task_id_tab.count;
17429       WriteLog('iexvdunb.pls:GetRS:RsTaskCount='||l_task_count);
17430        if (l_task_count > 0) then
17431            for i in 1..l_task_count loop
17432                WriteLog('iexvdunb.pls:GetRS:rs_task-i='||i);
17433                WriteLog('iexvdunb.pls:GetRS:id='||l_p_rs_task_id_tab(i));
17434                WriteLog('iexvdunb.pls:GetRS:id='||l_p_rs_task_cnt_tab(i));
17435            end loop;
17436        end if;
17437 
17438       --
17439       -- get all resources which have no task for this party
17440       WriteLog('iexvdunb.pls:GetRS:Get Resources withnot task');
17441       OPEN c_resource_notask_count(p_party_id);
17442       FETCH c_resource_notask_count
17443        BULK COLLECT INTO l_p_rs_notask_id_tab, l_p_rs_notask_cnt_tab;
17444       CLOSE c_resource_notask_count;
17445       WriteLog('iexvdunb.pls:GetRS:Close Get ResourceNoTask count');
17446 
17447       l_notask_count := l_p_rs_notask_id_tab.count;
17448       WriteLog('iexvdunb.pls:GetRS:RsNoTaskCount='||l_notask_count);
17449 
17450       --
17451 
17452       if (l_notask_count > 0 )  then
17453           -- it means there're some resources haven't been assigned tasks yet
17454           l_resource_id := l_p_rs_notask_id_tab(1);
17455           WriteLog('iexvdunb.pls:GetRS:resource_id='||l_resource_id);
17456           for i in 1..l_notask_count loop
17457              WriteLog('iexvdunb.pls:GetRS:rs_notask-i='||i);
17458              WriteLog('iexvdunb.pls:GetRS:id='||l_p_rs_notask_id_tab(i));
17459              WriteLog('iexvdunb.pls:GetRS:cnt='||l_p_rs_notask_cnt_tab(i));
17460           end loop;
17461       else
17462           -- l_notask_count = 0
17463           if (l_task_count > 0) then
17464               -- all resources have tasks
17465               -- get resource_id which has the least tasks based on query
17466               OPEN c_resource_mintask(p_party_id);
17467               FETCH c_resource_mintask into l_resource_id;
17468               CLOSE c_resource_mintask;
17469           else
17470               -- l_task_count = 0 and l_notask_count = 0
17471               -- no available resource based on party_resource relationship
17472               -- get the default resource
17473               l_resource_id := l_default_rs_id;
17474           end if;
17475           WriteLog('iexvdunb.pls:GetRS:resource_id='||l_resource_id);
17476       end if;
17477 
17478       --
17479       WriteLog('iexvdunb.pls:GetRS:END_RESOURCE');
17480       x_resource_id := l_resource_id;
17481       WriteLog('iexvdunb.pls:GetRS:x_resource_id='||x_resource_id);
17482 
17483       --
17484       -- End of API body
17485       --
17486 
17487       -- Standard check for p_commit
17488       IF FND_API.to_Boolean( p_commit )
17489       THEN
17490          COMMIT WORK;
17491       END IF;
17492 
17493       WriteLog('iexvdunb.pls:GetRS:END');
17494 
17495       -- Standard call to get message count and if count is 1, get message info.
17496       FND_MSG_PUB.Count_And_Get
17497       (  p_count          =>   x_msg_count,
17498          p_data           =>   x_msg_data
17499       );
17500 
17501           EXCEPTION
17502               WHEN FND_API.G_EXC_ERROR THEN
17503                  ROLLBACK TO GET_RESOURCE_PVT;
17504                  x_return_status := FND_API.G_RET_STS_ERROR;
17505                  l_errmsg := SQLERRM;
17506                  WriteLog('iexvdunb:GetRs-G_EXC_EXCEPTION::' || l_errmsg);
17507                  FND_MSG_PUB.Count_And_Get
17508                  (  p_count          =>   x_msg_count,
17509                     p_data           =>   x_msg_data
17510                  );
17511 
17512               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
17513                  ROLLBACK TO GET_RESOURCE_PVT;
17514                  x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
17515                  l_errmsg := SQLERRM;
17516                  WriteLog('iexvdunb:GetRs-G_EXC_UNEXP_EXCEPTION:OTHERS:' || l_errmsg);
17517                  FND_MSG_PUB.Count_And_Get
17518                  (  p_count          =>   x_msg_count,
17519                     p_data           =>   x_msg_data
17520                  );
17521 
17522               WHEN OTHERS THEN
17523                  ROLLBACK TO GET_RESOURCE_PVT;
17524                  x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
17525                  l_errmsg := SQLERRM;
17526                  WriteLog('iexvdunb:GetRs-EXCEPTION:OTHERS:' || l_errmsg);
17527                  FND_MSG_PUB.Count_And_Get
17528                  (  p_count          =>   x_msg_count,
17529                     p_data           =>   x_msg_data
17530                  );*/
17531     NULL;
17532 
17533     END GET_RESOURCE;
17534 
17535     FUNCTION Party_currency_code(p_party_id NUMBER) RETURN VARCHAR2
17536     IS
17537       cursor c_amount (IN_ID number) is
17538          select ps.invoice_currency_code
17539            from ar_payment_schedules_all ps,
17540                 iex_delinquencies del
17541           where ps.payment_schedule_id (+)= del.payment_schedule_id
17542             and del.party_cust_id = in_id;
17543       l_code VARCHAR2(15);
17544     BEGIN
17545       WriteLog ('Party_currency_code: ' || 'currency_code');
17546       WriteLog ('Party_currency_code: ' || 'party_id='||p_party_id);
17547       open c_amount(p_party_id);
17548       fetch c_amount into l_code;
17549       if c_amount%found then
17550          WriteLog('Party_currency_code: ' || 'code='||l_code);
17551       else
17552          WriteLog ('Party_currency_code: ' || 'notfound');
17553         l_code := '';
17554       END if;
17555       close c_amount;
17556 
17557       RETURN l_code;
17558 
17559     END party_currency_code;
17560 
17561     FUNCTION acct_currency_code(p_account_id NUMBER) RETURN VARCHAR2
17562     IS
17563       cursor c_amount (IN_ID number) is
17564          select ps.invoice_currency_code
17565            from ar_payment_schedules_all ps,
17566                 --iex_delinquencies_all del
17567                 iex_delinquencies del
17568           where ps.payment_schedule_id (+)= del.payment_schedule_id
17569             and del.cust_account_id = in_id;
17570       l_code VARCHAR2(15);
17571     BEGIN
17572       WriteLog('acct_currency_code: ' || 'currency_code');
17573       WriteLog('acct_currency_code: ' || 'account_id='||p_account_id);
17574       open c_amount(p_account_id);
17575       fetch c_amount into l_code;
17576       if c_amount%found then
17577         WriteLog('acct_currency_code: ' || 'code='||l_code);
17578       else
17579         WriteLog ('acct_currency_code: ' || 'notfound');
17580         l_code := '';
17581       END if;
17582       close c_amount;
17583 
17584       RETURN l_code;
17585 
17586     END acct_currency_code;
17587 
17588     FUNCTION site_currency_code(p_customer_site_use_id NUMBER) RETURN VARCHAR2
17589     IS
17590       cursor c_amount (IN_ID number) is
17591          select ps.invoice_currency_code
17592            from ar_payment_schedules_all ps,
17593                 iex_delinquencies del
17594           where ps.payment_schedule_id (+)= del.payment_schedule_id
17595             and del.customer_site_use_id = in_id;
17596 
17597       l_code VARCHAR2(15);
17598 
17599     BEGIN
17600       WriteLog ('site_currency_code: ' || 'currency_code');
17601       WriteLog ('site_currency_code: ' || 'customer_site_use_id='||p_customer_site_use_id);
17602       open c_amount(p_customer_site_use_id);
17603       fetch c_amount into l_code;
17604       if c_amount%found then
17605          WriteLog ('site_currency_code: ' || 'code='||l_code);
17606       else
17607          WriteLog('site_currency_code: ' || 'notfound');
17608          l_code := '';
17609       END if;
17610       close c_amount;
17611 
17612       RETURN l_code;
17613 
17614     END site_currency_code;
17615 
17616     FUNCTION party_amount_due_remaining(p_party_id NUMBER) RETURN NUMBER
17617     IS
17618       cursor c_amount (IN_ID number) is
17619          select sum(ps.acctd_amount_due_remaining)
17620            from ar_payment_schedules_all ps,
17621                 iex_delinquencies del
17622           where ps.payment_schedule_id (+)= del.payment_schedule_id
17623             and del.party_cust_id = in_id;
17624       l_sum number;
17625     BEGIN
17626       WriteLog('party_amount_due_remaining: ' || 'party_amount_due_remainging');
17627       WriteLog('party_amount_due_remaining: ' || 'party_id='||p_party_id);
17628       open c_amount(p_party_id);
17629       fetch c_amount into l_sum;
17630       if c_amount%found then
17631         WriteLog('party_amount_due_remaining: ' || 'sum='||l_sum);
17632       else
17633         WriteLog('party_amount_due_remaining: ' || 'notfound');
17634         l_sum := 0;
17635       END if;
17636       close c_amount;
17637 
17638       RETURN l_sum;
17639 
17640     END party_amount_due_remaining;
17641 
17642     FUNCTION acct_amount_due_remaining(p_account_id NUMBER) RETURN NUMBER
17643     IS
17644       cursor c_amount (IN_ID number) is
17645          select sum(ps.acctd_amount_due_remaining)
17646            from ar_payment_schedules_all ps,
17647                 --iex_delinquencies_all del
17648                 iex_delinquencies del
17649           where ps.payment_schedule_id (+)= del.payment_schedule_id
17650             and del.cust_account_id = in_id;
17651       l_sum number;
17652     BEGIN
17653       WriteLog('acct_amount_due_remaining: ' || 'acct_amount_due_remainging');
17654       WriteLog('acct_amount_due_remaining: ' || 'account_id='||p_account_id);
17655       open c_amount(p_account_id);
17656       fetch c_amount into l_sum;
17657       if c_amount%found then
17658          WriteLog ('acct_amount_due_remaining: ' || 'sum='||l_sum);
17659       else
17660          WriteLog ('acct_amount_due_remaining: ' || 'notfound');
17661         l_sum := 0;
17662       END if;
17663       close c_amount;
17664 
17665       RETURN l_sum;
17666 
17667     END acct_amount_due_remaining;
17668 
17669     FUNCTION site_amount_due_remaining(p_customer_site_use_id NUMBER) RETURN NUMBER
17670     IS
17671       cursor c_amount (IN_ID number) is
17672          select sum(ps.acctd_amount_due_remaining)
17673            from ar_payment_schedules_all ps,
17674                 iex_delinquencies del
17675           where ps.payment_schedule_id (+)= del.payment_schedule_id
17676             and del.customer_site_use_id = in_id;
17677       l_sum number;
17678     --
17679     BEGIN
17680       --
17681       WriteLog ('site_amount_due_remaining: ' || 'site_amount_due_remainging');
17682       WriteLog('site_amount_due_remaining: ' || 'customer_site_use_id='||p_customer_site_use_id);
17683       --
17684       open c_amount(p_customer_site_use_id);
17685       fetch c_amount into l_sum;
17686       if c_amount%found then
17687          WriteLog ('site_amount_due_remaining: ' || 'sum='||l_sum);
17688       else
17689          WriteLog ('site_amount_due_remaining: ' || 'notfound');
17690          l_sum := 0;
17691       END if;
17692       close c_amount;
17693       --
17694       RETURN l_sum;
17695 
17696     END site_amount_due_remaining;
17697 
17698     --Start adding for bug 9503251 gnramasa 2nd Apr 2010
17699     FUNCTION staged_dunn_amt_due_remaining(p_dunning_id number) RETURN NUMBER
17700     IS
17701       cursor c_amount (dunn_id number) is
17702          select sum(ps.acctd_amount_due_remaining)
17703            from ar_payment_schedules_all ps,
17704                 iex_dunning_transactions dtrx
17705           where ps.payment_schedule_id = dtrx.payment_schedule_id
17706             and dtrx.dunning_id = dunn_id;
17707       l_sum number;
17708     BEGIN
17709       WriteLog('staged_dunn_amt_due_remaining: Start');
17710       WriteLog('staged_dunn_amt_due_remaining: p_dunning_id='||p_dunning_id);
17711       open c_amount(p_dunning_id);
17712       fetch c_amount into l_sum;
17713       if c_amount%found then
17714         WriteLog('acct_amount_due_remaining: sum='||l_sum);
17715       else
17716         WriteLog('acct_amount_due_remaining: notfound');
17717         l_sum := 0;
17718       END if;
17719       close c_amount;
17720 
17721       RETURN l_sum;
17722 
17723     END staged_dunn_amt_due_remaining;
17724     --End adding for bug 9503251 gnramasa 2nd Apr 2010
17725 
17726     FUNCTION get_party_id(p_account_id NUMBER) RETURN NUMBER
17727     IS
17728       cursor c_party (IN_ID number) is
17729          select del.party_cust_id
17730            from iex_delinquencies del
17731           where del.cust_account_id = in_id;
17732       l_party number;
17733     BEGIN
17734       WriteLog('get_party_id');
17735       WriteLog('get_party_id: ' || 'account_id='||p_account_id);
17736       open c_party(p_account_id);
17737       fetch c_party into l_party;
17738       if c_party%found then
17739          WriteLog ('get_party_id: ' || 'party='||l_party);
17740       else
17741          WriteLog ('get_party_id: ' || 'notfound');
17742         l_party := 0;
17743       END if;
17744       close c_party;
17745 
17746       RETURN l_party;
17747 
17748     END get_party_id;
17749 
17750     --Start adding for bug 8489610 by gnramasa 14-May-09
17751     PROCEDURE PRINT_CLOB
17752       (lob_loc IN CLOB)
17753                 IS
17754       /*-----------------------------------------------------------------------+
17755       | Local Variable Declarations and initializations                       |
17756       +-----------------------------------------------------------------------*/
17757       l_api_name    CONSTANT VARCHAR2(30) := 'PRINT_CLOB';
17758       l_api_version CONSTANT NUMBER       := 1.0;
17759       c_endline     CONSTANT VARCHAR2 (1) := '
17760 ';
17761       c_endline_len CONSTANT NUMBER       := LENGTH (c_endline);
17762       l_start       NUMBER                := 1;
17763       l_end         NUMBER;
17764       l_one_line    VARCHAR2 (7000);
17765       l_charset     VARCHAR2(100);
17766       /*-----------------------------------------------------------------------+
17767       | Cursor Declarations                                                   |
17768       +-----------------------------------------------------------------------*/
17769     BEGIN
17770       -- LogMessage(FND_LOG.LEVEL_PROCEDURE, G_PKG_NAME || '.' || l_api_name || ' +');
17771       LOOP
17772         l_end := DBMS_LOB.INSTR (lob_loc => lob_loc, pattern => c_endline, offset => l_start, nth => 1 );
17773         --FND_FILE.put_line( FND_FILE.LOG,'l_end-->'||l_end);
17774         IF (NVL (l_end, 0) < 1) THEN
17775           EXIT;
17776         END IF;
17777         l_one_line := DBMS_LOB.SUBSTR (lob_loc => lob_loc, amount => l_end - l_start, offset => l_start );
17778         --FND_FILE.put_line( FND_FILE.LOG,'l_one_line-->'||l_one_line);
17779         --FND_FILE.put_line( FND_FILE.LOG,'c_endline_len-->'||c_endline_len);
17780         l_start := l_end + c_endline_len;
17781         --FND_FILE.put_line( FND_FILE.LOG,'l_start-->'||l_start);
17782         --FND_FILE.put_line( FND_FILE.LOG,'32');
17783         Fnd_File.PUT_line(Fnd_File.OUTPUT,l_one_line);
17784       END LOOP;
17785     END PRINT_CLOB;
17786 
17787     /*========================================================================+
17788        Function which replaces the special characters in the strings to form
17789        a valid XML string
17790      +========================================================================*/
17791     FUNCTION format_string(p_string varchar2) return varchar2 IS
17792 
17793       l_string varchar2(2000);
17794     BEGIN
17795 
17796         l_string := replace(p_string,'&','&'||'amp;');
17797         l_string := replace(l_string,'<','&'||'lt;');
17798         l_string := replace(l_string,'>','&'||'gt;');
17799 
17800         RETURN l_string;
17801 
17802     END format_string;
17803 
17804     Procedure gen_xml_data_dunning (p_request_id			IN  NUMBER,
17805                                     p_running_level			IN  VARCHAR2,
17806     				p_dunning_plan_id		IN  NUMBER,
17807     				p_dunning_mode			IN  VARCHAR2,     -- added by gnramasa for bug 8489610 28-May-09
17808     	                        p_confirmation_mode		IN  VARCHAR2,     -- added by gnramasa for bug 8489610 28-May-09
17809     				p_process_err_rec_only          IN  VARCHAR2,
17810     				p_no_of_rec_prc_bylastrun	IN  NUMBER,
17811     				p_no_of_succ_rec_bylastrun	IN  NUMBER,
17812     				p_no_of_fail_rec_bylastrun	IN  NUMBER,
17813     				p_org_id_coll_method            IN VARCHAR2,   -- Added by snuthala for bug 10221334 21/10/2010
17814     				x_no_of_rec_prc			OUT NOCOPY NUMBER,
17815     				x_no_of_succ_rec		OUT NOCOPY NUMBER,
17816     				x_no_of_fail_rec		OUT NOCOPY NUMBER)
17817     is
17818        l_api_version           CONSTANT NUMBER := 1.0;
17819        ctx                     DBMS_XMLQUERY.ctxType;
17820        result                  CLOB;
17821        qryCtx                  DBMS_XMLGEN.ctxHandle;
17822        l_result                CLOB;
17823        tempResult              CLOB;
17824        l_version               varchar2(20);
17825        l_compatibility         varchar2(20);
17826        l_suffix                varchar2(2);
17827        l_majorVersion          number;
17828        l_resultOffset          number;
17829        l_xml_header            varchar2(4000);
17830        l_xml_header_length     number;
17831        l_errNo                 NUMBER;
17832        l_errMsg                VARCHAR2(200);
17833        queryCtx                DBMS_XMLquery.ctxType;
17834        l_xml_query             VARCHAR2(32767);
17835        TYPE ref_cur IS REF CURSOR;
17836        l_xml_stmt              ref_cur;
17837        l_rows_processed        NUMBER;
17838        l_new_line              VARCHAR2(1);
17839        l_close_tag             VARCHAR2(100);
17840        l_no_of_rec_prc	   number;
17841        l_no_of_succ_rec        number;
17842        l_no_of_fail_rec        number;
17843 
17844        cursor c_calculate_no_rec (p_req_id number) is
17845        SELECT
17846     	count(*) no_of_rec_processed,
17847     	sum(decode(delivery_status,NULL,1,0)) no_of_success_records,
17848     	sum(decode(delivery_status,NULL,0,1)) no_of_failure_records
17849        FROM iex_dunnings id
17850        WHERE id.request_id = p_req_id
17851             AND id.object_type <> 'IEX_INVOICES'
17852     	AND id.dunning_id =  (SELECT MAX(dunning_id)
17853     			      FROM iex_dunnings d
17854     			      WHERE d.dunning_object_id = id.dunning_object_id
17855     				   AND d.dunning_level = id.dunning_level
17856     				   AND d.request_id = id.request_id
17857     				   AND d.object_type <> 'IEX_INVOICES');
17858 
17859      l_query_party varchar2(11000) :=
17860     'select ' ||
17861     'id.dunning_object_id PARTY_ID, ' ||
17862     'p.party_name PARTY_NAME, ' ||
17863     'id.dunning_object_id DUNNING_OBJECT_ID, ' ||
17864     'id.xml_template_id TEMPLATE_ID,  ' ||
17865     'xtvl.template_name TEMPLATE_NAME, ' ||
17866     'id.delivery_status ERROR, ' ||
17867     'fnd_message.get_string(''IEX'',id.delivery_status) ERROR_DESC, ' ||
17868     'iex_utilities.get_lookup_meaning(''IEX_FULFILLMENT_SEND_METHOD'',id.dunning_method) DUNNING_METHOD, '||
17869     'ixr.destination DESTINATION, ' ||
17870     'decode(id.DUNNING_MODE, ''DRAFT'', iex_utilities.get_lookup_meaning(''IEX_CONFIRMATION_MODE'', nvl(id.CONFIRMATION_MODE,''DRAFT'')),iex_utilities.get_lookup_meaning(''IEX_CONFIRMATION_MODE'',''CONFIRMED'')) CONFIRMATION_STATUS '||
17871     --'ixr.xml_request_id REQUEST_ID ' ||
17872     --' ''http://techcm.us.oracle.com:8000/OA_HTML/IEXDUNCPRRedirect.jsp?RequestId=''  || ixr.xml_request_id DOWNLOAD_URL ' ||
17873     'from iex_xml_request_histories ixr, ' ||
17874     'hz_parties p, ' ||
17875     'iex_dunnings id, ' ||
17876     'XDO_TEMPLATES_B xtb, ' ||
17877     'XDO_TEMPLATES_TL xtvl ' ||
17878     'where id.dunning_object_id = p.party_id ' ||
17879     'and ixr.xml_request_id (+) = id.xml_request_id ' ||
17880     'and id.request_id = :l_request_id ' ||
17881     'and xtb.template_code=xtvl.template_code ' ||
17882     'and xtb.template_id = id.xml_template_id ' ||
17883     'and xtvl.language=userenv(''LANG'') ' ||
17884     'AND id.object_type <> ''IEX_INVOICES'' ' ||
17885     'and id.dunning_id = (select max(dunning_id) from iex_dunnings d ' ||
17886                          ' where d.dunning_object_id = id.dunning_object_id and d.dunning_level=id.dunning_level and d.request_id = id.request_id ' ||
17887     		     ' AND d.object_type <> ''IEX_INVOICES'' ) ' ||
17888     --'order by lower(p.party_name)' ;
17889     'order by NLSSORT(lower(p.party_name),''NLS_SORT=BINARY'')'; -- added by sunagesh for bug 13877178
17890     l_query_account varchar2(11000) :=
17891     'select ' ||
17892     'p.party_id PARTY_ID, ' ||
17893     'p.party_name PARTY_NAME, ' ||
17894     'hcu.account_number ACCOUNT_NUMBER, ' ||
17895     'id.dunning_object_id DUNNING_OBJECT_ID, ' ||
17896     'id.xml_template_id TEMPLATE_ID,  ' ||
17897     'xtvl.template_name TEMPLATE_NAME,  ' ||
17898     'id.delivery_status ERROR, ' ||
17899     'fnd_message.get_string(''IEX'',id.delivery_status) ERROR_DESC, ' ||
17900     'iex_utilities.get_lookup_meaning(''IEX_FULFILLMENT_SEND_METHOD'',id.dunning_method) DUNNING_METHOD, '||
17901     'ixr.destination DESTINATION, ' ||
17902     'decode(id.DUNNING_MODE, ''DRAFT'', iex_utilities.get_lookup_meaning(''IEX_CONFIRMATION_MODE'', nvl(id.CONFIRMATION_MODE,''DRAFT'')),iex_utilities.get_lookup_meaning(''IEX_CONFIRMATION_MODE'',''CONFIRMED'')) CONFIRMATION_STATUS '||
17903     --'ixr.xml_request_id REQUEST_ID ' ||
17904     --' ''http://techcm.us.oracle.com:8000/OA_HTML/IEXDUNCPRRedirect.jsp?RequestId=''  || ixr.xml_request_id DOWNLOAD_URL ' ||
17905     'from iex_xml_request_histories ixr, ' ||
17906     'hz_parties p, ' ||
17907     'hz_cust_accounts hcu, ' ||
17908     'iex_dunnings id, ' ||
17909     'XDO_TEMPLATES_B xtb, ' ||
17910     'XDO_TEMPLATES_TL xtvl ' ||
17911     'where id.dunning_object_id = hcu.cust_account_id ' ||
17912     'and hcu.party_id = p.party_id ' ||
17913     'and ixr.xml_request_id (+) = id.xml_request_id  ' ||
17914     'and id.request_id = :l_request_id ' ||
17915     'and xtb.template_code=xtvl.template_code ' ||
17916     'and xtb.template_id = id.xml_template_id ' ||
17917     'and xtvl.language=userenv(''LANG'') ' ||
17918     'AND id.object_type <> ''IEX_INVOICES'' ' ||
17919     'and id.dunning_id = (select max(dunning_id) from iex_dunnings d ' ||
17920                          ' where d.dunning_object_id = id.dunning_object_id and d.dunning_level=id.dunning_level and d.request_id = id.request_id ' ||
17921     		     ' AND d.object_type <> ''IEX_INVOICES'' ) ' ||
17922     --'order by lower(p.party_name)' ;
17923     'order by NLSSORT(lower(p.party_name),''NLS_SORT=BINARY'')'; -- added by sunagesh for bug 13877178
17924     l_query_bill_to varchar2(11000) :=
17925     'select ' ||
17926     'p.party_id PARTY_ID, ' ||
17927     'p.party_name PARTY_NAME, ' ||
17928     'hcu.account_number ACCOUNT_NUMBER, ' ||
17929     'site_uses.location LOCATION, ' ||
17930     'id.dunning_object_id DUNNING_OBJECT_ID, ' ||
17931     'id.xml_template_id TEMPLATE_ID,  ' ||
17932     'xtvl.template_name TEMPLATE_NAME,  ' ||
17933     'id.delivery_status ERROR, ' ||
17934     'fnd_message.get_string(''IEX'',id.delivery_status) ERROR_DESC, ' ||
17935     'iex_utilities.get_lookup_meaning(''IEX_FULFILLMENT_SEND_METHOD'',id.dunning_method) DUNNING_METHOD, '||
17936     'ixr.destination DESTINATION, ' ||
17937     'decode(id.DUNNING_MODE, ''DRAFT'', iex_utilities.get_lookup_meaning(''IEX_CONFIRMATION_MODE'', nvl(id.CONFIRMATION_MODE,''DRAFT'')),iex_utilities.get_lookup_meaning(''IEX_CONFIRMATION_MODE'',''CONFIRMED'')) CONFIRMATION_STATUS '||
17938     --'ixr.xml_request_id REQUEST_ID ' ||
17939     --' ''http://techcm.us.oracle.com:8000/OA_HTML/IEXDUNCPRRedirect.jsp?RequestId=''  || ixr.xml_request_id DOWNLOAD_URL ' ||
17940     'from iex_xml_request_histories ixr, ' ||
17941     'hz_parties p, ' ||
17942     'hz_cust_accounts hcu,' ||
17943     'hz_cust_acct_sites_all acct_sites, ' ||
17944     'hz_cust_site_uses_all site_uses, ' ||
17945     'iex_dunnings id, ' ||
17946     'XDO_TEMPLATES_B xtb, ' ||
17947     'XDO_TEMPLATES_TL xtvl ' ||
17948     'where id.dunning_object_id = site_uses.site_use_id ' ||
17949     'and acct_sites.cust_acct_site_id = site_uses.cust_acct_site_id ' ||
17950     'and hcu.cust_account_id = acct_sites.cust_account_id ' ||
17951     'and p.party_id = hcu.party_id ' ||
17952     'and ixr.xml_request_id (+) = id.xml_request_id ' ||
17953     'and id.request_id = :l_request_id ' ||
17954     'and xtb.template_code=xtvl.template_code ' ||
17955     'and xtb.template_id = id.xml_template_id ' ||
17956     'and xtvl.language=userenv(''LANG'') ' ||
17957     'AND id.object_type <> ''IEX_INVOICES'' ' ||
17958     --'and nvl(id.confirmation_mode,''CONFIRMED'') <> ''REJECTED'' ' ||
17959     'and id.dunning_id = (select max(dunning_id) from iex_dunnings d ' ||
17960                          ' where d.dunning_object_id = id.dunning_object_id and d.dunning_level=id.dunning_level and d.request_id = id.request_id ' ||
17961     		     ' AND d.object_type <> ''IEX_INVOICES'' ) ' ||
17962    -- 'order by lower(p.party_name)' ;
17963     'order by NLSSORT(lower(p.party_name),''NLS_SORT=BINARY'')'; -- added by sunagesh for bug 13877178
17964     l_query_delinquency varchar2(11000) :=
17965     'select ' ||
17966     'id.dunning_object_id PARTY_ID, ' ||
17967     'p.party_name PARTY_NAME, ' ||
17968     'aps.trx_number TRANSACTION_NUMBER, ' ||
17969     'id.dunning_object_id DUNNING_OBJECT_ID, ' ||
17970     'id.xml_template_id TEMPLATE_ID,  ' ||
17971     'xtvl.template_name TEMPLATE_NAME,  ' ||
17972     'id.delivery_status ERROR, ' ||
17973     'fnd_message.get_string(''IEX'',id.delivery_status) ERROR_DESC, ' ||
17974     'iex_utilities.get_lookup_meaning(''IEX_FULFILLMENT_SEND_METHOD'',id.dunning_method) DUNNING_METHOD, '||
17975     'ixr.destination DESTINATION, ' ||
17976     'decode(id.DUNNING_MODE, ''DRAFT'', iex_utilities.get_lookup_meaning(''IEX_CONFIRMATION_MODE'', nvl(id.CONFIRMATION_MODE,''DRAFT'')),iex_utilities.get_lookup_meaning(''IEX_CONFIRMATION_MODE'',''CONFIRMED'')) CONFIRMATION_STATUS '||
17977     --'ixr.xml_request_id REQUEST_ID ' ||
17978     --' ''http://techcm.us.oracle.com:8000/OA_HTML/IEXDUNCPRRedirect.jsp?RequestId=''  || ixr.xml_request_id DOWNLOAD_URL ' ||
17979     'from iex_xml_request_histories ixr, ' ||
17980     'hz_parties p, ' ||
17981     'iex_dunnings id, ' ||
17982     'XDO_TEMPLATES_B xtb, ' ||
17983     'XDO_TEMPLATES_TL xtvl, ' ||
17984     'iex_delinquencies_all del, ' ||
17985     'ar_payment_schedules_all aps ' ||
17986     'where id.dunning_object_id = del.delinquency_id ' ||
17987     'and del.payment_Schedule_id = aps.payment_Schedule_id ' ||
17988     'and del.party_cust_id = p.party_id ' ||
17989     'and ixr.xml_request_id (+) = id.xml_request_id  ' ||
17990     'and id.request_id = :l_request_id ' ||
17991     'and xtb.template_code=xtvl.template_code ' ||
17992     'and xtb.template_id = id.xml_template_id ' ||
17993     'and xtvl.language=userenv(''LANG'') ' ||
17994     'AND id.object_type <> ''IEX_INVOICES'' ' ||
17995     'and id.dunning_id = (select max(dunning_id) from iex_dunnings d ' ||
17996                          ' where d.dunning_object_id = id.dunning_object_id and d.dunning_level=id.dunning_level and d.request_id = id.request_id ' ||
17997     		     ' AND d.object_type <> ''IEX_INVOICES'' ) ' ||
17998    -- 'order by lower(p.party_name)' ;
17999     'order by NLSSORT(lower(p.party_name),''NLS_SORT=BINARY'')'; -- added by sunagesh for bug 13877178
18000     l_report_date   varchar2(30);
18001     l_dunning_plan  iex_dunning_plans_vl.name%type;
18002     l_req_id	number;
18003     l_encoding      VARCHAR2(100);  --Added for bug 10141904 gnramasa 24th Sep 10
18004 
18005     begin
18006     FND_FILE.put_line( FND_FILE.LOG,'XML generation starts');
18007     l_req_id := p_request_id;
18008 
18009     select to_char(sysdate,  'YYYY-MM-DD')
18010     into l_report_date
18011     from dual;
18012 
18013     select name
18014     into l_dunning_plan
18015     from iex_dunning_plans_vl
18016     where dunning_plan_id= p_dunning_plan_id;
18017 
18018     open c_calculate_no_rec (l_req_id);
18019     fetch c_calculate_no_rec into l_no_of_rec_prc, l_no_of_succ_rec, l_no_of_fail_rec;
18020     close c_calculate_no_rec;
18021 
18022        if p_running_level = 'PARTY' then
18023     	ctx := DBMS_XMLQUERY.newContext(l_query_party);
18024     	FND_FILE.put_line( FND_FILE.LOG,'l_query_party ==> ' || l_query_party);
18025        elsif p_running_level = 'ACCOUNT' then
18026     	ctx := DBMS_XMLQUERY.newContext(l_query_account);
18027     	FND_FILE.put_line( FND_FILE.LOG,'l_query_party ==> ' || l_query_account);
18028        elsif p_running_level = 'BILL_TO' then
18029     	ctx := DBMS_XMLQUERY.newContext(l_query_bill_to);
18030     	FND_FILE.put_line( FND_FILE.LOG,'l_query_party ==> ' || l_query_bill_to);
18031        elsif p_running_level = 'DELINQUENCY' then
18032     	ctx := DBMS_XMLQUERY.newContext(l_query_delinquency);
18033     	FND_FILE.put_line( FND_FILE.LOG,'l_query_party ==> ' || l_query_delinquency);
18034        else
18035     	ctx := DBMS_XMLQUERY.newContext(l_query_party);
18036     	FND_FILE.put_line( FND_FILE.LOG,'l_query_party ==> ' || l_query_party);
18037        end if;
18038 
18039        DBMS_XMLQuery.setRaiseNoRowsException(ctx,TRUE);
18040        -- Bind Mandatory Variables
18041        DBMS_XMLQuery.setBindValue(ctx, 'l_request_id', l_req_id);
18042 
18043        --get the result
18044 
18045         BEGIN
18046             l_result := DBMS_XMLQUERY.getXML(ctx);
18047     	DBMS_XMLQuery.closeContext(ctx);
18048     	l_rows_processed := 1;
18049          EXCEPTION
18050          WHEN OTHERS THEN
18051             FND_FILE.put_line( FND_FILE.LOG,'In excepition, Error is: '||sqlerrm);
18052             DBMS_XMLQuery.getExceptionContent(ctx,l_errNo,l_errMsg);
18053             IF l_errNo = 1403 THEN
18054     	   FND_FILE.put_line( FND_FILE.LOG,'Query not returned any rows');
18055                l_rows_processed := 0;
18056             END IF;
18057             DBMS_XMLQuery.closeContext(ctx);
18058          END;
18059 
18060         IF l_rows_processed <> 0 THEN
18061              l_resultOffset   := DBMS_LOB.INSTR(l_result,'>');
18062         ELSE
18063              l_resultOffset   := 0;
18064         END IF;
18065 
18066           FND_FILE.put_line( FND_FILE.LOG,'Start constructing the XML Header');
18067 l_new_line := '
18068 ';
18069           /*Get the special characters replaced */
18070           l_report_date      := format_string(l_report_date);
18071           l_dunning_plan      := format_string(l_dunning_plan);
18072 
18073           /* Prepare the tag for the report heading */
18074        --Start adding for bug 10141904 gnramasa 24th Sep 10
18075        --l_xml_header     := '<?xml version="1.0" encoding="UTF-8"?>';
18076        -- Instead of hard coding the value, pick the charcter set value from "ICX: Client IANA Encoding" profile.
18077        l_encoding       := fnd_profile.value('ICX_CLIENT_IANA_ENCODING');
18078        l_xml_header     := '<?xml version="1.0" encoding="'||l_encoding||'"?>';
18079        --End adding for bug 10141904 gnramasa 24th Sep 10
18080        l_xml_header     := l_xml_header ||l_new_line||'<DUNNINGSET>';
18081        l_xml_header     := l_xml_header ||l_new_line||'        <REPORT_DATE>'||l_report_date||'</REPORT_DATE>';
18082        l_xml_header     := l_xml_header ||l_new_line||'        <DUNNING_LEVEL>'||p_running_level||'</DUNNING_LEVEL>';
18083        l_xml_header     := l_xml_header ||l_new_line||'        <DUNNING_PLAN>' ||l_dunning_plan ||'</DUNNING_PLAN>';
18084        l_xml_header     := l_xml_header ||l_new_line||'        <DUNNING_MODE>' ||iex_utilities.get_lookup_meaning('IEX_DUNNING_MODE',p_dunning_mode) ||'</DUNNING_MODE>';
18085        l_xml_header     := l_xml_header ||l_new_line||'        <CONC_REQUEST_ID>' || p_request_id ||'</CONC_REQUEST_ID>';
18086        l_xml_header     := l_xml_header ||l_new_line||'        <NO_OF_REC_PROCESSED>' || l_no_of_rec_prc ||'</NO_OF_REC_PROCESSED>';
18087        l_xml_header     := l_xml_header ||l_new_line||'        <NO_OF_SUCCESS_REC>' || l_no_of_succ_rec ||'</NO_OF_SUCCESS_REC>';
18088        l_xml_header     := l_xml_header ||l_new_line||'        <NO_OF_FAILURE_REC>' || l_no_of_fail_rec ||'</NO_OF_FAILURE_REC>';
18089        l_xml_header     := l_xml_header ||l_new_line||'        <IN_ERROR_MODE>' || p_process_err_rec_only ||'</IN_ERROR_MODE>';
18090        l_xml_header     := l_xml_header ||l_new_line||'        <NO_OF_ERRORED_REC_PROCESSED>' || p_no_of_rec_prc_bylastrun ||'</NO_OF_ERRORED_REC_PROCESSED>';
18091        l_xml_header     := l_xml_header ||l_new_line||'        <NO_OF_SUCCESS_REC_BY_LASTRUN>' || p_no_of_succ_rec_bylastrun ||'</NO_OF_SUCCESS_REC_BY_LASTRUN>';
18092        l_xml_header     := l_xml_header ||l_new_line||'        <NO_OF_FAILURE_REC_BY_LASTRUN>' || p_no_of_fail_rec_bylastrun ||'</NO_OF_FAILURE_REC_BY_LASTRUN>';
18093        l_xml_header     := l_xml_header ||l_new_line||'        <COLLECTIONS_METHOD>' || p_org_id_coll_method ||'</COLLECTIONS_METHOD>'; -- Added by snuthala for bug 10221334 21/10/2010
18094        l_close_tag      := l_new_line||'</DUNNINGSET>'||l_new_line;
18095        l_xml_header_length := length(l_xml_header);
18096        tempResult := l_xml_header;
18097        FND_FILE.put_line( FND_FILE.LOG,'Constructing the XML Header is success');
18098 
18099        IF l_rows_processed <> 0 THEN
18100           FND_FILE.put_line( FND_FILE.LOG,'Start constructing the XML body');
18101           dbms_lob.copy(tempResult,l_result
18102                       ,dbms_lob.getlength(l_result)-l_resultOffset
18103                        ,l_xml_header_length,l_resultOffset);
18104        ELSE
18105           dbms_lob.createtemporary(tempResult,FALSE,DBMS_LOB.CALL);
18106           dbms_lob.open(tempResult,dbms_lob.lob_readwrite);
18107           dbms_lob.writeAppend(tempResult, length(l_xml_header), l_xml_header);
18108        END IF;
18109 
18110       FND_FILE.put_line( FND_FILE.LOG,'Constructing the XML Body is success');
18111       dbms_lob.writeAppend(tempResult, length(l_close_tag), l_close_tag);
18112       FND_FILE.put_line( FND_FILE.LOG,'Appended close tag to XML data');
18113      -- Fnd_File.PUT_line(Fnd_File.OUTPUT,tempResult);
18114       print_clob(lob_loc => tempResult);
18115       FND_FILE.put_line( FND_FILE.LOG,'XML generation is success');
18116 
18117       x_no_of_rec_prc := l_no_of_rec_prc;
18118       x_no_of_succ_rec := l_no_of_succ_rec;
18119       x_no_of_fail_rec := l_no_of_fail_rec;
18120 
18121     EXCEPTION
18122        WHEN OTHERS THEN
18123        FND_FILE.put_line( FND_FILE.LOG,'err'||sqlerrm);
18124        RAISE;
18125     END gen_xml_data_dunning;
18126     --End adding for bug 8489610 by gnramasa 14-May-09
18127 
18128     Procedure stage_dunning_inv_copy
18129                (p_api_version             IN NUMBER := 1.0,
18130                 p_init_msg_list           IN VARCHAR2 ,
18131                 p_commit                  IN VARCHAR2 ,
18132                 p_no_of_workers           IN NUMBER,
18133     	    p_process_err_rec_only    IN VARCHAR2,
18134                 p_request_id	      IN NUMBER,
18135     	    p_dunning_mode	      IN VARCHAR2,
18136     	    p_confirmation_mode	      IN VARCHAR2,
18137     	    p_running_level           IN VARCHAR2,
18138     	    p_correspondence_date     IN DATE,
18139     	    p_max_dunning_trx_id      IN NUMBER,
18140     	    x_return_status           OUT NOCOPY VARCHAR2,
18141                 x_msg_count               OUT NOCOPY NUMBER,
18142                 x_msg_data                OUT NOCOPY VARCHAR2)
18143     IS
18144     l_object_type		varchar2(20);
18145     l_object_id		number;
18146     l_send_method		varchar2(10);
18147     l_fulfillment_bind_tbl	IEX_DUNNING_PVT.FULFILLMENT_BIND_TBL;
18148     l_request_id		number := 0;
18149     l_source_id		number;
18150     l_template_id		number;
18151     l_cust_trx_id		number;
18152     l_party_type		varchar2(20);
18153     l_party_id		number;
18154     l_contact_destination	varchar2(240);
18155     l_contact_party_id	number;
18156     l_location_id		number;
18157     l_msg_count		number;
18158     l_msg_data		varchar2(200);
18159     l_return_status		varchar2(10);
18160     l_key_id		number;
18161     l_bind_var		varchar2(50);
18162     n_key_id		varchar2(2000);
18163     l_trx_type		varchar2(20);
18164     n_bind_var		varchar2(50);
18165     l_api_name		varchar2(50) := 'stage_dunning_inv_copy';
18166     Type refCur             is Ref Cursor;
18167     sql_cur1                refCur;
18168     vPLSQL1                 VARCHAR2(2000);
18169 
18170     /*
18171     cursor c_get_invoice_ct (p_conc_req_id number) is
18172           select idt.cust_trx_id,
18173                  dunn.object_id,
18174                  dunn.object_type
18175           from iex_dunning_transactions idt,
18176                iex_dunnings dunn,
18177     	   iex_ag_dn_xref xref
18178           where idt.dunning_id = dunn.dunning_id
18179           and dunn.request_id = p_conc_req_id
18180           and dunn.ag_dn_xref_id = xref.ag_dn_xref_id
18181           and xref.invoice_copies = 'Y'
18182           and idt.cust_trx_id is not null;
18183           --and not exists (select 1 from iex_xml_request_histories xml
18184           --               where xml.xml_request_id = dunn.xml_request_id);
18185     */
18186 
18187     begin
18188     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start');
18189     l_template_id := fnd_profile.value('IEX_INVOICE_FULFILLMENT_TEMPLATE');
18190     --l_send_method  := NVL(fnd_profile.value('IEX_FULFILLMENT_SEND_METHOD'),'EMAIL');
18191     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Template ID for Invoice : '||l_template_id);
18192     --WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Send method : '||l_send_method);
18193 
18194     vPLSQL1 := 'select idt.cust_trx_id, ' ||
18195         '         dunn.object_id, ' ||
18196         '         dunn.object_type, ' ||
18197         '         dunn.dunning_method ' ||
18198         '  from iex_dunning_transactions idt,  ' ||
18199         '       iex_dunnings dunn, ' ||
18200         '	   iex_ag_dn_xref xref,  ' ||
18201         '      ra_customer_trx trx ' ||
18202         '  where idt.dunning_id = dunn.dunning_id ' ||
18203         '  and dunn.request_id = :p_conc_req_id  ' ||
18204         '  and dunn.ag_dn_xref_id = xref.ag_dn_xref_id  ' ||
18205         '  and xref.invoice_copies = ''Y''  ' ||
18206         '  and idt.cust_trx_id is not null ' ||
18207         '  and trx.customer_trx_id = idt.cust_trx_id ' ||
18208         '  and trx.printing_option = ''PRI'' ' ;
18209 
18210     if p_process_err_rec_only = 'Y' then
18211     	vPLSQL1 := vPLSQL1 || ' and idt.dunning_trx_id > :p_max_dunn_trx_id ' ;
18212     end if;
18213 
18214     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - vPLSQL1 ' || vPLSQL1);
18215     if p_process_err_rec_only = 'Y' then
18216     	open sql_cur1 for vPLSQL1 using p_request_id, p_max_dunning_trx_id;
18217     else
18218     	open sql_cur1 for vPLSQL1 using p_request_id;
18219     end if;
18220 
18221     LOOP
18222     	fetch sql_cur1 into l_cust_trx_id,l_object_id,l_object_type,l_send_method;
18223     	exit when sql_cur1%NOTFOUND;
18224 
18225     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' l_cust_trx_id : '||l_cust_trx_id);
18226     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' l_object_id : '||l_object_id);
18227     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' l_object_type : '||l_object_type);
18228     	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' Send method : '||l_send_method);
18229 
18230     	if(l_cust_trx_id is not null ) then
18231 
18232     		l_key_id     := l_cust_trx_id;
18233     		l_party_type := l_object_type;
18234 
18235     		If l_object_type = 'IEX_BILLTO' then
18236     			l_source_id := l_object_id;
18237     			SELECT  ca.party_id into l_party_id
18238     			FROM hz_cust_site_uses site_uses,
18239     			     hz_cust_acct_sites acct_sites,
18240     			     hz_cust_accounts ca
18241     			WHERE site_uses.site_use_id = l_object_id
18242     			AND acct_sites.cust_acct_site_id = site_uses.cust_acct_site_id
18243     			AND ca.cust_account_id = acct_sites.cust_account_id;
18244 
18245     		Elsif l_object_type = 'IEX_DELINQUENCY' then
18246     			l_source_id := l_object_id;
18247     			SELECT  ca.PARTY_CUST_ID into l_party_id
18248     			FROM IEX_DELINQUENCIES ca
18249     			WHERE ca.DELINQUENCY_ID = l_object_id;
18250 
18251     		Elsif l_object_type = 'IEX_ACCOUNT' then
18252     			l_source_id := l_object_id;
18253     			SELECT ca.party_id into l_party_id
18254     			FROM hz_cust_accounts ca
18255     			WHERE ca.cust_account_id = l_object_id;
18256 
18257     		Elsif l_object_type = 'PARTY' then
18258     			l_party_id := l_object_id;
18259     			l_source_id := l_object_id;
18260     		End if;
18261     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' l_party_id : '||l_party_id);
18262     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' l_key IDs for Invoice....'||l_key_id);
18263     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' l_party IDss for Invoice....'||l_party_id);
18264 
18265     		n_key_id        := l_key_id||','||l_party_id;
18266     		l_bind_var      := 'invoice_id';
18267     		n_bind_var      := 'invoice_id,party_id';
18268     		l_object_type   := 'IEX_INVOICES';
18269     		l_trx_type      := 'INVOICES';
18270 
18271     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' n_key IDss for Invoice....'||n_key_id);
18272 
18273     		l_fulfillment_bind_tbl(1).key_name  := l_bind_var;
18274     		l_fulfillment_bind_tbl(1).key_type  := 'NUMBER';
18275     		l_fulfillment_bind_tbl(1).key_value := to_char(l_key_id);
18276 
18277     		l_fulfillment_bind_tbl(2).key_name  := 'party_id';
18278     		l_fulfillment_bind_tbl(2).key_type  := 'NUMBER';
18279     		l_fulfillment_bind_tbl(2).key_value := to_char(l_party_id);
18280 
18281     		begin
18282     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' getting primary address');
18283     			select location_id into l_location_id
18284     			from ast_locations_v
18285     			where party_id = l_party_id
18286     			AND primary_flag = 'Y';
18287 
18288     			WriteLog(G_PKG_NAME || ' ' || l_api_name || ' primart address location ID: ' || l_location_id);
18289 
18290     			-- check if location exists and add it to bind table
18291     			if l_location_id is not null then
18292     			  l_fulfillment_bind_tbl(3).key_value := l_location_id;
18293     			  l_fulfillment_bind_tbl(3).key_name  := 'location_id';
18294     			  l_fulfillment_bind_tbl(3).key_type  := 'NUMBER';
18295     			end if;
18296     		exception
18297     			when no_data_found then
18298     				WriteLog(G_PKG_NAME || ' ' || l_api_name || sqlerrm);
18299     			when others then
18300     				WriteLog(G_PKG_NAME || ' ' || l_api_name || sqlerrm);
18301     		end;
18302 
18303     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' calling iex_dunning_pvt.send_xml');
18304 
18305     		send_xml(
18306     		p_api_version             => 1.0,
18307     		p_init_msg_list           => 'T',
18308     		p_commit                  => 'T',
18309     		p_resend                  => 'N',
18310     		p_request_id              => null,
18311     		p_FULFILLMENT_BIND_TBL    => l_fulfillment_bind_tbl,
18312     		p_template_id             => l_template_id,
18313     		p_method                  => l_send_method,
18314     		p_user_id                 => NULL,
18315     		p_email                   => NULL,
18316     		p_party_id                => l_party_id,
18317     		p_level                   => p_running_level,
18318     		p_source_id               => l_source_id,
18319     		p_object_code             => l_object_type,
18320     		p_object_id               => l_key_id,
18321     		p_parent_request_id       => p_request_id,
18322     		p_dunning_mode		  => p_dunning_mode,
18323     		p_correspondence_date     => p_correspondence_date,
18324     		x_return_status           => l_return_status,
18325     		x_msg_count               => l_msg_count,
18326     		x_msg_data                => l_msg_data,
18327     		x_contact_destination     => l_contact_destination,
18328     		x_contact_party_id        => l_contact_party_id,
18329     		x_REQUEST_ID              => l_request_id);
18330     	end if;
18331     end loop;
18332     close sql_cur1;
18333 
18334     IF FND_API.to_Boolean( p_commit )
18335     THEN
18336       COMMIT WORK;
18337     END IF;
18338 
18339     x_return_status := FND_API.G_RET_STS_SUCCESS;
18340     WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
18341 
18342     FND_MSG_PUB.Count_And_Get
18343     (  p_count          =>   x_msg_count,
18344     p_data           =>   x_msg_data );
18345 
18346     EXCEPTION
18347      WHEN FND_API.G_EXC_ERROR THEN
18348          COMMIT WORK;
18349          x_return_status := FND_API.G_RET_STS_ERROR;
18350          FND_MSG_PUB.Count_And_Get
18351          (  p_count          =>   x_msg_count,
18352     	p_data           =>   x_msg_data );
18353          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Exc Exception');
18354          FND_FILE.PUT_LINE(FND_FILE.LOG, 'expect exception' );
18355          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
18356 
18357      WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
18358          COMMIT WORK;
18359          x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
18360          FND_MSG_PUB.Count_And_Get
18361          (  p_count          =>   x_msg_count,
18362     	p_data           =>   x_msg_data );
18363          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - UnExc Exception');
18364          FND_FILE.PUT_LINE(FND_FILE.LOG, 'unexpect exception' );
18365          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
18366 
18367      WHEN OTHERS THEN
18368          COMMIT WORK;
18369          x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
18370          FND_MSG_PUB.Count_And_Get
18371          (  p_count          =>   x_msg_count,
18372     	p_data           =>   x_msg_data );
18373          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Other Exception');
18374          FND_FILE.PUT_LINE(FND_FILE.LOG, 'unexpect exception' );
18375          WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - error='||SQLERRM);
18376 
18377     END stage_dunning_inv_copy;
18378 
18379     Procedure INSERT_DUNNING_TRANSACTION
18380                (p_api_version             IN NUMBER := 1.0,
18381                 p_init_msg_list           IN VARCHAR2 ,
18382                 p_commit                  IN VARCHAR2 ,
18383                 p_delinquencies_tbl       IN IEX_DELINQUENCY_PUB.DELINQUENCY_TBL_TYPE,
18384     	        p_dunning_id	          IN NUMBER,
18385     	        p_correspondence_date     IN DATE,
18386     	        p_ag_dn_xref_id           IN NUMBER ,
18387                 p_running_level           IN VARCHAR2,
18388     	        p_grace_days              IN NUMBER,
18389     	        p_include_dispute_items   IN VARCHAR2 ,
18390     	        x_return_status           OUT NOCOPY VARCHAR2,
18391                 x_msg_count               OUT NOCOPY NUMBER,
18392                 x_msg_data                OUT NOCOPY VARCHAR2
18393                 ,p_workitem_id            IN  NUMBER)  -- bug 14772139
18394     IS
18395         l_api_name                    CONSTANT VARCHAR2(30) := 'Inser_dunning_transaction';
18396         l_api_version_number          CONSTANT NUMBER   := 1.0;
18397         l_return_status               VARCHAR2(1);
18398         l_msg_count                   NUMBER;
18399         l_msg_data                    VARCHAR2(32767);
18400         l_rowid                       Varchar2(50);
18401         l_Dunning_REC                 IEX_DUNNING_PUB.Dunning_REC_TYPE ;
18402         errmsg                        VARCHAR2(32767);
18403 
18404         --l_dunning_plan_lines	c_dunning_plan_lines%rowtype;
18405         Type refCur			is Ref Cursor;
18406         sql_cur			refCur;
18407         sql_cur1			refCur;
18408         sql_cur2			refCur;
18409         sql_cur3			refCur;
18410         vPLSQL			VARCHAR2(2000);
18411         vPLSQL1			VARCHAR2(2000);
18412         vPLSQL2			VARCHAR2(2000);
18413         vPLSQL3			VARCHAR2(2000);
18414         l_delinquency_id		number;
18415         l_transaction_id		number;
18416         l_customer_trx_id		number;
18417         l_payment_schedule_id	number;
18418         l_object_id			number;
18419 
18420         cursor c_dunn_plan_line_dtls (p_ag_dn_xref_id number) is
18421         select nvl(dunn.include_current ,'N'),
18422                nvl(dunn.include_unused_payments_flag,'N')
18423         from iex_ag_dn_xref xref,
18424              iex_dunning_plans_b dunn
18425         where AG_DN_XREF_ID = p_ag_dn_xref_id
18426         and xref.dunning_plan_id = dunn.dunning_plan_id;
18427 
18428         x_dunning_trx_id	number;
18429         l_stage	        number;
18430         l_include_curr_inv  varchar2(10);
18431         l_include_unapp_rec varchar2(10);
18432         l_curr_count        number := 0;
18433         l_grace_days        number; -- bug 14772139
18434 
18435     BEGIN
18436           -- Standard Start of API savepoint
18437           SAVEPOINT INSERT_DUNNING_TRANSACTION_PVT;
18438 
18439           -- Standard call to check for call compatibility.
18440           IF NOT FND_API.Compatible_API_Call ( l_api_version_number,
18441                                                p_api_version,
18442                                                l_api_name,
18443                                                G_PKG_NAME)
18444           THEN
18445               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
18446           END IF;
18447 
18448           -- Initialize message list if p_init_msg_list is set to TRUE.
18449           IF FND_API.to_Boolean( p_init_msg_list )
18450           THEN
18451               FND_MSG_PUB.initialize;
18452           END IF;
18453 
18454           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - START');
18455           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_dunning_id :'|| p_dunning_id);
18456           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_ag_dn_xref_id :'|| p_ag_dn_xref_id); -- bug 14772139
18457           l_grace_days := p_grace_days; -- bug 14772139
18458           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_grace_days :'|| p_grace_days);
18459           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_include_dispute_items :'|| p_include_dispute_items);
18460           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_curr_count :'|| l_curr_count);
18461           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_running_level :'|| p_running_level);
18462 
18463           -- Added below condition and else block code to fix 14256867
18464           -- when called from Strategy fulfillment p_ag_dn_xref_id  => 0
18465           if p_ag_dn_xref_id <> 0 then
18466             open c_dunn_plan_line_dtls (p_ag_dn_xref_id);
18467             fetch c_dunn_plan_line_dtls into l_include_curr_inv, l_include_unapp_rec;
18468             close c_dunn_plan_line_dtls;
18469           else
18470              begin  -- bug 14772139  start....
18471                 select nvl(b.INCLUDE_CURRENT,'N') ,nvl(INCLUDE_UNUSED_PAYMENTS_FLAG,'N')
18472                        into l_include_curr_inv, l_include_unapp_rec
18473                   from iex_strategy_work_items a, IEX_STRY_TEMP_WORK_ITEMS_VL b
18474                   where a.work_item_template_id = b.work_item_temp_id
18475                     and a.work_item_id = p_workitem_id -- p_grace_days -- indicating workitem Id when p_ag_dn_xref_id is 0 from iexpstmb.pls
18476                     and b.work_type in ('AUTOMATIC','WORKFLOW');  -- bug 14772139
18477                     --and b.work_type = 'AUTOMATIC';  -- bug 14772139
18478                exception
18479                  when others then
18480                       l_include_curr_inv := 'N';
18481                       l_include_unapp_rec:= 'Y';
18482               end;
18483               g_included_unapplied_rec := 'N';
18484               g_included_current_invs  := 'N';
18485               -- bug 14772139  end....
18486               -- bug 14772139  l_include_curr_inv := 'N'; -- For Strategies we don't include current invoices
18487               -- bug 14772139  l_include_unapp_rec:= 'Y'; -- For Strategies we include upnapplied receipts
18488           end if;
18489 
18490           x_return_status := FND_API.G_RET_STS_SUCCESS;
18491           --
18492           -- API body
18493           --
18494 
18495           if (p_running_level = 'CUSTOMER') then
18496     	        l_object_id	:= p_delinquencies_tbl(1).party_cust_id;
18497     	  elsif  (p_running_level = 'ACCOUNT') then
18498     		l_object_id	:= p_delinquencies_tbl(1).cust_account_id;
18499     	  elsif  (p_running_level = 'BILL_TO') then
18500     		l_object_id	:= p_delinquencies_tbl(1).customer_site_use_id;
18501     	  elsif  (p_running_level = 'DELINQUENCY') then
18502     	        l_object_id	:= p_delinquencies_tbl(1).delinquency_id;
18503     	  end if;
18504 
18505     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || 'l_object_id : '|| l_object_id);
18506     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || 'p_grace_days : '|| p_grace_days);
18507     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || 'l_grace_days : '|| l_grace_days); -- bug 14772139
18508           WriteLog(G_PKG_NAME || ' ' || l_api_name || 'p_correspondence_date : '||p_correspondence_date);
18509     	  WriteLog(G_PKG_NAME || ' ' || l_api_name || 'p_include_dispute_items : '|| p_include_dispute_items);
18510 
18511     	  vPLSQL := 'select  del.delinquency_id, ' ||
18512     	            '        del.transaction_id, ' ||
18513     	            '        del.payment_schedule_id ' ||
18514     		    '    from iex_delinquencies del, ' ||
18515     		    '	      ar_payment_schedules arp ' ||
18516     		    '    where del.payment_schedule_id = arp.payment_schedule_id ' ||
18517      		    '    and del.status in (''DELINQUENT'',''PREDELINQUENT'') ' ||
18518     		    -- '    and del.staged_dunning_level is NULL ' || commented to fix 12621875 snuthala 6/6/2011
18519     		    '    and (trunc(arp.due_date) + :p_gra_days) <= :p_corr_date ' ||
18520     		    '    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ';  -- bug 14772139
18521                     --'    and nvl(arp.amount_due_remaining,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), nvl(arp.amount_due_remaining,0)) ';
18522 
18523     	 if (p_running_level = 'CUSTOMER') then
18524     	         vPLSQL3		:= '    and del.party_cust_id = :p_party_id ' ||
18525     					   '    order by del.payment_schedule_id';
18526     	 elsif  (p_running_level = 'ACCOUNT') then
18527     	         vPLSQL3		:= '    and del.cust_account_id = :p_cust_acct_id ' ||
18528     	                                   --Begin Bug 10401991 03-feb-2011 barathsr
18529     		                           '    and arp.amount_due_remaining >= NVL ( '||
18530     					   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
18531     					   '	FROM hz_cust_profile_amts '||
18532     					   '	WHERE site_use_id  IS NULL '||
18533     					   '	AND cust_account_id = arp.customer_id '||
18534     					   '	AND currency_code   = arp.invoice_currency_code),0) '||
18535     				           '    order by del.payment_schedule_id';
18536     				           --End Bug 10401991 03-feb-2011 barathsr
18537     	 elsif  (p_running_level = 'BILL_TO') then
18538     	         vPLSQL3		:= '    and del.customer_site_use_id = :p_site_use_id ' ||
18539     	                                   --Begin Bug 10401991 03-feb-2011 barathsr
18540     				           '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
18541     					   '	from hz_cust_profile_amts '||
18542     					   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
18543     					   '	and currency_code = arp.invoice_currency_code),0) '||
18544     				           '    order by del.payment_schedule_id';
18545     				           --End Bug 10401991 03-feb-2011 barathsr
18546     	  elsif (p_running_level = 'DELINQUENCY') then
18547     	         vPLSQL3		:= '    and del.delinquency_id = :p_delinquency_id ' ||
18548     		          		   '    order by del.payment_schedule_id';
18549           end if;
18550 
18551           vPLSQL := vPLSQL || vPLSQL3;
18552     	  WriteLog(G_PKG_NAME || ' ' || l_api_name  || ' - vPLSQL : ' ||vPLSQL);
18553 
18554           open sql_cur for vPLSQL using l_grace_days,  -- p_grace_days, bug 14772139
18555                                         p_correspondence_date,
18556     	                                p_include_dispute_items,
18557     					l_object_id;
18558     	  loop
18559     	      fetch sql_cur into l_delinquency_id, l_transaction_id, l_payment_schedule_id;
18560     	      exit when sql_cur%notfound;
18561 
18562     	      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
18563     	      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_delinquency_id :'||l_delinquency_id);
18564     	      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_transaction_id :'||l_transaction_id);
18565     	      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_payment_schedule_id : '||l_payment_schedule_id);
18566 
18567     	      IEX_Dunnings_PKG.insert_staged_dunning_row(
18568     					  px_rowid                          => l_rowid
18569     					, px_dunning_trx_id                 => x_dunning_trx_id
18570     					, p_dunning_id                      => p_dunning_id
18571     					, p_cust_trx_id                     => l_transaction_id
18572     					, p_payment_schedule_id             => l_payment_schedule_id
18573     					, p_ag_dn_xref_id                   => p_ag_dn_xref_id
18574     					, p_stage_number                    => -1
18575     					, p_created_by                      => FND_GLOBAL.USER_ID
18576     					, p_creation_date                   => sysdate
18577     					, p_last_updated_by                 => FND_GLOBAL.USER_ID
18578     					, p_last_update_date                => sysdate
18579     					, p_last_update_login               => FND_GLOBAL.USER_ID
18580     					, p_object_version_number	    => 1.0);
18581 
18582    	      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
18583 
18584     	      IF x_return_status = FND_API.G_RET_STS_ERROR then
18585     			raise FND_API.G_EXC_ERROR;
18586     	      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
18587     		       raise FND_API.G_EXC_UNEXPECTED_ERROR;
18588     	      END IF;
18589 
18590     	      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
18591     	      x_dunning_trx_id	:= null;
18592 
18593             end loop;
18594     	    close sql_cur;
18595 
18596             if l_include_curr_inv = 'Y' then
18597 
18598     		       vPLSQL := 'select  del.delinquency_id, ' ||
18599    	                         '        del.transaction_id, ' ||
18600     				 '        del.payment_schedule_id ' ||
18601     				 '    from iex_delinquencies del, ' ||
18602     				 '	 ar_payment_schedules arp ' ||
18603     				 '    where del.payment_schedule_id = arp.payment_schedule_id ' ||
18604     				 '    and del.status in (''DELINQUENT'',''PREDELINQUENT'') ' ||
18605     			       --'    and del.staged_dunning_level is NULL ' || commented to fix 12621875 snuthala 6/6/2011
18606     			         '    and (trunc(arp.due_date) + 0) <= :p_corr_date ' ||
18607     				 '    and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ';
18608 
18609     			if (p_running_level = 'CUSTOMER') then
18610     			      vPLSQL3		:= '    and del.party_cust_id = :p_party_id ' ;
18611 	                                    --     '    order by del.payment_schedule_id'; added below 12/23/2011 fix 13519242
18612     			elsif  (p_running_level = 'ACCOUNT') then
18613     			      vPLSQL3		:= '    and del.cust_account_id = :p_cust_acct_id ' ||
18614     	                                           --Begin Bug 10401991 03-feb-2011 barathsr
18615     						   '    and arp.amount_due_remaining >= NVL ( '||
18616     						   '	(SELECT NVL(min(min_dunning_invoice_amount),0) '||
18617     						   '	FROM hz_cust_profile_amts '||
18618     						   '	WHERE site_use_id  IS NULL '||
18619     						   '	AND cust_account_id = arp.customer_id '||
18620     						   '	AND currency_code   = arp.invoice_currency_code),0) ';
18621 			                    --     '    order by del.payment_schedule_id'; added below 12/23/2011 fix 13519242
18622     					            --End Bug 10401991 03-feb-2011 barathsr
18623     			elsif  (p_running_level = 'BILL_TO') then
18624     			      vPLSQL3		:= '    and del.customer_site_use_id = :p_site_use_id ' ||
18625     			                           --Begin Bug 10401991 03-feb-2011 barathsr
18626     						   '    and arp.amount_due_remaining >= nvl ((select nvl(min(min_dunning_invoice_amount),0) '||
18627     						   '	from hz_cust_profile_amts '||
18628     						   '	where site_use_id =  arp.CUSTOMER_SITE_USE_ID '||
18629     						   '	and currency_code = arp.invoice_currency_code),0) ';
18630 				            --     '    order by del.payment_schedule_id'; added below 12/23/2011 fix 13519242
18631     					           --End Bug 10401991 03-feb-2011 barathsr
18632     			elsif (p_running_level = 'DELINQUENCY') then
18633     			      vPLSQL3		:= '    and del.delinquency_id = :p_delinquency_id ' ;
18634 	                                    --     '    order by del.payment_schedule_id'; added below 12/23/2011 fix 13519242
18635     			end if;
18636 	                --    start  added  12/23/2011 fix 13519242 to stop inserting duplicate rows
18637 			vPLSQL3 := vPLSQL3 ||  '   and not exists (select 1 from iex_dunning_transactions dun_trx '||
18638 			                        '   where dun_trx.payment_schedule_id = del.payment_schedule_id '||
18639 					        '   and dun_trx.dunning_id = :p_dunning_id ) ' ||
18640     					        '    order by del.payment_schedule_id';
18641                         -- end added 12/23/2011 fix 13519242
18642     			vPLSQL	:= vPLSQL || vPLSQL3;
18643     			WriteLog(G_PKG_NAME || ' ' || l_api_name  || ' - vPLSQL : ' ||vPLSQL);
18644     			open sql_cur for vPLSQL using --p_grace_days, commented to fix 13519242  12/21/2011
18645     						    p_correspondence_date,
18646     						    p_include_dispute_items,
18647     						    l_object_id,
18648 			                            p_dunning_id;
18649     			loop
18650     	                   fetch sql_cur into l_delinquency_id, l_transaction_id, l_payment_schedule_id;
18651     			   exit when sql_cur%notfound;
18652 
18653     			   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
18654     			   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_delinquency_id :'||l_delinquency_id);
18655     			   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_transaction_id :'||l_transaction_id);
18656     			   WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur.l_payment_schedule_id : '||l_payment_schedule_id);
18657 
18658     			   IEX_Dunnings_PKG.insert_staged_dunning_row(
18659     						  px_rowid                          => l_rowid
18660     						, px_dunning_trx_id                 => x_dunning_trx_id
18661     						, p_dunning_id                      => p_dunning_id
18662     						, p_cust_trx_id                     => l_transaction_id
18663     						, p_payment_schedule_id             => l_payment_schedule_id
18664     						, p_ag_dn_xref_id                   => p_ag_dn_xref_id
18665     						, p_stage_number                    => 0
18666     						, p_created_by                      => FND_GLOBAL.USER_ID
18667     						, p_creation_date                   => sysdate
18668     						, p_last_updated_by                 => FND_GLOBAL.USER_ID
18669     						, p_last_update_date                => sysdate
18670     						, p_last_update_login               => FND_GLOBAL.USER_ID
18671     						, p_object_version_number	    => 1.0
18672     					      );
18673 
18674     			    WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
18675 
18676     			    IF x_return_status = FND_API.G_RET_STS_ERROR then
18677     			               raise FND_API.G_EXC_ERROR;
18678     			    elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
18679     				       raise FND_API.G_EXC_UNEXPECTED_ERROR;
18680     			    END IF;
18681 
18682     		            --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
18683     			    x_dunning_trx_id	:= null;
18684     			end loop;
18685     			close sql_cur;
18686            end if; -- end if for l_include_curr_inv = 'Y'
18687 
18688         --   if p_ag_dn_xref_id <> 0 then  -- commented for bug#15932721 schekuri 30-Nov-12
18689     		--Include past due fully disputed invoices
18690     		WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start Include past due fully disputed invoices');
18691     		vPLSQL1 :=
18692                                 'select del.delinquency_id, ' ||
18693     			        '       del.transaction_id, ' ||
18694     			        '       del.payment_schedule_id  ' ||
18695     				'    from iex_delinquencies del,  ar_payment_schedules arp ' ||
18696     				'    where del.payment_schedule_id = arp.payment_schedule_id ' ||
18697     				'      and del.status = ''CURRENT'' ' ||
18698     		--		'      and del.staged_dunning_level is NULL ' ||  -- commented for bug#15932721 schekuri 30-Nov-12
18699     				'      and arp.status = ''OP'' ' ||
18700     				-- '   and arp.class = ''INV'' ' ||  -- Bills Receivables
18701                                 '      and (arp.class = ''INV'' or arp.class = ''BR'') ' ||   -- Bills Receivables
18702     			        '      and (trunc(arp.due_date) + :p_gra_days) <= :p_corr_date ' ||   -- Bills Receivables
18703     				'      and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ;
18704 
18705     		vPLSQL1	:= vPLSQL1 || vPLSQL3;
18706     		WriteLog(G_PKG_NAME || ' ' || l_api_name  || ' - vPLSQL1 : ' ||vPLSQL1);
18707 
18708 		if  l_include_curr_inv = 'Y' then
18709     			open sql_cur1 for vPLSQL1 using
18710                                             l_grace_days, -- p_grace_days, bug 14772139
18711     					    p_correspondence_date,
18712     					    p_include_dispute_items,
18713     					    l_object_id,
18714 					    p_dunning_id;
18715 		else
18716 		         open sql_cur1 for vPLSQL1 using
18717                                             l_grace_days, -- p_grace_days, bug 14772139
18718     					    p_correspondence_date,
18719     					    p_include_dispute_items,
18720     					    l_object_id;
18721 		end if;
18722 
18723     		loop
18724     		      fetch sql_cur1 into l_delinquency_id, l_transaction_id, l_payment_schedule_id;
18725     		      exit when sql_cur1%notfound;
18726 
18727     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - InsertRow');
18728     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur1.l_delinquency_id :'||l_delinquency_id);
18729     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur1.l_transaction_id :'||l_transaction_id);
18730     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur1.l_payment_schedule_id : '||l_payment_schedule_id);
18731 
18732     		      IEX_Dunnings_PKG.insert_staged_dunning_row(
18733     					  px_rowid                          => l_rowid
18734     					, px_dunning_trx_id                 => x_dunning_trx_id
18735     					, p_dunning_id                      => p_dunning_id
18736     					, p_cust_trx_id                     => l_transaction_id
18737     					, p_payment_schedule_id             => l_payment_schedule_id
18738     					, p_ag_dn_xref_id                   => p_ag_dn_xref_id
18739     					, p_stage_number                    => -1  --changed by schekuri bug#15932721
18740     					, p_created_by                      => FND_GLOBAL.USER_ID
18741     					, p_creation_date                   => sysdate
18742     					, p_last_updated_by                 => FND_GLOBAL.USER_ID
18743     					, p_last_update_date                => sysdate
18744     					, p_last_update_login               => FND_GLOBAL.USER_ID
18745     					, p_object_version_number	    => 1.0
18746     				      );
18747 
18748     				      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
18749 
18750     				      IF x_return_status = FND_API.G_RET_STS_ERROR then
18751     						raise FND_API.G_EXC_ERROR;
18752     				      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
18753     					       raise FND_API.G_EXC_UNEXPECTED_ERROR;
18754     				      END IF;
18755 
18756     				      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
18757     				      x_dunning_trx_id	:= null;
18758 
18759     		end loop;
18760     		close sql_cur1;
18761 
18762                 WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End Include past due fully disputed invoices');
18763          -- end if;
18764 
18765           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - p_ag_dn_xref_id :' || p_ag_dn_xref_id);
18766           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Insert current invoices');
18767           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - g_included_current_invs: '|| g_included_current_invs);
18768           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_include_curr_inv: '|| l_include_curr_inv);
18769           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_include_unapp_rec: '|| l_include_unapp_rec);
18770 
18771           if (g_included_current_invs = 'N') and (l_include_curr_inv = 'Y') then
18772     	        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start insert current invoices');
18773 
18774     		if (p_running_level = 'CUSTOMER') then
18775     			vPLSQL2 := 'select arp.customer_trx_id, ' ||
18776     				'	   arp.payment_schedule_id ' ||
18777     				'    from ar_payment_schedules arp, hz_cust_accounts hca ' ||
18778     				'    where arp.customer_id = hca.cust_account_id ' ||
18779     				'      and hca.party_id = :p_party_id ' ||
18780     			--	'      and trunc(arp.due_date) > trunc(:p_corr_date) ' ||
18781     				'      and arp.status = ''OP'' ' ||
18782     				'      and arp.amount_due_remaining <> 0 ' ||
18783     				--'    and arp.class = ''INV'' ' ||     -- Bills Receivables
18784                                 '      and (arp.class = ''INV'' or arp.class = ''BR'') ' ||   -- Bills Receivables
18785     				'      and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
18786     				'      and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'' ) ' ||
18787                                 '      and not exists (select 1 from iex_dunning_transactions dun_trx  where dun_trx.payment_schedule_id = arp.payment_schedule_id and dun_trx.dunning_id = :p_dunning_id ) ' || -- added by a bug 15932721
18788     				'    order by arp.payment_schedule_id';
18789     		elsif  (p_running_level = 'ACCOUNT') then
18790     		      vPLSQL2 := 'select arp.customer_trx_id, ' ||
18791     				'        arp.payment_schedule_id ' ||
18792     				'    from ar_payment_schedules arp ' ||
18793     				'    where arp.customer_id = :p_cust_acct_id ' ||
18794     				--'    and trunc(arp.due_date) > trunc(:p_corr_date) ' ||
18795     				'      and arp.status = ''OP'' ' ||
18796     				'      and arp.amount_due_remaining <> 0 ' ||
18797     				--'    and arp.class = ''INV'' ' ||     -- Bills Receivables
18798                                 '      and (arp.class = ''INV'' or arp.class = ''BR'') ' ||   -- Bills Receivables
18799     				'      and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
18800     				'      and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'' ) ' ||
18801                                 '      and not exists (select 1 from iex_dunning_transactions dun_trx  where dun_trx.payment_schedule_id = arp.payment_schedule_id and dun_trx.dunning_id = :p_dunning_id ) ' ||  -- added by a bug 15932721
18802     				'    order by arp.payment_schedule_id';
18803     		elsif  (p_running_level = 'BILL_TO') then
18804     		      vPLSQL2 := 'select arp.customer_trx_id, ' ||
18805     				'	 arp.payment_schedule_id ' ||
18806     				'    from ar_payment_schedules arp ' ||
18807     				'    where arp.customer_site_use_id = :p_site_use_id ' ||
18808     				--'    and trunc(arp.due_date) > trunc(:p_corr_date) ' ||
18809     				'      and arp.status = ''OP'' ' ||
18810     				'      and arp.amount_due_remaining <> 0 ' ||
18811     				--'    and arp.class = ''INV'' ' ||     -- Bills Receivables
18812                                 '      and (arp.class = ''INV'' or arp.class = ''BR'') ' ||   -- Bills Receivables
18813     				'      and nvl(arp.amount_in_dispute,0) = decode(:p_include_dis_items, ''Y'', nvl(arp.amount_in_dispute,0), 0) ' ||
18814     				'      and not exists (select 1 from iex_delinquencies del where del.payment_schedule_id = arp.payment_schedule_id and del.status <> ''CURRENT'' ) ' ||
18815                                 '      and not exists (select 1 from iex_dunning_transactions dun_trx  where dun_trx.payment_schedule_id = arp.payment_schedule_id and dun_trx.dunning_id = :p_dunning_id ) ' ||  -- added by a bug 15932721
18816     				'    order by arp.payment_schedule_id';
18817 
18818     		end if;
18819     		if vPLSQL2 is not null then -- If running level is delinquency then Account Credit memos is not requied so vplsq2 will be null
18820     		   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'vPLSQL2 : '||vPLSQL2);
18821     		   open sql_cur2 for vPLSQL2 using l_object_id,
18822     					  --  p_correspondence_date,
18823     					    p_include_dispute_items
18824                                             ,p_dunning_id; -- bug 15932721
18825     	 	   loop
18826     		      fetch sql_cur2 into l_customer_trx_id, l_payment_schedule_id;
18827     		      exit when sql_cur2%notfound;
18828 
18829     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_customer_trx_id :'||l_customer_trx_id);
18830     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_payment_schedule_id : '||l_payment_schedule_id);
18831 
18832     		      IEX_Dunnings_PKG.insert_staged_dunning_row(
18833     			  px_rowid                          => l_rowid
18834     			, px_dunning_trx_id                 => x_dunning_trx_id
18835     			, p_dunning_id                      => p_dunning_id
18836     			, p_cust_trx_id                     => l_customer_trx_id
18837     			, p_payment_schedule_id             => l_payment_schedule_id
18838     			, p_ag_dn_xref_id                   => p_ag_dn_xref_id
18839     			, p_stage_number                    => 0
18840     			, p_created_by                      => FND_GLOBAL.USER_ID
18841     			, p_creation_date                   => sysdate
18842     			, p_last_updated_by                 => FND_GLOBAL.USER_ID
18843     			, p_last_update_date                => sysdate
18844     			, p_last_update_login               => FND_GLOBAL.USER_ID
18845     			, p_object_version_number	    => 1.0
18846     		      );
18847 
18848     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
18849 
18850     		      IF x_return_status = FND_API.G_RET_STS_ERROR then
18851     				raise FND_API.G_EXC_ERROR;
18852     		      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
18853     			       raise FND_API.G_EXC_UNEXPECTED_ERROR;
18854     		      END IF;
18855 
18856     		      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
18857     		      x_dunning_trx_id	:= null;
18858     		   end loop;
18859     	           close sql_cur2;
18860 
18861     	           --Setting the variable to 'Y', so that current invoices won't be include in further stage letters for this
18862     	           --customer/account/Bill to/Delinquency
18863     	           g_included_current_invs:= 'Y';
18864     	           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End insert current invoices');
18865                 end if;
18866        end if;
18867 
18868        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Insert unapplied receipts and On Account Credit memos');
18869        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - g_included_unapplied_rec: '|| g_included_unapplied_rec);
18870        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - l_include_unapp_rec: '|| l_include_unapp_rec);
18871 
18872        if (g_included_unapplied_rec = 'N') and (l_include_unapp_rec = 'Y') then
18873           	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start insert unapplied receipts');
18874 
18875     		if (p_running_level = 'CUSTOMER') then
18876     			vPLSQL2 := 'select arp.payment_schedule_id ' ||
18877     				'    from ar_payment_schedules arp, ' ||
18878     				'         hz_cust_accounts hca ' ||
18879     				'    where arp.customer_id = hca.cust_account_id ' ||
18880     				'    and hca.party_id = :p_party_id ' ||
18881     				'    and arp.status = ''OP'' ' ||
18882     			        '    and arp.amount_due_remaining <> 0 ' ||
18883     			        '    and arp.class = ''PMT'' ' ||
18884     			        '    order by arp.payment_schedule_id';
18885     		elsif  (p_running_level = 'ACCOUNT') then
18886     		      vPLSQL2 := 'select arp.payment_schedule_id ' ||
18887     				    ' from ar_payment_schedules arp ' ||
18888     				    ' where arp.customer_id = :p_cust_acct_id ' ||
18889     				    ' and arp.status = ''OP'' ' ||
18890     				    ' and arp.amount_due_remaining <> 0 ' ||
18891     				    ' and arp.class = ''PMT'' ' ||
18892     				    ' order by arp.payment_schedule_id';
18893     		elsif  (p_running_level = 'BILL_TO') then
18894     		      vPLSQL2 := 'select arp.payment_schedule_id ' ||
18895     				    ' from ar_payment_schedules arp ' ||
18896     				    ' where arp.customer_site_use_id = :p_site_use_id ' ||
18897     				    ' and arp.status = ''OP'' ' ||
18898     				    ' and arp.amount_due_remaining <> 0 ' ||
18899     				    ' and arp.class = ''PMT'' ' ||
18900     				    ' order by arp.payment_schedule_id';
18901     		end if;
18902 
18903     		if vPLSQL2 is not null then -- If running level is delinquency then Account Credit memos is not requied so vplsq2 will be null
18904     		    WriteLog(G_PKG_NAME || ' ' || l_api_name || 'vPLSQL2 : '||vPLSQL2);
18905     		    open sql_cur2 for vPLSQL2 using l_object_id;
18906     		    loop
18907     		      fetch sql_cur2 into l_payment_schedule_id;
18908     		      exit when sql_cur2%notfound;
18909 
18910     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_payment_schedule_id : '||l_payment_schedule_id);
18911 
18912     		      IEX_Dunnings_PKG.insert_staged_dunning_row(
18913     			  px_rowid                          => l_rowid
18914     			, px_dunning_trx_id                 => x_dunning_trx_id
18915     			, p_dunning_id                      => p_dunning_id
18916     			--, p_cust_trx_id                     => l_customer_trx_id
18917     			, p_payment_schedule_id             => l_payment_schedule_id
18918     			, p_ag_dn_xref_id                   => p_ag_dn_xref_id
18919     			, p_stage_number                    => null
18920     			, p_created_by                      => FND_GLOBAL.USER_ID
18921     			, p_creation_date                   => sysdate
18922     			, p_last_updated_by                 => FND_GLOBAL.USER_ID
18923     			, p_last_update_date                => sysdate
18924     			, p_last_update_login               => FND_GLOBAL.USER_ID
18925     			, p_object_version_number	    => 1.0
18926     		      );
18927 
18928     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
18929 
18930     		      IF x_return_status = FND_API.G_RET_STS_ERROR then
18931     				raise FND_API.G_EXC_ERROR;
18932     		      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
18933     			       raise FND_API.G_EXC_UNEXPECTED_ERROR;
18934     		      END IF;
18935 
18936     		      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
18937     		      x_dunning_trx_id	:= null;
18938 
18939     	           end loop;
18940     		   close sql_cur2;
18941 
18942     	           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End insert unapplied receipts');
18943                 end if;
18944         	WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - Start insert On Account Credit memos');
18945 
18946         	if (p_running_level = 'CUSTOMER') then
18947     			vPLSQL2 := 'select arp.customer_trx_id customer_trx_id, ' ||
18948     			        '          arp.payment_schedule_id ' ||
18949     				'    from ar_payment_schedules arp, ' ||
18950     				'         hz_cust_accounts hca ' ||
18951     				'    where arp.customer_id = hca.cust_account_id ' ||
18952     				'    and hca.party_id = :p_party_id ' ||
18953     				'    and arp.amount_due_remaining <> 0 ' ||
18954     				'    and arp.class =''CM'' ' ||
18955     				'    and arp.status=''OP'' ';
18956     	        elsif  (p_running_level = 'ACCOUNT') then
18957     		      vPLSQL2 := 'select arp.customer_trx_id customer_trx_id, ' ||
18958     			            '    arp.payment_schedule_id ' ||
18959     				    ' from ar_payment_schedules arp ' ||
18960     				    ' where arp.customer_id = :p_cust_acct_id ' ||
18961     				    '    and arp.amount_due_remaining <> 0 ' ||
18962     				    '    and arp.class =''CM'' ' ||
18963     				    '    and arp.status=''OP'' ';
18964     	        elsif  (p_running_level = 'BILL_TO') then
18965     		      vPLSQL2 := 'select arp.customer_trx_id customer_trx_id, ' ||
18966     			            '    arp.payment_schedule_id ' ||
18967     				    ' from ar_payment_schedules arp ' ||
18968     				    ' where arp.customer_site_use_id = :p_site_use_id ' ||
18969     				    '    and arp.amount_due_remaining <> 0 ' ||
18970     				    '    and arp.class =''CM'' ' ||
18971     				    '    and arp.status=''OP'' ';
18972     	        end if;
18973 
18974     	        if vPLSQL2 is not null then -- If running level is delinquency then Account Credit memos is not requied so vplsq2 will be null
18975     	  	   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'vPLSQL2 : '||vPLSQL2);
18976     		   open sql_cur2 for vPLSQL2 using l_object_id;
18977     		   loop
18978     		      fetch sql_cur2 into l_customer_trx_id, l_payment_schedule_id;
18979     		      exit when sql_cur2%notfound;
18980 
18981     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_customer_trx_id :'||l_customer_trx_id);
18982     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - sql_cur2.l_payment_schedule_id : '||l_payment_schedule_id);
18983 
18984     		      IEX_Dunnings_PKG.insert_staged_dunning_row(
18985     			  px_rowid                          => l_rowid
18986     			, px_dunning_trx_id                 => x_dunning_trx_id
18987     			, p_dunning_id                      => p_dunning_id
18988     			, p_cust_trx_id                     => l_customer_trx_id
18989     			, p_payment_schedule_id             => l_payment_schedule_id
18990     			, p_ag_dn_xref_id                   => p_ag_dn_xref_id
18991     			, p_stage_number                    => null
18992     			, p_created_by                      => FND_GLOBAL.USER_ID
18993     			, p_creation_date                   => sysdate
18994     			, p_last_updated_by                 => FND_GLOBAL.USER_ID
18995     			, p_last_update_date                => sysdate
18996     			, p_last_update_login               => FND_GLOBAL.USER_ID
18997     			, p_object_version_number	    => 1.0
18998     		      );
18999 
19000     		      WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - x_dunning_trx_id :'|| x_dunning_trx_id);
19001 
19002     		      IF x_return_status = FND_API.G_RET_STS_ERROR then
19003     				raise FND_API.G_EXC_ERROR;
19004     		      elsif x_return_status = FND_API.G_RET_STS_UNEXP_ERROR then
19005     			       raise FND_API.G_EXC_UNEXPECTED_ERROR;
19006     		      END IF;
19007 
19008     		      --reset the x_dunning_trx_id, so that will get new no when inserting 2nd record.
19009     		      x_dunning_trx_id	:= null;
19010     	           end loop;
19011     	           close sql_cur2;
19012                 end if;
19013 
19014     	        --Setting the variable to 'Y', so that current invoices won't be include in further stage letters for this
19015     	        --customer/account/Bill to/Delinquency
19016     	        g_included_unapplied_rec:= 'Y';
19017     	        WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - End insert On Account Credit memos');
19018           end if;
19019 
19020           --
19021           -- End of API body
19022           --
19023 
19024           -- Standard check for p_commit
19025           IF FND_API.to_Boolean( p_commit )
19026           THEN
19027               COMMIT WORK;
19028           END IF;
19029 
19030           WriteLog(G_PKG_NAME || ' ' || l_api_name || ' - END');
19031           FND_MSG_PUB.Count_And_Get
19032           (  p_count          =>   x_msg_count,
19033              p_data           =>   x_msg_data
19034           );
19035 
19036     EXCEPTION
19037               WHEN FND_API.G_EXC_ERROR THEN
19038                   x_return_status := FND_API.G_RET_STS_ERROR;
19039                   FND_MSG_PUB.Count_And_Get
19040                   (  p_count          =>   x_msg_count,
19041                      p_data           =>   x_msg_data );
19042                   ROLLBACK TO INSERT_DUNNING_TRANSACTION_PVT;
19043                   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'exception ' || SQLERRM);
19044 
19045               WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
19046                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
19047                   FND_MSG_PUB.Count_And_Get
19048                   (  p_count          =>   x_msg_count,
19049                      p_data           =>   x_msg_data );
19050                   ROLLBACK TO INSERT_DUNNING_TRANSACTION_PVT;
19051                   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'error ' || SQLERRM);
19052 
19053               WHEN OTHERS THEN
19054                   x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
19055                   FND_MSG_PUB.Count_And_Get
19056                   (  p_count          =>   x_msg_count,
19057                      p_data           =>   x_msg_data );
19058                   ROLLBACK TO INSERT_DUNNING_TRANSACTION_PVT;
19059                   WriteLog(G_PKG_NAME || ' ' || l_api_name || 'error ' || SQLERRM);
19060 
19061     END INSERT_DUNNING_TRANSACTION;
19062 
19063 
19064     BEGIN
19065       PG_DEBUG  := FND_LOG.G_CURRENT_RUNTIME_LEVEL;
19066 
19067     END IEX_DUNNING_PVT;